distri-types 0.3.8

Shared message, tool, and config types for Distri
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
use crate::connections::{Connection, ConnectionStatus, ConnectionToken, NewConnection};
use crate::{ScratchpadEntry, ToolAuthStore, ToolResponse};
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use serde_json::Value;
use std::{collections::HashMap, sync::Arc};
use tokio::sync::oneshot;
use utoipa::ToSchema;
use uuid::Uuid;

use crate::{
    AgentEvent, CreateThreadRequest, Message, Task, TaskMessage, TaskStatus, Thread,
    UpdateThreadRequest,
};

// Redis and PostgreSQL stores moved to distri-stores crate

/// Filter for listing threads
#[derive(Debug, Clone, Default, Serialize, Deserialize, ToSchema, JsonSchema)]
pub struct ThreadListFilter {
    /// Filter by agent ID
    pub agent_id: Option<String>,
    /// Filter by external ID (for integration with external systems)
    pub external_id: Option<String>,
    /// Filter by thread attributes (JSON matching)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub attributes: Option<serde_json::Value>,
    /// Full-text search across title and last_message
    pub search: Option<String>,
    /// Filter threads updated after this time
    pub from_date: Option<DateTime<Utc>>,
    /// Filter threads updated before this time
    pub to_date: Option<DateTime<Utc>>,
    /// Filter by tags (array of tag strings to match)
    pub tags: Option<Vec<String>>,
}

/// Paginated response for thread listing
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, JsonSchema)]
pub struct ThreadListResponse {
    pub threads: Vec<crate::ThreadSummary>,
    pub total: i64,
    pub page: u32,
    pub page_size: u32,
}

/// Agent usage information for sorting agents by thread count
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, JsonSchema)]
pub struct AgentUsageInfo {
    pub agent_id: String,
    pub agent_name: String,
    pub thread_count: i64,
}

/// Initialized store collection
#[derive(Clone)]
pub struct InitializedStores {
    pub session_store: Arc<dyn SessionStore>,
    pub agent_store: Arc<dyn AgentStore>,
    pub task_store: Arc<dyn TaskStore>,
    pub thread_store: Arc<dyn ThreadStore>,
    pub tool_auth_store: Arc<dyn ToolAuthStore>,
    pub scratchpad_store: Arc<dyn ScratchpadStore>,
    pub memory_store: Option<Arc<dyn MemoryStore>>,
    pub crawl_store: Option<Arc<dyn CrawlStore>>,
    pub external_tool_calls_store: Arc<dyn ExternalToolCallsStore>,
    pub prompt_template_store: Option<Arc<dyn PromptTemplateStore>>,
    pub secret_store: Option<Arc<dyn SecretStore>>,
    pub skill_store: Option<Arc<dyn SkillStore>>,
    pub connection_store: Option<Arc<dyn ConnectionStore>>,
    pub connection_token_store: Option<Arc<dyn ConnectionTokenStore>>,
    pub provider_registry: Option<Arc<dyn crate::auth::ProviderRegistry>>,
}
impl InitializedStores {
    pub fn set_tool_auth_store(&mut self, tool_auth_store: Arc<dyn ToolAuthStore>) {
        self.tool_auth_store = tool_auth_store;
    }

    pub fn set_external_tool_calls_store(mut self, store: Arc<dyn ExternalToolCallsStore>) {
        self.external_tool_calls_store = store;
    }

    pub fn set_session_store(&mut self, session_store: Arc<dyn SessionStore>) {
        self.session_store = session_store;
    }

    pub fn set_agent_store(&mut self, agent_store: Arc<dyn AgentStore>) {
        self.agent_store = agent_store;
    }

    pub fn with_task_store(&mut self, task_store: Arc<dyn TaskStore>) {
        self.task_store = task_store;
    }

    pub fn with_thread_store(&mut self, thread_store: Arc<dyn ThreadStore>) {
        self.thread_store = thread_store;
    }

    pub fn with_scratchpad_store(&mut self, scratchpad_store: Arc<dyn ScratchpadStore>) {
        self.scratchpad_store = scratchpad_store;
    }
}

impl std::fmt::Debug for InitializedStores {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("InitializedStores").finish()
    }
}

#[derive(Debug, Serialize, Deserialize, Clone, ToSchema, JsonSchema)]
pub struct SessionSummary {
    pub session_id: String,
    pub keys: Vec<String>,
    pub key_count: usize,
    pub updated_at: Option<DateTime<Utc>>,
}

// SessionStore trait - manages current conversation thread/run
#[async_trait::async_trait]
pub trait SessionStore: Send + Sync + std::fmt::Debug {
    async fn clear_session(&self, namespace: &str) -> anyhow::Result<()>;

    async fn set_value(&self, namespace: &str, key: &str, value: &Value) -> anyhow::Result<()>;

    async fn set_value_with_expiry(
        &self,
        namespace: &str,
        key: &str,
        value: &Value,
        expiry: Option<chrono::DateTime<chrono::Utc>>,
    ) -> anyhow::Result<()>;

    async fn get_value(&self, namespace: &str, key: &str) -> anyhow::Result<Option<Value>>;

    async fn delete_value(&self, namespace: &str, key: &str) -> anyhow::Result<()>;

    async fn get_all_values(&self, namespace: &str) -> anyhow::Result<HashMap<String, Value>>;

    async fn list_sessions(
        &self,
        namespace: Option<&str>,
        limit: Option<usize>,
        offset: Option<usize>,
    ) -> anyhow::Result<Vec<SessionSummary>>;
}
#[async_trait::async_trait]
pub trait SessionStoreExt: SessionStore {
    async fn set<T: Serialize + Sync>(
        &self,
        namespace: &str,
        key: &str,
        value: &T,
    ) -> anyhow::Result<()> {
        self.set_value(namespace, key, &serde_json::to_value(value)?)
            .await
    }
    async fn set_with_expiry<T: Serialize + Sync>(
        &self,
        namespace: &str,
        key: &str,
        value: &T,
        expiry: Option<chrono::DateTime<chrono::Utc>>,
    ) -> anyhow::Result<()> {
        self.set_value_with_expiry(namespace, key, &serde_json::to_value(value)?, expiry)
            .await
    }
    async fn get<T: DeserializeOwned + Sync>(
        &self,
        namespace: &str,
        key: &str,
    ) -> anyhow::Result<Option<T>> {
        match self.get_value(namespace, key).await? {
            Some(b) => Ok(Some(serde_json::from_value(b)?)),
            None => Ok(None),
        }
    }
}
impl<T: SessionStore + ?Sized> SessionStoreExt for T {}

// Higher-level MemoryStore trait - manages cross-session permanent memory using user_id
#[async_trait::async_trait]
pub trait MemoryStore: Send + Sync {
    /// Store permanent memory from a session for cross-session access
    async fn store_memory(
        &self,
        user_id: &str,
        session_memory: SessionMemory,
    ) -> anyhow::Result<()>;

    /// Search for relevant memories across sessions for a user
    async fn search_memories(
        &self,
        user_id: &str,
        query: &str,
        limit: Option<usize>,
    ) -> anyhow::Result<Vec<String>>;

    /// Get all permanent memories for a user
    async fn get_user_memories(&self, user_id: &str) -> anyhow::Result<Vec<String>>;

    /// Clear all memories for a user
    async fn clear_user_memories(&self, user_id: &str) -> anyhow::Result<()>;
}

#[derive(Debug, Clone)]
pub struct SessionMemory {
    pub agent_id: String,
    pub thread_id: String,
    pub session_summary: String,
    pub key_insights: Vec<String>,
    pub important_facts: Vec<String>,
    pub timestamp: chrono::DateTime<chrono::Utc>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, ToSchema, JsonSchema)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum FilterMessageType {
    Events,
    Messages,
    Artifacts,
}

#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, JsonSchema)]
pub struct MessageFilter {
    pub filter: Option<Vec<FilterMessageType>>,
    pub limit: Option<usize>,
    pub offset: Option<usize>,
}

// Task Store trait for A2A task management
#[async_trait]
pub trait TaskStore: Send + Sync {
    fn init_task(
        &self,
        context_id: &str,
        task_id: Option<&str>,
        status: Option<TaskStatus>,
    ) -> Task {
        let task_id = task_id.unwrap_or(&Uuid::new_v4().to_string()).to_string();
        Task {
            id: task_id,
            status: status.unwrap_or(TaskStatus::Pending),
            created_at: chrono::Utc::now().timestamp_millis(),
            updated_at: chrono::Utc::now().timestamp_millis(),
            thread_id: context_id.to_string(),
            parent_task_id: None,
        }
    }
    async fn get_or_create_task(
        &self,
        thread_id: &str,
        task_id: &str,
    ) -> Result<(), anyhow::Error> {
        match self.get_task(task_id).await? {
            Some(task) => task,
            None => {
                self.create_task(thread_id, Some(task_id), Some(TaskStatus::Running))
                    .await?
            }
        };

        Ok(())
    }
    async fn create_task(
        &self,
        context_id: &str,
        task_id: Option<&str>,
        task_status: Option<TaskStatus>,
    ) -> anyhow::Result<Task>;
    async fn get_task(&self, task_id: &str) -> anyhow::Result<Option<Task>>;
    async fn update_task_status(&self, task_id: &str, status: TaskStatus) -> anyhow::Result<()>;
    async fn add_event_to_task(&self, task_id: &str, event: AgentEvent) -> anyhow::Result<()>;
    async fn add_message_to_task(&self, task_id: &str, message: &Message) -> anyhow::Result<()>;
    async fn cancel_task(&self, task_id: &str) -> anyhow::Result<Task>;
    async fn list_tasks(&self, thread_id: Option<&str>) -> anyhow::Result<Vec<Task>>;

    async fn get_history(
        &self,
        thread_id: &str,
        filter: Option<MessageFilter>,
    ) -> anyhow::Result<Vec<(Task, Vec<TaskMessage>)>>;

    async fn update_parent_task(
        &self,
        task_id: &str,
        parent_task_id: Option<&str>,
    ) -> anyhow::Result<()>;
}

// Thread Store trait for thread management
#[async_trait]
pub trait ThreadStore: Send + Sync {
    fn as_any(&self) -> &dyn std::any::Any;
    async fn create_thread(&self, request: CreateThreadRequest) -> anyhow::Result<Thread>;
    async fn get_thread(&self, thread_id: &str) -> anyhow::Result<Option<Thread>>;
    async fn update_thread(
        &self,
        thread_id: &str,
        request: UpdateThreadRequest,
    ) -> anyhow::Result<Thread>;
    async fn delete_thread(&self, thread_id: &str) -> anyhow::Result<()>;

    /// List threads with pagination and filtering
    /// Returns a paginated response with total count
    async fn list_threads(
        &self,
        filter: &ThreadListFilter,
        limit: Option<u32>,
        offset: Option<u32>,
    ) -> anyhow::Result<ThreadListResponse>;

    async fn update_thread_with_message(
        &self,
        thread_id: &str,
        message: &str,
    ) -> anyhow::Result<()>;

    /// Get aggregated home statistics
    async fn get_home_stats(&self) -> anyhow::Result<HomeStats>;

    /// Get agents sorted by thread count (most active first)
    /// Includes all registered agents (even those with 0 threads).
    /// Optionally filters by name using a search string.
    async fn get_agents_by_usage(
        &self,
        search: Option<&str>,
    ) -> anyhow::Result<Vec<AgentUsageInfo>>;

    /// Get a map of agent name -> stats for all agents with activity
    async fn get_agent_stats_map(
        &self,
    ) -> anyhow::Result<std::collections::HashMap<String, AgentStatsInfo>>;

    // ========== Message Read Status Methods ==========

    /// Mark a message as read by the current user
    async fn mark_message_read(
        &self,
        thread_id: &str,
        message_id: &str,
    ) -> anyhow::Result<MessageReadStatus>;

    /// Get read status for a specific message
    async fn get_message_read_status(
        &self,
        thread_id: &str,
        message_id: &str,
    ) -> anyhow::Result<Option<MessageReadStatus>>;

    /// Get read status for all messages in a thread for the current user
    async fn get_thread_read_status(
        &self,
        thread_id: &str,
    ) -> anyhow::Result<Vec<MessageReadStatus>>;

    // ========== Message Voting Methods ==========

    /// Vote on a message (upvote or downvote)
    /// For downvotes, a comment is required
    async fn vote_message(&self, request: VoteMessageRequest) -> anyhow::Result<MessageVote>;

    /// Remove a vote from a message
    async fn remove_vote(&self, thread_id: &str, message_id: &str) -> anyhow::Result<()>;

    /// Get the current user's vote on a message
    async fn get_user_vote(
        &self,
        thread_id: &str,
        message_id: &str,
    ) -> anyhow::Result<Option<MessageVote>>;

    /// Get vote summary for a message (counts + current user's vote)
    async fn get_message_vote_summary(
        &self,
        thread_id: &str,
        message_id: &str,
    ) -> anyhow::Result<MessageVoteSummary>;

    /// Get all votes for a message (admin/analytics use)
    async fn get_message_votes(
        &self,
        thread_id: &str,
        message_id: &str,
    ) -> anyhow::Result<Vec<MessageVote>>;
}

/// Home statistics for dashboard
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, JsonSchema)]
pub struct HomeStats {
    pub total_agents: i64,
    pub total_threads: i64,
    pub total_messages: i64,
    pub avg_run_time_ms: Option<f64>,
    // Cloud-specific fields (optional)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub total_owned_agents: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub total_accessible_agents: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub most_active_agent: Option<MostActiveAgent>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub latest_threads: Option<Vec<LatestThreadInfo>>,
    /// Recently used agents (last 10 by most recent thread activity)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub recently_used_agents: Option<Vec<RecentlyUsedAgent>>,
    /// Custom metrics that can be displayed in the stats overview
    /// Key is the metric name (e.g., "usage"), value is the metric data
    #[serde(skip_serializing_if = "Option::is_none")]
    pub custom_metrics: Option<std::collections::HashMap<String, CustomMetric>>,
}

/// A custom metric for display in the stats overview
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, JsonSchema)]
pub struct CustomMetric {
    /// Display label (e.g., "Monthly Calls")
    pub label: String,
    /// Current value as a string (formatted)
    pub value: String,
    /// Optional helper text below the value
    #[serde(skip_serializing_if = "Option::is_none")]
    pub helper: Option<String>,
    /// Optional limit (for progress display)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<String>,
    /// Optional raw numeric value for calculations
    #[serde(skip_serializing_if = "Option::is_none")]
    pub raw_value: Option<i64>,
    /// Optional raw limit for calculations
    #[serde(skip_serializing_if = "Option::is_none")]
    pub raw_limit: Option<i64>,
}

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, JsonSchema)]
pub struct MostActiveAgent {
    pub id: String,
    pub name: String,
    pub thread_count: i64,
}

/// Agent that was recently used (based on thread activity)
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, JsonSchema)]
pub struct RecentlyUsedAgent {
    pub id: String,
    pub name: String,
    pub description: Option<String>,
    pub last_used_at: chrono::DateTime<chrono::Utc>,
}

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, JsonSchema)]
pub struct LatestThreadInfo {
    pub id: String,
    pub title: String,
    pub agent_id: String,
    pub agent_name: String,
    pub updated_at: chrono::DateTime<chrono::Utc>,
}

/// Agent statistics for display
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize, ToSchema, JsonSchema)]
pub struct AgentStatsInfo {
    pub thread_count: i64,
    pub sub_agent_usage_count: i64,
    pub last_used_at: Option<chrono::DateTime<chrono::Utc>>,
}

#[async_trait]
pub trait AgentStore: Send + Sync {
    async fn list(
        &self,
        cursor: Option<String>,
        limit: Option<usize>,
    ) -> (Vec<crate::configuration::AgentConfig>, Option<String>);

    async fn get(&self, name: &str) -> Option<crate::configuration::AgentConfig>;
    async fn register(&self, config: crate::configuration::AgentConfig) -> anyhow::Result<()>;
    /// Update an existing agent with new definition
    async fn update(&self, config: crate::configuration::AgentConfig) -> anyhow::Result<()>;

    async fn clear(&self) -> anyhow::Result<()>;

    /// Delete an agent by name or ID
    async fn delete(&self, id: &str) -> anyhow::Result<()>;

    /// Get an agent with cloud-specific metadata (id, published, is_owner, etc.)
    /// Default impl returns empty metadata — override in cloud stores.
    async fn get_with_cloud_metadata(
        &self,
        name: &str,
    ) -> Option<(
        crate::configuration::AgentConfig,
        crate::configuration::AgentCloudMetadata,
    )> {
        self.get(name)
            .await
            .map(|c| (c, crate::configuration::AgentCloudMetadata::default()))
    }

    /// List agents with cloud-specific metadata.
    /// Default impl returns empty metadata — override in cloud stores.
    async fn list_with_cloud_metadata(
        &self,
        cursor: Option<String>,
        limit: Option<usize>,
    ) -> (
        Vec<(
            crate::configuration::AgentConfig,
            crate::configuration::AgentCloudMetadata,
        )>,
        Option<String>,
    ) {
        let (configs, cursor) = self.list(cursor, limit).await;
        (
            configs
                .into_iter()
                .map(|c| (c, crate::configuration::AgentCloudMetadata::default()))
                .collect(),
            cursor,
        )
    }
}

/// Store for managing scratchpad entries across conversations
#[async_trait::async_trait]
pub trait ScratchpadStore: Send + Sync + std::fmt::Debug {
    /// Add a scratchpad entry for a specific thread
    async fn add_entry(
        &self,
        thread_id: &str,
        entry: ScratchpadEntry,
    ) -> Result<(), crate::AgentError>;

    /// Clear all scratchpad entries for a thread
    async fn clear_entries(&self, thread_id: &str) -> Result<(), crate::AgentError>;

    /// Get entries for a specific task within a thread
    async fn get_entries(
        &self,
        thread_id: &str,
        task_id: &str,
        limit: Option<usize>,
    ) -> Result<Vec<ScratchpadEntry>, crate::AgentError>;

    async fn get_all_entries(
        &self,
        thread_id: &str,
        limit: Option<usize>,
    ) -> Result<Vec<ScratchpadEntry>, crate::AgentError>;
}

/// Web crawl result data
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, JsonSchema)]
pub struct CrawlResult {
    pub id: String,
    pub url: String,
    pub title: Option<String>,
    pub content: String,
    pub html: Option<String>,
    pub metadata: serde_json::Value,
    pub links: Vec<String>,
    pub images: Vec<String>,
    pub status_code: Option<u16>,
    pub crawled_at: chrono::DateTime<chrono::Utc>,
    pub processing_time_ms: Option<u64>,
}

/// Store for managing web crawl results
#[async_trait]
pub trait CrawlStore: Send + Sync {
    /// Store a crawl result
    async fn store_crawl_result(&self, result: CrawlResult) -> anyhow::Result<String>;

    /// Get a crawl result by ID
    async fn get_crawl_result(&self, id: &str) -> anyhow::Result<Option<CrawlResult>>;

    /// Get crawl results for a specific URL
    async fn get_crawl_results_by_url(&self, url: &str) -> anyhow::Result<Vec<CrawlResult>>;

    /// Get recent crawl results (within time limit)
    async fn get_recent_crawl_results(
        &self,
        limit: Option<usize>,
        since: Option<chrono::DateTime<chrono::Utc>>,
    ) -> anyhow::Result<Vec<CrawlResult>>;

    /// Check if URL was recently crawled (within cache duration)
    async fn is_url_recently_crawled(
        &self,
        url: &str,
        cache_duration: chrono::Duration,
    ) -> anyhow::Result<Option<CrawlResult>>;

    /// Delete crawl result
    async fn delete_crawl_result(&self, id: &str) -> anyhow::Result<()>;

    /// Clear all crawl results older than specified date
    async fn cleanup_old_results(
        &self,
        before: chrono::DateTime<chrono::Utc>,
    ) -> anyhow::Result<usize>;
}

// ========== Message Read & Voting Types ==========

/// Vote type for message feedback
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, ToSchema, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum VoteType {
    Upvote,
    Downvote,
}

/// Record of a message being read
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, JsonSchema)]
pub struct MessageReadStatus {
    pub thread_id: String,
    pub message_id: String,
    pub user_id: String,
    pub read_at: chrono::DateTime<chrono::Utc>,
}

/// Request to mark a message as read
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, JsonSchema)]
pub struct MarkMessageReadRequest {
    pub thread_id: String,
    pub message_id: String,
}

/// A vote on a message with optional feedback comment
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, JsonSchema)]
pub struct MessageVote {
    pub id: String,
    pub thread_id: String,
    pub message_id: String,
    pub user_id: String,
    pub vote_type: VoteType,
    /// Comment is required for downvotes, optional for upvotes
    pub comment: Option<String>,
    pub created_at: chrono::DateTime<chrono::Utc>,
    pub updated_at: chrono::DateTime<chrono::Utc>,
}

/// Request to vote on a message
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, JsonSchema)]
#[schema(example = json!({"vote_type": "up"}))]
pub struct VoteMessageRequest {
    pub thread_id: String,
    pub message_id: String,
    pub vote_type: VoteType,
    /// Required for downvotes
    pub comment: Option<String>,
}

/// Summary of votes for a message
#[derive(Debug, Clone, Serialize, Deserialize, Default, ToSchema, JsonSchema)]
pub struct MessageVoteSummary {
    pub message_id: String,
    pub upvotes: i64,
    pub downvotes: i64,
    /// Current user's vote on this message, if any
    pub user_vote: Option<VoteType>,
}

/// Store for managing external tool call completions using oneshot channels
#[async_trait]
pub trait ExternalToolCallsStore: Send + Sync + std::fmt::Debug {
    /// Register a new external tool call session and return a receiver for the response
    async fn register_external_tool_call(
        &self,
        session_id: &str,
    ) -> anyhow::Result<oneshot::Receiver<ToolResponse>>;

    /// Complete an external tool call by sending the response
    async fn complete_external_tool_call(
        &self,
        session_id: &str,
        tool_response: ToolResponse,
    ) -> anyhow::Result<()>;

    /// Remove a session (cleanup)
    async fn remove_tool_call(&self, session_id: &str) -> anyhow::Result<()>;

    /// List all pending sessions (for debugging)
    async fn list_pending_tool_calls(&self) -> anyhow::Result<Vec<String>>;
}

// ========== Prompt Template Store ==========

#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, JsonSchema)]
pub struct PromptTemplateRecord {
    pub id: String,
    pub name: String,
    pub template: String,
    pub description: Option<String>,
    pub version: Option<String>,
    pub is_system: bool,
    pub created_at: chrono::DateTime<chrono::Utc>,
    pub updated_at: chrono::DateTime<chrono::Utc>,
}

#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, JsonSchema)]
#[schema(example = json!({"name": "greeting", "content": "Hello {{name}}, welcome to {{service}}!", "description": "A greeting template"}))]
pub struct NewPromptTemplate {
    pub name: String,
    pub template: String,
    pub description: Option<String>,
    pub version: Option<String>,
    #[serde(default)]
    pub is_system: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, JsonSchema)]
pub struct UpdatePromptTemplate {
    pub name: String,
    pub template: String,
    pub description: Option<String>,
}

#[async_trait]
pub trait PromptTemplateStore: Send + Sync {
    async fn list(&self) -> anyhow::Result<Vec<PromptTemplateRecord>>;
    async fn get(&self, id: &str) -> anyhow::Result<Option<PromptTemplateRecord>>;
    /// Fetch multiple templates by name in a single query.
    async fn get_by_names(&self, names: &[String]) -> anyhow::Result<Vec<PromptTemplateRecord>>;
    async fn create(&self, template: NewPromptTemplate) -> anyhow::Result<PromptTemplateRecord>;
    async fn update(
        &self,
        id: &str,
        update: UpdatePromptTemplate,
    ) -> anyhow::Result<PromptTemplateRecord>;
    async fn delete(&self, id: &str) -> anyhow::Result<()>;
    async fn clone_template(&self, id: &str) -> anyhow::Result<PromptTemplateRecord>;
    async fn sync_system_templates(&self, templates: Vec<NewPromptTemplate>) -> anyhow::Result<()>;
}

// ========== Secret Store ==========

#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, JsonSchema)]
pub struct SecretRecord {
    pub id: String,
    pub key: String,
    pub value: String,
    pub created_at: chrono::DateTime<chrono::Utc>,
    pub updated_at: chrono::DateTime<chrono::Utc>,
}

#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, JsonSchema)]
#[schema(example = json!({"key": "OPENAI_API_KEY", "value": "sk-..."}))]
pub struct NewSecret {
    pub key: String,
    pub value: String,
}

#[async_trait]
pub trait SecretStore: Send + Sync {
    async fn list(&self) -> anyhow::Result<Vec<SecretRecord>>;
    async fn get(&self, key: &str) -> anyhow::Result<Option<SecretRecord>>;
    async fn create(&self, secret: NewSecret) -> anyhow::Result<SecretRecord>;
    async fn update(&self, key: &str, value: &str) -> anyhow::Result<SecretRecord>;
    async fn delete(&self, key: &str) -> anyhow::Result<()>;
}

// ========== Provider Store ==========

#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, JsonSchema)]
pub struct CustomProviderConfig {
    pub id: String,
    pub name: String,
    pub base_url: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub project_id: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, JsonSchema)]
pub struct CustomModelEntry {
    pub provider: String,
    pub model: String,
    /// "completion" (default), "tts", or "stt"
    #[serde(default = "default_completion")]
    pub capability: String,
}

fn default_completion() -> String {
    "completion".to_string()
}

/// A custom connection provider (OAuth integration) stored in workspace settings.
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, JsonSchema)]
pub struct ConnectionProviderConfig {
    /// Unique identifier (e.g., "linear", "figma", "custom_crm")
    pub id: String,
    /// Display name
    pub name: String,
    /// OAuth2 authorization URL
    pub authorization_url: String,
    /// OAuth2 token URL
    pub token_url: String,
    /// Optional refresh URL (defaults to token_url)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub refresh_url: Option<String>,
    /// Scopes the provider supports
    #[serde(default)]
    pub scopes_supported: Vec<String>,
    /// Default scopes to request
    #[serde(default)]
    pub default_scopes: Vec<String>,
    /// Friendly scope name → full scope string mappings
    #[serde(default)]
    pub scope_mappings: std::collections::HashMap<String, String>,
}

/// Request payload for upserting a provider configuration.
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, JsonSchema)]
pub struct UpsertProviderRequest {
    pub provider_id: String,
    #[serde(default)]
    pub secrets: std::collections::HashMap<String, String>,
    #[serde(default)]
    pub config: Option<CustomProviderConfig>,
    #[serde(default)]
    pub custom_models: Option<Vec<CustomModelEntry>>,
    /// Default model in "provider/model" format. Empty string or null to clear.
    #[serde(default)]
    pub default_model: Option<String>,
    /// Connection provider config (OAuth integration) to add/update.
    #[serde(default)]
    pub connection_provider: Option<ConnectionProviderConfig>,
}

/// Response after upserting a provider.
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, JsonSchema)]
pub struct UpsertProviderResponse {
    pub provider_id: String,
    pub secrets_saved: usize,
    pub config_saved: bool,
}

#[async_trait]
pub trait ProviderStore: Send + Sync {
    async fn upsert_provider(
        &self,
        req: UpsertProviderRequest,
    ) -> anyhow::Result<UpsertProviderResponse>;

    async fn delete_provider(&self, provider_id: &str) -> anyhow::Result<()>;

    async fn get_default_model(&self) -> anyhow::Result<Option<String>>;
}

// ========== Skill Store ==========

/// How a skill is executed relative to the calling agent's context.
/// Mirrors the `context` field in claude-code's prompt command spec.
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, ToSchema, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum ContextExecutionType {
    /// Inject the full skill content into the current agent's context window.
    /// The calling agent incorporates it directly — no sub-agent spawned.
    #[default]
    Inline,
    /// Spawn an isolated child agent with the skill as its instruction set.
    /// The child runs with its own token budget and task record; its result
    /// is summarised and returned to the parent.
    Fork,
}

impl std::fmt::Display for ContextExecutionType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ContextExecutionType::Inline => write!(f, "inline"),
            ContextExecutionType::Fork => write!(f, "fork"),
        }
    }
}

impl std::str::FromStr for ContextExecutionType {
    type Err = ();
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "fork" => Ok(ContextExecutionType::Fork),
            _ => Ok(ContextExecutionType::Inline),
        }
    }
}

/// Total token budget for all skill listings in the system prompt.
pub const SKILL_LISTING_BUDGET: usize = 2_000;
/// Max description chars per skill in system prompt listing.
pub const SKILL_DESCRIPTION_CAP: usize = 250;
/// Default max output tokens for a skill when not explicitly set.
pub const DEFAULT_SKILL_MAX_TOKENS: u32 = 8000;

/// Parsed frontmatter from a skill markdown file.
#[derive(Debug, Clone, Serialize, Deserialize, Default, ToSchema, JsonSchema)]
pub struct SkillFrontmatter {
    pub name: String,
    #[serde(default)]
    pub description: Option<String>,
    #[serde(default)]
    pub tags: Vec<String>,
    #[serde(default)]
    pub model: Option<String>,
    #[serde(default)]
    pub max_tokens: Option<u32>,
    #[serde(default)]
    pub can_spawn_tasks: bool,
    #[serde(default)]
    pub paths: Vec<String>,
    #[serde(default)]
    pub is_public: bool,
}

impl SkillFrontmatter {
    pub fn effective_max_tokens(&self) -> u32 {
        self.max_tokens.unwrap_or(DEFAULT_SKILL_MAX_TOKENS)
    }

    pub fn as_listing_line(&self) -> String {
        let desc = self.description.as_deref().unwrap_or("No description");
        let desc_truncated = if desc.len() > SKILL_DESCRIPTION_CAP {
            format!("{}...", &desc[..SKILL_DESCRIPTION_CAP.min(desc.len())])
        } else {
            desc.to_string()
        };
        let mut meta = Vec::new();
        if let Some(model) = &self.model {
            meta.push(format!("model: {}", model));
        }
        if self.can_spawn_tasks {
            meta.push("tasks: yes".to_string());
        }
        if meta.is_empty() {
            format!("- {}: {}", self.name, desc_truncated)
        } else {
            format!("- {}: {} ({})", self.name, desc_truncated, meta.join(", "))
        }
    }
}

/// Format a list of skills for the system prompt, respecting a token budget.
pub fn format_skill_listing(skills: &[SkillFrontmatter], budget_tokens: usize) -> String {
    let budget_chars = budget_tokens * 4;
    let mut result = String::new();
    let mut remaining_chars = budget_chars;
    for skill in skills {
        let line = format!("{}\n", skill.as_listing_line());
        if line.len() > remaining_chars {
            let name_line = format!("- {}\n", skill.name);
            if name_line.len() <= remaining_chars {
                result.push_str(&name_line);
                remaining_chars -= name_line.len();
            } else {
                break;
            }
        } else {
            result.push_str(&line);
            remaining_chars -= line.len();
        }
    }
    result.trim_end().to_string()
}

/// API response wrapper for skill list endpoints.
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, JsonSchema)]
pub struct SkillsListResponse {
    pub skills: Vec<SkillListItem>,
}

/// Lighter skill record for list endpoints — no content or scripts.
/// Used by both distri-server (OSS) and distri-cloud.
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, JsonSchema)]
pub struct SkillListItem {
    pub id: String,
    #[serde(default)]
    pub workspace_slug: String,
    pub name: String,
    #[serde(default)]
    pub full_name: String,
    #[serde(default)]
    pub description: Option<String>,
    #[serde(default)]
    pub tags: Vec<String>,
    #[serde(default)]
    pub is_public: bool,
    #[serde(default)]
    pub is_system: bool,
    #[serde(default)]
    pub is_owner: bool,
    /// True when the skill belongs to the current workspace
    #[serde(default)]
    pub is_workspace: bool,
    #[serde(default)]
    pub star_count: i32,
    #[serde(default)]
    pub clone_count: i32,
    #[serde(default)]
    pub is_starred: bool,
    pub created_at: chrono::DateTime<chrono::Utc>,
    pub updated_at: chrono::DateTime<chrono::Utc>,
}

#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, JsonSchema)]
pub struct SkillRecord {
    pub id: String,
    /// Workspace slug (cloud: resolved from workspace_id, OSS: "local")
    #[serde(default)]
    pub workspace_slug: String,
    pub name: String,
    /// Full qualified name: "{workspace_slug}/{name}"
    #[serde(default)]
    pub full_name: String,
    pub description: Option<String>,
    pub content: String,
    pub tags: Vec<String>,
    pub is_public: bool,
    pub is_system: bool,
    /// Whether the current user owns this skill
    #[serde(default)]
    pub is_owner: bool,
    /// True when the skill belongs to the current workspace
    #[serde(default)]
    pub is_workspace: bool,
    pub star_count: i32,
    pub clone_count: i32,
    /// Whether the current user has starred this skill
    #[serde(default)]
    pub is_starred: bool,
    pub created_at: chrono::DateTime<chrono::Utc>,
    pub updated_at: chrono::DateTime<chrono::Utc>,
    /// Preferred model for skill execution (overrides agent default)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
    /// How to deliver skill content: inline (default) or fork (isolated sub-agent)
    #[serde(default)]
    pub context: ContextExecutionType,
}

#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, JsonSchema)]
#[schema(example = json!({"name": "my-skill", "content": "# My Skill\nA helpful utility skill", "description": "A utility skill", "tags": ["utility"], "is_public": false}))]
pub struct NewSkill {
    pub name: String,
    pub description: Option<String>,
    pub content: String,
    #[serde(default)]
    pub tags: Vec<String>,
    #[serde(default)]
    pub is_public: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
    #[serde(default)]
    pub context: ContextExecutionType,
}

#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, JsonSchema)]
pub struct UpdateSkill {
    pub name: Option<String>,
    pub description: Option<String>,
    pub content: Option<String>,
    pub tags: Option<Vec<String>>,
    pub is_public: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub context: Option<ContextExecutionType>,
}

/// Which slice of skills to return.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum SkillScope {
    /// Skills belonging to the current workspace (not system)
    #[default]
    Workspace,
    /// Starred skills
    Starred,
    /// System skills
    System,
    /// Public skills from other workspaces (excludes own + system)
    Discover,
    /// Everything the user can see (workspace + public + system)
    All,
}

/// Filters for listing skills — one struct drives list, search, and pagination.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SkillFilter {
    /// Which slice of skills to return
    #[serde(default)]
    pub scope: SkillScope,
    /// Full-text search on name/description (empty = no search filter)
    #[serde(default)]
    pub search: Option<String>,
    /// Page number (1-based, default 1)
    #[serde(default = "default_page")]
    pub page: i64,
    /// Items per page (default 50)
    #[serde(default = "default_per_page")]
    pub per_page: i64,
}

fn default_page() -> i64 {
    1
}
fn default_per_page() -> i64 {
    50
}

/// Paginated skill list response.
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, JsonSchema)]
pub struct SkillListResponse {
    pub skills: Vec<SkillListItem>,
    pub total: i64,
    pub page: i64,
    pub per_page: i64,
    pub total_pages: i64,
}

#[async_trait]
pub trait SkillStore: Send + Sync {
    /// List skills — scope, search, and pagination all via SkillFilter.
    async fn list(&self, filter: SkillFilter) -> anyhow::Result<SkillListResponse>;
    async fn get(&self, id: &str) -> anyhow::Result<Option<SkillRecord>>;
    async fn create(&self, skill: NewSkill) -> anyhow::Result<SkillRecord>;
    async fn update(&self, id: &str, update: UpdateSkill) -> anyhow::Result<SkillRecord>;
    async fn delete(&self, id: &str) -> anyhow::Result<()>;
    async fn star(&self, skill_id: &str) -> anyhow::Result<()>;
    async fn unstar(&self, skill_id: &str) -> anyhow::Result<()>;
    async fn clone_skill(&self, skill_id: &str) -> anyhow::Result<SkillRecord>;
}

// ─── Usage Service ──────────────────────────────────────────────────────────

/// Current usage snapshot for a workspace/user.
#[derive(Debug, Clone, Default, Serialize, Deserialize, ToSchema, JsonSchema)]
pub struct UsageSnapshot {
    pub day_tokens: i64,
    pub week_tokens: i64,
    pub month_tokens: i64,
}

/// Configured token limits for a workspace.
#[derive(Debug, Clone, Default, Serialize, Deserialize, ToSchema, JsonSchema)]
pub struct UsageLimits {
    pub daily_tokens: Option<i64>,
    pub weekly_tokens: Option<i64>,
    pub monthly_tokens: Option<i64>,
}

/// Result of a rate limit check.
#[derive(Debug, Clone)]
pub enum UsageCheckResult {
    Allowed,
    Denied { reason: String },
}

/// Trait for usage tracking, rate limiting, and workspace limit management.
///
/// OSS: can use a no-op or in-memory implementation.
/// Cloud: backed by Redis + Postgres with caching.
#[async_trait]
pub trait UsageService: Send + Sync {
    /// Check whether a request should be allowed based on all rate limits.
    /// Called by middleware before processing a request.
    /// `is_llm` indicates whether this is an LLM-consuming endpoint.
    /// `auth_source` is "jwt" or "api_key" for per-source analytics.
    async fn check_request(
        &self,
        workspace_id: &str,
        user_id: &str,
        is_llm: bool,
        auth_source: &str,
    ) -> UsageCheckResult;

    /// Record token usage after a completed agent run.
    async fn record_usage(
        &self,
        workspace_id: &str,
        user_id: &str,
        tokens_used: i64,
    ) -> anyhow::Result<()>;

    /// Get current usage snapshot for display.
    async fn get_usage(&self, workspace_id: &str, user_id: &str) -> anyhow::Result<UsageSnapshot>;

    /// Get the configured limits for a workspace.
    async fn get_limits(&self, workspace_id: &str) -> anyhow::Result<UsageLimits>;
}

/// No-op usage service for OSS / development.
/// Always allows requests, never records anything.
#[derive(Debug, Clone)]
pub struct NoOpUsageService;

#[async_trait]
impl UsageService for NoOpUsageService {
    async fn check_request(
        &self,
        _workspace_id: &str,
        _user_id: &str,
        _is_llm: bool,
        _auth_source: &str,
    ) -> UsageCheckResult {
        UsageCheckResult::Allowed
    }

    async fn record_usage(
        &self,
        _workspace_id: &str,
        _user_id: &str,
        _tokens_used: i64,
    ) -> anyhow::Result<()> {
        Ok(())
    }

    async fn get_usage(
        &self,
        _workspace_id: &str,
        _user_id: &str,
    ) -> anyhow::Result<UsageSnapshot> {
        Ok(UsageSnapshot::default())
    }

    async fn get_limits(&self, _workspace_id: &str) -> anyhow::Result<UsageLimits> {
        Ok(UsageLimits::default())
    }
}

// ========== Connection Store ==========

/// Persistence for connection records (Postgres-backed in cloud).
#[async_trait]
pub trait ConnectionStore: Send + Sync + 'static {
    async fn create(&self, connection: NewConnection) -> anyhow::Result<Connection>;
    async fn get_by_id(&self, id: &str) -> anyhow::Result<Option<Connection>>;
    async fn list_by_workspace(&self, workspace_id: &str) -> anyhow::Result<Vec<Connection>>;
    async fn update_status(&self, id: &str, status: ConnectionStatus) -> anyhow::Result<()>;
    async fn update_skill_id(&self, id: &str, skill_id: uuid::Uuid) -> anyhow::Result<()>;
    async fn delete(&self, id: &str) -> anyhow::Result<()>;
    async fn get_by_provider(
        &self,
        workspace_id: &str,
        provider: &str,
    ) -> anyhow::Result<Option<Connection>>;
}

/// Token storage for OAuth connections (Redis-backed in cloud).
#[async_trait]
pub trait ConnectionTokenStore: Send + Sync + 'static {
    async fn store_token(&self, connection_id: &str, token: ConnectionToken) -> anyhow::Result<()>;
    async fn get_token(&self, connection_id: &str) -> anyhow::Result<Option<ConnectionToken>>;
    async fn remove_token(&self, connection_id: &str) -> anyhow::Result<()>;

    /// Attempt to refresh an expired OAuth token using the stored refresh_token.
    /// Returns the new token if refresh succeeds, or None if refresh is not
    /// supported or fails. The implementation should store the refreshed token.
    ///
    /// Cloud implementation uses OAuthHandler.refresh_get_session().
    /// Default: no refresh support (returns None).
    async fn refresh_token(
        &self,
        _connection_id: &str,
        _connection: &Connection,
    ) -> anyhow::Result<Option<ConnectionToken>> {
        Ok(None)
    }

    async fn store_oauth_state(
        &self,
        state_key: &str,
        state: serde_json::Value,
    ) -> anyhow::Result<()>;
    async fn get_oauth_state(&self, state_key: &str) -> anyhow::Result<Option<serde_json::Value>>;
    async fn remove_oauth_state(&self, state_key: &str) -> anyhow::Result<()>;
}

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

    #[test]
    fn test_skills_list_response_deserialize_cloud_format() {
        let json = r#"{"skills":[{"id":"abc","workspace_slug":"ws","name":"test","full_name":"ws/test","description":"desc","tags":["t"],"is_public":true,"is_system":false,"is_owner":true,"star_count":0,"clone_count":0,"is_starred":false,"created_at":"2026-01-01T00:00:00Z","updated_at":"2026-01-01T00:00:00Z"}]}"#;
        let resp: SkillsListResponse = serde_json::from_str(json).unwrap();
        assert_eq!(resp.skills.len(), 1);
        assert_eq!(resp.skills[0].name, "test");
        assert_eq!(resp.skills[0].workspace_slug, "ws");
        assert_eq!(resp.skills[0].full_name, "ws/test");
        assert!(resp.skills[0].is_public);
    }

    #[test]
    fn test_skills_list_response_deserialize_defaults() {
        let json = r#"{"skills":[{"id":"abc","name":"test","created_at":"2026-01-01T00:00:00Z","updated_at":"2026-01-01T00:00:00Z"}]}"#;
        let resp: SkillsListResponse = serde_json::from_str(json).unwrap();
        assert_eq!(resp.skills[0].workspace_slug, "");
        assert_eq!(resp.skills[0].full_name, "");
        assert!(!resp.skills[0].is_public);
        assert!(!resp.skills[0].is_owner);
    }

    #[test]
    fn test_skills_list_response_roundtrip() {
        let resp = SkillsListResponse {
            skills: vec![SkillListItem {
                id: "id1".into(),
                workspace_slug: "local".into(),
                name: "my_skill".into(),
                full_name: "local/my_skill".into(),
                description: Some("A skill".into()),
                tags: vec!["tag1".into()],
                is_public: false,
                is_system: false,
                is_owner: true,
                is_workspace: true,
                star_count: 5,
                clone_count: 2,
                is_starred: true,
                created_at: chrono::Utc::now(),
                updated_at: chrono::Utc::now(),
            }],
        };
        let json = serde_json::to_string(&resp).unwrap();
        let decoded: SkillsListResponse = serde_json::from_str(&json).unwrap();
        assert_eq!(decoded.skills[0].name, "my_skill");
        assert_eq!(decoded.skills[0].star_count, 5);
    }
}