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, CLAUDE_SETTINGS_PREFIX};
10use crate::billing::{Billing, BillingUse};
11use crate::config::agent_config_key;
12use crate::doctor::Session;
13use crate::gateway::{self, KeyStore};
14
15pub use crate::agents::via_gateway::shell_quote;
16
17pub fn key_helper_command(
20 visdom: &Path,
21 console_url: &str,
22 project_id: &str,
23 billing: Billing,
24) -> String {
25 let kind = match billing {
26 Billing::Project => String::new(),
27 Billing::Subscription => format!(" --billing {}", billing.name()),
28 };
29 format!(
30 "{} gateway-key --console {} --project {}{kind}",
31 shell_quote(&visdom.to_string_lossy()),
32 shell_quote(console_url),
33 shell_quote(project_id)
34 )
35}
36
37pub fn private_dir(config_root: &Path) -> std::path::PathBuf {
41 dirs::state_dir()
42 .unwrap_or_else(|| config_root.to_path_buf())
43 .join("visdom")
44}
45
46pub fn session_billing(session: &Session) -> Billing {
49 match session.billing_use {
50 BillingUse::Applies => session.billing.billing,
51 _ => Billing::Project,
52 }
53}
54
55pub fn key_http_client() -> reqwest::Client {
58 reqwest::Client::builder()
59 .timeout(std::time::Duration::from_secs(15))
60 .build()
61 .unwrap_or_default()
62}
63
64pub struct Prepared {
66 pub launch: GatewayLaunch,
67 pub notes: Vec<String>,
69 pub available: Vec<String>,
71 pub pickable: Vec<String>,
74 pub key_expires_at: i64,
76}
77
78pub fn prepare_gateway(
89 session: &Session,
90 runtime: &tokio::runtime::Runtime,
91 visdom: &Path,
92 now: i64,
93) -> Result<Prepared, String> {
94 let plan = match &session.gateway {
95 Some(Ok(plan)) => plan,
96 Some(Err(why)) => return Err(why.clone()),
97 None => return Err("this session is not in gateway mode".to_string()),
98 };
99 let token = session
100 .token
101 .as_deref()
102 .ok_or("the AI Gateway needs a Visdom account login: run `visdom login`")?;
103 let http = key_http_client();
104 let billing = session_billing(session);
105 let store = KeyStore::at(gateway::key_store_path_in(&session.config_root));
106 let key_unless = |rejected: Option<&str>| {
107 runtime.block_on(gateway::ensure_key(
108 &http,
109 &plan.console_url,
110 token,
111 &plan.project.id,
112 billing,
113 &store,
114 now,
115 rejected,
116 ))
117 };
118 let models = |key: &str| runtime.block_on(gateway::models(&http, &plan.llm_url, key));
119 let mut ensured = key_unless(None)?;
120 let available = match models(&ensured.key.secret) {
121 Ok(available) => available,
122 Err(refusal) if refusal.rejected && !ensured.issued => {
123 ensured = key_unless(Some(&ensured.key.secret))?;
124 models(&ensured.key.secret).map_err(|e| e.why)?
125 }
126 Err(e) => return Err(e.why),
127 };
128 let key = ensured.key;
129 let mut notes: Vec<String> = Vec::new();
130 let pickable = match billing {
133 Billing::Subscription => crate::subscription::eligible_of(&plan.project, &available),
134 Billing::Project => available.clone(),
135 };
136 let model = gateway::pick_model(
137 session.ctx.agent,
138 session.gateway_model.as_deref(),
139 &pickable,
140 );
141 if let Some(configured) = model
142 .as_deref()
143 .filter(|m| !available.iter().any(|a| a == m))
144 {
145 notes.push(format!(
146 "the model alias `{configured}` is not among those your key may call in the project \
147 `{}` ({}): the gateway will refuse it",
148 plan.project.slug,
149 available.join(", ")
150 ));
151 }
152 if model.is_none() {
153 notes.push(format!(
154 "no AI Gateway model alias was chosen for {}: it asks for its own default, which \
155 the project `{}` may not allow (set {}_model under [gateway] in your visdom config, \
156 or VISDOM_GATEWAY_MODEL)",
157 session.ctx.agent.label(),
158 plan.project.slug,
159 agent_config_key(session.ctx.agent)
160 ));
161 }
162 let repo_id = session
166 .ctx
167 .workdir
168 .primary
169 .as_deref()
170 .and_then(|root| TracevaultConfig::try_load(root).ok().flatten())
171 .and_then(|config| config.repo_id)
172 .filter(|id| !id.trim().is_empty())
173 .or_else(|| tracevault_cli::user_default::load().map(|binding| binding.repo_id))
174 .filter(|id| !id.trim().is_empty());
175 let key_expires_at = key.expires_at;
176 Ok(Prepared {
177 key_expires_at,
178 pickable,
179 launch: GatewayLaunch {
180 llm_url: plan.llm_url.clone(),
181 key: key.secret,
182 key_helper: key_helper_command(visdom, &plan.console_url, &plan.project.id, billing),
183 model,
184 repo_id,
185 session_id: uuid::Uuid::new_v4().to_string(),
186 billing,
187 private_dir: private_dir(&session.config_root),
188 },
189 notes,
190 available,
191 })
192}
193
194pub fn gateway_setting_env(key: &str) -> Option<&'static str> {
197 match key {
198 "project" => Some("export VISDOM_GATEWAY_PROJECT=<project>"),
199 "url" => Some("export VISDOM_GATEWAY_URL=<console address>"),
200 "billing" => Some("export VISDOM_GATEWAY_BILLING=<project|subscription>"),
201 key if key.ends_with("_model") => Some("export VISDOM_GATEWAY_MODEL=<model alias>"),
202 _ => None,
203 }
204}
205
206pub fn no_model(agent: Agent, project: &str, available: &[String]) -> String {
210 let key = format!("{}_model", agent_config_key(agent));
211 let choice = match available.is_empty() {
212 true => format!("the project `{project}` lets your key call no model alias at all"),
213 false => format!(
214 "none of the model aliases your key may call in the project `{project}` is named \
215 for {} ({})",
216 agent.label(),
217 available.join(", ")
218 ),
219 };
220 format!(
221 "{choice}: set {key} under [gateway] in your visdom config, or VISDOM_GATEWAY_MODEL, to \
222 the alias to use"
223 )
224}
225
226pub fn usable_model(
230 agent: Agent,
231 model: Option<&str>,
232 source: Option<&str>,
233 project: &str,
234 available: &[String],
235) -> Result<(), String> {
236 let Some(model) = model else {
237 return Err(no_model(agent, project, available));
238 };
239 if available.iter().any(|alias| alias == model) {
240 return Ok(());
241 }
242 let from = source.map(|s| format!(" ({s})")).unwrap_or_default();
243 let have = match available.is_empty() {
244 true => "it lets your key call none".to_string(),
245 false => format!("your key may call: {}", available.join(", ")),
246 };
247 Err(format!(
248 "the model alias `{model}`{from} is not one the project `{project}` has — {have}"
249 ))
250}
251
252pub fn gateway_settings_hint(user_config: &Path) -> String {
255 format!(
256 " Settings: `url`, `project`, `claude_code_model`, `codex_model`, `billing` under \
257 [gateway] and `tracing_mode` in {}.\n \
258 Left out there, they are taken from the environment — VISDOM_GATEWAY_URL, \
259 VISDOM_GATEWAY_PROJECT, VISDOM_GATEWAY_MODEL, VISDOM_GATEWAY_BILLING, \
260 VISDOM_TRACING_MODE (which win over the file when set) — and the gateway's address \
261 from the tracing server.",
262 user_config.display()
263 )
264}
265
266pub fn gateway_summary(
269 agent: Agent,
270 mode: &crate::mode::ResolvedMode,
271 plan: &crate::components::gateway::GatewayPlan,
272 sources: &crate::doctor::GatewaySources,
273 model: Option<&str>,
274 billing: &crate::billing::ResolvedBilling,
275 user_config: &Path,
276) -> String {
277 use crate::mode::ModeReason;
278 let mode_source = match mode.reason {
279 ModeReason::Policy(policy) => format!(
280 "required by the workspace's AI traffic policy, `{}`",
281 policy.name()
282 ),
283 _ => "your choice".to_string(),
284 };
285 let or = |source: &Option<String>, otherwise: &str| {
286 source.clone().unwrap_or_else(|| otherwise.to_string())
287 };
288 let rows = [
289 ("mode", "gateway".to_string(), mode_source),
290 (
291 "console",
292 plan.console_url.clone(),
293 or(&sources.console_url, "not set"),
294 ),
295 (
296 "LLM gateway",
297 plan.llm_url.clone(),
298 "named by the console".to_string(),
299 ),
300 (
301 "project",
302 plan.project.slug.clone(),
303 or(&sources.project, "the only project open to you"),
304 ),
305 (
306 "model",
307 model.unwrap_or("the agent's own default").to_string(),
308 match model {
309 Some(_) => or(
310 &sources.model,
311 "the first alias the key may call that is named for the agent",
312 ),
313 None => "no alias is set, and the project may refuse the default".to_string(),
314 },
315 ),
316 (
317 "billing",
318 match billing.billing {
319 crate::billing::Billing::Project => "project (gateway key)",
320 crate::billing::Billing::Subscription => "my Claude subscription",
321 }
322 .to_string(),
323 billing.source.describe(),
324 ),
325 match billing.billing {
326 crate::billing::Billing::Project => (
327 "personal key",
328 "issued, and accepted by the LLM gateway".to_string(),
329 "kept for you only, renewed by `visdom`".to_string(),
330 ),
331 crate::billing::Billing::Subscription => (
332 "key",
333 "a subscription key, accepted by the LLM gateway".to_string(),
334 "kept for you only, renewed by `visdom` a week before it expires".to_string(),
335 ),
336 },
337 ];
338 let width = rows
339 .iter()
340 .map(|(_, value, _)| value.len())
341 .max()
342 .unwrap_or(0);
343 let mut out = format!(
344 "AI Gateway ready for {}: `visdom` starts it through the gateway.\n",
345 agent.label()
346 );
347 for (name, value, source) in rows {
348 out.push_str(&format!(" {name:<13}{value:<width$} ({source})\n"));
349 }
350 out.push_str(&gateway_settings_hint(user_config));
351 out.push_str(
352 "\n To send an agent you start without `visdom` through the gateway as well: \
353 source <(visdom env)\n",
354 );
355 out
356}
357
358pub fn launch_error_message(
360 program: &str,
361 error: &std::io::Error,
362 agent: Agent,
363 user_config: &Path,
364) -> String {
365 format!(
366 "visdom: cannot start {program}: {error} (set agents.{} in {} to use another executable)",
367 agent_config_key(agent),
368 user_config.display()
369 )
370}
371
372pub fn exec_agent(mut cmd: Command, agent: Agent, user_config: &Path) -> ! {
376 let program = cmd.get_program().to_string_lossy().into_owned();
377 let error = replace_process(&mut cmd);
378 eprintln!(
379 "{}",
380 launch_error_message(&program, &error, agent, user_config)
381 );
382 std::process::exit(127)
383}
384
385pub fn run_agent_then_remove(
396 mut cmd: Command,
397 private_file: std::path::PathBuf,
398 agent: Agent,
399 user_config: &Path,
400) -> ! {
401 if let Some(dir) = private_file.parent() {
402 remove_stale_private_files(dir);
403 }
404 let program = cmd.get_program().to_string_lossy().into_owned();
405 signals::wait_them_out();
406 let status = cmd.spawn().and_then(|mut child| {
407 signals::pass_on_to(child.id());
408 child.wait()
409 });
410 let _ = std::fs::remove_file(&private_file);
411 match status {
412 Ok(status) => std::process::exit(exit_code(status)),
413 Err(error) => {
414 eprintln!(
415 "{}",
416 launch_error_message(&program, &error, agent, user_config)
417 );
418 std::process::exit(127)
419 }
420 }
421}
422
423fn exit_code(status: std::process::ExitStatus) -> i32 {
425 #[cfg(unix)]
426 {
427 use std::os::unix::process::ExitStatusExt;
428 if let Some(signal) = status.signal() {
429 return 128 + signal;
430 }
431 }
432 status.code().unwrap_or(1)
433}
434
435pub fn remove_stale_private_files(dir: &Path) {
438 let Ok(entries) = std::fs::read_dir(dir) else {
439 return;
440 };
441 for entry in entries.flatten() {
442 let name = entry.file_name().to_string_lossy().into_owned();
443 let pid = name
444 .strip_prefix(CLAUDE_SETTINGS_PREFIX)
445 .and_then(|rest| rest.split_once('-'))
446 .and_then(|(pid, _)| pid.parse::<u32>().ok());
447 if pid.is_some_and(|pid| !signals::is_running(pid)) {
448 let _ = std::fs::remove_file(entry.path());
449 }
450 }
451}
452
453#[cfg(unix)]
454mod signals {
455 use std::sync::atomic::{AtomicI32, Ordering};
456
457 static CHILD: AtomicI32 = AtomicI32::new(0);
458 static PENDING: AtomicI32 = AtomicI32::new(0);
461
462 extern "C" fn on_signal(signal: libc::c_int) {
463 if signal == libc::SIGTERM || signal == libc::SIGHUP {
464 let child = CHILD.load(Ordering::SeqCst);
465 if child > 0 {
466 unsafe {
468 libc::kill(child, signal);
469 }
470 } else {
471 PENDING.store(signal, Ordering::SeqCst);
472 }
473 }
474 }
475
476 pub fn wait_them_out() {
479 for signal in [libc::SIGINT, libc::SIGQUIT, libc::SIGTERM, libc::SIGHUP] {
480 unsafe {
483 let mut action: libc::sigaction = std::mem::zeroed();
484 action.sa_sigaction = on_signal as extern "C" fn(libc::c_int) as usize;
485 action.sa_flags = libc::SA_RESTART;
486 libc::sigemptyset(&mut action.sa_mask);
487 libc::sigaction(signal, &action, std::ptr::null_mut());
488 }
489 }
490 }
491
492 pub fn pass_on_to(child: u32) {
493 let Ok(child) = i32::try_from(child) else {
494 return;
495 };
496 CHILD.store(child, Ordering::SeqCst);
497 let pending = PENDING.swap(0, Ordering::SeqCst);
499 if pending != 0 {
500 unsafe {
502 libc::kill(child, pending);
503 }
504 }
505 }
506
507 pub fn is_running(pid: u32) -> bool {
509 let Ok(pid) = i32::try_from(pid) else {
510 return false;
511 };
512 let alive = unsafe { libc::kill(pid, 0) } == 0;
514 alive || std::io::Error::last_os_error().raw_os_error() != Some(libc::ESRCH)
515 }
516}
517
518#[cfg(not(unix))]
519mod signals {
520 pub fn wait_them_out() {}
521 pub fn pass_on_to(_child: u32) {}
522 pub fn is_running(_pid: u32) -> bool {
525 true
526 }
527}
528
529#[cfg(unix)]
530fn replace_process(cmd: &mut Command) -> std::io::Error {
531 use std::os::unix::process::CommandExt;
532 cmd.exec()
533}
534
535#[cfg(not(unix))]
537fn replace_process(cmd: &mut Command) -> std::io::Error {
538 match cmd.status() {
539 Ok(status) => std::process::exit(status.code().unwrap_or(1)),
540 Err(e) => e,
541 }
542}
543
544#[cfg(test)]
545mod tests {
546 use super::*;
547
548 #[test]
549 fn launch_error_names_the_program_and_the_config_key() {
550 let error = std::io::Error::new(std::io::ErrorKind::NotFound, "No such file");
551 let message = launch_error_message(
552 "claude",
553 &error,
554 Agent::ClaudeCode,
555 Path::new("/home/u/.config/visdom/config.toml"),
556 );
557 assert!(
558 message.contains("cannot start claude: No such file"),
559 "{message}"
560 );
561 assert!(message.contains("agents.claude_code"), "{message}");
562 assert!(
563 message.contains("/home/u/.config/visdom/config.toml"),
564 "{message}"
565 );
566 let message = launch_error_message("codex", &error, Agent::Codex, Path::new("/c"));
567 assert!(message.contains("agents.codex"), "{message}");
568 }
569
570 #[test]
571 fn the_key_helper_is_one_safe_shell_command() {
572 assert_eq!(shell_quote("plain"), "'plain'");
573 assert_eq!(shell_quote("it's"), r"'it'\''s'");
574 assert_eq!(
575 key_helper_command(
576 Path::new("/opt/my tools/visdom"),
577 "https://gw.example.com",
578 "p-1; rm -rf ~",
579 Billing::Project
580 ),
581 "'/opt/my tools/visdom' gateway-key --console 'https://gw.example.com' --project \
582 'p-1; rm -rf ~'"
583 );
584 assert_eq!(
585 key_helper_command(Path::new("/v"), "https://gw", "p-1", Billing::Subscription),
586 "'/v' gateway-key --console 'https://gw' --project 'p-1' --billing subscription"
587 );
588 }
589
590 #[cfg(unix)]
591 #[test]
592 fn settings_files_of_a_visdom_that_is_gone_are_removed() {
593 let tmp = tempfile::tempdir().unwrap();
594 let dir = tmp.path();
595 let gone = dir.join("claude-settings-4194304999-abc.json");
597 let mine = dir.join(format!("claude-settings-{}-abc.json", std::process::id()));
598 let other = dir.join("notes-1.json");
599 for file in [&gone, &mine, &other] {
600 std::fs::write(file, "{}").unwrap();
601 }
602 remove_stale_private_files(dir);
603 assert!(!gone.exists());
604 assert!(mine.exists(), "this process runs");
605 assert!(other.exists(), "not a settings file");
606 remove_stale_private_files(&dir.join("missing"));
607 }
608
609 #[cfg(unix)]
612 #[test]
613 fn a_termination_before_the_agent_runs_is_passed_on_to_it() {
614 signals::wait_them_out();
615 unsafe {
617 libc::raise(libc::SIGTERM);
618 }
619 let mut agent = Command::new("sleep").arg("30").spawn().unwrap();
620 signals::pass_on_to(agent.id());
621 let status = agent.wait().unwrap();
622 assert_eq!(exit_code(status), 128 + 15, "{status:?}");
623 }
624
625 #[cfg(unix)]
626 #[test]
627 fn a_shell_reports_a_signalled_agent_as_128_plus_the_signal() {
628 let status = Command::new("sh")
629 .arg("-c")
630 .arg("kill -TERM $$")
631 .status()
632 .unwrap();
633 assert_eq!(exit_code(status), 128 + 15);
634 let status = Command::new("sh").arg("-c").arg("exit 3").status().unwrap();
635 assert_eq!(exit_code(status), 3);
636 }
637
638 #[cfg(unix)]
640 #[test]
641 fn a_shell_reads_the_quoted_values_back() {
642 let tricky = ["it's", "a b", "$HOME `id` \"x\"", "p-1; echo no"];
643 for value in tricky {
644 let output = Command::new("sh")
645 .arg("-c")
646 .arg(format!("printf %s {}", shell_quote(value)))
647 .output()
648 .unwrap();
649 assert_eq!(String::from_utf8_lossy(&output.stdout), value);
650 }
651 }
652}