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