Skip to main content

mars_schema/
alias.rs

1//! A `[models.<alias>]` table of `mars.toml`: how an alias names a model, and the pure
2//! resolution of it over models.dev rows.
3//!
4//! Two kinds: a pinned alias names a model id (with optional `match`/`exclude` filters that
5//! widen what it accepts), an `auto` alias selects from the catalog by `match`, `exclude` and
6//! `provider`. Resolution is `models::auto_resolve_all`, so the CLI's snapshot and a host's rows
7//! choose the same id.
8
9use indexmap::IndexMap;
10use serde::{Deserialize, Serialize};
11
12use crate::agent::EffortRequest;
13use crate::models::{CachedModel, auto_resolve_all, infer_provider_from_model_id};
14
15#[derive(Debug, Clone, PartialEq, Serialize)]
16pub struct ModelAlias {
17    #[serde(skip_serializing_if = "Option::is_none")]
18    pub harness: Option<String>,
19    #[serde(skip_serializing_if = "Option::is_none")]
20    pub description: Option<String>,
21    #[serde(skip_serializing_if = "Option::is_none")]
22    pub prompting: Option<String>,
23    #[serde(skip_serializing_if = "Option::is_none")]
24    pub note: Option<String>,
25    #[serde(skip_serializing_if = "Option::is_none")]
26    pub default_effort: Option<EffortRequest>,
27    #[serde(skip_serializing_if = "Option::is_none")]
28    pub autocompact: Option<u32>,
29    #[serde(skip_serializing_if = "Option::is_none")]
30    pub autocompact_pct: Option<u8>,
31    #[serde(flatten)]
32    pub spec: ModelSpec,
33}
34
35impl ModelAlias {
36    pub fn pinned_model_id(&self) -> Option<&str> {
37        match &self.spec {
38            ModelSpec::Pinned { model, .. } | ModelSpec::PinnedWithMatch { model, .. } => {
39                Some(model.as_str())
40            }
41            ModelSpec::AutoResolve { .. } | ModelSpec::Inherit => None,
42        }
43    }
44
45    /// The text fields as shown: an empty one is a layer clearing the text below it, and reads
46    /// as none. Layers keep the empty string so it can clear.
47    pub fn description(&self) -> Option<&str> {
48        self.description.as_deref().filter(|text| !text.is_empty())
49    }
50
51    pub fn prompting(&self) -> Option<&str> {
52        self.prompting.as_deref().filter(|text| !text.is_empty())
53    }
54
55    pub fn note(&self) -> Option<&str> {
56        self.note.as_deref().filter(|text| !text.is_empty())
57    }
58
59    /// This entry as a higher layer over `lower`, field by field. The routing fields (`model`,
60    /// `match`, `exclude`, `provider`, `harness`) move as one group: an entry that sets any of
61    /// them drops all of `lower`'s. The rest inherit when unset. An empty `description`, `note`
62    /// or `prompting` clears the lower one (see the accessors).
63    pub fn over(&self, lower: &ModelAlias) -> ModelAlias {
64        let (harness, spec) = if matches!(self.spec, ModelSpec::Inherit) {
65            (lower.harness.clone(), lower.spec.clone())
66        } else {
67            (self.harness.clone(), self.spec.clone())
68        };
69        ModelAlias {
70            harness,
71            description: self
72                .description
73                .clone()
74                .or_else(|| lower.description.clone()),
75            prompting: self.prompting.clone().or_else(|| lower.prompting.clone()),
76            note: self.note.clone().or_else(|| lower.note.clone()),
77            default_effort: self.default_effort.or(lower.default_effort),
78            autocompact: self.autocompact.or(lower.autocompact),
79            autocompact_pct: self.autocompact_pct.or(lower.autocompact_pct),
80            spec,
81        }
82    }
83}
84
85/// `higher`'s aliases over `base`'s: each name in both merges field by field (`ModelAlias::over`),
86/// a name in one stays as it is. The one rule for config layers and for a dependency's aliases
87/// under the consumer's.
88pub fn overlay_aliases(
89    base: &IndexMap<String, ModelAlias>,
90    higher: &IndexMap<String, ModelAlias>,
91) -> IndexMap<String, ModelAlias> {
92    let mut merged = base.clone();
93    for (name, alias) in higher {
94        let layered = match base.get(name) {
95            Some(lower) => alias.over(lower),
96            None => alias.clone(),
97        };
98        merged.insert(name.clone(), layered);
99    }
100    merged
101}
102
103#[derive(Debug, Clone, PartialEq)]
104pub enum ModelSpec {
105    /// A layer that sets none of the routing fields: it takes them from the layer below.
106    Inherit,
107    Pinned {
108        model: String,
109        provider: Option<String>,
110    },
111    PinnedWithMatch {
112        model: String,
113        provider: Option<String>,
114        match_patterns: Vec<String>,
115        exclude_patterns: Vec<String>,
116    },
117    AutoResolve {
118        provider: Option<String>,
119        match_patterns: Vec<String>,
120        exclude_patterns: Vec<String>,
121    },
122}
123
124impl Serialize for ModelSpec {
125    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
126        use serde::ser::SerializeMap;
127        match self {
128            ModelSpec::Inherit => serializer.serialize_map(Some(0))?.end(),
129            ModelSpec::Pinned { model, provider } => {
130                let mut count = 1;
131                if provider.is_some() {
132                    count += 1;
133                }
134                let mut map = serializer.serialize_map(Some(count))?;
135                map.serialize_entry("model", model)?;
136                if let Some(provider) = provider {
137                    map.serialize_entry("provider", provider)?;
138                }
139                map.end()
140            }
141            ModelSpec::PinnedWithMatch {
142                model,
143                provider,
144                match_patterns,
145                exclude_patterns,
146            } => {
147                let mut count = 2; // model + match
148                if provider.is_some() {
149                    count += 1;
150                }
151                if !exclude_patterns.is_empty() {
152                    count += 1;
153                }
154                let mut map = serializer.serialize_map(Some(count))?;
155                map.serialize_entry("model", model)?;
156                map.serialize_entry("match", match_patterns)?;
157                if let Some(provider) = provider {
158                    map.serialize_entry("provider", provider)?;
159                }
160                if !exclude_patterns.is_empty() {
161                    map.serialize_entry("exclude", exclude_patterns)?;
162                }
163                map.end()
164            }
165            ModelSpec::AutoResolve {
166                provider,
167                match_patterns,
168                exclude_patterns,
169            } => {
170                let mut count = 1; // match
171                if provider.is_some() {
172                    count += 1;
173                }
174                if !exclude_patterns.is_empty() {
175                    count += 1;
176                }
177                let mut map = serializer.serialize_map(Some(count))?;
178                if let Some(provider) = provider {
179                    map.serialize_entry("provider", provider)?;
180                }
181                map.serialize_entry("match", match_patterns)?;
182                if !exclude_patterns.is_empty() {
183                    map.serialize_entry("exclude", exclude_patterns)?;
184                }
185                map.end()
186            }
187        }
188    }
189}
190
191#[derive(Debug, Deserialize)]
192struct RawModelAlias {
193    harness: Option<String>,
194    #[serde(default)]
195    description: Option<String>,
196    #[serde(default)]
197    prompting: Option<String>,
198    #[serde(default)]
199    note: Option<String>,
200    #[serde(default)]
201    native: Option<toml::Value>,
202    #[serde(default)]
203    default_effort: Option<String>,
204    #[serde(default)]
205    autocompact: Option<toml::Value>,
206    #[serde(default)]
207    autocompact_pct: Option<toml::Value>,
208    #[serde(default)]
209    model: Option<String>,
210    #[serde(default)]
211    provider: Option<String>,
212    #[serde(default, rename = "match")]
213    match_patterns: Option<Vec<String>>,
214    #[serde(default)]
215    exclude: Option<Vec<String>>,
216}
217
218impl<'de> Deserialize<'de> for ModelAlias {
219    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
220        let raw = RawModelAlias::deserialize(deserializer)?;
221        // A harness Mars retired pins nothing: published packages still name one.
222        let normalized_harness = match raw.harness.as_deref() {
223            Some(name) if crate::retired::retired_target(name).is_some() => None,
224            Some(name) => Some(crate::harness::normalize_name(name).ok_or_else(|| {
225                serde::de::Error::custom(format!(
226                    "invalid harness '{name}'; valid harnesses: {}",
227                    crate::harness::names()
228                ))
229            })?),
230            None => None,
231        };
232        if raw.native.is_some() {
233            return Err(serde::de::Error::custom(
234                "[models.<alias>.native] is no longer supported",
235            ));
236        }
237        let default_effort = raw
238            .default_effort
239            .filter(|value| !value.trim().is_empty())
240            .map(|effort| {
241                EffortRequest::parse(&effort).ok_or_else(|| {
242                    serde::de::Error::custom(format!(
243                        "invalid default_effort '{effort}'; accepted values: {}",
244                        EffortRequest::ALLOWED
245                    ))
246                })
247            })
248            .transpose()?;
249        let autocompact: Option<u32> = match raw.autocompact {
250            Some(toml::Value::Integer(value)) => match u32::try_from(value) {
251                Ok(v) => Some(v),
252                Err(_) => {
253                    return Err(serde::de::Error::custom(format!(
254                        "autocompact {value} is out of u32 range (0–4294967295)"
255                    )));
256                }
257            },
258            Some(other) => {
259                return Err(serde::de::Error::custom(format!(
260                    "autocompact must be an integer (token count), got {other:?}"
261                )));
262            }
263            None => None,
264        };
265        let autocompact_pct: Option<u8> = match raw.autocompact_pct {
266            Some(toml::Value::Integer(value)) if (1..=100).contains(&value) => Some(value as u8),
267            Some(toml::Value::Integer(value)) => {
268                return Err(serde::de::Error::custom(format!(
269                    "autocompact_pct {value} is out of range 1-100"
270                )));
271            }
272            Some(other) => {
273                return Err(serde::de::Error::custom(format!(
274                    "autocompact_pct must be an integer 1-100, got {other:?}"
275                )));
276            }
277            None => None,
278        };
279
280        let has_match = raw.match_patterns.is_some();
281
282        let spec = if let Some(model) = raw.model {
283            if !has_match && raw.exclude.is_some() {
284                return Err(serde::de::Error::custom(
285                    "model alias with 'exclude' must also include 'match'",
286                ));
287            }
288            if let Some(match_patterns) = raw.match_patterns {
289                ModelSpec::PinnedWithMatch {
290                    model,
291                    provider: raw.provider,
292                    match_patterns,
293                    exclude_patterns: raw.exclude.unwrap_or_default(),
294                }
295            } else {
296                ModelSpec::Pinned {
297                    model,
298                    provider: raw.provider,
299                }
300            }
301        } else if let Some(match_patterns) = raw.match_patterns {
302            ModelSpec::AutoResolve {
303                provider: raw.provider,
304                match_patterns,
305                exclude_patterns: raw.exclude.unwrap_or_default(),
306            }
307        } else if raw.provider.is_some() || raw.exclude.is_some() || normalized_harness.is_some() {
308            return Err(serde::de::Error::custom(
309                "model alias must have either 'model' (pinned) or 'match' (auto-resolve)",
310            ));
311        } else {
312            ModelSpec::Inherit
313        };
314        if let Some(note) = &raw.note
315            && note.contains('\n')
316        {
317            return Err(serde::de::Error::custom("note must be one line"));
318        }
319
320        Ok(ModelAlias {
321            harness: normalized_harness,
322            description: raw.description,
323            prompting: raw.prompting,
324            note: raw.note,
325            default_effort,
326            autocompact,
327            autocompact_pct,
328            spec,
329        })
330    }
331}
332
333impl ModelAlias {
334    /// The id the alias resolves to over `rows`: a pinned `model` as written, else the best row
335    /// an `auto` alias selects. `None` when an `auto` alias selects nothing.
336    pub fn resolve(&self, rows: &[CachedModel]) -> Option<String> {
337        self.pinned_model_id()
338            .map(str::to_owned)
339            .or_else(|| self.selected(rows).first().map(|row| row.id.clone()))
340    }
341
342    /// Every id the alias accepts, in `resolve`'s order: a pinned `model` first, then each row
343    /// `match`, `exclude` and `provider` select, best first. A pinned alias with no `match`
344    /// accepts its `model` alone.
345    pub fn candidates(&self, rows: &[CachedModel]) -> Vec<String> {
346        let mut ids: Vec<String> = self
347            .pinned_model_id()
348            .map(str::to_owned)
349            .into_iter()
350            .collect();
351        for row in self.selected(rows) {
352            if !ids.contains(&row.id) {
353                ids.push(row.id.clone());
354            }
355        }
356        ids
357    }
358
359    /// The rows `match`, `exclude` and `provider` select; a pinned model's provider is inferred
360    /// from its id when the alias names none.
361    pub fn selected<'a>(&self, rows: &'a [CachedModel]) -> Vec<&'a CachedModel> {
362        match &self.spec {
363            ModelSpec::Inherit | ModelSpec::Pinned { .. } => Vec::new(),
364            ModelSpec::PinnedWithMatch {
365                model,
366                provider,
367                match_patterns,
368                exclude_patterns,
369            } => auto_resolve_all(
370                provider
371                    .as_deref()
372                    .or_else(|| infer_provider_from_model_id(model)),
373                match_patterns,
374                exclude_patterns,
375                rows,
376            ),
377            ModelSpec::AutoResolve {
378                provider,
379                match_patterns,
380                exclude_patterns,
381            } => auto_resolve_all(provider.as_deref(), match_patterns, exclude_patterns, rows),
382        }
383    }
384}
385
386#[cfg(test)]
387mod tests {
388    use super::*;
389
390    fn alias(toml_text: &str) -> ModelAlias {
391        toml::from_str(toml_text).unwrap()
392    }
393
394    #[test]
395    fn routing_fields_move_as_one_group() {
396        let lower = alias("model = \"a\"\nharness = \"codex\"\ndescription = \"low\"");
397        let higher = alias("match = [\"b*\"]");
398        let merged = higher.over(&lower);
399        assert_eq!(merged.spec, higher.spec);
400        assert_eq!(merged.harness, None);
401        assert_eq!(merged.description.as_deref(), Some("low"));
402    }
403
404    #[test]
405    fn an_entry_without_routing_takes_it_from_below() {
406        let lower = alias("model = \"a\"\nharness = \"codex\"");
407        let merged = alias("note = \"n\"\ndefault_effort = \"high\"").over(&lower);
408        assert_eq!(merged.spec, lower.spec);
409        assert_eq!(merged.harness.as_deref(), Some("codex"));
410        assert_eq!(merged.note.as_deref(), Some("n"));
411        assert!(merged.default_effort.is_some());
412    }
413
414    #[test]
415    fn an_empty_text_field_clears_the_one_below() {
416        let lower = alias("model = \"a\"\ndescription = \"d\"\nnote = \"n\"\nprompting = \"p\"");
417        let merged = alias("description = \"\"\nnote = \"\"\nprompting = \"\"").over(&lower);
418        assert_eq!(merged.description(), None);
419        assert_eq!(merged.note(), None);
420        assert_eq!(merged.prompting(), None);
421        assert_eq!(merged.spec, lower.spec);
422    }
423}