Skip to main content

byob_types/
config.rs

1//! Layered settings: built-in defaults → global (`settings.json`) → workspace → chat.
2//!
3//! Each level is a [`Layer`] of optional values; [`resolve`] turns the levels into the
4//! [`Effective`] settings of one chat and says where each value came from. Only some
5//! settings exist at each level ([`Field::levels`]):
6//!
7//! | setting | global | workspace | chat |
8//! |---|---|---|---|
9//! | endpoint (URL + model; keys stay in the engine) | ✓ | ✓ | ✓ |
10//! | tool calling mode | ✓ | ✓ | ✓ |
11//! | approvals | ✓ | ✓ | ✓ |
12//! | compaction (auto, threshold) | ✓ | ✓ | ✓ |
13//! | subagents on/off | ✓ | ✓ | ✓ |
14//! | extra instructions (appended, never replaced) | ✓ | ✓ | ✓ |
15//! | environment (Auto, Host, Nix, Container) | | ✓ | Host / Container only |
16//! | container image | | ✓ | |
17//!
18//! Global-only settings (theme, storage, plugin folders, container runtime and default
19//! image, the workspaces folder, model roles, subagent limits) stay in `settings.json` and
20//! are not layered. The most specific level that sets a value wins, except instructions,
21//! which are joined in order global, workspace, chat. Command-line testing flags
22//! (`--auto-approve`, `--tool-mode`) beat every level ([`Level::Flag`]).
23//!
24//! This module is pure (no I/O) so the engine and the UI resolve the same way.
25
26use std::collections::BTreeMap;
27
28use serde::de::DeserializeOwned;
29use serde::{Deserialize, Deserializer, Serialize};
30use serde_json::Value;
31
32/// Longest base URL a level may set.
33pub const MAX_URL_CHARS: usize = 2048;
34/// Longest model name.
35pub const MAX_MODEL_CHARS: usize = 256;
36/// Longest extra instructions per level.
37pub const MAX_INSTRUCTIONS_CHARS: usize = 8000;
38/// Longest container image reference.
39pub const MAX_IMAGE_CHARS: usize = 255;
40
41/// The built-in endpoint when nothing is configured.
42pub 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/// JPEG quality images sent to the model get by default: a light pass, often much smaller
46/// than a PNG screenshot and hard to tell apart.
47pub const DEFAULT_IMAGE_QUALITY: u8 = 85;
48/// Tool calls one turn may make by default (`max_tool_calls`; 0 is no limit).
49pub const DEFAULT_TOOL_CALLS: u32 = 30;
50/// Largest limit that can be set short of none.
51pub const MAX_TOOL_CALLS: u32 = 100_000;
52
53/// Where a value comes from, least to most specific.
54#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
55#[serde(rename_all = "snake_case")]
56pub enum Level {
57    /// Built into byob.
58    #[default]
59    Default,
60    /// `settings.json` (or `--inference-url` / `--model` for this run).
61    Global,
62    Workspace,
63    Chat,
64    /// A command-line testing flag for this run (`--auto-approve`, `--tool-mode`).
65    Flag,
66}
67
68impl Level {
69    /// For the UI: "default", "global settings", "workspace", "chat", "command line".
70    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/// How turns pass tools to the model.
82#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
83#[serde(rename_all = "snake_case")]
84pub enum ToolMode {
85    /// Follow the endpoint probe; native first when it is inconclusive.
86    #[default]
87    Auto,
88    /// The server's structured `tools` / `tool_calls`.
89    Native,
90    /// Tools described in the system prompt; calls parsed from the reply text.
91    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/// Which tool calls run without asking.
116#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
117#[serde(rename_all = "snake_case")]
118pub enum Approvals {
119    /// Reads run; writes, network and commands ask.
120    #[default]
121    Ask,
122    /// Reads and file edits run; network and commands ask.
123    AllowEdits,
124    /// Everything runs without asking (calls a person must confirm still ask).
125    AllowAll,
126    /// Only reads: writes, network and commands are refused.
127    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/// Where a workspace's commands (`run_command`, `run_python`) run and what they get.
144#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
145#[serde(rename_all = "snake_case")]
146pub enum EnvKind {
147    /// Today's behaviour: on this machine; byob asks once before loading the folder's
148    /// project environment or using its devcontainer.json.
149    #[default]
150    Auto,
151    /// Always on this machine (byob's sandbox), never in a container. A project
152    /// environment is still asked about once.
153    Host,
154    /// On this machine with the folder's Nix dev shell (flake.nix / shell.nix, or another
155    /// project environment) loaded without asking.
156    Nix,
157    /// In the workspace's Docker/Podman container (devcontainer.json or an image).
158    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    /// May a chat choose this (a chat only picks where its commands run)?
174    pub fn per_chat(self) -> bool {
175        matches!(self, Self::Host | Self::Container)
176    }
177}
178
179/// Deserialize a field, falling back to `None` when the stored value has the wrong shape:
180/// one bad value shouldn't reset a whole layer.
181fn 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/// One level's own settings; `None` means "inherit".
187#[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    /// Compact when a request passes this percentage of the context window (10..=95).
200    #[serde(default, deserialize_with = "lenient", skip_serializing_if = "Option::is_none")]
201    pub compact_percent: Option<u8>,
202    /// Offer the `delegate` tool.
203    #[serde(default, deserialize_with = "lenient", skip_serializing_if = "Option::is_none")]
204    pub subagents: Option<bool>,
205    /// Images sent to the model are re-encoded as JPEG at this quality (1..=100) when that
206    /// makes them smaller; 0 sends them as they are (downscaled only).
207    #[serde(default, deserialize_with = "lenient", skip_serializing_if = "Option::is_none")]
208    pub image_quality: Option<u8>,
209    /// Most tool calls in one turn; 0: no limit.
210    #[serde(default, deserialize_with = "lenient", skip_serializing_if = "Option::is_none")]
211    pub max_tool_calls: Option<u32>,
212    /// Appended to the system prompt after the less specific levels' instructions.
213    #[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    /// The container image (workspace only). `None`: the folder's devcontainer.json if it
218    /// has one, else the global default image.
219    #[serde(default, deserialize_with = "lenient", skip_serializing_if = "Option::is_none")]
220    pub image: Option<String>,
221    /// Plugins turned on (`true`) or off (`false`) at this level, by plugin id; plugins not
222    /// named inherit (on by default). Every level has it; it changes through its own message
223    /// (`SetPluginEnabled`), not the settings form.
224    #[serde(default, deserialize_with = "lenient", skip_serializing_if = "Option::is_none")]
225    pub plugins: Option<BTreeMap<String, bool>>,
226}
227
228/// Most plugins one level may turn on or off.
229pub const MAX_PLUGIN_SWITCHES: usize = 500;
230
231/// A plugin id as manifests have it: `[a-z0-9][a-z0-9-]{0,47}`.
232pub 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/// The groups of settings, for [`Field::levels`] and the UI's reset buttons.
239#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
240pub enum Field {
241    /// `base_url` and `model` together.
242    Endpoint,
243    ToolMode,
244    Approvals,
245    /// `auto_compact` and `compact_percent`.
246    Compaction,
247    Subagents,
248    /// `image_quality`.
249    ModelImages,
250    /// `max_tool_calls`.
251    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    /// The levels this setting exists at (besides [`Level::Default`]).
272    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    /// Is `field` set at this level?
310    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    /// Forget `field` here (inherit it again).
326    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    /// Check an untrusted layer for `level`: trims text, turns blank text into `None`,
352    /// clamps the threshold, and refuses settings that don't exist at that level, values
353    /// that are too long, and images that aren't plain references.
354    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
405/// An image reference: no options, spaces or shell characters.
406pub 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/// A resolved value and the level it came from.
411#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
412pub struct Sourced<T> {
413    pub value: T,
414    pub from: Level,
415}
416
417/// What a chat (or a workspace's new chats) actually uses.
418#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
419pub struct Effective {
420    pub base_url: Sourced<String>,
421    pub model: Sourced<String>,
422    /// The level whose API key is used, if any (keys never leave the engine).
423    #[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    /// JPEG quality for images sent to the model; 0: as they are.
431    pub image_quality: Sourced<u8>,
432    /// Most tool calls in one turn; 0: no limit.
433    pub max_tool_calls: Sourced<u32>,
434    /// Every level's instructions, least specific first; all of them apply.
435    #[serde(default)]
436    pub instructions: Vec<(Level, String)>,
437    pub env: Sourced<EnvKind>,
438    /// Load the folder's project environment without asking (`Some(true)`: the workspace
439    /// is Nix), or ask as usual (`None`). Follows the workspace even when a chat moves its
440    /// commands to this machine.
441    #[serde(default)]
442    pub load_project: Option<bool>,
443    /// The workspace's own image, if it set one.
444    #[serde(default)]
445    pub image: Option<String>,
446    /// Plugins some level turned on or off, by id, with the level that decided. Plugins not
447    /// listed are on.
448    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
449    pub plugins: BTreeMap<String, Sourced<bool>>,
450}
451
452impl Effective {
453    /// Commands in a container (`Some(true)`), on this machine (`Some(false)`), or as the
454    /// workspace's answers say (`None`, asked once).
455    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    /// Is plugin `id` on (and which level says so; [`Level::Default`]: nobody switched it)?
464    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    /// The instructions as one block for the system prompt (empty if there are none).
469    pub fn instructions_text(&self) -> String {
470        self.instructions.iter().map(|(_, s)| s.as_str()).collect::<Vec<_>>().join("\n\n")
471    }
472}
473
474/// The levels of one chat.
475#[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/// Which levels store an API key.
483#[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/// Testing flags that beat every level for this run.
491#[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
507/// Scheme, host and port of a URL, lowercased ("http://127.0.0.1:8080").
508pub 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
515/// The effective settings of a chat with these levels. `keys` says which levels store an
516/// API key: a key belongs to the server its level points at, so it is used only when the
517/// effective URL has the same scheme, host and port (the most specific such level wins).
518pub 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    // The URL each level points at: its own, else what it inherits.
522    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
573/// Every level's plugin switches, the most specific level winning per plugin.
574fn 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        // Without the chat, the workspace's values show through.
630        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        // Out-of-range stored thresholds are clamped.
633        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        // The workspace's own key goes with its URL; the global key stays on the local server.
685        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        // A chat pointing back at the global server gets the global key again.
690        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        // A chat's own key wins for its own URL.
693        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        // A workspace with a key but no URL of its own: it points at the global server.
696        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        // The chat runs on this machine instead.
720        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        // On this machine in a Nix workspace: the dev shell still loads.
723        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        // A stored chat value that isn't a placement is ignored.
728        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        // A bad stored image is ignored rather than handed to docker.
732        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        // Settings that don't exist at a level.
764        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}