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 serde::{Deserialize, Serialize};
10
11use crate::agent::EffortRequest;
12use crate::models::{CachedModel, auto_resolve_all, infer_provider_from_model_id};
13
14#[derive(Debug, Clone, PartialEq, Serialize)]
15pub struct ModelAlias {
16    #[serde(skip_serializing_if = "Option::is_none")]
17    pub harness: Option<String>,
18    #[serde(skip_serializing_if = "Option::is_none")]
19    pub description: Option<String>,
20    #[serde(skip_serializing_if = "Option::is_none")]
21    pub prompting: Option<String>,
22    #[serde(skip_serializing_if = "Option::is_none")]
23    pub default_effort: Option<EffortRequest>,
24    #[serde(skip_serializing_if = "Option::is_none")]
25    pub autocompact: Option<u32>,
26    #[serde(skip_serializing_if = "Option::is_none")]
27    pub autocompact_pct: Option<u8>,
28    #[serde(flatten)]
29    pub spec: ModelSpec,
30}
31
32impl ModelAlias {
33    pub fn pinned_model_id(&self) -> Option<&str> {
34        match &self.spec {
35            ModelSpec::Pinned { model, .. } | ModelSpec::PinnedWithMatch { model, .. } => {
36                Some(model.as_str())
37            }
38            ModelSpec::AutoResolve { .. } => None,
39        }
40    }
41}
42
43#[derive(Debug, Clone, PartialEq)]
44pub enum ModelSpec {
45    Pinned {
46        model: String,
47        provider: Option<String>,
48    },
49    PinnedWithMatch {
50        model: String,
51        provider: Option<String>,
52        match_patterns: Vec<String>,
53        exclude_patterns: Vec<String>,
54    },
55    AutoResolve {
56        provider: Option<String>,
57        match_patterns: Vec<String>,
58        exclude_patterns: Vec<String>,
59    },
60}
61
62impl Serialize for ModelSpec {
63    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
64        use serde::ser::SerializeMap;
65        match self {
66            ModelSpec::Pinned { model, provider } => {
67                let mut count = 1;
68                if provider.is_some() {
69                    count += 1;
70                }
71                let mut map = serializer.serialize_map(Some(count))?;
72                map.serialize_entry("model", model)?;
73                if let Some(provider) = provider {
74                    map.serialize_entry("provider", provider)?;
75                }
76                map.end()
77            }
78            ModelSpec::PinnedWithMatch {
79                model,
80                provider,
81                match_patterns,
82                exclude_patterns,
83            } => {
84                let mut count = 2; // model + match
85                if provider.is_some() {
86                    count += 1;
87                }
88                if !exclude_patterns.is_empty() {
89                    count += 1;
90                }
91                let mut map = serializer.serialize_map(Some(count))?;
92                map.serialize_entry("model", model)?;
93                map.serialize_entry("match", match_patterns)?;
94                if let Some(provider) = provider {
95                    map.serialize_entry("provider", provider)?;
96                }
97                if !exclude_patterns.is_empty() {
98                    map.serialize_entry("exclude", exclude_patterns)?;
99                }
100                map.end()
101            }
102            ModelSpec::AutoResolve {
103                provider,
104                match_patterns,
105                exclude_patterns,
106            } => {
107                let mut count = 1; // match
108                if provider.is_some() {
109                    count += 1;
110                }
111                if !exclude_patterns.is_empty() {
112                    count += 1;
113                }
114                let mut map = serializer.serialize_map(Some(count))?;
115                if let Some(provider) = provider {
116                    map.serialize_entry("provider", provider)?;
117                }
118                map.serialize_entry("match", match_patterns)?;
119                if !exclude_patterns.is_empty() {
120                    map.serialize_entry("exclude", exclude_patterns)?;
121                }
122                map.end()
123            }
124        }
125    }
126}
127
128#[derive(Debug, Deserialize)]
129struct RawModelAlias {
130    harness: Option<String>,
131    #[serde(default)]
132    description: Option<String>,
133    #[serde(default)]
134    prompting: Option<String>,
135    #[serde(default)]
136    native: Option<toml::Value>,
137    #[serde(default)]
138    default_effort: Option<String>,
139    #[serde(default)]
140    autocompact: Option<toml::Value>,
141    #[serde(default)]
142    autocompact_pct: Option<toml::Value>,
143    #[serde(default)]
144    model: Option<String>,
145    #[serde(default)]
146    provider: Option<String>,
147    #[serde(default, rename = "match")]
148    match_patterns: Option<Vec<String>>,
149    #[serde(default)]
150    exclude: Option<Vec<String>>,
151}
152
153impl<'de> Deserialize<'de> for ModelAlias {
154    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
155        let raw = RawModelAlias::deserialize(deserializer)?;
156        // A harness Mars retired pins nothing: published packages still name one.
157        let normalized_harness = match raw.harness.as_deref() {
158            Some(name) if crate::retired::retired_target(name).is_some() => None,
159            Some(name) => Some(crate::harness::normalize_name(name).ok_or_else(|| {
160                serde::de::Error::custom(format!(
161                    "invalid harness '{name}'; valid harnesses: {}",
162                    crate::harness::names()
163                ))
164            })?),
165            None => None,
166        };
167        if raw.native.is_some() {
168            return Err(serde::de::Error::custom(
169                "[models.<alias>.native] is no longer supported",
170            ));
171        }
172        let default_effort = raw
173            .default_effort
174            .filter(|value| !value.trim().is_empty())
175            .map(|effort| {
176                EffortRequest::parse(&effort).ok_or_else(|| {
177                    serde::de::Error::custom(format!(
178                        "invalid default_effort '{effort}'; accepted values: {}",
179                        EffortRequest::ALLOWED
180                    ))
181                })
182            })
183            .transpose()?;
184        let autocompact: Option<u32> = match raw.autocompact {
185            Some(toml::Value::Integer(value)) => match u32::try_from(value) {
186                Ok(v) => Some(v),
187                Err(_) => {
188                    return Err(serde::de::Error::custom(format!(
189                        "autocompact {value} is out of u32 range (0–4294967295)"
190                    )));
191                }
192            },
193            Some(other) => {
194                return Err(serde::de::Error::custom(format!(
195                    "autocompact must be an integer (token count), got {other:?}"
196                )));
197            }
198            None => None,
199        };
200        let autocompact_pct: Option<u8> = match raw.autocompact_pct {
201            Some(toml::Value::Integer(value)) if (1..=100).contains(&value) => Some(value as u8),
202            Some(toml::Value::Integer(value)) => {
203                return Err(serde::de::Error::custom(format!(
204                    "autocompact_pct {value} is out of range 1-100"
205                )));
206            }
207            Some(other) => {
208                return Err(serde::de::Error::custom(format!(
209                    "autocompact_pct must be an integer 1-100, got {other:?}"
210                )));
211            }
212            None => None,
213        };
214
215        let has_match = raw.match_patterns.is_some();
216
217        let spec = if let Some(model) = raw.model {
218            if !has_match && raw.exclude.is_some() {
219                return Err(serde::de::Error::custom(
220                    "model alias with 'exclude' must also include 'match'",
221                ));
222            }
223            if let Some(match_patterns) = raw.match_patterns {
224                ModelSpec::PinnedWithMatch {
225                    model,
226                    provider: raw.provider,
227                    match_patterns,
228                    exclude_patterns: raw.exclude.unwrap_or_default(),
229                }
230            } else {
231                ModelSpec::Pinned {
232                    model,
233                    provider: raw.provider,
234                }
235            }
236        } else if let Some(match_patterns) = raw.match_patterns {
237            ModelSpec::AutoResolve {
238                provider: raw.provider,
239                match_patterns,
240                exclude_patterns: raw.exclude.unwrap_or_default(),
241            }
242        } else {
243            return Err(serde::de::Error::custom(
244                "model alias must have either 'model' (pinned) or 'match' (auto-resolve)",
245            ));
246        };
247
248        Ok(ModelAlias {
249            harness: normalized_harness,
250            description: raw.description,
251            prompting: raw.prompting,
252            default_effort,
253            autocompact,
254            autocompact_pct,
255            spec,
256        })
257    }
258}
259
260impl ModelAlias {
261    /// The id the alias resolves to over `rows`: a pinned `model` as written, else the best row
262    /// an `auto` alias selects. `None` when an `auto` alias selects nothing.
263    pub fn resolve(&self, rows: &[CachedModel]) -> Option<String> {
264        self.pinned_model_id()
265            .map(str::to_owned)
266            .or_else(|| self.selected(rows).first().map(|row| row.id.clone()))
267    }
268
269    /// Every id the alias accepts, in `resolve`'s order: a pinned `model` first, then each row
270    /// `match`, `exclude` and `provider` select, best first. A pinned alias with no `match`
271    /// accepts its `model` alone.
272    pub fn candidates(&self, rows: &[CachedModel]) -> Vec<String> {
273        let mut ids: Vec<String> = self
274            .pinned_model_id()
275            .map(str::to_owned)
276            .into_iter()
277            .collect();
278        for row in self.selected(rows) {
279            if !ids.contains(&row.id) {
280                ids.push(row.id.clone());
281            }
282        }
283        ids
284    }
285
286    /// The rows `match`, `exclude` and `provider` select; a pinned model's provider is inferred
287    /// from its id when the alias names none.
288    pub fn selected<'a>(&self, rows: &'a [CachedModel]) -> Vec<&'a CachedModel> {
289        match &self.spec {
290            ModelSpec::Pinned { .. } => Vec::new(),
291            ModelSpec::PinnedWithMatch {
292                model,
293                provider,
294                match_patterns,
295                exclude_patterns,
296            } => auto_resolve_all(
297                provider
298                    .as_deref()
299                    .or_else(|| infer_provider_from_model_id(model)),
300                match_patterns,
301                exclude_patterns,
302                rows,
303            ),
304            ModelSpec::AutoResolve {
305                provider,
306                match_patterns,
307                exclude_patterns,
308            } => auto_resolve_all(provider.as_deref(), match_patterns, exclude_patterns, rows),
309        }
310    }
311}