ante-protocol-shape 0.2.7

Protocol schema and wire message shapes for Ante
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
use std::path::PathBuf;

use chrono::{DateTime, Utc};
use serde::{Deserialize, Deserializer, Serialize};

use crate::id::Id;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EventMsg {
    pub timestamp: DateTime<Utc>,
    pub id: Id,
    pub event: Evt,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parent: Option<Id>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OpMsg {
    pub op: Op,
    pub id: Id,
}

/// `op` stamped with a fresh op id.
pub fn op_msg(op: Op) -> OpMsg {
    OpMsg { op, id: Id::op() }
}

/// `event` stamped with a fresh event id and the current time, correlated
/// to the op it answers (`parent`), if any.
pub fn event_msg(event: Evt, parent: Option<Id>) -> EventMsg {
    EventMsg { timestamp: Utc::now(), id: Id::evt(), event, parent }
}

#[allow(clippy::large_enum_variant)]
#[derive(Debug, Clone, Deserialize, Serialize)]
pub enum Op {
    /// Start a session from the request, replacing any running one: set
    /// fields are pinned, unset fields resolve to the host's defaults. There
    /// is no separate restart op — a client keeps the request it sent and
    /// re-sends it (optionally `patched`) for `/clear` semantics.
    StartSession(SessionRequest),
    UpdateSession(SessionUpdate),
    Interrupt,
    UserInput(String),
    ShellInput(String),
    Steer(String),
    ApprovalResponse {
        turn_id: Id,
        responses: Vec<ToolDecision>,
    },
    /// Resolve the active turn's pending question pause
    /// ([`TurnPauseReason::Question`]). `turn_id` must be the paused turn and
    /// `tool_use_id` must echo the pause's; stale or mismatched responses are
    /// dropped. `reply` is what the user did: answered, skipped, or asked to
    /// talk instead ([`QuestionReply`]).
    QuestionResponse {
        turn_id: Id,
        tool_use_id: String,
        reply: QuestionReply,
    },
    SlashCommand {
        name: String,
        args: String,
    },
    /// Continue a saved conversation from its persisted snapshot: what the
    /// host persisted is restored — the system instructions included — and
    /// everything the snapshot does not pin resolves like a fresh session
    /// from the host's current defaults.
    /// `unattended` is the resuming client's declaration, with the meaning
    /// of `SessionRequest::unattended`; absent means false.
    ResumeSession {
        session_id: Id,
        #[serde(default)]
        unattended: bool,
    },
    RegisterLocalProvider {
        port: u16,
        model: Option<ModelSpec>,
    },
    RestoreLocalProvider,
    /// Manually trigger conversation compaction on the active session.
    /// `instructions` optionally steer the replacement summary — what to
    /// emphasize or preserve. Ignored when the reduction needs no summary.
    Compact {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        instructions: Option<String>,
    },
    /// Request a per-category breakdown of the active session's context-window
    /// occupancy. Answered with [`Evt::ContextReport`].
    ContextReport,
    /// Rewind the active session's conversation — its model context and its
    /// visible history — to input `to`: how it stood just before that input
    /// was applied, the input and everything after it gone. `to` is a turn
    /// id as [`Evt::TurnStart`] reports it: for a user's input, the id of
    /// the op that submitted it. Answered with [`Evt::SessionRewound`];
    /// refused with an [`Evt::Error`], changing nothing, while a turn runs
    /// or is queued, a goal is set, or background jobs run, or when `to`
    /// cannot be restored: a turn from before the session was resumed, or
    /// one whose earlier conversation a compaction or provider switch has
    /// since rewritten. Starts no work and undoes nothing outside the
    /// conversation.
    RewindSession {
        to: Id,
    },
    /// Fork the active session's conversation into a new saved session: the
    /// conversation at input `at`, as [`Op::RewindSession`] to it would leave
    /// it, or the current conversation when `at` is absent. The active
    /// session must be idle and is left unchanged; the new session is not
    /// started. Answered with [`Evt::SessionForked`], or with an
    /// [`Evt::Error`] that creates nothing.
    ForkSession {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        at: Option<Id>,
    },
    /// Set, clear, or report a goal-driven execution loop on the active
    /// session. A set goal keeps the session working — re-running turns and
    /// judging the condition after each one — until it is met, judged
    /// unreachable, or cleared.
    Goal(GoalCommand),
    /// Request an ad-hoc "thinking phrase" prediction for the in-progress
    /// draft. Runs off the conversation critical path on a cheap model and
    /// answers with `Evt::Ambient`. `req_id` lets the client discard stale
    /// results when a newer request supersedes this one.
    AmbientPhrase {
        draft: String,
        req_id: u64,
    },
    /// Request an ad-hoc next-prompt suggestion from the last exchange, shown as
    /// input ghost text. Like [`Op::AmbientPhrase`] it runs off the critical
    /// path on a cheap model and answers with `Evt::Ambient`. The client carries
    /// the context (so this stays a client-only feature — headless never fires
    /// it) and a monotonic `req_id` to drop stale results.
    AmbientSuggestion {
        recent_user: String,
        recent_agent: String,
        req_id: u64,
    },
    Shutdown,
}

/// A `/goal` sub-command carried by [`Op::Goal`].
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum GoalCommand {
    /// Set (or replace) the active goal condition.
    Set(String),
    /// Clear the active goal, stopping the loop.
    Clear,
    /// Report the current goal status.
    Status,
}

/// Which ambient feature produced an [`Evt::Ambient`]. Both run off the main
/// conversation on a cheap model; they differ in trigger, prompt, and sink.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum AmbientKind {
    /// Predicted phrase for the in-progress draft, shown in the status spinner.
    ThinkingPhrase,
    /// Suggested next prompt from the conversation so far, shown as input ghost text.
    PromptSuggestion,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum Evt {
    SessionStart(Box<SessionInfo>),
    SessionUpdated(Box<SessionInfo>),
    ExtensionRefreshed(Box<ExtensionRefreshed>),
    /// The session span closed. Mirrors `TurnEnd`: carries the span's
    /// identity, why it ended, and its final usage accounting.
    SessionEnd {
        session_id: Id,
        reason: SessionEndReason,
        usage: Usage,
    },
    UserInput(String),
    ShellOutput {
        command: String,
        stdout: String,
        stderr: String,
        exit_code: Option<i32>,
    },
    AgentMessage(String),
    Thinking(String),
    MessageDelta(String),
    ThinkingDelta(String),
    Info(String),
    /// Open a grouped Info entry with `header`. Subsequent
    /// `InfoBlockAppend` events with the same `id` are rendered as
    /// tree-indented child lines under it. Use for multi-step background
    /// notifications (e.g. MCP warm-up) that should visually cluster.
    ///
    /// When `loading` is true the renderer appends an animated `.`/`../...`
    /// suffix to the header until the first `InfoBlockAppend` arrives,
    /// signalling that background work is still in flight.
    InfoBlockStart {
        id: String,
        header: String,
        #[serde(default)]
        loading: bool,
    },
    /// Append a child detail line to the `InfoBlockStart` with the same `id`.
    /// Drops silently if the matching block isn't present.
    InfoBlockAppend {
        id: String,
        detail: String,
    },
    Error(String),
    ToolStart(ToolUse),
    ToolUpdate(ToolUpdate),
    ToolEnd(ToolEnd),
    /// Work a tool call handed off ended: a Bash job that outlived its wait
    /// window. `tool_use_id` is the call whose `ToolEnd` reported the hand-off.
    /// `exit_code` is the process exit code, `128 + signal` for a signal
    /// death, absent only when the exit could not be observed.
    TaskEnd {
        tool_use_id: String,
        exit_code: Option<i32>,
    },
    CompactStart,
    /// Compaction finished. `summary` is the text that replaced the
    /// compacted history and carries forward as the session's context;
    /// `None` when compaction failed (history unchanged) or produced no
    /// displayable text.
    CompactEnd {
        #[serde(default)]
        summary: Option<String>,
    },
    TurnStart {
        turn_id: Id,
    },
    TurnPause {
        turn_id: Id,
        reason: TurnPauseReason,
    },
    /// The turn resumed after a `TurnPause` (e.g. the approval was answered
    /// or a steer arrived). Closes the pause bracket so clients never have to
    /// infer resumption from the next tool event.
    TurnResume {
        turn_id: Id,
    },
    TurnEnd {
        turn_id: Id,
        status: TurnEndStatus,
        /// Number of turn-loop steps attempted before the turn ended.
        #[serde(default)]
        steps: usize,
    },
    UsageUpdate {
        usage: Usage,
        /// Context-window occupancy for the root session. `None` carries no
        /// context update, including for subagent usage or an unverified model
        /// limit. Clients retain the last snapshot until the session or model changes.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        context: Option<ContextWindow>,
    },
    /// Answer to [`Op::ContextReport`]: a per-category breakdown of the
    /// session's context-window occupancy at the time of the request.
    ContextReport(ContextBreakdown),
    /// Answer to [`Op::RewindSession`]: the session's conversation, and the
    /// history a resume of it replays, now stand as they did just before
    /// input `to`. Never part of a resume replay.
    SessionRewound {
        to: Id,
    },
    /// Answer to [`Op::ForkSession`]: session `session_id` was forked from
    /// session `forked_from`: from its conversation at input `at`, or from
    /// its current conversation when absent. It is saved, not started;
    /// resuming it switches to it.
    SessionForked {
        forked_from: Id,
        session_id: Id,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        at: Option<Id>,
    },
    /// An ephemeral ambient hint produced off the main conversation (a predicted
    /// "thinking phrase" for the draft, or a suggested next prompt — see
    /// [`AmbientKind`]). Never persisted to the event log. `req_id` lets clients
    /// drop superseded results.
    Ambient {
        kind: AmbientKind,
        req_id: u64,
        text: String,
    },
    Goodbye,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum TurnPauseReason {
    Approval {
        tools: Vec<ToolUse>,
        message: String,
    },
    /// The model asked the user structured questions via the tool call
    /// identified by `tool_use_id`. Unlike `Approval`, this pause may coexist
    /// with sibling tools still running: `ToolStart`/`ToolEnd` events can
    /// arrive while it is pending. Each question's first option is the
    /// model's recommendation; clients resolve the pause with
    /// [`Op::QuestionResponse`], and no option is ever chosen on the user's
    /// behalf. Clients must clear question UI on `TurnResume` *and* on
    /// `TurnEnd` — a cancelled turn may end without a resume.
    Question {
        tool_use_id: String,
        questions: Vec<QuestionSpec>,
    },
}

/// One question in a [`TurnPauseReason::Question`] pause.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct QuestionSpec {
    /// Short label for this question, suitable for a chip or tab.
    pub header: String,
    /// The full question text.
    pub question: String,
    /// Whether the user may select more than one option.
    #[serde(default)]
    pub multi_select: bool,
    /// The offered choices. A free-text "Other" affordance is the client's
    /// to add; it is never part of this list.
    pub options: Vec<QuestionOption>,
}

/// One selectable option of a [`QuestionSpec`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct QuestionOption {
    pub label: String,
    /// What choosing this option means.
    pub description: String,
    /// Optional preview content (e.g. a code snippet or mockup) clients may
    /// render alongside the option.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub preview: Option<String>,
}

/// One question's answer in [`Op::QuestionResponse`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct QuestionAnswer {
    /// Selected option labels. Multi-select answers carry one entry per
    /// selected option; empty when the user only typed free text.
    pub selected: Vec<String>,
    /// Free text the user typed: a note attached to the selection, or —
    /// when `selected` is empty — the answer itself.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub note: Option<String>,
}

/// What the user did with a [`TurnPauseReason::Question`] pause.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum QuestionReply {
    /// One entry per question, in question order. An entry with nothing
    /// selected and no note leaves that question unanswered.
    Answered(Vec<QuestionAnswer>),
    /// The prompt was closed without answers.
    Dismissed,
    /// The user wants to talk before choosing. `message` carries their words
    /// when the client collected any; absent, the model is expected to ask
    /// what they want to clarify.
    Discuss {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        message: Option<String>,
    },
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum SessionEndReason {
    /// The session was replaced by a new or resumed session.
    Replaced,
    /// The connection is closing: the client sent `Shutdown` or went away.
    Shutdown,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum TurnEndStatus {
    Completed,
    Interrupted {
        #[serde(skip_serializing_if = "Option::is_none")]
        reason: Option<String>,
    },
    Error {
        /// Stable machine-readable LLM error kind. Absent for non-LLM errors
        /// and events produced by older daemons. Notably `"oauth"` means the
        /// provider's sign-in is missing, expired, or revoked, and only
        /// re-authenticating can recover; clients may offer their sign-in
        /// flow for the session's provider.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        kind: Option<String>,
        /// One-line summary. For a classified LLM failure this is the semantic
        /// error kind, e.g. "rate limited"; otherwise the top of the error chain.
        headline: String,
        /// Expanded cause shown as indented child rows beneath the headline,
        /// e.g. ["HTTP 400 Bad Request", "<server-provided message>"]. May be
        /// empty when there is nothing useful to add.
        details: Vec<String>,
    },
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolUpdate {
    pub tool_use_id: String,
    pub seq: u64,
    pub message: String,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ToolEndStatus {
    Completed,
    Cancelled,
    Denied,
    Failed,
}

impl ToolEndStatus {
    /// Whether this terminal status represents an error result. Mirrors the
    /// LLM-facing `ToolResult::is_error`: anything but a clean completion
    /// (failure, denial, cancellation) is an error.
    pub fn is_error(self) -> bool {
        !matches!(self, ToolEndStatus::Completed)
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolEnd {
    pub tool_use_id: String,
    /// Tool name, including when execution never started. Empty in older events.
    #[serde(default)]
    pub tool_name: String,
    pub status: ToolEndStatus,
    pub result_json: serde_json::Value,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum ReviewDecision {
    Accept,
    Deny,
    AcceptForSession,
    /// Approve and persist an allow rule to settings.json so the same call is
    /// auto-approved across future sessions ("always allow").
    AcceptAlways,
}

/// A decision for one requested tool call.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ToolDecision {
    pub tool_use_id: String,
    pub decision: ReviewDecision,
    /// Optional user feedback returned to the agent with a denial.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SkillMetadata {
    pub name: String,
    pub description: Option<String>,
    pub scope: Scope,
    pub argument_hint: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SubagentMetadata {
    pub name: String,
    pub description: String,
    pub scope: Scope,
}

/// The provider a session resolved to.
///
/// Carries only what a client cannot look up for itself: the id to key state
/// on, a name to show a user, and the endpoint actually in use — which env
/// overrides can move away from the published default, so it is a property of
/// this session rather than of the provider. The provider's model list is not
/// here; it is the same for every session and is published by `ante catalog`.
/// Unknown fields are ignored, so payloads still carrying it decode fine.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ProviderSpec {
    #[serde(alias = "name")]
    pub id: String,
    pub display_name: String,
    pub base_url: String,
}

/// A session's announced state: its identity and mutable settings
/// (`SessionStart`, `SessionUpdated`) plus the capabilities it was equipped
/// with, which are fixed for the session's lifetime.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SessionInfo {
    pub model: ModelSpec,
    pub provider: ProviderSpec,
    pub session_id: Id,
    pub cwd: PathBuf,
    pub permission_mode: PermissionMode,
    /// The skills the user can invoke in this session. Empty when absent.
    #[serde(default)]
    pub skills: Vec<SkillMetadata>,
    /// The subagents this session can delegate to. Empty when absent.
    #[serde(default)]
    pub subagents: Vec<SubagentMetadata>,
    /// The session's title, when one is set: a display name chosen by the
    /// user (or the client), never derived from the conversation.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    /// Set when the session was forked from another (see
    /// [`Op::ForkSession`]): the session it was forked from.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub forked_from: Option<Id>,
}

/// Partial update to a live session's mutable state. Each field is optional so
/// a caller patches only what changed; absent fields are left untouched.
/// Catalog-dependent fields are resolved before the update takes effect.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SessionUpdate {
    /// Provider change, taking effect on the next turn: the conversation
    /// continues on the named catalog provider, keeping the session id,
    /// messages, title and permission state. `model` then names a model on that
    /// provider; absent, the provider's default. Naming the current provider is
    /// not a switch. Refused whole, answered with `Error` instead of
    /// `SessionUpdated`, for an unknown provider id or for another provider
    /// while a turn is in flight; never re-routed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub provider: Option<String>,
    /// Model change, taking effect on the next turn. The spec carries the
    /// whole request, `effort` included: a set `effort` overrides the
    /// catalog default; unset fields resolve from the catalog. Resolved on
    /// the session's provider — the one `provider` names when both are set.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub model: Option<ModelSpec>,
    /// Permission mode change, taking effect on the next turn without
    /// aborting an in-flight one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub permission_mode: Option<PermissionMode>,
    /// Rename the session. The text is trimmed; an empty (or whitespace-only)
    /// text clears the title.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
}

/// The session's MCP servers and their tools, sent for `session_id` as the
/// servers come online. `skills` and `subagents` repeat the lists the
/// session's `SessionStart` announced.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExtensionRefreshed {
    pub session_id: Id,
    pub skills: Vec<SkillMetadata>,
    pub subagents: Vec<SubagentMetadata>,
    #[serde(default)]
    pub mcp_servers: Vec<McpServerInfo>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpServerInfo {
    pub name: String,
    pub command: String,
    pub args: Vec<String>,
    pub tools: Vec<McpToolInfo>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpToolInfo {
    pub name: String,
    pub qualified_name: String,
    pub description: String,
    pub parameters: Vec<McpToolParam>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpToolParam {
    pub name: String,
    pub param_type: String,
    pub required: bool,
    pub description: String,
}

/// The requested session configuration — the payload of [`Op::StartSession`].
/// A set field is pinned: it wins over every default. An unset field means
/// "the host's default for this, now": the daemon fills it from the user's
/// settings (re-read at the session boundary) or its built-in default. There
/// is exactly one meaning, regardless of who built the value — never "leave
/// unchanged".
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct SessionRequest {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub provider: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub permission_mode: Option<PermissionMode>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub system_prompt: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub append_system_prompt: Option<String>,
    /// Exactly these tools, replacing the default tool set as the base.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tools: Option<Vec<String>>,
    /// Tools added on top of the base set (`tools`, or the default set).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub include_tools: Option<Vec<String>>,
    /// Tools removed from the session; wins over `tools` and `include_tools`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub exclude_tools: Option<Vec<String>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cwd: Option<PathBuf>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub effort: Option<Effort>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub enable_auto_memory: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub short_prompt: Option<bool>,
    /// When true, the session loads no skills: none are discovered,
    /// advertised, or invocable.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub no_skills: Option<bool>,
    /// Skills added to the default set; names match exactly. Does not enable
    /// skill loading when disabled.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub include_skills: Option<Vec<String>>,
    /// Skills removed from the session; names match exactly. Wins over
    /// `include_skills`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub exclude_skills: Option<Vec<String>>,
    /// Whether the session writes a transcript and a resumable snapshot.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub save_session: Option<bool>,
    /// Whether no one can answer an approval prompt for this session. When
    /// true, a tool call that would pause the turn for approval is denied
    /// instead of pausing. Absent means false.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub unattended: Option<bool>,
    /// A title for the session (see `SessionUpdate::title` for the rules).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
}

impl SessionRequest {
    /// Fold `patch` onto `self`, field by field: a set field in the patch
    /// wins, an unset one keeps `self`'s value. This is the rule for every
    /// request-over-request combination (e.g. a client retargeting the
    /// request it keeps for `/clear`). `patch` is destructured exhaustively
    /// (no `..` rest) so adding a field fails to compile here until its fold
    /// rule is decided.
    pub fn patched(self, patch: SessionRequest) -> SessionRequest {
        let SessionRequest {
            model,
            provider,
            permission_mode,
            system_prompt,
            append_system_prompt,
            tools,
            include_tools,
            exclude_tools,
            cwd,
            effort,
            enable_auto_memory,
            short_prompt,
            no_skills,
            include_skills,
            exclude_skills,
            save_session,
            unattended,
            title,
        } = patch;
        SessionRequest {
            model: model.or(self.model),
            provider: provider.or(self.provider),
            permission_mode: permission_mode.or(self.permission_mode),
            system_prompt: system_prompt.or(self.system_prompt),
            append_system_prompt: append_system_prompt.or(self.append_system_prompt),
            tools: tools.or(self.tools),
            include_tools: include_tools.or(self.include_tools),
            exclude_tools: exclude_tools.or(self.exclude_tools),
            cwd: cwd.or(self.cwd),
            effort: effort.or(self.effort),
            enable_auto_memory: enable_auto_memory.or(self.enable_auto_memory),
            short_prompt: short_prompt.or(self.short_prompt),
            no_skills: no_skills.or(self.no_skills),
            include_skills: include_skills.or(self.include_skills),
            exclude_skills: exclude_skills.or(self.exclude_skills),
            save_session: save_session.or(self.save_session),
            unattended: unattended.or(self.unattended),
            title: title.or(self.title),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct MalformedToolArgs {
    /// Exact argument text emitted by the model for the undecodable call.
    pub raw: String,
    /// Decode diagnostic. This must not contain the raw argument text.
    pub error: String,
}

/// Sentinel [`ToolUse::name`] for a call whose stream never delivered a
/// function name; always paired with `malformed_args`.
pub const MISSING_TOOL_NAME: &str = "missing_function_name";

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ToolUse {
    pub id: String,
    pub name: String,
    pub args: serde_json::Value,
    /// Present when the model's raw call could not be decoded into an
    /// executable call: `args` that were not valid JSON, or a stream that
    /// never delivered the function name (`name` is then
    /// [`MISSING_TOOL_NAME`]). Such a call is non-executable and must be
    /// returned as an error result.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub malformed_args: Option<MalformedToolArgs>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub signature: Option<String>,
}

impl ToolUse {
    /// A well-formed call: decoded `args`, no malformed metadata, no signature.
    pub fn new(id: impl Into<String>, name: impl Into<String>, args: serde_json::Value) -> Self {
        Self { id: id.into(), name: name.into(), args, malformed_args: None, signature: None }
    }
}

#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct ModelSpec {
    #[serde(alias = "name")]
    pub id: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub display_name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub temperature: Option<f32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub top_p: Option<f32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub top_k: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_tokens: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stop_sequences: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub context_limit: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub effort: Option<Effort>,
    /// The effort levels this model supports when configured in the user catalog.
    /// When absent, the provider's built-in model profile supplies the ladder;
    /// an empty list means that the model takes no effort setting.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub supported_efforts: Option<Vec<Effort>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub support_vision: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub weight_class: Option<WeightClass>,
}

/// Requested output/reasoning effort for model turns, on an ordinal scale.
///
/// `min` is the lowest effort the model supports — thinking is disabled where
/// the model allows that; models with always-on reasoning clamp to their
/// lowest level. Providers that expose fewer levels round a requested effort
/// down to the nearest supported one. Variants are declared in ascending
/// order so the derived `Ord` sorts `Min < Low < ... < Max`.
#[derive(Debug, Clone, Serialize, Deserialize, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[serde(rename_all = "lowercase")]
pub enum Effort {
    Min,
    Low,
    Medium,
    High,
    XHigh,
    Max,
}

impl Effort {
    /// All levels in ascending order.
    pub const ALL: [Effort; 6] =
        [Effort::Min, Effort::Low, Effort::Medium, Effort::High, Effort::XHigh, Effort::Max];

    /// The wire token for this level (`"min"`, `"low"`, ..., `"max"`).
    pub fn as_str(self) -> &'static str {
        match self {
            Effort::Min => "min",
            Effort::Low => "low",
            Effort::Medium => "medium",
            Effort::High => "high",
            Effort::XHigh => "xhigh",
            Effort::Max => "max",
        }
    }
}

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

impl std::str::FromStr for Effort {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Effort::ALL.into_iter().find(|e| e.as_str() == s).ok_or_else(|| {
            format!("unknown effort `{s}` (expected min, low, medium, high, xhigh, max)")
        })
    }
}

/// Innate size/cost class of a model, set once per model in the catalog.
///
/// Orthogonal to the per-request [`Effort`] and to `context_limit`:
/// a model's weight class reflects roughly how large and costly it is to run,
/// not how hard it is asked to think on a given turn. Variants are declared in
/// ascending order so the derived `Ord` sorts `Feather < Middle < Heavy`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum WeightClass {
    /// Small, fast, cheap (Haiku- / GPT-nano-class).
    Feather,
    /// Mid workhorse (Sonnet- / GPT-mini- / Gemini-Flash-class).
    Middle,
    /// Largest, most capable, costliest (Opus- / GPT-5.x- / Gemini-Pro-class).
    Heavy,
}

impl<'de> Deserialize<'de> for WeightClass {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = String::deserialize(deserializer)?;
        match value.to_ascii_lowercase().as_str() {
            "feather" => Ok(Self::Feather),
            "middle" => Ok(Self::Middle),
            "heavy" => Ok(Self::Heavy),
            _ => Err(serde::de::Error::unknown_variant(&value, &["feather", "middle", "heavy"])),
        }
    }
}

/// Token usage for one model response.
///
/// Convention, uniform across every provider mapping: `input_tokens` is the
/// **full, cache-inclusive prompt size**. It always contains `cache_read_tokens`
/// as a subset (verified live: OpenAI/OpenRouter/DeepSeek report it inside
/// `prompt_tokens`; the Anthropic mapping adds it back since that API reports
/// input net of cache). `cache_creation_tokens` is likewise inside `input_tokens`
/// for providers that report cache writes (Anthropic); the OpenAI-style
/// providers we use don't report writes at all. So [`Usage::total`]
/// (`input + output`) is the context-window occupancy.
///
/// For **cost**, the cache buckets bill at different rates, so subtract them
/// from the input rate instead of charging the full rate twice:
/// `cost = (input - cache_read - cache_creation)·p_in
///        + cache_read·p_cache_read + cache_creation·p_cache_write
///        + output·p_out`.
#[derive(Debug, Clone, Deserialize, Serialize, Default, Copy)]
#[serde(default)]
pub struct Usage {
    /// Full prompt tokens, cache-inclusive (a superset of the two cache fields).
    pub input_tokens: u32,
    /// Generated output (completion) tokens.
    pub output_tokens: u32,
    /// Subset of `input_tokens` served from the prompt cache (cheaper rate).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cache_read_tokens: Option<u32>,
    /// Subset of `input_tokens` written into the prompt cache (surcharge rate).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cache_creation_tokens: Option<u32>,
}

/// Context-window occupancy snapshot for the current (root) session, surfaced in
/// the statusline. Raw measurements only — any percentage is a presentation
/// concern derived at the edges, with no policy (e.g. auto-compaction) baked in.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub struct ContextWindow {
    /// Tokens currently occupying the window (cache-inclusive input + output of
    /// the most recent response).
    pub used_tokens: u32,
    /// Raw model context limit (e.g. 200_000).
    pub limit_tokens: u32,
}

/// Per-category breakdown of context-window occupancy.
///
/// `used_tokens` is anchored on the provider-reported occupancy once the
/// session has seen a model response; before that it is estimated. The
/// per-category fields are estimates that normally sum to `used_tokens`, but
/// estimation error can make them disagree slightly — clients should clamp
/// rather than assume an exact identity.
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(default)]
pub struct ContextBreakdown {
    /// System prompt, excluding the skills and memory sections counted below.
    pub system_prompt_tokens: u32,
    /// Built-in tool schemas.
    pub system_tools_tokens: u32,
    /// MCP tool schemas.
    pub mcp_tools_tokens: u32,
    /// Memory content: project/user instruction files and the auto-memory prompt.
    pub memory_tokens: u32,
    /// The available-skills listing.
    pub skills_tokens: u32,
    /// Conversation messages: everything not attributed to a category above.
    pub messages_tokens: u32,
    /// Total context-window occupancy.
    pub used_tokens: u32,
    /// Model context limit. `None` when unverified, so clients never render a
    /// confidently-wrong percentage.
    pub limit_tokens: Option<u32>,
    /// Tokens reserved at the top of the window; auto-compaction triggers once
    /// occupancy grows into this reserve.
    pub compact_buffer_tokens: u32,
}

impl Usage {
    pub fn new(input_tokens: u32, output_tokens: u32) -> Self {
        Self { input_tokens, output_tokens, cache_read_tokens: None, cache_creation_tokens: None }
    }

    /// Context-window occupancy: the full (cache-inclusive) prompt plus output.
    pub fn total(&self) -> u32 {
        self.input_tokens.saturating_add(self.output_tokens)
    }
}

impl std::ops::Add<Usage> for Usage {
    type Output = Usage;

    fn add(self, other: Usage) -> Usage {
        Usage {
            input_tokens: self.input_tokens.saturating_add(other.input_tokens),
            output_tokens: self.output_tokens.saturating_add(other.output_tokens),
            cache_read_tokens: add_optional_u32(self.cache_read_tokens, other.cache_read_tokens),
            cache_creation_tokens: add_optional_u32(
                self.cache_creation_tokens,
                other.cache_creation_tokens,
            ),
        }
    }
}

fn add_optional_u32(a: Option<u32>, b: Option<u32>) -> Option<u32> {
    match (a, b) {
        (None, None) => None,
        _ => Some(a.unwrap_or(0).saturating_add(b.unwrap_or(0))),
    }
}

impl std::ops::AddAssign<Usage> for Usage {
    fn add_assign(&mut self, other: Usage) {
        *self = *self + other;
    }
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, Default, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum PermissionMode {
    /// Honor user rules; an unmatched call asks unless it is provably safe.
    #[default]
    Strict,
    /// Honor user rules; an unmatched call runs unless it is provably
    /// dangerous (a deliberately narrow classification).
    Auto,
    /// Bypass all permission checks, including user deny rules.
    Yolo,
}

#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[serde(rename_all = "kebab-case")]
pub enum Scope {
    Project,
    User,
    System,
}

#[cfg(test)]
mod tests {
    use super::{
        Effort, Evt, ExtensionRefreshed, Id, ModelSpec, Op, PermissionMode, ProviderSpec,
        ReviewDecision, SessionInfo, SessionRequest, SessionUpdate, ToolDecision, ToolEnd,
        ToolEndStatus, ToolUse, Usage, WeightClass, event_msg, op_msg,
    };
    use std::path::PathBuf;

    #[test]
    fn op_msg_assigns_runtime_id() {
        let msg = op_msg(Op::Interrupt);

        assert!(msg.id.to_string().starts_with("op_"));
        assert!(matches!(msg.op, Op::Interrupt));
    }

    #[test]
    fn event_msg_assigns_runtime_metadata() {
        let event = event_msg(Evt::Info("hello".to_string()), None);

        assert!(event.id.to_string().starts_with("evt_"));
        assert!(matches!(event.event, Evt::Info(message) if message == "hello"));
        assert!(event.parent.is_none());
    }

    fn model_spec(name: &str) -> ModelSpec {
        ModelSpec {
            id: name.to_string(),
            display_name: None,
            description: None,
            temperature: None,
            top_p: None,
            top_k: None,
            max_tokens: None,
            stop_sequences: None,
            context_limit: None,
            effort: None,
            supported_efforts: None,
            support_vision: None,
            weight_class: None,
        }
    }

    #[test]
    fn tool_use_without_malformed_args_remains_backward_compatible() {
        let tool_use: ToolUse = serde_json::from_value(serde_json::json!({
            "id": "call-1",
            "name": "Read",
            "args": { "file_path": "README.md" }
        }))
        .unwrap();

        assert!(tool_use.malformed_args.is_none());
        let encoded = serde_json::to_value(tool_use).unwrap();
        assert!(encoded.get("malformed_args").is_none());
    }

    #[test]
    fn tool_end_without_name_remains_backward_compatible() {
        let legacy = serde_json::json!({
            "tool_use_id": "call-1",
            "status": "Denied",
            "result_json": "Tool call denied by policy and was not executed."
        });
        let mut end: ToolEnd = serde_json::from_value(legacy.clone()).unwrap();
        assert!(end.tool_name.is_empty());
        assert_eq!(end.status, ToolEndStatus::Denied);

        end.tool_name = "Bash".to_string();
        let mut expected = legacy;
        expected["tool_name"] = serde_json::json!("Bash");
        assert_eq!(serde_json::to_value(end).unwrap(), expected);
    }

    #[test]
    fn task_end_round_trips_with_observed_or_unobserved_exit() {
        for exit_code in [Some(2), None] {
            let json = serde_json::json!({
                "TaskEnd": { "tool_use_id": "bash-1", "exit_code": exit_code }
            });
            let event: super::Evt = serde_json::from_value(json.clone()).unwrap();
            assert!(matches!(&event, super::Evt::TaskEnd { tool_use_id, exit_code: code }
                if tool_use_id == "bash-1" && *code == exit_code));
            assert_eq!(serde_json::to_value(event).unwrap(), json);
        }
    }

    #[test]
    fn turn_end_error_kind_is_optional_on_the_wire() {
        // Payloads from daemons predating the field still deserialize.
        let old: super::TurnEndStatus = serde_json::from_value(serde_json::json!({
            "Error": { "headline": "authentication error", "details": [] }
        }))
        .unwrap();
        let super::TurnEndStatus::Error { kind, .. } = &old else {
            panic!("expected Error variant");
        };
        assert!(kind.is_none());

        // None is skipped, not emitted as null.
        let json = serde_json::to_value(&old).unwrap();
        assert!(json["Error"].get("kind").is_none());

        // Some round-trips.
        let with = super::TurnEndStatus::Error {
            kind: Some("oauth".to_string()),
            headline: "OAuth sign-in required".to_string(),
            details: vec![],
        };
        let json = serde_json::to_value(&with).unwrap();
        assert_eq!(json["Error"]["kind"], "oauth");
    }

    #[test]
    fn turn_end_steps_default_for_older_events() {
        let event = super::Evt::TurnEnd {
            turn_id: super::Id::new("turn"),
            status: super::TurnEndStatus::Completed,
            steps: 3,
        };
        let mut json = serde_json::to_value(&event).unwrap();
        json["TurnEnd"].as_object_mut().unwrap().remove("steps");
        let old: super::Evt = serde_json::from_value(json).unwrap();

        assert!(matches!(old, super::Evt::TurnEnd { steps: 0, .. }));

        let json = serde_json::to_value(event).unwrap();
        assert_eq!(json["TurnEnd"]["steps"], 3);
    }

    #[test]
    fn effort_serializes_as_lowercase_tokens() {
        let mut spec = model_spec("m");
        spec.effort = Some(super::Effort::XHigh);
        let json = serde_json::to_value(&spec).unwrap();
        assert_eq!(json["effort"], "xhigh");

        // None is skipped, not emitted as null.
        let json_none = serde_json::to_value(model_spec("m")).unwrap();
        assert!(json_none.get("effort").is_none());

        // Every level round-trips through its wire token.
        for level in super::Effort::ALL {
            let parsed: ModelSpec =
                serde_json::from_value(serde_json::json!({"id": "m", "effort": level.as_str()}))
                    .unwrap();
            assert_eq!(parsed.effort, Some(level), "round-trip {level}");
        }
    }

    #[test]
    fn effort_orders_min_lowest_to_max_highest() {
        let mut sorted = super::Effort::ALL;
        sorted.sort();
        assert_eq!(sorted, super::Effort::ALL);
        assert!(super::Effort::Min < super::Effort::Low);
        assert!(super::Effort::XHigh < super::Effort::Max);
    }

    #[test]
    fn session_overrides_effort_round_trips() {
        let parsed: super::SessionRequest =
            serde_json::from_value(serde_json::json!({"effort": "max"})).unwrap();
        assert_eq!(parsed.effort, Some(super::Effort::Max));

        let parsed: super::SessionRequest = serde_json::from_value(serde_json::json!({})).unwrap();
        assert_eq!(parsed.effort, None);
    }

    #[test]
    fn short_prompt_round_trips_and_defaults_to_unset() {
        let parsed: super::SessionRequest =
            serde_json::from_value(serde_json::json!({"short_prompt": true})).unwrap();
        assert_eq!(parsed.short_prompt, Some(true));

        let parsed: super::SessionRequest = serde_json::from_value(serde_json::json!({})).unwrap();
        assert_eq!(parsed.short_prompt, None);
    }

    #[test]
    fn skill_filters_are_optional_on_the_wire_and_preserve_empty_overrides() {
        let absent: SessionRequest = serde_json::from_value(serde_json::json!({})).unwrap();
        assert_eq!(absent.include_skills, None);
        assert_eq!(absent.exclude_skills, None);
        let encoded = serde_json::to_value(absent).unwrap();
        assert!(encoded.get("include_skills").is_none());
        assert!(encoded.get("exclude_skills").is_none());

        let json = serde_json::json!({"include_skills": ["Review"], "exclude_skills": []});
        let parsed: SessionRequest = serde_json::from_value(json.clone()).unwrap();
        assert_eq!(parsed.include_skills, Some(vec!["Review".to_string()]));
        assert_eq!(parsed.exclude_skills, Some(Vec::new()));
        assert_eq!(serde_json::to_value(parsed).unwrap(), json);
    }

    fn pinned_request() -> SessionRequest {
        SessionRequest {
            model: Some("base-model".to_string()),
            provider: Some("anthropic".to_string()),
            permission_mode: Some(PermissionMode::Strict),
            system_prompt: Some("base prompt".to_string()),
            cwd: Some(std::path::PathBuf::from("/base")),
            effort: Some(Effort::Medium),
            enable_auto_memory: Some(true),
            short_prompt: Some(true),
            no_skills: Some(true),
            include_skills: Some(vec!["review".to_string()]),
            exclude_skills: Some(vec!["noisy".to_string()]),
            save_session: Some(true),
            unattended: Some(true),
            title: Some("pinned title".to_string()),
            ..Default::default()
        }
    }

    #[test]
    fn patched_with_an_empty_patch_keeps_every_field() {
        assert_eq!(pinned_request().patched(SessionRequest::default()), pinned_request());
    }

    #[test]
    fn patched_overwrites_only_the_patch_set_fields() {
        let patched = pinned_request().patched(SessionRequest {
            model: Some("new-model".to_string()),
            permission_mode: Some(PermissionMode::Yolo),
            enable_auto_memory: Some(false),
            short_prompt: Some(false),
            include_skills: Some(Vec::new()),
            ..Default::default()
        });
        // Overwritten by the patch:
        assert_eq!(patched.model.as_deref(), Some("new-model"));
        assert_eq!(patched.permission_mode, Some(PermissionMode::Yolo));
        assert_eq!(patched.enable_auto_memory, Some(false));
        assert_eq!(patched.short_prompt, Some(false));
        assert_eq!(patched.include_skills, Some(Vec::new()));
        // Untouched (patch unset == keep):
        assert_eq!(patched.provider.as_deref(), Some("anthropic"));
        assert_eq!(patched.system_prompt.as_deref(), Some("base prompt"));
        assert_eq!(patched.effort, Some(Effort::Medium));
        assert_eq!(patched.save_session, Some(true));
        assert_eq!(patched.unattended, Some(true));
        assert_eq!(patched.title.as_deref(), Some("pinned title"));
        assert_eq!(patched.exclude_skills, Some(vec!["noisy".to_string()]));
    }

    #[test]
    fn rewind_names_its_input_as_to() {
        let to = Id::op();
        let json = serde_json::to_value(Op::RewindSession { to }).unwrap();
        assert_eq!(json, serde_json::json!({ "RewindSession": { "to": to } }));
        let op: Op = serde_json::from_value(json).unwrap();
        assert!(matches!(op, Op::RewindSession { to: decoded } if decoded == to));

        let json = serde_json::to_value(Evt::SessionRewound { to }).unwrap();
        assert_eq!(json, serde_json::json!({ "SessionRewound": { "to": to } }));
    }

    #[test]
    fn fork_at_is_optional_on_the_wire() {
        let whole: Op = serde_json::from_value(serde_json::json!({ "ForkSession": {} })).unwrap();
        assert!(matches!(whole, Op::ForkSession { at: None }));

        let at = Id::op();
        let json = serde_json::to_value(Op::ForkSession { at: Some(at) }).unwrap();
        assert_eq!(json, serde_json::json!({ "ForkSession": { "at": at } }));
        let op: Op = serde_json::from_value(json).unwrap();
        assert!(matches!(op, Op::ForkSession { at: Some(decoded) } if decoded == at));

        let (forked_from, session_id) = (Id::ses(), Id::ses());
        let forked = Evt::SessionForked { forked_from, session_id, at: None };
        assert_eq!(
            serde_json::to_value(forked).unwrap(),
            serde_json::json!({
                "SessionForked": { "forked_from": forked_from, "session_id": session_id }
            })
        );
    }

    #[test]
    fn forked_from_is_optional_on_the_wire() {
        let source = Id::ses();
        let info = SessionInfo { forked_from: Some(source), ..Default::default() };
        let mut json = serde_json::to_value(&info).unwrap();
        assert_eq!(json["forked_from"], serde_json::json!(source));
        let decoded: SessionInfo = serde_json::from_value(json.clone()).unwrap();
        assert_eq!(decoded.forked_from, Some(source));

        // A payload written before the field existed reads as not forked.
        json.as_object_mut().unwrap().remove("forked_from");
        let plain: SessionInfo = serde_json::from_value(json).unwrap();
        assert_eq!(plain.forked_from, None);
        assert!(serde_json::to_value(&plain).unwrap().get("forked_from").is_none());
    }

    #[test]
    fn unattended_is_optional_on_the_wire() {
        // A request without the field, and a resume op written before the
        // field existed, both read as attended.
        let request: SessionRequest = serde_json::from_value(serde_json::json!({})).unwrap();
        assert_eq!(request.unattended, None);

        let op = Op::ResumeSession { session_id: Id::new("ses"), unattended: true };
        let mut json = serde_json::to_value(&op).unwrap();
        json["ResumeSession"].as_object_mut().unwrap().remove("unattended");
        let decoded: Op = serde_json::from_value(json).unwrap();
        assert!(matches!(decoded, Op::ResumeSession { unattended: false, .. }));
    }

    #[test]
    fn session_initialized_title_is_optional_on_the_wire() {
        let mut payload = SessionInfo {
            model: model_spec("m"),
            provider: provider_spec("p"),
            session_id: Id::new("ses"),
            cwd: PathBuf::from("/tmp"),
            permission_mode: PermissionMode::default(),
            skills: vec![],
            subagents: vec![],
            title: None,
            forked_from: None,
        };

        let json = serde_json::to_value(&payload).unwrap();
        assert!(json.get("title").is_none(), "an unset title is omitted: {json}");
        let decoded: SessionInfo = serde_json::from_value(json).unwrap();
        assert_eq!(decoded.title, None);

        payload.title = Some("fix".to_string());
        let json = serde_json::to_value(&payload).unwrap();
        assert_eq!(json["title"], "fix");
    }

    #[test]
    fn weight_class_serializes_lowercase_and_is_omitted_when_none() {
        let mut spec = model_spec("m");
        spec.weight_class = Some(WeightClass::Heavy);
        let json = serde_json::to_value(&spec).unwrap();
        assert_eq!(json["weight_class"], "heavy");

        // None is skipped, not emitted as null.
        let json_none = serde_json::to_value(model_spec("m")).unwrap();
        assert!(json_none.get("weight_class").is_none());

        // Round-trips from the lowercase wire form.
        let parsed: ModelSpec =
            serde_json::from_value(serde_json::json!({"id": "m", "weight_class": "feather"}))
                .unwrap();
        assert_eq!(parsed.weight_class, Some(WeightClass::Feather));
    }

    #[test]
    fn weight_class_deserializes_case_insensitively() {
        for (value, expected) in [
            ("Feather", WeightClass::Feather),
            ("MIDDLE", WeightClass::Middle),
            ("hEaVy", WeightClass::Heavy),
        ] {
            let parsed: ModelSpec =
                serde_json::from_value(serde_json::json!({"id": "m", "weight_class": value}))
                    .unwrap();
            assert_eq!(parsed.weight_class, Some(expected));
        }
    }

    #[test]
    fn weight_class_orders_feather_lightest_to_heavy_heaviest() {
        assert!(WeightClass::Feather < WeightClass::Middle);
        assert!(WeightClass::Middle < WeightClass::Heavy);
    }

    fn provider_spec(name: &str) -> ProviderSpec {
        ProviderSpec {
            id: name.to_string(),
            display_name: name.to_string(),
            base_url: format!("https://api.{name}.test/v1"),
        }
    }

    #[test]
    fn compact_events_serde_roundtrip() {
        let compact_start =
            serde_json::to_string(&Evt::CompactStart).expect("serialize CompactStart");
        let compact_end =
            serde_json::to_string(&Evt::CompactEnd { summary: Some("the summary".to_string()) })
                .expect("serialize CompactEnd");

        assert_eq!(compact_start, "\"CompactStart\"");
        assert_eq!(compact_end, r#"{"CompactEnd":{"summary":"the summary"}}"#);

        assert!(matches!(
            serde_json::from_str::<Evt>(&compact_start).expect("deserialize CompactStart"),
            Evt::CompactStart
        ));
        assert!(matches!(
            serde_json::from_str::<Evt>(&compact_end).expect("deserialize CompactEnd"),
            Evt::CompactEnd { summary: Some(s) } if s == "the summary"
        ));
        assert!(matches!(
            serde_json::from_str::<Evt>(r#"{"CompactEnd":{}}"#)
                .expect("deserialize CompactEnd without summary"),
            Evt::CompactEnd { summary: None }
        ));
    }

    #[test]
    fn compact_op_serde_roundtrip() {
        let plain = serde_json::to_string(&Op::Compact { instructions: None })
            .expect("serialize bare Compact");
        assert_eq!(plain, r#"{"Compact":{}}"#);
        assert!(matches!(
            serde_json::from_str::<Op>(&plain).expect("deserialize bare Compact"),
            Op::Compact { instructions: None }
        ));

        let steered =
            serde_json::to_string(&Op::Compact { instructions: Some("keep dates".to_string()) })
                .expect("serialize steered Compact");
        assert_eq!(steered, r#"{"Compact":{"instructions":"keep dates"}}"#);
        assert!(matches!(
            serde_json::from_str::<Op>(&steered).expect("deserialize steered Compact"),
            Op::Compact { instructions: Some(text) } if text == "keep dates"
        ));
    }

    #[test]
    fn session_end_and_turn_resume_serde_roundtrip() {
        let session_id = Id::new("ses");
        let end = Evt::SessionEnd {
            session_id,
            reason: super::SessionEndReason::Shutdown,
            usage: Usage::new(10, 5),
        };
        let json = serde_json::to_string(&end).expect("serialize SessionEnd");
        let decoded = serde_json::from_str::<Evt>(&json).expect("deserialize SessionEnd");
        assert!(matches!(
            decoded,
            Evt::SessionEnd { session_id: id, reason: super::SessionEndReason::Shutdown, usage }
                if id == session_id && usage.total() == 15
        ));

        let turn_id = Id::new("op");
        let resume = Evt::TurnResume { turn_id };
        let json = serde_json::to_string(&resume).expect("serialize TurnResume");
        let decoded = serde_json::from_str::<Evt>(&json).expect("deserialize TurnResume");
        assert!(matches!(decoded, Evt::TurnResume { turn_id: id } if id == turn_id));
    }

    #[test]
    fn extension_refreshed_serde_roundtrip() {
        let event = Evt::ExtensionRefreshed(Box::new(ExtensionRefreshed {
            session_id: Id::new("ses"),
            skills: Vec::new(),
            subagents: Vec::new(),
            mcp_servers: Vec::new(),
        }));

        let json = serde_json::to_string(&event).expect("serialize ExtensionRefreshed");
        let decoded = serde_json::from_str::<Evt>(&json).expect("deserialize ExtensionRefreshed");

        assert!(matches!(
            decoded,
            Evt::ExtensionRefreshed(payload)
                if payload.skills.is_empty() && payload.subagents.is_empty()
        ));
    }

    #[test]
    fn session_update_op_serde_roundtrip() {
        let op = Op::UpdateSession(SessionUpdate {
            provider: Some("openai".to_string()),
            model: Some(ModelSpec {
                temperature: Some(0.2),
                effort: Some(super::Effort::High),
                ..model_spec("gpt-5.4")
            }),
            permission_mode: Some(PermissionMode::Yolo),
            title: Some("renamed".to_string()),
        });

        let json = serde_json::to_string(&op).expect("serialize UpdateSession");
        let decoded = serde_json::from_str::<Op>(&json).expect("deserialize UpdateSession");

        assert!(matches!(
            decoded,
            Op::UpdateSession(SessionUpdate {
                provider: Some(provider),
                model: Some(model),
                permission_mode: Some(PermissionMode::Yolo),
                title: Some(title),
            })
                if provider == "openai"
                    && model.id == "gpt-5.4"
                    && model.temperature == Some(0.2)
                    && model.effort == Some(super::Effort::High)
                    && title == "renamed"
        ));
    }

    #[test]
    fn approval_response_uses_named_tool_decisions() {
        let turn_id = Id::new("turn");
        let op = Op::ApprovalResponse {
            turn_id,
            responses: vec![ToolDecision {
                tool_use_id: "call-1".to_string(),
                decision: ReviewDecision::Deny,
                message: Some("use the read-only endpoint".to_string()),
            }],
        };

        let json = serde_json::to_value(&op).expect("serialize ApprovalResponse");
        assert_eq!(
            json["ApprovalResponse"]["responses"],
            serde_json::json!([{
                "tool_use_id": "call-1",
                "decision": "Deny",
                "message": "use the read-only endpoint"
            }])
        );

        let decoded = serde_json::from_value::<Op>(json).expect("deserialize ApprovalResponse");
        assert!(matches!(
            decoded,
            Op::ApprovalResponse { turn_id: id, responses }
                if id == turn_id
                    && responses == vec![ToolDecision {
                        tool_use_id: "call-1".to_string(),
                        decision: ReviewDecision::Deny,
                        message: Some("use the read-only endpoint".to_string()),
                    }]
        ));
    }

    #[test]
    fn session_updated_event_serde_roundtrip() {
        let session_id = Id::new("ses");
        let event = Evt::SessionUpdated(Box::new(SessionInfo {
            model: model_spec("claude-sonnet-4-6"),
            provider: provider_spec("anthropic"),
            session_id,
            cwd: PathBuf::from("/tmp/session-updated"),
            permission_mode: PermissionMode::default(),
            skills: vec![],
            subagents: vec![],
            title: None,
            forked_from: None,
        }));

        let json = serde_json::to_string(&event).expect("serialize SessionUpdated");
        let decoded = serde_json::from_str::<Evt>(&json).expect("deserialize SessionUpdated");

        assert!(matches!(
            decoded,
            Evt::SessionUpdated(payload)
                if payload.model.id == "claude-sonnet-4-6"
                    && payload.provider.id == "anthropic"
                    && payload.provider.base_url == "https://api.anthropic.test/v1"
                    && payload.session_id == session_id
                    && payload.cwd == std::path::Path::new("/tmp/session-updated")
        ));
    }

    #[test]
    fn provider_spec_ignores_the_dropped_model_list() {
        // Payloads from daemons that still send the provider's model list
        // decode against the narrowed shape.
        let spec: ProviderSpec = serde_json::from_value(serde_json::json!({
            "id": "anthropic",
            "display_name": "Anthropic",
            "base_url": "https://api.anthropic.test/v1",
            "preferred_models": [{ "id": "claude-sonnet-4-6" }],
        }))
        .unwrap();

        assert_eq!(spec.id, "anthropic");
        assert_eq!(spec.display_name, "Anthropic");
        assert_eq!(spec.base_url, "https://api.anthropic.test/v1");

        // And the catalog data does not go back out.
        let encoded = serde_json::to_value(&spec).unwrap();
        assert!(encoded.get("preferred_models").is_none());
    }

    #[test]
    fn context_report_serde_roundtrip() {
        let breakdown = super::ContextBreakdown {
            system_prompt_tokens: 1200,
            system_tools_tokens: 3400,
            mcp_tools_tokens: 0,
            memory_tokens: 800,
            skills_tokens: 150,
            messages_tokens: 42_000,
            used_tokens: 47_550,
            limit_tokens: Some(200_000),
            compact_buffer_tokens: 20_000,
        };
        let json = serde_json::to_value(Evt::ContextReport(breakdown)).expect("serialize");
        assert_eq!(
            json,
            serde_json::json!({
                "ContextReport": {
                    "system_prompt_tokens": 1200,
                    "system_tools_tokens": 3400,
                    "mcp_tools_tokens": 0,
                    "memory_tokens": 800,
                    "skills_tokens": 150,
                    "messages_tokens": 42000,
                    "used_tokens": 47550,
                    "limit_tokens": 200000,
                    "compact_buffer_tokens": 20000
                }
            })
        );
        let decoded = serde_json::from_value::<Evt>(json).expect("deserialize");
        assert!(matches!(decoded, Evt::ContextReport(b) if b == breakdown));

        // Fields absent on the wire (older daemons) fall back to defaults.
        let sparse: super::ContextBreakdown =
            serde_json::from_value(serde_json::json!({"used_tokens": 10})).unwrap();
        assert_eq!(sparse.used_tokens, 10);
        assert_eq!(sparse.limit_tokens, None);

        let op = serde_json::to_value(Op::ContextReport).expect("serialize op");
        assert_eq!(op, serde_json::json!("ContextReport"));
        assert!(matches!(serde_json::from_value::<Op>(op).unwrap(), Op::ContextReport));
    }

    #[test]
    fn question_pause_serde_roundtrip() {
        let turn_id = Id::new("op");
        let pause = Evt::TurnPause {
            turn_id,
            reason: super::TurnPauseReason::Question {
                tool_use_id: "toolu_1".to_string(),
                questions: vec![super::QuestionSpec {
                    header: "Auth method".to_string(),
                    question: "Which auth method should we use?".to_string(),
                    multi_select: false,
                    options: vec![
                        super::QuestionOption {
                            label: "JWT (Recommended)".to_string(),
                            description: "Stateless tokens".to_string(),
                            preview: None,
                        },
                        super::QuestionOption {
                            label: "Sessions".to_string(),
                            description: "Server-side sessions".to_string(),
                            preview: Some("fn login() {}".to_string()),
                        },
                    ],
                }],
            },
        };

        let json = serde_json::to_value(&pause).expect("serialize question pause");
        // `multi_select` defaults and `preview: None` is skipped, not null.
        let spec = &json["TurnPause"]["reason"]["Question"]["questions"][0];
        assert!(spec["options"][0].get("preview").is_none());
        assert_eq!(spec["options"][1]["preview"], "fn login() {}");

        let decoded: Evt = serde_json::from_value(json).expect("deserialize question pause");
        let Evt::TurnPause {
            reason: super::TurnPauseReason::Question { tool_use_id, questions },
            ..
        } = decoded
        else {
            panic!("expected Question pause");
        };
        assert_eq!(tool_use_id, "toolu_1");
        assert_eq!(questions.len(), 1);
        assert!(!questions[0].multi_select);

        // A spec without `multi_select` on the wire still decodes.
        let sparse: super::QuestionSpec = serde_json::from_value(serde_json::json!({
            "header": "Scope",
            "question": "How broad?",
            "options": [],
        }))
        .unwrap();
        assert!(!sparse.multi_select);
    }

    #[test]
    fn question_response_serde_roundtrip() {
        let turn_id = Id::new("op");
        let op = Op::QuestionResponse {
            turn_id,
            tool_use_id: "toolu_1".to_string(),
            reply: super::QuestionReply::Answered(vec![super::QuestionAnswer {
                selected: vec!["JWT".to_string(), "Sessions".to_string()],
                note: None,
            }]),
        };
        let json = serde_json::to_string(&op).expect("serialize QuestionResponse");
        let decoded: Op = serde_json::from_str(&json).expect("deserialize QuestionResponse");
        assert!(matches!(
            decoded,
            Op::QuestionResponse { tool_use_id, reply: super::QuestionReply::Answered(answers), .. }
                if tool_use_id == "toolu_1" && answers[0].selected.len() == 2
        ));

        // A skip is the bare variant; a discussion request without words is
        // an empty object, so `message` is never null on the wire.
        for (reply, expected) in [
            (super::QuestionReply::Dismissed, serde_json::json!("Dismissed")),
            (super::QuestionReply::Discuss { message: None }, serde_json::json!({ "Discuss": {} })),
            (
                super::QuestionReply::Discuss { message: Some("later".to_string()) },
                serde_json::json!({ "Discuss": { "message": "later" } }),
            ),
        ] {
            let json = serde_json::to_value(&reply).expect("serialize reply");
            assert_eq!(json, expected);
            let decoded: super::QuestionReply =
                serde_json::from_value(json).expect("deserialize reply");
            assert_eq!(decoded, reply);
        }
    }

    #[test]
    fn usage_adds_cache_fields_without_overflowing() {
        let mut usage = Usage {
            input_tokens: 10,
            output_tokens: 20,
            cache_read_tokens: Some(3),
            cache_creation_tokens: None,
        };
        usage += Usage {
            input_tokens: 5,
            output_tokens: 6,
            cache_read_tokens: Some(4),
            cache_creation_tokens: Some(8),
        };

        assert_eq!(usage.input_tokens, 15);
        assert_eq!(usage.output_tokens, 26);
        assert_eq!(usage.total(), 41);
        assert_eq!(usage.cache_read_tokens, Some(7));
        assert_eq!(usage.cache_creation_tokens, Some(8));
    }
}