Skip to main content

scud/
config.rs

1use anyhow::{Context, Result};
2use serde::{Deserialize, Serialize};
3use std::fs;
4use std::path::Path;
5
6#[derive(Debug, Clone, Serialize, Deserialize)]
7pub struct Config {
8    pub llm: LLMConfig,
9    #[serde(default)]
10    pub swarm: SwarmConfig,
11}
12
13#[derive(Debug, Clone, Serialize, Deserialize)]
14pub struct SwarmConfig {
15    #[serde(default = "default_swarm_harness")]
16    pub harness: String,
17    #[serde(default = "default_round_size")]
18    pub round_size: usize,
19    #[serde(default = "default_default_tag")]
20    pub default_tag: Option<String>,
21    /// Use direct API instead of CLI harnesses.
22    /// Requires `direct-api` Cargo feature.
23    #[serde(default)]
24    pub use_direct_api: bool,
25    /// Provider for direct API mode: anthropic, openai, xai, openrouter, opencode-zen
26    #[serde(default = "default_direct_api_provider")]
27    pub direct_api_provider: String,
28}
29
30fn default_swarm_harness() -> String {
31    "claude".to_string()
32}
33
34fn default_round_size() -> usize {
35    5
36}
37
38fn default_default_tag() -> Option<String> {
39    None
40}
41
42fn default_direct_api_provider() -> String {
43    std::env::var("SCUD_DIRECT_API_PROVIDER").unwrap_or_else(|_| "anthropic".to_string())
44}
45
46impl Default for SwarmConfig {
47    fn default() -> Self {
48        SwarmConfig {
49            harness: default_swarm_harness(),
50            round_size: default_round_size(),
51            default_tag: default_default_tag(),
52            use_direct_api: false,
53            direct_api_provider: default_direct_api_provider(),
54        }
55    }
56}
57
58#[derive(Debug, Clone, Serialize, Deserialize)]
59pub struct LLMConfig {
60    /// Default provider
61    #[serde(default = "default_provider")]
62    pub provider: String,
63    /// Default model (used when no tier specified)
64    #[serde(default = "default_model")]
65    pub model: String,
66    /// Smart provider for validation/analysis tasks
67    #[serde(default = "default_smart_provider")]
68    pub smart_provider: String,
69    /// Smart model for validation/analysis tasks (large context)
70    #[serde(default = "default_smart_model")]
71    pub smart_model: String,
72    /// Fast provider for generation tasks
73    #[serde(default = "default_fast_provider")]
74    pub fast_provider: String,
75    /// Fast model for generation tasks
76    #[serde(default = "default_fast_model")]
77    pub fast_model: String,
78    /// Max tokens for LLM requests
79    #[serde(default = "default_max_tokens")]
80    pub max_tokens: u32,
81}
82
83fn default_provider() -> String {
84    std::env::var("SCUD_PROVIDER").unwrap_or_else(|_| "xai".to_string())
85}
86
87fn default_model() -> String {
88    std::env::var("SCUD_MODEL").unwrap_or_else(|_| "xai/grok-code-fast-1".to_string())
89}
90
91fn default_smart_provider() -> String {
92    std::env::var("SCUD_SMART_PROVIDER").unwrap_or_else(|_| "claude-cli".to_string())
93}
94
95fn default_smart_model() -> String {
96    std::env::var("SCUD_SMART_MODEL").unwrap_or_else(|_| "opus".to_string())
97}
98
99fn default_fast_provider() -> String {
100    std::env::var("SCUD_FAST_PROVIDER").unwrap_or_else(|_| "xai".to_string())
101}
102
103fn default_fast_model() -> String {
104    std::env::var("SCUD_FAST_MODEL").unwrap_or_else(|_| "xai/grok-code-fast-1".to_string())
105}
106
107fn default_max_tokens() -> u32 {
108    std::env::var("SCUD_MAX_TOKENS")
109        .ok()
110        .and_then(|s| s.parse().ok())
111        .unwrap_or(16000)
112}
113
114impl Default for Config {
115    fn default() -> Self {
116        Config {
117            llm: LLMConfig {
118                provider: default_provider(),
119                model: default_model(),
120                smart_provider: default_smart_provider(),
121                smart_model: default_smart_model(),
122                fast_provider: default_fast_provider(),
123                fast_model: default_fast_model(),
124                max_tokens: default_max_tokens(),
125            },
126            swarm: SwarmConfig::default(),
127        }
128    }
129}
130
131impl Config {
132    pub fn load(path: &Path) -> Result<Self> {
133        let content = fs::read_to_string(path)
134            .with_context(|| format!("Failed to read config file: {}", path.display()))?;
135
136        toml::from_str(&content)
137            .with_context(|| format!("Failed to parse config file: {}", path.display()))
138    }
139
140    pub fn save(&self, path: &Path) -> Result<()> {
141        let content = toml::to_string_pretty(self).context("Failed to serialize config to TOML")?;
142
143        if let Some(parent) = path.parent() {
144            fs::create_dir_all(parent).with_context(|| {
145                format!("Failed to create config directory: {}", parent.display())
146            })?;
147        }
148
149        fs::write(path, content)
150            .with_context(|| format!("Failed to write config file: {}", path.display()))
151    }
152
153    pub fn api_key_env_var(&self) -> &str {
154        Self::api_key_env_var_for_provider(&self.llm.provider)
155    }
156
157    pub fn api_key_env_var_for_provider(provider: &str) -> &str {
158        match provider {
159            "anthropic" => "ANTHROPIC_API_KEY",
160            "anthropic-oauth" => "NONE", // Uses Claude Code OAuth from Keychain
161            "xai" => "XAI_API_KEY",
162            "openai" => "OPENAI_API_KEY",
163            "openrouter" => "OPENROUTER_API_KEY",
164            "opencode-zen" | "opencode" | "zen" => "OPENCODE_API_KEY",
165            "claude-cli" => "NONE", // Claude CLI doesn't need API key
166            "codex" => "NONE",      // Codex CLI doesn't need API key
167            "cursor" => "NONE",     // Cursor Agent CLI doesn't need API key
168            _ => "API_KEY",
169        }
170    }
171
172    pub fn requires_api_key(&self) -> bool {
173        let providers = [
174            &self.llm.provider,
175            &self.llm.smart_provider,
176            &self.llm.fast_provider,
177        ];
178        providers.iter().any(|p| {
179            !matches!(
180                p.as_str(),
181                "claude-cli" | "codex" | "cursor" | "anthropic-oauth"
182            )
183        })
184    }
185
186    pub fn api_endpoint(&self) -> &str {
187        match self.llm.provider.as_str() {
188            "anthropic" => "https://api.anthropic.com/v1/messages",
189            "xai" => "https://api.x.ai/v1/chat/completions",
190            "openai" => "https://api.openai.com/v1/chat/completions",
191            "openrouter" => "https://openrouter.ai/api/v1/chat/completions",
192            _ => "https://api.anthropic.com/v1/messages",
193        }
194    }
195
196    pub fn default_model_for_provider(provider: &str) -> &str {
197        match provider {
198            "xai" => "xai/grok-code-fast-1",
199            "anthropic" => "claude-sonnet-4-5-20250929",
200            "openai" => "o3-mini",
201            "openrouter" => "anthropic/claude-sonnet-4.5",
202            "claude-cli" => "sonnet", // Claude CLI model names: sonnet, opus, haiku
203            "codex" => "gpt-5.1",         // Codex CLI default model
204            "cursor" => "claude-4-sonnet", // Cursor Agent default model
205            _ => "xai/grok-code-fast-1",
206        }
207    }
208
209    /// Get suggested models for a provider (for display in init)
210    pub fn suggested_models_for_provider(provider: &str) -> Vec<&str> {
211        match provider {
212            "xai" => vec![
213                "xai/grok-code-fast-1",
214                "xai/grok-4-1-fast",
215                "xai/grok-4-fast",
216                "xai/grok-3-fast",
217            ],
218            "anthropic" => vec![
219                "claude-sonnet-4-5-20250929",
220                "claude-opus-4-5-20251101",
221                "claude-haiku-4-5-20251001",
222                "claude-opus-4-1-20250805",
223            ],
224            "openai" => vec![
225                "gpt-5.2-high",
226                "gpt-5.1",
227                "gpt-5.1-mini",
228                "o3-mini",
229                "o3",
230                "o4-mini",
231                "gpt-4.1",
232            ],
233            "openrouter" => vec![
234                "anthropic/claude-sonnet-4.5",
235                "anthropic/claude-opus-4.5",
236                "openai/o3-mini",
237                "openai/gpt-4.1",
238                "xai/grok-4-1-fast-reasoning",
239            ],
240            "claude-cli" => vec![
241                "opus",   // Claude Opus 4.5 - smart/reasoning
242                "sonnet", // Claude Sonnet - fast/capable
243                "haiku",  // Claude Haiku - fastest
244            ],
245            "codex" => vec![
246                "gpt-5.2-high", // Smart/reasoning model
247                "gpt-5.1",      // Capable model
248                "gpt-5.1-mini", // Fast model
249                "o3",           // Reasoning model
250                "o3-mini",      // Fast reasoning
251            ],
252            "cursor" => vec![
253                "claude-4-opus",   // Smart/reasoning
254                "claude-4-sonnet", // Balanced
255                "gpt-5",          // OpenAI model
256                "gpt-5.2-high",   // High-capability
257            ],
258            _ => vec![],
259        }
260    }
261
262    /// Get the smart provider (for validation/analysis tasks with large context)
263    pub fn smart_provider(&self) -> &str {
264        &self.llm.smart_provider
265    }
266
267    /// Get the smart model (for validation/analysis tasks with large context)
268    pub fn smart_model(&self) -> &str {
269        &self.llm.smart_model
270    }
271
272    /// Get the fast provider (for generation tasks)
273    pub fn fast_provider(&self) -> &str {
274        &self.llm.fast_provider
275    }
276
277    /// Get the fast model (for generation tasks)
278    pub fn fast_model(&self) -> &str {
279        &self.llm.fast_model
280    }
281}
282
283#[cfg(test)]
284mod tests {
285    use super::*;
286    use tempfile::TempDir;
287
288    #[test]
289    fn test_default_config() {
290        let config = Config::default();
291        // Default provider is xai with xai/grok-code-fast-1 for speed
292        assert_eq!(config.llm.provider, "xai");
293        assert_eq!(config.llm.model, "xai/grok-code-fast-1");
294        // Smart tier uses claude-cli with opus
295        assert_eq!(config.llm.smart_provider, "claude-cli");
296        assert_eq!(config.llm.smart_model, "opus");
297        // Fast tier uses xai with xai/grok-code-fast-1
298        assert_eq!(config.llm.fast_provider, "xai");
299        assert_eq!(config.llm.fast_model, "xai/grok-code-fast-1");
300        assert_eq!(config.llm.max_tokens, 16000);
301    }
302
303    #[test]
304    fn test_model_tiers() {
305        let config = Config::default();
306        assert_eq!(config.smart_provider(), "claude-cli");
307        assert_eq!(config.smart_model(), "opus");
308        assert_eq!(config.fast_provider(), "xai");
309        assert_eq!(config.fast_model(), "xai/grok-code-fast-1");
310    }
311
312    #[test]
313    fn test_api_key_env_vars() {
314        let mut config = Config::default();
315
316        config.llm.provider = "anthropic".to_string();
317        assert_eq!(config.api_key_env_var(), "ANTHROPIC_API_KEY");
318
319        config.llm.provider = "xai".to_string();
320        assert_eq!(config.api_key_env_var(), "XAI_API_KEY");
321
322        config.llm.provider = "openai".to_string();
323        assert_eq!(config.api_key_env_var(), "OPENAI_API_KEY");
324
325        config.llm.provider = "claude-cli".to_string();
326        config.llm.smart_provider = "claude-cli".to_string();
327        config.llm.fast_provider = "claude-cli".to_string();
328        assert!(!config.requires_api_key());
329    }
330
331    #[test]
332    fn test_api_endpoints() {
333        let mut config = Config::default();
334
335        config.llm.provider = "anthropic".to_string();
336        assert_eq!(
337            config.api_endpoint(),
338            "https://api.anthropic.com/v1/messages"
339        );
340
341        config.llm.provider = "xai".to_string();
342        assert_eq!(
343            config.api_endpoint(),
344            "https://api.x.ai/v1/chat/completions"
345        );
346
347        config.llm.provider = "openai".to_string();
348        assert_eq!(
349            config.api_endpoint(),
350            "https://api.openai.com/v1/chat/completions"
351        );
352    }
353
354    #[test]
355    fn test_save_and_load_config() {
356        let temp_dir = TempDir::new().unwrap();
357        let config_path = temp_dir.path().join("config.toml");
358
359        let config = Config {
360            llm: LLMConfig {
361                provider: "claude-cli".to_string(),
362                model: "sonnet".to_string(),
363                smart_provider: "claude-cli".to_string(),
364                smart_model: "opus".to_string(),
365                fast_provider: "xai".to_string(),
366                fast_model: "haiku".to_string(),
367                max_tokens: 8192,
368            },
369            swarm: SwarmConfig::default(),
370        };
371
372        config.save(&config_path).unwrap();
373        assert!(config_path.exists());
374
375        let loaded = Config::load(&config_path).unwrap();
376        assert_eq!(loaded.llm.provider, "claude-cli");
377        assert_eq!(loaded.llm.model, "sonnet");
378        assert_eq!(loaded.llm.smart_provider, "claude-cli");
379        assert_eq!(loaded.llm.smart_model, "opus");
380        assert_eq!(loaded.llm.fast_provider, "xai");
381        assert_eq!(loaded.llm.fast_model, "haiku");
382        assert_eq!(loaded.llm.max_tokens, 8192);
383    }
384
385    #[test]
386    fn test_default_models() {
387        assert_eq!(
388            Config::default_model_for_provider("xai"),
389            "xai/grok-code-fast-1"
390        );
391        assert_eq!(
392            Config::default_model_for_provider("anthropic"),
393            "claude-sonnet-4-5-20250929"
394        );
395        assert_eq!(Config::default_model_for_provider("openai"), "o3-mini");
396        assert_eq!(Config::default_model_for_provider("claude-cli"), "sonnet");
397    }
398
399    #[test]
400    fn test_load_config_without_model_tiers() {
401        // Test backward compatibility - loading a config without smart/fast models
402        let temp_dir = TempDir::new().unwrap();
403        let config_path = temp_dir.path().join("config.toml");
404
405        // Write a config without smart_model and fast_model
406        std::fs::write(
407            &config_path,
408            r#"[llm]
409provider = "xai"
410model = "xai/grok-code-fast-1"
411max_tokens = 4096
412"#,
413        )
414        .unwrap();
415
416        let loaded = Config::load(&config_path).unwrap();
417        assert_eq!(loaded.llm.provider, "xai");
418        assert_eq!(loaded.llm.model, "xai/grok-code-fast-1");
419        // Should use defaults for missing fields
420        assert_eq!(loaded.llm.smart_provider, "claude-cli");
421        assert_eq!(loaded.llm.smart_model, "opus");
422        assert_eq!(loaded.llm.fast_provider, "xai");
423        assert_eq!(loaded.llm.fast_model, "xai/grok-code-fast-1");
424    }
425}