1use std::path::{Path, PathBuf};
12
13use tracevault_protocol::streaming::BillingMode;
14
15use crate::agent::Agent;
16
17pub struct Probe<'a> {
19 pub env: &'a dyn Fn(&str) -> Option<String>,
21 pub home: Option<PathBuf>,
23 pub project_dir: PathBuf,
25 pub managed_claude_settings: Vec<PathBuf>,
27 pub transcript_path: Option<PathBuf>,
29 pub codex_system_config: Vec<PathBuf>,
32 pub codex_managed_config: Vec<PathBuf>,
33}
34
35impl Probe<'_> {
36 fn var(&self, name: &str) -> Option<String> {
38 (self.env)(name).filter(|v| !v.trim().is_empty())
39 }
40
41 fn flag(&self, name: &str) -> bool {
43 self.var(name).is_some_and(|v| {
44 let v = v.trim();
45 v != "0" && !v.eq_ignore_ascii_case("false") && !v.eq_ignore_ascii_case("no")
46 })
47 }
48}
49
50pub fn detect_current(agent: Agent, hook_cwd: &Path, transcript_path: &str) -> BillingMode {
52 let env = |name: &str| std::env::var(name).ok();
53 let project_dir = std::env::var_os("CLAUDE_PROJECT_DIR")
54 .filter(|_| agent == Agent::ClaudeCode)
55 .map(PathBuf::from)
56 .unwrap_or_else(|| hook_cwd.to_path_buf());
57 let probe = Probe {
58 env: &env,
59 home: dirs::home_dir(),
60 project_dir,
61 managed_claude_settings: managed_claude_settings_paths(),
62 transcript_path: (!transcript_path.is_empty()).then(|| PathBuf::from(transcript_path)),
63 codex_system_config: codex_system_config_paths(),
64 codex_managed_config: codex_managed_config_paths(),
65 };
66 detect(agent, &probe)
67}
68
69pub fn detect(agent: Agent, probe: &Probe) -> BillingMode {
70 match agent {
71 Agent::ClaudeCode => claude_code(probe),
72 Agent::Codex => codex(probe),
73 Agent::Gsd | Agent::OpenCode | Agent::Amp => BillingMode::Unknown,
76 }
77}
78
79fn claude_code(p: &Probe) -> BillingMode {
90 for (flag, base_url) in [
91 ("CLAUDE_CODE_USE_BEDROCK", "ANTHROPIC_BEDROCK_BASE_URL"),
92 ("CLAUDE_CODE_USE_VERTEX", "ANTHROPIC_VERTEX_BASE_URL"),
93 ("CLAUDE_CODE_USE_FOUNDRY", "ANTHROPIC_FOUNDRY_BASE_URL"),
94 ] {
95 if p.flag(flag) {
96 let routed = p.var(base_url).is_some_and(|u| !is_direct_provider_api(&u));
97 return if routed {
98 BillingMode::Gateway
99 } else {
100 BillingMode::ApiKey
102 };
103 }
104 }
105
106 let config_dir = claude_config_dir(p);
107 let gateway_or_key = || {
108 let routed = p
109 .var("ANTHROPIC_BASE_URL")
110 .is_some_and(|u| !host_is(&u, "api.anthropic.com"));
111 if routed {
112 BillingMode::Gateway
113 } else {
114 BillingMode::ApiKey
115 }
116 };
117
118 if p.var("ANTHROPIC_AUTH_TOKEN").is_some() {
119 return gateway_or_key();
120 }
121 if let Some(key) = p.var("ANTHROPIC_API_KEY") {
122 if claude_api_key_declined(p, config_dir.as_deref(), &key) {
123 return BillingMode::Unknown;
126 }
127 return gateway_or_key();
128 }
129 if claude_api_key_helper_configured(p, config_dir.as_deref()) {
130 return gateway_or_key();
131 }
132 if p.var("CLAUDE_CODE_OAUTH_TOKEN").is_some() {
133 return BillingMode::Subscription;
135 }
136 if claude_subscription_login(p, config_dir.as_deref()) {
137 return BillingMode::Subscription;
138 }
139 BillingMode::Unknown
140}
141
142fn claude_config_dir(p: &Probe) -> Option<PathBuf> {
144 p.var("CLAUDE_CONFIG_DIR")
145 .map(PathBuf::from)
146 .or_else(|| p.home.as_ref().map(|h| h.join(".claude")))
147}
148
149fn claude_global_state(p: &Probe, config_dir: Option<&Path>) -> Option<serde_json::Value> {
152 let path = match p.var("CLAUDE_CONFIG_DIR") {
153 Some(_) => config_dir?.join(".claude.json"),
154 None => p.home.as_ref()?.join(".claude.json"),
155 };
156 read_json(&path)
157}
158
159fn claude_api_key_declined(p: &Probe, config_dir: Option<&Path>, key: &str) -> bool {
166 let Some(state) = claude_global_state(p, config_dir) else {
167 return false;
168 };
169 let suffix: String = {
170 let chars: Vec<char> = key.trim().chars().collect();
171 chars[chars.len().saturating_sub(20)..].iter().collect()
172 };
173 let listed = |list: &str| {
174 state
175 .pointer(&format!("/customApiKeyResponses/{list}"))
176 .and_then(|v| v.as_array())
177 .is_some_and(|a| a.iter().any(|e| e.as_str() == Some(suffix.as_str())))
178 };
179 listed("rejected") && !listed("approved")
180}
181
182fn claude_api_key_helper_configured(p: &Probe, config_dir: Option<&Path>) -> bool {
186 let project = p.project_dir.join(".claude");
187 p.managed_claude_settings
188 .iter()
189 .cloned()
190 .chain([
191 project.join("settings.local.json"),
192 project.join("settings.json"),
193 ])
194 .chain(config_dir.map(|d| d.join("settings.json")))
195 .filter_map(|path| read_json(&path))
196 .find_map(|s| s.get("apiKeyHelper").cloned())
197 .is_some_and(|v| v.as_str().is_some_and(|v| !v.trim().is_empty()))
198}
199
200fn claude_subscription_login(p: &Probe, config_dir: Option<&Path>) -> bool {
206 let has_oauth_credentials = config_dir
207 .and_then(|d| read_json(&d.join(".credentials.json")))
208 .is_some_and(|c| c.get("claudeAiOauth").is_some_and(|o| o.is_object()));
209 if has_oauth_credentials {
210 return true;
211 }
212 claude_global_state(p, config_dir).is_some_and(|s| {
213 s.pointer("/oauthAccount/billingType")
214 .and_then(|v| v.as_str())
215 .is_some_and(|t| t.contains("subscription"))
216 })
217}
218
219#[cfg(target_os = "macos")]
220fn managed_claude_settings_paths() -> Vec<PathBuf> {
221 vec![PathBuf::from(
222 "/Library/Application Support/ClaudeCode/managed-settings.json",
223 )]
224}
225
226#[cfg(target_os = "windows")]
227fn managed_claude_settings_paths() -> Vec<PathBuf> {
228 vec![PathBuf::from(
229 r"C:\Program Files\ClaudeCode\managed-settings.json",
230 )]
231}
232
233#[cfg(not(any(target_os = "macos", target_os = "windows")))]
234fn managed_claude_settings_paths() -> Vec<PathBuf> {
235 vec![PathBuf::from("/etc/claude-code/managed-settings.json")]
236}
237
238const CODEX_LOCAL_PROVIDERS: &[&str] = &["ollama", "lmstudio"];
255
256fn codex(p: &Probe) -> BillingMode {
257 let codex_home = p
258 .var("CODEX_HOME")
259 .map(PathBuf::from)
260 .or_else(|| p.home.as_ref().map(|h| h.join(".codex")));
261 let auth_json = codex_home
262 .as_ref()
263 .and_then(|h| read_json(&h.join("auth.json")));
264 let auth = auth_json.as_ref().map(codex_auth_mode);
265 let bedrock_auth = auth_json.as_ref().is_some_and(codex_auth_is_bedrock);
266 let access_token = p.var("CODEX_ACCESS_TOKEN").is_some();
267
268 let layers = codex_config_layers(p, codex_home.as_deref());
269 let config_str = |path: &[&str]| layers.iter().find_map(|l| toml_str(l, path));
270
271 let provider = p
272 .transcript_path
273 .as_deref()
274 .and_then(codex_rollout_provider)
275 .or_else(|| config_str(&["model_provider"]))
276 .unwrap_or_else(|| "openai".to_string());
277 if provider != "openai" {
278 if CODEX_LOCAL_PROVIDERS.contains(&provider.as_str()) {
279 return BillingMode::Unknown;
280 }
281 return match config_str(&["model_providers", &provider, "base_url"]) {
284 Some(url) if host_is(&url, "chatgpt.com") => match auth {
287 Some(BillingMode::Subscription) if !access_token => BillingMode::Subscription,
288 _ => BillingMode::Unknown,
289 },
290 Some(url) if is_direct_provider_api(&url) => BillingMode::ApiKey,
291 Some(_) => BillingMode::Gateway,
292 None if bedrock_auth && !access_token => BillingMode::ApiKey,
296 None => BillingMode::Unknown,
297 };
298 }
299 let redirected = config_str(&["openai_base_url"])
300 .is_some_and(|u| !host_is(&u, "api.openai.com") && !host_is(&u, "chatgpt.com"));
301 if redirected {
302 return BillingMode::Gateway;
303 }
304
305 if access_token {
306 return BillingMode::Unknown;
309 }
310 match auth {
311 Some(BillingMode::Subscription) if p.var("CODEX_API_KEY").is_some() => BillingMode::Unknown,
313 Some(mode) => mode,
314 None => BillingMode::Unknown,
315 }
316}
317
318fn codex_config_layers(p: &Probe, codex_home: Option<&Path>) -> Vec<toml::Table> {
325 let read =
326 |path: &Path| -> Option<toml::Table> { std::fs::read_to_string(path).ok()?.parse().ok() };
327 let user = codex_home.and_then(|h| read(&h.join("config.toml")));
328 let profile = user.as_ref().and_then(|u| {
329 let name = u.get("profile")?.as_str()?;
330 u.get("profiles")?.get(name)?.as_table().cloned()
331 });
332 p.codex_managed_config
333 .iter()
334 .filter_map(|path| read(path))
335 .chain(profile)
336 .chain(user)
337 .chain(p.codex_system_config.iter().filter_map(|path| read(path)))
338 .collect()
339}
340
341fn toml_str(table: &toml::Table, path: &[&str]) -> Option<String> {
343 let (last, parents) = path.split_last()?;
344 let mut table = table;
345 for key in parents {
346 table = table.get(*key)?.as_table()?;
347 }
348 table
349 .get(*last)?
350 .as_str()
351 .filter(|v| !v.trim().is_empty())
352 .map(str::to_string)
353}
354
355#[cfg(windows)]
356fn codex_system_config_paths() -> Vec<PathBuf> {
357 std::env::var_os("ProgramData")
358 .map(|d| PathBuf::from(d).join(r"OpenAI\Codex\config.toml"))
359 .into_iter()
360 .collect()
361}
362
363#[cfg(not(windows))]
364fn codex_system_config_paths() -> Vec<PathBuf> {
365 vec![PathBuf::from("/etc/codex/config.toml")]
366}
367
368#[cfg(windows)]
369fn codex_managed_config_paths() -> Vec<PathBuf> {
370 Vec::new()
371}
372
373#[cfg(not(windows))]
374fn codex_managed_config_paths() -> Vec<PathBuf> {
375 vec![PathBuf::from("/etc/codex/managed_config.toml")]
376}
377
378fn codex_auth_mode(auth: &serde_json::Value) -> BillingMode {
381 let present = |key: &str| auth.get(key).is_some_and(|v| !v.is_null());
382 match auth.get("auth_mode").and_then(|v| v.as_str()) {
383 Some("apikey" | "bedrockApiKey" | "bedrockAccessKeys") => BillingMode::ApiKey,
384 Some("chatgpt" | "chatgptAuthTokens" | "personalAccessToken") => BillingMode::Subscription,
385 Some(_) => BillingMode::Unknown,
387 None if present("personal_access_token") => BillingMode::Subscription,
388 None if codex_auth_is_bedrock(auth) => BillingMode::ApiKey,
389 None if present("OPENAI_API_KEY") => BillingMode::ApiKey,
390 None if present("tokens") => BillingMode::Subscription,
391 None => BillingMode::Unknown,
392 }
393}
394
395fn codex_auth_is_bedrock(auth: &serde_json::Value) -> bool {
398 match auth.get("auth_mode").and_then(|v| v.as_str()) {
399 Some(mode) => mode.starts_with("bedrock"),
400 None => ["bedrock_api_key", "bedrock_access_keys"]
401 .iter()
402 .any(|k| auth.get(k).is_some_and(|v| !v.is_null())),
403 }
404}
405
406fn is_direct_provider_api(url: &str) -> bool {
410 const EXACT: &[&str] = &[
411 "api.openai.com",
412 "api.anthropic.com",
413 "api.mistral.ai",
414 "generativelanguage.googleapis.com",
415 "api.deepseek.com",
416 "api.x.ai",
417 "api.groq.com",
418 "aiplatform.googleapis.com",
419 ];
420 const SUFFIXES: &[&str] = &[
421 ".openai.azure.com",
422 ".services.ai.azure.com",
423 ".cognitiveservices.azure.com",
424 "-aiplatform.googleapis.com",
425 ];
426 url_host(url).is_some_and(|h| {
427 EXACT.contains(&h.as_str())
428 || SUFFIXES.iter().any(|s| h.ends_with(s))
429 || ((h.ends_with(".amazonaws.com") || h.ends_with(".api.aws"))
434 && h.split('.').any(|label| label.starts_with("bedrock")))
435 })
436}
437
438fn codex_rollout_provider(rollout: &Path) -> Option<String> {
440 use std::io::BufRead;
441 let file = std::fs::File::open(rollout).ok()?;
442 let mut first = String::new();
443 std::io::BufReader::new(file).read_line(&mut first).ok()?;
444 let meta: serde_json::Value = serde_json::from_str(&first).ok()?;
445 if meta.get("type").and_then(|v| v.as_str()) != Some("session_meta") {
446 return None;
447 }
448 meta.pointer("/payload/model_provider")
449 .and_then(|v| v.as_str())
450 .filter(|v| !v.trim().is_empty())
451 .map(str::to_string)
452}
453
454fn read_json(path: &Path) -> Option<serde_json::Value> {
457 serde_json::from_str(&std::fs::read_to_string(path).ok()?).ok()
458}
459
460fn url_host(url: &str) -> Option<String> {
462 let rest = url.trim().split_once("://").map_or(url.trim(), |(_, r)| r);
463 let authority = rest.split(['/', '?', '#']).next()?;
464 let host_port = authority.rsplit_once('@').map_or(authority, |(_, h)| h);
465 let host = if let Some(v6) = host_port.strip_prefix('[') {
466 v6.split(']').next()?
467 } else {
468 host_port.split(':').next()?
469 };
470 (!host.is_empty()).then(|| host.to_ascii_lowercase())
471}
472
473fn host_is(url: &str, expected: &str) -> bool {
474 url_host(url).is_some_and(|h| h == expected)
475}
476
477#[cfg(test)]
478mod tests {
479 use super::*;
480 use serde_json::json;
481 use std::collections::HashMap;
482 use tempfile::TempDir;
483
484 struct Fixture {
486 home: TempDir,
487 project: TempDir,
488 env: HashMap<String, String>,
489 managed: Vec<PathBuf>,
490 codex_system: Vec<PathBuf>,
491 codex_managed: Vec<PathBuf>,
492 transcript: Option<PathBuf>,
493 }
494
495 impl Fixture {
496 fn new() -> Self {
497 Self {
498 home: TempDir::new().unwrap(),
499 project: TempDir::new().unwrap(),
500 env: HashMap::new(),
501 managed: Vec::new(),
502 codex_system: Vec::new(),
503 codex_managed: Vec::new(),
504 transcript: None,
505 }
506 }
507
508 fn env(mut self, key: &str, val: &str) -> Self {
509 self.env.insert(key.into(), val.into());
510 self
511 }
512
513 fn home_file(self, rel: &str, contents: &str) -> Self {
514 write(&self.home.path().join(rel), contents);
515 self
516 }
517
518 fn project_file(self, rel: &str, contents: &str) -> Self {
519 write(&self.project.path().join(rel), contents);
520 self
521 }
522
523 fn managed_settings(mut self, contents: &str) -> Self {
524 let path = self.home.path().join("managed/managed-settings.json");
525 write(&path, contents);
526 self.managed.push(path);
527 self
528 }
529
530 fn system_config(mut self, contents: &str) -> Self {
531 let path = self.home.path().join("etc/codex/config.toml");
532 write(&path, contents);
533 self.codex_system.push(path);
534 self
535 }
536
537 fn managed_codex_config(mut self, contents: &str) -> Self {
538 let path = self.home.path().join("etc/codex/managed_config.toml");
539 write(&path, contents);
540 self.codex_managed.push(path);
541 self
542 }
543
544 fn rollout(mut self, first_line: serde_json::Value) -> Self {
545 let path = self.home.path().join("rollout.jsonl");
546 write(
547 &path,
548 &format!("{first_line}\n{{\"type\":\"turn_context\"}}\n"),
549 );
550 self.transcript = Some(path);
551 self
552 }
553
554 fn detect(&self, agent: Agent) -> BillingMode {
555 let env = |k: &str| self.env.get(k).cloned();
556 detect(
557 agent,
558 &Probe {
559 env: &env,
560 home: Some(self.home.path().to_path_buf()),
561 project_dir: self.project.path().to_path_buf(),
562 managed_claude_settings: self.managed.clone(),
563 transcript_path: self.transcript.clone(),
564 codex_system_config: self.codex_system.clone(),
565 codex_managed_config: self.codex_managed.clone(),
566 },
567 )
568 }
569 }
570
571 fn write(path: &Path, contents: &str) {
572 std::fs::create_dir_all(path.parent().unwrap()).unwrap();
573 std::fs::write(path, contents).unwrap();
574 }
575
576 const CLAUDE_OAUTH_CREDENTIALS: &str =
577 r#"{"claudeAiOauth":{"accessToken":"x","refreshToken":"y","subscriptionType":"max"}}"#;
578
579 #[test]
582 fn claude_nothing_configured_is_unknown() {
583 assert_eq!(
584 Fixture::new().detect(Agent::ClaudeCode),
585 BillingMode::Unknown
586 );
587 }
588
589 #[test]
590 fn claude_login_credentials_are_a_subscription() {
591 let f = Fixture::new().home_file(".claude/.credentials.json", CLAUDE_OAUTH_CREDENTIALS);
592 assert_eq!(f.detect(Agent::ClaudeCode), BillingMode::Subscription);
593 }
594
595 #[test]
596 fn claude_keychain_login_falls_back_to_the_cached_account_profile() {
597 let f = Fixture::new().home_file(
599 ".claude.json",
600 r#"{"oauthAccount":{"billingType":"stripe_subscription"}}"#,
601 );
602 assert_eq!(f.detect(Agent::ClaudeCode), BillingMode::Subscription);
603 }
604
605 #[test]
606 fn claude_account_profile_without_subscription_billing_is_unknown() {
607 let f = Fixture::new().home_file(
608 ".claude.json",
609 r#"{"oauthAccount":{"billingType":"other"}}"#,
610 );
611 assert_eq!(f.detect(Agent::ClaudeCode), BillingMode::Unknown);
612 }
613
614 #[test]
615 fn claude_config_dir_override_is_honoured() {
616 let f = Fixture::new();
617 let dir = f.home.path().join("alt-claude");
618 write(&dir.join(".credentials.json"), CLAUDE_OAUTH_CREDENTIALS);
619 let f = f.env("CLAUDE_CONFIG_DIR", dir.to_str().unwrap());
620 assert_eq!(f.detect(Agent::ClaudeCode), BillingMode::Subscription);
621
622 let f = Fixture::new()
624 .home_file(".claude/.credentials.json", CLAUDE_OAUTH_CREDENTIALS)
625 .env("CLAUDE_CONFIG_DIR", "/nonexistent/claude-config");
626 assert_eq!(f.detect(Agent::ClaudeCode), BillingMode::Unknown);
627 }
628
629 #[test]
630 fn claude_setup_token_is_a_subscription() {
631 let f = Fixture::new().env("CLAUDE_CODE_OAUTH_TOKEN", "sk-ant-oat01-x");
632 assert_eq!(f.detect(Agent::ClaudeCode), BillingMode::Subscription);
633 }
634
635 #[test]
636 fn claude_api_key_beats_a_subscription_login() {
637 let f = Fixture::new()
638 .home_file(".claude/.credentials.json", CLAUDE_OAUTH_CREDENTIALS)
639 .env(
640 "ANTHROPIC_API_KEY",
641 "sk-ant-api03-abcdefghijklmnopqrstuvwxyz",
642 );
643 assert_eq!(f.detect(Agent::ClaudeCode), BillingMode::ApiKey);
644 }
645
646 #[test]
647 fn claude_empty_api_key_counts_as_unset() {
648 let f = Fixture::new()
649 .home_file(".claude/.credentials.json", CLAUDE_OAUTH_CREDENTIALS)
650 .env("ANTHROPIC_API_KEY", "");
651 assert_eq!(f.detect(Agent::ClaudeCode), BillingMode::Subscription);
652 }
653
654 #[test]
655 fn claude_declined_api_key_is_unknown() {
656 let key = "sk-ant-api03-abcdefghijklmnopqrstuvwxyz";
659 let last20 = &key[key.len() - 20..];
660 let f = Fixture::new()
661 .home_file(".claude/.credentials.json", CLAUDE_OAUTH_CREDENTIALS)
662 .home_file(
663 ".claude.json",
664 &json!({"customApiKeyResponses": {"approved": [], "rejected": [last20]}})
665 .to_string(),
666 )
667 .env("ANTHROPIC_API_KEY", key);
668 assert_eq!(f.detect(Agent::ClaudeCode), BillingMode::Unknown);
669 }
670
671 #[test]
672 fn claude_approved_api_key_is_used() {
673 let key = "sk-ant-api03-abcdefghijklmnopqrstuvwxyz";
674 let last20 = &key[key.len() - 20..];
675 let f = Fixture::new()
676 .home_file(".claude/.credentials.json", CLAUDE_OAUTH_CREDENTIALS)
677 .home_file(
678 ".claude.json",
679 &json!({"customApiKeyResponses": {"approved": [last20], "rejected": []}})
680 .to_string(),
681 )
682 .env("ANTHROPIC_API_KEY", key);
683 assert_eq!(f.detect(Agent::ClaudeCode), BillingMode::ApiKey);
684 }
685
686 #[test]
687 fn claude_api_key_through_a_gateway_base_url_is_gateway() {
688 let f = Fixture::new()
689 .env("ANTHROPIC_API_KEY", "sk-litellm-virtual-key")
690 .env("ANTHROPIC_BASE_URL", "https://litellm.internal.example.com");
691 assert_eq!(f.detect(Agent::ClaudeCode), BillingMode::Gateway);
692 }
693
694 #[test]
695 fn claude_auth_token_through_a_gateway_is_gateway() {
696 let f = Fixture::new()
697 .env("ANTHROPIC_AUTH_TOKEN", "sk-litellm")
698 .env("ANTHROPIC_BASE_URL", "http://localhost:4000");
699 assert_eq!(f.detect(Agent::ClaudeCode), BillingMode::Gateway);
700 }
701
702 #[test]
703 fn claude_explicit_anthropic_base_url_is_not_a_gateway() {
704 let f = Fixture::new()
705 .env("ANTHROPIC_API_KEY", "sk-ant-api03-x")
706 .env("ANTHROPIC_BASE_URL", "https://API.anthropic.com/");
707 assert_eq!(f.detect(Agent::ClaudeCode), BillingMode::ApiKey);
708 }
709
710 #[test]
711 fn claude_base_url_alone_keeps_subscription_billing() {
712 let f = Fixture::new()
715 .home_file(".claude/.credentials.json", CLAUDE_OAUTH_CREDENTIALS)
716 .env("ANTHROPIC_BASE_URL", "https://proxy.example.com");
717 assert_eq!(f.detect(Agent::ClaudeCode), BillingMode::Subscription);
718 }
719
720 #[test]
721 fn claude_api_key_helper_in_any_settings_scope_is_detected() {
722 let helper = r#"{"apiKeyHelper":"~/bin/get-key.sh"}"#;
723 for f in [
724 Fixture::new().home_file(".claude/settings.json", helper),
725 Fixture::new().project_file(".claude/settings.json", helper),
726 Fixture::new().project_file(".claude/settings.local.json", helper),
727 Fixture::new().managed_settings(helper),
728 ] {
729 let f = f.home_file(".claude/.credentials.json", CLAUDE_OAUTH_CREDENTIALS);
730 assert_eq!(f.detect(Agent::ClaudeCode), BillingMode::ApiKey);
731 }
732 let f = Fixture::new()
733 .project_file(".claude/settings.json", helper)
734 .env("ANTHROPIC_BASE_URL", "https://litellm.example.com");
735 assert_eq!(f.detect(Agent::ClaudeCode), BillingMode::Gateway);
736 }
737
738 #[test]
739 fn claude_settings_without_a_helper_do_not_count() {
740 let f = Fixture::new()
741 .project_file(".claude/settings.json", r#"{"apiKeyHelper":"","hooks":{}}"#)
742 .project_file(".claude/settings.local.json", "not json");
743 assert_eq!(f.detect(Agent::ClaudeCode), BillingMode::Unknown);
744 }
745
746 #[test]
747 fn claude_cloud_providers_bill_per_token() {
748 for flag in [
749 "CLAUDE_CODE_USE_BEDROCK",
750 "CLAUDE_CODE_USE_VERTEX",
751 "CLAUDE_CODE_USE_FOUNDRY",
752 ] {
753 let f = Fixture::new()
754 .home_file(".claude/.credentials.json", CLAUDE_OAUTH_CREDENTIALS)
755 .env(flag, "1");
756 assert_eq!(f.detect(Agent::ClaudeCode), BillingMode::ApiKey, "{flag}");
757 }
758 }
759
760 #[test]
761 fn claude_cloud_provider_flag_set_to_false_is_off() {
762 let f = Fixture::new()
763 .home_file(".claude/.credentials.json", CLAUDE_OAUTH_CREDENTIALS)
764 .env("CLAUDE_CODE_USE_BEDROCK", "0")
765 .env("CLAUDE_CODE_USE_VERTEX", "false");
766 assert_eq!(f.detect(Agent::ClaudeCode), BillingMode::Subscription);
767 }
768
769 #[test]
770 fn claude_cloud_provider_routed_through_a_gateway_is_gateway() {
771 let f = Fixture::new().env("CLAUDE_CODE_USE_BEDROCK", "1").env(
772 "ANTHROPIC_BEDROCK_BASE_URL",
773 "https://litellm.example.com/bedrock",
774 );
775 assert_eq!(f.detect(Agent::ClaudeCode), BillingMode::Gateway);
776
777 let f = Fixture::new().env("CLAUDE_CODE_USE_BEDROCK", "1").env(
779 "ANTHROPIC_BEDROCK_BASE_URL",
780 "https://bedrock-runtime.eu-west-1.amazonaws.com",
781 );
782 assert_eq!(f.detect(Agent::ClaudeCode), BillingMode::ApiKey);
783 }
784
785 fn session_meta(provider: &str) -> serde_json::Value {
788 json!({"type": "session_meta", "payload": {"id": "s", "model_provider": provider}})
789 }
790
791 #[test]
792 fn codex_nothing_configured_is_unknown() {
793 assert_eq!(Fixture::new().detect(Agent::Codex), BillingMode::Unknown);
794 }
795
796 #[test]
797 fn codex_auth_modes_map_to_billing() {
798 for (mode, expected) in [
799 ("chatgpt", BillingMode::Subscription),
800 ("chatgptAuthTokens", BillingMode::Subscription),
801 ("personalAccessToken", BillingMode::Subscription),
802 ("apikey", BillingMode::ApiKey),
803 ("bedrockApiKey", BillingMode::ApiKey),
804 ("bedrockAccessKeys", BillingMode::ApiKey),
805 ("headers", BillingMode::Unknown),
806 ("agentIdentity", BillingMode::Unknown),
807 ("someFutureMode", BillingMode::Unknown),
808 ] {
809 let f = Fixture::new().home_file(
810 ".codex/auth.json",
811 &json!({"auth_mode": mode, "OPENAI_API_KEY": null}).to_string(),
812 );
813 assert_eq!(f.detect(Agent::Codex), expected, "auth_mode {mode}");
814 }
815 }
816
817 #[test]
818 fn codex_auth_json_without_a_mode_is_inferred_like_codex_does() {
819 for (auth, expected) in [
820 (json!({"OPENAI_API_KEY": "sk-x"}), BillingMode::ApiKey),
821 (
822 json!({"OPENAI_API_KEY": null, "tokens": {"access_token": "a"}}),
823 BillingMode::Subscription,
824 ),
825 (
826 json!({"OPENAI_API_KEY": null, "personal_access_token": "p"}),
827 BillingMode::Subscription,
828 ),
829 (
830 json!({"OPENAI_API_KEY": null, "bedrock_api_key": {"api_key": "b"}}),
831 BillingMode::ApiKey,
832 ),
833 (json!({"OPENAI_API_KEY": null}), BillingMode::Unknown),
834 ] {
835 let f = Fixture::new().home_file(".codex/auth.json", &auth.to_string());
836 assert_eq!(f.detect(Agent::Codex), expected, "{auth}");
837 }
838 }
839
840 #[test]
841 fn codex_home_override_is_honoured() {
842 let f = Fixture::new();
843 let dir = f.home.path().join("alt-codex");
844 write(
845 &dir.join("auth.json"),
846 r#"{"auth_mode":"apikey","OPENAI_API_KEY":"sk"}"#,
847 );
848 let f = f
849 .home_file(".codex/auth.json", r#"{"auth_mode":"chatgpt"}"#)
850 .env("CODEX_HOME", dir.to_str().unwrap());
851 assert_eq!(f.detect(Agent::Codex), BillingMode::ApiKey);
852 }
853
854 #[test]
855 fn codex_custom_provider_in_the_rollout_is_gateway() {
856 let f = Fixture::new()
857 .home_file(".codex/auth.json", r#"{"auth_mode":"chatgpt"}"#)
858 .home_file(
859 ".codex/config.toml",
860 "[model_providers.litellm]\nbase_url = \"http://localhost:4000/v1\"\n",
861 )
862 .rollout(session_meta("litellm"));
863 assert_eq!(f.detect(Agent::Codex), BillingMode::Gateway);
864 }
865
866 #[test]
867 fn codex_custom_provider_at_a_vendor_api_is_billed_directly() {
868 for url in [
869 "https://my-res.openai.azure.com/openai/v1",
870 "https://api.mistral.ai/v1",
871 "https://us-central1-aiplatform.googleapis.com/v1",
872 ] {
873 let f = Fixture::new()
874 .home_file(
875 ".codex/config.toml",
876 &format!("[model_providers.direct]\nbase_url = \"{url}\"\n"),
877 )
878 .rollout(session_meta("direct"));
879 assert_eq!(f.detect(Agent::Codex), BillingMode::ApiKey, "{url}");
880 }
881 }
882
883 #[test]
884 fn codex_custom_provider_without_a_resolvable_endpoint_is_unknown() {
885 let f = Fixture::new()
886 .home_file(".codex/auth.json", r#"{"auth_mode":"chatgpt"}"#)
887 .rollout(session_meta("defined-elsewhere"));
888 assert_eq!(f.detect(Agent::Codex), BillingMode::Unknown);
889 }
890
891 #[test]
892 fn codex_openai_provider_in_the_rollout_defers_to_auth() {
893 let f = Fixture::new()
894 .home_file(".codex/auth.json", r#"{"auth_mode":"chatgpt"}"#)
895 .home_file(".codex/config.toml", "model_provider = \"litellm\"\n")
897 .rollout(session_meta("openai"));
898 assert_eq!(f.detect(Agent::Codex), BillingMode::Subscription);
899 }
900
901 #[test]
902 fn codex_local_oss_provider_is_unknown() {
903 let f = Fixture::new()
904 .home_file(".codex/auth.json", r#"{"auth_mode":"chatgpt"}"#)
905 .rollout(session_meta("ollama"));
906 assert_eq!(f.detect(Agent::Codex), BillingMode::Unknown);
907 }
908
909 #[test]
910 fn codex_custom_provider_in_config_is_gateway_without_a_rollout() {
911 let f = Fixture::new()
912 .home_file(".codex/auth.json", r#"{"auth_mode":"chatgpt"}"#)
913 .home_file(
914 ".codex/config.toml",
915 "model_provider = \"litellm\"\n[model_providers.litellm]\nbase_url = \"https://litellm.example.com\"\n",
916 );
917 assert_eq!(f.detect(Agent::Codex), BillingMode::Gateway);
918 }
919
920 #[test]
921 fn codex_openai_base_url_redirect_is_gateway() {
922 let f = Fixture::new()
923 .home_file(
924 ".codex/auth.json",
925 r#"{"auth_mode":"apikey","OPENAI_API_KEY":"sk"}"#,
926 )
927 .home_file(
928 ".codex/config.toml",
929 "openai_base_url = \"https://gw.example.com/v1\"\n",
930 )
931 .rollout(session_meta("openai"));
932 assert_eq!(f.detect(Agent::Codex), BillingMode::Gateway);
933
934 let f = Fixture::new()
936 .home_file(
937 ".codex/auth.json",
938 r#"{"auth_mode":"apikey","OPENAI_API_KEY":"sk"}"#,
939 )
940 .home_file(
941 ".codex/config.toml",
942 "openai_base_url = \"https://api.openai.com/v1\"\n",
943 );
944 assert_eq!(f.detect(Agent::Codex), BillingMode::ApiKey);
945 }
946
947 #[test]
948 fn codex_ignores_project_routing_config() {
949 let f = Fixture::new()
950 .home_file(".codex/auth.json", r#"{"auth_mode":"chatgpt"}"#)
951 .project_file(
952 ".codex/config.toml",
953 "model_provider = \"litellm\"\nopenai_base_url = \"https://gw.example.com/v1\"\n",
954 )
955 .rollout(session_meta("openai"));
956 assert_eq!(f.detect(Agent::Codex), BillingMode::Subscription);
957 }
958
959 #[test]
960 fn codex_ignores_openai_base_url_env() {
961 let f = Fixture::new()
963 .home_file(".codex/auth.json", r#"{"auth_mode":"chatgpt"}"#)
964 .env("OPENAI_BASE_URL", "https://gw.example.com/v1");
965 assert_eq!(f.detect(Agent::Codex), BillingMode::Subscription);
966 }
967
968 #[test]
969 fn codex_bedrock_auth_is_api_key_whatever_the_provider() {
970 let f = Fixture::new()
971 .home_file(".codex/auth.json", r#"{"auth_mode":"bedrockApiKey"}"#)
972 .rollout(session_meta("amazon-bedrock"));
973 assert_eq!(f.detect(Agent::Codex), BillingMode::ApiKey);
974 }
975
976 #[test]
977 fn codex_access_token_overrides_stored_bedrock_credentials() {
978 for provider in ["amazon-bedrock", "openai"] {
979 let f = Fixture::new()
980 .home_file(".codex/auth.json", r#"{"auth_mode":"bedrockApiKey"}"#)
981 .env("CODEX_ACCESS_TOKEN", "t")
982 .rollout(session_meta(provider));
983 assert_eq!(f.detect(Agent::Codex), BillingMode::Unknown, "{provider}");
984 }
985 }
986
987 #[test]
990 fn detect_current_reads_the_process_environment_and_transcript() {
991 use crate::test_helpers::{lock_env_mutation_sync, EnvVarGuard};
992 let _lock = lock_env_mutation_sync();
993 let f = Fixture::new()
994 .home_file(".codex/auth.json", r#"{"auth_mode":"chatgpt"}"#)
995 .home_file(
996 ".codex/config.toml",
997 "[model_providers.litellm]\nbase_url = \"https://litellm.example.com\"\n",
998 )
999 .rollout(session_meta("litellm"));
1000 let mut env = EnvVarGuard::new();
1001 env.set("CODEX_HOME", f.home.path().join(".codex"));
1002 env.remove("CODEX_ACCESS_TOKEN");
1003 env.remove("CODEX_API_KEY");
1004 let transcript = f.transcript.clone().unwrap();
1005 let transcript = transcript.to_str().unwrap();
1006
1007 assert_eq!(
1008 detect_current(Agent::Codex, f.project.path(), transcript),
1009 BillingMode::Gateway
1010 );
1011 assert_eq!(
1013 detect_current(Agent::Codex, f.project.path(), ""),
1014 BillingMode::Subscription
1015 );
1016 }
1017
1018 #[test]
1019 fn codex_env_overrides_make_a_login_ambiguous() {
1020 let f = Fixture::new()
1021 .home_file(".codex/auth.json", r#"{"auth_mode":"chatgpt"}"#)
1022 .env("CODEX_ACCESS_TOKEN", "t");
1023 assert_eq!(f.detect(Agent::Codex), BillingMode::Unknown);
1024
1025 let f = Fixture::new()
1027 .home_file(".codex/auth.json", r#"{"auth_mode":"chatgpt"}"#)
1028 .env("CODEX_API_KEY", "sk");
1029 assert_eq!(f.detect(Agent::Codex), BillingMode::Unknown);
1030 let f = Fixture::new()
1031 .home_file(
1032 ".codex/auth.json",
1033 r#"{"auth_mode":"apikey","OPENAI_API_KEY":"sk"}"#,
1034 )
1035 .env("CODEX_API_KEY", "sk");
1036 assert_eq!(f.detect(Agent::Codex), BillingMode::ApiKey);
1037 }
1038
1039 #[test]
1040 fn codex_malformed_files_are_unknown_not_an_error() {
1041 let f = Fixture::new()
1042 .home_file(".codex/auth.json", "{not json")
1043 .home_file(".codex/config.toml", "= broken")
1044 .rollout(json!({"type": "something_else"}));
1045 assert_eq!(f.detect(Agent::Codex), BillingMode::Unknown);
1046 }
1047
1048 #[test]
1051 fn agents_without_reliable_signals_are_unknown() {
1052 let f = Fixture::new()
1053 .home_file(".claude/.credentials.json", CLAUDE_OAUTH_CREDENTIALS)
1054 .home_file(".codex/auth.json", r#"{"auth_mode":"chatgpt"}"#)
1055 .env("ANTHROPIC_API_KEY", "sk");
1056 assert_eq!(f.detect(Agent::OpenCode), BillingMode::Unknown);
1057 assert_eq!(f.detect(Agent::Amp), BillingMode::Unknown);
1058 assert_eq!(f.detect(Agent::Gsd), BillingMode::Unknown);
1059 }
1060
1061 #[test]
1062 fn url_host_parsing() {
1063 assert_eq!(
1064 url_host("https://API.Anthropic.com/v1").as_deref(),
1065 Some("api.anthropic.com")
1066 );
1067 assert_eq!(
1068 url_host("http://user:pw@localhost:4000").as_deref(),
1069 Some("localhost")
1070 );
1071 assert_eq!(url_host("http://[::1]:4000/x").as_deref(), Some("::1"));
1072 assert_eq!(
1073 url_host("gw.example.com:8080").as_deref(),
1074 Some("gw.example.com")
1075 );
1076 assert_eq!(url_host("https://"), None);
1077 }
1078
1079 #[test]
1080 fn direct_provider_hosts() {
1081 for direct in [
1082 "https://api.openai.com/v1",
1083 "https://my-res.openai.azure.com/openai",
1084 "https://my-res.services.ai.azure.com",
1085 "https://us-east5-aiplatform.googleapis.com/v1",
1086 "https://bedrock-runtime.eu-west-1.amazonaws.com",
1087 "https://bedrock-runtime-fips.us-east-1.amazonaws.com",
1088 "https://vpce-0abc.bedrock-runtime.us-east-1.vpce.amazonaws.com",
1089 "https://bedrock-mantle.us-east-1.api.aws/openai/v1",
1090 ] {
1091 assert!(is_direct_provider_api(direct), "{direct}");
1092 }
1093 for gateway in [
1094 "http://localhost:4000",
1095 "https://litellm.example.com",
1096 "https://abc123.execute-api.eu-west-1.amazonaws.com/prod",
1097 "https://my-apim.azure-api.net/openai",
1098 "https://evilamazonaws.com/bedrock",
1099 "https://api.openai.com.evil.example",
1100 ] {
1101 assert!(!is_direct_provider_api(gateway), "{gateway}");
1102 }
1103 }
1104
1105 #[test]
1108 fn claude_helper_overridden_by_an_empty_higher_scope_value_is_off() {
1109 let f = Fixture::new()
1110 .home_file(".claude/.credentials.json", CLAUDE_OAUTH_CREDENTIALS)
1111 .home_file(
1112 ".claude/settings.json",
1113 r#"{"apiKeyHelper":"~/bin/key.sh"}"#,
1114 )
1115 .project_file(".claude/settings.local.json", r#"{"apiKeyHelper":""}"#)
1116 .env("ANTHROPIC_BASE_URL", "https://litellm.example.com");
1117 assert_eq!(f.detect(Agent::ClaudeCode), BillingMode::Subscription);
1118
1119 let f = Fixture::new()
1121 .home_file(
1122 ".claude/settings.json",
1123 r#"{"apiKeyHelper":"~/bin/key.sh"}"#,
1124 )
1125 .project_file(".claude/settings.local.json", r#"{"model":"opus"}"#);
1126 assert_eq!(f.detect(Agent::ClaudeCode), BillingMode::ApiKey);
1127 }
1128
1129 #[test]
1130 fn claude_bedrock_behind_aws_api_gateway_is_gateway() {
1131 let f = Fixture::new().env("CLAUDE_CODE_USE_BEDROCK", "1").env(
1132 "ANTHROPIC_BEDROCK_BASE_URL",
1133 "https://abc123.execute-api.eu-west-1.amazonaws.com/prod",
1134 );
1135 assert_eq!(f.detect(Agent::ClaudeCode), BillingMode::Gateway);
1136 }
1137
1138 #[test]
1139 fn codex_system_config_redirect_is_gateway() {
1140 let f = Fixture::new()
1141 .home_file(".codex/auth.json", r#"{"auth_mode":"chatgpt"}"#)
1142 .system_config("openai_base_url = \"https://gw.example.com/v1\"\n")
1143 .rollout(session_meta("openai"));
1144 assert_eq!(f.detect(Agent::Codex), BillingMode::Gateway);
1145 }
1146
1147 #[test]
1148 fn codex_config_layers_follow_codex_precedence() {
1149 let f = Fixture::new()
1151 .home_file(".codex/auth.json", r#"{"auth_mode":"chatgpt"}"#)
1152 .system_config("openai_base_url = \"https://gw.example.com/v1\"\n")
1153 .home_file(
1154 ".codex/config.toml",
1155 "openai_base_url = \"https://api.openai.com/v1\"\n",
1156 );
1157 assert_eq!(f.detect(Agent::Codex), BillingMode::Subscription);
1158
1159 let f = Fixture::new()
1161 .home_file(".codex/auth.json", r#"{"auth_mode":"chatgpt"}"#)
1162 .home_file(
1163 ".codex/config.toml",
1164 "openai_base_url = \"https://api.openai.com/v1\"\n",
1165 )
1166 .managed_codex_config("openai_base_url = \"https://gw.example.com/v1\"\n");
1167 assert_eq!(f.detect(Agent::Codex), BillingMode::Gateway);
1168 }
1169
1170 #[test]
1171 fn codex_legacy_profile_selects_the_provider() {
1172 let f = Fixture::new()
1173 .home_file(".codex/auth.json", r#"{"auth_mode":"chatgpt"}"#)
1174 .home_file(
1175 ".codex/config.toml",
1176 "profile = \"work\"\nmodel_provider = \"openai\"\n\
1177 [profiles.work]\nmodel_provider = \"litellm\"\n\
1178 [model_providers.litellm]\nbase_url = \"https://litellm.example.com\"\n",
1179 );
1180 assert_eq!(f.detect(Agent::Codex), BillingMode::Gateway);
1181 }
1182
1183 #[test]
1184 fn codex_provider_routing_wins_over_stored_bedrock_auth() {
1185 let f = Fixture::new()
1186 .home_file(".codex/auth.json", r#"{"auth_mode":"bedrockApiKey"}"#)
1187 .home_file(
1188 ".codex/config.toml",
1189 "[model_providers.litellm]\nbase_url = \"https://litellm.example.com\"\n",
1190 )
1191 .rollout(session_meta("litellm"));
1192 assert_eq!(f.detect(Agent::Codex), BillingMode::Gateway);
1193 }
1194
1195 #[test]
1196 fn codex_custom_provider_on_the_chatgpt_backend_uses_the_login() {
1197 let config = "[model_providers.chatgpt-alt]\nbase_url = \"https://chatgpt.com/backend-api/codex\"\nrequires_openai_auth = true\n";
1198 let f = Fixture::new()
1199 .home_file(".codex/auth.json", r#"{"auth_mode":"chatgpt"}"#)
1200 .home_file(".codex/config.toml", config)
1201 .rollout(session_meta("chatgpt-alt"));
1202 assert_eq!(f.detect(Agent::Codex), BillingMode::Subscription);
1203
1204 let f = Fixture::new()
1205 .home_file(".codex/config.toml", config)
1206 .rollout(session_meta("chatgpt-alt"));
1207 assert_eq!(f.detect(Agent::Codex), BillingMode::Unknown);
1208 }
1209
1210 #[test]
1211 fn codex_bedrock_default_endpoint_is_billed_directly() {
1212 let f = Fixture::new()
1213 .home_file(
1214 ".codex/config.toml",
1215 "[model_providers.amazon-bedrock]\nbase_url = \"https://bedrock-mantle.us-east-1.api.aws/openai/v1\"\n",
1216 )
1217 .rollout(session_meta("amazon-bedrock"));
1218 assert_eq!(f.detect(Agent::Codex), BillingMode::ApiKey);
1219 }
1220
1221 #[test]
1222 fn codex_custom_provider_behind_aws_api_gateway_is_gateway() {
1223 let f = Fixture::new()
1224 .home_file(
1225 ".codex/config.toml",
1226 "[model_providers.aws]\nbase_url = \"https://abc.execute-api.us-east-1.amazonaws.com/v1\"\n",
1227 )
1228 .rollout(session_meta("aws"));
1229 assert_eq!(f.detect(Agent::Codex), BillingMode::Gateway);
1230 }
1231}