Skip to main content

mars_schema/
agent.rs

1//! Agent definition reader.
2
3use crate::HarnessId;
4use serde_yaml::Value;
5
6use crate::diagnostic::{push_invalid, unrecognized_field};
7use crate::frontmatter::{Frontmatter, SkillsSpec};
8use crate::harness_overrides::{HarnessOverrides, parse_harness_overrides};
9use crate::invocability::parse_invocability_axis;
10use crate::item::DefinitionKind;
11use crate::model_policy::{ModelEntry, ModelPolicyMatchType, ModelPolicyRule};
12use crate::network::{NetworkHost, NetworkPolicy};
13use crate::permission_set::PermissionSet;
14use crate::tool_policy::{self, EffectiveToolPolicy};
15
16/// The Agent keys Mars lowers into a harness's native file itself, by the field that owns them.
17/// A `harness-overrides` entry never replaces one (native lowering keeps Mars's value and reports
18/// the override as dropped), so the translation's set-aside never moves one there either.
19#[derive(Debug, Clone, Copy)]
20pub enum LoweredField {
21    Identity,
22    Model,
23    Skills,
24    Tools,
25    Effort,
26    Mode,
27    /// `agy`'s `tools`: an allowlist, every known tool when the policy does not restrict, and no
28    /// deny list.
29    AllowlistOrAll,
30}
31
32impl LoweredField {
33    pub const ALL: [Self; 7] = [
34        Self::Identity,
35        Self::Model,
36        Self::Skills,
37        Self::Tools,
38        Self::Effort,
39        Self::Mode,
40        Self::AllowlistOrAll,
41    ];
42
43    /// Frontmatter keys this field lowers, whether or not the profile has a value for them.
44    pub const fn keys(self) -> &'static [&'static str] {
45        match self {
46            Self::Identity => &["name", "description"],
47            Self::Model => &["model"],
48            Self::Skills => &["skills"],
49            Self::Tools => &["tools", "disallowed-tools"],
50            Self::Effort => &["effort"],
51            Self::Mode => &["mode"],
52            Self::AllowlistOrAll => &["tools"],
53        }
54    }
55
56    /// Whether Mars lowers `key` itself on some harness.
57    pub fn reserves(key: &str) -> bool {
58        Self::ALL.iter().any(|field| field.keys().contains(&key))
59    }
60}
61
62/// Agent execution mode — how the agent is launched.
63#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
64#[serde(rename_all = "kebab-case")]
65pub enum AgentMode {
66    Primary,
67    Subagent,
68}
69
70impl AgentMode {
71    pub fn as_str(&self) -> &str {
72        match self {
73            AgentMode::Primary => "primary",
74            AgentMode::Subagent => "subagent",
75        }
76    }
77}
78
79impl std::fmt::Display for AgentMode {
80    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
81        f.write_str(self.as_str())
82    }
83}
84
85/// Approval policy field.
86#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
87#[serde(rename_all = "kebab-case")]
88pub enum ApprovalMode {
89    Default,
90    Auto,
91    Confirm,
92    Never,
93}
94
95impl ApprovalMode {
96    /// The values `parse` accepts, as the invalid-value errors list them.
97    pub const ALLOWED: &'static str = "default, auto, confirm, never";
98
99    pub fn parse(s: &str) -> Option<Self> {
100        match s {
101            "default" => Some(Self::Default),
102            "auto" => Some(Self::Auto),
103            "confirm" => Some(Self::Confirm),
104            "never" => Some(Self::Never),
105            _ => None,
106        }
107    }
108
109    pub fn as_str(&self) -> &str {
110        match self {
111            Self::Default => "default",
112            Self::Auto => "auto",
113            Self::Confirm => "confirm",
114            Self::Never => "never",
115        }
116    }
117}
118
119/// Sandbox mode field.
120#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
121#[serde(rename_all = "kebab-case")]
122pub enum SandboxMode {
123    Default,
124    ReadOnly,
125    WorkspaceWrite,
126    DangerFullAccess,
127}
128
129impl SandboxMode {
130    /// The values `parse` accepts, as the invalid-value errors list them.
131    pub const ALLOWED: &'static str = "default, read-only, workspace-write, danger-full-access";
132
133    pub fn parse(s: &str) -> Option<Self> {
134        match s {
135            "default" => Some(Self::Default),
136            "read-only" => Some(Self::ReadOnly),
137            "workspace-write" => Some(Self::WorkspaceWrite),
138            "danger-full-access" => Some(Self::DangerFullAccess),
139            _ => None,
140        }
141    }
142
143    pub fn as_str(&self) -> &str {
144        match self {
145            Self::Default => "default",
146            Self::ReadOnly => "read-only",
147            Self::WorkspaceWrite => "workspace-write",
148            Self::DangerFullAccess => "danger-full-access",
149        }
150    }
151}
152
153/// A reasoning level, in ladder order: `none < minimal < low < medium < high < xhigh < max`.
154/// These are every effort value models.dev lists for any model.
155#[derive(
156    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize,
157)]
158#[serde(rename_all = "kebab-case")]
159pub enum EffortLevel {
160    None,
161    Minimal,
162    Low,
163    Medium,
164    High,
165    #[serde(rename = "xhigh")]
166    XHigh,
167    Max,
168}
169
170impl EffortLevel {
171    /// The ladder, lowest first.
172    pub const LADDER: [EffortLevel; 7] = [
173        Self::None,
174        Self::Minimal,
175        Self::Low,
176        Self::Medium,
177        Self::High,
178        Self::XHigh,
179        Self::Max,
180    ];
181
182    pub fn parse(s: &str) -> Option<Self> {
183        let s = s.to_ascii_lowercase();
184        Self::LADDER.into_iter().find(|level| level.as_str() == s)
185    }
186
187    pub const fn as_str(self) -> &'static str {
188        match self {
189            Self::None => "none",
190            Self::Minimal => "minimal",
191            Self::Low => "low",
192            Self::Medium => "medium",
193            Self::High => "high",
194            Self::XHigh => "xhigh",
195            Self::Max => "max",
196        }
197    }
198}
199
200/// What a layer asks for: a level, or the harness's own default (`auto`, or YAML `null`).
201/// A separate type so `auto` never meets ladder order. A layer field is `Option<EffortRequest>`:
202/// `None` is a key left out, which falls through to the next layer, and `Some(Default)` overrides
203/// the lower layers and sends no effort.
204#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
205pub enum EffortRequest {
206    Default,
207    Level(EffortLevel),
208}
209
210impl EffortRequest {
211    /// The values `parse` accepts, as the invalid-value errors list them.
212    pub const ALLOWED: &'static str = "auto, none, minimal, low, medium, high, xhigh, max";
213
214    pub fn parse(s: &str) -> Option<Self> {
215        if s.eq_ignore_ascii_case("auto") {
216            return Some(Self::Default);
217        }
218        EffortLevel::parse(s).map(Self::Level)
219    }
220
221    pub const fn as_str(self) -> &'static str {
222        match self {
223            Self::Default => "auto",
224            Self::Level(level) => level.as_str(),
225        }
226    }
227}
228
229impl serde::Serialize for EffortRequest {
230    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
231        serializer.serialize_str(self.as_str())
232    }
233}
234
235/// Reads the same spellings `parse` does, so a config field typed `EffortRequest` holds the
236/// canonical request and no later reader re-parses a string.
237impl<'de> serde::Deserialize<'de> for EffortRequest {
238    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
239        let text = String::deserialize(deserializer)?;
240        Self::parse(&text).ok_or_else(|| {
241            serde::de::Error::custom(format!(
242                "`effort` has invalid value `{text}`; allowed: {}",
243                Self::ALLOWED
244            ))
245        })
246    }
247}
248
249/// Strongly-typed representation of an agent profile's frontmatter.
250///
251/// Parsed from YAML frontmatter by [`read`].
252/// Used for:
253/// - Compile-time validation (mode values, passthrough shape)
254/// - Dual-surface routing (harness → output target)
255/// - Per-target lowering (field lowering per agent-compilation-mapping.md)
256#[derive(Debug, Clone, serde::Serialize)]
257#[serde(rename_all = "kebab-case")]
258pub struct AgentProfile {
259    // --- Identity fields ---
260    pub name: Option<String>,
261    pub description: Option<String>,
262
263    // --- Routing fields ---
264    pub harness: Option<HarnessId>,
265
266    // --- Model fields ---
267    pub model: Option<String>,
268    /// The agent's ordered `models` list; the first entry is the default. `None` when the
269    /// profile uses the older `model` and `model-policies` spelling.
270    #[serde(skip_serializing_if = "Option::is_none")]
271    pub models: Option<Vec<ModelEntry>>,
272
273    // --- Runtime policy fields ---
274    pub mode: Option<AgentMode>,
275    pub model_invocable: bool,
276    /// Whether the user can invoke this agent directly (slash command, picker, etc.).
277    pub user_invocable: bool,
278    /// `true` when source frontmatter explicitly set `model-invocable`.
279    #[serde(skip)]
280    pub had_model_invocable_field: bool,
281    /// `true` when source frontmatter explicitly set `user-invocable`.
282    #[serde(skip)]
283    pub had_user_invocable_field: bool,
284    pub approval: Option<ApprovalMode>,
285    pub sandbox: Option<SandboxMode>,
286    pub network: Option<NetworkPolicy>,
287    pub network_allow: PermissionSet<NetworkHost>,
288    pub network_deny: PermissionSet<NetworkHost>,
289    pub effort: Option<EffortRequest>,
290
291    // --- Tool fields ---
292    pub skills: SkillsSpec,
293    pub subagents: Vec<String>,
294    /// `tools:` and `disallowed-tools:` as one rule list. An allowlist has an explicit
295    /// `'*': deny`; deprecated list form only grants its entries.
296    pub tools: EffectiveToolPolicy,
297
298    // --- Override tables ---
299    pub harness_overrides: HarnessOverrides,
300    pub model_policies: Vec<ModelPolicyRule>,
301}
302
303impl AgentProfile {
304    /// The harness's passthrough block as a JSON map (keys then sort), if it has entries.
305    pub fn effective_native_config(
306        &self,
307        harness: &HarnessId,
308    ) -> Option<serde_json::Map<String, serde_json::Value>> {
309        self.harness_overrides
310            .get(harness)
311            .filter(|map| !map.is_empty())
312            .map(|map| {
313                map.iter()
314                    .map(|(key, value)| (key.clone(), value.to_json()))
315                    .collect()
316            })
317    }
318}
319
320fn push_agent_invalid(
321    diags: &mut Vec<crate::diagnostic::SchemaDiagnostic>,
322    path: Vec<crate::diagnostic::PathSegment>,
323    value: impl Into<String>,
324    allowed: &'static str,
325) {
326    push_invalid("agent", diags, path, value, allowed);
327}
328
329fn push_unknown_harness(diags: &mut Vec<crate::diagnostic::SchemaDiagnostic>, value: &str) {
330    use crate::diagnostic::{SchemaDiagnostic, Severity, key_path};
331    diags.push(SchemaDiagnostic::new(
332        "harness.unknown",
333        Severity::Error,
334        key_path("harness"),
335        format!(
336            "unknown harness `{value}`; known: {}",
337            crate::harness::names()
338        ),
339    ));
340}
341
342/// `field` is the list the rule or entry sits in: `model-policies` or `models`. An entry writes
343/// its settings flat, a rule under `override`.
344fn push_model_policy_parse_error(
345    diags: &mut Vec<crate::diagnostic::SchemaDiagnostic>,
346    field: &str,
347    position: usize,
348    error: crate::model_policy::ModelPolicyRuleParseError,
349) {
350    use crate::diagnostic::{PathSegment, key_path};
351    let mut rule_path = key_path(field);
352    rule_path.push(PathSegment::Index(position));
353    let child = |key: &str| {
354        let mut path = rule_path.clone();
355        path.push(PathSegment::Key(key.to_owned()));
356        path
357    };
358    let grandchild = |first: &str, second: &str| {
359        if field == "models" {
360            return child(second);
361        }
362        let mut path = child(first);
363        path.push(PathSegment::Key(second.to_owned()));
364        path
365    };
366    match error {
367        crate::model_policy::ModelPolicyRuleParseError::RuleMustBeMapping { found } => {
368            push_agent_invalid(diags, rule_path, found, "mapping with match and override");
369        }
370        crate::model_policy::ModelPolicyRuleParseError::MatchMissing => {
371            push_agent_invalid(
372                diags,
373                child("match"),
374                "<missing>",
375                "mapping with exactly one of model, alias, model-glob",
376            );
377        }
378        crate::model_policy::ModelPolicyRuleParseError::MatchMustBeMapping { found } => {
379            push_agent_invalid(
380                diags,
381                child("match"),
382                found,
383                "mapping with exactly one of model, alias, model-glob",
384            );
385        }
386        crate::model_policy::ModelPolicyRuleParseError::MatchMustContainExactlyOne { found } => {
387            push_agent_invalid(
388                diags,
389                child("match"),
390                found,
391                "exactly one of model, alias, model-glob",
392            );
393        }
394        crate::model_policy::ModelPolicyRuleParseError::MatchKeyMustBeString { found } => {
395            push_agent_invalid(diags, child("match"), found, "model, alias, model-glob");
396        }
397        crate::model_policy::ModelPolicyRuleParseError::UnknownMatchKey { key } => {
398            push_agent_invalid(diags, child("match"), key, "model, alias, model-glob");
399        }
400        crate::model_policy::ModelPolicyRuleParseError::MatchValueMustBeString { key, found } => {
401            push_agent_invalid(diags, grandchild("match", &key), found, "non-empty string");
402        }
403        crate::model_policy::ModelPolicyRuleParseError::MatchValueEmpty { key } => {
404            push_agent_invalid(
405                diags,
406                grandchild("match", &key),
407                "<empty>",
408                "non-empty string",
409            );
410        }
411        crate::model_policy::ModelPolicyRuleParseError::OverrideMustBeMapping { found } => {
412            push_agent_invalid(diags, child("override"), found, "mapping");
413        }
414        crate::model_policy::ModelPolicyRuleParseError::UnknownOverrideKey { key } => {
415            push_agent_invalid(
416                diags,
417                grandchild("override", &key),
418                key,
419                "effort, sandbox, approval, network",
420            );
421        }
422        crate::model_policy::ModelPolicyRuleParseError::NetworkHostsNotAllowed { key } => {
423            push_agent_invalid(
424                diags,
425                grandchild("override", &key),
426                key,
427                "network host sets on settings, profile, overlay, or CLI",
428            );
429        }
430        crate::model_policy::ModelPolicyRuleParseError::OverrideValueInvalid {
431            key,
432            found,
433            allowed,
434        } => {
435            push_agent_invalid(diags, grandchild("override", &key), found, allowed);
436        }
437        crate::model_policy::ModelPolicyRuleParseError::NoFallbackMustBeBoolean { found } => {
438            push_agent_invalid(diags, child("no-fallback"), found, "boolean");
439        }
440        crate::model_policy::ModelPolicyRuleParseError::WhenInvalid { found } => {
441            push_agent_invalid(diags, child("when"), found, "non-empty one-line string");
442        }
443        crate::model_policy::ModelPolicyRuleParseError::EntryMustBeNameOrMapping { found } => {
444            push_agent_invalid(
445                diags,
446                rule_path,
447                found,
448                "model name or mapping with `model`",
449            );
450        }
451        crate::model_policy::ModelPolicyRuleParseError::EntryModelMissing => {
452            push_agent_invalid(diags, child("model"), "<missing>", "non-empty string");
453        }
454        crate::model_policy::ModelPolicyRuleParseError::EntryModelInvalid { found } => {
455            push_agent_invalid(diags, child("model"), found, "non-empty string");
456        }
457    }
458}
459
460fn parse_model_policies(
461    val: &Value,
462    diags: &mut Vec<crate::diagnostic::SchemaDiagnostic>,
463) -> Vec<ModelPolicyRule> {
464    let Some(seq) = val.as_sequence() else {
465        push_agent_invalid(
466            diags,
467            crate::diagnostic::key_path("model-policies"),
468            crate::ordered::plain(val),
469            "sequence of rules",
470        );
471        return vec![];
472    };
473
474    let mut out = Vec::new();
475    for (index, entry) in seq.iter().enumerate() {
476        let reading = crate::model_policy::read_model_policy_rule(entry);
477        for unknown in reading.unknown {
478            let mut path = crate::diagnostic::key_path("model-policies");
479            path.push(crate::diagnostic::PathSegment::Index(index));
480            path.push(crate::diagnostic::PathSegment::Key(unknown.clone()));
481            diags.push(crate::diagnostic::unknown_field(
482                path,
483                &format!("model-policies[{index}]"),
484                &unknown,
485            ));
486        }
487        match reading.rule {
488            Ok(rule) => out.push(rule),
489            Err(errors) => {
490                for error in errors {
491                    push_model_policy_parse_error(diags, "model-policies", index, error);
492                }
493            }
494        }
495    }
496    out
497}
498
499fn parse_models(
500    val: &Value,
501    diags: &mut Vec<crate::diagnostic::SchemaDiagnostic>,
502) -> Vec<ModelEntry> {
503    let Some(seq) = val.as_sequence() else {
504        push_agent_invalid(
505            diags,
506            crate::diagnostic::key_path("models"),
507            crate::ordered::plain(val),
508            "sequence of model names or mappings",
509        );
510        return vec![];
511    };
512
513    let mut out = Vec::new();
514    for (index, entry) in seq.iter().enumerate() {
515        let entry_path = || {
516            let mut path = crate::diagnostic::key_path("models");
517            path.push(crate::diagnostic::PathSegment::Index(index));
518            path
519        };
520        if entry.as_str() == Some(crate::model_policy::MODELS_SPLICE) {
521            diags.push(crate::diagnostic::SchemaDiagnostic::new(
522                "models.splice",
523                crate::diagnostic::Severity::Error,
524                entry_path(),
525                format!(
526                    "`models[{index}]` is `{}`, which stands for the list of the layer below; a profile has none",
527                    crate::model_policy::MODELS_SPLICE
528                ),
529            ));
530            continue;
531        }
532        let reading = crate::model_policy::read_model_entry(entry);
533        for unknown in reading.unknown {
534            let mut path = entry_path();
535            path.push(crate::diagnostic::PathSegment::Key(unknown.clone()));
536            diags.push(crate::diagnostic::unknown_field(
537                path,
538                &format!("models[{index}]"),
539                &unknown,
540            ));
541        }
542        match reading.entry {
543            Ok(entry) => out.push(entry),
544            Err(errors) => {
545                for error in errors {
546                    push_model_policy_parse_error(diags, "models", index, error);
547                }
548            }
549        }
550    }
551    out
552}
553
554fn parse_invocability_field(
555    field: &str,
556    raw: Option<&Value>,
557    diags: &mut Vec<crate::diagnostic::SchemaDiagnostic>,
558) -> (bool, bool) {
559    let (value, had_field, invalid) = parse_invocability_axis(raw);
560    if let Some(invalid) = invalid {
561        push_agent_invalid(
562            diags,
563            crate::diagnostic::key_path(field),
564            invalid,
565            "boolean",
566        );
567    }
568    (value, had_field)
569}
570
571fn read_string(
572    value: &Value,
573    field: &'static str,
574    non_empty: bool,
575    diags: &mut Vec<crate::diagnostic::SchemaDiagnostic>,
576) -> Option<String> {
577    let Some(value) = value.as_str() else {
578        diags.push(crate::diagnostic::SchemaDiagnostic::new(
579            "field.type",
580            crate::diagnostic::Severity::Error,
581            crate::diagnostic::key_path(field),
582            format!("`{field}` must be a string"),
583        ));
584        return None;
585    };
586    if non_empty {
587        let value = value.trim();
588        if value.is_empty() {
589            diags.push(crate::diagnostic::SchemaDiagnostic::new(
590                "field.value",
591                crate::diagnostic::Severity::Error,
592                crate::diagnostic::key_path(field),
593                format!("`{field}` must be a non-empty string"),
594            ));
595            return None;
596        }
597        return Some(value.to_owned());
598    }
599    Some(value.to_owned())
600}
601
602fn read_string_list(
603    value: Option<&Value>,
604    path: Vec<crate::diagnostic::PathSegment>,
605    diags: &mut Vec<crate::diagnostic::SchemaDiagnostic>,
606) -> Vec<String> {
607    use crate::diagnostic::{PathSegment, SchemaDiagnostic, Severity, display_path};
608    let Some(value) = value else {
609        return Vec::new();
610    };
611    let Some(values) = value.as_sequence() else {
612        let display = display_path(&path);
613        diags.push(SchemaDiagnostic::new(
614            "field.type",
615            Severity::Error,
616            path,
617            format!("`{display}` must be a list of non-empty strings"),
618        ));
619        return Vec::new();
620    };
621    let display = display_path(&path);
622    values
623        .iter()
624        .enumerate()
625        .filter_map(|(index, value)| {
626            if let Value::String(text) = value
627                && !text.trim().is_empty()
628            {
629                return Some(text.clone());
630            }
631            let mut entry_path = path.clone();
632            entry_path.push(PathSegment::Index(index));
633            diags.push(SchemaDiagnostic::new(
634                if value.is_string() {
635                    "field.value"
636                } else {
637                    "field.type"
638                },
639                Severity::Error,
640                entry_path,
641                format!("`{display}` entry {} must be a non-empty string", index + 1),
642            ));
643            None
644        })
645        .collect()
646}
647
648/// A host set: a list of hosts, or for an allow set `{replace: [...]}`, which clears the lower
649/// layers' hosts. A package profile cannot replace a deny set, so a project's deny always applies.
650fn read_host_set(
651    field: &'static str,
652    value: &Value,
653    allow_replace: bool,
654    diags: &mut Vec<crate::diagnostic::SchemaDiagnostic>,
655) -> PermissionSet<NetworkHost> {
656    use crate::diagnostic::{PathSegment, key_path};
657    const SHAPE: &str = "list of exact hosts, IPs, *.example.com, or **.example.com; or {replace: [...]} for an allow set";
658    let mut path = key_path(field);
659    let (replace, entries) = match value {
660        Value::Sequence(entries) => (false, entries),
661        Value::Mapping(mapping)
662            if mapping.len() == 1
663                && mapping
664                    .get("replace")
665                    .is_some_and(|entries| entries.is_sequence()) =>
666        {
667            if !allow_replace {
668                push_agent_invalid(
669                    diags,
670                    path,
671                    crate::ordered::plain(value),
672                    "plain list; package profiles cannot replace a deny set",
673                );
674                return PermissionSet::default();
675            }
676            path.push(PathSegment::Key("replace".to_owned()));
677            let entries = mapping.get("replace").and_then(Value::as_sequence);
678            (true, entries.expect("checked to be a sequence"))
679        }
680        _ => {
681            push_agent_invalid(diags, path, crate::ordered::plain(value), SHAPE);
682            return PermissionSet::default();
683        }
684    };
685    let hosts = entries
686        .iter()
687        .enumerate()
688        .filter_map(|(index, entry)| {
689            let parsed = entry
690                .as_str()
691                .ok_or_else(|| crate::ordered::plain(entry))
692                .and_then(|text| text.parse::<NetworkHost>().map_err(|_| text.to_owned()));
693            parsed
694                .map_err(|found| {
695                    let mut entry_path = path.clone();
696                    entry_path.push(PathSegment::Index(index));
697                    push_agent_invalid(diags, entry_path, found, NetworkHost::ALLOWED);
698                })
699                .ok()
700        })
701        .collect();
702    if replace {
703        PermissionSet::Replace { replace: hosts }
704    } else {
705        PermissionSet::Add(hosts)
706    }
707}
708
709fn read_skills(value: &Value, diags: &mut Vec<crate::diagnostic::SchemaDiagnostic>) -> SkillsSpec {
710    use crate::diagnostic::{PathSegment, key_path};
711    let root = key_path("skills");
712    let Value::Mapping(mapping) = value else {
713        return SkillsSpec {
714            load: read_string_list(Some(value), root, diags),
715            available: Vec::new(),
716        };
717    };
718    let read_axis = |name: &str, diags: &mut Vec<_>| {
719        let mut path = root.clone();
720        path.push(PathSegment::Key(name.to_owned()));
721        read_string_list(mapping.get(Value::String(name.to_owned())), path, diags)
722    };
723    SkillsSpec {
724        load: read_axis("load", diags),
725        available: read_axis("available", diags),
726    }
727}
728
729pub(crate) fn read_fields(
730    fm: &Frontmatter,
731    diags: &mut Vec<crate::diagnostic::SchemaDiagnostic>,
732) -> AgentProfile {
733    use crate::diagnostic::{SchemaDiagnostic, Severity, key_path};
734
735    let mut profile = AgentProfile {
736        name: None,
737        description: None,
738        harness: None,
739        model: None,
740        models: None,
741        mode: None,
742        model_invocable: true,
743        user_invocable: true,
744        had_model_invocable_field: false,
745        had_user_invocable_field: false,
746        approval: None,
747        sandbox: None,
748        network: None,
749        network_allow: PermissionSet::default(),
750        network_deny: PermissionSet::default(),
751        effort: None,
752        skills: SkillsSpec::default(),
753        subagents: Vec::new(),
754        tools: EffectiveToolPolicy::default(),
755        harness_overrides: HarnessOverrides::default(),
756        model_policies: Vec::new(),
757    };
758
759    for key in fm.keys() {
760        let value = fm.get(&key).expect("frontmatter key came from mapping");
761        match key.as_str() {
762            "name" => profile.name = read_string(value, "name", true, diags),
763            "description" => {
764                profile.description = read_string(value, "description", false, diags);
765            }
766            "harness" => {
767                profile.harness = read_string(value, "harness", false, diags).and_then(|name| {
768                    crate::harness::parse(&name).or_else(|| {
769                        match crate::retired::harness_diagnostic(&name, key_path("harness")) {
770                            Some(retired) => diags.push(retired),
771                            None => push_unknown_harness(diags, &name),
772                        }
773                        None
774                    })
775                });
776            }
777            "model" => profile.model = read_string(value, "model", true, diags),
778            "mode" => {
779                profile.mode =
780                    read_string(value, "mode", false, diags).and_then(|mode| match mode.as_str() {
781                        "primary" => Some(AgentMode::Primary),
782                        "subagent" => Some(AgentMode::Subagent),
783                        other => {
784                            push_agent_invalid(
785                                diags,
786                                key_path("mode"),
787                                other.to_string(),
788                                "primary, subagent",
789                            );
790                            None
791                        }
792                    });
793            }
794            "model-invocable" => {
795                (profile.model_invocable, profile.had_model_invocable_field) =
796                    parse_invocability_field("model-invocable", Some(value), diags);
797            }
798            "user-invocable" => {
799                (profile.user_invocable, profile.had_user_invocable_field) =
800                    parse_invocability_field("user-invocable", Some(value), diags);
801            }
802            "approval" => {
803                profile.approval =
804                    read_string(value, "approval", false, diags).and_then(|approval| {
805                        ApprovalMode::parse(&approval).or_else(|| {
806                            push_agent_invalid(
807                                diags,
808                                key_path("approval"),
809                                approval,
810                                ApprovalMode::ALLOWED,
811                            );
812                            None
813                        })
814                    });
815            }
816            "sandbox" => {
817                profile.sandbox = read_string(value, "sandbox", false, diags).and_then(|sandbox| {
818                    SandboxMode::parse(&sandbox).or_else(|| {
819                        push_agent_invalid(
820                            diags,
821                            key_path("sandbox"),
822                            sandbox,
823                            SandboxMode::ALLOWED,
824                        );
825                        None
826                    })
827                });
828            }
829            "network" => {
830                profile.network = read_string(value, "network", false, diags).and_then(|network| {
831                    NetworkPolicy::parse(&network).or_else(|| {
832                        push_agent_invalid(
833                            diags,
834                            key_path("network"),
835                            network,
836                            NetworkPolicy::ALLOWED,
837                        );
838                        None
839                    })
840                });
841            }
842            "network-allow" => {
843                profile.network_allow = read_host_set("network-allow", value, true, diags);
844            }
845            "network-deny" => {
846                profile.network_deny = read_host_set("network-deny", value, false, diags);
847            }
848            "effort" if value.is_null() => profile.effort = Some(EffortRequest::Default),
849            "effort" => {
850                profile.effort = read_string(value, "effort", false, diags).and_then(|effort| {
851                    EffortRequest::parse(&effort).or_else(|| {
852                        push_agent_invalid(
853                            diags,
854                            key_path("effort"),
855                            effort,
856                            EffortRequest::ALLOWED,
857                        );
858                        None
859                    })
860                });
861            }
862            "skills" => profile.skills = read_skills(value, diags),
863            "subagents" => {
864                profile.subagents = read_string_list(Some(value), key_path("subagents"), diags);
865            }
866            "tools" => {
867                if value.is_sequence() {
868                    diags.push(SchemaDiagnostic::new(
869                        "tools.list-form",
870                        Severity::Error,
871                        key_path("tools"),
872                        "`tools` must be an action map; list form was removed",
873                    ));
874                } else {
875                    let mut invalid = |path, value: &str, allowed: &'static str| {
876                        push_agent_invalid(diags, path, value, allowed);
877                    };
878                    profile.tools = tool_policy::parse_tool_policy(Some(value), &mut invalid);
879                }
880            }
881            "harness-overrides" => {
882                profile.harness_overrides = parse_harness_overrides("agent", value, diags);
883            }
884            "model-policies" => profile.model_policies = parse_model_policies(value, diags),
885            "models" => profile.models = Some(parse_models(value, diags)),
886            _ => diags.push(unrecognized_field(DefinitionKind::Agent, &key)),
887        }
888    }
889
890    check_model_list(&profile, diags);
891    profile
892}
893
894/// What the profile's two spellings of its model list may not do together, and what a list may
895/// not repeat. `mars sync` fails the package that has such a profile.
896fn check_model_list(profile: &AgentProfile, diags: &mut Vec<crate::diagnostic::SchemaDiagnostic>) {
897    use crate::diagnostic::{PathSegment, SchemaDiagnostic, Severity, key_path};
898    for (index, rule) in profile.model_policies.iter().enumerate() {
899        if rule.match_type != ModelPolicyMatchType::ModelGlob || rule.when.is_none() {
900            continue;
901        }
902        let mut path = key_path("model-policies");
903        path.extend([PathSegment::Index(index), PathSegment::Key("when".into())]);
904        diags.push(SchemaDiagnostic::new(
905            "models.glob-when",
906            Severity::Warning,
907            path,
908            format!(
909                "`model-policies[{index}]` is a glob rule, and only list entries show their `when`"
910            ),
911        ));
912    }
913    let Some(models) = &profile.models else {
914        return;
915    };
916    let error = |code: &str, path, message: String| {
917        SchemaDiagnostic::new(code, Severity::Error, path, message)
918    };
919    if profile.model.is_some() {
920        diags.push(error(
921            "models.with-model",
922            key_path("model"),
923            "`model` beside `models`: the first entry of `models` is the default; delete `model`"
924                .into(),
925        ));
926    }
927    for (index, rule) in profile.model_policies.iter().enumerate() {
928        if rule.match_type == ModelPolicyMatchType::ModelGlob {
929            continue;
930        }
931        let mut path = key_path("model-policies");
932        path.push(PathSegment::Index(index));
933        diags.push(error(
934            "models.with-rule",
935            path,
936            format!(
937                "`model-policies[{index}]` names `{}` beside `models`: write it as an entry of `models`; `model-policies` keeps only glob rules there",
938                rule.match_value
939            ),
940        ));
941    }
942    for problem in crate::model_policy::list_problems(models.iter().map(Some)) {
943        let mut path = key_path("models");
944        path.extend(problem.index.map(PathSegment::Index));
945        diags.push(error(problem.code, path, problem.message));
946    }
947}
948
949/// Read an Agent definition through the versioned schema contract.
950pub fn read(content: &str) -> crate::read::DefinitionRead<AgentProfile> {
951    crate::read::read_with(content, read_fields)
952}