Skip to main content

codive_core/
config.rs

1//! Configuration types for the Agent system
2//!
3//! This module defines configuration structures that control agent behavior.
4//! All configs have sensible defaults and can be loaded from files or environment.
5//!
6//! # Design Principles
7//!
8//! 1. **Sensible Defaults** - Should work out of the box
9//! 2. **Optional Fields** - Only require what's essential
10//! 3. **Serializable** - Can be loaded from TOML/JSON/YAML
11//! 4. **Type Safe** - Invalid configs won't compile
12//!
13//! # Loading Configuration
14//!
15//! Configuration is loaded from multiple sources with the following priority:
16//! 1. Environment variables (highest priority)
17//! 2. Config file (if specified or found)
18//! 3. Default values (lowest priority)
19//!
20//! ## Config File Discovery
21//!
22//! If no config file is specified, the following locations are searched:
23//! 1. `./agent.toml` (current directory)
24//! 2. `~/.config/agent/config.toml` (user config directory)
25//!
26//! ## Environment Variables
27//!
28//! The following environment variables are supported:
29//! - `ANTHROPIC_API_KEY` - API key for Anthropic
30//! - `OPENAI_API_KEY` - API key for OpenAI
31//! - `AGENT_MODEL` - Override the default model
32//! - `AGENT_PROVIDER` - Override the default provider
33//!
34//! # Example
35//!
36//! ```rust,ignore
37//! use codive_core::config::AppConfig;
38//!
39//! // Load from default locations with env var overrides
40//! let config = AppConfig::load(None)?;
41//!
42//! // Load from specific file
43//! let config = AppConfig::load(Some("./my-config.toml"))?;
44//! ```
45
46use codive_prompts::{EnvironmentContext, PromptComposer, PromptStore};
47use serde::{Deserialize, Serialize};
48use std::collections::HashMap;
49use std::path::{Path, PathBuf};
50
51// ============================================================================
52// Provider Registry
53// ============================================================================
54
55/// Information about a supported LLM provider
56#[derive(Debug, Clone, Copy)]
57pub struct ProviderInfo {
58    /// Provider name (e.g., "anthropic", "openai", "gemini")
59    pub name: &'static str,
60    /// Environment variable for API key
61    pub env_var: &'static str,
62    /// Default model for this provider
63    pub default_model: &'static str,
64}
65
66/// Registry of supported providers in priority order.
67/// When auto-detecting, the first provider with an available API key is used.
68/// Models are selected for best coding performance (as of Jan 2026).
69pub const PROVIDERS: &[ProviderInfo] = &[
70    ProviderInfo {
71        name: "anthropic",
72        env_var: "ANTHROPIC_API_KEY",
73        default_model: "claude-opus-4-5-20251101", // Opus 4.5 - best coding model
74    },
75    ProviderInfo {
76        name: "openai",
77        env_var: "OPENAI_API_KEY",
78        default_model: "gpt-5.2-2025-12-11", // GPT-5.2 - latest and best OpenAI model
79    },
80    ProviderInfo {
81        name: "gemini",
82        env_var: "GEMINI_API_KEY",
83        default_model: "gemini-2.5-pro", // Gemini 2.5 Pro - stable with adaptive thinking
84    },
85];
86
87/// Get provider info by name
88pub fn get_provider(name: &str) -> Option<&'static ProviderInfo> {
89    PROVIDERS.iter().find(|p| p.name == name)
90}
91
92/// Detect the best available provider based on API keys.
93/// Returns the first provider that has an API key set in the environment.
94pub fn detect_provider() -> Option<&'static ProviderInfo> {
95    PROVIDERS
96        .iter()
97        .find(|p| std::env::var(p.env_var).is_ok())
98}
99
100// ============================================================================
101// ModelConfig
102// ============================================================================
103
104/// Configuration for the LLM model
105///
106/// Controls which provider and model to use, along with generation parameters.
107#[derive(Debug, Clone, Serialize, Deserialize)]
108pub struct ModelConfig {
109    /// Provider name (e.g., "anthropic", "openai")
110    #[serde(default = "default_provider")]
111    pub provider: String,
112
113    /// Model identifier (e.g., "claude-3-opus-20240229", "gpt-4")
114    #[serde(default = "default_model")]
115    pub model: String,
116
117    /// Maximum tokens to generate per response
118    #[serde(default = "default_max_tokens")]
119    pub max_tokens: u32,
120
121    /// Temperature for sampling (0.0 = deterministic, 1.0 = creative)
122    #[serde(default = "default_temperature")]
123    pub temperature: f32,
124
125    /// Optional API key (if not set, reads from environment)
126    #[serde(default, skip_serializing_if = "Option::is_none")]
127    pub api_key: Option<String>,
128
129    /// Optional API base URL (for custom endpoints)
130    #[serde(default, skip_serializing_if = "Option::is_none")]
131    pub api_base: Option<String>,
132}
133
134fn default_provider() -> String {
135    "anthropic".to_string()
136}
137
138fn default_model() -> String {
139    "claude-opus-4-5-20251101".to_string()
140}
141
142fn default_max_tokens() -> u32 {
143    4096
144}
145
146fn default_temperature() -> f32 {
147    0.0
148}
149
150impl Default for ModelConfig {
151    fn default() -> Self {
152        Self {
153            provider: default_provider(),
154            model: default_model(),
155            max_tokens: default_max_tokens(),
156            temperature: default_temperature(),
157            api_key: None,
158            api_base: None,
159        }
160    }
161}
162
163impl ModelConfig {
164    /// Create a new model config with the given provider and model
165    pub fn new(provider: impl Into<String>, model: impl Into<String>) -> Self {
166        Self {
167            provider: provider.into(),
168            model: model.into(),
169            ..Default::default()
170        }
171    }
172
173    /// Set the maximum tokens
174    pub fn with_max_tokens(mut self, max_tokens: u32) -> Self {
175        self.max_tokens = max_tokens;
176        self
177    }
178
179    /// Set the temperature
180    pub fn with_temperature(mut self, temperature: f32) -> Self {
181        self.temperature = temperature;
182        self
183    }
184
185    /// Set the API key
186    pub fn with_api_key(mut self, api_key: impl Into<String>) -> Self {
187        self.api_key = Some(api_key.into());
188        self
189    }
190
191    /// Set the API base URL
192    pub fn with_api_base(mut self, api_base: impl Into<String>) -> Self {
193        self.api_base = Some(api_base.into());
194        self
195    }
196}
197
198// ============================================================================
199// VerificationConfig
200// ============================================================================
201
202/// Configuration for AI-driven code verification
203///
204/// When enabled, the system prompt instructs the AI to automatically verify
205/// code changes by running appropriate build/test commands for the project type.
206/// The AI detects the project type and figures out the right commands to run.
207#[derive(Debug, Clone, Serialize, Deserialize)]
208pub struct VerificationConfig {
209    /// Whether AI-driven verification is enabled in the system prompt
210    /// When true, the AI is instructed to verify code changes before reporting success
211    #[serde(default = "default_verification_enabled")]
212    pub enabled: bool,
213}
214
215fn default_verification_enabled() -> bool {
216    true // Enabled by default for better code quality
217}
218
219impl Default for VerificationConfig {
220    fn default() -> Self {
221        Self {
222            enabled: default_verification_enabled(),
223        }
224    }
225}
226
227impl VerificationConfig {
228    /// Create a new verification config
229    pub fn new() -> Self {
230        Self::default()
231    }
232
233    /// Enable verification
234    pub fn enabled(mut self) -> Self {
235        self.enabled = true;
236        self
237    }
238
239    /// Disable verification
240    pub fn disabled(mut self) -> Self {
241        self.enabled = false;
242        self
243    }
244}
245
246// ============================================================================
247// AgentConfig
248// ============================================================================
249
250/// Configuration for an agent instance
251///
252/// Defines the agent's identity, behavior, and capabilities.
253#[derive(Debug, Clone, Serialize, Deserialize)]
254pub struct AgentConfig {
255    /// Agent name (used in logging and identification)
256    #[serde(default = "default_agent_name")]
257    pub name: String,
258
259    /// Human-readable description of the agent
260    #[serde(default, skip_serializing_if = "Option::is_none")]
261    pub description: Option<String>,
262
263    /// System prompt - instructions for the model
264    #[serde(default, skip_serializing_if = "Option::is_none")]
265    pub system_prompt: Option<String>,
266
267    /// Model configuration
268    #[serde(default)]
269    pub model: ModelConfig,
270
271    /// List of enabled tool names
272    #[serde(default)]
273    pub tools: Vec<String>,
274
275    /// Maximum steps (tool calls) per conversation turn
276    #[serde(default = "default_max_steps")]
277    pub max_steps: u32,
278
279    /// Maximum conversation history length (messages to keep)
280    #[serde(default = "default_max_history")]
281    pub max_history: usize,
282
283    /// Whether to allow parallel tool calls
284    #[serde(default = "default_parallel_tools")]
285    pub parallel_tool_calls: bool,
286
287    /// Verification configuration for auto-build/test
288    #[serde(default)]
289    pub verification: VerificationConfig,
290}
291
292fn default_agent_name() -> String {
293    "agent".to_string()
294}
295
296fn default_max_steps() -> u32 {
297    50
298}
299
300fn default_max_history() -> usize {
301    100
302}
303
304fn default_parallel_tools() -> bool {
305    true
306}
307
308impl Default for AgentConfig {
309    fn default() -> Self {
310        Self {
311            name: default_agent_name(),
312            description: None,
313            system_prompt: None,
314            model: ModelConfig::default(),
315            tools: Vec::new(),
316            max_steps: default_max_steps(),
317            max_history: default_max_history(),
318            parallel_tool_calls: default_parallel_tools(),
319            verification: VerificationConfig::default(),
320        }
321    }
322}
323
324impl AgentConfig {
325    /// Create a new agent config with the given name
326    pub fn new(name: impl Into<String>) -> Self {
327        Self {
328            name: name.into(),
329            ..Default::default()
330        }
331    }
332
333    /// Set the agent name
334    pub fn with_name(mut self, name: impl Into<String>) -> Self {
335        self.name = name.into();
336        self
337    }
338
339    /// Set the description
340    pub fn with_description(mut self, description: impl Into<String>) -> Self {
341        self.description = Some(description.into());
342        self
343    }
344
345    /// Set the system prompt
346    pub fn with_system_prompt(mut self, prompt: impl Into<String>) -> Self {
347        self.system_prompt = Some(prompt.into());
348        self
349    }
350
351    /// Set the model configuration
352    pub fn with_model(mut self, model: ModelConfig) -> Self {
353        self.model = model;
354        self
355    }
356
357    /// Set enabled tools
358    pub fn with_tools(mut self, tools: Vec<String>) -> Self {
359        self.tools = tools;
360        self
361    }
362
363    /// Add a single tool to enabled tools
364    pub fn with_tool(mut self, tool: impl Into<String>) -> Self {
365        self.tools.push(tool.into());
366        self
367    }
368
369    /// Set maximum steps
370    pub fn with_max_steps(mut self, max_steps: u32) -> Self {
371        self.max_steps = max_steps;
372        self
373    }
374
375    /// Set maximum history length
376    pub fn with_max_history(mut self, max_history: usize) -> Self {
377        self.max_history = max_history;
378        self
379    }
380
381    /// Set whether to allow parallel tool calls
382    pub fn with_parallel_tool_calls(mut self, parallel: bool) -> Self {
383        self.parallel_tool_calls = parallel;
384        self
385    }
386
387    /// Set verification configuration
388    pub fn with_verification(mut self, verification: VerificationConfig) -> Self {
389        self.verification = verification;
390        self
391    }
392
393    /// Build the system prompt using the PromptStore
394    ///
395    /// This composes the system prompt from multiple layers:
396    /// 1. Base prompt (agent identity)
397    /// 2. Provider-specific instructions (based on model)
398    /// 3. Environment context (working dir, git status, date)
399    /// 4. Verification instructions (if enabled)
400    ///
401    /// If a custom system_prompt is set, it takes precedence.
402    pub fn build_system_prompt(&self, store: &PromptStore) -> String {
403        // Custom prompt override takes precedence
404        if let Some(ref custom) = self.system_prompt {
405            return custom.clone();
406        }
407
408        PromptComposer::new(store)
409            .with_base()
410            .with_provider_auto(&self.model.model)
411            .with_current_environment()
412            .with_verification_if(self.verification.enabled)
413            .compose()
414    }
415
416    /// Build system prompt with custom environment context
417    pub fn build_system_prompt_with_env(
418        &self,
419        store: &PromptStore,
420        env: EnvironmentContext,
421    ) -> String {
422        if let Some(ref custom) = self.system_prompt {
423            return custom.clone();
424        }
425
426        PromptComposer::new(store)
427            .with_base()
428            .with_provider_auto(&self.model.model)
429            .with_environment(env)
430            .with_verification_if(self.verification.enabled)
431            .compose()
432    }
433}
434
435
436// ============================================================================
437// PromptConfig
438// ============================================================================
439
440/// Configuration for prompt management
441///
442/// Controls where prompt overrides are loaded from.
443#[derive(Debug, Clone, Serialize, Deserialize)]
444pub struct PromptConfig {
445    /// Optional directory for prompt overrides
446    /// If not set, uses default location (~/.config/agent/prompts)
447    #[serde(default, skip_serializing_if = "Option::is_none")]
448    pub overrides_dir: Option<PathBuf>,
449}
450
451impl Default for PromptConfig {
452    fn default() -> Self {
453        Self { overrides_dir: None }
454    }
455}
456
457impl PromptConfig {
458    /// Create a new prompt config
459    pub fn new() -> Self {
460        Self::default()
461    }
462
463    /// Set the overrides directory
464    pub fn with_overrides_dir(mut self, dir: impl Into<PathBuf>) -> Self {
465        self.overrides_dir = Some(dir.into());
466        self
467    }
468
469    /// Build a PromptStore from this config
470    pub fn build_store(&self) -> PromptStore {
471        // Try to load overrides from configured or default directory
472        let overrides_dir = self
473            .overrides_dir
474            .clone()
475            .or_else(codive_prompts::default_overrides_dir);
476
477        if let Some(dir) = overrides_dir {
478            if dir.exists() {
479                match PromptStore::new().with_overrides_dir(&dir) {
480                    Ok(store) => return store,
481                    Err(e) => {
482                        tracing::warn!("Failed to load prompt overrides from {:?}: {}", dir, e);
483                    }
484                }
485            }
486        }
487
488        PromptStore::new()
489    }
490}
491
492// ============================================================================
493// ServerConfig
494// ============================================================================
495
496/// Configuration for the server component
497#[derive(Debug, Clone, Serialize, Deserialize)]
498pub struct ServerConfig {
499    /// Host to bind to
500    #[serde(default = "default_host")]
501    pub host: String,
502
503    /// Port to listen on
504    #[serde(default = "default_port")]
505    pub port: u16,
506
507    /// Whether to enable CORS
508    #[serde(default = "default_cors")]
509    pub cors_enabled: bool,
510}
511
512fn default_host() -> String {
513    "127.0.0.1".to_string()
514}
515
516fn default_port() -> u16 {
517    3000
518}
519
520fn default_cors() -> bool {
521    true
522}
523
524impl Default for ServerConfig {
525    fn default() -> Self {
526        Self {
527            host: default_host(),
528            port: default_port(),
529            cors_enabled: default_cors(),
530        }
531    }
532}
533
534impl ServerConfig {
535    /// Get the full address string
536    pub fn address(&self) -> String {
537        format!("{}:{}", self.host, self.port)
538    }
539}
540
541// ============================================================================
542// McpConfig
543// ============================================================================
544
545/// Configuration for MCP (Model Context Protocol) servers
546///
547/// MCP allows the agent to connect to external tool providers that implement
548/// the MCP protocol. Servers can be local (via stdio) or remote (via HTTP).
549///
550/// # Example Configuration
551///
552/// ```toml
553/// [[mcp.servers]]
554/// name = "filesystem"
555/// transport = "stdio"
556/// command = "npx"
557/// args = ["-y", "@anthropic/mcp-server-filesystem", "/home/user"]
558///
559/// [[mcp.servers]]
560/// name = "api"
561/// transport = "http"
562/// url = "https://mcp.example.com/api"
563/// ```
564#[derive(Debug, Clone, Default, Serialize, Deserialize)]
565pub struct McpConfig {
566    /// List of MCP server configurations
567    #[serde(default)]
568    pub servers: Vec<McpServerConfig>,
569}
570
571impl McpConfig {
572    /// Create a new empty MCP config
573    pub fn new() -> Self {
574        Self::default()
575    }
576
577    /// Check if any MCP servers are configured
578    pub fn has_servers(&self) -> bool {
579        !self.servers.is_empty()
580    }
581}
582
583/// Configuration for a single MCP server
584#[derive(Debug, Clone, Serialize, Deserialize)]
585pub struct McpServerConfig {
586    /// Unique name for this server (used as tool prefix)
587    pub name: String,
588
589    /// Transport type (stdio or http)
590    #[serde(default)]
591    pub transport: McpTransport,
592
593    // Stdio transport options
594    /// Command to execute (for stdio transport)
595    #[serde(skip_serializing_if = "Option::is_none")]
596    pub command: Option<String>,
597
598    /// Arguments to pass to the command
599    #[serde(skip_serializing_if = "Option::is_none")]
600    pub args: Option<Vec<String>>,
601
602    /// Environment variables to set (supports ${VAR} expansion)
603    #[serde(skip_serializing_if = "Option::is_none")]
604    pub env: Option<HashMap<String, String>>,
605
606    // HTTP transport options
607    /// URL for HTTP transport
608    #[serde(skip_serializing_if = "Option::is_none")]
609    pub url: Option<String>,
610
611    /// Custom headers for HTTP transport (supports ${VAR} expansion)
612    #[serde(skip_serializing_if = "Option::is_none")]
613    pub headers: Option<HashMap<String, String>>,
614}
615
616/// Transport type for MCP communication
617#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
618#[serde(rename_all = "lowercase")]
619pub enum McpTransport {
620    /// Stdio transport (spawn child process)
621    #[default]
622    Stdio,
623    /// HTTP transport (remote server)
624    Http,
625}
626
627// ============================================================================
628// ConfigError
629// ============================================================================
630
631/// Errors that can occur when loading configuration
632#[derive(Debug, thiserror::Error)]
633pub enum ConfigError {
634    /// Config file not found at specified path
635    #[error("Config file not found: {path}")]
636    FileNotFound { path: PathBuf },
637
638    /// Failed to read config file
639    #[error("Failed to read config file: {message}")]
640    ReadError { message: String },
641
642    /// Failed to parse config file
643    #[error("Failed to parse config file: {message}")]
644    ParseError { message: String },
645
646    /// Invalid configuration value
647    #[error("Invalid configuration: {message}")]
648    InvalidConfig { message: String },
649}
650
651impl ConfigError {
652    /// Create a read error
653    pub fn read_error(message: impl Into<String>) -> Self {
654        Self::ReadError {
655            message: message.into(),
656        }
657    }
658
659    /// Create a parse error
660    pub fn parse_error(message: impl Into<String>) -> Self {
661        Self::ParseError {
662            message: message.into(),
663        }
664    }
665}
666
667// ============================================================================
668// TuiConfig
669// ============================================================================
670
671/// Configuration for the TUI (Terminal User Interface)
672///
673/// Controls visual appearance and behavior preferences.
674#[derive(Debug, Clone, Serialize, Deserialize)]
675pub struct TuiConfig {
676    /// Theme name (github_dark, dracula, nord, catppuccin_mocha, high_contrast, light)
677    #[serde(default = "default_theme")]
678    pub theme: String,
679
680    /// Whether to auto-show file preview when files are changed
681    #[serde(default = "default_preview_auto_show")]
682    pub preview_auto_show: bool,
683
684    /// Whether the sidebar is visible by default
685    #[serde(default = "default_sidebar_visible")]
686    pub sidebar_visible: bool,
687}
688
689fn default_theme() -> String {
690    "github_dark".to_string()
691}
692
693fn default_preview_auto_show() -> bool {
694    true
695}
696
697fn default_sidebar_visible() -> bool {
698    true
699}
700
701impl Default for TuiConfig {
702    fn default() -> Self {
703        Self {
704            theme: default_theme(),
705            preview_auto_show: default_preview_auto_show(),
706            sidebar_visible: default_sidebar_visible(),
707        }
708    }
709}
710
711impl TuiConfig {
712    /// Create a new TUI config with defaults
713    pub fn new() -> Self {
714        Self::default()
715    }
716
717    /// Set the theme
718    pub fn with_theme(mut self, theme: impl Into<String>) -> Self {
719        self.theme = theme.into();
720        self
721    }
722
723    /// Set preview auto-show
724    pub fn with_preview_auto_show(mut self, auto_show: bool) -> Self {
725        self.preview_auto_show = auto_show;
726        self
727    }
728}
729
730// ============================================================================
731// AppConfig
732// ============================================================================
733
734/// Top-level application configuration
735///
736/// This combines all configuration sections into a single struct
737/// that can be loaded from a configuration file.
738#[derive(Debug, Clone, Default, Serialize, Deserialize)]
739pub struct AppConfig {
740    /// Agent configuration
741    #[serde(default)]
742    pub agent: AgentConfig,
743
744    /// Server configuration
745    #[serde(default)]
746    pub server: ServerConfig,
747
748    /// MCP (Model Context Protocol) configuration
749    #[serde(default)]
750    pub mcp: McpConfig,
751
752    /// TUI configuration
753    #[serde(default)]
754    pub tui: TuiConfig,
755
756    /// Prompt configuration
757    #[serde(default)]
758    pub prompts: PromptConfig,
759}
760
761impl AppConfig {
762    /// Create a new app config with defaults
763    pub fn new() -> Self {
764        Self::default()
765    }
766
767    /// Load configuration from file with environment variable overrides
768    ///
769    /// # Arguments
770    ///
771    /// * `path` - Optional path to config file. If None, searches default locations.
772    ///
773    /// # Config File Discovery
774    ///
775    /// When no path is specified, searches in order:
776    /// 1. `./agent.toml`
777    /// 2. `~/.config/agent/config.toml`
778    ///
779    /// If no config file is found, returns defaults with env var overrides.
780    pub fn load(path: Option<&Path>) -> Result<Self, ConfigError> {
781        let mut config = if let Some(p) = path {
782            // Load from specified path
783            Self::load_from_file(p)?
784        } else if let Some(p) = Self::discover_config_file() {
785            // Load from discovered path
786            Self::load_from_file(&p)?
787        } else {
788            // Use defaults
789            Self::default()
790        };
791
792        // Apply environment variable overrides
793        config.apply_env_overrides();
794
795        Ok(config)
796    }
797
798    /// Load configuration from a specific file
799    pub fn load_from_file(path: &Path) -> Result<Self, ConfigError> {
800        if !path.exists() {
801            return Err(ConfigError::FileNotFound {
802                path: path.to_path_buf(),
803            });
804        }
805
806        let content =
807            std::fs::read_to_string(path).map_err(|e| ConfigError::read_error(e.to_string()))?;
808
809        Self::parse_toml(&content)
810    }
811
812    /// Parse configuration from TOML string
813    pub fn parse_toml(content: &str) -> Result<Self, ConfigError> {
814        toml::from_str(content).map_err(|e| ConfigError::parse_error(e.to_string()))
815    }
816
817    /// Discover config file in standard locations
818    ///
819    /// Searches in order:
820    /// 1. `./agent.toml` (current directory)
821    /// 2. `~/.config/agent/config.toml` (user config)
822    pub fn discover_config_file() -> Option<PathBuf> {
823        // Check current directory first
824        let local_config = PathBuf::from("agent.toml");
825        if local_config.exists() {
826            return Some(local_config);
827        }
828
829        // Check user config directory
830        if let Some(config_dir) = dirs::config_dir() {
831            let user_config = config_dir.join("agent").join("config.toml");
832            if user_config.exists() {
833                return Some(user_config);
834            }
835        }
836
837        None
838    }
839
840    /// Apply environment variable overrides to the configuration
841    ///
842    /// Supported environment variables:
843    /// - `ANTHROPIC_API_KEY` - API key for Anthropic provider
844    /// - `OPENAI_API_KEY` - API key for OpenAI provider
845    /// - `GEMINI_API_KEY` - API key for Gemini provider
846    /// - `AGENT_MODEL` - Override the model
847    /// - `AGENT_PROVIDER` - Override the provider
848    /// - `AGENT_MAX_TOKENS` - Override max tokens
849    /// - `AGENT_HOST` - Override server host
850    /// - `AGENT_PORT` - Override server port
851    ///
852    /// If no provider is explicitly set (via config or AGENT_PROVIDER), the system
853    /// auto-detects the provider based on available API keys in priority order:
854    /// Anthropic > OpenAI > Gemini
855    pub fn apply_env_overrides(&mut self) {
856        // Track if provider/model were explicitly set
857        let explicit_provider = std::env::var("AGENT_PROVIDER").ok();
858        let explicit_model = std::env::var("AGENT_MODEL").ok();
859
860        // Check if provider was explicitly configured in config file
861        // (i.e., differs from default)
862        let provider_from_config = self.agent.model.provider != "anthropic";
863
864        // Apply explicit overrides first
865        if let Some(provider) = explicit_provider {
866            self.agent.model.provider = provider;
867        }
868        if let Some(model) = explicit_model {
869            self.agent.model.model = model;
870        }
871
872        // Auto-detect provider if not explicitly configured
873        // Only auto-detect if:
874        // 1. No AGENT_PROVIDER env var
875        // 2. Provider in config is still default ("anthropic")
876        // 3. Model in config is still default
877        if !provider_from_config
878            && std::env::var("AGENT_PROVIDER").is_err()
879            && std::env::var("AGENT_MODEL").is_err()
880        {
881            if let Some(detected) = detect_provider() {
882                self.agent.model.provider = detected.name.to_string();
883                self.agent.model.model = detected.default_model.to_string();
884            }
885        }
886
887        // Other overrides
888        if let Ok(max_tokens) = std::env::var("AGENT_MAX_TOKENS") {
889            if let Ok(tokens) = max_tokens.parse() {
890                self.agent.model.max_tokens = tokens;
891            }
892        }
893
894        // Server overrides
895        if let Ok(host) = std::env::var("AGENT_HOST") {
896            self.server.host = host;
897        }
898        if let Ok(port) = std::env::var("AGENT_PORT") {
899            if let Ok(p) = port.parse() {
900                self.server.port = p;
901            }
902        }
903    }
904
905    /// Get the API key for the current provider from config or environment
906    ///
907    /// Checks in order:
908    /// 1. Config file api_key
909    /// 2. Provider-specific env var (ANTHROPIC_API_KEY, OPENAI_API_KEY, GEMINI_API_KEY)
910    pub fn api_key(&self) -> Option<String> {
911        // First check config
912        if let Some(ref key) = self.agent.model.api_key {
913            return Some(key.clone());
914        }
915
916        // Then check environment based on provider using registry
917        get_provider(&self.agent.model.provider)
918            .and_then(|p| std::env::var(p.env_var).ok())
919    }
920
921    /// Set the agent configuration
922    pub fn with_agent(mut self, agent: AgentConfig) -> Self {
923        self.agent = agent;
924        self
925    }
926
927    /// Set the server configuration
928    pub fn with_server(mut self, server: ServerConfig) -> Self {
929        self.server = server;
930        self
931    }
932
933    /// Set the MCP configuration
934    pub fn with_mcp(mut self, mcp: McpConfig) -> Self {
935        self.mcp = mcp;
936        self
937    }
938
939    /// Save configuration to a TOML file
940    pub fn save_to_file(&self, path: &Path) -> Result<(), ConfigError> {
941        let content =
942            toml::to_string_pretty(self).map_err(|e| ConfigError::parse_error(e.to_string()))?;
943
944        std::fs::write(path, content).map_err(|e| ConfigError::read_error(e.to_string()))
945    }
946
947    /// Get the default config file path in user config directory
948    pub fn default_config_path() -> Option<PathBuf> {
949        dirs::config_dir().map(|p| p.join("agent").join("config.toml"))
950    }
951}
952
953// ============================================================================
954// RUST CONCEPTS EXPLAINED (for learning)
955// ============================================================================
956//
957// 1. `#[derive(Default)]`
958//    - Auto-implements the Default trait
959//    - Requires all fields to implement Default
960//    - Use `impl Default` manually when you need custom defaults
961//
962// 2. `#[serde(default)]`
963//    - Uses Default::default() when field is missing in input
964//    - `#[serde(default = "function")]` - use custom default function
965//    - Allows config files to omit optional fields
966//
967// 3. `#[serde(skip_serializing_if = "Option::is_none")]`
968//    - Don't include None values in serialized output
969//    - Keeps config files clean
970//
971// 4. Builder pattern with `with_*` methods
972//    - `mut self` - takes ownership, modifies, returns
973//    - Allows chaining: `Config::new().with_x(1).with_y(2)`
974//    - Ergonomic API for complex construction
975//
976// 5. `impl Into<String>` parameters
977//    - Accepts &str, String, Cow<str>, etc.
978//    - More flexible than just `String`
979//    - `.into()` converts to the target type
980//
981// 6. Default functions
982//    - Serde requires a function that returns T
983//    - Can't use closures, must be named functions
984//    - `fn default_x() -> Type { value }`
985//
986// 7. `Option<T>` for optional fields
987//    - `Some(value)` or `None`
988//    - `.as_deref()` - converts Option<String> to Option<&str>
989//    - `.unwrap_or()` - provide fallback value
990//
991// **📚 Read:**
992// - [Default trait](https://doc.rust-lang.org/std/default/trait.Default.html)
993// - [Serde field attributes](https://serde.rs/field-attrs.html)
994
995// ============================================================================
996// Tests
997// ============================================================================
998
999#[cfg(test)]
1000mod tests {
1001    use super::*;
1002
1003    #[test]
1004    fn test_model_config_defaults() {
1005        let config = ModelConfig::default();
1006        assert_eq!(config.provider, "anthropic");
1007        assert_eq!(config.model, "claude-opus-4-5-20251101");
1008        assert_eq!(config.max_tokens, 4096);
1009        assert_eq!(config.temperature, 0.0);
1010        assert!(config.api_key.is_none());
1011    }
1012
1013    #[test]
1014    fn test_model_config_builder() {
1015        let config = ModelConfig::new("openai", "gpt-4")
1016            .with_max_tokens(2000)
1017            .with_temperature(0.7)
1018            .with_api_key("sk-test");
1019
1020        assert_eq!(config.provider, "openai");
1021        assert_eq!(config.model, "gpt-4");
1022        assert_eq!(config.max_tokens, 2000);
1023        assert_eq!(config.temperature, 0.7);
1024        assert_eq!(config.api_key, Some("sk-test".to_string()));
1025    }
1026
1027    #[test]
1028    fn test_agent_config_defaults() {
1029        let config = AgentConfig::default();
1030        assert_eq!(config.name, "agent");
1031        assert!(config.description.is_none());
1032        assert!(config.system_prompt.is_none());
1033        assert!(config.tools.is_empty());
1034        assert_eq!(config.max_steps, 50);
1035        assert!(config.parallel_tool_calls);
1036    }
1037
1038    #[test]
1039    fn test_agent_config_builder() {
1040        let config = AgentConfig::new("my-agent")
1041            .with_description("A test agent")
1042            .with_system_prompt("You are helpful")
1043            .with_tool("bash")
1044            .with_tool("read_file")
1045            .with_max_steps(10);
1046
1047        assert_eq!(config.name, "my-agent");
1048        assert_eq!(config.description, Some("A test agent".to_string()));
1049        assert_eq!(config.system_prompt, Some("You are helpful".to_string()));
1050        assert_eq!(config.tools, vec!["bash", "read_file"]);
1051        assert_eq!(config.max_steps, 10);
1052    }
1053
1054    #[test]
1055    fn test_build_system_prompt() {
1056        let store = PromptStore::new();
1057
1058        // Custom prompt should be returned as-is
1059        let config_with = AgentConfig::default().with_system_prompt("Custom prompt");
1060        assert_eq!(config_with.build_system_prompt(&store), "Custom prompt");
1061
1062        // Default config has verification enabled, so should include verification instructions
1063        let config_default = AgentConfig::default();
1064        let prompt = config_default.build_system_prompt(&store);
1065        // Should contain base prompt content
1066        assert!(prompt.contains("AI"));
1067        assert!(prompt.contains("Verification"));
1068
1069        // With verification disabled, should not contain verification
1070        let config_no_verify = AgentConfig::default()
1071            .with_verification(VerificationConfig::new().disabled());
1072        let prompt = config_no_verify.build_system_prompt(&store);
1073        assert!(!prompt.contains("Verification"));
1074    }
1075
1076    #[test]
1077    fn test_server_config_defaults() {
1078        let config = ServerConfig::default();
1079        assert_eq!(config.host, "127.0.0.1");
1080        assert_eq!(config.port, 3000);
1081        assert!(config.cors_enabled);
1082    }
1083
1084    #[test]
1085    fn test_server_config_address() {
1086        let config = ServerConfig::default();
1087        assert_eq!(config.address(), "127.0.0.1:3000");
1088    }
1089
1090    #[test]
1091    fn test_app_config_defaults() {
1092        let config = AppConfig::default();
1093        assert_eq!(config.agent.name, "agent");
1094        assert_eq!(config.server.port, 3000);
1095    }
1096
1097    #[test]
1098    fn test_model_config_serialization() {
1099        let config = ModelConfig::default();
1100        let json = serde_json::to_string(&config).unwrap();
1101        assert!(json.contains("\"provider\":\"anthropic\""));
1102        assert!(json.contains("\"model\":\"claude-opus-4-5-20251101\""));
1103
1104        // api_key should be skipped when None
1105        assert!(!json.contains("api_key"));
1106    }
1107
1108    #[test]
1109    fn test_model_config_deserialization_with_defaults() {
1110        // Minimal JSON - should fill in defaults
1111        let json = r#"{"provider": "openai"}"#;
1112        let config: ModelConfig = serde_json::from_str(json).unwrap();
1113
1114        assert_eq!(config.provider, "openai");
1115        // These should be defaults
1116        assert_eq!(config.model, "claude-opus-4-5-20251101");
1117        assert_eq!(config.max_tokens, 4096);
1118    }
1119
1120    #[test]
1121    fn test_agent_config_serialization_roundtrip() {
1122        let original = AgentConfig::new("test")
1123            .with_description("Test agent")
1124            .with_tool("bash");
1125
1126        let json = serde_json::to_string(&original).unwrap();
1127        let restored: AgentConfig = serde_json::from_str(&json).unwrap();
1128
1129        assert_eq!(original.name, restored.name);
1130        assert_eq!(original.description, restored.description);
1131        assert_eq!(original.tools, restored.tools);
1132    }
1133
1134    #[test]
1135    fn test_empty_json_uses_all_defaults() {
1136        let json = "{}";
1137        let config: AppConfig = serde_json::from_str(json).unwrap();
1138
1139        assert_eq!(config.agent.name, "agent");
1140        assert_eq!(config.agent.model.provider, "anthropic");
1141        assert_eq!(config.server.port, 3000);
1142    }
1143
1144    // =========================================================================
1145    // TOML Parsing Tests
1146    // =========================================================================
1147
1148    #[test]
1149    fn test_parse_toml_empty() {
1150        let toml = "";
1151        let config = AppConfig::parse_toml(toml).unwrap();
1152        assert_eq!(config.agent.name, "agent");
1153        assert_eq!(config.server.port, 3000);
1154    }
1155
1156    #[test]
1157    fn test_parse_toml_full() {
1158        let toml = r#"
1159[agent]
1160name = "my-agent"
1161description = "A custom agent"
1162max_steps = 25
1163
1164[agent.model]
1165provider = "openai"
1166model = "gpt-4"
1167max_tokens = 2000
1168temperature = 0.5
1169
1170[server]
1171host = "0.0.0.0"
1172port = 8080
1173cors_enabled = false
1174"#;
1175        let config = AppConfig::parse_toml(toml).unwrap();
1176
1177        assert_eq!(config.agent.name, "my-agent");
1178        assert_eq!(config.agent.description, Some("A custom agent".to_string()));
1179        assert_eq!(config.agent.max_steps, 25);
1180        assert_eq!(config.agent.model.provider, "openai");
1181        assert_eq!(config.agent.model.model, "gpt-4");
1182        assert_eq!(config.agent.model.max_tokens, 2000);
1183        assert_eq!(config.agent.model.temperature, 0.5);
1184        assert_eq!(config.server.host, "0.0.0.0");
1185        assert_eq!(config.server.port, 8080);
1186        assert!(!config.server.cors_enabled);
1187    }
1188
1189    #[test]
1190    fn test_parse_toml_partial() {
1191        let toml = r#"
1192[agent]
1193name = "partial-agent"
1194
1195[server]
1196port = 4000
1197"#;
1198        let config = AppConfig::parse_toml(toml).unwrap();
1199
1200        // Specified values
1201        assert_eq!(config.agent.name, "partial-agent");
1202        assert_eq!(config.server.port, 4000);
1203
1204        // Defaults
1205        assert_eq!(config.agent.model.provider, "anthropic");
1206        assert_eq!(config.server.host, "127.0.0.1");
1207    }
1208
1209    #[test]
1210    fn test_parse_toml_with_tools() {
1211        let toml = r#"
1212[agent]
1213name = "tool-agent"
1214tools = ["bash", "read_file", "write_file"]
1215"#;
1216        let config = AppConfig::parse_toml(toml).unwrap();
1217
1218        assert_eq!(config.agent.tools, vec!["bash", "read_file", "write_file"]);
1219    }
1220
1221    #[test]
1222    fn test_parse_toml_invalid() {
1223        let toml = "this is not valid toml [[[";
1224        let result = AppConfig::parse_toml(toml);
1225        assert!(result.is_err());
1226        assert!(matches!(
1227            result.unwrap_err(),
1228            ConfigError::ParseError { .. }
1229        ));
1230    }
1231
1232    #[test]
1233    fn test_toml_serialization_roundtrip() {
1234        let original =
1235            AppConfig::default().with_agent(AgentConfig::new("test-agent").with_tool("bash"));
1236
1237        let toml_str = toml::to_string_pretty(&original).unwrap();
1238        let restored = AppConfig::parse_toml(&toml_str).unwrap();
1239
1240        assert_eq!(original.agent.name, restored.agent.name);
1241        assert_eq!(original.agent.tools, restored.agent.tools);
1242    }
1243
1244    // =========================================================================
1245    // Config Loading Tests
1246    // =========================================================================
1247
1248    #[test]
1249    fn test_load_nonexistent_file() {
1250        let result = AppConfig::load_from_file(Path::new("/nonexistent/path/config.toml"));
1251        assert!(result.is_err());
1252        assert!(matches!(
1253            result.unwrap_err(),
1254            ConfigError::FileNotFound { .. }
1255        ));
1256    }
1257
1258    #[test]
1259    fn test_load_with_no_config_uses_defaults() {
1260        // When no config file exists and none specified, should use defaults
1261        let config = AppConfig::load(None).unwrap();
1262        assert_eq!(config.agent.name, "agent");
1263    }
1264
1265    #[test]
1266    fn test_config_error_display() {
1267        let err = ConfigError::FileNotFound {
1268            path: PathBuf::from("/test/path"),
1269        };
1270        assert!(err.to_string().contains("/test/path"));
1271
1272        let err = ConfigError::parse_error("invalid syntax");
1273        assert!(err.to_string().contains("invalid syntax"));
1274    }
1275
1276    #[test]
1277    fn test_save_and_load_config() {
1278        use std::fs;
1279
1280        let temp_dir = std::env::temp_dir();
1281        let config_path = temp_dir.join("agent_test_config.toml");
1282
1283        // Create and save config
1284        let original =
1285            AppConfig::default().with_agent(AgentConfig::new("saved-agent").with_max_steps(30));
1286
1287        original.save_to_file(&config_path).unwrap();
1288
1289        // Load it back
1290        let loaded = AppConfig::load_from_file(&config_path).unwrap();
1291
1292        assert_eq!(loaded.agent.name, "saved-agent");
1293        assert_eq!(loaded.agent.max_steps, 30);
1294
1295        // Cleanup
1296        fs::remove_file(&config_path).ok();
1297    }
1298
1299    #[test]
1300    fn test_default_config_path() {
1301        let path = AppConfig::default_config_path();
1302        // Should return Some on most systems
1303        if let Some(p) = path {
1304            assert!(p.to_string_lossy().contains("agent"));
1305            assert!(p.to_string_lossy().contains("config.toml"));
1306        }
1307    }
1308
1309    // =========================================================================
1310    // Environment Variable Tests
1311    // =========================================================================
1312
1313    #[test]
1314    fn test_api_key_from_config() {
1315        let config = AppConfig::default().with_agent(
1316            AgentConfig::default().with_model(ModelConfig::default().with_api_key("config-key")),
1317        );
1318
1319        assert_eq!(config.api_key(), Some("config-key".to_string()));
1320    }
1321
1322    #[test]
1323    fn test_env_override_model() {
1324        // Save current env
1325        let old_model = std::env::var("AGENT_MODEL").ok();
1326
1327        // Set env var
1328        std::env::set_var("AGENT_MODEL", "test-model-from-env");
1329
1330        let mut config = AppConfig::default();
1331        config.apply_env_overrides();
1332
1333        assert_eq!(config.agent.model.model, "test-model-from-env");
1334
1335        // Restore env
1336        if let Some(old) = old_model {
1337            std::env::set_var("AGENT_MODEL", old);
1338        } else {
1339            std::env::remove_var("AGENT_MODEL");
1340        }
1341    }
1342
1343    #[test]
1344    fn test_env_override_port() {
1345        let old_port = std::env::var("AGENT_PORT").ok();
1346
1347        std::env::set_var("AGENT_PORT", "9999");
1348
1349        let mut config = AppConfig::default();
1350        config.apply_env_overrides();
1351
1352        assert_eq!(config.server.port, 9999);
1353
1354        if let Some(old) = old_port {
1355            std::env::set_var("AGENT_PORT", old);
1356        } else {
1357            std::env::remove_var("AGENT_PORT");
1358        }
1359    }
1360}