everruns-sdk 0.1.7

Rust SDK for Everruns API
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
//! Data models for Everruns API
//!
//! These types represent the request and response objects used by the API.

use serde::{Deserialize, Serialize};

/// Per-agent capability configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct AgentCapabilityConfig {
    /// Reference to the capability ID
    #[serde(rename = "ref")]
    pub capability_ref: String,
    /// Per-agent configuration for this capability (capability-specific)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub config: Option<serde_json::Value>,
}

impl AgentCapabilityConfig {
    /// Create a new capability config with just a ref
    pub fn new(capability_ref: impl Into<String>) -> Self {
        Self {
            capability_ref: capability_ref.into(),
            config: None,
        }
    }

    /// Set the config
    pub fn config(mut self, config: serde_json::Value) -> Self {
        self.config = Some(config);
        self
    }
}

/// Public capability information
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct CapabilityInfo {
    pub id: String,
    pub name: String,
    pub description: String,
    pub status: String,
    #[serde(default)]
    pub category: Option<String>,
    #[serde(default)]
    pub dependencies: Vec<String>,
    #[serde(default)]
    pub icon: Option<String>,
    #[serde(default)]
    pub is_mcp: bool,
    /// Human-readable display name for UI rendering
    #[serde(default)]
    pub display_name: Option<String>,
    /// UI feature strings this capability contributes to
    #[serde(default)]
    pub features: Vec<String>,
    /// Whether this is an Agent Skill capability
    #[serde(default)]
    pub is_skill: bool,
    /// Risk level for approval requirements (TM-AGENT-005)
    #[serde(default)]
    pub risk_level: Option<String>,
}

/// Agent configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Agent {
    pub id: String,
    pub name: String,
    #[serde(default)]
    pub description: Option<String>,
    pub system_prompt: String,
    #[serde(default)]
    pub default_model_id: Option<String>,
    #[serde(default)]
    pub tags: Vec<String>,
    #[serde(default)]
    pub capabilities: Vec<AgentCapabilityConfig>,
    #[serde(default)]
    pub initial_files: Vec<InitialFile>,
    pub status: AgentStatus,
    pub created_at: String,
    pub updated_at: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AgentStatus {
    Active,
    Archived,
}

/// Request to create an agent
#[derive(Debug, Clone, Serialize)]
#[non_exhaustive]
pub struct CreateAgentRequest {
    /// Client-supplied agent ID (format: agent_{32-hex}).
    /// If not provided, one is auto-generated by the server.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    pub name: String,
    pub system_prompt: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub default_model_id: Option<String>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub tags: Vec<String>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub capabilities: Vec<AgentCapabilityConfig>,
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub initial_files: Vec<InitialFile>,
}

impl CreateAgentRequest {
    /// Create a new request with required fields
    pub fn new(name: impl Into<String>, system_prompt: impl Into<String>) -> Self {
        Self {
            id: None,
            name: name.into(),
            system_prompt: system_prompt.into(),
            description: None,
            default_model_id: None,
            tags: vec![],
            capabilities: vec![],
            initial_files: vec![],
        }
    }

    /// Set a client-supplied agent ID
    pub fn id(mut self, id: impl Into<String>) -> Self {
        self.id = Some(id.into());
        self
    }

    /// Set the description
    pub fn description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }

    /// Set the default model ID
    pub fn default_model_id(mut self, model_id: impl Into<String>) -> Self {
        self.default_model_id = Some(model_id.into());
        self
    }

    /// Set the tags
    pub fn tags(mut self, tags: Vec<String>) -> Self {
        self.tags = tags;
        self
    }

    /// Set the capabilities
    pub fn capabilities(mut self, capabilities: Vec<AgentCapabilityConfig>) -> Self {
        self.capabilities = capabilities;
        self
    }

    /// Set the starter files copied into each new session for this agent
    pub fn initial_files(mut self, initial_files: Vec<InitialFile>) -> Self {
        self.initial_files = initial_files;
        self
    }
}

/// Generate a random agent ID in the format `agent_<32-hex>`.
pub fn generate_agent_id() -> String {
    let mut bytes = [0u8; 16];
    getrandom::getrandom(&mut bytes).expect("failed to generate random bytes");
    let hex: String = bytes.iter().map(|b| format!("{:02x}", b)).collect();
    format!("agent_{}", hex)
}

/// Generate a random harness ID in the format `harness_<32-hex>`.
pub fn generate_harness_id() -> String {
    let mut bytes = [0u8; 16];
    getrandom::getrandom(&mut bytes).expect("failed to generate random bytes");
    let hex: String = bytes.iter().map(|b| format!("{:02x}", b)).collect();
    format!("harness_{}", hex)
}

/// Session representing an active conversation
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Session {
    pub id: String,
    pub organization_id: String,
    pub harness_id: String,
    #[serde(default)]
    pub agent_id: Option<String>,
    #[serde(default)]
    pub title: Option<String>,
    #[serde(default)]
    pub tags: Vec<String>,
    #[serde(default)]
    pub locale: Option<String>,
    #[serde(default)]
    pub model_id: Option<String>,
    #[serde(default)]
    pub capabilities: Vec<AgentCapabilityConfig>,
    pub status: SessionStatus,
    pub created_at: String,
    pub updated_at: String,
    #[serde(default)]
    pub usage: Option<TokenUsage>,
    /// Number of active (enabled) schedules for this session
    #[serde(default)]
    pub active_schedule_count: Option<i32>,
    /// Aggregated UI features from all active capabilities
    #[serde(default)]
    pub features: Vec<String>,
    /// Whether this session is pinned by the current user
    #[serde(default)]
    pub is_pinned: Option<bool>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SessionStatus {
    Started,
    Active,
    Idle,
    #[serde(rename = "waitingfortoolresults")]
    WaitingForToolResults,
}

/// Token usage statistics
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct TokenUsage {
    #[serde(default)]
    pub input_tokens: u64,
    #[serde(default)]
    pub output_tokens: u64,
    #[serde(default)]
    pub cache_read_tokens: u64,
}

/// Starter file copied into a new session workspace
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct InitialFile {
    pub path: String,
    pub content: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub encoding: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub is_readonly: Option<bool>,
}

impl InitialFile {
    /// Create a new initial file with required fields
    pub fn new(path: impl Into<String>, content: impl Into<String>) -> Self {
        Self {
            path: path.into(),
            content: content.into(),
            encoding: None,
            is_readonly: None,
        }
    }

    /// Set the content encoding
    pub fn encoding(mut self, encoding: impl Into<String>) -> Self {
        self.encoding = Some(encoding.into());
        self
    }

    /// Set the readonly flag
    pub fn is_readonly(mut self, is_readonly: bool) -> Self {
        self.is_readonly = Some(is_readonly);
        self
    }
}

/// Request to create a session
#[derive(Debug, Clone, Serialize)]
#[non_exhaustive]
pub struct CreateSessionRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub harness_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub agent_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub locale: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub model_id: Option<String>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub tags: Vec<String>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub capabilities: Vec<AgentCapabilityConfig>,
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub initial_files: Vec<InitialFile>,
}

impl Default for CreateSessionRequest {
    fn default() -> Self {
        Self::new()
    }
}

impl CreateSessionRequest {
    /// Create a new request (server defaults to Generic harness)
    pub fn new() -> Self {
        Self {
            harness_id: None,
            agent_id: None,
            title: None,
            locale: None,
            model_id: None,
            tags: vec![],
            capabilities: vec![],
            initial_files: vec![],
        }
    }

    /// Set the harness ID
    pub fn harness_id(mut self, harness_id: impl Into<String>) -> Self {
        self.harness_id = Some(harness_id.into());
        self
    }

    /// Set the agent ID
    pub fn agent_id(mut self, agent_id: impl Into<String>) -> Self {
        self.agent_id = Some(agent_id.into());
        self
    }

    /// Set the session title
    pub fn title(mut self, title: impl Into<String>) -> Self {
        self.title = Some(title.into());
        self
    }

    /// Set the session locale
    pub fn locale(mut self, locale: impl Into<String>) -> Self {
        self.locale = Some(locale.into());
        self
    }

    /// Set the model ID
    pub fn model_id(mut self, model_id: impl Into<String>) -> Self {
        self.model_id = Some(model_id.into());
        self
    }

    /// Set the tags
    pub fn tags(mut self, tags: Vec<String>) -> Self {
        self.tags = tags;
        self
    }

    /// Set the capabilities
    pub fn capabilities(mut self, capabilities: Vec<AgentCapabilityConfig>) -> Self {
        self.capabilities = capabilities;
        self
    }

    /// Set the initial files copied into the session workspace
    pub fn initial_files(mut self, initial_files: Vec<InitialFile>) -> Self {
        self.initial_files = initial_files;
        self
    }
}

/// External actor identity for messages from external channels (Slack, Discord, etc.)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ExternalActor {
    /// Opaque actor identifier from the source channel
    pub actor_id: String,
    /// Source channel identifier (e.g. "slack", "discord")
    pub source: String,
    /// Resolved display name (falls back to actor_id if absent)
    #[serde(default)]
    pub actor_name: Option<String>,
    /// Channel-specific metadata
    #[serde(default)]
    pub metadata: Option<std::collections::HashMap<String, String>>,
}

impl ExternalActor {
    /// Create a new ExternalActor with required fields
    pub fn new(actor_id: impl Into<String>, source: impl Into<String>) -> Self {
        Self {
            actor_id: actor_id.into(),
            source: source.into(),
            actor_name: None,
            metadata: None,
        }
    }

    /// Set the display name
    pub fn actor_name(mut self, name: impl Into<String>) -> Self {
        self.actor_name = Some(name.into());
        self
    }

    /// Set metadata
    pub fn metadata(mut self, metadata: std::collections::HashMap<String, String>) -> Self {
        self.metadata = Some(metadata);
        self
    }
}

/// Message in a session
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Message {
    pub id: String,
    pub session_id: String,
    pub sequence: u64,
    pub role: MessageRole,
    pub content: Vec<ContentPart>,
    #[serde(default)]
    pub thinking: Option<String>,
    #[serde(default)]
    pub tags: Vec<String>,
    pub created_at: String,
    /// External actor identity (for messages from external channels)
    #[serde(default)]
    pub external_actor: Option<ExternalActor>,
    /// Execution phase for multi-step tool-calling flows
    #[serde(default)]
    pub phase: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MessageRole {
    User,
    Agent,
    ToolResult,
}

/// Content part within a message
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ContentPart {
    Text {
        text: String,
    },
    Image {
        url: Option<String>,
        base64: Option<String>,
    },
    ImageFile {
        image_id: String,
    },
    ToolCall {
        id: String,
        name: String,
        arguments: serde_json::Value,
    },
    ToolResult {
        tool_call_id: String,
        result: Option<serde_json::Value>,
        error: Option<String>,
    },
}

impl ContentPart {
    /// Create a text content part
    pub fn text(text: impl Into<String>) -> Self {
        Self::Text { text: text.into() }
    }

    /// Create a tool result content part with a successful result
    pub fn tool_result(tool_call_id: impl Into<String>, result: serde_json::Value) -> Self {
        Self::ToolResult {
            tool_call_id: tool_call_id.into(),
            result: Some(result),
            error: None,
        }
    }

    /// Create a tool result content part with an error
    pub fn tool_error(tool_call_id: impl Into<String>, error: impl Into<String>) -> Self {
        Self::ToolResult {
            tool_call_id: tool_call_id.into(),
            result: None,
            error: Some(error.into()),
        }
    }

    /// Returns true if this is a tool call content part
    pub fn is_tool_call(&self) -> bool {
        matches!(self, Self::ToolCall { .. })
    }

    /// Extract tool call info if this is a tool call content part
    pub fn as_tool_call(&self) -> Option<ToolCallInfo<'_>> {
        match self {
            Self::ToolCall {
                id,
                name,
                arguments,
            } => Some(ToolCallInfo {
                id,
                name,
                arguments,
            }),
            _ => None,
        }
    }
}

/// Borrowed view of a tool call content part
#[derive(Debug, Clone)]
pub struct ToolCallInfo<'a> {
    pub id: &'a str,
    pub name: &'a str,
    pub arguments: &'a serde_json::Value,
}

/// Request to create a message
#[derive(Debug, Clone, Serialize)]
#[non_exhaustive]
pub struct CreateMessageRequest {
    pub message: MessageInput,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub controls: Option<Controls>,
    /// External actor identity (for messages from external channels like Slack)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub external_actor: Option<ExternalActor>,
}

impl CreateMessageRequest {
    /// Create a new request with message input
    pub fn new(message: MessageInput) -> Self {
        Self {
            message,
            controls: None,
            external_actor: None,
        }
    }

    /// Create a user text message
    pub fn user_text(text: impl Into<String>) -> Self {
        Self::new(MessageInput::user_text(text))
    }

    /// Create a tool result message containing one or more tool results
    pub fn tool_results(results: Vec<ContentPart>) -> Self {
        Self::new(MessageInput::tool_results(results))
    }

    /// Set the controls
    pub fn controls(mut self, controls: Controls) -> Self {
        self.controls = Some(controls);
        self
    }

    /// Set the external actor identity
    pub fn external_actor(mut self, actor: ExternalActor) -> Self {
        self.external_actor = Some(actor);
        self
    }
}

/// Input for creating a message
#[derive(Debug, Clone, Serialize)]
#[non_exhaustive]
pub struct MessageInput {
    pub role: MessageRole,
    pub content: Vec<ContentPart>,
}

impl MessageInput {
    /// Create a new message input
    pub fn new(role: MessageRole, content: Vec<ContentPart>) -> Self {
        Self { role, content }
    }

    /// Create a user text message
    pub fn user_text(text: impl Into<String>) -> Self {
        Self::new(
            MessageRole::User,
            vec![ContentPart::Text { text: text.into() }],
        )
    }

    /// Create a tool result message containing one or more tool results
    pub fn tool_results(results: Vec<ContentPart>) -> Self {
        Self::new(MessageRole::ToolResult, results)
    }
}

/// Controls for message generation
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Controls {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub model_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_tokens: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub temperature: Option<f32>,
}

impl Default for Controls {
    fn default() -> Self {
        Self::new()
    }
}

impl Controls {
    /// Create new empty controls
    pub fn new() -> Self {
        Self {
            model_id: None,
            max_tokens: None,
            temperature: None,
        }
    }

    /// Set the model ID
    pub fn model_id(mut self, model_id: impl Into<String>) -> Self {
        self.model_id = Some(model_id.into());
        self
    }

    /// Set the max tokens
    pub fn max_tokens(mut self, max_tokens: u32) -> Self {
        self.max_tokens = Some(max_tokens);
        self
    }

    /// Set the temperature
    pub fn temperature(mut self, temperature: f32) -> Self {
        self.temperature = Some(temperature);
        self
    }
}

/// Paginated list response
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ListResponse<T> {
    pub data: Vec<T>,
    #[serde(default)]
    pub total: u64,
    #[serde(default)]
    pub offset: u64,
    #[serde(default)]
    pub limit: u64,
}

/// SSE Event from the server
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Event {
    pub id: String,
    #[serde(rename = "type")]
    pub event_type: String,
    pub ts: String,
    pub session_id: String,
    pub data: serde_json::Value,
    #[serde(default)]
    pub context: EventContext,
}

impl Event {
    /// Extract tool calls from an `output.message.completed` event's data.
    ///
    /// Returns tool call content parts found in `data.message.content`.
    pub fn tool_calls(&self) -> Vec<ToolCallInfo<'_>> {
        extract_tool_calls(&self.data)
    }
}

/// Extract tool call info from event data (`data.message.content`).
pub fn extract_tool_calls(data: &serde_json::Value) -> Vec<ToolCallInfo<'_>> {
    let Some(content) = data
        .get("message")
        .and_then(|m| m.get("content"))
        .and_then(|c| c.as_array())
    else {
        return vec![];
    };
    content
        .iter()
        .filter_map(|part| {
            if part.get("type")?.as_str()? != "tool_call" {
                return None;
            }
            Some(ToolCallInfo {
                id: part.get("id")?.as_str()?,
                name: part.get("name")?.as_str()?,
                arguments: part.get("arguments")?,
            })
        })
        .collect()
}

/// Context for an event
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[non_exhaustive]
pub struct EventContext {
    #[serde(default)]
    pub turn_id: Option<String>,
    #[serde(default)]
    pub input_message_id: Option<String>,
}

// --- Session Filesystem Models ---

/// File metadata without content
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct FileInfo {
    pub id: String,
    pub session_id: String,
    pub path: String,
    pub name: String,
    pub is_directory: bool,
    pub is_readonly: bool,
    pub size_bytes: i64,
    pub created_at: String,
    pub updated_at: String,
}

/// Complete file with content
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct SessionFile {
    pub id: String,
    pub session_id: String,
    pub path: String,
    pub name: String,
    pub is_directory: bool,
    pub is_readonly: bool,
    pub size_bytes: i64,
    pub created_at: String,
    pub updated_at: String,
    #[serde(default)]
    pub content: Option<String>,
    #[serde(default)]
    pub encoding: Option<String>,
}

/// File stat information (without id/session_id)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct FileStat {
    pub path: String,
    pub name: String,
    pub is_directory: bool,
    pub is_readonly: bool,
    pub size_bytes: i64,
    pub created_at: String,
    pub updated_at: String,
}

/// Request to create a file or directory
#[derive(Debug, Clone, Serialize)]
#[non_exhaustive]
pub struct CreateFileRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub encoding: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub is_directory: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub is_readonly: Option<bool>,
}

impl CreateFileRequest {
    /// Create a request for a new file
    pub fn file(content: impl Into<String>) -> Self {
        Self {
            content: Some(content.into()),
            encoding: None,
            is_directory: None,
            is_readonly: None,
        }
    }

    /// Create a request for a new directory
    pub fn directory() -> Self {
        Self {
            content: None,
            encoding: None,
            is_directory: Some(true),
            is_readonly: None,
        }
    }

    /// Set the content encoding ("text" or "base64")
    pub fn encoding(mut self, encoding: impl Into<String>) -> Self {
        self.encoding = Some(encoding.into());
        self
    }

    /// Set the readonly flag
    pub fn is_readonly(mut self, is_readonly: bool) -> Self {
        self.is_readonly = Some(is_readonly);
        self
    }
}

/// Request to update a file
#[derive(Debug, Clone, Serialize)]
#[non_exhaustive]
pub struct UpdateFileRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub encoding: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub is_readonly: Option<bool>,
}

impl UpdateFileRequest {
    /// Create a request to update file content
    pub fn content(content: impl Into<String>) -> Self {
        Self {
            content: Some(content.into()),
            encoding: None,
            is_readonly: None,
        }
    }

    /// Set the content encoding ("text" or "base64")
    pub fn encoding(mut self, encoding: impl Into<String>) -> Self {
        self.encoding = Some(encoding.into());
        self
    }

    /// Set the readonly flag
    pub fn is_readonly(mut self, is_readonly: bool) -> Self {
        self.is_readonly = Some(is_readonly);
        self
    }
}

/// Request to copy a file
#[derive(Debug, Clone, Serialize)]
pub struct CopyFileRequest {
    pub src_path: String,
    pub dst_path: String,
}

impl CopyFileRequest {
    pub fn new(src_path: impl Into<String>, dst_path: impl Into<String>) -> Self {
        Self {
            src_path: src_path.into(),
            dst_path: dst_path.into(),
        }
    }
}

/// Request to move/rename a file
#[derive(Debug, Clone, Serialize)]
pub struct MoveFileRequest {
    pub src_path: String,
    pub dst_path: String,
}

impl MoveFileRequest {
    pub fn new(src_path: impl Into<String>, dst_path: impl Into<String>) -> Self {
        Self {
            src_path: src_path.into(),
            dst_path: dst_path.into(),
        }
    }
}

/// Request to search files with regex
#[derive(Debug, Clone, Serialize)]
pub struct GrepRequest {
    pub pattern: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub path_pattern: Option<String>,
}

impl GrepRequest {
    pub fn new(pattern: impl Into<String>) -> Self {
        Self {
            pattern: pattern.into(),
            path_pattern: None,
        }
    }

    /// Set an optional path pattern to filter files
    pub fn path_pattern(mut self, path_pattern: impl Into<String>) -> Self {
        self.path_pattern = Some(path_pattern.into());
        self
    }
}

/// Request to get file stat
#[derive(Debug, Clone, Serialize)]
pub struct StatRequest {
    pub path: String,
}

impl StatRequest {
    pub fn new(path: impl Into<String>) -> Self {
        Self { path: path.into() }
    }
}

/// Single grep match
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct GrepMatch {
    pub path: String,
    pub line_number: u64,
    pub line: String,
}

/// Grep result for a file
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct GrepResult {
    pub path: String,
    pub matches: Vec<GrepMatch>,
}

/// Response for delete operations
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DeleteResponse {
    pub deleted: bool,
}

// --- Budget Models ---

/// Budget status
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum BudgetStatus {
    Active,
    Paused,
    Exhausted,
    Disabled,
}

/// Budget period configuration for recurring budgets
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum BudgetPeriod {
    /// Rolling window (e.g. "last 24 hours")
    Rolling { window: String },
    /// Calendar-aligned (e.g. "per month")
    Calendar { unit: String },
}

/// Budget — a spending cap for a subject in a currency
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Budget {
    pub id: String,
    pub organization_id: String,
    pub subject_type: String,
    pub subject_id: String,
    pub currency: String,
    pub limit: f64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub soft_limit: Option<f64>,
    pub balance: f64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub period: Option<BudgetPeriod>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub metadata: Option<serde_json::Value>,
    pub status: BudgetStatus,
    pub created_at: String,
    pub updated_at: String,
}

/// Request to create a budget
#[derive(Debug, Clone, Serialize)]
#[non_exhaustive]
pub struct CreateBudgetRequest {
    pub subject_type: String,
    pub subject_id: String,
    pub currency: String,
    pub limit: f64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub soft_limit: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub period: Option<BudgetPeriod>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<serde_json::Value>,
}

impl CreateBudgetRequest {
    /// Create a new budget request with required fields
    pub fn new(
        subject_type: impl Into<String>,
        subject_id: impl Into<String>,
        currency: impl Into<String>,
        limit: f64,
    ) -> Self {
        Self {
            subject_type: subject_type.into(),
            subject_id: subject_id.into(),
            currency: currency.into(),
            limit,
            soft_limit: None,
            period: None,
            metadata: None,
        }
    }

    /// Set the soft limit
    pub fn soft_limit(mut self, soft_limit: f64) -> Self {
        self.soft_limit = Some(soft_limit);
        self
    }

    /// Set the period
    pub fn period(mut self, period: BudgetPeriod) -> Self {
        self.period = Some(period);
        self
    }

    /// Set metadata
    pub fn metadata(mut self, metadata: serde_json::Value) -> Self {
        self.metadata = Some(metadata);
        self
    }
}

/// Request to update a budget
#[derive(Debug, Clone, Serialize)]
#[non_exhaustive]
pub struct UpdateBudgetRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub soft_limit: Option<Option<f64>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<serde_json::Value>,
}

impl UpdateBudgetRequest {
    /// Create a new empty update request
    pub fn new() -> Self {
        Self {
            limit: None,
            soft_limit: None,
            status: None,
            metadata: None,
        }
    }

    /// Set the limit
    pub fn limit(mut self, limit: f64) -> Self {
        self.limit = Some(limit);
        self
    }

    /// Set the soft limit (None to remove)
    pub fn soft_limit(mut self, soft_limit: Option<f64>) -> Self {
        self.soft_limit = Some(soft_limit);
        self
    }

    /// Set the status
    pub fn status(mut self, status: impl Into<String>) -> Self {
        self.status = Some(status.into());
        self
    }

    /// Set metadata
    pub fn metadata(mut self, metadata: serde_json::Value) -> Self {
        self.metadata = Some(metadata);
        self
    }
}

impl Default for UpdateBudgetRequest {
    fn default() -> Self {
        Self::new()
    }
}

/// Request to top up a budget
#[derive(Debug, Clone, Serialize)]
pub struct TopUpRequest {
    pub amount: f64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

impl TopUpRequest {
    /// Create a new top-up request
    pub fn new(amount: f64) -> Self {
        Self {
            amount,
            description: None,
        }
    }

    /// Set the description
    pub fn description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }
}

/// Ledger entry recording resource consumption or credit
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct LedgerEntry {
    pub id: String,
    pub budget_id: String,
    pub amount: f64,
    pub meter_source: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ref_type: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ref_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub session_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    pub created_at: String,
}

/// Result of checking all budgets for a session
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct BudgetCheckResult {
    pub action: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub budget_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub balance: Option<f64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub currency: Option<String>,
}

/// Response from session resume endpoint
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResumeSessionResponse {
    pub resumed_budgets: i32,
    pub session_id: String,
}

// --- Connections Models ---

/// A user connection to an external provider
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Connection {
    pub provider: String,
    pub created_at: String,
    pub updated_at: String,
}

/// Request to set a connection API key
#[derive(Debug, Clone, Serialize)]
pub struct SetConnectionRequest {
    pub api_key: String,
}

impl SetConnectionRequest {
    pub fn new(api_key: impl Into<String>) -> Self {
        Self {
            api_key: api_key.into(),
        }
    }
}

// --- Session Secrets Models ---

/// Request to batch-set session secrets
#[derive(Debug, Clone, Serialize)]
pub struct SetSecretsRequest {
    pub secrets: std::collections::HashMap<String, String>,
}

impl SetSecretsRequest {
    pub fn new(secrets: std::collections::HashMap<String, String>) -> Self {
        Self { secrets }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn list_response_deserializes_without_pagination_fields() {
        let json = r#"{"data": [1, 2, 3]}"#;
        let resp: ListResponse<i32> = serde_json::from_str(json).unwrap();
        assert_eq!(resp.data, vec![1, 2, 3]);
        assert_eq!(resp.total, 0);
        assert_eq!(resp.offset, 0);
        assert_eq!(resp.limit, 0);
    }

    #[test]
    fn list_response_deserializes_with_pagination_fields() {
        let json = r#"{"data": ["a"], "total": 10, "offset": 5, "limit": 25}"#;
        let resp: ListResponse<String> = serde_json::from_str(json).unwrap();
        assert_eq!(resp.data, vec!["a"]);
        assert_eq!(resp.total, 10);
        assert_eq!(resp.offset, 5);
        assert_eq!(resp.limit, 25);
    }
}