Skip to main content

visdom_cli/
config.rs

1//! visdom's own settings: the user file (`<config dir>/visdom/config.toml`)
2//! and the optional committed repository file (`.visdom/config.toml`), plus
3//! the choice of agent.
4
5use std::path::{Path, PathBuf};
6
7use clap::ValueEnum;
8use serde::{Deserialize, Deserializer};
9use tracevault_cli::agent::Agent;
10
11use crate::billing::{parse_billing, Billing};
12use crate::mode::{parse_mode, TracingMode};
13
14/// `<config dir>/visdom/config.toml`.
15#[derive(Debug, Default, Deserialize)]
16pub struct UserConfig {
17    /// The agent `visdom` launches by default.
18    #[serde(default, deserialize_with = "de_agent")]
19    pub agent: Option<Agent>,
20    /// The bazaar MCP endpoint, when the server does not publish it.
21    #[serde(default)]
22    pub bazaar_url: Option<String>,
23    /// How this developer's sessions are traced: `hooks` or `gateway`.
24    #[serde(default, deserialize_with = "de_mode")]
25    pub tracing_mode: Option<TracingMode>,
26    /// Control Plane's address, when the server does not publish it.
27    #[serde(default)]
28    pub control_plane_url: Option<String>,
29    /// Per-agent executable overrides.
30    #[serde(default)]
31    pub agents: AgentCommands,
32    /// The AI Gateway, for `tracing_mode = "gateway"`.
33    #[serde(default)]
34    pub gateway: GatewayConfig,
35    /// `false`: an agent `visdom` starts is told nothing about Visdom's
36    /// tools (see [`crate::instructions`]). Told by default.
37    #[serde(default)]
38    pub agent_instructions: Option<bool>,
39}
40
41/// `[gateway]`: how to reach and use the AI Gateway.
42#[derive(Debug, Default, Deserialize)]
43pub struct GatewayConfig {
44    /// The gateway console's address, when the server does not publish it.
45    #[serde(default)]
46    pub url: Option<String>,
47    /// The gateway project (its slug) whose personal key the agent uses.
48    #[serde(default)]
49    pub project: Option<String>,
50    /// The model alias Claude Code asks the gateway for.
51    #[serde(default, alias = "claude-code-model")]
52    pub claude_code_model: Option<String>,
53    /// The model alias Codex asks the gateway for.
54    #[serde(default, alias = "codex-model")]
55    pub codex_model: Option<String>,
56    /// Who pays for the agent's calls through the gateway: `project` (the
57    /// default) or `subscription`.
58    #[serde(default, deserialize_with = "de_billing")]
59    pub billing: Option<Billing>,
60}
61
62impl GatewayConfig {
63    /// The configured model alias for `agent`, if any.
64    pub fn model_for(&self, agent: Agent) -> Option<String> {
65        match agent {
66            Agent::ClaudeCode => self.claude_code_model.clone(),
67            Agent::Codex => self.codex_model.clone(),
68            _ => None,
69        }
70    }
71}
72
73/// `[agents]`: the executable to run for an agent instead of the default.
74#[derive(Debug, Default, Deserialize)]
75pub struct AgentCommands {
76    #[serde(default, alias = "claude-code")]
77    pub claude_code: Option<String>,
78    #[serde(default)]
79    pub codex: Option<String>,
80}
81
82impl AgentCommands {
83    /// The configured executable for `agent`, if any.
84    pub fn program_for(&self, agent: Agent) -> Option<String> {
85        match agent {
86            Agent::ClaudeCode => self.claude_code.clone(),
87            Agent::Codex => self.codex.clone(),
88            _ => None,
89        }
90    }
91}
92
93/// `.visdom/config.toml` in a repository: what the team prefers for it.
94#[derive(Debug, Default, Deserialize)]
95pub struct RepoConfig {
96    #[serde(default, deserialize_with = "de_agent")]
97    pub agent: Option<Agent>,
98    /// The tracing mode the team prefers here; a developer's own choice on
99    /// the command line or in the environment still wins.
100    #[serde(default, deserialize_with = "de_mode")]
101    pub tracing_mode: Option<TracingMode>,
102    #[serde(default)]
103    pub gateway: RepoGatewayConfig,
104}
105
106/// `[gateway]` in a repository: the gateway project this repository belongs to.
107#[derive(Debug, Default, Deserialize)]
108pub struct RepoGatewayConfig {
109    #[serde(default)]
110    pub project: Option<String>,
111    /// Who pays, when the repository or workspace folder says so.
112    #[serde(default, deserialize_with = "de_billing")]
113    pub billing: Option<Billing>,
114}
115
116/// The `[agents]` key that overrides `agent`'s executable.
117pub fn agent_config_key(agent: Agent) -> &'static str {
118    match agent {
119        Agent::ClaudeCode => "claude_code",
120        Agent::Codex => "codex",
121        Agent::Gsd => "gsd",
122        Agent::OpenCode => "opencode",
123        Agent::Amp => "amp",
124    }
125}
126
127/// Parse an agent name as the command line spells it (`claude-code`, `codex`).
128pub fn parse_agent(name: &str) -> Result<Agent, String> {
129    Agent::from_str(name.trim(), true)
130        .map_err(|_| format!("unknown agent `{name}` (visdom can launch claude-code and codex)"))
131}
132
133fn de_agent<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Agent>, D::Error> {
134    match Option::<String>::deserialize(d)? {
135        None => Ok(None),
136        Some(name) => parse_agent(&name)
137            .map(Some)
138            .map_err(serde::de::Error::custom),
139    }
140}
141
142fn de_mode<'de, D: Deserializer<'de>>(d: D) -> Result<Option<TracingMode>, D::Error> {
143    match Option::<String>::deserialize(d)? {
144        None => Ok(None),
145        Some(name) => parse_mode(&name)
146            .map(Some)
147            .map_err(serde::de::Error::custom),
148    }
149}
150
151fn de_billing<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Billing>, D::Error> {
152    match Option::<String>::deserialize(d)? {
153        None => Ok(None),
154        Some(name) => parse_billing(&name)
155            .map(Some)
156            .map_err(serde::de::Error::custom),
157    }
158}
159
160pub fn user_config_path_in(config_root: &Path) -> PathBuf {
161    config_root.join("visdom").join("config.toml")
162}
163
164pub fn repo_config_path_in(project_root: &Path) -> PathBuf {
165    project_root.join(".visdom").join("config.toml")
166}
167
168fn load<T: Default + for<'de> Deserialize<'de>>(path: &Path) -> Result<T, String> {
169    let text = match std::fs::read_to_string(path) {
170        Ok(text) => text,
171        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(T::default()),
172        Err(e) => return Err(format!("cannot read {}: {e}", path.display())),
173    };
174    toml::from_str(&text).map_err(|e| format!("cannot parse {}: {e}", path.display()))
175}
176
177/// The user config under `config_root` (the platform config directory). A
178/// missing file is the default config.
179pub fn load_user_config_in(config_root: &Path) -> Result<UserConfig, String> {
180    load(&user_config_path_in(config_root))
181}
182
183/// The repository config in `project_root`. A missing file is the default.
184pub fn load_repo_config_in(project_root: &Path) -> Result<RepoConfig, String> {
185    load(&repo_config_path_in(project_root))
186}
187
188/// The agent somebody chose outside the command line: `VISDOM_AGENT`, then
189/// the repository config, then the user config. `None` when nobody did.
190pub fn configured_agent(
191    env: Option<&str>,
192    repo: &RepoConfig,
193    user: &UserConfig,
194) -> Result<Option<Agent>, String> {
195    match env.filter(|v| !v.trim().is_empty()) {
196        Some(name) => parse_agent(name)
197            .map(Some)
198            .map_err(|e| format!("VISDOM_AGENT: {e}")),
199        None => Ok(repo.agent.or(user.agent)),
200    }
201}
202
203/// Which agent to use: `--agent`, then `VISDOM_AGENT`, then the repository
204/// config, then the user config, then Claude Code. Only Claude Code and Codex
205/// can be launched.
206pub fn resolve_agent(
207    flag: Option<Agent>,
208    env: Option<&str>,
209    repo: &RepoConfig,
210    user: &UserConfig,
211) -> Result<Agent, String> {
212    let agent = match flag {
213        Some(agent) => agent,
214        None => configured_agent(env, repo, user)?.unwrap_or(Agent::ClaudeCode),
215    };
216    match agent {
217        Agent::ClaudeCode | Agent::Codex => Ok(agent),
218        other => Err(format!(
219            "visdom can launch claude-code and codex; {} is not supported yet",
220            other.tool_name()
221        )),
222    }
223}
224
225#[cfg(test)]
226mod tests {
227    use super::*;
228
229    fn user(agent: Option<Agent>) -> UserConfig {
230        UserConfig {
231            agent,
232            ..Default::default()
233        }
234    }
235
236    #[test]
237    fn agent_precedence_flag_env_repo_user_default() {
238        let repo = RepoConfig {
239            agent: Some(Agent::Codex),
240            ..Default::default()
241        };
242        let none = RepoConfig::default();
243        let cases = [
244            // (flag, env, repo, user) => expected
245            (
246                Some(Agent::ClaudeCode),
247                Some("codex"),
248                &repo,
249                Some(Agent::Codex),
250                Agent::ClaudeCode,
251            ),
252            (
253                None,
254                Some("codex"),
255                &none,
256                Some(Agent::ClaudeCode),
257                Agent::Codex,
258            ),
259            (None, None, &repo, Some(Agent::ClaudeCode), Agent::Codex),
260            (None, None, &none, Some(Agent::Codex), Agent::Codex),
261            (None, None, &none, None, Agent::ClaudeCode),
262        ];
263        for (flag, env, repo, user_agent, expected) in cases {
264            assert_eq!(
265                resolve_agent(flag, env, repo, &user(user_agent)),
266                Ok(expected),
267                "flag={flag:?} env={env:?} repo={:?} user={user_agent:?}",
268                repo.agent
269            );
270        }
271        // An empty variable is the same as an unset one.
272        assert_eq!(
273            resolve_agent(None, Some(""), &none, &user(None)),
274            Ok(Agent::ClaudeCode)
275        );
276    }
277
278    #[test]
279    fn configured_agent_is_none_when_nobody_chose() {
280        let none = RepoConfig::default();
281        assert_eq!(configured_agent(None, &none, &user(None)), Ok(None));
282        assert_eq!(configured_agent(Some(" "), &none, &user(None)), Ok(None));
283        assert_eq!(
284            configured_agent(None, &none, &user(Some(Agent::Codex))),
285            Ok(Some(Agent::Codex))
286        );
287        assert_eq!(
288            configured_agent(Some("codex"), &none, &user(None)),
289            Ok(Some(Agent::Codex))
290        );
291        assert!(configured_agent(Some("emacs"), &none, &user(None)).is_err());
292    }
293
294    #[test]
295    fn unsupported_agent_is_error() {
296        let err = resolve_agent(
297            Some(Agent::Gsd),
298            None,
299            &RepoConfig::default(),
300            &UserConfig::default(),
301        )
302        .unwrap_err();
303        assert!(err.contains("gsd is not supported yet"), "{err}");
304        let err = resolve_agent(
305            None,
306            Some("emacs"),
307            &RepoConfig::default(),
308            &UserConfig::default(),
309        )
310        .unwrap_err();
311        assert!(
312            err.contains("VISDOM_AGENT") && err.contains("emacs"),
313            "{err}"
314        );
315    }
316
317    #[test]
318    fn missing_config_files_are_default() {
319        let tmp = tempfile::tempdir().unwrap();
320        let user = load_user_config_in(tmp.path()).unwrap();
321        assert!(user.agent.is_none() && user.bazaar_url.is_none());
322        assert!(load_repo_config_in(tmp.path()).unwrap().agent.is_none());
323    }
324
325    #[test]
326    fn user_config_reads_every_field() {
327        let tmp = tempfile::tempdir().unwrap();
328        let path = user_config_path_in(tmp.path());
329        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
330        std::fs::write(
331            &path,
332            "agent = \"codex\"\nbazaar_url = \"https://ctx.example.com/mcp/remote\"\n\
333             [agents]\nclaude_code = \"/opt/claude\"\ncodex = \"/opt/codex\"\n",
334        )
335        .unwrap();
336        let user = load_user_config_in(tmp.path()).unwrap();
337        assert_eq!(user.agent, Some(Agent::Codex));
338        assert_eq!(
339            user.bazaar_url.as_deref(),
340            Some("https://ctx.example.com/mcp/remote")
341        );
342        assert_eq!(
343            user.agents.program_for(Agent::ClaudeCode).as_deref(),
344            Some("/opt/claude")
345        );
346        assert_eq!(
347            user.agents.program_for(Agent::Codex).as_deref(),
348            Some("/opt/codex")
349        );
350    }
351
352    #[test]
353    fn malformed_user_config_is_error_naming_the_path() {
354        let tmp = tempfile::tempdir().unwrap();
355        let path = user_config_path_in(tmp.path());
356        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
357        std::fs::write(&path, "agent = [not toml").unwrap();
358        let err = load_user_config_in(tmp.path()).unwrap_err();
359        assert!(err.contains(&path.display().to_string()), "{err}");
360
361        std::fs::write(&path, "agent = \"emacs\"\n").unwrap();
362        let err = load_user_config_in(tmp.path()).unwrap_err();
363        assert!(err.contains("emacs"), "{err}");
364    }
365
366    #[test]
367    fn the_tracing_mode_and_gateway_settings_are_read() {
368        let tmp = tempfile::tempdir().unwrap();
369        let path = user_config_path_in(tmp.path());
370        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
371        std::fs::write(
372            &path,
373            "tracing_mode = \"gateway\"\ncontrol_plane_url = \"https://cp.example.com\"\n\n\
374             [gateway]\nurl = \"https://gw.example.com\"\nproject = \"alpha\"\n\
375             claude_code_model = \"claude-sonnet\"\ncodex-model = \"gpt-general\"\n",
376        )
377        .unwrap();
378        let user = load_user_config_in(tmp.path()).unwrap();
379        assert_eq!(user.tracing_mode, Some(TracingMode::Gateway));
380        assert_eq!(
381            user.control_plane_url.as_deref(),
382            Some("https://cp.example.com")
383        );
384        assert_eq!(user.gateway.url.as_deref(), Some("https://gw.example.com"));
385        assert_eq!(user.gateway.project.as_deref(), Some("alpha"));
386        assert_eq!(
387            user.gateway.model_for(Agent::ClaudeCode).as_deref(),
388            Some("claude-sonnet")
389        );
390        assert_eq!(
391            user.gateway.model_for(Agent::Codex).as_deref(),
392            Some("gpt-general")
393        );
394        assert_eq!(user.gateway.model_for(Agent::Amp), None);
395        assert_eq!(user.gateway.billing, None);
396    }
397
398    #[test]
399    fn who_pays_is_read_from_both_files_and_checked() {
400        let tmp = tempfile::tempdir().unwrap();
401        let path = user_config_path_in(tmp.path());
402        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
403        std::fs::write(&path, "[gateway]\nbilling = \"subscription\"\n").unwrap();
404        let user = load_user_config_in(tmp.path()).unwrap();
405        assert_eq!(user.gateway.billing, Some(Billing::Subscription));
406
407        let repo_path = repo_config_path_in(tmp.path());
408        std::fs::create_dir_all(repo_path.parent().unwrap()).unwrap();
409        std::fs::write(&repo_path, "[gateway]\nbilling = \"project\"\n").unwrap();
410        let repo = load_repo_config_in(tmp.path()).unwrap();
411        assert_eq!(repo.gateway.billing, Some(Billing::Project));
412
413        std::fs::write(&path, "[gateway]\nbilling = \"free\"\n").unwrap();
414        let err = load_user_config_in(tmp.path()).unwrap_err();
415        assert!(err.contains("project or subscription"), "{err}");
416    }
417
418    #[test]
419    fn a_repository_names_its_mode_and_gateway_project() {
420        let tmp = tempfile::tempdir().unwrap();
421        let path = repo_config_path_in(tmp.path());
422        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
423        std::fs::write(
424            &path,
425            "tracing_mode = \"hooks\"\n\n[gateway]\nproject = \"beta\"\n",
426        )
427        .unwrap();
428        let repo = load_repo_config_in(tmp.path()).unwrap();
429        assert_eq!(repo.tracing_mode, Some(TracingMode::Hooks));
430        assert_eq!(repo.gateway.project.as_deref(), Some("beta"));
431        assert_eq!(repo.agent, None);
432    }
433
434    #[test]
435    fn an_unknown_tracing_mode_is_a_config_error() {
436        let tmp = tempfile::tempdir().unwrap();
437        let path = user_config_path_in(tmp.path());
438        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
439        std::fs::write(&path, "tracing_mode = \"proxy\"\n").unwrap();
440        let err = load_user_config_in(tmp.path()).unwrap_err();
441        assert!(err.contains("hooks or gateway"), "{err}");
442    }
443}