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    /// Never asks: every call runs, also those a person is normally asked to confirm
130    /// (questions the model asks you still come to you).
131    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/// Where a workspace's commands (`run_command`, `run_python`) run and what they get.
149#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
150#[serde(rename_all = "snake_case")]
151pub enum EnvKind {
152    /// Today's behaviour: on this machine; byob asks once before loading the folder's
153    /// project environment or using its devcontainer.json.
154    #[default]
155    Auto,
156    /// Always on this machine (byob's sandbox), never in a container. A project
157    /// environment is still asked about once.
158    Host,
159    /// On this machine with the folder's Nix dev shell (flake.nix / shell.nix, or another
160    /// project environment) loaded without asking.
161    Nix,
162    /// In the workspace's Docker/Podman container (devcontainer.json or an image).
163    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    /// May a chat choose this (a chat only picks where its commands run)?
179    pub fn per_chat(self) -> bool {
180        matches!(self, Self::Host | Self::Container)
181    }
182}
183
184/// Deserialize a field, falling back to `None` when the stored value has the wrong shape:
185/// one bad value shouldn't reset a whole layer.
186fn 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/// One level's own settings; `None` means "inherit".
192#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
193pub struct Layer {
194    /// A saved model ([`crate::profile::Profile`], by id). When it exists it beats this
195    /// level's `base_url`/`model`, which are kept as a copy of it for older builds; when it
196    /// doesn't (deleted), the level inherits the endpoint.
197    #[serde(default, deserialize_with = "lenient", skip_serializing_if = "Option::is_none")]
198    pub profile: Option<String>,
199    /// The saved model this level's subagents run on unless the `delegate` call or the
200    /// agent's `model:` names one (by id). A workspace or chat sets it here; the global one is
201    /// the `subagents` role ([`crate::profile::ROLE_SUBAGENTS`]), which the engine shows in
202    /// the global layer it builds. One that doesn't exist (deleted) is skipped.
203    #[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    /// Compact when a request passes this percentage of the context window (10..=95).
216    #[serde(default, deserialize_with = "lenient", skip_serializing_if = "Option::is_none")]
217    pub compact_percent: Option<u8>,
218    /// Offer the `delegate` tool.
219    #[serde(default, deserialize_with = "lenient", skip_serializing_if = "Option::is_none")]
220    pub subagents: Option<bool>,
221    /// Images sent to the model are re-encoded as JPEG at this quality (1..=100) when that
222    /// makes them smaller; 0 sends them as they are (downscaled only).
223    #[serde(default, deserialize_with = "lenient", skip_serializing_if = "Option::is_none")]
224    pub image_quality: Option<u8>,
225    /// Most tool calls in one turn; 0: no limit.
226    #[serde(default, deserialize_with = "lenient", skip_serializing_if = "Option::is_none")]
227    pub max_tool_calls: Option<u32>,
228    /// Appended to the system prompt after the less specific levels' instructions.
229    #[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    /// The container image (workspace only). `None`: the folder's devcontainer.json if it
234    /// has one, else the global default image.
235    #[serde(default, deserialize_with = "lenient", skip_serializing_if = "Option::is_none")]
236    pub image: Option<String>,
237    /// Plugins turned on (`true`) or off (`false`) at this level, by plugin id; plugins not
238    /// named inherit (on by default). Every level has it; it changes through its own message
239    /// (`SetPluginEnabled`), not the settings form.
240    #[serde(default, deserialize_with = "lenient", skip_serializing_if = "Option::is_none")]
241    pub plugins: Option<BTreeMap<String, bool>>,
242}
243
244/// Most plugins one level may turn on or off.
245pub const MAX_PLUGIN_SWITCHES: usize = 500;
246
247/// A plugin id as manifests have it: `[a-z0-9][a-z0-9-]{0,47}`.
248pub 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/// The groups of settings, for [`Field::levels`] and the UI's reset buttons.
255#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
256pub enum Field {
257    /// `profile`, `base_url` and `model` together.
258    Endpoint,
259    ToolMode,
260    Approvals,
261    /// `auto_compact` and `compact_percent`.
262    Compaction,
263    Subagents,
264    /// `subagent_profile`.
265    SubagentModel,
266    /// `image_quality`.
267    ModelImages,
268    /// `max_tool_calls`.
269    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    /// The levels this setting exists at (besides [`Level::Default`]).
291    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    /// Is `field` set at this level?
331    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    /// Forget `field` here (inherit it again).
348    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    /// Check an untrusted layer for `level`: trims text, turns blank text into `None`,
376    /// clamps the threshold, and refuses settings that don't exist at that level, values
377    /// that are too long, and images that aren't plain references.
378    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
436/// An image reference: no options, spaces or shell characters.
437pub 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/// A resolved value and the level it came from.
442#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
443pub struct Sourced<T> {
444    pub value: T,
445    pub from: Level,
446}
447
448/// What a chat (or a workspace's new chats) actually uses.
449#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
450pub struct Effective {
451    pub base_url: Sourced<String>,
452    pub model: Sourced<String>,
453    /// The level whose API key is used, if any (keys never leave the engine).
454    #[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    /// The saved model (profile id) subagents use by default, and the level that picked it;
462    /// `None`: the chat's own model. [`resolve`] takes the most specific level's;
463    /// [`crate::profile::resolve_with`] skips ones that don't exist.
464    #[serde(default, skip_serializing_if = "Option::is_none")]
465    pub subagent_profile: Option<Sourced<String>>,
466    /// JPEG quality for images sent to the model; 0: as they are.
467    pub image_quality: Sourced<u8>,
468    /// Most tool calls in one turn; 0: no limit.
469    pub max_tool_calls: Sourced<u32>,
470    /// Every level's instructions, least specific first; all of them apply.
471    #[serde(default)]
472    pub instructions: Vec<(Level, String)>,
473    pub env: Sourced<EnvKind>,
474    /// Load the folder's project environment without asking (`Some(true)`: the workspace
475    /// is Nix), or ask as usual (`None`). Follows the workspace even when a chat moves its
476    /// commands to this machine.
477    #[serde(default)]
478    pub load_project: Option<bool>,
479    /// The workspace's own image, if it set one.
480    #[serde(default)]
481    pub image: Option<String>,
482    /// Plugins some level turned on or off, by id, with the level that decided. Plugins not
483    /// listed are on.
484    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
485    pub plugins: BTreeMap<String, Sourced<bool>>,
486}
487
488impl Effective {
489    /// Commands in a container (`Some(true)`), on this machine (`Some(false)`), or as the
490    /// workspace's answers say (`None`, asked once).
491    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    /// Is plugin `id` on (and which level says so; [`Level::Default`]: nobody switched it)?
500    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    /// The instructions as one block for the system prompt (empty if there are none).
505    pub fn instructions_text(&self) -> String {
506        self.instructions.iter().map(|(_, s)| s.as_str()).collect::<Vec<_>>().join("\n\n")
507    }
508}
509
510/// The levels of one chat.
511#[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/// Which levels store an API key.
519#[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/// Testing flags that beat every level for this run.
527#[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
543/// Scheme, host and port of a URL, lowercased ("http://127.0.0.1:8080").
544pub 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
551/// The effective settings of a chat with these levels. `keys` says which levels store an
552/// API key: a key belongs to the server its level points at, so it is used only when the
553/// effective URL has the same scheme, host and port (the most specific such level wins).
554pub 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    // The URL each level points at: its own, else what it inherits.
558    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
611/// Every level's plugin switches, the most specific level winning per plugin.
612fn 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        // Without the chat, the workspace's values show through.
668        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        // Out-of-range stored thresholds are clamped.
671        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        // The workspace's own key goes with its URL; the global key stays on the local server.
723        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        // A chat pointing back at the global server gets the global key again.
728        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        // A chat's own key wins for its own URL.
731        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        // A workspace with a key but no URL of its own: it points at the global server.
734        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        // The chat runs on this machine instead.
758        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        // On this machine in a Nix workspace: the dev shell still loads.
761        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        // A stored chat value that isn't a placement is ignored.
766        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        // A bad stored image is ignored rather than handed to docker.
770        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        // Settings that don't exist at a level.
802        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}