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}
781
782impl Default for ProviderConfig {
783    fn default() -> Self {
784        Self {
785            api_key_env: None,
786            base_url: None,
787            num_ctx: None,
788            num_ctx_max: None,
789            connect_timeout_s: default_connect_timeout_s(),
790            read_timeout_s: default_read_timeout_s(),
791            max_retries: default_max_retries(),
792            max_tokens: None,
793            prompt_cache: true,
794            routing: None,
795            temperature: None,
796            adapter: None,
797            store: false,
798        }
799    }
800}
801
802impl Config {
803    /// The output cap for one call: the provider's `max_tokens`, else `limits.max_output_tokens`.
804    pub fn max_output_tokens_for(&self, provider: &str) -> u32 {
805        self.providers
806            .get(provider)
807            .and_then(|config| config.max_tokens)
808            .filter(|&cap| cap > 0)
809            .unwrap_or(if self.limits.max_output_tokens > 0 {
810                self.limits.max_output_tokens
811            } else {
812                8192
813            })
814    }
815}
816
817/// Where the user and project config files live.
818#[derive(Debug, Clone, PartialEq, Eq)]
819pub struct ConfigPaths {
820    pub user: Option<PathBuf>,
821    pub project: PathBuf,
822    /// Whether the project file's settings that need trust count (beyond Python;
823    /// see `crate::trust`).
824    pub project_trust: ProjectTrust,
825}
826
827/// How far the project config file is trusted (beyond Python, which honors all of
828/// it). A file in a repository someone else wrote can start MCP servers, send API
829/// keys to a server of its choosing, or turn approvals off, so only the settings in
830/// [`crate::trust::TRUST_FREE`] count until the user trusts it.
831#[derive(Debug, Clone, Copy, PartialEq, Eq)]
832pub enum ProjectTrust {
833    /// Every setting counts: the user trusted this file, or the run said to.
834    Trusted,
835    /// Only the settings that need no trust; the rest are left out and listed in
836    /// [`Config::untrusted`].
837    Restricted,
838}
839
840impl ConfigPaths {
841    /// `~/.agent86/config.toml` and `./.agent86/config.toml`, as in Python. The
842    /// project file starts restricted; `crate::trust::decide` says otherwise.
843    pub fn discover() -> Self {
844        Self {
845            user: home_dir().map(|home| home.join(".agent86").join("config.toml")),
846            project: Path::new(".agent86").join("config.toml"),
847            project_trust: ProjectTrust::Restricted,
848        }
849    }
850}
851
852/// The overrides that sit above the config files.
853#[derive(Debug, Clone, Default, PartialEq, Eq)]
854pub struct Overrides {
855    /// `AGENT86_MODEL`.
856    pub env_model: Option<String>,
857    /// `AGENT86_SANDBOX`.
858    pub env_sandbox: Option<String>,
859    /// `AGENT86_APPROVAL`.
860    pub env_approval: Option<String>,
861    /// `AGENT86_RUN_OUTPUT` (beyond Python). `run --output` is applied by `run` itself.
862    pub env_run_output: Option<String>,
863    /// `--model`.
864    pub model: Option<String>,
865    /// `--sandbox`.
866    pub sandbox: Option<String>,
867    /// `--approval`.
868    pub approval: Option<String>,
869}
870
871impl Overrides {
872    /// Read the supported `AGENT86_*` environment variables; empty values are ignored.
873    /// `model`, `sandbox`, and `approval` are the `--model`, `--sandbox`, and
874    /// `--approval` flags.
875    pub fn from_env(
876        model: Option<String>,
877        sandbox: Option<String>,
878        approval: Option<String>,
879    ) -> Self {
880        Self {
881            env_model: non_empty_env("AGENT86_MODEL"),
882            env_sandbox: non_empty_env("AGENT86_SANDBOX"),
883            env_approval: non_empty_env("AGENT86_APPROVAL"),
884            env_run_output: non_empty_env("AGENT86_RUN_OUTPUT"),
885            model,
886            sandbox,
887            approval,
888        }
889    }
890}
891
892#[derive(Debug, Clone, PartialEq, Eq, Error)]
893pub enum ConfigError {
894    #[error("Malformed config at {path}: {detail}")]
895    Malformed { path: String, detail: String },
896    #[error("Invalid config: {detail}")]
897    Invalid { detail: String },
898}
899
900/// Resolve configuration from all layers.
901/// The built-in defaults alone, with no file, environment variable, or flag read:
902/// what [`load_config`] starts from. The embedding API (`crate::sdk`) takes its
903/// defaults from here, so they are never kept in two places.
904pub fn builtin_config() -> Config {
905    let mut merged: Table = DEFAULTS.parse().expect("built-in defaults are valid TOML");
906    accept_legacy_status_line(&mut merged);
907    let mut config: Config = Value::Table(merged.clone())
908        .try_into()
909        .expect("built-in defaults deserialize");
910    validate(&mut config).expect("built-in defaults are valid");
911    config.table = merged;
912    config
913}
914
915pub fn load_config(paths: &ConfigPaths, overrides: &Overrides) -> Result<Config, ConfigError> {
916    let mut merged: Table = DEFAULTS.parse().expect("built-in defaults are valid TOML");
917    let mut sources = Vec::new();
918
919    let mut untrusted = Vec::new();
920    let files = paths.user.iter().chain(std::iter::once(&paths.project));
921    for path in files {
922        let mut layer = normalize(read_toml(path)?);
923        if path == &paths.project && paths.project_trust == ProjectTrust::Restricted {
924            untrusted = crate::trust::take_untrusted(&mut layer)
925                .into_iter()
926                .map(|(key, _)| key)
927                .collect();
928        }
929        if !layer.is_empty() {
930            deep_merge(&mut merged, layer);
931            sources.push(path.clone());
932        }
933    }
934
935    // Environment variables first, then CLI flags, as in Python.
936    let layers = [
937        ("model", "default", &overrides.env_model),
938        ("sandbox", "mode", &overrides.env_sandbox),
939        ("guardrails", "approval", &overrides.env_approval),
940        ("run", "output", &overrides.env_run_output),
941        ("model", "default", &overrides.model),
942        ("sandbox", "mode", &overrides.sandbox),
943        ("guardrails", "approval", &overrides.approval),
944    ];
945    for (section, key, value) in layers {
946        if let Some(value) = value {
947            let mut table = Table::new();
948            table.insert(key.to_owned(), Value::String(value.clone()));
949            let mut layer = Table::new();
950            layer.insert(section.to_owned(), Value::Table(table));
951            deep_merge(&mut merged, layer);
952        }
953    }
954
955    accept_legacy_status_line(&mut merged);
956    let mut config: Config =
957        Value::Table(merged.clone())
958            .try_into()
959            .map_err(|error: toml::de::Error| ConfigError::Invalid {
960                detail: error.message().to_owned(),
961            })?;
962    validate(&mut config)?;
963    config.sources = sources;
964    config.table = merged;
965    config.untrusted = untrusted;
966    Ok(config)
967}
968
969/// One config file as a table, as loading reads it (empty when absent).
970pub(crate) fn read_toml_layer(path: &Path) -> Result<Table, ConfigError> {
971    read_toml(path)
972}
973
974/// A layer with `[mcp.servers.<name>]` mapped onto `mcp_servers`, as loading does.
975pub(crate) fn normalize_layer(layer: Table) -> Table {
976    normalize(layer)
977}
978
979/// Checks serde cannot express, matching the Python schema's constraints.
980/// Map `[mcp.servers.<name>]` onto `mcp_servers`, as Python's `_normalize`.
981fn normalize(mut layer: Table) -> Table {
982    if let Some(Value::Table(mcp)) = layer.get_mut("mcp") {
983        if let Some(servers) = mcp.remove("servers") {
984            let empty = mcp.is_empty();
985            if empty {
986                layer.remove("mcp");
987            }
988            layer.insert("mcp_servers".to_owned(), servers);
989        }
990    }
991    layer
992}
993
994/// Map `[ui] status_line` onto `tui` (an explicit `tui` wins), as Python's
995/// `UIConfig` validator does on the merged layers.
996fn accept_legacy_status_line(merged: &mut Table) {
997    if let Some(Value::Table(ui)) = merged.get_mut("ui") {
998        if let Some(legacy) = ui.remove("status_line") {
999            ui.entry("tui").or_insert(legacy);
1000        }
1001    }
1002}
1003
1004fn validate(config: &mut Config) -> Result<(), ConfigError> {
1005    // Beyond Python: zero would time every command and fetch out at once.
1006    if config.limits.tool_timeout_s == 0 {
1007        return Err(ConfigError::Invalid {
1008            detail: "limits.tool_timeout_s must be at least 1 second, not 0".to_owned(),
1009        });
1010    }
1011    for (name, server) in &mut config.mcp_servers {
1012        server
1013            .resolve_transport()
1014            .map_err(|detail| ConfigError::Invalid {
1015                detail: format!("mcp_servers.{name}: {detail}"),
1016            })?;
1017    }
1018    for (model, price) in &config.pricing.models {
1019        for (field, value) in [
1020            ("input_per_mtok", price.input_per_mtok),
1021            ("output_per_mtok", price.output_per_mtok),
1022        ] {
1023            if !(value >= 0.0 && value.is_finite()) {
1024                return Err(ConfigError::Invalid {
1025                    detail: format!(
1026                        "pricing.models.\"{model}\".{field} must be a non-negative number, not {value}"
1027                    ),
1028                });
1029            }
1030        }
1031    }
1032    Ok(())
1033}
1034
1035fn read_toml(path: &Path) -> Result<Table, ConfigError> {
1036    let text = match std::fs::read_to_string(path) {
1037        Ok(text) => text,
1038        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Table::new()),
1039        Err(error) => {
1040            return Err(ConfigError::Malformed {
1041                path: path.display().to_string(),
1042                detail: error.to_string(),
1043            })
1044        }
1045    };
1046    text.parse()
1047        .map_err(|error: toml::de::Error| ConfigError::Malformed {
1048            path: path.display().to_string(),
1049            detail: error.to_string().trim_end().to_owned(),
1050        })
1051}
1052
1053/// Recursively merge `overlay` into `base`; tables merge, everything else replaces.
1054fn deep_merge(base: &mut Table, overlay: Table) {
1055    for (key, value) in overlay {
1056        match (base.get_mut(&key), value) {
1057            (Some(Value::Table(existing)), Value::Table(incoming)) => {
1058                deep_merge(existing, incoming)
1059            }
1060            (_, value) => {
1061                base.insert(key, value);
1062            }
1063        }
1064    }
1065}
1066
1067fn non_empty_env(name: &str) -> Option<String> {
1068    std::env::var(name).ok().filter(|value| !value.is_empty())
1069}
1070
1071/// The home directory as Python's `Path.home()` resolves it.
1072pub fn home_dir() -> Option<PathBuf> {
1073    let variable = if cfg!(windows) { "USERPROFILE" } else { "HOME" };
1074    std::env::var_os(variable)
1075        .filter(|value| !value.is_empty())
1076        .map(PathBuf::from)
1077}
1078
1079fn default_connect_timeout_s() -> f64 {
1080    10.0
1081}
1082
1083fn default_read_timeout_s() -> f64 {
1084    300.0
1085}
1086
1087fn default_max_retries() -> u32 {
1088    2
1089}
1090
1091fn default_true() -> bool {
1092    true
1093}
1094
1095#[cfg(test)]
1096mod tests {
1097    use super::*;
1098
1099    fn paths_in(dir: &Path) -> ConfigPaths {
1100        ConfigPaths {
1101            user: Some(dir.join("user.toml")),
1102            project: dir.join("project.toml"),
1103            project_trust: crate::config::ProjectTrust::Trusted,
1104        }
1105    }
1106
1107    fn temp_dir(name: &str) -> PathBuf {
1108        let dir =
1109            std::env::temp_dir().join(format!("agent86-config-{name}-{}", std::process::id()));
1110        let _ = std::fs::remove_dir_all(&dir);
1111        std::fs::create_dir_all(&dir).unwrap();
1112        dir
1113    }
1114
1115    #[test]
1116    fn a_zero_tool_timeout_is_invalid() {
1117        let dir = temp_dir("timeout");
1118        let paths = paths_in(&dir);
1119        std::fs::write(&paths.project, "[limits]\ntool_timeout_s = 0\n").unwrap();
1120        let error = load_config(&paths, &Overrides::default()).unwrap_err();
1121        assert_eq!(
1122            error.to_string(),
1123            "Invalid config: limits.tool_timeout_s must be at least 1 second, not 0"
1124        );
1125        std::fs::write(&paths.project, "[limits]\ntool_timeout_s = 1\n").unwrap();
1126        assert_eq!(
1127            load_config(&paths, &Overrides::default())
1128                .unwrap()
1129                .limits
1130                .tool_timeout_s,
1131            1
1132        );
1133    }
1134
1135    #[test]
1136    fn ui_settings_default_and_accept_the_legacy_status_line_key() {
1137        let dir = temp_dir("ui");
1138        let paths = paths_in(&dir);
1139        let config = load_config(&paths, &Overrides::default()).unwrap();
1140        assert!(config.ui.tui);
1141        assert_eq!(config.ui.history_file, "~/.agent86/history");
1142        assert_eq!(config.ui.history_size, 1000);
1143        assert_eq!(config.tools.mention_max_bytes, 200_000);
1144        assert_eq!(config.model.router, RouterMode::Off);
1145        assert_eq!(config.model.route.cheap, "ollama:llama3.1");
1146
1147        // Pre-v0.6 configs spelled `tui` as `status_line`...
1148        std::fs::write(&paths.project, "[ui]\nstatus_line = false\n").unwrap();
1149        assert!(!load_config(&paths, &Overrides::default()).unwrap().ui.tui);
1150        // ...and an explicit `tui` in any layer wins over it.
1151        std::fs::write(dir.join("user.toml"), "[ui]\ntui = true\n").unwrap();
1152        let config = load_config(&paths, &Overrides::default()).unwrap();
1153        assert!(config.ui.tui);
1154        assert!(!config.table["ui"]
1155            .as_table()
1156            .unwrap()
1157            .contains_key("status_line"));
1158        let _ = std::fs::remove_dir_all(&dir);
1159    }
1160
1161    #[test]
1162    fn thinking_and_tool_use_default_to_summary_and_take_the_three_levels() {
1163        let dir = temp_dir("display-levels");
1164        let paths = paths_in(&dir);
1165        let config = load_config(&paths, &Overrides::default()).unwrap();
1166        assert_eq!(config.ui.thinking, DisplayLevel::Summary);
1167        assert_eq!(config.ui.tool_use, DisplayLevel::Summary);
1168
1169        std::fs::write(
1170            &paths.project,
1171            "[ui]\nthinking = \"full\"\ntool_use = \"hidden\"\n",
1172        )
1173        .unwrap();
1174        let config = load_config(&paths, &Overrides::default()).unwrap();
1175        assert_eq!(config.ui.thinking, DisplayLevel::Full);
1176        assert_eq!(config.ui.tool_use, DisplayLevel::Hidden);
1177
1178        // Anything else is refused, naming what is allowed.
1179        std::fs::write(&paths.project, "[ui]\nthinking = \"loud\"\n").unwrap();
1180        let error = load_config(&paths, &Overrides::default())
1181            .unwrap_err()
1182            .to_string();
1183        assert!(
1184            error.contains("loud") && error.contains("full") && error.contains("hidden"),
1185            "{error}"
1186        );
1187        let _ = std::fs::remove_dir_all(&dir);
1188    }
1189
1190    #[test]
1191    fn agent86ui_defaults_to_auto_without_remote_media() {
1192        let dir = temp_dir("agent86ui-settings");
1193        let paths = paths_in(&dir);
1194        let config = load_config(&paths, &Overrides::default()).unwrap();
1195        assert_eq!(config.ui.agent86ui, Agent86UiMode::Auto);
1196        assert!(!config.ui.agent86ui_remote_media);
1197
1198        std::fs::write(
1199            &paths.project,
1200            "[ui]\nagent86ui = \"off\"\nagent86ui_remote_media = true\n",
1201        )
1202        .unwrap();
1203        let config = load_config(&paths, &Overrides::default()).unwrap();
1204        assert_eq!(config.ui.agent86ui, Agent86UiMode::Off);
1205        assert!(config.ui.agent86ui_remote_media);
1206
1207        std::fs::write(&paths.project, "[ui]\nagent86ui = \"on\"\n").unwrap();
1208        let error = load_config(&paths, &Overrides::default())
1209            .unwrap_err()
1210            .to_string();
1211        assert!(error.contains("auto") && error.contains("off"), "{error}");
1212        let _ = std::fs::remove_dir_all(&dir);
1213    }
1214
1215    #[test]
1216    fn ask_user_defaults_to_auto_and_can_be_turned_off() {
1217        let dir = temp_dir("ask-user-setting");
1218        let paths = paths_in(&dir);
1219        let config = load_config(&paths, &Overrides::default()).unwrap();
1220        assert_eq!(config.ui.ask_user, AskUserMode::Auto);
1221        std::fs::write(&paths.project, "[ui]\nask_user = \"off\"\n").unwrap();
1222        let config = load_config(&paths, &Overrides::default()).unwrap();
1223        assert_eq!(config.ui.ask_user, AskUserMode::Off);
1224        let _ = std::fs::remove_dir_all(&dir);
1225    }
1226
1227    #[test]
1228    fn display_levels_parse_cycle_and_name_themselves() {
1229        assert_eq!(DisplayLevel::parse(" Hidden "), Some(DisplayLevel::Hidden));
1230        assert_eq!(DisplayLevel::parse("loud"), None);
1231        let cycle: Vec<&str> =
1232            std::iter::successors(Some(DisplayLevel::Full), |level| Some(level.next()))
1233                .take(4)
1234                .map(DisplayLevel::as_str)
1235                .collect();
1236        assert_eq!(cycle, ["full", "summary", "hidden", "full"]);
1237    }
1238
1239    #[test]
1240    fn defaults_include_the_builtin_providers() {
1241        let dir = temp_dir("defaults");
1242        let config = load_config(&paths_in(&dir), &Overrides::default()).unwrap();
1243
1244        assert_eq!(config.model.default, "anthropic:claude-opus-4-8");
1245        let openrouter = &config.providers["openrouter"];
1246        assert_eq!(
1247            openrouter.api_key_env.as_deref(),
1248            Some("OPENROUTER_API_KEY")
1249        );
1250        assert_eq!(
1251            openrouter.base_url.as_deref(),
1252            Some("https://openrouter.ai/api/v1")
1253        );
1254        assert_eq!(openrouter.read_timeout_s, 300.0);
1255        assert_eq!(config.max_output_tokens_for("openrouter"), 8192);
1256        assert!(config.sources.is_empty());
1257        assert_eq!(openrouter.routing, None);
1258    }
1259
1260    #[test]
1261    fn a_routing_table_is_read_as_json() {
1262        let dir = temp_dir("routing");
1263        let paths = paths_in(&dir);
1264        std::fs::write(
1265            &paths.project,
1266            "[providers.openrouter.routing]\nignore = [\"Phala\"]\nallow_fallbacks = true\n",
1267        )
1268        .unwrap();
1269        let config = load_config(&paths, &Overrides::default()).unwrap();
1270        let routing = config.providers["openrouter"].routing.clone().unwrap();
1271        assert_eq!(
1272            serde_json::Value::Object(routing),
1273            serde_json::json!({"ignore": ["Phala"], "allow_fallbacks": true})
1274        );
1275        let _ = std::fs::remove_dir_all(&dir);
1276    }
1277
1278    #[test]
1279    fn layers_deep_merge_and_overrides_win() {
1280        let dir = temp_dir("layers");
1281        std::fs::write(
1282            dir.join("user.toml"),
1283            "[model]\ndefault = \"openrouter:a\"\n[providers.openrouter]\nmax_tokens = 512\n",
1284        )
1285        .unwrap();
1286        std::fs::write(
1287            dir.join("project.toml"),
1288            "[providers.openrouter]\nbase_url = \"http://localhost:9\"\n[providers.mine]\nbase_url = \"http://x\"\n[tools]\nanything = 1\n",
1289        )
1290        .unwrap();
1291
1292        let config = load_config(&paths_in(&dir), &Overrides::default()).unwrap();
1293        let openrouter = &config.providers["openrouter"];
1294        assert_eq!(config.model.default, "openrouter:a");
1295        assert_eq!(openrouter.base_url.as_deref(), Some("http://localhost:9"));
1296        assert_eq!(
1297            openrouter.api_key_env.as_deref(),
1298            Some("OPENROUTER_API_KEY")
1299        );
1300        assert_eq!(config.max_output_tokens_for("openrouter"), 512);
1301        assert!(config.providers.contains_key("groq"));
1302        assert_eq!(config.providers["mine"].max_retries, 2);
1303        assert_eq!(config.sources.len(), 2);
1304
1305        let env = Overrides {
1306            env_model: Some("groq:b".to_owned()),
1307            ..Overrides::default()
1308        };
1309        assert_eq!(
1310            load_config(&paths_in(&dir), &env).unwrap().model.default,
1311            "groq:b"
1312        );
1313
1314        let flag = Overrides {
1315            env_model: Some("groq:b".to_owned()),
1316            model: Some("openai:c".to_owned()),
1317            ..Overrides::default()
1318        };
1319        assert_eq!(
1320            load_config(&paths_in(&dir), &flag).unwrap().model.default,
1321            "openai:c"
1322        );
1323    }
1324
1325    #[test]
1326    fn malformed_toml_names_the_file() {
1327        let dir = temp_dir("malformed");
1328        std::fs::write(dir.join("project.toml"), "[model\n").unwrap();
1329
1330        let error = load_config(&paths_in(&dir), &Overrides::default()).unwrap_err();
1331        let ConfigError::Malformed { path, .. } = &error else {
1332            panic!("{error:?}");
1333        };
1334        assert!(path.ends_with("project.toml"));
1335        assert!(error.to_string().starts_with("Malformed config at "));
1336    }
1337
1338    #[test]
1339    fn pricing_overrides_load_and_negative_prices_are_rejected() {
1340        let dir = temp_dir("pricing");
1341        std::fs::write(
1342            dir.join("project.toml"),
1343            "[pricing.models.\"openrouter:openai/gpt-4o-mini\"]\ninput_per_mtok = 0.15\noutput_per_mtok = 0.6\n",
1344        )
1345        .unwrap();
1346        let config = load_config(&paths_in(&dir), &Overrides::default()).unwrap();
1347        let price = config.pricing.models["openrouter:openai/gpt-4o-mini"];
1348        assert_eq!(price.input_per_mtok, 0.15);
1349        assert_eq!(price.output_per_mtok, 0.6);
1350
1351        std::fs::write(
1352            dir.join("project.toml"),
1353            "[pricing.models.cheap]\ninput_per_mtok = -1\noutput_per_mtok = 0\n",
1354        )
1355        .unwrap();
1356        let error = load_config(&paths_in(&dir), &Overrides::default()).unwrap_err();
1357        assert!(matches!(error, ConfigError::Invalid { .. }), "{error:?}");
1358        assert!(error.to_string().contains("input_per_mtok"), "{error}");
1359    }
1360
1361    #[test]
1362    fn sandbox_mode_defaults_to_subprocess_and_rejects_unknown_values() {
1363        let dir = temp_dir("sandbox");
1364        let config = load_config(&paths_in(&dir), &Overrides::default()).unwrap();
1365        assert_eq!(config.sandbox.mode, SandboxMode::Subprocess);
1366
1367        let env = Overrides {
1368            env_sandbox: Some("docker".to_owned()),
1369            ..Overrides::default()
1370        };
1371        assert_eq!(
1372            load_config(&paths_in(&dir), &env).unwrap().sandbox.mode,
1373            SandboxMode::Docker
1374        );
1375        // `--sandbox` wins over `AGENT86_SANDBOX`, as Python's CLI overrides do.
1376        let flag = Overrides {
1377            sandbox: Some("subprocess".to_owned()),
1378            ..env
1379        };
1380        assert_eq!(
1381            load_config(&paths_in(&dir), &flag).unwrap().sandbox.mode,
1382            SandboxMode::Subprocess
1383        );
1384
1385        std::fs::write(
1386            dir.join("project.toml"),
1387            "[sandbox]
1388mode = \"vm\"
1389",
1390        )
1391        .unwrap();
1392        let error = load_config(&paths_in(&dir), &Overrides::default()).unwrap_err();
1393        assert!(matches!(error, ConfigError::Invalid { .. }), "{error:?}");
1394    }
1395}