horus 0.6.10

A small, modular Rust framework for building coding agents
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
//! The small event protocol shared by agent frontends.

use serde::Deserialize;
use serde::Deserializer;
use serde::Serialize;

pub use self::replay::events as replay_events;
pub(crate) use self::replay::{
    ATTACHMENTS_FIELD, INTERNAL_MESSAGE_FIELD, REPLAY_REASONING_FIELD, TOOL_ERROR_FIELD,
    internal_message_kind, is_internal_message, strip_attachment_references,
};

mod replay;

/// Maximum total UTF-8 bytes accepted in one user-input submission.
pub const MAX_USER_INPUT_BYTES: usize = 1024 * 1024;

/// Maximum UTF-8 bytes accepted in capability command input or queued active input.
pub const MAX_CAPABILITY_INPUT_BYTES: usize = 64 * 1024;

/// One immutable, session-bound file addressed by an opaque reference.
///
/// Only upload-origin references are valid in `Op::UserInput.attachments`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SessionFileReference {
    pub id: String,
    pub name: String,
    pub size: u64,
    pub media_type: String,
}

/// A command submitted by a frontend.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Submission {
    /// Correlates all events produced by this command.
    pub id: String,
    /// Command payload.
    pub op: Op,
}

/// Frontend-visible context for the session owner, workspace, and origin.
///
/// These values are correlation metadata, not authentication or authorization.
/// A remote host must derive them after authentication and inject tenant-scoped
/// backends when it creates the agent.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct SessionContext {
    /// Opaque tenant or organization identifier.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tenant_id: Option<String>,
    /// Opaque identifier for the user who owns the session.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub user_id: Option<String>,
    /// Optional display label, such as the local operating-system user name.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub user_name: Option<String>,
    /// Opaque workspace identifier; this is not a filesystem path.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub workspace_id: Option<String>,
    /// Optional frontend-facing workspace label.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub workspace_label: Option<String>,
    /// Optional label describing what created the session.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub origin_label: Option<String>,
}

/// Commands supported by the agent.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
#[non_exhaustive]
pub enum Op {
    /// Start a user turn.
    UserInput {
        text: String,
        attachments: Vec<SessionFileReference>,
    },
    /// Submit capability-owned input while a turn is active.
    ActiveInput {
        operation: String,
        turn_id: String,
        text: String,
    },
    /// Abort one active turn.
    Interrupt { turn_id: String },
    /// Resolve a paused tool batch.
    ExecApproval {
        id: String,
        decision: ReviewDecision,
    },
    /// Invokes a command owned by one capability.
    CapabilityCommand {
        capability: String,
        command: String,
        arguments: String,
        /// Optional caller-editable text kept separate from routing arguments.
        ///
        /// When embedded in a frontend action, a present value is its caller-editable text.
        #[serde(deserialize_with = "required_option")]
        input: Option<String>,
        #[serde(deserialize_with = "required_option")]
        target: Option<MessageTarget>,
    },
    /// Selects one immutable registered model route.
    SetModel { route: String },
    /// Requests that the frontend reopen an existing session.
    ResumeSession { session_id: String },
}

fn required_option<'de, D, T>(deserializer: D) -> std::result::Result<Option<T>, D::Error>
where
    D: Deserializer<'de>,
    T: Deserialize<'de>,
{
    Option::deserialize(deserializer)
}

/// An event emitted to a frontend.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Event {
    /// Submission ID that caused this event, if it was command-driven.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub submission_id: Option<String>,
    /// Event payload.
    pub msg: EventMsg,
}

/// Events supported by the minimal frontend contract.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
#[non_exhaustive]
pub enum EventMsg {
    Error(ErrorEvent),
    Warning(WarningEvent),
    SessionConfigured(SessionConfiguredEvent),
    #[serde(rename = "task_started")]
    TurnStarted(TurnStartedEvent),
    #[serde(rename = "task_complete")]
    TurnComplete(TurnCompleteEvent),
    TurnAborted(TurnAbortedEvent),
    UserMessage(UserMessageEvent),
    AgentMessage(AgentMessageEvent),
    AgentMessageContentDelta(AgentMessageContentDeltaEvent),
    AgentReasoningContentDelta(AgentReasoningContentDeltaEvent),
    SessionHistory(SessionHistoryEvent),
    ModelChanged(ModelChangedEvent),
    SessionResumeRequested(SessionResumeRequestedEvent),
    ToolCallBegin(ToolCallBeginEvent),
    ToolCallEnd(ToolCallEndEvent),
    ExecApprovalRequest(ExecApprovalRequestEvent),
    TokenCount(TokenCountEvent),
    ContextCompacted,
    WebSearchBegin(WebSearchBeginEvent),
    WebSearchEnd(WebSearchEndEvent),
    Frontend(FrontendEvent),
}

/// Provider-neutral streaming output before submission correlation is attached.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ModelEvent {
    TextDelta(String),
    CommentaryDelta(String),
    ReasoningDelta(String),
    WebSearchStarted {
        call_id: String,
    },
    WebSearchCompleted {
        call_id: String,
        action: WebSearchAction,
    },
}

/// Provider-neutral action reported by hosted web search.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum WebSearchAction {
    Search {
        query: Option<String>,
    },
    OpenPage {
        url: Option<String>,
    },
    FindInPage {
        url: Option<String>,
        pattern: Option<String>,
    },
    Other,
}

impl ModelEvent {
    /// Converts one normalized provider event into the frontend protocol.
    #[must_use]
    pub fn into_event(self, thread_id: &str, turn_id: &str, item_id: &str) -> EventMsg {
        match self {
            Self::TextDelta(delta) => {
                EventMsg::AgentMessageContentDelta(AgentMessageContentDeltaEvent {
                    thread_id: thread_id.into(),
                    turn_id: turn_id.into(),
                    item_id: item_id.into(),
                    delta,
                    phase: Some(AgentMessagePhase::FinalAnswer),
                })
            }
            Self::CommentaryDelta(delta) => {
                EventMsg::AgentMessageContentDelta(AgentMessageContentDeltaEvent {
                    thread_id: thread_id.into(),
                    turn_id: turn_id.into(),
                    item_id: item_id.into(),
                    delta,
                    phase: Some(AgentMessagePhase::Commentary),
                })
            }
            Self::ReasoningDelta(delta) => {
                EventMsg::AgentReasoningContentDelta(AgentReasoningContentDeltaEvent {
                    thread_id: thread_id.into(),
                    turn_id: turn_id.into(),
                    item_id: item_id.into(),
                    delta,
                })
            }
            Self::WebSearchStarted { call_id } => {
                EventMsg::WebSearchBegin(WebSearchBeginEvent { call_id })
            }
            Self::WebSearchCompleted { call_id, action } => {
                let (action, query) = match action {
                    WebSearchAction::Search { query } => ("search", query),
                    WebSearchAction::OpenPage { url } => ("open_page", url),
                    WebSearchAction::FindInPage { url, pattern } => {
                        ("find_in_page", pattern.or(url))
                    }
                    WebSearchAction::Other => ("other", None),
                };
                EventMsg::WebSearchEnd(WebSearchEndEvent {
                    call_id,
                    query,
                    action: action.into(),
                })
            }
        }
    }
}

/// A frontend command declared by a capability.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FrontendCommand {
    pub name: String,
    pub arguments: String,
    pub description: String,
}

/// UI metadata exported by one capability.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct FrontendContribution {
    pub capability: String,
    /// Whether the composed runtime installs session-bound file attachment endpoints.
    pub accepts_file_attachments: bool,
    /// Optional capability-owned item count for generic summaries.
    pub count: Option<usize>,
    pub commands: Vec<FrontendCommand>,
    pub widgets: Vec<FrontendWidget>,
    pub references: Vec<FrontendReference>,
    pub active_input: Option<FrontendActiveInput>,
}

/// One middleware entry and its frontend-neutral configuration controls.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MiddlewareFeature {
    pub id: String,
    pub label: String,
    pub description: String,
    pub required: bool,
    pub settings: Vec<FrontendSetting>,
}

/// One schema-advertised setting rendered by a thin frontend.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FrontendSetting {
    pub id: String,
    pub label: String,
    pub description: String,
    #[serde(flatten)]
    pub kind: FrontendSettingKind,
}

/// Generic control metadata for a schema-advertised setting.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
pub enum FrontendSettingKind {
    Integer {
        min: i64,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        max: Option<i64>,
        step: i64,
    },
    Select {
        options: Vec<FrontendSettingOption>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        unset_label: Option<String>,
    },
}

/// One exact value in a schema-advertised select control.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FrontendSettingOption {
    pub value: String,
    pub label: String,
    pub description: String,
}

/// Scalar value accepted by the generic setting controls.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum FrontendSettingValue {
    Integer(i64),
    String(String),
}

/// How normal composer input is submitted while a turn is active.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FrontendActiveInput {
    pub operation: String,
}

/// One chat reference supplied by a capability.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FrontendReference {
    pub trigger: char,
    pub value: String,
    pub description: String,
}

/// One capability-rendered view mounted into a standard frontend slot.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FrontendWidget {
    pub id: String,
    pub slot: FrontendSlot,
    pub text: String,
    pub tone: FrontendTone,
    pub symbol: Option<FrontendSymbol>,
    pub icon_only: bool,
    pub progress: Option<FrontendProgress>,
    pub content: Option<FrontendWidgetContent>,
    /// Optional operation invoked when a frontend activates this widget.
    pub action: Option<Op>,
}

/// Determinate progress rendered by a frontend widget.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct FrontendProgress {
    pub completed: usize,
    pub total: usize,
}

/// Capability-owned content shown when a frontend widget is opened.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum FrontendWidgetContent {
    Blocks {
        title: String,
        blocks: Vec<FrontendBlock>,
    },
    Picker {
        title: String,
        options: Vec<FrontendPickerOption>,
    },
    ActionList {
        title: String,
        items: Vec<FrontendActionListItem>,
    },
}

/// Stable locations a thin frontend shell makes available to capabilities.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FrontendSlot {
    Header,
    ComposerHeader,
    ComposerFooter,
    MessageActions,
    /// A transient capability-owned item after the live transcript.
    TranscriptTail,
    /// A capability destination mounted by the frontend shell.
    Navigation,
    /// A capability action mounted in the current chat's menu.
    ChatMenu,
}

/// Capability-rendered transcript content with frontend-neutral formatting and tone.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FrontendBlock {
    pub id: Option<String>,
    pub group: Option<String>,
    pub append: bool,
    /// Whether this block represents work that has not completed yet.
    pub pending: bool,
    pub text: String,
    /// Downloadable files owned by the session rendering this block.
    pub files: Vec<SessionFileReference>,
    pub format: FrontendBlockFormat,
    pub tone: FrontendTone,
}

impl FrontendBlock {
    /// Scopes replacement and grouping IDs to one capability.
    #[must_use]
    pub fn namespaced(mut self, capability: &str) -> Self {
        if let Some(id) = self.id.take() {
            self.id = Some(format!("{capability}/{id}"));
        }
        if let Some(group) = self.group.take() {
            self.group = Some(format!("{capability}/{group}"));
        }
        self
    }
}

/// Frontend-neutral structure carried by a transcript block.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FrontendBlockFormat {
    PlainText,
    UnifiedDiff,
}

/// One selectable action supplied by a capability.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FrontendPickerOption {
    pub label: String,
    pub description: String,
    pub detail: String,
    pub op: Op,
}

/// One compact status row with optional trailing actions.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FrontendActionListItem {
    pub id: String,
    pub text: String,
    pub state: FrontendListItemState,
    pub actions: Vec<FrontendAction>,
}

/// Semantic state for one compact list row.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FrontendListItemState {
    Plain,
    Pending,
    InProgress,
    Completed,
}

/// One labeled, icon-forward action attached to a list item.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FrontendAction {
    pub id: String,
    pub label: String,
    pub symbol: FrontendSymbol,
    pub tone: FrontendTone,
    pub op: Op,
}

/// Generic capability UI updates understood by every frontend.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "frontend_type", rename_all = "snake_case")]
pub enum FrontendEvent {
    Render {
        capability: String,
        block: FrontendBlock,
    },
    Widget {
        capability: String,
        item: FrontendWidget,
    },
    RemoveWidget {
        capability: String,
        id: String,
    },
    Picker {
        title: String,
        options: Vec<FrontendPickerOption>,
    },
    Preview {
        title: String,
        events: Vec<EventMsg>,
    },
}

/// A presentation hint rather than a terminal-specific color.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FrontendTone {
    Neutral,
    Success,
    Warning,
    Error,
}

/// A presentation hint rather than a name from any one icon set, the same way
/// [`FrontendTone`] names a role instead of a color.
///
/// A gateway does not know whether the frontend draws SF Symbols, terminal glyphs, or
/// SVGs, so it names what a glyph stands for and each frontend supplies its own artwork.
/// Most variants are roles. The rest are provider identity, where no role applies: some
/// name the vendor outright (`ChatGpt`, `Claude`, `Deepseek`, `Kimi`) and the others name
/// what the mark depicts (`Moon`, `Sparkle`) where a frontend has no vendor artwork to draw.
///
/// [`Self::Custom`] carries anything outside this list so a plugin can still ship a glyph
/// this enum has never heard of. It is explicitly best-effort: a frontend that cannot
/// resolve the name falls back to a placeholder, which is why everything shipped in-tree
/// should earn a variant instead.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FrontendSymbol {
    Agent,
    Brain,
    Branch,
    Chat,
    ChatGpt,
    Claude,
    Deepseek,
    Delete,
    Edit,
    Kimi,
    Moon,
    Promote,
    Route,
    Search,
    Sparkle,
    Storage,
    Task,
    Custom(String),
}

impl FrontendSymbol {
    /// The wire name. Also the stable token capabilities build action ids from.
    pub fn as_str(&self) -> &str {
        match self {
            Self::Agent => "agent",
            Self::Brain => "brain",
            Self::Branch => "branch",
            Self::Chat => "chat",
            Self::ChatGpt => "chat_gpt",
            Self::Claude => "claude",
            Self::Deepseek => "deepseek",
            Self::Delete => "delete",
            Self::Edit => "edit",
            Self::Kimi => "kimi",
            Self::Moon => "moon",
            Self::Promote => "promote",
            Self::Route => "route",
            Self::Search => "search",
            Self::Sparkle => "sparkle",
            Self::Storage => "storage",
            Self::Task => "task",
            Self::Custom(name) => name,
        }
    }

    /// Unknown names become [`Self::Custom`] rather than an error: a frontend rendering a
    /// placeholder is a better outcome than a gateway refusing to decode a whole frame.
    fn from_wire(name: &str) -> Self {
        match name {
            "agent" => Self::Agent,
            "brain" => Self::Brain,
            "branch" => Self::Branch,
            "chat" => Self::Chat,
            "chat_gpt" => Self::ChatGpt,
            "claude" => Self::Claude,
            "deepseek" => Self::Deepseek,
            "delete" => Self::Delete,
            "edit" => Self::Edit,
            "kimi" => Self::Kimi,
            "moon" => Self::Moon,
            "promote" => Self::Promote,
            "route" => Self::Route,
            "search" => Self::Search,
            "sparkle" => Self::Sparkle,
            "storage" => Self::Storage,
            "task" => Self::Task,
            other => Self::Custom(other.to_owned()),
        }
    }
}

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

impl Serialize for FrontendSymbol {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(self.as_str())
    }
}

impl<'de> Deserialize<'de> for FrontendSymbol {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        // A known name round-trips out of `Custom` on the way back in, so the two spellings
        // of the same glyph cannot drift apart once a frame has crossed the wire.
        String::deserialize(deserializer).map(|name| Self::from_wire(&name))
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ErrorEvent {
    pub message: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct WarningEvent {
    pub message: String,
}

/// Immutable session data emitted once when an agent starts or resumes.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SessionConfiguredEvent {
    pub session_id: String,
    pub context: SessionContext,
    pub model: ModelChangedEvent,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TurnStartedEvent {
    pub turn_id: String,
    pub model_context_window: Option<i64>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TurnCompleteEvent {
    pub turn_id: String,
    pub last_agent_message: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TurnAbortedEvent {
    pub turn_id: String,
    pub reason: String,
}

/// Exact durable transcript prefix selected by a message action.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct MessageTarget {
    /// Durable checkpoint sequence containing the selected message.
    pub checkpoint_sequence: u64,
    /// One-based item count within the checkpoint's transcript batch.
    #[serde(deserialize_with = "positive_usize")]
    pub batch_item_count: usize,
}

fn positive_usize<'de, D>(deserializer: D) -> std::result::Result<usize, D::Error>
where
    D: Deserializer<'de>,
{
    let value = usize::deserialize(deserializer)?;
    if value == 0 {
        return Err(serde::de::Error::custom(
            "message target item count must be positive",
        ));
    }
    Ok(value)
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct UserMessageEvent {
    pub message: String,
    pub attachments: Vec<SessionFileReference>,
    #[serde(deserialize_with = "required_option")]
    pub message_target: Option<MessageTarget>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AgentMessageEvent {
    pub message: String,
    pub phase: Option<AgentMessagePhase>,
    #[serde(deserialize_with = "required_option")]
    pub message_target: Option<MessageTarget>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AgentMessageContentDeltaEvent {
    pub thread_id: String,
    pub turn_id: String,
    pub item_id: String,
    pub delta: String,
    pub phase: Option<AgentMessagePhase>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AgentReasoningContentDeltaEvent {
    pub thread_id: String,
    pub turn_id: String,
    pub item_id: String,
    pub delta: String,
}

/// A restored transcript kept distinct from live turn lifecycle events.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SessionHistoryEvent {
    pub events: Vec<EventMsg>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ModelChangedEvent {
    pub route: String,
    pub model: String,
    pub reasoning_effort: Option<String>,
    pub model_context_window: Option<i64>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SessionResumeRequestedEvent {
    pub session_id: String,
    pub context: SessionContext,
}

/// Assistant message phases understood by frontends.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AgentMessagePhase {
    Commentary,
    FinalAnswer,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ToolCallBeginEvent {
    pub turn_id: String,
    pub call_id: String,
    pub name: String,
    pub arguments: serde_json::Value,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ToolCallEndEvent {
    pub turn_id: String,
    pub call_id: String,
    pub name: String,
    pub output: String,
    pub is_error: bool,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ExecApprovalRequestEvent {
    pub id: String,
    pub turn_id: String,
    pub calls: Vec<ApprovalCall>,
    pub reason: String,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ApprovalCall {
    pub call_id: String,
    pub name: String,
    pub arguments: serde_json::Value,
}

/// A user's decision for a paused tool batch.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ReviewDecision {
    Approved,
    ApprovedForSession,
    Denied { rejection: String },
    Abort,
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct TokenUsage {
    pub input_tokens: i64,
    pub cached_input_tokens: i64,
    pub cache_write_input_tokens: i64,
    pub output_tokens: i64,
    pub reasoning_output_tokens: i64,
    pub total_tokens: i64,
}

impl TokenUsage {
    /// Adds another response's usage, returning `None` on integer overflow.
    pub fn checked_add(&mut self, other: &Self) -> Option<()> {
        let input_tokens = self.input_tokens.checked_add(other.input_tokens)?;
        let cached_input_tokens = self
            .cached_input_tokens
            .checked_add(other.cached_input_tokens)?;
        let cache_write_input_tokens = self
            .cache_write_input_tokens
            .checked_add(other.cache_write_input_tokens)?;
        let output_tokens = self.output_tokens.checked_add(other.output_tokens)?;
        let reasoning_output_tokens = self
            .reasoning_output_tokens
            .checked_add(other.reasoning_output_tokens)?;
        let total_tokens = self.total_tokens.checked_add(other.total_tokens)?;
        *self = Self {
            input_tokens,
            cached_input_tokens,
            cache_write_input_tokens,
            output_tokens,
            reasoning_output_tokens,
            total_tokens,
        };
        Some(())
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TokenUsageInfo {
    pub total_token_usage: TokenUsage,
    pub last_token_usage: TokenUsage,
    pub model_context_window: Option<i64>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TokenCountEvent {
    pub info: Option<TokenUsageInfo>,
    pub rate_limits: Option<serde_json::Value>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct WebSearchBeginEvent {
    pub call_id: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct WebSearchEndEvent {
    pub call_id: String,
    pub query: Option<String>,
    pub action: String,
}

#[cfg(test)]
mod tests {
    use serde_json::json;

    use super::*;

    #[test]
    fn middleware_settings_have_a_generic_wire_shape() {
        let feature = MiddlewareFeature {
            id: "example".into(),
            label: "Example".into(),
            description: "Example capability".into(),
            required: false,
            settings: vec![FrontendSetting {
                id: "limit".into(),
                label: "Limit".into(),
                description: "Example limit".into(),
                kind: FrontendSettingKind::Integer {
                    min: 1,
                    max: None,
                    step: 10,
                },
            }],
        };

        assert_eq!(
            serde_json::to_value(feature).expect("serialize middleware setting"),
            json!({
                "id": "example",
                "label": "Example",
                "description": "Example capability",
                "required": false,
                "settings": [{
                    "id": "limit",
                    "label": "Limit",
                    "description": "Example limit",
                    "type": "integer",
                    "min": 1,
                    "step": 10
                }]
            })
        );
    }

    #[test]
    fn session_configured_has_a_stable_wire_shape() {
        let event = EventMsg::SessionConfigured(SessionConfiguredEvent {
            session_id: "session-1".into(),
            context: SessionContext {
                tenant_id: Some("tenant-1".into()),
                user_id: Some("user-1".into()),
                user_name: Some("Ada".into()),
                workspace_id: Some("workspace-1".into()),
                workspace_label: Some("Project One".into()),
                origin_label: Some("cron".into()),
            },
            model: ModelChangedEvent {
                route: "default".into(),
                model: "test-model".into(),
                reasoning_effort: Some("high".into()),
                model_context_window: Some(128_000),
            },
        });

        assert_eq!(
            serde_json::to_value(event).expect("serialize session event"),
            json!({
                "type": "session_configured",
                "session_id": "session-1",
                "context": {
                    "tenant_id": "tenant-1",
                    "user_id": "user-1",
                    "user_name": "Ada",
                    "workspace_id": "workspace-1",
                    "workspace_label": "Project One",
                    "origin_label": "cron"
                },
                "model": {
                    "route": "default",
                    "model": "test-model",
                    "reasoning_effort": "high",
                    "model_context_window": 128_000
                }
            })
        );
    }

    #[test]
    fn session_resume_request_carries_the_target_context() {
        let event = EventMsg::SessionResumeRequested(SessionResumeRequestedEvent {
            session_id: "session-2".into(),
            context: SessionContext {
                workspace_label: Some("Project Two".into()),
                origin_label: Some("cron".into()),
                ..SessionContext::default()
            },
        });

        assert_eq!(
            serde_json::to_value(event).expect("serialize resume event"),
            json!({
                "type": "session_resume_requested",
                "session_id": "session-2",
                "context": {
                    "workspace_label": "Project Two",
                    "origin_label": "cron"
                }
            })
        );
    }

    #[test]
    fn frontend_event_has_a_distinct_nested_discriminator() {
        let event = EventMsg::Frontend(FrontendEvent::Widget {
            capability: "subagents".into(),
            item: FrontendWidget {
                id: "status".into(),
                slot: FrontendSlot::ComposerHeader,
                text: "2 agents".into(),
                tone: FrontendTone::Neutral,
                symbol: Some(FrontendSymbol::Agent),
                icon_only: true,
                progress: None,
                content: None,
                action: None,
            },
        });
        let value = serde_json::to_value(&event).expect("serialize frontend event");

        assert_eq!(value["type"], "frontend");
        assert_eq!(value["frontend_type"], "widget");
        assert_eq!(
            serde_json::from_value::<EventMsg>(value).expect("deserialize frontend event"),
            event
        );
    }

    #[test]
    fn capability_surface_slots_have_stable_wire_names() {
        assert_eq!(
            serde_json::to_value(FrontendSlot::Navigation).expect("navigation slot"),
            json!("navigation")
        );
        assert_eq!(
            serde_json::to_value(FrontendSlot::ChatMenu).expect("chat menu slot"),
            json!("chat_menu")
        );
        assert_eq!(
            serde_json::to_value(FrontendSlot::TranscriptTail).expect("transcript tail slot"),
            json!("transcript_tail")
        );
    }

    #[test]
    fn interrupt_has_a_targeted_wire_shape() {
        let submission = Submission {
            id: "cancel-1".into(),
            op: Op::Interrupt {
                turn_id: "turn-1".into(),
            },
        };

        assert_eq!(
            serde_json::to_value(submission).expect("serialize interrupt"),
            json!({
                "id": "cancel-1",
                "op": {
                    "type": "interrupt",
                    "turn_id": "turn-1"
                }
            })
        );
    }

    #[test]
    fn user_input_has_one_text_payload() {
        let submission = Submission {
            id: "input-1".into(),
            op: Op::UserInput {
                text: "hello".into(),
                attachments: Vec::new(),
            },
        };

        assert_eq!(
            serde_json::to_value(submission).expect("serialize input"),
            json!({
                "id": "input-1",
                "op": {
                    "type": "user_input",
                    "text": "hello",
                    "attachments": []
                }
            })
        );
    }

    #[test]
    fn system_event_omits_submission_correlation() {
        let event = Event {
            submission_id: None,
            msg: EventMsg::Warning(WarningEvent {
                message: "system notice".into(),
            }),
        };

        assert_eq!(
            serde_json::to_value(event).expect("serialize system event"),
            json!({
                "msg": {
                    "type": "warning",
                    "message": "system notice"
                }
            })
        );
    }

    #[test]
    fn context_compacted_is_a_unit_event() {
        assert_eq!(
            serde_json::to_value(EventMsg::ContextCompacted).expect("serialize compaction"),
            json!({"type": "context_compacted"})
        );
    }

    #[test]
    fn token_usage_overflow_does_not_partially_update_the_total() {
        let mut total = TokenUsage {
            input_tokens: 7,
            total_tokens: i64::MAX,
            ..TokenUsage::default()
        };
        let original = total.clone();

        assert!(
            total
                .checked_add(&TokenUsage {
                    input_tokens: 1,
                    total_tokens: 1,
                    ..TokenUsage::default()
                })
                .is_none()
        );
        assert_eq!(total, original);
    }

    #[test]
    fn symbols_round_trip_and_keep_unknown_names() {
        for symbol in [
            FrontendSymbol::Agent,
            FrontendSymbol::Brain,
            FrontendSymbol::Branch,
            FrontendSymbol::Chat,
            FrontendSymbol::ChatGpt,
            FrontendSymbol::Claude,
            FrontendSymbol::Deepseek,
            FrontendSymbol::Delete,
            FrontendSymbol::Edit,
            FrontendSymbol::Kimi,
            FrontendSymbol::Moon,
            FrontendSymbol::Promote,
            FrontendSymbol::Route,
            FrontendSymbol::Search,
            FrontendSymbol::Sparkle,
            FrontendSymbol::Storage,
            FrontendSymbol::Task,
        ] {
            let json = serde_json::to_string(&symbol).expect("symbol serializes");
            assert_eq!(json, format!("\"{}\"", symbol.as_str()));
            let decoded: FrontendSymbol = serde_json::from_str(&json).expect("symbol deserializes");
            assert_eq!(decoded, symbol);
        }

        // A name this build has never heard of survives instead of failing the frame.
        let custom: FrontendSymbol =
            serde_json::from_str("\"telescope\"").expect("unknown symbol deserializes");
        assert_eq!(custom, FrontendSymbol::Custom("telescope".into()));
        assert_eq!(custom.as_str(), "telescope");

        // A known name never lingers as a `Custom` once it has crossed the wire, so the two
        // spellings of one glyph cannot compare unequal.
        let normalized: FrontendSymbol = serde_json::from_str(
            &serde_json::to_string(&FrontendSymbol::Custom("edit".into()))
                .expect("custom serializes"),
        )
        .expect("custom deserializes");
        assert_eq!(normalized, FrontendSymbol::Edit);
    }
}