Skip to main content

mars_schema/
model_policy.rs

1//! Model-policy definition and validation shared by profiles and consumer config.
2
3use crate::agent::{ApprovalMode, EffortLevel, SandboxMode};
4use crate::network::NetworkPolicy;
5use serde::ser::SerializeMap;
6use serde::{Deserialize, Serialize};
7
8#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
9#[serde(rename_all = "kebab-case")]
10pub enum ModelPolicyMatchType {
11    Model,
12    Alias,
13    ModelGlob,
14}
15
16#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
17#[serde(deny_unknown_fields)]
18pub struct ModelPolicyOverride {
19    #[serde(default, skip_serializing_if = "Option::is_none")]
20    pub effort: Option<String>,
21    #[serde(default, skip_serializing_if = "Option::is_none")]
22    pub sandbox: Option<String>,
23    #[serde(default, skip_serializing_if = "Option::is_none")]
24    pub approval: Option<String>,
25    #[serde(default, skip_serializing_if = "Option::is_none")]
26    pub network: Option<String>,
27}
28
29impl ModelPolicyOverride {
30    pub fn is_empty(&self) -> bool {
31        self.effort.is_none()
32            && self.sandbox.is_none()
33            && self.approval.is_none()
34            && self.network.is_none()
35    }
36
37    pub fn get(&self, key: &str) -> Option<&str> {
38        match key {
39            "effort" => self.effort.as_deref(),
40            "sandbox" => self.sandbox.as_deref(),
41            "approval" => self.approval.as_deref(),
42            "network" => self.network.as_deref(),
43            _ => None,
44        }
45    }
46}
47
48/// Shared model-policy rule type used by profile frontmatter, agent overlays,
49/// and settings-level model policies.
50#[derive(Debug, Clone, PartialEq)]
51pub struct ModelPolicyRule {
52    pub match_type: ModelPolicyMatchType,
53    pub match_value: String,
54    pub no_fallback: bool,
55    pub overrides: ModelPolicyOverride,
56    /// A compact, authored guide explaining when this model is a good choice.
57    pub when: Option<String>,
58}
59
60#[derive(Debug, Clone, PartialEq, Eq)]
61pub enum ModelPolicyRuleParseError {
62    RuleMustBeMapping {
63        found: String,
64    },
65    MatchMissing,
66    MatchMustBeMapping {
67        found: String,
68    },
69    MatchMustContainExactlyOne {
70        found: String,
71    },
72    MatchKeyMustBeString {
73        found: String,
74    },
75    UnknownMatchKey {
76        key: String,
77    },
78    MatchValueMustBeString {
79        key: String,
80        found: String,
81    },
82    MatchValueEmpty {
83        key: String,
84    },
85    OverrideMustBeMapping {
86        found: String,
87    },
88    UnknownOverrideKey {
89        key: String,
90    },
91    /// A host set is layered by settings, profile, overlay and CLI, never by a model rule.
92    NetworkHostsNotAllowed {
93        key: String,
94    },
95    OverrideValueInvalid {
96        key: String,
97        found: String,
98        allowed: &'static str,
99    },
100    NoFallbackMustBeBoolean {
101        found: String,
102    },
103    WhenInvalid {
104        found: String,
105    },
106}
107
108impl ModelPolicyRuleParseError {
109    fn deserialize_message(&self) -> String {
110        match self {
111            Self::MatchMustContainExactlyOne { .. }
112            | Self::MatchMissing
113            | Self::MatchMustBeMapping { .. } => {
114                "model policy `match` must contain exactly one of model, alias, model-glob"
115                    .to_string()
116            }
117            Self::MatchKeyMustBeString { .. } => {
118                "model policy `match` key must be a string".to_string()
119            }
120            Self::MatchValueMustBeString { .. } => {
121                "model policy `match` value must be a string".to_string()
122            }
123            Self::MatchValueEmpty { .. } => {
124                "model policy `match` value must be a non-empty string".to_string()
125            }
126            Self::UnknownMatchKey { key } => format!(
127                "unknown model policy match key `{key}`; expected model, alias, or model-glob"
128            ),
129            Self::OverrideMustBeMapping { .. } => {
130                "model policy `override` must be a mapping".to_string()
131            }
132            Self::UnknownOverrideKey { key } => format!(
133                "unknown model policy override `{key}`; expected effort, sandbox, approval, or network"
134            ),
135            Self::NetworkHostsNotAllowed { key } => format!(
136                "model policy override `{key}` is not supported; set it on settings, the profile, an agent overlay, or the CLI"
137            ),
138            Self::OverrideValueInvalid {
139                key,
140                found,
141                allowed,
142            } => format!(
143                "model policy override `{key}` has invalid value `{found}`; allowed: {allowed}"
144            ),
145            Self::NoFallbackMustBeBoolean { .. } => {
146                "model policy `no-fallback` must be a boolean".to_string()
147            }
148            Self::WhenInvalid { .. } => {
149                "model policy `when` must be a non-empty one-line string".to_string()
150            }
151            Self::RuleMustBeMapping { .. } => "model policy rule must be a mapping".to_string(),
152        }
153    }
154}
155
156/// The keys of a rule that Mars reads. A key beside them is unknown. An `override` takes only
157/// the fields below, every one of them an execution or restriction setting, so an unknown key
158/// there is an error rather than a note.
159const RULE_KEYS: &[&str] = &["match", "override", "no-fallback", "when"];
160const OVERRIDE_KEYS: &[&str] = &[
161    "effort",
162    "sandbox",
163    "approval",
164    "network",
165    "network-allow",
166    "network-deny",
167];
168
169/// What reading one rule found, all in one pass: the rule when nothing in it is rejected, every
170/// rejection when something is, and the unknown keys either way.
171pub(crate) struct RuleReading {
172    pub rule: Result<ModelPolicyRule, Vec<ModelPolicyRuleParseError>>,
173    pub unknown: Vec<String>,
174}
175
176pub(crate) fn read_model_policy_rule(value: &serde_yaml::Value) -> RuleReading {
177    use ModelPolicyRuleParseError as Error;
178    let Some(rule) = value.as_mapping() else {
179        return RuleReading {
180            rule: Err(vec![Error::RuleMustBeMapping {
181                found: crate::ordered::plain(value),
182            }]),
183            unknown: Vec::new(),
184        };
185    };
186    let mut errors = Vec::new();
187    let unknown = unknown_keys(rule, RULE_KEYS);
188
189    let matched = read_match(rule).map_err(|error| errors.push(error)).ok();
190
191    let overrides = match rule.get(serde_yaml::Value::String("override".to_string())) {
192        Some(value) if !value.is_null() => match value.as_mapping() {
193            Some(mapping) => read_overrides(mapping, &mut errors),
194            None => {
195                errors.push(Error::OverrideMustBeMapping {
196                    found: crate::ordered::plain(value),
197                });
198                ModelPolicyOverride::default()
199            }
200        },
201        _ => ModelPolicyOverride::default(),
202    };
203
204    let no_fallback = match rule.get(serde_yaml::Value::String("no-fallback".to_string())) {
205        None | Some(serde_yaml::Value::Null) => false,
206        Some(serde_yaml::Value::Bool(value)) => *value,
207        Some(value) => {
208            errors.push(Error::NoFallbackMustBeBoolean {
209                found: crate::ordered::plain(value),
210            });
211            false
212        }
213    };
214
215    let when = match rule.get(serde_yaml::Value::String("when".to_string())) {
216        None | Some(serde_yaml::Value::Null) => None,
217        Some(serde_yaml::Value::String(value))
218            if !value.is_empty() && !value.contains(['\n', '\r']) =>
219        {
220            Some(value.clone())
221        }
222        Some(value) => {
223            errors.push(Error::WhenInvalid {
224                found: crate::ordered::plain(value),
225            });
226            None
227        }
228    };
229
230    let rule = match matched {
231        Some((match_type, match_value)) if errors.is_empty() => Ok(ModelPolicyRule {
232            match_type,
233            match_value,
234            no_fallback,
235            overrides,
236            when,
237        }),
238        _ => Err(errors),
239    };
240    RuleReading { rule, unknown }
241}
242
243fn unknown_keys(mapping: &serde_yaml::Mapping, known: &[&str]) -> Vec<String> {
244    mapping
245        .keys()
246        .filter(|key| !key.as_str().is_some_and(|key| known.contains(&key)))
247        .map(|key| {
248            key.as_str()
249                .map_or_else(|| crate::ordered::plain(key), str::to_owned)
250        })
251        .collect()
252}
253
254fn read_match(
255    rule: &serde_yaml::Mapping,
256) -> Result<(ModelPolicyMatchType, String), ModelPolicyRuleParseError> {
257    use ModelPolicyRuleParseError as Error;
258    let match_mapping = match rule.get(serde_yaml::Value::String("match".to_string())) {
259        Some(value) => value
260            .as_mapping()
261            .ok_or_else(|| Error::MatchMustBeMapping {
262                found: crate::ordered::plain(value),
263            })?,
264        None => return Err(Error::MatchMissing),
265    };
266    let exactly_one = || Error::MatchMustContainExactlyOne {
267        found: crate::ordered::plain(&serde_yaml::Value::Mapping(match_mapping.clone())),
268    };
269    let mut entries = match_mapping.iter();
270    let Some((match_key, match_value)) = entries.next() else {
271        return Err(exactly_one());
272    };
273    if entries.next().is_some() {
274        return Err(exactly_one());
275    }
276
277    let key = match_key
278        .as_str()
279        .ok_or_else(|| Error::MatchKeyMustBeString {
280            found: crate::ordered::plain(match_key),
281        })?;
282    let value = match_value
283        .as_str()
284        .ok_or_else(|| Error::MatchValueMustBeString {
285            key: key.to_string(),
286            found: crate::ordered::plain(match_value),
287        })?;
288    if value.is_empty() {
289        return Err(Error::MatchValueEmpty {
290            key: key.to_string(),
291        });
292    }
293    let match_type = match key {
294        "model" => ModelPolicyMatchType::Model,
295        "alias" => ModelPolicyMatchType::Alias,
296        "model-glob" => ModelPolicyMatchType::ModelGlob,
297        _ => {
298            return Err(Error::UnknownMatchKey {
299                key: key.to_string(),
300            });
301        }
302    };
303    Ok((match_type, value.to_string()))
304}
305
306/// The override keys Mars reads; each rejected one adds its own error.
307fn read_overrides(
308    mapping: &serde_yaml::Mapping,
309    errors: &mut Vec<ModelPolicyRuleParseError>,
310) -> ModelPolicyOverride {
311    let mut overrides = ModelPolicyOverride::default();
312    for (key, value) in mapping {
313        let Some(key) = key.as_str().filter(|key| OVERRIDE_KEYS.contains(key)) else {
314            errors.push(ModelPolicyRuleParseError::UnknownOverrideKey {
315                key: key
316                    .as_str()
317                    .map_or_else(|| crate::ordered::plain(key), str::to_owned),
318            });
319            continue;
320        };
321        if matches!(key, "network-allow" | "network-deny") {
322            errors.push(ModelPolicyRuleParseError::NetworkHostsNotAllowed {
323                key: key.to_string(),
324            });
325            continue;
326        }
327        let invalid = |found: String| ModelPolicyRuleParseError::OverrideValueInvalid {
328            key: key.to_string(),
329            found,
330            allowed: allowed_override_values(key),
331        };
332        let Some(raw) = value.as_str() else {
333            errors.push(invalid(crate::ordered::plain(value)));
334            continue;
335        };
336        let parsed = match key {
337            "effort" => EffortLevel::parse(raw).map(|value| value.as_str().to_string()),
338            "sandbox" => SandboxMode::parse(raw).map(|value| value.as_str().to_string()),
339            "approval" => ApprovalMode::parse(raw).map(|value| value.as_str().to_string()),
340            _ => NetworkPolicy::parse(raw).map(|value| value.as_str().to_string()),
341        };
342        let Some(parsed) = parsed else {
343            errors.push(invalid(raw.to_string()));
344            continue;
345        };
346        match key {
347            "effort" => overrides.effort = Some(parsed),
348            "sandbox" => overrides.sandbox = Some(parsed),
349            "approval" => overrides.approval = Some(parsed),
350            _ => overrides.network = Some(parsed),
351        }
352    }
353    overrides
354}
355
356fn allowed_override_values(key: &str) -> &'static str {
357    match key {
358        "effort" => EffortLevel::ALLOWED,
359        "sandbox" => SandboxMode::ALLOWED,
360        "approval" => ApprovalMode::ALLOWED,
361        "network" => NetworkPolicy::ALLOWED,
362        _ => "effort, sandbox, approval, network",
363    }
364}
365
366impl<'de> Deserialize<'de> for ModelPolicyRule {
367    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
368    where
369        D: serde::Deserializer<'de>,
370    {
371        /// Takes the keys a rule reads and hands every other value to serde as ignored, so a
372        /// reader that reports ignored keys sees an unknown field of a rule or of its `override`.
373        struct RuleVisitor;
374
375        impl<'de> serde::de::Visitor<'de> for RuleVisitor {
376            type Value = ModelPolicyRule;
377
378            fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
379                f.write_str("a model policy rule mapping")
380            }
381
382            fn visit_map<A: serde::de::MapAccess<'de>>(
383                self,
384                mut map: A,
385            ) -> Result<Self::Value, A::Error> {
386                let mut rule = serde_yaml::Mapping::new();
387                while let Some(key) = map.next_key::<String>()? {
388                    if RULE_KEYS.contains(&key.as_str()) {
389                        rule.insert(key.into(), map.next_value::<serde_yaml::Value>()?);
390                    } else {
391                        map.next_value::<serde::de::IgnoredAny>()?;
392                    }
393                }
394                read_model_policy_rule(&serde_yaml::Value::Mapping(rule))
395                    .rule
396                    .map_err(|errors| {
397                        serde::de::Error::custom(
398                            errors
399                                .iter()
400                                .map(ModelPolicyRuleParseError::deserialize_message)
401                                .collect::<Vec<_>>()
402                                .join("; "),
403                        )
404                    })
405            }
406        }
407
408        deserializer.deserialize_map(RuleVisitor)
409    }
410}
411
412impl Serialize for ModelPolicyRule {
413    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
414    where
415        S: serde::Serializer,
416    {
417        let mut map = serializer.serialize_map(None)?;
418        let match_key = match self.match_type {
419            ModelPolicyMatchType::Model => "model",
420            ModelPolicyMatchType::Alias => "alias",
421            ModelPolicyMatchType::ModelGlob => "model-glob",
422        };
423
424        let mut match_clause = serde_yaml::Mapping::new();
425        match_clause.insert(
426            serde_yaml::Value::String(match_key.to_string()),
427            serde_yaml::Value::String(self.match_value.clone()),
428        );
429        map.serialize_entry("match", &match_clause)?;
430        if !self.overrides.is_empty() {
431            map.serialize_entry("override", &self.overrides)?;
432        }
433        if self.no_fallback {
434            map.serialize_entry("no-fallback", &self.no_fallback)?;
435        }
436        if let Some(when) = &self.when {
437            map.serialize_entry("when", when)?;
438        }
439        map.end()
440    }
441}