mars-schema 0.42.0

Pure schema reader and editor for Mars agent packages
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
//! A `[models.<alias>]` table of `mars.toml`: how an alias names a model, and the pure
//! resolution of it over models.dev rows.
//!
//! Two kinds: a pinned alias names a model id (with optional `match`/`exclude` filters that
//! widen what it accepts), an `auto` alias selects from the catalog by `match`, `exclude` and
//! `provider`. Resolution is `models::auto_resolve_all`, so the CLI's snapshot and a host's rows
//! choose the same id.

use indexmap::IndexMap;
use serde::{Deserialize, Serialize};

use crate::agent::EffortRequest;
use crate::models::{CachedModel, auto_resolve_all, infer_provider_from_model_id};

#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct ModelAlias {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub harness: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub prompting: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub note: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub default_effort: Option<EffortRequest>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub autocompact: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub autocompact_pct: Option<u8>,
    #[serde(flatten)]
    pub spec: ModelSpec,
}

impl ModelAlias {
    pub fn pinned_model_id(&self) -> Option<&str> {
        match &self.spec {
            ModelSpec::Pinned { model, .. } | ModelSpec::PinnedWithMatch { model, .. } => {
                Some(model.as_str())
            }
            ModelSpec::AutoResolve { .. } | ModelSpec::Inherit => None,
        }
    }

    /// The text fields as shown: an empty one is a layer clearing the text below it, and reads
    /// as none. Layers keep the empty string so it can clear.
    pub fn description(&self) -> Option<&str> {
        self.description.as_deref().filter(|text| !text.is_empty())
    }

    pub fn prompting(&self) -> Option<&str> {
        self.prompting.as_deref().filter(|text| !text.is_empty())
    }

    pub fn note(&self) -> Option<&str> {
        self.note.as_deref().filter(|text| !text.is_empty())
    }

    /// This entry as a higher layer over `lower`, field by field. The routing fields (`model`,
    /// `match`, `exclude`, `provider`, `harness`) move as one group: an entry that sets any of
    /// them drops all of `lower`'s. The rest inherit when unset. An empty `description`, `note`
    /// or `prompting` clears the lower one (see the accessors).
    pub fn over(&self, lower: &ModelAlias) -> ModelAlias {
        let (harness, spec) = if matches!(self.spec, ModelSpec::Inherit) {
            (lower.harness.clone(), lower.spec.clone())
        } else {
            (self.harness.clone(), self.spec.clone())
        };
        ModelAlias {
            harness,
            description: self
                .description
                .clone()
                .or_else(|| lower.description.clone()),
            prompting: self.prompting.clone().or_else(|| lower.prompting.clone()),
            note: self.note.clone().or_else(|| lower.note.clone()),
            default_effort: self.default_effort.or(lower.default_effort),
            autocompact: self.autocompact.or(lower.autocompact),
            autocompact_pct: self.autocompact_pct.or(lower.autocompact_pct),
            spec,
        }
    }
}

/// `higher`'s aliases over `base`'s: each name in both merges field by field (`ModelAlias::over`),
/// a name in one stays as it is. The one rule for config layers and for a dependency's aliases
/// under the consumer's.
pub fn overlay_aliases(
    base: &IndexMap<String, ModelAlias>,
    higher: &IndexMap<String, ModelAlias>,
) -> IndexMap<String, ModelAlias> {
    let mut merged = base.clone();
    for (name, alias) in higher {
        let layered = match base.get(name) {
            Some(lower) => alias.over(lower),
            None => alias.clone(),
        };
        merged.insert(name.clone(), layered);
    }
    merged
}

#[derive(Debug, Clone, PartialEq)]
pub enum ModelSpec {
    /// A layer that sets none of the routing fields: it takes them from the layer below.
    Inherit,
    Pinned {
        model: String,
        provider: Option<String>,
    },
    PinnedWithMatch {
        model: String,
        provider: Option<String>,
        match_patterns: Vec<String>,
        exclude_patterns: Vec<String>,
    },
    AutoResolve {
        provider: Option<String>,
        match_patterns: Vec<String>,
        exclude_patterns: Vec<String>,
    },
}

impl Serialize for ModelSpec {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        use serde::ser::SerializeMap;
        match self {
            ModelSpec::Inherit => serializer.serialize_map(Some(0))?.end(),
            ModelSpec::Pinned { model, provider } => {
                let mut count = 1;
                if provider.is_some() {
                    count += 1;
                }
                let mut map = serializer.serialize_map(Some(count))?;
                map.serialize_entry("model", model)?;
                if let Some(provider) = provider {
                    map.serialize_entry("provider", provider)?;
                }
                map.end()
            }
            ModelSpec::PinnedWithMatch {
                model,
                provider,
                match_patterns,
                exclude_patterns,
            } => {
                let mut count = 2; // model + match
                if provider.is_some() {
                    count += 1;
                }
                if !exclude_patterns.is_empty() {
                    count += 1;
                }
                let mut map = serializer.serialize_map(Some(count))?;
                map.serialize_entry("model", model)?;
                map.serialize_entry("match", match_patterns)?;
                if let Some(provider) = provider {
                    map.serialize_entry("provider", provider)?;
                }
                if !exclude_patterns.is_empty() {
                    map.serialize_entry("exclude", exclude_patterns)?;
                }
                map.end()
            }
            ModelSpec::AutoResolve {
                provider,
                match_patterns,
                exclude_patterns,
            } => {
                let mut count = 1; // match
                if provider.is_some() {
                    count += 1;
                }
                if !exclude_patterns.is_empty() {
                    count += 1;
                }
                let mut map = serializer.serialize_map(Some(count))?;
                if let Some(provider) = provider {
                    map.serialize_entry("provider", provider)?;
                }
                map.serialize_entry("match", match_patterns)?;
                if !exclude_patterns.is_empty() {
                    map.serialize_entry("exclude", exclude_patterns)?;
                }
                map.end()
            }
        }
    }
}

#[derive(Debug, Deserialize)]
struct RawModelAlias {
    harness: Option<String>,
    #[serde(default)]
    description: Option<String>,
    #[serde(default)]
    prompting: Option<String>,
    #[serde(default)]
    note: Option<String>,
    #[serde(default)]
    native: Option<toml::Value>,
    #[serde(default)]
    default_effort: Option<String>,
    #[serde(default)]
    autocompact: Option<toml::Value>,
    #[serde(default)]
    autocompact_pct: Option<toml::Value>,
    #[serde(default)]
    model: Option<String>,
    #[serde(default)]
    provider: Option<String>,
    #[serde(default, rename = "match")]
    match_patterns: Option<Vec<String>>,
    #[serde(default)]
    exclude: Option<Vec<String>>,
}

impl<'de> Deserialize<'de> for ModelAlias {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let raw = RawModelAlias::deserialize(deserializer)?;
        // A harness Mars retired pins nothing: published packages still name one.
        let normalized_harness = match raw.harness.as_deref() {
            Some(name) if crate::retired::retired_target(name).is_some() => None,
            Some(name) => Some(crate::harness::normalize_name(name).ok_or_else(|| {
                serde::de::Error::custom(format!(
                    "invalid harness '{name}'; valid harnesses: {}",
                    crate::harness::names()
                ))
            })?),
            None => None,
        };
        if raw.native.is_some() {
            return Err(serde::de::Error::custom(
                "[models.<alias>.native] is no longer supported",
            ));
        }
        let default_effort = raw
            .default_effort
            .filter(|value| !value.trim().is_empty())
            .map(|effort| {
                EffortRequest::parse(&effort).ok_or_else(|| {
                    serde::de::Error::custom(format!(
                        "invalid default_effort '{effort}'; accepted values: {}",
                        EffortRequest::ALLOWED
                    ))
                })
            })
            .transpose()?;
        let autocompact: Option<u32> = match raw.autocompact {
            Some(toml::Value::Integer(value)) => match u32::try_from(value) {
                Ok(v) => Some(v),
                Err(_) => {
                    return Err(serde::de::Error::custom(format!(
                        "autocompact {value} is out of u32 range (0–4294967295)"
                    )));
                }
            },
            Some(other) => {
                return Err(serde::de::Error::custom(format!(
                    "autocompact must be an integer (token count), got {other:?}"
                )));
            }
            None => None,
        };
        let autocompact_pct: Option<u8> = match raw.autocompact_pct {
            Some(toml::Value::Integer(value)) if (1..=100).contains(&value) => Some(value as u8),
            Some(toml::Value::Integer(value)) => {
                return Err(serde::de::Error::custom(format!(
                    "autocompact_pct {value} is out of range 1-100"
                )));
            }
            Some(other) => {
                return Err(serde::de::Error::custom(format!(
                    "autocompact_pct must be an integer 1-100, got {other:?}"
                )));
            }
            None => None,
        };

        let has_match = raw.match_patterns.is_some();

        let spec = if let Some(model) = raw.model {
            if !has_match && raw.exclude.is_some() {
                return Err(serde::de::Error::custom(
                    "model alias with 'exclude' must also include 'match'",
                ));
            }
            if let Some(match_patterns) = raw.match_patterns {
                ModelSpec::PinnedWithMatch {
                    model,
                    provider: raw.provider,
                    match_patterns,
                    exclude_patterns: raw.exclude.unwrap_or_default(),
                }
            } else {
                ModelSpec::Pinned {
                    model,
                    provider: raw.provider,
                }
            }
        } else if let Some(match_patterns) = raw.match_patterns {
            ModelSpec::AutoResolve {
                provider: raw.provider,
                match_patterns,
                exclude_patterns: raw.exclude.unwrap_or_default(),
            }
        } else if raw.provider.is_some() || raw.exclude.is_some() || normalized_harness.is_some() {
            return Err(serde::de::Error::custom(
                "model alias must have either 'model' (pinned) or 'match' (auto-resolve)",
            ));
        } else {
            ModelSpec::Inherit
        };
        if let Some(note) = &raw.note
            && note.contains('\n')
        {
            return Err(serde::de::Error::custom("note must be one line"));
        }

        Ok(ModelAlias {
            harness: normalized_harness,
            description: raw.description,
            prompting: raw.prompting,
            note: raw.note,
            default_effort,
            autocompact,
            autocompact_pct,
            spec,
        })
    }
}

impl ModelAlias {
    /// The id the alias resolves to over `rows`: a pinned `model` as written, else the best row
    /// an `auto` alias selects. `None` when an `auto` alias selects nothing.
    pub fn resolve(&self, rows: &[CachedModel]) -> Option<String> {
        self.pinned_model_id()
            .map(str::to_owned)
            .or_else(|| self.selected(rows).first().map(|row| row.id.clone()))
    }

    /// Every id the alias accepts, in `resolve`'s order: a pinned `model` first, then each row
    /// `match`, `exclude` and `provider` select, best first. A pinned alias with no `match`
    /// accepts its `model` alone.
    pub fn candidates(&self, rows: &[CachedModel]) -> Vec<String> {
        let mut ids: Vec<String> = self
            .pinned_model_id()
            .map(str::to_owned)
            .into_iter()
            .collect();
        for row in self.selected(rows) {
            if !ids.contains(&row.id) {
                ids.push(row.id.clone());
            }
        }
        ids
    }

    /// The rows `match`, `exclude` and `provider` select; a pinned model's provider is inferred
    /// from its id when the alias names none.
    pub fn selected<'a>(&self, rows: &'a [CachedModel]) -> Vec<&'a CachedModel> {
        match &self.spec {
            ModelSpec::Inherit | ModelSpec::Pinned { .. } => Vec::new(),
            ModelSpec::PinnedWithMatch {
                model,
                provider,
                match_patterns,
                exclude_patterns,
            } => auto_resolve_all(
                provider
                    .as_deref()
                    .or_else(|| infer_provider_from_model_id(model)),
                match_patterns,
                exclude_patterns,
                rows,
            ),
            ModelSpec::AutoResolve {
                provider,
                match_patterns,
                exclude_patterns,
            } => auto_resolve_all(provider.as_deref(), match_patterns, exclude_patterns, rows),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn alias(toml_text: &str) -> ModelAlias {
        toml::from_str(toml_text).unwrap()
    }

    #[test]
    fn routing_fields_move_as_one_group() {
        let lower = alias("model = \"a\"\nharness = \"codex\"\ndescription = \"low\"");
        let higher = alias("match = [\"b*\"]");
        let merged = higher.over(&lower);
        assert_eq!(merged.spec, higher.spec);
        assert_eq!(merged.harness, None);
        assert_eq!(merged.description.as_deref(), Some("low"));
    }

    #[test]
    fn an_entry_without_routing_takes_it_from_below() {
        let lower = alias("model = \"a\"\nharness = \"codex\"");
        let merged = alias("note = \"n\"\ndefault_effort = \"high\"").over(&lower);
        assert_eq!(merged.spec, lower.spec);
        assert_eq!(merged.harness.as_deref(), Some("codex"));
        assert_eq!(merged.note.as_deref(), Some("n"));
        assert!(merged.default_effort.is_some());
    }

    #[test]
    fn an_empty_text_field_clears_the_one_below() {
        let lower = alias("model = \"a\"\ndescription = \"d\"\nnote = \"n\"\nprompting = \"p\"");
        let merged = alias("description = \"\"\nnote = \"\"\nprompting = \"\"").over(&lower);
        assert_eq!(merged.description(), None);
        assert_eq!(merged.note(), None);
        assert_eq!(merged.prompting(), None);
        assert_eq!(merged.spec, lower.spec);
    }
}