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::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
269    // --- Runtime policy fields ---
270    pub mode: Option<AgentMode>,
271    pub model_invocable: bool,
272    /// Whether the user can invoke this agent directly (slash command, picker, etc.).
273    pub user_invocable: bool,
274    /// `true` when source frontmatter explicitly set `model-invocable`.
275    #[serde(skip)]
276    pub had_model_invocable_field: bool,
277    /// `true` when source frontmatter explicitly set `user-invocable`.
278    #[serde(skip)]
279    pub had_user_invocable_field: bool,
280    pub approval: Option<ApprovalMode>,
281    pub sandbox: Option<SandboxMode>,
282    pub network: Option<NetworkPolicy>,
283    pub network_allow: PermissionSet<NetworkHost>,
284    pub network_deny: PermissionSet<NetworkHost>,
285    pub effort: Option<EffortRequest>,
286
287    // --- Tool fields ---
288    pub skills: SkillsSpec,
289    pub subagents: Vec<String>,
290    /// `tools:` and `disallowed-tools:` as one rule list. An allowlist has an explicit
291    /// `'*': deny`; deprecated list form only grants its entries.
292    pub tools: EffectiveToolPolicy,
293
294    // --- Override tables ---
295    pub harness_overrides: HarnessOverrides,
296    pub model_policies: Vec<ModelPolicyRule>,
297}
298
299impl AgentProfile {
300    /// The harness's passthrough block as a JSON map (keys then sort), if it has entries.
301    pub fn effective_native_config(
302        &self,
303        harness: &HarnessId,
304    ) -> Option<serde_json::Map<String, serde_json::Value>> {
305        self.harness_overrides
306            .get(harness)
307            .filter(|map| !map.is_empty())
308            .map(|map| {
309                map.iter()
310                    .map(|(key, value)| (key.clone(), value.to_json()))
311                    .collect()
312            })
313    }
314}
315
316fn push_agent_invalid(
317    diags: &mut Vec<crate::diagnostic::SchemaDiagnostic>,
318    path: Vec<crate::diagnostic::PathSegment>,
319    value: impl Into<String>,
320    allowed: &'static str,
321) {
322    push_invalid("agent", diags, path, value, allowed);
323}
324
325fn push_unknown_harness(diags: &mut Vec<crate::diagnostic::SchemaDiagnostic>, value: &str) {
326    use crate::diagnostic::{SchemaDiagnostic, Severity, key_path};
327    diags.push(SchemaDiagnostic::new(
328        "harness.unknown",
329        Severity::Error,
330        key_path("harness"),
331        format!("unknown harness `{value}`; known: claude, codex, opencode, cursor, pi"),
332    ));
333}
334
335fn push_model_policy_parse_error(
336    diags: &mut Vec<crate::diagnostic::SchemaDiagnostic>,
337    position: usize,
338    error: crate::model_policy::ModelPolicyRuleParseError,
339) {
340    use crate::diagnostic::{PathSegment, key_path};
341    let mut rule_path = key_path("model-policies");
342    rule_path.push(PathSegment::Index(position));
343    let child = |key: &str| {
344        let mut path = rule_path.clone();
345        path.push(PathSegment::Key(key.to_owned()));
346        path
347    };
348    let grandchild = |first: &str, second: &str| {
349        let mut path = child(first);
350        path.push(PathSegment::Key(second.to_owned()));
351        path
352    };
353    match error {
354        crate::model_policy::ModelPolicyRuleParseError::RuleMustBeMapping { found } => {
355            push_agent_invalid(diags, rule_path, found, "mapping with match and override");
356        }
357        crate::model_policy::ModelPolicyRuleParseError::MatchMissing => {
358            push_agent_invalid(
359                diags,
360                child("match"),
361                "<missing>",
362                "mapping with exactly one of model, alias, model-glob",
363            );
364        }
365        crate::model_policy::ModelPolicyRuleParseError::MatchMustBeMapping { found } => {
366            push_agent_invalid(
367                diags,
368                child("match"),
369                found,
370                "mapping with exactly one of model, alias, model-glob",
371            );
372        }
373        crate::model_policy::ModelPolicyRuleParseError::MatchMustContainExactlyOne { found } => {
374            push_agent_invalid(
375                diags,
376                child("match"),
377                found,
378                "exactly one of model, alias, model-glob",
379            );
380        }
381        crate::model_policy::ModelPolicyRuleParseError::MatchKeyMustBeString { found } => {
382            push_agent_invalid(diags, child("match"), found, "model, alias, model-glob");
383        }
384        crate::model_policy::ModelPolicyRuleParseError::UnknownMatchKey { key } => {
385            push_agent_invalid(diags, child("match"), key, "model, alias, model-glob");
386        }
387        crate::model_policy::ModelPolicyRuleParseError::MatchValueMustBeString { key, found } => {
388            push_agent_invalid(diags, grandchild("match", &key), found, "non-empty string");
389        }
390        crate::model_policy::ModelPolicyRuleParseError::MatchValueEmpty { key } => {
391            push_agent_invalid(
392                diags,
393                grandchild("match", &key),
394                "<empty>",
395                "non-empty string",
396            );
397        }
398        crate::model_policy::ModelPolicyRuleParseError::OverrideMustBeMapping { found } => {
399            push_agent_invalid(diags, child("override"), found, "mapping");
400        }
401        crate::model_policy::ModelPolicyRuleParseError::UnknownOverrideKey { key } => {
402            push_agent_invalid(
403                diags,
404                grandchild("override", &key),
405                key,
406                "effort, sandbox, approval, network",
407            );
408        }
409        crate::model_policy::ModelPolicyRuleParseError::NetworkHostsNotAllowed { key } => {
410            push_agent_invalid(
411                diags,
412                grandchild("override", &key),
413                key,
414                "network host sets on settings, profile, overlay, or CLI",
415            );
416        }
417        crate::model_policy::ModelPolicyRuleParseError::OverrideValueInvalid {
418            key,
419            found,
420            allowed,
421        } => {
422            push_agent_invalid(diags, grandchild("override", &key), found, allowed);
423        }
424        crate::model_policy::ModelPolicyRuleParseError::NoFallbackMustBeBoolean { found } => {
425            push_agent_invalid(diags, child("no-fallback"), found, "boolean");
426        }
427        crate::model_policy::ModelPolicyRuleParseError::WhenInvalid { found } => {
428            push_agent_invalid(diags, child("when"), found, "non-empty one-line string");
429        }
430    }
431}
432
433fn parse_model_policies(
434    val: &Value,
435    diags: &mut Vec<crate::diagnostic::SchemaDiagnostic>,
436) -> Vec<ModelPolicyRule> {
437    let Some(seq) = val.as_sequence() else {
438        push_agent_invalid(
439            diags,
440            crate::diagnostic::key_path("model-policies"),
441            crate::ordered::plain(val),
442            "sequence of rules",
443        );
444        return vec![];
445    };
446
447    let mut out = Vec::new();
448    for (index, entry) in seq.iter().enumerate() {
449        let reading = crate::model_policy::read_model_policy_rule(entry);
450        for unknown in reading.unknown {
451            let mut path = crate::diagnostic::key_path("model-policies");
452            path.push(crate::diagnostic::PathSegment::Index(index));
453            path.push(crate::diagnostic::PathSegment::Key(unknown.clone()));
454            diags.push(crate::diagnostic::unknown_field(
455                path,
456                &format!("model-policies[{index}]"),
457                &unknown,
458            ));
459        }
460        match reading.rule {
461            Ok(rule) => out.push(rule),
462            Err(errors) => {
463                for error in errors {
464                    push_model_policy_parse_error(diags, index, error);
465                }
466            }
467        }
468    }
469    out
470}
471
472fn parse_invocability_field(
473    field: &str,
474    raw: Option<&Value>,
475    diags: &mut Vec<crate::diagnostic::SchemaDiagnostic>,
476) -> (bool, bool) {
477    let (value, had_field, invalid) = parse_invocability_axis(raw);
478    if let Some(invalid) = invalid {
479        push_agent_invalid(
480            diags,
481            crate::diagnostic::key_path(field),
482            invalid,
483            "boolean",
484        );
485    }
486    (value, had_field)
487}
488
489fn read_string(
490    value: &Value,
491    field: &'static str,
492    non_empty: bool,
493    diags: &mut Vec<crate::diagnostic::SchemaDiagnostic>,
494) -> Option<String> {
495    let Some(value) = value.as_str() else {
496        diags.push(crate::diagnostic::SchemaDiagnostic::new(
497            "field.type",
498            crate::diagnostic::Severity::Error,
499            crate::diagnostic::key_path(field),
500            format!("`{field}` must be a string"),
501        ));
502        return None;
503    };
504    if non_empty {
505        let value = value.trim();
506        if value.is_empty() {
507            diags.push(crate::diagnostic::SchemaDiagnostic::new(
508                "field.value",
509                crate::diagnostic::Severity::Error,
510                crate::diagnostic::key_path(field),
511                format!("`{field}` must be a non-empty string"),
512            ));
513            return None;
514        }
515        return Some(value.to_owned());
516    }
517    Some(value.to_owned())
518}
519
520fn read_string_list(
521    value: Option<&Value>,
522    path: Vec<crate::diagnostic::PathSegment>,
523    diags: &mut Vec<crate::diagnostic::SchemaDiagnostic>,
524) -> Vec<String> {
525    use crate::diagnostic::{PathSegment, SchemaDiagnostic, Severity, display_path};
526    let Some(value) = value else {
527        return Vec::new();
528    };
529    let Some(values) = value.as_sequence() else {
530        let display = display_path(&path);
531        diags.push(SchemaDiagnostic::new(
532            "field.type",
533            Severity::Error,
534            path,
535            format!("`{display}` must be a list of non-empty strings"),
536        ));
537        return Vec::new();
538    };
539    let display = display_path(&path);
540    values
541        .iter()
542        .enumerate()
543        .filter_map(|(index, value)| {
544            if let Value::String(text) = value
545                && !text.trim().is_empty()
546            {
547                return Some(text.clone());
548            }
549            let mut entry_path = path.clone();
550            entry_path.push(PathSegment::Index(index));
551            diags.push(SchemaDiagnostic::new(
552                if value.is_string() {
553                    "field.value"
554                } else {
555                    "field.type"
556                },
557                Severity::Error,
558                entry_path,
559                format!("`{display}` entry {} must be a non-empty string", index + 1),
560            ));
561            None
562        })
563        .collect()
564}
565
566/// A host set: a list of hosts, or for an allow set `{replace: [...]}`, which clears the lower
567/// layers' hosts. A package profile cannot replace a deny set, so a project's deny always applies.
568fn read_host_set(
569    field: &'static str,
570    value: &Value,
571    allow_replace: bool,
572    diags: &mut Vec<crate::diagnostic::SchemaDiagnostic>,
573) -> PermissionSet<NetworkHost> {
574    use crate::diagnostic::{PathSegment, key_path};
575    const SHAPE: &str = "list of exact hosts, IPs, *.example.com, or **.example.com; or {replace: [...]} for an allow set";
576    let mut path = key_path(field);
577    let (replace, entries) = match value {
578        Value::Sequence(entries) => (false, entries),
579        Value::Mapping(mapping)
580            if mapping.len() == 1
581                && mapping
582                    .get("replace")
583                    .is_some_and(|entries| entries.is_sequence()) =>
584        {
585            if !allow_replace {
586                push_agent_invalid(
587                    diags,
588                    path,
589                    crate::ordered::plain(value),
590                    "plain list; package profiles cannot replace a deny set",
591                );
592                return PermissionSet::default();
593            }
594            path.push(PathSegment::Key("replace".to_owned()));
595            let entries = mapping.get("replace").and_then(Value::as_sequence);
596            (true, entries.expect("checked to be a sequence"))
597        }
598        _ => {
599            push_agent_invalid(diags, path, crate::ordered::plain(value), SHAPE);
600            return PermissionSet::default();
601        }
602    };
603    let hosts = entries
604        .iter()
605        .enumerate()
606        .filter_map(|(index, entry)| {
607            let parsed = entry
608                .as_str()
609                .ok_or_else(|| crate::ordered::plain(entry))
610                .and_then(|text| text.parse::<NetworkHost>().map_err(|_| text.to_owned()));
611            parsed
612                .map_err(|found| {
613                    let mut entry_path = path.clone();
614                    entry_path.push(PathSegment::Index(index));
615                    push_agent_invalid(diags, entry_path, found, NetworkHost::ALLOWED);
616                })
617                .ok()
618        })
619        .collect();
620    if replace {
621        PermissionSet::Replace { replace: hosts }
622    } else {
623        PermissionSet::Add(hosts)
624    }
625}
626
627fn read_skills(value: &Value, diags: &mut Vec<crate::diagnostic::SchemaDiagnostic>) -> SkillsSpec {
628    use crate::diagnostic::{PathSegment, key_path};
629    let root = key_path("skills");
630    let Value::Mapping(mapping) = value else {
631        return SkillsSpec {
632            load: read_string_list(Some(value), root, diags),
633            available: Vec::new(),
634        };
635    };
636    let read_axis = |name: &str, diags: &mut Vec<_>| {
637        let mut path = root.clone();
638        path.push(PathSegment::Key(name.to_owned()));
639        read_string_list(mapping.get(Value::String(name.to_owned())), path, diags)
640    };
641    SkillsSpec {
642        load: read_axis("load", diags),
643        available: read_axis("available", diags),
644    }
645}
646
647pub(crate) fn read_fields(
648    fm: &Frontmatter,
649    diags: &mut Vec<crate::diagnostic::SchemaDiagnostic>,
650) -> AgentProfile {
651    use crate::diagnostic::{SchemaDiagnostic, Severity, key_path};
652
653    let mut profile = AgentProfile {
654        name: None,
655        description: None,
656        harness: None,
657        model: None,
658        mode: None,
659        model_invocable: true,
660        user_invocable: true,
661        had_model_invocable_field: false,
662        had_user_invocable_field: false,
663        approval: None,
664        sandbox: None,
665        network: None,
666        network_allow: PermissionSet::default(),
667        network_deny: PermissionSet::default(),
668        effort: None,
669        skills: SkillsSpec::default(),
670        subagents: Vec::new(),
671        tools: EffectiveToolPolicy::default(),
672        harness_overrides: HarnessOverrides::default(),
673        model_policies: Vec::new(),
674    };
675
676    for key in fm.keys() {
677        let value = fm.get(&key).expect("frontmatter key came from mapping");
678        match key.as_str() {
679            "name" => profile.name = read_string(value, "name", true, diags),
680            "description" => {
681                profile.description = read_string(value, "description", false, diags);
682            }
683            "harness" => {
684                profile.harness = read_string(value, "harness", false, diags).and_then(|name| {
685                    crate::harness::parse(&name).or_else(|| {
686                        push_unknown_harness(diags, &name);
687                        None
688                    })
689                });
690            }
691            "model" => profile.model = read_string(value, "model", true, diags),
692            "mode" => {
693                profile.mode =
694                    read_string(value, "mode", false, diags).and_then(|mode| match mode.as_str() {
695                        "primary" => Some(AgentMode::Primary),
696                        "subagent" => Some(AgentMode::Subagent),
697                        other => {
698                            push_agent_invalid(
699                                diags,
700                                key_path("mode"),
701                                other.to_string(),
702                                "primary, subagent",
703                            );
704                            None
705                        }
706                    });
707            }
708            "model-invocable" => {
709                (profile.model_invocable, profile.had_model_invocable_field) =
710                    parse_invocability_field("model-invocable", Some(value), diags);
711            }
712            "user-invocable" => {
713                (profile.user_invocable, profile.had_user_invocable_field) =
714                    parse_invocability_field("user-invocable", Some(value), diags);
715            }
716            "approval" => {
717                profile.approval =
718                    read_string(value, "approval", false, diags).and_then(|approval| {
719                        ApprovalMode::parse(&approval).or_else(|| {
720                            push_agent_invalid(
721                                diags,
722                                key_path("approval"),
723                                approval,
724                                ApprovalMode::ALLOWED,
725                            );
726                            None
727                        })
728                    });
729            }
730            "sandbox" => {
731                profile.sandbox = read_string(value, "sandbox", false, diags).and_then(|sandbox| {
732                    SandboxMode::parse(&sandbox).or_else(|| {
733                        push_agent_invalid(
734                            diags,
735                            key_path("sandbox"),
736                            sandbox,
737                            SandboxMode::ALLOWED,
738                        );
739                        None
740                    })
741                });
742            }
743            "network" => {
744                profile.network = read_string(value, "network", false, diags).and_then(|network| {
745                    NetworkPolicy::parse(&network).or_else(|| {
746                        push_agent_invalid(
747                            diags,
748                            key_path("network"),
749                            network,
750                            NetworkPolicy::ALLOWED,
751                        );
752                        None
753                    })
754                });
755            }
756            "network-allow" => {
757                profile.network_allow = read_host_set("network-allow", value, true, diags);
758            }
759            "network-deny" => {
760                profile.network_deny = read_host_set("network-deny", value, false, diags);
761            }
762            "effort" if value.is_null() => profile.effort = Some(EffortRequest::Default),
763            "effort" => {
764                profile.effort = read_string(value, "effort", false, diags).and_then(|effort| {
765                    EffortRequest::parse(&effort).or_else(|| {
766                        push_agent_invalid(
767                            diags,
768                            key_path("effort"),
769                            effort,
770                            EffortRequest::ALLOWED,
771                        );
772                        None
773                    })
774                });
775            }
776            "skills" => profile.skills = read_skills(value, diags),
777            "subagents" => {
778                profile.subagents = read_string_list(Some(value), key_path("subagents"), diags);
779            }
780            "tools" => {
781                if value.is_sequence() {
782                    diags.push(SchemaDiagnostic::new(
783                        "tools.list-form",
784                        Severity::Error,
785                        key_path("tools"),
786                        "`tools` must be an action map; list form was removed",
787                    ));
788                } else {
789                    let mut invalid = |path, value: &str, allowed: &'static str| {
790                        push_agent_invalid(diags, path, value, allowed);
791                    };
792                    profile.tools = tool_policy::parse_tool_policy(Some(value), &mut invalid);
793                }
794            }
795            "harness-overrides" => {
796                profile.harness_overrides = parse_harness_overrides("agent", value, diags);
797            }
798            "model-policies" => profile.model_policies = parse_model_policies(value, diags),
799            _ => diags.push(unrecognized_field(DefinitionKind::Agent, &key)),
800        }
801    }
802
803    profile
804}
805
806/// Read an Agent definition through the versioned schema contract.
807pub fn read(content: &str) -> crate::read::DefinitionRead<AgentProfile> {
808    crate::read::read_with(content, read_fields)
809}