Skip to main content

agent86_core/
config.rs

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