Skip to main content

tracevault_cli/commands/
proxy.rs

1//! `tracevault proxy info` — print the Visdom LLM proxy configuration
2//! a user needs to point their AI tool (Claude Code, GSD2, Cursor, etc.) at
3//! the proxy.
4//!
5//! Read-only and purely local: never calls the network. Output is intended
6//! to be copy-pasted directly into a shell or tool config.
7
8use crate::credentials::{Credential, Credentials};
9use crate::program::{ENV, TOP};
10
11const ANSI_BOLD: &str = "\x1b[1m";
12const ANSI_DIM: &str = "\x1b[2m";
13const ANSI_RESET: &str = "\x1b[0m";
14
15/// Print the proxy configuration. Returns process exit code: 0 on success,
16/// 1 when no credentials are available (user has not logged in).
17pub fn run_proxy_info() -> i32 {
18    let creds = match Credentials::load() {
19        Some(c) => c,
20        None => {
21            eprintln!(
22                "Not logged in. Run `{TOP} login --server-url <url>` first \
23                 to obtain a Visdom session token, then try again."
24            );
25            eprintln!(
26                "Credentials file expected at: {}",
27                Credentials::path_for_display()
28            );
29            return 1;
30        }
31    };
32
33    let creds_path = Credentials::path_for_display();
34
35    // Resolved BEFORE any instructions are printed: the setup script below
36    // cannot be followed without a credential, so bailing here avoids
37    // sandwiching the error between steps the user is being told to perform.
38    let credential = match creds.credential() {
39        Some(c) => c,
40        None => {
41            eprintln!(
42                "The credentials file at {} holds no usable credential (no API key and no \
43                 Keycloak session).",
44                creds_path
45            );
46            eprintln!(
47                "Run `{TOP} login --server-url <url>`, or set {ENV}_API_KEY to a \
48                 Visdom API key (tvk_...)."
49            );
50            return 1;
51        }
52    };
53
54    let server_url = creds.server_url.trim_end_matches('/');
55    let proxy_url = format!("{server_url}/proxy/anthropic");
56
57    println!("{ANSI_BOLD}Visdom LLM Proxy{ANSI_RESET}");
58    println!();
59    println!("  Server:           {server_url}");
60    println!("  Proxy base URL:   {ANSI_BOLD}{proxy_url}{ANSI_RESET}");
61    println!("  Credentials file: {}", creds_path);
62    println!();
63    println!("{ANSI_BOLD}Setup{ANSI_RESET}");
64    println!();
65    println!("  1. Configure your Anthropic API key once at:");
66    println!("       {server_url}/me/proxy");
67    println!();
68    println!("  2. Set these environment variables for your AI tool:");
69    println!();
70    println!("       {ANSI_BOLD}export ANTHROPIC_BASE_URL=\"{proxy_url}\"{ANSI_RESET}");
71    println!(
72        "       {ANSI_BOLD}export ANTHROPIC_API_KEY=\"<your Visdom session token>\"{ANSI_RESET}"
73    );
74    println!();
75    // `ANTHROPIC_API_KEY` is static tool configuration, so it needs a static
76    // credential. Both arms are spelled out rather than using a catch-all, so a
77    // future `Credential` variant cannot silently inherit the API-key wording.
78    match credential {
79        Credential::ApiKey(_) => {
80            println!(
81                "     {ANSI_DIM}Your Visdom token lives in {} as the \"token\" field.{ANSI_RESET}",
82                creds_path
83            );
84        }
85        // A Keycloak access token is refreshed every few minutes and would
86        // silently stop working if pasted into a static env var.
87        Credential::Keycloak(_) => {
88            println!(
89                "     {ANSI_DIM}This machine is signed in with a Keycloak session, whose access \
90                 token expires every few minutes — it cannot be pasted here as a static value. \
91                 Use a Visdom API key (tvk_...) for the proxy instead.{ANSI_RESET}"
92            );
93        }
94    }
95    println!();
96    println!("  3. Run your AI tool as usual. Requests go through Visdom and are");
97    println!("     forwarded to api.anthropic.com using the Anthropic key you stored");
98    println!("     in step 1.");
99
100    0
101}
102
103#[cfg(test)]
104mod tests {
105    use super::run_proxy_info;
106    use std::fs;
107
108    /// Redirect `XDG_CONFIG_HOME` at a tempdir containing `body` as the
109    /// credentials file (or no file at all when `body` is `None`), run
110    /// `run_proxy_info`, and return its exit code.
111    fn exit_code_for(body: Option<&str>) -> i32 {
112        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
113        let dir = tempfile::tempdir().unwrap();
114        let mut _guard = crate::test_helpers::EnvVarGuard::new();
115        _guard.set("XDG_CONFIG_HOME", dir.path());
116
117        if let Some(body) = body {
118            let creds_dir = dir.path().join("visdom");
119            fs::create_dir_all(&creds_dir).unwrap();
120            fs::write(creds_dir.join("credentials.json"), body).unwrap();
121        }
122        run_proxy_info()
123    }
124
125    /// A credentials file with neither a `token` nor an `auth` object holds
126    /// nothing the user can paste. Reporting success and pointing at a "token"
127    /// field that isn't in the file sends them looking for it.
128    #[test]
129    fn a_file_with_no_usable_credential_exits_non_zero() {
130        let code = exit_code_for(Some(
131            r#"{"server_url":"https://example.com","email":"a@b.com"}"#,
132        ));
133        assert_eq!(
134            code, 1,
135            "a file with no usable credential must not report success"
136        );
137    }
138
139    #[test]
140    fn an_api_key_file_still_succeeds() {
141        let code = exit_code_for(Some(
142            r#"{"server_url":"https://example.com","token":"tvk_abc","email":"a@b.com"}"#,
143        ));
144        assert_eq!(code, 0);
145    }
146
147    #[test]
148    fn a_keycloak_file_still_succeeds() {
149        let code = exit_code_for(Some(
150            r#"{"server_url":"https://example.com","email":"a@b.com","auth":{"issuer":"i","client_id":"c","refresh_token":"rt","access_token":"at","access_expires_at":1}}"#,
151        ));
152        assert_eq!(code, 0);
153    }
154
155    /// The pre-existing contract: no credentials file at all is exit 1.
156    #[test]
157    fn a_missing_credentials_file_exits_non_zero() {
158        assert_eq!(exit_code_for(None), 1);
159    }
160}