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