1use crate::agent::{ApprovalMode, EffortRequest, SandboxMode};
4use crate::network::NetworkPolicy;
5use serde::ser::SerializeMap;
6use serde::{Deserialize, Serialize};
7
8#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
9#[serde(rename_all = "kebab-case")]
10pub enum ModelPolicyMatchType {
11 Model,
12 Alias,
13 ModelGlob,
14}
15
16#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
17#[serde(deny_unknown_fields)]
18pub struct ModelPolicyOverride {
19 #[serde(default, skip_serializing_if = "Option::is_none")]
20 pub effort: Option<String>,
21 #[serde(default, skip_serializing_if = "Option::is_none")]
22 pub sandbox: Option<String>,
23 #[serde(default, skip_serializing_if = "Option::is_none")]
24 pub approval: Option<String>,
25 #[serde(default, skip_serializing_if = "Option::is_none")]
26 pub network: Option<String>,
27}
28
29impl ModelPolicyOverride {
30 pub fn is_empty(&self) -> bool {
31 self.effort.is_none()
32 && self.sandbox.is_none()
33 && self.approval.is_none()
34 && self.network.is_none()
35 }
36
37 pub fn get(&self, key: &str) -> Option<&str> {
38 match key {
39 "effort" => self.effort.as_deref(),
40 "sandbox" => self.sandbox.as_deref(),
41 "approval" => self.approval.as_deref(),
42 "network" => self.network.as_deref(),
43 _ => None,
44 }
45 }
46}
47
48#[derive(Debug, Clone, PartialEq)]
51pub struct ModelPolicyRule {
52 pub match_type: ModelPolicyMatchType,
53 pub match_value: String,
54 pub no_fallback: bool,
55 pub overrides: ModelPolicyOverride,
56 pub when: Option<String>,
58}
59
60#[derive(Debug, Clone, PartialEq, Eq)]
61pub enum ModelPolicyRuleParseError {
62 RuleMustBeMapping {
63 found: String,
64 },
65 MatchMissing,
66 MatchMustBeMapping {
67 found: String,
68 },
69 MatchMustContainExactlyOne {
70 found: String,
71 },
72 MatchKeyMustBeString {
73 found: String,
74 },
75 UnknownMatchKey {
76 key: String,
77 },
78 MatchValueMustBeString {
79 key: String,
80 found: String,
81 },
82 MatchValueEmpty {
83 key: String,
84 },
85 OverrideMustBeMapping {
86 found: String,
87 },
88 UnknownOverrideKey {
89 key: String,
90 },
91 NetworkHostsNotAllowed {
93 key: String,
94 },
95 OverrideValueInvalid {
96 key: String,
97 found: String,
98 allowed: &'static str,
99 },
100 NoFallbackMustBeBoolean {
101 found: String,
102 },
103 WhenInvalid {
104 found: String,
105 },
106 EntryMustBeNameOrMapping {
108 found: String,
109 },
110 EntryModelMissing,
111 EntryModelInvalid {
112 found: String,
113 },
114}
115
116impl ModelPolicyRuleParseError {
117 fn deserialize_message(&self) -> String {
118 match self {
119 Self::MatchMustContainExactlyOne { .. }
120 | Self::MatchMissing
121 | Self::MatchMustBeMapping { .. } => {
122 "model policy `match` must contain exactly one of model, alias, model-glob"
123 .to_string()
124 }
125 Self::MatchKeyMustBeString { .. } => {
126 "model policy `match` key must be a string".to_string()
127 }
128 Self::MatchValueMustBeString { .. } => {
129 "model policy `match` value must be a string".to_string()
130 }
131 Self::MatchValueEmpty { .. } => {
132 "model policy `match` value must be a non-empty string".to_string()
133 }
134 Self::UnknownMatchKey { key } => format!(
135 "unknown model policy match key `{key}`; expected model, alias, or model-glob"
136 ),
137 Self::OverrideMustBeMapping { .. } => {
138 "model policy `override` must be a mapping".to_string()
139 }
140 Self::UnknownOverrideKey { key } => format!(
141 "unknown model policy override `{key}`; expected effort, sandbox, approval, or network"
142 ),
143 Self::NetworkHostsNotAllowed { key } => format!(
144 "model policy override `{key}` is not supported; set it on settings, the profile, an agent overlay, or the CLI"
145 ),
146 Self::OverrideValueInvalid {
147 key,
148 found,
149 allowed,
150 } => format!(
151 "model policy override `{key}` has invalid value `{found}`; allowed: {allowed}"
152 ),
153 Self::NoFallbackMustBeBoolean { .. } => {
154 "model policy `no-fallback` must be a boolean".to_string()
155 }
156 Self::WhenInvalid { .. } => {
157 "model policy `when` must be a non-empty one-line string".to_string()
158 }
159 Self::RuleMustBeMapping { .. } => "model policy rule must be a mapping".to_string(),
160 Self::EntryMustBeNameOrMapping { .. } => {
161 "a `models` entry must be a model name or a mapping".to_string()
162 }
163 Self::EntryModelMissing | Self::EntryModelInvalid { .. } => {
164 "a `models` entry needs `model`, a non-empty string".to_string()
165 }
166 }
167 }
168}
169
170const RULE_KEYS: &[&str] = &["match", "override", "no-fallback", "when"];
174const OVERRIDE_KEYS: &[&str] = &[
175 "effort",
176 "sandbox",
177 "approval",
178 "network",
179 "network-allow",
180 "network-deny",
181];
182
183pub(crate) struct RuleReading {
186 pub rule: Result<ModelPolicyRule, Vec<ModelPolicyRuleParseError>>,
187 pub unknown: Vec<String>,
188}
189
190pub(crate) fn read_model_policy_rule(value: &serde_yaml::Value) -> RuleReading {
191 use ModelPolicyRuleParseError as Error;
192 let Some(rule) = value.as_mapping() else {
193 return RuleReading {
194 rule: Err(vec![Error::RuleMustBeMapping {
195 found: crate::ordered::plain(value),
196 }]),
197 unknown: Vec::new(),
198 };
199 };
200 let mut errors = Vec::new();
201 let unknown = unknown_keys(rule, RULE_KEYS);
202
203 let matched = read_match(rule).map_err(|error| errors.push(error)).ok();
204
205 let overrides = match rule.get(serde_yaml::Value::String("override".to_string())) {
206 Some(value) if !value.is_null() => match value.as_mapping() {
207 Some(mapping) => read_overrides(mapping, &mut errors),
208 None => {
209 errors.push(Error::OverrideMustBeMapping {
210 found: crate::ordered::plain(value),
211 });
212 ModelPolicyOverride::default()
213 }
214 },
215 _ => ModelPolicyOverride::default(),
216 };
217
218 let no_fallback = read_no_fallback(rule, &mut errors).unwrap_or(false);
219 let when = read_when(rule, &mut errors);
220
221 let rule = match matched {
222 Some((match_type, match_value)) if errors.is_empty() => Ok(ModelPolicyRule {
223 match_type,
224 match_value,
225 no_fallback,
226 overrides,
227 when,
228 }),
229 _ => Err(errors),
230 };
231 RuleReading { rule, unknown }
232}
233
234fn read_no_fallback(
235 mapping: &serde_yaml::Mapping,
236 errors: &mut Vec<ModelPolicyRuleParseError>,
237) -> Option<bool> {
238 match mapping.get(serde_yaml::Value::String("no-fallback".to_string())) {
239 None | Some(serde_yaml::Value::Null) => None,
240 Some(serde_yaml::Value::Bool(value)) => Some(*value),
241 Some(value) => {
242 errors.push(ModelPolicyRuleParseError::NoFallbackMustBeBoolean {
243 found: crate::ordered::plain(value),
244 });
245 None
246 }
247 }
248}
249
250fn read_when(
251 mapping: &serde_yaml::Mapping,
252 errors: &mut Vec<ModelPolicyRuleParseError>,
253) -> Option<String> {
254 match mapping.get(serde_yaml::Value::String("when".to_string())) {
255 None | Some(serde_yaml::Value::Null) => None,
256 Some(serde_yaml::Value::String(value))
257 if !value.is_empty() && !value.contains(['\n', '\r']) =>
258 {
259 Some(value.clone())
260 }
261 Some(value) => {
262 errors.push(ModelPolicyRuleParseError::WhenInvalid {
263 found: crate::ordered::plain(value),
264 });
265 None
266 }
267 }
268}
269
270fn unknown_keys(mapping: &serde_yaml::Mapping, known: &[&str]) -> Vec<String> {
271 mapping
272 .keys()
273 .filter(|key| !key.as_str().is_some_and(|key| known.contains(&key)))
274 .map(|key| {
275 key.as_str()
276 .map_or_else(|| crate::ordered::plain(key), str::to_owned)
277 })
278 .collect()
279}
280
281fn read_match(
282 rule: &serde_yaml::Mapping,
283) -> Result<(ModelPolicyMatchType, String), ModelPolicyRuleParseError> {
284 use ModelPolicyRuleParseError as Error;
285 let match_mapping = match rule.get(serde_yaml::Value::String("match".to_string())) {
286 Some(value) => value
287 .as_mapping()
288 .ok_or_else(|| Error::MatchMustBeMapping {
289 found: crate::ordered::plain(value),
290 })?,
291 None => return Err(Error::MatchMissing),
292 };
293 let exactly_one = || Error::MatchMustContainExactlyOne {
294 found: crate::ordered::plain(&serde_yaml::Value::Mapping(match_mapping.clone())),
295 };
296 let mut entries = match_mapping.iter();
297 let Some((match_key, match_value)) = entries.next() else {
298 return Err(exactly_one());
299 };
300 if entries.next().is_some() {
301 return Err(exactly_one());
302 }
303
304 let key = match_key
305 .as_str()
306 .ok_or_else(|| Error::MatchKeyMustBeString {
307 found: crate::ordered::plain(match_key),
308 })?;
309 let value = match_value
310 .as_str()
311 .ok_or_else(|| Error::MatchValueMustBeString {
312 key: key.to_string(),
313 found: crate::ordered::plain(match_value),
314 })?;
315 if value.is_empty() {
316 return Err(Error::MatchValueEmpty {
317 key: key.to_string(),
318 });
319 }
320 let match_type = match key {
321 "model" => ModelPolicyMatchType::Model,
322 "alias" => ModelPolicyMatchType::Alias,
323 "model-glob" => ModelPolicyMatchType::ModelGlob,
324 _ => {
325 return Err(Error::UnknownMatchKey {
326 key: key.to_string(),
327 });
328 }
329 };
330 Ok((match_type, value.to_string()))
331}
332
333fn read_overrides(
335 mapping: &serde_yaml::Mapping,
336 errors: &mut Vec<ModelPolicyRuleParseError>,
337) -> ModelPolicyOverride {
338 let mut overrides = ModelPolicyOverride::default();
339 for (key, value) in mapping {
340 let Some(key) = key.as_str().filter(|key| OVERRIDE_KEYS.contains(key)) else {
341 errors.push(ModelPolicyRuleParseError::UnknownOverrideKey {
342 key: key
343 .as_str()
344 .map_or_else(|| crate::ordered::plain(key), str::to_owned),
345 });
346 continue;
347 };
348 if matches!(key, "network-allow" | "network-deny") {
349 errors.push(ModelPolicyRuleParseError::NetworkHostsNotAllowed {
350 key: key.to_string(),
351 });
352 continue;
353 }
354 let invalid = |found: String| ModelPolicyRuleParseError::OverrideValueInvalid {
355 key: key.to_string(),
356 found,
357 allowed: allowed_override_values(key),
358 };
359 let raw = if key == "effort" && value.is_null() {
361 Some("auto")
362 } else {
363 value.as_str()
364 };
365 let Some(raw) = raw else {
366 errors.push(invalid(crate::ordered::plain(value)));
367 continue;
368 };
369 let parsed = match key {
370 "effort" => EffortRequest::parse(raw).map(|value| value.as_str().to_string()),
371 "sandbox" => SandboxMode::parse(raw).map(|value| value.as_str().to_string()),
372 "approval" => ApprovalMode::parse(raw).map(|value| value.as_str().to_string()),
373 _ => NetworkPolicy::parse(raw).map(|value| value.as_str().to_string()),
374 };
375 let Some(parsed) = parsed else {
376 errors.push(invalid(raw.to_string()));
377 continue;
378 };
379 match key {
380 "effort" => overrides.effort = Some(parsed),
381 "sandbox" => overrides.sandbox = Some(parsed),
382 "approval" => overrides.approval = Some(parsed),
383 _ => overrides.network = Some(parsed),
384 }
385 }
386 overrides
387}
388
389fn allowed_override_values(key: &str) -> &'static str {
390 match key {
391 "effort" => EffortRequest::ALLOWED,
392 "sandbox" => SandboxMode::ALLOWED,
393 "approval" => ApprovalMode::ALLOWED,
394 "network" => NetworkPolicy::ALLOWED,
395 _ => "effort, sandbox, approval, network",
396 }
397}
398
399#[derive(Debug, Clone, Default, PartialEq)]
402pub struct ModelEntry {
403 pub model: String,
405 pub when: Option<String>,
406 pub no_fallback: Option<bool>,
409 pub overrides: ModelPolicyOverride,
410}
411
412pub const MODELS_SPLICE: &str = "...";
414
415#[derive(Debug, Clone, PartialEq)]
417pub enum ModelsItem {
418 Rest,
419 Entry(ModelEntry),
420}
421
422impl ModelsItem {
423 pub fn entry(&self) -> Option<&ModelEntry> {
425 match self {
426 Self::Rest => None,
427 Self::Entry(entry) => Some(entry),
428 }
429 }
430}
431
432#[derive(Debug, Clone, PartialEq)]
434pub struct ListProblem {
435 pub code: &'static str,
436 pub index: Option<usize>,
438 pub message: String,
439}
440
441pub fn list_problems<'a>(
445 items: impl IntoIterator<Item = Option<&'a ModelEntry>>,
446) -> Vec<ListProblem> {
447 let mut problems = Vec::new();
448 let mut problem = |code, index, message| {
449 problems.push(ListProblem {
450 code,
451 index,
452 message,
453 })
454 };
455 let mut seen = std::collections::HashSet::new();
456 let (mut splices, mut len) = (0, 0);
457 for (index, item) in items.into_iter().enumerate() {
458 len += 1;
459 let Some(entry) = item else {
460 splices += 1;
461 if splices == 2 {
462 let message = format!("`{MODELS_SPLICE}` may appear once in `models`");
463 problem("models.splice-twice", Some(index), message);
464 }
465 continue;
466 };
467 if !seen.insert(entry.model.as_str()) {
468 let message = format!("`models` lists `{}` twice", entry.model);
469 problem("models.duplicate", Some(index), message);
470 }
471 if index == 0 && entry.no_fallback == Some(true) {
472 let message = format!(
473 "`models[0]` (`{}`) is the default, and `no-fallback` marks a model used only when asked for",
474 entry.model
475 );
476 problem("models.default-no-fallback", Some(index), message);
477 }
478 }
479 if len == 0 {
480 let message = "`models` is empty: remove the line, or name a model".to_string();
481 problem("models.empty", None, message);
482 }
483 problems
484}
485
486const ENTRY_KEYS: &[&str] = &[
487 "model",
488 "when",
489 "no-fallback",
490 "effort",
491 "sandbox",
492 "approval",
493 "network",
494];
495
496pub(crate) struct EntryReading {
497 pub entry: Result<ModelEntry, Vec<ModelPolicyRuleParseError>>,
498 pub unknown: Vec<String>,
499}
500
501pub(crate) fn read_model_entry(value: &serde_yaml::Value) -> EntryReading {
503 use ModelPolicyRuleParseError as Error;
504 let fail = |error| EntryReading {
505 entry: Err(vec![error]),
506 unknown: Vec::new(),
507 };
508 let named = |name: &str| {
509 let name = name.trim();
510 (!name.is_empty()).then(|| ModelEntry {
511 model: name.to_string(),
512 ..ModelEntry::default()
513 })
514 };
515 let mapping = match value {
516 serde_yaml::Value::String(name) => {
517 return match named(name) {
518 Some(entry) => EntryReading {
519 entry: Ok(entry),
520 unknown: Vec::new(),
521 },
522 None => fail(Error::EntryModelInvalid {
523 found: crate::ordered::plain(value),
524 }),
525 };
526 }
527 serde_yaml::Value::Mapping(mapping) => mapping,
528 other => {
529 return fail(Error::EntryMustBeNameOrMapping {
530 found: crate::ordered::plain(other),
531 });
532 }
533 };
534 let mut errors = Vec::new();
535 let unknown = unknown_keys(mapping, ENTRY_KEYS);
536 let model = match mapping.get(serde_yaml::Value::String("model".to_string())) {
537 None => {
538 errors.push(Error::EntryModelMissing);
539 None
540 }
541 Some(serde_yaml::Value::String(name)) if !name.trim().is_empty() => {
542 Some(name.trim().to_string())
543 }
544 Some(other) => {
545 errors.push(Error::EntryModelInvalid {
546 found: crate::ordered::plain(other),
547 });
548 None
549 }
550 };
551 let settings: serde_yaml::Mapping = mapping
552 .iter()
553 .filter(|(key, _)| {
554 key.as_str()
555 .is_some_and(|key| matches!(key, "effort" | "sandbox" | "approval" | "network"))
556 })
557 .map(|(key, value)| (key.clone(), value.clone()))
558 .collect();
559 let overrides = read_overrides(&settings, &mut errors);
560 let no_fallback = read_no_fallback(mapping, &mut errors);
561 let when = read_when(mapping, &mut errors);
562 let entry = match model {
563 Some(model) if errors.is_empty() => Ok(ModelEntry {
564 model,
565 when,
566 no_fallback,
567 overrides,
568 }),
569 _ => Err(errors),
570 };
571 EntryReading { entry, unknown }
572}
573
574fn entry_error(errors: &[ModelPolicyRuleParseError]) -> String {
575 errors
576 .iter()
577 .map(ModelPolicyRuleParseError::deserialize_message)
578 .collect::<Vec<_>>()
579 .join("; ")
580}
581
582struct EntryVisitor;
585
586impl<'de> serde::de::Visitor<'de> for EntryVisitor {
587 type Value = ModelsItem;
588
589 fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
590 f.write_str("a model name, `...`, or a mapping with `model`")
591 }
592
593 fn visit_str<E: serde::de::Error>(self, name: &str) -> Result<Self::Value, E> {
594 if name == MODELS_SPLICE {
595 return Ok(ModelsItem::Rest);
596 }
597 read_model_entry(&serde_yaml::Value::String(name.to_string()))
598 .entry
599 .map(ModelsItem::Entry)
600 .map_err(|errors| E::custom(entry_error(&errors)))
601 }
602
603 fn visit_map<A: serde::de::MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
604 let mut entry = serde_yaml::Mapping::new();
605 while let Some(key) = map.next_key::<String>()? {
606 if ENTRY_KEYS.contains(&key.as_str()) {
607 entry.insert(key.into(), map.next_value::<serde_yaml::Value>()?);
608 } else {
609 map.next_value::<serde::de::IgnoredAny>()?;
610 }
611 }
612 read_model_entry(&serde_yaml::Value::Mapping(entry))
613 .entry
614 .map(ModelsItem::Entry)
615 .map_err(|errors| serde::de::Error::custom(entry_error(&errors)))
616 }
617}
618
619impl<'de> Deserialize<'de> for ModelsItem {
620 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
621 deserializer.deserialize_any(EntryVisitor)
622 }
623}
624
625impl Serialize for ModelEntry {
626 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
627 if self.when.is_none() && self.no_fallback.is_none() && self.overrides.is_empty() {
628 return serializer.serialize_str(&self.model);
629 }
630 let mut map = serializer.serialize_map(None)?;
631 map.serialize_entry("model", &self.model)?;
632 if let Some(when) = &self.when {
633 map.serialize_entry("when", when)?;
634 }
635 if let Some(no_fallback) = self.no_fallback {
636 map.serialize_entry("no-fallback", &no_fallback)?;
637 }
638 for key in ["effort", "sandbox", "approval", "network"] {
639 if let Some(value) = self.overrides.get(key) {
640 map.serialize_entry(key, value)?;
641 }
642 }
643 map.end()
644 }
645}
646
647impl Serialize for ModelsItem {
648 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
649 match self {
650 Self::Rest => serializer.serialize_str(MODELS_SPLICE),
651 Self::Entry(entry) => entry.serialize(serializer),
652 }
653 }
654}
655
656impl<'de> Deserialize<'de> for ModelPolicyRule {
657 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
658 where
659 D: serde::Deserializer<'de>,
660 {
661 struct RuleVisitor;
664
665 impl<'de> serde::de::Visitor<'de> for RuleVisitor {
666 type Value = ModelPolicyRule;
667
668 fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
669 f.write_str("a model policy rule mapping")
670 }
671
672 fn visit_map<A: serde::de::MapAccess<'de>>(
673 self,
674 mut map: A,
675 ) -> Result<Self::Value, A::Error> {
676 let mut rule = serde_yaml::Mapping::new();
677 while let Some(key) = map.next_key::<String>()? {
678 if RULE_KEYS.contains(&key.as_str()) {
679 rule.insert(key.into(), map.next_value::<serde_yaml::Value>()?);
680 } else {
681 map.next_value::<serde::de::IgnoredAny>()?;
682 }
683 }
684 read_model_policy_rule(&serde_yaml::Value::Mapping(rule))
685 .rule
686 .map_err(|errors| {
687 serde::de::Error::custom(
688 errors
689 .iter()
690 .map(ModelPolicyRuleParseError::deserialize_message)
691 .collect::<Vec<_>>()
692 .join("; "),
693 )
694 })
695 }
696 }
697
698 deserializer.deserialize_map(RuleVisitor)
699 }
700}
701
702impl Serialize for ModelPolicyRule {
703 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
704 where
705 S: serde::Serializer,
706 {
707 let mut map = serializer.serialize_map(None)?;
708 let match_key = match self.match_type {
709 ModelPolicyMatchType::Model => "model",
710 ModelPolicyMatchType::Alias => "alias",
711 ModelPolicyMatchType::ModelGlob => "model-glob",
712 };
713
714 let mut match_clause = serde_yaml::Mapping::new();
715 match_clause.insert(
716 serde_yaml::Value::String(match_key.to_string()),
717 serde_yaml::Value::String(self.match_value.clone()),
718 );
719 map.serialize_entry("match", &match_clause)?;
720 if !self.overrides.is_empty() {
721 map.serialize_entry("override", &self.overrides)?;
722 }
723 if self.no_fallback {
724 map.serialize_entry("no-fallback", &self.no_fallback)?;
725 }
726 if let Some(when) = &self.when {
727 map.serialize_entry("when", when)?;
728 }
729 map.end()
730 }
731}