Skip to main content

dot/
config.rs

1use anyhow::{Context, Result};
2use serde::{Deserialize, Serialize};
3use std::collections::HashMap;
4use std::path::PathBuf;
5
6#[derive(Debug, Clone, Serialize, Deserialize)]
7pub struct Config {
8    pub default_provider: String,
9    pub default_model: String,
10    pub theme: ThemeConfig,
11    #[serde(default)]
12    pub context: ContextConfig,
13    #[serde(default)]
14    pub acp_agents: HashMap<String, AcpAgentConfig>,
15    #[serde(default)]
16    pub mcp: HashMap<String, McpServerConfig>,
17    #[serde(default)]
18    pub agents: HashMap<String, AgentConfig>,
19    #[serde(default)]
20    pub tui: TuiConfig,
21    #[serde(default)]
22    pub permissions: HashMap<String, String>,
23    #[serde(default)]
24    pub providers: HashMap<String, ProviderDefinition>,
25    #[serde(default)]
26    pub custom_tools: HashMap<String, CustomToolConfig>,
27    #[serde(default)]
28    pub commands: HashMap<String, CommandConfig>,
29    #[serde(default)]
30    pub hooks: HashMap<String, HookConfig>,
31    #[serde(default)]
32    pub subagents: SubagentSettings,
33    #[serde(default)]
34    pub memory: MemoryConfig,
35}
36
37#[derive(Debug, Clone, Serialize, Deserialize)]
38pub struct ContextConfig {
39    #[serde(default = "default_true")]
40    pub auto_load_global: bool,
41    #[serde(default = "default_true")]
42    pub auto_load_project: bool,
43}
44impl Default for ContextConfig {
45    fn default() -> Self {
46        Self {
47            auto_load_global: true,
48            auto_load_project: true,
49        }
50    }
51}
52
53#[derive(Debug, Clone, Serialize, Deserialize)]
54pub struct ThemeConfig {
55    pub name: String,
56}
57
58#[derive(Debug, Clone, Serialize, Deserialize, Default)]
59pub struct AcpAgentConfig {
60    #[serde(default)]
61    pub command: Vec<String>,
62    #[serde(default)]
63    pub env: HashMap<String, String>,
64    #[serde(default = "default_true")]
65    pub enabled: bool,
66    #[serde(default)]
67    pub description: String,
68}
69
70#[derive(Debug, Clone, Serialize, Deserialize)]
71pub struct McpServerConfig {
72    #[serde(default)]
73    pub command: Vec<String>,
74    pub url: Option<String>,
75    #[serde(default = "default_true")]
76    pub enabled: bool,
77    #[serde(default)]
78    pub env: HashMap<String, String>,
79    #[serde(default = "default_timeout")]
80    pub timeout: u64,
81}
82
83#[derive(Debug, Clone, Serialize, Deserialize)]
84pub struct AgentConfig {
85    pub description: String,
86    pub model: Option<String>,
87    pub system_prompt: Option<String>,
88    #[serde(default)]
89    pub tools: HashMap<String, bool>,
90    #[serde(default = "default_true")]
91    pub enabled: bool,
92}
93
94#[derive(Debug, Clone, Serialize, Deserialize, Default)]
95#[serde(rename_all = "snake_case")]
96pub enum CursorShape {
97    #[default]
98    Block,
99    Underline,
100    Line,
101}
102
103#[derive(Debug, Clone, Serialize, Deserialize)]
104pub struct TuiConfig {
105    #[serde(default = "default_true")]
106    pub vim_mode: bool,
107    #[serde(default)]
108    pub favorite_models: Vec<String>,
109    #[serde(default)]
110    pub cursor_shape: CursorShape,
111    #[serde(default)]
112    pub cursor_shape_normal: Option<CursorShape>,
113    #[serde(default = "default_true")]
114    pub cursor_blink: bool,
115    #[serde(default)]
116    pub cursor_blink_normal: Option<bool>,
117}
118
119impl Default for TuiConfig {
120    fn default() -> Self {
121        Self {
122            vim_mode: true,
123            favorite_models: Vec::new(),
124            cursor_shape: CursorShape::default(),
125            cursor_shape_normal: None,
126            cursor_blink: true,
127            cursor_blink_normal: None,
128        }
129    }
130}
131
132#[derive(Debug, Clone, Serialize, Deserialize)]
133pub struct ProviderDefinition {
134    pub api: String,
135    pub base_url: Option<String>,
136    #[serde(default)]
137    pub api_key_env: Option<String>,
138    #[serde(default)]
139    pub models: Vec<String>,
140    pub default_model: Option<String>,
141    #[serde(default = "default_true")]
142    pub enabled: bool,
143}
144
145#[derive(Debug, Clone, Serialize, Deserialize)]
146pub struct CustomToolConfig {
147    pub description: String,
148    pub command: String,
149    #[serde(default = "default_schema")]
150    pub schema: serde_json::Value,
151    #[serde(default = "default_timeout")]
152    pub timeout: u64,
153}
154
155#[derive(Debug, Clone, Serialize, Deserialize)]
156pub struct CommandConfig {
157    pub description: String,
158    pub command: String,
159    #[serde(default = "default_timeout")]
160    pub timeout: u64,
161}
162
163#[derive(Debug, Clone, Serialize, Deserialize)]
164pub struct HookConfig {
165    pub command: String,
166    #[serde(default = "default_timeout")]
167    pub timeout: u64,
168}
169
170#[derive(Debug, Clone, Serialize, Deserialize)]
171pub struct SubagentSettings {
172    #[serde(default = "default_true")]
173    pub enabled: bool,
174    #[serde(default)]
175    pub max_turns: Option<usize>,
176    #[serde(default)]
177    pub default_model: Option<String>,
178}
179
180impl Default for SubagentSettings {
181    fn default() -> Self {
182        Self {
183            enabled: true,
184            max_turns: None,
185            default_model: None,
186        }
187    }
188}
189
190#[derive(Debug, Clone, Serialize, Deserialize)]
191pub struct MemoryConfig {
192    #[serde(default = "default_true")]
193    pub enabled: bool,
194    #[serde(default = "default_true")]
195    pub auto_extract: bool,
196    #[serde(default = "default_inject_count")]
197    pub inject_count: usize,
198    #[serde(default = "default_max_memories")]
199    pub max_memories: usize,
200}
201
202impl Default for MemoryConfig {
203    fn default() -> Self {
204        Self {
205            enabled: true,
206            auto_extract: true,
207            inject_count: 15,
208            max_memories: 2000,
209        }
210    }
211}
212
213fn default_inject_count() -> usize {
214    15
215}
216
217fn default_max_memories() -> usize {
218    2000
219}
220
221fn default_true() -> bool {
222    true
223}
224
225fn default_timeout() -> u64 {
226    30
227}
228
229fn default_schema() -> serde_json::Value {
230    serde_json::json!({
231        "type": "object",
232        "properties": {},
233        "required": []
234    })
235}
236
237impl Default for Config {
238    fn default() -> Self {
239        Self {
240            default_provider: "anthropic".to_string(),
241            default_model: "claude-sonnet-4-20250514".to_string(),
242            theme: ThemeConfig {
243                name: "terminal".to_string(),
244            },
245            context: ContextConfig::default(),
246            acp_agents: HashMap::new(),
247            mcp: HashMap::new(),
248            agents: HashMap::new(),
249            tui: TuiConfig::default(),
250            permissions: HashMap::new(),
251            providers: HashMap::new(),
252            custom_tools: HashMap::new(),
253            commands: HashMap::new(),
254            hooks: HashMap::new(),
255            subagents: SubagentSettings::default(),
256            memory: MemoryConfig::default(),
257        }
258    }
259}
260
261impl Config {
262    pub fn config_dir() -> PathBuf {
263        if let Ok(xdg) = std::env::var("XDG_CONFIG_HOME")
264            && !xdg.is_empty()
265        {
266            return PathBuf::from(xdg).join("dot");
267        }
268        #[cfg(unix)]
269        return dirs::home_dir()
270            .unwrap_or_else(|| PathBuf::from("."))
271            .join(".config")
272            .join("dot");
273        #[cfg(not(unix))]
274        dirs::config_dir()
275            .unwrap_or_else(|| PathBuf::from("."))
276            .join("dot")
277    }
278
279    pub fn config_path() -> PathBuf {
280        Self::config_dir().join("config.toml")
281    }
282
283    pub fn data_dir() -> PathBuf {
284        if let Ok(xdg) = std::env::var("XDG_DATA_HOME")
285            && !xdg.is_empty()
286        {
287            return PathBuf::from(xdg).join("dot");
288        }
289        #[cfg(unix)]
290        return dirs::home_dir()
291            .unwrap_or_else(|| PathBuf::from("."))
292            .join(".local")
293            .join("share")
294            .join("dot");
295        #[cfg(not(unix))]
296        dirs::data_local_dir()
297            .unwrap_or_else(|| PathBuf::from("."))
298            .join("dot")
299    }
300
301    pub fn db_path() -> PathBuf {
302        Self::data_dir().join("dot.db")
303    }
304
305    pub fn load() -> Result<Self> {
306        let path = Self::config_path();
307        if path.exists() {
308            let content = std::fs::read_to_string(&path)
309                .with_context(|| format!("reading config from {}", path.display()))?;
310            toml::from_str(&content).context("parsing config.toml")
311        } else {
312            let config = Self::default();
313            config.save()?;
314            Ok(config)
315        }
316    }
317
318    pub fn save(&self) -> Result<()> {
319        let dir = Self::config_dir();
320        std::fs::create_dir_all(&dir)
321            .with_context(|| format!("creating config dir {}", dir.display()))?;
322        let content = toml::to_string_pretty(self).context("serializing config")?;
323        std::fs::write(Self::config_path(), content).context("writing config.toml")
324    }
325
326    pub fn ensure_dirs() -> Result<()> {
327        std::fs::create_dir_all(Self::config_dir()).context("creating config directory")?;
328        std::fs::create_dir_all(Self::data_dir()).context("creating data directory")?;
329        Ok(())
330    }
331
332    pub fn enabled_mcp_servers(&self) -> Vec<(&str, &McpServerConfig)> {
333        self.mcp
334            .iter()
335            .filter(|(_, cfg)| cfg.enabled && !cfg.command.is_empty())
336            .map(|(name, cfg)| (name.as_str(), cfg))
337            .collect()
338    }
339
340    pub fn enabled_agents(&self) -> Vec<(&str, &AgentConfig)> {
341        self.agents
342            .iter()
343            .filter(|(_, cfg)| cfg.enabled)
344            .map(|(name, cfg)| (name.as_str(), cfg))
345            .collect()
346    }
347
348    /// Parse a `provider/model` spec. Returns `(provider, model)` if `/` present,
349    /// otherwise `(None, spec)`.
350    pub fn parse_model_spec(spec: &str) -> (Option<&str>, &str) {
351        if let Some((provider, model)) = spec.split_once('/') {
352            (Some(provider), model)
353        } else {
354            (None, spec)
355        }
356    }
357}