1use std::collections::BTreeMap;
27
28use serde::de::DeserializeOwned;
29use serde::{Deserialize, Deserializer, Serialize};
30use serde_json::Value;
31
32pub const MAX_URL_CHARS: usize = 2048;
34pub const MAX_MODEL_CHARS: usize = 256;
36pub const MAX_INSTRUCTIONS_CHARS: usize = 8000;
38pub const MAX_IMAGE_CHARS: usize = 255;
40
41pub const DEFAULT_BASE_URL: &str = "http://127.0.0.1:8080/v1";
43pub const DEFAULT_MODEL: &str = "default";
44pub const DEFAULT_COMPACT_PERCENT: u8 = 80;
45
46#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
48#[serde(rename_all = "snake_case")]
49pub enum Level {
50 #[default]
52 Default,
53 Global,
55 Workspace,
56 Chat,
57 Flag,
59}
60
61impl Level {
62 pub fn label(self) -> &'static str {
64 match self {
65 Self::Default => "default",
66 Self::Global => "global settings",
67 Self::Workspace => "workspace",
68 Self::Chat => "chat",
69 Self::Flag => "command line",
70 }
71 }
72}
73
74#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
76#[serde(rename_all = "snake_case")]
77pub enum ToolMode {
78 #[default]
80 Auto,
81 Native,
83 Prompt,
85}
86
87impl ToolMode {
88 pub const ALL: [Self; 3] = [Self::Auto, Self::Native, Self::Prompt];
89
90 pub fn parse(s: &str) -> Option<Self> {
91 match s {
92 "auto" => Some(Self::Auto),
93 "native" => Some(Self::Native),
94 "prompt" => Some(Self::Prompt),
95 _ => None,
96 }
97 }
98
99 pub fn label(self) -> &'static str {
100 match self {
101 Self::Auto => "Automatic",
102 Self::Native => "Native tool calls",
103 Self::Prompt => "Tools in the prompt",
104 }
105 }
106}
107
108#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
110#[serde(rename_all = "snake_case")]
111pub enum Approvals {
112 #[default]
114 Ask,
115 AllowEdits,
117 AllowAll,
119 ReadOnly,
121}
122
123impl Approvals {
124 pub const ALL: [Self; 4] = [Self::Ask, Self::AllowEdits, Self::AllowAll, Self::ReadOnly];
125
126 pub fn label(self) -> &'static str {
127 match self {
128 Self::Ask => "Ask before changes",
129 Self::AllowEdits => "Allow file edits",
130 Self::AllowAll => "Allow everything",
131 Self::ReadOnly => "Read only",
132 }
133 }
134}
135
136#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
138#[serde(rename_all = "snake_case")]
139pub enum EnvKind {
140 #[default]
143 Auto,
144 Host,
147 Nix,
150 Container,
152}
153
154impl EnvKind {
155 pub const ALL: [Self; 4] = [Self::Auto, Self::Host, Self::Nix, Self::Container];
156
157 pub fn label(self) -> &'static str {
158 match self {
159 Self::Auto => "Auto",
160 Self::Host => "This machine",
161 Self::Nix => "Nix dev shell",
162 Self::Container => "Container",
163 }
164 }
165
166 pub fn per_chat(self) -> bool {
168 matches!(self, Self::Host | Self::Container)
169 }
170}
171
172fn lenient<'de, D: Deserializer<'de>, T: DeserializeOwned>(d: D) -> Result<Option<T>, D::Error> {
175 let v = Value::deserialize(d)?;
176 Ok(serde_json::from_value(v).ok())
177}
178
179#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
181pub struct Layer {
182 #[serde(default, deserialize_with = "lenient", skip_serializing_if = "Option::is_none")]
183 pub base_url: Option<String>,
184 #[serde(default, deserialize_with = "lenient", skip_serializing_if = "Option::is_none")]
185 pub model: Option<String>,
186 #[serde(default, deserialize_with = "lenient", skip_serializing_if = "Option::is_none")]
187 pub tool_mode: Option<ToolMode>,
188 #[serde(default, deserialize_with = "lenient", skip_serializing_if = "Option::is_none")]
189 pub approvals: Option<Approvals>,
190 #[serde(default, deserialize_with = "lenient", skip_serializing_if = "Option::is_none")]
191 pub auto_compact: Option<bool>,
192 #[serde(default, deserialize_with = "lenient", skip_serializing_if = "Option::is_none")]
194 pub compact_percent: Option<u8>,
195 #[serde(default, deserialize_with = "lenient", skip_serializing_if = "Option::is_none")]
197 pub subagents: Option<bool>,
198 #[serde(default, deserialize_with = "lenient", skip_serializing_if = "Option::is_none")]
200 pub instructions: Option<String>,
201 #[serde(default, deserialize_with = "lenient", skip_serializing_if = "Option::is_none")]
202 pub env: Option<EnvKind>,
203 #[serde(default, deserialize_with = "lenient", skip_serializing_if = "Option::is_none")]
206 pub image: Option<String>,
207 #[serde(default, deserialize_with = "lenient", skip_serializing_if = "Option::is_none")]
211 pub plugins: Option<BTreeMap<String, bool>>,
212}
213
214pub const MAX_PLUGIN_SWITCHES: usize = 500;
216
217pub fn plugin_id_ok(id: &str) -> bool {
219 let b = id.as_bytes();
220 let alnum = |c: u8| c.is_ascii_lowercase() || c.is_ascii_digit();
221 !b.is_empty() && b.len() <= 48 && alnum(b[0]) && b.iter().all(|&c| alnum(c) || c == b'-')
222}
223
224#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
226pub enum Field {
227 Endpoint,
229 ToolMode,
230 Approvals,
231 Compaction,
233 Subagents,
234 Instructions,
235 Env,
236 Image,
237}
238
239impl Field {
240 pub const ALL: [Self; 8] = [Self::Endpoint, Self::ToolMode, Self::Approvals, Self::Compaction, Self::Subagents, Self::Instructions, Self::Env, Self::Image];
241
242 pub fn levels(self) -> &'static [Level] {
244 const ALL: &[Level] = &[Level::Global, Level::Workspace, Level::Chat];
245 match self {
246 Self::Endpoint | Self::ToolMode | Self::Approvals | Self::Compaction | Self::Subagents | Self::Instructions => ALL,
247 Self::Env => &[Level::Workspace, Level::Chat],
248 Self::Image => &[Level::Workspace],
249 }
250 }
251
252 pub fn at(self, level: Level) -> bool {
253 self.levels().contains(&level)
254 }
255
256 pub fn label(self) -> &'static str {
257 match self {
258 Self::Endpoint => "Model",
259 Self::ToolMode => "Tool calling",
260 Self::Approvals => "Approvals",
261 Self::Compaction => "Compaction",
262 Self::Subagents => "Subagents",
263 Self::Instructions => "Instructions",
264 Self::Env => "Environment",
265 Self::Image => "Container image",
266 }
267 }
268}
269
270impl Layer {
271 pub fn has(&self, field: Field) -> bool {
273 match field {
274 Field::Endpoint => self.base_url.is_some() || self.model.is_some(),
275 Field::ToolMode => self.tool_mode.is_some(),
276 Field::Approvals => self.approvals.is_some(),
277 Field::Compaction => self.auto_compact.is_some() || self.compact_percent.is_some(),
278 Field::Subagents => self.subagents.is_some(),
279 Field::Instructions => self.instructions.is_some(),
280 Field::Env => self.env.is_some(),
281 Field::Image => self.image.is_some(),
282 }
283 }
284
285 pub fn reset(&mut self, field: Field) {
287 match field {
288 Field::Endpoint => {
289 self.base_url = None;
290 self.model = None;
291 }
292 Field::ToolMode => self.tool_mode = None,
293 Field::Approvals => self.approvals = None,
294 Field::Compaction => {
295 self.auto_compact = None;
296 self.compact_percent = None;
297 }
298 Field::Subagents => self.subagents = None,
299 Field::Instructions => self.instructions = None,
300 Field::Env => self.env = None,
301 Field::Image => self.image = None,
302 }
303 }
304
305 pub fn is_empty(&self) -> bool {
306 *self == Self::default()
307 }
308
309 pub fn validated(mut self, level: Level) -> Result<Self, String> {
313 let clean = |v: Option<String>| v.map(|s| s.trim().to_owned()).filter(|s| !s.is_empty());
314 self.base_url = clean(self.base_url);
315 self.model = clean(self.model);
316 self.image = clean(self.image);
317 self.instructions = self.instructions.map(|s| s.trim().to_owned()).filter(|s| !s.is_empty());
318 if self.base_url.as_ref().is_some_and(|u| u.chars().count() > MAX_URL_CHARS) {
319 return Err("the URL is too long".into());
320 }
321 if let Some(u) = &self.base_url
322 && !(u.starts_with("http://") || u.starts_with("https://"))
323 {
324 return Err(format!("{u:?} isn't an http:// or https:// URL"));
325 }
326 if self.model.as_ref().is_some_and(|m| m.chars().count() > MAX_MODEL_CHARS) {
327 return Err("the model name is too long".into());
328 }
329 if self.instructions.as_ref().is_some_and(|i| i.chars().count() > MAX_INSTRUCTIONS_CHARS) {
330 return Err(format!("instructions are limited to {MAX_INSTRUCTIONS_CHARS} characters"));
331 }
332 if let Some(i) = &self.image
333 && !valid_image(i)
334 {
335 return Err(format!("{i:?} isn't a container image reference (like python:3-slim)"));
336 }
337 self.compact_percent = self.compact_percent.map(|p| p.clamp(10, 95));
338 if let Some(p) = &self.plugins {
339 if p.len() > MAX_PLUGIN_SWITCHES {
340 return Err(format!("at most {MAX_PLUGIN_SWITCHES} plugins can be switched per level"));
341 }
342 if let Some(bad) = p.keys().find(|id| !plugin_id_ok(id)) {
343 return Err(format!("{bad:?} isn't a plugin id"));
344 }
345 }
346 self.plugins = self.plugins.filter(|p| !p.is_empty());
347 for field in Field::ALL {
348 if self.has(field) && !field.at(level) {
349 return Err(format!("{} can't be set per {}", field.label().to_lowercase(), level.label()));
350 }
351 }
352 if level == Level::Chat
353 && let Some(e) = self.env.filter(|e| !e.per_chat())
354 {
355 return Err(format!("a chat can only run its commands on this machine or in the container, not {:?}", e.label()));
356 }
357 Ok(self)
358 }
359}
360
361pub fn valid_image(i: &str) -> bool {
363 !i.is_empty() && i.len() <= MAX_IMAGE_CHARS && !i.starts_with('-') && i.chars().all(|c| c.is_ascii_alphanumeric() || "._-/:@".contains(c))
364}
365
366#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
368pub struct Sourced<T> {
369 pub value: T,
370 pub from: Level,
371}
372
373#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
375pub struct Effective {
376 pub base_url: Sourced<String>,
377 pub model: Sourced<String>,
378 #[serde(default)]
380 pub key_from: Option<Level>,
381 pub tool_mode: Sourced<ToolMode>,
382 pub approvals: Sourced<Approvals>,
383 pub auto_compact: Sourced<bool>,
384 pub compact_percent: Sourced<u8>,
385 pub subagents: Sourced<bool>,
386 #[serde(default)]
388 pub instructions: Vec<(Level, String)>,
389 pub env: Sourced<EnvKind>,
390 #[serde(default)]
394 pub load_project: Option<bool>,
395 #[serde(default)]
397 pub image: Option<String>,
398 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
401 pub plugins: BTreeMap<String, Sourced<bool>>,
402}
403
404impl Effective {
405 pub fn container(&self) -> Option<bool> {
408 match self.env.value {
409 EnvKind::Auto => None,
410 EnvKind::Host | EnvKind::Nix => Some(false),
411 EnvKind::Container => Some(true),
412 }
413 }
414
415 pub fn plugin_on(&self, id: &str) -> Sourced<bool> {
417 self.plugins.get(id).cloned().unwrap_or(Sourced { value: true, from: Level::Default })
418 }
419
420 pub fn instructions_text(&self) -> String {
422 self.instructions.iter().map(|(_, s)| s.as_str()).collect::<Vec<_>>().join("\n\n")
423 }
424}
425
426#[derive(Debug, Clone, Copy, Default)]
428pub struct Levels<'a> {
429 pub global: Option<&'a Layer>,
430 pub workspace: Option<&'a Layer>,
431 pub chat: Option<&'a Layer>,
432}
433
434#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
436pub struct Keys {
437 pub global: bool,
438 pub workspace: bool,
439 pub chat: bool,
440}
441
442#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
444pub struct Forced {
445 pub approvals: Option<Approvals>,
446 pub tool_mode: Option<ToolMode>,
447}
448
449fn pick<T: Clone>(levels: &Levels<'_>, default: T, get: impl Fn(&Layer) -> Option<T>) -> Sourced<T> {
450 let ordered = [(Level::Chat, levels.chat), (Level::Workspace, levels.workspace), (Level::Global, levels.global)];
451 for (level, layer) in ordered {
452 if let Some(v) = layer.and_then(&get) {
453 return Sourced { value: v, from: level };
454 }
455 }
456 Sourced { value: default, from: Level::Default }
457}
458
459pub fn origin(url: &str) -> String {
461 let u = url.trim().to_ascii_lowercase();
462 let (scheme, rest) = u.split_once("://").unwrap_or(("", u.as_str()));
463 let host = rest.split(['/', '?', '#']).next().unwrap_or_default();
464 format!("{scheme}://{host}")
465}
466
467pub fn resolve(levels: Levels<'_>, keys: Keys, forced: Forced) -> Effective {
471 let base_url = pick(&levels, DEFAULT_BASE_URL.to_owned(), |l| l.base_url.clone());
472 let model = pick(&levels, DEFAULT_MODEL.to_owned(), |l| l.model.clone());
473 let upto = |stop: Level| {
475 let partial = Levels {
476 global: levels.global,
477 workspace: levels.workspace.filter(|_| stop >= Level::Workspace),
478 chat: levels.chat.filter(|_| stop >= Level::Chat),
479 };
480 pick(&partial, DEFAULT_BASE_URL.to_owned(), |l| l.base_url.clone()).value
481 };
482 let want = origin(&base_url.value);
483 let key_from = [(Level::Chat, keys.chat), (Level::Workspace, keys.workspace), (Level::Global, keys.global)]
484 .into_iter()
485 .find(|(level, has)| *has && origin(&upto(*level)) == want)
486 .map(|(level, _)| level);
487 let mut tool_mode = pick(&levels, ToolMode::Auto, |l| l.tool_mode);
488 if let Some(m) = forced.tool_mode {
489 tool_mode = Sourced { value: m, from: Level::Flag };
490 }
491 let mut approvals = pick(&levels, Approvals::Ask, |l| l.approvals);
492 if let Some(a) = forced.approvals {
493 approvals = Sourced { value: a, from: Level::Flag };
494 }
495 let instructions = [(Level::Global, levels.global), (Level::Workspace, levels.workspace), (Level::Chat, levels.chat)]
496 .into_iter()
497 .filter_map(|(level, layer)| layer.and_then(|l| l.instructions.clone()).filter(|s| !s.trim().is_empty()).map(|s| (level, s)))
498 .collect();
499 let ws_env = levels.workspace.and_then(|l| l.env).unwrap_or_default();
500 let chat_env = levels.chat.and_then(|l| l.env).filter(|e| e.per_chat());
501 let env = match (chat_env, levels.workspace.and_then(|l| l.env)) {
502 (Some(e), _) => Sourced { value: e, from: Level::Chat },
503 (None, Some(e)) => Sourced { value: e, from: Level::Workspace },
504 (None, None) => Sourced { value: EnvKind::Auto, from: Level::Default },
505 };
506 Effective {
507 base_url,
508 model,
509 key_from,
510 tool_mode,
511 approvals,
512 auto_compact: pick(&levels, true, |l| l.auto_compact),
513 compact_percent: pick(&levels, DEFAULT_COMPACT_PERCENT, |l| l.compact_percent.map(|p| p.clamp(10, 95))),
514 subagents: pick(&levels, true, |l| l.subagents),
515 instructions,
516 env,
517 load_project: (ws_env == EnvKind::Nix).then_some(true),
518 image: levels.workspace.and_then(|l| l.image.clone()).filter(|i| valid_image(i)),
519 plugins: plugin_switches(&levels),
520 }
521}
522
523fn plugin_switches(levels: &Levels<'_>) -> BTreeMap<String, Sourced<bool>> {
525 let mut out = BTreeMap::new();
526 for (level, layer) in [(Level::Global, levels.global), (Level::Workspace, levels.workspace), (Level::Chat, levels.chat)] {
527 for (id, on) in layer.and_then(|l| l.plugins.as_ref()).into_iter().flatten() {
528 out.insert(id.clone(), Sourced { value: *on, from: level });
529 }
530 }
531 out
532}
533
534#[cfg(test)]
535mod tests {
536 use super::*;
537
538 fn layer(f: impl FnOnce(&mut Layer)) -> Layer {
539 let mut l = Layer::default();
540 f(&mut l);
541 l
542 }
543
544 #[test]
545 fn nothing_set_gives_the_built_in_defaults() {
546 let e = resolve(Levels::default(), Keys::default(), Forced::default());
547 assert_eq!(e.base_url, Sourced { value: DEFAULT_BASE_URL.to_owned(), from: Level::Default });
548 assert_eq!(e.model.value, DEFAULT_MODEL);
549 assert_eq!((e.tool_mode.value, e.approvals.value, e.env.value), (ToolMode::Auto, Approvals::Ask, EnvKind::Auto));
550 assert_eq!((e.auto_compact.value, e.compact_percent.value, e.subagents.value), (true, 80, true));
551 assert!(e.instructions.is_empty() && e.key_from.is_none() && e.load_project.is_none() && e.container().is_none());
552 }
553
554 #[test]
555 fn the_most_specific_level_wins_per_field() {
556 let g = layer(|l| {
557 l.base_url = Some("http://g/v1".into());
558 l.model = Some("gm".into());
559 l.approvals = Some(Approvals::AllowEdits);
560 l.compact_percent = Some(70);
561 });
562 let w = layer(|l| {
563 l.model = Some("wm".into());
564 l.tool_mode = Some(ToolMode::Prompt);
565 l.compact_percent = Some(60);
566 });
567 let c = layer(|l| {
568 l.compact_percent = Some(50);
569 l.subagents = Some(false);
570 });
571 let e = resolve(Levels { global: Some(&g), workspace: Some(&w), chat: Some(&c) }, Keys::default(), Forced::default());
572 assert_eq!(e.base_url, Sourced { value: "http://g/v1".into(), from: Level::Global });
573 assert_eq!(e.model, Sourced { value: "wm".into(), from: Level::Workspace });
574 assert_eq!(e.tool_mode, Sourced { value: ToolMode::Prompt, from: Level::Workspace });
575 assert_eq!(e.approvals, Sourced { value: Approvals::AllowEdits, from: Level::Global });
576 assert_eq!(e.compact_percent, Sourced { value: 50, from: Level::Chat });
577 assert_eq!(e.subagents, Sourced { value: false, from: Level::Chat });
578 assert_eq!(e.auto_compact.from, Level::Default);
579 let e = resolve(Levels { global: Some(&g), workspace: Some(&w), chat: None }, Keys::default(), Forced::default());
581 assert_eq!(e.compact_percent, Sourced { value: 60, from: Level::Workspace });
582 let wild = layer(|l| l.compact_percent = Some(200));
584 assert_eq!(resolve(Levels { chat: Some(&wild), ..Default::default() }, Keys::default(), Forced::default()).compact_percent.value, 95);
585 }
586
587 #[test]
588 fn plugin_switches_resolve_per_plugin() {
589 let g = layer(|l| l.plugins = Some([("web".to_owned(), false), ("pdf".to_owned(), false)].into()));
590 let w = layer(|l| l.plugins = Some([("web".to_owned(), true)].into()));
591 let c = layer(|l| l.plugins = Some([("pdf".to_owned(), true), ("git".to_owned(), false)].into()));
592 let e = resolve(Levels { global: Some(&g), workspace: Some(&w), chat: Some(&c) }, Keys::default(), Forced::default());
593 assert_eq!(e.plugin_on("web"), Sourced { value: true, from: Level::Workspace });
594 assert_eq!(e.plugin_on("pdf"), Sourced { value: true, from: Level::Chat });
595 assert_eq!(e.plugin_on("git"), Sourced { value: false, from: Level::Chat });
596 assert_eq!(e.plugin_on("other"), Sourced { value: true, from: Level::Default });
597 assert!(layer(|l| l.plugins = Some([("Bad Id".to_owned(), true)].into())).validated(Level::Chat).is_err());
598 assert_eq!(layer(|l| l.plugins = Some(BTreeMap::new())).validated(Level::Chat).unwrap().plugins, None);
599 }
600
601 #[test]
602 fn instructions_are_appended_in_order() {
603 let g = layer(|l| l.instructions = Some("Be brief.".into()));
604 let w = layer(|l| l.instructions = Some("This repo uses Rust.".into()));
605 let c = layer(|l| l.instructions = Some(" ".into()));
606 let e = resolve(Levels { global: Some(&g), workspace: Some(&w), chat: Some(&c) }, Keys::default(), Forced::default());
607 assert_eq!(e.instructions, vec![(Level::Global, "Be brief.".to_owned()), (Level::Workspace, "This repo uses Rust.".to_owned())]);
608 assert_eq!(e.instructions_text(), "Be brief.\n\nThis repo uses Rust.");
609 }
610
611 #[test]
612 fn keys_follow_only_their_own_server() {
613 let g = layer(|l| l.base_url = Some("http://local:8080/v1".into()));
614 let w = layer(|l| l.base_url = Some("https://api.example.com/v1".into()));
615 let c_same = layer(|l| l.model = Some("other".into()));
616 let c_back = layer(|l| l.base_url = Some("http://local:8080/v1/".into()));
617 let all = Keys { global: true, workspace: true, chat: false };
618 let e = resolve(Levels { global: Some(&g), workspace: Some(&w), chat: Some(&c_same) }, all, Forced::default());
620 assert_eq!(e.key_from, Some(Level::Workspace));
621 let e = resolve(Levels { global: Some(&g), workspace: Some(&w), chat: Some(&c_same) }, Keys { global: true, ..Keys::default() }, Forced::default());
622 assert_eq!(e.key_from, None, "the global key never follows the URL to another server");
623 let e = resolve(Levels { global: Some(&g), workspace: Some(&w), chat: Some(&c_back) }, all, Forced::default());
625 assert_eq!(e.key_from, Some(Level::Global));
626 let e = resolve(Levels { global: Some(&g), workspace: Some(&w), chat: Some(&c_back) }, Keys { chat: true, ..all }, Forced::default());
628 assert_eq!(e.key_from, Some(Level::Chat));
629 let w_key_only = layer(|l| l.model = Some("m".into()));
631 let e = resolve(Levels { global: Some(&g), workspace: Some(&w_key_only), chat: None }, Keys { workspace: true, ..Keys::default() }, Forced::default());
632 assert_eq!(e.key_from, Some(Level::Workspace));
633 assert_eq!(origin("HTTP://Example.com:8080/v1/"), "http://example.com:8080");
634 assert_ne!(origin("http://127.0.0.1:8080/v1"), origin("http://127.0.0.1:11434/v1"));
635 }
636
637 #[test]
638 fn environments_come_from_the_workspace_and_a_chat_may_move_its_commands() {
639 let none = resolve(Levels::default(), Keys::default(), Forced::default());
640 assert_eq!((none.container(), none.load_project), (None, None));
641 let nix = layer(|l| l.env = Some(EnvKind::Nix));
642 let container = layer(|l| {
643 l.env = Some(EnvKind::Container);
644 l.image = Some("debian:stable-slim".into());
645 });
646 let host = layer(|l| l.env = Some(EnvKind::Host));
647 let to_container = layer(|l| l.env = Some(EnvKind::Container));
648 let e = resolve(Levels { workspace: Some(&container), ..Default::default() }, Keys::default(), Forced::default());
649 assert_eq!(
650 (e.env.value, e.env.from, e.container(), e.image.as_deref()),
651 (EnvKind::Container, Level::Workspace, Some(true), Some("debian:stable-slim"))
652 );
653 let e = resolve(Levels { workspace: Some(&container), chat: Some(&host), ..Default::default() }, Keys::default(), Forced::default());
655 assert_eq!((e.env.value, e.env.from, e.container()), (EnvKind::Host, Level::Chat, Some(false)));
656 let e = resolve(Levels { workspace: Some(&nix), chat: Some(&host), ..Default::default() }, Keys::default(), Forced::default());
658 assert_eq!((e.container(), e.load_project), (Some(false), Some(true)));
659 let e = resolve(Levels { workspace: Some(&nix), chat: Some(&to_container), ..Default::default() }, Keys::default(), Forced::default());
660 assert_eq!(e.container(), Some(true));
661 let bad_chat = layer(|l| l.env = Some(EnvKind::Nix));
663 let e = resolve(Levels { workspace: Some(&container), chat: Some(&bad_chat), ..Default::default() }, Keys::default(), Forced::default());
664 assert_eq!(e.env.from, Level::Workspace);
665 let evil = layer(|l| l.image = Some("--privileged".into()));
667 assert_eq!(resolve(Levels { workspace: Some(&evil), ..Default::default() }, Keys::default(), Forced::default()).image, None);
668 }
669
670 #[test]
671 fn flags_beat_every_level() {
672 let c = layer(|l| {
673 l.approvals = Some(Approvals::ReadOnly);
674 l.tool_mode = Some(ToolMode::Native);
675 });
676 let forced = Forced { approvals: Some(Approvals::AllowAll), tool_mode: Some(ToolMode::Prompt) };
677 let e = resolve(Levels { chat: Some(&c), ..Default::default() }, Keys::default(), forced);
678 assert_eq!(e.approvals, Sourced { value: Approvals::AllowAll, from: Level::Flag });
679 assert_eq!(e.tool_mode, Sourced { value: ToolMode::Prompt, from: Level::Flag });
680 }
681
682 #[test]
683 fn layers_from_clients_are_checked_per_level() {
684 let ok = layer(|l| {
685 l.base_url = Some(" http://h/v1 ".into());
686 l.model = Some(" ".into());
687 l.compact_percent = Some(3);
688 l.instructions = Some("\n".into());
689 })
690 .validated(Level::Chat)
691 .unwrap();
692 assert_eq!((ok.base_url.as_deref(), ok.model.as_deref(), ok.compact_percent, ok.instructions.as_deref()), (Some("http://h/v1"), None, Some(10), None));
693 assert!(layer(|l| l.base_url = Some("file:///etc/passwd".into())).validated(Level::Chat).is_err());
694 assert!(layer(|l| l.base_url = Some(format!("http://{}", "a".repeat(MAX_URL_CHARS)))).validated(Level::Workspace).is_err());
695 assert!(layer(|l| l.model = Some("m".repeat(MAX_MODEL_CHARS + 1))).validated(Level::Chat).is_err());
696 assert!(layer(|l| l.instructions = Some("x".repeat(MAX_INSTRUCTIONS_CHARS + 1))).validated(Level::Global).is_err());
697 assert!(layer(|l| l.env = Some(EnvKind::Container)).validated(Level::Global).is_err());
699 assert!(layer(|l| l.image = Some("alpine".into())).validated(Level::Chat).is_err());
700 assert!(layer(|l| l.env = Some(EnvKind::Nix)).validated(Level::Chat).is_err());
701 assert!(layer(|l| l.env = Some(EnvKind::Host)).validated(Level::Chat).is_ok());
702 assert!(layer(|l| l.image = Some("alpine; rm -rf /".into())).validated(Level::Workspace).is_err());
703 assert!(layer(|l| l.image = Some("ghcr.io/me/img:1.2@sha256:abc".into())).validated(Level::Workspace).is_ok());
704 }
705
706 #[test]
707 fn layers_round_trip_and_bad_values_are_dropped_alone() {
708 let l = layer(|l| {
709 l.approvals = Some(Approvals::AllowEdits);
710 l.env = Some(EnvKind::Container);
711 });
712 let json = serde_json::to_string(&l).unwrap();
713 assert_eq!(json, r#"{"approvals":"allow_edits","env":"container"}"#);
714 assert_eq!(serde_json::from_str::<Layer>(&json).unwrap(), l);
715 let damaged: Layer = serde_json::from_str(r#"{"approvals":"sometimes","model":"m","compact_percent":"lots","future":1}"#).unwrap();
716 assert_eq!(damaged, layer(|l| l.model = Some("m".into())));
717 let mut reset = l.clone();
718 reset.reset(Field::Env);
719 assert!(!reset.has(Field::Env) && reset.has(Field::Approvals));
720 reset.reset(Field::Approvals);
721 assert!(reset.is_empty());
722 }
723}