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