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}
107
108impl ModelPolicyRuleParseError {
109 fn deserialize_message(&self) -> String {
110 match self {
111 Self::MatchMustContainExactlyOne { .. }
112 | Self::MatchMissing
113 | Self::MatchMustBeMapping { .. } => {
114 "model policy `match` must contain exactly one of model, alias, model-glob"
115 .to_string()
116 }
117 Self::MatchKeyMustBeString { .. } => {
118 "model policy `match` key must be a string".to_string()
119 }
120 Self::MatchValueMustBeString { .. } => {
121 "model policy `match` value must be a string".to_string()
122 }
123 Self::MatchValueEmpty { .. } => {
124 "model policy `match` value must be a non-empty string".to_string()
125 }
126 Self::UnknownMatchKey { key } => format!(
127 "unknown model policy match key `{key}`; expected model, alias, or model-glob"
128 ),
129 Self::OverrideMustBeMapping { .. } => {
130 "model policy `override` must be a mapping".to_string()
131 }
132 Self::UnknownOverrideKey { key } => format!(
133 "unknown model policy override `{key}`; expected effort, sandbox, approval, or network"
134 ),
135 Self::NetworkHostsNotAllowed { key } => format!(
136 "model policy override `{key}` is not supported; set it on settings, the profile, an agent overlay, or the CLI"
137 ),
138 Self::OverrideValueInvalid {
139 key,
140 found,
141 allowed,
142 } => format!(
143 "model policy override `{key}` has invalid value `{found}`; allowed: {allowed}"
144 ),
145 Self::NoFallbackMustBeBoolean { .. } => {
146 "model policy `no-fallback` must be a boolean".to_string()
147 }
148 Self::WhenInvalid { .. } => {
149 "model policy `when` must be a non-empty one-line string".to_string()
150 }
151 Self::RuleMustBeMapping { .. } => "model policy rule must be a mapping".to_string(),
152 }
153 }
154}
155
156const RULE_KEYS: &[&str] = &["match", "override", "no-fallback", "when"];
160const OVERRIDE_KEYS: &[&str] = &[
161 "effort",
162 "sandbox",
163 "approval",
164 "network",
165 "network-allow",
166 "network-deny",
167];
168
169pub(crate) struct RuleReading {
172 pub rule: Result<ModelPolicyRule, Vec<ModelPolicyRuleParseError>>,
173 pub unknown: Vec<String>,
174}
175
176pub(crate) fn read_model_policy_rule(value: &serde_yaml::Value) -> RuleReading {
177 use ModelPolicyRuleParseError as Error;
178 let Some(rule) = value.as_mapping() else {
179 return RuleReading {
180 rule: Err(vec![Error::RuleMustBeMapping {
181 found: crate::ordered::plain(value),
182 }]),
183 unknown: Vec::new(),
184 };
185 };
186 let mut errors = Vec::new();
187 let unknown = unknown_keys(rule, RULE_KEYS);
188
189 let matched = read_match(rule).map_err(|error| errors.push(error)).ok();
190
191 let overrides = match rule.get(serde_yaml::Value::String("override".to_string())) {
192 Some(value) if !value.is_null() => match value.as_mapping() {
193 Some(mapping) => read_overrides(mapping, &mut errors),
194 None => {
195 errors.push(Error::OverrideMustBeMapping {
196 found: crate::ordered::plain(value),
197 });
198 ModelPolicyOverride::default()
199 }
200 },
201 _ => ModelPolicyOverride::default(),
202 };
203
204 let no_fallback = match rule.get(serde_yaml::Value::String("no-fallback".to_string())) {
205 None | Some(serde_yaml::Value::Null) => false,
206 Some(serde_yaml::Value::Bool(value)) => *value,
207 Some(value) => {
208 errors.push(Error::NoFallbackMustBeBoolean {
209 found: crate::ordered::plain(value),
210 });
211 false
212 }
213 };
214
215 let when = match rule.get(serde_yaml::Value::String("when".to_string())) {
216 None | Some(serde_yaml::Value::Null) => None,
217 Some(serde_yaml::Value::String(value))
218 if !value.is_empty() && !value.contains(['\n', '\r']) =>
219 {
220 Some(value.clone())
221 }
222 Some(value) => {
223 errors.push(Error::WhenInvalid {
224 found: crate::ordered::plain(value),
225 });
226 None
227 }
228 };
229
230 let rule = match matched {
231 Some((match_type, match_value)) if errors.is_empty() => Ok(ModelPolicyRule {
232 match_type,
233 match_value,
234 no_fallback,
235 overrides,
236 when,
237 }),
238 _ => Err(errors),
239 };
240 RuleReading { rule, unknown }
241}
242
243fn unknown_keys(mapping: &serde_yaml::Mapping, known: &[&str]) -> Vec<String> {
244 mapping
245 .keys()
246 .filter(|key| !key.as_str().is_some_and(|key| known.contains(&key)))
247 .map(|key| {
248 key.as_str()
249 .map_or_else(|| crate::ordered::plain(key), str::to_owned)
250 })
251 .collect()
252}
253
254fn read_match(
255 rule: &serde_yaml::Mapping,
256) -> Result<(ModelPolicyMatchType, String), ModelPolicyRuleParseError> {
257 use ModelPolicyRuleParseError as Error;
258 let match_mapping = match rule.get(serde_yaml::Value::String("match".to_string())) {
259 Some(value) => value
260 .as_mapping()
261 .ok_or_else(|| Error::MatchMustBeMapping {
262 found: crate::ordered::plain(value),
263 })?,
264 None => return Err(Error::MatchMissing),
265 };
266 let exactly_one = || Error::MatchMustContainExactlyOne {
267 found: crate::ordered::plain(&serde_yaml::Value::Mapping(match_mapping.clone())),
268 };
269 let mut entries = match_mapping.iter();
270 let Some((match_key, match_value)) = entries.next() else {
271 return Err(exactly_one());
272 };
273 if entries.next().is_some() {
274 return Err(exactly_one());
275 }
276
277 let key = match_key
278 .as_str()
279 .ok_or_else(|| Error::MatchKeyMustBeString {
280 found: crate::ordered::plain(match_key),
281 })?;
282 let value = match_value
283 .as_str()
284 .ok_or_else(|| Error::MatchValueMustBeString {
285 key: key.to_string(),
286 found: crate::ordered::plain(match_value),
287 })?;
288 if value.is_empty() {
289 return Err(Error::MatchValueEmpty {
290 key: key.to_string(),
291 });
292 }
293 let match_type = match key {
294 "model" => ModelPolicyMatchType::Model,
295 "alias" => ModelPolicyMatchType::Alias,
296 "model-glob" => ModelPolicyMatchType::ModelGlob,
297 _ => {
298 return Err(Error::UnknownMatchKey {
299 key: key.to_string(),
300 });
301 }
302 };
303 Ok((match_type, value.to_string()))
304}
305
306fn read_overrides(
308 mapping: &serde_yaml::Mapping,
309 errors: &mut Vec<ModelPolicyRuleParseError>,
310) -> ModelPolicyOverride {
311 let mut overrides = ModelPolicyOverride::default();
312 for (key, value) in mapping {
313 let Some(key) = key.as_str().filter(|key| OVERRIDE_KEYS.contains(key)) else {
314 errors.push(ModelPolicyRuleParseError::UnknownOverrideKey {
315 key: key
316 .as_str()
317 .map_or_else(|| crate::ordered::plain(key), str::to_owned),
318 });
319 continue;
320 };
321 if matches!(key, "network-allow" | "network-deny") {
322 errors.push(ModelPolicyRuleParseError::NetworkHostsNotAllowed {
323 key: key.to_string(),
324 });
325 continue;
326 }
327 let invalid = |found: String| ModelPolicyRuleParseError::OverrideValueInvalid {
328 key: key.to_string(),
329 found,
330 allowed: allowed_override_values(key),
331 };
332 let raw = if key == "effort" && value.is_null() {
334 Some("auto")
335 } else {
336 value.as_str()
337 };
338 let Some(raw) = raw else {
339 errors.push(invalid(crate::ordered::plain(value)));
340 continue;
341 };
342 let parsed = match key {
343 "effort" => EffortRequest::parse(raw).map(|value| value.as_str().to_string()),
344 "sandbox" => SandboxMode::parse(raw).map(|value| value.as_str().to_string()),
345 "approval" => ApprovalMode::parse(raw).map(|value| value.as_str().to_string()),
346 _ => NetworkPolicy::parse(raw).map(|value| value.as_str().to_string()),
347 };
348 let Some(parsed) = parsed else {
349 errors.push(invalid(raw.to_string()));
350 continue;
351 };
352 match key {
353 "effort" => overrides.effort = Some(parsed),
354 "sandbox" => overrides.sandbox = Some(parsed),
355 "approval" => overrides.approval = Some(parsed),
356 _ => overrides.network = Some(parsed),
357 }
358 }
359 overrides
360}
361
362fn allowed_override_values(key: &str) -> &'static str {
363 match key {
364 "effort" => EffortRequest::ALLOWED,
365 "sandbox" => SandboxMode::ALLOWED,
366 "approval" => ApprovalMode::ALLOWED,
367 "network" => NetworkPolicy::ALLOWED,
368 _ => "effort, sandbox, approval, network",
369 }
370}
371
372impl<'de> Deserialize<'de> for ModelPolicyRule {
373 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
374 where
375 D: serde::Deserializer<'de>,
376 {
377 struct RuleVisitor;
380
381 impl<'de> serde::de::Visitor<'de> for RuleVisitor {
382 type Value = ModelPolicyRule;
383
384 fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
385 f.write_str("a model policy rule mapping")
386 }
387
388 fn visit_map<A: serde::de::MapAccess<'de>>(
389 self,
390 mut map: A,
391 ) -> Result<Self::Value, A::Error> {
392 let mut rule = serde_yaml::Mapping::new();
393 while let Some(key) = map.next_key::<String>()? {
394 if RULE_KEYS.contains(&key.as_str()) {
395 rule.insert(key.into(), map.next_value::<serde_yaml::Value>()?);
396 } else {
397 map.next_value::<serde::de::IgnoredAny>()?;
398 }
399 }
400 read_model_policy_rule(&serde_yaml::Value::Mapping(rule))
401 .rule
402 .map_err(|errors| {
403 serde::de::Error::custom(
404 errors
405 .iter()
406 .map(ModelPolicyRuleParseError::deserialize_message)
407 .collect::<Vec<_>>()
408 .join("; "),
409 )
410 })
411 }
412 }
413
414 deserializer.deserialize_map(RuleVisitor)
415 }
416}
417
418impl Serialize for ModelPolicyRule {
419 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
420 where
421 S: serde::Serializer,
422 {
423 let mut map = serializer.serialize_map(None)?;
424 let match_key = match self.match_type {
425 ModelPolicyMatchType::Model => "model",
426 ModelPolicyMatchType::Alias => "alias",
427 ModelPolicyMatchType::ModelGlob => "model-glob",
428 };
429
430 let mut match_clause = serde_yaml::Mapping::new();
431 match_clause.insert(
432 serde_yaml::Value::String(match_key.to_string()),
433 serde_yaml::Value::String(self.match_value.clone()),
434 );
435 map.serialize_entry("match", &match_clause)?;
436 if !self.overrides.is_empty() {
437 map.serialize_entry("override", &self.overrides)?;
438 }
439 if self.no_fallback {
440 map.serialize_entry("no-fallback", &self.no_fallback)?;
441 }
442 if let Some(when) = &self.when {
443 map.serialize_entry("when", when)?;
444 }
445 map.end()
446 }
447}