1use eyre::Result;
2use serde::{Deserialize, Serialize};
3use std::collections::BTreeMap;
4
5pub const DEFAULT_MAX_TURNS: usize = 100;
6
7pub const DEFAULT_AGGREGATOR_MAX_TOKENS: u64 = 16_384;
10
11#[derive(Serialize, Deserialize)]
12#[serde(deny_unknown_fields)]
13pub struct Config {
14 #[serde(skip_serializing_if = "Option::is_none")]
15 pub defaults: Option<DefaultsConfig>,
16 pub aggregator: AggregatorConfig,
17 pub reviewer: Vec<ReviewerConfig>,
18 #[serde(skip_serializing_if = "Option::is_none")]
21 pub presets: Option<BTreeMap<String, PresetConfig>>,
22}
23
24#[derive(Serialize, Deserialize)]
26#[serde(deny_unknown_fields)]
27pub struct PresetConfig {
28 pub prompt: String,
29}
30
31#[derive(Serialize, Deserialize)]
32#[serde(deny_unknown_fields)]
33pub struct DefaultsConfig {
34 #[serde(skip_serializing_if = "Option::is_none")]
35 pub debate: Option<bool>,
36 #[serde(skip_serializing_if = "Option::is_none")]
37 pub alloy: Option<bool>,
38 #[serde(skip_serializing_if = "Option::is_none")]
40 pub fallback: Option<bool>,
41 #[serde(skip_serializing_if = "Option::is_none")]
42 pub max_turns: Option<usize>,
43 #[serde(skip_serializing_if = "Option::is_none")]
44 pub compact_threshold: Option<u64>,
45 #[serde(skip_serializing_if = "Option::is_none")]
46 pub log_trajectories: Option<bool>,
47 #[serde(skip_serializing_if = "Option::is_none")]
50 pub presets: Option<Vec<String>>,
51}
52
53#[derive(Serialize, Deserialize)]
54#[serde(deny_unknown_fields)]
55pub struct AggregatorConfig {
56 #[serde(default)]
57 pub model: String,
58 pub provider: ProviderType,
59 #[serde(skip_serializing_if = "Option::is_none")]
60 pub base_url: Option<String>,
61 #[serde(skip_serializing_if = "Option::is_none")]
62 pub api_key_env: Option<String>,
63 #[serde(skip_serializing_if = "Option::is_none")]
64 pub max_tokens: Option<u64>,
65 #[serde(skip_serializing_if = "Option::is_none")]
66 pub auth: Option<String>,
67 #[serde(skip_serializing_if = "Option::is_none")]
69 pub azure_scope: Option<String>,
70 #[serde(skip_serializing_if = "Option::is_none")]
72 pub azure_credentials: Option<String>,
73}
74
75#[derive(Serialize, Deserialize)]
76#[serde(deny_unknown_fields)]
77pub struct ReviewerConfig {
78 #[serde(default)]
79 pub name: String,
80 #[serde(default)]
81 pub model: String,
82 pub provider: ProviderType,
83 #[serde(skip_serializing_if = "Option::is_none")]
84 pub base_url: Option<String>,
85 #[serde(skip_serializing_if = "Option::is_none")]
86 pub api_key_env: Option<String>,
87 #[serde(skip_serializing_if = "Option::is_none")]
89 pub max_tokens: Option<u64>,
90 #[serde(skip_serializing_if = "Option::is_none")]
91 pub compact_threshold: Option<u64>,
92 #[serde(skip_serializing_if = "Option::is_none")]
93 pub auth: Option<String>,
94 #[serde(skip_serializing_if = "Option::is_none")]
96 pub azure_scope: Option<String>,
97 #[serde(skip_serializing_if = "Option::is_none")]
99 pub azure_credentials: Option<String>,
100}
101
102pub(crate) struct ClientSettings<'a> {
106 pub(crate) provider: &'a ProviderType,
107 pub(crate) auth: Option<&'a str>,
108 pub(crate) base_url: Option<&'a str>,
109 pub(crate) api_key_env: Option<&'a str>,
110 pub(crate) azure_scope: Option<&'a str>,
111 pub(crate) azure_credentials: Option<&'a str>,
112}
113
114impl<'a> From<&'a ReviewerConfig> for ClientSettings<'a> {
115 fn from(reviewer: &'a ReviewerConfig) -> Self {
116 Self {
117 provider: &reviewer.provider,
118 auth: reviewer.auth.as_deref(),
119 base_url: reviewer.base_url.as_deref(),
120 api_key_env: reviewer.api_key_env.as_deref(),
121 azure_scope: reviewer.azure_scope.as_deref(),
122 azure_credentials: reviewer.azure_credentials.as_deref(),
123 }
124 }
125}
126
127impl<'a> From<&'a AggregatorConfig> for ClientSettings<'a> {
128 fn from(agg: &'a AggregatorConfig) -> Self {
129 Self {
130 provider: &agg.provider,
131 auth: agg.auth.as_deref(),
132 base_url: agg.base_url.as_deref(),
133 api_key_env: agg.api_key_env.as_deref(),
134 azure_scope: agg.azure_scope.as_deref(),
135 azure_credentials: agg.azure_credentials.as_deref(),
136 }
137 }
138}
139
140#[derive(Serialize, Deserialize)]
141pub enum ProviderType {
142 #[serde(rename = "anthropic", alias = "anthropic_compatible")]
143 Anthropic,
144 #[serde(rename = "gemini")]
145 Gemini,
146 #[serde(rename = "openai", alias = "openai_compatible")]
147 OpenAi,
148 #[serde(rename = "openrouter")]
149 OpenRouter,
150}
151
152impl ProviderType {
153 #[cfg(feature = "antigravity")]
155 pub fn is_gemini(&self) -> bool {
156 matches!(self, ProviderType::Gemini)
157 }
158}
159
160impl Config {
161 pub fn validate(&self) -> Result<()> {
162 self.validate_structure()?;
163 self.validate_credentials()
164 }
165
166 pub fn validate_structure(&self) -> Result<()> {
170 if self.reviewer.is_empty() {
171 eyre::bail!("no reviewers configured");
172 }
173
174 self.validate_alloy(self.default_alloy())?;
175 self.validate_fallback(self.default_fallback())?;
176
177 validate_free_model(
178 "[aggregator]",
179 &self.aggregator.provider,
180 &self.aggregator.model,
181 )?;
182
183 validate_auth(
187 "[aggregator]",
188 &self.aggregator.provider,
189 &self.aggregator.auth,
190 self.aggregator.base_url.as_deref(),
191 self.aggregator.api_key_env.as_deref(),
192 self.aggregator.azure_credentials.as_deref(),
193 )?;
194
195 for reviewer in &self.reviewer {
196 let reviewer_label = match reviewer.name.is_empty() {
197 true => "reviewer <unnamed>".to_string(),
198 false => format!("reviewer {}", reviewer.name),
199 };
200 validate_free_model(&reviewer_label, &reviewer.provider, &reviewer.model)?;
201 validate_auth(
202 &reviewer_label,
203 &reviewer.provider,
204 &reviewer.auth,
205 reviewer.base_url.as_deref(),
206 reviewer.api_key_env.as_deref(),
207 reviewer.azure_credentials.as_deref(),
208 )?;
209 if reviewer.compact_threshold == Some(0) {
210 eyre::bail!(
211 "reviewer {}: compact_threshold must be greater than 0",
212 reviewer.name
213 );
214 }
215 if reviewer.max_tokens == Some(0) {
216 eyre::bail!(
217 "reviewer {}: max_tokens must be greater than 0",
218 reviewer.name
219 );
220 }
221 }
222
223 if self.aggregator.max_tokens == Some(0) {
224 eyre::bail!("[aggregator].max_tokens must be greater than 0");
225 }
226
227 if self.defaults.as_ref().and_then(|d| d.compact_threshold) == Some(0) {
228 eyre::bail!("[defaults].compact_threshold must be greater than 0");
229 }
230
231 validate_presets(self.presets.as_ref())?;
232
233 Ok(())
234 }
235
236 pub fn default_debate(&self) -> bool {
237 self.defaults
238 .as_ref()
239 .and_then(|d| d.debate)
240 .unwrap_or(true)
241 }
242
243 pub fn validate_alloy(&self, alloy: bool) -> Result<()> {
244 if alloy && self.reviewer.len() < 2 {
245 eyre::bail!(
246 "--alloy requires at least 2 reviewers, found {}",
247 self.reviewer.len()
248 );
249 }
250 Ok(())
251 }
252
253 pub fn validate_credentials(&self) -> Result<()> {
256 if let Some(env) = required_env_var(ClientSettings::from(&self.aggregator)) {
257 check_env_var(env)
258 .map_err(|_| eyre::eyre!("[aggregator]: env var {env} is not set"))?;
259 }
260 for reviewer in &self.reviewer {
261 if let Some(env) = required_env_var(ClientSettings::from(reviewer)) {
262 check_env_var(env).map_err(|_| {
263 eyre::eyre!("reviewer {}: env var {env} is not set", reviewer.name)
264 })?;
265 }
266 }
267 Ok(())
268 }
269
270 pub fn default_alloy(&self) -> bool {
271 self.defaults
272 .as_ref()
273 .and_then(|d| d.alloy)
274 .unwrap_or(false)
275 }
276
277 pub fn validate_fallback(&self, fallback: bool) -> Result<()> {
278 if fallback && self.reviewer.len() < 2 {
279 eyre::bail!(
280 "fallback = true / --fallback requires at least 2 reviewers, found {}",
281 self.reviewer.len()
282 );
283 }
284 Ok(())
285 }
286
287 pub fn default_fallback(&self) -> bool {
288 self.defaults
289 .as_ref()
290 .and_then(|d| d.fallback)
291 .unwrap_or(false)
292 }
293
294 pub fn max_turns(&self, override_max_turns: Option<usize>) -> Result<usize> {
295 match override_max_turns {
296 Some(max_turns) => Ok(max_turns),
297 None => self.default_max_turns(),
298 }
299 }
300
301 pub fn default_max_turns(&self) -> Result<usize> {
302 let max_turns = self
303 .defaults
304 .as_ref()
305 .and_then(|d| d.max_turns)
306 .unwrap_or(DEFAULT_MAX_TURNS);
307
308 if max_turns == 0 {
309 eyre::bail!("[defaults].max_turns must be greater than 0");
310 }
311
312 Ok(max_turns)
313 }
314
315 pub fn default_compact_threshold(&self) -> Option<u64> {
316 self.defaults.as_ref().and_then(|d| d.compact_threshold)
317 }
318
319 pub fn log_trajectories(&self) -> bool {
320 self.defaults
321 .as_ref()
322 .and_then(|d| d.log_trajectories)
323 .unwrap_or(false)
324 }
325
326 pub fn aggregator_max_tokens(&self) -> u64 {
327 self.aggregator
328 .max_tokens
329 .unwrap_or(DEFAULT_AGGREGATOR_MAX_TOKENS)
330 }
331
332 pub fn reviewer_compact_threshold(&self, reviewer: &ReviewerConfig) -> Option<u64> {
333 reviewer
334 .compact_threshold
335 .or(self.default_compact_threshold())
336 }
337}
338
339fn validate_presets(presets: Option<&BTreeMap<String, PresetConfig>>) -> Result<()> {
340 let presets = match presets {
341 Some(presets) => presets,
342 None => return Ok(()),
343 };
344 for (name, preset) in presets {
345 if name.trim().is_empty() {
346 eyre::bail!("[presets]: preset names must contain non-whitespace content");
347 }
348 if name != name.trim() {
351 eyre::bail!("[presets.{name:?}]: preset names must not have surrounding whitespace");
352 }
353 if name.chars().any(char::is_control) {
356 eyre::bail!("[presets.{name:?}]: preset names must not contain control characters");
357 }
358 if preset.prompt.trim().is_empty() {
359 eyre::bail!("[presets.{name}].prompt must contain non-whitespace content");
360 }
361 }
362 Ok(())
363}
364
365fn validate_free_model(label: &str, provider: &ProviderType, model: &str) -> Result<()> {
366 if model == "free" && !matches!(provider, ProviderType::OpenRouter) {
367 eyre::bail!("{label}: model = \"free\" is only supported with provider = \"openrouter\"");
368 }
369
370 Ok(())
371}
372
373fn validate_auth(
374 label: &str,
375 provider: &ProviderType,
376 auth: &Option<String>,
377 base_url: Option<&str>,
378 api_key_env: Option<&str>,
379 azure_credentials: Option<&str>,
380) -> Result<()> {
381 match (provider, auth.as_deref()) {
382 (_, None) => Ok(()),
384 (ProviderType::Gemini, Some("oauth")) => {
385 eyre::bail!(
386 "{label}: auth = \"oauth\" has been removed — use auth = \"agy-keyring\" (see README) or unset `auth` to use GEMINI_API_KEY"
387 );
388 }
389 (ProviderType::Gemini, Some("agy-keyring")) => {
392 if !cfg!(feature = "antigravity") {
393 eyre::bail!(
394 "{label}: auth = \"agy-keyring\" requires building nitpicker with `--features antigravity`"
395 );
396 }
397 Ok(())
398 }
399 (ProviderType::Gemini, Some(other)) => {
400 eyre::bail!(
401 "{label}: unknown auth value \"{other}\" — expected \"agy-keyring\" or unset"
402 );
403 }
404 (ProviderType::OpenAi | ProviderType::Anthropic, Some("azure-ad")) => {
407 if !cfg!(feature = "azure") {
408 eyre::bail!(
409 "{label}: auth = \"azure-ad\" requires building nitpicker with `--features azure`"
410 );
411 }
412 validate_azure_fields(label, base_url, azure_credentials)
413 }
414 (_, Some("azure-ad")) => {
415 eyre::bail!(
416 "{label}: auth = \"azure-ad\" is only supported with provider \"openai\" or \"anthropic\""
417 );
418 }
419 (ProviderType::OpenAi, Some("codex")) => {
424 if base_url.is_some() {
425 eyre::bail!(
426 "{label}: auth = \"codex\" ignores `base_url` (requests always go to the Codex endpoint) — remove it"
427 );
428 }
429 if api_key_env.is_some() {
430 eyre::bail!(
431 "{label}: auth = \"codex\" ignores `api_key_env` (the token comes from ~/.codex/auth.json) — remove it"
432 );
433 }
434 Ok(())
435 }
436 (_, Some("codex")) => {
437 eyre::bail!("{label}: auth = \"codex\" is only supported with provider \"openai\"");
438 }
439 (_, Some(other)) => {
442 eyre::bail!("{label}: unknown auth value \"{other}\"");
443 }
444 }
445}
446
447fn validate_azure_fields(
451 label: &str,
452 base_url: Option<&str>,
453 azure_credentials: Option<&str>,
454) -> Result<()> {
455 if base_url.map(str::trim).filter(|u| !u.is_empty()).is_none() {
456 eyre::bail!(
457 "{label}: auth = \"azure-ad\" requires a non-empty `base_url` (the Azure Foundry endpoint)"
458 );
459 }
460 match azure_credentials {
465 Some(mode) => validate_azure_credentials_mode(label, "azure_credentials", mode)?,
466 None => {
467 if let Ok(env_mode) = std::env::var("AZURE_TOKEN_CREDENTIALS") {
468 validate_azure_credentials_mode(label, "AZURE_TOKEN_CREDENTIALS", &env_mode)?;
469 }
470 }
471 }
472 Ok(())
473}
474
475fn validate_azure_credentials_mode(label: &str, source: &str, mode: &str) -> Result<()> {
480 let normalized = mode.trim().to_ascii_lowercase();
481 if !normalized.is_empty() && !matches!(normalized.as_str(), "dev" | "prod" | "auto") {
482 eyre::bail!(
483 "{label}: unknown {source} value \"{mode}\" — expected \"dev\", \"prod\", or unset (\"auto\")"
484 );
485 }
486 Ok(())
487}
488
489fn check_env_var(name: &str) -> Result<(), std::env::VarError> {
490 if name == "GEMINI_API_KEY" {
492 if std::env::var("GEMINI_API_KEY").is_ok() || std::env::var("GOOGLE_AI_API_KEY").is_ok() {
493 return Ok(());
494 }
495 return Err(std::env::VarError::NotPresent);
496 }
497 std::env::var(name).map(|_| ())
498}
499
500fn is_local_server(base_url: Option<&str>) -> bool {
501 base_url
502 .map(|u| u.starts_with("http://localhost") || u.starts_with("http://127.0.0.1"))
503 .unwrap_or(false)
504}
505
506fn required_env_var<'a>(settings: ClientSettings<'a>) -> Option<&'a str> {
507 if matches!(settings.provider, ProviderType::Gemini) && is_gemini_proxy_auth(settings.auth) {
508 return None;
509 }
510 if is_azure_ad_auth(settings.auth) {
511 return None;
512 }
513 if is_codex_auth(settings.auth) {
514 return None;
515 }
516 if is_local_server(settings.base_url) {
517 return None;
518 }
519 if let Some(env) = settings.api_key_env {
520 return Some(env);
521 }
522 default_env_var(settings.provider)
523}
524
525fn is_gemini_proxy_auth(auth: Option<&str>) -> bool {
526 matches!(auth, Some("agy-keyring"))
527}
528
529pub fn is_azure_ad_auth(auth: Option<&str>) -> bool {
532 matches!(auth, Some("azure-ad"))
533}
534
535pub fn is_codex_auth(auth: Option<&str>) -> bool {
537 matches!(auth, Some("codex"))
538}
539
540fn default_env_var(provider: &ProviderType) -> Option<&'static str> {
541 match provider {
542 ProviderType::Anthropic => Some("ANTHROPIC_API_KEY"),
543 ProviderType::Gemini => Some("GEMINI_API_KEY"),
544 ProviderType::OpenAi => Some("OPENAI_API_KEY"),
545 ProviderType::OpenRouter => Some("OPENROUTER_API_KEY"),
546 }
547}
548
549#[cfg(test)]
550mod tests {
551 use super::*;
552
553 const FOUNDRY_URL: &str = "https://res.services.ai.azure.com/openai/v1";
554
555 #[test]
556 fn azure_ad_auth_detection() {
557 assert!(is_azure_ad_auth(Some("azure-ad")));
558 assert!(!is_azure_ad_auth(Some("agy-keyring")));
559 assert!(!is_azure_ad_auth(None));
560 }
561
562 #[test]
563 fn validate_auth_rejects_azure_ad_on_unsupported_providers() {
564 let auth = Some("azure-ad".to_string());
565 assert!(validate_auth("[t]", &ProviderType::Gemini, &auth, None, None, None).is_err());
566 assert!(validate_auth("[t]", &ProviderType::OpenRouter, &auth, None, None, None).is_err());
567 }
568
569 #[test]
570 fn validate_auth_azure_ad_on_supported_providers() {
571 let auth = Some("azure-ad".to_string());
572 let creds = Some("auto");
575 let openai = validate_auth(
576 "[t]",
577 &ProviderType::OpenAi,
578 &auth,
579 Some(FOUNDRY_URL),
580 None,
581 creds,
582 );
583 let anthropic = validate_auth(
584 "[t]",
585 &ProviderType::Anthropic,
586 &auth,
587 Some(FOUNDRY_URL),
588 None,
589 creds,
590 );
591 if cfg!(feature = "azure") {
594 assert!(openai.is_ok());
595 assert!(anthropic.is_ok());
596 } else {
597 assert!(openai.is_err());
598 assert!(anthropic.is_err());
599 }
600 }
601
602 #[test]
603 fn validate_auth_allows_unset_and_known_values() {
604 assert!(validate_auth("[t]", &ProviderType::OpenAi, &None, None, None, None).is_ok());
605 let agy = validate_auth(
608 "[t]",
609 &ProviderType::Gemini,
610 &Some("agy-keyring".to_string()),
611 None,
612 None,
613 None,
614 );
615 if cfg!(feature = "antigravity") {
616 assert!(agy.is_ok());
617 } else {
618 assert!(agy.is_err());
619 }
620 }
621
622 #[test]
623 fn validate_auth_codex_rejects_ignored_fields() {
624 let auth = Some("codex".to_string());
625 assert!(validate_auth("[t]", &ProviderType::OpenAi, &auth, None, None, None).is_ok());
627 assert!(
629 validate_auth(
630 "[t]",
631 &ProviderType::OpenAi,
632 &auth,
633 Some("https://example.com"),
634 None,
635 None,
636 )
637 .is_err()
638 );
639 assert!(
640 validate_auth(
641 "[t]",
642 &ProviderType::OpenAi,
643 &auth,
644 None,
645 Some("MY_KEY"),
646 None,
647 )
648 .is_err()
649 );
650 }
651
652 #[test]
653 fn codex_auth_detection() {
654 assert!(is_codex_auth(Some("codex")));
655 assert!(!is_codex_auth(Some("azure-ad")));
656 assert!(!is_codex_auth(None));
657 }
658
659 #[test]
660 fn validate_auth_codex_only_on_openai() {
661 let auth = Some("codex".to_string());
662 assert!(validate_auth("[t]", &ProviderType::OpenAi, &auth, None, None, None).is_ok());
663 assert!(validate_auth("[t]", &ProviderType::Anthropic, &auth, None, None, None).is_err());
664 assert!(validate_auth("[t]", &ProviderType::Gemini, &auth, None, None, None).is_err());
665 assert!(validate_auth("[t]", &ProviderType::OpenRouter, &auth, None, None, None).is_err());
666 }
667
668 fn config_with(reviewer_max_tokens: Option<u64>, aggregator_max_tokens: Option<u64>) -> Config {
670 Config {
671 defaults: None,
672 aggregator: AggregatorConfig {
673 model: "gpt-5.4".to_string(),
674 provider: ProviderType::OpenAi,
675 base_url: None,
676 api_key_env: None,
677 max_tokens: aggregator_max_tokens,
678 auth: Some("codex".to_string()),
679 azure_scope: None,
680 azure_credentials: None,
681 },
682 reviewer: vec![ReviewerConfig {
683 name: "r".to_string(),
684 model: "gpt-5.4".to_string(),
685 provider: ProviderType::OpenAi,
686 base_url: None,
687 api_key_env: None,
688 max_tokens: reviewer_max_tokens,
689 compact_threshold: None,
690 auth: Some("codex".to_string()),
691 azure_scope: None,
692 azure_credentials: None,
693 }],
694 presets: None,
695 }
696 }
697
698 #[test]
700 fn zero_max_tokens_is_rejected_on_both_entities() {
701 assert!(config_with(None, None).validate().is_ok());
702 assert!(config_with(Some(0), None).validate().is_err());
703 assert!(config_with(None, Some(0)).validate().is_err());
704 }
705
706 #[test]
707 fn fallback_default_is_opt_in_and_requires_a_next_reviewer() {
708 let mut config = config_with(None, None);
709 assert!(!config.default_fallback());
710 config.defaults = Some(DefaultsConfig {
711 debate: None,
712 alloy: None,
713 fallback: Some(true),
714 max_turns: None,
715 compact_threshold: None,
716 log_trajectories: None,
717 presets: None,
718 });
719 assert!(config.default_fallback());
720 assert!(config.validate().is_err());
721
722 config.reviewer.push(ReviewerConfig {
723 name: "r2".to_string(),
724 model: "gpt-5.4".to_string(),
725 provider: ProviderType::OpenAi,
726 base_url: None,
727 api_key_env: None,
728 max_tokens: None,
729 compact_threshold: None,
730 auth: Some("codex".to_string()),
731 azure_scope: None,
732 azure_credentials: None,
733 });
734 assert!(config.validate().is_ok());
735 }
736
737 #[test]
738 fn structural_validation_defers_missing_route_credentials() {
739 let mut config = config_with(None, None);
740 config.aggregator.auth = None;
741 config.aggregator.api_key_env =
742 Some("NITPICKER_TEST_MISSING_AGGREGATOR_CREDENTIAL_FOR_FALLBACK_7C51".to_string());
743
744 assert!(config.validate_structure().is_ok());
745 let err = config.validate_credentials().unwrap_err();
746 assert!(format!("{err:#}").contains("env var"));
747 assert!(config.validate().is_err());
748 }
749
750 #[test]
751 fn codex_auth_requires_no_env_var() {
752 let reviewer = ReviewerConfig {
753 name: "r".to_string(),
754 model: "gpt-5.4".to_string(),
755 provider: ProviderType::OpenAi,
756 base_url: None,
757 api_key_env: None,
758 max_tokens: None,
759 compact_threshold: None,
760 auth: Some("codex".to_string()),
761 azure_scope: None,
762 azure_credentials: None,
763 };
764 assert_eq!(required_env_var(ClientSettings::from(&reviewer)), None);
765 let agg = AggregatorConfig {
766 model: "gpt-5.4".to_string(),
767 provider: ProviderType::OpenAi,
768 base_url: None,
769 api_key_env: None,
770 max_tokens: None,
771 auth: Some("codex".to_string()),
772 azure_scope: None,
773 azure_credentials: None,
774 };
775 assert_eq!(required_env_var(ClientSettings::from(&agg)), None);
776 }
777
778 #[test]
783 fn required_env_var_branch_table_and_precedence() {
784 fn provider(name: &str) -> ProviderType {
785 match name {
786 "anthropic" => ProviderType::Anthropic,
787 "gemini" => ProviderType::Gemini,
788 "openai" => ProviderType::OpenAi,
789 "openrouter" => ProviderType::OpenRouter,
790 other => panic!("unknown provider in table: {other}"),
791 }
792 }
793
794 #[rustfmt::skip]
797 let rows = [
798 ("gemini", Some("agy-keyring"), None, None, None),
799 ("gemini", Some("agy-keyring"), None, Some("EXPLICIT"), None),
800 ("openai", Some("agy-keyring"), None, None, Some("OPENAI_API_KEY")),
802 ("openai", Some("azure-ad"), Some("https://f.example/v1"), Some("EXPLICIT"), None),
803 ("openai", Some("codex"), None, Some("EXPLICIT"), None),
804 ("openai", None, Some("http://localhost:1234/v1"), Some("EXPLICIT"), None),
805 ("openai", None, Some("http://127.0.0.1:1234/v1"), None, None),
806 ("anthropic", None, Some("https://gw.example"), Some("EXPLICIT"), Some("EXPLICIT")),
808 ("anthropic", None, None, None, Some("ANTHROPIC_API_KEY")),
809 ("gemini", None, None, None, Some("GEMINI_API_KEY")),
810 ("openai", None, None, None, Some("OPENAI_API_KEY")),
811 ("openrouter", None, None, None, Some("OPENROUTER_API_KEY")),
812 ];
813
814 for (name, auth, base_url, api_key_env, expected) in rows {
815 let reviewer = ReviewerConfig {
816 name: String::new(),
817 model: String::new(),
818 provider: provider(name),
819 base_url: base_url.map(str::to_string),
820 api_key_env: api_key_env.map(str::to_string),
821 max_tokens: None,
822 compact_threshold: None,
823 auth: auth.map(str::to_string),
824 azure_scope: None,
825 azure_credentials: None,
826 };
827 let agg = AggregatorConfig {
828 model: String::new(),
829 provider: provider(name),
830 base_url: base_url.map(str::to_string),
831 api_key_env: api_key_env.map(str::to_string),
832 max_tokens: None,
833 auth: auth.map(str::to_string),
834 azure_scope: None,
835 azure_credentials: None,
836 };
837 for (role, settings) in [
838 ("reviewer", ClientSettings::from(&reviewer)),
839 ("aggregator", ClientSettings::from(&agg)),
840 ] {
841 assert_eq!(
842 required_env_var(settings),
843 expected,
844 "{role}: {name} auth={auth:?} base_url={base_url:?} api_key_env={api_key_env:?}"
845 );
846 }
847 }
848 }
849
850 #[test]
851 fn validate_auth_rejects_unknown_value_on_non_gemini() {
852 let typo = Some("azure_ad".to_string());
854 assert!(
855 validate_auth(
856 "[t]",
857 &ProviderType::OpenAi,
858 &typo,
859 Some(FOUNDRY_URL),
860 None,
861 None
862 )
863 .is_err()
864 );
865 assert!(validate_auth("[t]", &ProviderType::Anthropic, &typo, None, None, None).is_err());
866 }
867
868 #[cfg(feature = "azure")]
869 #[test]
870 fn validate_auth_azure_ad_requires_base_url() {
871 let auth = Some("azure-ad".to_string());
872 assert!(validate_auth("[t]", &ProviderType::OpenAi, &auth, None, None, None).is_err());
876 assert!(validate_auth("[t]", &ProviderType::OpenAi, &auth, Some(""), None, None).is_err());
877 assert!(
878 validate_auth(
879 "[t]",
880 &ProviderType::OpenAi,
881 &auth,
882 Some(FOUNDRY_URL),
883 None,
884 Some("auto")
885 )
886 .is_ok()
887 );
888 }
889
890 #[test]
891 fn validate_azure_credentials_mode_rejects_unknown_only() {
892 assert!(validate_azure_credentials_mode("[t]", "azure_credentials", "dev").is_ok());
894 assert!(validate_azure_credentials_mode("[t]", "azure_credentials", "PROD").is_ok());
895 assert!(validate_azure_credentials_mode("[t]", "azure_credentials", "auto").is_ok());
896 assert!(validate_azure_credentials_mode("[t]", "azure_credentials", "").is_ok());
898 assert!(validate_azure_credentials_mode("[t]", "azure_credentials", " ").is_ok());
899 let err = validate_azure_credentials_mode("[t]", "AZURE_TOKEN_CREDENTIALS", "bogus")
902 .unwrap_err()
903 .to_string();
904 assert!(err.contains("AZURE_TOKEN_CREDENTIALS"), "got: {err}");
905 assert!(err.contains("bogus"), "got: {err}");
906 }
907
908 #[cfg(feature = "azure")]
909 #[test]
910 fn validate_auth_azure_ad_validates_credentials() {
911 let auth = Some("azure-ad".to_string());
912 let ok = |creds| {
913 validate_auth(
914 "[t]",
915 &ProviderType::OpenAi,
916 &auth,
917 Some(FOUNDRY_URL),
918 None,
919 creds,
920 )
921 .is_ok()
922 };
923 assert!(ok(Some("auto")));
928 assert!(ok(Some("dev")));
929 assert!(ok(Some("PROD"))); assert!(ok(Some("auto")));
931 assert!(
932 validate_auth(
933 "[t]",
934 &ProviderType::OpenAi,
935 &auth,
936 Some(FOUNDRY_URL),
937 None,
938 Some("deve")
939 )
940 .is_err()
941 );
942 }
943
944 #[test]
948 fn preset_tables_reject_blank_and_padded_names_and_blank_prompts() {
949 let table = |name: &str, prompt: &str| {
950 let mut presets = BTreeMap::new();
951 presets.insert(
952 name.to_string(),
953 PresetConfig {
954 prompt: prompt.to_string(),
955 },
956 );
957 presets
958 };
959 assert!(validate_presets(None).is_ok());
960 assert!(validate_presets(Some(&table("tone", "review the docs"))).is_ok());
961 assert!(validate_presets(Some(&table(" tone", "review the docs"))).is_err());
962 assert!(validate_presets(Some(&table(" ", "review the docs"))).is_err());
963 assert!(validate_presets(Some(&table("tone", " "))).is_err());
964 }
965
966 #[test]
969 fn preset_tables_reject_control_bytes_in_names() {
970 let table = |name: &str| {
971 let mut presets = BTreeMap::new();
972 presets.insert(
973 name.to_string(),
974 PresetConfig {
975 prompt: "review the docs".to_string(),
976 },
977 );
978 presets
979 };
980 for name in [
981 "esc\u{1b}]0;pwn\u{7}",
982 "csi\u{9b}31m",
983 "tab\tname",
984 "nl\nname",
985 ] {
986 let err = validate_presets(Some(&table(name))).expect_err("control bytes rejected");
987 assert!(
988 format!("{err:#}").contains("control characters"),
989 "wrong error for {name:?}: {err:#}"
990 );
991 }
992 }
993}