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