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
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 #[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 #[serde(skip)]
173 pub table: Table,
174 #[serde(skip)]
176 pub sources: Vec<PathBuf>,
177 #[serde(skip)]
179 pub untrusted: Vec<String>,
180}
181
182#[derive(Debug, Clone, PartialEq, Deserialize)]
183pub struct ModelConfig {
184 pub default: String,
185 pub router: RouterMode,
187 pub route: ModelRoute,
188 #[serde(default)]
191 pub context_window: BTreeMap<String, u64>,
192}
193
194#[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#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
213pub struct ModelRoute {
214 pub cheap: String,
215 pub frontier: String,
216}
217
218#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
220pub struct UiConfig {
221 #[serde(default = "default_true")]
224 pub tui: bool,
225 pub spinner: bool,
226 pub history_file: String,
228 pub history_size: i64,
230 pub markdown: bool,
232 #[serde(default = "default_true")]
235 pub update_check: bool,
236 #[serde(default = "default_summary")]
238 pub thinking: DisplayLevel,
239 #[serde(default = "default_summary")]
241 pub tool_use: DisplayLevel,
242 #[serde(default)]
245 pub agent86ui: Agent86UiMode,
246 #[serde(default)]
249 pub agent86ui_remote_media: bool,
250 #[serde(default)]
253 pub ask_user: AskUserMode,
254}
255
256#[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#[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#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
278pub struct RunConfig {
279 #[serde(default = "default_run_output")]
281 pub output: RunOutputMode,
282}
283
284fn default_run_output() -> RunOutputMode {
285 RunOutputMode::Final
286}
287
288#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
291#[serde(rename_all = "lowercase")]
292pub enum RunOutputMode {
293 Final,
296 Full,
298 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
321#[serde(rename_all = "lowercase")]
322pub enum DisplayLevel {
323 Full,
325 Summary,
327 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 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 pub max_steps: u32,
366 pub max_cost_usd: f64,
368 pub max_wall_clock_s: u64,
370 pub max_consecutive_errors: u32,
372 pub max_context_tokens: u64,
375 pub max_output_tokens: u32,
376 pub context_reserve_tokens: u64,
379 pub compaction: CompactionMode,
381 pub parallel_tools: bool,
383 pub tool_timeout_s: u64,
385}
386
387#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
389pub struct SkillsConfig {
390 pub enabled: bool,
391 pub paths: Vec<String>,
393}
394
395#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
397pub struct AgentsConfig {
398 pub enabled: bool,
399 pub max_depth: u32,
401 pub max_steps: u32,
403 #[serde(default = "default_max_parallel")]
407 pub max_parallel: u32,
408}
409
410pub const MAX_PARALLEL_CEILING: u32 = 8;
413
414fn default_max_parallel() -> u32 {
415 3
416}
417
418impl AgentsConfig {
419 pub fn parallel_limit(&self) -> usize {
421 self.max_parallel.clamp(1, MAX_PARALLEL_CEILING) as usize
422 }
423}
424
425#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
427pub struct McpConfig {
428 pub enabled: bool,
429}
430
431#[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 #[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 #[serde(default)]
460 pub defaults: indexmap::IndexMap<String, serde_json::Map<String, serde_json::Value>>,
461}
462
463impl McpServerConfig {
464 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 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#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
528pub struct ObservabilityConfig {
529 pub trace: bool,
531 pub path: String,
533 #[serde(default)]
535 pub otel: bool,
536 #[serde(default)]
538 pub otel_exporter: OtelExporter,
539 #[serde(default)]
541 pub otel_endpoint: Option<String>,
542 pub redact: RedactMode,
543 pub max_field_chars: usize,
545 pub max_trace_bytes: u64,
547 pub keep_traces: usize,
549}
550
551#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
553#[serde(rename_all = "snake_case")]
554pub enum OtelExporter {
555 #[default]
557 Otlp,
558 Console,
560 None,
562}
563
564#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
566#[serde(rename_all = "snake_case")]
567pub enum RedactMode {
568 Secrets,
570 None,
572}
573
574#[derive(Debug, Clone, PartialEq, Deserialize)]
576pub struct MemoryConfig {
577 pub enabled: bool,
578 pub path: String,
580 pub embeddings: String,
583 pub hf_offline: bool,
585 pub retention_max_episodes: i64,
588 pub retention_max_sessions: i64,
589 pub retention_max_age_days: f64,
590}
591
592#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
594pub struct ToolsConfig {
595 pub web_allow_private: bool,
597 #[serde(default = "crate::tools::web::default_user_agent")]
599 pub web_user_agent: String,
600 pub web_max_chars: usize,
602 pub mention_max_bytes: u64,
604}
605
606#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
608pub struct GuardrailsConfig {
609 pub approval: ApprovalMode,
611 pub ingress: IngressMode,
613 pub egress: EgressMode,
615 pub scan_observations: bool,
617}
618
619#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
621#[serde(rename_all = "snake_case")]
622pub enum IngressMode {
623 Off,
624 Warn,
626 Block,
628}
629
630#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
633#[serde(rename_all = "snake_case")]
634pub enum CompactionMode {
635 Summarize,
637 Drop,
639}
640
641#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
643#[serde(rename_all = "snake_case")]
644pub enum EgressMode {
645 Off,
646 Warn,
648 Redact,
650}
651
652#[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 pub docker_network: bool,
661 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 Subprocess,
671 Docker,
673}
674
675impl SandboxMode {
676 pub fn as_str(self) -> &'static str {
678 match self {
679 Self::Subprocess => "subprocess",
680 Self::Docker => "docker",
681 }
682 }
683}
684
685#[derive(Debug, Clone, Default, PartialEq, Deserialize)]
691pub struct PricingConfig {
692 #[serde(default)]
693 pub models: BTreeMap<String, ModelPrice>,
694}
695
696#[derive(Debug, Clone, Copy, PartialEq, Deserialize)]
698pub struct ModelPrice {
699 pub input_per_mtok: f64,
700 pub output_per_mtok: f64,
701}
702
703#[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 #[serde(default)]
713 pub num_ctx: Option<u32>,
714 #[serde(default)]
717 pub num_ctx_max: Option<u32>,
718 #[serde(default = "default_connect_timeout_s")]
720 pub connect_timeout_s: f64,
721 #[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 #[serde(default)]
735 pub routing: Option<serde_json::Map<String, serde_json::Value>>,
736 #[serde(default)]
742 pub adapter: Option<String>,
743 #[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 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#[derive(Debug, Clone, PartialEq, Eq)]
786pub struct ConfigPaths {
787 pub user: Option<PathBuf>,
788 pub project: PathBuf,
789 pub project_trust: ProjectTrust,
792}
793
794#[derive(Debug, Clone, Copy, PartialEq, Eq)]
799pub enum ProjectTrust {
800 Trusted,
802 Restricted,
805}
806
807impl ConfigPaths {
808 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#[derive(Debug, Clone, Default, PartialEq, Eq)]
821pub struct Overrides {
822 pub env_model: Option<String>,
824 pub env_sandbox: Option<String>,
826 pub env_approval: Option<String>,
828 pub env_run_output: Option<String>,
830 pub model: Option<String>,
832 pub sandbox: Option<String>,
834 pub approval: Option<String>,
836}
837
838impl Overrides {
839 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
867pub 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 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
936pub(crate) fn read_toml_layer(path: &Path) -> Result<Table, ConfigError> {
938 read_toml(path)
939}
940
941pub(crate) fn normalize_layer(layer: Table) -> Table {
943 normalize(layer)
944}
945
946fn 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
961fn 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 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
1020fn 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
1038pub 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 std::fs::write(&paths.project, "[ui]\nstatus_line = false\n").unwrap();
1116 assert!(!load_config(&paths, &Overrides::default()).unwrap().ui.tui);
1117 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 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 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}