Skip to main content

oxios_kernel/kernel_handle/
engine_api.rs

1//! Engine API — LLM engine introspection + config writes + routing control.
2//!
3//! Provides access to the oxi-sdk model catalog (providers, models, search)
4//! and write operations that persist to config.toml (model, API key, routing).
5//!
6//! Routing statistics (`RoutingStats`) are shared between this API and
7//! `AgentRuntime` via an `Arc`, so model usage is recorded end-to-end.
8
9use crate::config::OxiosConfig;
10use crate::credential::CredentialStore;
11use anyhow::Context;
12use chrono::{DateTime, Utc};
13use parking_lot::RwLock;
14use serde::{Deserialize, Serialize};
15use std::collections::HashMap;
16use std::path::PathBuf;
17use std::sync::Arc;
18
19// ── Routing types ─────────────────────────────────────────────────────────────
20
21/// Snapshot of routing configuration (read-only API response).
22#[derive(Debug, Clone, Serialize, Deserialize)]
23#[serde(rename_all = "camelCase")]
24pub struct RoutingConfigSnapshot {
25    /// Whether automatic model routing is enabled.
26    pub routing_enabled: bool,
27    /// Whether cost-efficient models are preferred when routing.
28    pub prefer_cost_efficient: bool,
29    /// Ordered list of fallback models (tried left-to-right on primary failure).
30    pub fallback_models: Vec<String>,
31    /// Models excluded from automatic routing.
32    pub excluded_models: Vec<String>,
33}
34
35/// Model usage statistics.
36#[derive(Debug, Clone, Serialize, Deserialize)]
37#[serde(rename_all = "camelCase")]
38pub struct RoutingStatsSnapshot {
39    /// Model ID → number of calls.
40    pub model_calls: HashMap<String, u64>,
41    /// Model ID → estimated total cost (USD).
42    pub model_cost: HashMap<String, f64>,
43    /// Total number of requests.
44    pub total_requests: u64,
45    /// Total estimated cost (USD).
46    pub total_cost: f64,
47}
48
49/// Single fallback event record.
50#[derive(Debug, Clone, Serialize, Deserialize)]
51#[serde(rename_all = "camelCase")]
52pub struct FallbackEvent {
53    /// When the fallback occurred.
54    pub timestamp: DateTime<Utc>,
55    /// Model that was skipped/replaced.
56    pub from_model: String,
57    /// Model that was used instead.
58    pub to_model: String,
59    /// Reason for fallback (e.g. "rate_limit", "context_overflow", "error").
60    pub reason: String,
61    /// Whether the fallback succeeded (no further fallback needed).
62    pub success: bool,
63}
64
65/// Request body for `PUT /api/engine/routing`.
66#[derive(Debug, Deserialize)]
67#[serde(rename_all = "camelCase")]
68pub struct RoutingUpdate {
69    pub routing_enabled: Option<bool>,
70    pub prefer_cost_efficient: Option<bool>,
71    pub fallback_models: Option<Vec<String>>,
72    pub excluded_models: Option<Vec<String>>,
73}
74
75// ── RoutingStats ─────────────────────────────────────────────────────────────
76
77/// In-memory routing statistics, shared between `EngineApi` and `AgentRuntime`.
78/// Uses simple RwLock for thread-safe reads/writes.
79pub struct RoutingStats {
80    calls: RwLock<HashMap<String, u64>>,
81    costs: RwLock<HashMap<String, f64>>,
82    /// Circular buffer of recent fallback events (max 200).
83    fallbacks: RwLock<std::collections::VecDeque<FallbackEvent>>,
84}
85
86impl Default for RoutingStats {
87    fn default() -> Self {
88        Self {
89            calls: RwLock::new(HashMap::new()),
90            costs: RwLock::new(HashMap::new()),
91            fallbacks: RwLock::new(std::collections::VecDeque::new()),
92        }
93    }
94}
95
96impl RoutingStats {
97    /// Create a new stats tracker.
98    pub fn new() -> Self {
99        Self::default()
100    }
101
102    /// Record one model invocation.
103    pub fn record_model_usage(&self, model_id: &str, cost_usd: f64) {
104        let mut calls = self.calls.write();
105        *calls.entry(model_id.to_string()).or_insert(0) += 1;
106        if cost_usd > 0.0 {
107            let mut costs = self.costs.write();
108            *costs.entry(model_id.to_string()).or_insert(0.0) += cost_usd;
109        }
110    }
111
112    /// Record a fallback event.
113    ///
114    /// Uses `VecDeque` so trimming is O(1) (`pop_front`) instead of the O(n)
115    /// memmove that `Vec::drain(0..keep)` performs under the write lock.
116    pub fn record_fallback(&self, event: FallbackEvent) {
117        let mut fb = self.fallbacks.write();
118        fb.push_back(event);
119        while fb.len() > 200 {
120            fb.pop_front();
121        }
122    }
123
124    /// Get a snapshot of current stats.
125    pub fn snapshot(&self) -> RoutingStatsSnapshot {
126        let calls = self.calls.read();
127        let costs = self.costs.read();
128        let total_requests: u64 = calls.values().sum();
129        let total_cost: f64 = costs.values().sum();
130        RoutingStatsSnapshot {
131            model_calls: calls.clone(),
132            model_cost: costs.clone(),
133            total_requests,
134            total_cost,
135        }
136    }
137
138    /// Get recent fallback events, newest first.
139    pub fn fallback_history(&self, limit: usize) -> Vec<FallbackEvent> {
140        let fb = self.fallbacks.read();
141        fb.iter().rev().take(limit).cloned().collect()
142    }
143}
144
145// ── Model cost estimation ────────────────────────────────────────────────────
146
147/// Estimate cost in USD for a model given token usage.
148/// Uses oxi-sdk's model_db for per-model pricing.
149pub fn estimate_cost(model_id: &str, input_tokens: u64, output_tokens: u64) -> f64 {
150    let entries = oxi_sdk::get_provider_models(model_id.split('/').next().unwrap_or(model_id));
151    let entry = entries
152        .iter()
153        .find(|e| format!("{}/{}", e.provider, e.id) == model_id);
154    match entry {
155        Some(e) => {
156            (e.cost_input * input_tokens as f64 / 1_000_000.0)
157                + (e.cost_output * output_tokens as f64 / 1_000_000.0)
158        }
159        None => {
160            // Fall back to a rough estimate for unknown models
161            (0.003 * input_tokens as f64 / 1_000_000.0)
162                + (0.015 * output_tokens as f64 / 1_000_000.0)
163        }
164    }
165}
166
167// ── Provider/Model response types ──────────────────────────────────────────
168
169/// Provider category for UI grouping.
170#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
171#[serde(rename_all = "lowercase")]
172pub enum ProviderCategory {
173    /// Major providers (Anthropic, OpenAI, Google).
174    Major,
175    /// Open / specialty providers (Groq, OpenRouter, DeepSeek, etc.).
176    Open,
177    /// Regional providers.
178    Regional,
179    /// Local / self-hosted providers.
180    Local,
181}
182
183/// Static metadata for an LLM provider.
184///
185/// This table is the **single source of truth** for provider-facing
186/// metadata in the Web UI. It enriches the dynamic list returned by
187/// `oxi_sdk::get_providers()` with human-friendly labels, UI grouping,
188/// and a flag for providers that should not be exposed to the Web
189/// dashboard (e.g. those requiring non-API-key auth like AWS SigV4 or
190/// OAuth, or region-specific endpoints).
191///
192/// New providers added to `oxi-sdk` automatically appear in the UI
193/// with sensible fallbacks (`Open` category, derived display name)
194/// even before they get an entry here.
195#[derive(Debug, Clone, Copy)]
196struct ProviderMeta {
197    /// Canonical provider id (matches `oxi_sdk::get_providers()`).
198    id: &'static str,
199    /// Human-readable name shown in dropdowns and badges.
200    display_name: &'static str,
201    /// UI grouping for the provider selector.
202    category: ProviderCategory,
203    /// Whether to exclude from the Web UI providers list.
204    /// Used for providers with non-standard auth (AWS SigV4, OAuth,
205    /// account-scoped URLs) or that are region-specific duplicates.
206    hidden: bool,
207    /// Short description for tooltips / help text.
208    description: &'static str,
209    /// Primary environment variable name holding the API key.
210    /// Empty string when the provider does not use a single env var
211    /// (e.g. AWS Bedrock uses a credential chain).
212    env_key: &'static str,
213    /// Alternative ids that should resolve to this provider.
214    /// Used so that an alias such as `aws-bedrock` matches the
215    /// canonical `amazon-bedrock` entry.
216    aliases: &'static [&'static str],
217}
218
219/// All provider metadata, in a single static table.
220///
221/// Order is for human readability only — the runtime lookup is O(n)
222/// linear scan, which is fine for ~30 entries. If the table grows
223/// past ~100 entries, swap to a `phf` or `once_cell` hash map.
224const PROVIDER_META: &[ProviderMeta] = &[
225    // ── Major (top 3) ──────────────────────────────────────────────
226    ProviderMeta {
227        id: "anthropic",
228        display_name: "Anthropic",
229        category: ProviderCategory::Major,
230        hidden: false,
231        description: "Claude models with extended thinking",
232        env_key: "ANTHROPIC_API_KEY",
233        aliases: &["anthropic"],
234    },
235    ProviderMeta {
236        id: "openai",
237        display_name: "OpenAI",
238        category: ProviderCategory::Major,
239        hidden: false,
240        description: "GPT, o-series, and Codex models",
241        env_key: "OPENAI_API_KEY",
242        aliases: &["openai"],
243    },
244    ProviderMeta {
245        id: "google",
246        display_name: "Google Gemini",
247        category: ProviderCategory::Major,
248        hidden: false,
249        description: "Gemini models with thinking and tool use",
250        env_key: "GOOGLE_API_KEY",
251        aliases: &["google"],
252    },
253    // ── Open / specialty (gateways + open-weight hosts) ────────────
254    ProviderMeta {
255        id: "groq",
256        display_name: "Groq",
257        category: ProviderCategory::Open,
258        hidden: false,
259        description: "Fast Llama, Mixtral, and Gemma inference",
260        env_key: "GROQ_API_KEY",
261        aliases: &["groq"],
262    },
263    ProviderMeta {
264        id: "openrouter",
265        display_name: "OpenRouter",
266        category: ProviderCategory::Open,
267        hidden: false,
268        description: "Unified gateway to 200+ models",
269        env_key: "OPENROUTER_API_KEY",
270        aliases: &["openrouter"],
271    },
272    ProviderMeta {
273        id: "deepseek",
274        display_name: "DeepSeek",
275        category: ProviderCategory::Open,
276        hidden: false,
277        description: "DeepSeek-V3 and DeepSeek-R1",
278        env_key: "DEEPSEEK_API_KEY",
279        aliases: &["deepseek"],
280    },
281    ProviderMeta {
282        id: "mistral",
283        display_name: "Mistral",
284        category: ProviderCategory::Open,
285        hidden: false,
286        description: "Mistral and Codestral models",
287        env_key: "MISTRAL_API_KEY",
288        aliases: &["mistral"],
289    },
290    ProviderMeta {
291        id: "xai",
292        display_name: "xAI (Grok)",
293        category: ProviderCategory::Open,
294        hidden: false,
295        description: "Grok models from xAI",
296        env_key: "XAI_API_KEY",
297        aliases: &["xai", "grok"],
298    },
299    ProviderMeta {
300        id: "cerebras",
301        display_name: "Cerebras",
302        category: ProviderCategory::Open,
303        hidden: false,
304        description: "Ultra-fast open model inference",
305        env_key: "CEREBRAS_API_KEY",
306        aliases: &["cerebras"],
307    },
308    ProviderMeta {
309        id: "fireworks",
310        display_name: "Fireworks",
311        category: ProviderCategory::Open,
312        hidden: false,
313        description: "Fast open-source model serving",
314        env_key: "FIREWORKS_API_KEY",
315        aliases: &["fireworks"],
316    },
317    ProviderMeta {
318        id: "github-copilot",
319        display_name: "GitHub Copilot",
320        category: ProviderCategory::Open,
321        hidden: false,
322        description: "GitHub Copilot models (GPT-4, Claude)",
323        env_key: "GITHUB_COPILOT_TOKEN",
324        aliases: &["github-copilot", "copilot"],
325    },
326    ProviderMeta {
327        id: "huggingface",
328        display_name: "Hugging Face",
329        category: ProviderCategory::Open,
330        hidden: false,
331        description: "Open model inference hub",
332        env_key: "HUGGINGFACE_API_KEY",
333        aliases: &["huggingface", "hf"],
334    },
335    ProviderMeta {
336        id: "together",
337        display_name: "Together AI",
338        category: ProviderCategory::Open,
339        hidden: false,
340        description: "Open-source model hosting (Llama, Mixtral, ...)",
341        env_key: "TOGETHER_API_KEY",
342        aliases: &["together", "togetherai"],
343    },
344    ProviderMeta {
345        id: "opencode",
346        display_name: "OpenCode",
347        category: ProviderCategory::Open,
348        hidden: false,
349        description: "OpenCode coding agent gateway",
350        env_key: "",
351        aliases: &["opencode"],
352    },
353    ProviderMeta {
354        id: "perplexity",
355        display_name: "Perplexity",
356        category: ProviderCategory::Open,
357        hidden: false,
358        description: "Search-augmented answer models",
359        env_key: "PERPLEXITY_API_KEY",
360        aliases: &["perplexity"],
361    },
362    ProviderMeta {
363        id: "cohere",
364        display_name: "Cohere",
365        category: ProviderCategory::Open,
366        hidden: false,
367        description: "Cohere Command and Embed models",
368        env_key: "COHERE_API_KEY",
369        aliases: &["cohere"],
370    },
371    // ── Regional (Chinese / Asian providers) ───────────────────────
372    ProviderMeta {
373        id: "minimax",
374        display_name: "MiniMax",
375        category: ProviderCategory::Regional,
376        hidden: false,
377        description: "MiniMax-M2.7, abab models",
378        env_key: "MINIMAX_API_KEY",
379        aliases: &["minimax"],
380    },
381    ProviderMeta {
382        id: "moonshotai",
383        display_name: "Moonshot AI (Kimi)",
384        category: ProviderCategory::Regional,
385        hidden: false,
386        description: "Kimi models from Moonshot AI",
387        env_key: "MOONSHOT_API_KEY",
388        aliases: &["moonshotai", "moonshot", "kimi"],
389    },
390    ProviderMeta {
391        id: "kimi-coding",
392        display_name: "Kimi Coding",
393        category: ProviderCategory::Regional,
394        hidden: false,
395        description: "Kimi Coding Plan — optimized for coding",
396        env_key: "KIMI_CODING_API_KEY",
397        aliases: &["kimi-coding"],
398    },
399    ProviderMeta {
400        id: "zai",
401        display_name: "Z.AI (GLM)",
402        category: ProviderCategory::Regional,
403        hidden: false,
404        description: "Z.AI GLM models (coding plan)",
405        env_key: "ZAI_API_KEY",
406        aliases: &["zai"],
407    },
408    // ── Hidden in Web UI today; mapped for forward-compatibility ───
409    // These providers are not exposed by `EngineHandle::providers()`
410    // because they require non-standard auth or region-specific setup,
411    // but listing them here means the metadata is already wired up if
412    // a future change decides to surface them.
413    ProviderMeta {
414        id: "amazon-bedrock",
415        display_name: "Amazon Bedrock",
416        category: ProviderCategory::Open,
417        hidden: true,
418        description: "Multi-model via AWS Bedrock ConverseStream",
419        env_key: "AWS_ACCESS_KEY_ID",
420        aliases: &["amazon-bedrock", "aws-bedrock", "bedrock"],
421    },
422    ProviderMeta {
423        id: "azure-openai-responses",
424        display_name: "Azure OpenAI (Responses)",
425        category: ProviderCategory::Open,
426        hidden: true,
427        description: "OpenAI models via Azure Cognitive Services",
428        env_key: "AZURE_OPENAI_API_KEY",
429        aliases: &["azure-openai-responses", "azure"],
430    },
431    ProviderMeta {
432        id: "cloudflare-ai-gateway",
433        display_name: "Cloudflare AI Gateway",
434        category: ProviderCategory::Open,
435        hidden: true,
436        description: "Serverless AI via Cloudflare AI Gateway",
437        env_key: "CLOUDFLARE_API_TOKEN",
438        aliases: &["cloudflare-ai-gateway", "cf-ai-gateway"],
439    },
440    ProviderMeta {
441        id: "cloudflare-workers-ai",
442        display_name: "Cloudflare Workers AI",
443        category: ProviderCategory::Open,
444        hidden: true,
445        description: "Serverless AI via Cloudflare Workers",
446        env_key: "CLOUDFLARE_API_KEY",
447        aliases: &["cloudflare-workers-ai", "cloudflare", "workers-ai"],
448    },
449    ProviderMeta {
450        id: "google-vertex",
451        display_name: "Google Vertex AI",
452        category: ProviderCategory::Open,
453        hidden: true,
454        description: "Gemini via Google Cloud Vertex AI",
455        env_key: "GOOGLE_APPLICATION_CREDENTIALS",
456        aliases: &["google-vertex", "vertex"],
457    },
458    ProviderMeta {
459        id: "minimax-cn",
460        display_name: "MiniMax (China)",
461        category: ProviderCategory::Regional,
462        hidden: true,
463        description: "MiniMax China region endpoint",
464        env_key: "MINIMAX_CN_API_KEY",
465        aliases: &["minimax-cn"],
466    },
467    ProviderMeta {
468        id: "moonshotai-cn",
469        display_name: "Moonshot AI (China)",
470        category: ProviderCategory::Regional,
471        hidden: true,
472        description: "Kimi models — China region endpoint",
473        env_key: "MOONSHOT_CN_API_KEY",
474        aliases: &["moonshotai-cn", "moonshot-cn"],
475    },
476    ProviderMeta {
477        id: "openai-codex",
478        display_name: "OpenAI Codex",
479        category: ProviderCategory::Open,
480        hidden: true,
481        description: "OpenAI Codex coding agent (Responses API)",
482        env_key: "OPENAI_API_KEY",
483        aliases: &["openai-codex"],
484    },
485    ProviderMeta {
486        id: "opencode-go",
487        display_name: "OpenCode Go",
488        category: ProviderCategory::Open,
489        hidden: true,
490        description: "OpenCode Go Gateway",
491        env_key: "OPENCODE_GO_API_KEY",
492        aliases: &["opencode-go"],
493    },
494    ProviderMeta {
495        id: "vercel-ai-gateway",
496        display_name: "Vercel AI Gateway",
497        category: ProviderCategory::Open,
498        hidden: true,
499        description: "Vercel AI Gateway",
500        env_key: "VERCEL_API_KEY",
501        aliases: &["vercel-ai-gateway", "vercel"],
502    },
503    ProviderMeta {
504        id: "xiaomi",
505        display_name: "Xiaomi MiMo",
506        category: ProviderCategory::Regional,
507        hidden: true,
508        description: "Xiaomi MiMo models",
509        env_key: "XIAOMI_API_KEY",
510        aliases: &["xiaomi"],
511    },
512];
513
514/// Look up metadata by canonical id or alias.
515fn provider_meta(id: &str) -> Option<&'static ProviderMeta> {
516    PROVIDER_META
517        .iter()
518        .find(|m| m.id == id || m.aliases.contains(&id))
519}
520
521fn provider_category(id: &str) -> ProviderCategory {
522    provider_meta(id)
523        .map(|m| m.category)
524        .unwrap_or(ProviderCategory::Open)
525}
526
527/// Resolve a display name for a provider id.
528///
529/// Falls back to a Title-Cased id for unknown providers so that
530/// newly added `oxi-sdk` providers still render acceptably until a
531/// real entry lands in [`PROVIDER_META`].
532fn provider_display_name(id: &str) -> String {
533    provider_meta(id)
534        .map(|m| m.display_name.to_string())
535        .unwrap_or_else(|| fallback_display_name(id))
536}
537
538/// Render a fallback display name by splitting on `-` / `_` and
539/// Title-Casing each segment. Examples:
540///   `"kimi-coding"`   → `"Kimi Coding"`
541///   `"some_id"`       → `"Some Id"`
542///   `"openai"`        → `"Openai"`
543fn fallback_display_name(id: &str) -> String {
544    id.split(['-', '_'])
545        .filter(|s| !s.is_empty())
546        .map(|segment| {
547            let mut chars = segment.chars();
548            match chars.next() {
549                Some(c) => c.to_uppercase().collect::<String>() + chars.as_str(),
550                None => String::new(),
551            }
552        })
553        .collect::<Vec<_>>()
554        .join(" ")
555}
556
557/// Summary of an LLM provider.
558#[derive(Debug, Clone, Serialize, Deserialize)]
559#[serde(rename_all = "camelCase")]
560pub struct ProviderInfo {
561    /// Provider identifier (e.g. "anthropic", "openai").
562    pub id: String,
563    /// Human-readable display name.
564    pub name: String,
565    /// Category for UI grouping.
566    pub category: ProviderCategory,
567    /// Number of models available for this provider.
568    pub model_count: usize,
569    /// Whether an API key is currently configured.
570    pub has_key: bool,
571    /// Source of the API key: `"env"`, `"auth_store"`, `"config"`, or `"none"`.
572    /// Used by the Web UI to determine whether the key is removable
573    /// (env-var-sourced keys cannot be cleared via the API).
574    #[serde(default)]
575    pub key_source: String,
576    /// Short description for tooltips / help text. Empty for unknown
577    /// providers that have no entry in [`PROVIDER_META`].
578    #[serde(default)]
579    pub description: String,
580    /// Primary environment variable name for the API key. Empty for
581    /// providers that do not use a single env var (e.g. AWS Bedrock
582    /// uses a credential chain rather than a single API key var).
583    #[serde(default)]
584    pub env_key: String,
585}
586
587/// Input modality for a model.
588#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
589#[serde(rename_all = "lowercase")]
590pub enum InputModality {
591    /// Text input.
592    Text,
593    /// Image input (vision).
594    Image,
595}
596
597/// Summary of a model from the catalog.
598#[derive(Debug, Clone, Serialize, Deserialize)]
599#[serde(rename_all = "camelCase")]
600pub struct ModelInfo {
601    /// Full model ID: "provider/model-id".
602    pub id: String,
603    /// Human-readable model name.
604    pub name: String,
605    /// API protocol used by the model's provider.
606    pub api: String,
607    /// Provider name.
608    pub provider: String,
609    /// Whether this model supports reasoning/thinking.
610    pub reasoning: bool,
611    /// Supported input modalities.
612    pub input: Vec<InputModality>,
613    /// Maximum context window in tokens.
614    pub context_window: u32,
615    /// Maximum output tokens.
616    pub max_tokens: u32,
617    /// Cost per million input tokens (USD).
618    pub cost_input: f64,
619    /// Cost per million output tokens (USD).
620    pub cost_output: f64,
621    /// Cost per million cached read tokens (USD).
622    pub cost_cache_read: f64,
623    /// Cost per million cached write tokens (USD).
624    pub cost_cache_write: f64,
625}
626
627impl From<&oxi_sdk::ModelEntry> for ModelInfo {
628    fn from(entry: &oxi_sdk::ModelEntry) -> Self {
629        Self {
630            id: format!("{}/{}", entry.provider, entry.id),
631            name: entry.name.to_string(),
632            api: entry.api.to_string(),
633            provider: entry.provider.to_string(),
634            reasoning: entry.reasoning,
635            input: entry
636                .input
637                .iter()
638                .map(|m| match m {
639                    oxi_sdk::InputModality::Text => InputModality::Text,
640                    oxi_sdk::InputModality::Image => InputModality::Image,
641                    _ => InputModality::Text,
642                })
643                .collect(),
644            context_window: entry.context_window,
645            max_tokens: entry.max_tokens,
646            cost_input: entry.cost_input,
647            cost_output: entry.cost_output,
648            cost_cache_read: entry.cost_cache_read,
649            cost_cache_write: entry.cost_cache_write,
650        }
651    }
652}
653
654impl From<&oxi_sdk::CatalogModelEntry> for ModelInfo {
655    /// Build a [`ModelInfo`] from a live catalog entry (catalog port).
656    ///
657    /// Same fields as the [`ModelEntry`](oxi_sdk::ModelEntry) path; the
658    /// catalog entry additionally reflects runtime models.dev refresh +
659    /// user overrides when wired into the engine.
660    fn from(entry: &oxi_sdk::CatalogModelEntry) -> Self {
661        Self {
662            id: format!("{}/{}", entry.provider, entry.model_id),
663            name: entry.name.clone(),
664            api: entry.protocol.as_str().to_string(),
665            provider: entry.provider.clone(),
666            reasoning: entry.reasoning,
667            input: entry
668                .input_modalities
669                .iter()
670                .map(|m| match m.as_str() {
671                    "image" => InputModality::Image,
672                    _ => InputModality::Text,
673                })
674                .collect(),
675            context_window: entry.context_window,
676            max_tokens: entry.max_tokens,
677            cost_input: entry.cost_input,
678            cost_output: entry.cost_output,
679            cost_cache_read: entry.cost_cache_read,
680            cost_cache_write: entry.cost_cache_write,
681        }
682    }
683}
684
685/// Current engine configuration + credential status + routing.
686#[derive(Debug, Clone, Serialize, Deserialize)]
687pub struct EngineConfigResponse {
688    /// Currently configured default model.
689    pub default_model: String,
690    /// Whether an API key is set for the current provider.
691    pub api_key_set: bool,
692    /// Source of the API key (if any).
693    pub api_key_source: Option<String>,
694    /// Provider name extracted from default_model.
695    pub provider: Option<String>,
696    /// Current routing configuration.
697    pub routing: RoutingConfigSnapshot,
698}
699
700/// Result of an API key validation attempt.
701#[derive(Debug, Clone, Serialize, Deserialize)]
702pub struct ValidateKeyResult {
703    /// Whether the key is valid.
704    pub valid: bool,
705    /// Provider that was validated.
706    pub provider: String,
707    /// Optional message (error detail or success note).
708    pub message: Option<String>,
709}
710
711// ── EngineApi ───────────────────────────────────────────────────────────────
712
713/// Engine API facade — model catalog introspection + config writes + routing.
714///
715/// Holds a shared reference to the live config (behind `RwLock`) and the
716/// path to config.toml so write operations can persist to disk.
717/// Routing stats are shared with `AgentRuntime` via `Arc<RoutingStats>`.
718///
719/// When config writes change the model or API key, `EngineApi` rebuilds
720/// `OxiosEngine` via [`EngineHandle`] so the runtime picks up the change
721/// on the next agent execution (hot-swap, no restart required).
722pub struct EngineApi {
723    config: Arc<RwLock<OxiosConfig>>,
724    config_path: PathBuf,
725    routing_stats: Arc<RoutingStats>,
726    /// Hot-swap handle — config writes rebuild `OxiosEngine` and swap it in.
727    engine_handle: Arc<crate::engine::EngineHandle>,
728}
729
730impl EngineApi {
731    /// Create a new EngineApi.
732    ///
733    /// - `config` — shared config store (backed by RwLock)
734    /// - `config_path` — path to config.toml for persistence
735    /// - `routing_stats` — shared stats tracker (shared with AgentRuntime)
736    /// - `engine_handle` — hot-swap handle for live engine replacement
737    pub fn new(
738        config: Arc<RwLock<OxiosConfig>>,
739        config_path: PathBuf,
740        routing_stats: Arc<RoutingStats>,
741        engine_handle: Arc<crate::engine::EngineHandle>,
742    ) -> Self {
743        Self {
744            config,
745            config_path,
746            routing_stats,
747            engine_handle,
748        }
749    }
750
751    /// Get the shared `RoutingStats` reference (for `AgentRuntime` wiring).
752    pub fn routing_stats(&self) -> Arc<RoutingStats> {
753        Arc::clone(&self.routing_stats)
754    }
755
756    /// Get a reference to the engine handle.
757    pub fn engine_handle(&self) -> &Arc<crate::engine::EngineHandle> {
758        &self.engine_handle
759    }
760
761    // ── Read operations ────────────────────────────────────────────────
762
763    /// List all available providers from the oxi-sdk catalog.
764    ///
765    /// Reads provider/model counts from the live catalog (runtime models.dev
766    /// refresh + user overrides) when wired into the engine, falling back to
767    /// the static registry otherwise.
768    ///
769    /// Filters out hidden/internal providers (those flagged with
770    /// `hidden: true` in [`PROVIDER_META`]) and augments each entry
771    /// with credential status, display name, and description.
772    ///
773    /// Providers without a [`PROVIDER_META`] entry are shown by
774    /// default — a new provider landing in `oxi-sdk` should be
775    /// available to users even before its metadata is added here.
776    pub fn providers(&self) -> Vec<ProviderInfo> {
777        let catalog = self.engine_handle.get().oxi().catalog().clone();
778        let use_catalog = catalog.model_count_sync() > 0;
779        let all: Vec<String> = if use_catalog {
780            catalog.list_providers_sync()
781        } else {
782            oxi_sdk::get_providers()
783                .into_iter()
784                .map(|s| s.to_string())
785                .collect()
786        };
787
788        // Hoist the read-lock out of the per-provider closure: the previous
789        // implementation took the lock once per provider (~30 times) and
790        // re-read the same api_key each time. One read + clone is enough.
791        let api_key_override = {
792            let cfg = self.config.read();
793            cfg.engine
794                .api_key
795                .as_deref()
796                .filter(|k| !k.is_empty())
797                .map(str::to_owned)
798        };
799        all.into_iter()
800            .filter(|p| provider_meta(p).map(|m| !m.hidden).unwrap_or(true))
801            .map(|p| {
802                let model_count = if use_catalog {
803                    catalog.list_models_sync(&p).len()
804                } else {
805                    oxi_sdk::get_provider_models(&p).len()
806                };
807                let resolved = CredentialStore::resolve(&p, api_key_override.as_deref());
808                let has_key = resolved.is_some();
809                let key_source = resolved
810                    .map(|(_, src)| match src {
811                        crate::credential::CredentialSource::EnvVar => "env",
812                        crate::credential::CredentialSource::Config => "config",
813                        crate::credential::CredentialSource::OxiAuthStore => "auth_store",
814                    })
815                    .unwrap_or("none")
816                    .to_string();
817                let meta = provider_meta(&p);
818                ProviderInfo {
819                    id: p.clone(),
820                    name: provider_display_name(&p),
821                    category: provider_category(&p),
822                    model_count,
823                    has_key,
824                    key_source,
825                    description: meta.map(|m| m.description.to_string()).unwrap_or_default(),
826                    env_key: meta.map(|m| m.env_key.to_string()).unwrap_or_default(),
827                }
828            })
829            .collect()
830    }
831
832    /// List models for a given provider, optionally filtered by a query.
833    ///
834    /// Reads from the live catalog (runtime models.dev refresh + user
835    /// overrides) when wired into the engine, falling back to the static
836    /// registry (embedded snapshot) otherwise.
837    pub fn models(&self, provider: &str, query: Option<&str>) -> Vec<ModelInfo> {
838        let catalog = self.engine_handle.get().oxi().catalog().clone();
839        let live = catalog.list_models_sync(provider);
840        let models: Vec<ModelInfo> = if !live.is_empty() {
841            live.iter().map(ModelInfo::from).collect()
842        } else {
843            oxi_sdk::get_provider_models(provider)
844                .iter()
845                .map(ModelInfo::from)
846                .collect()
847        };
848        models
849            .into_iter()
850            .filter(|m| !m.name.contains("latest"))
851            .filter(|m| {
852                if let Some(q) = query {
853                    let q = q.to_lowercase();
854                    m.name.to_lowercase().contains(&q)
855                        || m.id.to_lowercase().contains(&q)
856                        || m.provider.to_lowercase().contains(&q)
857                } else {
858                    true
859                }
860            })
861            .collect()
862    }
863
864    /// Search models across all providers.
865    ///
866    /// Uses the live catalog's `search_sync` when available, else the static
867    /// registry.
868    pub fn search_models(&self, query: &str) -> Vec<ModelInfo> {
869        let catalog = self.engine_handle.get().oxi().catalog().clone();
870        let live = catalog.search_sync(query);
871        if !live.is_empty() {
872            live.iter().map(ModelInfo::from).collect()
873        } else {
874            oxi_sdk::search_models(query)
875                .into_iter()
876                .map(ModelInfo::from)
877                .collect()
878        }
879    }
880
881    /// Get the current engine configuration + credential status + routing.
882    pub fn config(&self) -> EngineConfigResponse {
883        let cfg = self.config.read();
884        let provider =
885            CredentialStore::provider_from_model(&cfg.engine.default_model).map(|s| s.to_string());
886        let api_key_source = provider.as_deref().and_then(|p| {
887            CredentialStore::resolve(p, cfg.api_key().as_deref()).map(|(_, src)| {
888                match src {
889                    crate::credential::CredentialSource::EnvVar => "env",
890                    crate::credential::CredentialSource::Config => "config",
891                    crate::credential::CredentialSource::OxiAuthStore => "auth_store",
892                }
893                .to_string()
894            })
895        });
896        let api_key_set = provider
897            .as_deref()
898            .map(|p| CredentialStore::has_credential(p, cfg.api_key().as_deref()))
899            .unwrap_or(false);
900
901        EngineConfigResponse {
902            default_model: cfg.engine.default_model.clone(),
903            api_key_set,
904            api_key_source,
905            provider,
906            routing: RoutingConfigSnapshot {
907                routing_enabled: cfg.engine.routing_enabled,
908                prefer_cost_efficient: cfg.engine.prefer_cost_efficient,
909                fallback_models: cfg.engine.fallback_models.clone(),
910                excluded_models: cfg.engine.excluded_models.clone(),
911            },
912        }
913    }
914
915    /// Get routing stats snapshot (for Web dashboard).
916    pub fn routing_stats_snapshot(&self) -> RoutingStatsSnapshot {
917        self.routing_stats.snapshot()
918    }
919
920    /// Get recent fallback history.
921    pub fn fallback_history(&self, limit: usize) -> Vec<FallbackEvent> {
922        self.routing_stats.fallback_history(limit)
923    }
924
925    // ── Write operations ───────────────────────────────────────────────
926
927    /// Set the default model in config.toml.
928    ///
929    /// Updates both the in-memory config and the on-disk file, then
930    /// hot-swaps the runtime engine so the next agent execution uses the new model.
931    pub fn set_model(&self, model_id: &str) -> anyhow::Result<()> {
932        // Validate BEFORE persisting/swapping: reject unknown models and
933        // unconfigured providers so the Web UI's "switch succeeded" is truthful.
934        // This prevents the divergence where a bad model ID was silently
935        // accepted at swap time and only surfaced as "Model not found" at the
936        // execute phase — after interview/seed had already run.
937        {
938            let engine = self.engine_handle.get();
939            let model = engine
940                .resolve_model(model_id)
941                .with_context(|| format!("Unknown model '{model_id}'"))?;
942            engine.create_provider(&model.provider).with_context(|| {
943                format!(
944                    "Provider '{}' is not configured for '{model_id}'",
945                    model.provider
946                )
947            })?;
948        }
949        let snapshot = {
950            let mut cfg = self.config.write();
951            cfg.engine.default_model = model_id.to_string();
952            cfg.clone()
953        };
954        // Persist outside the write lock — synchronous fs::write under the
955        // lock would serialize every reader (providers/config/routing_stats).
956        self.persist(&snapshot)?;
957        tracing::info!(model = %model_id, "Default model updated in config");
958        self.rebuild_and_swap();
959        Ok(())
960    }
961
962    /// Set an API key for a provider.
963    ///
964    /// Stores the key via CredentialStore (→ ~/.oxi/auth.json) and also
965    /// updates config.toml's `[engine].api_key` when the provider matches
966    /// the current default model. Hot-swaps the runtime engine afterward.
967    pub fn set_api_key(&self, provider: &str, key: &str) -> anyhow::Result<()> {
968        CredentialStore::store(provider, key)?;
969
970        // Acquire the write lock up-front and do the provider-match check and
971        // the assignment atomically. The previous read-lock-then-write-lock
972        // sequence was a TOCTOU: another writer could change `default_model`
973        // between the check and the assignment, leaving an api_key stored
974        // against the wrong provider.
975        let snapshot = {
976            let mut cfg = self.config.write();
977            let matches = CredentialStore::provider_from_model(&cfg.engine.default_model)
978                .is_some_and(|current_provider| current_provider == provider);
979            if matches {
980                cfg.engine.api_key = Some(key.to_string());
981                Some(cfg.clone())
982            } else {
983                None
984            }
985        };
986        if let Some(snap) = snapshot {
987            // Persist outside the lock (see set_model).
988            self.persist(&snap)?;
989        }
990        tracing::info!(provider = %provider, "API key stored");
991        self.rebuild_and_swap();
992        Ok(())
993    }
994
995    /// Clear an API key for a provider.
996    ///
997    /// Removes the key from config.toml's `[engine].api_key` (when the
998    /// provider matches the current default model) and rebuilds the engine
999    /// so the credential is dropped from the running process. The key in
1000    /// `~/.oxi/auth.json` must be removed separately via `CredentialStore::delete`.
1001    pub fn clear_api_key(&self, provider: &str) -> anyhow::Result<()> {
1002        let snapshot = {
1003            let mut cfg = self.config.write();
1004            let matches = CredentialStore::provider_from_model(&cfg.engine.default_model)
1005                .is_some_and(|current_provider| current_provider == provider);
1006            if matches {
1007                cfg.engine.api_key = None;
1008                Some(cfg.clone())
1009            } else {
1010                None
1011            }
1012        };
1013        if let Some(snap) = snapshot {
1014            self.persist(&snap)?;
1015        }
1016        tracing::info!(provider = %provider, "API key cleared from config");
1017        self.rebuild_and_swap();
1018        Ok(())
1019    }
1020
1021    /// Delete a provider's API key entirely.
1022    ///
1023    /// Removes the credential from both the auth store (`~/.oxi/auth.json`)
1024    /// and `config.toml` (when the provider matches the current default).
1025    /// Hot-swaps the runtime engine so the credential is dropped immediately.
1026    ///
1027    /// Note: keys sourced from environment variables (`OXIOS_<PROVIDER>_API_KEY`
1028    /// or provider-native vars) cannot be removed via this method — they persist
1029    /// as long as the env var is set. The caller should check the credential
1030    /// source before offering a "remove" action.
1031    pub fn delete_api_key(&self, provider: &str) -> anyhow::Result<()> {
1032        CredentialStore::delete(provider)?;
1033        // Also clear from config.toml if this is the default provider.
1034        let snapshot = {
1035            let mut cfg = self.config.write();
1036            let matches = CredentialStore::provider_from_model(&cfg.engine.default_model)
1037                .is_some_and(|current_provider| current_provider == provider);
1038            if matches {
1039                cfg.engine.api_key = None;
1040                Some(cfg.clone())
1041            } else {
1042                None
1043            }
1044        };
1045        if let Some(snap) = snapshot {
1046            self.persist(&snap)?;
1047        }
1048        tracing::info!(provider = %provider, "API key deleted from credential store");
1049        self.rebuild_and_swap();
1050        Ok(())
1051    }
1052
1053    /// Update provider options in config.toml.
1054    ///
1055    /// Persists the options and makes them available for the next agent run.
1056    /// They are passed through to `AgentLoopConfig::provider_options`.
1057    pub fn set_provider_options(&self, opts: &oxi_sdk::ProviderOptions) -> anyhow::Result<()> {
1058        let snapshot = {
1059            let mut cfg = self.config.write();
1060            cfg.engine.provider_options = Some(opts.clone());
1061            cfg.clone()
1062        };
1063        self.persist(&snapshot)?;
1064        tracing::info!("Provider options updated and persisted");
1065        // No engine rebuild needed — provider_options are per-request,
1066        // picked up from config on the next agent run.
1067        Ok(())
1068    }
1069
1070    /// Update routing configuration in config.toml.
1071    ///
1072    /// Only the fields provided in `update` are changed; others are left untouched.
1073    /// Changes are persisted to disk immediately.
1074    pub fn set_routing(&self, update: RoutingUpdate) -> anyhow::Result<()> {
1075        let snapshot = {
1076            let mut cfg = self.config.write();
1077            if let Some(v) = update.routing_enabled {
1078                cfg.engine.routing_enabled = v;
1079            }
1080            if let Some(v) = update.prefer_cost_efficient {
1081                cfg.engine.prefer_cost_efficient = v;
1082            }
1083            if let Some(v) = update.fallback_models {
1084                cfg.engine.fallback_models = v;
1085            }
1086            if let Some(v) = update.excluded_models {
1087                cfg.engine.excluded_models = v;
1088            }
1089            cfg.clone()
1090        };
1091        self.persist(&snapshot)?;
1092        tracing::info!("Routing configuration updated via API");
1093        self.rebuild_and_swap();
1094        Ok(())
1095    }
1096
1097    /// Validate an API key by making a real minimal completion request.
1098    ///
1099    /// Sends a 1-token "Hi" request to the provider's API. If the key
1100    /// is invalid or expired, the provider returns an auth error.
1101    pub async fn validate_key(&self, provider: &str, api_key: &str) -> ValidateKeyResult {
1102        match self.try_validate(provider, api_key).await {
1103            Ok(()) => ValidateKeyResult {
1104                valid: true,
1105                provider: provider.to_string(),
1106                message: Some("API key is valid".to_string()),
1107            },
1108            Err(e) => ValidateKeyResult {
1109                valid: false,
1110                provider: provider.to_string(),
1111                message: Some(format!("{e}")),
1112            },
1113        }
1114    }
1115
1116    /// Validate the stored API key for a provider.
1117    ///
1118    /// Resolves the key from the credential store (env var → config → auth.json)
1119    /// and validates it via a real API call. Returns `valid: false` with a
1120    /// descriptive message when no key is found.
1121    pub async fn validate_stored_key(&self, provider: &str) -> ValidateKeyResult {
1122        let api_key_override = {
1123            let cfg = self.config.read();
1124            cfg.api_key().as_deref().map(str::to_owned)
1125        };
1126        match CredentialStore::resolve(provider, api_key_override.as_deref()) {
1127            Some((key, _)) => self.validate_key(provider, &key).await,
1128            None => ValidateKeyResult {
1129                valid: false,
1130                provider: provider.to_string(),
1131                message: Some("No API key found for this provider".to_string()),
1132            },
1133        }
1134    }
1135
1136    /// Make a real minimal API call to verify the key works.
1137    ///
1138    /// Sends a "Hi" completion request with a 15-second timeout.
1139    /// Invalid/expired keys trigger an immediate auth error from the provider.
1140    async fn try_validate(&self, provider: &str, api_key: &str) -> anyhow::Result<()> {
1141        if api_key.is_empty() {
1142            anyhow::bail!("API key is empty");
1143        }
1144
1145        let builder = oxi_sdk::OxiBuilder::new()
1146            .with_builtins()
1147            .api_key(provider, api_key);
1148        let oxi = builder.build();
1149
1150        let models = oxi_sdk::get_provider_models(provider);
1151        if models.is_empty() {
1152            anyhow::bail!("No models found for provider '{provider}'");
1153        }
1154
1155        let model_id = format!("{}/{}", provider, models[0].id);
1156        let model = oxi
1157            .resolve_model(&model_id)
1158            .with_context(|| format!("Unknown model '{model_id}'"))?;
1159        let provider_inst = oxi
1160            .create_provider(provider)
1161            .with_context(|| format!("Failed to create provider '{provider}'"))?;
1162
1163        let mut ctx = oxi_sdk::Context::new();
1164        ctx.add_message(oxi_sdk::Message::User(oxi_sdk::UserMessage::new("Hi")));
1165
1166        let stream_result = tokio::time::timeout(
1167            std::time::Duration::from_secs(15),
1168            provider_inst.stream(&model, &ctx, None),
1169        )
1170        .await
1171        .map_err(|_| anyhow::anyhow!("Request timed out (15s)"))?;
1172
1173        match stream_result {
1174            Ok(_) => {
1175                tracing::debug!(provider = %provider, model = %model_id, "Key validated via real API call");
1176                Ok(())
1177            }
1178            Err(e) => Err(anyhow::anyhow!("{e}")),
1179        }
1180    }
1181
1182    // ── Helpers ─────────────────────────────────────────────────────────
1183
1184    /// Estimate cost for a model invocation.
1185    pub fn estimate_cost(model_id: &str, input_tokens: u64, output_tokens: u64) -> f64 {
1186        estimate_cost(model_id, input_tokens, output_tokens)
1187    }
1188
1189    /// Persist the current config to disk.
1190    fn persist(&self, config: &OxiosConfig) -> anyhow::Result<()> {
1191        let content = toml::to_string_pretty(config)
1192            .map_err(|e| anyhow::anyhow!("Failed to serialize config: {e}"))?;
1193        std::fs::write(&self.config_path, content)?;
1194        Ok(())
1195    }
1196
1197    /// Rebuild `OxiosEngine` from current config and swap into the handle.
1198    ///
1199    /// Reuses the model catalog from the current engine (it holds the
1200    /// in-memory models.dev snapshot — re-initializing it on every config
1201    /// change would just reload the same data). No network calls beyond
1202    /// what `CredentialStore` already caches in memory.
1203    fn rebuild_and_swap(&self) {
1204        // Narrow the read-lock window: clone the small fields we need, then
1205        // build the engine outside the lock so concurrent readers/writers are
1206        // not blocked by `OxiosEngine::from_config_with_catalog` work.
1207        let (model_id, api_key, catalog) = {
1208            let cfg = self.config.read();
1209            let catalog = self.engine_handle.get().oxi().catalog().clone();
1210            (cfg.engine.default_model.clone(), cfg.api_key(), catalog)
1211        };
1212        let new_engine = crate::engine::OxiosEngine::from_config_with_catalog(
1213            &model_id,
1214            api_key.as_deref(),
1215            catalog,
1216        );
1217        self.engine_handle.swap(new_engine);
1218    }
1219}
1220
1221impl std::fmt::Debug for EngineApi {
1222    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1223        f.debug_struct("EngineApi")
1224            .field("config_path", &self.config_path)
1225            .finish()
1226    }
1227}
1228
1229// Expose `RoutingStats::record_model_usage` via a public helper for AgentRuntime.
1230// This avoids exposing the internal Arc to outside crates.
1231pub fn record_usage_to_stats(
1232    stats: &Option<Arc<RoutingStats>>,
1233    model_id: &str,
1234    input_tokens: u64,
1235    output_tokens: u64,
1236) {
1237    if let Some(s) = stats {
1238        let cost = estimate_cost(model_id, input_tokens, output_tokens);
1239        s.record_model_usage(model_id, cost);
1240    }
1241}
1242
1243#[cfg(test)]
1244mod tests {
1245    use super::*;
1246
1247    #[test]
1248    fn test_provider_category_known() {
1249        // Major
1250        assert_eq!(provider_category("anthropic"), ProviderCategory::Major);
1251        assert_eq!(provider_category("openai"), ProviderCategory::Major);
1252        assert_eq!(provider_category("google"), ProviderCategory::Major);
1253        // Open / specialty
1254        assert_eq!(provider_category("groq"), ProviderCategory::Open);
1255        assert_eq!(provider_category("opencode"), ProviderCategory::Open);
1256        // Regional
1257        assert_eq!(provider_category("minimax"), ProviderCategory::Regional);
1258        assert_eq!(provider_category("moonshotai"), ProviderCategory::Regional);
1259        assert_eq!(provider_category("kimi-coding"), ProviderCategory::Regional);
1260        assert_eq!(provider_category("zai"), ProviderCategory::Regional);
1261        assert_eq!(provider_category("minimax-cn"), ProviderCategory::Regional);
1262        assert_eq!(provider_category("xiaomi"), ProviderCategory::Regional);
1263    }
1264
1265    #[test]
1266    fn test_provider_category_fallback() {
1267        // Unknown ids fall back to Open, not panic.
1268        assert_eq!(
1269            provider_category("not-a-real-provider"),
1270            ProviderCategory::Open
1271        );
1272        assert_eq!(provider_category(""), ProviderCategory::Open);
1273    }
1274
1275    #[test]
1276    fn test_provider_display_name_known() {
1277        assert_eq!(provider_display_name("anthropic"), "Anthropic");
1278        assert_eq!(provider_display_name("minimax"), "MiniMax");
1279        assert_eq!(provider_display_name("moonshotai"), "Moonshot AI (Kimi)");
1280        assert_eq!(provider_display_name("kimi-coding"), "Kimi Coding");
1281        assert_eq!(provider_display_name("zai"), "Z.AI (GLM)");
1282        assert_eq!(provider_display_name("opencode"), "OpenCode");
1283        assert_eq!(provider_display_name("amazon-bedrock"), "Amazon Bedrock");
1284    }
1285
1286    #[test]
1287    fn test_provider_display_name_fallback() {
1288        // Unknown ids get Title-Cased per segment as a fallback.
1289        assert_eq!(
1290            provider_display_name("some-new-provider"),
1291            "Some New Provider"
1292        );
1293        assert_eq!(provider_display_name("kimi-coding"), "Kimi Coding");
1294        assert_eq!(provider_display_name("some_id"), "Some Id");
1295        // Empty string stays empty.
1296        assert_eq!(provider_display_name(""), "");
1297    }
1298
1299    #[test]
1300    fn test_provider_meta_lookup_by_alias() {
1301        // Aliases resolve to the same meta entry as the canonical id.
1302        let by_id = provider_meta("github-copilot").unwrap();
1303        let by_alias = provider_meta("copilot").unwrap();
1304        assert_eq!(by_id.id, by_alias.id);
1305
1306        let bedrock_id = provider_meta("amazon-bedrock").unwrap();
1307        let bedrock_alias = provider_meta("aws-bedrock").unwrap();
1308        let bedrock_canonical = provider_meta("bedrock").unwrap();
1309        assert_eq!(bedrock_id.id, bedrock_alias.id);
1310        assert_eq!(bedrock_id.id, bedrock_canonical.id);
1311    }
1312
1313    #[test]
1314    fn test_provider_meta_unknown_is_none() {
1315        assert!(provider_meta("not-a-real-provider").is_none());
1316        assert!(provider_meta("").is_none());
1317    }
1318
1319    #[test]
1320    fn test_provider_info_serialization() {
1321        let info = ProviderInfo {
1322            id: "anthropic".to_string(),
1323            name: "Anthropic".to_string(),
1324            category: ProviderCategory::Major,
1325            model_count: 15,
1326            has_key: true,
1327            key_source: "auth_store".to_string(),
1328            description: "Claude models with extended thinking".to_string(),
1329            env_key: "ANTHROPIC_API_KEY".to_string(),
1330        };
1331        let json = serde_json::to_string(&info).unwrap();
1332        // camelCase serialization
1333        assert!(json.contains("\"modelCount\":15"));
1334        assert!(json.contains("\"hasKey\":true"));
1335        assert!(json.contains("\"envKey\":\"ANTHROPIC_API_KEY\""));
1336        let restored: ProviderInfo = serde_json::from_str(&json).unwrap();
1337        assert_eq!(restored.id, "anthropic");
1338        assert_eq!(restored.name, "Anthropic");
1339        assert_eq!(restored.model_count, 15);
1340        assert!(restored.has_key);
1341        assert_eq!(restored.env_key, "ANTHROPIC_API_KEY");
1342    }
1343
1344    #[test]
1345    fn test_provider_info_serialization_missing_optional() {
1346        // description / env_key have serde(default) so old clients that
1347        // omit them still deserialize cleanly.
1348        let json = r#"{
1349            "id": "anthropic",
1350            "name": "Anthropic",
1351            "category": "major",
1352            "modelCount": 15,
1353            "hasKey": true
1354        }"#;
1355        let info: ProviderInfo = serde_json::from_str(json).unwrap();
1356        assert_eq!(info.id, "anthropic");
1357        assert_eq!(info.description, "");
1358        assert_eq!(info.env_key, "");
1359    }
1360
1361    #[test]
1362    fn test_model_info_serialization() {
1363        let info = ModelInfo {
1364            id: "anthropic/claude-sonnet-4".to_string(),
1365            name: "Claude Sonnet 4".to_string(),
1366            api: "anthropic-messages".to_string(),
1367            provider: "anthropic".to_string(),
1368            reasoning: true,
1369            input: vec![InputModality::Text, InputModality::Image],
1370            context_window: 200000,
1371            max_tokens: 16000,
1372            cost_input: 3.0,
1373            cost_output: 15.0,
1374            cost_cache_read: 0.3,
1375            cost_cache_write: 3.75,
1376        };
1377        let json = serde_json::to_string(&info).unwrap();
1378        let restored: ModelInfo = serde_json::from_str(&json).unwrap();
1379        assert_eq!(restored.id, "anthropic/claude-sonnet-4");
1380        assert!(restored.reasoning);
1381        assert_eq!(restored.context_window, 200000);
1382        assert!(restored.input.contains(&InputModality::Image));
1383        assert_eq!(restored.api, "anthropic-messages");
1384    }
1385
1386    #[test]
1387    fn test_engine_config_response_serialization() {
1388        let resp = EngineConfigResponse {
1389            default_model: "anthropic/claude-sonnet-4".to_string(),
1390            api_key_set: true,
1391            api_key_source: Some("config.toml".to_string()),
1392            provider: Some("anthropic".to_string()),
1393            routing: RoutingConfigSnapshot {
1394                routing_enabled: false,
1395                prefer_cost_efficient: false,
1396                fallback_models: vec![],
1397                excluded_models: vec![],
1398            },
1399        };
1400        let json = serde_json::to_string(&resp).unwrap();
1401        let restored: EngineConfigResponse = serde_json::from_str(&json).unwrap();
1402        assert_eq!(restored.default_model, "anthropic/claude-sonnet-4");
1403        assert!(restored.api_key_set);
1404        assert_eq!(restored.api_key_source.as_deref(), Some("config.toml"));
1405        assert!(!restored.routing.routing_enabled);
1406    }
1407
1408    #[test]
1409    fn test_validate_key_result_serialization() {
1410        let result = ValidateKeyResult {
1411            valid: true,
1412            provider: "openai".to_string(),
1413            message: Some("API key is valid".to_string()),
1414        };
1415        let json = serde_json::to_string(&result).unwrap();
1416        let restored: ValidateKeyResult = serde_json::from_str(&json).unwrap();
1417        assert!(restored.valid);
1418        assert_eq!(restored.provider, "openai");
1419    }
1420
1421    #[test]
1422    fn test_validate_key_result_invalid() {
1423        let result = ValidateKeyResult {
1424            valid: false,
1425            provider: "anthropic".to_string(),
1426            message: Some("Validation failed: key too short".to_string()),
1427        };
1428        assert!(!result.valid);
1429        assert!(result.message.as_ref().unwrap().contains("failed"));
1430    }
1431
1432    #[test]
1433    fn test_routing_stats_snapshot() {
1434        let stats = RoutingStats::new();
1435        stats.record_model_usage("anthropic/claude-sonnet-4", 0.05);
1436        stats.record_model_usage("anthropic/claude-sonnet-4", 0.03);
1437        stats.record_model_usage("openai/gpt-4o-mini", 0.01);
1438
1439        let snap = stats.snapshot();
1440        assert_eq!(snap.total_requests, 3);
1441        assert_eq!(snap.model_calls["anthropic/claude-sonnet-4"], 2);
1442        assert_eq!(snap.model_calls["openai/gpt-4o-mini"], 1);
1443        assert!((snap.total_cost - 0.09).abs() < 0.001);
1444    }
1445
1446    #[test]
1447    fn test_fallback_history_circular() {
1448        let stats = RoutingStats::new();
1449        for i in 0..210 {
1450            stats.record_fallback(FallbackEvent {
1451                timestamp: DateTime::from_timestamp(i as i64, 0).unwrap(),
1452                from_model: format!("model-{}", i),
1453                to_model: "fallback".to_string(),
1454                reason: "test".to_string(),
1455                success: true,
1456            });
1457        }
1458        let history = stats.fallback_history(200);
1459        assert_eq!(history.len(), 200);
1460        // Most recent first (i=209 down to i=10)
1461        assert_eq!(history[0].from_model, "model-209");
1462        assert_eq!(history[199].from_model, "model-10");
1463    }
1464
1465    #[test]
1466    fn set_model_rejects_unknown_model_before_persist() {
1467        use crate::engine::{EngineHandle, OxiosEngine};
1468
1469        let engine = Arc::new(OxiosEngine::new("anthropic/claude-sonnet-4-20250514"));
1470        let handle = Arc::new(EngineHandle::new(engine));
1471        let config = Arc::new(parking_lot::RwLock::new(OxiosConfig::default()));
1472        // Validation runs before any IO, so a non-existent path is safe — it
1473        // must never be written to.
1474        let path = PathBuf::from("/tmp/oxios-set-model-test-NONEXISTENT.toml");
1475        let api = EngineApi::new(config, path, Arc::new(RoutingStats::new()), handle);
1476
1477        // The malformed id from the user-reported bug. Must be rejected, not
1478        // silently accepted and deferred to the execute phase.
1479        let before = api.config.read().engine.default_model.clone();
1480        let err = api.set_model("zai-coding-plan/glm-5-turbo").unwrap_err();
1481        assert!(
1482            err.to_string().contains("Unknown model"),
1483            "expected unknown-model error, got: {err}"
1484        );
1485        // Rejection happened before persist: config is untouched.
1486        assert_eq!(api.config.read().engine.default_model, before);
1487    }
1488
1489    #[test]
1490    fn set_model_accepts_known_builtin_model() {
1491        use crate::engine::{EngineHandle, OxiosEngine};
1492
1493        let engine = Arc::new(OxiosEngine::new("anthropic/claude-sonnet-4-20250514"));
1494        let handle = Arc::new(EngineHandle::new(engine));
1495        let config = Arc::new(parking_lot::RwLock::new(OxiosConfig::default()));
1496        let tmp =
1497            std::env::temp_dir().join(format!("oxios-set-model-ok-{}.toml", std::process::id()));
1498        let api = EngineApi::new(config, tmp.clone(), Arc::new(RoutingStats::new()), handle);
1499
1500        // A builtin model with a built-in provider resolves + creates a provider
1501        // without any API key, so validation passes. The swap should succeed.
1502        let result = api.set_model("openai/gpt-4o");
1503        // create_provider may still fail without a key on some SDK builds; treat
1504        // both Ok and a provider-config error as acceptable, but never an
1505        // "Unknown model" rejection for a known builtin.
1506        match result {
1507            Ok(()) => assert_eq!(api.config.read().engine.default_model, "openai/gpt-4o"),
1508            Err(e) => assert!(
1509                !e.to_string().contains("Unknown model"),
1510                "known model rejected as unknown: {e}"
1511            ),
1512        }
1513        let _ = std::fs::remove_file(&tmp);
1514    }
1515}