Skip to main content

visdom_cli/agents/
mod.rs

1//! What `visdom` knows about each agent it can launch: where the agent keeps
2//! its MCP servers, how to register one through the agent's own CLI, and how
3//! to start it. Components never read an agent's files themselves.
4
5use std::path::{Path, PathBuf};
6
7use tracevault_cli::agent::Agent;
8
9use crate::finding::FixAction;
10
11pub mod claude;
12pub mod codex;
13pub mod via_gateway;
14
15/// Where an MCP server entry is configured.
16#[derive(Clone, Copy, Debug, PartialEq, Eq)]
17pub enum McpScope {
18    /// For one project directory, in the user's private agent state.
19    Local,
20    /// In a file committed to the repository.
21    Project,
22    /// For every project of this user.
23    User,
24}
25
26#[derive(Clone, Debug, PartialEq, Eq)]
27pub struct McpEntry {
28    pub name: String,
29    pub url: Option<String>,
30    pub oauth_client_id: Option<String>,
31    pub scope: McpScope,
32    /// The entry carries settings beyond its URL and OAuth client (headers,
33    /// timeouts, …) that removing and re-adding it would lose.
34    pub extra_settings: bool,
35    /// Configured but switched off: the agent does not load it.
36    pub disabled: bool,
37}
38
39/// Where the agent is about to run.
40#[derive(Clone, Debug, PartialEq, Eq)]
41pub struct Workdir {
42    /// The directory `visdom` was run in; the agent starts there.
43    pub start_dir: PathBuf,
44    /// Top level of the git checkout around it. `None` outside a repository.
45    pub checkout: Option<PathBuf>,
46    /// The repository's primary checkout: the same as `checkout`, except in a
47    /// linked worktree.
48    pub primary: Option<PathBuf>,
49}
50
51impl Workdir {
52    /// A directory outside any repository.
53    pub fn plain(start_dir: impl Into<PathBuf>) -> Self {
54        Workdir {
55            start_dir: start_dir.into(),
56            checkout: None,
57            primary: None,
58        }
59    }
60
61    /// A primary checkout, entered at its top level.
62    pub fn checkout(dir: impl Into<PathBuf>) -> Self {
63        let dir = dir.into();
64        Workdir {
65            start_dir: dir.clone(),
66            checkout: Some(dir.clone()),
67            primary: Some(dir),
68        }
69    }
70}
71
72/// The directories the agents keep their state under.
73#[derive(Clone, Debug)]
74pub struct AgentPaths {
75    pub home: PathBuf,
76    /// `$CODEX_HOME`, or `~/.codex`.
77    pub codex_home: PathBuf,
78}
79
80pub trait AgentAdapter {
81    fn agent(&self) -> Agent;
82
83    /// The executable `visdom` runs for this agent.
84    fn program(&self) -> &str;
85
86    /// Every MCP server the agent would load when started in `workdir`. An
87    /// unreadable or malformed file is an error that names it.
88    fn mcp_entries(&self, workdir: &Workdir) -> Result<Vec<McpEntry>, String>;
89
90    /// The command that registers an HTTP MCP server with a fixed OAuth
91    /// client in `scope`, for an agent started in `workdir`. An agent with a
92    /// single configuration ignores the scope.
93    fn register_mcp(
94        &self,
95        name: &str,
96        url: &str,
97        client_id: &str,
98        scope: McpScope,
99        workdir: &Workdir,
100    ) -> FixAction;
101
102    /// The command that removes `entry`.
103    fn remove_mcp(&self, entry: &McpEntry, workdir: &Workdir) -> FixAction;
104
105    /// The command that starts the agent with `args`.
106    fn launch(&self, args: &[String]) -> std::process::Command {
107        let mut cmd = std::process::Command::new(self.program());
108        cmd.args(args);
109        cmd
110    }
111
112    /// The command that starts the agent with `args` and its LLM traffic
113    /// going through the AI Gateway. `env` reads the current environment.
114    /// `Err` when the caller's own `args` would take the session elsewhere.
115    fn launch_via_gateway(
116        &self,
117        args: &[String],
118        gateway: &via_gateway::GatewayLaunch,
119        env: &dyn Fn(&str) -> Option<String>,
120    ) -> Result<std::process::Command, String> {
121        match self.agent() {
122            Agent::Codex => via_gateway::codex_command(self.program(), args, gateway),
123            _ => via_gateway::claude_command(self.program(), args, gateway, env),
124        }
125    }
126}
127
128/// The adapter for `agent`. `program_override` replaces the executable name.
129/// Agents `visdom` cannot launch have no adapter.
130pub fn adapter_for(
131    agent: Agent,
132    paths: AgentPaths,
133    program_override: Option<String>,
134) -> Option<Box<dyn AgentAdapter>> {
135    match agent {
136        Agent::ClaudeCode => Some(Box::new(claude::Claude::new(paths, program_override))),
137        Agent::Codex => Some(Box::new(codex::Codex::new(paths, program_override))),
138        Agent::Gsd | Agent::OpenCode | Agent::Amp => None,
139    }
140}
141
142/// `text` of the file at `path`, `None` when it does not exist.
143pub(crate) fn read_optional(path: &Path) -> Result<Option<String>, String> {
144    match std::fs::read_to_string(path) {
145        Ok(text) => Ok(Some(text)),
146        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
147        Err(e) => Err(format!("cannot read {}: {e}", path.display())),
148    }
149}
150
151fn run_command(program: &str, args: &[&str], cwd: Option<&Path>) -> FixAction {
152    FixAction::RunCommand {
153        program: program.to_string(),
154        args: args.iter().map(|a| a.to_string()).collect(),
155        cwd: cwd.map(Path::to_path_buf),
156    }
157}
158
159#[cfg(test)]
160mod tests {
161    use super::*;
162
163    fn paths(root: &Path) -> AgentPaths {
164        AgentPaths {
165            home: root.to_path_buf(),
166            codex_home: root.join(".codex"),
167        }
168    }
169
170    fn args_of(action: &FixAction) -> (String, Vec<String>, Option<PathBuf>) {
171        match action {
172            FixAction::RunCommand { program, args, cwd } => {
173                (program.clone(), args.clone(), cwd.clone())
174            }
175            other => panic!("expected a command, got {other:?}"),
176        }
177    }
178
179    #[test]
180    fn register_commands_exact_args() {
181        let tmp = tempfile::tempdir().unwrap();
182        let repo = Path::new("/work/repo");
183        let workdir = Workdir {
184            start_dir: repo.join("src"),
185            checkout: Some(repo.to_path_buf()),
186            primary: Some(repo.to_path_buf()),
187        };
188        let url = "https://ctx.example.com/mcp/remote";
189
190        let claude = adapter_for(Agent::ClaudeCode, paths(tmp.path()), None).unwrap();
191        let (program, args, cwd) = args_of(&claude.register_mcp(
192            "bazaar",
193            url,
194            "visdom-context-mcp",
195            McpScope::Local,
196            &workdir,
197        ));
198        assert_eq!(program, "claude");
199        assert_eq!(
200            args,
201            [
202                "mcp",
203                "add",
204                "--transport",
205                "http",
206                "--scope",
207                "local",
208                "--client-id",
209                "visdom-context-mcp",
210                "bazaar",
211                url
212            ]
213        );
214        assert_eq!(
215            cwd.as_deref(),
216            Some(repo.join("src").as_path()),
217            "local scope belongs to the project the command runs in"
218        );
219
220        let codex = adapter_for(Agent::Codex, paths(tmp.path()), None).unwrap();
221        let (program, args, cwd) = args_of(&codex.register_mcp(
222            "bazaar",
223            url,
224            "visdom-context-mcp",
225            McpScope::Local,
226            &workdir,
227        ));
228        assert_eq!(program, "codex");
229        assert_eq!(
230            args,
231            [
232                "mcp",
233                "add",
234                "bazaar",
235                "--url",
236                url,
237                "--oauth-client-id",
238                "visdom-context-mcp"
239            ]
240        );
241        assert_eq!(cwd, None, "Codex has one global configuration");
242
243        // A user-scope registration stays a user-scope one.
244        let (_, args, _) =
245            args_of(&claude.register_mcp("visdom", url, "c", McpScope::User, &workdir));
246        assert_eq!(args[4..6], ["--scope", "user"]);
247    }
248
249    #[test]
250    fn remove_commands_exact_args() {
251        let tmp = tempfile::tempdir().unwrap();
252        let repo = Path::new("/work/repo");
253        let workdir = Workdir::checkout(repo);
254        let entry = |scope| McpEntry {
255            name: "visdom".to_string(),
256            url: None,
257            oauth_client_id: None,
258            scope,
259            extra_settings: false,
260            disabled: false,
261        };
262        let claude = adapter_for(Agent::ClaudeCode, paths(tmp.path()), None).unwrap();
263        let (_, args, cwd) = args_of(&claude.remove_mcp(&entry(McpScope::User), &workdir));
264        assert_eq!(args, ["mcp", "remove", "--scope", "user", "visdom"]);
265        assert_eq!(cwd.as_deref(), Some(repo));
266        let (_, args, _) = args_of(&claude.remove_mcp(&entry(McpScope::Local), &workdir));
267        assert_eq!(args, ["mcp", "remove", "--scope", "local", "visdom"]);
268
269        let codex = adapter_for(Agent::Codex, paths(tmp.path()), None).unwrap();
270        let (_, args, _) = args_of(&codex.remove_mcp(&entry(McpScope::User), &workdir));
271        assert_eq!(args, ["mcp", "remove", "visdom"]);
272    }
273
274    #[test]
275    fn launch_passes_args_through() {
276        let tmp = tempfile::tempdir().unwrap();
277        let args = ["--model".to_string(), "x".to_string()];
278
279        let claude = adapter_for(Agent::ClaudeCode, paths(tmp.path()), None).unwrap();
280        let cmd = claude.launch(&args);
281        assert_eq!(cmd.get_program(), "claude");
282        assert_eq!(cmd.get_args().collect::<Vec<_>>(), ["--model", "x"]);
283
284        let codex = adapter_for(
285            Agent::Codex,
286            paths(tmp.path()),
287            Some("/opt/codex".to_string()),
288        )
289        .unwrap();
290        let cmd = codex.launch(&args);
291        assert_eq!(cmd.get_program(), "/opt/codex");
292        assert_eq!(cmd.get_args().collect::<Vec<_>>(), ["--model", "x"]);
293        // The override also names the program of the registration command.
294        let (program, ..) = args_of(&codex.register_mcp(
295            "bazaar",
296            "https://x/mcp",
297            "c",
298            McpScope::User,
299            &Workdir::plain("/tmp"),
300        ));
301        assert_eq!(program, "/opt/codex");
302    }
303
304    #[test]
305    fn agents_visdom_cannot_launch_have_no_adapter() {
306        let tmp = tempfile::tempdir().unwrap();
307        for agent in [Agent::Gsd, Agent::OpenCode, Agent::Amp] {
308            assert!(adapter_for(agent, paths(tmp.path()), None).is_none());
309        }
310    }
311}