Skip to main content

llm_codegen/
lib.rs

1#![doc = include_str!("../README.md")]
2
3use proc_macro2::TokenStream;
4use quote::{ToTokens, format_ident, quote};
5use serde::Deserialize;
6use std::collections::{BTreeMap, HashMap, HashSet};
7use std::fmt::Write;
8use std::path::Path;
9
10type ModelsDevData = HashMap<String, ProviderData>;
11
12#[derive(Debug, Deserialize)]
13struct ProviderData {
14    #[allow(dead_code)]
15    id: String,
16    #[allow(dead_code)]
17    name: String,
18    #[serde(default)]
19    #[allow(dead_code)]
20    env: Vec<String>,
21    #[serde(default)]
22    models: HashMap<String, ModelData>,
23}
24
25#[derive(Debug, Deserialize)]
26struct ModelData {
27    id: String,
28    name: String,
29    #[serde(default)]
30    tool_call: Option<bool>,
31    #[serde(default)]
32    reasoning: Option<bool>,
33    #[serde(default)]
34    reasoning_options: Vec<ReasoningOption>,
35    #[serde(default)]
36    #[allow(dead_code)]
37    cost: Option<CostData>,
38    #[serde(default)]
39    limit: Option<LimitData>,
40    #[serde(default)]
41    modalities: Option<ModalitiesData>,
42    #[serde(default)]
43    provider: Option<ModelProviderData>,
44}
45
46/// Per-model transport override.
47#[derive(Debug, Deserialize)]
48struct ModelProviderData {
49    #[serde(default)]
50    api: Option<String>,
51    #[serde(default)]
52    shape: Option<String>,
53}
54
55#[derive(Debug, Deserialize)]
56#[serde(tag = "type", rename_all = "snake_case")]
57enum ReasoningOption {
58    Effort { values: Vec<Option<String>> },
59    Toggle,
60    BudgetTokens,
61}
62
63#[derive(Debug, Deserialize, Default)]
64struct ModalitiesData {
65    #[serde(default)]
66    input: Vec<String>,
67}
68
69#[derive(Debug, Clone, PartialEq, Deserialize)]
70struct CostData {
71    #[serde(default)]
72    input: f64,
73    #[serde(default)]
74    output: f64,
75    #[serde(default)]
76    cache_read: Option<f64>,
77    #[serde(default)]
78    cache_write: Option<f64>,
79}
80
81#[derive(Debug, Deserialize)]
82struct LimitData {
83    #[serde(default)]
84    context: u32,
85    #[serde(default)]
86    #[allow(dead_code)]
87    output: u32,
88}
89
90impl CostData {
91    fn has_prompt_caching(&self) -> bool {
92        self.cache_read.is_some() || self.cache_write.is_some()
93    }
94}
95
96/// Provider configuration for codegen (catalog providers with known model lists)
97struct ProviderConfig {
98    /// Unique provider key used in `provider_models` map (e.g. "codex")
99    dev_id: &'static str,
100    /// models.dev provider ID to read models from (defaults to `dev_id` when `None`)
101    source_dev_id: Option<&'static str>,
102    /// Additional models.dev keys whose models are merged into this provider
103    extra_source_ids: &'static [&'static str],
104    /// When set, the provider exposes exactly these models with these context
105    /// windows (e.g. subscription-gated providers whose limits differ from the
106    /// source metadata). Every entry must exist and be tool-capable in the
107    /// source data.
108    explicit_models: Option<&'static [ExplicitModel]>,
109    /// Our Rust enum name (e.g. "Gemini")
110    enum_name: &'static str,
111    /// Our internal provider name used for parsing (e.g. "gemini")
112    parser_name: &'static str,
113    /// OpenTelemetry `GenAI` semantic-convention provider name.
114    genai_provider_name: &'static str,
115    /// Human-readable provider name (e.g. "AWS Bedrock")
116    display_name: &'static str,
117    /// Env var our code actually checks (None for providers with complex credential chains)
118    env_var: Option<&'static str>,
119    /// OAuth provider ID for providers that require OAuth login (e.g. "codex")
120    oauth_provider_id: Option<&'static str>,
121    /// Fallback levels when source metadata does not declare granular efforts.
122    fallback_reasoning_levels: &'static [&'static str],
123    /// When true, a model's `provider.api`/`provider.shape` metadata is read as a
124    /// per-model transport override. Off elsewhere because most providers publish
125    /// unrelated data (npm package names) under the same key.
126    use_model_transport: bool,
127    /// When true, the provider uses the shared OpenAI-compatible chat transport.
128    uses_openai_compatible_api: bool,
129    /// When true, the inner catalog enum is named `{Enum}FoundationModel` and
130    /// `LlmModel::{Enum}` carries a hand-written `{Enum}Model` wrapper (defined
131    /// outside of codegen) that adds a `Profile(String)` fall-through plus any
132    /// provider-specific parsing policy. Used for Bedrock to accept arbitrary
133    /// inference profile IDs at runtime while keeping ARNs out of model identity.
134    is_hybrid_dynamic: bool,
135}
136
137/// A model exposed by a provider with an explicit model list.
138struct ExplicitModel {
139    id: &'static str,
140    context_window: u32,
141    supports_reasoning_off: bool,
142}
143
144impl ProviderConfig {
145    /// Shorthand for providers with default `source_dev_id`, `explicit_models`, and `oauth_provider_id`.
146    const fn standard(
147        dev_id: &'static str,
148        enum_name: &'static str,
149        parser_name: &'static str,
150        display_name: &'static str,
151        env_var: Option<&'static str>,
152    ) -> Self {
153        Self {
154            dev_id,
155            source_dev_id: None,
156            extra_source_ids: &[],
157            explicit_models: None,
158            enum_name,
159            parser_name,
160            genai_provider_name: parser_name,
161            display_name,
162            env_var,
163            oauth_provider_id: None,
164            fallback_reasoning_levels: &["low", "medium", "high"],
165            use_model_transport: false,
166            uses_openai_compatible_api: false,
167            is_hybrid_dynamic: false,
168        }
169    }
170
171    const fn openai_compatible(
172        dev_id: &'static str,
173        enum_name: &'static str,
174        parser_name: &'static str,
175        display_name: &'static str,
176        env_var: &'static str,
177    ) -> Self {
178        let mut config = Self::standard(dev_id, enum_name, parser_name, display_name, Some(env_var));
179        config.uses_openai_compatible_api = true;
180        config
181    }
182
183    fn explicit_model(&self, model_id: &str) -> Option<&'static ExplicitModel> {
184        self.explicit_models.and_then(|models| models.iter().find(|model| model.id == model_id))
185    }
186
187    /// Inner catalog-enum name. For hybrid providers the outer `{enum_name}Model`
188    /// is a wrapper; the catalog enum is `{enum_name}FoundationModel`.
189    fn inner_enum_name(&self) -> String {
190        if self.is_hybrid_dynamic {
191            format!("{}FoundationModel", self.enum_name)
192        } else {
193            format!("{}Model", self.enum_name)
194        }
195    }
196
197    /// Outer enum name as referenced by `LlmModel::{enum_name}(...)`.
198    fn outer_enum_name(&self) -> String {
199        format!("{}Model", self.enum_name)
200    }
201
202    /// The models.dev key to look up in the JSON data.
203    fn json_key(&self) -> &'static str {
204        self.source_dev_id.unwrap_or(self.dev_id)
205    }
206}
207
208/// Dynamic provider — model name is user-supplied at runtime, no fixed enum
209#[allow(clippy::struct_field_names)]
210struct DynamicProviderConfig {
211    /// Rust variant name in `LlmModel` (e.g. "Ollama")
212    enum_name: &'static str,
213    /// Parser name used in "provider:model" strings (e.g. "ollama")
214    parser_name: &'static str,
215    /// OpenTelemetry `GenAI` semantic-convention provider name.
216    genai_provider_name: &'static str,
217    /// Human-readable provider name (e.g. "Ollama")
218    display_name: &'static str,
219}
220
221const PROVIDERS: &[ProviderConfig] = &[
222    ProviderConfig::standard("anthropic", "Anthropic", "anthropic", "Anthropic", Some("ANTHROPIC_API_KEY")),
223    ProviderConfig {
224        source_dev_id: Some("azure"),
225        genai_provider_name: "azure.ai.openai",
226        ..ProviderConfig::openai_compatible(
227            "azure-foundry",
228            "AzureFoundry",
229            "azure-foundry",
230            "Microsoft Foundry",
231            "AZURE_OPENAI_API_KEY",
232        )
233    },
234    ProviderConfig {
235        dev_id: "codex",
236        source_dev_id: Some("openai"),
237        extra_source_ids: &[],
238        explicit_models: Some(CODEX_SUBSCRIPTION_MODELS),
239        enum_name: "Codex",
240        parser_name: "codex",
241        genai_provider_name: "openai",
242        display_name: "Codex",
243        env_var: None,
244        oauth_provider_id: Some("codex"),
245        fallback_reasoning_levels: &["low", "medium", "high", "xhigh"],
246        use_model_transport: false,
247        uses_openai_compatible_api: false,
248        is_hybrid_dynamic: false,
249    },
250    ProviderConfig::openai_compatible("deepseek", "DeepSeek", "deepseek", "DeepSeek", "DEEPSEEK_API_KEY"),
251    ProviderConfig {
252        source_dev_id: Some("fireworks-ai"),
253        ..ProviderConfig::openai_compatible("fireworks", "Fireworks", "fireworks", "Fireworks AI", "FIREWORKS_API_KEY")
254    },
255    ProviderConfig {
256        genai_provider_name: "gcp.gemini",
257        ..ProviderConfig::standard("google", "Gemini", "gemini", "Gemini", Some("GEMINI_API_KEY"))
258    },
259    ProviderConfig {
260        genai_provider_name: "moonshot_ai",
261        ..ProviderConfig::openai_compatible("moonshotai", "Moonshot", "moonshot", "Moonshot", "MOONSHOT_API_KEY")
262    },
263    ProviderConfig::standard("openai", "Openai", "openai", "OpenAI", Some("OPENAI_API_KEY")),
264    ProviderConfig::standard("openrouter", "OpenRouter", "openrouter", "OpenRouter", Some("OPENROUTER_API_KEY")),
265    ProviderConfig::standard("xiaomi", "Xiaomi", "xiaomi", "Xiaomi", Some("XIAOMI_API_KEY")),
266    ProviderConfig {
267        extra_source_ids: &["zai-coding-plan"],
268        ..ProviderConfig::openai_compatible("zai", "ZAi", "zai", "ZAI", "ZAI_API_KEY")
269    },
270    ProviderConfig {
271        genai_provider_name: "aws.bedrock",
272        use_model_transport: true,
273        is_hybrid_dynamic: true,
274        ..ProviderConfig::standard("amazon-bedrock", "Bedrock", "bedrock", "AWS Bedrock", None)
275    },
276];
277
278const DYNAMIC_PROVIDERS: &[DynamicProviderConfig] = &[
279    DynamicProviderConfig {
280        enum_name: "Ollama",
281        parser_name: "ollama",
282        genai_provider_name: "ollama",
283        display_name: "Ollama",
284    },
285    DynamicProviderConfig {
286        enum_name: "LlamaCpp",
287        parser_name: "llamacpp",
288        genai_provider_name: "llama.cpp",
289        display_name: "LlamaCpp",
290    },
291];
292
293const CODEX_SUBSCRIPTION_CONTEXT_WINDOW: u32 = 272_000;
294
295const CODEX_SUBSCRIPTION_MODELS: &[ExplicitModel] = &[
296    ExplicitModel {
297        id: "gpt-6.1-sol",
298        context_window: CODEX_SUBSCRIPTION_CONTEXT_WINDOW,
299        supports_reasoning_off: false,
300    },
301    ExplicitModel { id: "gpt-6-sol", context_window: CODEX_SUBSCRIPTION_CONTEXT_WINDOW, supports_reasoning_off: false },
302    ExplicitModel {
303        id: "gpt-6-astra",
304        context_window: CODEX_SUBSCRIPTION_CONTEXT_WINDOW,
305        supports_reasoning_off: false,
306    },
307    ExplicitModel {
308        id: "gpt-6-luna",
309        context_window: CODEX_SUBSCRIPTION_CONTEXT_WINDOW,
310        supports_reasoning_off: false,
311    },
312    ExplicitModel {
313        id: "gpt-5.6-sol",
314        context_window: CODEX_SUBSCRIPTION_CONTEXT_WINDOW,
315        supports_reasoning_off: false,
316    },
317    ExplicitModel {
318        id: "gpt-5.6-terra",
319        context_window: CODEX_SUBSCRIPTION_CONTEXT_WINDOW,
320        supports_reasoning_off: false,
321    },
322    ExplicitModel {
323        id: "gpt-5.6-luna",
324        context_window: CODEX_SUBSCRIPTION_CONTEXT_WINDOW,
325        supports_reasoning_off: false,
326    },
327    ExplicitModel { id: "gpt-5.5", context_window: CODEX_SUBSCRIPTION_CONTEXT_WINDOW, supports_reasoning_off: false },
328    ExplicitModel { id: "gpt-5.4", context_window: CODEX_SUBSCRIPTION_CONTEXT_WINDOW, supports_reasoning_off: false },
329    ExplicitModel {
330        id: "gpt-5.4-mini",
331        context_window: CODEX_SUBSCRIPTION_CONTEXT_WINDOW,
332        supports_reasoning_off: false,
333    },
334    ExplicitModel { id: "gpt-5.2", context_window: CODEX_SUBSCRIPTION_CONTEXT_WINDOW, supports_reasoning_off: false },
335];
336
337#[derive(Debug, Clone)]
338struct ModelInfo {
339    variant_name: String,
340    model_id: String,
341    display_name: String,
342    context_window: u32,
343    reasoning_levels: Vec<String>,
344    disabled_support: &'static str,
345    input_modalities: Vec<String>,
346    pricing: Option<CostData>,
347    supports_prompt_caching: bool,
348    transport: Option<TransportInfo>,
349}
350
351#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
352enum TransportInfo {
353    OpenAiResponses { base_url_template: String },
354}
355
356type ProviderModels = BTreeMap<&'static str, Vec<ModelInfo>>;
357
358struct CodegenCtx {
359    provider_models: ProviderModels,
360}
361
362/// Output of the code generator.
363pub struct GeneratedOutput {
364    /// The generated Rust source (for `generated.rs`).
365    pub rust_source: String,
366    /// Provider documentation keys for the shared OpenAI-compatible module.
367    pub openai_compatible_provider_ids: Vec<&'static str>,
368    /// Per-provider markdown documentation keyed by provider identifier.
369    ///
370    /// Keys are provider `dev_ids` (e.g. `"anthropic"`, `"ollama"`) and values
371    /// are markdown strings suitable for `#![doc = include_str!(...)]`.
372    pub provider_docs: HashMap<String, String>,
373}
374
375#[derive(Debug, thiserror::Error)]
376pub enum CodegenError {
377    #[error("read: {0}")]
378    Read(#[from] std::io::Error),
379    #[error("parse: {0}")]
380    Parse(#[from] serde_json::Error),
381    #[error("Provider '{0}' not found in models.dev data")]
382    ProviderNotFound(String),
383    #[error("Configured model '{model_id}' was not found in provider '{provider_id}'")]
384    ConfiguredModelNotFound { provider_id: String, model_id: String },
385    #[error("Configured model '{model_id}' is duplicated for provider '{provider_id}'")]
386    DuplicateConfiguredModel { provider_id: String, model_id: String },
387    #[error("Configured model '{model_id}' is not tool-capable in provider '{provider_id}'")]
388    ConfiguredModelUnavailable { provider_id: String, model_id: String },
389    #[error("Model '{model_id}' declares unsupported reasoning effort '{effort}'")]
390    UnsupportedReasoningEffort { model_id: String, effort: String },
391    #[error("Model '{model_id}' declares unsupported wire shape '{shape}'")]
392    UnsupportedWireShape { model_id: String, shape: String },
393    #[error("Model '{model_id}' must declare both an endpoint and wire shape")]
394    IncompleteTransport { model_id: String },
395}
396
397/// Run the codegen, returning the generated Rust source and per-provider docs.
398pub fn generate(models_json_path: &Path) -> Result<GeneratedOutput, CodegenError> {
399    let json_bytes = std::fs::read_to_string(models_json_path)?;
400    let data: ModelsDevData = serde_json::from_str(&json_bytes)?;
401
402    let provider_models = build_provider_models(&data)?;
403    let ctx = CodegenCtx { provider_models };
404    let openai_compatible_provider_ids =
405        PROVIDERS.iter().filter(|config| config.uses_openai_compatible_api).map(|config| config.dev_id).collect();
406    Ok(GeneratedOutput {
407        rust_source: emit_generated_source(&ctx),
408        openai_compatible_provider_ids,
409        provider_docs: emit_provider_docs(&ctx),
410    })
411}
412
413fn build_provider_models(data: &ModelsDevData) -> Result<ProviderModels, CodegenError> {
414    let mut provider_models = ProviderModels::new();
415
416    for cfg in PROVIDERS {
417        let json_key = cfg.json_key();
418        let provider_data = data.get(json_key).ok_or_else(|| CodegenError::ProviderNotFound(json_key.to_string()))?;
419
420        validate_provider_config(cfg, provider_data)?;
421        let mut models: Vec<ModelInfo> = collect_models_from(cfg, &provider_data.models)?;
422
423        for &extra_key in cfg.extra_source_ids {
424            if let Some(extra_data) = data.get(extra_key) {
425                let extra = collect_models_from(cfg, &extra_data.models)?;
426                let existing_ids: std::collections::HashSet<String> =
427                    models.iter().map(|m| m.model_id.clone()).collect();
428                models.extend(extra.into_iter().filter(|m| !existing_ids.contains(&m.model_id)));
429            }
430        }
431
432        if cfg.dev_id == "amazon-bedrock" {
433            for model in &mut models {
434                if (model.model_id.starts_with("us.openai.gpt-6-") || model.model_id == "us.openai.gpt-6.1-sol")
435                    && model.transport.is_none()
436                {
437                    model.transport = Some(TransportInfo::OpenAiResponses {
438                        base_url_template: "https://bedrock-runtime.${AWS_REGION}.amazonaws.com/openai/v1".to_string(),
439                    });
440                }
441            }
442        }
443
444        models.sort_by(|a, b| a.model_id.cmp(&b.model_id));
445        provider_models.insert(cfg.dev_id, models);
446    }
447
448    Ok(provider_models)
449}
450
451fn validate_provider_config(cfg: &ProviderConfig, provider: &ProviderData) -> Result<(), CodegenError> {
452    let Some(explicit_models) = cfg.explicit_models else {
453        return Ok(());
454    };
455    let mut seen = HashSet::new();
456    for configured in explicit_models {
457        if !seen.insert(configured.id) {
458            return Err(CodegenError::DuplicateConfiguredModel {
459                provider_id: cfg.dev_id.to_string(),
460                model_id: configured.id.to_string(),
461            });
462        }
463        let Some(model) = provider.models.get(configured.id) else {
464            return Err(CodegenError::ConfiguredModelNotFound {
465                provider_id: cfg.dev_id.to_string(),
466                model_id: configured.id.to_string(),
467            });
468        };
469        if model.tool_call != Some(true) {
470            return Err(CodegenError::ConfiguredModelUnavailable {
471                provider_id: cfg.dev_id.to_string(),
472                model_id: configured.id.to_string(),
473            });
474        }
475    }
476    Ok(())
477}
478
479fn collect_models_from(
480    cfg: &ProviderConfig,
481    models: &HashMap<String, ModelData>,
482) -> Result<Vec<ModelInfo>, CodegenError> {
483    models
484        .values()
485        .filter(|m| m.tool_call == Some(true))
486        .filter(|m| !is_alias(&m.id))
487        .filter(|m| cfg.explicit_models.is_none() || cfg.explicit_model(&m.id).is_some())
488        .map(|m| {
489            let reasoning_levels =
490                if m.reasoning.unwrap_or(false) { reasoning_levels_for_model(cfg, m)? } else { Vec::new() };
491            let input_modalities =
492                m.modalities.as_ref().map_or_else(|| vec!["text".to_string()], |md| md.input.clone());
493            let source_context_window = m.limit.as_ref().map_or(0, |l| l.context);
494            let context_window =
495                cfg.explicit_model(&m.id).map_or(source_context_window, |explicit| explicit.context_window);
496            let pricing = if cfg.dev_id == "codex" { None } else { m.cost.clone() };
497            Ok(ModelInfo {
498                variant_name: model_id_to_variant(&m.id),
499                model_id: m.id.clone(),
500                display_name: m.name.clone(),
501                context_window,
502                reasoning_levels,
503                disabled_support: disabled_support_for_model(cfg, m),
504                input_modalities,
505                supports_prompt_caching: m.cost.as_ref().is_some_and(CostData::has_prompt_caching),
506                pricing,
507                transport: transport_for_model(cfg, m)?,
508            })
509        })
510        .collect()
511}
512
513fn transport_for_model(cfg: &ProviderConfig, model: &ModelData) -> Result<Option<TransportInfo>, CodegenError> {
514    if !cfg.use_model_transport {
515        return Ok(None);
516    }
517    let Some(provider) = &model.provider else {
518        return Ok(None);
519    };
520
521    match (&provider.api, provider.shape.as_deref()) {
522        (None, None) => Ok(None),
523        (Some(base_url_template), Some("responses")) => {
524            Ok(Some(TransportInfo::OpenAiResponses { base_url_template: base_url_template.clone() }))
525        }
526        (_, Some(shape)) if shape != "responses" => {
527            Err(CodegenError::UnsupportedWireShape { model_id: model.id.clone(), shape: shape.to_string() })
528        }
529        _ => Err(CodegenError::IncompleteTransport { model_id: model.id.clone() }),
530    }
531}
532
533fn disabled_support_for_model(cfg: &ProviderConfig, model: &ModelData) -> &'static str {
534    if !model.reasoning.unwrap_or(false) {
535        return "Unsupported";
536    }
537    if let Some(explicit) = cfg.explicit_model(&model.id) {
538        return if explicit.supports_reasoning_off { "Effort" } else { "Unsupported" };
539    }
540    if model.reasoning_options.iter().any(|option| {
541        matches!(option,
542            ReasoningOption::Effort { values } if values.iter().any(|value| value.as_deref() == Some("none"))
543        )
544    }) {
545        "Effort"
546    } else if model.reasoning_options.iter().any(|option| matches!(option, ReasoningOption::Toggle)) {
547        "Toggle"
548    } else {
549        "Unsupported"
550    }
551}
552
553fn reasoning_levels_for_model(cfg: &ProviderConfig, model: &ModelData) -> Result<Vec<String>, CodegenError> {
554    let values = model
555        .reasoning_options
556        .iter()
557        .filter_map(|option| match option {
558            ReasoningOption::Effort { values } => Some(values),
559            ReasoningOption::Toggle | ReasoningOption::BudgetTokens => None,
560        })
561        .collect::<Vec<_>>();
562    let mut levels = Vec::new();
563    if values.is_empty() {
564        levels.extend(cfg.fallback_reasoning_levels.iter().map(|level| (*level).to_string()));
565    } else {
566        for effort in values.into_iter().flatten().filter_map(|value| value.as_deref()) {
567            if matches!(effort, "none" | "default") {
568                continue;
569            }
570            let parsed =
571                effort.parse::<utils::ReasoningEffort>().ok().filter(|effort| effort.is_enabled()).ok_or_else(
572                    || CodegenError::UnsupportedReasoningEffort {
573                        model_id: model.id.clone(),
574                        effort: effort.to_string(),
575                    },
576                )?;
577            levels.push(parsed.as_str().to_string());
578        }
579    }
580    if disabled_support_for_model(cfg, model) != "Unsupported" {
581        levels.push("disabled".to_string());
582    }
583    Ok(utils::ReasoningEffort::selectable_levels()
584        .iter()
585        .filter(|level| levels.iter().any(|value| value == level.as_str()))
586        .map(|level| level.as_str().to_string())
587        .collect())
588}
589
590/// Returns true for "latest" alias IDs that just point to another model
591fn is_alias(id: &str) -> bool {
592    id.ends_with("-latest")
593}
594
595/// Convert a model ID like "claude-sonnet-4-5-20250929" into a `PascalCase` variant name.
596/// Treats `-`, `.`, `/`, and `:` as word separators.
597fn model_id_to_variant(id: &str) -> String {
598    let mut result = String::new();
599    let mut capitalize_next = true;
600
601    for ch in id.chars() {
602        if ch == '-' || ch == '.' || ch == '/' || ch == ':' {
603            capitalize_next = true;
604        } else if capitalize_next {
605            result.push(ch.to_ascii_uppercase());
606            capitalize_next = false;
607        } else {
608            result.push(ch);
609        }
610    }
611
612    if result.starts_with(|c: char| c.is_ascii_digit()) {
613        result.insert(0, '_');
614    }
615
616    result
617}
618
619fn emit_generated_source(ctx: &CodegenCtx) -> String {
620    let provider_enum = emit_provider_enum();
621    let provider_enum_impl = emit_provider_enum_impl();
622    let provider_enum_display = emit_provider_enum_display();
623    let provider_enum_fromstr = emit_provider_enum_fromstr();
624    let provider_enums = emit_provider_enums(&ctx.provider_models);
625    let provider_impls = emit_provider_impls(&ctx.provider_models);
626    let llm_model_enum = emit_llm_model_enum();
627    let from_impls = emit_from_impls();
628    let llm_model_impl = emit_llm_model_impl();
629    let display_impl = emit_display_impl();
630    let fromstr_impl = emit_fromstr_impl();
631
632    let file_tokens = quote! {
633        use std::borrow::Cow;
634        use std::sync::LazyLock;
635        use crate::ReasoningEffort;
636
637        #provider_enum
638        #provider_enum_impl
639        #provider_enum_display
640        #provider_enum_fromstr
641        #provider_enums
642        #provider_impls
643        #llm_model_enum
644        #from_impls
645        #llm_model_impl
646        #display_impl
647        #fromstr_impl
648    };
649
650    let file: syn::File = syn::parse2(file_tokens).expect("generated tokens parse as Rust");
651    let formatted = prettyplease::unparse(&file);
652    format!(
653        "// Auto-generated from models.dev — do not edit manually\n// Regenerated automatically by build.rs\n\n{formatted}"
654    )
655}
656
657fn emit_provider_enum() -> TokenStream {
658    let catalog_variants = PROVIDERS.iter().map(|cfg| format_ident!("{}", cfg.enum_name));
659    let dynamic_variants = DYNAMIC_PROVIDERS.iter().map(|d| format_ident!("{}", d.enum_name));
660    quote! {
661        /// Typed provider identifier — covers both catalog providers
662        /// (`Anthropic`, `Codex`, …) and dynamic providers whose model name is
663        /// user-supplied (`Ollama`, `LlamaCpp`).
664        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
665        pub enum Provider {
666            #(#catalog_variants,)*
667            #(#dynamic_variants,)*
668        }
669    }
670}
671
672fn emit_provider_enum_impl() -> TokenStream {
673    let parser_arms = provider_match_arms(|cfg| cfg.parser_name, |d| d.parser_name);
674    let genai_provider_name_arms = provider_match_arms(|cfg| cfg.genai_provider_name, |d| d.genai_provider_name);
675    let display_arms = provider_match_arms(|cfg| cfg.display_name, |d| d.display_name);
676
677    let env_var_some = PROVIDERS.iter().filter_map(|cfg| {
678        cfg.env_var.map(|var| {
679            let v = format_ident!("{}", cfg.enum_name);
680            quote! { Self::#v => Some(#var), }
681        })
682    });
683
684    let env_var_none = provider_or_pats(|cfg| cfg.env_var.is_none(), |_| true);
685    let oauth_some = PROVIDERS.iter().filter_map(|cfg| {
686        cfg.oauth_provider_id.map(|id| {
687            let v = format_ident!("{}", cfg.enum_name);
688            quote! { Self::#v => Some(#id), }
689        })
690    });
691    let oauth_none = provider_or_pats(|cfg| cfg.oauth_provider_id.is_none(), |_| true);
692
693    let is_local_true = provider_or_pats(|_| false, |_| true);
694    let is_local_false = provider_or_pats(|_| true, |_| false);
695    let all_variants = PROVIDERS
696        .iter()
697        .map(|cfg| format_ident!("{}", cfg.enum_name))
698        .chain(DYNAMIC_PROVIDERS.iter().map(|d| format_ident!("{}", d.enum_name)));
699
700    quote! {
701        impl Provider {
702            /// All providers — catalog and dynamic — in declaration order.
703            pub const ALL: &[Provider] = &[#(Self::#all_variants),*];
704
705            /// Parser name used in `provider:model` strings (e.g. `"anthropic"`).
706            pub fn parser_name(self) -> &'static str {
707                match self { #parser_arms }
708            }
709
710            /// OpenTelemetry `GenAI` semantic-convention provider name.
711            #[allow(clippy::match_same_arms)]
712            pub fn genai_provider_name(self) -> &'static str {
713                match self { #genai_provider_name_arms }
714            }
715
716            /// Human-readable provider name (e.g. `"AWS Bedrock"`).
717            pub fn display_name(self) -> &'static str {
718                match self { #display_arms }
719            }
720
721            /// API-key env var the provider requires, if any.
722            pub fn required_env_var(self) -> Option<&'static str> {
723                match self {
724                    #(#env_var_some)*
725                    #env_var_none => None,
726                }
727            }
728
729            /// OAuth provider ID if this provider authenticates via OAuth.
730            pub fn oauth_provider_id(self) -> Option<&'static str> {
731                match self {
732                    #(#oauth_some)*
733                    #oauth_none => None,
734                }
735            }
736
737            /// Local providers run models on the user's machine — there's no
738            /// remote API to call and no env var to satisfy.
739            pub fn is_local(self) -> bool {
740                match self {
741                    #is_local_true => true,
742                    #is_local_false => false,
743                }
744            }
745        }
746    }
747}
748
749fn emit_provider_enum_display() -> TokenStream {
750    quote! {
751        impl std::fmt::Display for Provider {
752            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
753                f.write_str(self.parser_name())
754            }
755        }
756    }
757}
758
759fn emit_provider_enum_fromstr() -> TokenStream {
760    let catalog_arms = PROVIDERS.iter().map(|cfg| {
761        let v = format_ident!("{}", cfg.enum_name);
762        let name = cfg.parser_name;
763        quote! { #name => Ok(Self::#v), }
764    });
765
766    let dynamic_arms = DYNAMIC_PROVIDERS.iter().map(|d| {
767        let v = format_ident!("{}", d.enum_name);
768        let name = d.parser_name;
769        quote! { #name => Ok(Self::#v), }
770    });
771
772    quote! {
773        impl std::str::FromStr for Provider {
774            type Err = String;
775            fn from_str(s: &str) -> Result<Self, Self::Err> {
776                match s {
777                    #(#catalog_arms)*
778                    #(#dynamic_arms)*
779                    other => Err(format!("Unknown provider: '{other}'")),
780                }
781            }
782        }
783    }
784}
785
786fn emit_provider_enums(provider_models: &ProviderModels) -> TokenStream {
787    let enums = PROVIDERS.iter().map(|cfg| {
788        let inner = format_ident!("{}", cfg.inner_enum_name());
789        let variants = provider_models[cfg.dev_id].iter().map(|m| format_ident!("{}", m.variant_name));
790        quote! {
791            #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
792            pub enum #inner {
793                #(#variants,)*
794            }
795        }
796    });
797    quote! { #(#enums)* }
798}
799
800fn emit_provider_impls(provider_models: &ProviderModels) -> TokenStream {
801    let impls = PROVIDERS.iter().map(|cfg| {
802        let models = &provider_models[cfg.dev_id];
803        let enum_ident = format_ident!("{}", cfg.inner_enum_name());
804
805        let model_id_arms = models.iter().map(|m| {
806            let v = format_ident!("{}", m.variant_name);
807            let id = &m.model_id;
808            quote! { Self::#v => #id, }
809        });
810
811        let display_name_arms = grouped_arms(
812            models,
813            |m| m.display_name.clone(),
814            |m| {
815                let s = &m.display_name;
816                quote! { #s }
817            },
818        );
819
820        let context_window_arms =
821            grouped_arms(models, |m| m.context_window, |m| num_lit_with_underscores(m.context_window));
822
823        let reasoning_levels_arms = emit_reasoning_levels_arms(models);
824        let disabled_support_arms = grouped_arms(
825            models,
826            |m| m.disabled_support,
827            |m| {
828                let variant = format_ident!("{}", m.disabled_support);
829                quote! { crate::reasoning::ReasoningDisabledSupport::#variant }
830            },
831        );
832
833        let prompt_caching_arms = grouped_arms(
834            models,
835            |m| m.supports_prompt_caching,
836            |m| {
837                let b = m.supports_prompt_caching;
838                quote! { #b }
839            },
840        );
841
842        let pricing_arms = emit_pricing_arms(models);
843
844        let modality_methods = ["image", "audio"].iter().map(|modality| {
845            let method = format_ident!("supports_{}", modality);
846            let mod_owned = (*modality).to_string();
847            let arms = grouped_arms(models, move |m| m.input_modalities.contains(&mod_owned), {
848                let mod_owned = (*modality).to_string();
849                move |m| {
850                    let b = m.input_modalities.contains(&mod_owned);
851                    quote! { #b }
852                }
853            });
854            quote! {
855                #[allow(clippy::too_many_lines)]
856                pub fn #method(self) -> bool {
857                    match self { #arms }
858                }
859            }
860        });
861
862        let transport_arms = emit_transport_arms(models);
863
864        let all_variants = models.iter().map(|m| format_ident!("{}", m.variant_name));
865
866        let from_str_impl = emit_from_str_impl(&enum_ident, cfg.parser_name, models);
867
868        quote! {
869            impl #enum_ident {
870                #[allow(clippy::too_many_lines)]
871                fn model_id(self) -> &'static str {
872                    match self { #(#model_id_arms)* }
873                }
874
875                #[allow(clippy::too_many_lines)]
876                fn display_name(self) -> &'static str {
877                    match self { #display_name_arms }
878                }
879
880                #[allow(clippy::too_many_lines)]
881                fn context_window(self) -> u32 {
882                    match self { #context_window_arms }
883                }
884
885                #[allow(clippy::too_many_lines)]
886                pub fn reasoning_levels(self) -> &'static [ReasoningEffort] {
887                    match self { #reasoning_levels_arms }
888                }
889
890                #[allow(clippy::too_many_lines)]
891                pub fn reasoning_disabled_support(self) -> crate::reasoning::ReasoningDisabledSupport {
892                    match self { #disabled_support_arms }
893                }
894
895                pub fn supports_reasoning(self) -> bool {
896                    self.reasoning_levels().iter().any(|effort| effort.is_enabled())
897                }
898
899                #[allow(clippy::too_many_lines)]
900                pub fn supports_prompt_caching(self) -> bool {
901                    match self { #prompt_caching_arms }
902                }
903
904                #[allow(clippy::too_many_lines, clippy::match_same_arms, clippy::unreadable_literal)]
905                pub fn pricing(self) -> Option<ModelPricing> {
906                    match self { #pricing_arms }
907                }
908
909                #(#modality_methods)*
910
911                #[allow(clippy::too_many_lines)]
912                pub fn transport(self) -> Option<ModelTransport> {
913                    match self { #transport_arms }
914                }
915
916                const ALL: &[#enum_ident] = &[#(Self::#all_variants),*];
917            }
918
919            #from_str_impl
920        }
921    });
922    quote! { #(#impls)* }
923}
924
925fn emit_pricing_arms(models: &[ModelInfo]) -> TokenStream {
926    let arms = models.iter().map(|model| {
927        let variant = format_ident!("{}", model.variant_name);
928        let Some(pricing) = &model.pricing else {
929            return quote! { Self::#variant => None, };
930        };
931        let input = pricing.input;
932        let output = pricing.output;
933        let cache_read = pricing.cache_read.map_or_else(|| quote! { None }, |value| quote! { Some(#value) });
934        let cache_write = pricing.cache_write.map_or_else(|| quote! { None }, |value| quote! { Some(#value) });
935        quote! {
936            Self::#variant => Some(ModelPricing {
937                input_per_million: #input,
938                output_per_million: #output,
939                cache_read_per_million: #cache_read,
940                cache_write_per_million: #cache_write,
941            }),
942        }
943    });
944    quote! { #(#arms)* }
945}
946
947fn emit_from_str_impl(enum_ident: &proc_macro2::Ident, parser_name: &str, models: &[ModelInfo]) -> TokenStream {
948    let arms = models.iter().map(|m| {
949        let id = &m.model_id;
950        let v = format_ident!("{}", m.variant_name);
951        quote! { #id => Ok(Self::#v), }
952    });
953    let err_msg = format!("Unknown {parser_name} model: '{{s}}'");
954    quote! {
955        impl std::str::FromStr for #enum_ident {
956            type Err = String;
957
958            #[allow(clippy::too_many_lines)]
959            fn from_str(s: &str) -> Result<Self, Self::Err> {
960                match s {
961                    #(#arms)*
962                    _ => Err(format!(#err_msg)),
963                }
964            }
965        }
966    }
967}
968
969/// Emit match arms grouped by value to avoid clippy `match_same_arms`.
970fn grouped_arms<K, R>(
971    models: &[ModelInfo],
972    key_fn: impl Fn(&ModelInfo) -> K,
973    rhs_fn: impl Fn(&ModelInfo) -> R,
974) -> TokenStream
975where
976    K: Eq + Ord,
977    R: ToTokens,
978{
979    let mut groups: BTreeMap<K, Vec<&ModelInfo>> = BTreeMap::new();
980    for m in models {
981        groups.entry(key_fn(m)).or_default().push(m);
982    }
983    let arms = groups.values().map(|members| {
984        let pats = members.iter().map(|m| {
985            let v = format_ident!("{}", m.variant_name);
986            quote! { Self::#v }
987        });
988        let rhs = rhs_fn(members[0]);
989        quote! { #(#pats)|* => #rhs, }
990    });
991    quote! { #(#arms)* }
992}
993
994fn emit_reasoning_levels_arms(models: &[ModelInfo]) -> TokenStream {
995    grouped_arms(
996        models,
997        |m| m.reasoning_levels.clone(),
998        |m| {
999            if m.reasoning_levels.is_empty() {
1000                quote! { &[] }
1001            } else {
1002                let items = m.reasoning_levels.iter().map(|l| {
1003                    let variant = format_ident!("{}", level_str_to_variant(l));
1004                    quote! { ReasoningEffort::#variant }
1005                });
1006                quote! { &[#(#items),*] }
1007            }
1008        },
1009    )
1010}
1011
1012fn emit_transport_arms(models: &[ModelInfo]) -> TokenStream {
1013    grouped_arms(
1014        models,
1015        |m| m.transport.clone(),
1016        |m| match m.transport.as_ref() {
1017            Some(TransportInfo::OpenAiResponses { base_url_template }) => {
1018                quote! { Some(ModelTransport::OpenAiResponses { base_url_template: #base_url_template }) }
1019            }
1020            None => quote! { None },
1021        },
1022    )
1023}
1024
1025/// Map a reasoning level string to its `ReasoningEffort` variant name
1026/// (the serialized name with the first letter capitalized).
1027fn level_str_to_variant(level: &str) -> String {
1028    let canonical =
1029        level.parse::<utils::ReasoningEffort>().unwrap_or_else(|_| panic!("Unknown reasoning level: {level}")).as_str();
1030    let mut variant = canonical.to_string();
1031    variant[..1].make_ascii_uppercase();
1032    variant
1033}
1034
1035fn emit_llm_model_enum() -> TokenStream {
1036    let catalog_variants = PROVIDERS.iter().map(|cfg| {
1037        let v = format_ident!("{}", cfg.enum_name);
1038        let inner = format_ident!("{}Model", cfg.enum_name);
1039        quote! { #v(#inner) }
1040    });
1041    let dynamic_variants = DYNAMIC_PROVIDERS.iter().map(|d| {
1042        let v = format_ident!("{}", d.enum_name);
1043        quote! { #v(String) }
1044    });
1045    quote! {
1046        /// A model from a specific provider
1047        #[derive(Debug, Clone, PartialEq, Eq, Hash)]
1048        pub enum LlmModel {
1049            #(#catalog_variants,)*
1050            #(#dynamic_variants,)*
1051        }
1052    }
1053}
1054
1055fn emit_from_impls() -> TokenStream {
1056    let impls = PROVIDERS.iter().map(|cfg| {
1057        let outer = format_ident!("{}Model", cfg.enum_name);
1058        let v = format_ident!("{}", cfg.enum_name);
1059        quote! {
1060            impl From<#outer> for LlmModel {
1061                fn from(m: #outer) -> Self {
1062                    LlmModel::#v(m)
1063                }
1064            }
1065        }
1066    });
1067    quote! { #(#impls)* }
1068}
1069
1070fn emit_llm_model_impl() -> TokenStream {
1071    let model_id = emit_llm_model_id();
1072    let display_name = emit_llm_display_name();
1073    let provider = emit_llm_provider();
1074    let provider_enum = emit_llm_provider_enum();
1075    let provider_display_name = emit_llm_provider_display_name();
1076    let context_window = emit_llm_context_window();
1077    let required_env_var = emit_llm_required_env_var();
1078    let all_required_env_vars = emit_llm_all_required_env_vars();
1079    let oauth_provider_id = emit_llm_oauth_provider_id();
1080    let reasoning_levels = emit_llm_reasoning_levels();
1081    let disabled_support = llm_delegate_with_dynamic_default(
1082        "reasoning_disabled_support",
1083        &quote! { crate::reasoning::ReasoningDisabledSupport::Unsupported },
1084    );
1085    let supports_reasoning = emit_llm_supports_reasoning();
1086    let supports_reasoning_off_transport = emit_llm_supports_reasoning_off_transport();
1087    let supports_prompt_caching = emit_llm_supports_prompt_caching();
1088    let pricing = emit_llm_pricing();
1089    let modality_methods = ["image", "audio"].iter().map(|m| emit_llm_supports_modality(m));
1090    let transport = emit_llm_transport();
1091    let all = emit_llm_all();
1092
1093    quote! {
1094        impl LlmModel {
1095            #model_id
1096            #display_name
1097            #provider
1098            #provider_enum
1099            #provider_display_name
1100            #context_window
1101            #required_env_var
1102            #all_required_env_vars
1103            #oauth_provider_id
1104            #reasoning_levels
1105            pub fn reasoning_disabled_support(&self) -> crate::reasoning::ReasoningDisabledSupport {
1106                #disabled_support
1107            }
1108
1109            /// Whether this model advertises an explicit off selection.
1110            pub fn supports_reasoning_off(&self) -> bool {
1111                self.reasoning_levels().contains(&ReasoningEffort::Disabled)
1112            }
1113
1114            #supports_reasoning_off_transport
1115
1116            /// Explicit choices executable by the current adapter. Default is always valid.
1117            pub fn effective_reasoning_levels(&self) -> Vec<ReasoningEffort> {
1118                self.reasoning_levels()
1119                    .iter()
1120                    .copied()
1121                    .filter(|effort| *effort != ReasoningEffort::Disabled || self.supports_reasoning_off_transport())
1122                    .collect()
1123            }
1124
1125            pub fn validate_reasoning_effort(&self, effort: ReasoningEffort) -> Result<(), crate::catalog::ReasoningEffortError> {
1126                let supported = self.effective_reasoning_levels();
1127                if effort == ReasoningEffort::Default || supported.contains(&effort) {
1128                    Ok(())
1129                } else {
1130                    Err(crate::catalog::ReasoningEffortError::Unsupported { model: self.to_string(), effort, supported })
1131                }
1132            }
1133
1134            #supports_reasoning
1135            #supports_prompt_caching
1136            #pricing
1137            #(#modality_methods)*
1138            #transport
1139            #all
1140        }
1141    }
1142}
1143
1144fn emit_llm_model_id() -> TokenStream {
1145    let catalog_arms = PROVIDERS.iter().map(|cfg| {
1146        let v = format_ident!("{}", cfg.enum_name);
1147        if cfg.is_hybrid_dynamic {
1148            quote! { Self::#v(m) => m.model_id(), }
1149        } else {
1150            quote! { Self::#v(m) => Cow::Borrowed(m.model_id()), }
1151        }
1152    });
1153    let dyn_pats = dynamic_pattern_with_binding("s");
1154    quote! {
1155        /// Raw model ID (e.g. `claude-opus-4-6`, `llama3.2`)
1156        pub fn model_id(&self) -> Cow<'static, str> {
1157            match self {
1158                #(#catalog_arms)*
1159                #dyn_pats => Cow::Owned(s.clone()),
1160            }
1161        }
1162    }
1163}
1164
1165fn emit_llm_display_name() -> TokenStream {
1166    let catalog_arms = PROVIDERS.iter().map(|cfg| {
1167        let v = format_ident!("{}", cfg.enum_name);
1168        if cfg.is_hybrid_dynamic {
1169            quote! { Self::#v(m) => m.display_name(), }
1170        } else {
1171            quote! { Self::#v(m) => Cow::Borrowed(m.display_name()), }
1172        }
1173    });
1174    let dyn_arms = DYNAMIC_PROVIDERS.iter().map(|d| {
1175        let v = format_ident!("{}", d.enum_name);
1176        let fmt = format!("{} {{s}}", d.enum_name);
1177        quote! { Self::#v(s) => Cow::Owned(format!(#fmt)), }
1178    });
1179    quote! {
1180        /// Human-readable display name (e.g. `Claude Opus 4.6`)
1181        pub fn display_name(&self) -> Cow<'static, str> {
1182            match self {
1183                #(#catalog_arms)*
1184                #(#dyn_arms)*
1185            }
1186        }
1187    }
1188}
1189
1190fn emit_llm_provider() -> TokenStream {
1191    let arms = llm_match_arms_ignored(|cfg| cfg.parser_name, |d| d.parser_name);
1192    quote! {
1193        /// Provider identifier (e.g. `anthropic`)
1194        pub fn provider(&self) -> &'static str {
1195            match self { #arms }
1196        }
1197    }
1198}
1199
1200fn emit_llm_provider_enum() -> TokenStream {
1201    let arms = llm_match_arms_ignored(
1202        |cfg| {
1203            let v = format_ident!("{}", cfg.enum_name);
1204            quote! { Provider::#v }
1205        },
1206        |d| {
1207            let v = format_ident!("{}", d.enum_name);
1208            quote! { Provider::#v }
1209        },
1210    );
1211    quote! {
1212        /// Typed provider identifier.
1213        pub fn provider_enum(&self) -> Provider {
1214            match self { #arms }
1215        }
1216    }
1217}
1218
1219fn emit_llm_provider_display_name() -> TokenStream {
1220    let arms = llm_match_arms_ignored(|cfg| cfg.display_name, |d| d.display_name);
1221    quote! {
1222        /// Human-readable provider name (e.g. `AWS Bedrock`)
1223        pub fn provider_display_name(&self) -> &'static str {
1224            match self { #arms }
1225        }
1226    }
1227}
1228
1229fn emit_llm_context_window() -> TokenStream {
1230    let catalog_arms = PROVIDERS.iter().map(|cfg| {
1231        let v = format_ident!("{}", cfg.enum_name);
1232        if cfg.is_hybrid_dynamic {
1233            quote! { Self::#v(m) => m.context_window(), }
1234        } else {
1235            quote! { Self::#v(m) => Some(m.context_window()), }
1236        }
1237    });
1238    let dyn_pats = dynamic_pattern_with_binding("_");
1239    quote! {
1240        /// Context window size in tokens (None for dynamic providers)
1241        pub fn context_window(&self) -> Option<u32> {
1242            match self {
1243                #(#catalog_arms)*
1244                #dyn_pats => None,
1245            }
1246        }
1247    }
1248}
1249
1250fn emit_llm_required_env_var() -> TokenStream {
1251    let some_arms = PROVIDERS.iter().filter_map(|cfg| {
1252        cfg.env_var.map(|var| {
1253            let v = format_ident!("{}", cfg.enum_name);
1254            quote! { Self::#v(_) => Some(#var), }
1255        })
1256    });
1257    let none_pats = llm_or_pats(|cfg| cfg.env_var.is_none(), |_| true);
1258    quote! {
1259        /// Required env var for this model's provider (None for local providers)
1260        pub fn required_env_var(&self) -> Option<&'static str> {
1261            match self {
1262                #(#some_arms)*
1263                #none_pats => None,
1264            }
1265        }
1266    }
1267}
1268
1269fn emit_llm_all_required_env_vars() -> TokenStream {
1270    let vars = PROVIDERS.iter().filter_map(|cfg| cfg.env_var);
1271    quote! {
1272        /// All provider API key env var names (deduplicated, static)
1273        pub const ALL_REQUIRED_ENV_VARS: &[&str] = &[#(#vars),*];
1274    }
1275}
1276
1277fn emit_llm_oauth_provider_id() -> TokenStream {
1278    let some_arms = PROVIDERS.iter().filter_map(|cfg| {
1279        cfg.oauth_provider_id.map(|id| {
1280            let v = format_ident!("{}", cfg.enum_name);
1281            quote! { Self::#v(_) => Some(#id), }
1282        })
1283    });
1284    let none_pats = llm_or_pats(|cfg| cfg.oauth_provider_id.is_none(), |_| true);
1285    quote! {
1286        /// OAuth provider ID if this model requires OAuth login (e.g. `"codex"`)
1287        pub fn oauth_provider_id(&self) -> Option<&'static str> {
1288            match self {
1289                #(#some_arms)*
1290                #none_pats => None,
1291            }
1292        }
1293    }
1294}
1295
1296fn emit_llm_reasoning_levels() -> TokenStream {
1297    let body = llm_delegate_with_dynamic_default("reasoning_levels", &quote! { &[] });
1298    quote! {
1299        /// Reasoning levels supported by this model (empty if not a reasoning model)
1300        pub fn reasoning_levels(&self) -> &'static [ReasoningEffort] {
1301            #body
1302        }
1303    }
1304}
1305
1306fn emit_llm_supports_reasoning() -> TokenStream {
1307    quote! {
1308        /// Whether this model supports reasoning/extended thinking
1309        pub fn supports_reasoning(&self) -> bool {
1310            self.reasoning_levels().iter().any(|effort| effort.is_enabled())
1311        }
1312    }
1313}
1314
1315fn emit_llm_supports_reasoning_off_transport() -> TokenStream {
1316    let variants = |filter: fn(&ProviderConfig) -> bool| {
1317        let pats = PROVIDERS.iter().filter(|cfg| filter(cfg)).map(|cfg| {
1318            let v = format_ident!("{}", cfg.enum_name);
1319            quote! { Provider::#v }
1320        });
1321        quote! { #(#pats)|* }
1322    };
1323    let effort_only = variants(|cfg| cfg.uses_openai_compatible_api);
1324    let model_transport = variants(|cfg| cfg.use_model_transport);
1325    let always = variants(|cfg| !cfg.uses_openai_compatible_api && !cfg.use_model_transport);
1326    let dynamic = DYNAMIC_PROVIDERS.iter().map(|d| {
1327        let v = format_ident!("{}", d.enum_name);
1328        quote! { Provider::#v }
1329    });
1330    quote! {
1331        pub fn supports_reasoning_off_transport(&self) -> bool {
1332            if !self.supports_reasoning_off() {
1333                return false;
1334            }
1335            match self.provider_enum() {
1336                #always => true,
1337                #model_transport => self.transport().is_some(),
1338                #effort_only => {
1339                    self.reasoning_disabled_support() == crate::reasoning::ReasoningDisabledSupport::Effort
1340                }
1341                #(#dynamic)|* => false,
1342            }
1343        }
1344    }
1345}
1346
1347fn emit_llm_supports_prompt_caching() -> TokenStream {
1348    let body = llm_delegate_with_dynamic_default("supports_prompt_caching", &quote! { false });
1349    quote! {
1350        /// Whether this model supports provider-side prompt caching
1351        pub fn supports_prompt_caching(&self) -> bool {
1352            #body
1353        }
1354    }
1355}
1356
1357fn emit_llm_pricing() -> TokenStream {
1358    let body = llm_delegate_with_dynamic_default("pricing", &quote! { None });
1359    quote! {
1360        pub fn pricing(&self) -> Option<ModelPricing> {
1361            #body
1362        }
1363    }
1364}
1365
1366fn emit_llm_transport() -> TokenStream {
1367    let body = llm_delegate_with_dynamic_default("transport", &quote! { None });
1368    quote! {
1369        /// Per-model transport override, when the model does not use its
1370        /// provider's default endpoint and wire protocol.
1371        pub fn transport(&self) -> Option<ModelTransport> {
1372            #body
1373        }
1374    }
1375}
1376
1377fn emit_llm_supports_modality(modality: &str) -> TokenStream {
1378    let method = format!("supports_{modality}");
1379    let method_ident = format_ident!("{}", method);
1380    let doc = format!(" Whether this model supports {modality} input");
1381    let body = llm_delegate_with_dynamic_default(&method, &quote! { false });
1382    quote! {
1383        #[doc = #doc]
1384        pub fn #method_ident(&self) -> bool {
1385            #body
1386        }
1387    }
1388}
1389
1390fn emit_llm_all() -> TokenStream {
1391    let pushes = PROVIDERS.iter().map(|cfg| {
1392        let inner = format_ident!("{}", cfg.inner_enum_name());
1393        let outer = format_ident!("{}", cfg.outer_enum_name());
1394        let v = format_ident!("{}", cfg.enum_name);
1395        if cfg.is_hybrid_dynamic {
1396            quote! {
1397                v.extend(#inner::ALL.iter().copied().map(#outer::Foundation).map(LlmModel::#v));
1398            }
1399        } else {
1400            quote! {
1401                v.extend(#inner::ALL.iter().copied().map(LlmModel::#v));
1402            }
1403        }
1404    });
1405    quote! {
1406        /// All catalog models (excludes dynamic providers)
1407        pub fn all() -> &'static [LlmModel] {
1408            static ALL: LazyLock<Vec<LlmModel>> = LazyLock::new(|| {
1409                let mut v = Vec::new();
1410                #(#pushes)*
1411                v
1412            });
1413            &ALL
1414        }
1415    }
1416}
1417
1418fn emit_display_impl() -> TokenStream {
1419    quote! {
1420        impl std::fmt::Display for LlmModel {
1421            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1422                write!(f, "{}:{}", self.provider(), self.model_id())
1423            }
1424        }
1425    }
1426}
1427
1428fn emit_fromstr_impl() -> TokenStream {
1429    let catalog_arms = PROVIDERS.iter().map(|cfg| {
1430        let name = cfg.parser_name;
1431        let outer = format_ident!("{}Model", cfg.enum_name);
1432        let v = format_ident!("{}", cfg.enum_name);
1433        quote! { #name => model_str.parse::<#outer>().map(Self::#v), }
1434    });
1435    let dyn_arms = DYNAMIC_PROVIDERS.iter().map(|d| {
1436        let name = d.parser_name;
1437        let v = format_ident!("{}", d.enum_name);
1438        quote! { #name => Ok(Self::#v(model_str.to_string())), }
1439    });
1440    quote! {
1441        impl std::str::FromStr for LlmModel {
1442            type Err = String;
1443
1444            /// Parse a `provider:model` string into an `LlmModel`
1445            fn from_str(s: &str) -> Result<Self, Self::Err> {
1446                let (provider_str, model_str) = s.split_once(':').unwrap_or((s, ""));
1447                match provider_str {
1448                    #(#catalog_arms)*
1449                    #(#dyn_arms)*
1450                    _ => Err(format!("Unknown provider: '{provider_str}'")),
1451                }
1452            }
1453        }
1454    }
1455}
1456
1457/// Build a `Self::Ollama(b) | Self::LlamaCpp(b)` pattern for all dynamic providers.
1458fn dynamic_pattern_with_binding(binding: &str) -> TokenStream {
1459    let binding_ident = if binding == "_" {
1460        quote! { _ }
1461    } else {
1462        let b = format_ident!("{}", binding);
1463        quote! { #b }
1464    };
1465    let pats = DYNAMIC_PROVIDERS.iter().map(|d| {
1466        let v = format_ident!("{}", d.enum_name);
1467        quote! { Self::#v(#binding_ident) }
1468    });
1469    quote! { #(#pats)|* }
1470}
1471
1472/// Build `Self::A => va, Self::B => vb, ...` arms for every `Provider` variant
1473/// (catalog + dynamic). The `Provider` enum carries no inner data so there is
1474/// no binding.
1475fn provider_match_arms<V: ToTokens>(
1476    catalog_value: impl Fn(&ProviderConfig) -> V,
1477    dynamic_value: impl Fn(&DynamicProviderConfig) -> V,
1478) -> TokenStream {
1479    let catalog = PROVIDERS.iter().map(|cfg| {
1480        let v = format_ident!("{}", cfg.enum_name);
1481        let val = catalog_value(cfg);
1482        quote! { Self::#v => #val, }
1483    });
1484    let dynamic = DYNAMIC_PROVIDERS.iter().map(|d| {
1485        let v = format_ident!("{}", d.enum_name);
1486        let val = dynamic_value(d);
1487        quote! { Self::#v => #val, }
1488    });
1489    quote! { #(#catalog)* #(#dynamic)* }
1490}
1491
1492/// Build `Self::A | Self::B | ...` patterns selecting `Provider` variants by
1493/// predicate, across catalog + dynamic.
1494fn provider_or_pats(
1495    include_catalog: impl Fn(&ProviderConfig) -> bool,
1496    include_dynamic: impl Fn(&DynamicProviderConfig) -> bool,
1497) -> TokenStream {
1498    let catalog = PROVIDERS.iter().filter(|cfg| include_catalog(cfg)).map(|cfg| {
1499        let v = format_ident!("{}", cfg.enum_name);
1500        quote! { Self::#v }
1501    });
1502    let dynamic = DYNAMIC_PROVIDERS.iter().filter(|d| include_dynamic(d)).map(|d| {
1503        let v = format_ident!("{}", d.enum_name);
1504        quote! { Self::#v }
1505    });
1506    let pats = catalog.chain(dynamic);
1507    quote! { #(#pats)|* }
1508}
1509
1510/// Build `Self::A(_) => va, ...` arms for every `LlmModel` variant — the
1511/// wrapped inner value is ignored.
1512fn llm_match_arms_ignored<V: ToTokens>(
1513    catalog_value: impl Fn(&ProviderConfig) -> V,
1514    dynamic_value: impl Fn(&DynamicProviderConfig) -> V,
1515) -> TokenStream {
1516    let catalog = PROVIDERS.iter().map(|cfg| {
1517        let v = format_ident!("{}", cfg.enum_name);
1518        let val = catalog_value(cfg);
1519        quote! { Self::#v(_) => #val, }
1520    });
1521    let dynamic = DYNAMIC_PROVIDERS.iter().map(|d| {
1522        let v = format_ident!("{}", d.enum_name);
1523        let val = dynamic_value(d);
1524        quote! { Self::#v(_) => #val, }
1525    });
1526    quote! { #(#catalog)* #(#dynamic)* }
1527}
1528
1529/// Build `Self::A(_) | Self::B(_) | ...` patterns selecting `LlmModel`
1530/// variants by predicate, across catalog + dynamic.
1531fn llm_or_pats(
1532    include_catalog: impl Fn(&ProviderConfig) -> bool,
1533    include_dynamic: impl Fn(&DynamicProviderConfig) -> bool,
1534) -> TokenStream {
1535    let catalog = PROVIDERS.iter().filter(|cfg| include_catalog(cfg)).map(|cfg| {
1536        let v = format_ident!("{}", cfg.enum_name);
1537        quote! { Self::#v(_) }
1538    });
1539    let dynamic = DYNAMIC_PROVIDERS.iter().filter(|d| include_dynamic(d)).map(|d| {
1540        let v = format_ident!("{}", d.enum_name);
1541        quote! { Self::#v(_) }
1542    });
1543    let pats = catalog.chain(dynamic);
1544    quote! { #(#pats)|* }
1545}
1546
1547/// Build the body of an `LlmModel` method that delegates to a same-named
1548/// method on the inner catalog enum, with a single combined arm for all
1549/// dynamic providers.
1550fn llm_delegate_with_dynamic_default(method: &str, dynamic_value: &TokenStream) -> TokenStream {
1551    let method_ident = format_ident!("{}", method);
1552    let catalog_arms = PROVIDERS.iter().map(|cfg| {
1553        let v = format_ident!("{}", cfg.enum_name);
1554        quote! { Self::#v(m) => m.#method_ident(), }
1555    });
1556    let dyn_pat = dynamic_pattern_with_binding("_");
1557    quote! {
1558        match self {
1559            #(#catalog_arms)*
1560            #dyn_pat => #dynamic_value,
1561        }
1562    }
1563}
1564
1565/// Emit a `u32` literal with underscore separators (e.g. `200_000`).
1566fn num_lit_with_underscores(n: u32) -> TokenStream {
1567    format_number(n).parse().expect("formatted number parses as a token")
1568}
1569
1570/// Format a number with underscore separators (e.g. `200000` → `200_000`).
1571fn format_number(n: u32) -> String {
1572    let s = n.to_string();
1573    if s.len() <= 4 {
1574        return s;
1575    }
1576    let mut result = String::with_capacity(s.len() + s.len() / 3);
1577    for (i, ch) in s.chars().enumerate() {
1578        if i > 0 && (s.len() - i).is_multiple_of(3) {
1579            result.push('_');
1580        }
1581        result.push(ch);
1582    }
1583    result
1584}
1585
1586fn emit_provider_docs(ctx: &CodegenCtx) -> HashMap<String, String> {
1587    let mut docs = HashMap::new();
1588
1589    for cfg in PROVIDERS {
1590        let models = &ctx.provider_models[cfg.dev_id];
1591        let mut doc = String::new();
1592
1593        pushln(&mut doc, format!("`{}` LLM provider.", cfg.display_name));
1594        blank(&mut doc);
1595
1596        pushln(&mut doc, "# Authentication");
1597        blank(&mut doc);
1598        match cfg.env_var {
1599            Some(var) => pushln(&mut doc, format!("Set the `{var}` environment variable.")),
1600            None if cfg.oauth_provider_id.is_some() => {
1601                pushln(&mut doc, "This provider uses OAuth authentication.");
1602            }
1603            None => {
1604                pushln(
1605                    &mut doc,
1606                    "Uses the default AWS credential chain (environment variables, config files, IAM roles).",
1607                );
1608                pushln(
1609                    &mut doc,
1610                    "Models served from a dedicated endpoint also accept a Bedrock API key in `AWS_BEARER_TOKEN_BEDROCK`.",
1611                );
1612            }
1613        }
1614        blank(&mut doc);
1615
1616        pushln(&mut doc, "# Supported models");
1617        blank(&mut doc);
1618        pushln(&mut doc, "| Model ID | Name | Context | Reasoning | Image | Audio |");
1619        pushln(&mut doc, "|----------|------|---------|-----------|-------|-------|");
1620        for model in models {
1621            let ctx_str = format_context_window(model.context_window);
1622            let reasoning = if model.reasoning_levels.iter().any(|level| level != "disabled") { "yes" } else { "" };
1623            let image = if model.input_modalities.contains(&"image".to_string()) { "yes" } else { "" };
1624            let audio = if model.input_modalities.contains(&"audio".to_string()) { "yes" } else { "" };
1625            pushln(
1626                &mut doc,
1627                format!(
1628                    "| `{}` | `{}` | `{}` | {} | {} | {} |",
1629                    model.model_id, model.display_name, ctx_str, reasoning, image, audio
1630                ),
1631            );
1632        }
1633
1634        for model in models.iter().filter(|model| model.disabled_support != "Unsupported") {
1635            pushln(
1636                &mut doc,
1637                format!("Model `{}` advertises `disabled` reasoning (subject to adapter support).", model.model_id),
1638            );
1639        }
1640        push_transport_section(&mut doc, models);
1641
1642        docs.insert(cfg.dev_id.to_string(), doc);
1643    }
1644
1645    for dyn_cfg in DYNAMIC_PROVIDERS {
1646        let mut doc = String::new();
1647        pushln(&mut doc, format!("`{}` LLM provider.", dyn_cfg.display_name));
1648        blank(&mut doc);
1649        pushln(
1650            &mut doc,
1651            format!("This provider accepts any model name at runtime (e.g. `{}:my-model`).", dyn_cfg.parser_name),
1652        );
1653        pushln(&mut doc, "No API key is required.");
1654        docs.insert(dyn_cfg.parser_name.to_string(), doc);
1655    }
1656
1657    docs
1658}
1659
1660/// Document the models that do not use the provider's default endpoint.
1661fn push_transport_section(doc: &mut String, models: &[ModelInfo]) {
1662    let overridden: Vec<&ModelInfo> = models.iter().filter(|m| m.transport.is_some()).collect();
1663    if overridden.is_empty() {
1664        return;
1665    }
1666
1667    blank(doc);
1668    pushln(doc, "# Models with a dedicated endpoint");
1669    blank(doc);
1670    pushln(doc, "These models are served from their own endpoint and wire protocol");
1671    pushln(doc, "rather than the provider's default. `${VAR}` placeholders are resolved");
1672    pushln(doc, "at request time.");
1673    blank(doc);
1674    pushln(doc, "| Model ID | Endpoint | Wire shape |");
1675    pushln(doc, "|----------|----------|------------|");
1676    for model in overridden {
1677        let transport = model.transport.as_ref().expect("filtered to models with a transport");
1678        let (api, shape) = match transport {
1679            TransportInfo::OpenAiResponses { base_url_template } => (base_url_template.as_str(), "responses"),
1680        };
1681        pushln(doc, format!("| `{}` | `{api}` | `{shape}` |", model.model_id));
1682    }
1683}
1684
1685/// Format a token count as human-readable (e.g. `1_000_000` → `1M`, `200_000` → `200k`).
1686fn format_context_window(tokens: u32) -> String {
1687    if tokens == 0 {
1688        return "unknown".to_string();
1689    }
1690    if tokens >= 1_000_000 && tokens.is_multiple_of(1_000_000) {
1691        format!("{}M", tokens / 1_000_000)
1692    } else if tokens >= 1_000 && tokens.is_multiple_of(1_000) {
1693        format!("{}k", tokens / 1_000)
1694    } else {
1695        format_number(tokens)
1696    }
1697}
1698
1699fn pushln(out: &mut String, line: impl AsRef<str>) {
1700    writeln!(out, "{}", line.as_ref()).expect("writing to String should not fail");
1701}
1702
1703fn blank(out: &mut String) {
1704    pushln(out, "");
1705}
1706
1707#[cfg(test)]
1708mod tests {
1709    use super::*;
1710    use serde_json::Value;
1711    use serde_json::json;
1712    use tempfile::NamedTempFile;
1713
1714    #[test]
1715    fn model_id_to_variant_pascal_cases_segments() {
1716        assert_eq!(model_id_to_variant("claude-sonnet-4-5-20250929"), "ClaudeSonnet4520250929");
1717        assert_eq!(model_id_to_variant("gemini-2.5-flash"), "Gemini25Flash");
1718        assert_eq!(model_id_to_variant("deepseek-chat"), "DeepseekChat");
1719        assert_eq!(model_id_to_variant("glm-4.5"), "Glm45");
1720    }
1721
1722    #[test]
1723    fn model_id_to_variant_handles_slash_and_colon() {
1724        assert_eq!(model_id_to_variant("anthropic/claude-opus-4.6"), "AnthropicClaudeOpus46");
1725        assert_eq!(model_id_to_variant("openai/gpt-5.1-codex-max"), "OpenaiGpt51CodexMax");
1726        assert_eq!(model_id_to_variant("deepseek/deepseek-r1:free"), "DeepseekDeepseekR1Free");
1727    }
1728
1729    #[test]
1730    fn is_alias_detects_latest_suffix() {
1731        assert!(is_alias("claude-sonnet-4-5-latest"));
1732        assert!(is_alias("claude-3-7-sonnet-latest"));
1733        assert!(!is_alias("claude-sonnet-4-5-20250929"));
1734    }
1735
1736    #[test]
1737    fn build_uses_explicit_context_windows_for_codex_models() {
1738        let data = minimal_models_dev_json();
1739
1740        let models = build_from_value(&data);
1741        let window = |id: &str| models["codex"].iter().find(|model| model.model_id == id).unwrap().context_window;
1742        for model_id in [
1743            "gpt-6.1-sol",
1744            "gpt-6-sol",
1745            "gpt-6-astra",
1746            "gpt-6-luna",
1747            "gpt-5.6-sol",
1748            "gpt-5.6-terra",
1749            "gpt-5.6-luna",
1750            "gpt-5.5",
1751            "gpt-5.4",
1752            "gpt-5.4-mini",
1753            "gpt-5.2",
1754        ] {
1755            assert_eq!(window(model_id), 272_000);
1756        }
1757    }
1758
1759    #[test]
1760    fn transport_override_is_preserved_from_model_metadata() {
1761        let mut data = minimal_models_dev_json();
1762        insert_models(
1763            &mut data,
1764            "amazon-bedrock",
1765            json!({
1766                "with-transport": {
1767                    "id": "with-transport", "name": "With Transport", "tool_call": true,
1768                    "limit": {"context": 1000, "output": 0},
1769                    "provider": {
1770                        "npm": "@ai-sdk/amazon-bedrock/mantle",
1771                        "api": "https://example.${AWS_REGION}.api.aws/openai/v1",
1772                        "shape": "responses"
1773                    }
1774                },
1775                "without-transport": {
1776                    "id": "without-transport", "name": "Without Transport", "tool_call": true,
1777                    "limit": {"context": 1000, "output": 0}
1778                }
1779            }),
1780        );
1781
1782        let models = build_from_value(&data);
1783        let transport =
1784            |id: &str| models["amazon-bedrock"].iter().find(|m| m.model_id == id).unwrap().transport.clone();
1785
1786        assert_eq!(
1787            transport("with-transport"),
1788            Some(TransportInfo::OpenAiResponses {
1789                base_url_template: "https://example.${AWS_REGION}.api.aws/openai/v1".to_string(),
1790            })
1791        );
1792        assert_eq!(transport("without-transport"), None);
1793    }
1794
1795    #[test]
1796    fn transport_override_with_only_an_npm_package_is_ignored() {
1797        let mut data = minimal_models_dev_json();
1798        anthropic_models(
1799            &mut data,
1800            json!({
1801                "npm-only": {
1802                    "id": "npm-only", "name": "Npm Only", "tool_call": true,
1803                    "limit": {"context": 1000, "output": 0},
1804                    "provider": {"npm": "@ai-sdk/anthropic"}
1805                }
1806            }),
1807        );
1808
1809        let models = build_from_value(&data);
1810
1811        assert_eq!(models["anthropic"].iter().find(|m| m.model_id == "npm-only").unwrap().transport, None);
1812    }
1813
1814    #[test]
1815    fn unknown_wire_shape_is_rejected() {
1816        let mut data = minimal_models_dev_json();
1817        insert_models(
1818            &mut data,
1819            "amazon-bedrock",
1820            json!({
1821                "weird": {
1822                    "id": "weird", "name": "Weird", "tool_call": true,
1823                    "limit": {"context": 1000, "output": 0},
1824                    "provider": {"api": "https://example.com/v1", "shape": "telepathy"}
1825                }
1826            }),
1827        );
1828        let parsed: ModelsDevData = serde_json::from_value(data).expect("parse fixture");
1829
1830        let error = build_provider_models(&parsed).unwrap_err();
1831
1832        assert!(
1833            matches!(error, CodegenError::UnsupportedWireShape { ref model_id, ref shape }
1834                if model_id == "weird" && shape == "telepathy"),
1835            "unexpected error: {error}"
1836        );
1837    }
1838
1839    #[test]
1840    fn incomplete_bedrock_transport_is_rejected() {
1841        let mut data = minimal_models_dev_json();
1842        insert_models(
1843            &mut data,
1844            "amazon-bedrock",
1845            json!({
1846                "incomplete": {
1847                    "id": "incomplete", "name": "Incomplete", "tool_call": true,
1848                    "limit": {"context": 1000, "output": 0},
1849                    "provider": {"api": "https://example.com/v1"}
1850                }
1851            }),
1852        );
1853        let parsed: ModelsDevData = serde_json::from_value(data).expect("parse fixture");
1854
1855        let error = build_provider_models(&parsed).unwrap_err();
1856
1857        assert!(matches!(error, CodegenError::IncompleteTransport { ref model_id } if model_id == "incomplete"));
1858    }
1859
1860    #[test]
1861    fn format_context_window_formats_correctly() {
1862        assert_eq!(format_context_window(1_000_000), "1M");
1863        assert_eq!(format_context_window(200_000), "200k");
1864        assert_eq!(format_context_window(8_000), "8k");
1865        assert_eq!(format_context_window(0), "unknown");
1866    }
1867
1868    #[test]
1869    fn level_str_to_variant_covers_all_reasoning_efforts() {
1870        for effort in utils::ReasoningEffort::all() {
1871            let _ = level_str_to_variant(effort.as_str());
1872        }
1873    }
1874
1875    #[test]
1876    fn build_sorts_models_and_filters_aliases_and_non_tool_call() {
1877        let mut data = minimal_models_dev_json();
1878        anthropic_models(
1879            &mut data,
1880            json!({
1881                "b-model": {"id": "b-model", "name": "B Model", "tool_call": true, "limit": {"context": 2000, "output": 0}},
1882                "a-model": {"id": "a-model", "name": "A Model", "tool_call": true, "limit": {"context": 1000, "output": 0}},
1883                "alpha-latest": {"id": "alpha-latest", "name": "Alias", "tool_call": true, "limit": {"context": 500, "output": 0}},
1884                "no-tools": {"id": "no-tools", "name": "No Tools", "tool_call": false, "limit": {"context": 500, "output": 0}}
1885            }),
1886        );
1887
1888        let models = build_from_value(&data);
1889        let ids: Vec<&str> = models["anthropic"].iter().map(|m| m.model_id.as_str()).collect();
1890        assert_eq!(ids, vec!["a-model", "b-model"]);
1891    }
1892
1893    #[test]
1894    fn build_extra_source_ids_merges_unique_models_into_provider() {
1895        let mut data = minimal_models_dev_json();
1896        zai_extra_models(
1897            &mut data,
1898            json!({
1899                "extra-model": {"id": "extra-model", "name": "Extra Model", "tool_call": true, "limit": {"context": 4000, "output": 0}}
1900            }),
1901        );
1902
1903        let models = build_from_value(&data);
1904        assert!(models["zai"].iter().any(|m| m.model_id == "extra-model"));
1905    }
1906
1907    #[test]
1908    fn build_extra_source_ids_does_not_duplicate_existing_models() {
1909        let mut data = minimal_models_dev_json();
1910        let shared = json!({
1911            "shared-model": {"id": "shared-model", "name": "Shared Model", "tool_call": true, "limit": {"context": 1000, "output": 0}}
1912        });
1913        insert_models(&mut data, "zai", shared.clone());
1914        insert_models(&mut data, "zai-coding-plan", shared);
1915
1916        let models = build_from_value(&data);
1917        let count = models["zai"].iter().filter(|m| m.model_id == "shared-model").count();
1918        assert_eq!(count, 1);
1919    }
1920
1921    #[test]
1922    fn build_derives_reasoning_levels_from_source_metadata() {
1923        let mut data = minimal_models_dev_json();
1924        anthropic_models(
1925            &mut data,
1926            json!({
1927                "claude-test": {
1928                    "id": "claude-test", "name": "Claude Test", "tool_call": true, "reasoning": true,
1929                    "reasoning_options": [{"type": "effort", "values": ["low", "high", "max"]}],
1930                    "limit": {"context": 200_000, "output": 0}
1931                }
1932            }),
1933        );
1934
1935        let models = build_from_value(&data);
1936        let model = models["anthropic"].iter().find(|model| model.model_id == "claude-test").unwrap();
1937        assert_eq!(model.reasoning_levels, ["low", "high", "max"]);
1938    }
1939
1940    #[test]
1941    fn generate_rejects_unknown_reasoning_effort_metadata() {
1942        let mut data = minimal_models_dev_json();
1943        anthropic_models(
1944            &mut data,
1945            json!({
1946                "claude-test": {
1947                    "id": "claude-test", "name": "Claude Test", "tool_call": true, "reasoning": true,
1948                    "reasoning_options": [{"type": "effort", "values": ["ultra"]}],
1949                    "limit": {"context": 200_000, "output": 0}
1950                }
1951            }),
1952        );
1953        let tmp = NamedTempFile::new().unwrap();
1954        std::fs::write(tmp.path(), serde_json::to_string(&data).unwrap()).unwrap();
1955        assert!(matches!(generate(tmp.path()), Err(CodegenError::UnsupportedReasoningEffort { .. })));
1956    }
1957
1958    #[test]
1959    fn build_preserves_model_pricing_and_omits_codex_subscription_pricing() {
1960        let mut data = minimal_models_dev_json();
1961        anthropic_models(
1962            &mut data,
1963            json!({
1964                "priced": {
1965                    "id": "priced", "name": "Priced", "tool_call": true,
1966                    "limit": {"context": 200_000, "output": 0},
1967                    "cost": {"input": 3.0, "output": 15.0, "cache_read": 0.3, "cache_write": 3.75}
1968                }
1969            }),
1970        );
1971        insert_models(
1972            &mut data,
1973            "openai",
1974            json!({
1975                "gpt-5.5": {
1976                    "id": "gpt-5.5", "name": "GPT-5.5", "tool_call": true,
1977                    "limit": {"context": 1_050_000, "output": 128_000},
1978                    "cost": {"input": 1.25, "output": 10.0, "cache_read": 0.125}
1979                }
1980            }),
1981        );
1982
1983        let models = build_from_value(&data);
1984        let priced = models["anthropic"].iter().find(|model| model.model_id == "priced").unwrap();
1985        assert_eq!(priced.pricing.as_ref().map(|pricing| pricing.input), Some(3.0));
1986        assert_eq!(priced.pricing.as_ref().map(|pricing| pricing.output), Some(15.0));
1987        assert_eq!(priced.pricing.as_ref().and_then(|pricing| pricing.cache_read), Some(0.3));
1988        assert_eq!(priced.pricing.as_ref().and_then(|pricing| pricing.cache_write), Some(3.75));
1989
1990        let codex = models["codex"].iter().find(|model| model.model_id == "gpt-5.5").unwrap();
1991        assert_eq!(codex.pricing, None);
1992        assert!(codex.supports_prompt_caching);
1993    }
1994
1995    #[test]
1996    fn build_derives_prompt_caching_from_cost_fields() {
1997        let mut data = minimal_models_dev_json();
1998        insert_models(
1999            &mut data,
2000            "amazon-bedrock",
2001            json!({
2002                "cached": {
2003                    "id": "cached", "name": "Cached", "tool_call": true,
2004                    "limit": {"context": 200_000, "output": 0},
2005                    "cost": {"input": 3.0, "output": 15.0, "cache_read": 0.3, "cache_write": 3.75}
2006                },
2007                "uncached": {
2008                    "id": "uncached", "name": "Uncached", "tool_call": true,
2009                    "limit": {"context": 200_000, "output": 0},
2010                    "cost": {"input": 3.0, "output": 15.0}
2011                }
2012            }),
2013        );
2014
2015        let models = build_from_value(&data);
2016        let bedrock = &models["amazon-bedrock"];
2017        let cached = bedrock.iter().find(|m| m.model_id == "cached").unwrap();
2018        let uncached = bedrock.iter().find(|m| m.model_id == "uncached").unwrap();
2019        assert!(cached.supports_prompt_caching);
2020        assert!(!uncached.supports_prompt_caching);
2021    }
2022
2023    #[test]
2024    fn build_assigns_codex_model_specific_reasoning_levels() {
2025        let mut data = minimal_models_dev_json();
2026        insert_models(
2027            &mut data,
2028            "openai",
2029            json!({
2030                "gpt-5.6-sol": {
2031                    "id": "gpt-5.6-sol", "name": "GPT-5.6 Sol", "tool_call": true, "reasoning": true,
2032                    "reasoning_options": [{"type": "effort", "values": ["none", "low", "medium", "high", "xhigh", "max"]}],
2033                    "limit": {"context": 200_000, "output": 0}
2034                },
2035                "gpt-5.6-luna": {
2036                    "id": "gpt-5.6-luna", "name": "GPT-5.6 Luna", "tool_call": true, "reasoning": true,
2037                    "reasoning_options": [{"type": "effort", "values": ["none", "low", "medium", "high", "xhigh", "max"]}],
2038                    "limit": {"context": 200_000, "output": 0}
2039                },
2040                "gpt-5.4": {
2041                    "id": "gpt-5.4", "name": "GPT-5.4", "tool_call": true, "reasoning": true,
2042                    "limit": {"context": 200_000, "output": 0}
2043                }
2044            }),
2045        );
2046
2047        let models = build_from_value(&data);
2048        let levels = |id: &str| models["codex"].iter().find(|m| m.model_id == id).unwrap().reasoning_levels.clone();
2049        assert_eq!(levels("gpt-5.6-sol"), vec!["low", "medium", "high", "xhigh", "max"]);
2050        assert_eq!(levels("gpt-5.6-luna"), vec!["low", "medium", "high", "xhigh", "max"]);
2051        assert_eq!(levels("gpt-5.4"), vec!["low", "medium", "high", "xhigh"]);
2052    }
2053
2054    #[test]
2055    fn build_applies_codex_subscription_context_window_override() {
2056        let mut data = minimal_models_dev_json();
2057        insert_models(
2058            &mut data,
2059            "openai",
2060            json!({
2061                "gpt-5.5": {
2062                    "id": "gpt-5.5", "name": "GPT-5.5", "tool_call": true, "reasoning": true,
2063                    "limit": {"context": 1_050_000, "output": 128_000}
2064                }
2065            }),
2066        );
2067
2068        let models = build_from_value(&data);
2069        let codex = models["codex"].iter().find(|m| m.model_id == "gpt-5.5").unwrap();
2070        let openai = models["openai"].iter().find(|m| m.model_id == "gpt-5.5").unwrap();
2071        assert_eq!(codex.context_window, 272_000);
2072        assert_eq!(openai.context_window, 1_050_000);
2073    }
2074
2075    #[test]
2076    fn generate_uses_codex_subscription_model_ids() {
2077        let mut data = minimal_models_dev_json();
2078        insert_models(
2079            &mut data,
2080            "openai",
2081            json!({
2082                "gpt-6.1-sol": {
2083                    "id": "gpt-6.1-sol", "name": "GPT-6.1 Sol", "tool_call": true, "reasoning": true,
2084                    "reasoning_options": [{"type": "effort", "values": ["low", "medium", "high", "xhigh", "max"]}],
2085                    "limit": {"context": 1_050_000, "output": 128_000}
2086                },
2087                "gpt-5.1-codex": {
2088                    "id": "gpt-5.1-codex", "name": "GPT-5.1 Codex", "tool_call": true, "reasoning": true,
2089                    "limit": {"context": 400_000, "output": 128_000}
2090                },
2091                "gpt-5.6": {
2092                    "id": "gpt-5.6", "name": "GPT-5.6 Sol", "tool_call": true, "reasoning": true,
2093                    "limit": {"context": 1_050_000, "output": 128_000}
2094                },
2095                "gpt-5.6-sol": {
2096                    "id": "gpt-5.6-sol", "name": "GPT-5.6 Sol", "tool_call": true, "reasoning": true,
2097                    "limit": {"context": 1_050_000, "output": 128_000}
2098                },
2099                "gpt-5.6-terra": {
2100                    "id": "gpt-5.6-terra", "name": "GPT-5.6 Terra", "tool_call": true, "reasoning": true,
2101                    "limit": {"context": 1_050_000, "output": 128_000}
2102                },
2103                "gpt-5.6-luna": {
2104                    "id": "gpt-5.6-luna", "name": "GPT-5.6 Luna", "tool_call": true, "reasoning": true,
2105                    "limit": {"context": 1_050_000, "output": 128_000}
2106                }
2107            }),
2108        );
2109
2110        let tmp = NamedTempFile::new().unwrap();
2111        std::fs::write(tmp.path(), serde_json::to_string(&data).unwrap()).unwrap();
2112        let output = generate(tmp.path()).unwrap();
2113
2114        let codex_doc = &output.provider_docs["codex"];
2115        assert!(!codex_doc.contains("`gpt-5.6`"));
2116        assert!(!codex_doc.contains("`gpt-5.1-codex`"));
2117        assert!(codex_doc.contains("| `gpt-6.1-sol` | `GPT-6.1 Sol` | `272k` |"));
2118        assert!(codex_doc.contains("| `gpt-5.6-sol` | `GPT-5.6 Sol` | `272k` |"));
2119        assert!(codex_doc.contains("| `gpt-5.6-terra` | `GPT-5.6 Terra` | `272k` |"));
2120        assert!(codex_doc.contains("| `gpt-5.6-luna` | `GPT-5.6 Luna` | `272k` |"));
2121
2122        let openai_doc = &output.provider_docs["openai"];
2123        assert!(openai_doc.contains("`gpt-5.6`"));
2124        assert!(openai_doc.contains("`gpt-5.1-codex`"));
2125        assert!(openai_doc.contains("`gpt-5.6-sol`"));
2126    }
2127
2128    #[test]
2129    fn generate_emits_provider_docs() {
2130        let mut data = minimal_models_dev_json();
2131        anthropic_models(
2132            &mut data,
2133            json!({
2134                "claude-test": {
2135                    "id": "claude-test", "name": "Claude Test", "tool_call": true, "reasoning": true,
2136                    "limit": {"context": 200_000, "output": 0},
2137                    "modalities": {"input": ["text", "image"]}
2138                }
2139            }),
2140        );
2141
2142        let tmp = NamedTempFile::new().unwrap();
2143        std::fs::write(tmp.path(), serde_json::to_string(&data).unwrap()).unwrap();
2144        let output = generate(tmp.path()).unwrap();
2145
2146        let anthropic_doc = &output.provider_docs["anthropic"];
2147        assert!(anthropic_doc.contains("`Anthropic` LLM provider."));
2148        assert!(anthropic_doc.contains("`ANTHROPIC_API_KEY`"));
2149        assert!(anthropic_doc.contains("| `claude-test` | `Claude Test` | `200k` | yes | yes |  |"));
2150
2151        let ollama_doc = &output.provider_docs["ollama"];
2152        assert!(ollama_doc.contains("`Ollama` LLM provider."));
2153        assert!(ollama_doc.contains("any model name at runtime"));
2154    }
2155
2156    #[test]
2157    fn generate_routes_only_existing_us_gpt_6_profiles_to_runtime() {
2158        let mut data = minimal_models_dev_json();
2159        let mut models = serde_json::Map::new();
2160        for version in ["6-luna", "6-sol", "6-astra", "6.1-sol"] {
2161            for prefix in ["us", "global"] {
2162                let id = format!("{prefix}.openai.gpt-{version}");
2163                models.insert(
2164                    id.clone(),
2165                    json!({
2166                        "id": id, "name": format!("GPT-{version} ({prefix})"), "tool_call": true,
2167                        "limit": {"context": 1_050_000, "output": 128_000}
2168                    }),
2169                );
2170            }
2171        }
2172        models.insert(
2173            "openai.gpt-6-astra".to_string(),
2174            json!({
2175                "id": "openai.gpt-6-astra", "name": "GPT-6 Astra", "tool_call": true,
2176                "provider": {"api": "https://bedrock-mantle.${AWS_REGION}.api.aws/openai/v1", "shape": "responses"}
2177            }),
2178        );
2179        insert_models(&mut data, "amazon-bedrock", serde_json::Value::Object(models));
2180        let tmp = NamedTempFile::new().unwrap();
2181        std::fs::write(tmp.path(), serde_json::to_string(&data).unwrap()).unwrap();
2182        let docs = generate(tmp.path()).unwrap().provider_docs.remove("amazon-bedrock").unwrap();
2183
2184        for version in ["6-luna", "6-sol", "6-astra", "6.1-sol"] {
2185            let id = format!("openai.gpt-{version}");
2186            assert!(docs.contains(&format!(
2187                "| `us.{id}` | `https://bedrock-runtime.${{AWS_REGION}}.amazonaws.com/openai/v1` | `responses` |"
2188            )));
2189            assert!(!docs.contains(&format!("| `global.{id}` | `https://bedrock-runtime.")));
2190        }
2191        assert!(docs.contains(
2192            "| `openai.gpt-6-astra` | `https://bedrock-mantle.${AWS_REGION}.api.aws/openai/v1` | `responses` |"
2193        ));
2194        assert!(!docs.contains("| `openai.gpt-6-luna` |"));
2195        assert!(!docs.contains("| `openai.gpt-6-sol` |"));
2196    }
2197
2198    #[test]
2199    fn generate_preserves_disabled_separately_from_default() {
2200        let mut data = minimal_models_dev_json();
2201        data["openai"]["models"]["gpt-5.4"]["reasoning_options"] = json!([
2202            {"type": "effort", "values": [null, "default", "none", "low", "high"]}
2203        ]);
2204        anthropic_models(
2205            &mut data,
2206            json!({
2207                "claude-toggle": {
2208                    "id": "claude-toggle", "name": "Toggle", "tool_call": true, "reasoning": true,
2209                    "reasoning_options": [{"type": "toggle"}, {"type": "effort", "values": ["low", "high"]}]
2210                }
2211            }),
2212        );
2213        let tmp = NamedTempFile::new().unwrap();
2214        std::fs::write(tmp.path(), serde_json::to_string(&data).unwrap()).unwrap();
2215        let output = generate(tmp.path()).unwrap();
2216        assert!(output.rust_source.contains("ReasoningEffort::Disabled"));
2217        assert_default_is_not_capability(&output.rust_source);
2218        assert!(output.provider_docs["openai"].contains("disabled"));
2219        assert!(output.provider_docs["anthropic"].contains("disabled"));
2220        assert!(!output.provider_docs["codex"].contains("disabled"));
2221    }
2222
2223    #[test]
2224    fn generate_reasoning_capability_edge_cases() {
2225        let mut data = minimal_models_dev_json();
2226        for (id, reasoning, options, disabled) in [
2227            ("toggle", true, json!([{"type": "toggle"}]), true),
2228            (
2229                "both",
2230                true,
2231                json!([{"type": "toggle"}, {"type": "effort", "values": ["none", "high", "none", "low", "low"]}]),
2232                true,
2233            ),
2234            ("defaults", true, json!([{"type": "effort", "values": [null, "default"]}]), false),
2235            ("budget", true, json!([{"type": "budget_tokens"}]), false),
2236            ("missing", true, json!([]), false),
2237            ("plain", false, json!([{"type": "toggle"}]), false),
2238        ] {
2239            data["anthropic"]["models"] = json!({id: {"id": id, "name": id, "reasoning": reasoning, "tool_call": true, "reasoning_options": options}});
2240            let tmp = NamedTempFile::new().unwrap();
2241            std::fs::write(tmp.path(), serde_json::to_string(&data).unwrap()).unwrap();
2242            let output = generate(tmp.path()).unwrap();
2243            assert_eq!(output.provider_docs["anthropic"].contains("advertises `disabled`"), disabled, "{id}");
2244            assert_default_is_not_capability(&output.rust_source);
2245            if id == "both" {
2246                assert!(output.rust_source.contains("ReasoningDisabledSupport::Effort"));
2247                assert!(!output.rust_source.contains("ReasoningEffort::Disabled, ReasoningEffort::Disabled"));
2248            }
2249        }
2250    }
2251
2252    fn assert_default_is_not_capability(source: &str) {
2253        let file = syn::parse_file(source).unwrap();
2254        for item in file.items {
2255            if let syn::Item::Impl(implementation) = item {
2256                for item in implementation.items {
2257                    if let syn::ImplItem::Fn(method) = item
2258                        && method.sig.ident == "reasoning_levels"
2259                    {
2260                        let body = method.block;
2261                        assert!(!quote! { #body }.to_string().contains("ReasoningEffort :: Default"));
2262                    }
2263                }
2264            }
2265        }
2266    }
2267
2268    fn build_from_value(data: &Value) -> ProviderModels {
2269        let parsed: ModelsDevData = serde_json::from_value(data.clone()).expect("parse fixture");
2270        build_provider_models(&parsed).expect("build provider models")
2271    }
2272
2273    fn anthropic_models(data: &mut Value, models: Value) {
2274        insert_models(data, "anthropic", models);
2275    }
2276
2277    fn zai_extra_models(data: &mut Value, models: Value) {
2278        insert_models(data, "zai-coding-plan", models);
2279    }
2280
2281    fn insert_models(data: &mut Value, provider_key: &str, models: Value) {
2282        let provider = data.as_object_mut().unwrap().get_mut(provider_key).unwrap().as_object_mut().unwrap();
2283        let target = provider.get_mut("models").unwrap().as_object_mut().unwrap();
2284        let Value::Object(models) = models else {
2285            panic!("models fixture must be an object");
2286        };
2287        target.extend(models);
2288    }
2289
2290    fn minimal_models_dev_json() -> Value {
2291        let mut root = serde_json::Map::new();
2292        for cfg in PROVIDERS {
2293            let json_key = cfg.json_key();
2294            root.entry(json_key.to_string())
2295                .or_insert_with(|| json!({"id": json_key, "name": json_key, "env": [], "models": {}}));
2296            for &extra in cfg.extra_source_ids {
2297                root.entry(extra.to_string())
2298                    .or_insert_with(|| json!({"id": extra, "name": extra, "env": [], "models": {}}));
2299            }
2300        }
2301        let openai = root.get_mut("openai").unwrap()["models"].as_object_mut().unwrap();
2302        for model in CODEX_SUBSCRIPTION_MODELS {
2303            openai.insert(
2304                model.id.to_string(),
2305                json!({
2306                    "id": model.id,
2307                    "name": model.id,
2308                    "tool_call": true,
2309                    "reasoning": true,
2310                    "reasoning_options": [{"type": "effort", "values": ["low", "medium", "high", "xhigh"]}],
2311                    "limit": {"context": 1_050_000, "output": 0}
2312                }),
2313            );
2314        }
2315        Value::Object(root)
2316    }
2317}