agent-protocols 0.2.2

Rust SDK for Agent Identity, Agent Profile, and Agent Discourse protocols
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
use std::collections::{BTreeMap, BTreeSet};

use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use base64::Engine as _;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use sha3::{Digest, Sha3_256};

use crate::error::{Result, SdkError};
use crate::identity::{verify_envelope, AgentId, Envelope, Event};

pub const PROTOCOL: &str = "agent-discourse/1.0";

pub mod event_type {
    pub const ROOM_CREATE: &str = "room.create";
    pub const ROOM_JOIN: &str = "room.join";
    pub const ROOM_JOIN_REVIEW: &str = "room.join.review";
    pub const ROOM_LEAVE: &str = "room.leave";
    pub const ROOM_MEMBER_ROLE_UPDATE: &str = "room.member.role.update";
    pub const ROOM_CLOSE: &str = "room.close";
    pub const ROOM_CANCEL: &str = "room.cancel";
    pub const MESSAGE_CREATE: &str = "message.create";
    pub const REACTION_CREATE: &str = "reaction.create";
    pub const MESSAGE_PROPOSAL_CREATE: &str = "message.proposal.create";
    pub const MESSAGE_POLL_CREATE: &str = "message.poll.create";
    pub const MESSAGE_POLL_VOTE: &str = "message.poll.vote";
    pub const MESSAGE_RESOLUTION_CREATE: &str = "message.resolution.create";
    pub const SOURCE_ADD: &str = "source.add";
    pub const TURN_UPDATE: &str = "turn.update";
    pub const QUESTION_CREATE: &str = "question.create";
    pub const ROOM_STEER: &str = "room.steer";
    pub const MAP_UPDATE: &str = "map.update";
    pub const ARTIFACT_CREATE: &str = "artifact.create";
}

#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum RoomState {
    Scheduled,
    Active,
    Ended,
    Cancelled,
}

#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum Visibility {
    Public,
    Restricted,
    Private,
}

#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum TurnPolicy {
    Free,
    RoundRobin,
    ModeratorLed,
}

#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum Role {
    Moderator,
    Expert,
    Participant,
    Observer,
}

#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum JoinRequestStatus {
    Pending,
    Approved,
    Rejected,
    Expired,
}

#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum MessageIntent {
    Question,
    Answer,
    Clarification,
    Critique,
    Synthesis,
    FollowUp,
    Other,
}

#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum MapOperation {
    UpsertNode,
    MoveNode,
    DeleteNode,
    MergeNodes,
    ReplaceSnapshot,
    MarkResolved,
}

#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ResolutionOutcome {
    Accepted,
    Rejected,
    Deferred,
    Superseded,
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct RoomCreatePayload {
    pub topic: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub agenda: Option<String>,
    pub visibility: Visibility,
    pub start_time: i64,
    pub end_time: i64,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub tags: Vec<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub language: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub policy: Option<RoomPolicy>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub extensions: BTreeMap<String, Value>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub extra: BTreeMap<String, Value>,
}

#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
pub struct RoomPolicy {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub turn_policy: Option<TurnPolicy>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub moderator_agent_ids: Vec<AgentId>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_participants: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub observer_allowed: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub observer_steering_allowed: Option<bool>,
    #[serde(default, flatten)]
    pub extra: BTreeMap<String, Value>,
}

impl RoomPolicy {
    pub fn new() -> Self {
        Self::default()
    }
}

impl RoomCreatePayload {
    pub fn new(
        topic: impl Into<String>,
        visibility: Visibility,
        start_time: i64,
        end_time: i64,
    ) -> Self {
        Self {
            topic: topic.into(),
            agenda: None,
            visibility,
            start_time,
            end_time,
            tags: Vec::new(),
            language: None,
            policy: None,
            extensions: BTreeMap::new(),
            extra: BTreeMap::new(),
        }
    }
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ServerRecord<P = Value> {
    pub room_id: String,
    pub seq: u64,
    #[serde(default)]
    pub pre_hash: Option<String>,
    pub hash: String,
    pub received_at: i64,
    pub envelope: Envelope<P>,
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct ServerRecordHashPayload {
    pub room_id: String,
    pub seq: u64,
    pub pre_hash: Option<String>,
    pub envelope_hash: String,
    pub received_at: i64,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RoomResponse {
    pub id: String,
    pub status: RoomState,
    pub url: String,
    pub seq: u64,
    #[serde(default)]
    pub pre_hash: Option<String>,
    pub hash: String,
    pub received_at: i64,
    pub envelope: Option<Envelope<RoomCreatePayload>>,
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct RoomJoinPayload {
    pub request_id: String,
    pub role: Role,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub perspective: Option<String>,
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct RoomJoinRequestPayload {
    pub requested_role: Role,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub perspective: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub extra: BTreeMap<String, Value>,
}

impl RoomJoinRequestPayload {
    pub fn new(requested_role: Role) -> Self {
        Self {
            requested_role,
            perspective: None,
            reason: None,
            extra: BTreeMap::new(),
        }
    }
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct RoomJoinRequest {
    pub id: String,
    pub room_id: String,
    pub applicant: AgentId,
    pub requested_role: Role,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub approved_role: Option<Role>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub perspective: Option<String>,
    pub status: JoinRequestStatus,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub request_reason: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub review_reason: Option<String>,
    pub created_at: i64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reviewed_by: Option<AgentId>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reviewed_at: Option<i64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expires_at: Option<i64>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub extra: BTreeMap<String, Value>,
}

#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum JoinDecision {
    Approve,
    Reject,
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct RoomJoinReviewPayload {
    pub request_id: String,
    pub member: AgentId,
    pub decision: JoinDecision,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub role: Option<Role>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct RoomLeavePayload {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct RoleUpdatePayload {
    pub member: AgentId,
    pub role: Role,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct MessageCreatePayload {
    pub content_type: String,
    pub content: Value,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub references: Vec<String>,
}

impl MessageCreatePayload {
    pub fn new(content_type: impl Into<String>, content: Value) -> Self {
        Self {
            content_type: content_type.into(),
            content,
            references: Vec::new(),
        }
    }

    pub fn text(text: impl Into<String>) -> Self {
        Self::new("text/plain", Value::String(text.into()))
    }

    pub fn markdown(markdown: impl Into<String>) -> Self {
        Self::new("text/markdown", Value::String(markdown.into()))
    }
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct ProposalCreatePayload {
    pub proposal_id: String,
    pub title: String,
    pub body: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub content_type: Option<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub references: Vec<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub source_event_ids: Vec<String>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub extra: BTreeMap<String, Value>,
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct PollOption {
    pub id: String,
    pub label: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct PollCreatePayload {
    pub poll_id: String,
    pub question: String,
    pub options: Vec<PollOption>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub min_choices: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_choices: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub closes_at: Option<i64>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub references: Vec<String>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub extra: BTreeMap<String, Value>,
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct PollVotePayload {
    pub event_id: String,
    pub option_ids: Vec<String>,
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct ResolutionCreatePayload {
    pub resolution_id: String,
    pub outcome: ResolutionOutcome,
    pub summary: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub proposal_event_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub poll_event_id: Option<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub references: Vec<String>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub extra: BTreeMap<String, Value>,
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct ReactionCreatePayload {
    pub event_id: String,
    pub reaction: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub score: Option<f64>,
}

impl ReactionCreatePayload {
    pub fn new(event_id: impl Into<String>, reaction: impl Into<String>) -> Self {
        Self {
            event_id: event_id.into(),
            reaction: reaction.into(),
            score: None,
        }
    }
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct SourceAddPayload {
    pub source_type: String,
    pub uri: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub retrieved_at: Option<i64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub content_digest: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub excerpt: Option<String>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub extra: BTreeMap<String, Value>,
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct TurnUpdatePayload {
    pub turn_id: u64,
    pub speaker: AgentId,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub intent: Option<MessageIntent>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub topic: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expires_at: Option<i64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct QuestionGeneratePayload {
    pub question: String,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub target_perspectives: Vec<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub basis: Option<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub source_event_ids: Vec<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub references: Vec<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub priority: Option<f64>,
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct DiscourseSteerPayload {
    pub instruction: String,
    pub target: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub priority: Option<f64>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub references: Vec<String>,
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum MapNodeStatus {
    Open,
    Resolved,
    Closed,
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct MapNode {
    pub id: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub parent_id: Option<String>,
    pub title: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub summary: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub status: Option<MapNodeStatus>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub source_event_ids: Vec<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub discussion_event_ids: Vec<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub children: Vec<MapNode>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub extra: BTreeMap<String, Value>,
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct MapUpdatePayload {
    pub operation: MapOperation,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub node: Option<MapNode>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub extra: BTreeMap<String, Value>,
    #[serde(default, flatten)]
    pub extensions: BTreeMap<String, Value>,
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct ArtifactCreatePayload {
    pub artifact_id: String,
    pub format: String,
    pub title: String,
    pub uri: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub content_digest: Option<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub source_event_ids: Vec<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub discussion_event_ids: Vec<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub map_event_id: Option<String>,
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct RoomClosePayload {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct RoomCancelPayload {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct ProfileResolverMetadata {
    pub mode: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub service: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub protocol: Option<String>,
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
pub struct DiscourseProtocolDiscovery {
    pub protocol: String,
    pub host: String,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub features: Vec<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub profile: Option<ProfileResolverMetadata>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub endpoints: BTreeMap<String, String>,
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct MapSnapshotRef {
    pub event_id: String,
    pub digest: String,
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct ArtifactManifest {
    pub artifact_id: String,
    #[serde(rename = "type")]
    pub kind: String,
    pub format: String,
    pub uri: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub content_digest: Option<String>,
}

#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub struct ArchiveManifest {
    pub protocol: String,
    #[serde(rename = "type")]
    pub kind: String,
    pub host: String,
    pub room_id: String,
    pub url: String,
    pub generated_at: i64,
    pub event_count: u64,
    pub first_seq: u64,
    pub last_seq: u64,
    pub last_hash: String,
    pub events_sha3_256: String,
    pub archive_root: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub map_snapshot: Option<MapSnapshotRef>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub artifacts: Vec<ArtifactManifest>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub discourse_trace_quality_score: Option<f64>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub formats: BTreeMap<String, String>,
}

pub fn room_create_event(
    actor: AgentId,
    created_at: i64,
    nonce: u64,
    payload: RoomCreatePayload,
) -> Event<RoomCreatePayload> {
    Event::new(
        PROTOCOL,
        event_type::ROOM_CREATE,
        actor,
        created_at,
        nonce,
        payload,
    )
}

pub fn discourse_event<P>(
    kind: impl Into<String>,
    actor: AgentId,
    created_at: i64,
    nonce: u64,
    room_id: impl Into<String>,
    payload: P,
) -> Event<P> {
    Event::new(PROTOCOL, kind, actor, created_at, nonce, payload).with_room_id(room_id)
}

pub fn validate_discourse_envelope<P>(envelope: &Envelope<P>) -> Result<()>
where
    P: Serialize,
{
    verify_envelope(envelope)?;
    let protocol = envelope.event.protocol.as_str();
    if protocol != PROTOCOL {
        return Err(SdkError::InvalidEventProtocol {
            expected: PROTOCOL.to_owned(),
            actual: envelope.event.protocol.clone(),
        });
    }
    if event_requires_room_id(&envelope.event.kind) && envelope.event.room_id.is_none() {
        return Err(SdkError::MissingRoomId);
    }
    Ok(())
}

pub fn validate_room_path<P>(envelope: &Envelope<P>, path_room_id: &str) -> Result<()> {
    match envelope.event.room_id.as_deref() {
        Some(actual) if actual == path_room_id => Ok(()),
        Some(actual) => Err(SdkError::RoomIdMismatch {
            expected: path_room_id.to_owned(),
            actual: actual.to_owned(),
        }),
        None if envelope.event.kind == event_type::ROOM_CREATE => Ok(()),
        None => Err(SdkError::MissingRoomId),
    }
}

pub fn event_requires_room_id(event_type: &str) -> bool {
    event_type != event_type::ROOM_CREATE
}

pub fn validate_room_create_payload(payload: &RoomCreatePayload) -> Result<()> {
    if payload.topic.trim().is_empty() {
        return Err(SdkError::InvalidPayload(
            "room topic must not be empty".to_owned(),
        ));
    }
    if payload.start_time >= payload.end_time {
        return Err(SdkError::InvalidPayload(
            "start_time must be before end_time".to_owned(),
        ));
    }
    if let Some(policy) = &payload.policy {
        if matches!(policy.max_participants, Some(0)) {
            return Err(SdkError::InvalidPayload(
                "max_participants must be a positive integer".to_owned(),
            ));
        }
    }
    Ok(())
}

pub fn validate_poll_create_payload(payload: &PollCreatePayload) -> Result<()> {
    if payload.poll_id.trim().is_empty() || payload.question.trim().is_empty() {
        return Err(SdkError::InvalidPayload(
            "poll_id and question are required".to_owned(),
        ));
    }
    if payload.options.len() < 2 {
        return Err(SdkError::InvalidPayload(
            "poll requires at least two options".to_owned(),
        ));
    }
    let mut option_ids = BTreeSet::new();
    for option in &payload.options {
        if option.id.trim().is_empty() || option.label.trim().is_empty() {
            return Err(SdkError::InvalidPayload(
                "option id and label are required".to_owned(),
            ));
        }
        if !option_ids.insert(option.id.as_str()) {
            return Err(SdkError::InvalidPayload(
                "poll option ids must be unique".to_owned(),
            ));
        }
    }
    let min_choices = payload.min_choices.unwrap_or(1);
    let max_choices = payload.max_choices.unwrap_or(1);
    if min_choices < 1 || max_choices < min_choices {
        return Err(SdkError::InvalidPayload(
            "invalid poll choice limits".to_owned(),
        ));
    }
    Ok(())
}

pub fn validate_poll_vote_payload(
    payload: &PollVotePayload,
    poll: &PollCreatePayload,
    now_ms: Option<i64>,
) -> Result<()> {
    if let (Some(closes_at), Some(now_ms)) = (poll.closes_at, now_ms) {
        if now_ms > closes_at {
            return Err(SdkError::InvalidPayload("poll is closed".to_owned()));
        }
    }
    let min_choices = poll.min_choices.unwrap_or(1) as usize;
    let max_choices = poll.max_choices.unwrap_or(1) as usize;
    let option_ids: BTreeSet<&str> = poll
        .options
        .iter()
        .map(|option| option.id.as_str())
        .collect();
    let selected: BTreeSet<&str> = payload.option_ids.iter().map(String::as_str).collect();
    if selected.len() != payload.option_ids.len() {
        return Err(SdkError::InvalidPayload(
            "duplicate poll options".to_owned(),
        ));
    }
    if selected.len() < min_choices || selected.len() > max_choices {
        return Err(SdkError::InvalidPayload(
            "invalid number of options".to_owned(),
        ));
    }
    if selected
        .iter()
        .any(|option_id| !option_ids.contains(option_id))
    {
        return Err(SdkError::InvalidPayload("unknown poll option".to_owned()));
    }
    Ok(())
}

pub fn server_record_hash_payload(
    room_id: &str,
    seq: u64,
    pre_hash: Option<&str>,
    envelope_hash: &str,
    received_at: i64,
) -> ServerRecordHashPayload {
    ServerRecordHashPayload {
        room_id: room_id.to_owned(),
        seq,
        pre_hash: pre_hash.map(str::to_owned),
        envelope_hash: envelope_hash.to_owned(),
        received_at,
    }
}

pub fn server_record_hash(
    room_id: &str,
    seq: u64,
    pre_hash: Option<&str>,
    envelope_hash: &str,
    received_at: i64,
) -> Result<String> {
    hash_canonical_json(&server_record_hash_payload(
        room_id,
        seq,
        pre_hash,
        envelope_hash,
        received_at,
    ))
}

pub fn build_server_record<P>(
    room_id: impl Into<String>,
    seq: u64,
    pre_hash: Option<String>,
    received_at: i64,
    envelope: Envelope<P>,
) -> Result<ServerRecord<P>> {
    let room_id = room_id.into();
    let hash = server_record_hash(
        &room_id,
        seq,
        pre_hash.as_deref(),
        &envelope.hash,
        received_at,
    )?;
    Ok(ServerRecord {
        room_id,
        seq,
        pre_hash,
        hash,
        received_at,
        envelope,
    })
}

pub fn verify_server_record<P>(record: &ServerRecord<P>) -> Result<()>
where
    P: Serialize,
{
    let expected = server_record_hash(
        &record.room_id,
        record.seq,
        record.pre_hash.as_deref(),
        &record.envelope.hash,
        record.received_at,
    )?;
    if record.hash == expected {
        Ok(())
    } else {
        Err(SdkError::InvalidEventHash {
            expected,
            actual: record.hash.clone(),
        })
    }
}

pub fn verify_server_record_chain<P>(records: &[ServerRecord<P>]) -> Result<()>
where
    P: Serialize,
{
    let mut previous: Option<&ServerRecord<P>> = None;
    for record in records {
        verify_server_record(record)?;
        if let Some(previous) = previous {
            if record.seq != previous.seq + 1 {
                return Err(SdkError::InvalidPayload(
                    "seq must increase by 1".to_owned(),
                ));
            }
            if record.pre_hash.as_deref() != Some(previous.hash.as_str()) {
                return Err(SdkError::InvalidPayload("pre_hash mismatch".to_owned()));
            }
        } else if record.seq != 1 {
            return Err(SdkError::InvalidPayload("first seq must be 1".to_owned()));
        } else if record.pre_hash.is_some() {
            return Err(SdkError::InvalidPayload(
                "first pre_hash must be null".to_owned(),
            ));
        }
        previous = Some(record);
    }
    Ok(())
}

pub fn archive_events_digest<P>(records: &[ServerRecord<P>]) -> Result<String>
where
    P: Serialize,
{
    hash_canonical_json(records)
}

#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct PermissionContext {
    pub role: Option<Role>,
    pub is_creator: bool,
    pub join_request_approved: bool,
    pub moderator_authorized: bool,
    pub expert_policy_allowed: bool,
    pub participant_policy_allowed: bool,
    pub observer_steering_allowed: bool,
    pub observer_poll_vote_allowed: bool,
}

impl PermissionContext {
    pub fn for_role(role: Role) -> Self {
        Self {
            role: Some(role),
            ..Self::default()
        }
    }

    pub fn creator(role: Option<Role>) -> Self {
        Self {
            role,
            is_creator: true,
            ..Self::default()
        }
    }
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct StateWriteOptions {
    pub post_end_reaction_allowed: bool,
}

pub fn can_submit_event(event_type: &str, context: &PermissionContext) -> bool {
    if event_type == event_type::ROOM_CREATE {
        return true;
    }
    if event_type == event_type::ROOM_JOIN {
        return context.join_request_approved;
    }

    if context.is_creator {
        return is_known_event_type(event_type);
    }

    match context.role {
        Some(Role::Moderator) => moderator_can_submit(event_type, context.moderator_authorized),
        Some(Role::Expert) => speaker_can_submit(event_type, context.expert_policy_allowed),
        Some(Role::Participant) => {
            speaker_can_submit(event_type, context.participant_policy_allowed)
        }
        Some(Role::Observer) => observer_can_submit(event_type, context),
        None => false,
    }
}

pub fn can_write_in_state(event_type: &str, state: RoomState, options: StateWriteOptions) -> bool {
    match state {
        RoomState::Scheduled => matches!(
            event_type,
            event_type::ROOM_JOIN | event_type::ROOM_JOIN_REVIEW | event_type::ROOM_CANCEL
        ),
        RoomState::Active => {
            event_type != event_type::ROOM_CREATE && event_type != event_type::ROOM_CANCEL
        }
        RoomState::Ended => {
            options.post_end_reaction_allowed && event_type == event_type::REACTION_CREATE
        }
        RoomState::Cancelled => false,
    }
}

pub fn can_accept_room_write(
    event_type: &str,
    state: RoomState,
    permission: &PermissionContext,
    state_options: StateWriteOptions,
) -> bool {
    can_submit_event(event_type, permission) && can_write_in_state(event_type, state, state_options)
}

pub fn validate_room_write(
    event_type: &str,
    state: RoomState,
    permission: &PermissionContext,
    state_options: StateWriteOptions,
) -> Result<()> {
    if can_accept_room_write(event_type, state, permission, state_options) {
        Ok(())
    } else {
        Err(SdkError::PermissionDenied)
    }
}

fn moderator_can_submit(event_type: &str, moderator_authorized: bool) -> bool {
    matches!(
        event_type,
        event_type::ROOM_JOIN_REVIEW
            | event_type::ROOM_CLOSE
            | event_type::MESSAGE_CREATE
            | event_type::SOURCE_ADD
            | event_type::TURN_UPDATE
            | event_type::QUESTION_CREATE
            | event_type::ROOM_STEER
            | event_type::MAP_UPDATE
            | event_type::ARTIFACT_CREATE
            | event_type::MESSAGE_PROPOSAL_CREATE
            | event_type::MESSAGE_POLL_CREATE
            | event_type::MESSAGE_POLL_VOTE
            | event_type::MESSAGE_RESOLUTION_CREATE
            | event_type::REACTION_CREATE
            | event_type::ROOM_LEAVE
    ) || (moderator_authorized
        && matches!(
            event_type,
            event_type::ROOM_MEMBER_ROLE_UPDATE | event_type::ROOM_CANCEL
        ))
}

fn speaker_can_submit(event_type: &str, policy_allowed: bool) -> bool {
    matches!(
        event_type,
        event_type::MESSAGE_CREATE
            | event_type::SOURCE_ADD
            | event_type::ROOM_STEER
            | event_type::MESSAGE_PROPOSAL_CREATE
            | event_type::MESSAGE_POLL_CREATE
            | event_type::MESSAGE_POLL_VOTE
            | event_type::REACTION_CREATE
            | event_type::ROOM_LEAVE
    ) || (policy_allowed
        && matches!(
            event_type,
            event_type::QUESTION_CREATE
                | event_type::MAP_UPDATE
                | event_type::ARTIFACT_CREATE
                | event_type::MESSAGE_RESOLUTION_CREATE
        ))
}

fn observer_can_submit(event_type: &str, context: &PermissionContext) -> bool {
    matches!(
        event_type,
        event_type::REACTION_CREATE | event_type::ROOM_LEAVE
    ) || (context.observer_steering_allowed && event_type == event_type::ROOM_STEER)
        || (context.observer_poll_vote_allowed && event_type == event_type::MESSAGE_POLL_VOTE)
}

fn is_known_event_type(event_type: &str) -> bool {
    matches!(
        event_type,
        event_type::ROOM_CREATE
            | event_type::ROOM_JOIN
            | event_type::ROOM_JOIN_REVIEW
            | event_type::ROOM_LEAVE
            | event_type::ROOM_MEMBER_ROLE_UPDATE
            | event_type::ROOM_CLOSE
            | event_type::ROOM_CANCEL
            | event_type::MESSAGE_CREATE
            | event_type::REACTION_CREATE
            | event_type::MESSAGE_PROPOSAL_CREATE
            | event_type::MESSAGE_POLL_CREATE
            | event_type::MESSAGE_POLL_VOTE
            | event_type::MESSAGE_RESOLUTION_CREATE
            | event_type::SOURCE_ADD
            | event_type::TURN_UPDATE
            | event_type::QUESTION_CREATE
            | event_type::ROOM_STEER
            | event_type::MAP_UPDATE
            | event_type::ARTIFACT_CREATE
    )
}

fn hash_canonical_json<T>(value: &T) -> Result<String>
where
    T: Serialize + ?Sized,
{
    let bytes = serde_jcs::to_vec(value).map_err(|err| SdkError::CanonicalJson(err.to_string()))?;
    let digest = Sha3_256::digest(bytes);
    Ok(URL_SAFE_NO_PAD.encode(digest))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::identity::AgentSigner;
    use serde_json::json;

    #[test]
    fn validates_room_create_without_room_id() {
        let signer = AgentSigner::from_seed([14; 32]);
        let payload = RoomCreatePayload::new("Research room", Visibility::Public, 1000, 2000);
        let event = Event::new(
            PROTOCOL,
            event_type::ROOM_CREATE,
            signer.agent_id(),
            100,
            1,
            payload,
        );
        let envelope = signer.sign_event(event).unwrap();

        validate_discourse_envelope(&envelope).unwrap();
        validate_room_path(&envelope, "d8ftedhpqhsusbg001tg").unwrap();
    }

    #[test]
    fn rejects_room_event_without_room_id() {
        let signer = AgentSigner::from_seed([15; 32]);
        let event = Event::new(
            PROTOCOL,
            event_type::MESSAGE_CREATE,
            signer.agent_id(),
            100,
            1,
            MessageCreatePayload::text("hello"),
        );
        let envelope = signer.sign_event(event).unwrap();

        assert!(matches!(
            validate_discourse_envelope(&envelope),
            Err(SdkError::MissingRoomId)
        ));
    }

    #[test]
    fn applies_permission_matrix() {
        let observer = PermissionContext::for_role(Role::Observer);
        assert!(can_submit_event(event_type::REACTION_CREATE, &observer));
        assert!(!can_submit_event(event_type::MESSAGE_CREATE, &observer));
        assert!(!can_submit_event(event_type::ROOM_JOIN, &observer));

        let approved_join = PermissionContext {
            join_request_approved: true,
            ..PermissionContext::default()
        };
        assert!(can_submit_event(event_type::ROOM_JOIN, &approved_join));

        let mut moderator = PermissionContext::for_role(Role::Moderator);
        assert!(can_submit_event(event_type::ROOM_JOIN_REVIEW, &moderator));
        assert!(!can_submit_event(event_type::ROOM_CANCEL, &moderator));
        moderator.moderator_authorized = true;
        assert!(can_submit_event(event_type::ROOM_CANCEL, &moderator));

        let participant = PermissionContext::for_role(Role::Participant);
        assert!(!can_submit_event(
            event_type::ROOM_JOIN_REVIEW,
            &participant
        ));
    }

    #[test]
    fn applies_state_restrictions() {
        let participant = PermissionContext::for_role(Role::Participant);
        assert!(can_accept_room_write(
            event_type::MESSAGE_CREATE,
            RoomState::Active,
            &participant,
            StateWriteOptions::default()
        ));
        assert!(!can_accept_room_write(
            event_type::MESSAGE_CREATE,
            RoomState::Scheduled,
            &participant,
            StateWriteOptions::default()
        ));
        assert!(!can_accept_room_write(
            event_type::REACTION_CREATE,
            RoomState::Ended,
            &participant,
            StateWriteOptions::default()
        ));
        assert!(can_accept_room_write(
            event_type::ROOM_JOIN_REVIEW,
            RoomState::Scheduled,
            &PermissionContext::for_role(Role::Moderator),
            StateWriteOptions::default()
        ));
        assert!(can_accept_room_write(
            event_type::ROOM_JOIN,
            RoomState::Scheduled,
            &PermissionContext {
                join_request_approved: true,
                ..PermissionContext::default()
            },
            StateWriteOptions::default()
        ));
        assert!(can_accept_room_write(
            event_type::REACTION_CREATE,
            RoomState::Ended,
            &participant,
            StateWriteOptions {
                post_end_reaction_allowed: true,
            }
        ));
    }

    #[test]
    fn validates_room_creation_payloads() {
        let mut payload = RoomCreatePayload::new("Research room", Visibility::Public, 1000, 2000);
        payload.policy = Some(RoomPolicy {
            max_participants: Some(2),
            ..RoomPolicy::default()
        });
        validate_room_create_payload(&payload).unwrap();

        let empty_topic = RoomCreatePayload::new(" ", Visibility::Public, 1000, 2000);
        assert!(matches!(
            validate_room_create_payload(&empty_topic),
            Err(SdkError::InvalidPayload(_))
        ));

        let invalid_time = RoomCreatePayload::new("Research room", Visibility::Public, 2000, 1000);
        assert!(matches!(
            validate_room_create_payload(&invalid_time),
            Err(SdkError::InvalidPayload(_))
        ));
    }

    #[test]
    fn validates_poll_payloads_and_votes() {
        let poll = PollCreatePayload {
            poll_id: "poll_review_order".to_owned(),
            question: "Which review order?".to_owned(),
            options: vec![
                PollOption {
                    id: "a".to_owned(),
                    label: "Correctness first".to_owned(),
                    description: None,
                },
                PollOption {
                    id: "b".to_owned(),
                    label: "Security first".to_owned(),
                    description: None,
                },
            ],
            min_choices: Some(1),
            max_choices: Some(1),
            closes_at: None,
            references: Vec::new(),
            extra: BTreeMap::new(),
        };

        validate_poll_create_payload(&poll).unwrap();
        validate_poll_vote_payload(
            &PollVotePayload {
                event_id: "evt".to_owned(),
                option_ids: vec!["a".to_owned()],
            },
            &poll,
            None,
        )
        .unwrap();
        assert!(matches!(
            validate_poll_vote_payload(
                &PollVotePayload {
                    event_id: "evt".to_owned(),
                    option_ids: vec!["a".to_owned(), "b".to_owned()],
                },
                &poll,
                None,
            ),
            Err(SdkError::InvalidPayload(_))
        ));

        let mut duplicate = poll.clone();
        duplicate.options[1].id = "a".to_owned();
        assert!(matches!(
            validate_poll_create_payload(&duplicate),
            Err(SdkError::InvalidPayload(_))
        ));
    }

    #[test]
    fn builds_and_verifies_server_record_chains() {
        let signer = AgentSigner::from_seed([18; 32]);
        let envelope1 = signer
            .sign_event(Event::new(
                PROTOCOL,
                event_type::ROOM_CREATE,
                signer.agent_id(),
                100,
                1,
                json!({
                    "topic": "Research room",
                    "visibility": "public",
                    "start_time": 1000,
                    "end_time": 2000
                }),
            ))
            .unwrap();
        let record1 = build_server_record("room123", 1, None, 110, envelope1).unwrap();

        let envelope2 = signer
            .sign_event(discourse_event(
                event_type::MESSAGE_CREATE,
                signer.agent_id(),
                120,
                2,
                "room123",
                json!({"content_type": "text/plain", "content": "hello"}),
            ))
            .unwrap();
        let record2 =
            build_server_record("room123", 2, Some(record1.hash.clone()), 130, envelope2).unwrap();

        assert_eq!(
            record1.hash,
            server_record_hash("room123", 1, None, &record1.envelope.hash, 110).unwrap()
        );
        verify_server_record(&record1).unwrap();
        verify_server_record_chain(&[record1.clone(), record2.clone()]).unwrap();
        assert_eq!(
            archive_events_digest(&[record1.clone(), record2.clone()])
                .unwrap()
                .len(),
            43
        );
        assert!(verify_server_record_chain(&[record2]).is_err());

        let broken = ServerRecord {
            pre_hash: Some("bad".to_owned()),
            ..record1
        };
        assert!(verify_server_record_chain(&[broken]).is_err());
    }
}