Skip to main content

visdom_cli/
launch.rs

1//! Handing the terminal over to the agent.
2
3use std::path::Path;
4use std::process::Command;
5
6use tracevault_cli::agent::Agent;
7use tracevault_cli::config::TracevaultConfig;
8
9use crate::agents::via_gateway::GatewayLaunch;
10use crate::config::agent_config_key;
11use crate::doctor::Session;
12use crate::gateway::{self, KeyStore};
13
14/// `text` as one word of a POSIX shell command.
15pub fn shell_quote(text: &str) -> String {
16    format!("'{}'", text.replace('\'', "'\\''"))
17}
18
19/// The command a launched agent runs to get its gateway key: this `visdom`,
20/// asked for the key of one console and project.
21pub fn key_helper_command(visdom: &Path, console_url: &str, project_id: &str) -> String {
22    format!(
23        "{} gateway-key --console {} --project {}",
24        shell_quote(&visdom.to_string_lossy()),
25        shell_quote(console_url),
26        shell_quote(project_id)
27    )
28}
29
30/// The HTTP client for getting a key: the agent does not start without it,
31/// so it may take longer than a check.
32pub fn key_http_client() -> reqwest::Client {
33    reqwest::Client::builder()
34        .timeout(std::time::Duration::from_secs(15))
35        .build()
36        .unwrap_or_default()
37}
38
39/// Everything the agent needs to run through the gateway: the developer's
40/// key (the kept one, or a new one), a model alias and the ids that attribute
41/// the session. The second value holds what the developer should know (no
42/// model alias to ask for).
43///
44/// The LLM gateway is asked for its models with the key before anything is
45/// started: an agent pointed at a gateway that does not answer, or does not
46/// take the key, would run with nothing recording it. A kept key the gateway
47/// refuses (a newer one was issued elsewhere, which revoked it) is replaced
48/// once.
49pub fn prepare_gateway(
50    session: &Session,
51    runtime: &tokio::runtime::Runtime,
52    visdom: &Path,
53    now: i64,
54) -> Result<(GatewayLaunch, Vec<String>), String> {
55    let plan = match &session.gateway {
56        Some(Ok(plan)) => plan,
57        Some(Err(why)) => return Err(why.clone()),
58        None => return Err("this session is not in gateway mode".to_string()),
59    };
60    let token = session
61        .token
62        .as_deref()
63        .ok_or("the AI Gateway needs a Visdom account login: run `visdom login`")?;
64    let http = key_http_client();
65    let store = KeyStore::at(gateway::key_store_path_in(&session.config_root));
66    let key_unless = |rejected: Option<&str>| {
67        runtime.block_on(gateway::ensure_key(
68            &http,
69            &plan.console_url,
70            token,
71            &plan.project.id,
72            &store,
73            now,
74            rejected,
75        ))
76    };
77    let models = |key: &str| runtime.block_on(gateway::models(&http, &plan.llm_url, key));
78    let mut ensured = key_unless(None)?;
79    let available = match models(&ensured.key.secret) {
80        Ok(available) => available,
81        Err(refusal) if refusal.rejected && !ensured.issued => {
82            ensured = key_unless(Some(&ensured.key.secret))?;
83            models(&ensured.key.secret).map_err(|e| e.why)?
84        }
85        Err(e) => return Err(e.why),
86    };
87    let key = ensured.key;
88    let mut notes: Vec<String> = Vec::new();
89    let model = gateway::pick_model(
90        session.ctx.agent,
91        session.gateway_model.as_deref(),
92        &available,
93    );
94    if model.is_none() {
95        notes.push(format!(
96            "no AI Gateway model alias was chosen for {}: it asks for its own default, which \
97             the project `{}` may not allow (set {}_model under [gateway] in your visdom config)",
98            session.ctx.agent.label(),
99            plan.project.slug,
100            agent_config_key(session.ctx.agent)
101        ));
102    }
103    // The repository a new session's events go under, as far as it is known
104    // before the session exists: the checkout's own, else the user's default
105    // (`tracevault repo switch --user`), as the capture hook has it.
106    let repo_id = session
107        .ctx
108        .workdir
109        .primary
110        .as_deref()
111        .and_then(|root| TracevaultConfig::try_load(root).ok().flatten())
112        .and_then(|config| config.repo_id)
113        .filter(|id| !id.trim().is_empty())
114        .or_else(|| tracevault_cli::user_default::load().map(|binding| binding.repo_id))
115        .filter(|id| !id.trim().is_empty());
116    Ok((
117        GatewayLaunch {
118            llm_url: plan.llm_url.clone(),
119            key: key.secret,
120            key_helper: key_helper_command(visdom, &plan.console_url, &plan.project.id),
121            model,
122            repo_id,
123            session_id: uuid::Uuid::new_v4().to_string(),
124        },
125        notes,
126    ))
127}
128
129/// What to tell the user when the agent's executable cannot be started.
130pub fn launch_error_message(
131    program: &str,
132    error: &std::io::Error,
133    agent: Agent,
134    user_config: &Path,
135) -> String {
136    format!(
137        "visdom: cannot start {program}: {error} (set agents.{} in {} to use another executable)",
138        agent_config_key(agent),
139        user_config.display()
140    )
141}
142
143/// Replace this process with the agent, so the terminal, signals and exit
144/// code are the agent's. Returns only by exiting: 127 when the executable
145/// cannot be started.
146pub fn exec_agent(mut cmd: Command, agent: Agent, user_config: &Path) -> ! {
147    let program = cmd.get_program().to_string_lossy().into_owned();
148    let error = replace_process(&mut cmd);
149    eprintln!(
150        "{}",
151        launch_error_message(&program, &error, agent, user_config)
152    );
153    std::process::exit(127)
154}
155
156#[cfg(unix)]
157fn replace_process(cmd: &mut Command) -> std::io::Error {
158    use std::os::unix::process::CommandExt;
159    cmd.exec()
160}
161
162/// Without `exec`: run the agent as a child and exit with its status.
163#[cfg(not(unix))]
164fn replace_process(cmd: &mut Command) -> std::io::Error {
165    match cmd.status() {
166        Ok(status) => std::process::exit(status.code().unwrap_or(1)),
167        Err(e) => e,
168    }
169}
170
171#[cfg(test)]
172mod tests {
173    use super::*;
174
175    #[test]
176    fn launch_error_names_the_program_and_the_config_key() {
177        let error = std::io::Error::new(std::io::ErrorKind::NotFound, "No such file");
178        let message = launch_error_message(
179            "claude",
180            &error,
181            Agent::ClaudeCode,
182            Path::new("/home/u/.config/visdom/config.toml"),
183        );
184        assert!(
185            message.contains("cannot start claude: No such file"),
186            "{message}"
187        );
188        assert!(message.contains("agents.claude_code"), "{message}");
189        assert!(
190            message.contains("/home/u/.config/visdom/config.toml"),
191            "{message}"
192        );
193        let message = launch_error_message("codex", &error, Agent::Codex, Path::new("/c"));
194        assert!(message.contains("agents.codex"), "{message}");
195    }
196
197    #[test]
198    fn the_key_helper_is_one_safe_shell_command() {
199        assert_eq!(shell_quote("plain"), "'plain'");
200        assert_eq!(shell_quote("it's"), r"'it'\''s'");
201        assert_eq!(
202            key_helper_command(
203                Path::new("/opt/my tools/visdom"),
204                "https://gw.example.com",
205                "p-1; rm -rf ~"
206            ),
207            "'/opt/my tools/visdom' gateway-key --console 'https://gw.example.com' --project \
208             'p-1; rm -rf ~'"
209        );
210    }
211
212    /// The helper command survives a real shell as the three values it holds.
213    #[cfg(unix)]
214    #[test]
215    fn a_shell_reads_the_quoted_values_back() {
216        let tricky = ["it's", "a b", "$HOME `id` \"x\"", "p-1; echo no"];
217        for value in tricky {
218            let output = Command::new("sh")
219                .arg("-c")
220                .arg(format!("printf %s {}", shell_quote(value)))
221                .output()
222                .unwrap();
223            assert_eq!(String::from_utf8_lossy(&output.stdout), value);
224        }
225    }
226}