praisonai 0.2.0

Core library for PraisonAI - Agent, Tools, Workflows
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
//! Configuration types for PraisonAI
//!
//! This module provides configuration structs for various features.
//! Follows the Python SDK pattern of XConfig naming convention.
//!
//! # Feature Configurations
//!
//! - [`MemoryConfig`]: Memory and session management
//! - [`KnowledgeConfig`]: RAG and knowledge retrieval
//! - [`PlanningConfig`]: Planning mode settings
//! - [`ReflectionConfig`]: Self-reflection settings
//! - [`GuardrailConfig`]: Safety and validation
//! - [`WebConfig`]: Web search and fetch
//! - [`CachingConfig`]: Response caching
//! - [`AutonomyConfig`]: Agent autonomy levels
//!
//! All configs follow the agent-centric pattern:
//! - `false`: Feature disabled (zero overhead)
//! - `true`: Feature enabled with safe defaults
//! - `Config`: Custom configuration

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Memory configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MemoryConfig {
    /// Enable short-term memory (conversation history)
    #[serde(default = "default_true")]
    pub use_short_term: bool,

    /// Enable long-term memory (persistent storage)
    #[serde(default)]
    pub use_long_term: bool,

    /// Memory provider (e.g., "memory", "chroma", "sqlite")
    #[serde(default = "default_memory_provider")]
    pub provider: String,

    /// Maximum number of messages to keep in short-term memory
    #[serde(default = "default_max_messages")]
    pub max_messages: usize,
}

fn default_true() -> bool {
    true
}
fn default_memory_provider() -> String {
    "memory".to_string()
}
fn default_max_messages() -> usize {
    100
}

impl Default for MemoryConfig {
    fn default() -> Self {
        Self {
            use_short_term: true,
            use_long_term: false,
            provider: "memory".to_string(),
            max_messages: 100,
        }
    }
}

impl MemoryConfig {
    /// Create a new memory config with defaults
    pub fn new() -> Self {
        Self::default()
    }

    /// Enable long-term memory
    pub fn with_long_term(mut self) -> Self {
        self.use_long_term = true;
        self
    }

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

    /// Set max messages
    pub fn max_messages(mut self, max: usize) -> Self {
        self.max_messages = max;
        self
    }
}

/// Hooks configuration for before/after tool execution
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct HooksConfig {
    /// Enable hooks
    #[serde(default)]
    pub enabled: bool,
}

impl HooksConfig {
    /// Create a new hooks config
    pub fn new() -> Self {
        Self::default()
    }

    /// Enable hooks
    pub fn enabled(mut self) -> Self {
        self.enabled = true;
        self
    }
}

/// Output configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OutputConfig {
    /// Output mode: "silent", "verbose", "json"
    #[serde(default = "default_output_mode")]
    pub mode: String,

    /// Output file path (optional)
    #[serde(default)]
    pub file: Option<String>,
}

fn default_output_mode() -> String {
    "verbose".to_string()
}

impl Default for OutputConfig {
    fn default() -> Self {
        Self {
            mode: default_output_mode(),
            file: None,
        }
    }
}

impl OutputConfig {
    /// Create a new output config
    pub fn new() -> Self {
        Self::default()
    }

    /// Set silent mode
    pub fn silent(mut self) -> Self {
        self.mode = "silent".to_string();
        self
    }

    /// Set verbose mode
    pub fn verbose(mut self) -> Self {
        self.mode = "verbose".to_string();
        self
    }

    /// Set JSON output mode
    pub fn json(mut self) -> Self {
        self.mode = "json".to_string();
        self
    }

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

/// Execution configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExecutionConfig {
    /// Maximum number of iterations
    #[serde(default = "default_max_iterations")]
    pub max_iterations: usize,

    /// Timeout in seconds
    #[serde(default = "default_timeout")]
    pub timeout_secs: u64,

    /// Enable streaming output
    #[serde(default = "default_true")]
    pub stream: bool,
}

fn default_max_iterations() -> usize {
    10
}
fn default_timeout() -> u64 {
    300
}

impl Default for ExecutionConfig {
    fn default() -> Self {
        Self {
            max_iterations: default_max_iterations(),
            timeout_secs: default_timeout(),
            stream: true,
        }
    }
}

impl ExecutionConfig {
    /// Create a new execution config
    pub fn new() -> Self {
        Self::default()
    }

    /// Set max iterations
    pub fn max_iterations(mut self, max: usize) -> Self {
        self.max_iterations = max;
        self
    }

    /// Set timeout
    pub fn timeout(mut self, secs: u64) -> Self {
        self.timeout_secs = secs;
        self
    }

    /// Disable streaming
    pub fn no_stream(mut self) -> Self {
        self.stream = false;
        self
    }
}

// =============================================================================
// GUARDRAILS CONFIGURATION
// =============================================================================

/// Action to take when guardrail fails
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum GuardrailAction {
    /// Retry the operation
    #[default]
    Retry,
    /// Skip the operation
    Skip,
    /// Raise an error
    Raise,
}

/// Guardrail validation result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GuardrailResult {
    /// Whether the validation passed
    pub passed: bool,
    /// Validation message or error
    pub message: Option<String>,
    /// Modified output (if any)
    pub modified_output: Option<String>,
}

impl GuardrailResult {
    /// Create a passing result
    pub fn pass() -> Self {
        Self {
            passed: true,
            message: None,
            modified_output: None,
        }
    }

    /// Create a failing result with a message
    pub fn fail(message: impl Into<String>) -> Self {
        Self {
            passed: false,
            message: Some(message.into()),
            modified_output: None,
        }
    }

    /// Create a result with modified output
    pub fn with_modification(mut self, output: impl Into<String>) -> Self {
        self.modified_output = Some(output.into());
        self
    }
}

/// Configuration for guardrails and safety validation
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct GuardrailConfig {
    /// Enable guardrails
    #[serde(default)]
    pub enabled: bool,

    /// LLM-based validation prompt
    #[serde(default)]
    pub llm_validator: Option<String>,

    /// Maximum retries on failure
    #[serde(default = "default_guardrail_retries")]
    pub max_retries: usize,

    /// Action on failure
    #[serde(default)]
    pub on_fail: GuardrailAction,

    /// Policy strings (e.g., ["policy:strict", "pii:redact"])
    #[serde(default)]
    pub policies: Vec<String>,
}

fn default_guardrail_retries() -> usize {
    3
}

impl GuardrailConfig {
    /// Create a new guardrail config
    pub fn new() -> Self {
        Self::default()
    }

    /// Enable guardrails
    pub fn enabled(mut self) -> Self {
        self.enabled = true;
        self
    }

    /// Set LLM validator prompt
    pub fn llm_validator(mut self, prompt: impl Into<String>) -> Self {
        self.llm_validator = Some(prompt.into());
        self.enabled = true;
        self
    }

    /// Set max retries
    pub fn max_retries(mut self, retries: usize) -> Self {
        self.max_retries = retries;
        self
    }

    /// Set action on failure
    pub fn on_fail(mut self, action: GuardrailAction) -> Self {
        self.on_fail = action;
        self
    }

    /// Add a policy
    pub fn policy(mut self, policy: impl Into<String>) -> Self {
        self.policies.push(policy.into());
        self.enabled = true;
        self
    }
}

// =============================================================================
// KNOWLEDGE CONFIGURATION
// =============================================================================

/// Knowledge chunking strategies
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ChunkingStrategy {
    /// Fixed-size chunks
    Fixed,
    /// Semantic chunking
    #[default]
    Semantic,
    /// Sentence-based chunking
    Sentence,
    /// Paragraph-based chunking
    Paragraph,
}

/// Configuration for RAG and knowledge retrieval
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct KnowledgeConfig {
    /// Knowledge sources (files, directories, URLs)
    #[serde(default)]
    pub sources: Vec<String>,

    /// Embedder model
    #[serde(default = "default_embedder")]
    pub embedder: String,

    /// Chunking strategy
    #[serde(default)]
    pub chunking_strategy: ChunkingStrategy,

    /// Chunk size in characters
    #[serde(default = "default_chunk_size")]
    pub chunk_size: usize,

    /// Chunk overlap in characters
    #[serde(default = "default_chunk_overlap")]
    pub chunk_overlap: usize,

    /// Number of results to retrieve
    #[serde(default = "default_retrieval_k")]
    pub retrieval_k: usize,

    /// Retrieval threshold (0.0 - 1.0)
    #[serde(default)]
    pub retrieval_threshold: f32,

    /// Enable reranking
    #[serde(default)]
    pub rerank: bool,

    /// Rerank model
    #[serde(default)]
    pub rerank_model: Option<String>,

    /// Auto-retrieve context
    #[serde(default = "default_true")]
    pub auto_retrieve: bool,
}

fn default_embedder() -> String {
    "openai".to_string()
}

fn default_chunk_size() -> usize {
    1000
}

fn default_chunk_overlap() -> usize {
    200
}

fn default_retrieval_k() -> usize {
    5
}

impl KnowledgeConfig {
    /// Create a new knowledge config
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a source
    pub fn source(mut self, source: impl Into<String>) -> Self {
        self.sources.push(source.into());
        self
    }

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

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

    /// Set chunking strategy
    pub fn chunking(mut self, strategy: ChunkingStrategy) -> Self {
        self.chunking_strategy = strategy;
        self
    }

    /// Set chunk size
    pub fn chunk_size(mut self, size: usize) -> Self {
        self.chunk_size = size;
        self
    }

    /// Set retrieval k
    pub fn retrieval_k(mut self, k: usize) -> Self {
        self.retrieval_k = k;
        self
    }

    /// Enable reranking
    pub fn with_rerank(mut self) -> Self {
        self.rerank = true;
        self
    }

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

// =============================================================================
// PLANNING CONFIGURATION
// =============================================================================

/// Configuration for planning mode
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct PlanningConfig {
    /// Enable planning
    #[serde(default)]
    pub enabled: bool,

    /// Planning LLM (if different from main)
    #[serde(default)]
    pub llm: Option<String>,

    /// Enable reasoning during planning
    #[serde(default)]
    pub reasoning: bool,

    /// Auto-approve plans without user confirmation
    #[serde(default)]
    pub auto_approve: bool,

    /// Read-only mode (only read operations allowed)
    #[serde(default)]
    pub read_only: bool,
}

impl PlanningConfig {
    /// Create a new planning config
    pub fn new() -> Self {
        Self::default()
    }

    /// Enable planning
    pub fn enabled(mut self) -> Self {
        self.enabled = true;
        self
    }

    /// Set planning LLM
    pub fn llm(mut self, llm: impl Into<String>) -> Self {
        self.llm = Some(llm.into());
        self.enabled = true;
        self
    }

    /// Enable reasoning
    pub fn with_reasoning(mut self) -> Self {
        self.reasoning = true;
        self
    }

    /// Enable auto-approve
    pub fn auto_approve(mut self) -> Self {
        self.auto_approve = true;
        self
    }

    /// Enable read-only mode
    pub fn read_only(mut self) -> Self {
        self.read_only = true;
        self
    }
}

// =============================================================================
// REFLECTION CONFIGURATION
// =============================================================================

/// Configuration for self-reflection
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReflectionConfig {
    /// Enable reflection
    #[serde(default)]
    pub enabled: bool,

    /// Minimum iterations
    #[serde(default = "default_min_iterations")]
    pub min_iterations: usize,

    /// Maximum iterations
    #[serde(default = "default_max_reflect_iterations")]
    pub max_iterations: usize,

    /// Reflection LLM (if different from main)
    #[serde(default)]
    pub llm: Option<String>,

    /// Custom reflection prompt
    #[serde(default)]
    pub prompt: Option<String>,
}

fn default_min_iterations() -> usize {
    1
}

fn default_max_reflect_iterations() -> usize {
    3
}

impl Default for ReflectionConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            min_iterations: 1,
            max_iterations: 3,
            llm: None,
            prompt: None,
        }
    }
}

impl ReflectionConfig {
    /// Create a new reflection config
    pub fn new() -> Self {
        Self::default()
    }

    /// Enable reflection
    pub fn enabled(mut self) -> Self {
        self.enabled = true;
        self
    }

    /// Set min iterations
    pub fn min_iterations(mut self, min: usize) -> Self {
        self.min_iterations = min;
        self.enabled = true;
        self
    }

    /// Set max iterations
    pub fn max_iterations(mut self, max: usize) -> Self {
        self.max_iterations = max;
        self.enabled = true;
        self
    }

    /// Set reflection LLM
    pub fn llm(mut self, llm: impl Into<String>) -> Self {
        self.llm = Some(llm.into());
        self.enabled = true;
        self
    }

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

// =============================================================================
// CACHING CONFIGURATION
// =============================================================================

/// Configuration for caching behavior
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CachingConfig {
    /// Enable response caching
    #[serde(default = "default_true")]
    pub enabled: bool,

    /// Enable prompt caching (provider-specific)
    #[serde(default)]
    pub prompt_caching: bool,

    /// Cache TTL in seconds
    #[serde(default)]
    pub ttl_secs: Option<u64>,
}

impl Default for CachingConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            prompt_caching: false,
            ttl_secs: None,
        }
    }
}

impl CachingConfig {
    /// Create a new caching config
    pub fn new() -> Self {
        Self::default()
    }

    /// Disable caching
    pub fn disabled(mut self) -> Self {
        self.enabled = false;
        self
    }

    /// Enable prompt caching
    pub fn with_prompt_caching(mut self) -> Self {
        self.prompt_caching = true;
        self
    }

    /// Set TTL
    pub fn ttl(mut self, secs: u64) -> Self {
        self.ttl_secs = Some(secs);
        self
    }
}

// =============================================================================
// WEB CONFIGURATION
// =============================================================================

/// Web search providers
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum WebSearchProvider {
    /// DuckDuckGo search
    #[default]
    DuckDuckGo,
    /// Google search
    Google,
    /// Bing search
    Bing,
    /// Tavily search
    Tavily,
    /// Serper search
    Serper,
}

/// Configuration for web search and fetch capabilities
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WebConfig {
    /// Enable web search
    #[serde(default = "default_true")]
    pub search: bool,

    /// Enable web fetch (retrieve full page content)
    #[serde(default = "default_true")]
    pub fetch: bool,

    /// Search provider
    #[serde(default)]
    pub search_provider: WebSearchProvider,

    /// Maximum search results
    #[serde(default = "default_max_results")]
    pub max_results: usize,
}

fn default_max_results() -> usize {
    5
}

impl Default for WebConfig {
    fn default() -> Self {
        Self {
            search: true,
            fetch: true,
            search_provider: WebSearchProvider::default(),
            max_results: 5,
        }
    }
}

impl WebConfig {
    /// Create a new web config
    pub fn new() -> Self {
        Self::default()
    }

    /// Disable search
    pub fn no_search(mut self) -> Self {
        self.search = false;
        self
    }

    /// Disable fetch
    pub fn no_fetch(mut self) -> Self {
        self.fetch = false;
        self
    }

    /// Set search provider
    pub fn provider(mut self, provider: WebSearchProvider) -> Self {
        self.search_provider = provider;
        self
    }

    /// Set max results
    pub fn max_results(mut self, max: usize) -> Self {
        self.max_results = max;
        self
    }
}

// =============================================================================
// AUTONOMY CONFIGURATION
// =============================================================================

/// Autonomy levels for agent behavior
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AutonomyLevel {
    /// Suggest actions, wait for approval
    #[default]
    Suggest,
    /// Auto-edit with confirmation
    AutoEdit,
    /// Full autonomous operation
    FullAuto,
}

/// Configuration for agent autonomy
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct AutonomyConfig {
    /// Autonomy level
    #[serde(default)]
    pub level: AutonomyLevel,

    /// Require approval for destructive actions
    #[serde(default = "default_true")]
    pub require_approval: bool,

    /// Maximum autonomous actions before pause
    #[serde(default)]
    pub max_actions: Option<usize>,

    /// Allowed tools for autonomous execution
    #[serde(default)]
    pub allowed_tools: Vec<String>,

    /// Blocked tools (never run autonomously)
    #[serde(default)]
    pub blocked_tools: Vec<String>,
}

impl AutonomyConfig {
    /// Create a new autonomy config
    pub fn new() -> Self {
        Self::default()
    }

    /// Set autonomy level
    pub fn level(mut self, level: AutonomyLevel) -> Self {
        self.level = level;
        self
    }

    /// Disable approval requirement
    pub fn no_approval(mut self) -> Self {
        self.require_approval = false;
        self
    }

    /// Set max actions
    pub fn max_actions(mut self, max: usize) -> Self {
        self.max_actions = Some(max);
        self
    }

    /// Add allowed tool
    pub fn allow_tool(mut self, tool: impl Into<String>) -> Self {
        self.allowed_tools.push(tool.into());
        self
    }

    /// Add blocked tool
    pub fn block_tool(mut self, tool: impl Into<String>) -> Self {
        self.blocked_tools.push(tool.into());
        self
    }

    /// Set to full auto mode
    pub fn full_auto(mut self) -> Self {
        self.level = AutonomyLevel::FullAuto;
        self.require_approval = false;
        self
    }
}

// =============================================================================
// SKILLS CONFIGURATION
// =============================================================================

/// Configuration for agent skills
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SkillsConfig {
    /// Direct skill paths
    #[serde(default)]
    pub paths: Vec<String>,

    /// Directories to scan for skills
    #[serde(default)]
    pub dirs: Vec<String>,

    /// Auto-discover from default locations
    #[serde(default)]
    pub auto_discover: bool,
}

impl SkillsConfig {
    /// Create a new skills config
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a skill path
    pub fn path(mut self, path: impl Into<String>) -> Self {
        self.paths.push(path.into());
        self
    }

    /// Add a skills directory
    pub fn dir(mut self, dir: impl Into<String>) -> Self {
        self.dirs.push(dir.into());
        self
    }

    /// Enable auto-discovery
    pub fn auto_discover(mut self) -> Self {
        self.auto_discover = true;
        self
    }
}

// =============================================================================
// TEMPLATE CONFIGURATION
// =============================================================================

/// Configuration for prompt templates
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TemplateConfig {
    /// System template
    #[serde(default)]
    pub system: Option<String>,

    /// Prompt template
    #[serde(default)]
    pub prompt: Option<String>,

    /// Response template
    #[serde(default)]
    pub response: Option<String>,

    /// Use system prompt
    #[serde(default = "default_true")]
    pub use_system_prompt: bool,
}

impl Default for TemplateConfig {
    fn default() -> Self {
        Self {
            system: None,
            prompt: None,
            response: None,
            use_system_prompt: true,
        }
    }
}

impl TemplateConfig {
    /// Create a new template config
    pub fn new() -> Self {
        Self::default()
    }

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

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

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

    /// Disable system prompt
    pub fn no_system_prompt(mut self) -> Self {
        self.use_system_prompt = false;
        self
    }
}

// =============================================================================
// MULTI-AGENT CONFIGURATIONS
// =============================================================================

/// Configuration for multi-agent hooks
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct MultiAgentHooksConfig {
    /// Enable task start callback
    #[serde(default)]
    pub on_task_start: bool,

    /// Enable task complete callback
    #[serde(default)]
    pub on_task_complete: bool,

    /// Enable completion checker
    #[serde(default)]
    pub completion_checker: bool,
}

/// Configuration for multi-agent output
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct MultiAgentOutputConfig {
    /// Verbosity level (0=silent, 1=minimal, 2+=verbose)
    #[serde(default)]
    pub verbose: u8,

    /// Enable streaming output
    #[serde(default = "default_true")]
    pub stream: bool,
}

/// Configuration for multi-agent execution
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MultiAgentExecutionConfig {
    /// Maximum iterations per task
    #[serde(default = "default_multi_agent_iter")]
    pub max_iter: usize,

    /// Maximum retries on failure
    #[serde(default = "default_multi_agent_retries")]
    pub max_retries: usize,
}

fn default_multi_agent_iter() -> usize {
    10
}

fn default_multi_agent_retries() -> usize {
    5
}

impl Default for MultiAgentExecutionConfig {
    fn default() -> Self {
        Self {
            max_iter: 10,
            max_retries: 5,
        }
    }
}

/// Configuration for multi-agent planning
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct MultiAgentPlanningConfig {
    /// Planning LLM model
    #[serde(default)]
    pub llm: Option<String>,

    /// Auto-approve generated plans
    #[serde(default)]
    pub auto_approve: bool,

    /// Enable reasoning in planning
    #[serde(default)]
    pub reasoning: bool,
}

/// Configuration for multi-agent memory
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct MultiAgentMemoryConfig {
    /// User identification
    #[serde(default)]
    pub user_id: Option<String>,

    /// Memory provider config
    #[serde(default)]
    pub config: HashMap<String, serde_json::Value>,
}

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

    #[test]
    fn test_memory_config_defaults() {
        let config = MemoryConfig::new();
        assert!(config.use_short_term);
        assert!(!config.use_long_term);
        assert_eq!(config.provider, "memory");
    }

    #[test]
    fn test_guardrail_config() {
        let config = GuardrailConfig::new()
            .llm_validator("Ensure response is safe")
            .max_retries(5)
            .on_fail(GuardrailAction::Raise)
            .policy("pii:redact");

        assert!(config.enabled);
        assert_eq!(
            config.llm_validator,
            Some("Ensure response is safe".to_string())
        );
        assert_eq!(config.max_retries, 5);
        assert_eq!(config.on_fail, GuardrailAction::Raise);
        assert!(config.policies.contains(&"pii:redact".to_string()));
    }

    #[test]
    fn test_guardrail_result() {
        let pass = GuardrailResult::pass();
        assert!(pass.passed);
        assert!(pass.message.is_none());

        let fail = GuardrailResult::fail("Invalid content");
        assert!(!fail.passed);
        assert_eq!(fail.message, Some("Invalid content".to_string()));

        let modified = GuardrailResult::pass().with_modification("Modified output");
        assert!(modified.passed);
        assert_eq!(
            modified.modified_output,
            Some("Modified output".to_string())
        );
    }

    #[test]
    fn test_knowledge_config() {
        let config = KnowledgeConfig::new()
            .source("docs/")
            .source("data.pdf")
            .embedder("openai")
            .chunking(ChunkingStrategy::Semantic)
            .retrieval_k(10)
            .with_rerank();

        assert_eq!(config.sources.len(), 2);
        assert_eq!(config.embedder, "openai");
        assert_eq!(config.chunking_strategy, ChunkingStrategy::Semantic);
        assert_eq!(config.retrieval_k, 10);
        assert!(config.rerank);
    }

    #[test]
    fn test_planning_config() {
        let config = PlanningConfig::new()
            .llm("gpt-4o")
            .with_reasoning()
            .auto_approve();

        assert!(config.enabled);
        assert_eq!(config.llm, Some("gpt-4o".to_string()));
        assert!(config.reasoning);
        assert!(config.auto_approve);
    }

    #[test]
    fn test_reflection_config() {
        let config = ReflectionConfig::new()
            .min_iterations(2)
            .max_iterations(5)
            .prompt("Evaluate accuracy");

        assert!(config.enabled);
        assert_eq!(config.min_iterations, 2);
        assert_eq!(config.max_iterations, 5);
        assert_eq!(config.prompt, Some("Evaluate accuracy".to_string()));
    }

    #[test]
    fn test_caching_config() {
        let config = CachingConfig::new().with_prompt_caching().ttl(3600);

        assert!(config.enabled);
        assert!(config.prompt_caching);
        assert_eq!(config.ttl_secs, Some(3600));
    }

    #[test]
    fn test_web_config() {
        let config = WebConfig::new()
            .provider(WebSearchProvider::Tavily)
            .max_results(10);

        assert!(config.search);
        assert!(config.fetch);
        assert_eq!(config.search_provider, WebSearchProvider::Tavily);
        assert_eq!(config.max_results, 10);
    }

    #[test]
    fn test_autonomy_config() {
        let config = AutonomyConfig::new()
            .level(AutonomyLevel::AutoEdit)
            .max_actions(10)
            .allow_tool("search")
            .block_tool("delete");

        assert_eq!(config.level, AutonomyLevel::AutoEdit);
        assert_eq!(config.max_actions, Some(10));
        assert!(config.allowed_tools.contains(&"search".to_string()));
        assert!(config.blocked_tools.contains(&"delete".to_string()));
    }

    #[test]
    fn test_autonomy_full_auto() {
        let config = AutonomyConfig::new().full_auto();

        assert_eq!(config.level, AutonomyLevel::FullAuto);
        assert!(!config.require_approval);
    }

    #[test]
    fn test_skills_config() {
        let config = SkillsConfig::new()
            .path("./my-skill")
            .dir("~/.praisonai/skills/")
            .auto_discover();

        assert!(config.paths.contains(&"./my-skill".to_string()));
        assert!(config.dirs.contains(&"~/.praisonai/skills/".to_string()));
        assert!(config.auto_discover);
    }

    #[test]
    fn test_template_config() {
        let config = TemplateConfig::new()
            .system("You are a helpful assistant")
            .prompt("User: {input}")
            .response("Response format");

        assert_eq!(
            config.system,
            Some("You are a helpful assistant".to_string())
        );
        assert_eq!(config.prompt, Some("User: {input}".to_string()));
        assert_eq!(config.response, Some("Response format".to_string()));
        assert!(config.use_system_prompt);
    }

    #[test]
    fn test_memory_config_builder() {
        let config = MemoryConfig::new()
            .with_long_term()
            .provider("chroma")
            .max_messages(50);

        assert!(config.use_long_term);
        assert_eq!(config.provider, "chroma");
        assert_eq!(config.max_messages, 50);
    }

    #[test]
    fn test_output_config() {
        let config = OutputConfig::new().silent().file("output.txt");
        assert_eq!(config.mode, "silent");
        assert_eq!(config.file, Some("output.txt".to_string()));
    }
}