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