1use 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
14pub use crate::agents::via_gateway::shell_quote;
15
16pub fn key_helper_command(visdom: &Path, console_url: &str, project_id: &str) -> String {
19 format!(
20 "{} gateway-key --console {} --project {}",
21 shell_quote(&visdom.to_string_lossy()),
22 shell_quote(console_url),
23 shell_quote(project_id)
24 )
25}
26
27pub fn key_http_client() -> reqwest::Client {
30 reqwest::Client::builder()
31 .timeout(std::time::Duration::from_secs(15))
32 .build()
33 .unwrap_or_default()
34}
35
36pub struct Prepared {
38 pub launch: GatewayLaunch,
39 pub notes: Vec<String>,
41 pub available: Vec<String>,
43}
44
45pub fn prepare_gateway(
56 session: &Session,
57 runtime: &tokio::runtime::Runtime,
58 visdom: &Path,
59 now: i64,
60) -> Result<Prepared, String> {
61 let plan = match &session.gateway {
62 Some(Ok(plan)) => plan,
63 Some(Err(why)) => return Err(why.clone()),
64 None => return Err("this session is not in gateway mode".to_string()),
65 };
66 let token = session
67 .token
68 .as_deref()
69 .ok_or("the AI Gateway needs a Visdom account login: run `visdom login`")?;
70 let http = key_http_client();
71 let store = KeyStore::at(gateway::key_store_path_in(&session.config_root));
72 let key_unless = |rejected: Option<&str>| {
73 runtime.block_on(gateway::ensure_key(
74 &http,
75 &plan.console_url,
76 token,
77 &plan.project.id,
78 &store,
79 now,
80 rejected,
81 ))
82 };
83 let models = |key: &str| runtime.block_on(gateway::models(&http, &plan.llm_url, key));
84 let mut ensured = key_unless(None)?;
85 let available = match models(&ensured.key.secret) {
86 Ok(available) => available,
87 Err(refusal) if refusal.rejected && !ensured.issued => {
88 ensured = key_unless(Some(&ensured.key.secret))?;
89 models(&ensured.key.secret).map_err(|e| e.why)?
90 }
91 Err(e) => return Err(e.why),
92 };
93 let key = ensured.key;
94 let mut notes: Vec<String> = Vec::new();
95 let model = gateway::pick_model(
96 session.ctx.agent,
97 session.gateway_model.as_deref(),
98 &available,
99 );
100 if let Some(configured) = model
101 .as_deref()
102 .filter(|m| !available.iter().any(|a| a == m))
103 {
104 notes.push(format!(
105 "the model alias `{configured}` is not among those your key may call in the project \
106 `{}` ({}): the gateway will refuse it",
107 plan.project.slug,
108 available.join(", ")
109 ));
110 }
111 if model.is_none() {
112 notes.push(format!(
113 "no AI Gateway model alias was chosen for {}: it asks for its own default, which \
114 the project `{}` may not allow (set {}_model under [gateway] in your visdom config, \
115 or VISDOM_GATEWAY_MODEL)",
116 session.ctx.agent.label(),
117 plan.project.slug,
118 agent_config_key(session.ctx.agent)
119 ));
120 }
121 let repo_id = session
125 .ctx
126 .workdir
127 .primary
128 .as_deref()
129 .and_then(|root| TracevaultConfig::try_load(root).ok().flatten())
130 .and_then(|config| config.repo_id)
131 .filter(|id| !id.trim().is_empty())
132 .or_else(|| tracevault_cli::user_default::load().map(|binding| binding.repo_id))
133 .filter(|id| !id.trim().is_empty());
134 Ok(Prepared {
135 launch: GatewayLaunch {
136 llm_url: plan.llm_url.clone(),
137 key: key.secret,
138 key_helper: key_helper_command(visdom, &plan.console_url, &plan.project.id),
139 model,
140 repo_id,
141 session_id: uuid::Uuid::new_v4().to_string(),
142 },
143 notes,
144 available,
145 })
146}
147
148pub fn gateway_setting_env(key: &str) -> Option<&'static str> {
151 match key {
152 "project" => Some("export VISDOM_GATEWAY_PROJECT=<project>"),
153 "url" => Some("export VISDOM_GATEWAY_URL=<console address>"),
154 key if key.ends_with("_model") => Some("export VISDOM_GATEWAY_MODEL=<model alias>"),
155 _ => None,
156 }
157}
158
159pub fn no_model(agent: Agent, project: &str, available: &[String]) -> String {
163 let key = format!("{}_model", agent_config_key(agent));
164 let choice = match available.is_empty() {
165 true => format!("the project `{project}` lets your key call no model alias at all"),
166 false => format!(
167 "none of the model aliases your key may call in the project `{project}` is named \
168 for {} ({})",
169 agent.label(),
170 available.join(", ")
171 ),
172 };
173 format!(
174 "{choice}: set {key} under [gateway] in your visdom config, or VISDOM_GATEWAY_MODEL, to \
175 the alias to use"
176 )
177}
178
179pub fn usable_model(
183 agent: Agent,
184 model: Option<&str>,
185 source: Option<&str>,
186 project: &str,
187 available: &[String],
188) -> Result<(), String> {
189 let Some(model) = model else {
190 return Err(no_model(agent, project, available));
191 };
192 if available.iter().any(|alias| alias == model) {
193 return Ok(());
194 }
195 let from = source.map(|s| format!(" ({s})")).unwrap_or_default();
196 let have = match available.is_empty() {
197 true => "it lets your key call none".to_string(),
198 false => format!("your key may call: {}", available.join(", ")),
199 };
200 Err(format!(
201 "the model alias `{model}`{from} is not one the project `{project}` has — {have}"
202 ))
203}
204
205pub fn gateway_settings_hint(user_config: &Path) -> String {
208 format!(
209 " Settings: `url`, `project`, `claude_code_model`, `codex_model` under [gateway] and \
210 `tracing_mode` in {}.\n \
211 Left out there, they are taken from the environment — VISDOM_GATEWAY_URL, \
212 VISDOM_GATEWAY_PROJECT, VISDOM_GATEWAY_MODEL, VISDOM_TRACING_MODE (which win over the \
213 file when set) — and the gateway's address from the tracing server.",
214 user_config.display()
215 )
216}
217
218pub fn gateway_summary(
221 agent: Agent,
222 mode: &crate::mode::ResolvedMode,
223 plan: &crate::components::gateway::GatewayPlan,
224 sources: &crate::doctor::GatewaySources,
225 model: Option<&str>,
226 user_config: &Path,
227) -> String {
228 use crate::mode::ModeReason;
229 let mode_source = match mode.reason {
230 ModeReason::Policy(policy) => format!(
231 "required by the workspace's AI traffic policy, `{}`",
232 policy.name()
233 ),
234 _ => "your choice".to_string(),
235 };
236 let or = |source: &Option<String>, otherwise: &str| {
237 source.clone().unwrap_or_else(|| otherwise.to_string())
238 };
239 let rows = [
240 ("mode", "gateway".to_string(), mode_source),
241 (
242 "console",
243 plan.console_url.clone(),
244 or(&sources.console_url, "not set"),
245 ),
246 (
247 "LLM gateway",
248 plan.llm_url.clone(),
249 "named by the console".to_string(),
250 ),
251 (
252 "project",
253 plan.project.slug.clone(),
254 or(&sources.project, "the only project open to you"),
255 ),
256 (
257 "model",
258 model.unwrap_or("the agent's own default").to_string(),
259 match model {
260 Some(_) => or(
261 &sources.model,
262 "the first alias the key may call that is named for the agent",
263 ),
264 None => "no alias is set, and the project may refuse the default".to_string(),
265 },
266 ),
267 (
268 "personal key",
269 "issued, and accepted by the LLM gateway".to_string(),
270 "kept for you only, renewed by `visdom`".to_string(),
271 ),
272 ];
273 let width = rows
274 .iter()
275 .map(|(_, value, _)| value.len())
276 .max()
277 .unwrap_or(0);
278 let mut out = format!(
279 "AI Gateway ready for {}: `visdom` starts it through the gateway.\n",
280 agent.label()
281 );
282 for (name, value, source) in rows {
283 out.push_str(&format!(" {name:<13}{value:<width$} ({source})\n"));
284 }
285 out.push_str(&gateway_settings_hint(user_config));
286 out.push_str(
287 "\n To send an agent you start without `visdom` through the gateway as well: \
288 source <(visdom env)\n",
289 );
290 out
291}
292
293pub fn launch_error_message(
295 program: &str,
296 error: &std::io::Error,
297 agent: Agent,
298 user_config: &Path,
299) -> String {
300 format!(
301 "visdom: cannot start {program}: {error} (set agents.{} in {} to use another executable)",
302 agent_config_key(agent),
303 user_config.display()
304 )
305}
306
307pub fn exec_agent(mut cmd: Command, agent: Agent, user_config: &Path) -> ! {
311 let program = cmd.get_program().to_string_lossy().into_owned();
312 let error = replace_process(&mut cmd);
313 eprintln!(
314 "{}",
315 launch_error_message(&program, &error, agent, user_config)
316 );
317 std::process::exit(127)
318}
319
320#[cfg(unix)]
321fn replace_process(cmd: &mut Command) -> std::io::Error {
322 use std::os::unix::process::CommandExt;
323 cmd.exec()
324}
325
326#[cfg(not(unix))]
328fn replace_process(cmd: &mut Command) -> std::io::Error {
329 match cmd.status() {
330 Ok(status) => std::process::exit(status.code().unwrap_or(1)),
331 Err(e) => e,
332 }
333}
334
335#[cfg(test)]
336mod tests {
337 use super::*;
338
339 #[test]
340 fn launch_error_names_the_program_and_the_config_key() {
341 let error = std::io::Error::new(std::io::ErrorKind::NotFound, "No such file");
342 let message = launch_error_message(
343 "claude",
344 &error,
345 Agent::ClaudeCode,
346 Path::new("/home/u/.config/visdom/config.toml"),
347 );
348 assert!(
349 message.contains("cannot start claude: No such file"),
350 "{message}"
351 );
352 assert!(message.contains("agents.claude_code"), "{message}");
353 assert!(
354 message.contains("/home/u/.config/visdom/config.toml"),
355 "{message}"
356 );
357 let message = launch_error_message("codex", &error, Agent::Codex, Path::new("/c"));
358 assert!(message.contains("agents.codex"), "{message}");
359 }
360
361 #[test]
362 fn the_key_helper_is_one_safe_shell_command() {
363 assert_eq!(shell_quote("plain"), "'plain'");
364 assert_eq!(shell_quote("it's"), r"'it'\''s'");
365 assert_eq!(
366 key_helper_command(
367 Path::new("/opt/my tools/visdom"),
368 "https://gw.example.com",
369 "p-1; rm -rf ~"
370 ),
371 "'/opt/my tools/visdom' gateway-key --console 'https://gw.example.com' --project \
372 'p-1; rm -rf ~'"
373 );
374 }
375
376 #[cfg(unix)]
378 #[test]
379 fn a_shell_reads_the_quoted_values_back() {
380 let tricky = ["it's", "a b", "$HOME `id` \"x\"", "p-1; echo no"];
381 for value in tricky {
382 let output = Command::new("sh")
383 .arg("-c")
384 .arg(format!("printf %s {}", shell_quote(value)))
385 .output()
386 .unwrap();
387 assert_eq!(String::from_utf8_lossy(&output.stdout), value);
388 }
389 }
390}