relaycast 5.0.2

Rust SDK for RelayCast - multi-agent coordination platform
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
//! Type definitions for the RelayCast SDK.

use serde::{Deserialize, Serialize};

// === API Response Envelope ===

#[derive(Debug, Deserialize)]
pub struct ApiResponse<T> {
    pub ok: bool,
    pub data: Option<T>,
    pub error: Option<ApiErrorInfo>,
    pub cursor: Option<Cursor>,
}

#[derive(Debug, Deserialize)]
pub struct ApiErrorInfo {
    pub code: String,
    pub message: String,
}

#[derive(Debug, Deserialize)]
pub struct Cursor {
    pub next: Option<String>,
    pub has_more: bool,
}

// === Workspace ===

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Workspace {
    pub id: String,
    pub name: String,
    pub api_key_hash: String,
    pub system_prompt: Option<String>,
    pub plan: String,
    pub created_at: String,
    pub metadata: serde_json::Map<String, serde_json::Value>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateWorkspaceResponse {
    pub workspace_id: String,
    pub api_key: String,
    pub created_at: String,
}

#[derive(Debug, Clone, Serialize, Default)]
pub struct UpdateWorkspaceRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub system_prompt: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SystemPrompt {
    pub prompt: String,
    pub is_default: bool,
}

#[derive(Debug, Clone, Serialize, Default)]
pub struct SetSystemPromptRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub prompt: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reset: Option<bool>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkspaceStats {
    pub agents: AgentStats,
    pub messages: MessageStats,
    pub channels: ChannelStats,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentStats {
    pub total: i64,
    pub online: i64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MessageStats {
    pub total: i64,
    pub today: i64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChannelStats {
    pub total: i64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ActivityItem {
    #[serde(rename = "type")]
    pub item_type: String,
    pub id: String,
    pub channel_id: Option<String>,
    pub channel_name: Option<String>,
    pub conversation_id: Option<String>,
    pub agent_name: String,
    pub text: String,
    pub created_at: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkspaceDmLastMessage {
    pub text: String,
    pub agent_name: String,
    pub created_at: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkspaceDmConversation {
    pub id: String,
    #[serde(rename = "type")]
    pub dm_type: String,
    pub participants: Vec<String>,
    pub last_message: Option<WorkspaceDmLastMessage>,
    pub message_count: i64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkspaceDmMessage {
    pub id: String,
    pub agent_id: String,
    pub agent_name: String,
    pub text: String,
    pub created_at: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TokenRotateResponse {
    pub name: String,
    pub token: String,
}

// === Observer tokens ===

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum ObserverScope {
    #[serde(rename = "stream:read")]
    StreamRead,
    #[serde(rename = "messages:read")]
    MessagesRead,
    #[serde(rename = "threads:read")]
    ThreadsRead,
    #[serde(rename = "dms:read")]
    DmsRead,
    #[serde(rename = "channels:read")]
    ChannelsRead,
    #[serde(rename = "search:read")]
    SearchRead,
    #[serde(rename = "agents:read")]
    AgentsRead,
    #[serde(rename = "nodes:read")]
    NodesRead,
    #[serde(rename = "deliveries:read")]
    DeliveriesRead,
    #[serde(rename = "activity:read")]
    ActivityRead,
    #[serde(rename = "files:read")]
    FilesRead,
    #[serde(rename = "reactions:read")]
    ReactionsRead,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ObserverTokenFilters {
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub channel_ids: Vec<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub channel_names: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub include_dms: Option<bool>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub dm_conversation_ids: Vec<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub agent_ids: Vec<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub event_types: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub created_after: Option<String>,
}

#[derive(Debug, Clone, Serialize)]
pub struct CreateObserverTokenRequest {
    pub name: String,
    pub scopes: Vec<ObserverScope>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub filters: Option<ObserverTokenFilters>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expires_at: Option<String>,
}

#[derive(Debug, Clone, Serialize, Default)]
pub struct UpdateObserverTokenRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub scopes: Option<Vec<ObserverScope>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub filters: Option<ObserverTokenFilters>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expires_at: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ObserverToken {
    pub id: String,
    pub name: String,
    pub description: Option<String>,
    pub scopes: Vec<ObserverScope>,
    #[serde(default)]
    pub filters: ObserverTokenFilters,
    pub status: String,
    pub expires_at: Option<String>,
    pub created_at: String,
    pub updated_at: Option<String>,
    pub revoked_at: Option<String>,
    pub last_used_at: Option<String>,
    pub token: Option<String>,
}

// === Agents ===

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Agent {
    pub id: String,
    #[serde(default)]
    pub workspace_id: Option<String>,
    pub name: String,
    #[serde(rename = "type")]
    pub agent_type: String,
    pub status: String,
    pub persona: Option<String>,
    #[serde(default)]
    pub metadata: serde_json::Map<String, serde_json::Value>,
    #[serde(default)]
    pub created_at: Option<String>,
    #[serde(default)]
    pub last_seen: Option<String>,
    #[serde(default)]
    pub channels: Vec<AgentChannelMembership>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentChannelMembership {
    pub id: String,
    pub name: String,
    pub role: String,
    pub joined_at: String,
}

#[derive(Debug, Clone, Serialize)]
pub struct CreateAgentRequest {
    pub name: String,
    #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
    pub agent_type: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub persona: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<serde_json::Map<String, serde_json::Value>>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateAgentResponse {
    pub id: String,
    /// Workspace the agent registered into. `None` against engines that predate
    /// this field — callers that joined by workspace key rely on it to avoid an
    /// "unknown workspace" fallback.
    #[serde(default)]
    pub workspace_id: Option<String>,
    pub name: String,
    pub token: String,
    pub status: String,
    pub created_at: String,
}

#[derive(Debug, Clone, Serialize, Default)]
pub struct UpdateAgentRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub persona: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<serde_json::Map<String, serde_json::Value>>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentPresenceInfo {
    pub agent_id: String,
    pub agent_name: String,
    pub status: String,
}

#[derive(Debug, Clone, Serialize)]
pub struct SpawnAgentRequest {
    pub name: String,
    pub cli: String,
    pub task: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub channel: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub persona: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<serde_json::Value>,
}

pub type SpawnAgentResponse = InvokeActionResult;

#[derive(Debug, Clone, Serialize)]
pub struct ReleaseAgentRequest {
    pub name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub delete_agent: Option<bool>,
}

pub type ReleaseAgentResponse = InvokeActionResult;

#[derive(Debug, Clone, Default)]
pub struct AgentListQuery {
    pub status: Option<String>,
}

// === Channels ===

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Channel {
    pub id: String,
    pub workspace_id: Option<String>,
    pub name: String,
    pub channel_type: Option<i64>,
    pub topic: Option<String>,
    #[serde(default)]
    pub metadata: serde_json::Map<String, serde_json::Value>,
    pub created_by: Option<String>,
    pub created_at: String,
    #[serde(default)]
    pub is_archived: bool,
    pub member_count: Option<i64>,
}

#[derive(Debug, Clone, Serialize)]
pub struct CreateChannelRequest {
    pub name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub topic: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<serde_json::Map<String, serde_json::Value>>,
}

#[derive(Debug, Clone, Serialize, Default)]
pub struct UpdateChannelRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub topic: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<serde_json::Map<String, serde_json::Value>>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChannelMemberInfo {
    pub agent_id: String,
    pub agent_name: String,
    pub role: String,
    pub joined_at: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChannelWithMembers {
    #[serde(flatten)]
    pub channel: Channel,
    pub members: Vec<ChannelMemberInfo>,
}

// === Messages ===

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileAttachment {
    pub file_id: String,
    pub filename: String,
    pub content_type: String,
    pub size_bytes: i64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MessageBlock {
    #[serde(rename = "type")]
    pub block_type: String,
    #[serde(flatten)]
    pub data: serde_json::Value,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReactionGroup {
    pub emoji: String,
    pub count: i64,
    pub agents: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum MessageInjectionMode {
    Wait,
    Steer,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MessageWithMeta {
    pub id: String,
    pub agent_name: String,
    pub agent_id: String,
    pub text: String,
    pub blocks: Option<Vec<MessageBlock>>,
    #[serde(default)]
    pub metadata: serde_json::Map<String, serde_json::Value>,
    #[serde(default)]
    pub attachments: Vec<FileAttachment>,
    pub created_at: String,
    #[serde(default)]
    pub reply_count: i64,
    #[serde(default)]
    pub reactions: Vec<ReactionGroup>,
    #[serde(default)]
    pub read_by_count: i64,
    #[serde(default)]
    pub injection_mode: Option<MessageInjectionMode>,
}

#[derive(Debug, Clone, Serialize)]
pub struct PostMessageRequest {
    pub text: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub blocks: Option<Vec<MessageBlock>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub attachments: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data: Option<serde_json::Map<String, serde_json::Value>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mode: Option<MessageInjectionMode>,
}

#[derive(Debug, Clone, Serialize)]
pub struct ThreadReplyRequest {
    pub text: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub blocks: Option<Vec<MessageBlock>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data: Option<serde_json::Map<String, serde_json::Value>>,
}

#[derive(Debug, Clone, Default)]
pub struct MessageListQuery {
    pub limit: Option<i32>,
    pub before: Option<String>,
    pub after: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ThreadResponse {
    pub parent: MessageWithMeta,
    pub replies: Vec<MessageWithMeta>,
}

// === DMs ===

#[derive(Debug, Clone, Serialize)]
pub struct SendDmRequest {
    pub to: String,
    pub text: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub attachments: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mode: Option<MessageInjectionMode>,
}

#[derive(Debug, Clone, Serialize)]
pub struct CreateGroupDmRequest {
    pub participants: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    pub text: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DmConversationSummary {
    pub id: String,
    #[serde(rename = "type")]
    pub dm_type: String,
    pub name: Option<String>,
    #[serde(default, deserialize_with = "deserialize_dm_participants")]
    pub participants: Vec<String>,
    #[serde(default, deserialize_with = "deserialize_dm_last_message")]
    pub last_message: Option<String>,
    pub unread_count: i64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DmSendResponse {
    pub conversation_id: String,
    pub message: DmEventPayload,
    pub created_at: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GroupDmParticipantRef {
    pub agent_id: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GroupDmConversationResponse {
    pub id: String,
    pub channel_id: String,
    pub dm_type: String,
    pub name: Option<String>,
    pub participants: Vec<GroupDmParticipantRef>,
    pub created_at: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GroupDmMessageResponse {
    pub conversation_id: String,
    pub message: DmEventPayload,
    pub created_at: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GroupDmParticipantResponse {
    pub conversation_id: String,
    pub agent: String,
    pub already_member: bool,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
enum DmParticipantValue {
    Name(String),
    Object {
        agent_name: Option<String>,
        agent_id: Option<String>,
    },
}

fn deserialize_dm_participants<'de, D>(
    deserializer: D,
) -> std::result::Result<Vec<String>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let raw = Vec::<DmParticipantValue>::deserialize(deserializer)?;
    Ok(raw
        .into_iter()
        .filter_map(|item| match item {
            DmParticipantValue::Name(name) if !name.is_empty() => Some(name),
            DmParticipantValue::Object {
                agent_name: Some(name),
                ..
            } if !name.is_empty() => Some(name),
            DmParticipantValue::Object {
                agent_id: Some(id), ..
            } if !id.is_empty() => Some(id),
            _ => None,
        })
        .collect())
}

#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
enum DmLastMessageValue {
    Text(String),
    Object {
        text: Option<String>,
        body: Option<String>,
    },
}

fn deserialize_dm_last_message<'de, D>(
    deserializer: D,
) -> std::result::Result<Option<String>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let raw = Option::<DmLastMessageValue>::deserialize(deserializer)?;
    Ok(match raw {
        Some(DmLastMessageValue::Text(text)) if !text.is_empty() => Some(text),
        Some(DmLastMessageValue::Object {
            text: Some(text), ..
        }) if !text.is_empty() => Some(text),
        Some(DmLastMessageValue::Object {
            body: Some(body), ..
        }) if !body.is_empty() => Some(body),
        _ => None,
    })
}

// === Search ===

#[derive(Debug, Clone, Default)]
pub struct SearchOptions {
    pub channel: Option<String>,
    pub from: Option<String>,
    pub limit: Option<i32>,
    pub before: Option<String>,
    pub after: Option<String>,
}

// === Inbox ===

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UnreadChannel {
    pub channel_name: String,
    pub unread_count: i64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InboxMention {
    pub id: String,
    pub channel_name: String,
    pub agent_name: String,
    pub text: String,
    pub created_at: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UnreadDm {
    pub conversation_id: String,
    pub from: String,
    pub unread_count: i64,
    pub last_message: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InboxResponse {
    pub unread_channels: Vec<UnreadChannel>,
    pub mentions: Vec<InboxMention>,
    pub unread_dms: Vec<UnreadDm>,
}

// === Read Receipts ===

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReaderInfo {
    pub agent_name: String,
    pub agent_id: String,
    pub read_at: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChannelReadStatus {
    pub agent_name: String,
    pub last_read_id: Option<String>,
    pub last_read_at: Option<String>,
}

// === Durable Delivery ===

/// Status of a per-recipient durable delivery record.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DeliveryStatus {
    /// Durable row accepted, not yet sent to the current location.
    Queued,
    /// Sent to the current location, awaiting cumulative ack.
    Delivered,
    /// Recipient location acknowledged through the seq cursor.
    Acked,
    /// Explicit failure report (terminal).
    Failed,
    /// TTL-expired / dead-lettered (terminal).
    DeadLettered,
    #[serde(other)]
    Unknown,
}

impl DeliveryStatus {
    /// Return the API query value for this status, or `None` for unknown.
    pub fn as_query_value(self) -> Option<&'static str> {
        match self {
            DeliveryStatus::Queued => Some("queued"),
            DeliveryStatus::Delivered => Some("delivered"),
            DeliveryStatus::Acked => Some("acked"),
            DeliveryStatus::Failed => Some("failed"),
            DeliveryStatus::DeadLettered => Some("dead_lettered"),
            DeliveryStatus::Unknown => None,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DeliveryMessage {
    pub id: String,
    pub channel_id: String,
    pub agent_id: Option<String>,
    pub agent_name: Option<String>,
    pub text: String,
    pub thread_id: Option<String>,
    pub created_at: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Delivery {
    pub id: String,
    pub message_id: String,
    pub channel_id: String,
    pub agent_id: String,
    pub status: DeliveryStatus,
    #[serde(default)]
    pub seq: Option<i64>,
    #[serde(default)]
    pub location_type: Option<String>,
    #[serde(default)]
    pub location_node_id: Option<String>,
    #[serde(default)]
    pub route_node_id: Option<String>,
    #[serde(default)]
    pub route_node_kind: Option<String>,
    #[serde(default)]
    pub route_node_role: Option<String>,
    #[serde(default)]
    pub delivery_adapter: Option<String>,
    #[serde(default)]
    pub dispatch_attempts: Option<i64>,
    #[serde(default)]
    pub next_attempt_at: Option<String>,
    #[serde(default)]
    pub last_dispatch_error: Option<String>,
    pub mode: String,
    pub reason: Option<String>,
    pub priority: String,
    pub retryable: Option<bool>,
    pub error: Option<String>,
    pub available_at: Option<String>,
    pub deadline: Option<String>,
    #[serde(default)]
    pub expires_at: Option<String>,
    #[serde(default)]
    pub delivered_at: Option<String>,
    #[serde(default)]
    pub acked_at: Option<String>,
    #[serde(default)]
    pub dead_lettered_at: Option<String>,
    pub created_at: String,
    pub updated_at: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DeliveryItem {
    #[serde(flatten)]
    pub delivery: Delivery,
    pub message: Option<DeliveryMessage>,
}

#[derive(Debug, Clone, Default)]
pub struct ListDeliveriesOptions {
    pub status: Option<DeliveryStatus>,
    pub limit: Option<i32>,
}

#[derive(Debug, Clone, Serialize, Default)]
pub struct FailDeliveryRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub retryable: Option<bool>,
}

#[derive(Debug, Clone, Serialize)]
pub struct DeferDeliveryRequest {
    pub available_at: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
}

// === Files ===

#[derive(Debug, Clone, Serialize)]
pub struct UploadRequest {
    pub filename: String,
    pub content_type: String,
    pub size_bytes: i64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UploadResponse {
    pub file_id: String,
    pub upload_url: String,
    pub expires_at: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileInfo {
    pub file_id: String,
    pub filename: String,
    pub content_type: String,
    pub size: i64,
    pub url: String,
    pub uploaded_by: String,
    pub created_at: String,
}

#[derive(Debug, Clone, Default)]
pub struct FileListOptions {
    pub uploaded_by: Option<String>,
    pub limit: Option<i32>,
}

// === Webhooks ===

#[derive(Debug, Clone, Serialize)]
pub struct CreateWebhookRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    pub channel: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateWebhookResponse {
    pub webhook_id: String,
    pub name: String,
    pub channel: String,
    pub url: String,
    pub token: String,
    pub is_active: bool,
    pub created_at: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Webhook {
    pub id: String,
    pub workspace_id: String,
    pub name: String,
    pub channel_id: String,
    pub channel_name: String,
    pub url: String,
    pub created_by: Option<String>,
    pub created_at: String,
    pub is_active: bool,
}

#[derive(Debug, Clone, Serialize, Default)]
pub struct WebhookTriggerRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub blocks: Option<Vec<serde_json::Value>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub author: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payload: Option<serde_json::Map<String, serde_json::Value>>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WebhookTriggerResponse {
    pub message_id: String,
    pub channel: String,
    pub text: String,
    #[serde(default)]
    pub source: Option<String>,
    #[serde(default)]
    pub author: Option<String>,
    pub created_at: String,
}

// === Subscriptions ===

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SubscriptionFilter {
    pub channel: Option<String>,
    pub mentions: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EventSubscription {
    pub id: String,
    #[serde(default)]
    pub workspace_id: String,
    pub events: Vec<String>,
    pub filter: Option<SubscriptionFilter>,
    pub url: String,
    #[serde(default)]
    pub headers: Option<std::collections::BTreeMap<String, String>>,
    #[serde(default)]
    pub secret: Option<String>,
    pub is_active: bool,
    pub created_at: String,
}

#[derive(Debug, Clone, Serialize)]
pub struct CreateSubscriptionRequest {
    pub events: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub filter: Option<SubscriptionFilter>,
    pub url: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub headers: Option<std::collections::BTreeMap<String, String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub secret: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateSubscriptionResponse {
    pub id: String,
    pub events: Vec<String>,
    pub filter: Option<SubscriptionFilter>,
    pub url: String,
    #[serde(default)]
    pub headers: Option<std::collections::BTreeMap<String, String>>,
    pub is_active: bool,
    pub created_at: String,
}

// === Commands ===

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CommandParameter {
    pub name: String,
    pub description: Option<String>,
    #[serde(rename = "type")]
    pub parameter_type: String,
    pub required: Option<bool>,
}

#[derive(Debug, Clone, Serialize)]
pub struct CreateCommandRequest {
    pub command: String,
    pub description: String,
    pub handler_agent: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parameters: Option<Vec<CommandParameter>>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateCommandResponse {
    pub id: String,
    pub command: String,
    pub description: String,
    pub handler_agent: String,
    pub parameters: Vec<CommandParameter>,
    pub created_at: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentCommand {
    pub id: String,
    pub workspace_id: String,
    pub command: String,
    pub description: String,
    pub handler_agent_id: String,
    pub handler_agent_name: String,
    pub parameters: Vec<CommandParameter>,
    pub created_at: String,
    pub is_active: bool,
}

#[derive(Debug, Clone, Serialize)]
pub struct InvokeCommandRequest {
    pub channel: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub args: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parameters: Option<serde_json::Map<String, serde_json::Value>>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CommandInvocation {
    pub id: String,
    pub command: String,
    pub channel: String,
    pub invoked_by: String,
    pub args: Option<String>,
    pub parameters: Option<serde_json::Map<String, serde_json::Value>>,
    pub response_message_id: Option<String>,
    pub created_at: String,
}

// === Actions (agent-to-agent RPC) ===

/// Status of an action invocation. `action.completed` always reports
/// [`ActionInvocationStatus::Completed`] and `action.failed` reports
/// [`ActionInvocationStatus::Failed`]; `Unknown` is a forward-compatible fallback.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ActionInvocationStatus {
    Pending,
    Dispatched,
    Invoked,
    Completed,
    Failed,
    #[serde(other)]
    Unknown,
}

#[derive(Debug, Clone, Serialize)]
pub struct RegisterActionRequest {
    pub name: String,
    pub description: String,
    pub handler_agent: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub input_schema: Option<serde_json::Map<String, serde_json::Value>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub output_schema: Option<serde_json::Map<String, serde_json::Value>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub available_to: Option<Vec<String>>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ActionDefinition {
    pub id: String,
    pub name: String,
    pub description: String,
    pub handler_agent: String,
    #[serde(default)]
    pub input_schema: serde_json::Map<String, serde_json::Value>,
    #[serde(default)]
    pub output_schema: serde_json::Map<String, serde_json::Value>,
    #[serde(default)]
    pub available_to: Option<Vec<String>>,
    pub is_active: bool,
    pub created_at: String,
}

#[derive(Debug, Clone, Serialize)]
pub struct InvokeActionRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub input: Option<serde_json::Map<String, serde_json::Value>>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InvokeActionResult {
    pub invocation_id: String,
    pub action_name: String,
    pub handler_agent_id: Option<String>,
    #[serde(default)]
    pub handler_node_id: Option<String>,
    #[serde(default)]
    pub dispatched_node_id: Option<String>,
    #[serde(default)]
    pub input: serde_json::Map<String, serde_json::Value>,
    pub status: ActionInvocationStatus,
    pub created_at: String,
}

#[derive(Debug, Clone, Serialize)]
pub struct CompleteInvocationRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub output: Option<serde_json::Map<String, serde_json::Value>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub duration_ms: Option<u64>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ActionInvocation {
    pub invocation_id: String,
    pub action_name: String,
    #[serde(default)]
    pub caller_id: Option<String>,
    #[serde(default)]
    pub caller_name: Option<String>,
    #[serde(default)]
    pub input: Option<serde_json::Map<String, serde_json::Value>>,
    #[serde(default)]
    pub output: Option<serde_json::Map<String, serde_json::Value>>,
    pub status: ActionInvocationStatus,
    #[serde(default)]
    pub error: Option<String>,
    #[serde(default)]
    pub duration_ms: Option<u64>,
    #[serde(default)]
    pub created_at: Option<String>,
    #[serde(default)]
    pub completed_at: Option<String>,
}

// === Agent session events ===

#[derive(Debug, Clone, Serialize)]
pub struct EmitSessionEventRequest {
    #[serde(rename = "type")]
    pub event_type: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payload: Option<serde_json::Map<String, serde_json::Value>>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionEvent {
    pub id: String,
    pub agent_id: String,
    #[serde(rename = "type")]
    pub event_type: String,
    #[serde(default)]
    pub payload: serde_json::Map<String, serde_json::Value>,
    #[serde(default)]
    pub sequence: Option<i64>,
    pub created_at: String,
}

/// Query filters for [`crate::RelayCast::list_agent_events`].
#[derive(Debug, Clone, Default)]
pub struct ListSessionEventsQuery {
    pub event_type: Option<String>,
    pub limit: Option<i32>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DirectNodeToken {
    pub node_id: String,
    pub node_name: String,
    pub token: String,
}

// === WebSocket Events ===

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MessageEventPayload {
    pub id: String,
    #[serde(default)]
    pub agent_id: Option<String>,
    pub agent_name: String,
    pub text: String,
    pub attachments: Vec<FileAttachment>,
    #[serde(default)]
    pub injection_mode: Option<MessageInjectionMode>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MessageUpdatedPayload {
    pub id: String,
    #[serde(default)]
    pub agent_id: Option<String>,
    pub agent_name: String,
    pub text: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ThreadReplyPayload {
    pub id: String,
    #[serde(default)]
    pub agent_id: Option<String>,
    pub agent_name: String,
    pub text: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DmEventPayload {
    pub id: String,
    pub agent_id: String,
    pub agent_name: String,
    pub text: String,
    #[serde(default)]
    pub injection_mode: Option<MessageInjectionMode>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentEventPayload {
    pub name: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChannelEventPayload {
    pub name: String,
    pub topic: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChannelArchivedPayload {
    pub name: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileEventPayload {
    pub file_id: String,
    pub filename: String,
    pub uploaded_by: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WebhookMessagePayload {
    pub id: String,
    pub text: String,
    pub source: Option<String>,
    #[serde(default)]
    pub author: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum WsEvent {
    #[serde(rename = "message.created")]
    MessageCreated(MessageCreatedEvent),
    #[serde(rename = "message.updated")]
    MessageUpdated(MessageUpdatedEvent),
    #[serde(rename = "thread.reply")]
    ThreadReply(ThreadReplyEvent),
    #[serde(rename = "message.reacted")]
    MessageReacted(MessageReactedEvent),
    #[serde(rename = "dm.received")]
    DmReceived(DmReceivedEvent),
    #[serde(rename = "group_dm.received")]
    GroupDmReceived(GroupDmReceivedEvent),
    #[serde(rename = "agent.status.active")]
    AgentStatusActive(AgentStatusEvent),
    #[serde(rename = "agent.status.idle")]
    AgentStatusIdle(AgentStatusEvent),
    #[serde(rename = "agent.status.blocked")]
    AgentStatusBlocked(AgentStatusEvent),
    #[serde(rename = "agent.status.waiting")]
    AgentStatusWaiting(AgentStatusEvent),
    #[serde(rename = "agent.status.offline")]
    AgentStatusOffline(AgentStatusEvent),
    #[serde(rename = "agent.status.changed")]
    AgentStatusChanged(AgentStatusEvent),
    #[serde(rename = "channel.created")]
    ChannelCreated(ChannelCreatedEvent),
    #[serde(rename = "channel.updated")]
    ChannelUpdated(ChannelUpdatedEvent),
    #[serde(rename = "channel.archived")]
    ChannelArchived(ChannelArchivedEvent),
    #[serde(rename = "member.joined")]
    MemberJoined(MemberJoinedEvent),
    #[serde(rename = "member.left")]
    MemberLeft(MemberLeftEvent),
    #[serde(rename = "message.read")]
    MessageRead(MessageReadEvent),
    #[serde(rename = "file.uploaded")]
    FileUploaded(FileUploadedEvent),
    #[serde(rename = "webhook.received")]
    WebhookReceived(WebhookReceivedEvent),
    #[serde(rename = "command.invoked")]
    CommandInvoked(CommandInvokedEvent),
    #[serde(rename = "action.invoked")]
    ActionInvoked(ActionInvokedEvent),
    #[serde(rename = "action.completed")]
    ActionCompleted(ActionCompletedEvent),
    #[serde(rename = "action.failed")]
    ActionFailed(ActionFailedEvent),
    #[serde(rename = "action.denied")]
    ActionDenied(ActionDeniedEvent),
    #[serde(rename = "delivery.accepted")]
    DeliveryAccepted(DeliveryAcceptedEvent),
    #[serde(rename = "delivery.delivered")]
    DeliveryDelivered(DeliveryDeliveredEvent),
    #[serde(rename = "delivery.deferred")]
    DeliveryDeferred(DeliveryDeferredEvent),
    #[serde(rename = "delivery.failed")]
    DeliveryFailed(DeliveryFailedEvent),
    #[serde(rename = "pong")]
    Pong,
    #[serde(other)]
    Unknown,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MessageCreatedEvent {
    pub channel: String,
    pub message: MessageEventPayload,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MessageUpdatedEvent {
    pub channel: String,
    pub message: MessageUpdatedPayload,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ThreadReplyEvent {
    #[serde(default)]
    pub channel: Option<String>,
    pub parent_id: String,
    pub message: ThreadReplyPayload,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MessageReactedEvent {
    pub message_id: String,
    pub emoji: String,
    pub agent_name: String,
    #[serde(default)]
    pub action: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DmReceivedEvent {
    pub conversation_id: String,
    pub message: DmEventPayload,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GroupDmReceivedEvent {
    pub conversation_id: String,
    pub message: DmEventPayload,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentStatusEvent {
    pub agent: AgentEventPayload,
    pub status: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChannelCreatedEvent {
    pub channel: ChannelEventPayload,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChannelUpdatedEvent {
    pub channel: ChannelEventPayload,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChannelArchivedEvent {
    pub channel: ChannelArchivedPayload,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MemberJoinedEvent {
    pub channel: String,
    pub agent_name: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MemberLeftEvent {
    pub channel: String,
    pub agent_name: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MessageReadEvent {
    pub message_id: String,
    pub agent_name: String,
    pub read_at: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileUploadedEvent {
    pub file: FileEventPayload,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WebhookReceivedEvent {
    pub webhook_id: String,
    pub channel: String,
    pub message: WebhookMessagePayload,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CommandInvokedEvent {
    pub command: String,
    pub channel: String,
    pub invoked_by: String,
    pub handler_agent_id: String,
    pub args: Option<String>,
    pub parameters: Option<serde_json::Map<String, serde_json::Value>>,
}

/// `action.invoked` — delivered to the handler agent when an action is invoked.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ActionInvokedEvent {
    pub invocation_id: String,
    pub action_name: String,
    pub caller_name: String,
    pub handler_agent_id: String,
    #[serde(default)]
    pub handler_agent_name: Option<String>,
    #[serde(default)]
    pub input: Option<serde_json::Value>,
}

/// Literal `completed` status for [`ActionCompletedEvent`]; deserialization
/// rejects any other value so malformed `action.completed` payloads fail fast.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CompletedStatus {
    Completed,
}

/// Literal `failed` status for [`ActionFailedEvent`]; deserialization rejects
/// any other value so malformed `action.failed` payloads fail fast.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FailedStatus {
    Failed,
}

/// `action.completed` — delivered to the caller when an invocation succeeds.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ActionCompletedEvent {
    pub invocation_id: String,
    pub action_name: String,
    pub status: CompletedStatus,
    #[serde(default)]
    pub output: Option<serde_json::Map<String, serde_json::Value>>,
    #[serde(default)]
    pub error: Option<String>,
}

/// `action.failed` — delivered to the caller when an invocation fails.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ActionFailedEvent {
    pub invocation_id: String,
    pub action_name: String,
    pub status: FailedStatus,
    #[serde(default)]
    pub output: Option<serde_json::Map<String, serde_json::Value>>,
    #[serde(default)]
    pub error: Option<String>,
}

/// `action.denied` — delivered to the caller when authorization rejects an invocation.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ActionDeniedEvent {
    pub action_name: String,
    #[serde(default)]
    pub caller_name: Option<String>,
    pub error: String,
}

/// `delivery.accepted` — emitted when a delivery is queued for the recipient.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DeliveryAcceptedEvent {
    pub delivery_id: String,
    pub message_id: String,
    #[serde(default)]
    pub channel_id: Option<String>,
    #[serde(default)]
    pub reason: Option<String>,
}

/// `delivery.delivered` — emitted when a delivery is acknowledged.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DeliveryDeliveredEvent {
    pub delivery_id: String,
    pub message_id: String,
}

/// `delivery.deferred` — emitted when a delivery is deferred for retry.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DeliveryDeferredEvent {
    pub delivery_id: String,
    pub message_id: String,
    pub available_at: Option<String>,
    #[serde(default)]
    pub reason: Option<String>,
}

/// `delivery.failed` — emitted when a delivery handler reports failure.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DeliveryFailedEvent {
    #[serde(default)]
    pub delivery_id: Option<String>,
    pub message_id: String,
    #[serde(default)]
    pub error: Option<String>,
    #[serde(default)]
    pub retryable: Option<bool>,
}

// === Workspace bootstrap (by-name lookup) ===

/// Result of a `GET /v1/workspaces/by-name/{name}` lookup.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkspaceLookup {
    pub id: String,
    pub name: String,
    pub created_at: String,
}

// === A2A (agent-to-agent bridge) ===

/// A skill advertised on an A2A agent card.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct A2aAgentCardSkill {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    pub name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tags: Option<Vec<String>>,
}

/// An A2A agent card describing an external agent.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct A2aAgentCard {
    pub name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    pub url: String,
    pub version: String,
    #[serde(default)]
    pub skills: Vec<A2aAgentCardSkill>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub provider: Option<serde_json::Map<String, serde_json::Value>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub capabilities: Option<serde_json::Map<String, serde_json::Value>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub default_input_modes: Option<Vec<String>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub default_output_modes: Option<Vec<String>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub documentation_url: Option<String>,
}

/// Options for registering an A2A agent bridge.
#[derive(Debug, Clone, Default, Serialize)]
pub struct RegisterA2aOptions {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub agent_card_url: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub agent_card: Option<A2aAgentCard>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub auth_scheme: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub auth_credential: Option<String>,
}

/// Response from registering an A2A agent.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RegisterA2aResponse {
    pub relay_name: String,
    pub relay_token: String,
    pub webhook_url: String,
    pub certification: String,
}

/// A registered A2A agent record.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct A2aAgentRecord {
    pub id: String,
    pub workspace_id: String,
    pub relay_agent_id: String,
    pub relay_name: String,
    pub relay_status: String,
    #[serde(default)]
    pub relay_persona: Option<String>,
    #[serde(default)]
    pub relay_metadata: Option<serde_json::Map<String, serde_json::Value>>,
    pub agent_card: A2aAgentCard,
    pub external_url: String,
    #[serde(default)]
    pub auth_scheme: Option<String>,
    #[serde(default)]
    pub auth_credential: Option<String>,
    pub status: String,
    pub messages_sent: i64,
    pub messages_recv: i64,
    #[serde(default)]
    pub last_health: Option<String>,
    pub health_failures: i64,
    pub created_at: String,
    pub updated_at: String,
}

/// Response from removing an A2A agent.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RemoveA2aAgentResponse {
    pub name: String,
    pub removed: bool,
}

// === Directory ===

/// A skill input when publishing/importing directory agents.
#[derive(Debug, Clone, Serialize)]
pub struct DirectorySkillInput {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    pub name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tags: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<serde_json::Map<String, serde_json::Value>>,
}

/// A skill stored on a directory agent.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DirectorySkill {
    pub id: String,
    #[serde(default)]
    pub skill_id: Option<String>,
    pub name: String,
    #[serde(default)]
    pub description: Option<String>,
    #[serde(default)]
    pub tags: Vec<String>,
    #[serde(default)]
    pub metadata: serde_json::Map<String, serde_json::Value>,
}

/// A directory agent entry.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DirectoryAgent {
    pub id: String,
    #[serde(default)]
    pub source_agent_id: Option<String>,
    pub slug: String,
    pub name: String,
    #[serde(default)]
    pub description: Option<String>,
    #[serde(default)]
    pub provider: Option<String>,
    #[serde(default)]
    pub endpoint_url: Option<String>,
    #[serde(default)]
    pub documentation_url: Option<String>,
    #[serde(default)]
    pub version: Option<String>,
    #[serde(default)]
    pub tags: Vec<String>,
    #[serde(default)]
    pub capabilities: serde_json::Map<String, serde_json::Value>,
    #[serde(default)]
    pub metadata: serde_json::Map<String, serde_json::Value>,
    pub status: String,
    pub rating_avg: f64,
    pub rating_count: i64,
    #[serde(default)]
    pub skills: Vec<DirectorySkill>,
    pub created_at: String,
    pub updated_at: String,
}

/// A directory search result (a directory agent plus a relevance score).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DirectorySearchResult {
    #[serde(flatten)]
    pub agent: DirectoryAgent,
    pub relevance_score: f64,
}

/// Query parameters for searching the directory.
#[derive(Debug, Clone, Default)]
pub struct SearchDirectoryQuery {
    pub q: Option<String>,
    pub tags: Option<Vec<String>>,
    pub status: Option<String>,
    pub limit: Option<i32>,
}

/// Request body for publishing an agent to the directory.
#[derive(Debug, Clone, Serialize)]
pub struct PublishToDirectoryRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source_agent_name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub slug: Option<String>,
    pub name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub provider: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub endpoint_url: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub documentation_url: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub version: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tags: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub capabilities: Option<serde_json::Map<String, serde_json::Value>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<serde_json::Map<String, serde_json::Value>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub skills: Option<Vec<DirectorySkillInput>>,
}

/// Request body for updating a directory agent (all fields optional).
#[derive(Debug, Clone, Default, Serialize)]
pub struct UpdateDirectoryAgentRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source_agent_name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub slug: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub provider: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub endpoint_url: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub documentation_url: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub version: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tags: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub capabilities: Option<serde_json::Map<String, serde_json::Value>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<serde_json::Map<String, serde_json::Value>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub skills: Option<Vec<DirectorySkillInput>>,
}

/// Query parameters for listing directory agents.
#[derive(Debug, Clone, Default)]
pub struct ListDirectoryQuery {
    pub status: Option<String>,
    pub limit: Option<i32>,
}

/// A rating left on a directory agent.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DirectoryRating {
    pub id: String,
    pub score: f64,
    #[serde(default)]
    pub review: Option<String>,
    pub rater_agent_id: String,
    pub rater_agent_name: String,
    pub created_at: String,
    #[serde(default)]
    pub updated_at: Option<String>,
}

/// Request body for rating a directory agent.
#[derive(Debug, Clone, Serialize)]
pub struct RateDirectoryAgentRequest {
    pub score: f64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub review: Option<String>,
}

/// Request body for importing skills onto a directory agent.
#[derive(Debug, Clone, Serialize)]
pub struct ImportSkillsRequest {
    pub agent_name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<serde_json::Map<String, serde_json::Value>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub skills: Option<Vec<DirectorySkillInput>>,
}

// === Routing ===

/// Result of routing a message to a candidate agent.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RouteResult {
    pub agent_name: String,
    pub score: f64,
    pub fallback: bool,
}

/// Routing scorer weights.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RoutingWeights {
    pub skill_match: f64,
    pub message_match: f64,
    pub tag_match: f64,
    pub rating: f64,
    pub availability: f64,
}

/// Partial routing weights for updates (all fields optional).
#[derive(Debug, Clone, Default, Serialize)]
pub struct UpdateRoutingWeights {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub skill_match: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub message_match: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tag_match: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub rating: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub availability: Option<f64>,
}

/// Workspace routing configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RoutingConfig {
    pub weights: RoutingWeights,
    pub circuit_breaker_threshold: f64,
    pub circuit_breaker_cooldown_seconds: f64,
    #[serde(default)]
    pub updated_at: Option<String>,
}

/// Request body for updating routing configuration.
#[derive(Debug, Clone, Default, Serialize)]
pub struct UpdateRoutingConfigRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub weights: Option<UpdateRoutingWeights>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub circuit_breaker_threshold: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub circuit_breaker_cooldown_seconds: Option<f64>,
}

/// Request body for reporting route feedback.
#[derive(Debug, Clone, Serialize)]
pub struct RouteFeedbackRequest {
    pub agent_name: String,
    pub success: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
}

/// Result of reporting route feedback.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RouteFeedbackResult {
    pub ok: bool,
}

// === Skills ===

/// Query parameters for searching skills.
#[derive(Debug, Clone, Default)]
pub struct SkillSearchQuery {
    pub q: Option<String>,
    pub limit: Option<i32>,
}

/// A skill search result.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SkillSearchResult {
    pub agent_name: String,
    pub skill_name: String,
    #[serde(default)]
    pub description: Option<String>,
    #[serde(default)]
    pub tags: Vec<String>,
    pub relevance_score: f64,
}

// === Fleet nodes ===

/// A capability advertised by a fleet node on the roster.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NodeCapability {
    pub name: String,
    #[serde(default)]
    pub kind: Option<String>,
    #[serde(default)]
    pub metadata: Option<serde_json::Map<String, serde_json::Value>>,
}

/// A fleet node roster entry.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NodeRosterEntry {
    pub id: String,
    pub name: String,
    #[serde(default)]
    pub kind: Option<String>,
    #[serde(default)]
    pub role: Option<String>,
    #[serde(default)]
    pub delivery_adapter: Option<String>,
    #[serde(default)]
    pub delivery: Option<NodeDeliveryConfig>,
    #[serde(default)]
    pub capabilities: Vec<NodeCapability>,
    #[serde(default)]
    pub tags: Vec<String>,
    pub version: String,
    pub status: String,
    pub live: bool,
    pub handlers_live: bool,
    pub load: f64,
    pub active_agents: i64,
    pub max_agents: i64,
    #[serde(default)]
    pub last_heartbeat_at: Option<String>,
    pub created_at: String,
}

/// Query parameters for listing fleet nodes.
#[derive(Debug, Clone, Default)]
pub struct NodeListQuery {
    pub capability: Option<String>,
    pub name: Option<String>,
}

/// Delivery config for a node. HTTP push is typed; raw JSON keeps future adapters usable.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum NodeDeliveryConfig {
    HttpPush(Box<HttpPushNodeDelivery>),
    Raw(serde_json::Value),
}

impl From<HttpPushNodeDelivery> for NodeDeliveryConfig {
    fn from(delivery: HttpPushNodeDelivery) -> Self {
        Self::HttpPush(Box::new(delivery))
    }
}

/// HTTP push delivery settings for a node.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HttpPushNodeDelivery {
    pub url: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ack_mode: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub auth: Option<NodeDeliveryAuth>,
}

/// HTTP push authentication settings for a node delivery contract.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NodeDeliveryAuth {
    #[serde(rename = "type")]
    pub auth_type: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub token: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub headers: Option<std::collections::BTreeMap<String, String>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub secret: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub signature_header: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub timestamp_header: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub signed_payload: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub encoding: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub prefix: Option<String>,
}

/// Request to enroll or rotate a node token.
#[derive(Debug, Clone, Serialize)]
pub struct CreateNodeRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub node_id: Option<String>,
    pub name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub kind: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub role: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub delivery_adapter: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub delivery: Option<NodeDeliveryConfig>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub capabilities: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_agents: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tags: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub version: Option<String>,
}

/// Response from node enrollment or token rotation.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateNodeResponse {
    #[serde(flatten)]
    pub node: NodeRosterEntry,
    pub token: String,
}

/// Agent binding to a node delivery host.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NodeAgentBinding {
    pub id: String,
    pub agent_id: String,
    pub agent_name: String,
    pub node_id: String,
    pub node_name: String,
    pub node_kind: String,
    pub node_role: String,
    pub status: String,
    pub session_ref: Option<String>,
    pub priority: i64,
    pub created_at: String,
    pub updated_at: Option<String>,
}

/// Request to bind an agent to a node delivery host.
#[derive(Debug, Clone, Serialize)]
pub struct BindAgentToNodeRequest {
    pub agent_name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub session_ref: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub priority: Option<i64>,
}

// === Triggers ===

/// A trigger that fires an action when a message matches.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Trigger {
    pub id: String,
    #[serde(default)]
    pub channel: Option<String>,
    #[serde(default)]
    pub pattern: Option<String>,
    #[serde(default)]
    pub mention: Option<bool>,
    pub action_name: String,
    pub enabled: bool,
    #[serde(default)]
    pub last_triggered_at: Option<String>,
    pub created_at: String,
    #[serde(default)]
    pub updated_at: Option<String>,
}

/// Request body for creating a trigger.
#[derive(Debug, Clone, Serialize)]
pub struct CreateTriggerRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub channel: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pattern: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mention: Option<bool>,
    pub action_name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub enabled: Option<bool>,
}

/// Request body for updating a trigger (all fields optional).
#[derive(Debug, Clone, Default, Serialize)]
pub struct UpdateTriggerRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub channel: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pattern: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mention: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub action_name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub enabled: Option<bool>,
}

// === Certification ===

/// A single certification test result.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CertificationTestResult {
    #[serde(default)]
    pub name: Option<String>,
    #[serde(default)]
    pub passed: Option<bool>,
    #[serde(flatten)]
    pub extra: serde_json::Map<String, serde_json::Value>,
}

/// A certification run for an external agent.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CertificationRun {
    pub id: String,
    pub agent_url: String,
    pub level: i64,
    #[serde(default)]
    pub source: Option<String>,
    #[serde(default)]
    pub status: Option<String>,
    pub passed: bool,
    pub passed_tests: i64,
    pub total_tests: i64,
    #[serde(default)]
    pub monitor_enabled: Option<bool>,
    #[serde(default)]
    pub monitor_interval_minutes: Option<i64>,
    #[serde(default)]
    pub last_run_at: Option<String>,
    #[serde(default)]
    pub started_at: Option<String>,
    #[serde(default)]
    pub completed_at: Option<String>,
    #[serde(default)]
    pub created_at: Option<String>,
    #[serde(default)]
    pub updated_at: Option<String>,
    #[serde(default)]
    pub tests: Vec<CertificationTestResult>,
}

/// Request body for submitting a certification run.
#[derive(Debug, Clone, Serialize)]
pub struct SubmitCertificationRequest {
    pub agent_url: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub level: Option<i32>,
}

/// Request body for enabling certification monitoring.
#[derive(Debug, Clone, Serialize)]
pub struct MonitorCertificationRequest {
    pub agent_url: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub level: Option<i32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub interval_minutes: Option<i32>,
}

// === Console / observability ===

/// Query parameters for the console message log.
#[derive(Debug, Clone, Default)]
pub struct ConsoleMessagesQuery {
    pub limit: Option<i32>,
    pub before: Option<String>,
    pub agent_id: Option<String>,
    pub channel_id: Option<String>,
    pub conversation_id: Option<String>,
    pub delivery_kind: Option<String>,
}

/// A console message log entry.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConsoleMessageLog {
    pub id: String,
    #[serde(default)]
    pub message_id: Option<String>,
    #[serde(default)]
    pub channel_id: Option<String>,
    #[serde(default)]
    pub channel_name: Option<String>,
    #[serde(default)]
    pub agent_id: Option<String>,
    #[serde(default)]
    pub agent_name: Option<String>,
    #[serde(default)]
    pub conversation_id: Option<String>,
    pub delivery_kind: String,
    #[serde(default)]
    pub text: Option<String>,
    #[serde(default)]
    pub content_type: Option<String>,
    #[serde(default)]
    pub metadata: serde_json::Map<String, serde_json::Value>,
    pub attachment_count: i64,
    pub mention_count: i64,
    #[serde(default)]
    pub latency_ms: Option<i64>,
    pub created_at: String,
}

/// Query parameters for windowed console stats.
#[derive(Debug, Clone, Default)]
pub struct ConsoleWindowQuery {
    pub days: Option<i32>,
}

/// Query parameters for console agent stats.
#[derive(Debug, Clone, Default)]
pub struct ConsoleAgentStatsQuery {
    pub days: Option<i32>,
    pub limit: Option<i32>,
}

/// Console overview statistics.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConsoleOverview {
    pub window_days: i64,
    pub since: String,
    pub total_messages: i64,
    pub channel_messages: i64,
    pub dm_messages: i64,
    pub unique_agents: i64,
    pub avg_latency_ms: f64,
    pub max_latency_ms: f64,
    pub attachment_count: i64,
    pub mention_count: i64,
}

/// Per-agent console statistics.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConsoleAgentStat {
    pub agent_id: String,
    pub agent_name: String,
    pub message_count: i64,
    pub channel_count: i64,
    pub dm_count: i64,
    pub avg_latency_ms: f64,
    #[serde(default)]
    pub last_message_at: Option<String>,
}

/// Per-agent cost statistics.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConsoleCostAgent {
    pub agent_id: String,
    pub agent_name: String,
    pub message_count: i64,
    pub total_cost_usd: f64,
    pub prompt_tokens: i64,
    pub completion_tokens: i64,
    pub total_tokens: i64,
}

/// Aggregate cost totals across the window.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConsoleCostTotals {
    pub total_cost_usd: f64,
    pub prompt_tokens: i64,
    pub completion_tokens: i64,
    pub total_tokens: i64,
}

/// Console cost statistics for the window.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConsoleCostStats {
    pub window_days: i64,
    pub totals: ConsoleCostTotals,
    #[serde(default)]
    pub agents: Vec<ConsoleCostAgent>,
}