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
47context_sizing = true
48stall_nudge = true
49
50[sandbox]
51mode = "subprocess"
52docker_image = "python:3.12-slim"
53docker_memory = "512m"
54docker_cpus = "1"
55docker_network = false
56env_passthrough = []
57
58[mcp]
59enabled = true
60
61[skills]
62enabled = true
63paths = []
64
65[agents]
66enabled = true
67max_depth = 2
68max_steps = 8
69max_parallel = 3
70
71[observability]
72trace = true
73path = "~/.agent86/traces"
74otel = false
75otel_exporter = "otlp"
76redact = "secrets"
77max_field_chars = 2000
78max_trace_bytes = 50000000
79keep_traces = 5
80
81[memory]
82enabled = true
83path = "~/.agent86/memory.db"
84embeddings = "sentence-transformers:all-MiniLM-L6-v2"
85hf_offline = true
86retention_max_episodes = 1000
87retention_max_sessions = 500
88retention_max_age_days = 0.0
89
90[tools]
91web_allow_private = false
92web_max_chars = 8000
93mention_max_bytes = 200000
94
95[ui]
96spinner = true
97history_file = "~/.agent86/history"
98history_size = 1000
99markdown = true
100update_check = true
101thinking = "summary"
102tool_use = "summary"
103agent86ui = "auto"
104agent86ui_remote_media = false
105ask_user = "auto"
106
107[run]
108output = "final"
109
110[verify]
111command = ""
112max_attempts = 2
113
114[guardrails]
115approval = "ask"
116ingress = "warn"
117egress = "warn"
118scan_observations = true
119
120[providers.anthropic]
121api_key_env = "ANTHROPIC_API_KEY"
122
123[providers.google]
124api_key_env = "GEMINI_API_KEY"
125read_timeout_s = 1200.0
126store = false
127
128[providers.openai]
129api_key_env = "OPENAI_API_KEY"
130base_url = "https://api.openai.com/v1"
131
132[providers.openrouter]
133api_key_env = "OPENROUTER_API_KEY"
134base_url = "https://openrouter.ai/api/v1"
135
136[providers.groq]
137api_key_env = "GROQ_API_KEY"
138base_url = "https://api.groq.com/openai/v1"
139
140[providers.ollama]
141base_url = "http://localhost:11434"
142num_ctx_max = 32768
143
144[providers.llamacpp]
145base_url = "http://localhost:8080"
146
147[providers.vllm]
148base_url = "http://localhost:8000/v1"
149api_key_env = "VLLM_API_KEY"
150
151[providers.lmstudio]
152base_url = "http://localhost:1234/v1"
153api_key_env = "LM_API_TOKEN"
154"#;
155
156#[derive(Debug, Clone, PartialEq, Deserialize)]
157pub struct Config {
158 pub model: ModelConfig,
159 pub limits: LimitsConfig,
160 pub sandbox: SandboxConfig,
161 pub guardrails: GuardrailsConfig,
162 pub tools: ToolsConfig,
163 pub memory: MemoryConfig,
164 pub observability: ObservabilityConfig,
165 pub mcp: McpConfig,
166 pub skills: SkillsConfig,
167 pub agents: AgentsConfig,
168 #[serde(default)]
170 pub mcp_servers: indexmap::IndexMap<String, McpServerConfig>,
171 #[serde(default)]
172 pub providers: indexmap::IndexMap<String, ProviderConfig>,
173 #[serde(default)]
174 pub pricing: PricingConfig,
175 pub ui: UiConfig,
176 pub run: RunConfig,
177 pub verify: VerifyConfig,
179 #[serde(skip)]
181 pub table: Table,
182 #[serde(skip)]
184 pub sources: Vec<PathBuf>,
185 #[serde(skip)]
187 pub untrusted: Vec<String>,
188}
189
190#[derive(Debug, Clone, PartialEq, Deserialize)]
191pub struct ModelConfig {
192 pub default: String,
193 pub router: RouterMode,
195 pub route: ModelRoute,
196 #[serde(default)]
199 pub context_window: BTreeMap<String, u64>,
200}
201
202#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
204#[serde(rename_all = "snake_case")]
205pub enum RouterMode {
206 Off,
207 Triage,
208}
209
210impl RouterMode {
211 pub fn as_str(self) -> &'static str {
212 match self {
213 Self::Off => "off",
214 Self::Triage => "triage",
215 }
216 }
217}
218
219#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
221pub struct ModelRoute {
222 pub cheap: String,
223 pub frontier: String,
224}
225
226#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
228pub struct UiConfig {
229 #[serde(default = "default_true")]
232 pub tui: bool,
233 pub spinner: bool,
234 pub history_file: String,
236 pub history_size: i64,
238 pub markdown: bool,
240 #[serde(default = "default_true")]
243 pub update_check: bool,
244 #[serde(default = "default_summary")]
246 pub thinking: DisplayLevel,
247 #[serde(default = "default_summary")]
249 pub tool_use: DisplayLevel,
250 #[serde(default)]
253 pub agent86ui: Agent86UiMode,
254 #[serde(default)]
257 pub agent86ui_remote_media: bool,
258 #[serde(default)]
261 pub ask_user: AskUserMode,
262}
263
264#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
267#[serde(rename_all = "lowercase")]
268pub enum AskUserMode {
269 #[default]
270 Auto,
271 Off,
272}
273
274#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
277#[serde(rename_all = "lowercase")]
278pub enum Agent86UiMode {
279 #[default]
280 Auto,
281 Off,
282}
283
284#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
287pub struct VerifyConfig {
288 pub command: String,
291 pub max_attempts: u32,
293}
294
295#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
297pub struct RunConfig {
298 #[serde(default = "default_run_output")]
300 pub output: RunOutputMode,
301}
302
303fn default_run_output() -> RunOutputMode {
304 RunOutputMode::Final
305}
306
307#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
310#[serde(rename_all = "lowercase")]
311pub enum RunOutputMode {
312 Final,
315 Full,
317 Quiet,
319}
320
321impl RunOutputMode {
322 pub const ALL: [Self; 3] = [Self::Final, Self::Full, Self::Quiet];
323
324 pub fn as_str(self) -> &'static str {
325 match self {
326 Self::Final => "final",
327 Self::Full => "full",
328 Self::Quiet => "quiet",
329 }
330 }
331
332 pub fn parse(text: &str) -> Option<Self> {
333 Self::ALL.into_iter().find(|mode| mode.as_str() == text)
334 }
335}
336
337#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
340#[serde(rename_all = "lowercase")]
341pub enum DisplayLevel {
342 Full,
344 Summary,
346 Hidden,
348}
349
350impl DisplayLevel {
351 pub const ALL: [Self; 3] = [Self::Full, Self::Summary, Self::Hidden];
352
353 pub fn as_str(self) -> &'static str {
354 match self {
355 Self::Full => "full",
356 Self::Summary => "summary",
357 Self::Hidden => "hidden",
358 }
359 }
360
361 pub fn parse(text: &str) -> Option<Self> {
362 Self::ALL
363 .into_iter()
364 .find(|level| level.as_str() == text.trim().to_lowercase())
365 }
366
367 pub fn next(self) -> Self {
369 match self {
370 Self::Full => Self::Summary,
371 Self::Summary => Self::Hidden,
372 Self::Hidden => Self::Full,
373 }
374 }
375}
376
377fn default_summary() -> DisplayLevel {
378 DisplayLevel::Summary
379}
380
381#[derive(Debug, Clone, PartialEq, Deserialize)]
382pub struct LimitsConfig {
383 pub max_steps: u32,
385 pub max_cost_usd: f64,
387 pub max_wall_clock_s: u64,
389 pub max_consecutive_errors: u32,
391 pub max_context_tokens: u64,
394 pub max_output_tokens: u32,
395 pub context_reserve_tokens: u64,
398 pub compaction: CompactionMode,
400 pub parallel_tools: bool,
402 pub tool_timeout_s: u64,
404 pub context_sizing: bool,
408 pub stall_nudge: bool,
412}
413
414#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
416pub struct SkillsConfig {
417 pub enabled: bool,
418 pub paths: Vec<String>,
420}
421
422#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
424pub struct AgentsConfig {
425 pub enabled: bool,
426 pub max_depth: u32,
428 pub max_steps: u32,
430 #[serde(default = "default_max_parallel")]
434 pub max_parallel: u32,
435}
436
437pub const MAX_PARALLEL_CEILING: u32 = 8;
440
441fn default_max_parallel() -> u32 {
442 3
443}
444
445impl AgentsConfig {
446 pub fn parallel_limit(&self) -> usize {
448 self.max_parallel.clamp(1, MAX_PARALLEL_CEILING) as usize
449 }
450}
451
452#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
454pub struct McpConfig {
455 pub enabled: bool,
456}
457
458#[derive(Debug, Clone, PartialEq, Deserialize)]
460pub struct McpServerConfig {
461 #[serde(default)]
462 pub command: Option<String>,
463 #[serde(default)]
464 pub args: Vec<String>,
465 #[serde(default)]
466 pub env: indexmap::IndexMap<String, String>,
467 #[serde(default)]
468 pub url: Option<String>,
469 #[serde(default)]
470 pub headers: indexmap::IndexMap<String, String>,
471 #[serde(default)]
473 pub transport: Option<String>,
474 #[serde(default = "default_true")]
475 pub enabled: bool,
476 #[serde(default = "default_mcp_connect_timeout_s")]
477 pub connect_timeout_s: f64,
478 #[serde(default = "default_mcp_call_timeout_s")]
479 pub call_timeout_s: f64,
480 #[serde(default = "default_mcp_max_result_chars")]
481 pub max_result_chars: usize,
482 #[serde(default)]
487 pub defaults: indexmap::IndexMap<String, serde_json::Map<String, serde_json::Value>>,
488}
489
490impl McpServerConfig {
491 pub fn resolve_transport(&mut self) -> Result<(), String> {
493 let (has_command, has_url) = (
494 self.command.as_deref().is_some_and(|c| !c.is_empty()),
495 self.url.as_deref().is_some_and(|u| !u.is_empty()),
496 );
497 if has_command && has_url {
498 return Err("MCP server sets both 'command' and 'url'; use one transport".to_owned());
499 }
500 if !has_command && !has_url {
501 return Err("MCP server needs 'command' (stdio) or 'url' (sse/http)".to_owned());
502 }
503 let given = self
504 .transport
505 .clone()
506 .unwrap_or_else(|| if has_command { "stdio" } else { "http" }.to_owned());
507 let mut transport = given.to_lowercase().replace('-', "_");
508 if transport == "streamable_http" {
509 transport = "http".to_owned();
510 }
511 if !matches!(transport.as_str(), "stdio" | "sse" | "http") {
512 return Err(format!("unknown MCP transport '{given}' (stdio|sse|http)"));
513 }
514 if transport == "stdio" && !has_command {
515 return Err("stdio transport requires 'command'".to_owned());
516 }
517 if transport != "stdio" && !has_url {
518 return Err(format!("{transport} transport requires 'url'"));
519 }
520 for (field, value) in [
521 ("connect_timeout_s", self.connect_timeout_s),
522 ("call_timeout_s", self.call_timeout_s),
523 ] {
524 if !(value > 0.0 && value.is_finite()) {
525 return Err(format!("{field} must be greater than 0"));
526 }
527 }
528 if self.max_result_chars == 0 {
529 return Err("max_result_chars must be greater than 0".to_owned());
530 }
531 self.transport = Some(transport);
532 Ok(())
533 }
534
535 pub fn transport(&self) -> &str {
537 self.transport.as_deref().unwrap_or("stdio")
538 }
539}
540
541fn default_mcp_connect_timeout_s() -> f64 {
542 30.0
543}
544
545fn default_mcp_call_timeout_s() -> f64 {
546 120.0
547}
548
549fn default_mcp_max_result_chars() -> usize {
550 8000
551}
552
553#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
555pub struct ObservabilityConfig {
556 pub trace: bool,
558 pub path: String,
560 #[serde(default)]
562 pub otel: bool,
563 #[serde(default)]
565 pub otel_exporter: OtelExporter,
566 #[serde(default)]
568 pub otel_endpoint: Option<String>,
569 pub redact: RedactMode,
570 pub max_field_chars: usize,
572 pub max_trace_bytes: u64,
574 pub keep_traces: usize,
576}
577
578#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
580#[serde(rename_all = "snake_case")]
581pub enum OtelExporter {
582 #[default]
584 Otlp,
585 Console,
587 None,
589}
590
591#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
593#[serde(rename_all = "snake_case")]
594pub enum RedactMode {
595 Secrets,
597 None,
599}
600
601#[derive(Debug, Clone, PartialEq, Deserialize)]
603pub struct MemoryConfig {
604 pub enabled: bool,
605 pub path: String,
607 pub embeddings: String,
610 pub hf_offline: bool,
612 pub retention_max_episodes: i64,
615 pub retention_max_sessions: i64,
616 pub retention_max_age_days: f64,
617}
618
619#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
621pub struct ToolsConfig {
622 pub web_allow_private: bool,
624 #[serde(default = "crate::tools::web::default_user_agent")]
626 pub web_user_agent: String,
627 pub web_max_chars: usize,
629 pub mention_max_bytes: u64,
631}
632
633#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
635pub struct GuardrailsConfig {
636 pub approval: ApprovalMode,
638 pub ingress: IngressMode,
640 pub egress: EgressMode,
642 pub scan_observations: bool,
644}
645
646#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
648#[serde(rename_all = "snake_case")]
649pub enum IngressMode {
650 Off,
651 Warn,
653 Block,
655}
656
657#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
660#[serde(rename_all = "snake_case")]
661pub enum CompactionMode {
662 Summarize,
664 Drop,
666}
667
668#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
670#[serde(rename_all = "snake_case")]
671pub enum EgressMode {
672 Off,
673 Warn,
675 Redact,
677}
678
679#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
681pub struct SandboxConfig {
682 pub mode: SandboxMode,
683 pub docker_image: String,
684 pub docker_memory: String,
685 pub docker_cpus: String,
686 pub docker_network: bool,
688 pub env_passthrough: Vec<String>,
691}
692
693#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
694#[serde(rename_all = "snake_case")]
695pub enum SandboxMode {
696 Subprocess,
698 Docker,
700}
701
702impl SandboxMode {
703 pub fn as_str(self) -> &'static str {
705 match self {
706 Self::Subprocess => "subprocess",
707 Self::Docker => "docker",
708 }
709 }
710}
711
712#[derive(Debug, Clone, Default, PartialEq, Deserialize)]
718pub struct PricingConfig {
719 #[serde(default)]
720 pub models: BTreeMap<String, ModelPrice>,
721}
722
723#[derive(Debug, Clone, Copy, PartialEq, Deserialize)]
725pub struct ModelPrice {
726 pub input_per_mtok: f64,
727 pub output_per_mtok: f64,
728}
729
730#[derive(Debug, Clone, PartialEq, Deserialize)]
732pub struct ProviderConfig {
733 #[serde(default)]
734 pub api_key_env: Option<String>,
735 #[serde(default)]
736 pub base_url: Option<String>,
737 #[serde(default)]
740 pub num_ctx: Option<u32>,
741 #[serde(default)]
744 pub num_ctx_max: Option<u32>,
745 #[serde(default = "default_connect_timeout_s")]
747 pub connect_timeout_s: f64,
748 #[serde(default = "default_read_timeout_s")]
750 pub read_timeout_s: f64,
751 #[serde(default = "default_max_retries")]
752 pub max_retries: u32,
753 #[serde(default)]
754 pub max_tokens: Option<u32>,
755 #[serde(default = "default_true")]
756 pub prompt_cache: bool,
757 #[serde(default)]
762 pub routing: Option<serde_json::Map<String, serde_json::Value>>,
763 #[serde(default)]
767 pub temperature: Option<f32>,
768 #[serde(default)]
774 pub adapter: Option<String>,
775 #[serde(default)]
779 pub store: bool,
780}
781
782impl Default for ProviderConfig {
783 fn default() -> Self {
784 Self {
785 api_key_env: None,
786 base_url: None,
787 num_ctx: None,
788 num_ctx_max: None,
789 connect_timeout_s: default_connect_timeout_s(),
790 read_timeout_s: default_read_timeout_s(),
791 max_retries: default_max_retries(),
792 max_tokens: None,
793 prompt_cache: true,
794 routing: None,
795 temperature: None,
796 adapter: None,
797 store: false,
798 }
799 }
800}
801
802impl Config {
803 pub fn max_output_tokens_for(&self, provider: &str) -> u32 {
805 self.providers
806 .get(provider)
807 .and_then(|config| config.max_tokens)
808 .filter(|&cap| cap > 0)
809 .unwrap_or(if self.limits.max_output_tokens > 0 {
810 self.limits.max_output_tokens
811 } else {
812 8192
813 })
814 }
815}
816
817#[derive(Debug, Clone, PartialEq, Eq)]
819pub struct ConfigPaths {
820 pub user: Option<PathBuf>,
821 pub project: PathBuf,
822 pub project_trust: ProjectTrust,
825}
826
827#[derive(Debug, Clone, Copy, PartialEq, Eq)]
832pub enum ProjectTrust {
833 Trusted,
835 Restricted,
838}
839
840impl ConfigPaths {
841 pub fn discover() -> Self {
844 Self {
845 user: home_dir().map(|home| home.join(".agent86").join("config.toml")),
846 project: Path::new(".agent86").join("config.toml"),
847 project_trust: ProjectTrust::Restricted,
848 }
849 }
850}
851
852#[derive(Debug, Clone, Default, PartialEq, Eq)]
854pub struct Overrides {
855 pub env_model: Option<String>,
857 pub env_sandbox: Option<String>,
859 pub env_approval: Option<String>,
861 pub env_run_output: Option<String>,
863 pub model: Option<String>,
865 pub sandbox: Option<String>,
867 pub approval: Option<String>,
869}
870
871impl Overrides {
872 pub fn from_env(
876 model: Option<String>,
877 sandbox: Option<String>,
878 approval: Option<String>,
879 ) -> Self {
880 Self {
881 env_model: non_empty_env("AGENT86_MODEL"),
882 env_sandbox: non_empty_env("AGENT86_SANDBOX"),
883 env_approval: non_empty_env("AGENT86_APPROVAL"),
884 env_run_output: non_empty_env("AGENT86_RUN_OUTPUT"),
885 model,
886 sandbox,
887 approval,
888 }
889 }
890}
891
892#[derive(Debug, Clone, PartialEq, Eq, Error)]
893pub enum ConfigError {
894 #[error("Malformed config at {path}: {detail}")]
895 Malformed { path: String, detail: String },
896 #[error("Invalid config: {detail}")]
897 Invalid { detail: String },
898}
899
900pub fn builtin_config() -> Config {
905 let mut merged: Table = DEFAULTS.parse().expect("built-in defaults are valid TOML");
906 accept_legacy_status_line(&mut merged);
907 let mut config: Config = Value::Table(merged.clone())
908 .try_into()
909 .expect("built-in defaults deserialize");
910 validate(&mut config).expect("built-in defaults are valid");
911 config.table = merged;
912 config
913}
914
915pub fn load_config(paths: &ConfigPaths, overrides: &Overrides) -> Result<Config, ConfigError> {
916 let mut merged: Table = DEFAULTS.parse().expect("built-in defaults are valid TOML");
917 let mut sources = Vec::new();
918
919 let mut untrusted = Vec::new();
920 let files = paths.user.iter().chain(std::iter::once(&paths.project));
921 for path in files {
922 let mut layer = normalize(read_toml(path)?);
923 if path == &paths.project && paths.project_trust == ProjectTrust::Restricted {
924 untrusted = crate::trust::take_untrusted(&mut layer)
925 .into_iter()
926 .map(|(key, _)| key)
927 .collect();
928 }
929 if !layer.is_empty() {
930 deep_merge(&mut merged, layer);
931 sources.push(path.clone());
932 }
933 }
934
935 let layers = [
937 ("model", "default", &overrides.env_model),
938 ("sandbox", "mode", &overrides.env_sandbox),
939 ("guardrails", "approval", &overrides.env_approval),
940 ("run", "output", &overrides.env_run_output),
941 ("model", "default", &overrides.model),
942 ("sandbox", "mode", &overrides.sandbox),
943 ("guardrails", "approval", &overrides.approval),
944 ];
945 for (section, key, value) in layers {
946 if let Some(value) = value {
947 let mut table = Table::new();
948 table.insert(key.to_owned(), Value::String(value.clone()));
949 let mut layer = Table::new();
950 layer.insert(section.to_owned(), Value::Table(table));
951 deep_merge(&mut merged, layer);
952 }
953 }
954
955 accept_legacy_status_line(&mut merged);
956 let mut config: Config =
957 Value::Table(merged.clone())
958 .try_into()
959 .map_err(|error: toml::de::Error| ConfigError::Invalid {
960 detail: error.message().to_owned(),
961 })?;
962 validate(&mut config)?;
963 config.sources = sources;
964 config.table = merged;
965 config.untrusted = untrusted;
966 Ok(config)
967}
968
969pub(crate) fn read_toml_layer(path: &Path) -> Result<Table, ConfigError> {
971 read_toml(path)
972}
973
974pub(crate) fn normalize_layer(layer: Table) -> Table {
976 normalize(layer)
977}
978
979fn normalize(mut layer: Table) -> Table {
982 if let Some(Value::Table(mcp)) = layer.get_mut("mcp") {
983 if let Some(servers) = mcp.remove("servers") {
984 let empty = mcp.is_empty();
985 if empty {
986 layer.remove("mcp");
987 }
988 layer.insert("mcp_servers".to_owned(), servers);
989 }
990 }
991 layer
992}
993
994fn accept_legacy_status_line(merged: &mut Table) {
997 if let Some(Value::Table(ui)) = merged.get_mut("ui") {
998 if let Some(legacy) = ui.remove("status_line") {
999 ui.entry("tui").or_insert(legacy);
1000 }
1001 }
1002}
1003
1004fn validate(config: &mut Config) -> Result<(), ConfigError> {
1005 if config.limits.tool_timeout_s == 0 {
1007 return Err(ConfigError::Invalid {
1008 detail: "limits.tool_timeout_s must be at least 1 second, not 0".to_owned(),
1009 });
1010 }
1011 for (name, server) in &mut config.mcp_servers {
1012 server
1013 .resolve_transport()
1014 .map_err(|detail| ConfigError::Invalid {
1015 detail: format!("mcp_servers.{name}: {detail}"),
1016 })?;
1017 }
1018 for (model, price) in &config.pricing.models {
1019 for (field, value) in [
1020 ("input_per_mtok", price.input_per_mtok),
1021 ("output_per_mtok", price.output_per_mtok),
1022 ] {
1023 if !(value >= 0.0 && value.is_finite()) {
1024 return Err(ConfigError::Invalid {
1025 detail: format!(
1026 "pricing.models.\"{model}\".{field} must be a non-negative number, not {value}"
1027 ),
1028 });
1029 }
1030 }
1031 }
1032 Ok(())
1033}
1034
1035fn read_toml(path: &Path) -> Result<Table, ConfigError> {
1036 let text = match std::fs::read_to_string(path) {
1037 Ok(text) => text,
1038 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Table::new()),
1039 Err(error) => {
1040 return Err(ConfigError::Malformed {
1041 path: path.display().to_string(),
1042 detail: error.to_string(),
1043 })
1044 }
1045 };
1046 text.parse()
1047 .map_err(|error: toml::de::Error| ConfigError::Malformed {
1048 path: path.display().to_string(),
1049 detail: error.to_string().trim_end().to_owned(),
1050 })
1051}
1052
1053fn deep_merge(base: &mut Table, overlay: Table) {
1055 for (key, value) in overlay {
1056 match (base.get_mut(&key), value) {
1057 (Some(Value::Table(existing)), Value::Table(incoming)) => {
1058 deep_merge(existing, incoming)
1059 }
1060 (_, value) => {
1061 base.insert(key, value);
1062 }
1063 }
1064 }
1065}
1066
1067fn non_empty_env(name: &str) -> Option<String> {
1068 std::env::var(name).ok().filter(|value| !value.is_empty())
1069}
1070
1071pub fn home_dir() -> Option<PathBuf> {
1073 let variable = if cfg!(windows) { "USERPROFILE" } else { "HOME" };
1074 std::env::var_os(variable)
1075 .filter(|value| !value.is_empty())
1076 .map(PathBuf::from)
1077}
1078
1079fn default_connect_timeout_s() -> f64 {
1080 10.0
1081}
1082
1083fn default_read_timeout_s() -> f64 {
1084 300.0
1085}
1086
1087fn default_max_retries() -> u32 {
1088 2
1089}
1090
1091fn default_true() -> bool {
1092 true
1093}
1094
1095#[cfg(test)]
1096mod tests {
1097 use super::*;
1098
1099 fn paths_in(dir: &Path) -> ConfigPaths {
1100 ConfigPaths {
1101 user: Some(dir.join("user.toml")),
1102 project: dir.join("project.toml"),
1103 project_trust: crate::config::ProjectTrust::Trusted,
1104 }
1105 }
1106
1107 fn temp_dir(name: &str) -> PathBuf {
1108 let dir =
1109 std::env::temp_dir().join(format!("agent86-config-{name}-{}", std::process::id()));
1110 let _ = std::fs::remove_dir_all(&dir);
1111 std::fs::create_dir_all(&dir).unwrap();
1112 dir
1113 }
1114
1115 #[test]
1116 fn a_zero_tool_timeout_is_invalid() {
1117 let dir = temp_dir("timeout");
1118 let paths = paths_in(&dir);
1119 std::fs::write(&paths.project, "[limits]\ntool_timeout_s = 0\n").unwrap();
1120 let error = load_config(&paths, &Overrides::default()).unwrap_err();
1121 assert_eq!(
1122 error.to_string(),
1123 "Invalid config: limits.tool_timeout_s must be at least 1 second, not 0"
1124 );
1125 std::fs::write(&paths.project, "[limits]\ntool_timeout_s = 1\n").unwrap();
1126 assert_eq!(
1127 load_config(&paths, &Overrides::default())
1128 .unwrap()
1129 .limits
1130 .tool_timeout_s,
1131 1
1132 );
1133 }
1134
1135 #[test]
1136 fn ui_settings_default_and_accept_the_legacy_status_line_key() {
1137 let dir = temp_dir("ui");
1138 let paths = paths_in(&dir);
1139 let config = load_config(&paths, &Overrides::default()).unwrap();
1140 assert!(config.ui.tui);
1141 assert_eq!(config.ui.history_file, "~/.agent86/history");
1142 assert_eq!(config.ui.history_size, 1000);
1143 assert_eq!(config.tools.mention_max_bytes, 200_000);
1144 assert_eq!(config.model.router, RouterMode::Off);
1145 assert_eq!(config.model.route.cheap, "ollama:llama3.1");
1146
1147 std::fs::write(&paths.project, "[ui]\nstatus_line = false\n").unwrap();
1149 assert!(!load_config(&paths, &Overrides::default()).unwrap().ui.tui);
1150 std::fs::write(dir.join("user.toml"), "[ui]\ntui = true\n").unwrap();
1152 let config = load_config(&paths, &Overrides::default()).unwrap();
1153 assert!(config.ui.tui);
1154 assert!(!config.table["ui"]
1155 .as_table()
1156 .unwrap()
1157 .contains_key("status_line"));
1158 let _ = std::fs::remove_dir_all(&dir);
1159 }
1160
1161 #[test]
1162 fn thinking_and_tool_use_default_to_summary_and_take_the_three_levels() {
1163 let dir = temp_dir("display-levels");
1164 let paths = paths_in(&dir);
1165 let config = load_config(&paths, &Overrides::default()).unwrap();
1166 assert_eq!(config.ui.thinking, DisplayLevel::Summary);
1167 assert_eq!(config.ui.tool_use, DisplayLevel::Summary);
1168
1169 std::fs::write(
1170 &paths.project,
1171 "[ui]\nthinking = \"full\"\ntool_use = \"hidden\"\n",
1172 )
1173 .unwrap();
1174 let config = load_config(&paths, &Overrides::default()).unwrap();
1175 assert_eq!(config.ui.thinking, DisplayLevel::Full);
1176 assert_eq!(config.ui.tool_use, DisplayLevel::Hidden);
1177
1178 std::fs::write(&paths.project, "[ui]\nthinking = \"loud\"\n").unwrap();
1180 let error = load_config(&paths, &Overrides::default())
1181 .unwrap_err()
1182 .to_string();
1183 assert!(
1184 error.contains("loud") && error.contains("full") && error.contains("hidden"),
1185 "{error}"
1186 );
1187 let _ = std::fs::remove_dir_all(&dir);
1188 }
1189
1190 #[test]
1191 fn agent86ui_defaults_to_auto_without_remote_media() {
1192 let dir = temp_dir("agent86ui-settings");
1193 let paths = paths_in(&dir);
1194 let config = load_config(&paths, &Overrides::default()).unwrap();
1195 assert_eq!(config.ui.agent86ui, Agent86UiMode::Auto);
1196 assert!(!config.ui.agent86ui_remote_media);
1197
1198 std::fs::write(
1199 &paths.project,
1200 "[ui]\nagent86ui = \"off\"\nagent86ui_remote_media = true\n",
1201 )
1202 .unwrap();
1203 let config = load_config(&paths, &Overrides::default()).unwrap();
1204 assert_eq!(config.ui.agent86ui, Agent86UiMode::Off);
1205 assert!(config.ui.agent86ui_remote_media);
1206
1207 std::fs::write(&paths.project, "[ui]\nagent86ui = \"on\"\n").unwrap();
1208 let error = load_config(&paths, &Overrides::default())
1209 .unwrap_err()
1210 .to_string();
1211 assert!(error.contains("auto") && error.contains("off"), "{error}");
1212 let _ = std::fs::remove_dir_all(&dir);
1213 }
1214
1215 #[test]
1216 fn ask_user_defaults_to_auto_and_can_be_turned_off() {
1217 let dir = temp_dir("ask-user-setting");
1218 let paths = paths_in(&dir);
1219 let config = load_config(&paths, &Overrides::default()).unwrap();
1220 assert_eq!(config.ui.ask_user, AskUserMode::Auto);
1221 std::fs::write(&paths.project, "[ui]\nask_user = \"off\"\n").unwrap();
1222 let config = load_config(&paths, &Overrides::default()).unwrap();
1223 assert_eq!(config.ui.ask_user, AskUserMode::Off);
1224 let _ = std::fs::remove_dir_all(&dir);
1225 }
1226
1227 #[test]
1228 fn display_levels_parse_cycle_and_name_themselves() {
1229 assert_eq!(DisplayLevel::parse(" Hidden "), Some(DisplayLevel::Hidden));
1230 assert_eq!(DisplayLevel::parse("loud"), None);
1231 let cycle: Vec<&str> =
1232 std::iter::successors(Some(DisplayLevel::Full), |level| Some(level.next()))
1233 .take(4)
1234 .map(DisplayLevel::as_str)
1235 .collect();
1236 assert_eq!(cycle, ["full", "summary", "hidden", "full"]);
1237 }
1238
1239 #[test]
1240 fn defaults_include_the_builtin_providers() {
1241 let dir = temp_dir("defaults");
1242 let config = load_config(&paths_in(&dir), &Overrides::default()).unwrap();
1243
1244 assert_eq!(config.model.default, "anthropic:claude-opus-4-8");
1245 let openrouter = &config.providers["openrouter"];
1246 assert_eq!(
1247 openrouter.api_key_env.as_deref(),
1248 Some("OPENROUTER_API_KEY")
1249 );
1250 assert_eq!(
1251 openrouter.base_url.as_deref(),
1252 Some("https://openrouter.ai/api/v1")
1253 );
1254 assert_eq!(openrouter.read_timeout_s, 300.0);
1255 assert_eq!(config.max_output_tokens_for("openrouter"), 8192);
1256 assert!(config.sources.is_empty());
1257 assert_eq!(openrouter.routing, None);
1258 }
1259
1260 #[test]
1261 fn a_routing_table_is_read_as_json() {
1262 let dir = temp_dir("routing");
1263 let paths = paths_in(&dir);
1264 std::fs::write(
1265 &paths.project,
1266 "[providers.openrouter.routing]\nignore = [\"Phala\"]\nallow_fallbacks = true\n",
1267 )
1268 .unwrap();
1269 let config = load_config(&paths, &Overrides::default()).unwrap();
1270 let routing = config.providers["openrouter"].routing.clone().unwrap();
1271 assert_eq!(
1272 serde_json::Value::Object(routing),
1273 serde_json::json!({"ignore": ["Phala"], "allow_fallbacks": true})
1274 );
1275 let _ = std::fs::remove_dir_all(&dir);
1276 }
1277
1278 #[test]
1279 fn layers_deep_merge_and_overrides_win() {
1280 let dir = temp_dir("layers");
1281 std::fs::write(
1282 dir.join("user.toml"),
1283 "[model]\ndefault = \"openrouter:a\"\n[providers.openrouter]\nmax_tokens = 512\n",
1284 )
1285 .unwrap();
1286 std::fs::write(
1287 dir.join("project.toml"),
1288 "[providers.openrouter]\nbase_url = \"http://localhost:9\"\n[providers.mine]\nbase_url = \"http://x\"\n[tools]\nanything = 1\n",
1289 )
1290 .unwrap();
1291
1292 let config = load_config(&paths_in(&dir), &Overrides::default()).unwrap();
1293 let openrouter = &config.providers["openrouter"];
1294 assert_eq!(config.model.default, "openrouter:a");
1295 assert_eq!(openrouter.base_url.as_deref(), Some("http://localhost:9"));
1296 assert_eq!(
1297 openrouter.api_key_env.as_deref(),
1298 Some("OPENROUTER_API_KEY")
1299 );
1300 assert_eq!(config.max_output_tokens_for("openrouter"), 512);
1301 assert!(config.providers.contains_key("groq"));
1302 assert_eq!(config.providers["mine"].max_retries, 2);
1303 assert_eq!(config.sources.len(), 2);
1304
1305 let env = Overrides {
1306 env_model: Some("groq:b".to_owned()),
1307 ..Overrides::default()
1308 };
1309 assert_eq!(
1310 load_config(&paths_in(&dir), &env).unwrap().model.default,
1311 "groq:b"
1312 );
1313
1314 let flag = Overrides {
1315 env_model: Some("groq:b".to_owned()),
1316 model: Some("openai:c".to_owned()),
1317 ..Overrides::default()
1318 };
1319 assert_eq!(
1320 load_config(&paths_in(&dir), &flag).unwrap().model.default,
1321 "openai:c"
1322 );
1323 }
1324
1325 #[test]
1326 fn malformed_toml_names_the_file() {
1327 let dir = temp_dir("malformed");
1328 std::fs::write(dir.join("project.toml"), "[model\n").unwrap();
1329
1330 let error = load_config(&paths_in(&dir), &Overrides::default()).unwrap_err();
1331 let ConfigError::Malformed { path, .. } = &error else {
1332 panic!("{error:?}");
1333 };
1334 assert!(path.ends_with("project.toml"));
1335 assert!(error.to_string().starts_with("Malformed config at "));
1336 }
1337
1338 #[test]
1339 fn pricing_overrides_load_and_negative_prices_are_rejected() {
1340 let dir = temp_dir("pricing");
1341 std::fs::write(
1342 dir.join("project.toml"),
1343 "[pricing.models.\"openrouter:openai/gpt-4o-mini\"]\ninput_per_mtok = 0.15\noutput_per_mtok = 0.6\n",
1344 )
1345 .unwrap();
1346 let config = load_config(&paths_in(&dir), &Overrides::default()).unwrap();
1347 let price = config.pricing.models["openrouter:openai/gpt-4o-mini"];
1348 assert_eq!(price.input_per_mtok, 0.15);
1349 assert_eq!(price.output_per_mtok, 0.6);
1350
1351 std::fs::write(
1352 dir.join("project.toml"),
1353 "[pricing.models.cheap]\ninput_per_mtok = -1\noutput_per_mtok = 0\n",
1354 )
1355 .unwrap();
1356 let error = load_config(&paths_in(&dir), &Overrides::default()).unwrap_err();
1357 assert!(matches!(error, ConfigError::Invalid { .. }), "{error:?}");
1358 assert!(error.to_string().contains("input_per_mtok"), "{error}");
1359 }
1360
1361 #[test]
1362 fn sandbox_mode_defaults_to_subprocess_and_rejects_unknown_values() {
1363 let dir = temp_dir("sandbox");
1364 let config = load_config(&paths_in(&dir), &Overrides::default()).unwrap();
1365 assert_eq!(config.sandbox.mode, SandboxMode::Subprocess);
1366
1367 let env = Overrides {
1368 env_sandbox: Some("docker".to_owned()),
1369 ..Overrides::default()
1370 };
1371 assert_eq!(
1372 load_config(&paths_in(&dir), &env).unwrap().sandbox.mode,
1373 SandboxMode::Docker
1374 );
1375 let flag = Overrides {
1377 sandbox: Some("subprocess".to_owned()),
1378 ..env
1379 };
1380 assert_eq!(
1381 load_config(&paths_in(&dir), &flag).unwrap().sandbox.mode,
1382 SandboxMode::Subprocess
1383 );
1384
1385 std::fs::write(
1386 dir.join("project.toml"),
1387 "[sandbox]
1388mode = \"vm\"
1389",
1390 )
1391 .unwrap();
1392 let error = load_config(&paths_in(&dir), &Overrides::default()).unwrap_err();
1393 assert!(matches!(error, ConfigError::Invalid { .. }), "{error:?}");
1394 }
1395}