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//! | subagent model (a profile; the global one is the `subagents` role) | ✓ | ✓ | ✓ |
15//! | extra instructions (appended, never replaced) | ✓ | ✓ | ✓ |
16//! | environment (Auto, Host, Nix, Container) | | ✓ | Host / Container only |
17//! | container image | | ✓ | |
18//!
19//! Global-only settings (theme, storage, plugin folders, container runtime and default
20//! image, the workspaces folder, model roles, subagent limits) stay in `settings.json` and
21//! are not layered. The most specific level that sets a value wins, except instructions,
22//! which are joined in order global, workspace, chat. Command-line testing flags
23//! (`--auto-approve`, `--tool-mode`) beat every level ([`Level::Flag`]).
24//!
25//! This module is pure (no I/O) so the engine and the UI resolve the same way.
26
27use std::collections::BTreeMap;
28
29use serde::de::DeserializeOwned;
30use serde::{Deserialize, Deserializer, Serialize};
31use serde_json::Value;
32
33/// Longest base URL a level may set.
34pub const MAX_URL_CHARS: usize = 2048;
35/// Longest model name.
36pub const MAX_MODEL_CHARS: usize = 256;
37/// Longest extra instructions per level.
38pub const MAX_INSTRUCTIONS_CHARS: usize = 8000;
39/// Longest container image reference.
40pub const MAX_IMAGE_CHARS: usize = 255;
41
42/// The built-in endpoint when nothing is configured.
43pub 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;
46/// JPEG quality images sent to the model get by default: a light pass, often much smaller
47/// than a PNG screenshot and hard to tell apart.
48pub const DEFAULT_IMAGE_QUALITY: u8 = 85;
49/// Tool calls one turn may make by default (`max_tool_calls`; 0 is no limit).
50pub const DEFAULT_TOOL_CALLS: u32 = 30;
51/// Largest limit that can be set short of none.
52pub const MAX_TOOL_CALLS: u32 = 100_000;
53
54/// Where a value comes from, least to most specific.
55#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
56#[serde(rename_all = "snake_case")]
57pub enum Level {
58    /// Built into byob.
59    #[default]
60    Default,
61    /// `settings.json` (or `--inference-url` / `--model` for this run).
62    Global,
63    Workspace,
64    Chat,
65    /// A command-line testing flag for this run (`--auto-approve`, `--tool-mode`).
66    Flag,
67}
68
69impl Level {
70    /// For the UI: "default", "global settings", "workspace", "chat", "command line".
71    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/// How turns pass tools to the model.
83#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
84#[serde(rename_all = "snake_case")]
85pub enum ToolMode {
86    /// Follow the endpoint probe; native first when it is inconclusive.
87    #[default]
88    Auto,
89    /// The server's structured `tools` / `tool_calls`.
90    Native,
91    /// Tools described in the system prompt; calls parsed from the reply text.
92    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/// Which tool calls run without asking.
117#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
118#[serde(rename_all = "snake_case")]
119pub enum Approvals {
120    /// Reads run; writes, network and commands ask.
121    #[default]
122    Ask,
123    /// Reads and file edits run; network and commands ask.
124    AllowEdits,
125    /// Everything runs without asking (calls a person must confirm still ask).
126    AllowAll,
127    /// Only reads: writes, network and commands are refused.
128    ReadOnly,
129}
130
131impl Approvals {
132    pub const ALL: [Self; 4] = [Self::Ask, Self::AllowEdits, Self::AllowAll, Self::ReadOnly];
133
134    pub fn label(self) -> &'static str {
135        match self {
136            Self::Ask => "Ask before changes",
137            Self::AllowEdits => "Allow file edits",
138            Self::AllowAll => "Allow everything",
139            Self::ReadOnly => "Read only",
140        }
141    }
142}
143
144/// Where a workspace's commands (`run_command`, `run_python`) run and what they get.
145#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
146#[serde(rename_all = "snake_case")]
147pub enum EnvKind {
148    /// Today's behaviour: on this machine; byob asks once before loading the folder's
149    /// project environment or using its devcontainer.json.
150    #[default]
151    Auto,
152    /// Always on this machine (byob's sandbox), never in a container. A project
153    /// environment is still asked about once.
154    Host,
155    /// On this machine with the folder's Nix dev shell (flake.nix / shell.nix, or another
156    /// project environment) loaded without asking.
157    Nix,
158    /// In the workspace's Docker/Podman container (devcontainer.json or an image).
159    Container,
160}
161
162impl EnvKind {
163    pub const ALL: [Self; 4] = [Self::Auto, Self::Host, Self::Nix, Self::Container];
164
165    pub fn label(self) -> &'static str {
166        match self {
167            Self::Auto => "Auto",
168            Self::Host => "This machine",
169            Self::Nix => "Nix dev shell",
170            Self::Container => "Container",
171        }
172    }
173
174    /// May a chat choose this (a chat only picks where its commands run)?
175    pub fn per_chat(self) -> bool {
176        matches!(self, Self::Host | Self::Container)
177    }
178}
179
180/// Deserialize a field, falling back to `None` when the stored value has the wrong shape:
181/// one bad value shouldn't reset a whole layer.
182fn lenient<'de, D: Deserializer<'de>, T: DeserializeOwned>(d: D) -> Result<Option<T>, D::Error> {
183    let v = Value::deserialize(d)?;
184    Ok(serde_json::from_value(v).ok())
185}
186
187/// One level's own settings; `None` means "inherit".
188#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
189pub struct Layer {
190    /// A saved model ([`crate::profile::Profile`], by id). When it exists it beats this
191    /// level's `base_url`/`model`, which are kept as a copy of it for older builds; when it
192    /// doesn't (deleted), the level inherits the endpoint.
193    #[serde(default, deserialize_with = "lenient", skip_serializing_if = "Option::is_none")]
194    pub profile: Option<String>,
195    /// The saved model this level's subagents run on unless the `delegate` call or the
196    /// agent's `model:` names one (by id). A workspace or chat sets it here; the global one is
197    /// the `subagents` role ([`crate::profile::ROLE_SUBAGENTS`]), which the engine shows in
198    /// the global layer it builds. One that doesn't exist (deleted) is skipped.
199    #[serde(default, deserialize_with = "lenient", skip_serializing_if = "Option::is_none")]
200    pub subagent_profile: Option<String>,
201    #[serde(default, deserialize_with = "lenient", skip_serializing_if = "Option::is_none")]
202    pub base_url: Option<String>,
203    #[serde(default, deserialize_with = "lenient", skip_serializing_if = "Option::is_none")]
204    pub model: Option<String>,
205    #[serde(default, deserialize_with = "lenient", skip_serializing_if = "Option::is_none")]
206    pub tool_mode: Option<ToolMode>,
207    #[serde(default, deserialize_with = "lenient", skip_serializing_if = "Option::is_none")]
208    pub approvals: Option<Approvals>,
209    #[serde(default, deserialize_with = "lenient", skip_serializing_if = "Option::is_none")]
210    pub auto_compact: Option<bool>,
211    /// Compact when a request passes this percentage of the context window (10..=95).
212    #[serde(default, deserialize_with = "lenient", skip_serializing_if = "Option::is_none")]
213    pub compact_percent: Option<u8>,
214    /// Offer the `delegate` tool.
215    #[serde(default, deserialize_with = "lenient", skip_serializing_if = "Option::is_none")]
216    pub subagents: Option<bool>,
217    /// Images sent to the model are re-encoded as JPEG at this quality (1..=100) when that
218    /// makes them smaller; 0 sends them as they are (downscaled only).
219    #[serde(default, deserialize_with = "lenient", skip_serializing_if = "Option::is_none")]
220    pub image_quality: Option<u8>,
221    /// Most tool calls in one turn; 0: no limit.
222    #[serde(default, deserialize_with = "lenient", skip_serializing_if = "Option::is_none")]
223    pub max_tool_calls: Option<u32>,
224    /// Appended to the system prompt after the less specific levels' instructions.
225    #[serde(default, deserialize_with = "lenient", skip_serializing_if = "Option::is_none")]
226    pub instructions: Option<String>,
227    #[serde(default, deserialize_with = "lenient", skip_serializing_if = "Option::is_none")]
228    pub env: Option<EnvKind>,
229    /// The container image (workspace only). `None`: the folder's devcontainer.json if it
230    /// has one, else the global default image.
231    #[serde(default, deserialize_with = "lenient", skip_serializing_if = "Option::is_none")]
232    pub image: Option<String>,
233    /// Plugins turned on (`true`) or off (`false`) at this level, by plugin id; plugins not
234    /// named inherit (on by default). Every level has it; it changes through its own message
235    /// (`SetPluginEnabled`), not the settings form.
236    #[serde(default, deserialize_with = "lenient", skip_serializing_if = "Option::is_none")]
237    pub plugins: Option<BTreeMap<String, bool>>,
238}
239
240/// Most plugins one level may turn on or off.
241pub const MAX_PLUGIN_SWITCHES: usize = 500;
242
243/// A plugin id as manifests have it: `[a-z0-9][a-z0-9-]{0,47}`.
244pub fn plugin_id_ok(id: &str) -> bool {
245    let b = id.as_bytes();
246    let alnum = |c: u8| c.is_ascii_lowercase() || c.is_ascii_digit();
247    !b.is_empty() && b.len() <= 48 && alnum(b[0]) && b.iter().all(|&c| alnum(c) || c == b'-')
248}
249
250/// The groups of settings, for [`Field::levels`] and the UI's reset buttons.
251#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
252pub enum Field {
253    /// `profile`, `base_url` and `model` together.
254    Endpoint,
255    ToolMode,
256    Approvals,
257    /// `auto_compact` and `compact_percent`.
258    Compaction,
259    Subagents,
260    /// `subagent_profile`.
261    SubagentModel,
262    /// `image_quality`.
263    ModelImages,
264    /// `max_tool_calls`.
265    ToolCalls,
266    Instructions,
267    Env,
268    Image,
269}
270
271impl Field {
272    pub const ALL: [Self; 11] = [
273        Self::Endpoint,
274        Self::ToolMode,
275        Self::Approvals,
276        Self::Compaction,
277        Self::Subagents,
278        Self::SubagentModel,
279        Self::ToolCalls,
280        Self::ModelImages,
281        Self::Instructions,
282        Self::Env,
283        Self::Image,
284    ];
285
286    /// The levels this setting exists at (besides [`Level::Default`]).
287    pub fn levels(self) -> &'static [Level] {
288        const ALL: &[Level] = &[Level::Global, Level::Workspace, Level::Chat];
289        match self {
290            Self::Endpoint
291            | Self::ToolMode
292            | Self::Approvals
293            | Self::Compaction
294            | Self::Subagents
295            | Self::SubagentModel
296            | Self::ToolCalls
297            | Self::ModelImages
298            | Self::Instructions => ALL,
299            Self::Env => &[Level::Workspace, Level::Chat],
300            Self::Image => &[Level::Workspace],
301        }
302    }
303
304    pub fn at(self, level: Level) -> bool {
305        self.levels().contains(&level)
306    }
307
308    pub fn label(self) -> &'static str {
309        match self {
310            Self::Endpoint => "Model",
311            Self::ToolMode => "Tool calling",
312            Self::Approvals => "Approvals",
313            Self::Compaction => "Compaction",
314            Self::Subagents => "Subagents",
315            Self::SubagentModel => "Subagent model",
316            Self::ModelImages => "Images to the model",
317            Self::ToolCalls => "Tool calls per turn",
318            Self::Instructions => "Instructions",
319            Self::Env => "Environment",
320            Self::Image => "Container image",
321        }
322    }
323}
324
325impl Layer {
326    /// Is `field` set at this level?
327    pub fn has(&self, field: Field) -> bool {
328        match field {
329            Field::Endpoint => self.base_url.is_some() || self.model.is_some() || self.profile.is_some(),
330            Field::ToolMode => self.tool_mode.is_some(),
331            Field::Approvals => self.approvals.is_some(),
332            Field::Compaction => self.auto_compact.is_some() || self.compact_percent.is_some(),
333            Field::Subagents => self.subagents.is_some(),
334            Field::SubagentModel => self.subagent_profile.is_some(),
335            Field::ModelImages => self.image_quality.is_some(),
336            Field::ToolCalls => self.max_tool_calls.is_some(),
337            Field::Instructions => self.instructions.is_some(),
338            Field::Env => self.env.is_some(),
339            Field::Image => self.image.is_some(),
340        }
341    }
342
343    /// Forget `field` here (inherit it again).
344    pub fn reset(&mut self, field: Field) {
345        match field {
346            Field::Endpoint => {
347                self.profile = None;
348                self.base_url = None;
349                self.model = None;
350            }
351            Field::ToolMode => self.tool_mode = None,
352            Field::Approvals => self.approvals = None,
353            Field::Compaction => {
354                self.auto_compact = None;
355                self.compact_percent = None;
356            }
357            Field::Subagents => self.subagents = None,
358            Field::SubagentModel => self.subagent_profile = None,
359            Field::ModelImages => self.image_quality = None,
360            Field::ToolCalls => self.max_tool_calls = None,
361            Field::Instructions => self.instructions = None,
362            Field::Env => self.env = None,
363            Field::Image => self.image = None,
364        }
365    }
366
367    pub fn is_empty(&self) -> bool {
368        *self == Self::default()
369    }
370
371    /// Check an untrusted layer for `level`: trims text, turns blank text into `None`,
372    /// clamps the threshold, and refuses settings that don't exist at that level, values
373    /// that are too long, and images that aren't plain references.
374    pub fn validated(mut self, level: Level) -> Result<Self, String> {
375        let clean = |v: Option<String>| v.map(|s| s.trim().to_owned()).filter(|s| !s.is_empty());
376        self.base_url = clean(self.base_url);
377        self.model = clean(self.model);
378        self.image = clean(self.image);
379        self.profile = clean(self.profile);
380        self.subagent_profile = clean(self.subagent_profile);
381        for p in [&self.profile, &self.subagent_profile].into_iter().flatten() {
382            if !crate::profile::id_ok(p) {
383                return Err(format!("{:?} isn't a model profile id", p.chars().take(80).collect::<String>()));
384            }
385        }
386        self.instructions = self.instructions.map(|s| s.trim().to_owned()).filter(|s| !s.is_empty());
387        if self.base_url.as_ref().is_some_and(|u| u.chars().count() > MAX_URL_CHARS) {
388            return Err("the URL is too long".into());
389        }
390        if let Some(u) = &self.base_url
391            && !(u.starts_with("http://") || u.starts_with("https://"))
392        {
393            return Err(format!("{u:?} isn't an http:// or https:// URL"));
394        }
395        if self.model.as_ref().is_some_and(|m| m.chars().count() > MAX_MODEL_CHARS) {
396            return Err("the model name is too long".into());
397        }
398        if self.instructions.as_ref().is_some_and(|i| i.chars().count() > MAX_INSTRUCTIONS_CHARS) {
399            return Err(format!("instructions are limited to {MAX_INSTRUCTIONS_CHARS} characters"));
400        }
401        if let Some(i) = &self.image
402            && !valid_image(i)
403        {
404            return Err(format!("{i:?} isn't a container image reference (like python:3-slim)"));
405        }
406        self.compact_percent = self.compact_percent.map(|p| p.clamp(10, 95));
407        self.image_quality = self.image_quality.map(|q| q.min(100));
408        self.max_tool_calls = self.max_tool_calls.map(|n| n.min(MAX_TOOL_CALLS));
409        if let Some(p) = &self.plugins {
410            if p.len() > MAX_PLUGIN_SWITCHES {
411                return Err(format!("at most {MAX_PLUGIN_SWITCHES} plugins can be switched per level"));
412            }
413            if let Some(bad) = p.keys().find(|id| !plugin_id_ok(id)) {
414                return Err(format!("{bad:?} isn't a plugin id"));
415            }
416        }
417        self.plugins = self.plugins.filter(|p| !p.is_empty());
418        for field in Field::ALL {
419            if self.has(field) && !field.at(level) {
420                return Err(format!("{} can't be set per {}", field.label().to_lowercase(), level.label()));
421            }
422        }
423        if level == Level::Chat
424            && let Some(e) = self.env.filter(|e| !e.per_chat())
425        {
426            return Err(format!("a chat can only run its commands on this machine or in the container, not {:?}", e.label()));
427        }
428        Ok(self)
429    }
430}
431
432/// An image reference: no options, spaces or shell characters.
433pub fn valid_image(i: &str) -> bool {
434    !i.is_empty() && i.len() <= MAX_IMAGE_CHARS && !i.starts_with('-') && i.chars().all(|c| c.is_ascii_alphanumeric() || "._-/:@".contains(c))
435}
436
437/// A resolved value and the level it came from.
438#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
439pub struct Sourced<T> {
440    pub value: T,
441    pub from: Level,
442}
443
444/// What a chat (or a workspace's new chats) actually uses.
445#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
446pub struct Effective {
447    pub base_url: Sourced<String>,
448    pub model: Sourced<String>,
449    /// The level whose API key is used, if any (keys never leave the engine).
450    #[serde(default)]
451    pub key_from: Option<Level>,
452    pub tool_mode: Sourced<ToolMode>,
453    pub approvals: Sourced<Approvals>,
454    pub auto_compact: Sourced<bool>,
455    pub compact_percent: Sourced<u8>,
456    pub subagents: Sourced<bool>,
457    /// The saved model (profile id) subagents use by default, and the level that picked it;
458    /// `None`: the chat's own model. [`resolve`] takes the most specific level's;
459    /// [`crate::profile::resolve_with`] skips ones that don't exist.
460    #[serde(default, skip_serializing_if = "Option::is_none")]
461    pub subagent_profile: Option<Sourced<String>>,
462    /// JPEG quality for images sent to the model; 0: as they are.
463    pub image_quality: Sourced<u8>,
464    /// Most tool calls in one turn; 0: no limit.
465    pub max_tool_calls: Sourced<u32>,
466    /// Every level's instructions, least specific first; all of them apply.
467    #[serde(default)]
468    pub instructions: Vec<(Level, String)>,
469    pub env: Sourced<EnvKind>,
470    /// Load the folder's project environment without asking (`Some(true)`: the workspace
471    /// is Nix), or ask as usual (`None`). Follows the workspace even when a chat moves its
472    /// commands to this machine.
473    #[serde(default)]
474    pub load_project: Option<bool>,
475    /// The workspace's own image, if it set one.
476    #[serde(default)]
477    pub image: Option<String>,
478    /// Plugins some level turned on or off, by id, with the level that decided. Plugins not
479    /// listed are on.
480    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
481    pub plugins: BTreeMap<String, Sourced<bool>>,
482}
483
484impl Effective {
485    /// Commands in a container (`Some(true)`), on this machine (`Some(false)`), or as the
486    /// workspace's answers say (`None`, asked once).
487    pub fn container(&self) -> Option<bool> {
488        match self.env.value {
489            EnvKind::Auto => None,
490            EnvKind::Host | EnvKind::Nix => Some(false),
491            EnvKind::Container => Some(true),
492        }
493    }
494
495    /// Is plugin `id` on (and which level says so; [`Level::Default`]: nobody switched it)?
496    pub fn plugin_on(&self, id: &str) -> Sourced<bool> {
497        self.plugins.get(id).cloned().unwrap_or(Sourced { value: true, from: Level::Default })
498    }
499
500    /// The instructions as one block for the system prompt (empty if there are none).
501    pub fn instructions_text(&self) -> String {
502        self.instructions.iter().map(|(_, s)| s.as_str()).collect::<Vec<_>>().join("\n\n")
503    }
504}
505
506/// The levels of one chat.
507#[derive(Debug, Clone, Copy, Default)]
508pub struct Levels<'a> {
509    pub global: Option<&'a Layer>,
510    pub workspace: Option<&'a Layer>,
511    pub chat: Option<&'a Layer>,
512}
513
514/// Which levels store an API key.
515#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
516pub struct Keys {
517    pub global: bool,
518    pub workspace: bool,
519    pub chat: bool,
520}
521
522/// Testing flags that beat every level for this run.
523#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
524pub struct Forced {
525    pub approvals: Option<Approvals>,
526    pub tool_mode: Option<ToolMode>,
527}
528
529fn pick<T: Clone>(levels: &Levels<'_>, default: T, get: impl Fn(&Layer) -> Option<T>) -> Sourced<T> {
530    let ordered = [(Level::Chat, levels.chat), (Level::Workspace, levels.workspace), (Level::Global, levels.global)];
531    for (level, layer) in ordered {
532        if let Some(v) = layer.and_then(&get) {
533            return Sourced { value: v, from: level };
534        }
535    }
536    Sourced { value: default, from: Level::Default }
537}
538
539/// Scheme, host and port of a URL, lowercased ("http://127.0.0.1:8080").
540pub fn origin(url: &str) -> String {
541    let u = url.trim().to_ascii_lowercase();
542    let (scheme, rest) = u.split_once("://").unwrap_or(("", u.as_str()));
543    let host = rest.split(['/', '?', '#']).next().unwrap_or_default();
544    format!("{scheme}://{host}")
545}
546
547/// The effective settings of a chat with these levels. `keys` says which levels store an
548/// API key: a key belongs to the server its level points at, so it is used only when the
549/// effective URL has the same scheme, host and port (the most specific such level wins).
550pub fn resolve(levels: Levels<'_>, keys: Keys, forced: Forced) -> Effective {
551    let base_url = pick(&levels, DEFAULT_BASE_URL.to_owned(), |l| l.base_url.clone());
552    let model = pick(&levels, DEFAULT_MODEL.to_owned(), |l| l.model.clone());
553    // The URL each level points at: its own, else what it inherits.
554    let upto = |stop: Level| {
555        let partial = Levels {
556            global: levels.global,
557            workspace: levels.workspace.filter(|_| stop >= Level::Workspace),
558            chat: levels.chat.filter(|_| stop >= Level::Chat),
559        };
560        pick(&partial, DEFAULT_BASE_URL.to_owned(), |l| l.base_url.clone()).value
561    };
562    let want = origin(&base_url.value);
563    let key_from = [(Level::Chat, keys.chat), (Level::Workspace, keys.workspace), (Level::Global, keys.global)]
564        .into_iter()
565        .find(|(level, has)| *has && origin(&upto(*level)) == want)
566        .map(|(level, _)| level);
567    let mut tool_mode = pick(&levels, ToolMode::Auto, |l| l.tool_mode);
568    if let Some(m) = forced.tool_mode {
569        tool_mode = Sourced { value: m, from: Level::Flag };
570    }
571    let mut approvals = pick(&levels, Approvals::Ask, |l| l.approvals);
572    if let Some(a) = forced.approvals {
573        approvals = Sourced { value: a, from: Level::Flag };
574    }
575    let instructions = [(Level::Global, levels.global), (Level::Workspace, levels.workspace), (Level::Chat, levels.chat)]
576        .into_iter()
577        .filter_map(|(level, layer)| layer.and_then(|l| l.instructions.clone()).filter(|s| !s.trim().is_empty()).map(|s| (level, s)))
578        .collect();
579    let subagent_profile = pick(&levels, None, |l| l.subagent_profile.clone().map(Some));
580    let ws_env = levels.workspace.and_then(|l| l.env).unwrap_or_default();
581    let chat_env = levels.chat.and_then(|l| l.env).filter(|e| e.per_chat());
582    let env = match (chat_env, levels.workspace.and_then(|l| l.env)) {
583        (Some(e), _) => Sourced { value: e, from: Level::Chat },
584        (None, Some(e)) => Sourced { value: e, from: Level::Workspace },
585        (None, None) => Sourced { value: EnvKind::Auto, from: Level::Default },
586    };
587    Effective {
588        base_url,
589        model,
590        key_from,
591        tool_mode,
592        approvals,
593        auto_compact: pick(&levels, true, |l| l.auto_compact),
594        compact_percent: pick(&levels, DEFAULT_COMPACT_PERCENT, |l| l.compact_percent.map(|p| p.clamp(10, 95))),
595        subagents: pick(&levels, true, |l| l.subagents),
596        subagent_profile: subagent_profile.value.map(|value| Sourced { value, from: subagent_profile.from }),
597        image_quality: pick(&levels, DEFAULT_IMAGE_QUALITY, |l| l.image_quality.map(|q| q.min(100))),
598        max_tool_calls: pick(&levels, DEFAULT_TOOL_CALLS, |l| l.max_tool_calls.map(|n| n.min(MAX_TOOL_CALLS))),
599        instructions,
600        env,
601        load_project: (ws_env == EnvKind::Nix).then_some(true),
602        image: levels.workspace.and_then(|l| l.image.clone()).filter(|i| valid_image(i)),
603        plugins: plugin_switches(&levels),
604    }
605}
606
607/// Every level's plugin switches, the most specific level winning per plugin.
608fn plugin_switches(levels: &Levels<'_>) -> BTreeMap<String, Sourced<bool>> {
609    let mut out = BTreeMap::new();
610    for (level, layer) in [(Level::Global, levels.global), (Level::Workspace, levels.workspace), (Level::Chat, levels.chat)] {
611        for (id, on) in layer.and_then(|l| l.plugins.as_ref()).into_iter().flatten() {
612            out.insert(id.clone(), Sourced { value: *on, from: level });
613        }
614    }
615    out
616}
617
618#[cfg(test)]
619mod tests {
620    use super::*;
621
622    fn layer(f: impl FnOnce(&mut Layer)) -> Layer {
623        let mut l = Layer::default();
624        f(&mut l);
625        l
626    }
627
628    #[test]
629    fn nothing_set_gives_the_built_in_defaults() {
630        let e = resolve(Levels::default(), Keys::default(), Forced::default());
631        assert_eq!(e.base_url, Sourced { value: DEFAULT_BASE_URL.to_owned(), from: Level::Default });
632        assert_eq!(e.model.value, DEFAULT_MODEL);
633        assert_eq!((e.tool_mode.value, e.approvals.value, e.env.value), (ToolMode::Auto, Approvals::Ask, EnvKind::Auto));
634        assert_eq!((e.auto_compact.value, e.compact_percent.value, e.subagents.value), (true, 80, true));
635        assert!(e.instructions.is_empty() && e.key_from.is_none() && e.load_project.is_none() && e.container().is_none());
636    }
637
638    #[test]
639    fn the_most_specific_level_wins_per_field() {
640        let g = layer(|l| {
641            l.base_url = Some("http://g/v1".into());
642            l.model = Some("gm".into());
643            l.approvals = Some(Approvals::AllowEdits);
644            l.compact_percent = Some(70);
645        });
646        let w = layer(|l| {
647            l.model = Some("wm".into());
648            l.tool_mode = Some(ToolMode::Prompt);
649            l.compact_percent = Some(60);
650        });
651        let c = layer(|l| {
652            l.compact_percent = Some(50);
653            l.subagents = Some(false);
654        });
655        let e = resolve(Levels { global: Some(&g), workspace: Some(&w), chat: Some(&c) }, Keys::default(), Forced::default());
656        assert_eq!(e.base_url, Sourced { value: "http://g/v1".into(), from: Level::Global });
657        assert_eq!(e.model, Sourced { value: "wm".into(), from: Level::Workspace });
658        assert_eq!(e.tool_mode, Sourced { value: ToolMode::Prompt, from: Level::Workspace });
659        assert_eq!(e.approvals, Sourced { value: Approvals::AllowEdits, from: Level::Global });
660        assert_eq!(e.compact_percent, Sourced { value: 50, from: Level::Chat });
661        assert_eq!(e.subagents, Sourced { value: false, from: Level::Chat });
662        assert_eq!(e.auto_compact.from, Level::Default);
663        // Without the chat, the workspace's values show through.
664        let e = resolve(Levels { global: Some(&g), workspace: Some(&w), chat: None }, Keys::default(), Forced::default());
665        assert_eq!(e.compact_percent, Sourced { value: 60, from: Level::Workspace });
666        // Out-of-range stored thresholds are clamped.
667        assert_eq!(
668            resolve(Levels::default(), Keys::default(), Forced::default()).image_quality,
669            Sourced { value: DEFAULT_IMAGE_QUALITY, from: Level::Default }
670        );
671        let as_is = layer(|l| l.image_quality = Some(0));
672        let e = resolve(Levels { workspace: Some(&as_is), ..Default::default() }, Keys::default(), Forced::default());
673        assert_eq!(e.image_quality, Sourced { value: 0, from: Level::Workspace });
674        let wild_q = layer(|l| l.image_quality = Some(250));
675        assert_eq!(resolve(Levels { chat: Some(&wild_q), ..Default::default() }, Keys::default(), Forced::default()).image_quality.value, 100);
676        assert_eq!(wild_q.clone().validated(Level::Chat).unwrap().image_quality, Some(100));
677        let calls = |n| layer(|l| l.max_tool_calls = Some(n));
678        assert_eq!(resolve(Levels::default(), Keys::default(), Forced::default()).max_tool_calls.value, DEFAULT_TOOL_CALLS);
679        let (none, many) = (calls(0), calls(u32::MAX));
680        let e = resolve(Levels { global: Some(&many), chat: Some(&none), ..Default::default() }, Keys::default(), Forced::default());
681        assert_eq!(e.max_tool_calls, Sourced { value: 0, from: Level::Chat });
682        assert_eq!(resolve(Levels { global: Some(&many), ..Default::default() }, Keys::default(), Forced::default()).max_tool_calls.value, MAX_TOOL_CALLS);
683        let wild = layer(|l| l.compact_percent = Some(200));
684        assert_eq!(resolve(Levels { chat: Some(&wild), ..Default::default() }, Keys::default(), Forced::default()).compact_percent.value, 95);
685    }
686
687    #[test]
688    fn plugin_switches_resolve_per_plugin() {
689        let g = layer(|l| l.plugins = Some([("web".to_owned(), false), ("pdf".to_owned(), false)].into()));
690        let w = layer(|l| l.plugins = Some([("web".to_owned(), true)].into()));
691        let c = layer(|l| l.plugins = Some([("pdf".to_owned(), true), ("git".to_owned(), false)].into()));
692        let e = resolve(Levels { global: Some(&g), workspace: Some(&w), chat: Some(&c) }, Keys::default(), Forced::default());
693        assert_eq!(e.plugin_on("web"), Sourced { value: true, from: Level::Workspace });
694        assert_eq!(e.plugin_on("pdf"), Sourced { value: true, from: Level::Chat });
695        assert_eq!(e.plugin_on("git"), Sourced { value: false, from: Level::Chat });
696        assert_eq!(e.plugin_on("other"), Sourced { value: true, from: Level::Default });
697        assert!(layer(|l| l.plugins = Some([("Bad Id".to_owned(), true)].into())).validated(Level::Chat).is_err());
698        assert_eq!(layer(|l| l.plugins = Some(BTreeMap::new())).validated(Level::Chat).unwrap().plugins, None);
699    }
700
701    #[test]
702    fn instructions_are_appended_in_order() {
703        let g = layer(|l| l.instructions = Some("Be brief.".into()));
704        let w = layer(|l| l.instructions = Some("This repo uses Rust.".into()));
705        let c = layer(|l| l.instructions = Some("  ".into()));
706        let e = resolve(Levels { global: Some(&g), workspace: Some(&w), chat: Some(&c) }, Keys::default(), Forced::default());
707        assert_eq!(e.instructions, vec![(Level::Global, "Be brief.".to_owned()), (Level::Workspace, "This repo uses Rust.".to_owned())]);
708        assert_eq!(e.instructions_text(), "Be brief.\n\nThis repo uses Rust.");
709    }
710
711    #[test]
712    fn keys_follow_only_their_own_server() {
713        let g = layer(|l| l.base_url = Some("http://local:8080/v1".into()));
714        let w = layer(|l| l.base_url = Some("https://api.example.com/v1".into()));
715        let c_same = layer(|l| l.model = Some("other".into()));
716        let c_back = layer(|l| l.base_url = Some("http://local:8080/v1/".into()));
717        let all = Keys { global: true, workspace: true, chat: false };
718        // The workspace's own key goes with its URL; the global key stays on the local server.
719        let e = resolve(Levels { global: Some(&g), workspace: Some(&w), chat: Some(&c_same) }, all, Forced::default());
720        assert_eq!(e.key_from, Some(Level::Workspace));
721        let e = resolve(Levels { global: Some(&g), workspace: Some(&w), chat: Some(&c_same) }, Keys { global: true, ..Keys::default() }, Forced::default());
722        assert_eq!(e.key_from, None, "the global key never follows the URL to another server");
723        // A chat pointing back at the global server gets the global key again.
724        let e = resolve(Levels { global: Some(&g), workspace: Some(&w), chat: Some(&c_back) }, all, Forced::default());
725        assert_eq!(e.key_from, Some(Level::Global));
726        // A chat's own key wins for its own URL.
727        let e = resolve(Levels { global: Some(&g), workspace: Some(&w), chat: Some(&c_back) }, Keys { chat: true, ..all }, Forced::default());
728        assert_eq!(e.key_from, Some(Level::Chat));
729        // A workspace with a key but no URL of its own: it points at the global server.
730        let w_key_only = layer(|l| l.model = Some("m".into()));
731        let e = resolve(Levels { global: Some(&g), workspace: Some(&w_key_only), chat: None }, Keys { workspace: true, ..Keys::default() }, Forced::default());
732        assert_eq!(e.key_from, Some(Level::Workspace));
733        assert_eq!(origin("HTTP://Example.com:8080/v1/"), "http://example.com:8080");
734        assert_ne!(origin("http://127.0.0.1:8080/v1"), origin("http://127.0.0.1:11434/v1"));
735    }
736
737    #[test]
738    fn environments_come_from_the_workspace_and_a_chat_may_move_its_commands() {
739        let none = resolve(Levels::default(), Keys::default(), Forced::default());
740        assert_eq!((none.container(), none.load_project), (None, None));
741        let nix = layer(|l| l.env = Some(EnvKind::Nix));
742        let container = layer(|l| {
743            l.env = Some(EnvKind::Container);
744            l.image = Some("debian:stable-slim".into());
745        });
746        let host = layer(|l| l.env = Some(EnvKind::Host));
747        let to_container = layer(|l| l.env = Some(EnvKind::Container));
748        let e = resolve(Levels { workspace: Some(&container), ..Default::default() }, Keys::default(), Forced::default());
749        assert_eq!(
750            (e.env.value, e.env.from, e.container(), e.image.as_deref()),
751            (EnvKind::Container, Level::Workspace, Some(true), Some("debian:stable-slim"))
752        );
753        // The chat runs on this machine instead.
754        let e = resolve(Levels { workspace: Some(&container), chat: Some(&host), ..Default::default() }, Keys::default(), Forced::default());
755        assert_eq!((e.env.value, e.env.from, e.container()), (EnvKind::Host, Level::Chat, Some(false)));
756        // On this machine in a Nix workspace: the dev shell still loads.
757        let e = resolve(Levels { workspace: Some(&nix), chat: Some(&host), ..Default::default() }, Keys::default(), Forced::default());
758        assert_eq!((e.container(), e.load_project), (Some(false), Some(true)));
759        let e = resolve(Levels { workspace: Some(&nix), chat: Some(&to_container), ..Default::default() }, Keys::default(), Forced::default());
760        assert_eq!(e.container(), Some(true));
761        // A stored chat value that isn't a placement is ignored.
762        let bad_chat = layer(|l| l.env = Some(EnvKind::Nix));
763        let e = resolve(Levels { workspace: Some(&container), chat: Some(&bad_chat), ..Default::default() }, Keys::default(), Forced::default());
764        assert_eq!(e.env.from, Level::Workspace);
765        // A bad stored image is ignored rather than handed to docker.
766        let evil = layer(|l| l.image = Some("--privileged".into()));
767        assert_eq!(resolve(Levels { workspace: Some(&evil), ..Default::default() }, Keys::default(), Forced::default()).image, None);
768    }
769
770    #[test]
771    fn flags_beat_every_level() {
772        let c = layer(|l| {
773            l.approvals = Some(Approvals::ReadOnly);
774            l.tool_mode = Some(ToolMode::Native);
775        });
776        let forced = Forced { approvals: Some(Approvals::AllowAll), tool_mode: Some(ToolMode::Prompt) };
777        let e = resolve(Levels { chat: Some(&c), ..Default::default() }, Keys::default(), forced);
778        assert_eq!(e.approvals, Sourced { value: Approvals::AllowAll, from: Level::Flag });
779        assert_eq!(e.tool_mode, Sourced { value: ToolMode::Prompt, from: Level::Flag });
780    }
781
782    #[test]
783    fn layers_from_clients_are_checked_per_level() {
784        let ok = layer(|l| {
785            l.base_url = Some("  http://h/v1 ".into());
786            l.model = Some(" ".into());
787            l.compact_percent = Some(3);
788            l.instructions = Some("\n".into());
789        })
790        .validated(Level::Chat)
791        .unwrap();
792        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));
793        assert!(layer(|l| l.base_url = Some("file:///etc/passwd".into())).validated(Level::Chat).is_err());
794        assert!(layer(|l| l.base_url = Some(format!("http://{}", "a".repeat(MAX_URL_CHARS)))).validated(Level::Workspace).is_err());
795        assert!(layer(|l| l.model = Some("m".repeat(MAX_MODEL_CHARS + 1))).validated(Level::Chat).is_err());
796        assert!(layer(|l| l.instructions = Some("x".repeat(MAX_INSTRUCTIONS_CHARS + 1))).validated(Level::Global).is_err());
797        // Settings that don't exist at a level.
798        assert!(layer(|l| l.env = Some(EnvKind::Container)).validated(Level::Global).is_err());
799        assert!(layer(|l| l.image = Some("alpine".into())).validated(Level::Chat).is_err());
800        assert!(layer(|l| l.env = Some(EnvKind::Nix)).validated(Level::Chat).is_err());
801        assert!(layer(|l| l.env = Some(EnvKind::Host)).validated(Level::Chat).is_ok());
802        assert!(layer(|l| l.image = Some("alpine; rm -rf /".into())).validated(Level::Workspace).is_err());
803        assert!(layer(|l| l.image = Some("ghcr.io/me/img:1.2@sha256:abc".into())).validated(Level::Workspace).is_ok());
804    }
805
806    #[test]
807    fn layers_round_trip_and_bad_values_are_dropped_alone() {
808        let l = layer(|l| {
809            l.approvals = Some(Approvals::AllowEdits);
810            l.env = Some(EnvKind::Container);
811        });
812        let json = serde_json::to_string(&l).unwrap();
813        assert_eq!(json, r#"{"approvals":"allow_edits","env":"container"}"#);
814        assert_eq!(serde_json::from_str::<Layer>(&json).unwrap(), l);
815        let damaged: Layer = serde_json::from_str(r#"{"approvals":"sometimes","model":"m","compact_percent":"lots","future":1}"#).unwrap();
816        assert_eq!(damaged, layer(|l| l.model = Some("m".into())));
817        let mut reset = l.clone();
818        reset.reset(Field::Env);
819        assert!(!reset.has(Field::Env) && reset.has(Field::Approvals));
820        reset.reset(Field::Approvals);
821        assert!(reset.is_empty());
822    }
823}