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 #[serde(skip_serializing_if = "Option::is_none")]
46 pub azure_scope: Option<String>,
47 #[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 #[serde(skip_serializing_if = "Option::is_none")]
70 pub azure_scope: Option<String>,
71 #[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 #[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(
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 (_, 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 (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 (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 (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 (_, Some(other)) => {
300 eyre::bail!("{label}: unknown auth value \"{other}\"");
301 }
302 }
303}
304
305fn 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 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
333fn 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 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
406pub fn is_azure_ad_auth(auth: Option<&str>) -> bool {
409 matches!(auth, Some("azure-ad"))
410}
411
412pub 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 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 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 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 assert!(validate_auth("[t]", &ProviderType::OpenAi, &auth, None, None, None).is_ok());
504 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 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 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 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 assert!(validate_azure_credentials_mode("[t]", "azure_credentials", "").is_ok());
620 assert!(validate_azure_credentials_mode("[t]", "azure_credentials", " ").is_ok());
621 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 assert!(ok(Some("auto")));
650 assert!(ok(Some("dev")));
651 assert!(ok(Some("PROD"))); 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}