use codive_prompts::{EnvironmentContext, PromptComposer, PromptStore};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
#[derive(Debug, Clone, Copy)]
pub struct ProviderInfo {
pub name: &'static str,
pub env_var: &'static str,
pub default_model: &'static str,
}
pub const PROVIDERS: &[ProviderInfo] = &[
ProviderInfo {
name: "anthropic",
env_var: "ANTHROPIC_API_KEY",
default_model: "claude-opus-4-5-20251101", },
ProviderInfo {
name: "openai",
env_var: "OPENAI_API_KEY",
default_model: "gpt-5.2-2025-12-11", },
ProviderInfo {
name: "gemini",
env_var: "GEMINI_API_KEY",
default_model: "gemini-2.5-pro", },
];
pub fn get_provider(name: &str) -> Option<&'static ProviderInfo> {
PROVIDERS.iter().find(|p| p.name == name)
}
pub fn detect_provider() -> Option<&'static ProviderInfo> {
PROVIDERS
.iter()
.find(|p| std::env::var(p.env_var).is_ok())
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ModelConfig {
#[serde(default = "default_provider")]
pub provider: String,
#[serde(default = "default_model")]
pub model: String,
#[serde(default = "default_max_tokens")]
pub max_tokens: u32,
#[serde(default = "default_temperature")]
pub temperature: f32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub api_key: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub api_base: Option<String>,
}
fn default_provider() -> String {
"anthropic".to_string()
}
fn default_model() -> String {
"claude-opus-4-5-20251101".to_string()
}
fn default_max_tokens() -> u32 {
4096
}
fn default_temperature() -> f32 {
0.0
}
impl Default for ModelConfig {
fn default() -> Self {
Self {
provider: default_provider(),
model: default_model(),
max_tokens: default_max_tokens(),
temperature: default_temperature(),
api_key: None,
api_base: None,
}
}
}
impl ModelConfig {
pub fn new(provider: impl Into<String>, model: impl Into<String>) -> Self {
Self {
provider: provider.into(),
model: model.into(),
..Default::default()
}
}
pub fn with_max_tokens(mut self, max_tokens: u32) -> Self {
self.max_tokens = max_tokens;
self
}
pub fn with_temperature(mut self, temperature: f32) -> Self {
self.temperature = temperature;
self
}
pub fn with_api_key(mut self, api_key: impl Into<String>) -> Self {
self.api_key = Some(api_key.into());
self
}
pub fn with_api_base(mut self, api_base: impl Into<String>) -> Self {
self.api_base = Some(api_base.into());
self
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VerificationConfig {
#[serde(default = "default_verification_enabled")]
pub enabled: bool,
}
fn default_verification_enabled() -> bool {
true }
impl Default for VerificationConfig {
fn default() -> Self {
Self {
enabled: default_verification_enabled(),
}
}
}
impl VerificationConfig {
pub fn new() -> Self {
Self::default()
}
pub fn enabled(mut self) -> Self {
self.enabled = true;
self
}
pub fn disabled(mut self) -> Self {
self.enabled = false;
self
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentConfig {
#[serde(default = "default_agent_name")]
pub name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub system_prompt: Option<String>,
#[serde(default)]
pub model: ModelConfig,
#[serde(default)]
pub tools: Vec<String>,
#[serde(default = "default_max_steps")]
pub max_steps: u32,
#[serde(default = "default_max_history")]
pub max_history: usize,
#[serde(default = "default_parallel_tools")]
pub parallel_tool_calls: bool,
#[serde(default)]
pub verification: VerificationConfig,
}
fn default_agent_name() -> String {
"agent".to_string()
}
fn default_max_steps() -> u32 {
50
}
fn default_max_history() -> usize {
100
}
fn default_parallel_tools() -> bool {
true
}
impl Default for AgentConfig {
fn default() -> Self {
Self {
name: default_agent_name(),
description: None,
system_prompt: None,
model: ModelConfig::default(),
tools: Vec::new(),
max_steps: default_max_steps(),
max_history: default_max_history(),
parallel_tool_calls: default_parallel_tools(),
verification: VerificationConfig::default(),
}
}
}
impl AgentConfig {
pub fn new(name: impl Into<String>) -> Self {
Self {
name: name.into(),
..Default::default()
}
}
pub fn with_name(mut self, name: impl Into<String>) -> Self {
self.name = name.into();
self
}
pub fn with_description(mut self, description: impl Into<String>) -> Self {
self.description = Some(description.into());
self
}
pub fn with_system_prompt(mut self, prompt: impl Into<String>) -> Self {
self.system_prompt = Some(prompt.into());
self
}
pub fn with_model(mut self, model: ModelConfig) -> Self {
self.model = model;
self
}
pub fn with_tools(mut self, tools: Vec<String>) -> Self {
self.tools = tools;
self
}
pub fn with_tool(mut self, tool: impl Into<String>) -> Self {
self.tools.push(tool.into());
self
}
pub fn with_max_steps(mut self, max_steps: u32) -> Self {
self.max_steps = max_steps;
self
}
pub fn with_max_history(mut self, max_history: usize) -> Self {
self.max_history = max_history;
self
}
pub fn with_parallel_tool_calls(mut self, parallel: bool) -> Self {
self.parallel_tool_calls = parallel;
self
}
pub fn with_verification(mut self, verification: VerificationConfig) -> Self {
self.verification = verification;
self
}
pub fn build_system_prompt(&self, store: &PromptStore) -> String {
if let Some(ref custom) = self.system_prompt {
return custom.clone();
}
PromptComposer::new(store)
.with_base()
.with_provider_auto(&self.model.model)
.with_current_environment()
.with_verification_if(self.verification.enabled)
.compose()
}
pub fn build_system_prompt_with_env(
&self,
store: &PromptStore,
env: EnvironmentContext,
) -> String {
if let Some(ref custom) = self.system_prompt {
return custom.clone();
}
PromptComposer::new(store)
.with_base()
.with_provider_auto(&self.model.model)
.with_environment(env)
.with_verification_if(self.verification.enabled)
.compose()
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PromptConfig {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub overrides_dir: Option<PathBuf>,
}
impl Default for PromptConfig {
fn default() -> Self {
Self { overrides_dir: None }
}
}
impl PromptConfig {
pub fn new() -> Self {
Self::default()
}
pub fn with_overrides_dir(mut self, dir: impl Into<PathBuf>) -> Self {
self.overrides_dir = Some(dir.into());
self
}
pub fn build_store(&self) -> PromptStore {
let overrides_dir = self
.overrides_dir
.clone()
.or_else(codive_prompts::default_overrides_dir);
if let Some(dir) = overrides_dir {
if dir.exists() {
match PromptStore::new().with_overrides_dir(&dir) {
Ok(store) => return store,
Err(e) => {
tracing::warn!("Failed to load prompt overrides from {:?}: {}", dir, e);
}
}
}
}
PromptStore::new()
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServerConfig {
#[serde(default = "default_host")]
pub host: String,
#[serde(default = "default_port")]
pub port: u16,
#[serde(default = "default_cors")]
pub cors_enabled: bool,
}
fn default_host() -> String {
"127.0.0.1".to_string()
}
fn default_port() -> u16 {
3000
}
fn default_cors() -> bool {
true
}
impl Default for ServerConfig {
fn default() -> Self {
Self {
host: default_host(),
port: default_port(),
cors_enabled: default_cors(),
}
}
}
impl ServerConfig {
pub fn address(&self) -> String {
format!("{}:{}", self.host, self.port)
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct McpConfig {
#[serde(default)]
pub servers: Vec<McpServerConfig>,
}
impl McpConfig {
pub fn new() -> Self {
Self::default()
}
pub fn has_servers(&self) -> bool {
!self.servers.is_empty()
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpServerConfig {
pub name: String,
#[serde(default)]
pub transport: McpTransport,
#[serde(skip_serializing_if = "Option::is_none")]
pub command: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub args: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub env: Option<HashMap<String, String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub url: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub headers: Option<HashMap<String, String>>,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum McpTransport {
#[default]
Stdio,
Http,
}
#[derive(Debug, thiserror::Error)]
pub enum ConfigError {
#[error("Config file not found: {path}")]
FileNotFound { path: PathBuf },
#[error("Failed to read config file: {message}")]
ReadError { message: String },
#[error("Failed to parse config file: {message}")]
ParseError { message: String },
#[error("Invalid configuration: {message}")]
InvalidConfig { message: String },
}
impl ConfigError {
pub fn read_error(message: impl Into<String>) -> Self {
Self::ReadError {
message: message.into(),
}
}
pub fn parse_error(message: impl Into<String>) -> Self {
Self::ParseError {
message: message.into(),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TuiConfig {
#[serde(default = "default_theme")]
pub theme: String,
#[serde(default = "default_preview_auto_show")]
pub preview_auto_show: bool,
#[serde(default = "default_sidebar_visible")]
pub sidebar_visible: bool,
}
fn default_theme() -> String {
"github_dark".to_string()
}
fn default_preview_auto_show() -> bool {
true
}
fn default_sidebar_visible() -> bool {
true
}
impl Default for TuiConfig {
fn default() -> Self {
Self {
theme: default_theme(),
preview_auto_show: default_preview_auto_show(),
sidebar_visible: default_sidebar_visible(),
}
}
}
impl TuiConfig {
pub fn new() -> Self {
Self::default()
}
pub fn with_theme(mut self, theme: impl Into<String>) -> Self {
self.theme = theme.into();
self
}
pub fn with_preview_auto_show(mut self, auto_show: bool) -> Self {
self.preview_auto_show = auto_show;
self
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct AppConfig {
#[serde(default)]
pub agent: AgentConfig,
#[serde(default)]
pub server: ServerConfig,
#[serde(default)]
pub mcp: McpConfig,
#[serde(default)]
pub tui: TuiConfig,
#[serde(default)]
pub prompts: PromptConfig,
}
impl AppConfig {
pub fn new() -> Self {
Self::default()
}
pub fn load(path: Option<&Path>) -> Result<Self, ConfigError> {
let mut config = if let Some(p) = path {
Self::load_from_file(p)?
} else if let Some(p) = Self::discover_config_file() {
Self::load_from_file(&p)?
} else {
Self::default()
};
config.apply_env_overrides();
Ok(config)
}
pub fn load_from_file(path: &Path) -> Result<Self, ConfigError> {
if !path.exists() {
return Err(ConfigError::FileNotFound {
path: path.to_path_buf(),
});
}
let content =
std::fs::read_to_string(path).map_err(|e| ConfigError::read_error(e.to_string()))?;
Self::parse_toml(&content)
}
pub fn parse_toml(content: &str) -> Result<Self, ConfigError> {
toml::from_str(content).map_err(|e| ConfigError::parse_error(e.to_string()))
}
pub fn discover_config_file() -> Option<PathBuf> {
let local_config = PathBuf::from("agent.toml");
if local_config.exists() {
return Some(local_config);
}
if let Some(config_dir) = dirs::config_dir() {
let user_config = config_dir.join("agent").join("config.toml");
if user_config.exists() {
return Some(user_config);
}
}
None
}
pub fn apply_env_overrides(&mut self) {
let explicit_provider = std::env::var("AGENT_PROVIDER").ok();
let explicit_model = std::env::var("AGENT_MODEL").ok();
let provider_from_config = self.agent.model.provider != "anthropic";
if let Some(provider) = explicit_provider {
self.agent.model.provider = provider;
}
if let Some(model) = explicit_model {
self.agent.model.model = model;
}
if !provider_from_config
&& std::env::var("AGENT_PROVIDER").is_err()
&& std::env::var("AGENT_MODEL").is_err()
{
if let Some(detected) = detect_provider() {
self.agent.model.provider = detected.name.to_string();
self.agent.model.model = detected.default_model.to_string();
}
}
if let Ok(max_tokens) = std::env::var("AGENT_MAX_TOKENS") {
if let Ok(tokens) = max_tokens.parse() {
self.agent.model.max_tokens = tokens;
}
}
if let Ok(host) = std::env::var("AGENT_HOST") {
self.server.host = host;
}
if let Ok(port) = std::env::var("AGENT_PORT") {
if let Ok(p) = port.parse() {
self.server.port = p;
}
}
}
pub fn api_key(&self) -> Option<String> {
if let Some(ref key) = self.agent.model.api_key {
return Some(key.clone());
}
get_provider(&self.agent.model.provider)
.and_then(|p| std::env::var(p.env_var).ok())
}
pub fn with_agent(mut self, agent: AgentConfig) -> Self {
self.agent = agent;
self
}
pub fn with_server(mut self, server: ServerConfig) -> Self {
self.server = server;
self
}
pub fn with_mcp(mut self, mcp: McpConfig) -> Self {
self.mcp = mcp;
self
}
pub fn save_to_file(&self, path: &Path) -> Result<(), ConfigError> {
let content =
toml::to_string_pretty(self).map_err(|e| ConfigError::parse_error(e.to_string()))?;
std::fs::write(path, content).map_err(|e| ConfigError::read_error(e.to_string()))
}
pub fn default_config_path() -> Option<PathBuf> {
dirs::config_dir().map(|p| p.join("agent").join("config.toml"))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_model_config_defaults() {
let config = ModelConfig::default();
assert_eq!(config.provider, "anthropic");
assert_eq!(config.model, "claude-opus-4-5-20251101");
assert_eq!(config.max_tokens, 4096);
assert_eq!(config.temperature, 0.0);
assert!(config.api_key.is_none());
}
#[test]
fn test_model_config_builder() {
let config = ModelConfig::new("openai", "gpt-4")
.with_max_tokens(2000)
.with_temperature(0.7)
.with_api_key("sk-test");
assert_eq!(config.provider, "openai");
assert_eq!(config.model, "gpt-4");
assert_eq!(config.max_tokens, 2000);
assert_eq!(config.temperature, 0.7);
assert_eq!(config.api_key, Some("sk-test".to_string()));
}
#[test]
fn test_agent_config_defaults() {
let config = AgentConfig::default();
assert_eq!(config.name, "agent");
assert!(config.description.is_none());
assert!(config.system_prompt.is_none());
assert!(config.tools.is_empty());
assert_eq!(config.max_steps, 50);
assert!(config.parallel_tool_calls);
}
#[test]
fn test_agent_config_builder() {
let config = AgentConfig::new("my-agent")
.with_description("A test agent")
.with_system_prompt("You are helpful")
.with_tool("bash")
.with_tool("read_file")
.with_max_steps(10);
assert_eq!(config.name, "my-agent");
assert_eq!(config.description, Some("A test agent".to_string()));
assert_eq!(config.system_prompt, Some("You are helpful".to_string()));
assert_eq!(config.tools, vec!["bash", "read_file"]);
assert_eq!(config.max_steps, 10);
}
#[test]
fn test_build_system_prompt() {
let store = PromptStore::new();
let config_with = AgentConfig::default().with_system_prompt("Custom prompt");
assert_eq!(config_with.build_system_prompt(&store), "Custom prompt");
let config_default = AgentConfig::default();
let prompt = config_default.build_system_prompt(&store);
assert!(prompt.contains("AI"));
assert!(prompt.contains("Verification"));
let config_no_verify = AgentConfig::default()
.with_verification(VerificationConfig::new().disabled());
let prompt = config_no_verify.build_system_prompt(&store);
assert!(!prompt.contains("Verification"));
}
#[test]
fn test_server_config_defaults() {
let config = ServerConfig::default();
assert_eq!(config.host, "127.0.0.1");
assert_eq!(config.port, 3000);
assert!(config.cors_enabled);
}
#[test]
fn test_server_config_address() {
let config = ServerConfig::default();
assert_eq!(config.address(), "127.0.0.1:3000");
}
#[test]
fn test_app_config_defaults() {
let config = AppConfig::default();
assert_eq!(config.agent.name, "agent");
assert_eq!(config.server.port, 3000);
}
#[test]
fn test_model_config_serialization() {
let config = ModelConfig::default();
let json = serde_json::to_string(&config).unwrap();
assert!(json.contains("\"provider\":\"anthropic\""));
assert!(json.contains("\"model\":\"claude-opus-4-5-20251101\""));
assert!(!json.contains("api_key"));
}
#[test]
fn test_model_config_deserialization_with_defaults() {
let json = r#"{"provider": "openai"}"#;
let config: ModelConfig = serde_json::from_str(json).unwrap();
assert_eq!(config.provider, "openai");
assert_eq!(config.model, "claude-opus-4-5-20251101");
assert_eq!(config.max_tokens, 4096);
}
#[test]
fn test_agent_config_serialization_roundtrip() {
let original = AgentConfig::new("test")
.with_description("Test agent")
.with_tool("bash");
let json = serde_json::to_string(&original).unwrap();
let restored: AgentConfig = serde_json::from_str(&json).unwrap();
assert_eq!(original.name, restored.name);
assert_eq!(original.description, restored.description);
assert_eq!(original.tools, restored.tools);
}
#[test]
fn test_empty_json_uses_all_defaults() {
let json = "{}";
let config: AppConfig = serde_json::from_str(json).unwrap();
assert_eq!(config.agent.name, "agent");
assert_eq!(config.agent.model.provider, "anthropic");
assert_eq!(config.server.port, 3000);
}
#[test]
fn test_parse_toml_empty() {
let toml = "";
let config = AppConfig::parse_toml(toml).unwrap();
assert_eq!(config.agent.name, "agent");
assert_eq!(config.server.port, 3000);
}
#[test]
fn test_parse_toml_full() {
let toml = r#"
[agent]
name = "my-agent"
description = "A custom agent"
max_steps = 25
[agent.model]
provider = "openai"
model = "gpt-4"
max_tokens = 2000
temperature = 0.5
[server]
host = "0.0.0.0"
port = 8080
cors_enabled = false
"#;
let config = AppConfig::parse_toml(toml).unwrap();
assert_eq!(config.agent.name, "my-agent");
assert_eq!(config.agent.description, Some("A custom agent".to_string()));
assert_eq!(config.agent.max_steps, 25);
assert_eq!(config.agent.model.provider, "openai");
assert_eq!(config.agent.model.model, "gpt-4");
assert_eq!(config.agent.model.max_tokens, 2000);
assert_eq!(config.agent.model.temperature, 0.5);
assert_eq!(config.server.host, "0.0.0.0");
assert_eq!(config.server.port, 8080);
assert!(!config.server.cors_enabled);
}
#[test]
fn test_parse_toml_partial() {
let toml = r#"
[agent]
name = "partial-agent"
[server]
port = 4000
"#;
let config = AppConfig::parse_toml(toml).unwrap();
assert_eq!(config.agent.name, "partial-agent");
assert_eq!(config.server.port, 4000);
assert_eq!(config.agent.model.provider, "anthropic");
assert_eq!(config.server.host, "127.0.0.1");
}
#[test]
fn test_parse_toml_with_tools() {
let toml = r#"
[agent]
name = "tool-agent"
tools = ["bash", "read_file", "write_file"]
"#;
let config = AppConfig::parse_toml(toml).unwrap();
assert_eq!(config.agent.tools, vec!["bash", "read_file", "write_file"]);
}
#[test]
fn test_parse_toml_invalid() {
let toml = "this is not valid toml [[[";
let result = AppConfig::parse_toml(toml);
assert!(result.is_err());
assert!(matches!(
result.unwrap_err(),
ConfigError::ParseError { .. }
));
}
#[test]
fn test_toml_serialization_roundtrip() {
let original =
AppConfig::default().with_agent(AgentConfig::new("test-agent").with_tool("bash"));
let toml_str = toml::to_string_pretty(&original).unwrap();
let restored = AppConfig::parse_toml(&toml_str).unwrap();
assert_eq!(original.agent.name, restored.agent.name);
assert_eq!(original.agent.tools, restored.agent.tools);
}
#[test]
fn test_load_nonexistent_file() {
let result = AppConfig::load_from_file(Path::new("/nonexistent/path/config.toml"));
assert!(result.is_err());
assert!(matches!(
result.unwrap_err(),
ConfigError::FileNotFound { .. }
));
}
#[test]
fn test_load_with_no_config_uses_defaults() {
let config = AppConfig::load(None).unwrap();
assert_eq!(config.agent.name, "agent");
}
#[test]
fn test_config_error_display() {
let err = ConfigError::FileNotFound {
path: PathBuf::from("/test/path"),
};
assert!(err.to_string().contains("/test/path"));
let err = ConfigError::parse_error("invalid syntax");
assert!(err.to_string().contains("invalid syntax"));
}
#[test]
fn test_save_and_load_config() {
use std::fs;
let temp_dir = std::env::temp_dir();
let config_path = temp_dir.join("agent_test_config.toml");
let original =
AppConfig::default().with_agent(AgentConfig::new("saved-agent").with_max_steps(30));
original.save_to_file(&config_path).unwrap();
let loaded = AppConfig::load_from_file(&config_path).unwrap();
assert_eq!(loaded.agent.name, "saved-agent");
assert_eq!(loaded.agent.max_steps, 30);
fs::remove_file(&config_path).ok();
}
#[test]
fn test_default_config_path() {
let path = AppConfig::default_config_path();
if let Some(p) = path {
assert!(p.to_string_lossy().contains("agent"));
assert!(p.to_string_lossy().contains("config.toml"));
}
}
#[test]
fn test_api_key_from_config() {
let config = AppConfig::default().with_agent(
AgentConfig::default().with_model(ModelConfig::default().with_api_key("config-key")),
);
assert_eq!(config.api_key(), Some("config-key".to_string()));
}
#[test]
fn test_env_override_model() {
let old_model = std::env::var("AGENT_MODEL").ok();
std::env::set_var("AGENT_MODEL", "test-model-from-env");
let mut config = AppConfig::default();
config.apply_env_overrides();
assert_eq!(config.agent.model.model, "test-model-from-env");
if let Some(old) = old_model {
std::env::set_var("AGENT_MODEL", old);
} else {
std::env::remove_var("AGENT_MODEL");
}
}
#[test]
fn test_env_override_port() {
let old_port = std::env::var("AGENT_PORT").ok();
std::env::set_var("AGENT_PORT", "9999");
let mut config = AppConfig::default();
config.apply_env_overrides();
assert_eq!(config.server.port, 9999);
if let Some(old) = old_port {
std::env::set_var("AGENT_PORT", old);
} else {
std::env::remove_var("AGENT_PORT");
}
}
}