1use eyre::Result;
2use serde::{Deserialize, Serialize};
3
4pub const DEFAULT_MAX_TURNS: usize = 100;
5
6pub const DEFAULT_AGGREGATOR_MAX_TOKENS: u64 = 16_384;
9
10#[derive(Serialize, Deserialize)]
11#[serde(deny_unknown_fields)]
12pub struct Config {
13 #[serde(skip_serializing_if = "Option::is_none")]
14 pub defaults: Option<DefaultsConfig>,
15 pub aggregator: AggregatorConfig,
16 pub reviewer: Vec<ReviewerConfig>,
17}
18
19#[derive(Serialize, Deserialize)]
20#[serde(deny_unknown_fields)]
21pub struct DefaultsConfig {
22 #[serde(skip_serializing_if = "Option::is_none")]
23 pub debate: Option<bool>,
24 #[serde(skip_serializing_if = "Option::is_none")]
25 pub alloy: Option<bool>,
26 #[serde(skip_serializing_if = "Option::is_none")]
27 pub max_turns: Option<usize>,
28 #[serde(skip_serializing_if = "Option::is_none")]
29 pub compact_threshold: Option<u64>,
30 #[serde(skip_serializing_if = "Option::is_none")]
31 pub log_trajectories: Option<bool>,
32}
33
34#[derive(Serialize, Deserialize)]
35#[serde(deny_unknown_fields)]
36pub struct AggregatorConfig {
37 #[serde(default)]
38 pub model: String,
39 pub provider: ProviderType,
40 #[serde(skip_serializing_if = "Option::is_none")]
41 pub base_url: Option<String>,
42 #[serde(skip_serializing_if = "Option::is_none")]
43 pub api_key_env: Option<String>,
44 #[serde(skip_serializing_if = "Option::is_none")]
45 pub max_tokens: Option<u64>,
46 #[serde(skip_serializing_if = "Option::is_none")]
47 pub auth: Option<String>,
48 #[serde(skip_serializing_if = "Option::is_none")]
50 pub azure_scope: Option<String>,
51 #[serde(skip_serializing_if = "Option::is_none")]
53 pub azure_credentials: Option<String>,
54}
55
56#[derive(Serialize, Deserialize)]
57#[serde(deny_unknown_fields)]
58pub struct ReviewerConfig {
59 #[serde(default)]
60 pub name: String,
61 #[serde(default)]
62 pub model: String,
63 pub provider: ProviderType,
64 #[serde(skip_serializing_if = "Option::is_none")]
65 pub base_url: Option<String>,
66 #[serde(skip_serializing_if = "Option::is_none")]
67 pub api_key_env: Option<String>,
68 #[serde(skip_serializing_if = "Option::is_none")]
70 pub max_tokens: Option<u64>,
71 #[serde(skip_serializing_if = "Option::is_none")]
72 pub compact_threshold: Option<u64>,
73 #[serde(skip_serializing_if = "Option::is_none")]
74 pub auth: Option<String>,
75 #[serde(skip_serializing_if = "Option::is_none")]
77 pub azure_scope: Option<String>,
78 #[serde(skip_serializing_if = "Option::is_none")]
80 pub azure_credentials: Option<String>,
81}
82
83#[derive(Serialize, Deserialize)]
84pub enum ProviderType {
85 #[serde(rename = "anthropic", alias = "anthropic_compatible")]
86 Anthropic,
87 #[serde(rename = "gemini")]
88 Gemini,
89 #[serde(rename = "openai", alias = "openai_compatible")]
90 OpenAi,
91 #[serde(rename = "openrouter")]
92 OpenRouter,
93}
94
95impl ProviderType {
96 #[cfg(feature = "antigravity")]
98 pub fn is_gemini(&self) -> bool {
99 matches!(self, ProviderType::Gemini)
100 }
101}
102
103impl Config {
104 pub fn validate(&self) -> Result<()> {
105 if self.reviewer.is_empty() {
106 eyre::bail!("no reviewers configured");
107 }
108
109 self.validate_alloy(self.default_alloy())?;
110
111 validate_free_model(
112 "[aggregator]",
113 &self.aggregator.provider,
114 &self.aggregator.model,
115 )?;
116
117 validate_auth(
121 "[aggregator]",
122 &self.aggregator.provider,
123 &self.aggregator.auth,
124 self.aggregator.base_url.as_deref(),
125 self.aggregator.api_key_env.as_deref(),
126 self.aggregator.azure_credentials.as_deref(),
127 )?;
128
129 if let Some(env) = required_env_var_aggregator(&self.aggregator) {
130 check_env_var(env)
131 .map_err(|_| eyre::eyre!("[aggregator]: env var {env} is not set"))?;
132 }
133
134 for reviewer in &self.reviewer {
135 let reviewer_label = match reviewer.name.is_empty() {
136 true => "reviewer <unnamed>".to_string(),
137 false => format!("reviewer {}", reviewer.name),
138 };
139 validate_free_model(&reviewer_label, &reviewer.provider, &reviewer.model)?;
140 validate_auth(
141 &reviewer_label,
142 &reviewer.provider,
143 &reviewer.auth,
144 reviewer.base_url.as_deref(),
145 reviewer.api_key_env.as_deref(),
146 reviewer.azure_credentials.as_deref(),
147 )?;
148 if let Some(env) = required_env_var_reviewer(reviewer) {
149 check_env_var(env).map_err(|_| {
150 eyre::eyre!("reviewer {}: env var {env} is not set", reviewer.name)
151 })?;
152 }
153 if reviewer.compact_threshold == Some(0) {
154 eyre::bail!(
155 "reviewer {}: compact_threshold must be greater than 0",
156 reviewer.name
157 );
158 }
159 if reviewer.max_tokens == Some(0) {
160 eyre::bail!(
161 "reviewer {}: max_tokens must be greater than 0",
162 reviewer.name
163 );
164 }
165 }
166
167 if self.aggregator.max_tokens == Some(0) {
168 eyre::bail!("[aggregator].max_tokens must be greater than 0");
169 }
170
171 if self.defaults.as_ref().and_then(|d| d.compact_threshold) == Some(0) {
172 eyre::bail!("[defaults].compact_threshold must be greater than 0");
173 }
174
175 Ok(())
176 }
177
178 pub fn default_debate(&self) -> bool {
179 self.defaults
180 .as_ref()
181 .and_then(|d| d.debate)
182 .unwrap_or(true)
183 }
184
185 pub fn validate_alloy(&self, alloy: bool) -> Result<()> {
186 if alloy && self.reviewer.len() < 2 {
187 eyre::bail!(
188 "--alloy requires at least 2 reviewers, found {}",
189 self.reviewer.len()
190 );
191 }
192 Ok(())
193 }
194
195 pub fn default_alloy(&self) -> bool {
196 self.defaults
197 .as_ref()
198 .and_then(|d| d.alloy)
199 .unwrap_or(false)
200 }
201
202 pub fn max_turns(&self, override_max_turns: Option<usize>) -> Result<usize> {
203 match override_max_turns {
204 Some(max_turns) => Ok(max_turns),
205 None => self.default_max_turns(),
206 }
207 }
208
209 pub fn default_max_turns(&self) -> Result<usize> {
210 let max_turns = self
211 .defaults
212 .as_ref()
213 .and_then(|d| d.max_turns)
214 .unwrap_or(DEFAULT_MAX_TURNS);
215
216 if max_turns == 0 {
217 eyre::bail!("[defaults].max_turns must be greater than 0");
218 }
219
220 Ok(max_turns)
221 }
222
223 pub fn default_compact_threshold(&self) -> Option<u64> {
224 self.defaults.as_ref().and_then(|d| d.compact_threshold)
225 }
226
227 pub fn log_trajectories(&self) -> bool {
228 self.defaults
229 .as_ref()
230 .and_then(|d| d.log_trajectories)
231 .unwrap_or(false)
232 }
233
234 pub fn aggregator_max_tokens(&self) -> u64 {
235 self.aggregator
236 .max_tokens
237 .unwrap_or(DEFAULT_AGGREGATOR_MAX_TOKENS)
238 }
239
240 pub fn reviewer_compact_threshold(&self, reviewer: &ReviewerConfig) -> Option<u64> {
241 reviewer
242 .compact_threshold
243 .or(self.default_compact_threshold())
244 }
245}
246
247fn validate_free_model(label: &str, provider: &ProviderType, model: &str) -> Result<()> {
248 if model == "free" && !matches!(provider, ProviderType::OpenRouter) {
249 eyre::bail!("{label}: model = \"free\" is only supported with provider = \"openrouter\"");
250 }
251
252 Ok(())
253}
254
255fn validate_auth(
256 label: &str,
257 provider: &ProviderType,
258 auth: &Option<String>,
259 base_url: Option<&str>,
260 api_key_env: Option<&str>,
261 azure_credentials: Option<&str>,
262) -> Result<()> {
263 match (provider, auth.as_deref()) {
264 (_, None) => Ok(()),
266 (ProviderType::Gemini, Some("oauth")) => {
267 eyre::bail!(
268 "{label}: auth = \"oauth\" has been removed — use auth = \"agy-keyring\" (see README) or unset `auth` to use GEMINI_API_KEY"
269 );
270 }
271 (ProviderType::Gemini, Some("agy-keyring")) => {
274 if !cfg!(feature = "antigravity") {
275 eyre::bail!(
276 "{label}: auth = \"agy-keyring\" requires building nitpicker with `--features antigravity`"
277 );
278 }
279 Ok(())
280 }
281 (ProviderType::Gemini, Some(other)) => {
282 eyre::bail!(
283 "{label}: unknown auth value \"{other}\" — expected \"agy-keyring\" or unset"
284 );
285 }
286 (ProviderType::OpenAi | ProviderType::Anthropic, Some("azure-ad")) => {
289 if !cfg!(feature = "azure") {
290 eyre::bail!(
291 "{label}: auth = \"azure-ad\" requires building nitpicker with `--features azure`"
292 );
293 }
294 validate_azure_fields(label, base_url, azure_credentials)
295 }
296 (_, Some("azure-ad")) => {
297 eyre::bail!(
298 "{label}: auth = \"azure-ad\" is only supported with provider \"openai\" or \"anthropic\""
299 );
300 }
301 (ProviderType::OpenAi, Some("codex")) => {
306 if base_url.is_some() {
307 eyre::bail!(
308 "{label}: auth = \"codex\" ignores `base_url` (requests always go to the Codex endpoint) — remove it"
309 );
310 }
311 if api_key_env.is_some() {
312 eyre::bail!(
313 "{label}: auth = \"codex\" ignores `api_key_env` (the token comes from ~/.codex/auth.json) — remove it"
314 );
315 }
316 Ok(())
317 }
318 (_, Some("codex")) => {
319 eyre::bail!("{label}: auth = \"codex\" is only supported with provider \"openai\"");
320 }
321 (_, Some(other)) => {
324 eyre::bail!("{label}: unknown auth value \"{other}\"");
325 }
326 }
327}
328
329fn validate_azure_fields(
333 label: &str,
334 base_url: Option<&str>,
335 azure_credentials: Option<&str>,
336) -> Result<()> {
337 if base_url.map(str::trim).filter(|u| !u.is_empty()).is_none() {
338 eyre::bail!(
339 "{label}: auth = \"azure-ad\" requires a non-empty `base_url` (the Azure Foundry endpoint)"
340 );
341 }
342 match azure_credentials {
347 Some(mode) => validate_azure_credentials_mode(label, "azure_credentials", mode)?,
348 None => {
349 if let Ok(env_mode) = std::env::var("AZURE_TOKEN_CREDENTIALS") {
350 validate_azure_credentials_mode(label, "AZURE_TOKEN_CREDENTIALS", &env_mode)?;
351 }
352 }
353 }
354 Ok(())
355}
356
357fn validate_azure_credentials_mode(label: &str, source: &str, mode: &str) -> Result<()> {
362 let normalized = mode.trim().to_ascii_lowercase();
363 if !normalized.is_empty() && !matches!(normalized.as_str(), "dev" | "prod" | "auto") {
364 eyre::bail!(
365 "{label}: unknown {source} value \"{mode}\" — expected \"dev\", \"prod\", or unset (\"auto\")"
366 );
367 }
368 Ok(())
369}
370
371fn check_env_var(name: &str) -> Result<(), std::env::VarError> {
372 if name == "GEMINI_API_KEY" {
374 if std::env::var("GEMINI_API_KEY").is_ok() || std::env::var("GOOGLE_AI_API_KEY").is_ok() {
375 return Ok(());
376 }
377 return Err(std::env::VarError::NotPresent);
378 }
379 std::env::var(name).map(|_| ())
380}
381
382fn is_local_server(base_url: Option<&str>) -> bool {
383 base_url
384 .map(|u| u.starts_with("http://localhost") || u.starts_with("http://127.0.0.1"))
385 .unwrap_or(false)
386}
387
388fn required_env_var_reviewer(reviewer: &ReviewerConfig) -> Option<&str> {
389 if matches!(reviewer.provider, ProviderType::Gemini) && is_gemini_proxy_auth(&reviewer.auth) {
390 return None;
391 }
392 if is_azure_ad_auth(reviewer.auth.as_deref()) {
393 return None;
394 }
395 if is_codex_auth(reviewer.auth.as_deref()) {
396 return None;
397 }
398 if is_local_server(reviewer.base_url.as_deref()) {
399 return None;
400 }
401 if let Some(env) = &reviewer.api_key_env {
402 return Some(env.as_str());
403 }
404 default_env_var(&reviewer.provider)
405}
406
407fn required_env_var_aggregator(agg: &AggregatorConfig) -> Option<&str> {
408 if matches!(agg.provider, ProviderType::Gemini) && is_gemini_proxy_auth(&agg.auth) {
409 return None;
410 }
411 if is_azure_ad_auth(agg.auth.as_deref()) {
412 return None;
413 }
414 if is_codex_auth(agg.auth.as_deref()) {
415 return None;
416 }
417 if is_local_server(agg.base_url.as_deref()) {
418 return None;
419 }
420 if let Some(env) = &agg.api_key_env {
421 return Some(env.as_str());
422 }
423 default_env_var(&agg.provider)
424}
425
426fn is_gemini_proxy_auth(auth: &Option<String>) -> bool {
427 matches!(auth.as_deref(), Some("agy-keyring"))
428}
429
430pub fn is_azure_ad_auth(auth: Option<&str>) -> bool {
433 matches!(auth, Some("azure-ad"))
434}
435
436pub fn is_codex_auth(auth: Option<&str>) -> bool {
438 matches!(auth, Some("codex"))
439}
440
441fn default_env_var(provider: &ProviderType) -> Option<&'static str> {
442 match provider {
443 ProviderType::Anthropic => Some("ANTHROPIC_API_KEY"),
444 ProviderType::Gemini => Some("GEMINI_API_KEY"),
445 ProviderType::OpenAi => Some("OPENAI_API_KEY"),
446 ProviderType::OpenRouter => Some("OPENROUTER_API_KEY"),
447 }
448}
449
450#[cfg(test)]
451mod tests {
452 use super::*;
453
454 const FOUNDRY_URL: &str = "https://res.services.ai.azure.com/openai/v1";
455
456 #[test]
457 fn azure_ad_auth_detection() {
458 assert!(is_azure_ad_auth(Some("azure-ad")));
459 assert!(!is_azure_ad_auth(Some("agy-keyring")));
460 assert!(!is_azure_ad_auth(None));
461 }
462
463 #[test]
464 fn validate_auth_rejects_azure_ad_on_unsupported_providers() {
465 let auth = Some("azure-ad".to_string());
466 assert!(validate_auth("[t]", &ProviderType::Gemini, &auth, None, None, None).is_err());
467 assert!(validate_auth("[t]", &ProviderType::OpenRouter, &auth, None, None, None).is_err());
468 }
469
470 #[test]
471 fn validate_auth_azure_ad_on_supported_providers() {
472 let auth = Some("azure-ad".to_string());
473 let creds = Some("auto");
476 let openai = validate_auth(
477 "[t]",
478 &ProviderType::OpenAi,
479 &auth,
480 Some(FOUNDRY_URL),
481 None,
482 creds,
483 );
484 let anthropic = validate_auth(
485 "[t]",
486 &ProviderType::Anthropic,
487 &auth,
488 Some(FOUNDRY_URL),
489 None,
490 creds,
491 );
492 if cfg!(feature = "azure") {
495 assert!(openai.is_ok());
496 assert!(anthropic.is_ok());
497 } else {
498 assert!(openai.is_err());
499 assert!(anthropic.is_err());
500 }
501 }
502
503 #[test]
504 fn validate_auth_allows_unset_and_known_values() {
505 assert!(validate_auth("[t]", &ProviderType::OpenAi, &None, None, None, None).is_ok());
506 let agy = validate_auth(
509 "[t]",
510 &ProviderType::Gemini,
511 &Some("agy-keyring".to_string()),
512 None,
513 None,
514 None,
515 );
516 if cfg!(feature = "antigravity") {
517 assert!(agy.is_ok());
518 } else {
519 assert!(agy.is_err());
520 }
521 }
522
523 #[test]
524 fn validate_auth_codex_rejects_ignored_fields() {
525 let auth = Some("codex".to_string());
526 assert!(validate_auth("[t]", &ProviderType::OpenAi, &auth, None, None, None).is_ok());
528 assert!(
530 validate_auth(
531 "[t]",
532 &ProviderType::OpenAi,
533 &auth,
534 Some("https://example.com"),
535 None,
536 None,
537 )
538 .is_err()
539 );
540 assert!(
541 validate_auth(
542 "[t]",
543 &ProviderType::OpenAi,
544 &auth,
545 None,
546 Some("MY_KEY"),
547 None,
548 )
549 .is_err()
550 );
551 }
552
553 #[test]
554 fn codex_auth_detection() {
555 assert!(is_codex_auth(Some("codex")));
556 assert!(!is_codex_auth(Some("azure-ad")));
557 assert!(!is_codex_auth(None));
558 }
559
560 #[test]
561 fn validate_auth_codex_only_on_openai() {
562 let auth = Some("codex".to_string());
563 assert!(validate_auth("[t]", &ProviderType::OpenAi, &auth, None, None, None).is_ok());
564 assert!(validate_auth("[t]", &ProviderType::Anthropic, &auth, None, None, None).is_err());
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 fn config_with(reviewer_max_tokens: Option<u64>, aggregator_max_tokens: Option<u64>) -> Config {
571 Config {
572 defaults: None,
573 aggregator: AggregatorConfig {
574 model: "gpt-5.4".to_string(),
575 provider: ProviderType::OpenAi,
576 base_url: None,
577 api_key_env: None,
578 max_tokens: aggregator_max_tokens,
579 auth: Some("codex".to_string()),
580 azure_scope: None,
581 azure_credentials: None,
582 },
583 reviewer: vec![ReviewerConfig {
584 name: "r".to_string(),
585 model: "gpt-5.4".to_string(),
586 provider: ProviderType::OpenAi,
587 base_url: None,
588 api_key_env: None,
589 max_tokens: reviewer_max_tokens,
590 compact_threshold: None,
591 auth: Some("codex".to_string()),
592 azure_scope: None,
593 azure_credentials: None,
594 }],
595 }
596 }
597
598 #[test]
600 fn zero_max_tokens_is_rejected_on_both_entities() {
601 assert!(config_with(None, None).validate().is_ok());
602 assert!(config_with(Some(0), None).validate().is_err());
603 assert!(config_with(None, Some(0)).validate().is_err());
604 }
605
606 #[test]
607 fn codex_auth_requires_no_env_var() {
608 let reviewer = ReviewerConfig {
609 name: "r".to_string(),
610 model: "gpt-5.4".to_string(),
611 provider: ProviderType::OpenAi,
612 base_url: None,
613 api_key_env: None,
614 max_tokens: None,
615 compact_threshold: None,
616 auth: Some("codex".to_string()),
617 azure_scope: None,
618 azure_credentials: None,
619 };
620 assert_eq!(required_env_var_reviewer(&reviewer), None);
621 let agg = AggregatorConfig {
622 model: "gpt-5.4".to_string(),
623 provider: ProviderType::OpenAi,
624 base_url: None,
625 api_key_env: None,
626 max_tokens: None,
627 auth: Some("codex".to_string()),
628 azure_scope: None,
629 azure_credentials: None,
630 };
631 assert_eq!(required_env_var_aggregator(&agg), None);
632 }
633
634 #[test]
635 fn validate_auth_rejects_unknown_value_on_non_gemini() {
636 let typo = Some("azure_ad".to_string());
638 assert!(
639 validate_auth(
640 "[t]",
641 &ProviderType::OpenAi,
642 &typo,
643 Some(FOUNDRY_URL),
644 None,
645 None
646 )
647 .is_err()
648 );
649 assert!(validate_auth("[t]", &ProviderType::Anthropic, &typo, None, None, None).is_err());
650 }
651
652 #[cfg(feature = "azure")]
653 #[test]
654 fn validate_auth_azure_ad_requires_base_url() {
655 let auth = Some("azure-ad".to_string());
656 assert!(validate_auth("[t]", &ProviderType::OpenAi, &auth, None, None, None).is_err());
660 assert!(validate_auth("[t]", &ProviderType::OpenAi, &auth, Some(""), None, None).is_err());
661 assert!(
662 validate_auth(
663 "[t]",
664 &ProviderType::OpenAi,
665 &auth,
666 Some(FOUNDRY_URL),
667 None,
668 Some("auto")
669 )
670 .is_ok()
671 );
672 }
673
674 #[test]
675 fn validate_azure_credentials_mode_rejects_unknown_only() {
676 assert!(validate_azure_credentials_mode("[t]", "azure_credentials", "dev").is_ok());
678 assert!(validate_azure_credentials_mode("[t]", "azure_credentials", "PROD").is_ok());
679 assert!(validate_azure_credentials_mode("[t]", "azure_credentials", "auto").is_ok());
680 assert!(validate_azure_credentials_mode("[t]", "azure_credentials", "").is_ok());
682 assert!(validate_azure_credentials_mode("[t]", "azure_credentials", " ").is_ok());
683 let err = validate_azure_credentials_mode("[t]", "AZURE_TOKEN_CREDENTIALS", "bogus")
686 .unwrap_err()
687 .to_string();
688 assert!(err.contains("AZURE_TOKEN_CREDENTIALS"), "got: {err}");
689 assert!(err.contains("bogus"), "got: {err}");
690 }
691
692 #[cfg(feature = "azure")]
693 #[test]
694 fn validate_auth_azure_ad_validates_credentials() {
695 let auth = Some("azure-ad".to_string());
696 let ok = |creds| {
697 validate_auth(
698 "[t]",
699 &ProviderType::OpenAi,
700 &auth,
701 Some(FOUNDRY_URL),
702 None,
703 creds,
704 )
705 .is_ok()
706 };
707 assert!(ok(Some("auto")));
712 assert!(ok(Some("dev")));
713 assert!(ok(Some("PROD"))); assert!(ok(Some("auto")));
715 assert!(
716 validate_auth(
717 "[t]",
718 &ProviderType::OpenAi,
719 &auth,
720 Some(FOUNDRY_URL),
721 None,
722 Some("deve")
723 )
724 .is_err()
725 );
726 }
727}