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    /// Shell commands that send this agent, started from that shell without
128    /// `visdom`, through the AI Gateway (`visdom env`).
129    fn env_script(
130        &self,
131        gateway: &via_gateway::GatewayLaunch,
132        project: &str,
133    ) -> Result<String, String> {
134        match self.agent() {
135            Agent::Codex => via_gateway::codex_env_script(self.program(), gateway, project),
136            _ => Ok(via_gateway::claude_env_script(gateway, project)),
137        }
138    }
139}
140
141/// The adapter for `agent`. `program_override` replaces the executable name.
142/// Agents `visdom` cannot launch have no adapter.
143pub fn adapter_for(
144    agent: Agent,
145    paths: AgentPaths,
146    program_override: Option<String>,
147) -> Option<Box<dyn AgentAdapter>> {
148    match agent {
149        Agent::ClaudeCode => Some(Box::new(claude::Claude::new(paths, program_override))),
150        Agent::Codex => Some(Box::new(codex::Codex::new(paths, program_override))),
151        Agent::Gsd | Agent::OpenCode | Agent::Amp => None,
152    }
153}
154
155/// `text` of the file at `path`, `None` when it does not exist.
156pub(crate) fn read_optional(path: &Path) -> Result<Option<String>, String> {
157    match std::fs::read_to_string(path) {
158        Ok(text) => Ok(Some(text)),
159        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
160        Err(e) => Err(format!("cannot read {}: {e}", path.display())),
161    }
162}
163
164fn run_command(program: &str, args: &[&str], cwd: Option<&Path>) -> FixAction {
165    FixAction::RunCommand {
166        program: program.to_string(),
167        args: args.iter().map(|a| a.to_string()).collect(),
168        cwd: cwd.map(Path::to_path_buf),
169    }
170}
171
172#[cfg(test)]
173mod tests {
174    use super::*;
175
176    fn paths(root: &Path) -> AgentPaths {
177        AgentPaths {
178            home: root.to_path_buf(),
179            codex_home: root.join(".codex"),
180        }
181    }
182
183    fn args_of(action: &FixAction) -> (String, Vec<String>, Option<PathBuf>) {
184        match action {
185            FixAction::RunCommand { program, args, cwd } => {
186                (program.clone(), args.clone(), cwd.clone())
187            }
188            other => panic!("expected a command, got {other:?}"),
189        }
190    }
191
192    #[test]
193    fn register_commands_exact_args() {
194        let tmp = tempfile::tempdir().unwrap();
195        let repo = Path::new("/work/repo");
196        let workdir = Workdir {
197            start_dir: repo.join("src"),
198            checkout: Some(repo.to_path_buf()),
199            primary: Some(repo.to_path_buf()),
200        };
201        let url = "https://ctx.example.com/mcp/remote";
202
203        let claude = adapter_for(Agent::ClaudeCode, paths(tmp.path()), None).unwrap();
204        let (program, args, cwd) = args_of(&claude.register_mcp(
205            "bazaar",
206            url,
207            "visdom-context-mcp",
208            McpScope::Local,
209            &workdir,
210        ));
211        assert_eq!(program, "claude");
212        assert_eq!(
213            args,
214            [
215                "mcp",
216                "add",
217                "--transport",
218                "http",
219                "--scope",
220                "local",
221                "--client-id",
222                "visdom-context-mcp",
223                "bazaar",
224                url
225            ]
226        );
227        assert_eq!(
228            cwd.as_deref(),
229            Some(repo.join("src").as_path()),
230            "local scope belongs to the project the command runs in"
231        );
232
233        let codex = adapter_for(Agent::Codex, paths(tmp.path()), None).unwrap();
234        let (program, args, cwd) = args_of(&codex.register_mcp(
235            "bazaar",
236            url,
237            "visdom-context-mcp",
238            McpScope::Local,
239            &workdir,
240        ));
241        assert_eq!(program, "codex");
242        assert_eq!(
243            args,
244            [
245                "mcp",
246                "add",
247                "bazaar",
248                "--url",
249                url,
250                "--oauth-client-id",
251                "visdom-context-mcp"
252            ]
253        );
254        assert_eq!(cwd, None, "Codex has one global configuration");
255
256        // A user-scope registration stays a user-scope one.
257        let (_, args, _) =
258            args_of(&claude.register_mcp("visdom", url, "c", McpScope::User, &workdir));
259        assert_eq!(args[4..6], ["--scope", "user"]);
260    }
261
262    #[test]
263    fn remove_commands_exact_args() {
264        let tmp = tempfile::tempdir().unwrap();
265        let repo = Path::new("/work/repo");
266        let workdir = Workdir::checkout(repo);
267        let entry = |scope| McpEntry {
268            name: "visdom".to_string(),
269            url: None,
270            oauth_client_id: None,
271            scope,
272            extra_settings: false,
273            disabled: false,
274        };
275        let claude = adapter_for(Agent::ClaudeCode, paths(tmp.path()), None).unwrap();
276        let (_, args, cwd) = args_of(&claude.remove_mcp(&entry(McpScope::User), &workdir));
277        assert_eq!(args, ["mcp", "remove", "--scope", "user", "visdom"]);
278        assert_eq!(cwd.as_deref(), Some(repo));
279        let (_, args, _) = args_of(&claude.remove_mcp(&entry(McpScope::Local), &workdir));
280        assert_eq!(args, ["mcp", "remove", "--scope", "local", "visdom"]);
281
282        let codex = adapter_for(Agent::Codex, paths(tmp.path()), None).unwrap();
283        let (_, args, _) = args_of(&codex.remove_mcp(&entry(McpScope::User), &workdir));
284        assert_eq!(args, ["mcp", "remove", "visdom"]);
285    }
286
287    #[test]
288    fn launch_passes_args_through() {
289        let tmp = tempfile::tempdir().unwrap();
290        let args = ["--model".to_string(), "x".to_string()];
291
292        let claude = adapter_for(Agent::ClaudeCode, paths(tmp.path()), None).unwrap();
293        let cmd = claude.launch(&args);
294        assert_eq!(cmd.get_program(), "claude");
295        assert_eq!(cmd.get_args().collect::<Vec<_>>(), ["--model", "x"]);
296
297        let codex = adapter_for(
298            Agent::Codex,
299            paths(tmp.path()),
300            Some("/opt/codex".to_string()),
301        )
302        .unwrap();
303        let cmd = codex.launch(&args);
304        assert_eq!(cmd.get_program(), "/opt/codex");
305        assert_eq!(cmd.get_args().collect::<Vec<_>>(), ["--model", "x"]);
306        // The override also names the program of the registration command.
307        let (program, ..) = args_of(&codex.register_mcp(
308            "bazaar",
309            "https://x/mcp",
310            "c",
311            McpScope::User,
312            &Workdir::plain("/tmp"),
313        ));
314        assert_eq!(program, "/opt/codex");
315    }
316
317    #[test]
318    fn agents_visdom_cannot_launch_have_no_adapter() {
319        let tmp = tempfile::tempdir().unwrap();
320        for agent in [Agent::Gsd, Agent::OpenCode, Agent::Amp] {
321            assert!(adapter_for(agent, paths(tmp.path()), None).is_none());
322        }
323    }
324}