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