relaycast 2.1.0

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
//! 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 WorkspaceStreamConfig {
    pub enabled: bool,
    pub default_enabled: bool,
    #[serde(rename = "override")]
    pub override_value: 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_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,
}

// === Agents ===

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Agent {
    pub id: 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,
    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 metadata: Option<serde_json::Value>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SpawnAgentResponse {
    pub id: String,
    pub name: String,
    pub token: String,
    pub cli: String,
    pub task: String,
    pub channel: Option<String>,
    pub status: String,
    pub created_at: String,
    pub already_existed: bool,
}

#[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>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReleaseAgentResponse {
    pub name: String,
    pub released: bool,
    pub deleted: bool,
    pub reason: Option<String>,
}

#[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,
    #[serde(alias = "contentType")]
    pub content_type: String,
    #[serde(alias = "size")]
    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())
}

fn deserialize_string_or_default<'de, D>(deserializer: D) -> std::result::Result<String, D::Error>
where
    D: serde::Deserializer<'de>,
{
    Ok(Option::<String>::deserialize(deserializer)?.unwrap_or_default())
}

#[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 {
    Accepted,
    Delivered,
    Deferred,
    Failed,
    #[serde(other)]
    Unknown,
}

impl DeliveryStatus {
    /// Return the accepted API query value for this status.
    pub fn as_query_value(self) -> Option<&'static str> {
        match self {
            DeliveryStatus::Accepted => Some("accepted"),
            DeliveryStatus::Delivered => Some("delivered"),
            DeliveryStatus::Deferred => Some("deferred"),
            DeliveryStatus::Failed => Some("failed"),
            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,
    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>,
    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 {
    pub name: 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 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 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 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,
    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,
    pub workspace_id: String,
    pub events: Vec<String>,
    pub filter: Option<SubscriptionFilter>,
    pub url: String,
    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 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,
    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 {
    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: 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>,
}

// === 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>,
}

#[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 = "reaction.added")]
    ReactionAdded(ReactionAddedEvent),
    #[serde(rename = "reaction.removed")]
    ReactionRemoved(ReactionRemovedEvent),
    #[serde(rename = "dm.received")]
    DmReceived(DmReceivedEvent),
    #[serde(rename = "group_dm.received")]
    GroupDmReceived(GroupDmReceivedEvent),
    #[serde(rename = "agent.online")]
    AgentOnline(AgentOnlineEvent),
    #[serde(rename = "agent.offline")]
    AgentOffline(AgentOfflineEvent),
    #[serde(rename = "agent.spawn_requested")]
    AgentSpawnRequested(AgentSpawnRequestedEvent),
    #[serde(rename = "agent.release_requested")]
    AgentReleaseRequested(AgentReleaseRequestedEvent),
    #[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 = "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 ReactionAddedEvent {
    pub message_id: String,
    pub emoji: String,
    pub agent_name: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReactionRemovedEvent {
    pub message_id: String,
    pub emoji: String,
    pub agent_name: 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 AgentOnlineEvent {
    pub agent: AgentEventPayload,
}

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

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentSpawnRequestedEvent {
    pub agent: AgentSpawnRequestedPayload,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentSpawnRequestedPayload {
    pub name: String,
    pub cli: String,
    #[serde(default, deserialize_with = "deserialize_string_or_default")]
    pub task: String,
    #[serde(default)]
    pub channel: Option<String>,
    #[serde(default)]
    pub already_existed: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentReleaseRequestedEvent {
    pub agent: AgentEventPayload,
    pub reason: Option<String>,
    pub deleted: bool,
}

#[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,
}

/// 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>,
}

/// `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 {
    pub delivery_id: String,
    pub message_id: String,
    #[serde(default)]
    pub error: Option<String>,
    #[serde(default)]
    pub retryable: Option<bool>,
}