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