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::path::{Path, PathBuf};
8use std::process::Command;
9
10use tracevault_cli::agent::Agent;
11
12use crate::billing::Billing;
13use crate::mode::{TracingMode, GATEWAY_SESSION_ENV, MODE_ENV};
14
15/// The header the gateway takes its key from when Claude Code's own
16/// `Authorization` carries the developer's subscription token.
17pub const GATEWAY_KEY_HEADER: &str = "x-litellm-api-key";
18
19/// The environment variable Codex reads the gateway key from.
20pub const CODEX_KEY_ENV: &str = "VISDOM_GATEWAY_API_KEY";
21
22/// The name of the model provider `visdom` defines for Codex.
23const CODEX_PROVIDER: &str = "visdom-gateway";
24
25/// How long Claude Code keeps a key before asking the helper again. The
26/// helper answers from visdom's key store, so asking often is cheap, and a
27/// key replaced by another session is picked up within this time.
28const CLAUDE_KEY_TTL_MS: &str = "300000";
29
30/// What an agent needs to run through the gateway.
31#[derive(Clone, Debug, PartialEq, Eq)]
32pub struct GatewayLaunch {
33    /// The LLM gateway's address, without `/v1`.
34    pub llm_url: String,
35    /// The developer's personal key.
36    pub key: String,
37    /// A shell command that prints the current key (`visdom gateway-key …`).
38    pub key_helper: String,
39    /// The model alias to ask for; `None` leaves the agent's own choice.
40    pub model: Option<String>,
41    /// The repository's id in AI Tracing, for attribution.
42    pub repo_id: Option<String>,
43    /// The id the session gets, so the gateway's records join one session.
44    pub session_id: String,
45    /// Who pays: with `Subscription`, Claude Code keeps its own claude.ai
46    /// login and `key` is a subscription key, sent in [`GATEWAY_KEY_HEADER`].
47    pub billing: Billing,
48    /// Where a launch writes what must not be on its command line (the
49    /// user's own state directory).
50    pub private_dir: PathBuf,
51}
52
53/// An agent's command, and the private file it was given, which is removed
54/// once the agent has exited.
55pub struct AgentCommand {
56    pub cmd: Command,
57    pub private_file: Option<PathBuf>,
58}
59
60impl From<Command> for AgentCommand {
61    fn from(cmd: Command) -> Self {
62        AgentCommand {
63            cmd,
64            private_file: None,
65        }
66    }
67}
68
69/// The prefix of the settings files Claude Code launches are given.
70pub const CLAUDE_SETTINGS_PREFIX: &str = "claude-settings-";
71
72/// Write `text` to a new file in `dir` that only the user can read, named
73/// after this process (so a file left by a process that has gone can be told
74/// apart), and return its path.
75pub(crate) fn write_private_file(dir: &Path, text: &str) -> Result<PathBuf, String> {
76    use std::io::Write;
77    let failed = |e: std::io::Error| {
78        format!(
79            "the Claude Code settings could not be written to {}: {e}",
80            dir.display()
81        )
82    };
83    let mut builder = std::fs::DirBuilder::new();
84    builder.recursive(true);
85    #[cfg(unix)]
86    {
87        use std::os::unix::fs::DirBuilderExt;
88        builder.mode(0o700);
89    }
90    builder.create(dir).map_err(failed)?;
91    let path = dir.join(format!(
92        "{CLAUDE_SETTINGS_PREFIX}{}-{}.json",
93        std::process::id(),
94        uuid::Uuid::new_v4()
95    ));
96    let mut options = std::fs::OpenOptions::new();
97    options.write(true).create_new(true);
98    #[cfg(unix)]
99    {
100        use std::os::unix::fs::OpenOptionsExt;
101        options.mode(0o600);
102    }
103    let written = options
104        .open(&path)
105        .and_then(|mut file| file.write_all(text.as_bytes()));
106    if let Err(e) = written {
107        let _ = std::fs::remove_file(&path);
108        return Err(failed(e));
109    }
110    Ok(path)
111}
112
113/// Whether a line of `ANTHROPIC_CUSTOM_HEADERS` sets the header `name`.
114fn sets_header(line: &str, name: &str) -> bool {
115    line.split_once(':')
116        .is_some_and(|(header, _)| header.trim().eq_ignore_ascii_case(name))
117}
118
119/// `headers` without the lines that set the gateway key: `visdom` adds its
120/// own, and one left from elsewhere (an outer gateway session's environment)
121/// would be sent beside it.
122fn without_gateway_key(headers: &str) -> String {
123    headers
124        .lines()
125        .filter(|line| !sets_header(line, GATEWAY_KEY_HEADER))
126        .collect::<Vec<_>>()
127        .join("\n")
128}
129
130/// Whether `args` already carry one of `options` (as `--name value` or
131/// `--name=value`).
132fn has_option(args: &[String], options: &[&str]) -> bool {
133    args.iter().any(|arg| {
134        options.iter().any(|o| {
135            arg == o
136                || arg
137                    .strip_prefix(o)
138                    .is_some_and(|rest| rest.starts_with('='))
139        })
140    })
141}
142
143/// The value `args` give one of `options` (`--name value` or `--name=value`).
144fn option_value<'a>(args: &'a [String], options: &[&str]) -> Option<&'a str> {
145    args.iter().enumerate().find_map(|(i, arg)| {
146        options.iter().find_map(|o| {
147            if arg == o {
148                args.get(i + 1).map(String::as_str)
149            } else {
150                arg.strip_prefix(o).and_then(|rest| rest.strip_prefix('='))
151            }
152        })
153    })
154}
155
156/// `value` as one header value: no line breaks, which would start another
157/// header.
158fn header_value(value: &str) -> String {
159    value.chars().filter(|c| !c.is_control()).collect()
160}
161
162/// Claude Code's switches to another provider's API. Each takes precedence
163/// over `ANTHROPIC_BASE_URL`, so one left set would send the session past the
164/// gateway while the hooks record nothing. (`CLAUDE_CODE_USE_GATEWAY` is
165/// Claude Code's own gateway sign-in, which is not this key helper's.) The
166/// list is Claude Code's: a switch it gains has to be added here.
167pub(crate) const CLAUDE_OTHER_PROVIDERS: [&str; 7] = [
168    "CLAUDE_CODE_USE_BEDROCK",
169    "CLAUDE_CODE_USE_VERTEX",
170    "CLAUDE_CODE_USE_FOUNDRY",
171    "CLAUDE_CODE_USE_MANTLE",
172    "CLAUDE_CODE_USE_ANTHROPIC_AWS",
173    "CLAUDE_CODE_USE_ANTHROPIC_GOOGLE_CLOUD",
174    "CLAUDE_CODE_USE_GATEWAY",
175];
176
177/// The session id the caller's own options give Claude Code, when they name
178/// one: `--session-id`, or `--resume <id>`, which carries on under the same
179/// id unless `--fork-session` asks for a new one. `None` when Claude Code
180/// decides (a picker, `--continue`, a fork).
181fn callers_session(args: &[String]) -> Option<&str> {
182    let is_id = |value: &&str| uuid::Uuid::parse_str(value).is_ok();
183    option_value(args, &["--session-id"])
184        .filter(is_id)
185        .or_else(|| {
186            option_value(args, &["--resume", "-r"])
187                .filter(is_id)
188                .filter(|_| !has_option(args, &["--fork-session"]))
189        })
190}
191
192/// The values `args` give `--settings`, each a file or a JSON text, and
193/// `args` without them. Options after `--` are the prompt's.
194pub(crate) fn split_settings(args: &[String]) -> (Vec<String>, Vec<String>) {
195    let (mut given, mut rest) = (Vec::new(), Vec::new());
196    let mut i = 0;
197    while i < args.len() {
198        let arg = &args[i];
199        if arg == "--" {
200            rest.extend_from_slice(&args[i..]);
201            break;
202        }
203        if arg == "--settings" {
204            given.extend(args.get(i + 1).cloned());
205            i += 2;
206        } else if let Some(value) = arg.strip_prefix("--settings=") {
207            given.push(value.to_string());
208            i += 1;
209        } else {
210            rest.push(arg.clone());
211            i += 1;
212        }
213    }
214    (given, rest)
215}
216
217/// The settings object a `--settings` value stands for.
218pub(crate) fn read_settings(
219    value: &str,
220) -> Result<serde_json::Map<String, serde_json::Value>, String> {
221    let failed = |why: String| format!("the Claude Code settings given with --settings ({why})");
222    let text = if value.trim_start().starts_with('{') {
223        value.to_string()
224    } else {
225        std::fs::read_to_string(value)
226            .map_err(|e| failed(format!("`{value}` cannot be read: {e}")))?
227    };
228    match serde_json::from_str(&text) {
229        Ok(serde_json::Value::Object(map)) => Ok(map),
230        Ok(_) => Err(failed(format!("`{value}` is not a JSON object"))),
231        Err(e) => Err(failed(format!("`{value}` is not JSON: {e}"))),
232    }
233}
234
235/// Claude Code through the gateway. `env` reads the current environment.
236///
237/// Where the session goes is given as settings on the command line
238/// (`--settings`), not only as environment: Claude Code applies the `env` of
239/// its settings files over the environment it was started in, so a base URL
240/// or a provider switch left in the developer's `settings.json` would
241/// otherwise send the session past the gateway — or the gateway key to
242/// another address — while the hooks record nothing. Settings given on the
243/// command line come after the user's and the project's. (Settings an
244/// organisation manages come after everything and are not `visdom`'s to
245/// overrule.)
246///
247/// - The project pays (`billing = project`): the key comes from
248///   `apiKeyHelper`, so a key renewed during a long session is picked up.
249/// - The developer's subscription pays (`billing = subscription`): Claude
250///   Code keeps its own claude.ai login, which `apiKeyHelper` would outrank,
251///   so there is none — the settings set it to nothing, which also undoes
252///   one in the developer's own settings files. The subscription key goes in
253///   the `x-litellm-api-key` header instead (replacing one from elsewhere),
254///   and with it in the settings, they are written to a file only the user
255///   can read rather than onto the command line, where any process list
256///   would show them. The caller removes the file once the agent has exited.
257///   Settings an organisation manages could still override the headers: the
258///   gateway then refuses every request, which has no key.
259/// - Settings the caller passes with `--settings` are kept, merged under
260///   these.
261/// - The session id is fixed up front and sent with every request. A caller
262///   who names the session themselves gets theirs sent; one who leaves it to
263///   Claude Code (`--continue`, a picker) gets none, and the gateway's
264///   records of that session carry no session id.
265///
266/// `Err` when the caller's own `--settings` cannot be read: they could not be
267/// merged, and passing them on unread could undo the routing. Also when the
268/// private settings file cannot be written.
269pub fn claude_command(
270    program: &str,
271    args: &[String],
272    gateway: &GatewayLaunch,
273    env: &dyn Fn(&str) -> Option<String>,
274) -> Result<AgentCommand, String> {
275    let subscription = gateway.billing == Billing::Subscription;
276    let (given, args) = split_settings(args);
277    let mut settings = serde_json::Map::new();
278    for value in &given {
279        // A later one wins key by key, as far as this can tell.
280        settings.extend(read_settings(value)?);
281    }
282    let mut settings_env = match settings.remove("env") {
283        Some(serde_json::Value::Object(map)) => map,
284        _ => serde_json::Map::new(),
285    };
286
287    let own_session = has_option(
288        &args,
289        &[
290            "--session-id",
291            "--resume",
292            "-r",
293            "--continue",
294            "-c",
295            "--from-pr",
296            "--teleport",
297        ],
298    );
299    let session = match own_session {
300        true => callers_session(&args),
301        false => Some(gateway.session_id.as_str()),
302    };
303    // The developer's own headers stay, from the environment and from the
304    // settings they passed.
305    let callers_headers = settings_env
306        .get("ANTHROPIC_CUSTOM_HEADERS")
307        .and_then(|v| v.as_str())
308        .map(String::from);
309    let mut headers: Vec<String> = [env("ANTHROPIC_CUSTOM_HEADERS"), callers_headers]
310        .into_iter()
311        .flatten()
312        .map(|h| without_gateway_key(&h))
313        .filter(|h| !h.trim().is_empty())
314        .collect();
315    headers.push(format!(
316        "x-tracevault-agent: {}",
317        Agent::ClaudeCode.tool_name()
318    ));
319    if let Some(repo) = &gateway.repo_id {
320        headers.push(format!("x-tracevault-repo: {}", header_value(repo)));
321    }
322    if let Some(session) = session {
323        headers.push(format!("x-tracevault-session: {}", header_value(session)));
324    }
325    if subscription {
326        headers.push(format!(
327            "{GATEWAY_KEY_HEADER}: Bearer {}",
328            header_value(&gateway.key)
329        ));
330    }
331    let headers = headers.join("\n");
332
333    // What decides where the session goes: in the environment and, over
334    // whatever a settings file says, in the settings.
335    let mut routing: Vec<(&str, String)> = vec![
336        // The hooks read this to record nothing: a settings file must not
337        // switch them back on beside the gateway.
338        (
339            GATEWAY_SESSION_ENV,
340            Agent::ClaudeCode.tool_name().to_string(),
341        ),
342        (MODE_ENV, TracingMode::Gateway.name().to_string()),
343        ("ANTHROPIC_BASE_URL", gateway.llm_url.clone()),
344        ("ANTHROPIC_CUSTOM_HEADERS", headers),
345    ];
346    if !subscription {
347        routing.push((
348            "CLAUDE_CODE_API_KEY_HELPER_TTL_MS",
349            CLAUDE_KEY_TTL_MS.into(),
350        ));
351    }
352    // Claude Code reads "0" as off; a variable cannot be unset from settings.
353    routing.extend(CLAUDE_OTHER_PROVIDERS.map(|switch| (switch, "0".to_string())));
354
355    let mut cmd = Command::new(program);
356    for (name, value) in &routing {
357        cmd.env(name, value);
358        settings_env.insert(name.to_string(), value.clone().into());
359    }
360    for switch in CLAUDE_OTHER_PROVIDERS {
361        cmd.env_remove(switch);
362    }
363    // A key of the developer's own would be sent in place of the gateway's
364    // (and to the gateway), or in place of their subscription. Removed from
365    // the environment, and set to nothing in the settings, which is how one
366    // in a settings file is cleared: Claude Code then asks the key helper, or
367    // uses its login. (`CLAUDE_CODE_OAUTH_TOKEN` is a subscription login too,
368    // and is left alone.)
369    for key in ["ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN"] {
370        cmd.env_remove(key);
371        settings_env.insert(key.to_string(), "".into());
372    }
373    if let Some(model) = &gateway.model {
374        // The project's allow-list has aliases, not Claude Code's defaults:
375        // both the main and the small model must name one. A model the
376        // developer already chose stays; a blank one is no choice (Claude
377        // Code would fall back to its own default) and gets the alias.
378        for name in ["ANTHROPIC_MODEL", "ANTHROPIC_DEFAULT_HAIKU_MODEL"] {
379            if env(name).is_none_or(|v| v.trim().is_empty()) {
380                cmd.env(name, model);
381            }
382        }
383    }
384    settings.insert("env".to_string(), settings_env.into());
385    // Empty, a helper from the developer's own settings files is not used
386    // (Claude Code 2.1.332, tried by hand): it would outrank the login.
387    let helper = match subscription {
388        true => String::new(),
389        false => gateway.key_helper.clone(),
390    };
391    settings.insert("apiKeyHelper".to_string(), helper.into());
392    let settings = serde_json::Value::Object(settings).to_string();
393    let private_file = match subscription {
394        true => {
395            let file = write_private_file(&gateway.private_dir, &settings)?;
396            cmd.arg("--settings").arg(&file);
397            Some(file)
398        }
399        false => {
400            cmd.arg("--settings").arg(settings);
401            None
402        }
403    };
404    if !own_session {
405        cmd.arg("--session-id").arg(&gateway.session_id);
406    }
407    cmd.args(args);
408    Ok(AgentCommand { cmd, private_file })
409}
410
411/// A TOML basic string.
412fn toml_string(value: &str) -> String {
413    toml::Value::String(value.to_string()).to_string()
414}
415
416/// What the caller's own options would take away from the gateway, if
417/// anything. Codex applies configuration overrides in the order given, and
418/// the caller's come last: one that names another model provider, or redefines
419/// `visdom`'s, would send the session past the gateway (or the gateway key
420/// elsewhere) while the hooks record nothing. Options after `--` are the
421/// prompt's.
422fn codex_conflict(args: &[String]) -> Option<String> {
423    let options = args.iter().take_while(|arg| *arg != "--");
424    let mut overrides: Vec<&str> = Vec::new();
425    let mut awaiting = false;
426    for arg in options {
427        if std::mem::take(&mut awaiting) {
428            overrides.push(arg);
429        } else if arg == "-c" || arg == "--config" {
430            awaiting = true;
431        } else if let Some(value) = arg.strip_prefix("--config=") {
432            overrides.push(value);
433        } else if let Some(value) = arg.strip_prefix("-c").filter(|_| !arg.starts_with("--")) {
434            overrides.push(value.strip_prefix('=').unwrap_or(value));
435        } else if arg == "--oss"
436            || arg == "--local-provider"
437            || arg.starts_with("--local-provider=")
438        {
439            return Some(arg.clone());
440        }
441    }
442    overrides
443        .into_iter()
444        .find(|setting| {
445            let key: String = setting
446                .split('=')
447                .next()
448                .unwrap_or_default()
449                .chars()
450                .filter(|c| !c.is_whitespace() && *c != '"' && *c != '\'')
451                .collect();
452            key == "model_provider"
453                || key == "model_providers"
454                || key == format!("model_providers.{CODEX_PROVIDER}")
455                || key.starts_with(&format!("model_providers.{CODEX_PROVIDER}."))
456        })
457        .map(|setting| format!("-c {setting}"))
458}
459
460/// Codex through the gateway: a model provider defined for this run with
461/// `-c`, its key in the environment. Codex names the session itself
462/// (`thread-id`), which the gateway takes as the session. The key is fixed
463/// for the life of the process.
464///
465/// `Err` when the caller's own options choose or redefine the model provider:
466/// they come after these and would win.
467pub fn codex_command(
468    program: &str,
469    args: &[String],
470    gateway: &GatewayLaunch,
471) -> Result<Command, String> {
472    if let Some(option) = codex_conflict(args) {
473        return Err(format!(
474            "`{option}` chooses Codex's model provider, which through the AI Gateway is the \
475             gateway: leave it out, or use `--mode hooks`"
476        ));
477    }
478    let mut cmd = Command::new(program);
479    cmd.env(GATEWAY_SESSION_ENV, Agent::Codex.tool_name());
480    cmd.env(MODE_ENV, TracingMode::Gateway.name());
481    cmd.env(CODEX_KEY_ENV, &gateway.key);
482    let provider = format!("model_providers.{CODEX_PROVIDER}");
483    let mut headers = vec![format!(
484        "\"x-tracevault-agent\" = {}",
485        toml_string(Agent::Codex.tool_name())
486    )];
487    if let Some(repo) = &gateway.repo_id {
488        headers.push(format!(
489            "\"x-tracevault-repo\" = {}",
490            toml_string(&header_value(repo))
491        ));
492    }
493    let settings = [
494        format!("model_provider={}", toml_string(CODEX_PROVIDER)),
495        format!("{provider}.name={}", toml_string("Visdom AI Gateway")),
496        format!(
497            "{provider}.base_url={}",
498            toml_string(&format!("{}/v1", gateway.llm_url.trim_end_matches('/')))
499        ),
500        format!("{provider}.env_key={}", toml_string(CODEX_KEY_ENV)),
501        format!("{provider}.wire_api={}", toml_string("responses")),
502        format!("{provider}.http_headers={{ {} }}", headers.join(", ")),
503    ];
504    for setting in settings {
505        cmd.arg("-c").arg(setting);
506    }
507    if let Some(model) = &gateway.model {
508        if !has_option(args, &["-m", "--model"]) {
509            cmd.arg("--model").arg(model);
510        }
511    }
512    cmd.args(args);
513    Ok(cmd)
514}
515
516/// `text` as one word of a POSIX shell command.
517pub fn shell_quote(text: &str) -> String {
518    format!("'{}'", text.replace('\'', "'\\''"))
519}
520
521/// The lines every such script starts and ends with: the key is not in the
522/// script, which only says how to get it, so the script can be kept (a shell
523/// profile, an `.envrc`) and shown around.
524fn script(agent: Agent, project: &str, billing: Billing, lines: Vec<String>) -> String {
525    let (paid, again) = match billing {
526        Billing::Project => ("", "24 hours at most"),
527        Billing::Subscription => (
528            ", paid by your Claude subscription",
529            "a subscription key lasts weeks",
530        ),
531    };
532    let mut out = vec![
533        format!(
534            "# {} through the Visdom AI Gateway (project `{project}`{paid}), started without \
535             `visdom`.",
536            agent.label()
537        ),
538        format!("# Use:  source <(visdom env)    — again when the key expires ({again})."),
539        "# Settings your agent's own configuration files make still win over these;".into(),
540        "# `visdom` itself is the way that cannot be overruled.".into(),
541    ];
542    out.extend(lines);
543    // This agent's hooks record nothing when it is started from this shell:
544    // the gateway records it. Any other agent's still do.
545    out.push(format!(
546        "export {GATEWAY_SESSION_ENV}={}",
547        agent.tool_name()
548    ));
549    out.join("\n") + "\n"
550}
551
552/// Shell commands that send a Claude Code started from that shell, without
553/// `visdom`, through the gateway. The project pays: the key is the bearer
554/// token. The subscription pays: Claude Code keeps its login, and the key
555/// goes into the custom headers (still got by running `visdom gateway-key`,
556/// so the script holds no secret).
557pub fn claude_env_script(gateway: &GatewayLaunch, project: &str) -> String {
558    let mut headers = vec![format!(
559        "x-tracevault-agent: {}",
560        Agent::ClaudeCode.tool_name()
561    )];
562    if let Some(repo) = &gateway.repo_id {
563        headers.push(format!("x-tracevault-repo: {}", header_value(repo)));
564    }
565    let mut lines = vec![format!(
566        "export ANTHROPIC_BASE_URL={}",
567        shell_quote(&gateway.llm_url)
568    )];
569    match gateway.billing {
570        Billing::Project => {
571            lines.push(format!(
572                "export ANTHROPIC_AUTH_TOKEN=\"$({})\"",
573                gateway.key_helper
574            ));
575            lines.push(format!(
576                "export ANTHROPIC_CUSTOM_HEADERS={}",
577                shell_quote(&headers.join("\n"))
578            ));
579        }
580        Billing::Subscription => {
581            // The newline inside single quotes ends the last header line.
582            lines.push(format!(
583                "export ANTHROPIC_CUSTOM_HEADERS={}\"$({})\"",
584                shell_quote(&format!(
585                    "{}\n{GATEWAY_KEY_HEADER}: Bearer ",
586                    headers.join("\n")
587                )),
588                gateway.key_helper
589            ));
590        }
591    }
592    if let Some(model) = &gateway.model {
593        for name in ["ANTHROPIC_MODEL", "ANTHROPIC_DEFAULT_HAIKU_MODEL"] {
594            lines.push(format!("export {name}={}", shell_quote(model)));
595        }
596    }
597    let keys = match gateway.billing {
598        Billing::Project => "ANTHROPIC_API_KEY",
599        Billing::Subscription => "ANTHROPIC_API_KEY ANTHROPIC_AUTH_TOKEN",
600    };
601    lines.push(format!("unset {keys} {}", CLAUDE_OTHER_PROVIDERS.join(" ")));
602    script(Agent::ClaudeCode, project, gateway.billing, lines)
603}
604
605/// The same for Codex, whose provider is given as options, not variables:
606/// the script defines a `codex` function that adds them.
607pub fn codex_env_script(
608    program: &str,
609    gateway: &GatewayLaunch,
610    project: &str,
611) -> Result<String, String> {
612    let cmd = codex_command(program, &[], gateway)?;
613    let options: Vec<String> = cmd
614        .get_args()
615        .map(|arg| shell_quote(&arg.to_string_lossy()))
616        .collect();
617    let lines = vec![
618        format!("export {CODEX_KEY_ENV}=\"$({})\"", gateway.key_helper),
619        format!(
620            "codex() {{ command {} {} \"$@\"; }}",
621            shell_quote(program),
622            options.join(" ")
623        ),
624    ];
625    Ok(script(Agent::Codex, project, gateway.billing, lines))
626}
627
628#[cfg(test)]
629mod tests {
630    use super::*;
631    use std::collections::HashMap;
632    use std::ffi::OsStr;
633
634    fn gateway() -> GatewayLaunch {
635        GatewayLaunch {
636            llm_url: "https://llm.example.com".to_string(),
637            key: "sk-abc".to_string(),
638            key_helper: "'/usr/bin/visdom' gateway-key --console 'https://gw' --project 'p-1'"
639                .to_string(),
640            model: Some("claude-sonnet".to_string()),
641            repo_id: Some("11111111-2222-3333-4444-555555555555".to_string()),
642            session_id: "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee".to_string(),
643            billing: Billing::Project,
644            private_dir: PathBuf::from("/nonexistent/visdom-private"),
645        }
646    }
647
648    fn args_of(cmd: &Command) -> Vec<String> {
649        cmd.get_args()
650            .map(|a| a.to_string_lossy().into_owned())
651            .collect()
652    }
653
654    /// The variables a command sets (`Some`) or removes (`None`).
655    fn envs_of(cmd: &Command) -> HashMap<String, Option<String>> {
656        cmd.get_envs()
657            .map(|(k, v): (&OsStr, Option<&OsStr>)| {
658                (
659                    k.to_string_lossy().into_owned(),
660                    v.map(|v| v.to_string_lossy().into_owned()),
661                )
662            })
663            .collect()
664    }
665
666    fn strings(args: &[&str]) -> Vec<String> {
667        args.iter().map(|a| a.to_string()).collect()
668    }
669
670    fn no_env(_: &str) -> Option<String> {
671        None
672    }
673
674    fn claude(
675        args: &[String],
676        gateway: &GatewayLaunch,
677        env: &dyn Fn(&str) -> Option<String>,
678    ) -> Command {
679        let launched = claude_command("claude", args, gateway, env).unwrap();
680        assert_eq!(
681            launched.private_file, None,
682            "the project's key is not in it"
683        );
684        launched.cmd
685    }
686
687    fn codex(args: &[String], gateway: &GatewayLaunch) -> Command {
688        codex_command("codex", args, gateway).unwrap()
689    }
690
691    /// The settings a Claude command carries: always the first option.
692    fn settings_of(cmd: &Command) -> serde_json::Value {
693        let args = args_of(cmd);
694        assert_eq!(args[0], "--settings");
695        assert_eq!(args.iter().filter(|a| *a == "--settings").count(), 1);
696        serde_json::from_str(&args[1]).unwrap()
697    }
698
699    #[test]
700    fn claude_gets_the_gateway_the_key_helper_and_a_session() {
701        let cmd = claude(&strings(&["--verbose"]), &gateway(), &no_env);
702        let env = envs_of(&cmd);
703        assert_eq!(
704            env["VISDOM_GATEWAY_SESSION"].as_deref(),
705            Some("claude-code")
706        );
707        assert_eq!(env["VISDOM_TRACING_MODE"].as_deref(), Some("gateway"));
708        assert_eq!(
709            env["ANTHROPIC_BASE_URL"].as_deref(),
710            Some("https://llm.example.com")
711        );
712        assert_eq!(env["ANTHROPIC_API_KEY"], None, "removed");
713        assert_eq!(
714            env["ANTHROPIC_AUTH_TOKEN"], None,
715            "removed: the helper gives the key"
716        );
717        assert_eq!(env["ANTHROPIC_MODEL"].as_deref(), Some("claude-sonnet"));
718        assert_eq!(
719            env["ANTHROPIC_DEFAULT_HAIKU_MODEL"].as_deref(),
720            Some("claude-sonnet")
721        );
722        assert_eq!(
723            env["ANTHROPIC_CUSTOM_HEADERS"].as_deref(),
724            Some(
725                "x-tracevault-agent: claude-code\n\
726                 x-tracevault-repo: 11111111-2222-3333-4444-555555555555\n\
727                 x-tracevault-session: aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"
728            )
729        );
730        let args = args_of(&cmd);
731        let settings = settings_of(&cmd);
732        assert_eq!(settings["apiKeyHelper"], gateway().key_helper);
733        // Where the session goes is in the settings too, over whatever a
734        // settings file of the developer's says.
735        assert_eq!(
736            settings["env"],
737            serde_json::json!({
738                "VISDOM_GATEWAY_SESSION": "claude-code",
739                "VISDOM_TRACING_MODE": "gateway",
740                "ANTHROPIC_API_KEY": "",
741                "ANTHROPIC_AUTH_TOKEN": "",
742                "ANTHROPIC_BASE_URL": "https://llm.example.com",
743                "ANTHROPIC_CUSTOM_HEADERS": env["ANTHROPIC_CUSTOM_HEADERS"],
744                "CLAUDE_CODE_API_KEY_HELPER_TTL_MS": "300000",
745                "CLAUDE_CODE_USE_BEDROCK": "0",
746                "CLAUDE_CODE_USE_VERTEX": "0",
747                "CLAUDE_CODE_USE_FOUNDRY": "0",
748                "CLAUDE_CODE_USE_MANTLE": "0",
749                "CLAUDE_CODE_USE_ANTHROPIC_AWS": "0",
750                "CLAUDE_CODE_USE_ANTHROPIC_GOOGLE_CLOUD": "0",
751                "CLAUDE_CODE_USE_GATEWAY": "0",
752            })
753        );
754        assert_eq!(
755            args[2..],
756            [
757                "--session-id",
758                "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
759                "--verbose"
760            ]
761        );
762        // The key itself is in no argument.
763        assert!(!args.iter().any(|a| a.contains("sk-abc")));
764    }
765
766    #[test]
767    fn a_session_claude_code_picks_itself_gets_no_session_id() {
768        for resume in [
769            strings(&["--resume"]),
770            strings(&["--resume", "a title, not an id"]),
771            strings(&["-c"]),
772            strings(&["--session-id=xyz"]),
773            // A fork gets a new id, which only Claude Code knows.
774            strings(&["--resume", OTHER_SESSION, "--fork-session"]),
775        ] {
776            let cmd = claude(&resume, &gateway(), &no_env);
777            let args = args_of(&cmd);
778            assert_eq!(args[2..], resume[..], "{args:?}");
779            let headers = envs_of(&cmd)["ANTHROPIC_CUSTOM_HEADERS"].clone().unwrap();
780            assert!(!headers.contains("x-tracevault-session"), "{headers}");
781            assert!(headers.contains("x-tracevault-repo"), "{headers}");
782        }
783    }
784
785    const OTHER_SESSION: &str = "99999999-8888-7777-6666-555555555555";
786
787    #[test]
788    fn a_session_the_caller_names_is_the_one_sent() {
789        for named in [
790            strings(&["--session-id", OTHER_SESSION]),
791            strings(&[&format!("--session-id={OTHER_SESSION}")]),
792            strings(&["--resume", OTHER_SESSION]),
793            strings(&["-r", OTHER_SESSION, "--verbose"]),
794        ] {
795            let cmd = claude(&named, &gateway(), &no_env);
796            // Nothing of visdom's own is added to what the caller asked for.
797            assert_eq!(args_of(&cmd)[2..], named[..]);
798            let headers = envs_of(&cmd)["ANTHROPIC_CUSTOM_HEADERS"].clone().unwrap();
799            assert!(
800                headers.ends_with(&format!("x-tracevault-session: {OTHER_SESSION}")),
801                "{headers}"
802            );
803            assert!(!headers.contains(&gateway().session_id), "{headers}");
804        }
805    }
806
807    #[test]
808    fn claude_is_not_left_pointed_at_another_provider() {
809        let cmd = claude(&[], &gateway(), &no_env);
810        let env = envs_of(&cmd);
811        let settings = settings_of(&cmd);
812        for switch in [
813            "CLAUDE_CODE_USE_BEDROCK",
814            "CLAUDE_CODE_USE_VERTEX",
815            "CLAUDE_CODE_USE_FOUNDRY",
816            "CLAUDE_CODE_USE_MANTLE",
817            "CLAUDE_CODE_USE_ANTHROPIC_AWS",
818            "CLAUDE_CODE_USE_ANTHROPIC_GOOGLE_CLOUD",
819            "CLAUDE_CODE_USE_GATEWAY",
820        ] {
821            assert_eq!(env[switch], None, "{switch} must be removed");
822            assert_eq!(settings["env"][switch], "0", "{switch} must be off");
823        }
824    }
825
826    #[test]
827    fn the_callers_own_settings_are_merged_under_the_gateways() {
828        let tmp = tempfile::tempdir().unwrap();
829        let file = tmp.path().join("mine.json");
830        std::fs::write(
831            &file,
832            r#"{"permissions":{"allow":["Bash(ls)"]},"apiKeyHelper":"echo mine",
833                "env":{"ANTHROPIC_BASE_URL":"https://elsewhere.example.com",
834                       "CLAUDE_CODE_USE_BEDROCK":"1","ANTHROPIC_API_KEY":"sk-mine",
835                       "ANTHROPIC_AUTH_TOKEN":"tok-mine","VISDOM_TRACING_MODE":"hooks",
836                       "ANTHROPIC_CUSTOM_HEADERS":"x-team: blue","MY_VAR":"kept"}}"#,
837        )
838        .unwrap();
839        let inline = r#"{"model":"opus","env":{"OTHER":"1"}}"#;
840        for own in [
841            strings(&["--verbose", "--settings", file.to_str().unwrap()]),
842            strings(&[&format!("--settings={}", file.display()), "--verbose"]),
843        ] {
844            let cmd = claude(&own, &gateway(), &no_env);
845            let settings = settings_of(&cmd);
846            assert_eq!(settings["permissions"]["allow"][0], "Bash(ls)");
847            assert_eq!(settings["apiKeyHelper"], gateway().key_helper);
848            let env = &settings["env"];
849            assert_eq!(env["MY_VAR"], "kept");
850            assert_eq!(env["ANTHROPIC_BASE_URL"], "https://llm.example.com");
851            assert_eq!(env["CLAUDE_CODE_USE_BEDROCK"], "0");
852            assert_eq!(env["ANTHROPIC_API_KEY"], "");
853            assert_eq!(env["ANTHROPIC_AUTH_TOKEN"], "");
854            assert_eq!(env["VISDOM_TRACING_MODE"], "gateway");
855            let headers = env["ANTHROPIC_CUSTOM_HEADERS"].as_str().unwrap();
856            assert!(
857                headers.starts_with("x-team: blue\nx-tracevault-agent"),
858                "{headers}"
859            );
860            // Theirs is gone from the options; the rest stays.
861            let args = args_of(&cmd);
862            assert_eq!(args[2..4], ["--session-id", gateway().session_id.as_str()]);
863            assert_eq!(args[4..], ["--verbose"]);
864            // The key reaches Claude Code through the helper alone.
865            assert_eq!(envs_of(&cmd)["ANTHROPIC_AUTH_TOKEN"], None);
866        }
867        // JSON given in place, twice: both are kept.
868        let both = strings(&["--settings", inline, "--settings", file.to_str().unwrap()]);
869        let settings = settings_of(&claude(&both, &gateway(), &no_env));
870        assert_eq!(settings["model"], "opus");
871        assert_eq!(settings["permissions"]["allow"][0], "Bash(ls)");
872    }
873
874    #[test]
875    fn settings_that_cannot_be_read_stop_the_gateway_launch() {
876        for (own, said) in [
877            (
878                strings(&["--settings", "/nonexistent/mine.json"]),
879                "cannot be read",
880            ),
881            (strings(&["--settings", "{not json"]), "is not JSON"),
882            (strings(&["--settings=[1]"]), "cannot be read"),
883        ] {
884            let err = claude_command("claude", &own, &gateway(), &no_env)
885                .err()
886                .unwrap();
887            assert!(err.contains(said), "{err}");
888        }
889        // After `--` it is the prompt, not an option.
890        let prompt = strings(&["--", "--settings", "what does this flag do?"]);
891        let cmd = claude(&prompt, &gateway(), &no_env);
892        assert_eq!(args_of(&cmd)[4..], prompt[..]);
893    }
894
895    #[test]
896    fn claude_keeps_what_the_developer_already_set() {
897        let env = |name: &str| match name {
898            "ANTHROPIC_MODEL" => Some("my-alias".to_string()),
899            "ANTHROPIC_CUSTOM_HEADERS" => Some("x-team: blue".to_string()),
900            _ => None,
901        };
902        let mut launch = gateway();
903        launch.repo_id = None;
904        let cmd = claude(&[], &launch, &env);
905        let set = envs_of(&cmd);
906        assert!(!set.contains_key("ANTHROPIC_MODEL"), "left as it is");
907        assert_eq!(
908            set["ANTHROPIC_DEFAULT_HAIKU_MODEL"].as_deref(),
909            Some("claude-sonnet")
910        );
911        let headers = set["ANTHROPIC_CUSTOM_HEADERS"].clone().unwrap();
912        assert!(
913            headers.starts_with("x-team: blue\nx-tracevault-agent"),
914            "{headers}"
915        );
916        assert!(!headers.contains("x-tracevault-repo"), "{headers}");
917    }
918
919    #[test]
920    fn a_blank_model_variable_is_no_choice_and_gets_the_alias() {
921        let env = |name: &str| (name == "ANTHROPIC_MODEL").then(|| " ".to_string());
922        let set = envs_of(&claude(&[], &gateway(), &env));
923        assert_eq!(set["ANTHROPIC_MODEL"].as_deref(), Some("claude-sonnet"));
924    }
925
926    #[test]
927    fn without_a_model_claude_is_given_none() {
928        let mut launch = gateway();
929        launch.model = None;
930        let set = envs_of(&claude(&[], &launch, &no_env));
931        assert!(!set.contains_key("ANTHROPIC_MODEL"));
932        assert!(!set.contains_key("ANTHROPIC_DEFAULT_HAIKU_MODEL"));
933    }
934
935    #[test]
936    fn a_header_value_cannot_start_another_header() {
937        let mut launch = gateway();
938        launch.repo_id = Some("abc\nx-evil: 1".to_string());
939        let set = envs_of(&claude(&[], &launch, &no_env));
940        let headers = set["ANTHROPIC_CUSTOM_HEADERS"].clone().unwrap();
941        assert_eq!(headers.lines().count(), 3, "{headers}");
942        assert!(
943            headers.contains("x-tracevault-repo: abcx-evil: 1"),
944            "{headers}"
945        );
946    }
947
948    #[test]
949    fn codex_gets_a_provider_for_this_run_and_the_key_in_its_environment() {
950        let mut launch = gateway();
951        launch.model = Some("gpt-general".to_string());
952        let cmd = codex(&strings(&["exec", "hi"]), &launch);
953        let env = envs_of(&cmd);
954        assert_eq!(env["VISDOM_GATEWAY_SESSION"].as_deref(), Some("codex"));
955        assert_eq!(env["VISDOM_TRACING_MODE"].as_deref(), Some("gateway"));
956        assert_eq!(env["VISDOM_GATEWAY_API_KEY"].as_deref(), Some("sk-abc"));
957        let args = args_of(&cmd);
958        assert!(!args.iter().any(|a| a.contains("sk-abc")), "{args:?}");
959        let settings: Vec<&String> = args
960            .iter()
961            .zip(args.iter().skip(1))
962            .filter(|(flag, _)| *flag == "-c")
963            .map(|(_, value)| value)
964            .collect();
965        assert_eq!(
966            settings,
967            [
968                r#"model_provider="visdom-gateway""#,
969                r#"model_providers.visdom-gateway.name="Visdom AI Gateway""#,
970                r#"model_providers.visdom-gateway.base_url="https://llm.example.com/v1""#,
971                r#"model_providers.visdom-gateway.env_key="VISDOM_GATEWAY_API_KEY""#,
972                r#"model_providers.visdom-gateway.wire_api="responses""#,
973                r#"model_providers.visdom-gateway.http_headers={ "x-tracevault-agent" = "codex", "x-tracevault-repo" = "11111111-2222-3333-4444-555555555555" }"#,
974            ]
975        );
976        // Every value is valid TOML for the key it sets.
977        for setting in settings {
978            let (key, value) = setting.split_once('=').unwrap();
979            let parsed: Result<toml::Table, _> = toml::from_str(&format!("x = {value}"));
980            assert!(parsed.is_ok(), "{key}: {value}");
981        }
982        assert_eq!(
983            args[args.len() - 4..],
984            ["--model", "gpt-general", "exec", "hi"]
985        );
986    }
987
988    #[test]
989    fn codex_keeps_the_callers_model() {
990        let cmd = codex(&strings(&["-m", "o-mine"]), &gateway());
991        let args = args_of(&cmd);
992        assert!(!args.contains(&"--model".to_string()), "{args:?}");
993        assert_eq!(args[args.len() - 2..], ["-m", "o-mine"]);
994    }
995
996    #[test]
997    fn codex_options_that_choose_the_provider_stop_the_gateway_launch() {
998        for conflicting in [
999            strings(&["-c", "model_provider=openai"]),
1000            strings(&["exec", "--config", r#"model_provider = "openai""#, "hi"]),
1001            strings(&["--config=model_provider=openai"]),
1002            strings(&["-cmodel_provider=openai"]),
1003            strings(&[
1004                "-c",
1005                r#"model_providers.visdom-gateway.base_url="https://evil""#,
1006            ]),
1007            strings(&["-c", r#"model_providers."visdom-gateway".env_key="X""#]),
1008            strings(&["-c", "model_providers={}"]),
1009            strings(&["--oss"]),
1010            strings(&["--local-provider", "ollama"]),
1011        ] {
1012            let err = codex_command("codex", &conflicting, &gateway()).unwrap_err();
1013            assert!(err.contains("model provider"), "{conflicting:?}: {err}");
1014        }
1015        for fine in [
1016            strings(&["-c", "model_reasoning_effort=high", "exec", "hi"]),
1017            strings(&["-c", r#"model_providers.mine.base_url="https://x""#]),
1018            strings(&["--config", "model=o-mine"]),
1019            // After `--` it is the prompt.
1020            strings(&["exec", "--", "-c", "model_provider=openai"]),
1021        ] {
1022            assert!(
1023                codex_command("codex", &fine, &gateway()).is_ok(),
1024                "{fine:?}"
1025            );
1026        }
1027    }
1028
1029    /// A subscription launch, its settings read back from the private file.
1030    fn subscription(
1031        args: &[String],
1032        env: &dyn Fn(&str) -> Option<String>,
1033    ) -> (tempfile::TempDir, Command, PathBuf, serde_json::Value) {
1034        let tmp = tempfile::tempdir().unwrap();
1035        let mut launch = gateway();
1036        launch.billing = Billing::Subscription;
1037        launch.key = "sk-sub".to_string();
1038        launch.private_dir = tmp.path().join("state/visdom");
1039        let launched = claude_command("claude", args, &launch, env).unwrap();
1040        let file = launched.private_file.clone().expect("a private file");
1041        let settings = serde_json::from_str(&std::fs::read_to_string(&file).unwrap()).unwrap();
1042        (tmp, launched.cmd, file, settings)
1043    }
1044
1045    #[test]
1046    fn a_subscription_launch_keeps_the_login_and_sends_the_key_in_a_header() {
1047        let (_tmp, cmd, file, settings) = subscription(&strings(&["--verbose"]), &no_env);
1048        let args = args_of(&cmd);
1049        assert_eq!(args[0], "--settings");
1050        assert_eq!(args[1], file.to_string_lossy());
1051        assert_eq!(
1052            args[2..],
1053            [
1054                "--session-id",
1055                "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
1056                "--verbose"
1057            ]
1058        );
1059        assert!(!args.iter().any(|a| a.contains("sk-sub")), "{args:?}");
1060        // No helper: the empty one overrides any in the developer's files.
1061        assert_eq!(settings["apiKeyHelper"], "");
1062        let headers = "x-tracevault-agent: claude-code\n\
1063                       x-tracevault-repo: 11111111-2222-3333-4444-555555555555\n\
1064                       x-tracevault-session: aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee\n\
1065                       x-litellm-api-key: Bearer sk-sub";
1066        assert_eq!(settings["env"]["ANTHROPIC_CUSTOM_HEADERS"], headers);
1067        assert_eq!(settings["env"]["ANTHROPIC_API_KEY"], "");
1068        assert_eq!(settings["env"]["ANTHROPIC_AUTH_TOKEN"], "");
1069        assert_eq!(
1070            settings["env"]["ANTHROPIC_BASE_URL"],
1071            "https://llm.example.com"
1072        );
1073        assert_eq!(settings["env"]["VISDOM_GATEWAY_SESSION"], "claude-code");
1074        assert_eq!(settings["env"]["CLAUDE_CODE_USE_BEDROCK"], "0");
1075        assert!(settings["env"]
1076            .get("CLAUDE_CODE_API_KEY_HELPER_TTL_MS")
1077            .is_none());
1078        let env = envs_of(&cmd);
1079        assert_eq!(env["ANTHROPIC_CUSTOM_HEADERS"].as_deref(), Some(headers));
1080        assert_eq!(env["ANTHROPIC_API_KEY"], None);
1081        assert_eq!(env["ANTHROPIC_AUTH_TOKEN"], None);
1082        assert!(!env.contains_key("CLAUDE_CODE_API_KEY_HELPER_TTL_MS"));
1083        assert!(
1084            !env.contains_key("CLAUDE_CODE_OAUTH_TOKEN"),
1085            "a subscription login of the developer's own is left alone"
1086        );
1087        assert_eq!(env["ANTHROPIC_MODEL"].as_deref(), Some("claude-sonnet"));
1088    }
1089
1090    #[cfg(unix)]
1091    #[test]
1092    fn the_subscription_settings_file_is_the_users_alone() {
1093        use std::os::unix::fs::PermissionsExt;
1094        let (_tmp, _cmd, file, _settings) = subscription(&[], &no_env);
1095        let mode = |p: &Path| std::fs::metadata(p).unwrap().permissions().mode() & 0o777;
1096        assert_eq!(mode(&file), 0o600);
1097        assert_eq!(mode(file.parent().unwrap()), 0o700);
1098        let name = file.file_name().unwrap().to_string_lossy().into_owned();
1099        assert!(
1100            name.starts_with(&format!("claude-settings-{}-", std::process::id())),
1101            "{name}"
1102        );
1103    }
1104
1105    #[test]
1106    fn a_gateway_key_header_from_elsewhere_is_replaced_not_doubled() {
1107        let tmp = tempfile::tempdir().unwrap();
1108        let mine = tmp.path().join("mine.json");
1109        std::fs::write(
1110            &mine,
1111            r#"{"apiKeyHelper":"echo mine","env":{"ANTHROPIC_CUSTOM_HEADERS":"X-LiteLLM-API-Key: Bearer sk-settings\nx-team: blue"}}"#,
1112        )
1113        .unwrap();
1114        let env = |name: &str| {
1115            (name == "ANTHROPIC_CUSTOM_HEADERS")
1116                .then(|| "x-litellm-api-key: Bearer sk-outer\nx-env: 1".to_string())
1117        };
1118        let (_t, cmd, _file, settings) =
1119            subscription(&strings(&["--settings", mine.to_str().unwrap()]), &env);
1120        let headers = settings["env"]["ANTHROPIC_CUSTOM_HEADERS"]
1121            .as_str()
1122            .unwrap();
1123        let keys: Vec<&str> = headers
1124            .lines()
1125            .filter(|l| l.to_ascii_lowercase().starts_with("x-litellm-api-key"))
1126            .collect();
1127        assert_eq!(keys, ["x-litellm-api-key: Bearer sk-sub"], "{headers}");
1128        assert!(headers.starts_with("x-env: 1\nx-team: blue\n"), "{headers}");
1129        assert_eq!(settings["apiKeyHelper"], "", "the caller's helper too");
1130        assert_eq!(
1131            args_of(&cmd).iter().filter(|a| *a == "--settings").count(),
1132            1
1133        );
1134        // A project launch does not carry one from elsewhere either.
1135        let cmd = claude(&[], &gateway(), &env);
1136        let headers = envs_of(&cmd)["ANTHROPIC_CUSTOM_HEADERS"].clone().unwrap();
1137        assert!(!headers.contains("sk-outer"), "{headers}");
1138        assert!(headers.starts_with("x-env: 1\n"), "{headers}");
1139    }
1140
1141    #[test]
1142    fn a_subscription_launch_that_cannot_write_its_settings_does_not_start() {
1143        let tmp = tempfile::tempdir().unwrap();
1144        let blocker = tmp.path().join("file");
1145        std::fs::write(&blocker, "").unwrap();
1146        let mut launch = gateway();
1147        launch.billing = Billing::Subscription;
1148        launch.private_dir = blocker.join("visdom");
1149        let err = claude_command("claude", &[], &launch, &no_env)
1150            .err()
1151            .unwrap();
1152        assert!(err.contains("could not be written"), "{err}");
1153        assert!(!err.contains("sk-abc"), "{err}");
1154    }
1155
1156    #[test]
1157    fn the_subscription_env_script_puts_the_key_helper_in_the_headers() {
1158        let mut launch = gateway();
1159        launch.billing = Billing::Subscription;
1160        launch.key_helper = "'/usr/bin/visdom' gateway-key --console 'https://gw' --project \
1161                             'p-1' --billing subscription"
1162            .to_string();
1163        let script = claude_env_script(&launch, "alpha");
1164        assert!(!script.contains("sk-abc"), "{script}");
1165        assert!(!script.contains("ANTHROPIC_AUTH_TOKEN="), "{script}");
1166        assert!(
1167            script.contains(
1168                "x-tracevault-repo: 11111111-2222-3333-4444-555555555555\n\
1169                 x-litellm-api-key: Bearer '\"$('/usr/bin/visdom' gateway-key --console \
1170                 'https://gw' --project 'p-1' --billing subscription)\""
1171            ),
1172            "{script}"
1173        );
1174        assert!(
1175            script.contains("unset ANTHROPIC_API_KEY ANTHROPIC_AUTH_TOKEN CLAUDE_CODE_USE_BEDROCK"),
1176            "{script}"
1177        );
1178        assert!(
1179            script.contains("paid by your Claude subscription"),
1180            "{script}"
1181        );
1182    }
1183
1184    #[cfg(unix)]
1185    #[test]
1186    fn a_shell_reads_the_subscription_headers_back() {
1187        let mut launch = gateway();
1188        launch.billing = Billing::Subscription;
1189        launch.key_helper = "printf %s sk-from-helper".to_string();
1190        let script = claude_env_script(&launch, "alpha");
1191        let output = Command::new("sh")
1192            .arg("-c")
1193            .arg(format!("{script}\nprintf %s \"$ANTHROPIC_CUSTOM_HEADERS\""))
1194            .output()
1195            .unwrap();
1196        assert_eq!(
1197            String::from_utf8_lossy(&output.stdout),
1198            "x-tracevault-agent: claude-code\n\
1199             x-tracevault-repo: 11111111-2222-3333-4444-555555555555\n\
1200             x-litellm-api-key: Bearer sk-from-helper"
1201        );
1202    }
1203
1204    #[test]
1205    fn options_are_recognised_with_and_without_an_equals_sign() {
1206        let args = strings(&["--model=x", "--resume"]);
1207        assert!(has_option(&args, &["--model"]));
1208        assert!(has_option(&args, &["-r", "--resume"]));
1209        assert!(!has_option(&args, &["--mod", "--settings"]));
1210    }
1211}