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            "xai" => "XAI_API_KEY",
161            "openai" => "OPENAI_API_KEY",
162            "openrouter" => "OPENROUTER_API_KEY",
163            "opencode-zen" | "opencode" | "zen" => "OPENCODE_API_KEY",
164            "claude-cli" => "NONE", // Claude CLI doesn't need API key
165            "codex" => "NONE",      // Codex CLI doesn't need API key
166            "cursor" => "NONE",     // Cursor Agent CLI doesn't need API key
167            _ => "API_KEY",
168        }
169    }
170
171    pub fn requires_api_key(&self) -> bool {
172        let providers = [
173            &self.llm.provider,
174            &self.llm.smart_provider,
175            &self.llm.fast_provider,
176        ];
177        providers
178            .iter()
179            .any(|p| !matches!(p.as_str(), "claude-cli" | "codex" | "cursor"))
180    }
181
182    pub fn api_endpoint(&self) -> &str {
183        match self.llm.provider.as_str() {
184            "anthropic" => "https://api.anthropic.com/v1/messages",
185            "xai" => "https://api.x.ai/v1/chat/completions",
186            "openai" => "https://api.openai.com/v1/chat/completions",
187            "openrouter" => "https://openrouter.ai/api/v1/chat/completions",
188            _ => "https://api.anthropic.com/v1/messages",
189        }
190    }
191
192    pub fn default_model_for_provider(provider: &str) -> &str {
193        match provider {
194            "xai" => "xai/grok-code-fast-1",
195            "anthropic" => "claude-sonnet-4-5-20250929",
196            "openai" => "o3-mini",
197            "openrouter" => "anthropic/claude-sonnet-4.5",
198            "claude-cli" => "sonnet", // Claude CLI model names: sonnet, opus, haiku
199            "codex" => "gpt-5.1",         // Codex CLI default model
200            "cursor" => "claude-4-sonnet", // Cursor Agent default model
201            _ => "xai/grok-code-fast-1",
202        }
203    }
204
205    /// Get suggested models for a provider (for display in init)
206    pub fn suggested_models_for_provider(provider: &str) -> Vec<&str> {
207        match provider {
208            "xai" => vec![
209                "xai/grok-code-fast-1",
210                "xai/grok-4-1-fast",
211                "xai/grok-4-fast",
212                "xai/grok-3-fast",
213            ],
214            "anthropic" => vec![
215                "claude-sonnet-4-5-20250929",
216                "claude-opus-4-5-20251101",
217                "claude-haiku-4-5-20251001",
218                "claude-opus-4-1-20250805",
219            ],
220            "openai" => vec![
221                "gpt-5.2-high",
222                "gpt-5.1",
223                "gpt-5.1-mini",
224                "o3-mini",
225                "o3",
226                "o4-mini",
227                "gpt-4.1",
228            ],
229            "openrouter" => vec![
230                "anthropic/claude-sonnet-4.5",
231                "anthropic/claude-opus-4.5",
232                "openai/o3-mini",
233                "openai/gpt-4.1",
234                "xai/grok-4-1-fast-reasoning",
235            ],
236            "claude-cli" => vec![
237                "opus",   // Claude Opus 4.5 - smart/reasoning
238                "sonnet", // Claude Sonnet - fast/capable
239                "haiku",  // Claude Haiku - fastest
240            ],
241            "codex" => vec![
242                "gpt-5.2-high", // Smart/reasoning model
243                "gpt-5.1",      // Capable model
244                "gpt-5.1-mini", // Fast model
245                "o3",           // Reasoning model
246                "o3-mini",      // Fast reasoning
247            ],
248            "cursor" => vec![
249                "claude-4-opus",   // Smart/reasoning
250                "claude-4-sonnet", // Balanced
251                "gpt-5",          // OpenAI model
252                "gpt-5.2-high",   // High-capability
253            ],
254            _ => vec![],
255        }
256    }
257
258    /// Get the smart provider (for validation/analysis tasks with large context)
259    pub fn smart_provider(&self) -> &str {
260        &self.llm.smart_provider
261    }
262
263    /// Get the smart model (for validation/analysis tasks with large context)
264    pub fn smart_model(&self) -> &str {
265        &self.llm.smart_model
266    }
267
268    /// Get the fast provider (for generation tasks)
269    pub fn fast_provider(&self) -> &str {
270        &self.llm.fast_provider
271    }
272
273    /// Get the fast model (for generation tasks)
274    pub fn fast_model(&self) -> &str {
275        &self.llm.fast_model
276    }
277}
278
279#[cfg(test)]
280mod tests {
281    use super::*;
282    use tempfile::TempDir;
283
284    #[test]
285    fn test_default_config() {
286        let config = Config::default();
287        // Default provider is xai with xai/grok-code-fast-1 for speed
288        assert_eq!(config.llm.provider, "xai");
289        assert_eq!(config.llm.model, "xai/grok-code-fast-1");
290        // Smart tier uses claude-cli with opus
291        assert_eq!(config.llm.smart_provider, "claude-cli");
292        assert_eq!(config.llm.smart_model, "opus");
293        // Fast tier uses xai with xai/grok-code-fast-1
294        assert_eq!(config.llm.fast_provider, "xai");
295        assert_eq!(config.llm.fast_model, "xai/grok-code-fast-1");
296        assert_eq!(config.llm.max_tokens, 16000);
297    }
298
299    #[test]
300    fn test_model_tiers() {
301        let config = Config::default();
302        assert_eq!(config.smart_provider(), "claude-cli");
303        assert_eq!(config.smart_model(), "opus");
304        assert_eq!(config.fast_provider(), "xai");
305        assert_eq!(config.fast_model(), "xai/grok-code-fast-1");
306    }
307
308    #[test]
309    fn test_api_key_env_vars() {
310        let mut config = Config::default();
311
312        config.llm.provider = "anthropic".to_string();
313        assert_eq!(config.api_key_env_var(), "ANTHROPIC_API_KEY");
314
315        config.llm.provider = "xai".to_string();
316        assert_eq!(config.api_key_env_var(), "XAI_API_KEY");
317
318        config.llm.provider = "openai".to_string();
319        assert_eq!(config.api_key_env_var(), "OPENAI_API_KEY");
320
321        config.llm.provider = "claude-cli".to_string();
322        config.llm.smart_provider = "claude-cli".to_string();
323        config.llm.fast_provider = "claude-cli".to_string();
324        assert!(!config.requires_api_key());
325    }
326
327    #[test]
328    fn test_api_endpoints() {
329        let mut config = Config::default();
330
331        config.llm.provider = "anthropic".to_string();
332        assert_eq!(
333            config.api_endpoint(),
334            "https://api.anthropic.com/v1/messages"
335        );
336
337        config.llm.provider = "xai".to_string();
338        assert_eq!(
339            config.api_endpoint(),
340            "https://api.x.ai/v1/chat/completions"
341        );
342
343        config.llm.provider = "openai".to_string();
344        assert_eq!(
345            config.api_endpoint(),
346            "https://api.openai.com/v1/chat/completions"
347        );
348    }
349
350    #[test]
351    fn test_save_and_load_config() {
352        let temp_dir = TempDir::new().unwrap();
353        let config_path = temp_dir.path().join("config.toml");
354
355        let config = Config {
356            llm: LLMConfig {
357                provider: "claude-cli".to_string(),
358                model: "sonnet".to_string(),
359                smart_provider: "claude-cli".to_string(),
360                smart_model: "opus".to_string(),
361                fast_provider: "xai".to_string(),
362                fast_model: "haiku".to_string(),
363                max_tokens: 8192,
364            },
365            swarm: SwarmConfig::default(),
366        };
367
368        config.save(&config_path).unwrap();
369        assert!(config_path.exists());
370
371        let loaded = Config::load(&config_path).unwrap();
372        assert_eq!(loaded.llm.provider, "claude-cli");
373        assert_eq!(loaded.llm.model, "sonnet");
374        assert_eq!(loaded.llm.smart_provider, "claude-cli");
375        assert_eq!(loaded.llm.smart_model, "opus");
376        assert_eq!(loaded.llm.fast_provider, "xai");
377        assert_eq!(loaded.llm.fast_model, "haiku");
378        assert_eq!(loaded.llm.max_tokens, 8192);
379    }
380
381    #[test]
382    fn test_default_models() {
383        assert_eq!(
384            Config::default_model_for_provider("xai"),
385            "xai/grok-code-fast-1"
386        );
387        assert_eq!(
388            Config::default_model_for_provider("anthropic"),
389            "claude-sonnet-4-5-20250929"
390        );
391        assert_eq!(Config::default_model_for_provider("openai"), "o3-mini");
392        assert_eq!(Config::default_model_for_provider("claude-cli"), "sonnet");
393    }
394
395    #[test]
396    fn test_load_config_without_model_tiers() {
397        // Test backward compatibility - loading a config without smart/fast models
398        let temp_dir = TempDir::new().unwrap();
399        let config_path = temp_dir.path().join("config.toml");
400
401        // Write a config without smart_model and fast_model
402        std::fs::write(
403            &config_path,
404            r#"[llm]
405provider = "xai"
406model = "xai/grok-code-fast-1"
407max_tokens = 4096
408"#,
409        )
410        .unwrap();
411
412        let loaded = Config::load(&config_path).unwrap();
413        assert_eq!(loaded.llm.provider, "xai");
414        assert_eq!(loaded.llm.model, "xai/grok-code-fast-1");
415        // Should use defaults for missing fields
416        assert_eq!(loaded.llm.smart_provider, "claude-cli");
417        assert_eq!(loaded.llm.smart_model, "opus");
418        assert_eq!(loaded.llm.fast_provider, "xai");
419        assert_eq!(loaded.llm.fast_model, "xai/grok-code-fast-1");
420    }
421}