spec-ai 0.8.4

A framework for building AI agents with structured outputs, policy enforcement, and execution tracking
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
//! Application-level configuration
//!
//! Defines the top-level application configuration, including model settings,
//! database configuration, UI preferences, and logging.

use crate::spec_ai_config::config::agent::AgentProfile;
use anyhow::{Context, Result};
use directories::BaseDirs;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::PathBuf;

/// Embedded default configuration file
const DEFAULT_CONFIG: &str =
    include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/spec-ai.config.toml"));

/// Configuration file name
const CONFIG_FILE_NAME: &str = "spec-ai.config.toml";

/// Top-level application configuration
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct AppConfig {
    /// Database configuration
    #[serde(default)]
    pub database: DatabaseConfig,
    /// Model provider configuration
    #[serde(default)]
    pub model: ModelConfig,
    /// UI configuration
    #[serde(default)]
    pub ui: UiConfig,
    /// Logging configuration
    #[serde(default)]
    pub logging: LoggingConfig,
    /// Audio transcription configuration
    #[serde(default)]
    pub audio: AudioConfig,
    /// Mesh networking configuration
    #[serde(default)]
    pub mesh: MeshConfig,
    /// Plugin configuration for custom tools
    #[serde(default)]
    pub plugins: PluginConfig,
    /// Graph synchronization configuration
    #[serde(default)]
    pub sync: SyncConfig,
    /// Agent Skills Protocol configuration (https://agentskills.io)
    #[serde(default)]
    pub skills: SkillsConfig,
    /// Model Context Protocol (MCP) configuration
    #[serde(default)]
    pub mcp: McpConfig,
    /// HTTP API authentication configuration
    #[serde(default)]
    pub auth: AuthConfig,
    /// Recursion and cost safety configuration
    #[serde(default)]
    pub safety: SafetyConfig,
    /// Tool approval behavior for eligible tools
    #[serde(default)]
    pub approval: ApprovalConfig,
    /// Available agent profiles
    #[serde(default)]
    pub agents: HashMap<String, AgentProfile>,
    /// Default agent to use (if not specified)
    #[serde(default)]
    pub default_agent: Option<String>,
}

impl AppConfig {
    /// Load configuration from file or create a default configuration
    pub fn load() -> Result<Self> {
        // Try to load from spec-ai.config.toml in current directory
        if let Ok(content) = std::fs::read_to_string(CONFIG_FILE_NAME) {
            return toml::from_str(&content)
                .map_err(|e| anyhow::anyhow!("Failed to parse {}: {}", CONFIG_FILE_NAME, e));
        }

        // Try to load from ~/.spec-ai/spec-ai.config.toml
        if let Ok(base_dirs) =
            BaseDirs::new().ok_or(anyhow::anyhow!("Could not determine home directory"))
        {
            let home_config = base_dirs.home_dir().join(".spec-ai").join(CONFIG_FILE_NAME);
            if let Ok(content) = std::fs::read_to_string(&home_config) {
                return toml::from_str(&content).map_err(|e| {
                    anyhow::anyhow!("Failed to parse {}: {}", home_config.display(), e)
                });
            }
        }

        // Try to load from environment variable CONFIG_PATH
        if let Ok(config_path) = std::env::var("CONFIG_PATH") {
            if let Ok(content) = std::fs::read_to_string(&config_path) {
                return toml::from_str(&content)
                    .map_err(|e| anyhow::anyhow!("Failed to parse config: {}", e));
            }
        }

        // No config file found - create one from embedded default
        eprintln!(
            "No configuration file found. Creating {} with default settings...",
            CONFIG_FILE_NAME
        );
        if let Err(e) = std::fs::write(CONFIG_FILE_NAME, DEFAULT_CONFIG) {
            eprintln!("Warning: Could not create {}: {}", CONFIG_FILE_NAME, e);
            eprintln!("Continuing with default configuration in memory.");
        } else {
            eprintln!(
                "Created {}. You can edit this file to customize your settings.",
                CONFIG_FILE_NAME
            );
        }

        // Parse and return the embedded default config
        toml::from_str(DEFAULT_CONFIG)
            .map_err(|e| anyhow::anyhow!("Failed to parse embedded default config: {}", e))
    }

    /// Load configuration from a specific file path
    /// If the file doesn't exist, creates it with default settings
    pub fn load_from_file(path: &std::path::Path) -> Result<Self> {
        // Try to read existing file
        match std::fs::read_to_string(path) {
            Ok(content) => toml::from_str(&content).map_err(|e| {
                anyhow::anyhow!("Failed to parse config file {}: {}", path.display(), e)
            }),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
                // File doesn't exist - create it with default config
                eprintln!(
                    "Configuration file not found at {}. Creating with default settings...",
                    path.display()
                );

                // Create parent directories if needed
                if let Some(parent) = path.parent() {
                    std::fs::create_dir_all(parent)
                        .context(format!("Failed to create directory {}", parent.display()))?;
                }

                // Write default config
                std::fs::write(path, DEFAULT_CONFIG).context(format!(
                    "Failed to create config file at {}",
                    path.display()
                ))?;

                eprintln!(
                    "Created {}. You can edit this file to customize your settings.",
                    path.display()
                );

                // Parse and return the embedded default config
                toml::from_str(DEFAULT_CONFIG)
                    .map_err(|e| anyhow::anyhow!("Failed to parse embedded default config: {}", e))
            }
            Err(e) => Err(anyhow::anyhow!(
                "Failed to read config file {}: {}",
                path.display(),
                e
            )),
        }
    }

    /// Validate the configuration
    pub fn validate(&self) -> Result<()> {
        // Validate model provider: must be non-empty and supported
        if self.model.provider.is_empty() {
            return Err(anyhow::anyhow!("Model provider cannot be empty"));
        }
        // Validate against known provider names independent of compile-time feature flags
        {
            let p = self.model.provider.to_lowercase();
            let known = ["mock", "openai", "anthropic", "ollama", "mlx", "lmstudio"];
            if !known.contains(&p.as_str()) {
                return Err(anyhow::anyhow!(
                    "Invalid model provider: {}",
                    self.model.provider
                ));
            }
        }

        // Validate temperature
        if self.model.temperature < 0.0 || self.model.temperature > 2.0 {
            return Err(anyhow::anyhow!(
                "Temperature must be between 0.0 and 2.0, got {}",
                self.model.temperature
            ));
        }

        self.safety.validate()?;
        self.approval.validate()?;

        // Validate log level
        match self.logging.level.as_str() {
            "trace" | "debug" | "info" | "warn" | "error" => {}
            _ => return Err(anyhow::anyhow!("Invalid log level: {}", self.logging.level)),
        }

        // If a default agent is specified, it must exist in the agents map
        if let Some(default_agent) = &self.default_agent {
            if !self.agents.contains_key(default_agent) {
                return Err(anyhow::anyhow!(
                    "Default agent '{}' not found in agents map",
                    default_agent
                ));
            }
        }

        Ok(())
    }

    /// Apply environment variable overrides to the configuration
    pub fn apply_env_overrides(&mut self) {
        // Helper: prefer AGENT_* over SPEC_AI_* if both present
        fn first(a: &str, b: &str) -> Option<String> {
            std::env::var(a).ok().or_else(|| std::env::var(b).ok())
        }

        if let Some(provider) = first("AGENT_MODEL_PROVIDER", "SPEC_AI_PROVIDER") {
            self.model.provider = provider;
        }
        if let Some(model_name) = first("AGENT_MODEL_NAME", "SPEC_AI_MODEL") {
            self.model.model_name = Some(model_name);
        }
        if let Some(code_model) = first("AGENT_CODE_MODEL", "SPEC_AI_CODE_MODEL") {
            self.model.code_model = Some(code_model);
        }
        if let Some(api_key_source) = first("AGENT_API_KEY_SOURCE", "SPEC_AI_API_KEY_SOURCE") {
            self.model.api_key_source = Some(api_key_source);
        }
        if let Some(temp_str) = first("AGENT_MODEL_TEMPERATURE", "SPEC_AI_TEMPERATURE") {
            if let Ok(temp) = temp_str.parse::<f32>() {
                self.model.temperature = temp;
            }
        }
        if let Some(level) = first("AGENT_LOG_LEVEL", "SPEC_AI_LOG_LEVEL") {
            self.logging.level = level;
        }
        if let Some(db_path) = first("AGENT_DB_PATH", "SPEC_AI_DB_PATH") {
            self.database.path = PathBuf::from(db_path);
        }
        if let Some(theme) = first("AGENT_UI_THEME", "SPEC_AI_UI_THEME") {
            self.ui.theme = theme;
        }
        if let Some(default_agent) = first("AGENT_DEFAULT_AGENT", "SPEC_AI_DEFAULT_AGENT") {
            self.default_agent = Some(default_agent);
        }
        if let Some(value) = first(
            "AGENT_MAX_MODEL_CALLS_PER_RUN",
            "SPEC_AI_MAX_MODEL_CALLS_PER_RUN",
        ) {
            if let Ok(parsed) = value.parse::<usize>() {
                self.safety.max_model_calls_per_run = parsed;
            }
        }
        if let Some(value) = first(
            "AGENT_MAX_TOOL_CALLS_PER_RUN",
            "SPEC_AI_MAX_TOOL_CALLS_PER_RUN",
        ) {
            if let Ok(parsed) = value.parse::<usize>() {
                self.safety.max_tool_calls_per_run = parsed;
            }
        }
        if let Some(value) = first(
            "AGENT_MAX_TOOL_LOOP_ITERATIONS",
            "SPEC_AI_MAX_TOOL_LOOP_ITERATIONS",
        ) {
            if let Ok(parsed) = value.parse::<usize>() {
                self.safety.max_tool_loop_iterations = parsed;
            }
        }
        if let Some(value) = first(
            "AGENT_MAX_TOTAL_TOKENS_PER_RUN",
            "SPEC_AI_MAX_TOTAL_TOKENS_PER_RUN",
        ) {
            if let Ok(parsed) = value.parse::<u64>() {
                self.safety.max_total_tokens_per_run = parsed;
            }
        }
        if let Some(value) = first(
            "AGENT_MAX_OUTPUT_TOKENS_PER_CALL",
            "SPEC_AI_MAX_OUTPUT_TOKENS_PER_CALL",
        ) {
            if let Ok(parsed) = value.parse::<u32>() {
                self.safety.max_output_tokens_per_call = parsed;
            }
        }
    }

    /// Get a summary of the configuration
    pub fn summary(&self) -> String {
        let mut summary = String::new();
        summary.push_str("Configuration loaded:\n");
        summary.push_str(&format!("Database: {}\n", self.database.path.display()));
        summary.push_str(&format!("Model Provider: {}\n", self.model.provider));
        if let Some(model) = &self.model.model_name {
            summary.push_str(&format!("Model Name: {}\n", model));
        }
        if let Some(code_model) = &self.model.code_model {
            summary.push_str(&format!("Code Model: {}\n", code_model));
        }
        summary.push_str(&format!("Temperature: {}\n", self.model.temperature));
        summary.push_str(&format!("Logging Level: {}\n", self.logging.level));
        summary.push_str(&format!("Approval Mode: {}\n", self.approval.mode.as_str()));
        summary.push_str(&format!("UI Theme: {}\n", self.ui.theme));
        summary.push_str(&format!("Available Agents: {}\n", self.agents.len()));
        if let Some(default) = &self.default_agent {
            summary.push_str(&format!("Default Agent: {}\n", default));
        }
        summary
    }
}

/// Approval behavior for tool calls after capability and policy filters pass.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ApprovalConfig {
    /// Default approval mode for eligible tools.
    #[serde(default = "default_approval_mode")]
    pub mode: ApprovalMode,
    /// Per-tool approval overrides keyed by registered tool name.
    #[serde(default)]
    pub tools: HashMap<String, ApprovalMode>,
}

impl ApprovalConfig {
    pub fn validate(&self) -> Result<()> {
        for tool_name in self.tools.keys() {
            if tool_name.trim().is_empty() {
                return Err(anyhow::anyhow!(
                    "approval.tools contains an empty tool name"
                ));
            }
        }
        Ok(())
    }

    pub fn mode_for_tool(&self, tool_name: &str) -> ApprovalMode {
        self.tools.get(tool_name).copied().unwrap_or(self.mode)
    }
}

impl Default for ApprovalConfig {
    fn default() -> Self {
        Self {
            mode: default_approval_mode(),
            tools: HashMap::new(),
        }
    }
}

/// Tool approval mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ApprovalMode {
    /// Prompt the user for every eligible tool call.
    Ask,
    /// Ask the configured model to approve or deny the tool call.
    Auto,
    /// Approve the matching tool without prompting.
    Allow,
    /// Approve all eligible tools without prompting.
    AllowAll,
    /// Deny the matching tool without prompting.
    Deny,
}

impl ApprovalMode {
    pub fn as_str(&self) -> &'static str {
        match self {
            ApprovalMode::Ask => "ask",
            ApprovalMode::Auto => "auto",
            ApprovalMode::Allow => "allow",
            ApprovalMode::AllowAll => "allow_all",
            ApprovalMode::Deny => "deny",
        }
    }

    pub fn is_allowing(&self) -> bool {
        matches!(self, ApprovalMode::Allow | ApprovalMode::AllowAll)
    }
}

fn default_approval_mode() -> ApprovalMode {
    ApprovalMode::Ask
}

/// Database configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DatabaseConfig {
    /// Path to the database file
    pub path: PathBuf,
}

impl Default for DatabaseConfig {
    fn default() -> Self {
        Self {
            path: PathBuf::from("spec-ai.duckdb"),
        }
    }
}

/// Model provider configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ModelConfig {
    /// Provider name (e.g., "openai", "anthropic", "mlx", "lmstudio", "mock")
    pub provider: String,
    /// Model name to use (e.g., "gpt-5", "claude-opus-4-8")
    #[serde(default)]
    pub model_name: Option<String>,
    /// Dedicated text model for code generation/review tasks
    #[serde(default)]
    pub code_model: Option<String>,
    /// Embeddings model name (optional, for semantic search)
    #[serde(default)]
    pub embeddings_model: Option<String>,
    /// API key source (e.g., environment variable name or path)
    #[serde(default)]
    pub api_key_source: Option<String>,
    /// Default temperature for model completions (0.0 to 2.0)
    #[serde(default = "default_temperature")]
    pub temperature: f32,
}

/// Recursion and cost safety configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SafetyConfig {
    /// Enable run-level safety guards.
    #[serde(default = "default_safety_enabled")]
    pub enabled: bool,
    /// Maximum model calls allowed in a single agent run.
    #[serde(default = "default_max_model_calls_per_run")]
    pub max_model_calls_per_run: usize,
    /// Maximum tool calls allowed in a single agent run.
    #[serde(default = "default_max_tool_calls_per_run")]
    pub max_tool_calls_per_run: usize,
    /// Maximum model/tool loop iterations allowed in a single agent run.
    #[serde(default = "default_max_tool_loop_iterations")]
    pub max_tool_loop_iterations: usize,
    /// Maximum repeated calls to the same tool with identical arguments.
    #[serde(default = "default_max_repeated_tool_calls")]
    pub max_repeated_tool_calls: usize,
    /// Maximum accumulated tokens allowed in a single agent run.
    #[serde(default = "default_max_total_tokens_per_run")]
    pub max_total_tokens_per_run: u64,
    /// Maximum output tokens requested for any single model call.
    #[serde(default = "default_max_output_tokens_per_call")]
    pub max_output_tokens_per_call: u32,
    /// Maximum accumulated prompt bytes allowed in a single agent run.
    #[serde(default = "default_max_prompt_bytes_per_run")]
    pub max_prompt_bytes_per_run: usize,
    /// Maximum tool output bytes allowed before the run is stopped.
    #[serde(default = "default_max_tool_output_bytes")]
    pub max_tool_output_bytes: usize,
    /// Maximum delegation chain depth for mesh/collective task delegation.
    #[serde(default = "default_max_delegation_depth")]
    pub max_delegation_depth: usize,
}

fn default_safety_enabled() -> bool {
    true
}

fn default_max_model_calls_per_run() -> usize {
    6
}

fn default_max_tool_calls_per_run() -> usize {
    12
}

fn default_max_tool_loop_iterations() -> usize {
    5
}

fn default_max_repeated_tool_calls() -> usize {
    3
}

fn default_max_total_tokens_per_run() -> u64 {
    50_000
}

fn default_max_output_tokens_per_call() -> u32 {
    4_096
}

fn default_max_prompt_bytes_per_run() -> usize {
    200_000
}

fn default_max_tool_output_bytes() -> usize {
    64_000
}

fn default_max_delegation_depth() -> usize {
    3
}

impl SafetyConfig {
    pub fn validate(&self) -> Result<()> {
        if !self.enabled {
            return Ok(());
        }

        if self.max_model_calls_per_run == 0 {
            return Err(anyhow::anyhow!(
                "safety.max_model_calls_per_run must be greater than 0"
            ));
        }
        if self.max_tool_calls_per_run == 0 {
            return Err(anyhow::anyhow!(
                "safety.max_tool_calls_per_run must be greater than 0"
            ));
        }
        if self.max_tool_loop_iterations == 0 {
            return Err(anyhow::anyhow!(
                "safety.max_tool_loop_iterations must be greater than 0"
            ));
        }
        if self.max_repeated_tool_calls == 0 {
            return Err(anyhow::anyhow!(
                "safety.max_repeated_tool_calls must be greater than 0"
            ));
        }
        if self.max_total_tokens_per_run == 0 {
            return Err(anyhow::anyhow!(
                "safety.max_total_tokens_per_run must be greater than 0"
            ));
        }
        if self.max_output_tokens_per_call == 0 {
            return Err(anyhow::anyhow!(
                "safety.max_output_tokens_per_call must be greater than 0"
            ));
        }
        if self.max_prompt_bytes_per_run == 0 {
            return Err(anyhow::anyhow!(
                "safety.max_prompt_bytes_per_run must be greater than 0"
            ));
        }
        if self.max_tool_output_bytes == 0 {
            return Err(anyhow::anyhow!(
                "safety.max_tool_output_bytes must be greater than 0"
            ));
        }

        Ok(())
    }
}

impl Default for SafetyConfig {
    fn default() -> Self {
        Self {
            enabled: default_safety_enabled(),
            max_model_calls_per_run: default_max_model_calls_per_run(),
            max_tool_calls_per_run: default_max_tool_calls_per_run(),
            max_tool_loop_iterations: default_max_tool_loop_iterations(),
            max_repeated_tool_calls: default_max_repeated_tool_calls(),
            max_total_tokens_per_run: default_max_total_tokens_per_run(),
            max_output_tokens_per_call: default_max_output_tokens_per_call(),
            max_prompt_bytes_per_run: default_max_prompt_bytes_per_run(),
            max_tool_output_bytes: default_max_tool_output_bytes(),
            max_delegation_depth: default_max_delegation_depth(),
        }
    }
}

fn default_temperature() -> f32 {
    0.7
}

impl Default for ModelConfig {
    fn default() -> Self {
        Self {
            provider: "mock".to_string(),
            model_name: None,
            code_model: None,
            embeddings_model: None,
            api_key_source: None,
            temperature: default_temperature(),
        }
    }
}

/// UI configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UiConfig {
    /// Command prompt string
    pub prompt: String,
    /// UI theme name
    pub theme: String,
}

impl Default for UiConfig {
    fn default() -> Self {
        Self {
            prompt: "> ".to_string(),
            theme: "default".to_string(),
        }
    }
}

/// Logging configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LoggingConfig {
    /// Log level (trace, debug, info, warn, error)
    pub level: String,
}

impl Default for LoggingConfig {
    fn default() -> Self {
        Self {
            level: "info".to_string(),
        }
    }
}

/// Mesh networking configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MeshConfig {
    /// Enable mesh networking
    #[serde(default)]
    pub enabled: bool,
    /// Registry port for mesh coordination
    #[serde(default = "default_registry_port")]
    pub registry_port: u16,
    /// Heartbeat interval in seconds
    #[serde(default = "default_heartbeat_interval")]
    pub heartbeat_interval_secs: u64,
    /// Leader timeout in seconds (how long before new election)
    #[serde(default = "default_leader_timeout")]
    pub leader_timeout_secs: u64,
    /// Replication factor for knowledge graph
    #[serde(default = "default_replication_factor")]
    pub replication_factor: usize,
    /// Auto-join mesh on startup
    #[serde(default)]
    pub auto_join: bool,
}

fn default_registry_port() -> u16 {
    3000
}

fn default_heartbeat_interval() -> u64 {
    5
}

fn default_leader_timeout() -> u64 {
    15
}

fn default_replication_factor() -> usize {
    2
}

impl Default for MeshConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            registry_port: default_registry_port(),
            heartbeat_interval_secs: default_heartbeat_interval(),
            leader_timeout_secs: default_leader_timeout(),
            replication_factor: default_replication_factor(),
            auto_join: true,
        }
    }
}

/// Audio transcription configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AudioConfig {
    /// Enable audio transcription
    #[serde(default)]
    pub enabled: bool,
    /// Transcription provider (mock, vttrs)
    #[serde(default = "default_transcription_provider")]
    pub provider: String,
    /// Transcription model (e.g., "whisper-1", "whisper-large-v3")
    #[serde(default)]
    pub model: Option<String>,
    /// API key source for cloud transcription
    #[serde(default)]
    pub api_key_source: Option<String>,
    /// Use on-device transcription (offline mode)
    #[serde(default)]
    pub on_device: bool,
    /// Custom API endpoint (optional)
    #[serde(default)]
    pub endpoint: Option<String>,
    /// Audio chunk duration in seconds
    #[serde(default = "default_chunk_duration")]
    pub chunk_duration_secs: f64,
    /// Default transcription duration in seconds
    #[serde(default = "default_duration")]
    pub default_duration_secs: u64,
    /// Default transcription duration in seconds (legacy field name)
    #[serde(default = "default_duration")]
    pub default_duration: u64,
    /// Output file path for transcripts (optional)
    #[serde(default)]
    pub out_file: Option<String>,
    /// Language code (e.g., "en", "es", "fr")
    #[serde(default)]
    pub language: Option<String>,
    /// Whether to automatically respond to transcriptions
    #[serde(default)]
    pub auto_respond: bool,
    /// Mock scenario for testing (e.g., "simple_conversation", "emotional_context")
    #[serde(default = "default_mock_scenario")]
    pub mock_scenario: String,
    /// Delay between mock transcription events in milliseconds
    #[serde(default = "default_event_delay_ms")]
    pub event_delay_ms: u64,
    /// Speak assistant responses aloud (macOS only, uses `say`)
    #[serde(default)]
    pub speak_responses: bool,
}

fn default_transcription_provider() -> String {
    "vttrs".to_string()
}

fn default_chunk_duration() -> f64 {
    5.0
}

fn default_duration() -> u64 {
    30
}

fn default_mock_scenario() -> String {
    "simple_conversation".to_string()
}

fn default_event_delay_ms() -> u64 {
    500
}

impl Default for AudioConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            provider: default_transcription_provider(),
            model: Some("whisper-1".to_string()),
            api_key_source: None,
            on_device: false,
            endpoint: None,
            chunk_duration_secs: default_chunk_duration(),
            default_duration_secs: default_duration(),
            default_duration: default_duration(),
            out_file: None,
            language: None,
            auto_respond: false,
            mock_scenario: default_mock_scenario(),
            event_delay_ms: default_event_delay_ms(),
            speak_responses: false,
        }
    }
}

/// Plugin configuration for custom tools
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PluginConfig {
    /// Enable plugin loading
    #[serde(default)]
    pub enabled: bool,

    /// Directory containing plugin libraries (.dylib/.so/.dll)
    #[serde(default = "default_plugins_dir")]
    pub custom_tools_dir: PathBuf,

    /// Continue startup even if some plugins fail to load
    #[serde(default = "default_continue_on_error")]
    pub continue_on_error: bool,

    /// Allow plugins to override built-in tools
    #[serde(default)]
    pub allow_override_builtin: bool,
}

fn default_plugins_dir() -> PathBuf {
    PathBuf::from("~/.spec-ai/tools")
}

fn default_continue_on_error() -> bool {
    true
}

impl Default for PluginConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            custom_tools_dir: default_plugins_dir(),
            continue_on_error: true,
            allow_override_builtin: false,
        }
    }
}

/// HTTP API authentication configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuthConfig {
    /// Enable authentication for the HTTP API
    #[serde(default)]
    pub enabled: bool,

    /// Path to JSON file containing user credentials
    /// The file should contain an array of objects with "username" and "password_hash" fields
    /// Password hashes should be created using bcrypt
    #[serde(default)]
    pub credentials_file: Option<PathBuf>,

    /// Token expiration time in seconds (default: 24 hours)
    #[serde(default = "default_token_expiry")]
    pub token_expiry_secs: u64,

    /// Secret key for signing tokens (if not set, a random key is generated at startup)
    /// Can be set via environment variable for consistency across restarts
    #[serde(default)]
    pub token_secret: Option<String>,
}

fn default_token_expiry() -> u64 {
    86400 // 24 hours
}

impl Default for AuthConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            credentials_file: None,
            token_expiry_secs: default_token_expiry(),
            token_secret: None,
        }
    }
}

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

    #[test]
    fn safety_config_defaults_are_strict() {
        let safety = SafetyConfig::default();

        assert!(safety.enabled);
        assert_eq!(safety.max_model_calls_per_run, 6);
        assert_eq!(safety.max_tool_calls_per_run, 12);
        assert_eq!(safety.max_tool_loop_iterations, 5);
        assert_eq!(safety.max_repeated_tool_calls, 3);
        assert_eq!(safety.max_total_tokens_per_run, 50_000);
        assert_eq!(safety.max_output_tokens_per_call, 4_096);
        assert!(safety.validate().is_ok());
    }

    #[test]
    fn safety_config_rejects_zero_limits_when_enabled() {
        let safety = SafetyConfig {
            max_model_calls_per_run: 0,
            ..SafetyConfig::default()
        };

        assert!(safety.validate().is_err());
    }

    #[test]
    fn app_config_parses_safety_section() {
        let toml = r#"
[model]
provider = "mock"

[safety]
max_model_calls_per_run = 9
max_tool_calls_per_run = 20
"#;

        let config: AppConfig = toml::from_str(toml).unwrap();

        assert_eq!(config.safety.max_model_calls_per_run, 9);
        assert_eq!(config.safety.max_tool_calls_per_run, 20);
        assert!(config.safety.enabled);
    }
}

/// Graph synchronization configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SyncConfig {
    /// Enable graph synchronization
    #[serde(default)]
    pub enabled: bool,

    /// How often to check for sync opportunities (in seconds)
    #[serde(default = "default_sync_interval")]
    pub interval_secs: u64,

    /// Maximum number of concurrent sync operations
    #[serde(default = "default_max_concurrent_syncs")]
    pub max_concurrent_syncs: usize,

    /// Retry interval for failed syncs (in seconds)
    #[serde(default = "default_retry_interval")]
    pub retry_interval_secs: u64,

    /// Maximum number of retry attempts
    #[serde(default = "default_max_retries")]
    pub max_retries: usize,

    /// Graph namespaces to sync automatically on startup
    #[serde(default)]
    pub namespaces: Vec<SyncNamespace>,
}

/// A graph namespace to participate in synchronization
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SyncNamespace {
    /// Session ID (namespace) for the graph
    pub session_id: String,
    /// Graph name within the session (defaults to "default")
    #[serde(default = "default_graph_name")]
    pub graph_name: String,
}

fn default_sync_interval() -> u64 {
    60
}

fn default_max_concurrent_syncs() -> usize {
    3
}

fn default_retry_interval() -> u64 {
    300
}

fn default_max_retries() -> usize {
    3
}

fn default_graph_name() -> String {
    "default".to_string()
}

impl Default for SyncConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            interval_secs: default_sync_interval(),
            max_concurrent_syncs: default_max_concurrent_syncs(),
            retry_interval_secs: default_retry_interval(),
            max_retries: default_max_retries(),
            namespaces: Vec::new(),
        }
    }
}

/// Agent Skills Protocol configuration (https://agentskills.io)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SkillsConfig {
    /// Enable Agent Skills Protocol support
    #[serde(default = "default_true")]
    pub enabled: bool,

    /// Directories to scan for skills (SKILL.md files)
    #[serde(default = "default_skills_dirs")]
    pub skills_dirs: Vec<PathBuf>,
}

fn default_skills_dirs() -> Vec<PathBuf> {
    vec![PathBuf::from("~/.agents/skills")]
}

impl Default for SkillsConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            skills_dirs: default_skills_dirs(),
        }
    }
}

/// Model Context Protocol (MCP) configuration
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct McpConfig {
    /// Enable MCP support
    #[serde(default = "default_true")]
    pub enabled: bool,

    /// Configuration for MCP servers
    #[serde(default)]
    pub servers: HashMap<String, McpServerConfig>,
}

/// Configuration for an individual MCP server
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpServerConfig {
    /// Command to execute (stdio transport)
    pub command: String,

    /// Arguments to pass to the command
    #[serde(default)]
    pub args: Vec<String>,

    /// Environment variables for the server process
    #[serde(default)]
    pub env: HashMap<String, String>,
}

fn default_true() -> bool {
    true
}