Skip to main content

fetchium_core/ai/
providers.rs

1//! Multi-provider AI configuration and types.
2//!
3//! Supported providers:
4//! - `ollama`        — local models via Ollama HTTP API (no API key)
5//! - `openai`        — OpenAI chat completions API (API key or Codex CLI OAuth)
6//! - `anthropic`     — Anthropic Messages API / Claude (API key or Claude Code OAuth)
7//! - `gemini`        — Google Gemini REST API (API key or Gemini CLI OAuth)
8//! - `gemini_cli`    — Local `gemini` CLI subprocess (Gemini subscription)
9//! - `openrouter`    — OpenRouter aggregator — 100+ models, one API key
10//! - `antigravity`   — OpenCode Antigravity (Google Cloud Code Assist proxy:
11//!   free Gemini 3 + Claude Sonnet/Opus via `opencode-antigravity-auth`)
12
13use serde::{Deserialize, Serialize};
14
15// ─── Model Registry ──────────────────────────────────────────────────────────
16//
17// **Single source of truth for all model names in Fetchium.**
18// To add or change a model: update `ModelRegistry::models_for()` and, if it
19// becomes the new default, update `ModelRegistry::default_model()`.
20// No other file should ever hardcode a model string.
21
22/// Model capability tier for routing and display purposes.
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
24#[serde(rename_all = "snake_case")]
25pub enum ModelCapability {
26    /// Sub-500 ms, minimal cost — HyDE, intent classification, autocomplete.
27    Fast,
28    /// Default for user-facing queries — good quality/speed balance.
29    Standard,
30    /// Highest quality, slower and costlier — deep research synthesis.
31    Powerful,
32}
33
34impl ModelCapability {
35    /// Short label for display (`"fast"`, `"standard"`, `"powerful"`).
36    pub fn label(&self) -> &'static str {
37        match self {
38            Self::Fast => "fast",
39            Self::Standard => "standard",
40            Self::Powerful => "powerful",
41        }
42    }
43}
44
45/// Metadata for a single model available to a provider.
46#[derive(Debug, Clone)]
47pub struct ModelInfo {
48    /// Canonical model ID sent to the API or CLI.
49    pub id: &'static str,
50    /// Capability tier — controls default routing behavior.
51    pub capability: ModelCapability,
52    /// Short aliases accepted by `fetchium provider set <provider> --model <alias>`.
53    pub aliases: &'static [&'static str],
54    /// One-line description shown in `fetchium provider models`.
55    pub note: &'static str,
56}
57
58/// **Central model registry** — the one place where all model names live.
59///
60/// # Usage
61/// - `ModelRegistry::default_model(kind)` — provider's default model ID.
62/// - `ModelRegistry::fast_model(kind)`    — low-latency model for HyDE / intent.
63/// - `ModelRegistry::models_for(kind)`   — full list for tab-complete / display.
64/// - `ModelRegistry::resolve_alias(kind, s)` — expand `"flash"` → full model ID.
65pub struct ModelRegistry;
66
67impl ModelRegistry {
68    /// Canonical default model for a provider.
69    ///
70    /// **This is the only place default model strings are defined.**
71    /// All other code (`ProviderKind::default_model`, `ProviderEntry::resolve_model`,
72    /// `call_gemini_cli`, etc.) ultimately resolves through here.
73    pub fn default_model(kind: ProviderKind) -> &'static str {
74        match kind {
75            ProviderKind::GeminiCli => "gemini-3-flash-preview", // Gemini 3 Flash — thinking-capable
76            ProviderKind::Gemini => "gemini-3-flash-preview",    // Gemini 3 Flash (latest)
77            ProviderKind::Anthropic => "claude-haiku-4-5-20251001", // Fast, affordable
78            ProviderKind::OpenAi => "gpt-4o-mini",               // Fast, affordable
79            ProviderKind::Ollama => "qwen3:8b",                  // Good local default
80            ProviderKind::OpenRouter => "google/gemini-2.5-flash", // Via OpenRouter (2.5 Flash still most stable there)
81            ProviderKind::Antigravity => "antigravity-gemini-3-flash", // Free via OpenCode
82        }
83    }
84
85    /// Fast / low-latency model for HyDE queries and intent classification.
86    pub fn fast_model(kind: ProviderKind) -> &'static str {
87        match kind {
88            ProviderKind::GeminiCli => "gemini-3-flash-preview", // Thinking-capable for fast mode override
89            ProviderKind::Gemini => "gemini-3-flash-preview",
90            ProviderKind::Anthropic => "claude-haiku-4-5-20251001",
91            ProviderKind::OpenAi => "gpt-4o-mini",
92            ProviderKind::Ollama => "qwen3:0.6b",
93            ProviderKind::OpenRouter => "google/gemini-2.5-flash",
94            ProviderKind::Antigravity => "antigravity-gemini-3-flash",
95        }
96    }
97
98    /// Resolve a short alias or exact model ID to a canonical model ID.
99    ///
100    /// Returns `None` when the alias is unrecognized — callers should treat
101    /// the input as a literal model ID (passed through unchanged).
102    pub fn resolve_alias(kind: ProviderKind, alias: &str) -> Option<&'static str> {
103        Self::models_for(kind)
104            .iter()
105            .find(|m| m.id == alias || m.aliases.contains(&alias))
106            .map(|m| m.id)
107    }
108
109    /// All known models for a provider, ordered fast → standard → powerful.
110    ///
111    /// Used by `fetchium provider models` and alias resolution.
112    pub fn models_for(kind: ProviderKind) -> &'static [ModelInfo] {
113        match kind {
114            ProviderKind::GeminiCli => &[
115                ModelInfo {
116                    id: "gemini-3-flash-preview",
117                    capability: ModelCapability::Standard,
118                    aliases: &["flash3", "flash", "g3flash", "gemini3flash"],
119                    note: "Gemini 3 Flash — newest, thinking-capable (default)",
120                },
121                ModelInfo {
122                    id: "gemini-2.5-flash",
123                    capability: ModelCapability::Fast,
124                    aliases: &["flash25", "fast", "2.5flash", "flash2.5"],
125                    note: "Gemini 2.5 Flash — ~5x faster, no thinking. Use with --fast flag.",
126                },
127                ModelInfo {
128                    id: "gemini-3-pro-preview",
129                    capability: ModelCapability::Powerful,
130                    aliases: &["pro3", "pro", "g3pro", "gemini3pro"],
131                    note: "Gemini 3 Pro — most capable (preview, may 429 under load)",
132                },
133            ],
134            ProviderKind::Gemini => &[
135                ModelInfo {
136                    id: "gemini-3-flash-preview",
137                    capability: ModelCapability::Standard,
138                    aliases: &["flash3", "g3flash", "gemini3flash", "flash"],
139                    note: "Gemini 3 Flash Preview — latest generation (default)",
140                },
141                ModelInfo {
142                    id: "gemini-2.5-flash",
143                    capability: ModelCapability::Standard,
144                    aliases: &["flash25", "flash2.5"],
145                    note: "Gemini 2.5 Flash — previous generation stable model",
146                },
147                ModelInfo {
148                    id: "gemini-2.5-pro",
149                    capability: ModelCapability::Powerful,
150                    aliases: &["pro", "pro25"],
151                    note: "Gemini 2.5 Pro — highest REST API quality",
152                },
153                ModelInfo {
154                    id: "gemini-2.5-flash-thinking-exp",
155                    capability: ModelCapability::Powerful,
156                    aliases: &["thinking", "flash-thinking"],
157                    note: "Gemini 2.5 Flash Thinking — extended reasoning",
158                },
159                ModelInfo {
160                    id: "gemini-2.0-flash",
161                    capability: ModelCapability::Fast,
162                    aliases: &["flash20", "2.0flash"],
163                    note: "Gemini 2.0 Flash — fast, lower cost",
164                },
165            ],
166            ProviderKind::Anthropic => &[
167                ModelInfo {
168                    id: "claude-haiku-4-5-20251001",
169                    capability: ModelCapability::Fast,
170                    aliases: &["haiku", "claude-haiku"],
171                    note: "Claude Haiku — fastest, lowest cost (default)",
172                },
173                ModelInfo {
174                    id: "claude-sonnet-4-6",
175                    capability: ModelCapability::Standard,
176                    aliases: &["sonnet", "claude-sonnet"],
177                    note: "Claude Sonnet — best quality/speed balance",
178                },
179                ModelInfo {
180                    id: "claude-opus-4-6",
181                    capability: ModelCapability::Powerful,
182                    aliases: &["opus", "claude-opus"],
183                    note: "Claude Opus — most capable, highest cost",
184                },
185            ],
186            ProviderKind::OpenAi => &[
187                ModelInfo {
188                    id: "gpt-4o-mini",
189                    capability: ModelCapability::Fast,
190                    aliases: &["mini", "4o-mini"],
191                    note: "GPT-4o Mini — fast, affordable (default)",
192                },
193                ModelInfo {
194                    id: "gpt-4o",
195                    capability: ModelCapability::Standard,
196                    aliases: &["4o", "gpt4o"],
197                    note: "GPT-4o — flagship multimodal model",
198                },
199                ModelInfo {
200                    id: "o3-mini",
201                    capability: ModelCapability::Powerful,
202                    aliases: &["o3mini", "o3"],
203                    note: "o3-mini — advanced reasoning model",
204                },
205            ],
206            ProviderKind::Ollama => &[
207                ModelInfo {
208                    id: "qwen3:0.6b",
209                    capability: ModelCapability::Fast,
210                    aliases: &["tiny", "qwen-tiny"],
211                    note: "Qwen3 0.6B — ultra-fast, ~0.5 GB RAM",
212                },
213                ModelInfo {
214                    id: "qwen3:8b",
215                    capability: ModelCapability::Standard,
216                    aliases: &["qwen3"],
217                    note: "Qwen3 8B — good local default (~5 GB RAM)",
218                },
219                ModelInfo {
220                    id: "qwen3:30b-a3b",
221                    capability: ModelCapability::Powerful,
222                    aliases: &["qwen3-large"],
223                    note: "Qwen3 30B MoE — high quality (~8 GB RAM, sparse)",
224                },
225                ModelInfo {
226                    id: "gemma3:1b",
227                    capability: ModelCapability::Fast,
228                    aliases: &["gemma-tiny", "gemma1b"],
229                    note: "Gemma3 1B — Google compact model",
230                },
231                ModelInfo {
232                    id: "gemma3:27b",
233                    capability: ModelCapability::Powerful,
234                    aliases: &["gemma"],
235                    note: "Gemma3 27B — Google powerful model (~20 GB RAM)",
236                },
237                ModelInfo {
238                    id: "llama3.3:70b",
239                    capability: ModelCapability::Powerful,
240                    aliases: &["llama"],
241                    note: "Llama 3.3 70B — Meta flagship (~40 GB RAM required)",
242                },
243            ],
244            ProviderKind::OpenRouter => &[
245                ModelInfo {
246                    id: "google/gemini-2.5-flash",
247                    capability: ModelCapability::Standard,
248                    aliases: &["gemini-flash", "gflash"],
249                    note: "Gemini 2.5 Flash via OpenRouter (default)",
250                },
251                ModelInfo {
252                    id: "anthropic/claude-haiku-4-5",
253                    capability: ModelCapability::Fast,
254                    aliases: &["claude-haiku"],
255                    note: "Claude Haiku via OpenRouter",
256                },
257                ModelInfo {
258                    id: "anthropic/claude-sonnet-4-6",
259                    capability: ModelCapability::Standard,
260                    aliases: &["claude-sonnet"],
261                    note: "Claude Sonnet via OpenRouter",
262                },
263                ModelInfo {
264                    id: "openai/gpt-4o-mini",
265                    capability: ModelCapability::Fast,
266                    aliases: &["gpt-mini"],
267                    note: "GPT-4o Mini via OpenRouter",
268                },
269                ModelInfo {
270                    id: "mistralai/mistral-small",
271                    capability: ModelCapability::Fast,
272                    aliases: &["mistral"],
273                    note: "Mistral Small via OpenRouter",
274                },
275            ],
276            ProviderKind::Antigravity => &[
277                ModelInfo {
278                    id: "antigravity-gemini-3-flash",
279                    capability: ModelCapability::Standard,
280                    aliases: &["ag-flash", "ag-gemini"],
281                    note: "Gemini 3 Flash via Antigravity/OpenCode (default)",
282                },
283                ModelInfo {
284                    id: "antigravity-gemini-3-pro",
285                    capability: ModelCapability::Powerful,
286                    aliases: &["ag-pro", "ag-gemini-pro"],
287                    note: "Gemini 3 Pro via Antigravity/OpenCode",
288                },
289                ModelInfo {
290                    id: "antigravity-claude-sonnet",
291                    capability: ModelCapability::Standard,
292                    aliases: &["ag-sonnet", "ag-claude"],
293                    note: "Claude Sonnet via Antigravity/OpenCode",
294                },
295                ModelInfo {
296                    id: "antigravity-claude-opus",
297                    capability: ModelCapability::Powerful,
298                    aliases: &["ag-opus"],
299                    note: "Claude Opus via Antigravity/OpenCode",
300                },
301            ],
302        }
303    }
304}
305
306/// Which AI backend to route requests to.
307#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
308#[serde(rename_all = "snake_case")]
309pub enum ProviderKind {
310    /// Ollama local models (no API key required).
311    Ollama,
312    /// OpenAI chat completions API (API key or Codex CLI OAuth).
313    OpenAi,
314    /// Anthropic Messages API — Claude models (API key or Claude Code OAuth).
315    Anthropic,
316    /// Google Gemini REST API (API key or Gemini CLI OAuth).
317    Gemini,
318    /// Local `gemini` CLI subprocess (requires `gemini` in PATH + Gemini subscription).
319    GeminiCli,
320    /// OpenRouter aggregator — access 100+ models with one API key.
321    OpenRouter,
322    /// OpenCode Antigravity — Google Cloud Code Assist proxy.
323    ///
324    /// Provides free access to Gemini 3 (Pro, Flash) and Claude Sonnet/Opus models
325    /// using credentials from the `opencode-antigravity-auth` plugin.
326    /// Credentials are stored in `~/.config/opencode/antigravity-accounts.json`.
327    Antigravity,
328}
329
330impl ProviderKind {
331    /// Human-readable display name.
332    pub fn display_name(&self) -> &'static str {
333        match self {
334            Self::Ollama => "Ollama (local)",
335            Self::OpenAi => "OpenAI",
336            Self::Anthropic => "Anthropic / Claude",
337            Self::Gemini => "Google Gemini",
338            Self::GeminiCli => "Gemini CLI (local)",
339            Self::OpenRouter => "OpenRouter",
340            Self::Antigravity => "Antigravity (OpenCode)",
341        }
342    }
343
344    /// Default model ID for this provider.
345    ///
346    /// Delegates to [`ModelRegistry::default_model`] — the single source of truth.
347    /// To change a default, update the registry rather than this method.
348    pub fn default_model(&self) -> &'static str {
349        ModelRegistry::default_model(*self)
350    }
351
352    /// Parse from a string slug (case-insensitive, accepts common aliases).
353    pub fn from_slug(s: &str) -> Option<Self> {
354        match s.to_lowercase().as_str() {
355            "ollama" => Some(Self::Ollama),
356            "openai" | "open-ai" | "open_ai" => Some(Self::OpenAi),
357            "anthropic" | "claude" => Some(Self::Anthropic),
358            "gemini" | "google" | "google-gemini" => Some(Self::Gemini),
359            "gemini-cli" | "gemini_cli" | "geminicli" => Some(Self::GeminiCli),
360            "openrouter" | "open-router" | "open_router" => Some(Self::OpenRouter),
361            "antigravity" | "anti-gravity" | "anti_gravity" | "opencode" | "open-code"
362            | "open_code" => Some(Self::Antigravity),
363            _ => None,
364        }
365    }
366
367    /// Canonical config key slug used in TOML and the CLI.
368    pub fn slug(&self) -> &'static str {
369        match self {
370            Self::Ollama => "ollama",
371            Self::OpenAi => "openai",
372            Self::Anthropic => "anthropic",
373            Self::Gemini => "gemini",
374            Self::GeminiCli => "gemini_cli",
375            Self::OpenRouter => "openrouter",
376            Self::Antigravity => "antigravity",
377        }
378    }
379
380    /// Environment variable name for the API key (`None` for no-key providers).
381    ///
382    /// Note: Antigravity uses OAuth rather than an API key, so this returns `None`.
383    pub fn api_key_env(&self) -> Option<&'static str> {
384        match self {
385            Self::Ollama | Self::GeminiCli | Self::Antigravity => None,
386            Self::OpenAi => Some("OPENAI_API_KEY"),
387            Self::Anthropic => Some("ANTHROPIC_API_KEY"),
388            Self::Gemini => Some("GEMINI_API_KEY"),
389            Self::OpenRouter => Some("OPENROUTER_API_KEY"),
390        }
391    }
392
393    /// Whether this provider requires an explicit API key to operate.
394    ///
395    /// Returns `false` for local providers and OAuth-only providers (Antigravity).
396    pub fn requires_api_key(&self) -> bool {
397        self.api_key_env().is_some()
398    }
399
400    /// All canonical provider slugs (for help text and tab completion).
401    pub fn all_slugs() -> &'static [&'static str] {
402        &[
403            "ollama",
404            "openai",
405            "anthropic",
406            "gemini",
407            "gemini_cli",
408            "openrouter",
409            "antigravity",
410        ]
411    }
412
413    /// Link to the API key management page for this provider (`None` if no key needed).
414    pub fn api_docs_url(&self) -> Option<&'static str> {
415        match self {
416            Self::OpenAi => Some("https://platform.openai.com/api-keys"),
417            Self::Anthropic => Some("https://console.anthropic.com/settings/keys"),
418            Self::Gemini => Some("https://aistudio.google.com/app/apikey"),
419            Self::OpenRouter => Some("https://openrouter.ai/keys"),
420            _ => None,
421        }
422    }
423
424    /// Short note about how this provider authenticates (for help text).
425    pub fn auth_note(&self) -> &'static str {
426        match self {
427            Self::Ollama => "local binary, no key",
428            Self::OpenAi => "API key or Codex CLI OAuth (ChatGPT subscription)",
429            Self::Anthropic => "API key or Claude Code OAuth (Max/Pro subscription)",
430            Self::Gemini => "API key or Gemini CLI OAuth (Gemini subscription)",
431            Self::GeminiCli => "local binary + Gemini subscription",
432            Self::OpenRouter => "API key (openrouter.ai)",
433            Self::Antigravity => "OAuth via opencode-antigravity-auth — no key needed",
434        }
435    }
436}
437
438impl std::fmt::Display for ProviderKind {
439    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
440        f.write_str(self.display_name())
441    }
442}
443
444/// Per-provider configuration stored in `~/.fetchium/config.toml`.
445#[derive(Debug, Clone, Serialize, Deserialize)]
446#[serde(default)]
447pub struct ProviderEntry {
448    /// API key stored in plain text.
449    ///
450    /// Prefer setting the corresponding environment variable instead
451    /// (e.g. `OPENAI_API_KEY`) to avoid storing secrets in config files.
452    pub api_key: Option<String>,
453    /// Additional API keys for pool rotation.
454    /// All keys in this array plus `api_key` are combined into a single pool.
455    /// Keys are rotated with rate-limit awareness — if one key gets 429'd,
456    /// the next key is tried automatically.
457    #[serde(default)]
458    pub api_keys: Vec<String>,
459    /// Model name override. Uses the provider default when absent.
460    pub model: Option<String>,
461    /// Base URL override (useful for proxies or custom deployments).
462    pub base_url: Option<String>,
463    /// Whether this entry is active in fallback resolution.
464    pub enabled: bool,
465}
466
467impl Default for ProviderEntry {
468    fn default() -> Self {
469        Self {
470            api_key: None,
471            api_keys: Vec::new(),
472            model: None,
473            base_url: None,
474            enabled: true,
475        }
476    }
477}
478
479impl ProviderEntry {
480    /// Resolve the API key: config value first, then environment variable.
481    ///
482    /// Returns `None` if neither source has a non-empty, non-placeholder value.
483    pub fn resolve_api_key(&self, env_var: &str) -> Option<String> {
484        if let Some(ref k) = self.api_key {
485            if !k.is_empty() && !k.starts_with("your-") && k != "REPLACE_ME" {
486                return Some(k.clone());
487            }
488        }
489        std::env::var(env_var).ok().filter(|v| !v.is_empty())
490    }
491
492    /// Resolve the model, falling back to the provider's built-in default.
493    ///
494    /// Supports short aliases (e.g. `"flash"` → `"gemini-3-flash-preview"` for
495    /// `gemini_cli`, `"haiku"` → `"claude-haiku-4-5-20251001"` for `anthropic`).
496    /// Any unrecognized string is treated as a literal model ID and passed through.
497    pub fn resolve_model(&self, kind: ProviderKind) -> String {
498        if let Some(ref m) = self.model {
499            if !m.is_empty() {
500                return ModelRegistry::resolve_alias(kind, m)
501                    .map(str::to_string)
502                    .unwrap_or_else(|| m.clone());
503            }
504        }
505        ModelRegistry::default_model(kind).to_string()
506    }
507
508    /// Return `true` if this entry appears to have a usable API key.
509    pub fn has_key(&self, env_var: &str) -> bool {
510        self.resolve_api_key(env_var).is_some()
511    }
512}
513
514/// Full multi-provider configuration block (`[ai.providers]` in config.toml).
515#[derive(Debug, Clone, Serialize, Deserialize, Default)]
516#[serde(default)]
517pub struct ProvidersConfig {
518    /// Ordered list of provider slugs to try (first = highest priority).
519    ///
520    /// If a provider fails (bad key, network error, etc.), the next one in
521    /// the list is tried automatically.
522    ///
523    /// Example: `["antigravity", "gemini", "anthropic", "openai", "ollama"]`
524    ///
525    /// Defaults to `["ollama"]` for backward compatibility when empty.
526    pub fallback_chain: Vec<String>,
527
528    /// Ollama local model configuration.
529    pub ollama: ProviderEntry,
530    /// OpenAI API configuration.
531    pub openai: ProviderEntry,
532    /// Anthropic (Claude) API configuration.
533    pub anthropic: ProviderEntry,
534    /// Google Gemini API configuration.
535    pub gemini: ProviderEntry,
536    /// Gemini CLI subprocess configuration.
537    pub gemini_cli: ProviderEntry,
538    /// OpenRouter API configuration.
539    pub openrouter: ProviderEntry,
540    /// OpenCode Antigravity OAuth configuration (model override only — no API key needed).
541    pub antigravity: ProviderEntry,
542}
543
544impl ProvidersConfig {
545    /// Immutable reference to the entry for a given provider kind.
546    pub fn entry(&self, kind: ProviderKind) -> &ProviderEntry {
547        match kind {
548            ProviderKind::Ollama => &self.ollama,
549            ProviderKind::OpenAi => &self.openai,
550            ProviderKind::Anthropic => &self.anthropic,
551            ProviderKind::Gemini => &self.gemini,
552            ProviderKind::GeminiCli => &self.gemini_cli,
553            ProviderKind::OpenRouter => &self.openrouter,
554            ProviderKind::Antigravity => &self.antigravity,
555        }
556    }
557
558    /// Mutable reference to the entry for a given provider kind.
559    pub fn entry_mut(&mut self, kind: ProviderKind) -> &mut ProviderEntry {
560        match kind {
561            ProviderKind::Ollama => &mut self.ollama,
562            ProviderKind::OpenAi => &mut self.openai,
563            ProviderKind::Anthropic => &mut self.anthropic,
564            ProviderKind::Gemini => &mut self.gemini,
565            ProviderKind::GeminiCli => &mut self.gemini_cli,
566            ProviderKind::OpenRouter => &mut self.openrouter,
567            ProviderKind::Antigravity => &mut self.antigravity,
568        }
569    }
570
571    /// Resolve the ordered fallback chain as `ProviderKind` values.
572    ///
573    /// Filters out unknown slugs and disabled entries, then **auto-appends** any
574    /// subscription-auth providers that are locally available but not in the explicit chain.
575    ///
576    /// Auto-discovery order (appended only when not already present):
577    /// 1. **Antigravity** — OpenCode account at `~/.config/opencode/antigravity-accounts.json`
578    /// 2. **GeminiCli** — Gemini OAuth session (subprocess works even when REST API scope is
579    ///    insufficient — covers `gemini auth login` tokens)
580    /// 3. **OpenAI** — Codex CLI session at `~/.codex/auth.json` (ChatGPT subscription)
581    /// 4. **Anthropic** — Claude Code session (Agent SDK / Claude Max/Pro subscription).
582    ///    If the session is rejected by `api.anthropic.com` the error is logged as a warning
583    ///    and the chain continues — this is a graceful fallback.
584    ///
585    /// Falls back to `[Ollama]` when no chain is configured and nothing is discovered.
586    pub fn resolved_chain(&self) -> Vec<ProviderKind> {
587        use crate::ai::credentials::{
588            antigravity_auth_available, codex_auth_available, read_gemini_creds,
589        };
590
591        // Build the explicit user-configured chain first.
592        let mut chain: Vec<ProviderKind> = self
593            .fallback_chain
594            .iter()
595            .filter_map(|s| ProviderKind::from_slug(s))
596            .filter(|k| self.entry(*k).enabled)
597            .collect();
598
599        // Auto-append subscription-auth providers not already in the chain.
600        //
601        // Gemini REST API is auto-prepended when any API key is available
602        // (env var, config.toml, or auth store pool) — it's the fastest path.
603        //
604        // GeminiCli is also auto-discovered via `gemini auth login` sessions,
605        // as a fallback when keys aren't configured.
606        //
607        // NOTE: Anthropic is only auto-added when a real API key is present.
608        let gemini_session = read_gemini_creds()
609            .map(|c| c.is_refreshable())
610            .unwrap_or(false);
611        let has_gemini_api_key = {
612            let entry = self.entry(ProviderKind::Gemini);
613            let from_config = entry
614                .api_key
615                .as_ref()
616                .map(|k| !k.is_empty() && !k.starts_with("your-") && k != "REPLACE_ME")
617                .unwrap_or(false);
618            let from_env = std::env::var("GEMINI_API_KEY")
619                .map(|k| !k.is_empty())
620                .unwrap_or(false);
621            let from_multi_env = std::env::var("GEMINI_API_KEYS")
622                .map(|k| !k.is_empty())
623                .unwrap_or(false);
624            let from_auth = crate::ai::credentials::fetchium_auth_get("gemini")
625                .map(|a| a.key_count() > 0)
626                .unwrap_or(false);
627            from_config || from_env || from_multi_env || from_auth
628        };
629        let has_anthropic_key = self
630            .entry(ProviderKind::Anthropic)
631            .resolve_api_key("ANTHROPIC_API_KEY")
632            .is_some();
633        let auto_fallbacks: [(ProviderKind, bool); 5] = [
634            // Gemini REST API — fastest when keys are present
635            (ProviderKind::Gemini, has_gemini_api_key),
636            (ProviderKind::Antigravity, antigravity_auth_available()),
637            (ProviderKind::GeminiCli, gemini_session),
638            (ProviderKind::OpenAi, codex_auth_available()),
639            (ProviderKind::Anthropic, has_anthropic_key),
640        ];
641        for (kind, available) in auto_fallbacks {
642            if available && self.entry(kind).enabled && !chain.contains(&kind) {
643                chain.push(kind);
644            }
645        }
646
647        if chain.is_empty() {
648            vec![ProviderKind::Ollama]
649        } else {
650            chain
651        }
652    }
653
654    /// Return all providers that appear to be usable (key set or local/OAuth).
655    pub fn configured_providers(&self) -> Vec<ProviderKind> {
656        use crate::ai::credentials::{
657            antigravity_auth_available, claude_code_auth_available, codex_auth_available,
658            get_gemini_access_token_if_valid, read_gemini_creds,
659        };
660        // Note: `read_gemini_creds().is_some()` is intentionally NOT used as a signal —
661        // a creds file can exist with an empty refresh_token after `invalidate_gemini_creds()`.
662        // Use `is_refreshable()` to distinguish a live session from a dead one.
663        const ALL: &[ProviderKind] = &[
664            ProviderKind::Ollama,
665            ProviderKind::OpenAi,
666            ProviderKind::Anthropic,
667            ProviderKind::Gemini,
668            ProviderKind::GeminiCli,
669            ProviderKind::OpenRouter,
670            ProviderKind::Antigravity,
671        ];
672        ALL.iter()
673            .copied()
674            .filter(|k| {
675                let entry = self.entry(*k);
676                if !entry.enabled {
677                    return false;
678                }
679                match k {
680                    // OAuth-capable: API key OR subscription session
681                    ProviderKind::OpenAi => {
682                        entry.has_key("OPENAI_API_KEY") || codex_auth_available()
683                    }
684                    ProviderKind::Anthropic => {
685                        entry.has_key("ANTHROPIC_API_KEY") || claude_code_auth_available()
686                    }
687                    ProviderKind::Gemini => {
688                        entry.has_key("GEMINI_API_KEY")
689                            || std::env::var("GEMINI_API_KEYS")
690                                .map(|k| !k.is_empty())
691                                .unwrap_or(false)
692                            || crate::ai::credentials::fetchium_auth_get("gemini")
693                                .map(|a| a.key_count() > 0)
694                                .unwrap_or(false)
695                            || get_gemini_access_token_if_valid().is_some()
696                            || read_gemini_creds()
697                                .map(|c| c.is_refreshable())
698                                .unwrap_or(false)
699                    }
700                    // OAuth-only (no API key)
701                    ProviderKind::Antigravity => antigravity_auth_available(),
702                    // Local — always usable (availability checked at runtime)
703                    ProviderKind::Ollama | ProviderKind::GeminiCli => true,
704                    // API key only
705                    ProviderKind::OpenRouter => entry.has_key("OPENROUTER_API_KEY"),
706                }
707            })
708            .collect()
709    }
710}
711
712#[cfg(test)]
713mod tests {
714    use super::*;
715
716    #[test]
717    fn from_slug_roundtrip() {
718        assert_eq!(
719            ProviderKind::from_slug("openai"),
720            Some(ProviderKind::OpenAi)
721        );
722        assert_eq!(
723            ProviderKind::from_slug("claude"),
724            Some(ProviderKind::Anthropic)
725        );
726        assert_eq!(
727            ProviderKind::from_slug("gemini"),
728            Some(ProviderKind::Gemini)
729        );
730        assert_eq!(
731            ProviderKind::from_slug("gemini_cli"),
732            Some(ProviderKind::GeminiCli)
733        );
734        assert_eq!(
735            ProviderKind::from_slug("openrouter"),
736            Some(ProviderKind::OpenRouter)
737        );
738        assert_eq!(
739            ProviderKind::from_slug("ollama"),
740            Some(ProviderKind::Ollama)
741        );
742        assert_eq!(
743            ProviderKind::from_slug("antigravity"),
744            Some(ProviderKind::Antigravity)
745        );
746        assert_eq!(
747            ProviderKind::from_slug("opencode"),
748            Some(ProviderKind::Antigravity)
749        );
750        assert_eq!(ProviderKind::from_slug("bogus"), None);
751    }
752
753    #[test]
754    fn resolved_chain_defaults_to_ollama() {
755        let cfg = ProvidersConfig::default();
756        let chain = cfg.resolved_chain();
757        // Chain must always be non-empty.  When no explicit chain is configured and
758        // no subscription sessions are present the result is [Ollama].  On machines
759        // with a Gemini session / Antigravity / Codex CLI, those providers appear
760        // instead.  Either way, all entries must be valid ProviderKind values.
761        assert!(!chain.is_empty());
762        for k in &chain {
763            assert!(ProviderKind::all_slugs().contains(&k.slug()));
764        }
765    }
766
767    #[test]
768    fn resolved_chain_respects_order() {
769        let cfg = ProvidersConfig {
770            fallback_chain: vec!["gemini".into(), "openai".into(), "ollama".into()],
771            ..ProvidersConfig::default()
772        };
773        let chain = cfg.resolved_chain();
774        // The explicit entries must appear first and in order.
775        assert_eq!(chain[0], ProviderKind::Gemini);
776        assert_eq!(chain[1], ProviderKind::OpenAi);
777        assert_eq!(chain[2], ProviderKind::Ollama);
778        // Auto-discovered subscription providers may be appended after index 2.
779    }
780
781    #[test]
782    fn resolved_chain_skips_disabled() {
783        let mut cfg = ProvidersConfig {
784            fallback_chain: vec!["openai".into(), "ollama".into()],
785            ..ProvidersConfig::default()
786        };
787        cfg.openai.enabled = false;
788        let chain = cfg.resolved_chain();
789        // Disabled provider must not appear in the chain, even as an auto-fallback.
790        assert!(!chain.contains(&ProviderKind::OpenAi));
791        // Ollama (explicitly added and enabled) must be present.
792        assert!(chain.contains(&ProviderKind::Ollama));
793    }
794
795    #[test]
796    fn entry_ref_all_kinds() {
797        let cfg = ProvidersConfig::default();
798        for k in ProviderKind::all_slugs() {
799            let kind = ProviderKind::from_slug(k).unwrap();
800            let _ = cfg.entry(kind);
801            // All slugs should round-trip correctly
802            assert_eq!(kind.slug(), *k);
803        }
804    }
805
806    #[test]
807    fn resolve_api_key_prefers_config() {
808        let entry = ProviderEntry {
809            api_key: Some("cfg-key".into()),
810            ..ProviderEntry::default()
811        };
812        // Even if env var is set, config key wins
813        let resolved = entry.resolve_api_key("NONEXISTENT_TEST_VAR_XYZ");
814        assert_eq!(resolved, Some("cfg-key".into()));
815    }
816
817    #[test]
818    fn resolve_model_uses_default_when_unset() {
819        let entry = ProviderEntry::default();
820        assert_eq!(
821            entry.resolve_model(ProviderKind::Gemini),
822            "gemini-3-flash-preview"
823        );
824        // GeminiCli now defaults to gemini-3-flash-preview (Gemini 3 Flash)
825        assert_eq!(
826            entry.resolve_model(ProviderKind::GeminiCli),
827            "gemini-3-flash-preview"
828        );
829    }
830
831    #[test]
832    fn resolve_model_alias_expansion() {
833        // "flash" → gemini-3-flash-preview for GeminiCli
834        let mut entry = ProviderEntry {
835            model: Some("flash".into()),
836            ..ProviderEntry::default()
837        };
838        assert_eq!(
839            entry.resolve_model(ProviderKind::GeminiCli),
840            "gemini-3-flash-preview"
841        );
842        // "flash" → gemini-3-flash-preview for Gemini REST (now added as alias)
843        assert_eq!(
844            entry.resolve_model(ProviderKind::Gemini),
845            "gemini-3-flash-preview"
846        );
847        // "flash" is not a known Anthropic alias — passed through as literal
848        assert_eq!(entry.resolve_model(ProviderKind::Anthropic), "flash");
849
850        // "haiku" → full Anthropic model ID
851        entry.model = Some("haiku".into());
852        assert_eq!(
853            entry.resolve_model(ProviderKind::Anthropic),
854            "claude-haiku-4-5-20251001"
855        );
856
857        // "sonnet" → Claude Sonnet
858        entry.model = Some("sonnet".into());
859        assert_eq!(
860            entry.resolve_model(ProviderKind::Anthropic),
861            "claude-sonnet-4-6"
862        );
863    }
864
865    #[test]
866    fn resolve_model_unknown_alias_passes_through() {
867        let entry = ProviderEntry {
868            model: Some("my-custom-model:latest".into()),
869            ..ProviderEntry::default()
870        };
871        assert_eq!(
872            entry.resolve_model(ProviderKind::Ollama),
873            "my-custom-model:latest"
874        );
875    }
876
877    #[test]
878    fn model_registry_all_providers_have_default() {
879        for slug in ProviderKind::all_slugs() {
880            let kind = ProviderKind::from_slug(slug).unwrap();
881            let default = ModelRegistry::default_model(kind);
882            assert!(
883                !default.is_empty(),
884                "Provider {slug} has empty default model"
885            );
886            // Default must appear in models_for() list
887            let listed = ModelRegistry::models_for(kind)
888                .iter()
889                .any(|m| m.id == default);
890            assert!(
891                listed,
892                "Provider {slug} default model '{default}' not in models_for() list"
893            );
894        }
895    }
896
897    #[test]
898    fn model_registry_no_duplicate_aliases() {
899        for slug in ProviderKind::all_slugs() {
900            let kind = ProviderKind::from_slug(slug).unwrap();
901            let mut seen = std::collections::HashSet::new();
902            for model in ModelRegistry::models_for(kind) {
903                for alias in model.aliases {
904                    assert!(
905                        seen.insert(*alias),
906                        "Provider {slug}: duplicate alias '{alias}'"
907                    );
908                }
909            }
910        }
911    }
912}