Skip to main content

visdom_cli/agents/
via_gateway.rs

1//! Starting an agent so that its LLM traffic goes through the AI Gateway.
2//!
3//! Everything is given to the launched process alone — environment variables
4//! and launch options — never written into the agent's configuration files:
5//! an agent started without `visdom` is exactly as it was.
6
7use std::process::Command;
8
9use tracevault_cli::agent::Agent;
10
11use crate::mode::{TracingMode, GATEWAY_SESSION_ENV, MODE_ENV};
12
13/// The environment variable Codex reads the gateway key from.
14pub const CODEX_KEY_ENV: &str = "VISDOM_GATEWAY_API_KEY";
15
16/// The name of the model provider `visdom` defines for Codex.
17const CODEX_PROVIDER: &str = "visdom-gateway";
18
19/// How long Claude Code keeps a key before asking the helper again. The
20/// helper answers from visdom's key store, so asking often is cheap, and a
21/// key replaced by another session is picked up within this time.
22const CLAUDE_KEY_TTL_MS: &str = "300000";
23
24/// What an agent needs to run through the gateway.
25#[derive(Clone, Debug, PartialEq, Eq)]
26pub struct GatewayLaunch {
27    /// The LLM gateway's address, without `/v1`.
28    pub llm_url: String,
29    /// The developer's personal key.
30    pub key: String,
31    /// A shell command that prints the current key (`visdom gateway-key …`).
32    pub key_helper: String,
33    /// The model alias to ask for; `None` leaves the agent's own choice.
34    pub model: Option<String>,
35    /// The repository's id in AI Tracing, for attribution.
36    pub repo_id: Option<String>,
37    /// The id the session gets, so the gateway's records join one session.
38    pub session_id: String,
39}
40
41/// Whether `args` already carry one of `options` (as `--name value` or
42/// `--name=value`).
43fn has_option(args: &[String], options: &[&str]) -> bool {
44    args.iter().any(|arg| {
45        options.iter().any(|o| {
46            arg == o
47                || arg
48                    .strip_prefix(o)
49                    .is_some_and(|rest| rest.starts_with('='))
50        })
51    })
52}
53
54/// The value `args` give one of `options` (`--name value` or `--name=value`).
55fn option_value<'a>(args: &'a [String], options: &[&str]) -> Option<&'a str> {
56    args.iter().enumerate().find_map(|(i, arg)| {
57        options.iter().find_map(|o| {
58            if arg == o {
59                args.get(i + 1).map(String::as_str)
60            } else {
61                arg.strip_prefix(o).and_then(|rest| rest.strip_prefix('='))
62            }
63        })
64    })
65}
66
67/// `value` as one header value: no line breaks, which would start another
68/// header.
69fn header_value(value: &str) -> String {
70    value.chars().filter(|c| !c.is_control()).collect()
71}
72
73/// Claude Code's switches to another provider's API. Each takes precedence
74/// over `ANTHROPIC_BASE_URL`, so one left set would send the session past the
75/// gateway while the hooks record nothing. (`CLAUDE_CODE_USE_GATEWAY` is
76/// Claude Code's own gateway sign-in, which is not this key helper's.) The
77/// list is Claude Code's: a switch it gains has to be added here.
78const CLAUDE_OTHER_PROVIDERS: [&str; 7] = [
79    "CLAUDE_CODE_USE_BEDROCK",
80    "CLAUDE_CODE_USE_VERTEX",
81    "CLAUDE_CODE_USE_FOUNDRY",
82    "CLAUDE_CODE_USE_MANTLE",
83    "CLAUDE_CODE_USE_ANTHROPIC_AWS",
84    "CLAUDE_CODE_USE_ANTHROPIC_GOOGLE_CLOUD",
85    "CLAUDE_CODE_USE_GATEWAY",
86];
87
88/// The session id the caller's own options give Claude Code, when they name
89/// one: `--session-id`, or `--resume <id>`, which carries on under the same
90/// id unless `--fork-session` asks for a new one. `None` when Claude Code
91/// decides (a picker, `--continue`, a fork).
92fn callers_session(args: &[String]) -> Option<&str> {
93    let is_id = |value: &&str| uuid::Uuid::parse_str(value).is_ok();
94    option_value(args, &["--session-id"])
95        .filter(is_id)
96        .or_else(|| {
97            option_value(args, &["--resume", "-r"])
98                .filter(is_id)
99                .filter(|_| !has_option(args, &["--fork-session"]))
100        })
101}
102
103/// The values `args` give `--settings`, each a file or a JSON text, and
104/// `args` without them. Options after `--` are the prompt's.
105fn split_settings(args: &[String]) -> (Vec<String>, Vec<String>) {
106    let (mut given, mut rest) = (Vec::new(), Vec::new());
107    let mut i = 0;
108    while i < args.len() {
109        let arg = &args[i];
110        if arg == "--" {
111            rest.extend_from_slice(&args[i..]);
112            break;
113        }
114        if arg == "--settings" {
115            given.extend(args.get(i + 1).cloned());
116            i += 2;
117        } else if let Some(value) = arg.strip_prefix("--settings=") {
118            given.push(value.to_string());
119            i += 1;
120        } else {
121            rest.push(arg.clone());
122            i += 1;
123        }
124    }
125    (given, rest)
126}
127
128/// The settings object a `--settings` value stands for.
129fn read_settings(value: &str) -> Result<serde_json::Map<String, serde_json::Value>, String> {
130    let failed = |why: String| format!("the Claude Code settings given with --settings ({why})");
131    let text = if value.trim_start().starts_with('{') {
132        value.to_string()
133    } else {
134        std::fs::read_to_string(value)
135            .map_err(|e| failed(format!("`{value}` cannot be read: {e}")))?
136    };
137    match serde_json::from_str(&text) {
138        Ok(serde_json::Value::Object(map)) => Ok(map),
139        Ok(_) => Err(failed(format!("`{value}` is not a JSON object"))),
140        Err(e) => Err(failed(format!("`{value}` is not JSON: {e}"))),
141    }
142}
143
144/// Claude Code through the gateway. `env` reads the current environment.
145///
146/// Where the session goes is given as settings on the command line
147/// (`--settings`), not only as environment: Claude Code applies the `env` of
148/// its settings files over the environment it was started in, so a base URL
149/// or a provider switch left in the developer's `settings.json` would
150/// otherwise send the session past the gateway — or the gateway key to
151/// another address — while the hooks record nothing. Settings given on the
152/// command line come after the user's and the project's. (Settings an
153/// organisation manages come after everything and are not `visdom`'s to
154/// overrule.)
155///
156/// - The key comes from `apiKeyHelper`, so a key renewed during a long
157///   session is picked up. Settings the caller passes with `--settings` are
158///   kept, merged under these.
159/// - The session id is fixed up front and sent with every request. A caller
160///   who names the session themselves gets theirs sent; one who leaves it to
161///   Claude Code (`--continue`, a picker) gets none, and the gateway's
162///   records of that session carry no session id.
163///
164/// `Err` when the caller's own `--settings` cannot be read: they could not be
165/// merged, and passing them on unread could undo the routing.
166pub fn claude_command(
167    program: &str,
168    args: &[String],
169    gateway: &GatewayLaunch,
170    env: &dyn Fn(&str) -> Option<String>,
171) -> Result<Command, String> {
172    let (given, args) = split_settings(args);
173    let mut settings = serde_json::Map::new();
174    for value in &given {
175        // A later one wins key by key, as far as this can tell.
176        settings.extend(read_settings(value)?);
177    }
178    let mut settings_env = match settings.remove("env") {
179        Some(serde_json::Value::Object(map)) => map,
180        _ => serde_json::Map::new(),
181    };
182
183    let own_session = has_option(
184        &args,
185        &[
186            "--session-id",
187            "--resume",
188            "-r",
189            "--continue",
190            "-c",
191            "--from-pr",
192            "--teleport",
193        ],
194    );
195    let session = match own_session {
196        true => callers_session(&args),
197        false => Some(gateway.session_id.as_str()),
198    };
199    // The developer's own headers stay, from the environment and from the
200    // settings they passed.
201    let callers_headers = settings_env
202        .get("ANTHROPIC_CUSTOM_HEADERS")
203        .and_then(|v| v.as_str())
204        .map(String::from);
205    let mut headers: Vec<String> = [env("ANTHROPIC_CUSTOM_HEADERS"), callers_headers]
206        .into_iter()
207        .flatten()
208        .filter(|h| !h.trim().is_empty())
209        .collect();
210    headers.push(format!(
211        "x-tracevault-agent: {}",
212        Agent::ClaudeCode.tool_name()
213    ));
214    if let Some(repo) = &gateway.repo_id {
215        headers.push(format!("x-tracevault-repo: {}", header_value(repo)));
216    }
217    if let Some(session) = session {
218        headers.push(format!("x-tracevault-session: {}", header_value(session)));
219    }
220    let headers = headers.join("\n");
221
222    // What decides where the session goes: in the environment and, over
223    // whatever a settings file says, in the settings.
224    let mut routing: Vec<(&str, String)> = vec![
225        // The hooks read this to record nothing: a settings file must not
226        // switch them back on beside the gateway.
227        (
228            GATEWAY_SESSION_ENV,
229            Agent::ClaudeCode.tool_name().to_string(),
230        ),
231        (MODE_ENV, TracingMode::Gateway.name().to_string()),
232        ("ANTHROPIC_BASE_URL", gateway.llm_url.clone()),
233        ("ANTHROPIC_CUSTOM_HEADERS", headers),
234        (
235            "CLAUDE_CODE_API_KEY_HELPER_TTL_MS",
236            CLAUDE_KEY_TTL_MS.into(),
237        ),
238    ];
239    // Claude Code reads "0" as off; a variable cannot be unset from settings.
240    routing.extend(CLAUDE_OTHER_PROVIDERS.map(|switch| (switch, "0".to_string())));
241
242    let mut cmd = Command::new(program);
243    for (name, value) in &routing {
244        cmd.env(name, value);
245        settings_env.insert(name.to_string(), value.clone().into());
246    }
247    for switch in CLAUDE_OTHER_PROVIDERS {
248        cmd.env_remove(switch);
249    }
250    // A key of the developer's own would be sent in place of the gateway's
251    // (and to the gateway). Removed from the environment, and set to nothing
252    // in the settings, which is how one in a settings file is cleared: Claude
253    // Code then asks the key helper.
254    for key in ["ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN"] {
255        cmd.env_remove(key);
256        settings_env.insert(key.to_string(), "".into());
257    }
258    if let Some(model) = &gateway.model {
259        // The project's allow-list has aliases, not Claude Code's defaults:
260        // both the main and the small model must name one. A model the
261        // developer already chose stays.
262        for name in ["ANTHROPIC_MODEL", "ANTHROPIC_DEFAULT_HAIKU_MODEL"] {
263            if env(name).is_none() {
264                cmd.env(name, model);
265            }
266        }
267    }
268    settings.insert("env".to_string(), settings_env.into());
269    settings.insert(
270        "apiKeyHelper".to_string(),
271        gateway.key_helper.clone().into(),
272    );
273    cmd.arg("--settings")
274        .arg(serde_json::Value::Object(settings).to_string());
275    if !own_session {
276        cmd.arg("--session-id").arg(&gateway.session_id);
277    }
278    cmd.args(args);
279    Ok(cmd)
280}
281
282/// A TOML basic string.
283fn toml_string(value: &str) -> String {
284    toml::Value::String(value.to_string()).to_string()
285}
286
287/// What the caller's own options would take away from the gateway, if
288/// anything. Codex applies configuration overrides in the order given, and
289/// the caller's come last: one that names another model provider, or redefines
290/// `visdom`'s, would send the session past the gateway (or the gateway key
291/// elsewhere) while the hooks record nothing. Options after `--` are the
292/// prompt's.
293fn codex_conflict(args: &[String]) -> Option<String> {
294    let options = args.iter().take_while(|arg| *arg != "--");
295    let mut overrides: Vec<&str> = Vec::new();
296    let mut awaiting = false;
297    for arg in options {
298        if std::mem::take(&mut awaiting) {
299            overrides.push(arg);
300        } else if arg == "-c" || arg == "--config" {
301            awaiting = true;
302        } else if let Some(value) = arg.strip_prefix("--config=") {
303            overrides.push(value);
304        } else if let Some(value) = arg.strip_prefix("-c").filter(|_| !arg.starts_with("--")) {
305            overrides.push(value.strip_prefix('=').unwrap_or(value));
306        } else if arg == "--oss"
307            || arg == "--local-provider"
308            || arg.starts_with("--local-provider=")
309        {
310            return Some(arg.clone());
311        }
312    }
313    overrides
314        .into_iter()
315        .find(|setting| {
316            let key: String = setting
317                .split('=')
318                .next()
319                .unwrap_or_default()
320                .chars()
321                .filter(|c| !c.is_whitespace() && *c != '"' && *c != '\'')
322                .collect();
323            key == "model_provider"
324                || key == "model_providers"
325                || key == format!("model_providers.{CODEX_PROVIDER}")
326                || key.starts_with(&format!("model_providers.{CODEX_PROVIDER}."))
327        })
328        .map(|setting| format!("-c {setting}"))
329}
330
331/// Codex through the gateway: a model provider defined for this run with
332/// `-c`, its key in the environment. Codex names the session itself
333/// (`thread-id`), which the gateway takes as the session. The key is fixed
334/// for the life of the process.
335///
336/// `Err` when the caller's own options choose or redefine the model provider:
337/// they come after these and would win.
338pub fn codex_command(
339    program: &str,
340    args: &[String],
341    gateway: &GatewayLaunch,
342) -> Result<Command, String> {
343    if let Some(option) = codex_conflict(args) {
344        return Err(format!(
345            "`{option}` chooses Codex's model provider, which through the AI Gateway is the \
346             gateway: leave it out, or use `--mode hooks`"
347        ));
348    }
349    let mut cmd = Command::new(program);
350    cmd.env(GATEWAY_SESSION_ENV, Agent::Codex.tool_name());
351    cmd.env(MODE_ENV, TracingMode::Gateway.name());
352    cmd.env(CODEX_KEY_ENV, &gateway.key);
353    let provider = format!("model_providers.{CODEX_PROVIDER}");
354    let mut headers = vec![format!(
355        "\"x-tracevault-agent\" = {}",
356        toml_string(Agent::Codex.tool_name())
357    )];
358    if let Some(repo) = &gateway.repo_id {
359        headers.push(format!(
360            "\"x-tracevault-repo\" = {}",
361            toml_string(&header_value(repo))
362        ));
363    }
364    let settings = [
365        format!("model_provider={}", toml_string(CODEX_PROVIDER)),
366        format!("{provider}.name={}", toml_string("Visdom AI Gateway")),
367        format!(
368            "{provider}.base_url={}",
369            toml_string(&format!("{}/v1", gateway.llm_url.trim_end_matches('/')))
370        ),
371        format!("{provider}.env_key={}", toml_string(CODEX_KEY_ENV)),
372        format!("{provider}.wire_api={}", toml_string("responses")),
373        format!("{provider}.http_headers={{ {} }}", headers.join(", ")),
374    ];
375    for setting in settings {
376        cmd.arg("-c").arg(setting);
377    }
378    if let Some(model) = &gateway.model {
379        if !has_option(args, &["-m", "--model"]) {
380            cmd.arg("--model").arg(model);
381        }
382    }
383    cmd.args(args);
384    Ok(cmd)
385}
386
387/// `text` as one word of a POSIX shell command.
388pub fn shell_quote(text: &str) -> String {
389    format!("'{}'", text.replace('\'', "'\\''"))
390}
391
392/// The lines every such script starts and ends with: the key is not in the
393/// script, which only says how to get it, so the script can be kept (a shell
394/// profile, an `.envrc`) and shown around.
395fn script(agent: Agent, project: &str, lines: Vec<String>) -> String {
396    let mut out = vec![
397        format!(
398            "# {} through the Visdom AI Gateway (project `{project}`), started without `visdom`.",
399            agent.label()
400        ),
401        "# Use:  source <(visdom env)    — again when the key expires (24 hours at most).".into(),
402        "# Settings your agent's own configuration files make still win over these;".into(),
403        "# `visdom` itself is the way that cannot be overruled.".into(),
404    ];
405    out.extend(lines);
406    // This agent's hooks record nothing when it is started from this shell:
407    // the gateway records it. Any other agent's still do.
408    out.push(format!(
409        "export {GATEWAY_SESSION_ENV}={}",
410        agent.tool_name()
411    ));
412    out.join("\n") + "\n"
413}
414
415/// Shell commands that send a Claude Code started from that shell, without
416/// `visdom`, through the gateway.
417pub fn claude_env_script(gateway: &GatewayLaunch, project: &str) -> String {
418    let mut headers = vec![format!(
419        "x-tracevault-agent: {}",
420        Agent::ClaudeCode.tool_name()
421    )];
422    if let Some(repo) = &gateway.repo_id {
423        headers.push(format!("x-tracevault-repo: {}", header_value(repo)));
424    }
425    let mut lines = vec![
426        format!(
427            "export ANTHROPIC_BASE_URL={}",
428            shell_quote(&gateway.llm_url)
429        ),
430        format!("export ANTHROPIC_AUTH_TOKEN=\"$({})\"", gateway.key_helper),
431        format!(
432            "export ANTHROPIC_CUSTOM_HEADERS={}",
433            shell_quote(&headers.join("\n"))
434        ),
435    ];
436    if let Some(model) = &gateway.model {
437        for name in ["ANTHROPIC_MODEL", "ANTHROPIC_DEFAULT_HAIKU_MODEL"] {
438            lines.push(format!("export {name}={}", shell_quote(model)));
439        }
440    }
441    lines.push(format!(
442        "unset ANTHROPIC_API_KEY {}",
443        CLAUDE_OTHER_PROVIDERS.join(" ")
444    ));
445    script(Agent::ClaudeCode, project, lines)
446}
447
448/// The same for Codex, whose provider is given as options, not variables:
449/// the script defines a `codex` function that adds them.
450pub fn codex_env_script(
451    program: &str,
452    gateway: &GatewayLaunch,
453    project: &str,
454) -> Result<String, String> {
455    let cmd = codex_command(program, &[], gateway)?;
456    let options: Vec<String> = cmd
457        .get_args()
458        .map(|arg| shell_quote(&arg.to_string_lossy()))
459        .collect();
460    let lines = vec![
461        format!("export {CODEX_KEY_ENV}=\"$({})\"", gateway.key_helper),
462        format!(
463            "codex() {{ command {} {} \"$@\"; }}",
464            shell_quote(program),
465            options.join(" ")
466        ),
467    ];
468    Ok(script(Agent::Codex, project, lines))
469}
470
471#[cfg(test)]
472mod tests {
473    use super::*;
474    use std::collections::HashMap;
475    use std::ffi::OsStr;
476
477    fn gateway() -> GatewayLaunch {
478        GatewayLaunch {
479            llm_url: "https://llm.example.com".to_string(),
480            key: "sk-abc".to_string(),
481            key_helper: "'/usr/bin/visdom' gateway-key --console 'https://gw' --project 'p-1'"
482                .to_string(),
483            model: Some("claude-sonnet".to_string()),
484            repo_id: Some("11111111-2222-3333-4444-555555555555".to_string()),
485            session_id: "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee".to_string(),
486        }
487    }
488
489    fn args_of(cmd: &Command) -> Vec<String> {
490        cmd.get_args()
491            .map(|a| a.to_string_lossy().into_owned())
492            .collect()
493    }
494
495    /// The variables a command sets (`Some`) or removes (`None`).
496    fn envs_of(cmd: &Command) -> HashMap<String, Option<String>> {
497        cmd.get_envs()
498            .map(|(k, v): (&OsStr, Option<&OsStr>)| {
499                (
500                    k.to_string_lossy().into_owned(),
501                    v.map(|v| v.to_string_lossy().into_owned()),
502                )
503            })
504            .collect()
505    }
506
507    fn strings(args: &[&str]) -> Vec<String> {
508        args.iter().map(|a| a.to_string()).collect()
509    }
510
511    fn no_env(_: &str) -> Option<String> {
512        None
513    }
514
515    fn claude(
516        args: &[String],
517        gateway: &GatewayLaunch,
518        env: &dyn Fn(&str) -> Option<String>,
519    ) -> Command {
520        claude_command("claude", args, gateway, env).unwrap()
521    }
522
523    fn codex(args: &[String], gateway: &GatewayLaunch) -> Command {
524        codex_command("codex", args, gateway).unwrap()
525    }
526
527    /// The settings a Claude command carries: always the first option.
528    fn settings_of(cmd: &Command) -> serde_json::Value {
529        let args = args_of(cmd);
530        assert_eq!(args[0], "--settings");
531        assert_eq!(args.iter().filter(|a| *a == "--settings").count(), 1);
532        serde_json::from_str(&args[1]).unwrap()
533    }
534
535    #[test]
536    fn claude_gets_the_gateway_the_key_helper_and_a_session() {
537        let cmd = claude(&strings(&["--verbose"]), &gateway(), &no_env);
538        let env = envs_of(&cmd);
539        assert_eq!(
540            env["VISDOM_GATEWAY_SESSION"].as_deref(),
541            Some("claude-code")
542        );
543        assert_eq!(env["VISDOM_TRACING_MODE"].as_deref(), Some("gateway"));
544        assert_eq!(
545            env["ANTHROPIC_BASE_URL"].as_deref(),
546            Some("https://llm.example.com")
547        );
548        assert_eq!(env["ANTHROPIC_API_KEY"], None, "removed");
549        assert_eq!(
550            env["ANTHROPIC_AUTH_TOKEN"], None,
551            "removed: the helper gives the key"
552        );
553        assert_eq!(env["ANTHROPIC_MODEL"].as_deref(), Some("claude-sonnet"));
554        assert_eq!(
555            env["ANTHROPIC_DEFAULT_HAIKU_MODEL"].as_deref(),
556            Some("claude-sonnet")
557        );
558        assert_eq!(
559            env["ANTHROPIC_CUSTOM_HEADERS"].as_deref(),
560            Some(
561                "x-tracevault-agent: claude-code\n\
562                 x-tracevault-repo: 11111111-2222-3333-4444-555555555555\n\
563                 x-tracevault-session: aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"
564            )
565        );
566        let args = args_of(&cmd);
567        let settings = settings_of(&cmd);
568        assert_eq!(settings["apiKeyHelper"], gateway().key_helper);
569        // Where the session goes is in the settings too, over whatever a
570        // settings file of the developer's says.
571        assert_eq!(
572            settings["env"],
573            serde_json::json!({
574                "VISDOM_GATEWAY_SESSION": "claude-code",
575                "VISDOM_TRACING_MODE": "gateway",
576                "ANTHROPIC_API_KEY": "",
577                "ANTHROPIC_AUTH_TOKEN": "",
578                "ANTHROPIC_BASE_URL": "https://llm.example.com",
579                "ANTHROPIC_CUSTOM_HEADERS": env["ANTHROPIC_CUSTOM_HEADERS"],
580                "CLAUDE_CODE_API_KEY_HELPER_TTL_MS": "300000",
581                "CLAUDE_CODE_USE_BEDROCK": "0",
582                "CLAUDE_CODE_USE_VERTEX": "0",
583                "CLAUDE_CODE_USE_FOUNDRY": "0",
584                "CLAUDE_CODE_USE_MANTLE": "0",
585                "CLAUDE_CODE_USE_ANTHROPIC_AWS": "0",
586                "CLAUDE_CODE_USE_ANTHROPIC_GOOGLE_CLOUD": "0",
587                "CLAUDE_CODE_USE_GATEWAY": "0",
588            })
589        );
590        assert_eq!(
591            args[2..],
592            [
593                "--session-id",
594                "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
595                "--verbose"
596            ]
597        );
598        // The key itself is in no argument.
599        assert!(!args.iter().any(|a| a.contains("sk-abc")));
600    }
601
602    #[test]
603    fn a_session_claude_code_picks_itself_gets_no_session_id() {
604        for resume in [
605            strings(&["--resume"]),
606            strings(&["--resume", "a title, not an id"]),
607            strings(&["-c"]),
608            strings(&["--session-id=xyz"]),
609            // A fork gets a new id, which only Claude Code knows.
610            strings(&["--resume", OTHER_SESSION, "--fork-session"]),
611        ] {
612            let cmd = claude(&resume, &gateway(), &no_env);
613            let args = args_of(&cmd);
614            assert_eq!(args[2..], resume[..], "{args:?}");
615            let headers = envs_of(&cmd)["ANTHROPIC_CUSTOM_HEADERS"].clone().unwrap();
616            assert!(!headers.contains("x-tracevault-session"), "{headers}");
617            assert!(headers.contains("x-tracevault-repo"), "{headers}");
618        }
619    }
620
621    const OTHER_SESSION: &str = "99999999-8888-7777-6666-555555555555";
622
623    #[test]
624    fn a_session_the_caller_names_is_the_one_sent() {
625        for named in [
626            strings(&["--session-id", OTHER_SESSION]),
627            strings(&[&format!("--session-id={OTHER_SESSION}")]),
628            strings(&["--resume", OTHER_SESSION]),
629            strings(&["-r", OTHER_SESSION, "--verbose"]),
630        ] {
631            let cmd = claude(&named, &gateway(), &no_env);
632            // Nothing of visdom's own is added to what the caller asked for.
633            assert_eq!(args_of(&cmd)[2..], named[..]);
634            let headers = envs_of(&cmd)["ANTHROPIC_CUSTOM_HEADERS"].clone().unwrap();
635            assert!(
636                headers.ends_with(&format!("x-tracevault-session: {OTHER_SESSION}")),
637                "{headers}"
638            );
639            assert!(!headers.contains(&gateway().session_id), "{headers}");
640        }
641    }
642
643    #[test]
644    fn claude_is_not_left_pointed_at_another_provider() {
645        let cmd = claude(&[], &gateway(), &no_env);
646        let env = envs_of(&cmd);
647        let settings = settings_of(&cmd);
648        for switch in [
649            "CLAUDE_CODE_USE_BEDROCK",
650            "CLAUDE_CODE_USE_VERTEX",
651            "CLAUDE_CODE_USE_FOUNDRY",
652            "CLAUDE_CODE_USE_MANTLE",
653            "CLAUDE_CODE_USE_ANTHROPIC_AWS",
654            "CLAUDE_CODE_USE_ANTHROPIC_GOOGLE_CLOUD",
655            "CLAUDE_CODE_USE_GATEWAY",
656        ] {
657            assert_eq!(env[switch], None, "{switch} must be removed");
658            assert_eq!(settings["env"][switch], "0", "{switch} must be off");
659        }
660    }
661
662    #[test]
663    fn the_callers_own_settings_are_merged_under_the_gateways() {
664        let tmp = tempfile::tempdir().unwrap();
665        let file = tmp.path().join("mine.json");
666        std::fs::write(
667            &file,
668            r#"{"permissions":{"allow":["Bash(ls)"]},"apiKeyHelper":"echo mine",
669                "env":{"ANTHROPIC_BASE_URL":"https://elsewhere.example.com",
670                       "CLAUDE_CODE_USE_BEDROCK":"1","ANTHROPIC_API_KEY":"sk-mine",
671                       "ANTHROPIC_AUTH_TOKEN":"tok-mine","VISDOM_TRACING_MODE":"hooks",
672                       "ANTHROPIC_CUSTOM_HEADERS":"x-team: blue","MY_VAR":"kept"}}"#,
673        )
674        .unwrap();
675        let inline = r#"{"model":"opus","env":{"OTHER":"1"}}"#;
676        for own in [
677            strings(&["--verbose", "--settings", file.to_str().unwrap()]),
678            strings(&[&format!("--settings={}", file.display()), "--verbose"]),
679        ] {
680            let cmd = claude(&own, &gateway(), &no_env);
681            let settings = settings_of(&cmd);
682            assert_eq!(settings["permissions"]["allow"][0], "Bash(ls)");
683            assert_eq!(settings["apiKeyHelper"], gateway().key_helper);
684            let env = &settings["env"];
685            assert_eq!(env["MY_VAR"], "kept");
686            assert_eq!(env["ANTHROPIC_BASE_URL"], "https://llm.example.com");
687            assert_eq!(env["CLAUDE_CODE_USE_BEDROCK"], "0");
688            assert_eq!(env["ANTHROPIC_API_KEY"], "");
689            assert_eq!(env["ANTHROPIC_AUTH_TOKEN"], "");
690            assert_eq!(env["VISDOM_TRACING_MODE"], "gateway");
691            let headers = env["ANTHROPIC_CUSTOM_HEADERS"].as_str().unwrap();
692            assert!(
693                headers.starts_with("x-team: blue\nx-tracevault-agent"),
694                "{headers}"
695            );
696            // Theirs is gone from the options; the rest stays.
697            let args = args_of(&cmd);
698            assert_eq!(args[2..4], ["--session-id", gateway().session_id.as_str()]);
699            assert_eq!(args[4..], ["--verbose"]);
700            // The key reaches Claude Code through the helper alone.
701            assert_eq!(envs_of(&cmd)["ANTHROPIC_AUTH_TOKEN"], None);
702        }
703        // JSON given in place, twice: both are kept.
704        let both = strings(&["--settings", inline, "--settings", file.to_str().unwrap()]);
705        let settings = settings_of(&claude(&both, &gateway(), &no_env));
706        assert_eq!(settings["model"], "opus");
707        assert_eq!(settings["permissions"]["allow"][0], "Bash(ls)");
708    }
709
710    #[test]
711    fn settings_that_cannot_be_read_stop_the_gateway_launch() {
712        for (own, said) in [
713            (
714                strings(&["--settings", "/nonexistent/mine.json"]),
715                "cannot be read",
716            ),
717            (strings(&["--settings", "{not json"]), "is not JSON"),
718            (strings(&["--settings=[1]"]), "cannot be read"),
719        ] {
720            let err = claude_command("claude", &own, &gateway(), &no_env).unwrap_err();
721            assert!(err.contains(said), "{err}");
722        }
723        // After `--` it is the prompt, not an option.
724        let prompt = strings(&["--", "--settings", "what does this flag do?"]);
725        let cmd = claude(&prompt, &gateway(), &no_env);
726        assert_eq!(args_of(&cmd)[4..], prompt[..]);
727    }
728
729    #[test]
730    fn claude_keeps_what_the_developer_already_set() {
731        let env = |name: &str| match name {
732            "ANTHROPIC_MODEL" => Some("my-alias".to_string()),
733            "ANTHROPIC_CUSTOM_HEADERS" => Some("x-team: blue".to_string()),
734            _ => None,
735        };
736        let mut launch = gateway();
737        launch.repo_id = None;
738        let cmd = claude(&[], &launch, &env);
739        let set = envs_of(&cmd);
740        assert!(!set.contains_key("ANTHROPIC_MODEL"), "left as it is");
741        assert_eq!(
742            set["ANTHROPIC_DEFAULT_HAIKU_MODEL"].as_deref(),
743            Some("claude-sonnet")
744        );
745        let headers = set["ANTHROPIC_CUSTOM_HEADERS"].clone().unwrap();
746        assert!(
747            headers.starts_with("x-team: blue\nx-tracevault-agent"),
748            "{headers}"
749        );
750        assert!(!headers.contains("x-tracevault-repo"), "{headers}");
751    }
752
753    #[test]
754    fn without_a_model_claude_is_given_none() {
755        let mut launch = gateway();
756        launch.model = None;
757        let set = envs_of(&claude(&[], &launch, &no_env));
758        assert!(!set.contains_key("ANTHROPIC_MODEL"));
759        assert!(!set.contains_key("ANTHROPIC_DEFAULT_HAIKU_MODEL"));
760    }
761
762    #[test]
763    fn a_header_value_cannot_start_another_header() {
764        let mut launch = gateway();
765        launch.repo_id = Some("abc\nx-evil: 1".to_string());
766        let set = envs_of(&claude(&[], &launch, &no_env));
767        let headers = set["ANTHROPIC_CUSTOM_HEADERS"].clone().unwrap();
768        assert_eq!(headers.lines().count(), 3, "{headers}");
769        assert!(
770            headers.contains("x-tracevault-repo: abcx-evil: 1"),
771            "{headers}"
772        );
773    }
774
775    #[test]
776    fn codex_gets_a_provider_for_this_run_and_the_key_in_its_environment() {
777        let mut launch = gateway();
778        launch.model = Some("gpt-general".to_string());
779        let cmd = codex(&strings(&["exec", "hi"]), &launch);
780        let env = envs_of(&cmd);
781        assert_eq!(env["VISDOM_GATEWAY_SESSION"].as_deref(), Some("codex"));
782        assert_eq!(env["VISDOM_TRACING_MODE"].as_deref(), Some("gateway"));
783        assert_eq!(env["VISDOM_GATEWAY_API_KEY"].as_deref(), Some("sk-abc"));
784        let args = args_of(&cmd);
785        assert!(!args.iter().any(|a| a.contains("sk-abc")), "{args:?}");
786        let settings: Vec<&String> = args
787            .iter()
788            .zip(args.iter().skip(1))
789            .filter(|(flag, _)| *flag == "-c")
790            .map(|(_, value)| value)
791            .collect();
792        assert_eq!(
793            settings,
794            [
795                r#"model_provider="visdom-gateway""#,
796                r#"model_providers.visdom-gateway.name="Visdom AI Gateway""#,
797                r#"model_providers.visdom-gateway.base_url="https://llm.example.com/v1""#,
798                r#"model_providers.visdom-gateway.env_key="VISDOM_GATEWAY_API_KEY""#,
799                r#"model_providers.visdom-gateway.wire_api="responses""#,
800                r#"model_providers.visdom-gateway.http_headers={ "x-tracevault-agent" = "codex", "x-tracevault-repo" = "11111111-2222-3333-4444-555555555555" }"#,
801            ]
802        );
803        // Every value is valid TOML for the key it sets.
804        for setting in settings {
805            let (key, value) = setting.split_once('=').unwrap();
806            let parsed: Result<toml::Table, _> = toml::from_str(&format!("x = {value}"));
807            assert!(parsed.is_ok(), "{key}: {value}");
808        }
809        assert_eq!(
810            args[args.len() - 4..],
811            ["--model", "gpt-general", "exec", "hi"]
812        );
813    }
814
815    #[test]
816    fn codex_keeps_the_callers_model() {
817        let cmd = codex(&strings(&["-m", "o-mine"]), &gateway());
818        let args = args_of(&cmd);
819        assert!(!args.contains(&"--model".to_string()), "{args:?}");
820        assert_eq!(args[args.len() - 2..], ["-m", "o-mine"]);
821    }
822
823    #[test]
824    fn codex_options_that_choose_the_provider_stop_the_gateway_launch() {
825        for conflicting in [
826            strings(&["-c", "model_provider=openai"]),
827            strings(&["exec", "--config", r#"model_provider = "openai""#, "hi"]),
828            strings(&["--config=model_provider=openai"]),
829            strings(&["-cmodel_provider=openai"]),
830            strings(&[
831                "-c",
832                r#"model_providers.visdom-gateway.base_url="https://evil""#,
833            ]),
834            strings(&["-c", r#"model_providers."visdom-gateway".env_key="X""#]),
835            strings(&["-c", "model_providers={}"]),
836            strings(&["--oss"]),
837            strings(&["--local-provider", "ollama"]),
838        ] {
839            let err = codex_command("codex", &conflicting, &gateway()).unwrap_err();
840            assert!(err.contains("model provider"), "{conflicting:?}: {err}");
841        }
842        for fine in [
843            strings(&["-c", "model_reasoning_effort=high", "exec", "hi"]),
844            strings(&["-c", r#"model_providers.mine.base_url="https://x""#]),
845            strings(&["--config", "model=o-mine"]),
846            // After `--` it is the prompt.
847            strings(&["exec", "--", "-c", "model_provider=openai"]),
848        ] {
849            assert!(
850                codex_command("codex", &fine, &gateway()).is_ok(),
851                "{fine:?}"
852            );
853        }
854    }
855
856    #[test]
857    fn options_are_recognised_with_and_without_an_equals_sign() {
858        let args = strings(&["--model=x", "--resume"]);
859        assert!(has_option(&args, &["--model"]));
860        assert!(has_option(&args, &["-r", "--resume"]));
861        assert!(!has_option(&args, &["--mod", "--settings"]));
862    }
863}