1use codive_prompts::{EnvironmentContext, PromptComposer, PromptStore};
47use serde::{Deserialize, Serialize};
48use std::collections::HashMap;
49use std::path::{Path, PathBuf};
50
51#[derive(Debug, Clone, Copy)]
57pub struct ProviderInfo {
58 pub name: &'static str,
60 pub env_var: &'static str,
62 pub default_model: &'static str,
64}
65
66pub const PROVIDERS: &[ProviderInfo] = &[
70 ProviderInfo {
71 name: "anthropic",
72 env_var: "ANTHROPIC_API_KEY",
73 default_model: "claude-opus-4-5-20251101", },
75 ProviderInfo {
76 name: "openai",
77 env_var: "OPENAI_API_KEY",
78 default_model: "gpt-5.2-2025-12-11", },
80 ProviderInfo {
81 name: "gemini",
82 env_var: "GEMINI_API_KEY",
83 default_model: "gemini-2.5-pro", },
85];
86
87pub fn get_provider(name: &str) -> Option<&'static ProviderInfo> {
89 PROVIDERS.iter().find(|p| p.name == name)
90}
91
92pub fn detect_provider() -> Option<&'static ProviderInfo> {
95 PROVIDERS
96 .iter()
97 .find(|p| std::env::var(p.env_var).is_ok())
98}
99
100#[derive(Debug, Clone, Serialize, Deserialize)]
108pub struct ModelConfig {
109 #[serde(default = "default_provider")]
111 pub provider: String,
112
113 #[serde(default = "default_model")]
115 pub model: String,
116
117 #[serde(default = "default_max_tokens")]
119 pub max_tokens: u32,
120
121 #[serde(default = "default_temperature")]
123 pub temperature: f32,
124
125 #[serde(default, skip_serializing_if = "Option::is_none")]
127 pub api_key: Option<String>,
128
129 #[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 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 pub fn with_max_tokens(mut self, max_tokens: u32) -> Self {
175 self.max_tokens = max_tokens;
176 self
177 }
178
179 pub fn with_temperature(mut self, temperature: f32) -> Self {
181 self.temperature = temperature;
182 self
183 }
184
185 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 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#[derive(Debug, Clone, Serialize, Deserialize)]
208pub struct VerificationConfig {
209 #[serde(default = "default_verification_enabled")]
212 pub enabled: bool,
213}
214
215fn default_verification_enabled() -> bool {
216 true }
218
219impl Default for VerificationConfig {
220 fn default() -> Self {
221 Self {
222 enabled: default_verification_enabled(),
223 }
224 }
225}
226
227impl VerificationConfig {
228 pub fn new() -> Self {
230 Self::default()
231 }
232
233 pub fn enabled(mut self) -> Self {
235 self.enabled = true;
236 self
237 }
238
239 pub fn disabled(mut self) -> Self {
241 self.enabled = false;
242 self
243 }
244}
245
246#[derive(Debug, Clone, Serialize, Deserialize)]
254pub struct AgentConfig {
255 #[serde(default = "default_agent_name")]
257 pub name: String,
258
259 #[serde(default, skip_serializing_if = "Option::is_none")]
261 pub description: Option<String>,
262
263 #[serde(default, skip_serializing_if = "Option::is_none")]
265 pub system_prompt: Option<String>,
266
267 #[serde(default)]
269 pub model: ModelConfig,
270
271 #[serde(default)]
273 pub tools: Vec<String>,
274
275 #[serde(default = "default_max_steps")]
277 pub max_steps: u32,
278
279 #[serde(default = "default_max_history")]
281 pub max_history: usize,
282
283 #[serde(default = "default_parallel_tools")]
285 pub parallel_tool_calls: bool,
286
287 #[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 pub fn new(name: impl Into<String>) -> Self {
327 Self {
328 name: name.into(),
329 ..Default::default()
330 }
331 }
332
333 pub fn with_name(mut self, name: impl Into<String>) -> Self {
335 self.name = name.into();
336 self
337 }
338
339 pub fn with_description(mut self, description: impl Into<String>) -> Self {
341 self.description = Some(description.into());
342 self
343 }
344
345 pub fn with_system_prompt(mut self, prompt: impl Into<String>) -> Self {
347 self.system_prompt = Some(prompt.into());
348 self
349 }
350
351 pub fn with_model(mut self, model: ModelConfig) -> Self {
353 self.model = model;
354 self
355 }
356
357 pub fn with_tools(mut self, tools: Vec<String>) -> Self {
359 self.tools = tools;
360 self
361 }
362
363 pub fn with_tool(mut self, tool: impl Into<String>) -> Self {
365 self.tools.push(tool.into());
366 self
367 }
368
369 pub fn with_max_steps(mut self, max_steps: u32) -> Self {
371 self.max_steps = max_steps;
372 self
373 }
374
375 pub fn with_max_history(mut self, max_history: usize) -> Self {
377 self.max_history = max_history;
378 self
379 }
380
381 pub fn with_parallel_tool_calls(mut self, parallel: bool) -> Self {
383 self.parallel_tool_calls = parallel;
384 self
385 }
386
387 pub fn with_verification(mut self, verification: VerificationConfig) -> Self {
389 self.verification = verification;
390 self
391 }
392
393 pub fn build_system_prompt(&self, store: &PromptStore) -> String {
403 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 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#[derive(Debug, Clone, Serialize, Deserialize)]
444pub struct PromptConfig {
445 #[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 pub fn new() -> Self {
460 Self::default()
461 }
462
463 pub fn with_overrides_dir(mut self, dir: impl Into<PathBuf>) -> Self {
465 self.overrides_dir = Some(dir.into());
466 self
467 }
468
469 pub fn build_store(&self) -> PromptStore {
471 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#[derive(Debug, Clone, Serialize, Deserialize)]
498pub struct ServerConfig {
499 #[serde(default = "default_host")]
501 pub host: String,
502
503 #[serde(default = "default_port")]
505 pub port: u16,
506
507 #[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 pub fn address(&self) -> String {
537 format!("{}:{}", self.host, self.port)
538 }
539}
540
541#[derive(Debug, Clone, Default, Serialize, Deserialize)]
565pub struct McpConfig {
566 #[serde(default)]
568 pub servers: Vec<McpServerConfig>,
569}
570
571impl McpConfig {
572 pub fn new() -> Self {
574 Self::default()
575 }
576
577 pub fn has_servers(&self) -> bool {
579 !self.servers.is_empty()
580 }
581}
582
583#[derive(Debug, Clone, Serialize, Deserialize)]
585pub struct McpServerConfig {
586 pub name: String,
588
589 #[serde(default)]
591 pub transport: McpTransport,
592
593 #[serde(skip_serializing_if = "Option::is_none")]
596 pub command: Option<String>,
597
598 #[serde(skip_serializing_if = "Option::is_none")]
600 pub args: Option<Vec<String>>,
601
602 #[serde(skip_serializing_if = "Option::is_none")]
604 pub env: Option<HashMap<String, String>>,
605
606 #[serde(skip_serializing_if = "Option::is_none")]
609 pub url: Option<String>,
610
611 #[serde(skip_serializing_if = "Option::is_none")]
613 pub headers: Option<HashMap<String, String>>,
614}
615
616#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
618#[serde(rename_all = "lowercase")]
619pub enum McpTransport {
620 #[default]
622 Stdio,
623 Http,
625}
626
627#[derive(Debug, thiserror::Error)]
633pub enum ConfigError {
634 #[error("Config file not found: {path}")]
636 FileNotFound { path: PathBuf },
637
638 #[error("Failed to read config file: {message}")]
640 ReadError { message: String },
641
642 #[error("Failed to parse config file: {message}")]
644 ParseError { message: String },
645
646 #[error("Invalid configuration: {message}")]
648 InvalidConfig { message: String },
649}
650
651impl ConfigError {
652 pub fn read_error(message: impl Into<String>) -> Self {
654 Self::ReadError {
655 message: message.into(),
656 }
657 }
658
659 pub fn parse_error(message: impl Into<String>) -> Self {
661 Self::ParseError {
662 message: message.into(),
663 }
664 }
665}
666
667#[derive(Debug, Clone, Serialize, Deserialize)]
675pub struct TuiConfig {
676 #[serde(default = "default_theme")]
678 pub theme: String,
679
680 #[serde(default = "default_preview_auto_show")]
682 pub preview_auto_show: bool,
683
684 #[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 pub fn new() -> Self {
714 Self::default()
715 }
716
717 pub fn with_theme(mut self, theme: impl Into<String>) -> Self {
719 self.theme = theme.into();
720 self
721 }
722
723 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#[derive(Debug, Clone, Default, Serialize, Deserialize)]
739pub struct AppConfig {
740 #[serde(default)]
742 pub agent: AgentConfig,
743
744 #[serde(default)]
746 pub server: ServerConfig,
747
748 #[serde(default)]
750 pub mcp: McpConfig,
751
752 #[serde(default)]
754 pub tui: TuiConfig,
755
756 #[serde(default)]
758 pub prompts: PromptConfig,
759}
760
761impl AppConfig {
762 pub fn new() -> Self {
764 Self::default()
765 }
766
767 pub fn load(path: Option<&Path>) -> Result<Self, ConfigError> {
781 let mut config = if let Some(p) = path {
782 Self::load_from_file(p)?
784 } else if let Some(p) = Self::discover_config_file() {
785 Self::load_from_file(&p)?
787 } else {
788 Self::default()
790 };
791
792 config.apply_env_overrides();
794
795 Ok(config)
796 }
797
798 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 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 pub fn discover_config_file() -> Option<PathBuf> {
823 let local_config = PathBuf::from("agent.toml");
825 if local_config.exists() {
826 return Some(local_config);
827 }
828
829 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 pub fn apply_env_overrides(&mut self) {
856 let explicit_provider = std::env::var("AGENT_PROVIDER").ok();
858 let explicit_model = std::env::var("AGENT_MODEL").ok();
859
860 let provider_from_config = self.agent.model.provider != "anthropic";
863
864 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 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 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 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 pub fn api_key(&self) -> Option<String> {
911 if let Some(ref key) = self.agent.model.api_key {
913 return Some(key.clone());
914 }
915
916 get_provider(&self.agent.model.provider)
918 .and_then(|p| std::env::var(p.env_var).ok())
919 }
920
921 pub fn with_agent(mut self, agent: AgentConfig) -> Self {
923 self.agent = agent;
924 self
925 }
926
927 pub fn with_server(mut self, server: ServerConfig) -> Self {
929 self.server = server;
930 self
931 }
932
933 pub fn with_mcp(mut self, mcp: McpConfig) -> Self {
935 self.mcp = mcp;
936 self
937 }
938
939 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 pub fn default_config_path() -> Option<PathBuf> {
949 dirs::config_dir().map(|p| p.join("agent").join("config.toml"))
950 }
951}
952
953#[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 let config_with = AgentConfig::default().with_system_prompt("Custom prompt");
1060 assert_eq!(config_with.build_system_prompt(&store), "Custom prompt");
1061
1062 let config_default = AgentConfig::default();
1064 let prompt = config_default.build_system_prompt(&store);
1065 assert!(prompt.contains("AI"));
1067 assert!(prompt.contains("Verification"));
1068
1069 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 assert!(!json.contains("api_key"));
1106 }
1107
1108 #[test]
1109 fn test_model_config_deserialization_with_defaults() {
1110 let json = r#"{"provider": "openai"}"#;
1112 let config: ModelConfig = serde_json::from_str(json).unwrap();
1113
1114 assert_eq!(config.provider, "openai");
1115 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 #[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 assert_eq!(config.agent.name, "partial-agent");
1202 assert_eq!(config.server.port, 4000);
1203
1204 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 #[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 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 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 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 fs::remove_file(&config_path).ok();
1297 }
1298
1299 #[test]
1300 fn test_default_config_path() {
1301 let path = AppConfig::default_config_path();
1302 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 #[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 let old_model = std::env::var("AGENT_MODEL").ok();
1326
1327 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 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}