claude-codes 2.1.297

Typed Rust SDK for the Claude Code agent CLI: serde models of its JSON-Lines (stream-json) protocol with streaming parsing, plus sync and async (Tokio) clients for driving Claude Code sessions, tools, and subagents.
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
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use serde_json::Value;
use std::fmt;

/// Result message for completed queries
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResultMessage {
    pub subtype: ResultSubtype,
    pub is_error: bool,
    pub duration_ms: u64,
    pub duration_api_ms: u64,

    /// Time to first token, in milliseconds.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ttft_ms: Option<u64>,

    /// Time to first streamed token, in milliseconds.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ttft_stream_ms: Option<u64>,

    /// Time from session start until the first request was issued, in milliseconds.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub time_to_request_ms: Option<u64>,

    /// How [`time_to_request_ms`](Self::time_to_request_ms) was spent, in
    /// integer milliseconds per phase, summing to it exactly (CLI 2.1.285+):
    /// `system_prompt`, `system_prompt_rebuild` (a second assembly of the
    /// system prompt, run when the tool pool re-read after the message was
    /// handled differs from the turn-start pool; CLIs before 2.1.287 report
    /// it inside `system_prompt`), `resume_other` (settling, before the
    /// turn's own prompt, tool calls that an earlier run left open or the
    /// session's client handed over — see
    /// [`turn_start_resume_kind`](Self::turn_start_resume_kind) — excluding
    /// four parts that have keys of their own: `resume_store_confirm`,
    /// `resume_staged_files_wait`, `resume_connector_wait` and
    /// `turn_start_tool_run`; CLIs before 2.1.287 report these five as one
    /// `turn_start_resume` key), `process_user_input` (excluding
    /// `input_images`, `input_attachments`, `input_command` and
    /// `input_hooks`, which have keys of their own on 2.1.287+),
    /// `transcript_persist`, `init_message`, `engine_pickup`,
    /// `memory_recall_wait`, `memory_context_wait`, `autocompact`,
    /// `query_setup`, `tool_schema_build`, `message_normalization`,
    /// `client_creation` and `other` (the remainder no phase covers). A phase
    /// that did not run is absent; `other` is always present. Open set —
    /// keep unrecognized phase names. Present where `time_to_request_ms` is,
    /// on `CLAUDE_CODE_REMOTE` sessions and hosts that set
    /// `CLAUDE_CODE_EMIT_STARTUP_TIMING`; absent elsewhere.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub time_to_request_phases_ms: Option<std::collections::BTreeMap<String, u64>>,

    /// What the turn was given to settle before its own prompt; the
    /// `resume_*` phases and `turn_start_tool_run` in
    /// [`time_to_request_phases_ms`](Self::time_to_request_phases_ms) say how
    /// long that took (CLI 2.1.287+). A turn given more than one kind reports
    /// the first in [`TurnStartResumeKind`] order. Present where
    /// `time_to_request_phases_ms` is.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub turn_start_resume_kind: Option<TurnStartResumeKind>,

    /// Number of earlier turns of this CLI process that sent a
    /// main-conversation model request: 0 is the process's first turn to
    /// reach the model, not the conversation's first. Turns stopped or
    /// failed after sending count but carry no value, so values can skip.
    /// Where one process hosts several sessions, each has its own count.
    /// Present where
    /// [`time_to_request_phases_ms`](Self::time_to_request_phases_ms) is
    /// (CLI 2.1.285+).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub process_turn_index: Option<u64>,

    /// CPU time (user plus system) the CLI process used from turn start
    /// until it sent the turn's first main-conversation model request, in
    /// milliseconds (CLI 2.1.285+). Near `time_to_request_ms`, the window
    /// was mostly computing; near 0, mostly waiting. It adds up all threads,
    /// so it can exceed the window, and leaves out child processes. Present
    /// where `time_to_request_phases_ms` is, unless the runtime reports no
    /// resource usage or the process hosts other sessions too.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub time_to_request_cpu_ms: Option<u64>,

    /// The longest single stall of the session's thread between turn start
    /// and the turn's first main-conversation model request, in
    /// milliseconds, measured as how late a 50 ms timer fired (CLI
    /// 2.1.285+): the real stall can be up to 50 ms longer, and a few ms is
    /// timer noise. Only the first two minutes are measured. Present where
    /// `time_to_request_phases_ms` is.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub time_to_request_loop_lag_ms: Option<u64>,

    /// Major page faults (waits for memory to be read from disk) by the
    /// process in the
    /// [`time_to_request_cpu_ms`](Self::time_to_request_cpu_ms) window;
    /// Windows also counts faults needing no disk read. Present where
    /// `time_to_request_cpu_ms` is (CLI 2.1.285+).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub time_to_request_major_faults: Option<u64>,

    /// What the `input_attachments` phase of `time_to_request_phases_ms` did
    /// on the turn, to tell a wait inside one attachment producer from a
    /// process that was busy. Present on turns where the phase started,
    /// unless nothing of it is known (CLI 2.1.288+).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub input_attachments_detail: Option<InputAttachmentsDetail>,

    /// How the `resume_store_confirm` phase of `time_to_request_phases_ms`
    /// was spent. Present where that phase is, in a session whose transcript
    /// goes to a hosted store: on the result of a handed-off turn whose lines
    /// were confirmed and that went on to a model request (CLI 2.1.290+).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub resume_store_confirm_detail: Option<ResumeStoreConfirmDetail>,

    /// Time from spawning a worker/spare until the first request was issued, in milliseconds.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub time_to_request_from_spawn_ms: Option<u64>,

    /// Whether a warm spare process was claimed for this request.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub warm_spare_claimed: Option<bool>,

    /// Whether this process started its start-up feature-flag fetch before
    /// the wait for it, or why not: the same value as `system/init`'s
    /// `startup_timing.flag_fetch_kick`. An open string set
    /// (`started_in_init_*`, `started_after_init_*`, `not_asked_warm`,
    /// `settings_pending_*`, `launch_excluded`, `not_eligible`; an `_empty`
    /// or `_warm` ending is the flag cache at that moment). Present only
    /// where `time_to_request_from_spawn_ms` is, and only when start-up
    /// judged it (CLI 2.1.288+).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub flag_fetch_kick: Option<String>,

    /// Epoch-ish timestamp origin used by CLI timing instrumentation.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub time_origin_ms: Option<u64>,

    /// Wall-clock epoch milliseconds when the API request was sent
    /// (fractional; from CLI timing instrumentation).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub request_sent_wall_ms: Option<f64>,

    /// Input tokens of the model call whose send time is
    /// [`request_sent_wall_ms`](Self::request_sent_wall_ms): `input_tokens +
    /// cache_read_input_tokens + cache_creation_input_tokens` from that call's
    /// `message_start`, so a consumer can group turn latency by prompt size
    /// (CLI 2.1.286+). Present only with `request_sent_wall_ms`, and only
    /// when the sum is above zero.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub first_request_input_tokens: Option<u64>,

    /// Time until the first content frame of the stream arrived, in
    /// milliseconds (CLI 2.1.260+ timing instrumentation).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub first_content_frame_ms: Option<u64>,

    /// Time until the first stream POST was issued, in milliseconds
    /// (CLI 2.1.260+).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub first_stream_post_ms: Option<u64>,

    /// Time until the first stream POST was acknowledged, in milliseconds
    /// (CLI 2.1.260+).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub first_stream_post_ack_ms: Option<u64>,

    /// Time the first stream POST spent waiting in the outbound queue, in
    /// milliseconds (CLI 2.1.278+).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub first_stream_post_queue_wait_ms: Option<u64>,

    /// What the first stream POST was queued behind (CLI 2.1.278+).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub first_stream_post_queued_behind: Option<StreamPostQueuedBehind>,

    /// Wall-clock epoch milliseconds when the first stream POST was issued
    /// (fractional; CLI 2.1.260+).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub first_stream_post_wall_ms: Option<f64>,

    /// Wall-clock epoch milliseconds when the triggering send's frame arrived
    /// on a session reading its input from the session server's SSE stream
    /// (`--sdk-url`), before the input loop read it (CLI 2.1.278+). With
    /// [`frame_enqueued_wall_ms`](Self::frame_enqueued_wall_ms) and
    /// [`turn_started_wall_ms`](Self::turn_started_wall_ms) it splits the
    /// stretch between the server's persist and `request_sent_wall_ms` into
    /// transit, the input loop's handling of the frame, its wait on the
    /// command queue, and the turn's own work. Present only together with
    /// `request_sent_wall_ms`, and only when the transport recorded the
    /// receipt; absent on a local stdin host.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub frame_received_wall_ms: Option<f64>,

    /// Wall-clock epoch milliseconds when the input loop put the triggering
    /// send's frame on the command queue (CLI 2.1.278+). Present exactly
    /// when [`frame_received_wall_ms`](Self::frame_received_wall_ms) is.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub frame_enqueued_wall_ms: Option<f64>,

    /// How the triggering send's frame spent the time between
    /// [`frame_received_wall_ms`](Self::frame_received_wall_ms) and
    /// [`frame_enqueued_wall_ms`](Self::frame_enqueued_wall_ms), in integer
    /// milliseconds per intake step (CLI 2.1.282+): `before_read` (until the
    /// input loop read the frame, including any wait behind earlier frames
    /// and a first message's wait for the worker to finish starting),
    /// `dedup`, `flag_settle`, `receive_hook`, `attachments`,
    /// `admission_wait` (held behind a pending model switch, a pending MCP
    /// server-set change, start-up work the worker still owed its first
    /// turn, or an earlier held frame), `admit_check` (the host's decision
    /// whether to queue the frame, when it had to be awaited) and `other`.
    /// Steps that did not run are absent; `before_read` and `other` are
    /// always present. The values sum to the enqueued-minus-received gap
    /// unless a step came out negative and was clamped to 0. Open set —
    /// keep unrecognized step names. Present exactly when
    /// `frame_received_wall_ms` is, except from older producers.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub frame_intake_phases_ms: Option<std::collections::BTreeMap<String, u64>>,

    /// Wall-clock epoch milliseconds when the turn's clock started: the
    /// anchor `duration_ms`, `ttft_ms`, `ttft_stream_ms`,
    /// `time_to_request_ms`, `first_content_frame_ms`, `first_stream_post_ms`
    /// and `first_stream_post_ack_ms` are measured from (CLI 2.1.278+).
    /// Present exactly when
    /// [`frame_received_wall_ms`](Self::frame_received_wall_ms) is.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub turn_started_wall_ms: Option<f64>,

    /// How the time from
    /// [`frame_enqueued_wall_ms`](Self::frame_enqueued_wall_ms) to
    /// [`turn_started_wall_ms`](Self::turn_started_wall_ms) was spent, in
    /// integer milliseconds per step of the host's work through its message
    /// queue (CLI 2.1.285+): `idle`, `earlier_turn`, `after_turn`,
    /// `background_wait`, `entry_joins`, `sdk_mcp_update`, `loop_top`,
    /// `session_start_wait`, `first_command`, `mcp_prewait`, `repo_wait`,
    /// `turn_joins`, `tool_pool`, `commit`, `after_arm`, `turn_gate`,
    /// `turn_open`, `engine_setup`, `tool_reread`, `cwd` and `other`. Each
    /// step is where the host was at the time, which for part of the stretch
    /// may be an earlier message's turn. A step that rounds to 0 is absent;
    /// `other` is always present. The values sum to the started-minus-enqueued
    /// gap, except that they can exceed it (usually by 1 ms from rounding).
    /// Open set — keep unrecognized step names. Present only when
    /// `frame_received_wall_ms` is, and absent from older producers.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub turn_start_phases_ms: Option<std::collections::BTreeMap<String, u64>>,

    /// Of the time from `frame_enqueued_wall_ms` to `turn_started_wall_ms`,
    /// the integer milliseconds in which the `claude -p` host's message
    /// reader was held by control requests (such as `mcp_set_servers` or
    /// `set_permission_mode`) instead of reading the next message (CLI
    /// 2.1.285+). It overlaps
    /// [`turn_start_phases_ms`](Self::turn_start_phases_ms) and is not part
    /// of its sum. Absent when 0.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub turn_start_control_requests_ms: Option<u64>,

    /// Time until the first text POST was issued, in milliseconds
    /// (CLI 2.1.278+).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub first_text_post_ms: Option<u64>,

    /// Time the first text POST spent waiting in the outbound queue, in
    /// milliseconds (CLI 2.1.287+).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub first_text_post_queue_wait_ms: Option<u64>,

    /// What the first text POST was queued behind (CLI 2.1.287+); the same
    /// value set as
    /// [`first_stream_post_queued_behind`](Self::first_stream_post_queued_behind).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub first_text_post_queued_behind: Option<StreamPostQueuedBehind>,

    /// Wall-clock epoch milliseconds when the first text POST was issued
    /// (fractional; CLI 2.1.278+).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub first_text_post_wall_ms: Option<f64>,

    /// Wire uuid of the user message this result answers.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub user_message_uuid: Option<String>,

    /// The [`server_received_wall_ms`](crate::io::UserMessage::server_received_wall_ms)
    /// of the user message [`user_message_uuid`](Self::user_message_uuid)
    /// names, copied unchanged, so the session server can measure from its
    /// own receipt to `request_sent_wall_ms` (CLI 2.1.286+). Present only with
    /// `request_sent_wall_ms`, and only when that message carried a positive
    /// finite number there.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub user_message_server_received_wall_ms: Option<f64>,

    /// Client uuids of every user message whose prompt this turn consumed, in
    /// consumption order — all members of a prompt batch the host merged into
    /// this one turn, plus any queued user message folded into the running
    /// turn between tool rounds. Always contains `user_message_uuid`; at most
    /// 64 entries. Absent on delivery-failure/zeroed results and from CLIs
    /// before 2.1.259 (fall back to `user_message_uuid`).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub user_message_uuids: Vec<String>,

    /// Why this turn was the automatic re-run of a turn a worker restart
    /// interrupted (`CLAUDE_CODE_RESUME_INTERRUPTED_TURN`): the host's
    /// `CLAUDE_CODE_RESUME_REASON` when it set one (`host_draining`,
    /// `checkpoint_restore`, `container_recreated`, ...), else
    /// `interrupted_turn`. Present on a headless re-run's result, success or
    /// error; absent on every other turn, on the Remote Control bridge's
    /// per-turn synthetic results, and from CLIs before 2.1.268.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub resume_reason: Option<String>,

    /// The local slash command that produced this result when the query loop
    /// was bypassed (success results only). Absent when the turn went to the
    /// model and from CLIs before 2.1.268.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub local_command: Option<String>,

    /// User-initiated sends still waiting in the command queue when this
    /// result was produced. Greater than 0 means at least one more user turn
    /// follows without further input, barring cancellation. Absent on fatal
    /// startup results, on surfaces without a command queue, and from CLIs
    /// before 2.1.259.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub queued_turn_count: Option<u64>,

    pub num_turns: i32,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub result: Option<String>,

    #[serde(alias = "sessionId")]
    pub session_id: String,
    pub total_cost_usd: f64,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub usage: Option<UsageInfo>,

    /// Tools that were blocked due to permission denials during the session
    #[serde(default)]
    pub permission_denials: Vec<PermissionDenial>,

    /// Error messages when `is_error` is true.
    ///
    /// Contains human-readable error strings (e.g., "No conversation found with session ID: ...").
    /// This allows typed access to error conditions without needing to serialize to JSON and search.
    #[serde(default)]
    pub errors: Vec<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub uuid: Option<String>,

    /// HTTP status code when the result is an API error (e.g., 429, 500, 529)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub api_error_status: Option<u16>,

    /// The `api_error_code` of the API error that ended the turn (see
    /// `AssistantMessage::api_error_code`): the server's
    /// `error.details.error_code` when it is an identifier. Absent when the
    /// turn did not end on an API error, when the response carried no code,
    /// and from CLIs before 2.1.274.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub api_error_code: Option<String>,

    /// The typed kind of the API error that ended the turn (see
    /// `AssistantMessage::api_error`). Absent when the turn did not end on
    /// an API error, when the error has no typed kind, and from CLIs before
    /// 2.1.285; treat an unknown value as absent.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub api_error: Option<String>,

    /// Why generation stopped (e.g., end_turn, max_tokens)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stop_reason: Option<String>,

    /// Why the session ended (e.g., "completed")
    #[serde(skip_serializing_if = "Option::is_none")]
    pub terminal_reason: Option<String>,

    /// Delivery sequence of this result within the run: how many results the
    /// run numbered before this one, starting at 0, in the order the process
    /// writes them. A result whose write fails still consumes its number, so
    /// a gap means a result was lost. Distinct from `num_turns`. Numbered by
    /// the process hosting the run (`claude -p`); a local client relaying a
    /// cloud session passes the cloud numbering through and its own locally
    /// built error results carry none. Absent from CLIs before 2.1.268.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub result_index: Option<u64>,

    /// Fast mode toggle state (e.g., "off")
    #[serde(skip_serializing_if = "Option::is_none")]
    pub fast_mode_state: Option<String>,

    /// Why fast mode can't serve right now. Absent when nothing blocks it.
    /// A paused-after-rate-limit run is not reported here; it rides
    /// `fast_mode_state` as `"cooldown"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub fast_mode_disabled_reason: Option<FastModeDisabledReason>,

    /// Per-model cost breakdown, keyed by model name (e.g. `"claude-opus-4-8"`).
    #[serde(skip_serializing_if = "Option::is_none", rename = "modelUsage")]
    pub model_usage: Option<std::collections::BTreeMap<String, ModelUsageEntry>>,

    /// Subagents started through the Agent tool in this session, as running
    /// totals. Cumulative like `modelUsage`: read the latest result rather
    /// than summing across results. Absent from CLIs before 2.1.239.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub subagent_stats: Option<SubagentStats>,

    /// How many times a safety system has stopped one of this session's
    /// model calls (main loop, subagents, forked skills, compaction and other
    /// internal calls), as a running total since the session started in this
    /// process: a `refusal` stop reason, a refusal answered on a fallback
    /// model, output the API's content filter stopped, and (where the build
    /// can tell) a server-side safety monitor block. Never sum across
    /// results. Not saved, so a resumed session or a mid-session `/clear`
    /// starts again at 0: over a stored log any result above 0 means a stop
    /// happened, and a later 0 does not cancel it. Absent from CLIs before
    /// 2.1.292. Marked `@internal` upstream.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub safety_stops: Option<u64>,

    /// Structured-output payload returned by the model, when enabled.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub structured_output: Option<Value>,

    /// Deferred tool-use termination payload.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub deferred_tool_use: Option<DeferredToolUse>,

    /// Provenance of the message/run.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub origin: Option<super::message_types::MessageOrigin>,

    /// Set by the self-hosted runner on the result it synthesizes when the
    /// session process fails to start or exits abnormally. Absent on normal
    /// results and on CLIs before 2.1.266.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub runner_exit: Option<RunnerExit>,

    /// Why Claude Code refused to start. Set on the zeroed
    /// `error_during_execution` result a stream-json run writes before
    /// exiting on a known startup failure; `errors` carries the same text as
    /// stderr. Failures that used to end with stderr alone write that result
    /// only when the host sets `CLAUDE_CODE_STARTUP_FAILURE_RESULTS`. Absent
    /// on every other result, on startup failures without a known cause, and
    /// from CLIs before 2.1.274.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub startup_failure_reason: Option<StartupFailureReason>,
}

/// [`ResultMessage::input_attachments_detail`] — what the
/// `input_attachments` phase did on the turn (CLI 2.1.288+).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
pub struct InputAttachmentsDetail {
    /// Label of the attachment producer that took longest from its start to
    /// its result, among those that began within the phase.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub slowest_producer: Option<String>,
    /// How long [`Self::slowest_producer`] took. Well above
    /// [`Self::cpu_ms`], that producer most likely waited (on a file, the
    /// network or a child process).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub slowest_producer_ms: Option<u64>,
    /// `time_to_request_cpu_ms`'s counter over this phase alone. Absent
    /// wherever `time_to_request_cpu_ms` is absent, and when the turn's
    /// first model request went out before the phase ended.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cpu_ms: Option<u64>,
    /// `time_to_request_major_faults`'s counter over this phase alone.
    /// Absent where [`Self::cpu_ms`] is.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub major_faults: Option<u64>,
    /// How many files the `changed_files` producer set out to read again in
    /// full because their modification time was later than the one recorded
    /// when the conversation last wrote or edited them. Absent when the
    /// conversation's record of files was empty or the producer did not run.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub changed_files_reread: Option<u64>,
}

/// [`ResultMessage::resume_store_confirm_detail`] — how the
/// `resume_store_confirm` phase was spent (CLI 2.1.290+). The four `_ms`
/// values sum to that phase exactly.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
pub struct ResumeStoreConfirmDetail {
    /// The transcript write, until the carried lines are in the queue of the
    /// lane that uploads transcript rows.
    pub write_ms: u64,
    /// A POST was out that held only rows queued before the hand-off's write
    /// began.
    pub ahead_ms: u64,
    /// Any other POST was out, each retry included.
    pub post_ms: u64,
    /// No POST was out (backoff, batching, a busy event loop), plus rounding
    /// and any POST still out when the wait was cut short.
    pub other_ms: u64,
    /// POST attempts that ended between the start of the write and the end
    /// of the wait.
    pub posts: u64,
    /// Those of [`Self::posts`] that did not go through.
    pub failed_posts: u64,
    /// Rows the lane had accepted and the store had not yet confirmed when
    /// the write began.
    pub rows_ahead: u64,
    /// Rows queued since then that a POST delivered, the carried lines among
    /// them.
    pub rows: u64,
}

/// Why Claude Code refused to start, carried as
/// [`ResultMessage::startup_failure_reason`] so a host can offer the fix
/// instead of a retry (CLI 2.1.274+).
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum StartupFailureReason {
    /// Managed settings pin a first-party or Cloud gateway sign-in, and an
    /// Anthropic API key or auth token is configured instead.
    OrgPinApiKeyConflict,
    /// Managed settings list the API providers this machine may use
    /// (`allowedProviders`), and the session is set up for one that is not
    /// listed (CLI 2.1.285+).
    ProviderNotAllowed,
    /// The sign-in's organization could not be verified against the pin
    /// (network, or a revoked token).
    OrgVerifyFailed,
    /// The sign-in belongs to an organization the pin does not allow.
    OrgPinMismatch,
    /// Managed policy settings could not be read, the pin names no
    /// organization, or managed model settings (`deniedModels`, or an
    /// `availableModels` list matched exactly) block the default model and
    /// leave no allowed model to use instead.
    ManagedSettingsInvalid,
    /// Managed settings the organization requires could not be loaded.
    RemoteSettingsRequiredUnavailable,
    /// The Cloud gateway ended this sign-in.
    GatewaySigninRequired,
    /// The Cloud gateway refused managed settings for this account.
    GatewayAccessDenied,
    /// A proxy setting is not a complete URL.
    ProxyInvalid,
    /// The per-user temp directory is unsafe or could not be created.
    TempDirUnusable,
    /// The working directory was deleted, moved or cannot be read.
    CwdUnavailable,
    /// Windows has no shell tool: Git Bash is missing, and PowerShell is
    /// missing or turned off by `CLAUDE_CODE_USE_POWERSHELL_TOOL`.
    ShellToolMissing,
    /// The conversation to resume or continue is running as a background
    /// session.
    SessionHeldByBackground,
    /// The resume was refused because the session's worktree failed its
    /// safety checks or the resume was launched from inside it; `errors`
    /// says whether a re-run continues without the worktree.
    WorktreeResumeRefused,
    /// The session's worktree could not be verified right now; retrying may
    /// succeed.
    WorktreeUnverified,
    /// This Claude Code version is below the minimum Anthropic requires.
    CliVersionTooOld,
    /// Bypass permissions mode was requested while running as root.
    BypassRoot,
    /// The organization requires its policy limits and managed settings
    /// before a session starts, and they could not be loaded (network,
    /// proxy, or an Anthropic error); retrying may succeed (CLI 2.1.293+).
    OrgConfigRequiredUnavailable,
    /// The organization requires its policy limits and managed settings, and
    /// Anthropic refused them for this sign-in (expired or revoked session,
    /// or the organization does not allow Claude Code for this account);
    /// signing in again or an admin's change is the fix, not a retry
    /// (CLI 2.1.293+).
    OrgConfigRefused,
    /// A cause not yet known to this version of the crate.
    Unknown(String),
}

impl StartupFailureReason {
    pub fn as_str(&self) -> &str {
        match self {
            Self::OrgPinApiKeyConflict => "org_pin_api_key_conflict",
            Self::ProviderNotAllowed => "provider_not_allowed",
            Self::OrgVerifyFailed => "org_verify_failed",
            Self::OrgPinMismatch => "org_pin_mismatch",
            Self::ManagedSettingsInvalid => "managed_settings_invalid",
            Self::RemoteSettingsRequiredUnavailable => "remote_settings_required_unavailable",
            Self::GatewaySigninRequired => "gateway_signin_required",
            Self::GatewayAccessDenied => "gateway_access_denied",
            Self::ProxyInvalid => "proxy_invalid",
            Self::TempDirUnusable => "temp_dir_unusable",
            Self::CwdUnavailable => "cwd_unavailable",
            Self::ShellToolMissing => "shell_tool_missing",
            Self::SessionHeldByBackground => "session_held_by_background",
            Self::WorktreeResumeRefused => "worktree_resume_refused",
            Self::WorktreeUnverified => "worktree_unverified",
            Self::CliVersionTooOld => "cli_version_too_old",
            Self::BypassRoot => "bypass_root",
            Self::OrgConfigRequiredUnavailable => "org_config_required_unavailable",
            Self::OrgConfigRefused => "org_config_refused",
            Self::Unknown(s) => s.as_str(),
        }
    }
}

impl fmt::Display for StartupFailureReason {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl From<&str> for StartupFailureReason {
    fn from(s: &str) -> Self {
        match s {
            "org_pin_api_key_conflict" => Self::OrgPinApiKeyConflict,
            "provider_not_allowed" => Self::ProviderNotAllowed,
            "org_verify_failed" => Self::OrgVerifyFailed,
            "org_pin_mismatch" => Self::OrgPinMismatch,
            "managed_settings_invalid" => Self::ManagedSettingsInvalid,
            "remote_settings_required_unavailable" => Self::RemoteSettingsRequiredUnavailable,
            "gateway_signin_required" => Self::GatewaySigninRequired,
            "gateway_access_denied" => Self::GatewayAccessDenied,
            "proxy_invalid" => Self::ProxyInvalid,
            "temp_dir_unusable" => Self::TempDirUnusable,
            "cwd_unavailable" => Self::CwdUnavailable,
            "shell_tool_missing" => Self::ShellToolMissing,
            "session_held_by_background" => Self::SessionHeldByBackground,
            "worktree_resume_refused" => Self::WorktreeResumeRefused,
            "worktree_unverified" => Self::WorktreeUnverified,
            "cli_version_too_old" => Self::CliVersionTooOld,
            "bypass_root" => Self::BypassRoot,
            "org_config_required_unavailable" => Self::OrgConfigRequiredUnavailable,
            "org_config_refused" => Self::OrgConfigRefused,
            other => Self::Unknown(other.to_string()),
        }
    }
}

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

impl<'de> Deserialize<'de> for StartupFailureReason {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let s = String::deserialize(deserializer)?;
        Ok(Self::from(s.as_str()))
    }
}

/// How the self-hosted runner's session process terminated, carried on a
/// synthesized failure [`ResultMessage`] as [`ResultMessage::runner_exit`]
/// (CLI 2.1.266+).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct RunnerExit {
    /// Which phase the process was in when it exited.
    pub phase: RunnerExitPhase,
    /// Process exit code. Absent (or wire `null`) when it exited on a signal
    /// instead, or when the runner did not capture one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub exit_code: Option<i64>,
    /// Terminating signal name. Absent (or wire `null`) when it exited with a
    /// code instead, or when the runner did not capture one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub signal: Option<String>,
}

/// Which phase the runner's session process was in when it exited, in
/// [`RunnerExit::phase`]. Open set — unrecognized values deserialize to
/// [`RunnerExitPhase::Unknown`].
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum RunnerExitPhase {
    /// Failed while starting up.
    Setup,
    /// Failed once running.
    Run,
    /// A phase not yet known to this version of the crate.
    Unknown(String),
}

impl RunnerExitPhase {
    pub fn as_str(&self) -> &str {
        match self {
            Self::Setup => "setup",
            Self::Run => "run",
            Self::Unknown(s) => s.as_str(),
        }
    }
}

impl std::fmt::Display for RunnerExitPhase {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

impl From<&str> for RunnerExitPhase {
    fn from(s: &str) -> Self {
        match s {
            "setup" => Self::Setup,
            "run" => Self::Run,
            other => Self::Unknown(other.to_string()),
        }
    }
}

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

impl<'de> Deserialize<'de> for RunnerExitPhase {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let s = String::deserialize(deserializer)?;
        Ok(Self::from(s.as_str()))
    }
}

/// Usage and cost for a single model within a session, as found in
/// [`ResultMessage::model_usage`].
///
/// The `extra` field captures any keys the CLI adds that aren't modeled here,
/// so new wire fields deserialize without error.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ModelUsageEntry {
    #[serde(default)]
    pub input_tokens: u64,
    #[serde(default)]
    pub output_tokens: u64,
    #[serde(default)]
    pub cache_read_input_tokens: u64,
    #[serde(default)]
    pub cache_creation_input_tokens: u64,
    #[serde(default, rename = "costUSD")]
    pub cost_usd: f64,
    #[serde(default)]
    pub web_search_requests: u32,
    #[serde(default)]
    pub context_window: u64,
    #[serde(default)]
    pub max_output_tokens: u64,
    #[serde(flatten)]
    pub extra: serde_json::Map<String, serde_json::Value>,
}

/// Tool use deferred by a terminal result.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct DeferredToolUse {
    pub id: String,
    pub name: String,
    pub input: Value,
}

/// Running totals for subagents started through the Agent tool, carried on
/// `result` frames (CLI 2.1.239+) as [`ResultMessage::subagent_stats`].
///
/// Cumulative for the session: a resumed session starts fresh, and a
/// mid-session `/clear` zeroes it — though a background subagent that outlives
/// the `/clear` still records its outcome, so `completed`, `failed`, and
/// `killed` can then exceed `spawned`. Forked skills, workflows, teammates,
/// and other internal agents are not counted.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub struct SubagentStats {
    /// Subagents actually started; a refused or failed launch is not counted.
    pub spawned: u64,
    /// Spawns by the `run_in_background` value the model passed; all count as
    /// `unset` while the parameter is not offered.
    pub requested: SubagentSpawnRequests,
    /// Spawns that started in the background after defaults and session
    /// settings; the rest blocked the spawning tool call.
    pub started_in_background: u64,
    /// Spawns by agent type.
    #[serde(default)]
    pub by_type: std::collections::BTreeMap<String, u64>,
    /// Deepest spawn: 1 = started by the main thread, 2 = by a depth-1
    /// subagent.
    pub max_depth: u64,
    /// Spawns made from inside another subagent (depth > 1).
    pub spawned_by_subagents: u64,
    pub completed: u64,
    pub failed: u64,
    /// Subagents stopped before finishing, by who stopped them.
    pub killed: SubagentKillCounts,
    /// Agent tool calls turned down because a limit was reached (other
    /// denials, such as an unknown agent type, are not counted).
    pub refused: SubagentRefusalCounts,
}

/// Spawn counts by the `run_in_background` value the model passed, carried in
/// [`SubagentStats::requested`].
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub struct SubagentSpawnRequests {
    pub background: u64,
    pub foreground: u64,
    pub unset: u64,
}

/// Subagents stopped before finishing, carried in [`SubagentStats::killed`].
/// `parent` = by another agent through TaskStop; `system` = by Claude Code
/// itself; `user` = any other stop.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub struct SubagentKillCounts {
    pub parent: u64,
    pub user: u64,
    pub system: u64,
}

/// Agent tool calls refused at a limit, carried in [`SubagentStats::refused`].
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub struct SubagentRefusalCounts {
    pub depth_limit: u64,
    pub concurrency_limit: u64,
    pub budget: u64,
}

/// A record of a tool permission that was denied during the session.
///
/// This is included in `ResultMessage.permission_denials` to provide a summary
/// of all permission denials that occurred.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct PermissionDenial {
    /// The name of the tool that was blocked (e.g., "Bash", "Write")
    pub tool_name: String,

    /// The input that was passed to the tool
    pub tool_input: Value,

    /// The unique identifier for this tool use request
    pub tool_use_id: String,
}

/// What the first stream POST of a turn was queued behind, carried as
/// [`ResultMessage::first_stream_post_queued_behind`] (CLI 2.1.278+).
/// Internal timing instrumentation; the CLI does not describe the values.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum StreamPostQueuedBehind {
    /// `durable_post`
    DurablePost,
    /// `ephemeral_post`
    EphemeralPost,
    /// `retry_backoff`
    RetryBackoff,
    /// `hold`
    Hold,
    /// `none`
    None,
    /// A value not yet known to this version of the crate.
    Unknown(String),
}

impl StreamPostQueuedBehind {
    pub fn as_str(&self) -> &str {
        match self {
            Self::DurablePost => "durable_post",
            Self::EphemeralPost => "ephemeral_post",
            Self::RetryBackoff => "retry_backoff",
            Self::Hold => "hold",
            Self::None => "none",
            Self::Unknown(s) => s.as_str(),
        }
    }
}

impl fmt::Display for StreamPostQueuedBehind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl From<&str> for StreamPostQueuedBehind {
    fn from(s: &str) -> Self {
        match s {
            "durable_post" => Self::DurablePost,
            "ephemeral_post" => Self::EphemeralPost,
            "retry_backoff" => Self::RetryBackoff,
            "hold" => Self::Hold,
            "none" => Self::None,
            other => Self::Unknown(other.to_string()),
        }
    }
}

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

impl<'de> Deserialize<'de> for StreamPostQueuedBehind {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let s = String::deserialize(deserializer)?;
        Ok(Self::from(s.as_str()))
    }
}

/// What a turn was given to settle before its own prompt, carried as
/// [`ResultMessage::turn_start_resume_kind`] (CLI 2.1.287+). A turn given
/// more than one reports the first in this order.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum TurnStartResumeKind {
    /// `orphaned_permission` — a permission answer whose pending request was
    /// lost (as when a worker restarts), so the tool call is settled with
    /// that answer.
    OrphanedPermission,
    /// `turn_handoff` — a turn in progress that the session's client handed
    /// over.
    TurnHandoff,
    /// `deferred_tool_use` — a call a `PreToolUse` hook deferred.
    DeferredToolUse,
    /// `none` — nothing to settle (`resume_other` is still reported, at
    /// about 0).
    None,
    /// A value not yet known to this version of the crate.
    Unknown(String),
}

impl TurnStartResumeKind {
    pub fn as_str(&self) -> &str {
        match self {
            Self::OrphanedPermission => "orphaned_permission",
            Self::TurnHandoff => "turn_handoff",
            Self::DeferredToolUse => "deferred_tool_use",
            Self::None => "none",
            Self::Unknown(s) => s.as_str(),
        }
    }
}

impl fmt::Display for TurnStartResumeKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl From<&str> for TurnStartResumeKind {
    fn from(s: &str) -> Self {
        match s {
            "orphaned_permission" => Self::OrphanedPermission,
            "turn_handoff" => Self::TurnHandoff,
            "deferred_tool_use" => Self::DeferredToolUse,
            "none" => Self::None,
            other => Self::Unknown(other.to_string()),
        }
    }
}

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

impl<'de> Deserialize<'de> for TurnStartResumeKind {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let s = String::deserialize(deserializer)?;
        Ok(Self::from(s.as_str()))
    }
}

/// Why fast mode can't serve right now, carried on `result` frames and
/// `system/init` (CLI 2.1.219+). Absent when nothing blocks fast mode.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum FastModeDisabledReason {
    /// Free-tier account.
    Free,
    /// Disabled by user preference.
    Preference,
    /// Extra-usage purchases are disabled for the account.
    ExtraUsageDisabled,
    /// A network error prevented fast-mode eligibility from resolving.
    NetworkError,
    /// The CLI could not determine the reason.
    UnknownReason,
    /// Not a first-party API session (e.g. Bedrock/Vertex).
    NotFirstParty,
    /// Disabled via environment variable.
    DisabledByEnv,
    /// The active model does not support fast mode.
    ModelNotAllowed,
    /// SDK sessions must opt in to fast mode.
    SdkOptInRequired,
    /// Eligibility is still being determined.
    Pending,
    /// A reason not yet known to this version of the crate.
    Unknown(String),
}

impl FastModeDisabledReason {
    pub fn as_str(&self) -> &str {
        match self {
            Self::Free => "free",
            Self::Preference => "preference",
            Self::ExtraUsageDisabled => "extra_usage_disabled",
            Self::NetworkError => "network_error",
            Self::UnknownReason => "unknown",
            Self::NotFirstParty => "not_first_party",
            Self::DisabledByEnv => "disabled_by_env",
            Self::ModelNotAllowed => "model_not_allowed",
            Self::SdkOptInRequired => "sdk_opt_in_required",
            Self::Pending => "pending",
            Self::Unknown(s) => s.as_str(),
        }
    }
}

impl fmt::Display for FastModeDisabledReason {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl From<&str> for FastModeDisabledReason {
    fn from(s: &str) -> Self {
        match s {
            "free" => Self::Free,
            "preference" => Self::Preference,
            "extra_usage_disabled" => Self::ExtraUsageDisabled,
            "network_error" => Self::NetworkError,
            "unknown" => Self::UnknownReason,
            "not_first_party" => Self::NotFirstParty,
            "disabled_by_env" => Self::DisabledByEnv,
            "model_not_allowed" => Self::ModelNotAllowed,
            "sdk_opt_in_required" => Self::SdkOptInRequired,
            "pending" => Self::Pending,
            other => Self::Unknown(other.to_string()),
        }
    }
}

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

impl<'de> Deserialize<'de> for FastModeDisabledReason {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let s = String::deserialize(deserializer)?;
        Ok(Self::from(s.as_str()))
    }
}

/// Result subtypes
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum ResultSubtype {
    Success,
    ErrorMaxTurns,
    ErrorDuringExecution,
    ErrorMaxBudgetUsd,
    ErrorMaxStructuredOutputRetries,
    Unknown(String),
}

impl ResultSubtype {
    pub fn as_str(&self) -> &str {
        match self {
            Self::Success => "success",
            Self::ErrorMaxTurns => "error_max_turns",
            Self::ErrorDuringExecution => "error_during_execution",
            Self::ErrorMaxBudgetUsd => "error_max_budget_usd",
            Self::ErrorMaxStructuredOutputRetries => "error_max_structured_output_retries",
            Self::Unknown(s) => s.as_str(),
        }
    }
}

impl fmt::Display for ResultSubtype {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl From<&str> for ResultSubtype {
    fn from(s: &str) -> Self {
        match s {
            "success" => Self::Success,
            "error_max_turns" => Self::ErrorMaxTurns,
            "error_during_execution" => Self::ErrorDuringExecution,
            "error_max_budget_usd" => Self::ErrorMaxBudgetUsd,
            "error_max_structured_output_retries" => Self::ErrorMaxStructuredOutputRetries,
            other => Self::Unknown(other.to_string()),
        }
    }
}

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

impl<'de> Deserialize<'de> for ResultSubtype {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let s = String::deserialize(deserializer)?;
        Ok(Self::from(s.as_str()))
    }
}

/// Usage information for the request.
///
/// **These counters are accumulated roll-ups, not snapshots.** The CLI sums
/// usage field-by-field across every API call ("iteration") in the turn's
/// tool-use loop, so on a turn with N iterations each counter is the sum of
/// all N. This is the right number for **cost**, and the wrong number for
/// **context occupancy**: `cache_read_input_tokens` in particular re-counts
/// the cached context on every iteration and can exceed the model's context
/// window several times over on tool-heavy turns. To estimate context
/// occupancy, use the *last* entry of [`iterations`](Self::iterations)
/// instead (the CLI itself does exactly this).
///
/// Note: the `result` frame's usage covers the **main agent only** — the
/// subagent (`Task` / sidechain) token rollup the CLI renders as
/// `<subagent_tokens>` / `<agent_count>` is not carried here or anywhere
/// else on the wire. Accumulate it from `Task` tool results with
/// [`SubagentUsageRollup`](crate::SubagentUsageRollup).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UsageInfo {
    /// Sum of fresh (uncached) input tokens across all iterations of the turn.
    #[serde(default)]
    pub input_tokens: u32,
    /// Sum of cache-write input tokens across all iterations of the turn.
    #[serde(default)]
    pub cache_creation_input_tokens: u32,
    /// Sum of cache-read input tokens across all iterations of the turn.
    /// Re-counts the cached context every iteration — **not** a measure of
    /// context occupancy; see the type-level docs.
    #[serde(default)]
    pub cache_read_input_tokens: u32,
    /// Sum of output tokens across all iterations of the turn.
    #[serde(default)]
    pub output_tokens: u32,
    #[serde(default)]
    pub server_tool_use: ServerToolUse,
    #[serde(default)]
    pub service_tier: String,

    /// Cache creation breakdown
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cache_creation: Option<super::message_types::CacheCreationDetails>,

    /// Inference geography (e.g., "not_available")
    #[serde(skip_serializing_if = "Option::is_none")]
    pub inference_geo: Option<String>,

    /// Per-iteration usage breakdown **within** this turn — one entry per
    /// API call in the tool-use loop, in order. The last entry reflects the
    /// final API call and is what the CLI reads for context-size estimates.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub iterations: Vec<UsageIteration>,

    /// Speed tier (e.g., "standard")
    #[serde(skip_serializing_if = "Option::is_none")]
    pub speed: Option<String>,

    /// Output-token breakdown (CLI 2.1.232+): currently the thinking-token
    /// share of `output_tokens`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub output_tokens_details: Option<OutputTokensDetails>,

    /// Outcome of a fallback-credit token the request presented; `null` on
    /// the wire when it presented none (CLI 2.1.285+).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub fallback_credit: Option<Value>,
}

/// Breakdown of a turn's output tokens, carried in
/// [`UsageInfo::output_tokens_details`].
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct OutputTokensDetails {
    /// Output tokens spent on extended thinking.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub thinking_tokens: Option<u64>,
}

/// Usage for a single API call ("iteration") within a turn's tool-use loop.
///
/// Carried in [`UsageInfo::iterations`]. The cache fields are optional on
/// the wire: some frames carry only `input_tokens` + `output_tokens`
/// (observed with `type: "turn"`), while others carry the full cache
/// breakdown (observed with `type: "message"` in captured subagent
/// sessions). The CLI computes its context estimate from
/// `input_tokens + output_tokens` of the **last** iteration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UsageIteration {
    #[serde(default)]
    pub input_tokens: u32,
    #[serde(default)]
    pub output_tokens: u32,
    /// Cache-read input tokens for this iteration, when carried.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cache_read_input_tokens: Option<u32>,
    /// Cache-write input tokens for this iteration, when carried.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cache_creation_input_tokens: Option<u32>,
    /// Cache-write breakdown by TTL, when carried.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cache_creation: Option<super::message_types::CacheCreationDetails>,
    /// Iteration kind; `"turn"` and `"message"` observed on the wire.
    #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
    pub kind: Option<String>,
}

/// Server tool usage information
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ServerToolUse {
    #[serde(default)]
    pub web_search_requests: u32,
    /// Number of web fetch requests made
    #[serde(default)]
    pub web_fetch_requests: u32,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::io::ClaudeOutput;

    #[test]
    fn test_deserialize_result_message() {
        let json = r#"{
            "type": "result",
            "subtype": "success",
            "is_error": false,
            "duration_ms": 100,
            "duration_api_ms": 200,
            "num_turns": 1,
            "result": "Done",
            "session_id": "123",
            "total_cost_usd": 0.01,
            "permission_denials": []
        }"#;

        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
        assert!(!output.is_error());
    }

    #[test]
    fn test_result_subtype_new_and_unknown_values_do_not_fail() {
        let json = r#"{
            "type": "result",
            "subtype": "error_max_budget_usd",
            "is_error": true,
            "duration_ms": 100,
            "duration_api_ms": 200,
            "num_turns": 1,
            "session_id": "123",
            "total_cost_usd": 0.01
        }"#;

        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
        let ClaudeOutput::Result(result) = output else {
            panic!("Expected Result");
        };
        assert_eq!(result.subtype, ResultSubtype::ErrorMaxBudgetUsd);

        let json = r#"{
            "type": "result",
            "subtype": "future_result_subtype",
            "is_error": true,
            "duration_ms": 100,
            "duration_api_ms": 200,
            "num_turns": 1,
            "session_id": "123",
            "total_cost_usd": 0.01
        }"#;

        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
        let ClaudeOutput::Result(result) = output else {
            panic!("Expected Result");
        };
        assert_eq!(
            result.subtype,
            ResultSubtype::Unknown("future_result_subtype".to_string())
        );
    }

    #[test]
    fn test_deserialize_result_with_permission_denials() {
        let json = r#"{
            "type": "result",
            "subtype": "success",
            "is_error": false,
            "duration_ms": 100,
            "duration_api_ms": 200,
            "num_turns": 2,
            "result": "Done",
            "session_id": "123",
            "total_cost_usd": 0.01,
            "permission_denials": [
                {
                    "tool_name": "Bash",
                    "tool_input": {"command": "rm -rf /", "description": "Delete everything"},
                    "tool_use_id": "toolu_123"
                }
            ]
        }"#;

        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
        if let ClaudeOutput::Result(result) = output {
            assert_eq!(result.permission_denials.len(), 1);
            assert_eq!(result.permission_denials[0].tool_name, "Bash");
            assert_eq!(result.permission_denials[0].tool_use_id, "toolu_123");
            assert_eq!(
                result.permission_denials[0]
                    .tool_input
                    .get("command")
                    .unwrap(),
                "rm -rf /"
            );
        } else {
            panic!("Expected Result");
        }
    }

    #[test]
    fn test_permission_denial_roundtrip() {
        let denial = PermissionDenial {
            tool_name: "Write".to_string(),
            tool_input: serde_json::json!({"file_path": "/etc/passwd", "content": "bad"}),
            tool_use_id: "toolu_456".to_string(),
        };

        let json = serde_json::to_string(&denial).unwrap();
        assert!(json.contains("\"tool_name\":\"Write\""));
        assert!(json.contains("\"tool_use_id\":\"toolu_456\""));
        assert!(json.contains("/etc/passwd"));

        let parsed: PermissionDenial = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, denial);
    }

    #[test]
    fn test_deserialize_result_message_with_errors() {
        let json = r#"{
            "type": "result",
            "subtype": "error_during_execution",
            "duration_ms": 0,
            "duration_api_ms": 0,
            "is_error": true,
            "num_turns": 0,
            "session_id": "27934753-425a-4182-892c-6b1c15050c3f",
            "total_cost_usd": 0,
            "errors": ["No conversation found with session ID: d56965c9-c855-4042-a8f5-f12bbb14d6f6"],
            "permission_denials": []
        }"#;

        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
        assert!(output.is_error());

        if let ClaudeOutput::Result(res) = output {
            assert!(res.is_error);
            assert_eq!(res.errors.len(), 1);
            assert!(res.errors[0].contains("No conversation found"));
        } else {
            panic!("Expected Result message");
        }
    }

    #[test]
    fn test_deserialize_result_message_errors_defaults_empty() {
        let json = r#"{
            "type": "result",
            "subtype": "success",
            "is_error": false,
            "duration_ms": 100,
            "duration_api_ms": 200,
            "num_turns": 1,
            "session_id": "123",
            "total_cost_usd": 0.01
        }"#;

        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
        if let ClaudeOutput::Result(res) = output {
            assert!(res.errors.is_empty());
        } else {
            panic!("Expected Result message");
        }
    }

    #[test]
    fn test_result_message_errors_roundtrip() {
        let json = r#"{
            "type": "result",
            "subtype": "error_during_execution",
            "is_error": true,
            "duration_ms": 0,
            "duration_api_ms": 0,
            "num_turns": 0,
            "session_id": "test-session",
            "total_cost_usd": 0.0,
            "errors": ["Error 1", "Error 2"]
        }"#;

        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
        let reserialized = serde_json::to_string(&output).unwrap();

        assert!(reserialized.contains("Error 1"));
        assert!(reserialized.contains("Error 2"));
    }

    #[test]
    fn test_result_with_new_fields() {
        let json = r#"{
            "type": "result",
            "subtype": "success",
            "is_error": false,
            "duration_ms": 5000,
            "duration_api_ms": 4500,
            "num_turns": 1,
            "result": "Done",
            "session_id": "abc",
            "total_cost_usd": 0.06,
            "api_error_status": null,
            "stop_reason": "end_turn",
            "terminal_reason": "completed",
            "fast_mode_state": "off",
            "modelUsage": {
                "claude-opus-4-7[1m]": {
                    "inputTokens": 3817,
                    "outputTokens": 14,
                    "costUSD": 0.06
                }
            },
            "usage": {
                "input_tokens": 3817,
                "output_tokens": 14,
                "cache_creation_input_tokens": 3540,
                "cache_read_input_tokens": 0,
                "server_tool_use": {
                    "web_search_requests": 0,
                    "web_fetch_requests": 2
                },
                "service_tier": "standard",
                "inference_geo": "not_available",
                "speed": "standard",
                "iterations": [
                    {"input_tokens": 3817, "output_tokens": 14, "type": "turn"}
                ]
            }
        }"#;

        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
        if let ClaudeOutput::Result(res) = output {
            assert_eq!(res.stop_reason.as_deref(), Some("end_turn"));
            assert_eq!(res.terminal_reason.as_deref(), Some("completed"));
            assert_eq!(res.fast_mode_state.as_deref(), Some("off"));
            let model_usage = res.model_usage.as_ref().unwrap();
            let entry = model_usage
                .get("claude-opus-4-7[1m]")
                .expect("per-model entry present");
            assert_eq!(entry.input_tokens, 3817);
            assert_eq!(entry.output_tokens, 14);
            assert_eq!(entry.cost_usd, 0.06);
            assert!(res.api_error_status.is_none());

            let usage = res.usage.unwrap();
            assert_eq!(usage.server_tool_use.web_fetch_requests, 2);
            assert_eq!(usage.inference_geo.as_deref(), Some("not_available"));
            assert_eq!(usage.speed.as_deref(), Some("standard"));
            assert_eq!(usage.iterations.len(), 1);
            assert_eq!(usage.iterations[0].input_tokens, 3817);
            assert_eq!(usage.iterations[0].output_tokens, 14);
            assert_eq!(usage.iterations[0].kind.as_deref(), Some("turn"));
        } else {
            panic!("Expected Result");
        }
    }

    #[test]
    fn test_result_backwards_compatible_without_new_fields() {
        // Verify old-format messages still parse fine
        let json = r#"{
            "type": "result",
            "subtype": "success",
            "is_error": false,
            "duration_ms": 100,
            "duration_api_ms": 200,
            "num_turns": 1,
            "session_id": "abc",
            "total_cost_usd": 0.01
        }"#;

        let output: ClaudeOutput = serde_json::from_str(json).unwrap();
        if let ClaudeOutput::Result(res) = output {
            assert!(res.api_error_status.is_none());
            assert!(res.stop_reason.is_none());
            assert!(res.terminal_reason.is_none());
            assert!(res.fast_mode_state.is_none());
            assert!(res.model_usage.is_none());
        } else {
            panic!("Expected Result");
        }
    }

    #[test]
    fn test_result_fast_mode_disabled_reason() {
        let json = r#"{
            "type":"result","subtype":"success","is_error":false,
            "duration_ms":100,"duration_api_ms":80,"num_turns":1,
            "session_id":"s1","total_cost_usd":0.01,
            "fast_mode_state":"off",
            "fast_mode_disabled_reason":"sdk_opt_in_required"
        }"#;
        let output: crate::ClaudeOutput = serde_json::from_str(json).unwrap();
        let crate::ClaudeOutput::Result(res) = &output else {
            panic!("expected Result");
        };
        assert_eq!(
            res.fast_mode_disabled_reason,
            Some(FastModeDisabledReason::SdkOptInRequired)
        );
        assert!(serde_json::to_string(&output)
            .unwrap()
            .contains("\"fast_mode_disabled_reason\":\"sdk_opt_in_required\""));

        // Unknown reasons survive decode and round-trip verbatim; the wire
        // literal "unknown" maps to the typed UnknownReason, not the fallback.
        assert_eq!(
            FastModeDisabledReason::from("unknown"),
            FastModeDisabledReason::UnknownReason
        );
        let novel = FastModeDisabledReason::from("solar_flare");
        assert_eq!(novel, FastModeDisabledReason::Unknown("solar_flare".into()));
        assert_eq!(novel.as_str(), "solar_flare");
    }

    #[test]
    fn test_result_timing_and_user_message_uuid_fields() {
        let json = r#"{
            "type":"result","subtype":"success","is_error":false,
            "duration_ms":100,"duration_api_ms":80,"num_turns":1,
            "session_id":"s1","total_cost_usd":0.01,
            "request_sent_wall_ms":1753212345678.25,
            "user_message_uuid":"um-1"
        }"#;
        let output: crate::ClaudeOutput = serde_json::from_str(json).unwrap();
        let crate::ClaudeOutput::Result(res) = &output else {
            panic!("expected Result");
        };
        assert_eq!(res.request_sent_wall_ms, Some(1753212345678.25));
        assert_eq!(res.user_message_uuid.as_deref(), Some("um-1"));

        let reserialized = serde_json::to_string(&output).unwrap();
        assert!(reserialized.contains("\"user_message_uuid\":\"um-1\""));
    }

    #[test]
    fn test_result_queued_turn_count_and_user_message_uuids() {
        // CLI 2.1.259 additive fields on the result frame.
        let json = r#"{
            "type":"result","subtype":"success","is_error":false,
            "duration_ms":100,"duration_api_ms":80,"num_turns":1,
            "session_id":"s1","total_cost_usd":0.01,
            "user_message_uuid":"um-2",
            "user_message_uuids":["um-1","um-2"],
            "queued_turn_count":3
        }"#;
        let output: crate::ClaudeOutput = serde_json::from_str(json).unwrap();
        let crate::ClaudeOutput::Result(res) = &output else {
            panic!("expected Result");
        };
        assert_eq!(res.user_message_uuids, vec!["um-1", "um-2"]);
        assert_eq!(res.queued_turn_count, Some(3));

        let reserialized = serde_json::to_string(&output).unwrap();
        assert!(reserialized.contains("\"user_message_uuids\":[\"um-1\",\"um-2\"]"));
        assert!(reserialized.contains("\"queued_turn_count\":3"));

        // Both fields are absent from older producers and must default cleanly.
        let old = r#"{
            "type":"result","subtype":"success","is_error":false,
            "duration_ms":100,"duration_api_ms":80,"num_turns":1,
            "session_id":"s1","total_cost_usd":0.01
        }"#;
        let output: crate::ClaudeOutput = serde_json::from_str(old).unwrap();
        let crate::ClaudeOutput::Result(res) = &output else {
            panic!("expected Result");
        };
        assert!(res.user_message_uuids.is_empty());
        assert_eq!(res.queued_turn_count, None);
        let reserialized = serde_json::to_string(&output).unwrap();
        assert!(!reserialized.contains("user_message_uuids"));
        assert!(!reserialized.contains("queued_turn_count"));
    }
}