1use crate::types::ApprovalMode;
20use serde::Deserialize;
21use std::collections::BTreeMap;
22use std::path::{Path, PathBuf};
23use thiserror::Error;
24use toml::{Table, Value};
25
26const DEFAULTS: &str = r#"
28[model]
29default = "anthropic:claude-opus-4-8"
30router = "off"
31
32[model.route]
33cheap = "ollama:llama3.1"
34frontier = "anthropic:claude-opus-4-8"
35
36[limits]
37max_steps = 40
38max_cost_usd = 5.0
39max_wall_clock_s = 900
40max_consecutive_errors = 3
41max_context_tokens = 0
42max_output_tokens = 8192
43context_reserve_tokens = 4096
44compaction = "summarize"
45parallel_tools = true
46tool_timeout_s = 60
47
48[sandbox]
49mode = "subprocess"
50docker_image = "python:3.12-slim"
51docker_memory = "512m"
52docker_cpus = "1"
53docker_network = false
54env_passthrough = []
55
56[mcp]
57enabled = true
58
59[skills]
60enabled = true
61paths = []
62
63[agents]
64enabled = true
65max_depth = 2
66max_steps = 8
67max_parallel = 3
68
69[observability]
70trace = true
71path = "~/.agent86/traces"
72otel = false
73otel_exporter = "otlp"
74redact = "secrets"
75max_field_chars = 2000
76max_trace_bytes = 50000000
77keep_traces = 5
78
79[memory]
80enabled = true
81path = "~/.agent86/memory.db"
82embeddings = "sentence-transformers:all-MiniLM-L6-v2"
83hf_offline = true
84retention_max_episodes = 1000
85retention_max_sessions = 500
86retention_max_age_days = 0.0
87
88[tools]
89web_allow_private = false
90web_max_chars = 8000
91mention_max_bytes = 200000
92
93[ui]
94spinner = true
95history_file = "~/.agent86/history"
96history_size = 1000
97markdown = true
98update_check = true
99thinking = "summary"
100tool_use = "summary"
101agent86ui = "auto"
102agent86ui_remote_media = false
103
104[run]
105output = "final"
106
107[guardrails]
108approval = "ask"
109ingress = "warn"
110egress = "warn"
111scan_observations = true
112
113[providers.anthropic]
114api_key_env = "ANTHROPIC_API_KEY"
115
116[providers.google]
117api_key_env = "GEMINI_API_KEY"
118read_timeout_s = 1200.0
119store = false
120
121[providers.openai]
122api_key_env = "OPENAI_API_KEY"
123base_url = "https://api.openai.com/v1"
124
125[providers.openrouter]
126api_key_env = "OPENROUTER_API_KEY"
127base_url = "https://openrouter.ai/api/v1"
128
129[providers.groq]
130api_key_env = "GROQ_API_KEY"
131base_url = "https://api.groq.com/openai/v1"
132
133[providers.ollama]
134base_url = "http://localhost:11434"
135num_ctx_max = 32768
136
137[providers.llamacpp]
138base_url = "http://localhost:8080"
139
140[providers.vllm]
141base_url = "http://localhost:8000/v1"
142api_key_env = "VLLM_API_KEY"
143
144[providers.lmstudio]
145base_url = "http://localhost:1234/v1"
146api_key_env = "LM_API_TOKEN"
147"#;
148
149#[derive(Debug, Clone, PartialEq, Deserialize)]
150pub struct Config {
151 pub model: ModelConfig,
152 pub limits: LimitsConfig,
153 pub sandbox: SandboxConfig,
154 pub guardrails: GuardrailsConfig,
155 pub tools: ToolsConfig,
156 pub memory: MemoryConfig,
157 pub observability: ObservabilityConfig,
158 pub mcp: McpConfig,
159 pub skills: SkillsConfig,
160 pub agents: AgentsConfig,
161 #[serde(default)]
163 pub mcp_servers: indexmap::IndexMap<String, McpServerConfig>,
164 #[serde(default)]
165 pub providers: indexmap::IndexMap<String, ProviderConfig>,
166 #[serde(default)]
167 pub pricing: PricingConfig,
168 pub ui: UiConfig,
169 pub run: RunConfig,
170 #[serde(skip)]
172 pub table: Table,
173 #[serde(skip)]
175 pub sources: Vec<PathBuf>,
176 #[serde(skip)]
178 pub untrusted: Vec<String>,
179}
180
181#[derive(Debug, Clone, PartialEq, Deserialize)]
182pub struct ModelConfig {
183 pub default: String,
184 pub router: RouterMode,
186 pub route: ModelRoute,
187 #[serde(default)]
190 pub context_window: BTreeMap<String, u64>,
191}
192
193#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
195#[serde(rename_all = "snake_case")]
196pub enum RouterMode {
197 Off,
198 Triage,
199}
200
201impl RouterMode {
202 pub fn as_str(self) -> &'static str {
203 match self {
204 Self::Off => "off",
205 Self::Triage => "triage",
206 }
207 }
208}
209
210#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
212pub struct ModelRoute {
213 pub cheap: String,
214 pub frontier: String,
215}
216
217#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
219pub struct UiConfig {
220 #[serde(default = "default_true")]
223 pub tui: bool,
224 pub spinner: bool,
225 pub history_file: String,
227 pub history_size: i64,
229 pub markdown: bool,
231 #[serde(default = "default_true")]
234 pub update_check: bool,
235 #[serde(default = "default_summary")]
237 pub thinking: DisplayLevel,
238 #[serde(default = "default_summary")]
240 pub tool_use: DisplayLevel,
241 #[serde(default)]
244 pub agent86ui: Agent86UiMode,
245 #[serde(default)]
248 pub agent86ui_remote_media: bool,
249}
250
251#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
254#[serde(rename_all = "lowercase")]
255pub enum Agent86UiMode {
256 #[default]
257 Auto,
258 Off,
259}
260
261#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
263pub struct RunConfig {
264 #[serde(default = "default_run_output")]
266 pub output: RunOutputMode,
267}
268
269fn default_run_output() -> RunOutputMode {
270 RunOutputMode::Final
271}
272
273#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
276#[serde(rename_all = "lowercase")]
277pub enum RunOutputMode {
278 Final,
281 Full,
283 Quiet,
285}
286
287impl RunOutputMode {
288 pub const ALL: [Self; 3] = [Self::Final, Self::Full, Self::Quiet];
289
290 pub fn as_str(self) -> &'static str {
291 match self {
292 Self::Final => "final",
293 Self::Full => "full",
294 Self::Quiet => "quiet",
295 }
296 }
297
298 pub fn parse(text: &str) -> Option<Self> {
299 Self::ALL.into_iter().find(|mode| mode.as_str() == text)
300 }
301}
302
303#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
306#[serde(rename_all = "lowercase")]
307pub enum DisplayLevel {
308 Full,
310 Summary,
312 Hidden,
314}
315
316impl DisplayLevel {
317 pub const ALL: [Self; 3] = [Self::Full, Self::Summary, Self::Hidden];
318
319 pub fn as_str(self) -> &'static str {
320 match self {
321 Self::Full => "full",
322 Self::Summary => "summary",
323 Self::Hidden => "hidden",
324 }
325 }
326
327 pub fn parse(text: &str) -> Option<Self> {
328 Self::ALL
329 .into_iter()
330 .find(|level| level.as_str() == text.trim().to_lowercase())
331 }
332
333 pub fn next(self) -> Self {
335 match self {
336 Self::Full => Self::Summary,
337 Self::Summary => Self::Hidden,
338 Self::Hidden => Self::Full,
339 }
340 }
341}
342
343fn default_summary() -> DisplayLevel {
344 DisplayLevel::Summary
345}
346
347#[derive(Debug, Clone, PartialEq, Deserialize)]
348pub struct LimitsConfig {
349 pub max_steps: u32,
351 pub max_cost_usd: f64,
353 pub max_wall_clock_s: u64,
355 pub max_consecutive_errors: u32,
357 pub max_context_tokens: u64,
360 pub max_output_tokens: u32,
361 pub context_reserve_tokens: u64,
364 pub compaction: CompactionMode,
366 pub parallel_tools: bool,
368 pub tool_timeout_s: u64,
370}
371
372#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
374pub struct SkillsConfig {
375 pub enabled: bool,
376 pub paths: Vec<String>,
378}
379
380#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
382pub struct AgentsConfig {
383 pub enabled: bool,
384 pub max_depth: u32,
386 pub max_steps: u32,
388 #[serde(default = "default_max_parallel")]
392 pub max_parallel: u32,
393}
394
395pub const MAX_PARALLEL_CEILING: u32 = 8;
398
399fn default_max_parallel() -> u32 {
400 3
401}
402
403impl AgentsConfig {
404 pub fn parallel_limit(&self) -> usize {
406 self.max_parallel.clamp(1, MAX_PARALLEL_CEILING) as usize
407 }
408}
409
410#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
412pub struct McpConfig {
413 pub enabled: bool,
414}
415
416#[derive(Debug, Clone, PartialEq, Deserialize)]
418pub struct McpServerConfig {
419 #[serde(default)]
420 pub command: Option<String>,
421 #[serde(default)]
422 pub args: Vec<String>,
423 #[serde(default)]
424 pub env: indexmap::IndexMap<String, String>,
425 #[serde(default)]
426 pub url: Option<String>,
427 #[serde(default)]
428 pub headers: indexmap::IndexMap<String, String>,
429 #[serde(default)]
431 pub transport: Option<String>,
432 #[serde(default = "default_true")]
433 pub enabled: bool,
434 #[serde(default = "default_mcp_connect_timeout_s")]
435 pub connect_timeout_s: f64,
436 #[serde(default = "default_mcp_call_timeout_s")]
437 pub call_timeout_s: f64,
438 #[serde(default = "default_mcp_max_result_chars")]
439 pub max_result_chars: usize,
440 #[serde(default)]
445 pub defaults: indexmap::IndexMap<String, serde_json::Map<String, serde_json::Value>>,
446}
447
448impl McpServerConfig {
449 pub fn resolve_transport(&mut self) -> Result<(), String> {
451 let (has_command, has_url) = (
452 self.command.as_deref().is_some_and(|c| !c.is_empty()),
453 self.url.as_deref().is_some_and(|u| !u.is_empty()),
454 );
455 if has_command && has_url {
456 return Err("MCP server sets both 'command' and 'url'; use one transport".to_owned());
457 }
458 if !has_command && !has_url {
459 return Err("MCP server needs 'command' (stdio) or 'url' (sse/http)".to_owned());
460 }
461 let given = self
462 .transport
463 .clone()
464 .unwrap_or_else(|| if has_command { "stdio" } else { "http" }.to_owned());
465 let mut transport = given.to_lowercase().replace('-', "_");
466 if transport == "streamable_http" {
467 transport = "http".to_owned();
468 }
469 if !matches!(transport.as_str(), "stdio" | "sse" | "http") {
470 return Err(format!("unknown MCP transport '{given}' (stdio|sse|http)"));
471 }
472 if transport == "stdio" && !has_command {
473 return Err("stdio transport requires 'command'".to_owned());
474 }
475 if transport != "stdio" && !has_url {
476 return Err(format!("{transport} transport requires 'url'"));
477 }
478 for (field, value) in [
479 ("connect_timeout_s", self.connect_timeout_s),
480 ("call_timeout_s", self.call_timeout_s),
481 ] {
482 if !(value > 0.0 && value.is_finite()) {
483 return Err(format!("{field} must be greater than 0"));
484 }
485 }
486 if self.max_result_chars == 0 {
487 return Err("max_result_chars must be greater than 0".to_owned());
488 }
489 self.transport = Some(transport);
490 Ok(())
491 }
492
493 pub fn transport(&self) -> &str {
495 self.transport.as_deref().unwrap_or("stdio")
496 }
497}
498
499fn default_mcp_connect_timeout_s() -> f64 {
500 30.0
501}
502
503fn default_mcp_call_timeout_s() -> f64 {
504 120.0
505}
506
507fn default_mcp_max_result_chars() -> usize {
508 8000
509}
510
511#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
513pub struct ObservabilityConfig {
514 pub trace: bool,
516 pub path: String,
518 #[serde(default)]
520 pub otel: bool,
521 #[serde(default)]
523 pub otel_exporter: OtelExporter,
524 #[serde(default)]
526 pub otel_endpoint: Option<String>,
527 pub redact: RedactMode,
528 pub max_field_chars: usize,
530 pub max_trace_bytes: u64,
532 pub keep_traces: usize,
534}
535
536#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
538#[serde(rename_all = "snake_case")]
539pub enum OtelExporter {
540 #[default]
542 Otlp,
543 Console,
545 None,
547}
548
549#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
551#[serde(rename_all = "snake_case")]
552pub enum RedactMode {
553 Secrets,
555 None,
557}
558
559#[derive(Debug, Clone, PartialEq, Deserialize)]
561pub struct MemoryConfig {
562 pub enabled: bool,
563 pub path: String,
565 pub embeddings: String,
568 pub hf_offline: bool,
570 pub retention_max_episodes: i64,
573 pub retention_max_sessions: i64,
574 pub retention_max_age_days: f64,
575}
576
577#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
579pub struct ToolsConfig {
580 pub web_allow_private: bool,
582 #[serde(default = "crate::tools::web::default_user_agent")]
584 pub web_user_agent: String,
585 pub web_max_chars: usize,
587 pub mention_max_bytes: u64,
589}
590
591#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
593pub struct GuardrailsConfig {
594 pub approval: ApprovalMode,
596 pub ingress: IngressMode,
598 pub egress: EgressMode,
600 pub scan_observations: bool,
602}
603
604#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
606#[serde(rename_all = "snake_case")]
607pub enum IngressMode {
608 Off,
609 Warn,
611 Block,
613}
614
615#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
618#[serde(rename_all = "snake_case")]
619pub enum CompactionMode {
620 Summarize,
622 Drop,
624}
625
626#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
628#[serde(rename_all = "snake_case")]
629pub enum EgressMode {
630 Off,
631 Warn,
633 Redact,
635}
636
637#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
639pub struct SandboxConfig {
640 pub mode: SandboxMode,
641 pub docker_image: String,
642 pub docker_memory: String,
643 pub docker_cpus: String,
644 pub docker_network: bool,
646 pub env_passthrough: Vec<String>,
649}
650
651#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
652#[serde(rename_all = "snake_case")]
653pub enum SandboxMode {
654 Subprocess,
656 Docker,
658}
659
660impl SandboxMode {
661 pub fn as_str(self) -> &'static str {
663 match self {
664 Self::Subprocess => "subprocess",
665 Self::Docker => "docker",
666 }
667 }
668}
669
670#[derive(Debug, Clone, Default, PartialEq, Deserialize)]
676pub struct PricingConfig {
677 #[serde(default)]
678 pub models: BTreeMap<String, ModelPrice>,
679}
680
681#[derive(Debug, Clone, Copy, PartialEq, Deserialize)]
683pub struct ModelPrice {
684 pub input_per_mtok: f64,
685 pub output_per_mtok: f64,
686}
687
688#[derive(Debug, Clone, PartialEq, Deserialize)]
690pub struct ProviderConfig {
691 #[serde(default)]
692 pub api_key_env: Option<String>,
693 #[serde(default)]
694 pub base_url: Option<String>,
695 #[serde(default)]
698 pub num_ctx: Option<u32>,
699 #[serde(default)]
702 pub num_ctx_max: Option<u32>,
703 #[serde(default = "default_connect_timeout_s")]
705 pub connect_timeout_s: f64,
706 #[serde(default = "default_read_timeout_s")]
708 pub read_timeout_s: f64,
709 #[serde(default = "default_max_retries")]
710 pub max_retries: u32,
711 #[serde(default)]
712 pub max_tokens: Option<u32>,
713 #[serde(default = "default_true")]
714 pub prompt_cache: bool,
715 #[serde(default)]
720 pub routing: Option<serde_json::Map<String, serde_json::Value>>,
721 #[serde(default)]
727 pub adapter: Option<String>,
728 #[serde(default)]
732 pub store: bool,
733}
734
735impl Default for ProviderConfig {
736 fn default() -> Self {
737 Self {
738 api_key_env: None,
739 base_url: None,
740 num_ctx: None,
741 num_ctx_max: None,
742 connect_timeout_s: default_connect_timeout_s(),
743 read_timeout_s: default_read_timeout_s(),
744 max_retries: default_max_retries(),
745 max_tokens: None,
746 prompt_cache: true,
747 routing: None,
748 adapter: None,
749 store: false,
750 }
751 }
752}
753
754impl Config {
755 pub fn max_output_tokens_for(&self, provider: &str) -> u32 {
757 self.providers
758 .get(provider)
759 .and_then(|config| config.max_tokens)
760 .filter(|&cap| cap > 0)
761 .unwrap_or(if self.limits.max_output_tokens > 0 {
762 self.limits.max_output_tokens
763 } else {
764 8192
765 })
766 }
767}
768
769#[derive(Debug, Clone, PartialEq, Eq)]
771pub struct ConfigPaths {
772 pub user: Option<PathBuf>,
773 pub project: PathBuf,
774 pub project_trust: ProjectTrust,
777}
778
779#[derive(Debug, Clone, Copy, PartialEq, Eq)]
784pub enum ProjectTrust {
785 Trusted,
787 Restricted,
790}
791
792impl ConfigPaths {
793 pub fn discover() -> Self {
796 Self {
797 user: home_dir().map(|home| home.join(".agent86").join("config.toml")),
798 project: Path::new(".agent86").join("config.toml"),
799 project_trust: ProjectTrust::Restricted,
800 }
801 }
802}
803
804#[derive(Debug, Clone, Default, PartialEq, Eq)]
806pub struct Overrides {
807 pub env_model: Option<String>,
809 pub env_sandbox: Option<String>,
811 pub env_approval: Option<String>,
813 pub env_run_output: Option<String>,
815 pub model: Option<String>,
817 pub sandbox: Option<String>,
819 pub approval: Option<String>,
821}
822
823impl Overrides {
824 pub fn from_env(
828 model: Option<String>,
829 sandbox: Option<String>,
830 approval: Option<String>,
831 ) -> Self {
832 Self {
833 env_model: non_empty_env("AGENT86_MODEL"),
834 env_sandbox: non_empty_env("AGENT86_SANDBOX"),
835 env_approval: non_empty_env("AGENT86_APPROVAL"),
836 env_run_output: non_empty_env("AGENT86_RUN_OUTPUT"),
837 model,
838 sandbox,
839 approval,
840 }
841 }
842}
843
844#[derive(Debug, Clone, PartialEq, Eq, Error)]
845pub enum ConfigError {
846 #[error("Malformed config at {path}: {detail}")]
847 Malformed { path: String, detail: String },
848 #[error("Invalid config: {detail}")]
849 Invalid { detail: String },
850}
851
852pub fn builtin_config() -> Config {
857 let mut merged: Table = DEFAULTS.parse().expect("built-in defaults are valid TOML");
858 accept_legacy_status_line(&mut merged);
859 let mut config: Config = Value::Table(merged.clone())
860 .try_into()
861 .expect("built-in defaults deserialize");
862 validate(&mut config).expect("built-in defaults are valid");
863 config.table = merged;
864 config
865}
866
867pub fn load_config(paths: &ConfigPaths, overrides: &Overrides) -> Result<Config, ConfigError> {
868 let mut merged: Table = DEFAULTS.parse().expect("built-in defaults are valid TOML");
869 let mut sources = Vec::new();
870
871 let mut untrusted = Vec::new();
872 let files = paths.user.iter().chain(std::iter::once(&paths.project));
873 for path in files {
874 let mut layer = normalize(read_toml(path)?);
875 if path == &paths.project && paths.project_trust == ProjectTrust::Restricted {
876 untrusted = crate::trust::take_untrusted(&mut layer)
877 .into_iter()
878 .map(|(key, _)| key)
879 .collect();
880 }
881 if !layer.is_empty() {
882 deep_merge(&mut merged, layer);
883 sources.push(path.clone());
884 }
885 }
886
887 let layers = [
889 ("model", "default", &overrides.env_model),
890 ("sandbox", "mode", &overrides.env_sandbox),
891 ("guardrails", "approval", &overrides.env_approval),
892 ("run", "output", &overrides.env_run_output),
893 ("model", "default", &overrides.model),
894 ("sandbox", "mode", &overrides.sandbox),
895 ("guardrails", "approval", &overrides.approval),
896 ];
897 for (section, key, value) in layers {
898 if let Some(value) = value {
899 let mut table = Table::new();
900 table.insert(key.to_owned(), Value::String(value.clone()));
901 let mut layer = Table::new();
902 layer.insert(section.to_owned(), Value::Table(table));
903 deep_merge(&mut merged, layer);
904 }
905 }
906
907 accept_legacy_status_line(&mut merged);
908 let mut config: Config =
909 Value::Table(merged.clone())
910 .try_into()
911 .map_err(|error: toml::de::Error| ConfigError::Invalid {
912 detail: error.message().to_owned(),
913 })?;
914 validate(&mut config)?;
915 config.sources = sources;
916 config.table = merged;
917 config.untrusted = untrusted;
918 Ok(config)
919}
920
921pub(crate) fn read_toml_layer(path: &Path) -> Result<Table, ConfigError> {
923 read_toml(path)
924}
925
926pub(crate) fn normalize_layer(layer: Table) -> Table {
928 normalize(layer)
929}
930
931fn normalize(mut layer: Table) -> Table {
934 if let Some(Value::Table(mcp)) = layer.get_mut("mcp") {
935 if let Some(servers) = mcp.remove("servers") {
936 let empty = mcp.is_empty();
937 if empty {
938 layer.remove("mcp");
939 }
940 layer.insert("mcp_servers".to_owned(), servers);
941 }
942 }
943 layer
944}
945
946fn accept_legacy_status_line(merged: &mut Table) {
949 if let Some(Value::Table(ui)) = merged.get_mut("ui") {
950 if let Some(legacy) = ui.remove("status_line") {
951 ui.entry("tui").or_insert(legacy);
952 }
953 }
954}
955
956fn validate(config: &mut Config) -> Result<(), ConfigError> {
957 if config.limits.tool_timeout_s == 0 {
959 return Err(ConfigError::Invalid {
960 detail: "limits.tool_timeout_s must be at least 1 second, not 0".to_owned(),
961 });
962 }
963 for (name, server) in &mut config.mcp_servers {
964 server
965 .resolve_transport()
966 .map_err(|detail| ConfigError::Invalid {
967 detail: format!("mcp_servers.{name}: {detail}"),
968 })?;
969 }
970 for (model, price) in &config.pricing.models {
971 for (field, value) in [
972 ("input_per_mtok", price.input_per_mtok),
973 ("output_per_mtok", price.output_per_mtok),
974 ] {
975 if !(value >= 0.0 && value.is_finite()) {
976 return Err(ConfigError::Invalid {
977 detail: format!(
978 "pricing.models.\"{model}\".{field} must be a non-negative number, not {value}"
979 ),
980 });
981 }
982 }
983 }
984 Ok(())
985}
986
987fn read_toml(path: &Path) -> Result<Table, ConfigError> {
988 let text = match std::fs::read_to_string(path) {
989 Ok(text) => text,
990 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Table::new()),
991 Err(error) => {
992 return Err(ConfigError::Malformed {
993 path: path.display().to_string(),
994 detail: error.to_string(),
995 })
996 }
997 };
998 text.parse()
999 .map_err(|error: toml::de::Error| ConfigError::Malformed {
1000 path: path.display().to_string(),
1001 detail: error.to_string().trim_end().to_owned(),
1002 })
1003}
1004
1005fn deep_merge(base: &mut Table, overlay: Table) {
1007 for (key, value) in overlay {
1008 match (base.get_mut(&key), value) {
1009 (Some(Value::Table(existing)), Value::Table(incoming)) => {
1010 deep_merge(existing, incoming)
1011 }
1012 (_, value) => {
1013 base.insert(key, value);
1014 }
1015 }
1016 }
1017}
1018
1019fn non_empty_env(name: &str) -> Option<String> {
1020 std::env::var(name).ok().filter(|value| !value.is_empty())
1021}
1022
1023pub fn home_dir() -> Option<PathBuf> {
1025 let variable = if cfg!(windows) { "USERPROFILE" } else { "HOME" };
1026 std::env::var_os(variable)
1027 .filter(|value| !value.is_empty())
1028 .map(PathBuf::from)
1029}
1030
1031fn default_connect_timeout_s() -> f64 {
1032 10.0
1033}
1034
1035fn default_read_timeout_s() -> f64 {
1036 300.0
1037}
1038
1039fn default_max_retries() -> u32 {
1040 2
1041}
1042
1043fn default_true() -> bool {
1044 true
1045}
1046
1047#[cfg(test)]
1048mod tests {
1049 use super::*;
1050
1051 fn paths_in(dir: &Path) -> ConfigPaths {
1052 ConfigPaths {
1053 user: Some(dir.join("user.toml")),
1054 project: dir.join("project.toml"),
1055 project_trust: crate::config::ProjectTrust::Trusted,
1056 }
1057 }
1058
1059 fn temp_dir(name: &str) -> PathBuf {
1060 let dir =
1061 std::env::temp_dir().join(format!("agent86-config-{name}-{}", std::process::id()));
1062 let _ = std::fs::remove_dir_all(&dir);
1063 std::fs::create_dir_all(&dir).unwrap();
1064 dir
1065 }
1066
1067 #[test]
1068 fn a_zero_tool_timeout_is_invalid() {
1069 let dir = temp_dir("timeout");
1070 let paths = paths_in(&dir);
1071 std::fs::write(&paths.project, "[limits]\ntool_timeout_s = 0\n").unwrap();
1072 let error = load_config(&paths, &Overrides::default()).unwrap_err();
1073 assert_eq!(
1074 error.to_string(),
1075 "Invalid config: limits.tool_timeout_s must be at least 1 second, not 0"
1076 );
1077 std::fs::write(&paths.project, "[limits]\ntool_timeout_s = 1\n").unwrap();
1078 assert_eq!(
1079 load_config(&paths, &Overrides::default())
1080 .unwrap()
1081 .limits
1082 .tool_timeout_s,
1083 1
1084 );
1085 }
1086
1087 #[test]
1088 fn ui_settings_default_and_accept_the_legacy_status_line_key() {
1089 let dir = temp_dir("ui");
1090 let paths = paths_in(&dir);
1091 let config = load_config(&paths, &Overrides::default()).unwrap();
1092 assert!(config.ui.tui);
1093 assert_eq!(config.ui.history_file, "~/.agent86/history");
1094 assert_eq!(config.ui.history_size, 1000);
1095 assert_eq!(config.tools.mention_max_bytes, 200_000);
1096 assert_eq!(config.model.router, RouterMode::Off);
1097 assert_eq!(config.model.route.cheap, "ollama:llama3.1");
1098
1099 std::fs::write(&paths.project, "[ui]\nstatus_line = false\n").unwrap();
1101 assert!(!load_config(&paths, &Overrides::default()).unwrap().ui.tui);
1102 std::fs::write(dir.join("user.toml"), "[ui]\ntui = true\n").unwrap();
1104 let config = load_config(&paths, &Overrides::default()).unwrap();
1105 assert!(config.ui.tui);
1106 assert!(!config.table["ui"]
1107 .as_table()
1108 .unwrap()
1109 .contains_key("status_line"));
1110 let _ = std::fs::remove_dir_all(&dir);
1111 }
1112
1113 #[test]
1114 fn thinking_and_tool_use_default_to_summary_and_take_the_three_levels() {
1115 let dir = temp_dir("display-levels");
1116 let paths = paths_in(&dir);
1117 let config = load_config(&paths, &Overrides::default()).unwrap();
1118 assert_eq!(config.ui.thinking, DisplayLevel::Summary);
1119 assert_eq!(config.ui.tool_use, DisplayLevel::Summary);
1120
1121 std::fs::write(
1122 &paths.project,
1123 "[ui]\nthinking = \"full\"\ntool_use = \"hidden\"\n",
1124 )
1125 .unwrap();
1126 let config = load_config(&paths, &Overrides::default()).unwrap();
1127 assert_eq!(config.ui.thinking, DisplayLevel::Full);
1128 assert_eq!(config.ui.tool_use, DisplayLevel::Hidden);
1129
1130 std::fs::write(&paths.project, "[ui]\nthinking = \"loud\"\n").unwrap();
1132 let error = load_config(&paths, &Overrides::default())
1133 .unwrap_err()
1134 .to_string();
1135 assert!(
1136 error.contains("loud") && error.contains("full") && error.contains("hidden"),
1137 "{error}"
1138 );
1139 let _ = std::fs::remove_dir_all(&dir);
1140 }
1141
1142 #[test]
1143 fn agent86ui_defaults_to_auto_without_remote_media() {
1144 let dir = temp_dir("agent86ui-settings");
1145 let paths = paths_in(&dir);
1146 let config = load_config(&paths, &Overrides::default()).unwrap();
1147 assert_eq!(config.ui.agent86ui, Agent86UiMode::Auto);
1148 assert!(!config.ui.agent86ui_remote_media);
1149
1150 std::fs::write(
1151 &paths.project,
1152 "[ui]\nagent86ui = \"off\"\nagent86ui_remote_media = true\n",
1153 )
1154 .unwrap();
1155 let config = load_config(&paths, &Overrides::default()).unwrap();
1156 assert_eq!(config.ui.agent86ui, Agent86UiMode::Off);
1157 assert!(config.ui.agent86ui_remote_media);
1158
1159 std::fs::write(&paths.project, "[ui]\nagent86ui = \"on\"\n").unwrap();
1160 let error = load_config(&paths, &Overrides::default())
1161 .unwrap_err()
1162 .to_string();
1163 assert!(error.contains("auto") && error.contains("off"), "{error}");
1164 let _ = std::fs::remove_dir_all(&dir);
1165 }
1166
1167 #[test]
1168 fn display_levels_parse_cycle_and_name_themselves() {
1169 assert_eq!(DisplayLevel::parse(" Hidden "), Some(DisplayLevel::Hidden));
1170 assert_eq!(DisplayLevel::parse("loud"), None);
1171 let cycle: Vec<&str> =
1172 std::iter::successors(Some(DisplayLevel::Full), |level| Some(level.next()))
1173 .take(4)
1174 .map(DisplayLevel::as_str)
1175 .collect();
1176 assert_eq!(cycle, ["full", "summary", "hidden", "full"]);
1177 }
1178
1179 #[test]
1180 fn defaults_include_the_builtin_providers() {
1181 let dir = temp_dir("defaults");
1182 let config = load_config(&paths_in(&dir), &Overrides::default()).unwrap();
1183
1184 assert_eq!(config.model.default, "anthropic:claude-opus-4-8");
1185 let openrouter = &config.providers["openrouter"];
1186 assert_eq!(
1187 openrouter.api_key_env.as_deref(),
1188 Some("OPENROUTER_API_KEY")
1189 );
1190 assert_eq!(
1191 openrouter.base_url.as_deref(),
1192 Some("https://openrouter.ai/api/v1")
1193 );
1194 assert_eq!(openrouter.read_timeout_s, 300.0);
1195 assert_eq!(config.max_output_tokens_for("openrouter"), 8192);
1196 assert!(config.sources.is_empty());
1197 assert_eq!(openrouter.routing, None);
1198 }
1199
1200 #[test]
1201 fn a_routing_table_is_read_as_json() {
1202 let dir = temp_dir("routing");
1203 let paths = paths_in(&dir);
1204 std::fs::write(
1205 &paths.project,
1206 "[providers.openrouter.routing]\nignore = [\"Phala\"]\nallow_fallbacks = true\n",
1207 )
1208 .unwrap();
1209 let config = load_config(&paths, &Overrides::default()).unwrap();
1210 let routing = config.providers["openrouter"].routing.clone().unwrap();
1211 assert_eq!(
1212 serde_json::Value::Object(routing),
1213 serde_json::json!({"ignore": ["Phala"], "allow_fallbacks": true})
1214 );
1215 let _ = std::fs::remove_dir_all(&dir);
1216 }
1217
1218 #[test]
1219 fn layers_deep_merge_and_overrides_win() {
1220 let dir = temp_dir("layers");
1221 std::fs::write(
1222 dir.join("user.toml"),
1223 "[model]\ndefault = \"openrouter:a\"\n[providers.openrouter]\nmax_tokens = 512\n",
1224 )
1225 .unwrap();
1226 std::fs::write(
1227 dir.join("project.toml"),
1228 "[providers.openrouter]\nbase_url = \"http://localhost:9\"\n[providers.mine]\nbase_url = \"http://x\"\n[tools]\nanything = 1\n",
1229 )
1230 .unwrap();
1231
1232 let config = load_config(&paths_in(&dir), &Overrides::default()).unwrap();
1233 let openrouter = &config.providers["openrouter"];
1234 assert_eq!(config.model.default, "openrouter:a");
1235 assert_eq!(openrouter.base_url.as_deref(), Some("http://localhost:9"));
1236 assert_eq!(
1237 openrouter.api_key_env.as_deref(),
1238 Some("OPENROUTER_API_KEY")
1239 );
1240 assert_eq!(config.max_output_tokens_for("openrouter"), 512);
1241 assert!(config.providers.contains_key("groq"));
1242 assert_eq!(config.providers["mine"].max_retries, 2);
1243 assert_eq!(config.sources.len(), 2);
1244
1245 let env = Overrides {
1246 env_model: Some("groq:b".to_owned()),
1247 ..Overrides::default()
1248 };
1249 assert_eq!(
1250 load_config(&paths_in(&dir), &env).unwrap().model.default,
1251 "groq:b"
1252 );
1253
1254 let flag = Overrides {
1255 env_model: Some("groq:b".to_owned()),
1256 model: Some("openai:c".to_owned()),
1257 ..Overrides::default()
1258 };
1259 assert_eq!(
1260 load_config(&paths_in(&dir), &flag).unwrap().model.default,
1261 "openai:c"
1262 );
1263 }
1264
1265 #[test]
1266 fn malformed_toml_names_the_file() {
1267 let dir = temp_dir("malformed");
1268 std::fs::write(dir.join("project.toml"), "[model\n").unwrap();
1269
1270 let error = load_config(&paths_in(&dir), &Overrides::default()).unwrap_err();
1271 let ConfigError::Malformed { path, .. } = &error else {
1272 panic!("{error:?}");
1273 };
1274 assert!(path.ends_with("project.toml"));
1275 assert!(error.to_string().starts_with("Malformed config at "));
1276 }
1277
1278 #[test]
1279 fn pricing_overrides_load_and_negative_prices_are_rejected() {
1280 let dir = temp_dir("pricing");
1281 std::fs::write(
1282 dir.join("project.toml"),
1283 "[pricing.models.\"openrouter:openai/gpt-4o-mini\"]\ninput_per_mtok = 0.15\noutput_per_mtok = 0.6\n",
1284 )
1285 .unwrap();
1286 let config = load_config(&paths_in(&dir), &Overrides::default()).unwrap();
1287 let price = config.pricing.models["openrouter:openai/gpt-4o-mini"];
1288 assert_eq!(price.input_per_mtok, 0.15);
1289 assert_eq!(price.output_per_mtok, 0.6);
1290
1291 std::fs::write(
1292 dir.join("project.toml"),
1293 "[pricing.models.cheap]\ninput_per_mtok = -1\noutput_per_mtok = 0\n",
1294 )
1295 .unwrap();
1296 let error = load_config(&paths_in(&dir), &Overrides::default()).unwrap_err();
1297 assert!(matches!(error, ConfigError::Invalid { .. }), "{error:?}");
1298 assert!(error.to_string().contains("input_per_mtok"), "{error}");
1299 }
1300
1301 #[test]
1302 fn sandbox_mode_defaults_to_subprocess_and_rejects_unknown_values() {
1303 let dir = temp_dir("sandbox");
1304 let config = load_config(&paths_in(&dir), &Overrides::default()).unwrap();
1305 assert_eq!(config.sandbox.mode, SandboxMode::Subprocess);
1306
1307 let env = Overrides {
1308 env_sandbox: Some("docker".to_owned()),
1309 ..Overrides::default()
1310 };
1311 assert_eq!(
1312 load_config(&paths_in(&dir), &env).unwrap().sandbox.mode,
1313 SandboxMode::Docker
1314 );
1315 let flag = Overrides {
1317 sandbox: Some("subprocess".to_owned()),
1318 ..env
1319 };
1320 assert_eq!(
1321 load_config(&paths_in(&dir), &flag).unwrap().sandbox.mode,
1322 SandboxMode::Subprocess
1323 );
1324
1325 std::fs::write(
1326 dir.join("project.toml"),
1327 "[sandbox]
1328mode = \"vm\"
1329",
1330 )
1331 .unwrap();
1332 let error = load_config(&paths_in(&dir), &Overrides::default()).unwrap_err();
1333 assert!(matches!(error, ConfigError::Invalid { .. }), "{error:?}");
1334 }
1335}