Skip to main content

nitpicker_agent/
config.rs

1use eyre::Result;
2use serde::{Deserialize, Serialize};
3
4pub const DEFAULT_MAX_TURNS: usize = 100;
5
6#[derive(Serialize, Deserialize)]
7#[serde(deny_unknown_fields)]
8pub struct Config {
9    #[serde(skip_serializing_if = "Option::is_none")]
10    pub defaults: Option<DefaultsConfig>,
11    pub aggregator: AggregatorConfig,
12    pub reviewer: Vec<ReviewerConfig>,
13}
14
15#[derive(Serialize, Deserialize)]
16#[serde(deny_unknown_fields)]
17pub struct DefaultsConfig {
18    #[serde(skip_serializing_if = "Option::is_none")]
19    pub debate: Option<bool>,
20    #[serde(skip_serializing_if = "Option::is_none")]
21    pub alloy: Option<bool>,
22    #[serde(skip_serializing_if = "Option::is_none")]
23    pub max_turns: Option<usize>,
24    #[serde(skip_serializing_if = "Option::is_none")]
25    pub compact_threshold: Option<u64>,
26    #[serde(skip_serializing_if = "Option::is_none")]
27    pub log_trajectories: Option<bool>,
28}
29
30#[derive(Serialize, Deserialize)]
31#[serde(deny_unknown_fields)]
32pub struct AggregatorConfig {
33    #[serde(default)]
34    pub model: String,
35    pub provider: ProviderType,
36    #[serde(skip_serializing_if = "Option::is_none")]
37    pub base_url: Option<String>,
38    #[serde(skip_serializing_if = "Option::is_none")]
39    pub api_key_env: Option<String>,
40    #[serde(skip_serializing_if = "Option::is_none")]
41    pub max_tokens: Option<u64>,
42    #[serde(skip_serializing_if = "Option::is_none")]
43    pub auth: Option<String>,
44    /// AAD scope for `auth = "azure-ad"` (defaults to the Cognitive Services scope).
45    #[serde(skip_serializing_if = "Option::is_none")]
46    pub azure_scope: Option<String>,
47    /// Azure credential chain selector for `auth = "azure-ad"`: `"dev"`, `"prod"`, or unset.
48    #[serde(skip_serializing_if = "Option::is_none")]
49    pub azure_credentials: Option<String>,
50}
51
52#[derive(Serialize, Deserialize)]
53#[serde(deny_unknown_fields)]
54pub struct ReviewerConfig {
55    #[serde(default)]
56    pub name: String,
57    #[serde(default)]
58    pub model: String,
59    pub provider: ProviderType,
60    #[serde(skip_serializing_if = "Option::is_none")]
61    pub base_url: Option<String>,
62    #[serde(skip_serializing_if = "Option::is_none")]
63    pub api_key_env: Option<String>,
64    #[serde(skip_serializing_if = "Option::is_none")]
65    pub compact_threshold: Option<u64>,
66    #[serde(skip_serializing_if = "Option::is_none")]
67    pub auth: Option<String>,
68    /// AAD scope for `auth = "azure-ad"` (defaults to the Cognitive Services scope).
69    #[serde(skip_serializing_if = "Option::is_none")]
70    pub azure_scope: Option<String>,
71    /// Azure credential chain selector for `auth = "azure-ad"`: `"dev"`, `"prod"`, or unset.
72    #[serde(skip_serializing_if = "Option::is_none")]
73    pub azure_credentials: Option<String>,
74}
75
76#[derive(Serialize, Deserialize)]
77pub enum ProviderType {
78    #[serde(rename = "anthropic", alias = "anthropic_compatible")]
79    Anthropic,
80    #[serde(rename = "gemini")]
81    Gemini,
82    #[serde(rename = "openai", alias = "openai_compatible")]
83    OpenAi,
84    #[serde(rename = "openrouter")]
85    OpenRouter,
86}
87
88impl ProviderType {
89    // only consulted by the antigravity-gated gemini-proxy predicates in provider.rs
90    #[cfg(feature = "antigravity")]
91    pub fn is_gemini(&self) -> bool {
92        matches!(self, ProviderType::Gemini)
93    }
94}
95
96impl Config {
97    pub fn validate(&self) -> Result<()> {
98        if self.reviewer.is_empty() {
99            eyre::bail!("no reviewers configured");
100        }
101
102        self.validate_alloy(self.default_alloy())?;
103
104        validate_free_model(
105            "[aggregator]",
106            &self.aggregator.provider,
107            &self.aggregator.model,
108        )?;
109
110        // Validate `auth` before the env-var check (matching the reviewer loop below): an unknown
111        // auth value like the typo `azure_ad` should surface its own clear error rather than being
112        // masked by a missing-API-key error when the provider key happens to be unset.
113        validate_auth(
114            "[aggregator]",
115            &self.aggregator.provider,
116            &self.aggregator.auth,
117            self.aggregator.base_url.as_deref(),
118            self.aggregator.api_key_env.as_deref(),
119            self.aggregator.azure_credentials.as_deref(),
120        )?;
121
122        if let Some(env) = required_env_var_aggregator(&self.aggregator) {
123            check_env_var(env)
124                .map_err(|_| eyre::eyre!("[aggregator]: env var {env} is not set"))?;
125        }
126
127        for reviewer in &self.reviewer {
128            let reviewer_label = match reviewer.name.is_empty() {
129                true => "reviewer <unnamed>".to_string(),
130                false => format!("reviewer {}", reviewer.name),
131            };
132            validate_free_model(&reviewer_label, &reviewer.provider, &reviewer.model)?;
133            validate_auth(
134                &reviewer_label,
135                &reviewer.provider,
136                &reviewer.auth,
137                reviewer.base_url.as_deref(),
138                reviewer.api_key_env.as_deref(),
139                reviewer.azure_credentials.as_deref(),
140            )?;
141            if let Some(env) = required_env_var_reviewer(reviewer) {
142                check_env_var(env).map_err(|_| {
143                    eyre::eyre!("reviewer {}: env var {env} is not set", reviewer.name)
144                })?;
145            }
146            if reviewer.compact_threshold == Some(0) {
147                eyre::bail!(
148                    "reviewer {}: compact_threshold must be greater than 0",
149                    reviewer.name
150                );
151            }
152        }
153
154        if self.defaults.as_ref().and_then(|d| d.compact_threshold) == Some(0) {
155            eyre::bail!("[defaults].compact_threshold must be greater than 0");
156        }
157
158        Ok(())
159    }
160
161    pub fn default_debate(&self) -> bool {
162        self.defaults
163            .as_ref()
164            .and_then(|d| d.debate)
165            .unwrap_or(true)
166    }
167
168    pub fn validate_alloy(&self, alloy: bool) -> Result<()> {
169        if alloy && self.reviewer.len() < 2 {
170            eyre::bail!("--alloy requires at least 2 reviewers, found {}", self.reviewer.len());
171        }
172        Ok(())
173    }
174
175    pub fn default_alloy(&self) -> bool {
176        self.defaults
177            .as_ref()
178            .and_then(|d| d.alloy)
179            .unwrap_or(false)
180    }
181
182    pub fn max_turns(&self, override_max_turns: Option<usize>) -> Result<usize> {
183        match override_max_turns {
184            Some(max_turns) => Ok(max_turns),
185            None => self.default_max_turns(),
186        }
187    }
188
189    pub fn default_max_turns(&self) -> Result<usize> {
190        let max_turns = self
191            .defaults
192            .as_ref()
193            .and_then(|d| d.max_turns)
194            .unwrap_or(DEFAULT_MAX_TURNS);
195
196        if max_turns == 0 {
197            eyre::bail!("[defaults].max_turns must be greater than 0");
198        }
199
200        Ok(max_turns)
201    }
202
203    pub fn default_compact_threshold(&self) -> Option<u64> {
204        self.defaults.as_ref().and_then(|d| d.compact_threshold)
205    }
206
207    pub fn log_trajectories(&self) -> bool {
208        self.defaults
209            .as_ref()
210            .and_then(|d| d.log_trajectories)
211            .unwrap_or(false)
212    }
213
214    pub fn reviewer_compact_threshold(&self, reviewer: &ReviewerConfig) -> Option<u64> {
215        reviewer
216            .compact_threshold
217            .or(self.default_compact_threshold())
218    }
219}
220
221fn validate_free_model(label: &str, provider: &ProviderType, model: &str) -> Result<()> {
222    if model == "free" && !matches!(provider, ProviderType::OpenRouter) {
223        eyre::bail!("{label}: model = \"free\" is only supported with provider = \"openrouter\"");
224    }
225
226    Ok(())
227}
228
229fn validate_auth(
230    label: &str,
231    provider: &ProviderType,
232    auth: &Option<String>,
233    base_url: Option<&str>,
234    api_key_env: Option<&str>,
235    azure_credentials: Option<&str>,
236) -> Result<()> {
237    match (provider, auth.as_deref()) {
238        // Unset auth is always fine — providers fall back to their default env-var key.
239        (_, None) => Ok(()),
240        (ProviderType::Gemini, Some("oauth")) => {
241            eyre::bail!(
242                "{label}: auth = \"oauth\" has been removed — use auth = \"agy-keyring\" (see README) or unset `auth` to use GEMINI_API_KEY"
243            );
244        }
245        // agy-keyring routes through the local Gemini proxy, gated behind the `antigravity`
246        // feature (mirrors the azure-ad gate below).
247        (ProviderType::Gemini, Some("agy-keyring")) => {
248            if !cfg!(feature = "antigravity") {
249                eyre::bail!(
250                    "{label}: auth = \"agy-keyring\" requires building nitpicker with `--features antigravity`"
251                );
252            }
253            Ok(())
254        }
255        (ProviderType::Gemini, Some(other)) => {
256            eyre::bail!(
257                "{label}: unknown auth value \"{other}\" — expected \"agy-keyring\" or unset"
258            );
259        }
260        // Azure AD is only meaningful for the OpenAI/Anthropic Foundry passthrough endpoints,
261        // and only works when the `azure` feature was compiled in.
262        (ProviderType::OpenAi | ProviderType::Anthropic, Some("azure-ad")) => {
263            if !cfg!(feature = "azure") {
264                eyre::bail!(
265                    "{label}: auth = \"azure-ad\" requires building nitpicker with `--features azure`"
266                );
267            }
268            validate_azure_fields(label, base_url, azure_credentials)
269        }
270        (_, Some("azure-ad")) => {
271            eyre::bail!(
272                "{label}: auth = \"azure-ad\" is only supported with provider \"openai\" or \"anthropic\""
273            );
274        }
275        // Codex/ChatGPT subscription auth reuses the OpenAI Responses endpoint, so it only makes
276        // sense for the OpenAI provider; the token comes from `~/.codex/auth.json`, not an env var.
277        // Client construction returns the fixed shared CodexClient and ignores base_url/api_key_env,
278        // so reject them rather than silently dropping a configured endpoint or key.
279        (ProviderType::OpenAi, Some("codex")) => {
280            if base_url.is_some() {
281                eyre::bail!(
282                    "{label}: auth = \"codex\" ignores `base_url` (requests always go to the Codex endpoint) — remove it"
283                );
284            }
285            if api_key_env.is_some() {
286                eyre::bail!(
287                    "{label}: auth = \"codex\" ignores `api_key_env` (the token comes from ~/.codex/auth.json) — remove it"
288                );
289            }
290            Ok(())
291        }
292        (_, Some("codex")) => {
293            eyre::bail!(
294                "{label}: auth = \"codex\" is only supported with provider \"openai\""
295            );
296        }
297        // Any other auth value on a non-Gemini provider is a typo or unsupported — reject it at
298        // config time rather than failing cryptically at client construction.
299        (_, Some(other)) => {
300            eyre::bail!("{label}: unknown auth value \"{other}\"");
301        }
302    }
303}
304
305/// Validate the mandatory `auth = "azure-ad"` fields at config time so a typo fails fast here
306/// instead of at the first LLM call. Mirrors the runtime checks in `azure::build_azure_client`
307/// (base_url) and `azure::build_credential_chain` (azure_credentials).
308fn validate_azure_fields(
309    label: &str,
310    base_url: Option<&str>,
311    azure_credentials: Option<&str>,
312) -> Result<()> {
313    if base_url.map(str::trim).filter(|u| !u.is_empty()).is_none() {
314        eyre::bail!(
315            "{label}: auth = \"azure-ad\" requires a non-empty `base_url` (the Azure Foundry endpoint)"
316        );
317    }
318    // Validate whichever credential mode the runtime would actually use. `build_credential_chain`
319    // resolves explicit config first, then the `AZURE_TOKEN_CREDENTIALS` env var — so a bogus env
320    // value (with `azure_credentials` unset) would otherwise pass config validation and only fail
321    // at the first LLM call. Mirror that fallback here so it fails fast too.
322    match azure_credentials {
323        Some(mode) => validate_azure_credentials_mode(label, "azure_credentials", mode)?,
324        None => {
325            if let Ok(env_mode) = std::env::var("AZURE_TOKEN_CREDENTIALS") {
326                validate_azure_credentials_mode(label, "AZURE_TOKEN_CREDENTIALS", &env_mode)?;
327            }
328        }
329    }
330    Ok(())
331}
332
333/// Reject an unknown Azure credential-chain selector. Empty/whitespace is allowed: the runtime
334/// (`build_credential_chain`) treats it as unset and falls back to `"auto"`. `source` names where
335/// the value came from so the error points at the right place (the `azure_credentials` config field
336/// vs the `AZURE_TOKEN_CREDENTIALS` env var).
337fn validate_azure_credentials_mode(label: &str, source: &str, mode: &str) -> Result<()> {
338    let normalized = mode.trim().to_ascii_lowercase();
339    if !normalized.is_empty() && !matches!(normalized.as_str(), "dev" | "prod" | "auto") {
340        eyre::bail!(
341            "{label}: unknown {source} value \"{mode}\" — expected \"dev\", \"prod\", or unset (\"auto\")"
342        );
343    }
344    Ok(())
345}
346
347fn check_env_var(name: &str) -> Result<(), std::env::VarError> {
348    // gemini accepts either GEMINI_API_KEY or GOOGLE_AI_API_KEY
349    if name == "GEMINI_API_KEY" {
350        if std::env::var("GEMINI_API_KEY").is_ok() || std::env::var("GOOGLE_AI_API_KEY").is_ok() {
351            return Ok(());
352        }
353        return Err(std::env::VarError::NotPresent);
354    }
355    std::env::var(name).map(|_| ())
356}
357
358fn is_local_server(base_url: Option<&str>) -> bool {
359    base_url
360        .map(|u| u.starts_with("http://localhost") || u.starts_with("http://127.0.0.1"))
361        .unwrap_or(false)
362}
363
364fn required_env_var_reviewer(reviewer: &ReviewerConfig) -> Option<&str> {
365    if matches!(reviewer.provider, ProviderType::Gemini) && is_gemini_proxy_auth(&reviewer.auth) {
366        return None;
367    }
368    if is_azure_ad_auth(reviewer.auth.as_deref()) {
369        return None;
370    }
371    if is_codex_auth(reviewer.auth.as_deref()) {
372        return None;
373    }
374    if is_local_server(reviewer.base_url.as_deref()) {
375        return None;
376    }
377    if let Some(env) = &reviewer.api_key_env {
378        return Some(env.as_str());
379    }
380    default_env_var(&reviewer.provider)
381}
382
383fn required_env_var_aggregator(agg: &AggregatorConfig) -> Option<&str> {
384    if matches!(agg.provider, ProviderType::Gemini) && is_gemini_proxy_auth(&agg.auth) {
385        return None;
386    }
387    if is_azure_ad_auth(agg.auth.as_deref()) {
388        return None;
389    }
390    if is_codex_auth(agg.auth.as_deref()) {
391        return None;
392    }
393    if is_local_server(agg.base_url.as_deref()) {
394        return None;
395    }
396    if let Some(env) = &agg.api_key_env {
397        return Some(env.as_str());
398    }
399    default_env_var(&agg.provider)
400}
401
402fn is_gemini_proxy_auth(auth: &Option<String>) -> bool {
403    matches!(auth.as_deref(), Some("agy-keyring"))
404}
405
406/// Canonical check shared with `provider.rs` (the client-build path), kept here next to the
407/// config types so validation and construction can't drift apart.
408pub fn is_azure_ad_auth(auth: Option<&str>) -> bool {
409    matches!(auth, Some("azure-ad"))
410}
411
412/// Codex/ChatGPT subscription auth. Canonical check shared with `provider.rs`.
413pub fn is_codex_auth(auth: Option<&str>) -> bool {
414    matches!(auth, Some("codex"))
415}
416
417fn default_env_var(provider: &ProviderType) -> Option<&'static str> {
418    match provider {
419        ProviderType::Anthropic => Some("ANTHROPIC_API_KEY"),
420        ProviderType::Gemini => Some("GEMINI_API_KEY"),
421        ProviderType::OpenAi => Some("OPENAI_API_KEY"),
422        ProviderType::OpenRouter => Some("OPENROUTER_API_KEY"),
423    }
424}
425
426#[cfg(test)]
427mod tests {
428    use super::*;
429
430    const FOUNDRY_URL: &str = "https://res.services.ai.azure.com/openai/v1";
431
432    #[test]
433    fn azure_ad_auth_detection() {
434        assert!(is_azure_ad_auth(Some("azure-ad")));
435        assert!(!is_azure_ad_auth(Some("agy-keyring")));
436        assert!(!is_azure_ad_auth(None));
437    }
438
439    #[test]
440    fn validate_auth_rejects_azure_ad_on_unsupported_providers() {
441        let auth = Some("azure-ad".to_string());
442        assert!(validate_auth("[t]", &ProviderType::Gemini, &auth, None, None, None).is_err());
443        assert!(validate_auth("[t]", &ProviderType::OpenRouter, &auth, None, None, None).is_err());
444    }
445
446    #[test]
447    fn validate_auth_azure_ad_on_supported_providers() {
448        let auth = Some("azure-ad".to_string());
449        // Pass an explicit credential mode so the assertion can't depend on an ambient
450        // `AZURE_TOKEN_CREDENTIALS` (which `None` would make `validate_azure_fields` read).
451        let creds = Some("auto");
452        let openai = validate_auth(
453            "[t]",
454            &ProviderType::OpenAi,
455            &auth,
456            Some(FOUNDRY_URL),
457            None,
458            creds,
459        );
460        let anthropic = validate_auth(
461            "[t]",
462            &ProviderType::Anthropic,
463            &auth,
464            Some(FOUNDRY_URL),
465            None,
466            creds,
467        );
468        // Accepted only when compiled with the `azure` feature; otherwise validation fails fast
469        // with a build hint.
470        if cfg!(feature = "azure") {
471            assert!(openai.is_ok());
472            assert!(anthropic.is_ok());
473        } else {
474            assert!(openai.is_err());
475            assert!(anthropic.is_err());
476        }
477    }
478
479    #[test]
480    fn validate_auth_allows_unset_and_known_values() {
481        assert!(validate_auth("[t]", &ProviderType::OpenAi, &None, None, None, None).is_ok());
482        // agy-keyring is accepted only when compiled with the `antigravity` feature; otherwise
483        // validation fails fast with a build hint (mirrors the azure gate).
484        let agy = validate_auth(
485            "[t]",
486            &ProviderType::Gemini,
487            &Some("agy-keyring".to_string()),
488            None,
489            None,
490            None,
491        );
492        if cfg!(feature = "antigravity") {
493            assert!(agy.is_ok());
494        } else {
495            assert!(agy.is_err());
496        }
497    }
498
499    #[test]
500    fn validate_auth_codex_rejects_ignored_fields() {
501        let auth = Some("codex".to_string());
502        // bare codex auth is fine
503        assert!(validate_auth("[t]", &ProviderType::OpenAi, &auth, None, None, None).is_ok());
504        // base_url / api_key_env would be silently dropped, so they must be rejected
505        assert!(
506            validate_auth(
507                "[t]",
508                &ProviderType::OpenAi,
509                &auth,
510                Some("https://example.com"),
511                None,
512                None,
513            )
514            .is_err()
515        );
516        assert!(
517            validate_auth(
518                "[t]",
519                &ProviderType::OpenAi,
520                &auth,
521                None,
522                Some("MY_KEY"),
523                None,
524            )
525            .is_err()
526        );
527    }
528
529    #[test]
530    fn codex_auth_detection() {
531        assert!(is_codex_auth(Some("codex")));
532        assert!(!is_codex_auth(Some("azure-ad")));
533        assert!(!is_codex_auth(None));
534    }
535
536    #[test]
537    fn validate_auth_codex_only_on_openai() {
538        let auth = Some("codex".to_string());
539        assert!(validate_auth("[t]", &ProviderType::OpenAi, &auth, None, None, None).is_ok());
540        assert!(validate_auth("[t]", &ProviderType::Anthropic, &auth, None, None, None).is_err());
541        assert!(validate_auth("[t]", &ProviderType::Gemini, &auth, None, None, None).is_err());
542        assert!(validate_auth("[t]", &ProviderType::OpenRouter, &auth, None, None, None).is_err());
543    }
544
545    #[test]
546    fn codex_auth_requires_no_env_var() {
547        let reviewer = ReviewerConfig {
548            name: "r".to_string(),
549            model: "gpt-5.4".to_string(),
550            provider: ProviderType::OpenAi,
551            base_url: None,
552            api_key_env: None,
553            compact_threshold: None,
554            auth: Some("codex".to_string()),
555            azure_scope: None,
556            azure_credentials: None,
557        };
558        assert_eq!(required_env_var_reviewer(&reviewer), None);
559        let agg = AggregatorConfig {
560            model: "gpt-5.4".to_string(),
561            provider: ProviderType::OpenAi,
562            base_url: None,
563            api_key_env: None,
564            max_tokens: None,
565            auth: Some("codex".to_string()),
566            azure_scope: None,
567            azure_credentials: None,
568        };
569        assert_eq!(required_env_var_aggregator(&agg), None);
570    }
571
572    #[test]
573    fn validate_auth_rejects_unknown_value_on_non_gemini() {
574        // Typos like `azure_ad`/`Azure-AD` must fail at config time, not at client construction.
575        let typo = Some("azure_ad".to_string());
576        assert!(
577            validate_auth(
578                "[t]",
579                &ProviderType::OpenAi,
580                &typo,
581                Some(FOUNDRY_URL),
582                None,
583                None
584            )
585            .is_err()
586        );
587        assert!(validate_auth("[t]", &ProviderType::Anthropic, &typo, None, None, None).is_err());
588    }
589
590    #[cfg(feature = "azure")]
591    #[test]
592    fn validate_auth_azure_ad_requires_base_url() {
593        let auth = Some("azure-ad".to_string());
594        // The two error cases bail on `base_url` before any credential check, so they're already
595        // env-independent; the ok case passes an explicit mode so it doesn't read the ambient
596        // `AZURE_TOKEN_CREDENTIALS` (which a `None` here would).
597        assert!(validate_auth("[t]", &ProviderType::OpenAi, &auth, None, None, None).is_err());
598        assert!(validate_auth("[t]", &ProviderType::OpenAi, &auth, Some(""), None, None).is_err());
599        assert!(
600            validate_auth(
601                "[t]",
602                &ProviderType::OpenAi,
603                &auth,
604                Some(FOUNDRY_URL),
605                None,
606                Some("auto")
607            )
608            .is_ok()
609        );
610    }
611
612    #[test]
613    fn validate_azure_credentials_mode_rejects_unknown_only() {
614        // Known modes pass (case/whitespace normalized like the runtime chain builder).
615        assert!(validate_azure_credentials_mode("[t]", "azure_credentials", "dev").is_ok());
616        assert!(validate_azure_credentials_mode("[t]", "azure_credentials", "PROD").is_ok());
617        assert!(validate_azure_credentials_mode("[t]", "azure_credentials", "auto").is_ok());
618        // Empty/whitespace is treated as unset (runtime falls back to "auto"), so it's allowed.
619        assert!(validate_azure_credentials_mode("[t]", "azure_credentials", "").is_ok());
620        assert!(validate_azure_credentials_mode("[t]", "azure_credentials", "   ").is_ok());
621        // A bogus value is rejected, and the message names the source so a config with no
622        // `azure_credentials` field but a bad env var points the user at the env var.
623        let err = validate_azure_credentials_mode("[t]", "AZURE_TOKEN_CREDENTIALS", "bogus")
624            .unwrap_err()
625            .to_string();
626        assert!(err.contains("AZURE_TOKEN_CREDENTIALS"), "got: {err}");
627        assert!(err.contains("bogus"), "got: {err}");
628    }
629
630    #[cfg(feature = "azure")]
631    #[test]
632    fn validate_auth_azure_ad_validates_credentials() {
633        let auth = Some("azure-ad".to_string());
634        let ok = |creds| {
635            validate_auth(
636                "[t]",
637                &ProviderType::OpenAi,
638                &auth,
639                Some(FOUNDRY_URL),
640                None,
641                creds,
642            )
643            .is_ok()
644        };
645        // Use explicit modes only — `None` would make validation read the ambient
646        // `AZURE_TOKEN_CREDENTIALS`, so a developer/CI with a bogus value set would fail spuriously.
647        // The "unset falls back to auto" behavior is covered hermetically by
648        // `validate_azure_credentials_mode_rejects_unknown_only` (empty string is accepted).
649        assert!(ok(Some("auto")));
650        assert!(ok(Some("dev")));
651        assert!(ok(Some("PROD"))); // case/whitespace normalized like the runtime chain builder
652        assert!(ok(Some("auto")));
653        assert!(
654            validate_auth(
655                "[t]",
656                &ProviderType::OpenAi,
657                &auth,
658                Some(FOUNDRY_URL),
659                None,
660                Some("deve")
661            )
662            .is_err()
663        );
664    }
665}