ahp-types 0.5.2

Wire protocol types for the Agent Host Protocol (AHP).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
// Generated from types/*.ts — do not edit.
//
// Regenerate with: npm run generate:rust

#![allow(missing_docs)]

#[allow(unused_imports)]
use crate::common::{AnyValue, JsonObject, StringOrMarkdown, Uri};
#[allow(unused_imports)]
use serde::{Deserialize, Serialize};
#[allow(unused_imports)]
use serde_repr::{Deserialize_repr, Serialize_repr};

#[allow(unused_imports)]
use crate::state::{
    AgentInfo, AgentSelection, Annotation, AnnotationEntry, Changeset, ChangesetFile,
    ChangesetOperation, ChangesetOperationStatus, ChangesetStatus, ChatInputAnswer,
    ChatInputRequest, ChatInputResponseKind, ChatInteractivity, ChatOrigin, ChatSummary,
    ConfirmationOption, Customization, ErrorInfo, McpServerState, Message, ModelSelection,
    PendingMessageKind, ResponsePart, SessionActiveClient, SessionInputRequest, TerminalClaim,
    TerminalInfo, TextRange, ToolCallCancellationReason, ToolCallConfirmationReason,
    ToolCallContributor, ToolCallResult, ToolDefinition, ToolResultContent, Turn, UsageInfo,
};

// ─── ActionType ──────────────────────────────────────────────────────

/// Discriminant values for all state actions.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum ActionType {
    #[serde(rename = "root/agentsChanged")]
    RootAgentsChanged,
    #[serde(rename = "root/activeSessionsChanged")]
    RootActiveSessionsChanged,
    #[serde(rename = "session/ready")]
    SessionReady,
    #[serde(rename = "session/creationFailed")]
    SessionCreationFailed,
    #[serde(rename = "session/chatAdded")]
    SessionChatAdded,
    #[serde(rename = "session/chatRemoved")]
    SessionChatRemoved,
    #[serde(rename = "session/chatUpdated")]
    SessionChatUpdated,
    #[serde(rename = "session/defaultChatChanged")]
    SessionDefaultChatChanged,
    #[serde(rename = "chat/turnStarted")]
    ChatTurnStarted,
    #[serde(rename = "chat/delta")]
    ChatDelta,
    #[serde(rename = "chat/responsePart")]
    ChatResponsePart,
    #[serde(rename = "chat/toolCallStart")]
    ChatToolCallStart,
    #[serde(rename = "chat/toolCallDelta")]
    ChatToolCallDelta,
    #[serde(rename = "chat/toolCallReady")]
    ChatToolCallReady,
    #[serde(rename = "chat/toolCallConfirmed")]
    ChatToolCallConfirmed,
    #[serde(rename = "chat/toolCallComplete")]
    ChatToolCallComplete,
    #[serde(rename = "chat/toolCallResultConfirmed")]
    ChatToolCallResultConfirmed,
    #[serde(rename = "chat/toolCallContentChanged")]
    ChatToolCallContentChanged,
    #[serde(rename = "chat/turnComplete")]
    ChatTurnComplete,
    #[serde(rename = "chat/turnCancelled")]
    ChatTurnCancelled,
    #[serde(rename = "chat/error")]
    ChatError,
    #[serde(rename = "chat/activityChanged")]
    ChatActivityChanged,
    #[serde(rename = "session/titleChanged")]
    SessionTitleChanged,
    #[serde(rename = "chat/usage")]
    ChatUsage,
    #[serde(rename = "chat/reasoning")]
    ChatReasoning,
    #[serde(rename = "session/serverToolsChanged")]
    SessionServerToolsChanged,
    #[serde(rename = "session/activeClientSet")]
    SessionActiveClientSet,
    #[serde(rename = "session/activeClientRemoved")]
    SessionActiveClientRemoved,
    #[serde(rename = "session/inputNeededSet")]
    SessionInputNeededSet,
    #[serde(rename = "session/inputNeededRemoved")]
    SessionInputNeededRemoved,
    #[serde(rename = "chat/pendingMessageSet")]
    ChatPendingMessageSet,
    #[serde(rename = "chat/pendingMessageRemoved")]
    ChatPendingMessageRemoved,
    #[serde(rename = "chat/queuedMessagesReordered")]
    ChatQueuedMessagesReordered,
    #[serde(rename = "chat/draftChanged")]
    ChatDraftChanged,
    #[serde(rename = "chat/inputRequested")]
    ChatInputRequested,
    #[serde(rename = "chat/inputAnswerChanged")]
    ChatInputAnswerChanged,
    #[serde(rename = "chat/inputCompleted")]
    ChatInputCompleted,
    #[serde(rename = "session/customizationsChanged")]
    SessionCustomizationsChanged,
    #[serde(rename = "session/customizationToggled")]
    SessionCustomizationToggled,
    #[serde(rename = "session/customizationUpdated")]
    SessionCustomizationUpdated,
    #[serde(rename = "session/customizationRemoved")]
    SessionCustomizationRemoved,
    #[serde(rename = "session/mcpServerStateChanged")]
    SessionMcpServerStateChanged,
    #[serde(rename = "session/mcpServerStartRequested")]
    SessionMcpServerStartRequested,
    #[serde(rename = "session/mcpServerStopRequested")]
    SessionMcpServerStopRequested,
    #[serde(rename = "chat/truncated")]
    ChatTruncated,
    #[serde(rename = "chat/turnsLoaded")]
    ChatTurnsLoaded,
    #[serde(rename = "session/isReadChanged")]
    SessionIsReadChanged,
    #[serde(rename = "session/isArchivedChanged")]
    SessionIsArchivedChanged,
    #[serde(rename = "session/activityChanged")]
    SessionActivityChanged,
    #[serde(rename = "session/changesetsChanged")]
    SessionChangesetsChanged,
    #[serde(rename = "session/configChanged")]
    SessionConfigChanged,
    #[serde(rename = "session/metaChanged")]
    SessionMetaChanged,
    #[serde(rename = "changeset/statusChanged")]
    ChangesetStatusChanged,
    #[serde(rename = "changeset/fileSet")]
    ChangesetFileSet,
    #[serde(rename = "changeset/fileRemoved")]
    ChangesetFileRemoved,
    #[serde(rename = "changeset/filesReviewedChanged")]
    ChangesetFilesReviewedChanged,
    #[serde(rename = "changeset/contentChanged")]
    ChangesetContentChanged,
    #[serde(rename = "changeset/operationsChanged")]
    ChangesetOperationsChanged,
    #[serde(rename = "changeset/operationStatusChanged")]
    ChangesetOperationStatusChanged,
    #[serde(rename = "changeset/cleared")]
    ChangesetCleared,
    #[serde(rename = "annotations/set")]
    AnnotationsSet,
    #[serde(rename = "annotations/updated")]
    AnnotationsUpdated,
    #[serde(rename = "annotations/removed")]
    AnnotationsRemoved,
    #[serde(rename = "annotations/entrySet")]
    AnnotationsEntrySet,
    #[serde(rename = "annotations/entryRemoved")]
    AnnotationsEntryRemoved,
    #[serde(rename = "root/terminalsChanged")]
    RootTerminalsChanged,
    #[serde(rename = "root/configChanged")]
    RootConfigChanged,
    #[serde(rename = "terminal/data")]
    TerminalData,
    #[serde(rename = "terminal/input")]
    TerminalInput,
    #[serde(rename = "terminal/resized")]
    TerminalResized,
    #[serde(rename = "terminal/claimed")]
    TerminalClaimed,
    #[serde(rename = "terminal/titleChanged")]
    TerminalTitleChanged,
    #[serde(rename = "terminal/cwdChanged")]
    TerminalCwdChanged,
    #[serde(rename = "terminal/exited")]
    TerminalExited,
    #[serde(rename = "terminal/cleared")]
    TerminalCleared,
    #[serde(rename = "terminal/commandDetectionAvailable")]
    TerminalCommandDetectionAvailable,
    #[serde(rename = "terminal/commandExecuted")]
    TerminalCommandExecuted,
    #[serde(rename = "terminal/commandFinished")]
    TerminalCommandFinished,
    #[serde(rename = "resourceWatch/changed")]
    ResourceWatchChanged,
}

// ─── Action Envelope ─────────────────────────────────────────────────

/// Identifies the client that originally dispatched an action.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ActionOrigin {
    pub client_id: String,
    pub client_seq: i64,
}

/// Every action is wrapped in an `ActionEnvelope`.
///
/// The envelope identifies the channel the action belongs to (e.g.
/// `ahp-root://` for root actions, the session URI for session actions, the
/// terminal URI for terminal actions). Individual action payloads carry only
/// fields that are intrinsic to the action; the channel comes from the
/// envelope so that any subscribable resource can route its actions uniformly.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ActionEnvelope {
    /// Channel URI this action belongs to.
    pub channel: Uri,
    pub action: StateAction,
    pub server_seq: u64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub origin: Option<ActionOrigin>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub rejection_reason: Option<String>,
}

// ─── Action Payloads ─────────────────────────────────────────────────

/// Fired when available agent backends or their models change.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RootAgentsChangedAction {
    /// Updated agent list
    pub agents: Vec<AgentInfo>,
}

/// Fired when the number of active sessions changes.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RootActiveSessionsChangedAction {
    /// Current count of active sessions
    pub active_sessions: i64,
}

/// Fired when agent-host configuration values change.
///
/// By default, the reducer merges the new values into `state.config.values`.
/// Set `replace` to `true` to replace all values instead of merging.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RootConfigChangedAction {
    /// Updated config values
    pub config: JsonObject,
    /// When `true`, replaces all config values instead of merging
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub replace: Option<bool>,
}

/// Session backend initialized successfully.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SessionReadyAction {}

/// Session backend failed to initialize.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SessionCreationFailedAction {
    /// Error details
    pub error: ErrorInfo,
}

/// A chat was added to this session's catalog. Upsert semantics: if a chat
/// with the same `summary.resource` already exists, the existing entry is
/// replaced.
///
/// Mirrors the root-channel `root/sessionAdded` notification.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SessionChatAddedAction {
    /// The full summary of the newly added (or upserted) chat.
    pub summary: ChatSummary,
}

/// A chat was removed from this session's catalog. No-op when no entry matches.
///
/// Mirrors the root-channel `root/sessionRemoved` notification.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SessionChatRemovedAction {
    /// The URI of the chat to remove.
    pub chat: Uri,
}

/// One existing chat's summary fields changed.
///
/// Partial-update semantics: only fields present in `changes` are written;
/// omitted fields are preserved. Identity fields (`resource`) MUST NOT be
/// carried in `changes`. No-op when no entry with `chat` exists — clients
/// SHOULD then wait for a {@link SessionChatAddedAction | `session/chatAdded`}.
///
/// Mirrors the root-channel `root/sessionSummaryChanged` notification.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SessionChatUpdatedAction {
    /// The URI of the chat whose summary changed.
    pub chat: Uri,
    /// Mutable summary fields that changed; omitted fields are unchanged.
    ///
    /// Identity fields (`resource`) never change and MUST be omitted by
    /// senders; receivers SHOULD ignore them if present.
    pub changes: PartialChatSummary,
}

/// The default chat input-routing hint for this session changed.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct SessionDefaultChatChangedAction {
    /// New default chat URI, or `undefined` to clear the hint.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub default_chat: Option<Uri>,
}

/// A new message has been sent to the agent, and a new turn starts.
///
/// A client is only allowed to send {@link MessageKind.User} messages.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChatTurnStartedAction {
    /// Turn identifier
    pub turn_id: String,
    /// The new message
    pub message: Message,
    /// If this turn was auto-started from a queued message, the ID of that message
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub queued_message_id: Option<String>,
    /// Additional provider-specific metadata for this action.
    ///
    /// Clients MAY look for well-known keys here to provide enhanced UI, and
    /// agent hosts MAY use it to carry per-event context that does not fit any
    /// other field — for example, attributing the event to a specific agent
    /// (such as a sub-agent acting within the turn). Mirrors the MCP `_meta`
    /// convention.
    #[serde(rename = "_meta", default, skip_serializing_if = "Option::is_none")]
    pub meta: Option<JsonObject>,
}

/// Streaming text chunk from the assistant, appended to a specific response part.
///
/// The server MUST first emit a `chat/responsePart` to create the target
/// part (markdown or reasoning), then use this action to append text to it.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChatDeltaAction {
    /// Turn identifier
    pub turn_id: String,
    /// Identifier of the response part to append to
    pub part_id: String,
    /// Text chunk
    pub content: String,
    /// Additional provider-specific metadata for this action.
    ///
    /// Clients MAY look for well-known keys here to provide enhanced UI, and
    /// agent hosts MAY use it to carry per-event context that does not fit any
    /// other field — for example, attributing the event to a specific agent
    /// (such as a sub-agent acting within the turn). Mirrors the MCP `_meta`
    /// convention.
    #[serde(rename = "_meta", default, skip_serializing_if = "Option::is_none")]
    pub meta: Option<JsonObject>,
}

/// Structured content appended to the response.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChatResponsePartAction {
    /// Turn identifier
    pub turn_id: String,
    /// Response part (markdown or content ref)
    pub part: ResponsePart,
    /// Additional provider-specific metadata for this action.
    ///
    /// Clients MAY look for well-known keys here to provide enhanced UI, and
    /// agent hosts MAY use it to carry per-event context that does not fit any
    /// other field — for example, attributing the event to a specific agent
    /// (such as a sub-agent acting within the turn). Mirrors the MCP `_meta`
    /// convention.
    #[serde(rename = "_meta", default, skip_serializing_if = "Option::is_none")]
    pub meta: Option<JsonObject>,
}

/// A tool call begins — parameters are streaming from the LM.
///
/// The server sets {@link ToolCallContributor | `contributor`} to identify
/// the origin of the tool. For client-provided tools, the named client is
/// responsible for executing the tool once it reaches the `running` state
/// and dispatching `chat/toolCallComplete`. For MCP-served tools, the
/// server executes the call against the named `McpServerCustomization`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChatToolCallStartAction {
    /// Turn identifier
    pub turn_id: String,
    /// Tool call identifier
    pub tool_call_id: String,
    /// Additional provider-specific metadata for this tool call.
    ///
    /// Clients MAY look for well-known keys here to provide enhanced UI.
    /// For example, a `ptyTerminal` key with `{ input: string; output: string }`
    /// indicates the tool operated on a terminal (both `input` and `output` may
    /// contain escape sequences).
    #[serde(rename = "_meta", default, skip_serializing_if = "Option::is_none")]
    pub meta: Option<JsonObject>,
    /// Internal tool name (for debugging/logging)
    pub tool_name: String,
    /// Human-readable tool name
    pub display_name: String,
    /// Human-readable description of what the tool invocation intends to do
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub intention: Option<String>,
    /// Reference to the contributor of the tool being called. Absent for
    /// server-side tools that are not contributed by a client or MCP server.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub contributor: Option<ToolCallContributor>,
}

/// Streaming partial parameters for a tool call.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChatToolCallDeltaAction {
    /// Turn identifier
    pub turn_id: String,
    /// Tool call identifier
    pub tool_call_id: String,
    /// Additional provider-specific metadata for this tool call.
    ///
    /// Clients MAY look for well-known keys here to provide enhanced UI.
    /// For example, a `ptyTerminal` key with `{ input: string; output: string }`
    /// indicates the tool operated on a terminal (both `input` and `output` may
    /// contain escape sequences).
    #[serde(rename = "_meta", default, skip_serializing_if = "Option::is_none")]
    pub meta: Option<JsonObject>,
    /// Partial parameter content to append
    pub content: String,
    /// Updated progress message
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub invocation_message: Option<StringOrMarkdown>,
}

/// Tool call parameters are complete, or a running tool requires re-confirmation.
///
/// When dispatched for a `streaming` tool call, transitions to `pending-confirmation`
/// or directly to `running` if `confirmed` is set.
///
/// When dispatched for a `running` tool call (e.g. mid-execution permission needed),
/// transitions back to `pending-confirmation`. The `invocationMessage` and `_meta`
/// SHOULD be updated to describe the specific confirmation needed. Clients use the
/// standard `chat/toolCallConfirmed` flow to approve or deny.
///
/// For client-provided tools, the server typically sets `confirmed` to
/// `'not-needed'` so the tool transitions directly to `running`, where the
/// owning client can begin execution immediately.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChatToolCallReadyAction {
    /// Turn identifier
    pub turn_id: String,
    /// Tool call identifier
    pub tool_call_id: String,
    /// Additional provider-specific metadata for this tool call.
    ///
    /// Clients MAY look for well-known keys here to provide enhanced UI.
    /// For example, a `ptyTerminal` key with `{ input: string; output: string }`
    /// indicates the tool operated on a terminal (both `input` and `output` may
    /// contain escape sequences).
    #[serde(rename = "_meta", default, skip_serializing_if = "Option::is_none")]
    pub meta: Option<JsonObject>,
    /// Message describing what the tool will do or what confirmation is needed
    pub invocation_message: StringOrMarkdown,
    /// Raw tool input
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tool_input: Option<String>,
    /// Short title for the confirmation prompt (e.g. `"Run in terminal"`, `"Write file"`)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub confirmation_title: Option<StringOrMarkdown>,
    /// File edits that this tool call will perform, for preview before confirmation
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub edits: Option<AnyValue>,
    /// Whether the agent host allows the client to edit the tool's input parameters before confirming
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub editable: Option<bool>,
    /// If set, the tool was auto-confirmed and transitions directly to `running`
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub confirmed: Option<ToolCallConfirmationReason>,
    /// Options the server offers for this confirmation. When present, the client
    /// SHOULD render these instead of a plain approve/deny UI. Each option
    /// belongs to a {@link ConfirmationOptionGroup} so the client can still
    /// categorise the choices.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub options: Option<Vec<ConfirmationOption>>,
}

/// Client approves or denies a pending tool call (merged approved + denied variants).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChatToolCallConfirmedAction {
    pub turn_id: String,
    pub tool_call_id: String,
    /// Additional provider-specific metadata for this tool call.
    #[serde(rename = "_meta", default, skip_serializing_if = "Option::is_none")]
    pub meta: Option<JsonObject>,
    /// Whether the tool call was approved.
    pub approved: bool,
    /// How the tool was confirmed (present when approved).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub confirmed: Option<ToolCallConfirmationReason>,
    /// Why the tool was cancelled (present when denied).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason: Option<ToolCallCancellationReason>,
    /// Edited tool input parameters, if the client modified them before confirming.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub edited_tool_input: Option<String>,
    /// What the user suggested doing instead (present when denied).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub user_suggestion: Option<Message>,
    /// Explanation for the denial.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason_message: Option<StringOrMarkdown>,
    /// ID of the selected confirmation option, if the server provided options.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub selected_option_id: Option<String>,
}

/// Tool execution finished. Transitions to `completed` or `pending-result-confirmation`
/// if `requiresResultConfirmation` is `true`.
///
/// For client-provided tools (whose tool call state carries a client
/// `ToolCallContributor` with a `clientId`), the owning client dispatches this
/// action with the execution result. The server SHOULD reject this action if the
/// dispatching client does not match the contributor's `clientId`.
///
/// Servers waiting on a client tool call MAY time out after a reasonable duration
/// if the implementing client disconnects or becomes unresponsive, and dispatch
/// this action with `result.success = false` and an appropriate error.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChatToolCallCompleteAction {
    /// Turn identifier
    pub turn_id: String,
    /// Tool call identifier
    pub tool_call_id: String,
    /// Additional provider-specific metadata for this tool call.
    ///
    /// Clients MAY look for well-known keys here to provide enhanced UI.
    /// For example, a `ptyTerminal` key with `{ input: string; output: string }`
    /// indicates the tool operated on a terminal (both `input` and `output` may
    /// contain escape sequences).
    #[serde(rename = "_meta", default, skip_serializing_if = "Option::is_none")]
    pub meta: Option<JsonObject>,
    /// Execution result
    pub result: ToolCallResult,
    /// If true, the result requires client approval before finalizing
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub requires_result_confirmation: Option<bool>,
}

/// Client approves or denies a tool's result.
///
/// If `approved` is `false`, the tool transitions to `cancelled` with reason `result-denied`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChatToolCallResultConfirmedAction {
    /// Turn identifier
    pub turn_id: String,
    /// Tool call identifier
    pub tool_call_id: String,
    /// Additional provider-specific metadata for this tool call.
    ///
    /// Clients MAY look for well-known keys here to provide enhanced UI.
    /// For example, a `ptyTerminal` key with `{ input: string; output: string }`
    /// indicates the tool operated on a terminal (both `input` and `output` may
    /// contain escape sequences).
    #[serde(rename = "_meta", default, skip_serializing_if = "Option::is_none")]
    pub meta: Option<JsonObject>,
    /// Whether the result was approved
    pub approved: bool,
}

/// Partial content produced while a tool is still executing.
///
/// Replaces the `content` array on the running tool call state. Clients can
/// use this to display live feedback (e.g. a terminal reference) before the
/// tool completes.
///
/// For client-provided tools (whose tool call state carries a client
/// `ToolCallContributor` with a `clientId`), the owning client dispatches this
/// action to stream intermediate content while executing. The server SHOULD
/// reject this action if the dispatching client does not match the contributor's
/// `clientId`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChatToolCallContentChangedAction {
    /// Turn identifier
    pub turn_id: String,
    /// Tool call identifier
    pub tool_call_id: String,
    /// Additional provider-specific metadata for this tool call.
    ///
    /// Clients MAY look for well-known keys here to provide enhanced UI.
    /// For example, a `ptyTerminal` key with `{ input: string; output: string }`
    /// indicates the tool operated on a terminal (both `input` and `output` may
    /// contain escape sequences).
    #[serde(rename = "_meta", default, skip_serializing_if = "Option::is_none")]
    pub meta: Option<JsonObject>,
    /// The current partial content for the running tool call
    pub content: Vec<ToolResultContent>,
}

/// Turn finished — the assistant is idle.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChatTurnCompleteAction {
    /// Turn identifier
    pub turn_id: String,
    /// Additional provider-specific metadata for this action.
    ///
    /// Clients MAY look for well-known keys here to provide enhanced UI, and
    /// agent hosts MAY use it to carry per-event context that does not fit any
    /// other field — for example, attributing the event to a specific agent
    /// (such as a sub-agent acting within the turn). Mirrors the MCP `_meta`
    /// convention.
    #[serde(rename = "_meta", default, skip_serializing_if = "Option::is_none")]
    pub meta: Option<JsonObject>,
}

/// Turn was aborted; server stops processing.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChatTurnCancelledAction {
    /// Turn identifier
    pub turn_id: String,
    /// Additional provider-specific metadata for this action.
    ///
    /// Clients MAY look for well-known keys here to provide enhanced UI, and
    /// agent hosts MAY use it to carry per-event context that does not fit any
    /// other field — for example, attributing the event to a specific agent
    /// (such as a sub-agent acting within the turn). Mirrors the MCP `_meta`
    /// convention.
    #[serde(rename = "_meta", default, skip_serializing_if = "Option::is_none")]
    pub meta: Option<JsonObject>,
}

/// Error during turn processing.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChatErrorAction {
    /// Turn identifier
    pub turn_id: String,
    /// Error details
    pub error: ErrorInfo,
    /// Additional provider-specific metadata for this action.
    ///
    /// Clients MAY look for well-known keys here to provide enhanced UI, and
    /// agent hosts MAY use it to carry per-event context that does not fit any
    /// other field — for example, attributing the event to a specific agent
    /// (such as a sub-agent acting within the turn). Mirrors the MCP `_meta`
    /// convention.
    #[serde(rename = "_meta", default, skip_serializing_if = "Option::is_none")]
    pub meta: Option<JsonObject>,
}

/// The activity description of this chat changed.
///
/// Dispatched by the server to indicate what the chat is currently doing
/// (e.g. running a tool, thinking). Clear activity by omitting it or setting it
/// to `undefined`.
/// Producers SHOULD also update the parent session's chat catalog with
/// `session/chatUpdated` so `ChatSummary.activity` stays in sync.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct ChatActivityChangedAction {
    /// Human-readable description of current activity; omit or set `undefined` to clear
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub activity: Option<String>,
}

/// Session title updated. Fired by the server when the title is auto-generated
/// from conversation, or dispatched by a client to rename a session.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SessionTitleChangedAction {
    /// New title
    pub title: String,
}

/// Token usage report for a turn.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChatUsageAction {
    /// Turn identifier
    pub turn_id: String,
    /// Token usage data
    pub usage: UsageInfo,
    /// Additional provider-specific metadata for this action.
    ///
    /// Clients MAY look for well-known keys here to provide enhanced UI, and
    /// agent hosts MAY use it to carry per-event context that does not fit any
    /// other field — for example, attributing the event to a specific agent
    /// (such as a sub-agent acting within the turn). Mirrors the MCP `_meta`
    /// convention.
    #[serde(rename = "_meta", default, skip_serializing_if = "Option::is_none")]
    pub meta: Option<JsonObject>,
}

/// Reasoning/thinking text from the model, appended to a specific reasoning response part.
///
/// The server MUST first emit a `chat/responsePart` to create the target
/// reasoning part, then use this action to append text to it.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChatReasoningAction {
    /// Turn identifier
    pub turn_id: String,
    /// Identifier of the reasoning response part to append to
    pub part_id: String,
    /// Reasoning text chunk
    pub content: String,
    /// Additional provider-specific metadata for this action.
    ///
    /// Clients MAY look for well-known keys here to provide enhanced UI, and
    /// agent hosts MAY use it to carry per-event context that does not fit any
    /// other field — for example, attributing the event to a specific agent
    /// (such as a sub-agent acting within the turn). Mirrors the MCP `_meta`
    /// convention.
    #[serde(rename = "_meta", default, skip_serializing_if = "Option::is_none")]
    pub meta: Option<JsonObject>,
}

/// The read state of the session changed.
///
/// Dispatched by a client to mark a session as read (e.g. after viewing it)
/// or unread (e.g. after new activity since the client last looked at it).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SessionIsReadChangedAction {
    /// Whether the session has been read
    pub is_read: bool,
}

/// The archived state of the session changed.
///
/// Dispatched by a client to archive a session (e.g. the task is
/// complete) or to unarchive it.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SessionIsArchivedChangedAction {
    /// Whether the session is archived
    pub is_archived: bool,
}

/// The activity description of the session changed.
///
/// Dispatched by the server to indicate what the session is currently doing
/// (e.g. running a tool, thinking). Clear activity by setting it to `undefined`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct SessionActivityChangedAction {
    /// Human-readable description of current activity, or `undefined` to clear
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub activity: Option<String>,
}

/// The {@link Changeset | catalogue of changesets} the agent host
/// advertises for this session changed. Replaces
/// {@link SessionState.changesets | `state.changesets`} entirely
/// (full-replacement semantics) — set to `undefined` to clear the
/// catalogue.
///
/// Producers dispatch this whenever entries are added or removed. The
/// fan-out happens through this action so observers see catalogue
/// mutations in the same {@link ChangesetAction | per-changeset} action
/// stream they already follow for file-level updates.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct SessionChangesetsChangedAction {
    /// New catalogue, or `undefined` to clear it
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub changesets: Option<Vec<Changeset>>,
}

/// Server tools for this session have changed.
///
/// Full-replacement semantics: the `tools` array replaces the previous `serverTools` entirely.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SessionServerToolsChangedAction {
    /// Updated server tools list (full replacement)
    pub tools: Vec<ToolDefinition>,
}

/// An active client for this session was added or updated.
///
/// Upsert semantics keyed by {@link SessionActiveClient.clientId | `clientId`}:
/// a client dispatches this action with its own `SessionActiveClient` to join
/// the session's active clients or refresh its entry, replacing any existing
/// entry that has the same `clientId`. Multiple clients may be active at once.
/// This is also how a client updates its published tools or customizations —
/// re-dispatch with the full, updated entry. Use
/// {@link SessionActiveClientRemovedAction | `session/activeClientRemoved`} to
/// leave. The server SHOULD automatically dispatch that removal when an active
/// client disconnects.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SessionActiveClientSetAction {
    /// The active client to add or update, matched by `clientId`.
    pub active_client: SessionActiveClient,
}

/// An active client was removed from this session.
///
/// Removes the entry for the client identified by `clientId` from
/// {@link SessionState.activeClients}; a no-op when no entry matches.
///
/// The host SHOULD dispatch this automatically when a client stops participating
/// in the session — for example when it unsubscribes from the session channel,
/// when it disconnects and does not reconnect within a host-defined grace
/// period, or when a `reconnect` command's `subscriptions` omit a session the
/// client was still active in. When removing a client, the host SHOULD also
/// cancel that client's in-flight tool calls — those whose tool call state
/// carries a client `ToolCallContributor` with the matching `clientId` — by
/// dispatching `chat/toolCallComplete` with `result.success = false`. (There is
/// no per-tool-call server cancel; a failed completion is the cancellation
/// mechanism, and the call ends in `completed` status with a failed result.)
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SessionActiveClientRemovedAction {
    /// The `clientId` of the active client to remove.
    pub client_id: String,
}

/// A session-level input request was added or updated.
///
/// Upsert semantics keyed by {@link SessionInputRequest.id | `request.id`}: the
/// host dispatches this with the full {@link SessionInputRequest} to append a new
/// entry to {@link SessionState.inputNeeded} or replace the existing entry with
/// the same `id`.
///
/// Server-originated: the host mirrors chat-level requests (elicitations, tool
/// confirmations, client-tool executions) into the session aggregate so clients
/// subscribed only to the session channel can discover them. Clients respond by
/// dispatching the ordinary `chat/*` action to the entry's `chat` channel — see
/// {@link SessionInputRequest}.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SessionInputNeededSetAction {
    /// The input request to add or update, matched by `id`.
    pub request: SessionInputRequest,
}

/// A session-level input request was removed.
///
/// Removes the entry identified by `id` from
/// {@link SessionState.inputNeeded}; a no-op when no entry matches.
///
/// Server-originated: the host dispatches this once the underlying request
/// resolves (the user answers, the tool call is confirmed, or the client
/// reports its result).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SessionInputNeededRemovedAction {
    /// The `id` of the input request to remove.
    pub id: String,
}

/// A pending message was set (upsert semantics: creates or replaces).
///
/// For steering messages, this always replaces the single steering message.
/// For queued messages, if a message with the given `id` already exists it is
/// updated in place; otherwise it is appended to the queue. If the chat is
/// idle when a queued message is set, the server SHOULD immediately consume it
/// and start a new turn.
///
/// A client is only allowed to send {@link MessageKind.User} messages.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChatPendingMessageSetAction {
    /// Whether this is a steering or queued message
    pub kind: PendingMessageKind,
    /// Unique identifier for this pending message
    pub id: String,
    /// The message content
    pub message: Message,
}

/// A pending message was removed (steering or queued).
///
/// Dispatched by clients to cancel a pending message, or by the server when
/// it consumes a message (e.g. starting a turn from a queued message or
/// injecting a steering message into the current turn).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChatPendingMessageRemovedAction {
    /// Whether this is a steering or queued message
    pub kind: PendingMessageKind,
    /// Identifier of the pending message to remove
    pub id: String,
}

/// Reorder the queued messages.
///
/// The `order` array contains the IDs of queued messages in their new
/// desired order. IDs not present in the current queue are ignored.
/// Queued messages whose IDs are absent from `order` are appended at
/// the end in their original relative order (so a client with a stale
/// view of the queue never silently drops messages).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChatQueuedMessagesReorderedAction {
    /// Queued message IDs in the desired order
    pub order: Vec<String>,
}

/// The chat's draft input changed.
///
/// Clients MAY periodically sync their local input state — the message the user
/// is composing, including its {@link Message.model | model} /
/// {@link Message.agent | agent} selection and attachments — into the chat's
/// {@link ChatState.draft | `draft`} so it survives reloads and is visible to
/// other clients viewing the same chat. Eager syncing is **not** required;
/// clients SHOULD debounce and MAY sync only at convenient points. Set `draft`
/// to `undefined` to clear it (e.g. once the message is sent).
///
/// A client is only allowed to draft {@link MessageKind.User} messages.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct ChatDraftChangedAction {
    /// New draft message, or `undefined` to clear it
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub draft: Option<Message>,
}

/// A session requested input from the user.
///
/// Full-request upsert semantics: the `request` replaces any existing request
/// with the same `id`, or is appended if it is new. Answer drafts are preserved
/// unless `request.answers` is provided.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChatInputRequestedAction {
    /// Input request to create or replace
    pub request: ChatInputRequest,
}

/// A client updated, submitted, skipped, or removed a single in-progress answer.
///
/// Dispatching with `answer: undefined` removes that question's answer draft.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChatInputAnswerChangedAction {
    /// Input request identifier
    pub request_id: String,
    /// Question identifier within the input request
    pub question_id: String,
    /// Updated answer, or `undefined` to clear an answer draft
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub answer: Option<ChatInputAnswer>,
}

/// A client accepted, declined, or cancelled a session input request.
///
/// If accepted, the server uses `answers` (when provided) plus the request's
/// synced answer state to resume the blocked operation.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChatInputCompletedAction {
    /// Input request identifier
    pub request_id: String,
    /// Completion outcome
    pub response: ChatInputResponseKind,
    /// Optional final answer replacement, keyed by question ID
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub answers: Option<std::collections::HashMap<String, ChatInputAnswer>>,
}

/// The session's customizations have changed.
///
/// Full-replacement semantics: the `customizations` array replaces the
/// previous `customizations` entirely.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SessionCustomizationsChangedAction {
    /// Updated customization list (full replacement).
    pub customizations: Vec<Customization>,
}

/// A client toggled a customization on or off.
///
/// Matches `id` against every top-level customization first — a plugin or
/// directory container, or a bare top-level MCP server — then against the
/// children inside each container (a skill, agent, or other entry), and
/// sets the matched entry's `enabled` flag. Disabling a container still
/// disables all of its children — the effective state of a child is
/// `container.enabled && (child.enabled ?? true)` — so toggling a child
/// only matters while its container is enabled. Is a no-op when no
/// customization has the given `id`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SessionCustomizationToggledAction {
    /// The id of the container or child to toggle.
    pub id: String,
    /// Whether to enable or disable the targeted customization.
    pub enabled: bool,
}

/// Upserts a top-level customization (plugin or directory).
///
/// The reducer locates the existing entry by `customization.id`:
///
/// - If found, the entry is replaced entirely with `customization`,
///   including its `children` array. To preserve existing children, the
///   host must include them on the payload.
/// - If not found, the entry is appended.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SessionCustomizationUpdatedAction {
    /// The customization to upsert (matched by `customization.id`).
    pub customization: Customization,
}

/// Removes a customization by id.
///
/// Searches every container and its children for the entry. If the entry
/// is a container, its children are removed with it. Is a no-op when no
/// matching id is found.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SessionCustomizationRemovedAction {
    /// The id of the customization to remove.
    pub id: String,
}

/// Updates the runtime fields of an existing
/// {@link McpServerCustomization} — narrow alternative to
/// {@link SessionCustomizationUpdatedAction} for the high-frequency
/// `starting` ↔ `ready` ↔ `authRequired` transitions.
///
/// Locates the target entry by `id`, searching both the top-level
/// customization list and the `children` array of every container.
/// Replaces the entry's {@link McpServerCustomization.state | `state`}
/// and {@link McpServerCustomization.channel | `channel`}
/// (full-replacement semantics: omit `channel` to clear an existing
/// channel URI). Other fields of the customization are preserved.
///
/// Is a no-op when no matching `McpServerCustomization` is found. To
/// update any other field (name, icons, `mcpApp` capabilities, etc.) use
/// {@link SessionCustomizationUpdatedAction} instead.
///
/// When the transition is to {@link McpServerStatus.AuthRequired}
/// because of a request issued mid-turn, the host SHOULD also raise
/// {@link SessionStatus.InputNeeded} on the session — see
/// {@link McpServerAuthRequiredState} for the rationale.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SessionMcpServerStateChangedAction {
    /// The id of the {@link McpServerCustomization} to update.
    pub id: String,
    /// The new lifecycle state.
    pub state: McpServerState,
    /// Updated `mcp://` side-channel URI. Full-replacement: omit to clear
    /// an existing channel (typical when leaving
    /// {@link McpServerStatus.Ready | `Ready`}).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub channel: Option<Uri>,
}

/// Requests that the host start or restart an existing
/// {@link McpServerCustomization}.
///
/// Locates the target entry by `id`, searching both the top-level
/// customization list and the `children` array of every container. The
/// reducer optimistically moves the server to
/// {@link McpServerStatus.Starting | `starting`} and clears any previous
/// {@link McpServerCustomization.channel | `channel`}; the host remains
/// authoritative and SHOULD follow with
/// {@link SessionMcpServerStateChangedAction | `session/mcpServerStateChanged`}
/// once the server becomes ready, needs authentication, fails, or is
/// rejected. Is a no-op when no matching `McpServerCustomization` is found.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SessionMcpServerStartRequestedAction {
    /// The id of the {@link McpServerCustomization} to start.
    pub id: String,
}

/// Requests that the host stop an existing {@link McpServerCustomization}.
///
/// Locates the target entry by `id`, searching both the top-level
/// customization list and the `children` array of every container. The
/// reducer optimistically moves the server to
/// {@link McpServerStatus.Stopped | `stopped`} and clears any previous
/// {@link McpServerCustomization.channel | `channel`}. Replacing an
/// {@link McpServerStatus.AuthRequired | `authRequired`} lifecycle state with
/// `stopped` unblocks the server from waiting on authentication. If the host
/// also raised session-level input-needed state solely for that MCP server, it
/// SHOULD remove that input-needed entry when accepting the stop.
///
/// The host remains authoritative and MAY reject the action or follow with
/// {@link SessionMcpServerStateChangedAction | `session/mcpServerStateChanged`}
/// if the final lifecycle state differs. Is a no-op when no matching
/// `McpServerCustomization` is found.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SessionMcpServerStopRequestedAction {
    /// The id of the {@link McpServerCustomization} to stop.
    pub id: String,
}

/// Truncates a session's history. If `turnId` is provided, all turns after that
/// turn are removed and the specified turn is kept. If `turnId` is omitted, all
/// turns are removed.
///
/// If there is an active turn it is silently dropped and the chat status
/// returns to `idle`.
///
/// Common use-case: truncate old data then dispatch a new
/// `chat/turnStarted` with an edited message.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct ChatTruncatedAction {
    /// Keep turns up to and including this turn. Omit to clear all turns.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub turn_id: Option<String>,
}

/// Loads older completed turns into this chat's state.
///
/// Hosts dispatch this before responding to `fetchTurns`, and before applying
/// any operation that references a turn older than the currently loaded window.
/// `turns` is ordered oldest-first and is prepended to the current `turns`
/// window. `turnsNextCursor` replaces the state's cursor; omit it when all
/// retained turns are now loaded.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChatTurnsLoadedAction {
    /// Older completed turns loaded into the state, ordered oldest-first.
    pub turns: Vec<Turn>,
    /// Opaque cursor for loading the next older page, if one remains.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub turns_next_cursor: Option<String>,
}

/// Client changed a mutable config value mid-session.
///
/// Only properties with `sessionMutable: true` in the config schema may be
/// changed. The server validates and broadcasts the action; the reducer merges
/// the new values into `state.config.values`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SessionConfigChangedAction {
    /// Updated config values
    pub config: JsonObject,
    /// When `true`, replaces all config values instead of merging
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub replace: Option<bool>,
}

/// The session's `_meta` side-channel changed. Replaces `state._meta`
/// entirely (full-replacement semantics). Producers SHOULD merge any
/// keys they wish to preserve into the new value before dispatching.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct SessionMetaChangedAction {
    /// New `_meta` payload, or `undefined` to clear it
    #[serde(rename = "_meta", default, skip_serializing_if = "Option::is_none")]
    pub meta: Option<JsonObject>,
}

/// The {@link ChangesetState.status} for this changeset transitioned (e.g.
/// `computing → ready`). The error payload is set together with `status`
/// whenever it transitions to {@link ChangesetStatus.Error | Error}.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChangesetStatusChangedAction {
    /// New computation lifecycle status.
    pub status: ChangesetStatus,
    /// Cause when `status === ChangesetStatus.Error`; otherwise omitted.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error: Option<ErrorInfo>,
}

/// Upsert a {@link ChangesetFile} in the changeset — adds a new entry, or
/// replaces an existing one identified by {@link ChangesetFile.id}.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChangesetFileSetAction {
    /// The new or replacement file entry.
    pub file: ChangesetFile,
}

/// Remove a {@link ChangesetFile} from the changeset by its id.
///
/// Typically dispatched when a file is reverted, staged out, or otherwise
/// no longer in scope (e.g. a renamed file is replaced by a new entry).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChangesetFileRemovedAction {
    /// The {@link ChangesetFile.id} of the file to remove.
    pub file_id: String,
}

/// Update the {@link ChangesetFile.reviewed} flag for one or more files,
/// identified by their {@link ChangesetFile.id}.
///
/// Dispatched by the server as the user marks files reviewed or unreviewed
/// (e.g. toggling a single file, or a "mark all as reviewed" affordance).
/// Only servers that support the "review" functionality dispatch this; a
/// server that leaves {@link ChangesetFile.reviewed} `undefined` never does.
///
/// The reducer sets `reviewed` on every matching file and ignores any
/// `fileIds` entry that does not correspond to a current file.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChangesetFilesReviewedChangedAction {
    /// The {@link ChangesetFile.id}s whose reviewed state changed.
    pub file_ids: Vec<String>,
    /// The new reviewed state to apply to each listed file.
    pub reviewed: bool,
}

/// The changeset's full content changed. Full replacement semantics: `files`
/// replaces the previous file list, and `operations`, when present, replaces
/// the previous operation list.
///
/// Producers SHOULD use this action for initial snapshots and bulk refreshes;
/// use {@link ChangesetFileSetAction}, {@link ChangesetFileRemovedAction}, and
/// {@link ChangesetOperationsChangedAction} for incremental updates.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChangesetContentChangedAction {
    /// Full replacement file list.
    pub files: Vec<ChangesetFile>,
    /// Full replacement operation list. Omit when operations are unchanged.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub operations: Option<Vec<ChangesetOperation>>,
    /// Error information, if the changeset content change failed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error: Option<ErrorInfo>,
}

/// The set of operations available on this changeset changed. Full
/// replacement semantics: `operations` replaces the previous list (or
/// removes it entirely when `operations` is `undefined`).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct ChangesetOperationsChangedAction {
    /// Updated operation list. Pass `undefined` to clear all operations.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub operations: Option<Vec<ChangesetOperation>>,
}

/// The {@link ChangesetOperation.status} for a single operation transitioned
/// (e.g. `idle → running → idle`, or `running → error`). The error payload
/// is set together with `status` whenever it transitions to
/// {@link ChangesetOperationStatus.Error | Error}, and cleared on any other
/// transition.
///
/// Targets one operation by its {@link ChangesetOperation.id}. If no
/// operation with that id is currently present in the changeset, the action
/// is a no-op. Use {@link ChangesetOperationsChangedAction} to add, remove,
/// or otherwise replace the operation list itself.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChangesetOperationStatusChangedAction {
    /// The {@link ChangesetOperation.id} whose status changed.
    pub operation_id: String,
    /// New execution status.
    pub status: ChangesetOperationStatus,
    /// Cause when `status === ChangesetOperationStatus.Error`; otherwise omitted.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error: Option<ErrorInfo>,
}

/// Drop every file from the changeset.
///
/// Two cases use this:
/// 1. The underlying source moved (branch switched, fork point invalidated,
///    …) and the server is recomputing from scratch — subsequent
///    {@link ChangesetFileSetAction} entries will repopulate it.
/// 2. The owning session has ended and the URI is becoming
///    un-subscribable — the server will unsubscribe all clients shortly
///    after dispatching this action.
///
/// Clients SHOULD release any references on receipt and SHOULD NOT
/// distinguish the two cases from the action alone — instead, react to
/// the corresponding session-level lifecycle signal (e.g.
/// `root/sessionRemoved`) for the "going away" case.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChangesetClearedAction {}

/// Upsert an {@link Annotation} in the annotations channel — adds a new
/// annotation, or replaces an existing one identified by
/// {@link Annotation.id}.
///
/// Dispatched by a client to create an annotation (together with its
/// mandatory first entry) or to re-anchor / resolve an existing one; the
/// dispatching client assigns the {@link Annotation.id} and the id of any
/// new entry. When replacing, the full annotation payload (including its
/// {@link Annotation.entries | entries} list) is substituted; producers
/// SHOULD prefer {@link AnnotationsEntrySetAction} for per-entry edits, and
/// {@link AnnotationsUpdatedAction} to resolve / re-anchor an existing
/// annotation, to keep wire updates small.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AnnotationsSetAction {
    /// The new or replacement annotation. MUST contain at least one entry.
    pub annotation: Annotation,
}

/// Partially update an existing {@link Annotation}'s own properties — a narrow
/// alternative to {@link AnnotationsSetAction} for the common case of resolving
/// / re-opening or re-anchoring an annotation without resending its
/// {@link Annotation.entries | entries}.
///
/// Targets one annotation by its {@link annotationId}. Only the fields present
/// on the action are written; omitted fields leave the corresponding
/// {@link Annotation} property unchanged. The annotation's
/// {@link Annotation.entries | entries}, {@link Annotation.id | id}, and
/// {@link Annotation._meta | _meta} are never touched — dispatch
/// {@link AnnotationsSetAction} to replace those, to clear {@link range}
/// (re-anchor to the whole file), or {@link AnnotationsEntrySetAction} /
/// {@link AnnotationsEntryRemovedAction} to edit individual entries.
///
/// If {@link annotationId} does not match any current annotation the action is
/// a no-op.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AnnotationsUpdatedAction {
    /// The {@link Annotation.id} of the annotation to update.
    pub annotation_id: String,
    /// Re-anchors the annotation to the file versions this turn produced.
    /// Matches a {@link Turn.id} on the owning session. Omit to leave the
    /// current {@link Annotation.turnId} unchanged.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub turn_id: Option<String>,
    /// Re-anchors the annotation to this file. Omit to leave the current
    /// {@link Annotation.resource} unchanged.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub resource: Option<Uri>,
    /// Narrows the annotation to this range within {@link resource}. Omit to
    /// leave the current {@link Annotation.range} unchanged; this action cannot
    /// clear an existing range — dispatch {@link AnnotationsSetAction} to
    /// re-anchor to the whole file.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub range: Option<TextRange>,
    /// Marks the annotation resolved (`true`) or re-opens it (`false`). Omit to
    /// leave the current {@link Annotation.resolved} state unchanged.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub resolved: Option<bool>,
}

/// Remove an {@link Annotation} from the channel by its id.
///
/// Dispatched to delete an entire annotation and every entry it contains.
/// Because the protocol forbids empty annotations, a client that wants to
/// remove the last remaining entry dispatches this action — collapsing the
/// annotation — rather than {@link AnnotationsEntryRemovedAction}.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AnnotationsRemovedAction {
    /// The {@link Annotation.id} of the annotation to remove.
    pub annotation_id: String,
}

/// Upsert an {@link AnnotationEntry} within an existing annotation — adds a
/// new entry, or replaces one identified by {@link AnnotationEntry.id}. The
/// dispatching client assigns the {@link AnnotationEntry.id} of a new entry.
/// If {@link annotationId} does not match any current annotation the action
/// is a no-op.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AnnotationsEntrySetAction {
    /// The {@link Annotation.id} the entry belongs to.
    pub annotation_id: String,
    /// The new or replacement entry.
    pub entry: AnnotationEntry,
}

/// Remove a single {@link AnnotationEntry} from an annotation without
/// collapsing the annotation itself. Used when more than one entry remains —
/// to remove the last entry a client dispatches {@link AnnotationsRemovedAction}
/// instead, since the protocol forbids empty annotations.
///
/// If either {@link annotationId} or {@link entryId} does not match the
/// current state the action is a no-op.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AnnotationsEntryRemovedAction {
    /// The {@link Annotation.id} the entry belongs to.
    pub annotation_id: String,
    /// The {@link AnnotationEntry.id} to remove.
    pub entry_id: String,
}

/// Fired when the list of known terminals changes.
///
/// Full-replacement semantics: the `terminals` array replaces the previous
/// `terminals` entirely.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RootTerminalsChangedAction {
    /// Updated terminal list (full replacement)
    pub terminals: Vec<TerminalInfo>,
}

/// Terminal output data (pty → client direction).
///
/// Appends `data` to the terminal's `content` in the reducer.
///
/// `terminal/data` and `terminal/input` are intentionally separate actions
/// because standard write-ahead reconciliation is not safe for terminal I/O.
/// A pty is a stateful, mutable process — optimistically applying input or
/// predicting output would produce incorrect state. Instead, `terminal/input`
/// is a side-effect-only action (client → server → pty), and `terminal/data`
/// is server-authoritative output (pty → server → client).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TerminalDataAction {
    /// Output data (may contain ANSI escape sequences)
    pub data: String,
}

/// Keyboard input sent to the terminal process (client → pty direction).
///
/// This is a side-effect-only action: the server forwards the data to the
/// terminal's pty. The reducer treats this as a no-op since `terminal/data`
/// actions will reflect any resulting output.
///
/// See `terminal/data` for why these two actions are kept separate.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TerminalInputAction {
    /// Input data to send to the pty
    pub data: String,
}

/// Terminal dimensions changed.
///
/// Dispatchable by clients to request a resize, or by the server to inform
/// clients of the actual terminal dimensions.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TerminalResizedAction {
    /// Terminal width in columns
    pub cols: i64,
    /// Terminal height in rows
    pub rows: i64,
}

/// Terminal claim changed. A client or session transfers ownership of the terminal.
///
/// The server SHOULD reject if the dispatching client does not currently hold
/// the claim.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TerminalClaimedAction {
    /// The new claim
    pub claim: TerminalClaim,
}

/// Terminal title changed.
///
/// Fired by the server when the terminal process updates its title (e.g. via
/// escape sequences), or dispatched by a client to rename a terminal.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TerminalTitleChangedAction {
    /// New terminal title
    pub title: String,
}

/// Terminal working directory changed.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TerminalCwdChangedAction {
    /// New working directory
    pub cwd: Uri,
}

/// Terminal process exited.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct TerminalExitedAction {
    /// Process exit code. `undefined` if the process was killed without an exit code.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub exit_code: Option<i64>,
}

/// Terminal scrollback buffer cleared.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TerminalClearedAction {}

/// Shell integration has loaded and the terminal now supports command
/// detection. The server dispatches this when shell integration becomes
/// available (which may happen asynchronously after the terminal is created).
///
/// Clients MUST NOT assume command detection is available until this action
/// (or `terminal/commandExecuted`) has been received.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TerminalCommandDetectionAvailableAction {}

/// A command has been submitted to the shell and is now executing.
/// All subsequent `terminal/data` actions (until the matching
/// `terminal/commandFinished`) constitute this command's output.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TerminalCommandExecutedAction {
    /// Stable identifier for this command, scoped to the terminal URI.
    /// Allows correlating `commandExecuted` → `commandFinished` pairs.
    pub command_id: String,
    /// The command line text that was submitted
    pub command_line: String,
    /// Unix timestamp (ms) of when the command started executing, as measured
    /// on the server.
    pub timestamp: i64,
}

/// A command has finished executing.
///
/// The sequence of `terminal/data` actions between the preceding
/// `terminal/commandExecuted` (same `commandId`) and this action constitutes
/// the complete output of the command.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TerminalCommandFinishedAction {
    /// Matches the `commandId` from the corresponding `commandExecuted`
    pub command_id: String,
    /// Shell exit code. `undefined` if the shell did not report one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub exit_code: Option<i64>,
    /// Wall-clock duration of the command in milliseconds, as measured by the
    /// shell integration script on the server side.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub duration_ms: Option<i64>,
}

/// A batch of resource changes observed by the watcher.
///
/// Watch events are coalesced into batches by the server to keep the
/// action stream tractable; an empty `changes.items` list MUST NOT be
/// dispatched. The reducer does not retain change history — these
/// actions exist purely to deliver events to subscribers, who consume
/// them directly off the action stream and apply their own logic.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ResourceWatchChangedAction {
    /// The set of changes in this batch, wrapped for forward compatibility.
    pub changes: AnyValue,
}

// ─── Partial Summaries ────────────────────────────────────────────────

/// Partial equivalent of ChatSummary — every field is optional for delta updates.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct PartialChatSummary {
    /// Chat URI
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub resource: Option<Uri>,
    /// Chat title
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    /// Current chat status (reuses SessionStatus shape)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub status: Option<u32>,
    /// Human-readable description of what the chat is currently doing
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub activity: Option<String>,
    /// Last modification timestamp (ISO 8601, e.g. `"2025-03-10T18:42:03.123Z"`)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub modified_at: Option<String>,
    /// How this chat came into existence
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub origin: Option<ChatOrigin>,
    /// How the user can interact with this chat. See {@link ChatInteractivity}.
    ///
    /// Supports agent-team patterns where worker chats are read-only or hidden.
    /// Absence defaults to {@link ChatInteractivity.Full} for backward
    /// compatibility.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub interactivity: Option<ChatInteractivity>,
    /// Optional per-chat working directory.
    ///
    /// If absent, the chat inherits
    /// {@link SessionSummary.workingDirectory | the session's working directory}.
    /// See {@link ChatState.workingDirectory} for usage notes.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub working_directory: Option<Uri>,
}

// ─── StateAction Union ───────────────────────────────────────────────

/// Discriminated union of every state action.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum StateAction {
    #[serde(rename = "root/agentsChanged")]
    RootAgentsChanged(RootAgentsChangedAction),
    #[serde(rename = "root/activeSessionsChanged")]
    RootActiveSessionsChanged(RootActiveSessionsChangedAction),
    #[serde(rename = "root/configChanged")]
    RootConfigChanged(RootConfigChangedAction),
    #[serde(rename = "session/ready")]
    SessionReady(SessionReadyAction),
    #[serde(rename = "session/creationFailed")]
    SessionCreationFailed(SessionCreationFailedAction),
    #[serde(rename = "session/chatAdded")]
    SessionChatAdded(SessionChatAddedAction),
    #[serde(rename = "session/chatRemoved")]
    SessionChatRemoved(SessionChatRemovedAction),
    #[serde(rename = "session/chatUpdated")]
    SessionChatUpdated(SessionChatUpdatedAction),
    #[serde(rename = "session/defaultChatChanged")]
    SessionDefaultChatChanged(SessionDefaultChatChangedAction),
    #[serde(rename = "chat/turnStarted")]
    ChatTurnStarted(ChatTurnStartedAction),
    #[serde(rename = "chat/delta")]
    ChatDelta(ChatDeltaAction),
    #[serde(rename = "chat/responsePart")]
    ChatResponsePart(ChatResponsePartAction),
    #[serde(rename = "chat/toolCallStart")]
    ChatToolCallStart(ChatToolCallStartAction),
    #[serde(rename = "chat/toolCallDelta")]
    ChatToolCallDelta(ChatToolCallDeltaAction),
    #[serde(rename = "chat/toolCallReady")]
    ChatToolCallReady(ChatToolCallReadyAction),
    #[serde(rename = "chat/toolCallConfirmed")]
    ChatToolCallConfirmed(ChatToolCallConfirmedAction),
    #[serde(rename = "chat/toolCallComplete")]
    ChatToolCallComplete(ChatToolCallCompleteAction),
    #[serde(rename = "chat/toolCallResultConfirmed")]
    ChatToolCallResultConfirmed(ChatToolCallResultConfirmedAction),
    #[serde(rename = "chat/toolCallContentChanged")]
    ChatToolCallContentChanged(ChatToolCallContentChangedAction),
    #[serde(rename = "chat/turnComplete")]
    ChatTurnComplete(ChatTurnCompleteAction),
    #[serde(rename = "chat/turnCancelled")]
    ChatTurnCancelled(ChatTurnCancelledAction),
    #[serde(rename = "chat/error")]
    ChatError(ChatErrorAction),
    #[serde(rename = "chat/activityChanged")]
    ChatActivityChanged(ChatActivityChangedAction),
    #[serde(rename = "session/titleChanged")]
    SessionTitleChanged(SessionTitleChangedAction),
    #[serde(rename = "chat/usage")]
    ChatUsage(ChatUsageAction),
    #[serde(rename = "chat/reasoning")]
    ChatReasoning(ChatReasoningAction),
    #[serde(rename = "session/isReadChanged")]
    SessionIsReadChanged(SessionIsReadChangedAction),
    #[serde(rename = "session/isArchivedChanged")]
    SessionIsArchivedChanged(SessionIsArchivedChangedAction),
    #[serde(rename = "session/activityChanged")]
    SessionActivityChanged(SessionActivityChangedAction),
    #[serde(rename = "session/changesetsChanged")]
    SessionChangesetsChanged(SessionChangesetsChangedAction),
    #[serde(rename = "session/serverToolsChanged")]
    SessionServerToolsChanged(SessionServerToolsChangedAction),
    #[serde(rename = "session/activeClientSet")]
    SessionActiveClientSet(SessionActiveClientSetAction),
    #[serde(rename = "session/activeClientRemoved")]
    SessionActiveClientRemoved(SessionActiveClientRemovedAction),
    #[serde(rename = "session/inputNeededSet")]
    SessionInputNeededSet(Box<SessionInputNeededSetAction>),
    #[serde(rename = "session/inputNeededRemoved")]
    SessionInputNeededRemoved(SessionInputNeededRemovedAction),
    #[serde(rename = "chat/pendingMessageSet")]
    ChatPendingMessageSet(ChatPendingMessageSetAction),
    #[serde(rename = "chat/pendingMessageRemoved")]
    ChatPendingMessageRemoved(ChatPendingMessageRemovedAction),
    #[serde(rename = "chat/queuedMessagesReordered")]
    ChatQueuedMessagesReordered(ChatQueuedMessagesReorderedAction),
    #[serde(rename = "chat/draftChanged")]
    ChatDraftChanged(ChatDraftChangedAction),
    #[serde(rename = "chat/inputRequested")]
    ChatInputRequested(ChatInputRequestedAction),
    #[serde(rename = "chat/inputAnswerChanged")]
    ChatInputAnswerChanged(ChatInputAnswerChangedAction),
    #[serde(rename = "chat/inputCompleted")]
    ChatInputCompleted(ChatInputCompletedAction),
    #[serde(rename = "session/customizationsChanged")]
    SessionCustomizationsChanged(SessionCustomizationsChangedAction),
    #[serde(rename = "session/customizationToggled")]
    SessionCustomizationToggled(SessionCustomizationToggledAction),
    #[serde(rename = "session/customizationUpdated")]
    SessionCustomizationUpdated(Box<SessionCustomizationUpdatedAction>),
    #[serde(rename = "session/customizationRemoved")]
    SessionCustomizationRemoved(SessionCustomizationRemovedAction),
    #[serde(rename = "session/mcpServerStateChanged")]
    SessionMcpServerStateChanged(Box<SessionMcpServerStateChangedAction>),
    #[serde(rename = "session/mcpServerStartRequested")]
    SessionMcpServerStartRequested(SessionMcpServerStartRequestedAction),
    #[serde(rename = "session/mcpServerStopRequested")]
    SessionMcpServerStopRequested(SessionMcpServerStopRequestedAction),
    #[serde(rename = "chat/truncated")]
    ChatTruncated(ChatTruncatedAction),
    #[serde(rename = "chat/turnsLoaded")]
    ChatTurnsLoaded(ChatTurnsLoadedAction),
    #[serde(rename = "session/configChanged")]
    SessionConfigChanged(SessionConfigChangedAction),
    #[serde(rename = "session/metaChanged")]
    SessionMetaChanged(SessionMetaChangedAction),
    #[serde(rename = "changeset/statusChanged")]
    ChangesetStatusChanged(ChangesetStatusChangedAction),
    #[serde(rename = "changeset/fileSet")]
    ChangesetFileSet(ChangesetFileSetAction),
    #[serde(rename = "changeset/fileRemoved")]
    ChangesetFileRemoved(ChangesetFileRemovedAction),
    #[serde(rename = "changeset/filesReviewedChanged")]
    ChangesetFilesReviewedChanged(ChangesetFilesReviewedChangedAction),
    #[serde(rename = "changeset/contentChanged")]
    ChangesetContentChanged(Box<ChangesetContentChangedAction>),
    #[serde(rename = "changeset/operationsChanged")]
    ChangesetOperationsChanged(ChangesetOperationsChangedAction),
    #[serde(rename = "changeset/operationStatusChanged")]
    ChangesetOperationStatusChanged(ChangesetOperationStatusChangedAction),
    #[serde(rename = "changeset/cleared")]
    ChangesetCleared(ChangesetClearedAction),
    #[serde(rename = "annotations/set")]
    AnnotationsSet(AnnotationsSetAction),
    #[serde(rename = "annotations/updated")]
    AnnotationsUpdated(AnnotationsUpdatedAction),
    #[serde(rename = "annotations/removed")]
    AnnotationsRemoved(AnnotationsRemovedAction),
    #[serde(rename = "annotations/entrySet")]
    AnnotationsEntrySet(AnnotationsEntrySetAction),
    #[serde(rename = "annotations/entryRemoved")]
    AnnotationsEntryRemoved(AnnotationsEntryRemovedAction),
    #[serde(rename = "root/terminalsChanged")]
    RootTerminalsChanged(RootTerminalsChangedAction),
    #[serde(rename = "terminal/data")]
    TerminalData(TerminalDataAction),
    #[serde(rename = "terminal/input")]
    TerminalInput(TerminalInputAction),
    #[serde(rename = "terminal/resized")]
    TerminalResized(TerminalResizedAction),
    #[serde(rename = "terminal/claimed")]
    TerminalClaimed(TerminalClaimedAction),
    #[serde(rename = "terminal/titleChanged")]
    TerminalTitleChanged(TerminalTitleChangedAction),
    #[serde(rename = "terminal/cwdChanged")]
    TerminalCwdChanged(TerminalCwdChangedAction),
    #[serde(rename = "terminal/exited")]
    TerminalExited(TerminalExitedAction),
    #[serde(rename = "terminal/cleared")]
    TerminalCleared(TerminalClearedAction),
    #[serde(rename = "terminal/commandDetectionAvailable")]
    TerminalCommandDetectionAvailable(TerminalCommandDetectionAvailableAction),
    #[serde(rename = "terminal/commandExecuted")]
    TerminalCommandExecuted(TerminalCommandExecutedAction),
    #[serde(rename = "terminal/commandFinished")]
    TerminalCommandFinished(TerminalCommandFinishedAction),
    #[serde(rename = "resourceWatch/changed")]
    ResourceWatchChanged(ResourceWatchChangedAction),
    /// Unknown or future variant — preserved as raw JSON for round-trip fidelity.
    /// Reducers treat this as a no-op.
    #[serde(untagged)]
    Unknown(serde_json::Value),
}