Skip to main content

agent86_core/
config.rs

1//! Layered configuration, matching the Python `config.py`.
2//!
3//! Resolution order (later overrides earlier):
4//!
5//! ```text
6//! built-in defaults
7//!   -> ~/.agent86/config.toml        (user)
8//!   -> ./.agent86/config.toml        (project)
9//!   -> environment variables         (AGENT86_*)
10//!   -> explicit overrides            (CLI flags)
11//! ```
12//!
13//! Secrets are never stored here: config only names the environment variable
14//! that holds each provider's key (`api_key_env`).
15//!
16//! Only the sections agent86 uses are read; other sections are accepted and
17//! ignored.
18
19use crate::types::ApprovalMode;
20use serde::Deserialize;
21use std::collections::BTreeMap;
22use std::path::{Path, PathBuf};
23use thiserror::Error;
24use toml::{Table, Value};
25
26/// The built-in defaults, seeded first so partial layers deep-merge onto them.
27const DEFAULTS: &str = r#"
28[model]
29default = "anthropic:claude-opus-4-8"
30router = "off"
31
32[model.route]
33cheap = "ollama:llama3.1"
34frontier = "anthropic:claude-opus-4-8"
35
36[limits]
37max_steps = 40
38max_cost_usd = 5.0
39max_wall_clock_s = 900
40max_consecutive_errors = 3
41max_context_tokens = 0
42max_output_tokens = 8192
43context_reserve_tokens = 4096
44compaction = "summarize"
45parallel_tools = true
46tool_timeout_s = 60
47
48[sandbox]
49mode = "subprocess"
50docker_image = "python:3.12-slim"
51docker_memory = "512m"
52docker_cpus = "1"
53docker_network = false
54env_passthrough = []
55
56[mcp]
57enabled = true
58
59[skills]
60enabled = true
61paths = []
62
63[agents]
64enabled = true
65max_depth = 2
66max_steps = 8
67max_parallel = 3
68
69[observability]
70trace = true
71path = "~/.agent86/traces"
72otel = false
73otel_exporter = "otlp"
74redact = "secrets"
75max_field_chars = 2000
76max_trace_bytes = 50000000
77keep_traces = 5
78
79[memory]
80enabled = true
81path = "~/.agent86/memory.db"
82embeddings = "sentence-transformers:all-MiniLM-L6-v2"
83hf_offline = true
84retention_max_episodes = 1000
85retention_max_sessions = 500
86retention_max_age_days = 0.0
87
88[tools]
89web_allow_private = false
90web_max_chars = 8000
91mention_max_bytes = 200000
92
93[ui]
94spinner = true
95history_file = "~/.agent86/history"
96history_size = 1000
97markdown = true
98update_check = true
99thinking = "summary"
100tool_use = "summary"
101agent86ui = "auto"
102agent86ui_remote_media = false
103
104[run]
105output = "final"
106
107[guardrails]
108approval = "ask"
109ingress = "warn"
110egress = "warn"
111scan_observations = true
112
113[providers.anthropic]
114api_key_env = "ANTHROPIC_API_KEY"
115
116[providers.google]
117api_key_env = "GEMINI_API_KEY"
118read_timeout_s = 1200.0
119store = false
120
121[providers.openai]
122api_key_env = "OPENAI_API_KEY"
123base_url = "https://api.openai.com/v1"
124
125[providers.openrouter]
126api_key_env = "OPENROUTER_API_KEY"
127base_url = "https://openrouter.ai/api/v1"
128
129[providers.groq]
130api_key_env = "GROQ_API_KEY"
131base_url = "https://api.groq.com/openai/v1"
132
133[providers.ollama]
134base_url = "http://localhost:11434"
135num_ctx_max = 32768
136
137[providers.llamacpp]
138base_url = "http://localhost:8080"
139
140[providers.vllm]
141base_url = "http://localhost:8000/v1"
142api_key_env = "VLLM_API_KEY"
143
144[providers.lmstudio]
145base_url = "http://localhost:1234/v1"
146api_key_env = "LM_API_TOKEN"
147"#;
148
149#[derive(Debug, Clone, PartialEq, Deserialize)]
150pub struct Config {
151    pub model: ModelConfig,
152    pub limits: LimitsConfig,
153    pub sandbox: SandboxConfig,
154    pub guardrails: GuardrailsConfig,
155    pub tools: ToolsConfig,
156    pub memory: MemoryConfig,
157    pub observability: ObservabilityConfig,
158    pub mcp: McpConfig,
159    pub skills: SkillsConfig,
160    pub agents: AgentsConfig,
161    /// MCP servers in config order, from `[mcp_servers.<name>]` or `[mcp.servers.<name>]`.
162    #[serde(default)]
163    pub mcp_servers: indexmap::IndexMap<String, McpServerConfig>,
164    #[serde(default)]
165    pub providers: indexmap::IndexMap<String, ProviderConfig>,
166    #[serde(default)]
167    pub pricing: PricingConfig,
168    pub ui: UiConfig,
169    pub run: RunConfig,
170    /// Every layer merged, before deserializing; `/config` shows it.
171    #[serde(skip)]
172    pub table: Table,
173    /// The config files that contributed, in the order they were read.
174    #[serde(skip)]
175    pub sources: Vec<PathBuf>,
176    /// Settings in an untrusted project file that were left out, as dotted keys.
177    #[serde(skip)]
178    pub untrusted: Vec<String>,
179}
180
181#[derive(Debug, Clone, PartialEq, Deserialize)]
182pub struct ModelConfig {
183    pub default: String,
184    /// `off` or `triage`. Only reported: triage routing is not ported.
185    pub router: RouterMode,
186    pub route: ModelRoute,
187    /// `[model.context_window]`: tokens of context per `provider:model` ref or bare
188    /// model id, overriding the built-in table.
189    #[serde(default)]
190    pub context_window: BTreeMap<String, u64>,
191}
192
193/// `[model] router`.
194#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
195#[serde(rename_all = "snake_case")]
196pub enum RouterMode {
197    Off,
198    Triage,
199}
200
201impl RouterMode {
202    pub fn as_str(self) -> &'static str {
203        match self {
204            Self::Off => "off",
205            Self::Triage => "triage",
206        }
207    }
208}
209
210/// `[model.route]`: the models triage routing would choose between.
211#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
212pub struct ModelRoute {
213    pub cheap: String,
214    pub frontier: String,
215}
216
217/// Interactive-surface settings (`[ui]`).
218#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
219pub struct UiConfig {
220    /// Use the full-screen interface when the terminal can host it. Python's
221    /// pre-v0.6 spelling, `status_line`, is mapped onto it.
222    #[serde(default = "default_true")]
223    pub tui: bool,
224    pub spinner: bool,
225    /// Where submitted prompts are recorded; `~` and `$VARS` expand at use time.
226    pub history_file: String,
227    /// How many entries `history_file` keeps; `0` disables the cap.
228    pub history_size: i64,
229    /// Render answers as Markdown in the full-screen interface.
230    pub markdown: bool,
231    /// Check GitHub, at most once a day, for a newer release and say so in the
232    /// interactive surfaces (beyond Python; see the `agent86` binary's `update` module).
233    #[serde(default = "default_true")]
234    pub update_check: bool,
235    /// How much of the model's reasoning the interface shows (beyond Python).
236    #[serde(default = "default_summary")]
237    pub thinking: DisplayLevel,
238    /// How much of each tool call the interface shows (beyond Python).
239    #[serde(default = "default_summary")]
240    pub tool_use: DisplayLevel,
241    /// Whether the interface offers the model `render_ui` (agent86UI, beyond
242    /// Python; ADR 0005). `run`, the plain loop, and ACP never read it.
243    #[serde(default)]
244    pub agent86ui: Agent86UiMode,
245    /// Let a surface's media load `https` URLs, not only `data:` URLs and
246    /// workspace files. Needs project trust, since a fetch can track the user.
247    #[serde(default)]
248    pub agent86ui_remote_media: bool,
249}
250
251/// `[ui] agent86ui` (beyond Python): `auto` offers `render_ui` wherever a
252/// renderer is (the interactive interface); `off` never does.
253#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
254#[serde(rename_all = "lowercase")]
255pub enum Agent86UiMode {
256    #[default]
257    Auto,
258    Off,
259}
260
261/// `agent86 run` settings (`[run]`, beyond Python).
262#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
263pub struct RunConfig {
264    /// What `run` prints, and where (`AGENT86_RUN_OUTPUT` and `run --output` override it).
265    #[serde(default = "default_run_output")]
266    pub output: RunOutputMode,
267}
268
269fn default_run_output() -> RunOutputMode {
270    RunOutputMode::Final
271}
272
273/// What `agent86 run` writes to stdout and stderr (beyond Python, which streams
274/// everything to stdout, as `full` does). `run --json` is the same in every mode.
275#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
276#[serde(rename_all = "lowercase")]
277pub enum RunOutputMode {
278    /// The answer on stdout; the `[tool] ...` lines, the text of steps that called
279    /// tools, and the harness's notices on stderr, so a pipe gets only the answer.
280    Final,
281    /// Everything on stdout as it streams, as Python's `run` does.
282    Full,
283    /// The answer on stdout and nothing else but the summary line and errors.
284    Quiet,
285}
286
287impl RunOutputMode {
288    pub const ALL: [Self; 3] = [Self::Final, Self::Full, Self::Quiet];
289
290    pub fn as_str(self) -> &'static str {
291        match self {
292            Self::Final => "final",
293            Self::Full => "full",
294            Self::Quiet => "quiet",
295        }
296    }
297
298    pub fn parse(text: &str) -> Option<Self> {
299        Self::ALL.into_iter().find(|mode| mode.as_str() == text)
300    }
301}
302
303/// How much of something the interface shows, for the model's reasoning and for
304/// tool calls (beyond Python; `[ui] thinking` and `[ui] tool_use`).
305#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
306#[serde(rename_all = "lowercase")]
307pub enum DisplayLevel {
308    /// All of it: reasoning streamed dimmed; a tool call's arguments and result.
309    Full,
310    /// One line: how long the model thought; a tool call's name and a result summary.
311    Summary,
312    /// Nothing in the scrollback (failures and approvals still show).
313    Hidden,
314}
315
316impl DisplayLevel {
317    pub const ALL: [Self; 3] = [Self::Full, Self::Summary, Self::Hidden];
318
319    pub fn as_str(self) -> &'static str {
320        match self {
321            Self::Full => "full",
322            Self::Summary => "summary",
323            Self::Hidden => "hidden",
324        }
325    }
326
327    pub fn parse(text: &str) -> Option<Self> {
328        Self::ALL
329            .into_iter()
330            .find(|level| level.as_str() == text.trim().to_lowercase())
331    }
332
333    /// The next level, wrapping: full, summary, hidden, full.
334    pub fn next(self) -> Self {
335        match self {
336            Self::Full => Self::Summary,
337            Self::Summary => Self::Hidden,
338            Self::Hidden => Self::Full,
339        }
340    }
341}
342
343fn default_summary() -> DisplayLevel {
344    DisplayLevel::Summary
345}
346
347#[derive(Debug, Clone, PartialEq, Deserialize)]
348pub struct LimitsConfig {
349    /// Model calls one turn may make before the circuit trips.
350    pub max_steps: u32,
351    /// Cumulative cost (USD) at which the circuit trips; `0` disables the cap.
352    pub max_cost_usd: f64,
353    /// Seconds one turn may run before the circuit trips; `0` disables the limit.
354    pub max_wall_clock_s: u64,
355    /// Failed tool results tolerated in a row; one more trips the circuit.
356    pub max_consecutive_errors: u32,
357    /// An optional hard cap on the conversation's tokens; `0` derives the budget
358    /// from the model's real window alone.
359    pub max_context_tokens: u64,
360    pub max_output_tokens: u32,
361    /// Headroom kept free inside the window on top of the output cap: slack for
362    /// the provider counting tokens differently than the estimate does.
363    pub context_reserve_tokens: u64,
364    /// What happens to the oldest turns when the conversation outgrows its budget.
365    pub compaction: CompactionMode,
366    /// Run a step's read-only tool calls concurrently.
367    pub parallel_tools: bool,
368    /// Seconds a single sandboxed tool may run before its process tree is killed.
369    pub tool_timeout_s: u64,
370}
371
372/// `[skills]`.
373#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
374pub struct SkillsConfig {
375    pub enabled: bool,
376    /// Extra directories searched after the project's and the user's.
377    pub paths: Vec<String>,
378}
379
380/// `[agents]`: sub-agent spawning through the `delegate` tool.
381#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
382pub struct AgentsConfig {
383    pub enabled: bool,
384    /// How deep delegation may nest (the main agent is depth 0).
385    pub max_depth: u32,
386    /// Each sub-agent's step cap, kept below `limits.max_steps`.
387    pub max_steps: u32,
388    /// Beyond Python: how many adjacent specialist delegations run at once (the
389    /// rest queue). Trust-free, so it is clamped: below 1 counts as 1, and the
390    /// ceiling is [`MAX_PARALLEL_CEILING`].
391    #[serde(default = "default_max_parallel")]
392    pub max_parallel: u32,
393}
394
395/// The most specialist sub-agents that run at once, whatever `[agents]
396/// max_parallel` says (a cloned repo's config may set it).
397pub const MAX_PARALLEL_CEILING: u32 = 8;
398
399fn default_max_parallel() -> u32 {
400    3
401}
402
403impl AgentsConfig {
404    /// `max_parallel`, clamped to 1 ..= [`MAX_PARALLEL_CEILING`].
405    pub fn parallel_limit(&self) -> usize {
406        self.max_parallel.clamp(1, MAX_PARALLEL_CEILING) as usize
407    }
408}
409
410/// `[mcp]`.
411#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
412pub struct McpConfig {
413    pub enabled: bool,
414}
415
416/// One MCP server, reached over `stdio` (a local subprocess) or, in Python, `sse`/`http`.
417#[derive(Debug, Clone, PartialEq, Deserialize)]
418pub struct McpServerConfig {
419    #[serde(default)]
420    pub command: Option<String>,
421    #[serde(default)]
422    pub args: Vec<String>,
423    #[serde(default)]
424    pub env: indexmap::IndexMap<String, String>,
425    #[serde(default)]
426    pub url: Option<String>,
427    #[serde(default)]
428    pub headers: indexmap::IndexMap<String, String>,
429    /// `stdio`, `sse`, or `http`; inferred from `command` or `url` when omitted.
430    #[serde(default)]
431    pub transport: Option<String>,
432    #[serde(default = "default_true")]
433    pub enabled: bool,
434    #[serde(default = "default_mcp_connect_timeout_s")]
435    pub connect_timeout_s: f64,
436    #[serde(default = "default_mcp_call_timeout_s")]
437    pub call_timeout_s: f64,
438    #[serde(default = "default_mcp_max_result_chars")]
439    pub max_result_chars: usize,
440    /// Arguments to add to a tool's calls when the model leaves them out, by the
441    /// server's own tool name: `[mcp.servers.<name>.defaults] tool = { arg = value }`.
442    /// Only arguments the tool's schema declares are added; the model's own win.
443    /// Beyond Python, which has no such setting.
444    #[serde(default)]
445    pub defaults: indexmap::IndexMap<String, serde_json::Map<String, serde_json::Value>>,
446}
447
448impl McpServerConfig {
449    /// Validate and fill in `transport`, with Python's messages.
450    pub fn resolve_transport(&mut self) -> Result<(), String> {
451        let (has_command, has_url) = (
452            self.command.as_deref().is_some_and(|c| !c.is_empty()),
453            self.url.as_deref().is_some_and(|u| !u.is_empty()),
454        );
455        if has_command && has_url {
456            return Err("MCP server sets both 'command' and 'url'; use one transport".to_owned());
457        }
458        if !has_command && !has_url {
459            return Err("MCP server needs 'command' (stdio) or 'url' (sse/http)".to_owned());
460        }
461        let given = self
462            .transport
463            .clone()
464            .unwrap_or_else(|| if has_command { "stdio" } else { "http" }.to_owned());
465        let mut transport = given.to_lowercase().replace('-', "_");
466        if transport == "streamable_http" {
467            transport = "http".to_owned();
468        }
469        if !matches!(transport.as_str(), "stdio" | "sse" | "http") {
470            return Err(format!("unknown MCP transport '{given}' (stdio|sse|http)"));
471        }
472        if transport == "stdio" && !has_command {
473            return Err("stdio transport requires 'command'".to_owned());
474        }
475        if transport != "stdio" && !has_url {
476            return Err(format!("{transport} transport requires 'url'"));
477        }
478        for (field, value) in [
479            ("connect_timeout_s", self.connect_timeout_s),
480            ("call_timeout_s", self.call_timeout_s),
481        ] {
482            if !(value > 0.0 && value.is_finite()) {
483                return Err(format!("{field} must be greater than 0"));
484            }
485        }
486        if self.max_result_chars == 0 {
487            return Err("max_result_chars must be greater than 0".to_owned());
488        }
489        self.transport = Some(transport);
490        Ok(())
491    }
492
493    /// The resolved transport (`stdio`, `sse`, or `http`).
494    pub fn transport(&self) -> &str {
495        self.transport.as_deref().unwrap_or("stdio")
496    }
497}
498
499fn default_mcp_connect_timeout_s() -> f64 {
500    30.0
501}
502
503fn default_mcp_call_timeout_s() -> f64 {
504    120.0
505}
506
507fn default_mcp_max_result_chars() -> usize {
508    8000
509}
510
511/// Flight-recorder and OpenTelemetry settings (`[observability]`).
512#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
513pub struct ObservabilityConfig {
514    /// Write the JSONL flight recorder.
515    pub trace: bool,
516    /// The trace directory; `~` expands.
517    pub path: String,
518    /// Emit OpenTelemetry spans (`crate::otel`).
519    #[serde(default)]
520    pub otel: bool,
521    /// Where the spans go.
522    #[serde(default)]
523    pub otel_exporter: OtelExporter,
524    /// The collector, overriding `OTEL_EXPORTER_OTLP_ENDPOINT` when set.
525    #[serde(default)]
526    pub otel_endpoint: Option<String>,
527    pub redact: RedactMode,
528    /// Free-text fields are clipped to this many characters.
529    pub max_field_chars: usize,
530    /// The live trace rotates at this size; `0` disables rotation.
531    pub max_trace_bytes: u64,
532    /// Rotated generations kept; `0` keeps no history.
533    pub keep_traces: usize,
534}
535
536/// Where OpenTelemetry spans go (`[observability] otel_exporter`).
537#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
538#[serde(rename_all = "snake_case")]
539pub enum OtelExporter {
540    /// A collector over OTLP, honouring the standard `OTEL_*` variables.
541    #[default]
542    Otlp,
543    /// Printed to stderr, for local debugging.
544    Console,
545    /// Recorded, exported nowhere.
546    None,
547}
548
549/// What the recorder may write (`[observability] redact`).
550#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
551#[serde(rename_all = "snake_case")]
552pub enum RedactMode {
553    /// Scrub secret-shaped values and clip the big free-text fields.
554    Secrets,
555    /// Write events exactly as the loop emitted them.
556    None,
557}
558
559/// Memory settings (`[memory]`).
560#[derive(Debug, Clone, PartialEq, Deserialize)]
561pub struct MemoryConfig {
562    pub enabled: bool,
563    /// The SQLite database, shared with the Python implementation; `~` expands.
564    pub path: String,
565    /// The embedder spec: `hash:<dim>`, or `sentence-transformers:<model>`
566    /// (falling back to `hash:256` when the model cannot load).
567    pub embeddings: String,
568    /// Skip the Hugging Face update check for a cached model.
569    pub hf_offline: bool,
570    /// Retention caps for the episode and session log, applied when the harness
571    /// starts; 0 disables a cap. Curated facts are never pruned automatically.
572    pub retention_max_episodes: i64,
573    pub retention_max_sessions: i64,
574    pub retention_max_age_days: f64,
575}
576
577/// Tool settings (`[tools]`).
578#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
579pub struct ToolsConfig {
580    /// Let `web_fetch` reach private, loopback, and link-local addresses.
581    pub web_allow_private: bool,
582    /// The User-Agent `web_fetch` sends; defaults to agent86's own.
583    #[serde(default = "crate::tools::web::default_user_agent")]
584    pub web_user_agent: String,
585    /// Characters of page text `web_fetch` returns at most; `0` disables the cap.
586    pub web_max_chars: usize,
587    /// Largest file an `@path` mention inlines; `0` disables the cap.
588    pub mention_max_bytes: u64,
589}
590
591/// Safety settings (`[guardrails]`).
592#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
593pub struct GuardrailsConfig {
594    /// What happens before a side-effecting tool runs: `auto`, `ask`, or `deny`.
595    pub approval: ApprovalMode,
596    /// Scanning of user input for injection and PII.
597    pub ingress: IngressMode,
598    /// Scanning of model output for secrets and PII.
599    pub egress: EgressMode,
600    /// Wrap tool output that looks like injected instructions as untrusted data.
601    pub scan_observations: bool,
602}
603
604/// `[guardrails] ingress`.
605#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
606#[serde(rename_all = "snake_case")]
607pub enum IngressMode {
608    Off,
609    /// Scan and report findings.
610    Warn,
611    /// Also refuse turns carrying prompt injection.
612    Block,
613}
614
615/// `[limits] compaction`: what happens to the oldest turns when the
616/// conversation outgrows its budget.
617#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
618#[serde(rename_all = "snake_case")]
619pub enum CompactionMode {
620    /// Replace the oldest span with a model-written summary.
621    Summarize,
622    /// Silently drop the oldest span.
623    Drop,
624}
625
626/// `[guardrails] egress`.
627#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
628#[serde(rename_all = "snake_case")]
629pub enum EgressMode {
630    Off,
631    /// Scan and report findings.
632    Warn,
633    /// Also rewrite secrets and PII out of the text.
634    Redact,
635}
636
637/// Where tool code runs (`[sandbox]`).
638#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
639pub struct SandboxConfig {
640    pub mode: SandboxMode,
641    pub docker_image: String,
642    pub docker_memory: String,
643    pub docker_cpus: String,
644    /// Containers run with `--network none` unless this is true.
645    pub docker_network: bool,
646    /// Extra environment variable names forwarded into tool subprocesses. Names
647    /// only: values are read at spawn time, and credential-looking names are refused.
648    pub env_passthrough: Vec<String>,
649}
650
651#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
652#[serde(rename_all = "snake_case")]
653pub enum SandboxMode {
654    /// A local subprocess with resource limits.
655    Subprocess,
656    /// A throwaway container (opt-in).
657    Docker,
658}
659
660impl SandboxMode {
661    /// The config spelling, which is also how Python renders the mode.
662    pub fn as_str(self) -> &'static str {
663        match self {
664            Self::Subprocess => "subprocess",
665            Self::Docker => "docker",
666        }
667    }
668}
669
670/// Per-model price overrides (`[pricing.models."<ref or id>"]`).
671///
672/// Keys are the `provider:model` ref or the bare model id; the ref form wins when
673/// both are present. Dated snapshots resolve by prefix, so overriding
674/// `claude-sonnet-5` also covers `claude-sonnet-5-20260101`.
675#[derive(Debug, Clone, Default, PartialEq, Deserialize)]
676pub struct PricingConfig {
677    #[serde(default)]
678    pub models: BTreeMap<String, ModelPrice>,
679}
680
681/// A per-model price override, USD per million tokens.
682#[derive(Debug, Clone, Copy, PartialEq, Deserialize)]
683pub struct ModelPrice {
684    pub input_per_mtok: f64,
685    pub output_per_mtok: f64,
686}
687
688/// One `[providers.<name>]` block.
689#[derive(Debug, Clone, PartialEq, Deserialize)]
690pub struct ProviderConfig {
691    #[serde(default)]
692    pub api_key_env: Option<String>,
693    #[serde(default)]
694    pub base_url: Option<String>,
695    /// Ollama's context window, sent as `num_ctx`. Unset, the model's own maximum
696    /// is asked for, up to `num_ctx_max`.
697    #[serde(default)]
698    pub num_ctx: Option<u32>,
699    /// The largest window asked for when `num_ctx` is unset (a deliberate
700    /// difference from Python, which sends 8192): Ollama allocates all of it.
701    #[serde(default)]
702    pub num_ctx_max: Option<u32>,
703    /// A TCP connect that has not completed in this time is a down endpoint.
704    #[serde(default = "default_connect_timeout_s")]
705    pub connect_timeout_s: f64,
706    /// The maximum gap between streamed chunks, not the total generation time.
707    #[serde(default = "default_read_timeout_s")]
708    pub read_timeout_s: f64,
709    #[serde(default = "default_max_retries")]
710    pub max_retries: u32,
711    #[serde(default)]
712    pub max_tokens: Option<u32>,
713    #[serde(default = "default_true")]
714    pub prompt_cache: bool,
715    /// OpenRouter's provider routing preferences (`order`, `ignore`, `only`,
716    /// `sort`, ...), sent as the request's `provider` field by the
717    /// OpenAI-compatible adapter. Beyond Python: a way to keep a model off a host
718    /// that serves it badly.
719    #[serde(default)]
720    pub routing: Option<serde_json::Map<String, serde_json::Value>>,
721    /// The kind of server a section reaches (beyond Python): `"vllm"` or
722    /// `"lmstudio"` gives any section that server's behaviour (an optional key, the
723    /// window and model list it reports, local pricing, and hints for its errors),
724    /// so a local server and a remote box can sit side by side. Unset is today's
725    /// rules; the built-in sections need none. See `provider::ServerKind`.
726    #[serde(default)]
727    pub adapter: Option<String>,
728    /// `[providers.google] store` (beyond Python): let Google keep the requests in
729    /// AI Studio's logs. Off unless set, and sent as `store: false` on every
730    /// request, since a request holds every file the agent read.
731    #[serde(default)]
732    pub store: bool,
733}
734
735impl Default for ProviderConfig {
736    fn default() -> Self {
737        Self {
738            api_key_env: None,
739            base_url: None,
740            num_ctx: None,
741            num_ctx_max: None,
742            connect_timeout_s: default_connect_timeout_s(),
743            read_timeout_s: default_read_timeout_s(),
744            max_retries: default_max_retries(),
745            max_tokens: None,
746            prompt_cache: true,
747            routing: None,
748            adapter: None,
749            store: false,
750        }
751    }
752}
753
754impl Config {
755    /// The output cap for one call: the provider's `max_tokens`, else `limits.max_output_tokens`.
756    pub fn max_output_tokens_for(&self, provider: &str) -> u32 {
757        self.providers
758            .get(provider)
759            .and_then(|config| config.max_tokens)
760            .filter(|&cap| cap > 0)
761            .unwrap_or(if self.limits.max_output_tokens > 0 {
762                self.limits.max_output_tokens
763            } else {
764                8192
765            })
766    }
767}
768
769/// Where the user and project config files live.
770#[derive(Debug, Clone, PartialEq, Eq)]
771pub struct ConfigPaths {
772    pub user: Option<PathBuf>,
773    pub project: PathBuf,
774    /// Whether the project file's settings that need trust count (beyond Python;
775    /// see `crate::trust`).
776    pub project_trust: ProjectTrust,
777}
778
779/// How far the project config file is trusted (beyond Python, which honors all of
780/// it). A file in a repository someone else wrote can start MCP servers, send API
781/// keys to a server of its choosing, or turn approvals off, so only the settings in
782/// [`crate::trust::TRUST_FREE`] count until the user trusts it.
783#[derive(Debug, Clone, Copy, PartialEq, Eq)]
784pub enum ProjectTrust {
785    /// Every setting counts: the user trusted this file, or the run said to.
786    Trusted,
787    /// Only the settings that need no trust; the rest are left out and listed in
788    /// [`Config::untrusted`].
789    Restricted,
790}
791
792impl ConfigPaths {
793    /// `~/.agent86/config.toml` and `./.agent86/config.toml`, as in Python. The
794    /// project file starts restricted; `crate::trust::decide` says otherwise.
795    pub fn discover() -> Self {
796        Self {
797            user: home_dir().map(|home| home.join(".agent86").join("config.toml")),
798            project: Path::new(".agent86").join("config.toml"),
799            project_trust: ProjectTrust::Restricted,
800        }
801    }
802}
803
804/// The overrides that sit above the config files.
805#[derive(Debug, Clone, Default, PartialEq, Eq)]
806pub struct Overrides {
807    /// `AGENT86_MODEL`.
808    pub env_model: Option<String>,
809    /// `AGENT86_SANDBOX`.
810    pub env_sandbox: Option<String>,
811    /// `AGENT86_APPROVAL`.
812    pub env_approval: Option<String>,
813    /// `AGENT86_RUN_OUTPUT` (beyond Python). `run --output` is applied by `run` itself.
814    pub env_run_output: Option<String>,
815    /// `--model`.
816    pub model: Option<String>,
817    /// `--sandbox`.
818    pub sandbox: Option<String>,
819    /// `--approval`.
820    pub approval: Option<String>,
821}
822
823impl Overrides {
824    /// Read the supported `AGENT86_*` environment variables; empty values are ignored.
825    /// `model`, `sandbox`, and `approval` are the `--model`, `--sandbox`, and
826    /// `--approval` flags.
827    pub fn from_env(
828        model: Option<String>,
829        sandbox: Option<String>,
830        approval: Option<String>,
831    ) -> Self {
832        Self {
833            env_model: non_empty_env("AGENT86_MODEL"),
834            env_sandbox: non_empty_env("AGENT86_SANDBOX"),
835            env_approval: non_empty_env("AGENT86_APPROVAL"),
836            env_run_output: non_empty_env("AGENT86_RUN_OUTPUT"),
837            model,
838            sandbox,
839            approval,
840        }
841    }
842}
843
844#[derive(Debug, Clone, PartialEq, Eq, Error)]
845pub enum ConfigError {
846    #[error("Malformed config at {path}: {detail}")]
847    Malformed { path: String, detail: String },
848    #[error("Invalid config: {detail}")]
849    Invalid { detail: String },
850}
851
852/// Resolve configuration from all layers.
853/// The built-in defaults alone, with no file, environment variable, or flag read:
854/// what [`load_config`] starts from. The embedding API (`crate::sdk`) takes its
855/// defaults from here, so they are never kept in two places.
856pub fn builtin_config() -> Config {
857    let mut merged: Table = DEFAULTS.parse().expect("built-in defaults are valid TOML");
858    accept_legacy_status_line(&mut merged);
859    let mut config: Config = Value::Table(merged.clone())
860        .try_into()
861        .expect("built-in defaults deserialize");
862    validate(&mut config).expect("built-in defaults are valid");
863    config.table = merged;
864    config
865}
866
867pub fn load_config(paths: &ConfigPaths, overrides: &Overrides) -> Result<Config, ConfigError> {
868    let mut merged: Table = DEFAULTS.parse().expect("built-in defaults are valid TOML");
869    let mut sources = Vec::new();
870
871    let mut untrusted = Vec::new();
872    let files = paths.user.iter().chain(std::iter::once(&paths.project));
873    for path in files {
874        let mut layer = normalize(read_toml(path)?);
875        if path == &paths.project && paths.project_trust == ProjectTrust::Restricted {
876            untrusted = crate::trust::take_untrusted(&mut layer)
877                .into_iter()
878                .map(|(key, _)| key)
879                .collect();
880        }
881        if !layer.is_empty() {
882            deep_merge(&mut merged, layer);
883            sources.push(path.clone());
884        }
885    }
886
887    // Environment variables first, then CLI flags, as in Python.
888    let layers = [
889        ("model", "default", &overrides.env_model),
890        ("sandbox", "mode", &overrides.env_sandbox),
891        ("guardrails", "approval", &overrides.env_approval),
892        ("run", "output", &overrides.env_run_output),
893        ("model", "default", &overrides.model),
894        ("sandbox", "mode", &overrides.sandbox),
895        ("guardrails", "approval", &overrides.approval),
896    ];
897    for (section, key, value) in layers {
898        if let Some(value) = value {
899            let mut table = Table::new();
900            table.insert(key.to_owned(), Value::String(value.clone()));
901            let mut layer = Table::new();
902            layer.insert(section.to_owned(), Value::Table(table));
903            deep_merge(&mut merged, layer);
904        }
905    }
906
907    accept_legacy_status_line(&mut merged);
908    let mut config: Config =
909        Value::Table(merged.clone())
910            .try_into()
911            .map_err(|error: toml::de::Error| ConfigError::Invalid {
912                detail: error.message().to_owned(),
913            })?;
914    validate(&mut config)?;
915    config.sources = sources;
916    config.table = merged;
917    config.untrusted = untrusted;
918    Ok(config)
919}
920
921/// One config file as a table, as loading reads it (empty when absent).
922pub(crate) fn read_toml_layer(path: &Path) -> Result<Table, ConfigError> {
923    read_toml(path)
924}
925
926/// A layer with `[mcp.servers.<name>]` mapped onto `mcp_servers`, as loading does.
927pub(crate) fn normalize_layer(layer: Table) -> Table {
928    normalize(layer)
929}
930
931/// Checks serde cannot express, matching the Python schema's constraints.
932/// Map `[mcp.servers.<name>]` onto `mcp_servers`, as Python's `_normalize`.
933fn normalize(mut layer: Table) -> Table {
934    if let Some(Value::Table(mcp)) = layer.get_mut("mcp") {
935        if let Some(servers) = mcp.remove("servers") {
936            let empty = mcp.is_empty();
937            if empty {
938                layer.remove("mcp");
939            }
940            layer.insert("mcp_servers".to_owned(), servers);
941        }
942    }
943    layer
944}
945
946/// Map `[ui] status_line` onto `tui` (an explicit `tui` wins), as Python's
947/// `UIConfig` validator does on the merged layers.
948fn accept_legacy_status_line(merged: &mut Table) {
949    if let Some(Value::Table(ui)) = merged.get_mut("ui") {
950        if let Some(legacy) = ui.remove("status_line") {
951            ui.entry("tui").or_insert(legacy);
952        }
953    }
954}
955
956fn validate(config: &mut Config) -> Result<(), ConfigError> {
957    // Beyond Python: zero would time every command and fetch out at once.
958    if config.limits.tool_timeout_s == 0 {
959        return Err(ConfigError::Invalid {
960            detail: "limits.tool_timeout_s must be at least 1 second, not 0".to_owned(),
961        });
962    }
963    for (name, server) in &mut config.mcp_servers {
964        server
965            .resolve_transport()
966            .map_err(|detail| ConfigError::Invalid {
967                detail: format!("mcp_servers.{name}: {detail}"),
968            })?;
969    }
970    for (model, price) in &config.pricing.models {
971        for (field, value) in [
972            ("input_per_mtok", price.input_per_mtok),
973            ("output_per_mtok", price.output_per_mtok),
974        ] {
975            if !(value >= 0.0 && value.is_finite()) {
976                return Err(ConfigError::Invalid {
977                    detail: format!(
978                        "pricing.models.\"{model}\".{field} must be a non-negative number, not {value}"
979                    ),
980                });
981            }
982        }
983    }
984    Ok(())
985}
986
987fn read_toml(path: &Path) -> Result<Table, ConfigError> {
988    let text = match std::fs::read_to_string(path) {
989        Ok(text) => text,
990        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Table::new()),
991        Err(error) => {
992            return Err(ConfigError::Malformed {
993                path: path.display().to_string(),
994                detail: error.to_string(),
995            })
996        }
997    };
998    text.parse()
999        .map_err(|error: toml::de::Error| ConfigError::Malformed {
1000            path: path.display().to_string(),
1001            detail: error.to_string().trim_end().to_owned(),
1002        })
1003}
1004
1005/// Recursively merge `overlay` into `base`; tables merge, everything else replaces.
1006fn deep_merge(base: &mut Table, overlay: Table) {
1007    for (key, value) in overlay {
1008        match (base.get_mut(&key), value) {
1009            (Some(Value::Table(existing)), Value::Table(incoming)) => {
1010                deep_merge(existing, incoming)
1011            }
1012            (_, value) => {
1013                base.insert(key, value);
1014            }
1015        }
1016    }
1017}
1018
1019fn non_empty_env(name: &str) -> Option<String> {
1020    std::env::var(name).ok().filter(|value| !value.is_empty())
1021}
1022
1023/// The home directory as Python's `Path.home()` resolves it.
1024pub fn home_dir() -> Option<PathBuf> {
1025    let variable = if cfg!(windows) { "USERPROFILE" } else { "HOME" };
1026    std::env::var_os(variable)
1027        .filter(|value| !value.is_empty())
1028        .map(PathBuf::from)
1029}
1030
1031fn default_connect_timeout_s() -> f64 {
1032    10.0
1033}
1034
1035fn default_read_timeout_s() -> f64 {
1036    300.0
1037}
1038
1039fn default_max_retries() -> u32 {
1040    2
1041}
1042
1043fn default_true() -> bool {
1044    true
1045}
1046
1047#[cfg(test)]
1048mod tests {
1049    use super::*;
1050
1051    fn paths_in(dir: &Path) -> ConfigPaths {
1052        ConfigPaths {
1053            user: Some(dir.join("user.toml")),
1054            project: dir.join("project.toml"),
1055            project_trust: crate::config::ProjectTrust::Trusted,
1056        }
1057    }
1058
1059    fn temp_dir(name: &str) -> PathBuf {
1060        let dir =
1061            std::env::temp_dir().join(format!("agent86-config-{name}-{}", std::process::id()));
1062        let _ = std::fs::remove_dir_all(&dir);
1063        std::fs::create_dir_all(&dir).unwrap();
1064        dir
1065    }
1066
1067    #[test]
1068    fn a_zero_tool_timeout_is_invalid() {
1069        let dir = temp_dir("timeout");
1070        let paths = paths_in(&dir);
1071        std::fs::write(&paths.project, "[limits]\ntool_timeout_s = 0\n").unwrap();
1072        let error = load_config(&paths, &Overrides::default()).unwrap_err();
1073        assert_eq!(
1074            error.to_string(),
1075            "Invalid config: limits.tool_timeout_s must be at least 1 second, not 0"
1076        );
1077        std::fs::write(&paths.project, "[limits]\ntool_timeout_s = 1\n").unwrap();
1078        assert_eq!(
1079            load_config(&paths, &Overrides::default())
1080                .unwrap()
1081                .limits
1082                .tool_timeout_s,
1083            1
1084        );
1085    }
1086
1087    #[test]
1088    fn ui_settings_default_and_accept_the_legacy_status_line_key() {
1089        let dir = temp_dir("ui");
1090        let paths = paths_in(&dir);
1091        let config = load_config(&paths, &Overrides::default()).unwrap();
1092        assert!(config.ui.tui);
1093        assert_eq!(config.ui.history_file, "~/.agent86/history");
1094        assert_eq!(config.ui.history_size, 1000);
1095        assert_eq!(config.tools.mention_max_bytes, 200_000);
1096        assert_eq!(config.model.router, RouterMode::Off);
1097        assert_eq!(config.model.route.cheap, "ollama:llama3.1");
1098
1099        // Pre-v0.6 configs spelled `tui` as `status_line`...
1100        std::fs::write(&paths.project, "[ui]\nstatus_line = false\n").unwrap();
1101        assert!(!load_config(&paths, &Overrides::default()).unwrap().ui.tui);
1102        // ...and an explicit `tui` in any layer wins over it.
1103        std::fs::write(dir.join("user.toml"), "[ui]\ntui = true\n").unwrap();
1104        let config = load_config(&paths, &Overrides::default()).unwrap();
1105        assert!(config.ui.tui);
1106        assert!(!config.table["ui"]
1107            .as_table()
1108            .unwrap()
1109            .contains_key("status_line"));
1110        let _ = std::fs::remove_dir_all(&dir);
1111    }
1112
1113    #[test]
1114    fn thinking_and_tool_use_default_to_summary_and_take_the_three_levels() {
1115        let dir = temp_dir("display-levels");
1116        let paths = paths_in(&dir);
1117        let config = load_config(&paths, &Overrides::default()).unwrap();
1118        assert_eq!(config.ui.thinking, DisplayLevel::Summary);
1119        assert_eq!(config.ui.tool_use, DisplayLevel::Summary);
1120
1121        std::fs::write(
1122            &paths.project,
1123            "[ui]\nthinking = \"full\"\ntool_use = \"hidden\"\n",
1124        )
1125        .unwrap();
1126        let config = load_config(&paths, &Overrides::default()).unwrap();
1127        assert_eq!(config.ui.thinking, DisplayLevel::Full);
1128        assert_eq!(config.ui.tool_use, DisplayLevel::Hidden);
1129
1130        // Anything else is refused, naming what is allowed.
1131        std::fs::write(&paths.project, "[ui]\nthinking = \"loud\"\n").unwrap();
1132        let error = load_config(&paths, &Overrides::default())
1133            .unwrap_err()
1134            .to_string();
1135        assert!(
1136            error.contains("loud") && error.contains("full") && error.contains("hidden"),
1137            "{error}"
1138        );
1139        let _ = std::fs::remove_dir_all(&dir);
1140    }
1141
1142    #[test]
1143    fn agent86ui_defaults_to_auto_without_remote_media() {
1144        let dir = temp_dir("agent86ui-settings");
1145        let paths = paths_in(&dir);
1146        let config = load_config(&paths, &Overrides::default()).unwrap();
1147        assert_eq!(config.ui.agent86ui, Agent86UiMode::Auto);
1148        assert!(!config.ui.agent86ui_remote_media);
1149
1150        std::fs::write(
1151            &paths.project,
1152            "[ui]\nagent86ui = \"off\"\nagent86ui_remote_media = true\n",
1153        )
1154        .unwrap();
1155        let config = load_config(&paths, &Overrides::default()).unwrap();
1156        assert_eq!(config.ui.agent86ui, Agent86UiMode::Off);
1157        assert!(config.ui.agent86ui_remote_media);
1158
1159        std::fs::write(&paths.project, "[ui]\nagent86ui = \"on\"\n").unwrap();
1160        let error = load_config(&paths, &Overrides::default())
1161            .unwrap_err()
1162            .to_string();
1163        assert!(error.contains("auto") && error.contains("off"), "{error}");
1164        let _ = std::fs::remove_dir_all(&dir);
1165    }
1166
1167    #[test]
1168    fn display_levels_parse_cycle_and_name_themselves() {
1169        assert_eq!(DisplayLevel::parse(" Hidden "), Some(DisplayLevel::Hidden));
1170        assert_eq!(DisplayLevel::parse("loud"), None);
1171        let cycle: Vec<&str> =
1172            std::iter::successors(Some(DisplayLevel::Full), |level| Some(level.next()))
1173                .take(4)
1174                .map(DisplayLevel::as_str)
1175                .collect();
1176        assert_eq!(cycle, ["full", "summary", "hidden", "full"]);
1177    }
1178
1179    #[test]
1180    fn defaults_include_the_builtin_providers() {
1181        let dir = temp_dir("defaults");
1182        let config = load_config(&paths_in(&dir), &Overrides::default()).unwrap();
1183
1184        assert_eq!(config.model.default, "anthropic:claude-opus-4-8");
1185        let openrouter = &config.providers["openrouter"];
1186        assert_eq!(
1187            openrouter.api_key_env.as_deref(),
1188            Some("OPENROUTER_API_KEY")
1189        );
1190        assert_eq!(
1191            openrouter.base_url.as_deref(),
1192            Some("https://openrouter.ai/api/v1")
1193        );
1194        assert_eq!(openrouter.read_timeout_s, 300.0);
1195        assert_eq!(config.max_output_tokens_for("openrouter"), 8192);
1196        assert!(config.sources.is_empty());
1197        assert_eq!(openrouter.routing, None);
1198    }
1199
1200    #[test]
1201    fn a_routing_table_is_read_as_json() {
1202        let dir = temp_dir("routing");
1203        let paths = paths_in(&dir);
1204        std::fs::write(
1205            &paths.project,
1206            "[providers.openrouter.routing]\nignore = [\"Phala\"]\nallow_fallbacks = true\n",
1207        )
1208        .unwrap();
1209        let config = load_config(&paths, &Overrides::default()).unwrap();
1210        let routing = config.providers["openrouter"].routing.clone().unwrap();
1211        assert_eq!(
1212            serde_json::Value::Object(routing),
1213            serde_json::json!({"ignore": ["Phala"], "allow_fallbacks": true})
1214        );
1215        let _ = std::fs::remove_dir_all(&dir);
1216    }
1217
1218    #[test]
1219    fn layers_deep_merge_and_overrides_win() {
1220        let dir = temp_dir("layers");
1221        std::fs::write(
1222            dir.join("user.toml"),
1223            "[model]\ndefault = \"openrouter:a\"\n[providers.openrouter]\nmax_tokens = 512\n",
1224        )
1225        .unwrap();
1226        std::fs::write(
1227            dir.join("project.toml"),
1228            "[providers.openrouter]\nbase_url = \"http://localhost:9\"\n[providers.mine]\nbase_url = \"http://x\"\n[tools]\nanything = 1\n",
1229        )
1230        .unwrap();
1231
1232        let config = load_config(&paths_in(&dir), &Overrides::default()).unwrap();
1233        let openrouter = &config.providers["openrouter"];
1234        assert_eq!(config.model.default, "openrouter:a");
1235        assert_eq!(openrouter.base_url.as_deref(), Some("http://localhost:9"));
1236        assert_eq!(
1237            openrouter.api_key_env.as_deref(),
1238            Some("OPENROUTER_API_KEY")
1239        );
1240        assert_eq!(config.max_output_tokens_for("openrouter"), 512);
1241        assert!(config.providers.contains_key("groq"));
1242        assert_eq!(config.providers["mine"].max_retries, 2);
1243        assert_eq!(config.sources.len(), 2);
1244
1245        let env = Overrides {
1246            env_model: Some("groq:b".to_owned()),
1247            ..Overrides::default()
1248        };
1249        assert_eq!(
1250            load_config(&paths_in(&dir), &env).unwrap().model.default,
1251            "groq:b"
1252        );
1253
1254        let flag = Overrides {
1255            env_model: Some("groq:b".to_owned()),
1256            model: Some("openai:c".to_owned()),
1257            ..Overrides::default()
1258        };
1259        assert_eq!(
1260            load_config(&paths_in(&dir), &flag).unwrap().model.default,
1261            "openai:c"
1262        );
1263    }
1264
1265    #[test]
1266    fn malformed_toml_names_the_file() {
1267        let dir = temp_dir("malformed");
1268        std::fs::write(dir.join("project.toml"), "[model\n").unwrap();
1269
1270        let error = load_config(&paths_in(&dir), &Overrides::default()).unwrap_err();
1271        let ConfigError::Malformed { path, .. } = &error else {
1272            panic!("{error:?}");
1273        };
1274        assert!(path.ends_with("project.toml"));
1275        assert!(error.to_string().starts_with("Malformed config at "));
1276    }
1277
1278    #[test]
1279    fn pricing_overrides_load_and_negative_prices_are_rejected() {
1280        let dir = temp_dir("pricing");
1281        std::fs::write(
1282            dir.join("project.toml"),
1283            "[pricing.models.\"openrouter:openai/gpt-4o-mini\"]\ninput_per_mtok = 0.15\noutput_per_mtok = 0.6\n",
1284        )
1285        .unwrap();
1286        let config = load_config(&paths_in(&dir), &Overrides::default()).unwrap();
1287        let price = config.pricing.models["openrouter:openai/gpt-4o-mini"];
1288        assert_eq!(price.input_per_mtok, 0.15);
1289        assert_eq!(price.output_per_mtok, 0.6);
1290
1291        std::fs::write(
1292            dir.join("project.toml"),
1293            "[pricing.models.cheap]\ninput_per_mtok = -1\noutput_per_mtok = 0\n",
1294        )
1295        .unwrap();
1296        let error = load_config(&paths_in(&dir), &Overrides::default()).unwrap_err();
1297        assert!(matches!(error, ConfigError::Invalid { .. }), "{error:?}");
1298        assert!(error.to_string().contains("input_per_mtok"), "{error}");
1299    }
1300
1301    #[test]
1302    fn sandbox_mode_defaults_to_subprocess_and_rejects_unknown_values() {
1303        let dir = temp_dir("sandbox");
1304        let config = load_config(&paths_in(&dir), &Overrides::default()).unwrap();
1305        assert_eq!(config.sandbox.mode, SandboxMode::Subprocess);
1306
1307        let env = Overrides {
1308            env_sandbox: Some("docker".to_owned()),
1309            ..Overrides::default()
1310        };
1311        assert_eq!(
1312            load_config(&paths_in(&dir), &env).unwrap().sandbox.mode,
1313            SandboxMode::Docker
1314        );
1315        // `--sandbox` wins over `AGENT86_SANDBOX`, as Python's CLI overrides do.
1316        let flag = Overrides {
1317            sandbox: Some("subprocess".to_owned()),
1318            ..env
1319        };
1320        assert_eq!(
1321            load_config(&paths_in(&dir), &flag).unwrap().sandbox.mode,
1322            SandboxMode::Subprocess
1323        );
1324
1325        std::fs::write(
1326            dir.join("project.toml"),
1327            "[sandbox]
1328mode = \"vm\"
1329",
1330        )
1331        .unwrap();
1332        let error = load_config(&paths_in(&dir), &Overrides::default()).unwrap_err();
1333        assert!(matches!(error, ConfigError::Invalid { .. }), "{error:?}");
1334    }
1335}