Skip to main content

harn_vm/llm_config/
catalog.rs

1//! Catalog query surface: provider/model lookups, per-role and per-model
2//! parameter defaults, pricing, capability tags, tool-format resolution, and
3//! tier candidate enumeration.
4use std::collections::BTreeMap;
5
6use super::*;
7
8use harn_glob::match_name as glob_match;
9
10const LOGICAL_MODEL_DEFAULT_PREFIX: &str = "logical:";
11const MODEL_DEFAULT_UNSET_KEY: &str = "_unset";
12
13/// True for `[model_defaults."logical:<model>"]` selectors, which name one
14/// exact publisher-level logical model rather than globbing serving routes.
15/// The two selector kinds resolve through different lookups, so every site
16/// that must tell them apart asks here instead of re-testing the prefix.
17pub(crate) fn is_logical_model_selector(selector: &str) -> bool {
18    selector.starts_with(LOGICAL_MODEL_DEFAULT_PREFIX)
19}
20
21/// Get provider config for resolving base_url, auth, etc.
22pub fn provider_config(name: &str) -> Option<ProviderDef> {
23    let mut provider = effective_config().providers.get(name).cloned()?;
24    if let Some(base_url) = runtime_provider_endpoint(name) {
25        // The endpoint was host-verified for this execution. Clear catalog
26        // selectors only on this clone so every transport path resolves the
27        // same endpoint without making runtime state serializable or public.
28        provider.base_url = base_url;
29        provider.base_url_env = None;
30        provider.region_env = None;
31    }
32    Some(provider)
33}
34
35pub fn provider_protocol(name: &str) -> Option<String> {
36    provider_config(name).and_then(|def| def.protocol)
37}
38
39pub fn provider_uses_acp(name: &str) -> bool {
40    provider_protocol(name)
41        .as_deref()
42        .is_some_and(|protocol| protocol.eq_ignore_ascii_case("acp"))
43}
44
45/// Get model-specific default parameters (temperature, etc.).
46/// Matches glob patterns in model_defaults keys.
47pub fn model_params(model_id: &str) -> BTreeMap<String, toml::Value> {
48    let config = effective_config();
49    matching_model_params(&config, model_id)
50}
51
52fn matching_model_params(
53    config: &ProvidersConfig,
54    model_id: &str,
55) -> BTreeMap<String, toml::Value> {
56    let mut params = BTreeMap::new();
57    apply_matching_model_params(config, model_id, &mut params);
58    params
59}
60
61fn apply_matching_model_params(
62    config: &ProvidersConfig,
63    model_id: &str,
64    params: &mut BTreeMap<String, toml::Value>,
65) {
66    for (pattern, defaults) in &config.model_defaults {
67        if !is_logical_model_selector(pattern) && glob_match(pattern, model_id) {
68            apply_model_param_layer(params, defaults);
69        }
70    }
71}
72
73fn apply_model_param_layer(
74    params: &mut BTreeMap<String, toml::Value>,
75    defaults: &BTreeMap<String, toml::Value>,
76) {
77    for (key, value) in defaults {
78        if key != MODEL_DEFAULT_UNSET_KEY {
79            params.insert(key.clone(), value.clone());
80        }
81    }
82    if let Some(keys) = defaults
83        .get(MODEL_DEFAULT_UNSET_KEY)
84        .and_then(toml::Value::as_array)
85    {
86        for key in keys.iter().filter_map(toml::Value::as_str) {
87            params.remove(key);
88        }
89    }
90}
91
92/// Get generation defaults for one concrete serving route.
93///
94/// Publisher/model defaults use an exact `logical:<logical_model>` selector.
95/// Route-id patterns then override them, preserving the existing precedence
96/// where a provider-qualified pattern wins over a bare wire-model pattern.
97pub fn model_params_for_route(provider: &str, model_id: &str) -> BTreeMap<String, toml::Value> {
98    let config = effective_config();
99    model_params_for_route_with_config(&config, provider, model_id)
100}
101
102/// Return the Harn-validated generation defaults that are safe to persist in
103/// an execution receipt.
104///
105/// Route-specific overlays remain intentionally free-form so operators can
106/// configure provider-specific request parameters. Those fields must still
107/// influence inference, but they are not part of Harn's stable, secret-free
108/// receipt contract. Keep this filter beside Harn's generation validator so hosts do
109/// not duplicate the generation-default schema.
110pub fn generation_defaults_for_route(
111    provider: &str,
112    model_id: &str,
113) -> BTreeMap<String, toml::Value> {
114    model_params_for_route(provider, model_id)
115        .into_iter()
116        .filter(|(key, value)| is_valid_generation_default(key, value))
117        .collect()
118}
119
120pub(crate) fn model_params_for_route_with_config(
121    config: &ProvidersConfig,
122    provider: &str,
123    model_id: &str,
124) -> BTreeMap<String, toml::Value> {
125    let normalized_id = normalize_model_id(model_id);
126    let route = config
127        .models
128        .get_key_value(model_id)
129        .filter(|(_, model)| model.provider == provider)
130        .or_else(|| {
131            config
132                .models
133                .get_key_value(&normalized_id)
134                .filter(|(_, model)| model.provider == provider)
135        })
136        .or_else(|| {
137            config.models.iter().find(|(_, model)| {
138                model.provider == provider
139                    && model
140                        .wire_model
141                        .as_deref()
142                        .is_some_and(|wire| wire == model_id || wire == normalized_id.as_str())
143            })
144        });
145
146    let mut params = route
147        .and_then(|(_, model)| model.logical_model.as_deref())
148        .and_then(|logical_model| {
149            config
150                .model_defaults
151                .get(&format!("{LOGICAL_MODEL_DEFAULT_PREFIX}{logical_model}"))
152        })
153        .map(|defaults| {
154            let mut params = BTreeMap::new();
155            apply_model_param_layer(&mut params, defaults);
156            params
157        })
158        .unwrap_or_default();
159
160    let mut identities = vec![model_id.to_string()];
161    if normalized_id != model_id {
162        identities.push(normalized_id);
163    }
164    if let Some((catalog_id, model)) = route {
165        for identity in [Some(catalog_id.as_str()), model.wire_model.as_deref()]
166            .into_iter()
167            .flatten()
168        {
169            if !identities.iter().any(|known| known == identity) {
170                identities.push(identity.to_string());
171            }
172        }
173    }
174    for identity in &identities {
175        apply_matching_model_params(config, identity, &mut params);
176    }
177    let provider_prefix = format!("{provider}/");
178    for identity in identities {
179        if !identity.starts_with(&provider_prefix) {
180            apply_matching_model_params(
181                config,
182                &format!("{provider_prefix}{identity}"),
183                &mut params,
184            );
185        }
186    }
187    params
188}
189
190/// Validate logical-model defaults against catalog identities and route caps.
191/// Route-specific patterns remain intentionally free-form for operator
192/// overrides; `logical:` selectors are publisher-level contracts and must be
193/// exact, typed, and representable by every route that inherits them.
194pub fn model_default_issues(config: &ProvidersConfig) -> Vec<String> {
195    let mut issues = Vec::new();
196    for (selector, defaults) in &config.model_defaults {
197        if let Some(unset) = defaults.get(MODEL_DEFAULT_UNSET_KEY) {
198            let valid = !is_logical_model_selector(selector)
199                && unset.as_array().is_some_and(|keys| {
200                    !keys.is_empty()
201                        && keys.iter().all(|key| {
202                            key.as_str()
203                                .is_some_and(is_supported_generation_default_key)
204                        })
205                });
206            if !valid {
207                issues.push(format!(
208                    "model_defaults.{selector}.{MODEL_DEFAULT_UNSET_KEY} must be a non-empty list of supported route-default keys"
209                ));
210            }
211        }
212        let Some(logical_model) = selector.strip_prefix(LOGICAL_MODEL_DEFAULT_PREFIX) else {
213            continue;
214        };
215        if logical_model.is_empty()
216            || logical_model.contains('*')
217            || logical_model.contains('?')
218            || logical_model.contains('[')
219        {
220            issues.push(format!(
221                "model_defaults.{selector} must name one exact logical model"
222            ));
223            continue;
224        }
225        let routes: Vec<_> = config
226            .models
227            .iter()
228            .filter(|(_, model)| model.logical_model.as_deref() == Some(logical_model))
229            .collect();
230        if routes.is_empty() {
231            issues.push(format!(
232                "model_defaults.{selector} references an unknown logical model"
233            ));
234            continue;
235        }
236
237        for (key, value) in defaults {
238            if key == MODEL_DEFAULT_UNSET_KEY {
239                continue;
240            }
241            if !is_valid_generation_default(key, value) {
242                issues.push(format!(
243                    "model_defaults.{selector}.{key} is not a supported generation default"
244                ));
245                continue;
246            }
247
248            for (model_id, model) in &routes {
249                let caps = crate::llm::capabilities::lookup_with_user_overrides(
250                    &model.provider,
251                    model_id,
252                    None,
253                );
254                let supported = match key.as_str() {
255                    "temperature" => caps.temperature_supported,
256                    "top_p" => caps.top_p_supported,
257                    "top_k" => caps.top_k_supported,
258                    "frequency_penalty" => caps.frequency_penalty_supported,
259                    "presence_penalty" => caps.presence_penalty_supported,
260                    "reasoning_effort" => {
261                        let effort = value.as_str().expect("validated effort string");
262                        caps.reasoning_effort_supported
263                            && caps.thinking_modes.iter().any(|mode| mode == "effort")
264                            && (caps.reasoning_effort_levels.is_empty()
265                                || caps
266                                    .reasoning_effort_levels
267                                    .iter()
268                                    .any(|level| level == effort))
269                    }
270                    "max_tokens" => true,
271                    _ => false,
272                };
273                let effective =
274                    model_params_for_route_with_config(config, &model.provider, model_id);
275                if !supported && effective.contains_key(key) {
276                    issues.push(format!(
277                        "model_defaults.{selector}.{key} cannot be represented by route {}:{}",
278                        model.provider, model_id
279                    ));
280                }
281            }
282        }
283    }
284    issues
285}
286
287fn is_supported_generation_default_key(key: &str) -> bool {
288    matches!(
289        key,
290        "temperature"
291            | "top_p"
292            | "top_k"
293            | "frequency_penalty"
294            | "presence_penalty"
295            | "max_tokens"
296            | "reasoning_effort"
297    )
298}
299
300fn is_valid_generation_default(key: &str, value: &toml::Value) -> bool {
301    match key {
302        "temperature" => value
303            .as_float()
304            .is_some_and(|value| value.is_finite() && (0.0..=2.0).contains(&value)),
305        "frequency_penalty" | "presence_penalty" => value
306            .as_float()
307            .is_some_and(|value| value.is_finite() && (-2.0..=2.0).contains(&value)),
308        "top_p" => value
309            .as_float()
310            .is_some_and(|value| value.is_finite() && (0.0..=1.0).contains(&value)),
311        "top_k" => value.as_integer().is_some_and(|value| value >= 0),
312        "max_tokens" => value.as_integer().is_some_and(|value| value > 0),
313        "reasoning_effort" => value.as_str().is_some_and(|value| {
314            matches!(
315                value,
316                "none" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max"
317            )
318        }),
319        _ => false,
320    }
321}
322
323/// Get per-role LLM defaults, e.g. `[model_roles.merge]`.
324///
325/// Role defaults are intentionally shaped like ordinary `llm_call` options:
326/// callers can pin `provider`/`model`, install `route_policy` or `prefer`,
327/// and tune budget/latency knobs without creating a parallel routing stack.
328/// Environment variables provide a lightweight operational override for
329/// merge/fast-apply workers:
330///
331/// - `HARN_LLM_MERGE_PROVIDER`, `HARN_LLM_MERGE_MODEL`,
332///   `HARN_LLM_MERGE_ROUTE_POLICY`
333/// - `HARN_LLM_FAST_APPLY_PROVIDER`, `HARN_LLM_FAST_APPLY_MODEL`,
334///   `HARN_LLM_FAST_APPLY_ROUTE_POLICY`
335/// - `HARN_LLM_ROLE_<ROLE>_PROVIDER`, `_MODEL`, `_ROUTE_POLICY`
336pub fn model_role_defaults(role: &str) -> BTreeMap<String, toml::Value> {
337    let normalized = normalize_model_role_name(role);
338    if normalized.is_empty() {
339        return BTreeMap::new();
340    }
341    let config = effective_config();
342    let mut params = BTreeMap::new();
343    for key in role_lookup_keys(&normalized) {
344        extend_model_role_defaults(&config, &key, &mut params);
345    }
346    apply_model_role_env_overrides(&normalized, &mut params);
347    params
348}
349
350fn extend_model_role_defaults(
351    config: &ProvidersConfig,
352    role: &str,
353    params: &mut BTreeMap<String, toml::Value>,
354) {
355    for (configured_role, defaults) in &config.model_roles {
356        if normalize_model_role_name(configured_role) == role {
357            params.extend(defaults.clone());
358        }
359    }
360    if let Some(defaults) = config.model_roles.get(role) {
361        params.extend(defaults.clone());
362    }
363}
364
365fn normalize_model_role_name(role: &str) -> String {
366    role.trim().to_ascii_lowercase().replace('-', "_")
367}
368
369fn role_lookup_keys(role: &str) -> Vec<String> {
370    if role == "merge" {
371        vec!["fast_apply".to_string(), "merge".to_string()]
372    } else if role == "fast_apply" {
373        vec!["merge".to_string(), "fast_apply".to_string()]
374    } else {
375        vec![role.to_string()]
376    }
377}
378
379fn role_env_token(role: &str) -> String {
380    role.chars()
381        .map(|ch| {
382            if ch.is_ascii_alphanumeric() {
383                ch.to_ascii_uppercase()
384            } else {
385                '_'
386            }
387        })
388        .collect::<String>()
389        .split('_')
390        .filter(|part| !part.is_empty())
391        .collect::<Vec<_>>()
392        .join("_")
393}
394
395fn apply_model_role_env_overrides(role: &str, params: &mut BTreeMap<String, toml::Value>) {
396    for alias in role_env_aliases(role) {
397        apply_model_role_env_var(&format!("HARN_LLM_{alias}_PROVIDER"), "provider", params);
398        apply_model_role_env_var(&format!("HARN_LLM_{alias}_MODEL"), "model", params);
399        apply_model_role_env_var(
400            &format!("HARN_LLM_{alias}_ROUTE_POLICY"),
401            "route_policy",
402            params,
403        );
404        apply_model_role_env_var(
405            &format!("HARN_LLM_ROLE_{alias}_PROVIDER"),
406            "provider",
407            params,
408        );
409        apply_model_role_env_var(&format!("HARN_LLM_ROLE_{alias}_MODEL"), "model", params);
410        apply_model_role_env_var(
411            &format!("HARN_LLM_ROLE_{alias}_ROUTE_POLICY"),
412            "route_policy",
413            params,
414        );
415    }
416}
417
418fn role_env_aliases(role: &str) -> Vec<String> {
419    let token = role_env_token(role);
420    if token.is_empty() {
421        return Vec::new();
422    }
423    if token == "MERGE" {
424        vec!["FAST_APPLY".to_string(), "MERGE".to_string()]
425    } else if token == "FAST_APPLY" {
426        vec!["MERGE".to_string(), "FAST_APPLY".to_string()]
427    } else {
428        vec![token]
429    }
430}
431
432fn apply_model_role_env_var(
433    env_name: &str,
434    option_name: &str,
435    params: &mut BTreeMap<String, toml::Value>,
436) {
437    let Ok(Some(value)) = crate::stdlib::process::session_env_var(env_name) else {
438        return;
439    };
440    let trimmed = value.trim();
441    if trimmed.is_empty() {
442        return;
443    }
444    params.insert(
445        option_name.to_string(),
446        toml::Value::String(trimmed.to_string()),
447    );
448}
449
450/// Get list of configured provider names.
451pub fn provider_names() -> Vec<String> {
452    effective_config().providers.keys().cloned().collect()
453}
454
455/// Return every configured alias name, sorted deterministically.
456pub fn known_model_names() -> Vec<String> {
457    effective_config().aliases.keys().cloned().collect()
458}
459
460pub fn alias_entries() -> Vec<(String, AliasDef)> {
461    effective_config()
462        .aliases
463        .iter()
464        .map(|(name, alias)| (name.clone(), alias.clone()))
465        .collect()
466}
467
468pub fn alias_tool_calling_entry(alias: &str) -> Option<AliasToolCallingDef> {
469    effective_config().alias_tool_calling.get(alias).cloned()
470}
471
472/// Return every configured model-catalog entry, sorted by provider then id.
473pub fn model_catalog_entries() -> Vec<(String, ModelDef)> {
474    let config = effective_config();
475    model_catalog_entries_with_config(&config)
476}
477
478pub(crate) fn model_catalog_entries_with_config(
479    config: &ProvidersConfig,
480) -> Vec<(String, ModelDef)> {
481    sorted_model_entries_with_config(config)
482        .into_iter()
483        .map(|(id, model)| {
484            let provider = model.provider.clone();
485            (
486                id.clone(),
487                with_effective_capability_tags(id, provider, model),
488            )
489        })
490        .collect()
491}
492
493pub(crate) fn sorted_model_entries_with_config(
494    config: &ProvidersConfig,
495) -> Vec<(String, ModelDef)> {
496    let mut entries: Vec<_> = config
497        .models
498        .iter()
499        .map(|(id, model)| (id.clone(), model.clone()))
500        .collect();
501    entries.sort_by(|(id_a, model_a), (id_b, model_b)| {
502        model_a
503            .provider
504            .cmp(&model_b.provider)
505            .then_with(|| id_a.cmp(id_b))
506    });
507    entries
508}
509
510pub fn model_catalog_entry(model_id: &str) -> Option<ModelDef> {
511    effective_config()
512        .models
513        .get(model_id)
514        .cloned()
515        .map(|model| {
516            let provider = model.provider.clone();
517            with_effective_capability_tags(model_id.to_string(), provider, model)
518        })
519}
520
521/// Return the collision-free catalog id for one concrete provider route.
522///
523/// Runtime transports use `wire_model`, while pricing and other catalog
524/// metadata are keyed by the authored catalog id. Resolve either identity
525/// without allowing an identically named model from another provider to win.
526pub fn model_catalog_id_for_route(provider: &str, model_id: &str) -> Option<String> {
527    let config = effective_config();
528    let normalized_id = normalize_model_id(model_id);
529    config
530        .models
531        .get_key_value(model_id)
532        .filter(|(_, model)| model.provider == provider)
533        .or_else(|| {
534            config
535                .models
536                .get_key_value(&normalized_id)
537                .filter(|(_, model)| model.provider == provider)
538        })
539        .or_else(|| {
540            config.models.iter().find(|(_, model)| {
541                model.provider == provider
542                    && model
543                        .wire_model
544                        .as_deref()
545                        .is_some_and(|wire| wire == model_id || wire == normalized_id.as_str())
546            })
547        })
548        .map(|(id, _)| id.clone())
549}
550
551pub fn model_rate_limits(model_id: &str) -> Option<RateLimitsDef> {
552    model_catalog_entry(model_id).and_then(|model| model.rate_limits)
553}
554
555/// Resolve a named model ladder declared under `[model_ladders.<name>]`.
556/// Returns `None` when no ladder with that name exists in the effective
557/// (base + overlay) catalog.
558pub fn model_ladder(name: &str) -> Option<ModelLadderDef> {
559    effective_config().model_ladders.get(name).cloned()
560}
561
562/// Sorted names of every declared model ladder — used to build a helpful
563/// "did you mean" error when a `ladder:` option names an unknown ladder.
564pub fn model_ladder_names() -> Vec<String> {
565    effective_config().model_ladders.keys().cloned().collect()
566}
567
568pub fn wire_model_id(model_id: &str) -> String {
569    model_catalog_entry(model_id)
570        .and_then(|model| model.wire_model)
571        .unwrap_or_else(|| model_id.to_string())
572}
573
574/// Resolve the model identity used by the capability matrix for one concrete
575/// provider route without deriving capability tags (which would recurse back
576/// into capability lookup). Collision-free catalog ids may differ from the
577/// upstream creator/model slug that provider-family rules match.
578pub(crate) fn capability_model_id(provider: &str, model_id: &str) -> String {
579    if !provider_has_feature(provider, "wire_model_capabilities") {
580        return model_id.to_string();
581    }
582    effective_config()
583        .models
584        .get(model_id)
585        .filter(|model| model.provider == provider)
586        .and_then(|model| model.wire_model.clone())
587        .unwrap_or_else(|| model_id.to_string())
588}
589
590pub fn provider_rate_limits(provider: &str) -> Option<RateLimitsDef> {
591    provider_config(provider).and_then(|provider| {
592        provider
593            .rate_limits
594            .unwrap_or_default()
595            .with_rpm_fallback(provider.rpm)
596    })
597}
598
599pub fn model_equivalence_group(model_id: &str) -> Option<String> {
600    model_catalog_entry(model_id).and_then(|model| {
601        model
602            .equivalence_group
603            .or(model.logical_model)
604            .filter(|group| !group.trim().is_empty())
605    })
606}
607
608#[derive(Clone, Debug, Default, PartialEq, Eq)]
609pub struct EquivalentModelRequirements {
610    pub context_tokens: Option<u64>,
611    pub native_tools: bool,
612    pub text_tool_wire_format: bool,
613    pub provider_tool_types: Vec<String>,
614    pub vision: bool,
615    pub url_images: bool,
616    pub audio: bool,
617    pub pdf: bool,
618    pub video: bool,
619    pub files_api: bool,
620    pub thinking: bool,
621    pub reasoning_effort: bool,
622    pub structured_output: bool,
623    pub structured_output_mode: Option<String>,
624}
625
626impl EquivalentModelRequirements {
627    fn from_source_context(
628        context_tokens: u64,
629        caps: &crate::llm::capabilities::Capabilities,
630    ) -> Self {
631        Self {
632            context_tokens: Some(context_tokens),
633            native_tools: caps.native_tools,
634            text_tool_wire_format: caps.text_tool_wire_format_supported,
635            provider_tool_types: equivalent_provider_tool_types_for_capabilities(caps),
636            vision: caps.vision_supported,
637            url_images: caps.image_url_input_supported,
638            audio: caps.audio,
639            pdf: caps.pdf,
640            video: caps.video,
641            files_api: caps.files_api_supported,
642            thinking: !caps.thinking_modes.is_empty(),
643            reasoning_effort: caps.reasoning_effort_supported,
644            structured_output: caps.structured_output.is_some(),
645            structured_output_mode: Some(caps.structured_output_mode.clone()),
646        }
647    }
648}
649
650fn equivalent_provider_tool_types_for_capabilities(
651    caps: &crate::llm::capabilities::Capabilities,
652) -> Vec<String> {
653    let mut kinds = caps.hosted_tools.clone();
654    if caps.computer_use_style.is_some() {
655        kinds.push("computer_use".to_string());
656    }
657    kinds.sort();
658    kinds.dedup();
659    kinds
660}
661
662fn provider_tool_type_matches(
663    caps: &crate::llm::capabilities::Capabilities,
664    required: &str,
665) -> bool {
666    if required == "computer_use" && caps.computer_use_style.is_some() {
667        return true;
668    }
669    caps.hosted_tools
670        .iter()
671        .any(|kind| kind == required || (required == "computer_use" && kind == "computer"))
672}
673
674/// Return same-logical-model routes that can be considered for explicit
675/// failover or cross-provider experiments. Equivalence is a catalog assertion
676/// about compatible model weights/family, not wire-level identity.
677pub fn equivalent_model_catalog_entries_for_requirements(
678    selector: &str,
679    requirements: EquivalentModelRequirements,
680) -> Vec<(String, ModelDef)> {
681    let resolved = resolve_model_info(selector);
682    let Some(group) = model_equivalence_group(&resolved.id) else {
683        return Vec::new();
684    };
685    let config = effective_config();
686    let Some(source) = config.models.get(&resolved.id) else {
687        return Vec::new();
688    };
689    let source_context = source
690        .runtime_context_window
691        .unwrap_or(source.context_window);
692    let minimum_context = requirements.context_tokens.unwrap_or(source_context);
693
694    sorted_model_entries_with_config(&config)
695        .into_iter()
696        .filter(|(id, model)| !(id == &resolved.id && model.provider == resolved.provider))
697        .filter(|(_, model)| !model.deprecated)
698        .filter(|(_, model)| model.availability != ModelAvailability::Dedicated)
699        .filter(|(_, model)| {
700            model.equivalence_group.as_deref() == Some(group.as_str())
701                || model.logical_model.as_deref() == Some(group.as_str())
702        })
703        .filter(|(id, model)| {
704            let caps = crate::llm::capabilities::lookup(&model.provider, id);
705            let candidate_context = model.runtime_context_window.unwrap_or(model.context_window);
706            let context_matches = candidate_context >= minimum_context;
707            let native_tools_match = !requirements.native_tools || caps.native_tools;
708            let text_tool_format_match =
709                !requirements.text_tool_wire_format || caps.text_tool_wire_format_supported;
710            let provider_tools_match = requirements
711                .provider_tool_types
712                .iter()
713                .all(|required| provider_tool_type_matches(&caps, required));
714            let vision_match = !requirements.vision || caps.vision_supported;
715            let url_images_match = !requirements.url_images
716                || crate::llm::provider::provider_supports_image_urls(&model.provider, id);
717            let audio_match = !requirements.audio || caps.audio;
718            let pdf_match = !requirements.pdf || caps.pdf;
719            let video_match = !requirements.video || caps.video;
720            let files_api_match = !requirements.files_api || caps.files_api_supported;
721            let thinking_match = !requirements.thinking || !caps.thinking_modes.is_empty();
722            let reasoning_effort_match =
723                !requirements.reasoning_effort || caps.reasoning_effort_supported;
724            let structured_output_match =
725                !requirements.structured_output || caps.structured_output.is_some();
726            let structured_output_mode_match = requirements
727                .structured_output_mode
728                .as_ref()
729                .is_none_or(|mode| mode == &caps.structured_output_mode);
730            context_matches
731                && native_tools_match
732                && text_tool_format_match
733                && provider_tools_match
734                && vision_match
735                && url_images_match
736                && audio_match
737                && pdf_match
738                && video_match
739                && files_api_match
740                && thinking_match
741                && reasoning_effort_match
742                && structured_output_match
743                && structured_output_mode_match
744        })
745        .map(|(id, model)| {
746            let provider = model.provider.clone();
747            (
748                id.clone(),
749                with_effective_capability_tags(id, provider, model),
750            )
751        })
752        .collect()
753}
754
755/// Request-shaped equivalent routes: constrain the context window but only
756/// require capabilities the current call actually resolved to use.
757pub fn equivalent_model_catalog_entries_for_context(
758    selector: &str,
759    required_context_tokens: Option<u64>,
760) -> Vec<(String, ModelDef)> {
761    equivalent_model_catalog_entries_for_requirements(
762        selector,
763        EquivalentModelRequirements {
764            context_tokens: required_context_tokens,
765            ..EquivalentModelRequirements::default()
766        },
767    )
768}
769
770pub fn equivalent_model_catalog_entries(selector: &str) -> Vec<(String, ModelDef)> {
771    let resolved = resolve_model_info(selector);
772    let config = effective_config();
773    let Some(source) = config.models.get(&resolved.id) else {
774        return Vec::new();
775    };
776    let source_caps = crate::llm::capabilities::lookup(&source.provider, &resolved.id);
777    let source_context = source
778        .runtime_context_window
779        .unwrap_or(source.context_window);
780    equivalent_model_catalog_entries_for_requirements(
781        selector,
782        EquivalentModelRequirements::from_source_context(source_context, &source_caps),
783    )
784}
785
786pub fn qc_default_model(provider: &str) -> Option<String> {
787    crate::stdlib::process::session_env_var("BURIN_QC_MODEL")
788        .ok()
789        .flatten()
790        .filter(|value| !value.trim().is_empty())
791        .or_else(|| {
792            effective_config()
793                .qc_defaults
794                .get(&provider.to_lowercase())
795                .cloned()
796        })
797}
798
799pub fn default_model_for_provider(provider: &str) -> String {
800    if provider_uses_acp(provider) {
801        return "default".to_string();
802    }
803    match provider {
804        "local" => crate::stdlib::process::session_env_value("LOCAL_LLM_MODEL")
805            .or_else(|| crate::stdlib::process::session_env_value("HARN_LLM_MODEL"))
806            .unwrap_or_else(|| "gemma-4-26b-a4b-it".to_string()),
807        "mlx" => crate::stdlib::process::session_env_var("MLX_MODEL_ID")
808            .ok()
809            .flatten()
810            .unwrap_or_else(|| "unsloth/Qwen3.6-35B-A3B-UD-MLX-4bit".to_string()),
811        "openai" => "gpt-4o-mini".to_string(),
812        "ollama" => "llama3.2".to_string(),
813        "openrouter" => "anthropic/claude-sonnet-4.6".to_string(),
814        _ => "claude-sonnet-4-6".to_string(),
815    }
816}
817
818pub fn qc_defaults() -> BTreeMap<String, String> {
819    effective_config().qc_defaults.clone()
820}
821
822pub fn model_pricing_per_mtok(model_id: &str) -> Option<ModelPricing> {
823    effective_config()
824        .models
825        .get(model_id)
826        .and_then(|model| model.pricing.clone())
827}
828
829pub fn model_pricing_per_mtok_for_route(provider: &str, model_id: &str) -> Option<ModelPricing> {
830    let catalog_id = model_catalog_id_for_route(provider, model_id)?;
831    model_pricing_per_mtok(&catalog_id)
832}
833
834/// Per-MTok whole-request pricing selected for the provider-reported input
835/// usage. Models without input-token bands retain their base rates.
836pub fn model_pricing_for_input_tokens(model_id: &str, input_tokens: i64) -> Option<ModelPricing> {
837    model_pricing_per_mtok(model_id).map(|pricing| pricing.for_input_tokens(input_tokens))
838}
839
840pub fn model_pricing_for_route_input_tokens(
841    provider: &str,
842    model_id: &str,
843    input_tokens: i64,
844) -> Option<ModelPricing> {
845    model_pricing_per_mtok_for_route(provider, model_id)
846        .map(|pricing| pricing.for_input_tokens(input_tokens))
847}
848
849/// Per-MTok pricing for a named serving tier, when the catalog declares one.
850/// Returns `None` for models with no matching tier or a tier that omits
851/// explicit pricing — callers fall back to standard pricing in that case.
852pub fn model_serving_tier_pricing_per_mtok(model_id: &str, tier_id: &str) -> Option<ModelPricing> {
853    effective_config()
854        .models
855        .get(model_id)
856        .and_then(|model| model.serving_tiers.iter().find(|tier| tier.id == tier_id))
857        .and_then(|tier| tier.pricing.clone())
858}
859
860pub fn model_serving_tier_pricing_per_mtok_for_route(
861    provider: &str,
862    model_id: &str,
863    tier_id: &str,
864) -> Option<ModelPricing> {
865    let catalog_id = model_catalog_id_for_route(provider, model_id)?;
866    model_serving_tier_pricing_per_mtok(&catalog_id, tier_id)
867}
868
869pub fn pricing_per_1k_for(provider: &str, model_id: &str) -> Option<(f64, f64)> {
870    model_pricing_per_mtok_for_route(provider, model_id)
871        .map(|pricing| {
872            (
873                pricing.input_per_mtok / 1000.0,
874                pricing.output_per_mtok / 1000.0,
875            )
876        })
877        .or_else(|| {
878            let (input, output, _) = provider_economics(provider);
879            match (input, output) {
880                (Some(input), Some(output)) => Some((input, output)),
881                _ => None,
882            }
883        })
884}
885
886pub fn auth_env_names(auth_env: &AuthEnv) -> Vec<String> {
887    match auth_env {
888        AuthEnv::None => Vec::new(),
889        AuthEnv::Single(name) => vec![name.clone()],
890        AuthEnv::Multiple(names) => names.clone(),
891    }
892}
893
894/// Check if a provider advertises a legacy provider-level feature.
895pub fn provider_has_feature(provider: &str, feature: &str) -> bool {
896    provider_config(provider)
897        .map(|p| p.features.iter().any(|f| f == feature))
898        .unwrap_or(false)
899}
900
901/// Provider-level catalog pricing/latency. Model-specific catalog pricing
902/// wins when available; this is the adapter-level fallback used by routing
903/// and portal summaries when a model has no explicit catalog entry.
904pub fn provider_economics(provider: &str) -> (Option<f64>, Option<f64>, Option<u64>) {
905    provider_config(provider)
906        .map(|p| (p.cost_per_1k_in, p.cost_per_1k_out, p.latency_p50_ms))
907        .unwrap_or((None, None, None))
908}
909
910/// The tool-call channel a `tool_format` string addresses.
911///
912/// `native` is the provider JSON tool-calling channel; `text` (the canonical
913/// tagged/heredoc grammar) and `json` (fenced-JSON) are both TEXT-channel
914/// formats — they ride in the assistant's visible content and parse with a
915/// text parser. This is the single source of truth for "is this format a
916/// text-channel format?" so the parity gates, native-tools resolution, and
917/// tool-result message role all agree.
918#[derive(Debug, Clone, Copy, PartialEq, Eq)]
919pub enum ToolFormatChannel {
920    /// Provider native JSON tool calling.
921    Native,
922    /// A text-channel grammar carried in assistant content (`text` or `json`).
923    Text,
924}
925
926/// Classify a `tool_format` string into its channel, or `None` for an unknown
927/// value (a typo, or a not-yet-wired format). Callers use this to reject
928/// unknown formats loudly instead of silently defaulting.
929///
930/// EXHAUSTIVE-MATCH GUARD: this `match` is the canonical place tool_format is
931/// switched. Adding a new format requires a branch here, so a half-wired
932/// format fails to compile rather than silently reading as text.
933pub fn tool_format_channel(format: &str) -> Option<ToolFormatChannel> {
934    match format {
935        "native" => Some(ToolFormatChannel::Native),
936        // `adaptive` is an opt-in permissive text-channel union (DEFAULT-OFF:
937        // no route resolves to it; reachable only via an explicit pin/request).
938        "text" | "json" | "adaptive" => Some(ToolFormatChannel::Text),
939        _ => None,
940    }
941}
942
943/// True when `format` is a tool_format Harn understands (`native`, `text`, or
944/// `json`). Used to gate the capability-matrix `preferred_tool_format` so a
945/// pinned format is honored, while an unknown value falls through to the
946/// native/text heuristic.
947pub fn is_known_tool_format(format: &str) -> bool {
948    tool_format_channel(format).is_some()
949}
950
951/// Resolve the default tool format for a model+provider combination.
952/// Priority: alias `tool_format` (matched by model ID) > pinned empirical
953/// fitness > provider/model capability matrix > legacy provider feature >
954/// "json" (the global text-channel default; heredoc "text" is opt-in via a
955/// pin or explicit request).
956pub fn default_tool_format(model: &str, provider: &str) -> String {
957    let config = effective_config();
958    default_tool_format_with_config(&config, model, provider)
959}
960
961pub(crate) fn default_tool_format_with_config(
962    config: &ProvidersConfig,
963    model: &str,
964    provider: &str,
965) -> String {
966    default_tool_format_with_config_and_fitness(
967        config,
968        model,
969        provider,
970        crate::llm::tool_scorecard::pinned_tool_format(provider, model),
971    )
972}
973
974pub(crate) fn default_tool_format_with_config_and_fitness(
975    config: &ProvidersConfig,
976    model: &str,
977    provider: &str,
978    measured_format: Option<String>,
979) -> String {
980    // Aliases match by model ID + provider, or by alias name.
981    for (name, alias) in &config.aliases {
982        let matches = (alias.id == model && alias.provider == provider) || name == model;
983        if matches {
984            if let Some(ref fmt) = alias.tool_format {
985                return fmt.clone();
986            }
987        }
988    }
989    if let Some(format) =
990        measured_format.filter(|format| matches!(format.as_str(), "native" | "json" | "text"))
991    {
992        return format;
993    }
994    let capabilities = crate::llm::capabilities::lookup(provider, model);
995    if let Some(format) = capabilities.preferred_tool_format.as_deref() {
996        // A capability row may pin any known tool_format, including `text`
997        // (heredoc) — the reverse safety valve a regressing model uses to pin
998        // OFF the global json default. `json` is also honored when a row sets
999        // it. The exhaustive match below is the EXHAUSTIVE-MATCH GUARD: a new
1000        // tool_format that isn't classified here fails loudly rather than
1001        // silently falling through to the native/json heuristic.
1002        if is_known_tool_format(format) {
1003            return format.to_string();
1004        }
1005    }
1006    let capability_matrix_native = capabilities.native_tools;
1007    let legacy_provider_native = config
1008        .providers
1009        .get(provider)
1010        .map(|p| p.features.iter().any(|f| f == "native_tools"))
1011        .unwrap_or(false);
1012    if capability_matrix_native || legacy_provider_native {
1013        "native".to_string()
1014    } else {
1015        // GLOBAL DEFAULT: a text-channel model with no pinned format resolves
1016        // to fenced-json (`json`), not heredoc (`text`). The win is STRUCTURAL
1017        // — a JSON string can't carry a raw newline, so a `<<EOF` content
1018        // delimiter never collides with the call wrapper (heredoc's known
1019        // production defect: models leak `<<EOF` into file content → the
1020        // `line 0: <<` thrash). Fenced-json swept a clean 1.0/1.0/1.0
1021        // (compliance/parse-determinism/expressiveness) across every model
1022        // measured, and the structural guarantee generalizes to unmeasured
1023        // models. Heredoc (`text`) stays selectable explicitly and via a
1024        // per-model `preferred_tool_format = "text"` pin (the reverse valve).
1025        "json".to_string()
1026    }
1027}
1028
1029fn with_effective_capability_tags(
1030    model_id: String,
1031    provider: String,
1032    mut model: ModelDef,
1033) -> ModelDef {
1034    model.capabilities = effective_model_capability_tags(&provider, &model_id);
1035    model
1036}
1037
1038/// Legacy display tags derived from the canonical provider/model capability
1039/// matrix. The matrix is the source of truth; `models.*.capabilities` in
1040/// providers.toml is accepted only for backwards-compatible parsing.
1041pub fn effective_model_capability_tags(provider: &str, model_id: &str) -> Vec<String> {
1042    let caps = crate::llm::capabilities::lookup(provider, model_id);
1043    let mut tags = capability_tags_from_capabilities(&caps);
1044    if effective_batch_api_supported(provider, &caps) && !tags.iter().any(|tag| tag == "batch") {
1045        tags.push("batch".to_string());
1046    }
1047    tags
1048}
1049
1050pub fn effective_batch_api_supported(
1051    provider: &str,
1052    caps: &crate::llm::capabilities::Capabilities,
1053) -> bool {
1054    caps.batch_api || provider_has_feature(provider, "batch")
1055}
1056
1057pub(crate) fn capability_tags_from_capabilities(
1058    caps: &crate::llm::capabilities::Capabilities,
1059) -> Vec<String> {
1060    let mut tags = Vec::new();
1061    // Today all Harn chat providers expose streaming. Keep this as a
1062    // transport baseline rather than a duplicated per-model declaration.
1063    tags.push("streaming".to_string());
1064    if caps.native_tools || caps.text_tool_wire_format_supported {
1065        tags.push("tools".to_string());
1066    }
1067    if !caps.tool_search.is_empty() {
1068        tags.push("tool_search".to_string());
1069    }
1070    if caps.vision || caps.vision_supported {
1071        tags.push("vision".to_string());
1072    }
1073    if caps.audio {
1074        tags.push("audio".to_string());
1075    }
1076    if caps.pdf {
1077        tags.push("pdf".to_string());
1078    }
1079    if caps.video {
1080        tags.push("video".to_string());
1081    }
1082    if caps.files_api_supported {
1083        tags.push("files".to_string());
1084    }
1085    if caps.batch_api {
1086        tags.push("batch".to_string());
1087    }
1088    if caps.prompt_caching {
1089        tags.push("prompt_caching".to_string());
1090    }
1091    if !caps.thinking_modes.is_empty() {
1092        tags.push("thinking".to_string());
1093    }
1094    if caps.interleaved_thinking_supported
1095        || caps
1096            .thinking_modes
1097            .iter()
1098            .any(|mode| mode == "adaptive" || mode == "effort")
1099    {
1100        tags.push("extended_thinking".to_string());
1101    }
1102    if caps.structured_output.is_some() || caps.json_schema.is_some() {
1103        tags.push("structured_output".to_string());
1104    }
1105    tags
1106}
1107
1108/// Resolve a tier or alias into a concrete model/provider pair.
1109pub fn resolve_tier_model(
1110    target: &str,
1111    preferred_provider: Option<&str>,
1112) -> Option<(String, String)> {
1113    let config = effective_config();
1114
1115    let candidate_aliases = if let Some(provider) = preferred_provider {
1116        vec![
1117            format!("{provider}/{target}"),
1118            format!("{provider}:{target}"),
1119            format!("tier/{target}"),
1120            target.to_string(),
1121        ]
1122    } else {
1123        vec![format!("tier/{target}"), target.to_string()]
1124    };
1125
1126    for alias_name in candidate_aliases {
1127        if let Some(alias) = config.aliases.get(&alias_name) {
1128            return Some((alias.id.clone(), alias.provider.clone()));
1129        }
1130    }
1131
1132    None
1133}
1134
1135/// Return all configured alias-backed model/provider pairs whose resolved
1136/// model falls into the requested capability tier. The result is de-duplicated
1137/// and sorted deterministically by provider then model id.
1138pub fn tier_candidates(target: &str) -> Vec<(String, String)> {
1139    let config = effective_config();
1140    let mut seen = std::collections::BTreeSet::new();
1141    let mut candidates = Vec::new();
1142
1143    for alias in config.aliases.values() {
1144        let pair = (alias.id.clone(), alias.provider.clone());
1145        if seen.contains(&pair) {
1146            continue;
1147        }
1148        if model_tier(&alias.id) == target {
1149            seen.insert(pair.clone());
1150            candidates.push(pair);
1151        }
1152    }
1153
1154    candidates.sort_by(|(model_a, provider_a), (model_b, provider_b)| {
1155        provider_a
1156            .cmp(provider_b)
1157            .then_with(|| model_a.cmp(model_b))
1158    });
1159    candidates
1160}
1161
1162/// Return all configured alias-backed model/provider pairs. Used by routing
1163/// policies that need to compare alternatives across tiers.
1164pub fn all_model_candidates() -> Vec<(String, String)> {
1165    let config = effective_config();
1166    let mut seen = std::collections::BTreeSet::new();
1167    let mut candidates = Vec::new();
1168
1169    for alias in config.aliases.values() {
1170        let pair = (alias.id.clone(), alias.provider.clone());
1171        if seen.insert(pair.clone()) {
1172            candidates.push(pair);
1173        }
1174    }
1175
1176    candidates.sort_by(|(model_a, provider_a), (model_b, provider_b)| {
1177        provider_a
1178            .cmp(provider_b)
1179            .then_with(|| model_a.cmp(model_b))
1180    });
1181    candidates
1182}