Skip to main content

cpa_core/registry/
dynamic.rs

1//! Dynamic model registry: which credential serves which public model ID, derived from
2//! the credential set and config (sdk/cliproxy/service_models.go,
3//! internal/registry/model_registry.go). The server builds it on demand and publishes
4//! it through [`super::install_overlay`].
5//!
6//! The static catalog is `cpa_core::registry::pinned()`. Each enabled credential
7//! registers its provider's channel (or its configured `models`), minus exclusions, plus
8//! OAuth aliases and forks, plus `prefix/` copies. Selection admits a credential only
9//! when it registered the route model (M4-0028), and route-time provider lookup uses
10//! the registered providers, so a model nobody serves is Go's 400 `unknown provider`.
11//!
12//! Execution-model resolution (aliases back to upstream names, force mapping) lives
13//! here too, so listing and routing read one definition.
14
15use std::collections::HashMap;
16use std::sync::Arc;
17
18use serde::Deserialize;
19use serde_json::{Map, Value};
20
21use super::{ModelInfo, ThinkingSupport, pinned};
22use crate::config::Config;
23use crate::credential::{Credential, Source};
24use crate::gostr::GoStr;
25
26/// Go `responsesWebSearchProviderPathSupport`.
27fn provider_web_search_path(provider: &str) -> Option<bool> {
28    match provider.trim().go_lower().as_str() {
29        "codex" | "xai" | "claude" | "antigravity" => Some(true),
30        "openai"
31        | "openai-compatibility"
32        | "gemini"
33        | "aistudio"
34        | "vertex"
35        | "kimi"
36        | "kimi-ai"
37        | "kimi.ai"
38        | "kimi.com"
39        | "interactions"
40        | "gemini-interactions" => Some(false),
41        p if p.starts_with("openai-compatible-") => Some(false),
42        _ => None,
43    }
44}
45
46/// Go `canonicalModelKey`: the model without its terminal `(thinking)` suffix.
47pub fn canonical_model(model: &str) -> &str {
48    let model = model.trim();
49    if model.ends_with(')') {
50        model
51            .rsplit_once('(')
52            .map(|(base, _)| base.trim())
53            .filter(|base| !base.is_empty())
54            .unwrap_or(model)
55    } else {
56        model
57    }
58}
59
60/// One model definition (Go `registry.ModelInfo`), typed for rendering.
61#[derive(Debug, Clone, Default, PartialEq, Deserialize)]
62#[serde(default)]
63pub struct Spec {
64    pub id: String,
65    #[serde(skip)]
66    pub metadata_model_id: String,
67    pub object: String,
68    pub created: i64,
69    pub owned_by: String,
70    #[serde(rename = "type")]
71    pub kind: String,
72    pub display_name: String,
73    pub name: String,
74    pub version: String,
75    pub description: String,
76    #[serde(rename = "inputTokenLimit")]
77    pub input_token_limit: i64,
78    #[serde(rename = "outputTokenLimit")]
79    pub output_token_limit: i64,
80    #[serde(rename = "supportedGenerationMethods")]
81    pub supported_generation_methods: Vec<String>,
82    pub context_length: i64,
83    #[serde(skip)]
84    pub max_context_length: i64,
85    pub max_completion_tokens: i64,
86    pub supported_parameters: Vec<String>,
87    #[serde(rename = "supportedInputModalities")]
88    pub supported_input_modalities: Vec<String>,
89    #[serde(rename = "supportedOutputModalities")]
90    pub supported_output_modalities: Vec<String>,
91    pub thinking: Option<ThinkingSupport>,
92    pub support_configuration_update: bool,
93    /// Go `SupportsWebSearch` (Antigravity models whose upstream lists web search).
94    pub supports_web_search: bool,
95    #[serde(skip)]
96    pub is_compat: bool,
97    #[serde(skip)]
98    pub user_defined: bool,
99    /// Go `ExplicitThinking`: a config model that set `thinking` (the Codex client
100    /// catalog lets it narrow the advertised reasoning levels).
101    #[serde(skip)]
102    pub explicit_thinking: bool,
103    /// Go `ExplicitInputModalities`: an OpenAI-compatible model that set
104    /// `input-modalities`.
105    #[serde(skip)]
106    pub explicit_input_modalities: bool,
107    /// Go `NativeCapabilities.WebSearch` from the static catalog (`native_capabilities`),
108    /// `None` when unknown.
109    #[serde(skip)]
110    pub native_web_search: Option<bool>,
111}
112
113impl Spec {
114    fn from_static(info: &ModelInfo) -> Self {
115        let raw = super::go_integers(&info.raw);
116        let mut spec = serde_json::from_value(Value::Object(raw)).unwrap_or_else(|_| Self {
117            id: info.id.clone(),
118            kind: info.kind.clone(),
119            ..Self::default()
120        });
121        spec.native_web_search = native_web_search(info);
122        spec
123    }
124
125    /// The shared-contract view, for translators and executors.
126    pub fn to_info(&self) -> ModelInfo {
127        let mut raw = Map::new();
128        raw.insert("id".into(), self.id.clone().into());
129        raw.insert("object".into(), "model".into());
130        raw.insert("created".into(), self.created.into());
131        raw.insert("owned_by".into(), self.owned_by.clone().into());
132        raw.insert("type".into(), self.kind.clone().into());
133        let mut put = |k: &str, v: Value| {
134            let empty = match &v {
135                Value::String(s) => s.is_empty(),
136                Value::Number(n) => n.as_i64() == Some(0),
137                Value::Array(a) => a.is_empty(),
138                Value::Bool(b) => !b,
139                _ => false,
140            };
141            if !empty {
142                raw.insert(k.into(), v);
143            }
144        };
145        put("display_name", self.display_name.clone().into());
146        put("name", self.name.clone().into());
147        put("version", self.version.clone().into());
148        put("description", self.description.clone().into());
149        put("inputTokenLimit", self.input_token_limit.into());
150        put("outputTokenLimit", self.output_token_limit.into());
151        put(
152            "supportedGenerationMethods",
153            self.supported_generation_methods.clone().into(),
154        );
155        put("context_length", self.context_length.into());
156        put("max_context_length", self.max_context_length.into());
157        put("max_completion_tokens", self.max_completion_tokens.into());
158        put("supported_parameters", self.supported_parameters.clone().into());
159        put(
160            "supportedInputModalities",
161            self.supported_input_modalities.clone().into(),
162        );
163        put(
164            "supportedOutputModalities",
165            self.supported_output_modalities.clone().into(),
166        );
167        put("support_configuration_update", self.support_configuration_update.into());
168        put("supports_web_search", self.supports_web_search.into());
169        put("is_compat", self.is_compat.into());
170        // Config `models[]` entries: thinking passes through unvalidated (thinking.IsUserDefinedModel).
171        put("user_defined", self.user_defined.into());
172        if let Some(t) = &self.thinking {
173            raw.insert("thinking".into(), thinking_value(t));
174        }
175        ModelInfo::from_raw(raw).expect("spec renders a valid model")
176    }
177}
178
179/// Go's JSON for a `ThinkingSupport` (`omitempty` on every field).
180pub fn thinking_value(t: &ThinkingSupport) -> Value {
181    let mut m = Map::new();
182    for (k, v) in [("min", t.min), ("max", t.max)] {
183        if v != 0 {
184            m.insert(k.into(), v.into());
185        }
186    }
187    if t.zero_allowed {
188        m.insert("zero_allowed".into(), true.into());
189    }
190    if t.dynamic_allowed {
191        m.insert("dynamic_allowed".into(), true.into());
192    }
193    if !t.disable_type.is_empty() {
194        m.insert("disable_type".into(), t.disable_type.clone().into());
195    }
196    if !t.levels.is_empty() {
197        m.insert("levels".into(), t.levels.clone().into());
198    }
199    Value::Object(m)
200}
201
202/// Go `IsCodexUseSIWC`, for any provider: a `use_siwc` attribute that
203/// `strconv.ParseBool` reads as true, else the metadata flag (`parseBoolAny`: a bool, a
204/// string `ParseBool` accepts, or a non-zero number).
205pub fn uses_siwc(c: &Credential) -> bool {
206    fn parse_bool(s: &str) -> Option<bool> {
207        match s {
208            "1" | "t" | "T" | "TRUE" | "true" | "True" => Some(true),
209            "0" | "f" | "F" | "FALSE" | "false" | "False" => Some(false),
210            _ => None,
211        }
212    }
213    if c.attributes.get("use_siwc").and_then(|v| parse_bool(v.trim())) == Some(true) {
214        return true;
215    }
216    match c.metadata.get("use_siwc") {
217        Some(Value::Bool(b)) => *b,
218        Some(Value::String(s)) => parse_bool(s.trim()).unwrap_or(false),
219        Some(Value::Number(n)) => n.as_f64().is_some_and(|f| f != 0.0),
220        _ => false,
221    }
222}
223
224/// Go `Auth.AuthKind()` (sdk/cliproxy/auth/classification.go): a true `use_siwc`
225/// (`oauth`, 7b0319fb), a recognised `auth_kind` attribute, then a recognised
226/// `auth_kind` metadata string, then a non-empty `api_key` attribute (`apikey`), then
227/// OAuth token metadata (`oauth`). Unrecognised kinds fall through to the next source.
228pub fn auth_kind(c: &Credential) -> Option<&'static str> {
229    if uses_siwc(c) {
230        return Some("oauth");
231    }
232    let normalize = |s: &str| match s.trim().go_lower().as_str() {
233        "apikey" | "api_key" | "api-key" => Some("apikey"),
234        "oauth" | "oauth2" => Some("oauth"),
235        _ => None,
236    };
237    if let Some(kind) = c.attributes.get("auth_kind").and_then(|s| normalize(s)) {
238        return Some(kind);
239    }
240    if let Some(kind) = c.str("auth_kind").and_then(normalize) {
241        return Some(kind);
242    }
243    if c.attributes.get("api_key").is_some_and(|k| !k.trim().is_empty()) {
244        return Some("apikey");
245    }
246    let oauth = [
247        "access_token",
248        "refresh_token",
249        "id_token",
250        "email",
251        "token_type",
252        "expires_at",
253        "expired",
254    ]
255    .iter()
256    .any(|k| c.str(k).is_some_and(|v| !v.trim().is_empty()))
257        // A token object, a Sign in with ChatGPT section (7b0319fb) or a Vertex service
258        // account (d9451cb6).
259        || ["token", "siwc", "service_account"].iter().any(|k| {
260            c.metadata
261                .get(*k)
262                .and_then(Value::as_object)
263                .is_some_and(|t| !t.is_empty())
264        });
265    oauth.then_some("oauth")
266}
267
268/// Go `Auth.AccountInfo()`: the account kind and value request logs print. OAuth
269/// reports the trimmed metadata `email`, else (d9451cb6) the service account's
270/// `client_email`; an API key the trimmed `api_key` attribute; an unclassified
271/// credential reports nothing.
272pub fn account_info(c: &Credential) -> (&'static str, String) {
273    fn trimmed(v: Option<&Value>) -> Option<&str> {
274        v.and_then(Value::as_str).map(str::trim).filter(|v| !v.is_empty())
275    }
276    match auth_kind(c) {
277        Some("oauth") => (
278            "oauth",
279            trimmed(c.metadata.get("email"))
280                .or_else(|| trimmed(c.metadata.get("service_account").and_then(|sa| sa.get("client_email"))))
281                .unwrap_or_default()
282                .to_owned(),
283        ),
284        Some("apikey") => (
285            "api_key",
286            c.attributes
287                .get("api_key")
288                .map(|k| k.trim().to_owned())
289                .unwrap_or_default(),
290        ),
291        _ => ("", String::new()),
292    }
293}
294
295/// `auth.AuthKind() == AuthKindAPIKey`.
296pub fn is_api_key(c: &Credential) -> bool {
297    auth_kind(c) == Some("apikey")
298}
299
300/// Go `openAICompatInfoFromAuth`: a `compat_name` or the `openai-compatibility`
301/// provider. A `provider_key` alone does not count; Vertex API keys carry one.
302fn openai_compat(c: &Credential) -> bool {
303    c.attributes.get("compat_name").is_some_and(|v| !v.trim().is_empty())
304        || c.provider.trim().go_eq_fold("openai-compatibility")
305}
306
307/// The provider key a credential registers and is scheduled under. For an
308/// OpenAI-compatible credential, Go `registerModelsForAuth` takes a `provider_key`
309/// lowercased as written, and otherwise the `openAICompatInfoFromAuth` key: the
310/// `compat_name`, or else the label, through `util.OpenAICompatibleProviderKey`. A
311/// `provider_key` of `openai-compatibility` gives way to the bare, lowercased `compat_name`.
312pub fn provider_key(c: &Credential) -> String {
313    if !openai_compat(c) {
314        return c.provider.trim().go_lower();
315    }
316    let attr = |key: &str| c.attributes.get(key).map(|s| s.trim()).filter(|s| !s.is_empty());
317    match (attr("provider_key").map(|k| k.go_lower()), attr("compat_name")) {
318        (Some(key), Some(name)) if key == "openai-compatibility" => name.go_lower(),
319        (Some(key), _) => key,
320        (None, name) => crate::config::credentials::openai_compat_provider(name.unwrap_or(c.label.trim())),
321    }
322}
323
324/// The authoritative `prefix` (attributes first, then file metadata).
325pub fn credential_prefix(c: &Credential) -> &str {
326    c.attributes
327        .get("prefix")
328        .map(String::as_str)
329        .or_else(|| c.str("prefix"))
330        .unwrap_or("")
331        .trim()
332}
333
334/// One configured model entry (`models[]` of an API-key or OpenAI-compatible entry).
335#[derive(Debug, Clone, Default, Deserialize)]
336#[serde(default, rename_all = "kebab-case")]
337pub struct ConfigModel {
338    pub name: String,
339    pub alias: String,
340    pub display_name: String,
341    pub max_context_length: i64,
342    pub force_mapping: bool,
343    pub is_compat: bool,
344    pub support_configuration_update: bool,
345    pub image: bool,
346    pub thinking: Option<ThinkingSupport>,
347    pub input_modalities: Vec<String>,
348    pub output_modalities: Vec<String>,
349}
350
351/// Configured models carried on a config-backed credential: full entries under
352/// metadata `models` when synthesis provides them, otherwise `model_aliases` pairs.
353pub fn config_models(c: &Credential) -> Vec<ConfigModel> {
354    if !matches!(c.source, Source::Config { .. }) {
355        return Vec::new();
356    }
357    let raw = c.metadata.get("models").or_else(|| c.metadata.get("model_aliases"));
358    let Some(Value::Array(items)) = raw else {
359        return Vec::new();
360    };
361    items
362        .iter()
363        .filter_map(|v| {
364            let mut v = v.clone();
365            // Accept snake_case spellings from JSON metadata too.
366            if let Value::Object(m) = &mut v {
367                for key in [
368                    "display_name",
369                    "max_context_length",
370                    "force_mapping",
371                    "is_compat",
372                    "support_configuration_update",
373                    "input_modalities",
374                    "output_modalities",
375                ] {
376                    if let Some(x) = m.remove(key) {
377                        m.entry(key.replace('_', "-")).or_insert(x);
378                    }
379                }
380            }
381            serde_json::from_value(v).ok()
382        })
383        .collect()
384}
385
386/// One OAuth alias (`oauth.model-alias.<channel>[]` or attributes `model_aliases`).
387#[derive(Debug, Clone, Default, Deserialize)]
388#[serde(default, rename_all = "kebab-case")]
389pub struct OAuthAlias {
390    pub name: String,
391    pub alias: String,
392    pub fork: bool,
393    pub display_name: String,
394    pub force_mapping: bool,
395}
396
397/// Go `SanitizeOAuthModelAlias` for one channel.
398fn sanitize_aliases(entries: Vec<OAuthAlias>) -> Vec<OAuthAlias> {
399    let mut seen = std::collections::HashSet::new();
400    entries
401        .into_iter()
402        .filter_map(|mut e| {
403            e.name = e.name.trim().to_owned();
404            e.alias = e.alias.trim().to_owned();
405            e.display_name = e.display_name.trim().to_owned();
406            (!e.name.is_empty()
407                && !e.alias.is_empty()
408                && !e.name.go_eq_fold(&e.alias)
409                && seen.insert(e.alias.go_lower()))
410            .then_some(e)
411        })
412        .collect()
413}
414
415/// `oauth.model-alias`, sanitized, by lowercase channel.
416pub fn global_aliases(cfg: &Config) -> HashMap<String, Vec<OAuthAlias>> {
417    let mut out = HashMap::new();
418    let Some(map) = cfg
419        .document
420        .get("oauth")
421        .and_then(|o| o.get("model-alias"))
422        .and_then(serde_yaml_ng::Value::as_mapping)
423    else {
424        return out;
425    };
426    for (channel, list) in map {
427        let channel = channel.as_str().unwrap_or_default().trim().go_lower();
428        let entries: Vec<OAuthAlias> = serde_yaml_ng::from_value(list.clone()).unwrap_or_default();
429        let clean = sanitize_aliases(entries);
430        if !channel.is_empty() && !clean.is_empty() {
431            out.insert(channel, clean);
432        }
433    }
434    out
435}
436
437fn attribute_aliases(c: &Credential) -> Vec<OAuthAlias> {
438    c.attributes
439        .get("model_aliases")
440        .and_then(|raw| serde_json::from_str::<Vec<Value>>(raw).ok())
441        .map(|items| {
442            sanitize_aliases(
443                items
444                    .into_iter()
445                    .filter_map(|v| {
446                        let mut v = v;
447                        if let Value::Object(m) = &mut v {
448                            for key in ["display_name", "force_mapping"] {
449                                if let Some(x) = m.remove(key) {
450                                    m.entry(key.replace('_', "-")).or_insert(x);
451                                }
452                            }
453                        }
454                        serde_json::from_value(v).ok()
455                    })
456                    .collect(),
457            )
458        })
459        .unwrap_or_default()
460}
461
462/// `OAuthModelAliasChannel`: API keys and Gemini keys have none.
463fn alias_channel(c: &Credential) -> Option<String> {
464    if is_api_key(c) {
465        return None;
466    }
467    match c.provider.trim().go_lower().as_str() {
468        "gemini" | "" => None,
469        other => Some(other.to_owned()),
470    }
471}
472
473fn oauth_aliases_for(cfg_aliases: &HashMap<String, Vec<OAuthAlias>>, c: &Credential) -> Vec<OAuthAlias> {
474    let Some(channel) = alias_channel(c) else {
475        return Vec::new();
476    };
477    let mut out = attribute_aliases(c);
478    let mut seen: std::collections::HashSet<String> = out.iter().map(|a| a.alias.go_lower()).collect();
479    for entry in cfg_aliases.get(&channel).into_iter().flatten() {
480        if seen.insert(entry.alias.go_lower()) {
481            out.push(entry.clone());
482        }
483    }
484    out
485}
486
487/// Go `matchWildcard` (lowercased inputs).
488pub fn wildcard(pattern: &str, value: &str) -> bool {
489    if pattern.is_empty() {
490        return false;
491    }
492    if !pattern.contains('*') {
493        return pattern == value;
494    }
495    let parts: Vec<&str> = pattern.split('*').collect();
496    let mut value = value;
497    let first = parts[0];
498    if !first.is_empty() {
499        let Some(rest) = value.strip_prefix(first) else {
500            return false;
501        };
502        value = rest;
503    }
504    let last = parts[parts.len() - 1];
505    if !last.is_empty() {
506        let Some(rest) = value.strip_suffix(last) else {
507            return false;
508        };
509        value = rest;
510    }
511    for segment in &parts[1..parts.len() - 1] {
512        if segment.is_empty() {
513            continue;
514        }
515        match value.find(segment) {
516            Some(i) => value = &value[i + segment.len()..],
517            None => return false,
518        }
519    }
520    true
521}
522
523fn excluded_for(cfg: &Config, c: &Credential) -> Vec<String> {
524    if let Some(list) = c.attributes.get("excluded_models").filter(|v| !v.trim().is_empty()) {
525        return list.split(',').map(str::to_owned).collect();
526    }
527    if is_api_key(c) {
528        return Vec::new();
529    }
530    crate::config::credentials::oauth_excluded(cfg)
531        .remove(&c.provider.trim().go_lower())
532        .unwrap_or_default()
533}
534
535/// Go `applyExcludedModels`: patterns and model IDs both go through `strings.ToLower`.
536fn apply_excluded(models: Vec<Spec>, excluded: &[String]) -> Vec<Spec> {
537    let patterns: Vec<String> = excluded
538        .iter()
539        .map(|p| p.trim().go_lower())
540        .filter(|p| !p.is_empty())
541        .collect();
542    if patterns.is_empty() {
543        return models;
544    }
545    models
546        .into_iter()
547        .filter(|m| {
548            let id = m.id.trim().go_lower();
549            !patterns.iter().any(|p| wildcard(p, &id))
550        })
551        .collect()
552}
553
554/// `native_capabilities.web_search` of a static catalog model.
555/// Go `GetStaticModelDefinitionsByChannel`: the static section a channel name selects,
556/// through Go's getters (built-ins included); unknown names select nothing.
557fn static_channel(name: &str) -> Vec<Spec> {
558    match name.trim().go_lower().as_str() {
559        "claude" => channel("claude"),
560        "gemini" | "gemini-interactions" => channel("gemini"),
561        "vertex" => channel("vertex"),
562        "aistudio" => channel("aistudio"),
563        "codex" => codex_channel("codex-pro"),
564        "kimi" | "kimi-ai" | "kimi.ai" | "kimi.com" => channel("kimi"),
565        "antigravity" => channel("antigravity"),
566        "xai" | "x-ai" | "grok" => with_xai_builtins(channel("xai")),
567        "devin" => super::devin::models().iter().map(Spec::from_static).collect(),
568        "meta" | "muse" => channel("meta"),
569        _ => Vec::new(),
570    }
571}
572
573/// Go `LookupStaticModelInfoByChannel` over `models`, the section of `channel`: the
574/// exact (trimmed) ID, or for `claude` its family entry.
575fn lookup_by_channel<'a>(models: &'a [Spec], channel: &str, id: &str) -> Option<&'a Spec> {
576    let id = id.trim();
577    if id.is_empty() {
578        return None;
579    }
580    models.iter().find(|m| m.id == id).or_else(|| {
581        if !channel.trim().eq_ignore_ascii_case("claude") {
582            return None;
583        }
584        super::claude_family_ids(id)
585            .into_iter()
586            .find_map(|family| models.iter().find(|m| m.id == family))
587    })
588}
589
590fn native_web_search(info: &ModelInfo) -> Option<bool> {
591    info.raw
592        .get("native_capabilities")
593        .and_then(|c| c.get("web_search"))
594        .and_then(Value::as_bool)
595}
596
597/// Go `normalizeCompatConfigModalities`: lowercase, trimmed, unique, in order.
598fn normalize_modalities(raw: &[String]) -> Vec<String> {
599    let mut seen = std::collections::HashSet::new();
600    raw.iter()
601        .map(|m| m.trim().go_lower())
602        .filter(|m| !m.is_empty() && seen.insert(m.clone()))
603        .collect()
604}
605
606fn channel(name: &str) -> Vec<Spec> {
607    pinned().channel(name).iter().map(Spec::from_static).collect()
608}
609
610/// The Images API models every Codex catalog carries (`codexBuiltinImage*ModelInfo`).
611const CODEX_BUILTIN_IMAGES: [(&str, &str); 5] = [
612    ("gpt-image-1.5", "GPT Image 1.5"),
613    ("gpt-image-2", "GPT Image 2"),
614    ("gpt-image-2.5-flare", "GPT Image 2.5 Flare"),
615    ("gpt-image-2.5-sunburst", "GPT Image 2.5 Sunburst"),
616    ("gpt-image-2.5", "GPT Image 2.5"),
617];
618
619/// Go `GetCodex*Models`: a plan catalog `WithCodexBuiltins`.
620fn codex_channel(name: &str) -> Vec<Spec> {
621    upsert(channel(name), codex_builtins(), |m| &m.id)
622}
623
624/// Go `WithCodexBuiltins`' models.
625fn codex_builtins() -> Vec<Spec> {
626    CODEX_BUILTIN_IMAGES
627        .map(|(id, display_name)| Spec {
628            id: id.into(),
629            object: "model".into(),
630            // 2024-01-01.
631            created: 1_704_067_200,
632            owned_by: "openai".into(),
633            kind: "openai".into(),
634            display_name: display_name.into(),
635            version: id.into(),
636            ..Spec::default()
637        })
638        .into()
639}
640
641/// Go `upsertModelInfos`: `extras` replace same-ID models (trimmed, case-insensitive)
642/// and come last; models with an empty ID are dropped.
643fn upsert<T>(models: Vec<T>, extras: Vec<T>, id: impl Fn(&T) -> &str) -> Vec<T> {
644    let keys: Vec<String> = extras.iter().map(|e| id(e).trim().go_lower()).collect();
645    let mut out: Vec<T> = models
646        .into_iter()
647        .filter(|m| {
648            let key = id(m).trim().go_lower();
649            !key.is_empty() && !keys.contains(&key)
650        })
651        .collect();
652    out.extend(extras);
653    out
654}
655
656/// Go `GetStaticModelDefinitionsByChannel`: one channel of the current static catalog
657/// with Go's built-ins; `None` for an unknown channel.
658pub fn static_definitions(channel: &str) -> Option<Vec<ModelInfo>> {
659    let section = |name: &str| pinned().channel(name).to_vec();
660    let info = |specs: Vec<Spec>| specs.iter().map(Spec::to_info).collect();
661    Some(match channel.trim().go_lower().as_str() {
662        "claude" => section("claude"),
663        "gemini" | "gemini-interactions" => section("gemini"),
664        "vertex" => section("vertex"),
665        "aistudio" => section("aistudio"),
666        "codex" => upsert(section("codex-pro"), info(codex_builtins()), |m| &m.id),
667        "kimi" | "kimi-ai" | "kimi.ai" | "kimi.com" => section("kimi"),
668        "antigravity" => section("antigravity"),
669        "xai" | "x-ai" | "grok" => upsert(section("xai"), info(xai_builtins()), |m| &m.id),
670        "devin" => super::devin::models(),
671        "meta" | "muse" => section("meta"),
672        _ => return None,
673    })
674}
675
676/// Go `WithXAIBuiltins`: the hard-coded image, video and speech models, appended after
677/// the channel's models and replacing any with the same ID.
678fn with_xai_builtins(models: Vec<Spec>) -> Vec<Spec> {
679    upsert(models, xai_builtins(), |m| &m.id)
680}
681
682fn xai_builtins() -> Vec<Spec> {
683    const BUILTINS: [(&str, i64, &str, &str); 8] = [
684        (
685            "grok-imagine-image",
686            1735689600,
687            "Grok Imagine Image",
688            "xAI Grok image generation model.",
689        ),
690        (
691            "grok-imagine-image-quality",
692            1735689600,
693            "Grok Imagine Image Quality",
694            "xAI Grok higher-fidelity image generation model.",
695        ),
696        (
697            "grok-imagine-image-2.0",
698            1786060800,
699            "Grok Imagine Image 2.0",
700            "xAI Grok image generation model.",
701        ),
702        (
703            "grok-imagine-video",
704            1735689600,
705            "Grok Imagine Video",
706            "xAI Grok video generation model.",
707        ),
708        (
709            "grok-imagine-video-1.5",
710            1735689600,
711            "Grok Imagine Video 1.5",
712            "xAI Grok video generation model.",
713        ),
714        (
715            "grok-imagine-video-1.5-preview",
716            1735689600,
717            "Grok Imagine Video 1.5 Preview",
718            "Compatibility alias for the xAI Grok video generation model.",
719        ),
720        (
721            "grok-tts",
722            1773619200,
723            "Grok TTS",
724            "xAI Grok unary text-to-speech model.",
725        ),
726        (
727            "grok-voice-tts-1.0",
728            1773619200,
729            "Grok Voice TTS 1.0",
730            "xAI Grok unary text-to-speech model.",
731        ),
732    ];
733    BUILTINS
734        .iter()
735        .map(|(id, created, display, description)| Spec {
736            id: (*id).into(),
737            object: "model".into(),
738            created: *created,
739            owned_by: "xai".into(),
740            kind: "xai".into(),
741            display_name: (*display).into(),
742            name: (*id).into(),
743            description: (*description).into(),
744            ..Spec::default()
745        })
746        .collect()
747}
748
749/// Go `buildConfigModels`; `metadata_channel` is the static channel whose native
750/// capabilities a configured upstream name inherits.
751fn build_config_models(
752    models: &[ConfigModel],
753    owned_by: &str,
754    kind: &str,
755    metadata_channel: &str,
756    now: i64,
757) -> Vec<Spec> {
758    let mut seen = std::collections::HashSet::new();
759    let statics = static_channel(metadata_channel);
760    models
761        .iter()
762        .filter_map(|m| {
763            let name = m.name.trim();
764            let alias = if m.alias.trim().is_empty() {
765                name
766            } else {
767                m.alias.trim()
768            };
769            if alias.is_empty() || !seen.insert(alias.go_lower()) {
770                return None;
771            }
772            let display = [m.display_name.trim(), name, alias]
773                .into_iter()
774                .find(|s| !s.is_empty())
775                .unwrap_or(alias);
776            let base = canonical_model(name);
777            let thinking = m
778                .thinking
779                .clone()
780                .map(normalize_thinking)
781                .or_else(|| pinned().lookup(base).and_then(|i| i.thinking.clone()));
782            Some(Spec {
783                id: alias.to_owned(),
784                metadata_model_id: if name.is_empty() {
785                    alias.to_owned()
786                } else {
787                    name.to_owned()
788                },
789                object: "model".into(),
790                created: now,
791                owned_by: owned_by.into(),
792                kind: kind.into(),
793                display_name: display.to_owned(),
794                context_length: m.max_context_length.max(0),
795                max_context_length: m.max_context_length.max(0),
796                thinking,
797                is_compat: m.is_compat,
798                support_configuration_update: m.support_configuration_update,
799                user_defined: true,
800                explicit_thinking: m.thinking.is_some(),
801                native_web_search: lookup_by_channel(&statics, metadata_channel, name)
802                    .and_then(|s| s.native_web_search),
803                ..Spec::default()
804            })
805        })
806        .collect()
807}
808
809/// `NormalizeThinkingSupport`: lowercase unique levels; `none` and `auto` flags.
810pub fn normalize_thinking(mut t: ThinkingSupport) -> ThinkingSupport {
811    let mut seen = std::collections::HashSet::new();
812    let levels = std::mem::take(&mut t.levels);
813    for level in levels {
814        let level = level.trim().go_lower();
815        if level.is_empty() {
816            continue;
817        }
818        match level.as_str() {
819            "none" => t.zero_allowed = true,
820            "auto" => t.dynamic_allowed = true,
821            _ => {}
822        }
823        if seen.insert(level.clone()) {
824            t.levels.push(level);
825        }
826    }
827    t
828}
829
830fn compat_models(models: &[ConfigModel], owned_by: &str, now: i64) -> Vec<Spec> {
831    models
832        .iter()
833        .filter_map(|m| {
834            let name = m.name.trim();
835            let alias = if m.alias.trim().is_empty() {
836                name
837            } else {
838                m.alias.trim()
839            };
840            if alias.is_empty() {
841                return None;
842            }
843            let display = [m.display_name.trim(), m.alias.trim(), alias]
844                .into_iter()
845                .find(|s| !s.is_empty())
846                .unwrap_or(alias);
847            let thinking = match &m.thinking {
848                Some(t) => Some(normalize_thinking(t.clone())),
849                None if !m.image => Some(ThinkingSupport {
850                    levels: vec!["low".into(), "medium".into(), "high".into()],
851                    ..ThinkingSupport::default()
852                }),
853                None => None,
854            };
855            Some(Spec {
856                id: alias.to_owned(),
857                metadata_model_id: if name.is_empty() {
858                    alias.to_owned()
859                } else {
860                    name.to_owned()
861                },
862                object: "model".into(),
863                created: now,
864                owned_by: owned_by.into(),
865                kind: if m.image {
866                    "openai-image".into()
867                } else {
868                    "openai-compatibility".into()
869                },
870                display_name: display.to_owned(),
871                context_length: m.max_context_length.max(0),
872                max_context_length: m.max_context_length.max(0),
873                thinking,
874                is_compat: m.is_compat,
875                explicit_thinking: m.thinking.is_some(),
876                explicit_input_modalities: !m.input_modalities.is_empty(),
877                supported_input_modalities: normalize_modalities(&m.input_modalities),
878                supported_output_modalities: normalize_modalities(&m.output_modalities),
879                ..Spec::default()
880            })
881        })
882        .collect()
883}
884
885/// Go `applyOAuthModelAliasEntries`: aliases replace their source model unless an
886/// entry is a fork, which keeps both.
887fn apply_aliases(aliases: &[OAuthAlias], models: Vec<Spec>) -> Vec<Spec> {
888    let mut forward: HashMap<String, Vec<&OAuthAlias>> = HashMap::new();
889    for a in aliases {
890        forward.entry(a.name.go_lower()).or_default().push(a);
891    }
892    if forward.is_empty() {
893        return models;
894    }
895    let mut out = Vec::with_capacity(models.len());
896    let mut seen = std::collections::HashSet::new();
897    for model in models {
898        let id = model.id.trim().to_owned();
899        if id.is_empty() {
900            continue;
901        }
902        let key = id.go_lower();
903        let Some(entries) = forward.get(&key) else {
904            if seen.insert(key) {
905                out.push(model);
906            }
907            continue;
908        };
909        let keep_original = entries.iter().any(|e| e.fork);
910        if keep_original && seen.insert(key.clone()) {
911            out.push(model.clone());
912        }
913        let mut added = false;
914        for entry in entries {
915            let mapped = entry.alias.trim();
916            if mapped.is_empty() || mapped.go_eq_fold(&id) || !seen.insert(mapped.go_lower()) {
917                continue;
918            }
919            let mut clone = model.clone();
920            clone.id = mapped.to_owned();
921            if clone.metadata_model_id.is_empty() {
922                clone.metadata_model_id = id.clone();
923            }
924            if !entry.display_name.is_empty() {
925                clone.display_name = entry.display_name.clone();
926            }
927            if !clone.name.is_empty() {
928                clone.name = rewrite_name(&clone.name, &id, mapped);
929            }
930            out.push(clone);
931            added = true;
932        }
933        if !keep_original && !added && seen.insert(key) {
934            out.push(model);
935        }
936    }
937    out
938}
939
940fn rewrite_name(name: &str, old: &str, new: &str) -> String {
941    let trimmed = name.trim();
942    if trimmed.is_empty() || old.go_eq_fold(new) {
943        return name.to_owned();
944    }
945    if trimmed.go_eq_fold(old) {
946        return new.to_owned();
947    }
948    if let Some(prefix) = trimmed.strip_suffix(old).filter(|p| p.ends_with('/')) {
949        return format!("{prefix}{new}");
950    }
951    if trimmed == format!("models/{old}") {
952        return format!("models/{new}");
953    }
954    name.to_owned()
955}
956
957/// Go `applyModelPrefixes`.
958fn apply_prefix(models: Vec<Spec>, prefix: &str, force: bool) -> Vec<Spec> {
959    if prefix.is_empty() {
960        return models;
961    }
962    let mut out = Vec::with_capacity(models.len() * 2);
963    let mut seen = std::collections::HashSet::new();
964    for model in models {
965        let base = model.id.trim().to_owned();
966        if base.is_empty() {
967            continue;
968        }
969        let mut clone = model.clone();
970        if (!force || prefix == base) && seen.insert(base.clone()) {
971            out.push(model);
972        }
973        clone.id = format!("{prefix}/{base}");
974        if clone.metadata_model_id.is_empty() {
975            clone.metadata_model_id = base;
976        }
977        if seen.insert(clone.id.clone()) {
978            out.push(clone);
979        }
980    }
981    out
982}
983
984/// Go `asyncProbeAntigravityCapabilities`: the upstream model IDs (lowercased) that each
985/// Antigravity credential's capability probe reported in `webSearchModelIds`, written by
986/// the Antigravity executor ([`set_web_search_hints`]). [`models_for`] marks those
987/// models, and so their aliases and prefixed copies, `supports_web_search`.
988static WEB_SEARCH_HINTS: std::sync::LazyLock<std::sync::RwLock<HashMap<String, std::collections::HashSet<String>>>> =
989    std::sync::LazyLock::new(Default::default);
990static HINTS_GENERATION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
991
992/// Replaces the web-search hints of one credential (empty clears them) and reports
993/// whether they changed; a change bumps [`capabilities_generation`].
994pub fn set_web_search_hints(credential: &str, ids: std::collections::HashSet<String>) -> bool {
995    let mut hints = WEB_SEARCH_HINTS
996        .write()
997        .unwrap_or_else(std::sync::PoisonError::into_inner);
998    let changed = if ids.is_empty() {
999        hints.remove(credential).is_some()
1000    } else if hints.get(credential) == Some(&ids) {
1001        false
1002    } else {
1003        hints.insert(credential.to_owned(), ids);
1004        true
1005    };
1006    if changed {
1007        HINTS_GENERATION.fetch_add(1, std::sync::atomic::Ordering::AcqRel);
1008    }
1009    changed
1010}
1011
1012/// Plugin-owned models (Go v8.0.35 `pluginHost.ModelsForProvider` and the executor model
1013/// clients `plugin:<id>:<provider>:executor`), published by the server's plugin host.
1014/// Catalog models reach the registry only through credentials of their provider.
1015/// ponytail: one process-wide catalog, as the server runs one plugin host; a second host
1016/// in the same process would need the catalog on the runtime instead.
1017#[derive(Debug, Clone, Default, PartialEq)]
1018pub struct PluginCatalog {
1019    /// Lowercased provider to its plugin models, first registration of an ID first.
1020    pub providers: HashMap<String, Vec<Spec>>,
1021    /// `(client, provider, models)` of the plugin executors that claimed models.
1022    pub clients: Vec<(String, String, Vec<Spec>)>,
1023}
1024
1025static PLUGIN_CATALOG: std::sync::LazyLock<std::sync::RwLock<Arc<PluginCatalog>>> =
1026    std::sync::LazyLock::new(Default::default);
1027
1028/// Replaces the plugin catalog; a change bumps [`capabilities_generation`] and returns
1029/// true.
1030pub fn set_plugin_catalog(catalog: PluginCatalog) -> bool {
1031    let mut current = PLUGIN_CATALOG
1032        .write()
1033        .unwrap_or_else(std::sync::PoisonError::into_inner);
1034    if **current == catalog {
1035        return false;
1036    }
1037    *current = Arc::new(catalog);
1038    HINTS_GENERATION.fetch_add(1, std::sync::atomic::Ordering::AcqRel);
1039    true
1040}
1041
1042fn plugin_catalog() -> Arc<PluginCatalog> {
1043    PLUGIN_CATALOG
1044        .read()
1045        .unwrap_or_else(std::sync::PoisonError::into_inner)
1046        .clone()
1047}
1048
1049/// Go `appendPluginModels`: the provider's plugin models not excluded by their own IDs,
1050/// after the models the credential already has.
1051fn append_plugin_models(provider: &str, mut models: Vec<Spec>, excluded: &[String]) -> Vec<Spec> {
1052    let catalog = plugin_catalog();
1053    let Some(plugin) = catalog.providers.get(provider) else {
1054        return models;
1055    };
1056    let mut seen: std::collections::HashSet<String> = models.iter().map(|m| m.id.trim().to_owned()).collect();
1057    for model in apply_excluded(plugin.clone(), excluded) {
1058        if seen.insert(model.id.trim().to_owned()) {
1059            models.push(model);
1060        }
1061    }
1062    models
1063}
1064
1065/// Bumped whenever [`set_web_search_hints`] changes a credential's hints or
1066/// [`set_plugin_catalog`] the plugin catalog; registries derived from credentials key on it.
1067pub fn capabilities_generation() -> u64 {
1068    HINTS_GENERATION.load(std::sync::atomic::Ordering::Acquire)
1069}
1070
1071/// `applyAntigravityFetchedModelCapabilities` with the credential's probe result.
1072fn with_web_search_hints(credential: &str, mut models: Vec<Spec>) -> Vec<Spec> {
1073    let hints = WEB_SEARCH_HINTS
1074        .read()
1075        .unwrap_or_else(std::sync::PoisonError::into_inner);
1076    if let Some(ids) = hints.get(credential) {
1077        for model in &mut models {
1078            if ids.contains(&model.id.trim().go_lower()) {
1079                model.supports_web_search = true;
1080            }
1081        }
1082    }
1083    models
1084}
1085
1086/// The models one credential registers (Go `registerModelsForAuth`), or none.
1087pub fn models_for(cfg: &Config, aliases: &HashMap<String, Vec<OAuthAlias>>, c: &Credential, now: i64) -> Vec<Spec> {
1088    if c.disabled {
1089        return Vec::new();
1090    }
1091    let excluded = excluded_for(cfg, c);
1092    let configured = config_models(c);
1093    let api_key = is_api_key(c);
1094    let provider = c.provider.trim().go_lower();
1095    if openai_compat(c) {
1096        let owned_by = c.attributes.get("compat_name").cloned().unwrap_or_default();
1097        // Go appends the provider's plugin models here too, without exclusions, and
1098        // even when no models are configured.
1099        let models = append_plugin_models(&provider_key(c), compat_models(&configured, &owned_by, now), &[]);
1100        return apply_prefix(models, credential_prefix(c), cfg.routing.force_model_prefix);
1101    }
1102    let with_config = |channel_models: Vec<Spec>, owned_by: &str, kind: &str, metadata: &str| {
1103        if configured.is_empty() {
1104            channel_models
1105        } else {
1106            build_config_models(&configured, owned_by, kind, metadata, now)
1107        }
1108    };
1109    let models = match provider.as_str() {
1110        "gemini" | "gemini-interactions" => with_config(channel("gemini"), "google", "gemini", "gemini"),
1111        "vertex" if matches!(c.source, Source::Config { .. }) => {
1112            with_config(channel("vertex"), "google", "vertex", "vertex")
1113        }
1114        "vertex" => vertex_service_account_models(aliases, c, channel("vertex"), now),
1115        "aistudio" => channel("aistudio"),
1116        "antigravity" => with_web_search_hints(&c.id, channel("antigravity")),
1117        "claude" => with_config(channel("claude"), "anthropic", "claude", "claude"),
1118        "codex" if api_key => {
1119            if configured.is_empty() {
1120                let mut models = codex_channel("codex-pro");
1121                for m in &mut models {
1122                    m.support_configuration_update = false;
1123                }
1124                models
1125            } else {
1126                build_config_models(&configured, "openai", "openai", "codex", now)
1127            }
1128        }
1129        "codex" => {
1130            let plan = c
1131                .attributes
1132                .get("plan_type")
1133                .map(|p| p.trim().go_lower())
1134                .unwrap_or_default();
1135            codex_channel(match plan.as_str() {
1136                "plus" => "codex-plus",
1137                "team" | "business" | "go" => "codex-team",
1138                "free" => "codex-free",
1139                _ => "codex-pro",
1140            })
1141        }
1142        "kimi" | "kimi-ai" | "kimi.ai" | "kimi.com" => channel("kimi"),
1143        "xai" => with_config(with_xai_builtins(channel("xai")), "xai", "xai", "xai"),
1144        "meta" => with_config(channel("meta"), "meta", "meta", "meta"),
1145        // Go `registry.GetDevinModels()`: the live Devin catalog, never config models.
1146        "devin" => super::devin::models().iter().map(Spec::from_static).collect(),
1147        _ => Vec::new(),
1148    };
1149    let models = apply_excluded(models, &excluded);
1150    let models = apply_aliases(&oauth_aliases_for(aliases, c), models);
1151    let models = append_plugin_models(&provider, models, &excluded);
1152    // ponytail: oauth.settings max-context-length overrides are not applied yet.
1153    apply_prefix(models, credential_prefix(c), cfg.routing.force_model_prefix)
1154}
1155
1156/// The model names an auth file lists (Go d9451cb6): a comma-separated string, an
1157/// array of strings, or an array of entries with a string `name`.
1158pub fn for_each_model_name(raw: &Value, mut f: impl FnMut(&str)) {
1159    match raw {
1160        Value::String(s) => s.split(',').for_each(f),
1161        Value::Array(items) => {
1162            for item in items {
1163                match item {
1164                    Value::String(s) => f(s),
1165                    Value::Object(entry) => {
1166                        if let Some(name) = entry.get("name").and_then(Value::as_str) {
1167                            f(name);
1168                        }
1169                    }
1170                    _ => {}
1171                }
1172            }
1173        }
1174        _ => {}
1175    }
1176}
1177
1178/// Go `appendVertexServiceAccountModels` (d9451cb6): a Vertex file's catalog plus the
1179/// partner and open models it names (the `openapi_models` attribute, the file's
1180/// `openapi_models` and `models`) and the OAuth alias targets, each new one as a
1181/// user-defined Vertex model owned by its publisher.
1182fn vertex_service_account_models(
1183    aliases: &HashMap<String, Vec<OAuthAlias>>,
1184    c: &Credential,
1185    mut models: Vec<Spec>,
1186    now: i64,
1187) -> Vec<Spec> {
1188    let mut seen: std::collections::HashSet<String> = models.iter().map(|m| m.id.trim().go_lower()).collect();
1189    let mut extra = Vec::new();
1190    let mut add = |raw: &str| {
1191        let name = raw.trim();
1192        if !name.is_empty() && seen.insert(name.go_lower()) {
1193            extra.push(name.to_owned());
1194        }
1195    };
1196    if let Some(raw) = c.attributes.get("openapi_models") {
1197        raw.split(',').for_each(&mut add);
1198    }
1199    for key in ["openapi_models", "openapi-models", "models"] {
1200        if let Some(raw) = c.metadata.get(key) {
1201            for_each_model_name(raw, &mut add);
1202        }
1203    }
1204    for entry in oauth_aliases_for(aliases, c) {
1205        add(&entry.name);
1206    }
1207    models.extend(extra.into_iter().map(|name| {
1208        let owned_by = name
1209            .split_once('/')
1210            .map(|(publisher, _)| publisher.trim())
1211            .filter(|p| !p.is_empty())
1212            .unwrap_or("google")
1213            .to_owned();
1214        // `modelconfig.ResolveModelInfo`: the catalog's thinking for the base name.
1215        let thinking = pinned()
1216            .lookup(canonical_model(&name))
1217            .and_then(|i| i.thinking.clone())
1218            .or_else(|| {
1219                Some(ThinkingSupport {
1220                    levels: vec!["low".into(), "medium".into(), "high".into()],
1221                    ..ThinkingSupport::default()
1222                })
1223            });
1224        Spec {
1225            id: name.clone(),
1226            metadata_model_id: name.clone(),
1227            object: "model".into(),
1228            created: now,
1229            owned_by,
1230            kind: "vertex".into(),
1231            display_name: name,
1232            thinking,
1233            user_defined: true,
1234            ..Spec::default()
1235        }
1236    }));
1237    models
1238}
1239
1240struct Registration {
1241    id: String,
1242    info: Arc<Spec>,
1243    /// Provider registration counts, in first-registration order.
1244    providers: Vec<(String, usize)>,
1245    by_provider: HashMap<String, Arc<Spec>>,
1246    /// Credentials that registered this model.
1247    clients: Vec<String>,
1248}
1249
1250/// A credential's current state for one model, as Go projects it into the registry
1251/// (`ClientModelProjection`): quota cooling keeps a model listed, other suspensions
1252/// (auth failures, unsupported models, credential-wide quota) hide it.
1253#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1254pub enum Suspension {
1255    None,
1256    /// Suspended with reason `quota` (a 429 on this model).
1257    Quota,
1258    /// Suspended for any other reason; `quota_exceeded` when the state is also marked
1259    /// quota-exceeded (Cloudflare challenges).
1260    Other {
1261        quota_exceeded: bool,
1262    },
1263}
1264
1265/// Go's listing rule over the registering credentials' states
1266/// (`modelRegistrationAvailability`, `GetAvailableModelsByProvider`): listed while any
1267/// credential is usable, or when every unusable one is only quota-cooling.
1268fn listable(states: impl Iterator<Item = Suspension>) -> bool {
1269    let (mut count, mut expired, mut cooling, mut other, mut quota_and_other) = (0i64, 0i64, 0i64, 0i64, 0i64);
1270    for state in states {
1271        count += 1;
1272        match state {
1273            Suspension::None => {}
1274            Suspension::Quota => {
1275                expired += 1;
1276                cooling += 1;
1277            }
1278            Suspension::Other { quota_exceeded } => {
1279                other += 1;
1280                if quota_exceeded {
1281                    expired += 1;
1282                    quota_and_other += 1;
1283                }
1284            }
1285        }
1286    }
1287    let effective = count - expired - other + quota_and_other;
1288    effective > 0 || (count > 0 && (expired > 0 || cooling > 0) && other == 0)
1289}
1290
1291struct Client {
1292    provider: String,
1293    models: HashMap<String, Arc<Spec>>,
1294}
1295
1296/// A snapshot of every credential's registrations.
1297#[derive(Default)]
1298pub struct Registry {
1299    models: Vec<Registration>,
1300    index: HashMap<String, usize>,
1301    clients: HashMap<String, Client>,
1302}
1303
1304impl Registry {
1305    pub fn build(cfg: &Config, credentials: &[Arc<Credential>]) -> Self {
1306        let now = std::time::SystemTime::now()
1307            .duration_since(std::time::UNIX_EPOCH)
1308            .map_or(0, |d| d.as_secs() as i64);
1309        let aliases = global_aliases(cfg);
1310        let mut registry = Self::default();
1311        for c in credentials {
1312            let models = models_for(cfg, &aliases, c, now);
1313            if !models.is_empty() {
1314                registry.register(&c.id, &provider_key(c), models);
1315            }
1316        }
1317        for (client, provider, models) in &plugin_catalog().clients {
1318            if !registry.has_client(client) {
1319                registry.register(client, provider, models.clone());
1320            }
1321        }
1322        registry
1323    }
1324
1325    /// Go `RegisterClient` for a client not yet registered: duplicate IDs keep the
1326    /// first definition. `provider` is the lowercased provider key.
1327    pub fn register(&mut self, client: &str, provider: &str, models: Vec<Spec>) {
1328        let mut infos = HashMap::new();
1329        for model in models {
1330            if model.id.is_empty() || infos.contains_key(&model.id) {
1331                continue;
1332            }
1333            let info = Arc::new(model);
1334            infos.insert(info.id.clone(), info.clone());
1335            match self.index.get(&info.id) {
1336                Some(&i) => {
1337                    let reg = &mut self.models[i];
1338                    // Go keeps the latest registration's info, with `SupportsWebSearch`
1339                    // set when any registering credential (of that provider) has it.
1340                    let with_search = |seen: bool| {
1341                        if !seen || info.supports_web_search {
1342                            return info.clone();
1343                        }
1344                        let mut spec = (*info).clone();
1345                        spec.supports_web_search = true;
1346                        Arc::new(spec)
1347                    };
1348                    reg.info = with_search(reg.info.supports_web_search);
1349                    match reg.providers.iter_mut().find(|(p, _)| p == provider) {
1350                        Some((_, n)) => *n += 1,
1351                        None => reg.providers.push((provider.to_owned(), 1)),
1352                    }
1353                    let seen = reg.by_provider.get(provider).is_some_and(|s| s.supports_web_search);
1354                    reg.by_provider.insert(provider.to_owned(), with_search(seen));
1355                    reg.clients.push(client.to_owned());
1356                }
1357                None => {
1358                    self.index.insert(info.id.clone(), self.models.len());
1359                    self.models.push(Registration {
1360                        id: info.id.clone(),
1361                        info: info.clone(),
1362                        providers: vec![(provider.to_owned(), 1)],
1363                        by_provider: HashMap::from([(provider.to_owned(), info)]),
1364                        clients: vec![client.to_owned()],
1365                    });
1366                }
1367            }
1368        }
1369        self.clients.insert(
1370            client.to_owned(),
1371            Client {
1372                provider: provider.to_owned(),
1373                models: infos,
1374            },
1375        );
1376    }
1377
1378    /// Go `GetModelProviders`: most registrations first, then by name.
1379    pub fn model_providers(&self, model: &str) -> Vec<String> {
1380        let Some(&i) = self.index.get(model) else {
1381            return Vec::new();
1382        };
1383        let mut providers = self.models[i].providers.clone();
1384        providers.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
1385        providers.into_iter().map(|(p, _)| p).collect()
1386    }
1387
1388    /// Go `util.GetProviderName`: exact ID, then the lowercased ID.
1389    pub fn providers(&self, model: &str) -> Vec<String> {
1390        if model.is_empty() {
1391            return Vec::new();
1392        }
1393        let exact = self.model_providers(model);
1394        if exact.is_empty() && model.go_lower() != model {
1395            return self.model_providers(&model.go_lower());
1396        }
1397        exact
1398    }
1399
1400    /// Go `ClientSupportsModel`: case-insensitive membership.
1401    pub fn client_supports(&self, client: &str, model: &str) -> bool {
1402        let model = model.trim();
1403        !model.is_empty()
1404            && self
1405                .clients
1406                .get(client)
1407                .is_some_and(|c| c.models.keys().any(|id| id.go_eq_fold(model)))
1408    }
1409
1410    /// Whether `client` registered anything (unregistered credentials never route).
1411    pub fn has_client(&self, client: &str) -> bool {
1412        self.clients.contains_key(client)
1413    }
1414
1415    /// The model registered by one credential under `model`.
1416    pub fn client_model(&self, client: &str, model: &str) -> Option<Arc<Spec>> {
1417        let c = self.clients.get(client)?;
1418        c.models
1419            .get(model)
1420            .or_else(|| c.models.iter().find(|(id, _)| id.go_eq_fold(model)).map(|(_, m)| m))
1421            .cloned()
1422    }
1423
1424    pub fn client_provider(&self, client: &str) -> Option<&str> {
1425        self.clients.get(client).map(|c| c.provider.as_str())
1426    }
1427
1428    /// Go `GetModelInfo(id, provider)`.
1429    pub fn info(&self, id: &str, provider: Option<&str>) -> Option<Arc<Spec>> {
1430        let reg = &self.models[*self.index.get(id)?];
1431        provider
1432            .and_then(|p| reg.by_provider.get(p))
1433            .or(Some(&reg.info))
1434            .cloned()
1435    }
1436
1437    /// Go `GetResponsesWebSearchCapability`: native web search across every route that
1438    /// registered exactly `model`. A route known not to support it wins; any unknown
1439    /// route makes the answer unknown.
1440    pub fn responses_web_search(&self, model: &str) -> Option<bool> {
1441        let model = model.trim();
1442        let routes: Vec<(&str, Option<bool>)> = self
1443            .clients
1444            .values()
1445            .filter_map(|c| c.models.get(model).map(|m| (c.provider.as_str(), m.native_web_search)))
1446            .collect();
1447        if routes.is_empty() {
1448            return None;
1449        }
1450        let mut unknown = false;
1451        for (provider, native) in routes {
1452            if native == Some(false) {
1453                return Some(false);
1454            }
1455            match provider_web_search_path(provider) {
1456                None => unknown = true,
1457                Some(false) => return Some(false),
1458                Some(true) => unknown |= native.is_none(),
1459            }
1460        }
1461        (!unknown).then_some(true)
1462    }
1463
1464    /// Registered models in first-registration order, ignoring cooldown state.
1465    pub fn available(&self) -> impl Iterator<Item = &Spec> {
1466        self.models.iter().map(|r| r.info.as_ref())
1467    }
1468
1469    /// Registered models a client may list or `auto` may pick (Go
1470    /// `modelRegistrationAvailability`), given each credential's state per model.
1471    // ponytail: Go recomputes projections only when a result or refresh is recorded, so
1472    // a model can stay hidden after its cooldown lapses; this reads live state instead.
1473    pub fn available_with<'a>(
1474        &'a self,
1475        state: impl Fn(&str, &str) -> Suspension + 'a,
1476    ) -> impl Iterator<Item = &'a Spec> {
1477        self.models.iter().filter_map(move |r| {
1478            let states = r.clients.iter().map(|client| state(client, &r.id));
1479            listable(states).then_some(r.info.as_ref())
1480        })
1481    }
1482
1483    /// Go `GetAvailableModelsByProvider`: the models `provider`'s credentials
1484    /// registered that are still listable counting only that provider's credentials,
1485    /// each with the first such credential's model info. Registration order (Go's is
1486    /// map order).
1487    pub fn available_by_provider(&self, provider: &str, state: impl Fn(&str, &str) -> Suspension) -> Vec<Arc<Spec>> {
1488        let provider = provider.trim().go_lower();
1489        if provider.is_empty() {
1490            return Vec::new();
1491        }
1492        let mut out = Vec::new();
1493        for r in &self.models {
1494            let mut clients = r
1495                .clients
1496                .iter()
1497                .filter_map(|id| Some((id, self.clients.get(id).filter(|c| c.provider == provider)?)))
1498                .peekable();
1499            let Some(info) = clients.peek().and_then(|(_, c)| c.models.get(&r.id)).cloned() else {
1500                continue;
1501            };
1502            if listable(clients.map(|(id, _)| state(id, &r.id))) {
1503                out.push(info);
1504            }
1505        }
1506        out
1507    }
1508
1509    /// Go `ResolveAutoModel`: the newest available model.
1510    pub fn resolve_auto(&self, state: impl Fn(&str, &str) -> Suspension) -> Option<String> {
1511        let mut best: Option<&Spec> = None;
1512        for m in self.available_with(state) {
1513            if best.is_none_or(|b| m.created > b.created) {
1514                best = Some(m);
1515            }
1516        }
1517        best.map(|m| m.id.clone())
1518    }
1519
1520    pub fn ids(&self) -> impl Iterator<Item = &str> {
1521        self.models.iter().map(|r| r.id.as_str())
1522    }
1523}
1524
1525/// Result of resolving a route model for one credential (Go `OAuthModelAliasResult`).
1526#[derive(Debug, Clone, Default, PartialEq, Eq)]
1527pub struct AliasResult {
1528    pub upstream: String,
1529    pub force_mapping: bool,
1530    pub original_alias: String,
1531}
1532
1533fn suffix_of(model: &str) -> Option<&str> {
1534    let open = model.rfind('(')?;
1535    model.ends_with(')').then(|| &model[open + 1..model.len() - 1])
1536}
1537
1538fn preserve_suffix(resolved: &str, requested: &str) -> String {
1539    let resolved = resolved.trim();
1540    if resolved.is_empty() || suffix_of(resolved).is_some() {
1541        return resolved.to_owned();
1542    }
1543    match suffix_of(requested.trim()) {
1544        Some(s) if !s.is_empty() => format!("{resolved}({s})"),
1545        _ => resolved.to_owned(),
1546    }
1547}
1548
1549fn candidates(requested: &str) -> Vec<String> {
1550    let requested = requested.trim();
1551    if requested.is_empty() {
1552        return Vec::new();
1553    }
1554    let base = match suffix_of(requested) {
1555        Some(_) => &requested[..requested.rfind('(').unwrap()],
1556        None => requested,
1557    };
1558    let mut out = vec![requested.to_owned()];
1559    if !base.is_empty() && base != requested {
1560        out.push(base.to_owned());
1561    }
1562    out
1563}
1564
1565/// Go's alias resolution over `entries`: `matches(alias, candidate)` is `EqualFold` for
1566/// configured models and per-credential aliases, and `strings.ToLower` key equality for
1567/// the global OAuth alias table.
1568fn resolve_with<'a, I>(requested: &str, entries: I, matches: fn(&str, &str) -> bool) -> AliasResult
1569where
1570    I: Iterator<Item = (&'a str, &'a str, bool)> + Clone,
1571{
1572    let base = canonical_model(requested);
1573    for candidate in candidates(requested) {
1574        for (name, alias, force) in entries.clone() {
1575            let (name, alias) = (name.trim(), alias.trim());
1576            if name.is_empty() || alias.is_empty() || !matches(alias, &candidate) {
1577                continue;
1578            }
1579            if name.go_eq_fold(base) {
1580                if !force {
1581                    return AliasResult::default();
1582                }
1583                return AliasResult {
1584                    upstream: preserve_suffix(name, requested),
1585                    force_mapping: true,
1586                    original_alias: alias.to_owned(),
1587                };
1588            }
1589            return AliasResult {
1590                upstream: preserve_suffix(name, requested),
1591                force_mapping: force,
1592                original_alias: if force { alias.to_owned() } else { requested.to_owned() },
1593            };
1594        }
1595    }
1596    AliasResult::default()
1597}
1598
1599fn fold(a: &str, b: &str) -> bool {
1600    a.go_eq_fold(b)
1601}
1602
1603fn same_lower(a: &str, b: &str) -> bool {
1604    a.go_lower() == b.go_lower()
1605}
1606
1607/// Go `resolveOAuthModelAliasWithResult`: the credential's own aliases first, compared
1608/// with `EqualFold`, then the channel's global table, looked up by `strings.ToLower` key
1609/// (`resolveUpstreamModelFromAliasTable`), with no `EqualFold` fallback.
1610fn resolve_oauth(cfg_aliases: &HashMap<String, Vec<OAuthAlias>>, c: &Credential, requested: &str) -> AliasResult {
1611    let Some(channel) = alias_channel(c) else {
1612        return AliasResult::default();
1613    };
1614    fn entries(aliases: &[OAuthAlias]) -> impl Iterator<Item = (&str, &str, bool)> + Clone {
1615        aliases
1616            .iter()
1617            .map(|a| (a.name.as_str(), a.alias.as_str(), a.force_mapping))
1618    }
1619    let own = attribute_aliases(c);
1620    let r = resolve_with(requested, entries(&own), fold);
1621    if !r.upstream.is_empty() {
1622        return r;
1623    }
1624    let global = cfg_aliases.get(&channel).map(Vec::as_slice).unwrap_or_default();
1625    resolve_with(requested, entries(global), same_lower)
1626}
1627
1628/// Go `lookupAPIKeyUpstreamModel` over the table `compileAPIKeyModelAliasForModels`
1629/// builds: each entry with both a name and an alias adds its alias, suffix-free alias,
1630/// name and suffix-free name under `strings.ToLower` keys, the first entry winning a key.
1631/// The requested model is looked up, then its suffix-free form.
1632fn api_key_table_upstream(requested: &str, models: &[ConfigModel]) -> Option<String> {
1633    let requested = requested.trim();
1634    let base = |s: &'_ str| -> String {
1635        let s = s.trim();
1636        match suffix_of(s) {
1637            Some(_) => s[..s.rfind('(').unwrap()].trim().go_lower(),
1638            None => s.go_lower(),
1639        }
1640    };
1641    let mut keys = vec![requested.go_lower()];
1642    let requested_base = base(requested);
1643    if !requested_base.is_empty() && requested_base != keys[0] {
1644        keys.push(requested_base);
1645    }
1646    keys.into_iter().filter(|k| !k.is_empty()).find_map(|key| {
1647        models.iter().find_map(|m| {
1648            let (name, alias) = (m.name.trim(), m.alias.trim());
1649            if name.is_empty() || alias.is_empty() {
1650                return None;
1651            }
1652            [alias.go_lower(), base(alias), name.go_lower(), base(name)]
1653                .contains(&key)
1654                .then(|| preserve_suffix(name, requested))
1655        })
1656    })
1657}
1658
1659/// Go `rewriteModelForAuth`: drop the credential's `prefix/`.
1660pub fn strip_prefix<'a>(model: &'a str, c: &Credential) -> &'a str {
1661    let prefix = credential_prefix(c);
1662    if prefix.is_empty() || model.is_empty() {
1663        return model;
1664    }
1665    model.strip_prefix(&format!("{prefix}/")).unwrap_or(model)
1666}
1667
1668/// Upstream model candidates for one credential (Go `executionModelCandidatesWithAlias`).
1669/// More than one candidate is an OpenAI-compatible alias pool, tried in order.
1670pub fn execution_models(
1671    cfg_aliases: &HashMap<String, Vec<OAuthAlias>>,
1672    c: &Credential,
1673    route_model: &str,
1674) -> (Vec<String>, AliasResult) {
1675    let requested = strip_prefix(route_model, c);
1676    let configured = is_api_key(c) || openai_compat(c);
1677    let models = config_models(c);
1678    let alias = if configured {
1679        if models.is_empty() {
1680            AliasResult {
1681                upstream: requested.to_owned(),
1682                ..AliasResult::default()
1683            }
1684        } else {
1685            let r = resolve_with(
1686                requested,
1687                models
1688                    .iter()
1689                    .map(|m| (m.name.as_str(), m.alias.as_str(), m.force_mapping)),
1690                fold,
1691            );
1692            if r.upstream.is_empty() {
1693                AliasResult {
1694                    upstream: requested.to_owned(),
1695                    ..AliasResult::default()
1696                }
1697            } else {
1698                r
1699            }
1700        }
1701    } else {
1702        resolve_oauth(cfg_aliases, c, requested)
1703    };
1704    let upstream = if configured || alias.upstream.is_empty() {
1705        requested.to_owned()
1706    } else {
1707        alias.upstream.clone()
1708    };
1709    if configured && !models.is_empty() {
1710        let pool = alias_pool(&upstream, &models);
1711        // Go `executionModelCandidatesWithAlias`: a non-empty compat pool wins. Otherwise
1712        // `applyAPIKeyModelAliasWithRouting` tries an API key's lowercase-keyed table
1713        // before the `EqualFold` scan.
1714        if openai_compat(c) && !pool.is_empty() {
1715            return (pool, alias);
1716        }
1717        if is_api_key(c)
1718            && let Some(upstream) = api_key_table_upstream(&upstream, &models)
1719        {
1720            return (vec![upstream], alias);
1721        }
1722        if let Some(first) = pool.into_iter().next() {
1723            return (vec![first], alias);
1724        }
1725    }
1726    // Go `applyAPIKeyModelAliasWithRouting` returns an API key's unmatched model trimmed.
1727    let trimmed = upstream.trim();
1728    if is_api_key(c) && !trimmed.is_empty() {
1729        return (vec![trimmed.to_owned()], alias);
1730    }
1731    (vec![upstream], alias)
1732}
1733
1734/// Go `resolveModelAliasPoolFromConfigModels`.
1735fn alias_pool(requested: &str, models: &[ConfigModel]) -> Vec<String> {
1736    for candidate in candidates(requested) {
1737        let mut out = Vec::new();
1738        let mut seen = std::collections::HashSet::new();
1739        for m in models {
1740            let (name, alias) = (m.name.trim(), m.alias.trim());
1741            if alias.is_empty() || !alias.go_eq_fold(&candidate) {
1742                continue;
1743            }
1744            let resolved = preserve_suffix(if name.is_empty() { &candidate } else { name }, requested);
1745            if !resolved.is_empty() && seen.insert(resolved.go_lower()) {
1746                out.push(resolved);
1747            }
1748        }
1749        if !out.is_empty() {
1750            return out;
1751        }
1752    }
1753    for candidate in candidates(requested) {
1754        if let Some(m) = models
1755            .iter()
1756            .find(|m| !m.name.trim().is_empty() && m.name.trim().go_eq_fold(&candidate))
1757        {
1758            return vec![preserve_suffix(m.name.trim(), requested)];
1759        }
1760    }
1761    Vec::new()
1762}
1763
1764/// Go `selectionModelForAuth`: prefix stripped, OAuth alias applied. Cooldown state is
1765/// keyed by this when it equals the upstream model, else by the route model.
1766pub fn selection_model(cfg_aliases: &HashMap<String, Vec<OAuthAlias>>, c: &Credential, route_model: &str) -> String {
1767    let requested = strip_prefix(route_model, c);
1768    if is_api_key(c) || openai_compat(c) {
1769        return requested.to_owned();
1770    }
1771    let r = resolve_oauth(cfg_aliases, c, requested);
1772    if r.upstream.is_empty() {
1773        requested.to_owned()
1774    } else {
1775        r.upstream
1776    }
1777}
1778
1779/// Go `stateModelForExecution`.
1780pub fn state_model(selection: &str, route_model: &str, upstream: &str, pooled: bool) -> String {
1781    if !selection.trim().is_empty() && canonical_model(selection) == canonical_model(upstream) {
1782        return upstream.trim().to_owned();
1783    }
1784    if pooled && !upstream.trim().is_empty() {
1785        return upstream.trim().to_owned();
1786    }
1787    if !route_model.trim().is_empty() {
1788        route_model.trim().to_owned()
1789    } else {
1790        upstream.trim().to_owned()
1791    }
1792}
1793
1794#[cfg(test)]
1795mod tests {
1796    use super::*;
1797    use std::path::Path;
1798
1799    fn file(id: &str, meta: Value, attrs: &[(&str, &str)]) -> Arc<Credential> {
1800        let mut c = Credential::from_file(
1801            Path::new("/a"),
1802            &Path::new("/a").join(id),
1803            meta.as_object().unwrap().clone(),
1804        )
1805        .unwrap();
1806        for (k, v) in attrs {
1807            c.attributes.insert((*k).into(), (*v).into());
1808        }
1809        Arc::new(c)
1810    }
1811
1812    /// Go `GetStaticModelDefinitionsByChannel` and `LookupStaticModelInfoByChannel`: Go's
1813    /// channel names (folded with Unicode case rules), its getters' built-ins, trimmed
1814    /// IDs and Claude family entries; raw catalog sections are not channels.
1815    #[test]
1816    fn static_channel_lookup_matches_go() {
1817        let ids = |name: &str| static_channel(name).into_iter().map(|m| m.id).collect::<Vec<_>>();
1818        for (name, same_as) in [
1819            (" Claude ", "claude"),
1820            ("gemini-interactions", "gemini"),
1821            ("x-ai", "xai"),
1822            ("GROK", "xai"),
1823            ("muse", "meta"),
1824            ("kimi.com", "kimi"),
1825            // KELVIN SIGN folds to `k` in Go's strings.ToLower too.
1826            ("\u{212A}imi", "kimi"),
1827        ] {
1828            assert!(!ids(same_as).is_empty(), "{same_as}");
1829            assert_eq!(ids(name), ids(same_as), "{name}");
1830        }
1831        for raw in [
1832            "codex-pro",
1833            "codex-team",
1834            "codex-free",
1835            "codex-plus",
1836            "gemini-cli",
1837            "unknown",
1838        ] {
1839            assert!(static_channel(raw).is_empty(), "{raw} is not a Go channel");
1840        }
1841        assert!(
1842            ids("codex").iter().any(|id| id == "gpt-image-2"),
1843            "codex keeps its built-ins"
1844        );
1845        assert_eq!(
1846            ids("devin"),
1847            super::super::devin::models()
1848                .into_iter()
1849                .map(|m| m.id)
1850                .collect::<Vec<_>>()
1851        );
1852        let claude = static_channel("Claude");
1853        let found =
1854            |channel: &str, models: &[Spec], id: &str| lookup_by_channel(models, channel, id).map(|m| m.id.clone());
1855        assert_eq!(
1856            found(" Claude ", &claude, " claude-opus-5-5[1m] ").as_deref(),
1857            Some("claude-opus-5-5")
1858        );
1859        assert_eq!(
1860            found("claude", &claude, "claude-sonnet-5-5-20261001").as_deref(),
1861            Some("claude-sonnet-5-5")
1862        );
1863        assert_eq!(found("claude", &claude, "  "), None);
1864        // The family fallback is Claude's alone.
1865        let gemini = static_channel("gemini");
1866        let mut renamed = claude.clone();
1867        renamed.retain(|m| m.id == "claude-opus-5-5");
1868        assert_eq!(found("gemini", &renamed, "claude-opus-5-5[1m]"), None);
1869        assert!(found("gemini", &gemini, "claude-opus-5-5").is_none());
1870    }
1871
1872    /// Go `Auth.AccountInfo` (sdk/cliproxy/auth/types.go): kind first, then the
1873    /// trimmed email or API key; a non-string email or an unclassified auth is empty.
1874    #[test]
1875    fn account_info_matches_go() {
1876        let oauth = file(
1877            "o.json",
1878            serde_json::json!({"type":"claude","email":" a@b.test ","access_token":"t"}),
1879            &[],
1880        );
1881        assert_eq!(account_info(&oauth), ("oauth", "a@b.test".into()));
1882        let odd = file(
1883            "x.json",
1884            serde_json::json!({"type":"claude","email":7,"access_token":"t"}),
1885            &[],
1886        );
1887        assert_eq!(account_info(&odd), ("oauth", String::new()));
1888        let key = file(
1889            "k.json",
1890            serde_json::json!({"type":"claude","email":"ignored@b.test"}),
1891            &[("api_key", " sk-1 ")],
1892        );
1893        assert_eq!(account_info(&key), ("api_key", "sk-1".into()));
1894        let declared = file(
1895            "d.json",
1896            serde_json::json!({"type":"claude"}),
1897            &[("auth_kind", "API-KEY")],
1898        );
1899        assert_eq!(account_info(&declared), ("api_key", String::new()));
1900        let bare = file("b.json", serde_json::json!({"type":"claude"}), &[]);
1901        assert_eq!(account_info(&bare), ("", String::new()));
1902    }
1903
1904    fn config(provider: &str, id: &str, meta: Value, attrs: &[(&str, &str)]) -> Arc<Credential> {
1905        let mut c = Credential {
1906            id: id.into(),
1907            provider: provider.into(),
1908            source: Source::Config {
1909                section: format!("{provider}-api-key"),
1910                index: 0,
1911            },
1912            disabled: false,
1913            label: String::new(),
1914            attributes: attrs.iter().map(|(k, v)| ((*k).into(), (*v).into())).collect(),
1915            metadata: meta.as_object().unwrap().clone(),
1916            revision: 0,
1917            next_refresh_after: None,
1918        };
1919        c.attributes.insert("auth_kind".into(), "apikey".into());
1920        Arc::new(c)
1921    }
1922
1923    #[test]
1924    fn oauth_claude_registers_go_catalog_minus_disabled() {
1925        let cfg = Config::default();
1926        let live = file("a.json", serde_json::json!({"type":"claude"}), &[]);
1927        let off = file("b.json", serde_json::json!({"type":"claude","disabled":true}), &[]);
1928        let r = Registry::build(&cfg, &[live, off]);
1929        assert_eq!(r.available().count(), 19, "Go registers the 19-model Claude catalog");
1930        assert_eq!(r.providers("claude-sonnet-4-6"), ["claude"]);
1931        assert!(r.has_client("a.json") && !r.has_client("b.json"));
1932        assert!(r.providers("gpt-5.5").is_empty());
1933        let only_off = Registry::build(
1934            &cfg,
1935            &[file(
1936                "b.json",
1937                serde_json::json!({"type":"claude","disabled":true}),
1938                &[],
1939            )],
1940        );
1941        assert!(
1942            only_off.providers("claude-sonnet-4-6").is_empty(),
1943            "disabled credentials register nothing"
1944        );
1945    }
1946
1947    #[test]
1948    fn exclusions_aliases_forks_and_prefixes_follow_go() {
1949        let cfg = Config::parse(
1950            "oauth:\n  model-alias:\n    claude:\n      - {name: claude-opus-5, alias: big, fork: true}\n      - {name: claude-sonnet-5, alias: mid, display-name: Mid}\n",
1951        )
1952        .unwrap();
1953        let c = file(
1954            "a.json",
1955            serde_json::json!({"type":"claude"}),
1956            &[("excluded_models", "*haiku*,*-2025*"), ("prefix", "team")],
1957        );
1958        let r = Registry::build(&cfg, std::slice::from_ref(&c));
1959        let ids: Vec<&str> = r.ids().collect();
1960        assert!(
1961            !ids.iter().any(|id| id.contains("haiku") || id.contains("-2025")),
1962            "{ids:?}"
1963        );
1964        // Fork keeps the source model; a plain alias replaces it.
1965        assert!(ids.contains(&"claude-opus-5") && ids.contains(&"big"));
1966        assert!(!ids.contains(&"claude-sonnet-5") && ids.contains(&"mid"));
1967        assert_eq!(r.info("mid", None).unwrap().display_name, "Mid");
1968        assert!(ids.contains(&"team/mid") && ids.contains(&"team/claude-opus-5"));
1969        assert!(r.client_supports("a.json", "TEAM/MID"));
1970        // Forced prefixes drop the bare IDs.
1971        let forced = Config::parse("routing:\n  force-model-prefix: true\n").unwrap();
1972        let r = Registry::build(&forced, std::slice::from_ref(&c));
1973        assert!(r.ids().all(|id| id.starts_with("team/")));
1974        // Execution resolves the alias back to its upstream name and keeps the suffix.
1975        let aliases = global_aliases(&cfg);
1976        let (models, alias) = execution_models(&aliases, &c, "team/mid(high)");
1977        assert_eq!(models, ["claude-sonnet-5(high)"]);
1978        assert!(!alias.force_mapping);
1979        assert_eq!(
1980            state_model(
1981                &selection_model(&aliases, &c, "team/mid"),
1982                "team/mid",
1983                "claude-sonnet-5",
1984                false
1985            ),
1986            "claude-sonnet-5"
1987        );
1988    }
1989
1990    /// Exclusions match the way Go lowercases both sides (`strings.ToLower`, where U+0130
1991    /// becomes a plain `i`): a configured `MİNİ` excluded as `MİNİ` or `mini` is not
1992    /// registered.
1993    #[test]
1994    fn exclusions_match_with_go_lowercasing() {
1995        for excluded in ["MİNİ", "mini"] {
1996            let cfg = Config::parse(&format!(
1997                "claude-api-key:\n  - api-key: k\n    models: [{{name: MİNİ}}, {{name: keep}}]\n    excluded-models: [{excluded}]\n"
1998            ))
1999            .unwrap();
2000            let creds: Vec<_> = crate::config::credentials::from_config(&cfg)
2001                .into_iter()
2002                .map(Arc::new)
2003                .collect();
2004            let r = Registry::build(&cfg, &creds);
2005            assert_eq!(r.ids().collect::<Vec<_>>(), ["keep"], "excluded: {excluded}");
2006        }
2007    }
2008
2009    /// Go `registerModelsForAuth` (tests/reference/provider_key): the key an
2010    /// OpenAI-compatible credential that config synthesis did not build (a Home-dispatched
2011    /// or plugin auth) registers under. Without a `provider_key`, the compat name or else
2012    /// the label gets Go's `openai-compatible-` prefix.
2013    #[test]
2014    fn compat_provider_key_follows_go() {
2015        // DIFFERENCES-FROM-GO.md "Plugins, models of credentials with another provider":
2016        // Go registers these under the `provider_key` (or nothing without a plugin model),
2017        // cliproxy-rs under the provider.
2018        const OTHER_PROVIDER: [&str; 2] = ["unnamed-provider-provider-key", "unmatched-provider-provider-key"];
2019        let go: Value = serde_json::from_str(include_str!("../../tests/fixtures/provider_key_go.json")).unwrap();
2020        for case in go["cases"].as_array().unwrap() {
2021            let attrs: Vec<(&str, &str)> = case["attributes"]
2022                .as_object()
2023                .unwrap()
2024                .iter()
2025                .map(|(k, v)| (k.as_str(), v.as_str().unwrap()))
2026                .collect();
2027            let mut c = (*config(case["provider"].as_str().unwrap(), "zz", serde_json::json!({}), &attrs)).clone();
2028            c.label = case["label"].as_str().unwrap().into();
2029            if OTHER_PROVIDER.contains(&case["name"].as_str().unwrap()) {
2030                assert_eq!(provider_key(&c), case["provider"].as_str().unwrap().go_lower());
2031                continue;
2032            }
2033            assert_eq!(
2034                Value::from(vec![provider_key(&c)]),
2035                case["registered"],
2036                "{}",
2037                case["name"]
2038            );
2039        }
2040    }
2041
2042    /// An openai-compatibility group named `HİGH` registers under Go's lowercased key,
2043    /// and asking for it by its configured name finds its models (Go
2044    /// `GetAvailableModelsByProvider` lowercases with `strings.ToLower`).
2045    #[test]
2046    fn compat_provider_lookup_lowercases_like_go() {
2047        let cfg = Config::parse(
2048            "openai-compatibility:\n  - name: HİGH\n    base-url: http://127.0.0.1:9\n    api-key-entries: [{api-key: k}]\n    models: [{name: m1}]\n",
2049        )
2050        .unwrap();
2051        let creds: Vec<_> = crate::config::credentials::from_config(&cfg)
2052            .into_iter()
2053            .map(Arc::new)
2054            .collect();
2055        assert_eq!(provider_key(&creds[0]), "openai-compatible-high");
2056        let r = Registry::build(&cfg, &creds);
2057        for asked in ["openai-compatible-HİGH", "openai-compatible-high"] {
2058            let ids: Vec<String> = r
2059                .available_by_provider(asked, |_, _| Suspension::None)
2060                .iter()
2061                .map(|m| m.id.clone())
2062                .collect();
2063            assert_eq!(ids, ["m1"], "{asked}");
2064        }
2065    }
2066
2067    /// Go `applyAPIKeyModelAliasWithRouting`: an API key resolves through its
2068    /// `strings.ToLower`-keyed alias table before the `EqualFold` scan, so aliases σ and ς
2069    /// stay distinct; `Σ` lowercases to σ.
2070    #[test]
2071    fn api_key_aliases_use_lowercase_keys_before_fold() {
2072        let cfg = Config::parse(
2073            "claude-api-key:\n  - api-key: k\n    models: [{name: one, alias: σ}, {name: two, alias: ς}]\n",
2074        )
2075        .unwrap();
2076        let c = crate::config::credentials::from_config(&cfg).remove(0);
2077        let upstream = |model: &str| execution_models(&HashMap::new(), &c, model).0;
2078        assert_eq!(upstream("ς"), ["two"]);
2079        assert_eq!(upstream("σ"), ["one"]);
2080        assert_eq!(upstream("Σ(high)"), ["one(high)"]);
2081
2082        // go_lower("İ") is i, which EqualFold("i", "İ") does not match.
2083        let cfg = Config::parse("claude-api-key:\n  - api-key: k\n    models: [{name: one, alias: i}]\n").unwrap();
2084        let c = crate::config::credentials::from_config(&cfg).remove(0);
2085        assert_eq!(execution_models(&HashMap::new(), &c, "İ(high)").0, ["one(high)"]);
2086
2087        // An OpenAI-compatible API key falls back to the table when the EqualFold pool is
2088        // empty.
2089        let cfg = Config::parse(
2090            "openai-compatibility:\n  - name: g\n    base-url: http://127.0.0.1:9\n    api-key-entries: [{api-key: k}]\n    models: [{name: one, alias: i}]\n",
2091        )
2092        .unwrap();
2093        let c = crate::config::credentials::from_config(&cfg).remove(0);
2094        assert!(is_api_key(&c));
2095        assert_eq!(execution_models(&HashMap::new(), &c, "İ(high)").0, ["one(high)"]);
2096        // A single-entry EqualFold pool still wins over the table, which maps σ to the
2097        // name σ here.
2098        let cfg = Config::parse(
2099            "openai-compatibility:\n  - name: g\n    base-url: http://127.0.0.1:9\n    api-key-entries: [{api-key: k}]\n    models: [{name: σ, alias: x}, {name: one, alias: ς}]\n",
2100        )
2101        .unwrap();
2102        let c = crate::config::credentials::from_config(&cfg).remove(0);
2103        assert_eq!(execution_models(&HashMap::new(), &c, "σ").0, ["one"]);
2104        // A keyless compatible credential has no API-key table.
2105        let cfg = Config::parse(
2106            "openai-compatibility:\n  - name: g\n    base-url: http://127.0.0.1:9\n    models: [{name: one, alias: i}]\n",
2107        )
2108        .unwrap();
2109        let c = crate::config::credentials::from_config(&cfg).remove(0);
2110        assert!(!is_api_key(&c));
2111        assert_eq!(execution_models(&HashMap::new(), &c, "İ(high)").0, ["İ(high)"]);
2112    }
2113
2114    /// Go `resolveOAuthModelAliasWithResult`: the credential's own aliases match with
2115    /// `EqualFold`, the global table by `strings.ToLower` key only.
2116    #[test]
2117    fn oauth_aliases_fold_per_credential_and_key_globally() {
2118        let cfg = Config::parse(
2119            "oauth:\n  model-alias:\n    claude:\n      - {name: one, alias: σ}\n      - {name: two, alias: ς}\n      - {name: four, alias: i}\n",
2120        )
2121        .unwrap();
2122        let aliases = global_aliases(&cfg);
2123        let global = file("a.json", serde_json::json!({"type":"claude"}), &[]);
2124        assert_eq!(execution_models(&aliases, &global, "ς").0, ["two"]);
2125        assert_eq!(selection_model(&aliases, &global, "ς"), "two");
2126        assert_eq!(execution_models(&aliases, &global, "σ").0, ["one"]);
2127        let own = file(
2128            "b.json",
2129            serde_json::json!({"type":"claude"}),
2130            &[("model_aliases", r#"[{"name":"three","alias":"σ"}]"#)],
2131        );
2132        assert_eq!(
2133            execution_models(&aliases, &own, "ς").0,
2134            ["three"],
2135            "EqualFold on its own aliases"
2136        );
2137        // go_lower("İ") is i, so the global key matches; EqualFold("i", "İ") is false, so
2138        // the credential's own alias i does not, and resolution falls through to the
2139        // global table.
2140        assert_eq!(execution_models(&aliases, &global, "İ").0, ["four"]);
2141        let own_i = file(
2142            "c.json",
2143            serde_json::json!({"type":"claude"}),
2144            &[("model_aliases", r#"[{"name":"five","alias":"i"}]"#)],
2145        );
2146        assert_eq!(execution_models(&aliases, &own_i, "İ").0, ["four"]);
2147        // A global lowercase miss does not fall back to EqualFold.
2148        let only_sigma = global_aliases(
2149            &Config::parse("oauth:\n  model-alias:\n    claude:\n      - {name: one, alias: σ}\n").unwrap(),
2150        );
2151        assert_eq!(execution_models(&only_sigma, &global, "ς").0, ["ς"]);
2152    }
2153
2154    #[test]
2155    fn config_models_and_force_mapping() {
2156        let cfg = Config::default();
2157        let c = config(
2158            "claude",
2159            "claude:apikey:1",
2160            serde_json::json!({"models":[
2161                {"name":"claude-opus-5","alias":"opus","force-mapping":true,"is-compat":true},
2162                {"name":"claude-sonnet-5","alias":"opus"}]}),
2163            &[],
2164        );
2165        let r = Registry::build(&cfg, std::slice::from_ref(&c));
2166        assert_eq!(
2167            r.ids().collect::<Vec<_>>(),
2168            ["opus"],
2169            "first alias wins, duplicates dropped"
2170        );
2171        let spec = r.client_model("claude:apikey:1", "opus").unwrap();
2172        assert!(spec.is_compat && spec.user_defined);
2173        assert_eq!(spec.owned_by, "anthropic");
2174        assert_eq!(
2175            spec.thinking,
2176            pinned().lookup("claude-opus-5").unwrap().thinking,
2177            "static thinking inherited"
2178        );
2179        let (models, alias) = execution_models(&HashMap::new(), &c, "opus");
2180        assert_eq!(models, ["claude-opus-5"], "non-compat API keys never pool");
2181        assert_eq!(
2182            alias,
2183            AliasResult {
2184                upstream: "claude-opus-5".into(),
2185                force_mapping: true,
2186                original_alias: "opus".into()
2187            }
2188        );
2189        // Unknown models pass through unchanged.
2190        assert_eq!(execution_models(&HashMap::new(), &c, "other").0, ["other"]);
2191    }
2192
2193    #[test]
2194    fn compat_pools_rotate_through_every_name() {
2195        let c = config(
2196            "openai-compatible-pool",
2197            "openai-compatibility:pool:1",
2198            serde_json::json!({"model_aliases":[{"name":"a-1","alias":"fast"},{"name":"a-2","alias":"fast"}]}),
2199            &[("compat_name", "pool"), ("provider_key", "openai-compatible-pool")],
2200        );
2201        let r = Registry::build(&Config::default(), std::slice::from_ref(&c));
2202        assert_eq!(r.providers("fast"), ["openai-compatible-pool"]);
2203        assert_eq!(
2204            r.info("fast", None).unwrap().thinking.as_ref().unwrap().levels,
2205            ["low", "medium", "high"]
2206        );
2207        assert_eq!(execution_models(&HashMap::new(), &c, "fast").0, ["a-1", "a-2"]);
2208    }
2209
2210    #[test]
2211    fn wildcard_matches_go() {
2212        for (p, v, ok) in [
2213            ("a*c", "abc", true),
2214            ("a*c", "ab", false),
2215            ("*", "x", true),
2216            ("a**b", "ab", true),
2217            ("x", "x", true),
2218            ("*mid*", "a-mid-b", true),
2219            ("a*b*c", "acb", false),
2220        ] {
2221            assert_eq!(wildcard(p, v), ok, "{p} {v}");
2222        }
2223    }
2224}