aphrodite 1.3.8

aphrodite: Chat Completions proxy with CCR, tool relay, and programmatic CCR for Hermes agent integration.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
//! CLI configuration for aphrodite.
//!
//! Generic LLM proxy - works with any OpenAI-compatible API.
//! Cache and Token modes with CCR, tool relay, programmatic CCR.

use std::{net::SocketAddr, path::PathBuf};

use clap::{Parser, ValueEnum};

/// Resolve a boolean env var with one consistent truthiness rule across the
/// crate (report 07 F12): `"1"`/`"true"` (case-insensitive) is true,
/// anything else present (including `"0"`/`"false"`/empty string) or absent
/// is false. Previously this repo had three different ad-hoc conventions in
/// three places: `"true"/"1"` (the dead `config_loader`), `"1"` only
/// (Python's `APHRODITE_CONTEXT_ENGINE` check), and presence-only
/// (`APHRODITE_LOG_COMPACT=0` used to still enable compact logging, since
/// `.is_ok()` doesn't look at the value at all).
pub fn env_bool(var: &str) -> bool {
	match std::env::var(var) {
		Ok(v) => matches!(v.to_lowercase().as_str(), "1" | "true"),
		Err(_) => false,
	}
}

/// Parse a present env var, warning (not silently defaulting) if it fails to
/// parse as `T` - the bug class `Maintain/examples/01_env_var_typo.py`
/// documents and `MultiConfig::apply_port_override`'s comment explains
/// (report 07 F10/F15): a missing var is the unremarkable common case, but a
/// *present-and-malformed* one left an operator with no way to tell "my
/// override didn't apply" from "I didn't set an override". Single shared
/// implementation so every numeric env-var read in the crate uses the same
/// rule (report 07 ยง7 generalization note).
pub fn env_parse_warn<T: std::str::FromStr>(var: &str) -> Option<T> {
	match std::env::var(var) {
		Ok(v) => match v.parse::<T>() {
			Ok(parsed) => Some(parsed),
			Err(_) => {
				tracing::warn!("{}={:?} could not be parsed; ignoring override", var, v);
				None
			},
		},
		Err(_) => None,
	}
}

/// Proxy operation mode.
#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum ProxyMode {
	/// Cache mode - in-memory CCR, lightweight compression (>8KB threshold),
	/// preview preserved, no tool injection.
	Cache,
	/// Token mode - SQLite CCR, aggressive compression (>1KB threshold),
	/// tool injection, tool relay.
	Token,
}

/// aphrodite subcommands.
#[derive(clap::Subcommand, Debug, Clone)]
pub enum Command {
	/// Run the proxy server (default).
	Run,
	/// Bootstrap: copy binary, create config, register with hermes, launch
	/// proxy.
	Setup {
		/// API key for the upstream LLM provider (uses APHRODITE_API_KEY env).
		#[arg(long, env = "APHRODITE_API_KEY", hide_env_values = true)]
		api_key: Option<String>,

		/// Upstream API base URL.
		#[arg(long, env = "APHRODITE_API_URL", default_value = "https://api.deepseek.com")]
		api_url: String,

		/// Model name to forward.
		#[arg(long, env = "APHRODITE_MODEL", default_value = "deepseek-v4-pro")]
		model: String,

		/// Cache proxy listen port. Override per-instance to run multiple
		/// concurrent Hermes Agents on the same machine.
		#[arg(long, env = "APHRODITE_CACHE_PORT", default_value = "9797")]
		cache_port: u16,

		/// Token proxy listen port. Override per-instance to run multiple
		/// concurrent Hermes Agents on the same machine.
		#[arg(long, env = "APHRODITE_TOKEN_PORT", default_value = "9798")]
		token_port: u16,

		/// Skip launching the proxy after setup.
		#[arg(long)]
		no_launch: bool,

		/// Force re-setup even if already installed.
		#[arg(long)]
		force: bool,
	},
}

/// Arguments for the `setup` subcommand.
#[derive(Debug, Clone)]
pub struct SetupArgs {
	/// API key for the upstream LLM provider (uses APHRODITE_API_KEY env).
	pub api_key: Option<String>,
	/// Upstream API base URL.
	pub api_url: String,
	/// Model name to forward.
	pub model: String,
	/// Cache proxy listen port.
	pub cache_port: u16,
	/// Token proxy listen port.
	pub token_port: u16,
	/// Skip launching the proxy after setup.
	pub no_launch: bool,
	/// Force re-setup even if already installed.
	pub force: bool,
}

impl From<Command> for SetupArgs {
	fn from(cmd: Command) -> Self {
		match cmd {
			Command::Setup { api_key, api_url, model, cache_port, token_port, no_launch, force } => {
				Self { api_key, api_url, model, cache_port, token_port, no_launch, force }
			},
			_ => Self {
				api_key: None,
				api_url: "https://api.deepseek.com".into(),
				model: "deepseek-v4-pro".into(),
				cache_port: 9797,
				token_port: 9798,
				no_launch: false,
				force: false,
			},
		}
	}
}

/// aphrodite - generic LLM proxy with CCR, tool relay, and programmatic CCR.
/// Works with any OpenAI-compatible API (DeepSeek, OpenAI, Anthropic via proxy,
/// etc.)
#[derive(Parser, Debug, Clone)]
#[command(name = "aphrodite", version, about)]
pub struct Cli {
	/// Subcommand: `setup` to bootstrap, or omitted to run the proxy.
	#[command(subcommand)]
	pub command: Option<Command>,
	/// Proxy mode: cache or token
	#[arg(long, default_value = "token", env = "APHRODITE_MODE")]
	pub mode: ProxyMode,

	/// Listen address
	#[arg(long, default_value = "127.0.0.1:9797", env = "APHRODITE_LISTEN")]
	pub listen: SocketAddr,

	/// Upstream API base URL
	#[arg(long, default_value = "https://api.openai.com", env = "APHRODITE_API_URL")]
	pub api_url: String,

	/// Upstream API key (optional at parse time - `setup` and keyless
	/// launches don't require it; required only when a proxy must forward
	/// to an upstream). Empty string default so `aphrodite setup` and other
	/// subcommands parse without `--api-key`.
	#[arg(long, env = "APHRODITE_API_KEY", hide_env_values = true, default_value = "")]
	pub api_key: String,

	/// Model name to forward (set via APHRODITE_MODEL env or --model)
	#[arg(long, default_value = "default-model", env = "APHRODITE_MODEL")]
	pub model: String,

	/// Max context tokens
	#[arg(long, default_value = "1000000")]
	pub max_context: usize,

	/// Max output tokens
	#[arg(long, default_value = "384000")]
	pub max_output: usize,

	/// SQLite database path for CCR storage
	#[arg(long, env = "APHRODITE_DB")]
	pub ccr_db_path: Option<PathBuf>,

	/// CCR TTL in seconds (default: 3600 = 1 hour)
	#[arg(long, default_value = "3600", env = "APHRODITE_CCR_TTL")]
	pub ccr_ttl_seconds: u64,

	/// Disable CCR markers in compressed output
	#[arg(long)]
	pub no_ccr_marker: bool,

	/// Enable tool relay endpoint (POST /tool/relay)
	#[arg(long)]
	pub tool_relay: bool,

	/// Hermes callback URL for CCR notifications
	#[arg(long, env = "APHRODITE_NOTIFY_URL")]
	pub notify_url: Option<String>,

	/// Hermes API key for callback auth
	#[arg(long, env = "APHRODITE_NOTIFY_KEY", hide_env_values = true)]
	pub notify_key: Option<String>,

	/// Enable dev mode - verbose request/response logging
	#[arg(long)]
	pub dev: bool,

	/// Use compact log format (no timestamps, no targets)
	#[arg(long, env = "APHRODITE_LOG_COMPACT")]
	pub log_compact: bool,

	/// Upstream request timeout in seconds (default: 300)
	#[arg(long, default_value = "300")]
	pub timeout: u64,
}

/// Multi-proxy configuration loaded from aphrodite.toml.
#[derive(Debug, Clone, serde::Deserialize)]
pub struct MultiConfig {
	pub defaults: Option<Defaults>,
	pub proxies: Vec<ProxyConfig>,
	pub compression: Option<CompressionConfig>,
	pub previews: Option<PreviewsConfig>,
	pub prompts: Option<PromptsConfig>,
}

#[derive(Debug, Clone, serde::Deserialize)]
pub struct Defaults {
	pub api_url: Option<String>,
	pub model: Option<String>,
	pub ccr_ttl_seconds: Option<u64>,
	pub api_key: Option<String>,
}

/// Compression knobs - thresholds, engine, auto-expand, classifier poll.
#[derive(Debug, Clone, serde::Deserialize)]
pub struct CompressionConfig {
	pub engine_threshold_pct: Option<u32>,
	pub engine_protect_first: Option<u32>,
	pub engine_protect_last: Option<u32>,
	pub engine_min_msgs: Option<u32>,
	pub tool_threshold_token: Option<u32>,
	pub tool_threshold_cache: Option<u32>,
	pub terminal_threshold: Option<u32>,
	pub inline_threshold: Option<u32>,
	pub auto_expand: Option<bool>,
	pub auto_expand_limit: Option<u32>,
	pub catalog_mode: Option<String>,
	pub classifier_poll: Option<bool>,
	pub code_multiplier: Option<f64>,
}

/// Preview knobs - model-aware templates, code structure maps.
#[derive(Debug, Clone, serde::Deserialize)]
pub struct PreviewsConfig {
	pub model_family: Option<String>,
	pub code_structure_map: Option<bool>,
	pub preview_max_chars: Option<u32>,
	pub rust_preview_lines: Option<u32>,
}

/// Prompt knobs - how the system instructs the LLM about CCR.
#[derive(Debug, Clone, serde::Deserialize)]
pub struct PromptsConfig {
	pub retrieve_guidance: Option<String>,
	pub ccr_marker_hint: Option<bool>,
	pub catalog_intent_hints: Option<bool>,
}

#[derive(Debug, Clone, serde::Deserialize)]
pub struct ProxyConfig {
	pub name: Option<String>,
	#[serde(default)]
	pub listen: Option<String>,
	pub mode: Option<String>,
	pub api_key: Option<String>,
	pub api_url: Option<String>,
	pub model: Option<String>,
	pub tool_relay: Option<bool>,
	pub dev: Option<bool>,
	pub ccr_ttl_seconds: Option<u64>,
	pub ccr_db_path: Option<String>,
	pub notify_url: Option<String>,
	pub notify_key: Option<String>,
	pub timeout: Option<u64>,
	pub max_context: Option<usize>,
	pub max_output: Option<usize>,
}

impl MultiConfig {
	/// Load from the given aphrodite.toml path.
	pub fn load(path: &str) -> anyhow::Result<Self> {
		let content = std::fs::read_to_string(path)?;
		Ok(toml::from_str(&content)?)
	}

	/// Resolve a ProxyConfig with defaults applied.
	/// API key fallback chain: `proxy.api_key` โ†’ `defaults.api_key` โ†’
	/// `APHRODITE_API_KEY` โ†’ `DEEPSEEK_API_KEY` โ†’ `HEADROOM_DEEPSEEK_KEY`.
	/// Returns an error if no API key is found after all fallbacks.
	pub fn resolve(&self, cfg: &ProxyConfig) -> anyhow::Result<Cli> {
		let d = self.defaults.as_ref();
		let api_key: String = cfg
			// API key fallback chain: explicit config โ†’ APHRODITE_API_KEY โ†’ DEEPSEEK_API_KEY โ†’ HEADROOM_DEEPSEEK_KEY
		.api_key
			.clone()
			.or_else(|| d.and_then(|d| d.api_key.clone()))
			.or_else(|| std::env::var("APHRODITE_API_KEY").ok())
			.or_else(|| std::env::var("DEEPSEEK_API_KEY").ok())
			.or_else(|| std::env::var("HEADROOM_DEEPSEEK_KEY").ok())
			.unwrap_or_default();
		if api_key.is_empty() {
			anyhow::bail!("no API key configured - set APHRODITE_API_KEY env var or api_key in aphrodite.toml");
		}
		// Resolve listen: must parse or fail (no silent default when listen is
		// explicitly set).  After parsing, override with env var if set - this
		// lets multiple concurrent Hermes Agent instances each point at their
		// own proxy pair without editing aphrodite.toml.
		let listen: SocketAddr = match cfg.listen.as_deref() {
			Some(s) => s.parse().map_err(|_| anyhow::anyhow!("invalid listen address: {s}"))?,
			None => "127.0.0.1:9797".parse().unwrap(),
		};
		let listen = match (cfg.mode.as_deref(), cfg.name.as_deref()) {
			(_, Some("cache")) | (Some("cache"), _) => Self::apply_port_override(listen, "APHRODITE_CACHE_PORT"),
			(_, Some("token")) | (Some("token"), _) => Self::apply_port_override(listen, "APHRODITE_TOKEN_PORT"),
			_ => listen,
		};
		// Validate max_output < max_context
		let max_context = cfg.max_context.unwrap_or(1_000_000);
		let max_output = cfg.max_output.unwrap_or(384_000);
		if max_output >= max_context {
			anyhow::bail!("max_output ({max_output}) must be less than max_context ({max_context})");
		}
		Ok(Cli {
			command: None,
			mode: match cfg.mode.as_deref() {
				Some("token") => ProxyMode::Token,
				Some("cache") => ProxyMode::Cache,
				None => {
					tracing::info!("no mode specified, defaulting to token");
					ProxyMode::Token
				},
				Some(other) => {
					tracing::warn!("unknown mode {:?}, defaulting to token", other);
					ProxyMode::Token
				},
			},
			listen,
			// env > TOML (proxy > defaults) > hardcoded default (report 07
			// F1/T17) - previously only the API-key chain and the two port
			// vars pierced the TOML in this path, contradicting every shipped
			// TOML's own header comment ("Env vars override TOML values at
			// runtime"). `mode`/`listen` are deliberately NOT given a
			// blanket env override here: a single process-wide
			// `APHRODITE_MODE`/`APHRODITE_LISTEN` would incorrectly apply to
			// every `[[proxies]]` entry at once, breaking the cache/token
			// dual-proxy split that the existing per-mode
			// `APHRODITE_CACHE_PORT`/`APHRODITE_TOKEN_PORT` overrides above
			// are already careful to respect.
			api_url: std::env::var("APHRODITE_API_URL")
				.ok()
				.or_else(|| cfg.api_url.clone())
				.or_else(|| d.and_then(|d| d.api_url.clone()))
				.unwrap_or_else(|| "https://api.openai.com".into()),
			api_key,
			model: std::env::var("APHRODITE_MODEL")
				.ok()
				.or_else(|| cfg.model.clone())
				.or_else(|| d.and_then(|d| d.model.clone()))
				.unwrap_or_else(|| "default-model".into()),
			max_context,
			max_output,
			// Resolve from toml - proxy.rs handles None default
			ccr_db_path: std::env::var("APHRODITE_DB")
				.ok()
				.or_else(|| cfg.ccr_db_path.clone())
				.filter(|s| !s.is_empty())
				.map(Into::into),
			ccr_ttl_seconds: env_parse_warn::<u64>("APHRODITE_CCR_TTL")
				.or(cfg.ccr_ttl_seconds)
				.or_else(|| d.and_then(|d| d.ccr_ttl_seconds))
				.unwrap_or(3600),
			no_ccr_marker: false,
			tool_relay: cfg.tool_relay.unwrap_or(false),
			notify_url: std::env::var("APHRODITE_NOTIFY_URL").ok().or_else(|| cfg.notify_url.clone()),
			notify_key: std::env::var("APHRODITE_NOTIFY_KEY").ok().or_else(|| cfg.notify_key.clone()),
			dev: cfg.dev.unwrap_or(false),
			log_compact: false,
			timeout: {
				let t = cfg.timeout.unwrap_or(300);
				if t > 600 {
					tracing::warn!("timeout {}s exceeds maximum 600s, clamping", t);
					600
				} else {
					t
				}
			},
		})
	}

	/// Override `listen`'s port from the named env var, if set.
	///
	/// A missing env var is the common case and silently keeps `listen`
	/// unchanged. A *present but malformed* value (non-numeric, or outside
	/// the u16 port range) also keeps `listen` unchanged, but logs a
	/// warning - silently ignoring a typo'd override left the operator with
	/// no way to tell "my override didn't apply" from "I didn't set an
	/// override", the same silent-failure class as the missing-CCR-
	/// directory bug this override was added alongside.
	fn apply_port_override(listen: SocketAddr, env_var: &str) -> SocketAddr {
		match std::env::var(env_var) {
			Ok(p) => match p.parse::<u16>() {
				Ok(port) => {
					let mut addr = listen;
					addr.set_port(port);
					tracing::info!("{}={} overriding listen to {}", env_var, port, addr);
					addr
				},
				Err(_) => {
					tracing::warn!(
						"{}={:?} is not a valid port (1-65535); ignoring override, using {}",
						env_var,
						p,
						listen,
					);
					listen
				},
			},
			Err(_) => listen,
		}
	}
}

#[cfg(test)]
mod tests {
	use super::*;

	/// Serializes tests that touch process-global env vars
	/// (`APHRODITE_CACHE_PORT`/`APHRODITE_TOKEN_PORT`), since `cargo test`
	/// runs this module's tests concurrently by default.
	fn env_guard() -> std::sync::MutexGuard<'static, ()> {
		static G: std::sync::OnceLock<std::sync::Mutex<()>> = std::sync::OnceLock::new();
		G.get_or_init(|| std::sync::Mutex::new(()))
			.lock()
			.unwrap_or_else(std::sync::PoisonError::into_inner)
	}

	// โ”€โ”€ T10 (F12): one truthiness rule for boolean env vars everywhere. โ”€โ”€
	#[test]
	fn test_env_bool_true_values_case_insensitive() {
		let _g = env_guard();
		for v in ["1", "true", "TRUE", "True"] {
			std::env::set_var("APHRODITE_TEST_BOOL", v);
			assert!(env_bool("APHRODITE_TEST_BOOL"), "{v:?} should be true");
		}
		std::env::remove_var("APHRODITE_TEST_BOOL");
	}

	#[test]
	fn test_env_bool_false_values() {
		let _g = env_guard();
		for v in ["0", "false", "yes", ""] {
			std::env::set_var("APHRODITE_TEST_BOOL", v);
			assert!(!env_bool("APHRODITE_TEST_BOOL"), "{v:?} should be false");
		}
		std::env::remove_var("APHRODITE_TEST_BOOL");
		assert!(!env_bool("APHRODITE_TEST_BOOL"), "absent should be false");
	}

	fn multi_config_from_toml(toml_str: &str) -> MultiConfig {
		toml::from_str(toml_str).expect("valid test TOML")
	}

	#[test]
	fn test_resolve_default_ports_per_mode() {
		let _g = env_guard();
		std::env::remove_var("APHRODITE_CACHE_PORT");
		std::env::remove_var("APHRODITE_TOKEN_PORT");

		let mc = multi_config_from_toml(
			r#"
			[[proxies]]
			name = "cache"
			mode = "cache"
			api_key = "test-key"
			"#,
		);
		let cli = mc.resolve(&mc.proxies[0]).unwrap();
		assert_eq!(cli.listen.port(), 9797); // default listen, no override present

		let mc = multi_config_from_toml(
			r#"
			[[proxies]]
			name = "token"
			mode = "token"
			api_key = "test-key"
			"#,
		);
		let cli = mc.resolve(&mc.proxies[0]).unwrap();
		assert_eq!(cli.listen.port(), 9797); // still 9797: no explicit `listen` was set in the TOML
	}

	#[test]
	fn test_resolve_explicit_port_override_via_env() {
		let _g = env_guard();
		std::env::set_var("APHRODITE_CACHE_PORT", "19797");
		let mc = multi_config_from_toml(
			r#"
			[[proxies]]
			name = "cache"
			mode = "cache"
			api_key = "test-key"
			listen = "127.0.0.1:9797"
			"#,
		);
		let cli = mc.resolve(&mc.proxies[0]).unwrap();
		assert_eq!(cli.listen.port(), 19797);
		std::env::remove_var("APHRODITE_CACHE_PORT");
	}

	// โ”€โ”€ T17 (F1): env vars must override TOML values in multi-proxy mode,
	// matching every shipped TOML's own header comment ("Env vars
	// (APHRODITE_*) override TOML values at runtime") - previously only the
	// API-key chain and the two port vars actually did this. โ”€โ”€
	#[test]
	fn test_resolve_env_overrides_toml_for_api_url_model_ttl_db_notify() {
		let _g = env_guard();
		for (k, v) in [
			("APHRODITE_API_URL", "https://env-api.example.com"),
			("APHRODITE_MODEL", "env-model"),
			("APHRODITE_CCR_TTL", "42"),
			("APHRODITE_DB", "/tmp/env-ccr.db"),
			("APHRODITE_NOTIFY_URL", "https://env-notify.example.com"),
			("APHRODITE_NOTIFY_KEY", "env-notify-key"),
		] {
			std::env::set_var(k, v);
		}
		let mc = multi_config_from_toml(
			r#"
			[[proxies]]
			name = "token"
			mode = "token"
			api_key = "test-key"
			api_url = "https://toml-api.example.com"
			model = "toml-model"
			ccr_ttl_seconds = 111
			ccr_db_path = "/tmp/toml-ccr.db"
			notify_url = "https://toml-notify.example.com"
			notify_key = "toml-notify-key"
			"#,
		);
		let cli = mc.resolve(&mc.proxies[0]).unwrap();
		for k in [
			"APHRODITE_API_URL",
			"APHRODITE_MODEL",
			"APHRODITE_CCR_TTL",
			"APHRODITE_DB",
			"APHRODITE_NOTIFY_URL",
			"APHRODITE_NOTIFY_KEY",
		] {
			std::env::remove_var(k);
		}
		assert_eq!(cli.api_url, "https://env-api.example.com");
		assert_eq!(cli.model, "env-model");
		assert_eq!(cli.ccr_ttl_seconds, 42);
		assert_eq!(cli.ccr_db_path.unwrap().to_string_lossy(), "/tmp/env-ccr.db");
		assert_eq!(cli.notify_url.as_deref(), Some("https://env-notify.example.com"));
		assert_eq!(cli.notify_key.as_deref(), Some("env-notify-key"));
	}

	#[test]
	fn test_resolve_falls_back_to_toml_when_env_unset() {
		let _g = env_guard();
		for k in ["APHRODITE_API_URL", "APHRODITE_MODEL", "APHRODITE_CCR_TTL", "APHRODITE_DB"] {
			std::env::remove_var(k);
		}
		let mc = multi_config_from_toml(
			r#"
			[[proxies]]
			name = "token"
			mode = "token"
			api_key = "test-key"
			api_url = "https://toml-api.example.com"
			model = "toml-model"
			ccr_ttl_seconds = 111
			"#,
		);
		let cli = mc.resolve(&mc.proxies[0]).unwrap();
		assert_eq!(cli.api_url, "https://toml-api.example.com");
		assert_eq!(cli.model, "toml-model");
		assert_eq!(cli.ccr_ttl_seconds, 111);
	}

	#[test]
	fn test_resolve_invalid_mode_falls_back_to_token() {
		let mc = multi_config_from_toml(
			r#"
			[[proxies]]
			name = "weird"
			mode = "not_a_real_mode"
			api_key = "test-key"
			"#,
		);
		let cli = mc.resolve(&mc.proxies[0]).unwrap();
		assert!(matches!(cli.mode, ProxyMode::Token));
	}

	#[test]
	fn test_resolve_missing_mode_falls_back_to_token() {
		let mc = multi_config_from_toml(
			r#"
			[[proxies]]
			name = "no_mode"
			api_key = "test-key"
			"#,
		);
		let cli = mc.resolve(&mc.proxies[0]).unwrap();
		assert!(matches!(cli.mode, ProxyMode::Token));
	}

	#[test]
	fn test_resolve_timeout_clamped_to_600() {
		let mc = multi_config_from_toml(
			r#"
			[[proxies]]
			name = "slow"
			api_key = "test-key"
			timeout = 9999
			"#,
		);
		let cli = mc.resolve(&mc.proxies[0]).unwrap();
		assert_eq!(cli.timeout, 600);
	}

	#[test]
	fn test_resolve_timeout_under_max_is_unchanged() {
		let mc = multi_config_from_toml(
			r#"
			[[proxies]]
			name = "normal"
			api_key = "test-key"
			timeout = 120
			"#,
		);
		let cli = mc.resolve(&mc.proxies[0]).unwrap();
		assert_eq!(cli.timeout, 120);
	}

	#[test]
	fn test_resolve_missing_api_key_errors() {
		let _g = env_guard();
		std::env::remove_var("APHRODITE_API_KEY");
		std::env::remove_var("DEEPSEEK_API_KEY");
		std::env::remove_var("HEADROOM_DEEPSEEK_KEY");
		let mc = multi_config_from_toml(
			r#"
			[[proxies]]
			name = "no_key"
			"#,
		);
		let result = mc.resolve(&mc.proxies[0]);
		assert!(result.is_err());
	}

	#[test]
	fn test_resolve_invalid_listen_address_errors() {
		let mc = multi_config_from_toml(
			r#"
			[[proxies]]
			name = "bad_listen"
			api_key = "test-key"
			listen = "not-an-address"
			"#,
		);
		let result = mc.resolve(&mc.proxies[0]);
		assert!(result.is_err());
	}

	#[test]
	fn test_resolve_max_output_must_be_less_than_max_context() {
		let mc = multi_config_from_toml(
			r#"
			[[proxies]]
			name = "bad_budget"
			api_key = "test-key"
			max_context = 100
			max_output = 200
			"#,
		);
		let result = mc.resolve(&mc.proxies[0]);
		assert!(result.is_err());
	}

	#[test]
	fn test_resolve_defaults_fill_in_missing_proxy_fields() {
		// api_url/model are env-overridable since T17 - guard against the
		// process-global env vars racing with other tests in this module.
		let _g = env_guard();
		std::env::remove_var("APHRODITE_API_URL");
		std::env::remove_var("APHRODITE_MODEL");
		let mc = multi_config_from_toml(
			r#"
			[defaults]
			api_key = "default-key"
			api_url = "https://default.example.com"
			model = "default-model-name"

			[[proxies]]
			name = "uses_defaults"
			"#,
		);
		let cli = mc.resolve(&mc.proxies[0]).unwrap();
		assert_eq!(cli.api_key, "default-key");
		assert_eq!(cli.api_url, "https://default.example.com");
		assert_eq!(cli.model, "default-model-name");
	}
}