1use 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#[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 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 pub fn reserves(key: &str) -> bool {
53 Self::ALL.iter().any(|field| field.keys().contains(&key))
54 }
55}
56
57#[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#[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 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#[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 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#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
150#[serde(rename_all = "kebab-case")]
151pub enum EffortLevel {
152 None,
153 Low,
154 Medium,
155 High,
156 #[serde(rename = "xhigh")]
157 XHigh,
158 Max,
159}
160
161impl EffortLevel {
162 pub const ALLOWED: &'static str = "none, low, medium, high, xhigh, max";
164
165 pub fn parse(s: &str) -> Option<Self> {
166 match s.to_ascii_lowercase().as_str() {
167 "none" => Some(Self::None),
168 "low" => Some(Self::Low),
169 "medium" => Some(Self::Medium),
170 "high" => Some(Self::High),
171 "xhigh" => Some(Self::XHigh),
172 "max" => Some(Self::Max),
173 _ => None,
174 }
175 }
176
177 pub fn as_str(&self) -> &str {
178 match self {
179 Self::None => "none",
180 Self::Low => "low",
181 Self::Medium => "medium",
182 Self::High => "high",
183 Self::XHigh => "xhigh",
184 Self::Max => "max",
185 }
186 }
187}
188
189impl<'de> serde::Deserialize<'de> for EffortLevel {
192 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
193 let text = String::deserialize(deserializer)?;
194 Self::parse(&text).ok_or_else(|| {
195 serde::de::Error::custom(format!(
196 "`effort` has invalid value `{text}`; allowed: {}",
197 Self::ALLOWED
198 ))
199 })
200 }
201}
202
203#[derive(Debug, Clone, serde::Serialize)]
211#[serde(rename_all = "kebab-case")]
212pub struct AgentProfile {
213 pub name: Option<String>,
215 pub description: Option<String>,
216
217 pub harness: Option<HarnessId>,
219
220 pub model: Option<String>,
222
223 pub mode: Option<AgentMode>,
225 pub model_invocable: bool,
226 pub user_invocable: bool,
228 #[serde(skip)]
230 pub had_model_invocable_field: bool,
231 #[serde(skip)]
233 pub had_user_invocable_field: bool,
234 pub approval: Option<ApprovalMode>,
235 pub sandbox: Option<SandboxMode>,
236 pub network: Option<NetworkPolicy>,
237 pub network_allow: PermissionSet<NetworkHost>,
238 pub network_deny: PermissionSet<NetworkHost>,
239 pub effort: Option<EffortLevel>,
240
241 pub skills: SkillsSpec,
243 pub subagents: Vec<String>,
244 pub tools: EffectiveToolPolicy,
247
248 pub harness_overrides: HarnessOverrides,
250 pub model_policies: Vec<ModelPolicyRule>,
251}
252
253impl AgentProfile {
254 pub fn effective_native_config(
256 &self,
257 harness: &HarnessId,
258 ) -> Option<serde_json::Map<String, serde_json::Value>> {
259 self.harness_overrides
260 .get(harness)
261 .filter(|map| !map.is_empty())
262 .map(|map| {
263 map.iter()
264 .map(|(key, value)| (key.clone(), value.to_json()))
265 .collect()
266 })
267 }
268}
269
270fn push_agent_invalid(
271 diags: &mut Vec<crate::diagnostic::SchemaDiagnostic>,
272 path: Vec<crate::diagnostic::PathSegment>,
273 value: impl Into<String>,
274 allowed: &'static str,
275) {
276 push_invalid("agent", diags, path, value, allowed);
277}
278
279fn push_unknown_harness(diags: &mut Vec<crate::diagnostic::SchemaDiagnostic>, value: &str) {
280 use crate::diagnostic::{SchemaDiagnostic, Severity, key_path};
281 diags.push(SchemaDiagnostic::new(
282 "harness.unknown",
283 Severity::Error,
284 key_path("harness"),
285 format!("unknown harness `{value}`; known: claude, codex, opencode, cursor, pi"),
286 ));
287}
288
289fn push_model_policy_parse_error(
290 diags: &mut Vec<crate::diagnostic::SchemaDiagnostic>,
291 position: usize,
292 error: crate::model_policy::ModelPolicyRuleParseError,
293) {
294 use crate::diagnostic::{PathSegment, key_path};
295 let mut rule_path = key_path("model-policies");
296 rule_path.push(PathSegment::Index(position));
297 let child = |key: &str| {
298 let mut path = rule_path.clone();
299 path.push(PathSegment::Key(key.to_owned()));
300 path
301 };
302 let grandchild = |first: &str, second: &str| {
303 let mut path = child(first);
304 path.push(PathSegment::Key(second.to_owned()));
305 path
306 };
307 match error {
308 crate::model_policy::ModelPolicyRuleParseError::RuleMustBeMapping { found } => {
309 push_agent_invalid(diags, rule_path, found, "mapping with match and override");
310 }
311 crate::model_policy::ModelPolicyRuleParseError::MatchMissing => {
312 push_agent_invalid(
313 diags,
314 child("match"),
315 "<missing>",
316 "mapping with exactly one of model, alias, model-glob",
317 );
318 }
319 crate::model_policy::ModelPolicyRuleParseError::MatchMustBeMapping { found } => {
320 push_agent_invalid(
321 diags,
322 child("match"),
323 found,
324 "mapping with exactly one of model, alias, model-glob",
325 );
326 }
327 crate::model_policy::ModelPolicyRuleParseError::MatchMustContainExactlyOne { found } => {
328 push_agent_invalid(
329 diags,
330 child("match"),
331 found,
332 "exactly one of model, alias, model-glob",
333 );
334 }
335 crate::model_policy::ModelPolicyRuleParseError::MatchKeyMustBeString { found } => {
336 push_agent_invalid(diags, child("match"), found, "model, alias, model-glob");
337 }
338 crate::model_policy::ModelPolicyRuleParseError::UnknownMatchKey { key } => {
339 push_agent_invalid(diags, child("match"), key, "model, alias, model-glob");
340 }
341 crate::model_policy::ModelPolicyRuleParseError::MatchValueMustBeString { key, found } => {
342 push_agent_invalid(diags, grandchild("match", &key), found, "non-empty string");
343 }
344 crate::model_policy::ModelPolicyRuleParseError::MatchValueEmpty { key } => {
345 push_agent_invalid(
346 diags,
347 grandchild("match", &key),
348 "<empty>",
349 "non-empty string",
350 );
351 }
352 crate::model_policy::ModelPolicyRuleParseError::OverrideMustBeMapping { found } => {
353 push_agent_invalid(diags, child("override"), found, "mapping");
354 }
355 crate::model_policy::ModelPolicyRuleParseError::UnknownOverrideKey { key }
356 if crate::upgrade::PRE_V1
357 .policy_override_dropped
358 .contains(&key.as_str()) =>
359 {
360 diags.push(crate::upgrade::pre_v1_key(
361 grandchild("override", &key),
362 &key,
363 ));
364 }
365 crate::model_policy::ModelPolicyRuleParseError::UnknownOverrideKey { key } => {
366 push_agent_invalid(
367 diags,
368 grandchild("override", &key),
369 key,
370 "effort, sandbox, approval, network",
371 );
372 }
373 crate::model_policy::ModelPolicyRuleParseError::NetworkHostsNotAllowed { key } => {
374 push_agent_invalid(
375 diags,
376 grandchild("override", &key),
377 key,
378 "network host sets on settings, profile, overlay, or CLI",
379 );
380 }
381 crate::model_policy::ModelPolicyRuleParseError::OverrideValueInvalid {
382 key, found, ..
383 } if crate::upgrade::PRE_V1.value(&key, &found) => {
384 diags.push(crate::upgrade::pre_v1_value(
385 grandchild("override", &key),
386 &key,
387 &found,
388 ));
389 }
390 crate::model_policy::ModelPolicyRuleParseError::OverrideValueInvalid {
391 key,
392 found,
393 allowed,
394 } => {
395 push_agent_invalid(diags, grandchild("override", &key), found, allowed);
396 }
397 crate::model_policy::ModelPolicyRuleParseError::NoFallbackMustBeBoolean { found } => {
398 push_agent_invalid(diags, child("no-fallback"), found, "boolean");
399 }
400 crate::model_policy::ModelPolicyRuleParseError::WhenInvalid { found } => {
401 push_agent_invalid(diags, child("when"), found, "non-empty one-line string");
402 }
403 }
404}
405
406fn parse_model_policies(
407 val: &Value,
408 diags: &mut Vec<crate::diagnostic::SchemaDiagnostic>,
409) -> Vec<ModelPolicyRule> {
410 let Some(seq) = val.as_sequence() else {
411 push_agent_invalid(
412 diags,
413 crate::diagnostic::key_path("model-policies"),
414 crate::ordered::plain(val),
415 "sequence of rules",
416 );
417 return vec![];
418 };
419
420 let mut out = Vec::new();
421 for (index, entry) in seq.iter().enumerate() {
422 let reading = crate::model_policy::read_model_policy_rule(entry);
423 for unknown in reading.unknown {
424 let mut path = crate::diagnostic::key_path("model-policies");
425 path.push(crate::diagnostic::PathSegment::Index(index));
426 path.push(crate::diagnostic::PathSegment::Key(unknown.clone()));
427 diags.push(crate::diagnostic::unknown_field(
428 path,
429 &format!("model-policies[{index}]"),
430 &unknown,
431 ));
432 }
433 match reading.rule {
434 Ok(rule) => out.push(rule),
435 Err(errors) => {
436 for error in errors {
437 push_model_policy_parse_error(diags, index, error);
438 }
439 }
440 }
441 }
442 out
443}
444
445fn parse_invocability_field(
446 field: &str,
447 raw: Option<&Value>,
448 diags: &mut Vec<crate::diagnostic::SchemaDiagnostic>,
449) -> (bool, bool) {
450 let (value, had_field, invalid) = parse_invocability_axis(raw);
451 if let Some(invalid) = invalid {
452 push_agent_invalid(
453 diags,
454 crate::diagnostic::key_path(field),
455 invalid,
456 "boolean",
457 );
458 }
459 (value, had_field)
460}
461
462fn read_string(
463 value: &Value,
464 field: &'static str,
465 non_empty: bool,
466 diags: &mut Vec<crate::diagnostic::SchemaDiagnostic>,
467) -> Option<String> {
468 let Some(value) = value.as_str() else {
469 diags.push(crate::diagnostic::SchemaDiagnostic::new(
470 "field.type",
471 crate::diagnostic::Severity::Error,
472 crate::diagnostic::key_path(field),
473 format!("`{field}` must be a string"),
474 ));
475 return None;
476 };
477 if non_empty {
478 let value = value.trim();
479 if value.is_empty() {
480 diags.push(crate::diagnostic::SchemaDiagnostic::new(
481 "field.value",
482 crate::diagnostic::Severity::Error,
483 crate::diagnostic::key_path(field),
484 format!("`{field}` must be a non-empty string"),
485 ));
486 return None;
487 }
488 return Some(value.to_owned());
489 }
490 Some(value.to_owned())
491}
492
493fn read_string_list(
494 value: Option<&Value>,
495 path: Vec<crate::diagnostic::PathSegment>,
496 diags: &mut Vec<crate::diagnostic::SchemaDiagnostic>,
497) -> Vec<String> {
498 use crate::diagnostic::{PathSegment, SchemaDiagnostic, Severity, display_path};
499 let Some(value) = value else {
500 return Vec::new();
501 };
502 let Some(values) = value.as_sequence() else {
503 let display = display_path(&path);
504 diags.push(SchemaDiagnostic::new(
505 "field.type",
506 Severity::Error,
507 path,
508 format!("`{display}` must be a list of non-empty strings"),
509 ));
510 return Vec::new();
511 };
512 let display = display_path(&path);
513 values
514 .iter()
515 .enumerate()
516 .filter_map(|(index, value)| {
517 if let Value::String(text) = value
518 && !text.trim().is_empty()
519 {
520 return Some(text.clone());
521 }
522 let mut entry_path = path.clone();
523 entry_path.push(PathSegment::Index(index));
524 diags.push(SchemaDiagnostic::new(
525 if value.is_string() {
526 "field.value"
527 } else {
528 "field.type"
529 },
530 Severity::Error,
531 entry_path,
532 format!("`{display}` entry {} must be a non-empty string", index + 1),
533 ));
534 None
535 })
536 .collect()
537}
538
539fn read_host_set(
542 field: &'static str,
543 value: &Value,
544 allow_replace: bool,
545 diags: &mut Vec<crate::diagnostic::SchemaDiagnostic>,
546) -> PermissionSet<NetworkHost> {
547 use crate::diagnostic::{PathSegment, key_path};
548 const SHAPE: &str = "list of exact hosts, IPs, *.example.com, or **.example.com; or {replace: [...]} for an allow set";
549 let mut path = key_path(field);
550 let (replace, entries) = match value {
551 Value::Sequence(entries) => (false, entries),
552 Value::Mapping(mapping)
553 if mapping.len() == 1
554 && mapping
555 .get("replace")
556 .is_some_and(|entries| entries.is_sequence()) =>
557 {
558 if !allow_replace {
559 push_agent_invalid(
560 diags,
561 path,
562 crate::ordered::plain(value),
563 "plain list; package profiles cannot replace a deny set",
564 );
565 return PermissionSet::default();
566 }
567 path.push(PathSegment::Key("replace".to_owned()));
568 let entries = mapping.get("replace").and_then(Value::as_sequence);
569 (true, entries.expect("checked to be a sequence"))
570 }
571 _ => {
572 push_agent_invalid(diags, path, crate::ordered::plain(value), SHAPE);
573 return PermissionSet::default();
574 }
575 };
576 let hosts = entries
577 .iter()
578 .enumerate()
579 .filter_map(|(index, entry)| {
580 let parsed = entry
581 .as_str()
582 .ok_or_else(|| crate::ordered::plain(entry))
583 .and_then(|text| text.parse::<NetworkHost>().map_err(|_| text.to_owned()));
584 parsed
585 .map_err(|found| {
586 let mut entry_path = path.clone();
587 entry_path.push(PathSegment::Index(index));
588 push_agent_invalid(diags, entry_path, found, NetworkHost::ALLOWED);
589 })
590 .ok()
591 })
592 .collect();
593 if replace {
594 PermissionSet::Replace { replace: hosts }
595 } else {
596 PermissionSet::Add(hosts)
597 }
598}
599
600fn read_skills(value: &Value, diags: &mut Vec<crate::diagnostic::SchemaDiagnostic>) -> SkillsSpec {
601 use crate::diagnostic::{PathSegment, key_path};
602 let root = key_path("skills");
603 let Value::Mapping(mapping) = value else {
604 return SkillsSpec {
605 load: read_string_list(Some(value), root, diags),
606 available: Vec::new(),
607 };
608 };
609 let read_axis = |name: &str, diags: &mut Vec<_>| {
610 let mut path = root.clone();
611 path.push(PathSegment::Key(name.to_owned()));
612 read_string_list(mapping.get(Value::String(name.to_owned())), path, diags)
613 };
614 SkillsSpec {
615 load: read_axis("load", diags),
616 available: read_axis("available", diags),
617 }
618}
619
620pub(crate) fn read_fields(
621 fm: &Frontmatter,
622 diags: &mut Vec<crate::diagnostic::SchemaDiagnostic>,
623) -> AgentProfile {
624 use crate::diagnostic::{SchemaDiagnostic, Severity, key_path};
625
626 let mut profile = AgentProfile {
627 name: None,
628 description: None,
629 harness: None,
630 model: None,
631 mode: None,
632 model_invocable: true,
633 user_invocable: true,
634 had_model_invocable_field: false,
635 had_user_invocable_field: false,
636 approval: None,
637 sandbox: None,
638 network: None,
639 network_allow: PermissionSet::default(),
640 network_deny: PermissionSet::default(),
641 effort: None,
642 skills: SkillsSpec::default(),
643 subagents: Vec::new(),
644 tools: EffectiveToolPolicy::default(),
645 harness_overrides: HarnessOverrides::default(),
646 model_policies: Vec::new(),
647 };
648
649 for key in fm.keys() {
650 let value = fm.get(&key).expect("frontmatter key came from mapping");
651 match key.as_str() {
652 "name" => profile.name = read_string(value, "name", true, diags),
653 "description" => {
654 profile.description = read_string(value, "description", false, diags);
655 }
656 "harness" => {
657 profile.harness = read_string(value, "harness", false, diags).and_then(|name| {
658 crate::harness::parse(&name).or_else(|| {
659 push_unknown_harness(diags, &name);
660 None
661 })
662 });
663 }
664 "model" => profile.model = read_string(value, "model", true, diags),
665 "mode" => {
666 profile.mode =
667 read_string(value, "mode", false, diags).and_then(|mode| match mode.as_str() {
668 "primary" => Some(AgentMode::Primary),
669 "subagent" => Some(AgentMode::Subagent),
670 other => {
671 push_agent_invalid(
672 diags,
673 key_path("mode"),
674 other.to_string(),
675 "primary, subagent",
676 );
677 None
678 }
679 });
680 }
681 "model-invocable" => {
682 (profile.model_invocable, profile.had_model_invocable_field) =
683 parse_invocability_field("model-invocable", Some(value), diags);
684 }
685 "user-invocable" => {
686 (profile.user_invocable, profile.had_user_invocable_field) =
687 parse_invocability_field("user-invocable", Some(value), diags);
688 }
689 "approval" => {
690 profile.approval =
691 read_string(value, "approval", false, diags).and_then(|approval| {
692 if crate::upgrade::PRE_V1.value("approval", &approval) {
693 diags.push(crate::upgrade::pre_v1_value(
694 key_path("approval"),
695 "approval",
696 &approval,
697 ));
698 return None;
699 }
700 ApprovalMode::parse(&approval).or_else(|| {
701 push_agent_invalid(
702 diags,
703 key_path("approval"),
704 approval,
705 ApprovalMode::ALLOWED,
706 );
707 None
708 })
709 });
710 }
711 "sandbox" => {
712 profile.sandbox = read_string(value, "sandbox", false, diags).and_then(|sandbox| {
713 SandboxMode::parse(&sandbox).or_else(|| {
714 push_agent_invalid(
715 diags,
716 key_path("sandbox"),
717 sandbox,
718 SandboxMode::ALLOWED,
719 );
720 None
721 })
722 });
723 }
724 "network" => {
725 profile.network = read_string(value, "network", false, diags).and_then(|network| {
726 NetworkPolicy::parse(&network).or_else(|| {
727 push_agent_invalid(
728 diags,
729 key_path("network"),
730 network,
731 NetworkPolicy::ALLOWED,
732 );
733 None
734 })
735 });
736 }
737 "network-allow" => {
738 profile.network_allow = read_host_set("network-allow", value, true, diags);
739 }
740 "network-deny" => {
741 profile.network_deny = read_host_set("network-deny", value, false, diags);
742 }
743 "effort" => {
744 profile.effort = read_string(value, "effort", false, diags).and_then(|effort| {
745 if crate::upgrade::PRE_V1.value("effort", &effort) {
746 diags.push(crate::upgrade::pre_v1_value(
747 key_path("effort"),
748 "effort",
749 &effort,
750 ));
751 return None;
752 }
753 EffortLevel::parse(&effort).or_else(|| {
754 push_agent_invalid(diags, key_path("effort"), effort, EffortLevel::ALLOWED);
755 None
756 })
757 });
758 }
759 "skills" => profile.skills = read_skills(value, diags),
760 "subagents" => {
761 profile.subagents = read_string_list(Some(value), key_path("subagents"), diags);
762 }
763 "tools" => {
764 if value.is_sequence() {
765 diags.push(SchemaDiagnostic::new(
766 "tools.list-form",
767 Severity::Error,
768 key_path("tools"),
769 "`tools` must be an action map; list form was removed",
770 ));
771 } else {
772 let mut invalid = |path, value: &str, allowed: &'static str| {
773 push_agent_invalid(diags, path, value, allowed);
774 };
775 profile.tools = tool_policy::parse_tool_policy(Some(value), &mut invalid);
776 }
777 }
778 "harness-overrides" => {
779 profile.harness_overrides = parse_harness_overrides("agent", value, diags);
780 }
781 "model-policies" => profile.model_policies = parse_model_policies(value, diags),
782 _ => diags.push(unrecognized_field(DefinitionKind::Agent, &key)),
783 }
784 }
785
786 profile
787}
788
789pub fn read(content: &str) -> crate::read::DefinitionRead<AgentProfile> {
791 crate::read::read_with(content, read_fields)
792}