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 push_agent_invalid(
357 diags,
358 grandchild("override", &key),
359 key,
360 "effort, sandbox, approval, network",
361 );
362 }
363 crate::model_policy::ModelPolicyRuleParseError::NetworkHostsNotAllowed { key } => {
364 push_agent_invalid(
365 diags,
366 grandchild("override", &key),
367 key,
368 "network host sets on settings, profile, overlay, or CLI",
369 );
370 }
371 crate::model_policy::ModelPolicyRuleParseError::OverrideValueInvalid {
372 key,
373 found,
374 allowed,
375 } => {
376 push_agent_invalid(diags, grandchild("override", &key), found, allowed);
377 }
378 crate::model_policy::ModelPolicyRuleParseError::NoFallbackMustBeBoolean { found } => {
379 push_agent_invalid(diags, child("no-fallback"), found, "boolean");
380 }
381 crate::model_policy::ModelPolicyRuleParseError::WhenInvalid { found } => {
382 push_agent_invalid(diags, child("when"), found, "non-empty one-line string");
383 }
384 }
385}
386
387fn parse_model_policies(
388 val: &Value,
389 diags: &mut Vec<crate::diagnostic::SchemaDiagnostic>,
390) -> Vec<ModelPolicyRule> {
391 let Some(seq) = val.as_sequence() else {
392 push_agent_invalid(
393 diags,
394 crate::diagnostic::key_path("model-policies"),
395 crate::ordered::plain(val),
396 "sequence of rules",
397 );
398 return vec![];
399 };
400
401 let mut out = Vec::new();
402 for (index, entry) in seq.iter().enumerate() {
403 let reading = crate::model_policy::read_model_policy_rule(entry);
404 for unknown in reading.unknown {
405 let mut path = crate::diagnostic::key_path("model-policies");
406 path.push(crate::diagnostic::PathSegment::Index(index));
407 path.push(crate::diagnostic::PathSegment::Key(unknown.clone()));
408 diags.push(crate::diagnostic::unknown_field(
409 path,
410 &format!("model-policies[{index}]"),
411 &unknown,
412 ));
413 }
414 match reading.rule {
415 Ok(rule) => out.push(rule),
416 Err(errors) => {
417 for error in errors {
418 push_model_policy_parse_error(diags, index, error);
419 }
420 }
421 }
422 }
423 out
424}
425
426fn parse_invocability_field(
427 field: &str,
428 raw: Option<&Value>,
429 diags: &mut Vec<crate::diagnostic::SchemaDiagnostic>,
430) -> (bool, bool) {
431 let (value, had_field, invalid) = parse_invocability_axis(raw);
432 if let Some(invalid) = invalid {
433 push_agent_invalid(
434 diags,
435 crate::diagnostic::key_path(field),
436 invalid,
437 "boolean",
438 );
439 }
440 (value, had_field)
441}
442
443fn read_string(
444 value: &Value,
445 field: &'static str,
446 non_empty: bool,
447 diags: &mut Vec<crate::diagnostic::SchemaDiagnostic>,
448) -> Option<String> {
449 let Some(value) = value.as_str() else {
450 diags.push(crate::diagnostic::SchemaDiagnostic::new(
451 "field.type",
452 crate::diagnostic::Severity::Error,
453 crate::diagnostic::key_path(field),
454 format!("`{field}` must be a string"),
455 ));
456 return None;
457 };
458 if non_empty {
459 let value = value.trim();
460 if value.is_empty() {
461 diags.push(crate::diagnostic::SchemaDiagnostic::new(
462 "field.value",
463 crate::diagnostic::Severity::Error,
464 crate::diagnostic::key_path(field),
465 format!("`{field}` must be a non-empty string"),
466 ));
467 return None;
468 }
469 return Some(value.to_owned());
470 }
471 Some(value.to_owned())
472}
473
474fn read_string_list(
475 value: Option<&Value>,
476 path: Vec<crate::diagnostic::PathSegment>,
477 diags: &mut Vec<crate::diagnostic::SchemaDiagnostic>,
478) -> Vec<String> {
479 use crate::diagnostic::{PathSegment, SchemaDiagnostic, Severity, display_path};
480 let Some(value) = value else {
481 return Vec::new();
482 };
483 let Some(values) = value.as_sequence() else {
484 let display = display_path(&path);
485 diags.push(SchemaDiagnostic::new(
486 "field.type",
487 Severity::Error,
488 path,
489 format!("`{display}` must be a list of non-empty strings"),
490 ));
491 return Vec::new();
492 };
493 let display = display_path(&path);
494 values
495 .iter()
496 .enumerate()
497 .filter_map(|(index, value)| {
498 if let Value::String(text) = value
499 && !text.trim().is_empty()
500 {
501 return Some(text.clone());
502 }
503 let mut entry_path = path.clone();
504 entry_path.push(PathSegment::Index(index));
505 diags.push(SchemaDiagnostic::new(
506 if value.is_string() {
507 "field.value"
508 } else {
509 "field.type"
510 },
511 Severity::Error,
512 entry_path,
513 format!("`{display}` entry {} must be a non-empty string", index + 1),
514 ));
515 None
516 })
517 .collect()
518}
519
520fn read_host_set(
523 field: &'static str,
524 value: &Value,
525 allow_replace: bool,
526 diags: &mut Vec<crate::diagnostic::SchemaDiagnostic>,
527) -> PermissionSet<NetworkHost> {
528 use crate::diagnostic::{PathSegment, key_path};
529 const SHAPE: &str = "list of exact hosts, IPs, *.example.com, or **.example.com; or {replace: [...]} for an allow set";
530 let mut path = key_path(field);
531 let (replace, entries) = match value {
532 Value::Sequence(entries) => (false, entries),
533 Value::Mapping(mapping)
534 if mapping.len() == 1
535 && mapping
536 .get("replace")
537 .is_some_and(|entries| entries.is_sequence()) =>
538 {
539 if !allow_replace {
540 push_agent_invalid(
541 diags,
542 path,
543 crate::ordered::plain(value),
544 "plain list; package profiles cannot replace a deny set",
545 );
546 return PermissionSet::default();
547 }
548 path.push(PathSegment::Key("replace".to_owned()));
549 let entries = mapping.get("replace").and_then(Value::as_sequence);
550 (true, entries.expect("checked to be a sequence"))
551 }
552 _ => {
553 push_agent_invalid(diags, path, crate::ordered::plain(value), SHAPE);
554 return PermissionSet::default();
555 }
556 };
557 let hosts = entries
558 .iter()
559 .enumerate()
560 .filter_map(|(index, entry)| {
561 let parsed = entry
562 .as_str()
563 .ok_or_else(|| crate::ordered::plain(entry))
564 .and_then(|text| text.parse::<NetworkHost>().map_err(|_| text.to_owned()));
565 parsed
566 .map_err(|found| {
567 let mut entry_path = path.clone();
568 entry_path.push(PathSegment::Index(index));
569 push_agent_invalid(diags, entry_path, found, NetworkHost::ALLOWED);
570 })
571 .ok()
572 })
573 .collect();
574 if replace {
575 PermissionSet::Replace { replace: hosts }
576 } else {
577 PermissionSet::Add(hosts)
578 }
579}
580
581fn read_skills(value: &Value, diags: &mut Vec<crate::diagnostic::SchemaDiagnostic>) -> SkillsSpec {
582 use crate::diagnostic::{PathSegment, key_path};
583 let root = key_path("skills");
584 let Value::Mapping(mapping) = value else {
585 return SkillsSpec {
586 load: read_string_list(Some(value), root, diags),
587 available: Vec::new(),
588 };
589 };
590 let read_axis = |name: &str, diags: &mut Vec<_>| {
591 let mut path = root.clone();
592 path.push(PathSegment::Key(name.to_owned()));
593 read_string_list(mapping.get(Value::String(name.to_owned())), path, diags)
594 };
595 SkillsSpec {
596 load: read_axis("load", diags),
597 available: read_axis("available", diags),
598 }
599}
600
601pub(crate) fn read_fields(
602 fm: &Frontmatter,
603 diags: &mut Vec<crate::diagnostic::SchemaDiagnostic>,
604) -> AgentProfile {
605 use crate::diagnostic::{SchemaDiagnostic, Severity, key_path};
606
607 let mut profile = AgentProfile {
608 name: None,
609 description: None,
610 harness: None,
611 model: None,
612 mode: None,
613 model_invocable: true,
614 user_invocable: true,
615 had_model_invocable_field: false,
616 had_user_invocable_field: false,
617 approval: None,
618 sandbox: None,
619 network: None,
620 network_allow: PermissionSet::default(),
621 network_deny: PermissionSet::default(),
622 effort: None,
623 skills: SkillsSpec::default(),
624 subagents: Vec::new(),
625 tools: EffectiveToolPolicy::default(),
626 harness_overrides: HarnessOverrides::default(),
627 model_policies: Vec::new(),
628 };
629
630 for key in fm.keys() {
631 let value = fm.get(&key).expect("frontmatter key came from mapping");
632 match key.as_str() {
633 "name" => profile.name = read_string(value, "name", true, diags),
634 "description" => {
635 profile.description = read_string(value, "description", false, diags);
636 }
637 "harness" => {
638 profile.harness = read_string(value, "harness", false, diags).and_then(|name| {
639 crate::harness::parse(&name).or_else(|| {
640 push_unknown_harness(diags, &name);
641 None
642 })
643 });
644 }
645 "model" => profile.model = read_string(value, "model", true, diags),
646 "mode" => {
647 profile.mode =
648 read_string(value, "mode", false, diags).and_then(|mode| match mode.as_str() {
649 "primary" => Some(AgentMode::Primary),
650 "subagent" => Some(AgentMode::Subagent),
651 other => {
652 push_agent_invalid(
653 diags,
654 key_path("mode"),
655 other.to_string(),
656 "primary, subagent",
657 );
658 None
659 }
660 });
661 }
662 "model-invocable" => {
663 (profile.model_invocable, profile.had_model_invocable_field) =
664 parse_invocability_field("model-invocable", Some(value), diags);
665 }
666 "user-invocable" => {
667 (profile.user_invocable, profile.had_user_invocable_field) =
668 parse_invocability_field("user-invocable", Some(value), diags);
669 }
670 "approval" => {
671 profile.approval =
672 read_string(value, "approval", false, diags).and_then(|approval| {
673 ApprovalMode::parse(&approval).or_else(|| {
674 push_agent_invalid(
675 diags,
676 key_path("approval"),
677 approval,
678 ApprovalMode::ALLOWED,
679 );
680 None
681 })
682 });
683 }
684 "sandbox" => {
685 profile.sandbox = read_string(value, "sandbox", false, diags).and_then(|sandbox| {
686 SandboxMode::parse(&sandbox).or_else(|| {
687 push_agent_invalid(
688 diags,
689 key_path("sandbox"),
690 sandbox,
691 SandboxMode::ALLOWED,
692 );
693 None
694 })
695 });
696 }
697 "network" => {
698 profile.network = read_string(value, "network", false, diags).and_then(|network| {
699 NetworkPolicy::parse(&network).or_else(|| {
700 push_agent_invalid(
701 diags,
702 key_path("network"),
703 network,
704 NetworkPolicy::ALLOWED,
705 );
706 None
707 })
708 });
709 }
710 "network-allow" => {
711 profile.network_allow = read_host_set("network-allow", value, true, diags);
712 }
713 "network-deny" => {
714 profile.network_deny = read_host_set("network-deny", value, false, diags);
715 }
716 "effort" => {
717 profile.effort = read_string(value, "effort", false, diags).and_then(|effort| {
718 EffortLevel::parse(&effort).or_else(|| {
719 push_agent_invalid(diags, key_path("effort"), effort, EffortLevel::ALLOWED);
720 None
721 })
722 });
723 }
724 "skills" => profile.skills = read_skills(value, diags),
725 "subagents" => {
726 profile.subagents = read_string_list(Some(value), key_path("subagents"), diags);
727 }
728 "tools" => {
729 if value.is_sequence() {
730 diags.push(SchemaDiagnostic::new(
731 "tools.list-form",
732 Severity::Error,
733 key_path("tools"),
734 "`tools` must be an action map; list form was removed",
735 ));
736 } else {
737 let mut invalid = |path, value: &str, allowed: &'static str| {
738 push_agent_invalid(diags, path, value, allowed);
739 };
740 profile.tools = tool_policy::parse_tool_policy(Some(value), &mut invalid);
741 }
742 }
743 "harness-overrides" => {
744 profile.harness_overrides = parse_harness_overrides("agent", value, diags);
745 }
746 "model-policies" => profile.model_policies = parse_model_policies(value, diags),
747 _ => diags.push(unrecognized_field(DefinitionKind::Agent, &key)),
748 }
749 }
750
751 profile
752}
753
754pub fn read(content: &str) -> crate::read::DefinitionRead<AgentProfile> {
756 crate::read::read_with(content, read_fields)
757}