1use crate::error::{Error, Result};
14use serde::{Deserialize, Serialize};
15use std::collections::BTreeMap;
16use std::fmt;
17use std::path::{Path, PathBuf};
18
19pub const APP_DIR: &str = "eclipse";
20
21pub const CONFIG_VERSION: u32 = 1;
28
29pub type EnvFn<'a> = &'a dyn Fn(&str) -> Option<String>;
31
32pub fn process_env(key: &str) -> Option<String> {
33 std::env::var(key).ok().filter(|v| !v.is_empty())
34}
35
36pub(crate) fn home_dir(env: EnvFn) -> Option<PathBuf> {
37 env("HOME").map(PathBuf::from)
38}
39
40pub fn home_root(env: EnvFn) -> Option<PathBuf> {
53 if let Some(p) = env("ECLIPSE_HOME") {
54 if !p.is_empty() {
55 return Some(expand_tilde(Path::new(&p), env));
56 }
57 }
58 home_dir(env).map(|h| h.join(".eclipse"))
59}
60
61pub fn config_dir(env: EnvFn) -> Option<PathBuf> {
65 home_root(env)
66}
67
68pub fn state_dir(env: EnvFn) -> Option<PathBuf> {
72 home_root(env).map(|r| r.join("state"))
73}
74
75pub fn ensure_layout(root: &Path) -> std::io::Result<()> {
83 for dir in [
84 "",
85 "bin",
86 "memory",
87 "skills",
88 "plugins",
89 "profiles",
90 "workspace",
91 "state",
92 ] {
93 let p = if dir.is_empty() {
94 root.to_path_buf()
95 } else {
96 root.join(dir)
97 };
98 std::fs::create_dir_all(&p)?;
99 }
100 Ok(())
101}
102
103pub const STARTER_AGENT_MD: &str = "# How to work here
106# This file is injected into the system prompt on every run, along with USER.md and MEMORY.md.
107# Edit the lines below to describe this project: conventions, commands, gotchas.
108
109You are a direct, practical assistant. Read before acting, say what you are doing,
110and keep a reply short unless it needs to be long. Use the workspace and tools to verify
111what you are about to do, rather than describing it.
112
113MEMORY.md is for facts about the user and their machines. A procedure — the steps, commands and
114pitfalls for a kind of task — belongs in a skill: `skill_manage` writes one, and only its name and
115description sit in the prompt until the task calls for it.
116";
117
118pub const STARTER_USER_MD: &str = "# Who the operator is
121# This file is injected into the system prompt on every run. Describe the person who owns
122# this install — who they are, what they do, and the preferences you should follow.
123
124The operator is the person who owns this install. Edit this file with their name,
125what they do, and standing preferences. Keep it short: this is who they are,
126not a data dump.
127";
128
129pub fn seed_context_files(memory_dir: &Path) -> Result<Vec<PathBuf>> {
145 std::fs::create_dir_all(memory_dir).map_err(|e| Error::io(memory_dir, e))?;
146 let mut created = Vec::new();
147 for (name, body) in [
148 ("AGENT.md", STARTER_AGENT_MD),
149 ("USER.md", STARTER_USER_MD),
150 ("MEMORY.md", ""),
153 ] {
154 let path = memory_dir.join(name);
155 if path.exists() {
156 continue;
157 }
158 std::fs::write(&path, body).map_err(|e| Error::io(&path, e))?;
159 created.push(path);
160 }
161 Ok(created)
162}
163
164mod check;
165pub mod migrate;
166mod settings;
167
168pub use check::{unknown_keys_in_file, UnknownKey};
169pub use migrate::{baseline_path, plan as migration_plan, Change, Plan};
170pub use settings::{
171 about, choices, parse_value, set_in_text, set_list_in_text, unset_in_text, Applies, Kind,
172 Setting,
173};
174
175pub fn config_path(env: EnvFn) -> Option<PathBuf> {
177 if let Some(p) = env("ECLIPSE_CONFIG") {
178 return Some(PathBuf::from(p));
179 }
180 config_dir(env).map(|d| d.join("config.toml"))
181}
182
183pub fn validate_profile_name(name: &str) -> Result<()> {
186 let ok = !name.is_empty()
187 && name.len() <= 64
188 && name
189 .chars()
190 .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');
191 if ok {
192 Ok(())
193 } else {
194 Err(Error::Config(format!("invalid profile name {name:?}")))
195 }
196}
197
198pub fn profile_dir(env: EnvFn, name: &str) -> Option<PathBuf> {
201 home_root(env).map(|d| d.join("profiles").join(name))
202}
203
204pub fn write_target(
220 root: Option<&Path>,
221 explicit: Option<&Path>,
222 base: Option<&Path>,
223 profile: Option<&str>,
224) -> Option<PathBuf> {
225 if let Some(path) = explicit {
226 return Some(path.to_path_buf());
227 }
228 match profile {
229 None | Some("default") => base.map(Path::to_path_buf),
230 Some(name) => {
231 validate_profile_name(name).ok()?;
232 Some(root?.join("profiles").join(name).join("config.toml"))
233 }
234 }
235}
236
237pub fn state_dir_for(env: EnvFn, profile: Option<&str>) -> Option<PathBuf> {
241 match profile {
242 None | Some("default") => state_dir(env),
243 Some(name) => profile_dir(env, name).map(|d| d.join("state")),
244 }
245}
246
247fn expand_tilde(p: &Path, env: EnvFn) -> PathBuf {
248 if let Ok(rest) = p.strip_prefix("~") {
249 if let Some(h) = home_dir(env) {
250 return h.join(rest);
251 }
252 }
253 p.to_path_buf()
254}
255
256#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
259#[serde(rename_all = "lowercase")]
260pub enum FetchHtml {
261 Text,
263 Raw,
265}
266
267#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
269#[serde(rename_all = "lowercase")]
270pub enum ShellIsolate {
271 Off,
273 Process,
276 Fs,
280}
281
282impl std::fmt::Display for ShellIsolate {
283 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
284 f.write_str(match self {
285 Self::Off => "off",
286 Self::Process => "process",
287 Self::Fs => "fs",
288 })
289 }
290}
291
292#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
293#[serde(rename_all = "lowercase")]
294pub enum Policy {
295 Deny,
297 Ask,
301 Allow,
303}
304
305#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
307#[serde(rename_all = "lowercase")]
308pub enum ShellAsk {
309 #[default]
311 Dangerous,
312 Always,
315}
316
317#[derive(Clone, Default, PartialEq, Eq)]
327pub struct Dotenv {
328 pub files: Vec<PathBuf>,
330 pub values: BTreeMap<String, String>,
331}
332
333impl fmt::Debug for Dotenv {
334 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
335 f.debug_struct("Dotenv")
340 .field("files", &self.files)
341 .field("keys", &self.values.keys().collect::<Vec<_>>())
342 .finish()
343 }
344}
345
346impl Dotenv {
347 pub fn load(env: EnvFn<'_>, profile: Option<&str>) -> Result<Dotenv> {
349 let Some(dir) = config_dir(env) else {
350 return Ok(Dotenv::default());
351 };
352 let mut candidates = vec![dir.join(".env")];
353 if let Some(p) = profile {
354 validate_profile_name(p)?;
355 candidates.push(dir.join("profiles").join(p).join(".env"));
356 }
357 let mut values = BTreeMap::new();
358 let mut files = Vec::new();
359 for path in candidates {
360 if !path.exists() {
361 continue;
362 }
363 for assignment in crate::dotenv::load(&path)? {
369 if assignment.value.is_empty() {
370 values.remove(&assignment.key);
371 continue;
372 }
373 values.insert(assignment.key, assignment.value);
374 }
375 files.push(path);
376 }
377 Ok(Dotenv { files, values })
378 }
379}
380
381fn empty_is_none<'de, D>(d: D) -> std::result::Result<Option<String>, D::Error>
390where
391 D: serde::Deserializer<'de>,
392{
393 use serde::Deserialize;
394 Ok(Option::<String>::deserialize(d)?.filter(|v| !v.is_empty()))
395}
396
397#[derive(Clone, PartialEq, Serialize, Deserialize)]
398#[serde(default)]
399pub struct ProviderConfig {
400 pub base_url: String,
402 #[serde(deserialize_with = "empty_is_none")]
404 pub api_key: Option<String>,
405 #[serde(deserialize_with = "empty_is_none")]
407 pub api_key_env: Option<String>,
408 pub model: String,
409 pub temperature: Option<f64>,
410 pub timeout_secs: u64,
411 pub stream: bool,
414 pub max_retries: u32,
423 pub retry_after_send: bool,
428 pub retry_base_delay_ms: u64,
429 pub context_budget_tokens: usize,
433 pub max_tokens: Option<u32>,
436 #[serde(deserialize_with = "empty_is_none")]
439 pub profile: Option<String>,
440 pub top_p: Option<f64>,
443 pub seed: Option<i64>,
445 pub stop: Option<Vec<String>>,
447 #[serde(deserialize_with = "empty_is_none")]
452 pub reasoning_effort: Option<String>,
453 pub parallel_tool_calls: Option<bool>,
455 pub vision: Option<bool>,
460 pub tool_choice: Option<crate::hooks::ToolChoice>,
463 pub extra_body: Option<serde_json::Value>,
467 #[serde(skip_serializing_if = "Option::is_none")]
471 pub fallback: Option<Vec<String>>,
472 #[serde(skip_serializing_if = "Option::is_none")]
476 #[serde(deserialize_with = "empty_is_none")]
477 pub aux: Option<String>,
478 #[serde(skip_serializing_if = "Option::is_none")]
482 #[serde(deserialize_with = "empty_is_none")]
483 pub delegate: Option<String>,
484 #[serde(skip_serializing_if = "Vec::is_empty")]
487 pub route: Vec<RouteConfig>,
488}
489
490#[derive(Debug, Clone, PartialEq, Serialize)]
496pub struct RouteConfig {
497 pub name: String,
499 #[serde(skip_serializing_if = "Option::is_none")]
505 pub max_parallel: Option<usize>,
506 #[serde(skip_serializing_if = "Option::is_none")]
511 pub group: Option<String>,
512 #[serde(flatten)]
513 pub config: ProviderConfig,
514}
515
516impl<'de> Deserialize<'de> for RouteConfig {
520 fn deserialize<D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Self, D::Error> {
521 use serde::de::Error as _;
522 let mut table = toml::Table::deserialize(d)?;
523 let name = match table.remove("name") {
524 None => String::new(),
525 Some(toml::Value::String(name)) => name,
526 Some(other) => {
527 return Err(D::Error::custom(format!(
528 "provider.route `name` must be a string, got {}",
529 other.type_str()
530 )))
531 }
532 };
533 let label = if name.is_empty() {
534 "an unnamed route".to_string()
535 } else {
536 format!("route `{name}`")
537 };
538 let max_parallel = match table.remove("max_parallel") {
542 None => None,
543 Some(toml::Value::Integer(n)) if n >= 0 => Some(n as usize),
544 Some(other) => {
545 return Err(D::Error::custom(format!(
546 "{label}: `max_parallel` must be a positive integer, got {}",
547 other.type_str()
548 )))
549 }
550 };
551 let group = match table.remove("group") {
552 None => None,
553 Some(toml::Value::String(g)) if !g.trim().is_empty() => Some(g),
554 Some(_) => {
555 return Err(D::Error::custom(format!(
556 "{label}: `group` must be a non-empty string"
557 )))
558 }
559 };
560 let config = ProviderConfig::deserialize(toml::Value::Table(table))
561 .map_err(|e| D::Error::custom(format!("{label}: {e}")))?;
562 Ok(Self {
563 name,
564 max_parallel,
565 group,
566 config,
567 })
568 }
569}
570
571pub const DEFAULT_ROUTE: &str = "default";
573
574impl ProviderConfig {
575 fn declares_connection(&self) -> bool {
584 !self.base_url.trim().is_empty()
585 || !self.model.trim().is_empty()
586 || self.api_key.is_some()
587 || self.api_key_env.is_some()
588 }
589}
590
591#[derive(Debug, Clone, PartialEq)]
594pub struct NamedRoute {
595 pub name: String,
596 pub max_parallel: Option<usize>,
598 pub group: Option<String>,
600 pub config: ProviderConfig,
601}
602
603impl NamedRoute {
604 pub fn default_parallel(&self) -> usize {
609 let profile = self.config.profile.as_deref().unwrap_or("openai");
610 if profile.eq_ignore_ascii_case("openai") {
611 4
612 } else {
613 1
614 }
615 }
616
617 pub fn parallel(&self) -> usize {
619 self.max_parallel
620 .unwrap_or_else(|| self.default_parallel())
621 .max(1)
622 }
623
624 pub fn with_flare_shape(mut self, max_parallel: Option<usize>, group: Option<String>) -> Self {
627 self.max_parallel = max_parallel;
628 self.group = group;
629 self
630 }
631
632 fn new(name: &str, config: &ProviderConfig) -> Self {
633 let mut config = config.clone();
634 config.route.clear();
635 config.fallback = None;
636 config.aux = None;
637 config.delegate = None;
638 Self {
639 name: name.to_string(),
640 max_parallel: None,
641 group: None,
642 config,
643 }
644 }
645
646 fn require_endpoint(&self, source: ChainSource) -> Result<()> {
648 let plain = self.name == DEFAULT_ROUTE && source == ChainSource::Default;
649 let missing = |key: &str, hint: &str| {
650 Error::Config(if plain {
651 format!("provider.{key} is not set {hint}")
652 } else {
653 format!("route `{}` has no {key}", self.name)
654 })
655 };
656 if self.config.base_url.trim().is_empty() {
657 return Err(missing(
658 "base_url",
659 "(config file or ECLIPSE_BASE_URL); run `eclipse config init`",
660 ));
661 }
662 if self.config.model.trim().is_empty() {
663 return Err(missing("model", "(config file or ECLIPSE_MODEL)"));
664 }
665 Ok(())
666 }
667}
668
669#[derive(Debug, Clone, Copy, PartialEq, Eq)]
671pub enum ChainSource {
672 Default,
674 Fallback,
676 Pinned,
678}
679
680#[derive(Debug, Clone, PartialEq)]
682pub struct Chain {
683 pub routes: Vec<NamedRoute>,
684 pub source: ChainSource,
685 pub aux: Option<NamedRoute>,
687 pub delegate: Option<NamedRoute>,
689}
690
691impl Chain {
692 pub fn roles(&self) -> Vec<crate::router::RoleRoute> {
694 crate::router::role_table(
695 self.aux.as_ref().map(|r| r.name.as_str()),
696 self.delegate.as_ref().map(|r| r.name.as_str()),
697 self.routes.first().map_or("", |r| r.name.as_str()),
698 self.source == ChainSource::Pinned,
699 )
700 }
701}
702
703fn apply_key_env(cfg: &mut ProviderConfig, env: EnvFn, explicit: Option<String>) {
706 if let Some(v) = explicit {
707 cfg.api_key = Some(v);
708 } else if let Some(name) = cfg.api_key_env.clone() {
709 if let Some(v) = env(&name) {
710 cfg.api_key = Some(v);
711 }
712 }
713}
714
715impl Default for ProviderConfig {
716 fn default() -> Self {
717 Self {
718 base_url: String::new(),
719 api_key: None,
720 api_key_env: None,
721 model: String::new(),
722 temperature: None,
723 timeout_secs: 120,
724 stream: true,
725 max_retries: 3,
726 retry_after_send: false,
727 retry_base_delay_ms: 2000,
728 context_budget_tokens: 0,
729 max_tokens: None,
730 profile: None,
731 top_p: None,
732 seed: None,
733 stop: None,
734 reasoning_effort: None,
735 parallel_tool_calls: None,
736 vision: None,
737 tool_choice: None,
738 extra_body: None,
739 fallback: None,
740 aux: None,
741 delegate: None,
742 route: Vec::new(),
743 }
744 }
745}
746
747impl fmt::Debug for ProviderConfig {
748 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
749 f.debug_struct("ProviderConfig")
750 .field(
753 "base_url",
754 &redact_url(&self.base_url).unwrap_or_else(|| self.base_url.clone()),
755 )
756 .field("api_key", &self.api_key.as_ref().map(|_| "<redacted>"))
757 .field("api_key_env", &self.api_key_env)
758 .field("model", &self.model)
759 .field("temperature", &self.temperature)
760 .field("timeout_secs", &self.timeout_secs)
761 .field("stream", &self.stream)
762 .field("max_retries", &self.max_retries)
763 .field("retry_after_send", &self.retry_after_send)
764 .field("retry_base_delay_ms", &self.retry_base_delay_ms)
765 .field("context_budget_tokens", &self.context_budget_tokens)
766 .field("vision", &self.vision)
767 .field("fallback", &self.fallback)
768 .field("aux", &self.aux)
769 .field("delegate", &self.delegate)
770 .field("route", &self.route)
771 .finish()
772 }
773}
774
775#[derive(Debug, Clone, Serialize, Deserialize)]
776#[serde(default)]
777pub struct AgentConfig {
778 pub max_consecutive_malformed_tool_calls: usize,
782 pub system_prompt: String,
783 #[serde(
788 default = "unlimited_turns",
789 deserialize_with = "de_turn_limit",
790 serialize_with = "ser_turn_limit"
791 )]
792 pub max_iterations: usize,
793 #[serde(deserialize_with = "empty_is_none")]
797 pub output_schema: Option<String>,
798 pub context_file_max_chars: usize,
801 pub context_files_budget_chars: usize,
804 pub trace_content: bool,
807 pub prompt_blocks: crate::prompt_blocks::Choice,
811}
812
813fn unlimited_turns() -> usize {
816 usize::MAX
817}
818
819fn de_turn_limit<'de, D>(d: D) -> std::result::Result<usize, D::Error>
823where
824 D: serde::Deserializer<'de>,
825{
826 #[derive(serde::Deserialize)]
827 #[serde(untagged)]
828 enum Raw {
829 Number(i64),
830 Word(String),
831 }
832 let n = match Raw::deserialize(d)? {
833 Raw::Number(n) => n,
834 Raw::Word(word) => match word.trim().to_ascii_lowercase().as_str() {
835 "unlimited" | "none" | "null" | "inf" | "infinite" | "infinity" | "∞" => 0,
836 other => other.parse::<i64>().map_err(|_| {
837 serde::de::Error::custom(format!(
838 "`max_iterations` takes a whole number or `unlimited`, not `{other}`"
839 ))
840 })?,
841 },
842 };
843 Ok(if n <= 0 {
844 unlimited_turns()
845 } else {
846 n as usize
847 })
848}
849
850fn ser_turn_limit<S>(value: &usize, s: S) -> std::result::Result<S::Ok, S::Error>
853where
854 S: serde::Serializer,
855{
856 if *value == usize::MAX {
857 s.serialize_str("unlimited")
858 } else {
859 s.serialize_u64(*value as u64)
860 }
861}
862
863impl Default for AgentConfig {
864 fn default() -> Self {
865 Self {
866 system_prompt:
867 "You are a helpful personal assistant running locally on the user's machine. \
868Use tools only when they are needed, and explain briefly what you did."
869 .into(),
870 max_iterations: unlimited_turns(),
871 output_schema: None,
872 max_consecutive_malformed_tool_calls: 0,
873 context_file_max_chars: crate::context_files::DEFAULT_MAX_FILE_CHARS,
874 context_files_budget_chars: crate::context_files::DEFAULT_BUDGET_CHARS,
875 trace_content: false,
876 prompt_blocks: crate::prompt_blocks::Choice::Auto,
877 }
878 }
879}
880
881#[derive(Debug, Clone, Serialize, Deserialize)]
882#[serde(default)]
883pub struct ToolsConfig {
884 pub workspace_root: Option<PathBuf>,
886 pub read_file: Policy,
887 pub search_files: Policy,
891 pub write_file: Policy,
892 #[serde(default = "default_rewrite_guard")]
897 pub rewrite_guard_bytes: usize,
898 pub patch: Policy,
901 pub memory: Policy,
906 pub shell: Policy,
907 pub fetch: Policy,
908 pub script: Policy,
912 pub execute_code: Policy,
917 pub delegate: Policy,
921 pub shell_ask: ShellAsk,
925 pub shell_timeout_secs: u64,
926 pub shell_allowlist: Vec<String>,
928 pub shell_isolate: ShellIsolate,
933 pub shell_isolate_writable: Vec<PathBuf>,
936 pub shell_isolate_hide: Vec<PathBuf>,
939 pub shell_isolate_network: bool,
942 pub fetch_timeout_secs: u64,
943 pub fetch_html: FetchHtml,
946 pub max_output_bytes: usize,
948 pub concurrency: usize,
952 pub disabled: Vec<String>,
956 #[serde(default = "default_deferred")]
969 pub deferred: Vec<String>,
970 pub tool_search: Policy,
975 pub tool_describe: Policy,
976 pub tool_call: Policy,
977}
978
979pub fn default_hidden_paths() -> Vec<PathBuf> {
991 ["~/.ssh", "~/.gnupg", "~/.aws", "~/.hermes"]
992 .iter()
993 .map(PathBuf::from)
994 .collect()
995}
996
997fn default_deferred() -> Vec<String> {
1005 vec!["plugin:mcp:*".to_string(), "config:mcp:*".to_string()]
1006}
1007
1008fn default_rewrite_guard() -> usize {
1009 32 * 1024
1010}
1011
1012impl Default for ToolsConfig {
1013 fn default() -> Self {
1014 Self {
1015 workspace_root: None,
1016 read_file: Policy::Allow,
1017 search_files: Policy::Allow,
1018 write_file: Policy::Allow,
1022 rewrite_guard_bytes: default_rewrite_guard(),
1023 patch: Policy::Allow,
1024 memory: Policy::Ask,
1025 shell: Policy::Ask,
1026 fetch: Policy::Ask,
1027 script: Policy::Ask,
1028 execute_code: Policy::Ask,
1029 delegate: Policy::Ask,
1030 shell_ask: ShellAsk::Dangerous,
1031 shell_timeout_secs: 30,
1032 shell_allowlist: Vec::new(),
1033 shell_isolate: ShellIsolate::Process,
1034 shell_isolate_writable: Vec::new(),
1035 shell_isolate_hide: default_hidden_paths(),
1036 shell_isolate_network: true,
1037 fetch_timeout_secs: 20,
1038 fetch_html: FetchHtml::Text,
1039 max_output_bytes: 32 * 1024,
1040 concurrency: 1,
1041 disabled: Vec::new(),
1042 deferred: default_deferred(),
1043 tool_search: Policy::Allow,
1044 tool_describe: Policy::Allow,
1045 tool_call: Policy::Allow,
1046 }
1047 }
1048}
1049
1050#[derive(Debug, Clone, Serialize, Deserialize)]
1051#[serde(default)]
1052pub struct SessionsConfig {
1053 pub dir: Option<PathBuf>,
1055 pub retention_keep_days: u64,
1058 pub retention_keep_count: usize,
1061 pub auto_prune: bool,
1066 pub lock_wait_secs: u64,
1069 pub autotitle: bool,
1073}
1074
1075impl Default for SessionsConfig {
1076 fn default() -> Self {
1077 Self {
1078 dir: None,
1079 retention_keep_days: 0,
1080 retention_keep_count: 0,
1081 auto_prune: false,
1082 lock_wait_secs: 30,
1083 autotitle: true,
1084 }
1085 }
1086}
1087
1088#[derive(Clone, Serialize, Deserialize)]
1089#[serde(default)]
1090pub struct WebConfig {
1091 pub host: String,
1092 pub port: u16,
1093 #[serde(deserialize_with = "empty_is_none")]
1096 pub auth_token: Option<String>,
1097 pub session_ttl_hours: u64,
1100 #[serde(deserialize_with = "empty_is_none")]
1103 pub default_profile: Option<String>,
1104}
1105
1106impl Default for WebConfig {
1107 fn default() -> Self {
1108 Self {
1109 host: "127.0.0.1".into(),
1110 port: 8787,
1111 auth_token: None,
1112 session_ttl_hours: DEFAULT_SESSION_TTL_HOURS,
1113 default_profile: None,
1114 }
1115 }
1116}
1117
1118#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1120#[serde(default)]
1121pub struct GatewayConfig {
1122 pub check_interval_hours: u64,
1126 #[serde(default = "default_api_session_ttl_hours")]
1130 pub api_session_ttl_hours: u64,
1131}
1132
1133pub fn default_api_session_ttl_hours() -> u64 {
1134 24
1135}
1136
1137impl Default for GatewayConfig {
1138 fn default() -> Self {
1139 Self {
1140 check_interval_hours: 6,
1141 api_session_ttl_hours: default_api_session_ttl_hours(),
1142 }
1143 }
1144}
1145
1146pub const DEFAULT_SESSION_TTL_HOURS: u64 = 12;
1148
1149#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
1151#[serde(rename_all = "lowercase")]
1152pub enum Approval {
1153 #[default]
1155 Ask,
1156 Auto,
1158 Smart,
1164}
1165
1166#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1169#[serde(default)]
1170pub struct CliConfig {
1171 pub color: Option<bool>,
1173 pub markdown: Option<bool>,
1175 pub approval: Approval,
1178 pub history_size: usize,
1180 pub clear_on_exit: ClearOnExit,
1182}
1183
1184impl Default for CliConfig {
1185 fn default() -> Self {
1186 Self {
1187 color: None,
1188 markdown: None,
1189 approval: Approval::Ask,
1190 history_size: 1000,
1192 clear_on_exit: ClearOnExit::Screen,
1193 }
1194 }
1195}
1196
1197#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
1203#[serde(rename_all = "lowercase")]
1204pub enum ClearOnExit {
1205 #[default]
1208 Screen,
1209 All,
1211 Off,
1213}
1214
1215#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
1217#[serde(rename_all = "lowercase")]
1218pub enum UpdateCheck {
1219 #[default]
1221 Daily,
1222 Weekly,
1223 Off,
1225}
1226
1227impl UpdateCheck {
1228 pub fn period_secs(self) -> Option<u64> {
1230 match self {
1231 UpdateCheck::Daily => Some(86_400),
1232 UpdateCheck::Weekly => Some(7 * 86_400),
1233 UpdateCheck::Off => None,
1234 }
1235 }
1236}
1237
1238#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
1245#[serde(rename_all = "lowercase")]
1246pub enum Track {
1247 #[default]
1250 Release,
1251 Develop,
1253}
1254
1255impl Track {
1256 pub fn label(self) -> &'static str {
1258 match self {
1259 Track::Release => "release",
1260 Track::Develop => "develop",
1261 }
1262 }
1263
1264 pub fn branch(self) -> &'static str {
1267 match self {
1268 Track::Release => "main",
1269 Track::Develop => "develop",
1270 }
1271 }
1272}
1273
1274#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1280#[serde(default)]
1281pub struct HooksConfig {
1282 pub order: Vec<String>,
1283 #[serde(flatten)]
1286 pub settings: BTreeMap<String, toml::Value>,
1287}
1288
1289impl Default for HooksConfig {
1290 fn default() -> Self {
1291 Self {
1292 order: crate::hooks::DEFAULT_ORDER
1293 .iter()
1294 .map(|n| n.to_string())
1295 .collect(),
1296 settings: BTreeMap::new(),
1297 }
1298 }
1299}
1300
1301#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1304#[serde(default)]
1305pub struct UpdateConfig {
1306 pub check: UpdateCheck,
1307 pub track: Track,
1313 #[serde(deserialize_with = "empty_is_none")]
1318 pub remote: Option<String>,
1319 #[serde(deserialize_with = "empty_is_none")]
1324 pub releases: Option<String>,
1325}
1326
1327impl fmt::Debug for WebConfig {
1328 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1329 f.debug_struct("WebConfig")
1330 .field("host", &self.host)
1331 .field("port", &self.port)
1332 .field(
1333 "auth_token",
1334 &self.auth_token.as_ref().map(|_| "<redacted>"),
1335 )
1336 .finish()
1337 }
1338}
1339
1340#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1346#[serde(default)]
1347pub struct AttachmentsConfig {
1348 pub dir: Option<PathBuf>,
1352 pub max_total_bytes: u64,
1356}
1357
1358impl Default for AttachmentsConfig {
1359 fn default() -> Self {
1360 Self {
1361 dir: None,
1362 max_total_bytes: 2 * 1024 * 1024 * 1024,
1363 }
1364 }
1365}
1366
1367#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1368#[serde(default)]
1369pub struct Config {
1370 pub config_version: u32,
1377 pub provider: ProviderConfig,
1378 pub agent: AgentConfig,
1379 pub tools: ToolsConfig,
1380 pub sessions: SessionsConfig,
1381 pub attachments: AttachmentsConfig,
1382 pub plugins: PluginsConfig,
1383 pub web: WebConfig,
1384 pub gateway: GatewayConfig,
1385 pub cli: CliConfig,
1386 pub update: UpdateConfig,
1387 pub hooks: HooksConfig,
1388 pub context: ContextPolicyConfig,
1389 pub user: UserConfig,
1390 pub skills: SkillsConfig,
1391 pub vision: VisionConfig,
1392 #[serde(skip)]
1395 pub profile: Option<String>,
1396 #[serde(skip)]
1399 pub route_pin: Option<String>,
1400 #[serde(skip)]
1403 pub dotenv: Dotenv,
1404 #[serde(default)]
1409 pub mcp: Vec<crate::mcp::Spec>,
1410 #[serde(skip)]
1414 pub no_mcp: bool,
1415 #[serde(default)]
1417 pub flares: FlaresConfig,
1418 #[serde(default)]
1422 pub bots: std::collections::BTreeMap<String, BotConfig>,
1423}
1424
1425#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1431#[serde(default)]
1432pub struct FlaresConfig {
1433 pub count: usize,
1436 pub max_concurrent: usize,
1438 pub max_iterations: usize,
1440 pub total_iterations: usize,
1443 pub total_tokens: Option<u64>,
1445}
1446
1447impl Default for FlaresConfig {
1448 fn default() -> Self {
1449 Self {
1450 count: 3,
1451 max_concurrent: 4,
1452 max_iterations: 6,
1453 total_iterations: 24,
1454 total_tokens: None,
1455 }
1456 }
1457}
1458
1459impl FlaresConfig {
1460 pub fn concurrency(&self) -> usize {
1463 self.max_concurrent.max(1)
1464 }
1465
1466 pub fn per_flare(&self) -> usize {
1468 self.max_iterations.max(1)
1469 }
1470
1471 pub fn budget(&self) -> usize {
1475 self.total_iterations.max(1)
1476 }
1477}
1478
1479#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1486#[serde(default)]
1487pub struct BotConfig {
1488 pub instructions: Option<String>,
1492 pub skills: Option<Vec<String>>,
1496 pub memory: Option<String>,
1500 pub adapter: Option<String>,
1503}
1504
1505pub const BOT_ADAPTERS: &[&str] = &[];
1509
1510#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1513#[serde(default)]
1514pub struct ContextPolicyConfig {
1515 pub compact_at: f64,
1518 pub protect_last_n: usize,
1520 pub judge: bool,
1524 pub judge_timeout_secs: u64,
1526 pub window_tokens: usize,
1529 pub handoff_chars: usize,
1532}
1533
1534impl Default for ContextPolicyConfig {
1535 fn default() -> Self {
1536 Self {
1537 compact_at: 0.85,
1538 protect_last_n: crate::context::DEFAULT_PROTECT_LAST_N,
1539 judge: true,
1540 judge_timeout_secs: 20,
1541 window_tokens: 0,
1542 handoff_chars: 6_000,
1543 }
1544 }
1545}
1546
1547impl ContextPolicyConfig {
1548 pub fn budget_for(&self, window_tokens: usize) -> usize {
1550 if window_tokens == 0 || self.compact_at.is_nan() || self.compact_at <= 0.0 {
1551 return 0;
1552 }
1553 (window_tokens as f64 * self.compact_at) as usize
1554 }
1555
1556 pub fn validate(&self) -> Result<()> {
1559 if !(0.0..=1.0).contains(&self.compact_at) {
1560 return Err(Error::Config(format!(
1561 "context.compact_at: {} is not a share of the window; use 0.85 for 85%, or 0 to \
1562 turn the threshold off",
1563 self.compact_at
1564 )));
1565 }
1566 if self.handoff_chars < 200 {
1567 return Err(Error::Config(format!(
1568 "context.handoff_chars: {} is too small to compile a handoff; 200 is the floor \
1569 and 6000 is the default",
1570 self.handoff_chars
1571 )));
1572 }
1573 Ok(())
1574 }
1575}
1576
1577#[derive(Debug, Clone, Serialize, Deserialize)]
1579#[serde(default)]
1580pub struct UserConfig {
1581 pub file: String,
1583 pub memory_file: String,
1585 pub memory_budget_chars: usize,
1588}
1589
1590impl Default for UserConfig {
1591 fn default() -> Self {
1592 Self {
1593 file: "USER.md".into(),
1594 memory_file: "MEMORY.md".into(),
1595 memory_budget_chars: crate::memory::DEFAULT_BUDGET_CHARS,
1596 }
1597 }
1598}
1599
1600#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1607#[serde(default)]
1608pub struct VisionConfig {
1609 #[serde(default)]
1612 pub mode: VisionMode,
1613 #[serde(default)]
1616 pub route: String,
1617 #[serde(default)]
1620 pub allow_cloud: bool,
1621}
1622
1623#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
1625#[serde(rename_all = "lowercase")]
1626pub enum VisionMode {
1627 Native,
1629 Text,
1631 #[default]
1633 Auto,
1634}
1635
1636#[derive(Debug, Clone, Serialize, Deserialize)]
1637#[serde(default)]
1638pub struct SkillsConfig {
1639 pub index_budget_chars: usize,
1642}
1643
1644impl Default for SkillsConfig {
1645 fn default() -> Self {
1646 Self {
1647 index_budget_chars: crate::skills::DEFAULT_INDEX_BUDGET_CHARS,
1648 }
1649 }
1650}
1651
1652#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1654#[serde(default)]
1655pub struct PluginsConfig {
1656 pub dir: Option<PathBuf>,
1659 pub enabled: Vec<String>,
1661 pub mcp_timeout_secs: Option<u64>,
1664}
1665
1666impl Config {
1667 pub fn load(explicit: Option<&Path>) -> Result<Config> {
1670 Self::load_with(explicit, &process_env)
1671 }
1672
1673 pub fn load_with(explicit: Option<&Path>, env: EnvFn) -> Result<Config> {
1674 Self::load_with_profile(explicit, None, env)
1675 }
1676
1677 pub fn load_with_profile(
1686 explicit: Option<&Path>,
1687 profile: Option<&str>,
1688 env: EnvFn,
1689 ) -> Result<Config> {
1690 let profile = profile
1691 .map(str::to_string)
1692 .or_else(|| env("ECLIPSE_PROFILE"))
1693 .filter(|p| !p.trim().is_empty())
1694 .filter(|p| p != "default");
1700 if let Some(name) = &profile {
1701 validate_profile_name(name)?;
1702 }
1703 let dotenv = Dotenv::load(env, profile.as_deref())?;
1706 let lookup = |k: &str| {
1712 env(k).or_else(|| {
1713 dotenv
1714 .values
1715 .get(k)
1716 .filter(|v| !v.is_empty())
1717 .map(String::as_str)
1718 .map(str::to_string)
1719 })
1720 };
1721 let lookup: EnvFn<'_> = &lookup;
1722
1723 let base_path = match explicit {
1724 Some(p) => Some(p.to_path_buf()),
1725 None => config_path(env).filter(|p| p.exists()),
1726 };
1727 let mut hooks_path = base_path.clone();
1729 let mut value = match &base_path {
1730 Some(p) => {
1731 let mut parsed = read_toml(p)?;
1732 crate::interpolate::in_value(&mut parsed, p, lookup)?;
1733 parsed
1734 }
1735 None => toml::Value::try_from(Config::default())
1736 .map_err(|e| Error::Config(e.to_string()))?,
1737 };
1738 if let Some(name) = &profile {
1739 if let Some(dir) = profile_dir(env, name) {
1740 let overlay = dir.join("config.toml");
1741 if overlay.exists() {
1742 let mut over = read_toml(&overlay)?;
1743 crate::interpolate::in_value(&mut over, &overlay, lookup)?;
1746 if over.get("hooks").is_some() {
1747 hooks_path = Some(overlay.clone());
1748 }
1749 merge_toml(&mut value, over);
1750 }
1751 }
1752 }
1753 let mut cfg: Config = value
1754 .try_into()
1755 .map_err(|e: toml::de::Error| Error::Parse {
1756 path: base_path.unwrap_or_else(|| PathBuf::from("<defaults>")),
1757 message: e.to_string(),
1758 })?;
1759 cfg.profile = profile;
1760 cfg.apply_env(lookup);
1761 cfg.dotenv = dotenv;
1762 cfg.validate_routes()?;
1765 cfg.context.validate()?;
1766 cfg.validate_bots()?;
1769 crate::hooks::validate(&cfg.hooks).map_err(|message| Error::Parse {
1770 path: hooks_path.unwrap_or_else(|| PathBuf::from("<defaults>")),
1771 message,
1772 })?;
1773 Ok(cfg)
1774 }
1775
1776 pub fn profile_name(&self) -> &str {
1778 self.profile.as_deref().unwrap_or("default")
1779 }
1780
1781 pub fn state_dir(&self, env: EnvFn) -> Result<PathBuf> {
1783 state_dir_for(env, self.profile.as_deref())
1784 .ok_or_else(|| Error::Config("cannot determine state dir: HOME is not set".into()))
1785 }
1786
1787 pub fn plugins_dirs(&self, env: EnvFn) -> Vec<PathBuf> {
1791 let mut out = Vec::new();
1792 if let Some(name) = &self.profile {
1793 if let Some(dir) = profile_dir(env, name) {
1794 out.push(dir.join("plugins"));
1795 }
1796 }
1797 let shared = match &self.plugins.dir {
1798 Some(p) => expand_tilde(p, env),
1799 None => match config_dir(env) {
1800 Some(d) => d.join("plugins"),
1801 None => return out,
1802 },
1803 };
1804 if !out.contains(&shared) {
1805 out.push(shared);
1806 }
1807 out
1808 }
1809
1810 pub fn from_file(path: &Path) -> Result<Config> {
1811 let text = std::fs::read_to_string(path).map_err(|e| Error::io(path, e))?;
1812 Self::from_toml_str(&text).map_err(|message| Error::Parse {
1813 path: path.to_path_buf(),
1814 message,
1815 })
1816 }
1817
1818 pub fn from_toml_str(text: &str) -> std::result::Result<Config, String> {
1819 toml::from_str(text).map_err(|e| e.to_string())
1820 }
1821
1822 pub fn apply_env(&mut self, env: EnvFn) {
1828 if self.provider.route.is_empty() || self.provider.declares_connection() {
1834 if let Some(v) = env("ECLIPSE_BASE_URL") {
1835 self.provider.base_url = v;
1836 }
1837 if let Some(v) = env("ECLIPSE_MODEL") {
1838 self.provider.model = v;
1839 }
1840 apply_key_env(&mut self.provider, env, env("ECLIPSE_API_KEY"));
1841 }
1842 for route in &mut self.provider.route {
1843 apply_key_env(&mut route.config, env, None);
1844 }
1845 }
1846
1847 pub fn to_toml_redacted(&self) -> Result<String> {
1853 let mut value = toml::Value::try_from(self).map_err(|e| Error::Config(e.to_string()))?;
1854 redact(&mut value);
1855 toml::to_string_pretty(&value).map_err(|e| Error::Config(e.to_string()))
1856 }
1857
1858 pub fn require_provider(&self) -> Result<()> {
1860 self.chain().map(|_| ())
1861 }
1862
1863 pub fn declared_routes(&self) -> Vec<NamedRoute> {
1868 let mut out = Vec::new();
1869 if self.provider.route.is_empty() || self.provider.declares_connection() {
1870 out.push(NamedRoute::new(DEFAULT_ROUTE, &self.provider));
1871 }
1872 out.extend(self.provider.route.iter().map(|r| {
1873 NamedRoute::new(&r.name, &r.config).with_flare_shape(r.max_parallel, r.group.clone())
1874 }));
1875 out
1876 }
1877
1878 pub fn route_names(&self) -> String {
1880 let names: Vec<String> = self.declared_routes().into_iter().map(|r| r.name).collect();
1881 if names.is_empty() {
1882 "none".to_string()
1883 } else {
1884 names.join(", ")
1885 }
1886 }
1887
1888 pub fn validate_routes(&self) -> Result<()> {
1895 let p = &self.provider;
1896 let mut seen: Vec<&str> = Vec::new();
1897 for (i, r) in p.route.iter().enumerate() {
1898 let name = r.name.trim();
1899 if name.is_empty() {
1900 return Err(Error::Config(format!(
1901 "provider.route #{} has no name; every [[provider.route]] needs `name = \"...\"`",
1902 i + 1
1903 )));
1904 }
1905 if seen.contains(&name) {
1906 return Err(Error::Config(format!(
1907 "two routes are named `{name}`; route names must be unique"
1908 )));
1909 }
1910 seen.push(name);
1911 if name == DEFAULT_ROUTE && p.declares_connection() {
1912 return Err(Error::Config(format!(
1913 "a route is named `{DEFAULT_ROUTE}`, but `[provider]` is also set and is the \
1914 route of that name; rename the route, or move its settings out of [provider]"
1915 )));
1916 }
1917 if r.config.fallback.is_some()
1918 || r.config.aux.is_some()
1919 || r.config.delegate.is_some()
1920 || !r.config.route.is_empty()
1921 {
1922 return Err(Error::Config(format!(
1923 "route `{name}` has its own `fallback`, `aux`, `delegate` or `route`; those \
1924 belong directly under [provider], not inside a route"
1925 )));
1926 }
1927 if r.config.base_url.trim().is_empty() {
1928 return Err(Error::Config(format!(
1929 "route `{name}` has no base_url; a route is a complete provider \
1930 configuration and does not inherit from [provider]"
1931 )));
1932 }
1933 if r.config.model.trim().is_empty() {
1934 return Err(Error::Config(format!(
1935 "route `{name}` has no model; a route is a complete provider \
1936 configuration and does not inherit from [provider]"
1937 )));
1938 }
1939 }
1940 if let Some(fallback) = &p.fallback {
1941 if fallback.is_empty() {
1942 return Err(Error::Config(
1943 "provider.fallback is empty; name the routes to try in order, or remove the \
1944 key to use `default` alone"
1945 .into(),
1946 ));
1947 }
1948 let known: Vec<String> = self.declared_routes().into_iter().map(|r| r.name).collect();
1949 let mut listed: Vec<&str> = Vec::new();
1950 for name in fallback {
1951 if !known.contains(name) {
1952 return Err(Error::Config(format!(
1953 "provider.fallback names `{name}`, which is not a route. Routes that \
1954 exist: {}",
1955 self.route_names()
1956 )));
1957 }
1958 if listed.contains(&name.as_str()) {
1959 return Err(Error::Config(format!(
1960 "provider.fallback lists `{name}` twice; each route is tried at most \
1961 once per run"
1962 )));
1963 }
1964 listed.push(name);
1965 }
1966 if p.declares_connection() && !listed.contains(&DEFAULT_ROUTE) {
1971 return Err(Error::Config(
1972 "`[provider]` sets a connection, but provider.fallback is the whole chain \
1973 and does not list `default`, so that endpoint would never be called. Put \
1974 `default` first in `fallback`, or move the connection keys into a route \
1975 and leave `[provider]` to `fallback` alone"
1976 .into(),
1977 ));
1978 }
1979 }
1980 if let Some(aux) = &p.aux {
1981 if aux.trim().is_empty() {
1982 return Err(Error::Config(
1983 "provider.aux is empty; name the route that does housekeeping, or remove \
1984 the key to use the route the run is on"
1985 .into(),
1986 ));
1987 }
1988 if !self.declared_routes().iter().any(|r| &r.name == aux) {
1989 return Err(Error::Config(format!(
1990 "provider.aux names `{aux}`, which is not a route. Routes that exist: {}",
1991 self.route_names()
1992 )));
1993 }
1994 }
1995 if let Some(delegate) = &p.delegate {
1996 if delegate.trim().is_empty() {
1997 return Err(Error::Config(
1998 "provider.delegate is empty; name the route subagents run on, or remove \
1999 the key to use the route the run is on"
2000 .into(),
2001 ));
2002 }
2003 if !self.declared_routes().iter().any(|r| &r.name == delegate) {
2004 return Err(Error::Config(format!(
2005 "provider.delegate names `{delegate}`, which is not a route. Routes that \
2006 exist: {}",
2007 self.route_names()
2008 )));
2009 }
2010 }
2011 let vision_route = self.vision.route.trim();
2015 if !vision_route.is_empty()
2016 && !self
2017 .declared_routes()
2018 .iter()
2019 .any(|r| r.name == vision_route)
2020 {
2021 return Err(Error::Config(format!(
2022 "vision.route names `{vision_route}`, which is not a route. Routes that exist: {}",
2023 self.route_names()
2024 )));
2025 }
2026 Ok(())
2027 }
2028
2029 pub fn pin_route(&mut self, flag: Option<&str>, env: EnvFn) -> Result<()> {
2035 let wanted = match flag {
2036 Some(name) if name.trim().is_empty() => {
2037 return Err(Error::Config(
2038 "--route needs a route name; `eclipse config show` lists them".into(),
2039 ))
2040 }
2041 Some(name) => Some(name.trim().to_string()),
2042 None => env("ECLIPSE_ROUTE")
2043 .or_else(|| self.dotenv.values.get("ECLIPSE_ROUTE").cloned())
2044 .map(|v| v.trim().to_string())
2045 .filter(|v| !v.is_empty()),
2046 };
2047 if let Some(name) = &wanted {
2048 if !self.declared_routes().iter().any(|r| &r.name == name) {
2049 return Err(self.unknown_route(name));
2050 }
2051 }
2052 self.route_pin = wanted;
2053 Ok(())
2054 }
2055
2056 fn unknown_route(&self, name: &str) -> Error {
2057 Error::Config(format!(
2058 "unknown route `{name}`. Routes that exist: {}",
2059 self.route_names()
2060 ))
2061 }
2062
2063 pub fn chain(&self) -> Result<Chain> {
2069 self.validate_routes()?;
2070 let all = self.declared_routes();
2071 let find = |name: &str| all.iter().find(|r| r.name == name).cloned();
2072 let (routes, source) = if let Some(pin) = &self.route_pin {
2073 let route = find(pin).ok_or_else(|| self.unknown_route(pin))?;
2074 (vec![route], ChainSource::Pinned)
2075 } else if let Some(fallback) = &self.provider.fallback {
2076 let routes = fallback.iter().filter_map(|n| find(n)).collect();
2078 (routes, ChainSource::Fallback)
2079 } else if self.provider.declares_connection() || self.provider.route.is_empty() {
2080 (
2081 vec![NamedRoute::new(DEFAULT_ROUTE, &self.provider)],
2082 ChainSource::Default,
2083 )
2084 } else {
2085 return Err(Error::Config(format!(
2086 "routes are declared but nothing says which to use: set `[provider] fallback = \
2087 [...]`, or pass --route NAME. Routes that exist: {}",
2088 self.route_names()
2089 )));
2090 };
2091 for route in &routes {
2092 route.require_endpoint(source)?;
2093 }
2094 let pinned = source == ChainSource::Pinned;
2099 let only = routes.first().cloned();
2100 let (aux, delegate) = if pinned {
2101 (only.clone(), only)
2102 } else {
2103 (
2104 self.provider.aux.as_deref().and_then(find),
2105 self.provider.delegate.as_deref().and_then(find),
2106 )
2107 };
2108 if let Some(aux) = &aux {
2109 aux.require_endpoint(source)?;
2110 }
2111 if let Some(delegate) = &delegate {
2112 delegate.require_endpoint(source)?;
2113 }
2114 Ok(Chain {
2115 routes,
2116 source,
2117 aux,
2118 delegate,
2119 })
2120 }
2121
2122 pub fn sessions_dir(&self, env: EnvFn) -> Result<PathBuf> {
2123 if let Some(d) = &self.sessions.dir {
2124 return Ok(expand_tilde(d, env));
2125 }
2126 Ok(self.state_dir(env)?.join("sessions"))
2127 }
2128
2129 pub fn validate_bots(&self) -> Result<()> {
2136 for name in self.bots.keys() {
2137 let ok = !name.is_empty()
2138 && name.len() <= 32
2139 && name
2140 .chars()
2141 .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-' || c == '_');
2142 if !ok {
2143 return Err(Error::Config(format!(
2144 "bots.{name}: a bot name is lowercase letters, digits, `-` and `_`, at most \
2145 32 of them — it becomes part of a session's `origin` and a URL"
2146 )));
2147 }
2148 }
2149 Ok(())
2150 }
2151
2152 pub fn bot_file(&self, env: EnvFn, path: &str) -> Option<PathBuf> {
2155 let path = expand_tilde(Path::new(path), env);
2156 if path.is_absolute() {
2157 Some(path)
2158 } else {
2159 self.context_dir(env).map(|dir| dir.join(path))
2160 }
2161 }
2162
2163 pub fn bot_memory(&self, env: EnvFn, name: &str, bot: &BotConfig) -> Option<PathBuf> {
2167 match bot.memory.as_deref().filter(|m| !m.trim().is_empty()) {
2168 Some(m) => self.bot_file(env, m),
2169 None => {
2170 let file = std::path::Path::new(&self.user.memory_file)
2175 .file_name()
2176 .map(PathBuf::from)
2177 .unwrap_or_else(|| PathBuf::from("MEMORY.md"));
2178 self.memory_dir(env)
2179 .map(|dir| dir.join("bots").join(name).join(file))
2180 }
2181 }
2182 }
2183
2184 pub fn attachments_dir(&self, env: EnvFn) -> Option<PathBuf> {
2189 if let Some(dir) = &self.attachments.dir {
2190 return Some(expand_tilde(dir, env));
2191 }
2192 self.state_dir(env).ok().map(|d| d.join("attachments"))
2193 }
2194
2195 pub fn where_am_i(&self, env: EnvFn, loaded: Option<&Path>) -> Where {
2204 let overlay = self
2205 .profile
2206 .as_deref()
2207 .filter(|name| *name != "default")
2208 .and_then(|name| profile_dir(env, name))
2209 .map(|dir| dir.join("config.toml"))
2210 .filter(|path| path.exists());
2211 Where {
2212 profile: self.profile.clone(),
2213 config: loaded.map(Path::to_path_buf).or_else(|| config_path(env)),
2214 overlay,
2215 home: home_root(env),
2216 sessions: self.sessions_dir(env).ok(),
2217 }
2218 }
2219
2220 pub fn context_dir(&self, env: EnvFn) -> Option<PathBuf> {
2223 match self.profile.as_deref() {
2224 Some(name) if name != "default" => profile_dir(env, name),
2227 _ => config_path(env)
2228 .and_then(|p| p.parent().map(Path::to_path_buf))
2229 .or_else(|| config_dir(env)),
2230 }
2231 }
2232
2233 pub fn scripts_dir(&self, env: EnvFn) -> Option<PathBuf> {
2242 let dir = self.context_dir(env)?.join("scripts");
2243 if dir.is_absolute() {
2244 return Some(dir);
2245 }
2246 std::env::current_dir().ok().map(|cwd| cwd.join(dir))
2247 }
2248
2249 pub fn memory_dir(&self, env: EnvFn) -> Option<PathBuf> {
2257 self.context_dir(env).map(|d| d.join("memory"))
2258 }
2259
2260 pub fn global_context_dir(&self, env: EnvFn) -> Option<PathBuf> {
2262 config_path(env)
2263 .and_then(|p| p.parent().map(Path::to_path_buf))
2264 .or_else(|| config_dir(env))
2265 }
2266
2267 pub fn home(&self, env: EnvFn) -> Option<PathBuf> {
2268 home_dir(env)
2269 }
2270
2271 pub fn workspace_root(&self, env: EnvFn) -> PathBuf {
2272 match &self.tools.workspace_root {
2273 Some(p) => expand_tilde(p, env),
2274 None => std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
2275 }
2276 }
2277}
2278
2279#[derive(Debug, Clone, Default, PartialEq, Eq)]
2285pub struct Where {
2286 pub profile: Option<String>,
2288 pub config: Option<PathBuf>,
2291 pub overlay: Option<PathBuf>,
2293 pub home: Option<PathBuf>,
2295 pub sessions: Option<PathBuf>,
2297}
2298
2299impl Where {
2300 pub fn name(&self) -> &str {
2302 self.profile.as_deref().unwrap_or("default")
2303 }
2304
2305 pub fn is_default(&self) -> bool {
2308 matches!(self.profile.as_deref(), None | Some("default"))
2309 }
2310}
2311
2312fn read_toml(path: &Path) -> Result<toml::Value> {
2314 let text = std::fs::read_to_string(path).map_err(|e| Error::io(path, e))?;
2315 toml::from_str::<toml::Value>(&text).map_err(|message| Error::Parse {
2316 path: path.to_path_buf(),
2317 message: message.to_string(),
2318 })
2319}
2320
2321fn merge_toml(base: &mut toml::Value, over: toml::Value) {
2323 match (base, over) {
2324 (toml::Value::Table(base), toml::Value::Table(over)) => {
2325 for (key, value) in over {
2326 match base.get_mut(&key) {
2327 Some(slot) => merge_toml(slot, value),
2328 None => {
2329 base.insert(key, value);
2330 }
2331 }
2332 }
2333 }
2334 (slot, over) => *slot = over,
2335 }
2336}
2337
2338fn redact(value: &mut toml::Value) {
2340 match value {
2341 toml::Value::Table(table) => {
2342 for (key, slot) in table.iter_mut() {
2343 if is_secret_key(key) && matches!(slot, toml::Value::String(s) if !s.is_empty()) {
2344 *slot = toml::Value::String("<redacted>".into());
2345 continue;
2346 }
2347 if is_url_key(key) {
2348 if let toml::Value::String(url) = slot {
2349 if let Some(clean) = redact_url(url) {
2350 *slot = toml::Value::String(clean);
2351 continue;
2352 }
2353 }
2354 }
2355 redact(slot);
2356 }
2357 }
2358 toml::Value::Array(items) => items.iter_mut().for_each(redact),
2359 _ => {}
2360 }
2361}
2362
2363pub(crate) fn is_secret_key(key: &str) -> bool {
2367 let k = key.to_ascii_lowercase();
2368 if k.ends_with("_env") {
2369 return false;
2370 }
2371 const COUNTS: &[&str] = &[
2374 "_tokens",
2375 "_chars",
2376 "_secs",
2377 "_ms",
2378 "_count",
2379 "_size",
2380 "_hours",
2381 "_days",
2382 "_bytes",
2383 "_iterations",
2384 "_call",
2385 ];
2386 if COUNTS.iter().any(|suffix| k.ends_with(suffix)) {
2387 return false;
2388 }
2389 k == "api_key"
2390 || k.ends_with("_key")
2391 || k.contains("token")
2392 || k.contains("secret")
2393 || k.contains("password")
2394}
2395
2396fn is_url_key(key: &str) -> bool {
2405 let k = key.to_ascii_lowercase();
2406 k.ends_with("_url") || k == "url" || k == "remote" || k == "releases"
2407}
2408
2409pub(crate) fn redact_url(text: &str) -> Option<String> {
2416 let (body, fragment) = match text.split_once('#') {
2417 Some((b, f)) => (b, Some(f)),
2418 None => (text, None),
2419 };
2420 let (before_query, query) = match body.split_once('?') {
2421 Some((b, q)) => (b, Some(q)),
2422 None => (body, None),
2423 };
2424 let mut changed = false;
2425
2426 let head = match before_query.find("://") {
2429 Some(scheme_end) => {
2430 let start = scheme_end + 3;
2431 let rest = &before_query[start..];
2432 let authority_end = rest.find('/').unwrap_or(rest.len());
2433 match rest[..authority_end].rfind('@') {
2434 Some(at) => {
2435 changed = true;
2436 format!("{}{}<redacted>{}", &before_query[..start], "", &rest[at..])
2437 }
2438 None => before_query.to_string(),
2439 }
2440 }
2441 None => before_query.to_string(),
2442 };
2443
2444 let query = query.map(|q| {
2445 let pairs: Vec<String> = q
2446 .split('&')
2447 .map(|pair| {
2448 let name = pair.split_once('=').map(|(n, _)| n).unwrap_or(pair);
2449 if !name.is_empty() && is_secret_key(name) {
2450 changed = true;
2451 format!("{name}=<redacted>")
2452 } else {
2453 pair.to_string()
2454 }
2455 })
2456 .collect();
2457 pairs.join("&")
2458 });
2459
2460 if !changed {
2461 return None;
2462 }
2463 let mut out = head;
2464 if let Some(q) = query {
2465 out.push('?');
2466 out.push_str(&q);
2467 }
2468 if let Some(f) = fragment {
2469 out.push('#');
2470 out.push_str(f);
2471 }
2472 Some(out)
2473}
2474
2475const SHIPPED_SPELLING: &[(&str, &str, &str)] = &[
2492 ("provider", "api_key", "${OPENAI_API_KEY:-}"),
2493 ("provider", "api_key_env", ""),
2494 ("provider", "profile", ""),
2495 (
2496 "provider",
2497 "reasoning_effort",
2498 crate::reasoning::SHIPPED_DEFAULT,
2499 ),
2500 ("provider", "aux", ""),
2501 ("provider", "delegate", ""),
2502 ("agent", "output_schema", ""),
2503 ("web", "auth_token", "${ECLIPSE_WEB_AUTH_TOKEN:-}"),
2504 ("web", "default_profile", ""),
2505 ("update", "remote", ""),
2506 ("update", "releases", ""),
2507 ("tools", "write_file", "ask"),
2511 ("tools", "patch", "ask"),
2512];
2513
2514fn shipped_text(spelling: &str) -> String {
2517 toml::Value::String(spelling.to_string()).to_string()
2518}
2519
2520const SECTION_ORDER: &[&str] = &[
2522 "provider",
2523 "agent",
2524 "tools",
2525 "flares",
2526 "sessions",
2527 "attachments",
2528 "context",
2529 "plugins",
2530 "cli",
2531 "web",
2532 "gateway",
2533 "update",
2534 "hooks",
2535 "user",
2536 "skills",
2537 "vision",
2538];
2539
2540pub fn starter_config() -> Result<String> {
2564 let defaults = toml::Value::try_from(Config::default())
2565 .map_err(|e| Error::Config(format!("the default config does not serialise: {e}")))?;
2566 let mut out = String::with_capacity(8 * 1024);
2567 out.push_str("# Every setting this build reads, and nothing else.\n");
2568 out.push_str("# What one does, and what it accepts: `eclipse config docs`.\n");
2569 out.push_str("# A commented key is not in use; an empty value means the same.\n");
2570 out.push_str(&format!("config_version = {CONFIG_VERSION}\n"));
2571 for section in SECTION_ORDER {
2572 out.push_str(&format!("\n[{section}]\n"));
2573 let table = defaults.get(*section).and_then(toml::Value::as_table);
2574 let mut lines: Vec<(String, String)> = Vec::new();
2575 let mut nested: Vec<&str> = Vec::new();
2576 if let Some(table) = table {
2577 for (key, value) in table {
2578 match value {
2579 toml::Value::Table(_) => nested.push(key.as_str()),
2580 other => {
2581 let shipped = SHIPPED_SPELLING
2582 .iter()
2583 .find(|(s, k, _)| s == section && k == key)
2584 .map(|(_, _, spelling)| shipped_text(spelling));
2585 lines.push((key.clone(), shipped.unwrap_or_else(|| other.to_string())));
2586 }
2587 }
2588 }
2589 }
2590 for (abs_section, key, _) in settings::ABSENT_BY_DEFAULT {
2593 if abs_section == section && !lines.iter().any(|(k, _)| k == key) {
2594 let shipped = SHIPPED_SPELLING
2595 .iter()
2596 .find(|(s, k, _)| s == section && k == key)
2597 .map(|(_, _, spelling)| shipped_text(spelling));
2598 lines.push(((*key).to_string(), shipped.unwrap_or_default()));
2599 }
2600 }
2601 lines.sort();
2602 for (key, text) in lines {
2603 if text.is_empty() {
2604 out.push_str(&format!("# {key} =\n"));
2605 } else {
2606 out.push_str(&format!("{key} = {text}\n"));
2607 }
2608 }
2609 nested.sort();
2613 for key in nested {
2614 let Some(sub) = table.and_then(|t| t.get(key)) else {
2615 continue;
2616 };
2617 let mut wrapped = toml::map::Map::new();
2618 wrapped.insert(key.to_string(), sub.clone());
2619 if let Ok(text) = toml::to_string(&toml::Value::Table(wrapped)) {
2620 out.push('\n');
2621 out.push_str(&text);
2622 }
2623 }
2624 if *section == "hooks" {
2629 let default_hooks = Config::default().hooks;
2630 for name in &default_hooks.order {
2631 if default_hooks.settings.contains_key(name) {
2632 continue;
2633 }
2634 let Some(info) = crate::hooks::SHIPPED.iter().find(|h| h.name == name) else {
2635 continue;
2636 };
2637 out.push_str(&format!("\n[hooks.{name}]\n"));
2638 let mut keys = info.settings.to_vec();
2639 keys.sort_unstable();
2640 for key in keys {
2641 out.push_str(&format!("# {key} =\n"));
2642 }
2643 }
2644 }
2645 }
2646 Ok(out)
2647}
2648
2649pub const ENV_TEMPLATE: &[&str] = &[
2659 "ECLIPSE_BASE_URL",
2660 "ECLIPSE_MODEL",
2661 "ECLIPSE_API_KEY",
2662 "ECLIPSE_REASONING_EFFORT",
2663 "ECLIPSE_ROUTE",
2664 "OPENAI_API_KEY",
2665 "ECLIPSE_WEB_AUTH_TOKEN",
2666 "ECLIPSE_WEB_USER",
2667 "ECLIPSE_WEB_PASSWORD_HASH",
2668];
2669
2670pub const ENV_ABOUT: &[(&str, &str)] = &[
2676 ("ECLIPSE_BASE_URL", "The provider's base URL, up to and including the version: it beats `[provider] base_url` for this process only"),
2677 ("ECLIPSE_MODEL", "The model name to ask for, beating `[provider] model`; the same as `--model`"),
2678 ("ECLIPSE_API_KEY", "The provider's key, resolved by `api_key = \"${ECLIPSE_API_KEY}\"`; never put the key itself in `config.toml`"),
2679 ("ECLIPSE_REASONING_EFFORT", "The reasoning level for this process: none, minimal, low, medium, high, xhigh, max"),
2680 ("ECLIPSE_ROUTE", "Pin one named route and never fall back from it, the same as `--route`"),
2681 ("OPENAI_API_KEY", "The variable the shipped `provider.api_key` line refers to; any name works, this one is the convention"),
2682 ("ECLIPSE_WEB_AUTH_TOKEN", "The dashboard's bearer token, generated by `config init`; the dashboard refuses to start without it"),
2683 ("ECLIPSE_WEB_USER", "The dashboard's sign-in name, when it asks for a name and a password instead of the token"),
2684 ("ECLIPSE_WEB_PASSWORD_HASH", "That password, as `eclipse web passwd` writes it: `pbkdf2-sha256$<iterations>$<salt>$<digest>`"),
2685 ("ECLIPSE_HOME", "The one directory everything lives in (`~/.eclipse` otherwise). Read from the shell, never from this file"),
2686 ("ECLIPSE_CONFIG", "The config file to read (`<home>/config.toml` otherwise). Read from the shell, never from this file"),
2687 ("ECLIPSE_PROFILE", "The profile to load, the same as `--profile`. Read from the shell, never from this file"),
2688 ("ECLIPSE_BIN", "The `eclipse` binary a spawned job should use; this tool sets it, and only a test overrides it"),
2689 ("ECLIPSE_ARGS", "The JSON arguments of the tool call a plugin or MCP server is being asked about; set by this tool"),
2690 ("ECLIPSE_ARGS_BYTES", "How big that JSON was, when it was too big to duplicate into `ECLIPSE_ARGS` (over 64 KiB); set by this tool"),
2691 ("ECLIPSE_TOOL", "The tool name a bridged call is for; set by this tool"),
2692 ("ECLIPSE_TOOL_SOCKET", "Where a script or plugin calls back into the running agent; set by this tool"),
2693 ("ECLIPSE_WORKSPACE", "The workspace root, given to a child process; set by this tool from `[tools] workspace_root`"),
2694 ("ECLIPSE_PLUGIN_DIR", "The plugin directory, given to a child process; set by this tool"),
2695 ("ECLIPSE_SCRIPTS_DIR", "The scripts directory, given to a child process; set by this tool"),
2696];
2697
2698pub fn env_about(name: &str) -> &'static str {
2700 ENV_ABOUT
2701 .iter()
2702 .find(|(n, _)| *n == name)
2703 .map(|(_, about)| *about)
2704 .unwrap_or("")
2705}
2706
2707pub const ENV_SHELL_ONLY: &[&str] = &["ECLIPSE_HOME", "ECLIPSE_CONFIG", "ECLIPSE_PROFILE"];
2710
2711pub const ENV_INTERNAL: &[&str] = &[
2714 "ECLIPSE_BIN",
2715 "ECLIPSE_ARGS",
2716 "ECLIPSE_ARGS_BYTES",
2717 "ECLIPSE_TOOL",
2718 "ECLIPSE_TOOL_SOCKET",
2719 "ECLIPSE_WORKSPACE",
2720 "ECLIPSE_PLUGIN_DIR",
2721 "ECLIPSE_SCRIPTS_DIR",
2722];
2723
2724pub fn starter_env(token: &str) -> String {
2729 let mut out = String::with_capacity(1024);
2730 out.push_str("# Secrets and per-host overrides. The shell beats this file. Mode 0600.\n");
2731 out.push_str("# Every variable this build reads; an empty value is not set. `eclipse config docs` explains each.\n");
2732 for name in ENV_TEMPLATE {
2733 if *name == "ECLIPSE_WEB_AUTH_TOKEN" {
2734 out.push_str(&format!("{name}={token}\n"));
2735 } else {
2736 out.push_str(&format!("{name}=\n"));
2737 }
2738 }
2739 out
2740}
2741
2742pub const STARTER_PROFILE_CONFIG: &str = r#"# A profile overlay: keys here replace the base config's, and a key left out follows it.
2746# Examples are commented out on purpose — an empty value here *replaces* the base value.
2747
2748[provider]
2749# base_url = "http://127.0.0.1:8080/v1"
2750# model = "qwen3-coder:30b"
2751# profile = "llamacpp"
2752
2753[tools]
2754# shell = "ask"
2755"#;
2756
2757#[derive(Debug, Clone, PartialEq, Eq)]
2759pub struct InitReport {
2760 pub config: PathBuf,
2761 pub dotenv: PathBuf,
2762 pub dotenv_written: bool,
2765}
2766
2767pub fn write_starter_config(path: &Path, force: bool, env: EnvFn) -> Result<InitReport> {
2780 if path.exists() && !force {
2781 return Err(Error::Config(format!(
2782 "{} already exists (use --force to overwrite)",
2783 path.display()
2784 )));
2785 }
2786 let dir = path.parent().unwrap_or(Path::new("."));
2787 std::fs::create_dir_all(dir).map_err(|e| Error::io(dir, e))?;
2788 write_private(path, &starter_config()?)?;
2789
2790 let secrets_dir = config_dir(env).unwrap_or_else(|| dir.to_path_buf());
2791 std::fs::create_dir_all(&secrets_dir).map_err(|e| Error::io(&secrets_dir, e))?;
2792 let dotenv = secrets_dir.join(".env");
2793 let mut dotenv_written = false;
2794 if !dotenv.exists() {
2795 let token = crate::token::generate()?;
2796 write_private(&dotenv, &starter_env(&token))?;
2797 dotenv_written = true;
2798 }
2799 let _ = migrate::write_baseline(path);
2803 Ok(InitReport {
2804 config: path.to_path_buf(),
2805 dotenv,
2806 dotenv_written,
2807 })
2808}
2809
2810pub fn toml_value(text: &str, section: &str, key: &str) -> Option<String> {
2813 let mut in_section = false;
2814 for line in text.lines() {
2815 let trimmed = line.trim();
2816 if let Some(state) = header_state(trimmed, section) {
2817 in_section = state;
2818 continue;
2819 }
2820 if !in_section || trimmed.starts_with('#') {
2821 continue;
2822 }
2823 if let Some((k, v)) = key_value(trimmed) {
2824 if k == key {
2825 return Some(v);
2826 }
2827 }
2828 }
2829 None
2830}
2831
2832pub fn toml_set_string(text: &str, section: &str, key: &str, value: &str) -> String {
2840 toml_set_value(text, section, key, &format!("\"{}\"", escape_toml(value)))
2841}
2842
2843pub fn toml_set_value(text: &str, section: &str, key: &str, value: &str) -> String {
2846 place_line(text, section, key, &format!("{key} = {value}"))
2847}
2848
2849struct McpSpan {
2862 name: Option<String>,
2863 start: usize,
2864 end: usize,
2865}
2866
2867fn is_table_header(trimmed: &str) -> bool {
2868 trimmed.starts_with('[')
2869}
2870
2871fn mcp_spans(lines: &[String]) -> Vec<McpSpan> {
2872 let mut spans: Vec<McpSpan> = Vec::new();
2873 let mut open: Option<usize> = None;
2874 let mut closed_by_header = true;
2875 for (i, line) in lines.iter().enumerate() {
2876 let trimmed = line.trim();
2877 if open.is_some() && is_table_header(trimmed) {
2878 if let Some(start) = open.take() {
2879 spans.push(McpSpan {
2880 name: None,
2881 start,
2882 end: i,
2883 });
2884 closed_by_header = true;
2885 }
2886 }
2887 if trimmed == "[[mcp]]" {
2888 open = Some(i);
2889 }
2890 }
2891 if let Some(start) = open {
2892 spans.push(McpSpan {
2893 name: None,
2894 start,
2895 end: lines.len(),
2896 });
2897 closed_by_header = false;
2898 }
2899 let count = spans.len();
2905 for (i, span) in spans.iter_mut().enumerate() {
2906 let at_eof = i + 1 == count && !closed_by_header;
2907 while span.end > span.start + 1 {
2908 let tail = lines[span.end - 1].trim();
2909 let belongs_to_next = !at_eof && (tail.is_empty() || tail.starts_with('#'));
2910 if tail.is_empty() || belongs_to_next {
2911 span.end -= 1;
2912 } else {
2913 break;
2914 }
2915 }
2916 }
2917 for span in &mut spans {
2918 let body = lines[span.start + 1..span.end].join("\n");
2919 span.name = toml::from_str::<crate::mcp::Spec>(&body)
2920 .ok()
2921 .map(|spec| spec.name);
2922 }
2923 spans
2924}
2925
2926fn tidy_blanks(lines: Vec<String>) -> Vec<String> {
2929 let mut end = lines.len();
2930 while end > 0 && lines[end - 1].trim().is_empty() {
2931 end -= 1;
2932 }
2933 let mut out: Vec<String> = Vec::with_capacity(end);
2934 let mut blanks = 0;
2935 for line in &lines[..end] {
2936 if line.trim().is_empty() {
2937 blanks += 1;
2938 if blanks > 1 {
2939 continue;
2940 }
2941 } else {
2942 blanks = 0;
2943 }
2944 out.push(line.clone());
2945 }
2946 out
2947}
2948
2949fn render_mcp_entry(entry: &crate::mcp::Spec) -> String {
2953 let quote = |s: &str| toml::Value::String(s.to_string()).to_string();
2954 let mut out = String::from("[[mcp]]\n");
2955 out.push_str(&format!("name = {}\n", quote(&entry.name)));
2956 if entry.transport == crate::mcp::Transport::Http {
2957 out.push_str("transport = \"http\"\n");
2958 }
2959 if !entry.command.is_empty() {
2960 out.push_str(&format!("command = {}\n", quote(&entry.command)));
2961 }
2962 if !entry.args.is_empty() {
2963 let args: Vec<String> = entry.args.iter().map(|a| quote(a)).collect();
2964 out.push_str(&format!("args = [{}]\n", args.join(", ")));
2965 }
2966 if let Some(url) = &entry.url {
2967 out.push_str(&format!("url = {}\n", quote(url)));
2968 }
2969 if let Some(var) = &entry.token_env {
2970 out.push_str(&format!("token_env = {}\n", quote(var)));
2971 }
2972 if entry.cwd != crate::plugins::Cwd::default() {
2973 let cwd = match entry.cwd {
2974 crate::plugins::Cwd::Workspace => "workspace",
2975 crate::plugins::Cwd::Plugin => "plugin",
2976 };
2977 out.push_str(&format!("cwd = \"{cwd}\"\n"));
2978 }
2979 if let Some(secs) = entry.timeout_secs {
2980 out.push_str(&format!("timeout_secs = {secs}\n"));
2981 }
2982 if entry.policy != Policy::Ask {
2983 let policy = match entry.policy {
2984 Policy::Deny => "deny",
2985 Policy::Ask => "ask",
2986 Policy::Allow => "allow",
2987 };
2988 out.push_str(&format!("policy = \"{policy}\"\n"));
2989 }
2990 if !entry.policies.is_empty() {
2991 let pairs: Vec<String> = entry
2992 .policies
2993 .iter()
2994 .map(|(tool, policy)| {
2995 let policy = match policy {
2996 Policy::Deny => "deny",
2997 Policy::Ask => "ask",
2998 Policy::Allow => "allow",
2999 };
3000 format!("{} = \"{policy}\"", quote(tool))
3004 })
3005 .collect();
3006 out.push_str(&format!("policies = {{ {} }}\n", pairs.join(", ")));
3007 }
3008 if !entry.prefix.is_empty() {
3009 out.push_str(&format!("prefix = {}\n", quote(&entry.prefix)));
3010 }
3011 if !entry.env.is_empty() {
3012 let env: Vec<String> = entry.env.iter().map(|e| quote(e)).collect();
3013 out.push_str(&format!("env = [{}]\n", env.join(", ")));
3014 }
3015 if entry.override_builtin {
3016 out.push_str("override = true\n");
3017 }
3018 if entry.disabled {
3019 out.push_str("disabled = true\n");
3020 }
3021 out
3022}
3023
3024pub fn mcp_add(text: &str, entry: &crate::mcp::Spec) -> std::result::Result<String, String> {
3026 entry
3027 .validate()
3028 .map_err(|why| format!("that entry is not usable, so nothing was saved: {why}"))?;
3029 let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
3030 let spans = mcp_spans(&lines);
3031 if let Some(existing) = spans
3032 .iter()
3033 .find(|s| s.name.as_deref() == Some(&entry.name))
3034 {
3035 return Err(format!(
3036 "`{}` is already declared at line {} — `eclipse mcp remove {}` first, or edit that entry",
3037 entry.name,
3038 existing.start + 1,
3039 entry.name
3040 ));
3041 }
3042 let rendered = render_mcp_entry(entry);
3043 match spans.last() {
3044 Some(last) => {
3045 let at = last.end;
3046 let mut fresh: Vec<String> = Vec::new();
3047 if at > 0 && !lines[at - 1].trim().is_empty() {
3049 fresh.push(String::new());
3050 }
3051 fresh.extend(rendered.lines().map(str::to_string));
3052 lines.splice(at..at, fresh);
3053 }
3054 None => {
3055 if lines.last().is_some_and(|l| !l.trim().is_empty()) {
3056 lines.push(String::new());
3057 }
3058 lines.extend(rendered.lines().map(str::to_string));
3059 }
3060 }
3061 let out = join_lines(tidy_blanks(lines));
3062 readback_mcp(&out, &entry.name, |spec| spec == entry)
3063}
3064
3065pub fn mcp_remove(text: &str, name: &str) -> std::result::Result<String, String> {
3067 let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
3068 let spans = mcp_spans(&lines);
3069 let Some(span) = spans.iter().find(|s| s.name.as_deref() == Some(name)) else {
3070 let known: Vec<&str> = spans.iter().filter_map(|s| s.name.as_deref()).collect();
3071 return Err(if known.is_empty() {
3072 format!("no `[[mcp]]` entry for `{name}` in this file")
3073 } else {
3074 format!(
3075 "no `[[mcp]]` entry for `{name}`; this file declares {}",
3076 known.join(", ")
3077 )
3078 });
3079 };
3080 let mut start = span.start;
3083 while start > 0 && lines[start - 1].trim_start().starts_with('#') {
3084 start -= 1;
3085 }
3086 let mut end = span.end;
3089 if end < lines.len() && lines[end].trim().is_empty() {
3090 end += 1;
3091 }
3092 lines.drain(start..end);
3093 readback_mcp_absent(&join_lines(tidy_blanks(lines)), name)
3094}
3095
3096pub fn mcp_set_disabled(
3098 text: &str,
3099 name: &str,
3100 disabled: bool,
3101) -> std::result::Result<String, String> {
3102 let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
3103 let spans = mcp_spans(&lines);
3104 let Some(span) = spans.iter().find(|s| s.name.as_deref() == Some(name)) else {
3105 return Err(format!("no `[[mcp]]` entry for `{name}` in this file"));
3106 };
3107 let line = if disabled {
3108 "disabled = true".to_string()
3109 } else {
3110 "disabled = false".to_string()
3113 };
3114 let body = span.start + 1..span.end;
3115 match lines[body.clone()].iter().position(|l| {
3116 l.trim_start()
3117 .strip_prefix("disabled")
3118 .is_some_and(|rest| rest.trim_start().starts_with('='))
3119 }) {
3120 Some(offset) => lines[span.start + 1 + offset] = line,
3121 None => lines.insert(span.end, line),
3122 }
3123 readback_mcp(&join_lines(lines), name, |spec| spec.disabled == disabled)
3124}
3125
3126pub fn mcp_update(
3135 text: &str,
3136 name: &str,
3137 change: impl FnOnce(&mut crate::mcp::Spec),
3138) -> std::result::Result<String, String> {
3139 let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
3140 let spans = mcp_spans(&lines);
3141 let Some(span) = spans.iter().find(|s| s.name.as_deref() == Some(name)) else {
3142 let known: Vec<&str> = spans.iter().filter_map(|s| s.name.as_deref()).collect();
3143 return Err(if known.is_empty() {
3144 format!("no `[[mcp]]` entry for `{name}` in this file")
3145 } else {
3146 format!(
3147 "no `[[mcp]]` entry for `{name}`; this file declares {}",
3148 known.join(", ")
3149 )
3150 });
3151 };
3152 let body = lines[span.start + 1..span.end].join("\n");
3153 let before: crate::mcp::Spec = toml::from_str(&body).map_err(|e| {
3154 format!(
3155 "the entry for `{name}` at line {} does not read as it stands, so nothing was saved: {}",
3156 span.start + 1,
3157 crate::config::settings::one_line(&e.to_string())
3158 )
3159 })?;
3160 let mut after = before.clone();
3161 change(&mut after);
3162 if after.name != name {
3163 return Err(format!(
3164 "an edit does not rename: `{name}` stays `{name}` — remove the entry and add the new \
3165 name instead"
3166 ));
3167 }
3168 after
3169 .validate()
3170 .map_err(|why| format!("that entry is not usable, so nothing was saved: {why}"))?;
3171 let rendered = |spec: &crate::mcp::Spec| -> BTreeMap<String, String> {
3172 render_mcp_entry(spec)
3173 .lines()
3174 .skip(1) .filter_map(|line| key_of(line).map(|key| (key, line.to_string())))
3176 .collect()
3177 };
3178 let (old, new) = (rendered(&before), rendered(&after));
3179 let (mut start, mut end) = (span.start + 1, span.end);
3180 let block: Vec<String> = lines[start..end].to_vec();
3183 let mut rebuilt: Vec<String> = Vec::new();
3184 let mut seen: Vec<String> = Vec::new();
3185 let mut i = 0;
3186 while i < block.len() {
3187 let line = &block[i];
3188 let trimmed = line.trim();
3189 if trimmed.is_empty() || trimmed.starts_with('#') {
3190 rebuilt.push(line.clone());
3191 i += 1;
3192 continue;
3193 }
3194 let first = i;
3195 let mut depth = bracket_depth(line);
3196 i += 1;
3197 while depth > 0 && i < block.len() {
3198 depth += bracket_depth(&block[i]);
3199 i += 1;
3200 }
3201 match key_of(&block[first]) {
3202 Some(key) => {
3203 seen.push(key.clone());
3204 match (old.get(&key), new.get(&key)) {
3205 (Some(was), Some(is)) if was == is => {
3207 rebuilt.extend(block[first..i].iter().cloned())
3208 }
3209 (_, Some(is)) => rebuilt.push(is.clone()),
3210 (_, None) => {}
3212 }
3213 }
3214 None => rebuilt.extend(block[first..i].iter().cloned()),
3216 }
3217 }
3218 for (key, line) in &new {
3219 if !seen.contains(key) {
3220 rebuilt.push(line.clone());
3221 }
3222 }
3223 start = start.min(lines.len());
3224 end = end.min(lines.len());
3225 lines.splice(start..end, rebuilt);
3226 let out = join_lines(lines);
3227 readback_mcp(&out, name, |spec| spec == &after)
3228}
3229
3230fn key_of(line: &str) -> Option<String> {
3232 let trimmed = line.trim();
3233 if trimmed.starts_with('#') {
3234 return None;
3235 }
3236 let (key, _) = trimmed.split_once('=')?;
3237 let key = key.trim();
3238 let plain = !key.is_empty()
3239 && !key.contains(char::is_whitespace)
3240 && key
3241 .chars()
3242 .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-');
3243 plain.then(|| key.to_string())
3244}
3245
3246fn bracket_depth(line: &str) -> i32 {
3249 let mut depth = 0;
3250 let mut quote: Option<char> = None;
3251 let mut escaped = false;
3252 for c in line.chars() {
3253 if let Some(q) = quote {
3254 if escaped {
3255 escaped = false;
3256 } else if c == '\\' {
3257 escaped = true;
3258 } else if c == q {
3259 quote = None;
3260 }
3261 continue;
3262 }
3263 match c {
3264 '"' | '\'' => quote = Some(c),
3265 '[' | '{' => depth += 1,
3266 ']' | '}' => depth -= 1,
3267 '#' => break, _ => {}
3269 }
3270 }
3271 depth
3272}
3273
3274fn readback_mcp(
3277 text: &str,
3278 name: &str,
3279 ok: impl Fn(&crate::mcp::Spec) -> bool,
3280) -> std::result::Result<String, String> {
3281 let cfg = parse_text(text).map_err(|e| {
3282 format!(
3283 "that would not load, so nothing was saved: {}",
3284 settings::one_line(&e.to_string())
3285 )
3286 })?;
3287 match cfg.mcp.iter().find(|s| s.name == name) {
3288 Some(spec) if ok(spec) => Ok(text.to_string()),
3289 Some(_) => {
3290 Err("the file would not read that entry back as written; nothing was saved".into())
3291 }
3292 None => Err(format!(
3293 "the edit lost `{name}` on the way back in; nothing was saved"
3294 )),
3295 }
3296}
3297
3298fn readback_mcp_absent(text: &str, name: &str) -> std::result::Result<String, String> {
3299 let cfg = parse_text(text).map_err(|e| {
3300 format!(
3301 "that would not load, so nothing was saved: {}",
3302 settings::one_line(&e.to_string())
3303 )
3304 })?;
3305 if cfg.mcp.iter().any(|s| s.name == name) {
3306 return Err(format!("`{name}` survived the removal; nothing was saved"));
3307 }
3308 Ok(text.to_string())
3309}
3310
3311fn place_line(text: &str, section: &str, key: &str, replacement: &str) -> String {
3317 let quoted = replacement.to_string();
3318 let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
3319 let mut in_section = false;
3320 let mut header_at: Option<usize> = None;
3321 let mut commented_at: Option<usize> = None;
3322 for (i, line) in lines.iter().enumerate() {
3323 let trimmed = line.trim();
3324 if let Some(state) = header_state(trimmed, section) {
3325 in_section = state;
3326 if in_section && header_at.is_none() {
3327 header_at = Some(i);
3328 }
3329 continue;
3330 }
3331 if !in_section {
3332 continue;
3333 }
3334 if let Some((k, _)) = key_value(trimmed) {
3335 if k == key {
3336 lines[i] = quoted;
3337 return join_lines(lines);
3338 }
3339 } else if let Some(rest) = trimmed.strip_prefix('#') {
3340 if let Some((k, _)) = key_value(rest.trim()) {
3342 if k == key && commented_at.is_none() {
3343 commented_at = Some(i);
3344 }
3345 }
3346 }
3347 }
3348 match (header_at, commented_at) {
3349 (_, Some(i)) => lines[i] = quoted,
3350 (Some(i), None) => lines.insert(i + 1, quoted),
3351 (None, None) => {
3352 lines.push(String::new());
3353 lines.push(format!("[{section}]"));
3354 lines.push(quoted);
3355 }
3356 }
3357 join_lines(lines)
3358}
3359
3360pub fn comment_in_text(text: &str, section: &str, key: &str) -> String {
3366 place_line(text, section, key, &format!("# {key} ="))
3367}
3368
3369pub fn stamp_version(text: &str, version: u32) -> std::result::Result<String, String> {
3374 let line = format!("config_version = {version}");
3375 let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
3376 if let Some(at) = lines.iter().position(|l| {
3377 l.trim_start()
3378 .strip_prefix("config_version")
3379 .is_some_and(|rest| rest.trim_start().starts_with('='))
3380 }) {
3381 lines[at] = line;
3382 } else {
3383 let first_table = lines
3388 .iter()
3389 .position(|l| !matches!(classify(l.trim()), Header::Other))
3390 .unwrap_or(lines.len());
3391 let mut insert_at = 0;
3392 while insert_at < first_table
3393 && (lines[insert_at].trim_start().starts_with('#')
3394 || lines[insert_at].trim().is_empty())
3395 {
3396 insert_at += 1;
3397 }
3398 lines.insert(insert_at, String::new());
3399 lines.insert(insert_at, line);
3400 while insert_at > 0 && lines[insert_at - 1].trim().is_empty() {
3401 lines.remove(insert_at - 1);
3402 insert_at -= 1;
3403 }
3404 }
3405 let out = join_lines(lines);
3406 parse_text(&out).map_err(|e| format!("stamping the version would not load: {e}"))?;
3408 Ok(out)
3409}
3410
3411pub fn toml_comment_out(text: &str, section: &str, key: &str) -> String {
3417 let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
3418 let mut in_section = false;
3419 for line in lines.iter_mut() {
3420 let trimmed = line.trim();
3421 if let Some(state) = header_state(trimmed, section) {
3422 in_section = state;
3423 continue;
3424 }
3425 if !in_section || trimmed.starts_with('#') {
3426 continue;
3427 }
3428 if let Some((k, _)) = key_value(trimmed) {
3429 if k == key {
3430 let indent: String = line.chars().take_while(|c| c.is_whitespace()).collect();
3431 *line = format!("{indent}# {trimmed}");
3432 return join_lines(lines);
3433 }
3434 }
3435 }
3436 join_lines(lines)
3437}
3438
3439pub(crate) enum Header<'a> {
3447 Section(&'a str),
3449 Array,
3451 Other,
3453}
3454
3455pub(crate) fn classify(trimmed: &str) -> Header<'_> {
3458 if trimmed.starts_with("[[") {
3459 return Header::Array;
3460 }
3461 let Some(rest) = trimmed.strip_prefix('[') else {
3462 return Header::Other;
3463 };
3464 let Some(name) = rest.strip_suffix(']') else {
3465 return Header::Other;
3466 };
3467 if name.contains(['[', ']']) || name.trim() != name || name.is_empty() {
3468 return Header::Other;
3469 }
3470 Header::Section(name)
3471}
3472
3473pub(crate) fn header_state(trimmed: &str, section: &str) -> Option<bool> {
3479 match classify(trimmed) {
3480 Header::Section(name) => Some(name == section),
3481 Header::Array => Some(false),
3482 Header::Other => None,
3483 }
3484}
3485
3486pub(crate) fn key_value(trimmed: &str) -> Option<(&str, String)> {
3489 let (k, v) = trimmed.split_once('=')?;
3490 let k = k.trim();
3491 if k.is_empty() || k.contains([' ', '"', '\\']) {
3492 return None;
3493 }
3494 let v = v.trim();
3495 let unquoted = match v.strip_prefix('"').and_then(|r| r.strip_suffix('"')) {
3496 Some(inner) => inner.replace("\\\"", "\"").replace("\\\\", "\\"),
3497 None => v.to_string(),
3498 };
3499 Some((k, unquoted))
3500}
3501
3502fn escape_toml(value: &str) -> String {
3503 value.replace('\\', "\\\\").replace('"', "\\\"")
3504}
3505
3506fn join_lines(lines: Vec<String>) -> String {
3507 let mut out = lines.join("\n");
3508 if !out.ends_with('\n') {
3509 out.push('\n');
3510 }
3511 out
3512}
3513
3514pub fn save_config_text(path: &Path, text: &str) -> Result<()> {
3518 write_private(path, text)
3519}
3520
3521pub fn parse_text(text: &str) -> Result<Config> {
3524 let cfg: Config =
3525 toml::from_str(text).map_err(|e| Error::Config(format!("invalid config: {e}")))?;
3526 crate::hooks::validate(&cfg.hooks)
3527 .map_err(|e| Error::Config(format!("invalid config: {e}")))?;
3528 Ok(cfg)
3529}
3530
3531pub fn save_dotenv_var(path: &Path, key: &str, value: &str) -> Result<()> {
3535 if key.contains(['\n', '\r']) || value.contains(['\n', '\r']) {
3538 return Err(Error::Config(format!(
3539 "{key:?} cannot be written to {}: a line break in a key or a value would make a second \
3540 assignment",
3541 path.display()
3542 )));
3543 }
3544 let existing = match std::fs::read(path) {
3548 Ok(bytes) => String::from_utf8(bytes).map_err(|_| {
3549 Error::Config(format!(
3550 "{}: not valid UTF-8, so nothing was written — repair or remove it by hand",
3551 path.display()
3552 ))
3553 })?,
3554 Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
3555 Err(e) => {
3556 return Err(Error::Config(format!(
3557 "{}: {e}, so nothing was written — whatever else is in it is untouched",
3558 path.display()
3559 )))
3560 }
3561 };
3562 let line = format!("{key}={value}");
3563 let mut out = String::new();
3564 let mut replaced = false;
3565 for l in existing.lines() {
3566 let is_key = l
3567 .trim_start()
3568 .strip_prefix(key)
3569 .map(|rest| rest.starts_with('='))
3570 .unwrap_or(false);
3571 if is_key {
3572 out.push_str(&line);
3573 out.push('\n');
3574 replaced = true;
3575 } else {
3576 out.push_str(l);
3577 out.push('\n');
3578 }
3579 }
3580 if !replaced {
3581 if !out.is_empty() && !out.ends_with('\n') {
3582 out.push('\n');
3583 }
3584 out.push_str(&line);
3585 out.push('\n');
3586 }
3587 write_private(path, &out)?;
3588 let back = crate::dotenv::load(path)
3592 .map_err(|e| Error::Config(format!("{}: {e}", path.display())))?
3593 .into_iter()
3594 .rfind(|a| a.key == key)
3595 .map(|a| a.value);
3596 match back {
3597 Some(got) if got == value => Ok(()),
3598 Some(got) => Err(Error::Config(format!(
3599 "{}: {key} was written but reads back as {got:?}, not {value:?}; the rest of the file is \
3600 intact, so fix that line by hand",
3601 path.display()
3602 ))),
3603 None => Err(Error::Config(format!(
3604 "{}: {key} was written but the loader does not see it",
3605 path.display()
3606 ))),
3607 }
3608}
3609
3610pub fn dotenv_var(path: &Path, key: &str) -> Option<String> {
3618 crate::dotenv::load(path)
3619 .ok()?
3620 .into_iter()
3621 .rfind(|a| a.key == key)
3622 .map(|a| a.value)
3623 .filter(|value| !value.is_empty())
3624}
3625
3626pub(crate) fn write_private(path: &Path, text: &str) -> Result<()> {
3629 crate::atomic::write_file_atomically(path, text).map_err(|e| Error::io(path, e))
3634}
3635
3636#[test]
3637fn writing_the_empty_value_proves_itself_by_reading_back_as_unset() {
3638 let text = starter_config().unwrap();
3643 let without = settings::unset_in_text(&text, "agent.output_schema").expect("known key");
3644 assert_eq!(
3645 Config::from_toml_str(&without).unwrap().agent.output_schema,
3646 None
3647 );
3648 let back = settings::set_in_text(
3649 &without,
3650 "agent.output_schema",
3651 &toml::Value::String(String::new()),
3652 )
3653 .expect("an empty value can be written");
3654 assert!(back.contains("output_schema = \"\""), "{back}");
3655 assert_eq!(
3656 Config::from_toml_str(&back).unwrap().agent.output_schema,
3657 None,
3658 "and it reads as unset, which is what it means"
3659 );
3660 assert_eq!(
3661 toml_value(&back, "agent", "output_schema"),
3662 Some(String::new()),
3663 "the line is there; what it holds is nothing"
3664 );
3665}
3666
3667#[cfg(test)]
3668mod tests {
3669 #[test]
3676 fn a_route_can_say_how_many_flares_it_holds() {
3677 let cfg = Config::from_toml_str(
3678 r#"
3679[provider]
3680fallback = ["local", "cloud"]
3681
3682[[provider.route]]
3683name = "local"
3684base_url = "http://127.0.0.1:8080/v1"
3685model = "qwen"
3686profile = "llamacpp"
3687group = "gpu0"
3688max_parallel = 2
3689
3690[[provider.route]]
3691name = "cloud"
3692base_url = "https://api.example.com/v1"
3693model = "big"
3694"#,
3695 )
3696 .unwrap();
3697 let routes = cfg.declared_routes();
3698 let local = routes.iter().find(|r| r.name == "local").unwrap();
3699 assert_eq!(local.parallel(), 2, "the route said two slots");
3700 assert_eq!(local.group.as_deref(), Some("gpu0"));
3701 let cloud = routes.iter().find(|r| r.name == "cloud").unwrap();
3702 assert_eq!(cloud.parallel(), 4, "an openai route defaults to four");
3704 assert!(cloud.group.is_none());
3705 assert_eq!(
3706 local.default_parallel(),
3707 1,
3708 "llamacpp serves one model at a time"
3709 );
3710
3711 let zero = Config::from_toml_str(
3714 r#"
3715[[provider.route]]
3716name = "local"
3717base_url = "http://127.0.0.1:8080/v1"
3718model = "qwen"
3719max_parallel = 0
3720"#,
3721 )
3722 .unwrap();
3723 assert_eq!(zero.declared_routes()[0].parallel(), 1);
3724
3725 let bad = Config::from_toml_str(
3727 r#"
3728[[provider.route]]
3729name = "local"
3730base_url = "http://127.0.0.1:8080/v1"
3731model = "qwen"
3732max_parallel = "two"
3733"#,
3734 )
3735 .unwrap_err()
3736 .to_string();
3737 assert!(bad.contains("route `local`"), "{bad}");
3738 assert!(bad.contains("max_parallel"), "{bad}");
3739 }
3740
3741 #[test]
3742 fn flares_default_to_three_on_one_local_slot() {
3743 let cfg = Config::from_toml_str("").unwrap();
3744 assert_eq!(cfg.flares.count, 3, "the local default");
3745 assert_eq!(cfg.flares.concurrency(), 4);
3746 assert_eq!(cfg.flares.per_flare(), 6);
3747 assert_eq!(cfg.flares.budget(), 24);
3748
3749 let cfg = Config::from_toml_str(
3750 r#"
3751[flares]
3752count = 5
3753max_concurrent = 0
3754max_iterations = 0
3755total_iterations = 2
3756"#,
3757 )
3758 .unwrap();
3759 assert_eq!(cfg.flares.count, 5);
3760 assert_eq!(cfg.flares.concurrency(), 1);
3763 assert_eq!(cfg.flares.per_flare(), 1);
3764 assert_eq!(cfg.flares.budget(), 2);
3765 }
3766
3767 fn home_env(k: &str) -> Option<String> {
3773 (k == "HOME").then(|| "/home/op".to_string())
3774 }
3775
3776 #[test]
3780 fn a_bot_gets_its_own_memory_even_when_the_operator_names_an_absolute_file() {
3781 let mut cfg = Config::default();
3782 cfg.user.memory_file = "/srv/notes/MEMORY.md".to_string();
3783 let path = cfg
3784 .bot_memory(&home_env, "triage", &crate::config::BotConfig::default())
3785 .expect("a home directory is known");
3786 assert!(
3787 path.ends_with("bots/triage/MEMORY.md"),
3788 "{}",
3789 path.display()
3790 );
3791 assert!(
3792 !path.starts_with("/srv/notes"),
3793 "the absolute path is not a bot's memory: {}",
3794 path.display()
3795 );
3796 }
3797
3798 #[test]
3802 fn an_exported_model_does_not_break_a_routes_only_config() {
3803 let text = "\
3804[provider]
3805fallback = [\"local\"]
3806
3807[[provider.route]]
3808name = \"local\"
3809base_url = \"http://127.0.0.1:8080/v1\"
3810model = \"m\"
3811";
3812 let exported = |k: &str| match k {
3813 "ECLIPSE_MODEL" => Some("from-the-shell".to_string()),
3814 "ECLIPSE_BASE_URL" => Some("http://elsewhere.example/v1".to_string()),
3815 _ => None,
3816 };
3817 let mut cfg = Config::from_toml_str(text).unwrap();
3818 cfg.apply_env(&exported);
3819 assert_eq!(cfg.route_names(), "local", "no phantom `default` route");
3820 cfg.validate_routes()
3821 .expect("a routes-only config still validates with variables exported");
3822 }
3823
3824 #[test]
3828 fn the_default_profile_is_the_base_config() {
3829 let plain = Config::default();
3830 let named = Config {
3831 profile: Some("default".to_string()),
3832 ..Default::default()
3833 };
3834 assert_eq!(named.context_dir(&home_env), plain.context_dir(&home_env));
3835 assert_eq!(named.scripts_dir(&home_env), plain.scripts_dir(&home_env));
3836 assert_eq!(
3837 named.state_dir(&home_env).unwrap(),
3838 plain.state_dir(&home_env).unwrap()
3839 );
3840 let dir = named.context_dir(&home_env).unwrap();
3841 assert!(
3842 !dir.ends_with("profiles/default"),
3843 "`default` is not a profile directory: {}",
3844 dir.display()
3845 );
3846 }
3847
3848 const ROUTED: &str = "\
3858[provider]
3859base_url = \"http://127.0.0.1:8080/v1\"
3860
3861[[provider.route]]
3862name = \"slow\"
3863base_url = \"http://gpu-box:8000/v1\"
3864model = \"m\"
3865timeout_secs = 900
3866";
3867
3868 #[test]
3869 fn an_array_header_ends_the_section_above_it() {
3870 assert_eq!(
3871 toml_value(ROUTED, "provider", "timeout_secs"),
3872 None,
3873 "the route's key is not `[provider]`'s"
3874 );
3875
3876 let unset = toml_comment_out(ROUTED, "provider", "timeout_secs");
3878 assert_eq!(unset, ROUTED, "nothing in `[provider]` to comment out");
3879
3880 let set = toml_set_value(ROUTED, "provider", "timeout_secs", "45");
3883 let (provider, routes) = set.split_once("[[provider.route]]").unwrap();
3884 assert!(
3885 provider.contains("timeout_secs = 45"),
3886 "written under `[provider]`: {set}"
3887 );
3888 assert!(
3889 routes.contains("timeout_secs = 900"),
3890 "the route keeps its own timeout: {set}"
3891 );
3892 }
3893
3894 #[test]
3895 fn a_key_the_section_does_not_have_yet_is_added_under_its_own_header() {
3896 let set = toml_set_string(ROUTED, "provider", "api_key_env", "LOCAL_KEY");
3897 let (provider, routes) = set.split_once("[[provider.route]]").unwrap();
3898 assert!(
3899 provider.contains("api_key_env = \"LOCAL_KEY\""),
3900 "added under `[provider]`, not inside a route: {set}"
3901 );
3902 assert!(
3903 !routes.contains("api_key_env"),
3904 "the route is untouched: {set}"
3905 );
3906 }
3907
3908 #[test]
3909 fn a_header_is_classified_by_what_it_names() {
3910 assert!(matches!(
3911 classify("[provider]"),
3912 Header::Section("provider")
3913 ));
3914 assert!(matches!(classify("[[provider.route]]"), Header::Array));
3915 assert!(matches!(classify("[a.b]"), Header::Section("a.b")));
3916 assert!(matches!(classify("[ spaced ]"), Header::Other));
3917 assert!(matches!(classify("[provider"), Header::Other));
3918 assert!(matches!(classify("key = 1"), Header::Other));
3919 assert_eq!(header_state("[provider]", "provider"), Some(true));
3920 assert_eq!(header_state("[[provider.route]]", "provider"), Some(false));
3921 assert_eq!(header_state("key = 1", "provider"), None);
3922 }
3923
3924 #[test]
3926 fn an_mcp_tool_name_with_a_dot_or_a_space_is_quoted() {
3927 let spec: crate::mcp::Spec = toml::from_str(
3928 "name = \"srv\"\ncommand = \"x\"\n\
3929 policies = { \"a.b\" = \"allow\", \"read text\" = \"deny\" }\n",
3930 )
3931 .unwrap();
3932 let out = render_mcp_entry(&spec);
3933 assert!(out.contains("\"a.b\" = \"allow\""), "{out}");
3934 assert!(out.contains("\"read text\" = \"deny\""), "{out}");
3935 let body = out.lines().skip(1).collect::<Vec<_>>().join("\n");
3939 let back: crate::mcp::Spec = toml::from_str(&body).unwrap();
3940 assert_eq!(back.policies.get("a.b"), Some(&Policy::Allow));
3941 assert_eq!(back.policies.get("read text"), Some(&Policy::Deny));
3942 }
3943
3944 use super::*;
3945 use std::collections::HashMap;
3946
3947 fn starter() -> String {
3949 starter_config().expect("the starter config generates")
3950 }
3951
3952 fn env_of(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> {
3953 let m: HashMap<String, String> = pairs
3954 .iter()
3955 .map(|(k, v)| (k.to_string(), v.to_string()))
3956 .collect();
3957 move |k| m.get(k).cloned()
3958 }
3959
3960 fn load_hooks(text: &str) -> std::result::Result<Config, String> {
3962 let tmp = tempfile::tempdir().unwrap();
3963 let path = tmp.path().join("config.toml");
3964 std::fs::write(&path, text).unwrap();
3965 let env = env_of(&[("HOME", tmp.path().to_str().unwrap())]);
3966 Config::load_with_profile(Some(&path), None, &env).map_err(|e| e.to_string())
3967 }
3968
3969 #[test]
3970 fn the_memory_and_the_filter_are_on_by_default_when_there_is_no_hooks_section() {
3971 let want = crate::hooks::DEFAULT_ORDER;
3972 let c = load_hooks("[agent]\nmax_iterations = 3\n").unwrap();
3973 assert_eq!(c.hooks.order, want);
3974 assert_eq!(Config::default().hooks.order, want);
3975 let c = load_hooks("").unwrap();
3976 assert_eq!(c.hooks.order, want);
3977 assert!(
3978 !want.contains(&"recall-sessions"),
3979 "a new session is a new session: recall is opt-in, and `session_search` is how the \
3980 agent reaches the archive"
3981 );
3982 }
3983
3984 #[test]
3985 fn an_empty_order_turns_every_hook_off() {
3986 let c = load_hooks("[hooks]\norder = []\n").unwrap();
3987 assert!(c.hooks.order.is_empty());
3988 }
3989
3990 #[test]
3991 fn a_settings_table_alone_keeps_the_default_order() {
3992 let c = load_hooks("[hooks.redact-secrets]\nallow = [\"fixture-key\"]\n").unwrap();
3993 assert_eq!(c.hooks.order, crate::hooks::DEFAULT_ORDER);
3994 }
3995
3996 #[test]
3997 fn a_hook_name_this_build_does_not_have_is_refused_and_the_real_ones_are_listed() {
3998 let err =
3999 load_hooks("[hooks]\norder = [\"redact-secrets\", \"redact-secret\"]\n").unwrap_err();
4000 assert!(err.contains("`redact-secret`"), "{err}");
4001 assert!(
4002 err.contains("Hooks that exist: recall-sessions, redact-secrets"),
4003 "{err}"
4004 );
4005 assert!(err.contains("config.toml"), "the file is named: {err}");
4006 }
4007
4008 #[test]
4009 fn a_settings_table_for_a_hook_that_is_not_in_order_is_refused() {
4010 let err =
4011 load_hooks("[hooks]\norder = []\n[hooks.redact-secrets]\nallow = []\n").unwrap_err();
4012 assert!(err.contains("[hooks.redact-secrets]"), "{err}");
4013 assert!(err.contains("never run"), "{err}");
4014 assert!(err.contains("Add \"redact-secrets\" to order"), "{err}");
4015 }
4016
4017 #[test]
4018 fn a_settings_table_for_a_hook_that_does_not_exist_is_refused() {
4019 let err = load_hooks("[hooks.nope]\nx = 1\n").unwrap_err();
4020 assert!(err.contains("[hooks.nope]"), "{err}");
4021 assert!(err.contains("Hooks that exist"), "{err}");
4022 }
4023
4024 #[test]
4025 fn an_unknown_key_in_a_hooks_table_is_refused_and_the_known_ones_are_listed() {
4026 let err = load_hooks("[hooks.redact-secrets]\nalow = [\"x\"]\n").unwrap_err();
4027 assert!(err.contains("unknown key `alow`"), "{err}");
4028 assert!(err.contains("accepts: allow"), "{err}");
4029 }
4030
4031 #[test]
4032 fn a_stray_key_directly_under_hooks_is_refused() {
4033 let err = load_hooks("[hooks]\nenabled = true\n").unwrap_err();
4034 assert!(err.contains("`enabled`"), "{err}");
4035 assert!(err.contains("`order`"), "{err}");
4036 }
4037
4038 #[test]
4039 fn a_hook_listed_twice_and_a_malformed_allow_list_are_refused() {
4040 let err =
4041 load_hooks("[hooks]\norder = [\"redact-secrets\", \"redact-secrets\"]\n").unwrap_err();
4042 assert!(err.contains("twice"), "{err}");
4043 let err = load_hooks("[hooks.redact-secrets]\nallow = \"x\"\n").unwrap_err();
4044 assert!(err.contains("must be a list of strings"), "{err}");
4045 let err = load_hooks("[hooks.redact-secrets]\nallow = [\"\"]\n").unwrap_err();
4046 assert!(err.contains("empty string"), "{err}");
4047 let err = load_hooks("[hooks.redact-secrets]\nallow = [1]\n").unwrap_err();
4048 assert!(err.contains("only strings"), "{err}");
4049 }
4050
4051 #[test]
4052 fn a_profile_overlay_that_breaks_the_hooks_section_is_blamed_on_the_overlay() {
4053 let tmp = tempfile::tempdir().unwrap();
4054 let home = tmp.path().join("home");
4055 let dir = home.join(".eclipse");
4056 std::fs::create_dir_all(dir.join("profiles/work")).unwrap();
4057 std::fs::write(
4058 dir.join("config.toml"),
4059 "[hooks]\norder = [\"redact-secrets\"]\n",
4060 )
4061 .unwrap();
4062 std::fs::write(
4063 dir.join("profiles/work/config.toml"),
4064 "[hooks]\norder = [\"typo\"]\n",
4065 )
4066 .unwrap();
4067 let env = env_of(&[("HOME", home.to_str().unwrap())]);
4068 let err = Config::load_with_profile(None, Some("work"), &env)
4069 .unwrap_err()
4070 .to_string();
4071 assert!(err.contains("profiles/work/config.toml"), "{err}");
4072 assert!(err.contains("`typo`"), "{err}");
4073 }
4074
4075 #[test]
4079 fn an_empty_value_is_not_a_value_in_the_dotenv() {
4080 let dir = tempfile::tempdir().unwrap();
4081 let home = dir.path();
4082 std::fs::create_dir_all(home.join(".eclipse")).unwrap();
4083 let path = home.join(".eclipse/.env");
4084 std::fs::write(
4085 &path,
4086 "ECLIPSE_API_KEY=\nECLIPSE_MODEL=m\nECLIPSE_WEB_AUTH_TOKEN=\n",
4087 )
4088 .unwrap();
4089 let home_s = home.to_str().unwrap().to_string();
4090 let env = env_of(&[("HOME", &home_s)]);
4091 let loaded = Dotenv::load(&env, None).unwrap();
4092 assert_eq!(
4093 loaded.values.get("ECLIPSE_MODEL").map(String::as_str),
4094 Some("m")
4095 );
4096 assert!(
4097 !loaded.values.contains_key("ECLIPSE_API_KEY"),
4098 "an empty assignment is absent: {:?}",
4099 loaded.values.keys().collect::<Vec<_>>()
4100 );
4101 assert!(!loaded.values.contains_key("ECLIPSE_WEB_AUTH_TOKEN"));
4102 }
4103
4104 #[test]
4107 fn a_later_empty_assignment_unsets_an_earlier_one() {
4108 let dir = tempfile::tempdir().unwrap();
4109 let home = dir.path();
4110 std::fs::create_dir_all(home.join(".eclipse").join("profiles/work")).unwrap();
4111 std::fs::write(home.join(".eclipse/.env"), "ECLIPSE_MODEL=big\n").unwrap();
4112 std::fs::write(home.join(".eclipse/profiles/work/.env"), "ECLIPSE_MODEL=\n").unwrap();
4113 let home_s = home.to_str().unwrap().to_string();
4114 let env = env_of(&[("HOME", &home_s)]);
4115 let loaded = Dotenv::load(&env, Some("work")).unwrap();
4116 assert_eq!(loaded.files.len(), 2);
4117 assert_eq!(loaded.values.get("ECLIPSE_MODEL"), None);
4118 }
4119
4120 #[test]
4123 fn the_starter_env_lists_every_variable_and_sets_none_of_them() {
4124 let text = starter_env("tok");
4125 for name in ENV_TEMPLATE {
4126 assert!(
4127 text.contains(&format!("\n{name}=")),
4128 "`{name}` is in the shipped .env"
4129 );
4130 }
4131 for line in text.lines().filter(|l| !l.starts_with('#')) {
4132 let (name, value) = line.split_once('=').expect("KEY=VALUE");
4133 if name == "ECLIPSE_WEB_AUTH_TOKEN" {
4134 assert_eq!(value, "tok", "the one value a first install cannot invent");
4135 } else {
4136 assert!(value.is_empty(), "`{name}` ships unset, found `{value}`");
4137 }
4138 }
4139 }
4140
4141 #[test]
4145 fn every_environment_variable_the_build_reads_is_classified() {
4146 let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("..");
4147 let mut seen = Vec::new();
4148 let mut dirs = vec![
4149 root.join("eclipse-core/src"),
4150 root.join("eclipse-cli/src"),
4151 root.join("eclipse-web/src"),
4152 ];
4153 while let Some(dir) = dirs.pop() {
4154 let Ok(entries) = std::fs::read_dir(&dir) else {
4155 continue;
4156 };
4157 for entry in entries.flatten() {
4158 let path = entry.path();
4159 if path.is_dir() {
4160 dirs.push(path);
4161 continue;
4162 }
4163 if path.extension().and_then(|e| e.to_str()) != Some("rs") {
4164 continue;
4165 }
4166 let text = std::fs::read_to_string(&path).unwrap_or_default();
4167 for name in env_names(&text) {
4168 if !seen.contains(&name) {
4169 seen.push(name);
4170 }
4171 }
4172 }
4173 }
4174 assert!(seen.len() > 10, "the scan found the variables: {seen:?}");
4175 for name in &seen {
4176 let known = ENV_TEMPLATE.contains(&name.as_str())
4177 || ENV_SHELL_ONLY.contains(&name.as_str())
4178 || ENV_INTERNAL.contains(&name.as_str());
4179 assert!(
4180 known,
4181 "`{name}` is read by the build and is in none of ENV_TEMPLATE, ENV_SHELL_ONLY, ENV_INTERNAL"
4182 );
4183 }
4184 let shipped = starter();
4188 for name in ENV_TEMPLATE {
4189 let read = seen.iter().any(|s| s == name);
4190 let interpolated = shipped.contains(&format!("${{{name}"));
4191 assert!(
4192 read || interpolated,
4193 "`{name}` is in the shipped .env and nothing reads or interpolates it"
4194 );
4195 }
4196 }
4197
4198 #[test]
4202 fn every_classified_variable_has_a_description() {
4203 let classified: Vec<&str> = ENV_TEMPLATE
4204 .iter()
4205 .chain(ENV_SHELL_ONLY)
4206 .chain(ENV_INTERNAL)
4207 .copied()
4208 .collect();
4209 for name in &classified {
4210 assert!(
4211 !env_about(name).is_empty(),
4212 "`{name}` is classified and has no line in ENV_ABOUT"
4213 );
4214 }
4215 for (name, about) in ENV_ABOUT {
4216 assert!(
4217 classified.contains(name),
4218 "ENV_ABOUT explains `{name}`, which the build does not read"
4219 );
4220 assert!(
4221 about.len() > 30 && !about.ends_with('.'),
4222 "one sentence, no full stop: {about}"
4223 );
4224 }
4225 }
4226
4227 fn env_names(text: &str) -> Vec<String> {
4230 let mut out = Vec::new();
4231 let mut rest = text;
4232 while let Some(at) = rest.find("\"ECLIPSE_") {
4233 let after = &rest[at + 1..];
4234 let Some(end) = after.find('"') else {
4235 break;
4236 };
4237 let name = &after[..end];
4238 let complete = name
4241 .chars()
4242 .last()
4243 .is_some_and(|c| c.is_ascii_uppercase() || c.is_ascii_digit());
4244 if complete
4245 && name
4246 .chars()
4247 .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')
4248 {
4249 out.push(name.to_string());
4250 }
4251 rest = &after[end + 1..];
4252 }
4253 out
4254 }
4255
4256 #[test]
4257 fn an_empty_optional_string_loads_as_unset() {
4258 let c = Config::from_toml_str(
4261 "[provider]\napi_key = \"\"\napi_key_env = \"\"\nmodel = \"m\"\n[web]\nauth_token = \"\"\n",
4262 )
4263 .unwrap();
4264 assert_eq!(c.provider.api_key, None);
4265 assert_eq!(c.provider.api_key_env, None);
4266 assert_eq!(c.web.auth_token, None);
4267 assert_eq!(c.provider.model, "m");
4269 let dir = tempfile::tempdir().unwrap();
4272 let path = dir.path().join("config.toml");
4273 std::fs::write(&path, "[provider]\napi_key = \"${NOT_SET_ANYWHERE:-}\"\n").unwrap();
4274 let from_var = Config::load_with(Some(&path), &env_of(&[])).unwrap();
4275 assert_eq!(
4276 from_var.provider.api_key, None,
4277 "an absent variable is no key"
4278 );
4279 }
4280
4281 #[test]
4285 fn the_starter_config_carries_every_setting_the_build_reads() {
4286 let text = starter();
4287 let c = parse_text(&text).unwrap();
4288 let settings = Config::default().settings();
4289 assert!(
4290 settings.len() > 80,
4291 "the catalogue is the yardstick: {settings:?}"
4292 );
4293 for setting in &settings {
4294 let key = setting.key.clone();
4295 let present = text.lines().any(|l| {
4296 l.trim_start_matches("# ")
4297 .trim_start()
4298 .starts_with(&format!("{key} ="))
4299 });
4300 assert!(
4301 present,
4302 "[{}] `{key}` is missing from the shipped file:\n{text}",
4303 setting.section
4304 );
4305 }
4306 for line in text.lines().filter(|l| l.starts_with('#')) {
4309 assert!(
4310 line.starts_with("# ") && line[2..].contains(" =") || line.len() < 120,
4311 "a comment in the settings file should be a key, not a sentence: {line}"
4312 );
4313 }
4314 let prose = text
4315 .lines()
4316 .filter(|l| l.starts_with('#') && !l[1..].trim_start().contains(" ="))
4317 .count();
4318 assert!(prose <= 3, "only the three header lines: {prose}");
4319 assert_eq!(c.hooks.order, crate::hooks::DEFAULT_ORDER);
4321 assert_eq!(c.hooks.order, Config::default().hooks.order);
4322 assert!(c.hooks.settings.contains_key("redact-secrets"));
4323 crate::hooks::validate(&c.hooks).expect("the starter config's hooks validate");
4324 assert!(
4325 !c.hooks.settings.contains_key("recall-sessions"),
4326 "a settings table for a hook that is not in `order` cannot run"
4327 );
4328 let value: toml::Value = toml::from_str(&text).unwrap();
4331 let unknown = c.unknown_keys(&value);
4332 assert!(
4333 unknown.is_empty(),
4334 "unknown keys in the shipped file: {unknown:?}"
4335 );
4336 assert_eq!(
4337 c.config_version, CONFIG_VERSION,
4338 "the file stamps its shape"
4339 );
4340 }
4341
4342 #[test]
4346 fn config_show_scrubs_credentials_carried_in_an_mcp_url() {
4347 let c = Config::from_toml_str(
4348 "[provider]\nbase_url = \"http://127.0.0.1:1/v1\"\n\n\
4349 [[mcp]]\nname = \"gh\"\ntransport = \"http\"\n\
4350 url = \"https://user:pw@example.test/mcp?token=abc&limit=5\"\n\n\
4351 [[mcp]]\nname = \"plain\"\ntransport = \"http\"\n\
4352 url = \"https://example.test/mcp\"\n",
4353 )
4354 .unwrap();
4355 let shown = c.to_toml_redacted().unwrap();
4356 assert!(!shown.contains("pw"), "the password is gone: {shown}");
4357 assert!(!shown.contains("abc"), "the token is gone: {shown}");
4358 assert!(
4359 shown.contains("https://<redacted>@example.test/mcp"),
4360 "the shape is kept, the credentials are not: {shown}"
4361 );
4362 assert!(
4363 shown.contains("token=<redacted>"),
4364 "the parameter name stays, its value does not: {shown}"
4365 );
4366 assert!(
4367 shown.contains("limit=5"),
4368 "a parameter that is not a secret is not touched: {shown}"
4369 );
4370 assert!(
4371 shown.contains("url = \"https://example.test/mcp\""),
4372 "an endpoint with no credentials in it reads exactly as written: {shown}"
4373 );
4374 }
4375
4376 #[test]
4377 fn the_hooks_section_survives_a_round_trip_through_the_redacted_printout() {
4378 let c = load_hooks(
4379 "[hooks]\norder = [\"redact-secrets\"]\n[hooks.redact-secrets]\nallow = [\"fx\"]\n",
4380 )
4381 .unwrap();
4382 let shown = c.to_toml_redacted().unwrap();
4383 let again = Config::from_toml_str(&shown).unwrap();
4384 assert_eq!(again.hooks, c.hooks);
4385 }
4386
4387 #[test]
4388 fn defaults_have_no_endpoint_or_key() {
4389 let c = Config::default();
4390 assert!(c.provider.base_url.is_empty());
4391 assert!(c.provider.api_key.is_none());
4392 assert!(c.require_provider().is_err());
4393 assert_eq!(c.tools.write_file, Policy::Allow);
4396 assert_eq!(c.tools.shell, Policy::Ask);
4397 assert_eq!(c.tools.shell_ask, ShellAsk::Dangerous);
4398 }
4399
4400 #[test]
4401 fn cli_section_defaults_and_parses() {
4402 let d = Config::from_toml_str("").unwrap().cli;
4404 assert_eq!(d.color, None);
4405 assert_eq!(d.markdown, None);
4406 assert_eq!(d.approval, Approval::Ask);
4407 assert_eq!(d.history_size, 1000);
4408
4409 let c = Config::from_toml_str(
4410 "[cli]\ncolor = false\nmarkdown = true\napproval = \"auto\"\nhistory_size = 50\n",
4411 )
4412 .unwrap()
4413 .cli;
4414 assert_eq!(c.color, Some(false));
4415 assert_eq!(c.markdown, Some(true));
4416 assert_eq!(c.approval, Approval::Auto);
4417 assert_eq!(c.history_size, 50);
4418 }
4419
4420 #[test]
4421 fn an_unknown_approval_is_an_error_rather_than_a_silent_ask() {
4422 let err = Config::from_toml_str("[cli]\napproval = \"sometimes\"\n").unwrap_err();
4425 assert!(err.contains("approval"), "{err}");
4426 }
4427
4428 #[test]
4429 fn web_section_parses_its_ttl_and_default_profile() {
4430 let d = Config::from_toml_str("").unwrap().web;
4431 assert_eq!(d.session_ttl_hours, DEFAULT_SESSION_TTL_HOURS);
4432 assert_eq!(d.default_profile, None);
4433
4434 let w = Config::from_toml_str("[web]\nsession_ttl_hours = 1\ndefault_profile = \"work\"\n")
4435 .unwrap()
4436 .web;
4437 assert_eq!(w.session_ttl_hours, 1);
4438 assert_eq!(w.default_profile.as_deref(), Some("work"));
4439 }
4440
4441 #[test]
4445 fn the_starter_config_loads_without_a_dotenv_and_leaves_the_token_unset() {
4446 let dir = tempfile::tempdir().unwrap();
4447 let path = dir.path().join("config.toml");
4448 std::fs::write(&path, starter()).unwrap();
4449 let c = Config::load_with(Some(&path), &|_| None)
4452 .expect("the starter config loads with no .env at all");
4453 assert_eq!(
4454 c.web.auth_token, None,
4455 "an unset token loads as no token, not as a load error and not as an empty secret"
4456 );
4457 assert_eq!(c.provider.model, Config::default().provider.model);
4458 }
4459
4460 #[test]
4461 fn starter_config_parses_and_matches_defaults() {
4462 let c = Config::from_toml_str(&starter()).unwrap();
4463 let d = Config::default();
4464 assert_eq!(c.tools.read_file, d.tools.read_file);
4465 assert_eq!(c.tools.fetch, d.tools.fetch);
4466 assert_eq!(c.web.port, d.web.port);
4467 assert!(c.provider.base_url.is_empty());
4468 }
4469
4470 #[test]
4471 fn partial_file_fills_defaults() {
4472 let c = Config::from_toml_str(
4473 "[provider]\nbase_url=\"http://x/v1\"\nmodel=\"m\"\n[tools]\nshell=\"deny\"\n",
4474 )
4475 .unwrap();
4476 assert_eq!(c.provider.base_url, "http://x/v1");
4477 assert_eq!(c.tools.shell, Policy::Deny);
4478 assert_eq!(c.tools.write_file, Policy::Allow);
4479 assert_eq!(
4480 c.agent.max_iterations,
4481 usize::MAX,
4482 "no cap unless the box asks for one"
4483 );
4484 assert!(c.require_provider().is_ok());
4485
4486 for word in ["unlimited", "none", "inf", "0", "-1"] {
4487 let raw = format!("[agent]\nmax_iterations = {word}\n");
4488 let raw = if word.parse::<i64>().is_ok() {
4489 raw
4490 } else {
4491 format!("[agent]\nmax_iterations = \"{word}\"\n")
4492 };
4493 let c = Config::from_toml_str(&raw).unwrap();
4494 assert_eq!(c.agent.max_iterations, usize::MAX, "`{word}` means no cap");
4495 }
4496
4497 let c = Config::from_toml_str("[agent]\nmax_iterations = 12\n").unwrap();
4498 assert_eq!(c.agent.max_iterations, 12, "a number is a cap");
4499
4500 let words = Config::from_toml_str("[agent]\nmax_iterations = \"unlimited\"\n").unwrap();
4501 let printed = toml::to_string(&words).unwrap();
4502 assert!(
4503 printed.contains("max_iterations = \"unlimited\""),
4504 "the schema says the word, not a length: {printed}"
4505 );
4506
4507 let refused = Config::from_toml_str("[agent]\nmax_iterations = \"plenty\"\n");
4508 assert!(
4509 refused.is_err(),
4510 "a word that is not one of ours is an error"
4511 );
4512 }
4513
4514 #[test]
4515 fn unknown_policy_is_rejected() {
4516 assert!(Config::from_toml_str("[tools]\nshell=\"yolo\"\n").is_err());
4517 }
4518
4519 #[test]
4520 fn env_overrides_file() {
4521 let dir = tempfile::tempdir().unwrap();
4522 let p = dir.path().join("c.toml");
4523 std::fs::write(
4524 &p,
4525 "[provider]\nbase_url=\"http://file/v1\"\nmodel=\"file-model\"\napi_key=\"file-key\"\n",
4526 )
4527 .unwrap();
4528 let env = env_of(&[
4529 ("ECLIPSE_BASE_URL", "http://env/v1"),
4530 ("ECLIPSE_API_KEY", "env-key"),
4531 ]);
4532 let c = Config::load_with(Some(&p), &env).unwrap();
4533 assert_eq!(c.provider.base_url, "http://env/v1");
4534 assert_eq!(c.provider.model, "file-model");
4535 assert_eq!(c.provider.api_key.as_deref(), Some("env-key"));
4536 }
4537
4538 #[test]
4539 fn api_key_env_indirection() {
4540 let env = env_of(&[("MY_KEY", "secret")]);
4541 let mut c = Config::from_toml_str("[provider]\napi_key_env=\"MY_KEY\"\n").unwrap();
4542 c.apply_env(&env);
4543 assert_eq!(c.provider.api_key.as_deref(), Some("secret"));
4544 }
4545
4546 #[test]
4547 fn debug_redacts_api_key() {
4548 let mut c = Config::default();
4549 c.provider.api_key = Some("hunter2".into());
4550 assert!(!format!("{c:?}").contains("hunter2"));
4551 }
4552
4553 #[test]
4554 fn debug_and_redacted_toml_hide_web_token() {
4555 let mut c = Config::default();
4556 c.web.auth_token = Some("s3cret-token-value".into());
4557 assert!(!format!("{c:?}").contains("s3cret"));
4558 assert!(!c.to_toml_redacted().unwrap().contains("s3cret"));
4559 }
4560
4561 #[test]
4565 fn debug_never_prints_a_dotenv_value() {
4566 let dir = tempfile::tempdir().unwrap();
4567 let root = dir.path().join("root");
4568 std::fs::create_dir_all(&root).unwrap();
4569 std::fs::write(
4570 root.join(".env"),
4571 "ECLIPSE_API_KEY=dotenvvalue123\nMY_PRIVATE_MIRROR=mirrorvalue456\n",
4572 )
4573 .unwrap();
4574 let cfg_path = root.join("config.toml");
4575 std::fs::write(
4576 &cfg_path,
4577 "[provider]\nbase_url = \"http://127.0.0.1:9/v1\"\nmodel = \"m\"\napi_key = \"${ECLIPSE_API_KEY}\"\n",
4578 )
4579 .unwrap();
4580 let env = env_of(&[
4581 ("ECLIPSE_HOME", root.to_str().unwrap()),
4582 ("HOME", dir.path().to_str().unwrap()),
4583 ]);
4584
4585 let cfg = Config::load_with_profile(Some(&cfg_path), None, &env).unwrap();
4586 let debug = format!("{cfg:?}");
4587 assert!(
4588 !debug.contains("dotenvvalue123") && !debug.contains("mirrorvalue456"),
4589 "the .env values must never be printed: {debug}"
4590 );
4591 assert!(debug.contains("ECLIPSE_API_KEY"), "{debug}");
4592 assert!(debug.contains("Dotenv"), "{debug}");
4593 assert_eq!(cfg.provider.api_key.as_deref(), Some("dotenvvalue123"));
4595 }
4596
4597 #[test]
4598 fn redacted_toml_hides_key_and_round_trips() {
4599 let mut c = Config::default();
4600 c.provider.api_key = Some("hunter2".into());
4601 c.provider.model = "m".into();
4602 let t = c.to_toml_redacted().unwrap();
4603 assert!(!t.contains("hunter2"));
4604 assert_eq!(Config::from_toml_str(&t).unwrap().provider.model, "m");
4605 }
4606
4607 #[test]
4611 fn the_update_track_names_a_branch_and_takes_two_words() {
4612 assert_eq!(Config::default().update.track, Track::Release);
4613 assert_eq!(Track::Release.branch(), "main");
4614 assert_eq!(Track::Develop.branch(), "develop");
4615 let cfg = Config::from_toml_str("[update]\ntrack = \"develop\"\n").unwrap();
4616 assert_eq!(cfg.update.track, Track::Develop);
4617 assert_eq!(cfg.update.track.label(), "develop");
4618 let err = Config::from_toml_str("[update]\ntrack = \"main\"\n")
4619 .unwrap_err()
4620 .to_string();
4621 assert!(
4622 err.contains("main") && err.contains("develop"),
4623 "the refusal lists the words it takes: {err}"
4624 );
4625 }
4626
4627 #[test]
4630 fn a_url_keeps_its_shape_and_loses_its_secrets() {
4631 let mut c = Config::default();
4632 c.provider.base_url = "https://user:hunter2@gw.internal/v1".into();
4633 c.update.remote =
4634 Some("https://mirror.internal/releases?access_token=abc123&page=2".into());
4635 c.update.releases = Some("https://mirror.internal/api#frag".into());
4636
4637 let t = c.to_toml_redacted().unwrap();
4638 assert!(
4639 !t.contains("hunter2") && !t.contains("abc123"),
4640 "the secrets are gone: {t}"
4641 );
4642 assert!(
4644 t.contains("https://<redacted>@gw.internal/v1"),
4645 "the userinfo is replaced, not the URL: {t}"
4646 );
4647 assert!(
4648 t.contains("access_token=<redacted>&page=2"),
4649 "the secret parameter keeps its name and loses its value: {t}"
4650 );
4651 assert!(t.contains("https://mirror.internal/api#frag"), "{t}");
4652
4653 let debug = format!("{c:?}");
4655 assert!(!debug.contains("hunter2"), "{debug}");
4656
4657 let plain = Config::default();
4659 assert!(plain
4660 .to_toml_redacted()
4661 .unwrap()
4662 .contains(&plain.provider.base_url));
4663 }
4664
4665 #[test]
4666 fn one_root_layout() {
4667 let env = env_of(&[("HOME", "/home/u")]);
4669 assert_eq!(
4670 config_path(&env).unwrap(),
4671 PathBuf::from("/home/u/.eclipse/config.toml")
4672 );
4673 assert_eq!(
4674 Config::default().sessions_dir(&env).unwrap(),
4675 PathBuf::from("/home/u/.eclipse/state/sessions")
4676 );
4677 assert_eq!(
4678 Config::default().memory_dir(&env).unwrap(),
4679 PathBuf::from("/home/u/.eclipse/memory")
4680 );
4681 let env = env_of(&[
4684 ("HOME", "/home/u"),
4685 ("XDG_CONFIG_HOME", "/x/cfg"),
4686 ("XDG_STATE_HOME", "/x/state"),
4687 ]);
4688 assert_eq!(
4689 config_path(&env).unwrap(),
4690 PathBuf::from("/home/u/.eclipse/config.toml")
4691 );
4692 let env = env_of(&[("HOME", "/home/u"), ("ECLIPSE_HOME", "/opt/ecl")]);
4694 assert_eq!(
4695 config_path(&env).unwrap(),
4696 PathBuf::from("/opt/ecl/config.toml")
4697 );
4698 }
4699
4700 #[test]
4701 fn missing_default_file_is_ok_but_explicit_missing_is_error() {
4702 let dir = tempfile::tempdir().unwrap();
4703 let env = env_of(&[("HOME", dir.path().to_str().unwrap())]);
4704 assert!(Config::load_with(None, &env).is_ok());
4705 assert!(Config::load_with(Some(&dir.path().join("nope.toml")), &env).is_err());
4706 }
4707
4708 #[test]
4709 fn auto_prune_is_off_by_default_and_can_be_enabled() {
4710 assert!(!Config::default().sessions.auto_prune);
4711 let c = Config::from_toml_str("[sessions]\nauto_prune = true\nretention_keep_count = 5\n")
4712 .unwrap();
4713 assert!(c.sessions.auto_prune);
4714 assert_eq!(c.sessions.retention_keep_count, 5);
4715 }
4716
4717 #[test]
4718 fn sessions_dir_expands_tilde() {
4719 let env = env_of(&[("HOME", "/home/u")]);
4720 let mut c = Config::default();
4721 c.sessions.dir = Some("~/s".into());
4722 assert_eq!(c.sessions_dir(&env).unwrap(), PathBuf::from("/home/u/s"));
4723 }
4724
4725 #[test]
4726 fn config_init_writes_a_private_dotenv_and_the_config_refers_to_it() {
4727 let dir = tempfile::tempdir().unwrap();
4728 let p = dir.path().join("a/b/config.toml");
4729 let env = env_of(&[("ECLIPSE_HOME", dir.path().to_str().unwrap())]);
4730 let report = write_starter_config(&p, false, &env).unwrap();
4731 assert!(report.dotenv_written);
4732 assert_eq!(
4733 report.dotenv,
4734 dir.path().join(".env"),
4735 "the .env goes where the loader reads it, not beside a config elsewhere"
4736 );
4737
4738 let dotenv = std::fs::read_to_string(&report.dotenv).unwrap();
4739 let token = dotenv
4740 .lines()
4741 .find_map(|l| l.strip_prefix("ECLIPSE_WEB_AUTH_TOKEN="))
4742 .expect("the token lives in .env");
4743 assert_eq!(token.len(), 64, "a generated token, not a placeholder");
4744 assert!(token.bytes().all(|b| b.is_ascii_hexdigit()));
4745 assert!(
4746 !std::fs::read_to_string(&p).unwrap().contains(token),
4747 "the config carries the reference, never the secret"
4748 );
4749
4750 #[cfg(unix)]
4751 {
4752 use std::os::unix::fs::PermissionsExt;
4753 for f in [&p, &report.dotenv] {
4754 assert_eq!(f.metadata().unwrap().permissions().mode() & 0o777, 0o600);
4755 }
4756 }
4757
4758 let root = dir.path().join("root");
4761 let cfg_dir = root.clone();
4762 std::fs::create_dir_all(&cfg_dir).unwrap();
4763 let real = cfg_dir.join("config.toml");
4764 let env = env_of(&[
4765 ("ECLIPSE_HOME", root.to_str().unwrap()),
4766 ("HOME", dir.path().to_str().unwrap()),
4767 ]);
4768 let written = write_starter_config(&real, false, &env).unwrap();
4769 let cfg = Config::load_with_profile(Some(&real), None, &env).unwrap();
4770 let token = std::fs::read_to_string(&written.dotenv)
4771 .unwrap()
4772 .lines()
4773 .find_map(|l| {
4774 l.strip_prefix("ECLIPSE_WEB_AUTH_TOKEN=")
4775 .map(str::to_string)
4776 })
4777 .unwrap();
4778 assert_eq!(cfg.web.auth_token.as_deref(), Some(token.as_str()));
4779 assert_eq!(cfg.dotenv.files, vec![written.dotenv]);
4780 }
4781
4782 #[test]
4786 fn an_empty_dotenv_value_is_absent_not_an_empty_override() {
4787 let dir = tempfile::tempdir().unwrap();
4788 let root = dir.path().join("root");
4789 std::fs::create_dir_all(&root).unwrap();
4790 std::fs::write(
4791 root.join(".env"),
4792 "ECLIPSE_API_KEY=\nECLIPSE_MODEL=\nECLIPSE_BASE_URL=\n",
4793 )
4794 .unwrap();
4795 let cfg_path = root.join("config.toml");
4796 std::fs::write(
4797 &cfg_path,
4798 "[provider]\napi_key = \"sk-from-the-file\"\nmodel = \"keep-me\"\n\
4799 base_url = \"http://127.0.0.1:9999/v1\"\n",
4800 )
4801 .unwrap();
4802 let env = env_of(&[
4803 ("ECLIPSE_HOME", root.to_str().unwrap()),
4804 ("HOME", dir.path().to_str().unwrap()),
4805 ]);
4806
4807 let cfg = Config::load_with_profile(Some(&cfg_path), None, &env).unwrap();
4808 assert_eq!(
4809 cfg.provider.api_key.as_deref(),
4810 Some("sk-from-the-file"),
4811 "an empty .env value must not blank the key"
4812 );
4813 assert_eq!(cfg.provider.model, "keep-me", "nor the model");
4814 assert_eq!(
4815 cfg.provider.base_url, "http://127.0.0.1:9999/v1",
4816 "nor the base URL"
4817 );
4818 }
4819
4820 #[test]
4821 fn context_files_are_seeded_and_existing_ones_are_kept() {
4822 let tmp = tempfile::tempdir().unwrap();
4823 let memory = tmp.path().join("memory");
4824 let created = seed_context_files(&memory).unwrap();
4825 assert_eq!(created.len(), 3, "AGENT, USER, MEMORY: {created:?}");
4826 assert!(memory.join("AGENT.md").exists());
4827 assert!(memory.join("USER.md").exists());
4828 assert!(memory.join("MEMORY.md").exists());
4829 assert_eq!(
4830 std::fs::read_to_string(memory.join("MEMORY.md")).unwrap(),
4831 ""
4832 );
4833
4834 let created = seed_context_files(&memory).unwrap();
4836 assert!(
4837 created.is_empty(),
4838 "existing files are left alone: {created:?}"
4839 );
4840
4841 let written = [
4845 ("AGENT.md", "run make, no cargo test\n"),
4846 ("USER.md", "I am the operator; keep it short\n"),
4847 ("MEMORY.md", "- one durable fact\n"),
4848 ];
4849 for (name, body) in written {
4850 std::fs::write(memory.join(name), body).unwrap();
4851 }
4852 let created = seed_context_files(&memory).unwrap();
4853 assert!(created.is_empty(), "{created:?}");
4854 for (name, body) in written {
4855 assert_eq!(
4856 std::fs::read_to_string(memory.join(name)).unwrap(),
4857 body,
4858 "{name} was rewritten"
4859 );
4860 }
4861 }
4862
4863 #[test]
4868 fn a_new_profile_is_a_first_install_and_an_existing_one_is_never_rewritten() {
4869 let tmp = tempfile::tempdir().unwrap();
4870 let base = tmp.path().join("memory");
4871 let lived_in = tmp.path().join("profiles/work/memory");
4872 let fresh = tmp.path().join("profiles/lab/memory");
4873
4874 assert_eq!(seed_context_files(&base).unwrap().len(), 3);
4875 std::fs::write(base.join("USER.md"), "the operator\n").unwrap();
4876
4877 std::fs::create_dir_all(&lived_in).unwrap();
4878 for name in ["AGENT.md", "USER.md", "MEMORY.md"] {
4879 std::fs::write(lived_in.join(name), format!("{name} as it was lived in\n")).unwrap();
4880 }
4881
4882 assert!(
4883 seed_context_files(&lived_in).unwrap().is_empty(),
4884 "an existing profile's files are not rewritten"
4885 );
4886 assert_eq!(
4887 seed_context_files(&fresh).unwrap().len(),
4888 3,
4889 "a profile that has never been used is a first install"
4890 );
4891
4892 assert_eq!(
4893 std::fs::read_to_string(base.join("USER.md")).unwrap(),
4894 "the operator\n"
4895 );
4896 for name in ["AGENT.md", "USER.md", "MEMORY.md"] {
4897 assert_eq!(
4898 std::fs::read_to_string(lived_in.join(name)).unwrap(),
4899 format!("{name} as it was lived in\n")
4900 );
4901 }
4902 }
4903
4904 #[test]
4908 fn config_init_puts_the_dotenv_where_a_start_with_that_config_will_read_it() {
4909 let dir = tempfile::tempdir().unwrap();
4910 let home = dir.path().join("home");
4911 std::fs::create_dir_all(&home).unwrap();
4912 let elsewhere = dir.path().join("other");
4913 let path = elsewhere.join("config.toml");
4914 let env = env_of(&[
4915 ("ECLIPSE_HOME", home.to_str().unwrap()),
4916 ("HOME", dir.path().to_str().unwrap()),
4917 ]);
4918
4919 let report = write_starter_config(&path, false, &env).unwrap();
4920 let token = std::fs::read_to_string(&report.dotenv)
4921 .unwrap()
4922 .lines()
4923 .find_map(|l| l.strip_prefix("ECLIPSE_WEB_AUTH_TOKEN="))
4924 .expect("the token lives in .env")
4925 .to_string();
4926 assert_eq!(report.dotenv, home.join(".env"));
4927
4928 let cfg = Config::load_with_profile(Some(&path), None, &env).unwrap();
4929 assert_eq!(
4930 cfg.web.auth_token.as_deref(),
4931 Some(token.as_str()),
4932 "the token `config init` reported is the token the next start reads"
4933 );
4934 }
4935
4936 #[test]
4937 fn config_init_refuses_to_overwrite_a_config_without_force() {
4938 let dir = tempfile::tempdir().unwrap();
4939 let p = dir.path().join("c/config.toml");
4940 let env = env_of(&[("ECLIPSE_HOME", dir.path().to_str().unwrap())]);
4941 write_starter_config(&p, false, &env).unwrap();
4942 assert!(write_starter_config(&p, false, &env).is_err());
4943 }
4944
4945 #[test]
4946 fn config_init_never_overwrites_an_existing_dotenv() {
4947 let dir = tempfile::tempdir().unwrap();
4948 let p = dir.path().join("d/config.toml");
4949 let env = env_of(&[("ECLIPSE_HOME", dir.path().to_str().unwrap())]);
4950 let first = write_starter_config(&p, false, &env).unwrap();
4951 let before = std::fs::read_to_string(&first.dotenv).unwrap();
4952
4953 let again = write_starter_config(&p, true, &env).unwrap();
4955 assert!(!again.dotenv_written);
4956 assert_eq!(std::fs::read_to_string(&again.dotenv).unwrap(), before);
4957 }
4958
4959 #[test]
4960 fn a_profile_overlay_merges_over_the_base_config() {
4961 let tmp = tempfile::tempdir().unwrap();
4962 let home = tmp.path().join("home");
4963 let cfg_dir = home.join(".eclipse");
4964 std::fs::create_dir_all(cfg_dir.join("profiles/work")).unwrap();
4965 std::fs::write(
4966 cfg_dir.join("config.toml"),
4967 "[provider]\nbase_url = \"http://base/v1\"\nmodel = \"base-model\"\n\
4968 temperature = 0.2\n[agent]\nmax_iterations = 7\n",
4969 )
4970 .unwrap();
4971 std::fs::write(
4972 cfg_dir.join("profiles/work/config.toml"),
4973 "[provider]\nmodel = \"work-model\"\n",
4974 )
4975 .unwrap();
4976 let env = env_of(&[("HOME", home.to_str().unwrap())]);
4977
4978 let base = Config::load_with(None, &env).unwrap();
4979 assert_eq!(base.provider.model, "base-model");
4980 assert_eq!(base.profile_name(), "default");
4981
4982 let work = Config::load_with_profile(None, Some("work"), &env).unwrap();
4983 assert_eq!(work.provider.model, "work-model");
4985 assert_eq!(work.provider.base_url, "http://base/v1");
4986 assert_eq!(work.provider.temperature, Some(0.2));
4987 assert_eq!(work.agent.max_iterations, 7);
4988 assert_eq!(work.profile_name(), "work");
4989 assert_eq!(
4991 work.sessions_dir(&env).unwrap(),
4992 home.join(".eclipse/profiles/work/state/sessions")
4993 );
4994 assert_eq!(
4995 base.sessions_dir(&env).unwrap(),
4996 home.join(".eclipse/state/sessions")
4997 );
4998 assert_eq!(
4999 work.state_dir(&env).unwrap(),
5000 home.join(".eclipse/profiles/work/state")
5001 );
5002 }
5003
5004 #[test]
5005 fn the_profile_comes_from_the_environment_and_the_argument_wins() {
5006 let tmp = tempfile::tempdir().unwrap();
5007 let home = tmp.path().join("home");
5008 std::fs::create_dir_all(home.join(".eclipse/profiles/env")).unwrap();
5009 std::fs::write(
5010 home.join(".eclipse/profiles/env/config.toml"),
5011 "[agent]\nmax_iterations = 3\n",
5012 )
5013 .unwrap();
5014 let env = env_of(&[("HOME", home.to_str().unwrap()), ("ECLIPSE_PROFILE", "env")]);
5015 let from_env = Config::load_with(None, &env).unwrap();
5016 assert_eq!(from_env.profile_name(), "env");
5017 assert_eq!(from_env.agent.max_iterations, 3);
5018
5019 let explicit = Config::load_with_profile(None, Some("other"), &env).unwrap();
5020 assert_eq!(explicit.profile_name(), "other");
5021 assert_eq!(explicit.agent.max_iterations, usize::MAX);
5023 }
5024
5025 #[test]
5026 fn the_default_profile_keeps_the_plain_state_directory() {
5027 let env = env_of(&[("HOME", "/home/u")]);
5028 assert_eq!(
5029 state_dir_for(&env, Some("default")).unwrap(),
5030 PathBuf::from("/home/u/.eclipse/state")
5031 );
5032 assert_eq!(
5033 state_dir_for(&env, None).unwrap(),
5034 PathBuf::from("/home/u/.eclipse/state")
5035 );
5036 assert_eq!(
5037 state_dir_for(&env, Some("work")).unwrap(),
5038 PathBuf::from("/home/u/.eclipse/profiles/work/state")
5039 );
5040 }
5041
5042 #[test]
5043 fn a_profile_name_must_be_a_safe_directory_name() {
5044 for bad in ["", "../etc", "a/b", "sp ace"] {
5045 assert!(
5046 validate_profile_name(bad).is_err(),
5047 "{bad:?} should be rejected"
5048 );
5049 }
5050 assert!(validate_profile_name("work-2026_x").is_ok());
5051 let env = env_of(&[("HOME", "/home/u")]);
5052 assert!(Config::load_with_profile(None, Some("../evil"), &env).is_err());
5053 }
5054
5055 #[test]
5056 fn plugin_directories_put_the_profile_first() {
5057 let tmp = tempfile::tempdir().unwrap();
5058 let home = tmp.path().join("home");
5059 std::fs::create_dir_all(home.join(".eclipse")).unwrap();
5060 let env = env_of(&[("HOME", home.to_str().unwrap())]);
5061 let mut cfg = Config::default();
5062 let default_dirs = cfg.plugins_dirs(&env);
5063 assert_eq!(
5064 default_dirs,
5065 vec![home.join(".eclipse/plugins")],
5066 "the default profile has no profile plugin dir"
5067 );
5068
5069 cfg.profile = Some("work".into());
5070 let dirs = cfg.plugins_dirs(&env);
5071 assert_eq!(dirs.len(), 2);
5072 assert_eq!(dirs[0], home.join(".eclipse/profiles/work/plugins"));
5073 assert_eq!(dirs[1], home.join(".eclipse/plugins"));
5074
5075 cfg.plugins.dir = Some("~/elsewhere/plugins".into());
5076 assert_eq!(cfg.plugins_dirs(&env)[1], home.join("elsewhere/plugins"));
5077 }
5078
5079 #[test]
5080 fn plugins_are_off_until_named() {
5081 let cfg = Config::default();
5082 assert!(cfg.plugins.enabled.is_empty());
5083 assert!(cfg.plugins.dir.is_none());
5084 let parsed = Config::from_toml_str("[plugins]\nenabled = [\"a\", \"b\"]\n").unwrap();
5085 assert_eq!(parsed.plugins.enabled, ["a", "b"]);
5086 }
5087
5088 #[test]
5091 fn setting_a_key_fills_the_empty_value_and_keeps_every_other_line() {
5092 let text = toml_set_string(&starter(), "provider", "base_url", "http://h:1/v1");
5093 let text = toml_set_string(&text, "provider", "model", "some-model");
5094 assert!(text.contains("base_url = \"http://h:1/v1\""), "{text}");
5095 assert!(text.contains("model = \"some-model\""), "{text}");
5096 assert!(text.contains("# Every setting this build reads"));
5098 assert!(text.contains("[agent]"));
5099 assert!(
5100 !text.contains("base_url = \"\""),
5101 "the empty blank must be gone: {text}"
5102 );
5103 let cfg: Config = toml::from_str(&text).expect("edited config must parse");
5105 assert_eq!(cfg.provider.base_url, "http://h:1/v1");
5106 assert_eq!(cfg.provider.model, "some-model");
5107 }
5108
5109 #[test]
5110 fn setting_a_key_turns_a_commented_template_line_into_the_real_one() {
5111 let text = toml_set_string(&starter(), "provider", "profile", "llamacpp");
5112 assert!(text.contains("\nprofile = \"llamacpp\""), "{text}");
5113 assert_eq!(
5114 text.matches("\nprofile = ").count(),
5115 1,
5116 "no duplicate key (the commented [web] default_profile is a different key): {text}"
5117 );
5118 let cfg: Config = toml::from_str(&text).unwrap();
5119 assert_eq!(cfg.provider.profile.as_deref(), Some("llamacpp"));
5120 }
5121
5122 #[test]
5123 fn setting_a_key_does_not_reach_into_another_section_with_the_same_name() {
5124 let text = toml_set_string(&starter(), "sessions", "dir", "/tmp/sessions-here");
5126 let cfg: Config = toml::from_str(&text).unwrap();
5127 assert_eq!(
5128 cfg.sessions.dir.as_deref(),
5129 Some(std::path::Path::new("/tmp/sessions-here"))
5130 );
5131 assert_eq!(cfg.plugins.dir, None, "{text}");
5132 }
5133
5134 #[test]
5135 fn setting_a_key_in_a_missing_section_adds_the_section() {
5136 let text = toml_set_string("[agent]\nmax_iterations = 5\n", "web", "host", "0.0.0.0");
5137 let cfg: Config = toml::from_str(&text).unwrap();
5138 assert_eq!(cfg.web.host, "0.0.0.0");
5139 assert_eq!(cfg.agent.max_iterations, 5);
5140 }
5141
5142 #[test]
5143 fn reading_a_key_sees_the_live_line_and_not_the_commented_one() {
5144 let text = starter();
5145 assert_eq!(
5146 toml_value(&text, "provider", "base_url"),
5147 Some(String::new())
5148 );
5149 assert_eq!(toml_value(&text, "provider", "temperature"), None);
5153 assert!(text.contains("# temperature ="), "{text}");
5154 assert_eq!(
5155 toml_value(&text, "agent", "max_iterations"),
5156 Some("unlimited".to_string()),
5157 "the cap is written, and its off value is the word `unlimited`"
5158 );
5159 }
5160
5161 #[test]
5165 fn a_dotenv_that_cannot_be_read_is_not_treated_as_an_empty_one() {
5166 let dir = tempfile::tempdir().unwrap();
5167 let dotenv = dir.path().join(".env");
5168 std::fs::create_dir(&dotenv).unwrap();
5169 std::fs::write(dotenv.join("ECLIPSE_WEB_AUTH_TOKEN"), "still here").unwrap();
5170
5171 let err = save_dotenv_var(&dotenv, "ECLIPSE_API_KEY", "sk-1").unwrap_err();
5172 let said = err.to_string();
5173 assert!(
5174 said.contains("nothing was written"),
5175 "the refusal says the file is untouched: {said}"
5176 );
5177 assert!(
5178 dotenv.is_dir(),
5179 "a failed save must not have replaced the path"
5180 );
5181 assert_eq!(
5182 std::fs::read_to_string(dotenv.join("ECLIPSE_WEB_AUTH_TOKEN")).unwrap(),
5183 "still here",
5184 "and nothing under it was touched"
5185 );
5186 }
5187
5188 #[test]
5190 fn a_line_break_in_a_value_is_refused_before_it_writes() {
5191 let dir = tempfile::tempdir().unwrap();
5192 let dotenv = dir.path().join(".env");
5193 std::fs::write(&dotenv, "ECLIPSE_WEB_AUTH_TOKEN=tok\n").unwrap();
5194
5195 let err = save_dotenv_var(&dotenv, "ECLIPSE_API_KEY", "sk-1\nECLIPSE_ADMIN=1").unwrap_err();
5196 assert!(err.to_string().contains("second assignment"), "{err}");
5197 assert_eq!(
5198 std::fs::read_to_string(&dotenv).unwrap(),
5199 "ECLIPSE_WEB_AUTH_TOKEN=tok\n",
5200 "a refused save leaves the file byte for byte"
5201 );
5202 }
5203
5204 #[test]
5207 fn a_save_keeps_every_other_line_and_the_loader_still_reads_them() {
5208 let dir = tempfile::tempdir().unwrap();
5209 let dotenv = dir.path().join(".env");
5210 let before = "# secrets\n\
5211 export ECLIPSE_WEB_USER='max h'\n\
5212 ECLIPSE_WEB_PASSWORD_HASH=\"pbkdf2$abc\"\n\
5213 ECLIPSE_API_KEY=first\n\
5214 ECLIPSE_API_KEY=second\n";
5215 std::fs::write(&dotenv, before).unwrap();
5216
5217 save_dotenv_var(&dotenv, "ECLIPSE_WEB_AUTH_TOKEN", "tok").unwrap();
5218
5219 let after = std::fs::read_to_string(&dotenv).unwrap();
5220 for line in before.lines() {
5221 assert!(after.contains(line), "{line:?} did not survive:\n{after}");
5222 }
5223 assert!(after.contains("ECLIPSE_WEB_AUTH_TOKEN=tok"), "{after}");
5224 }
5225
5226 #[test]
5229 fn dotenv_var_answers_what_the_loader_answers() {
5230 let dir = tempfile::tempdir().unwrap();
5231 let dotenv = dir.path().join(".env");
5232 std::fs::write(
5233 &dotenv,
5234 "A=first\nA=second\nexport B='quoted value'\nC=\"also quoted\"\nD=\n",
5235 )
5236 .unwrap();
5237
5238 assert_eq!(
5239 dotenv_var(&dotenv, "A").as_deref(),
5240 Some("second"),
5241 "the loader is last-wins, so the reader is too"
5242 );
5243 assert_eq!(dotenv_var(&dotenv, "B").as_deref(), Some("quoted value"));
5244 assert_eq!(dotenv_var(&dotenv, "C").as_deref(), Some("also quoted"));
5245 assert_eq!(
5246 dotenv_var(&dotenv, "D"),
5247 None,
5248 "an empty value is absence, as everywhere else"
5249 );
5250 assert_eq!(dotenv_var(&dotenv, "MISSING"), None);
5251 }
5252
5253 #[test]
5254 fn a_config_written_by_setup_is_private_and_a_dotenv_keeps_its_other_lines() {
5255 let dir = tempfile::tempdir().unwrap();
5256 let cfg_path = dir.path().join("config.toml");
5257 let dotenv = dir.path().join(".env");
5258 save_config_text(&cfg_path, "[provider]\nbase_url = \"h\"\n").unwrap();
5259 save_dotenv_var(&dotenv, "ECLIPSE_WEB_AUTH_TOKEN", "tok").unwrap();
5260 save_dotenv_var(&dotenv, "ECLIPSE_API_KEY", "sk-1").unwrap();
5261 save_dotenv_var(&dotenv, "ECLIPSE_API_KEY", "sk-2").unwrap();
5262 let body = std::fs::read_to_string(&dotenv).unwrap();
5263 assert_eq!(body.matches("ECLIPSE_API_KEY").count(), 1, "{body}");
5264 assert_eq!(
5265 dotenv_var(&dotenv, "ECLIPSE_API_KEY").as_deref(),
5266 Some("sk-2")
5267 );
5268 assert_eq!(
5269 dotenv_var(&dotenv, "ECLIPSE_WEB_AUTH_TOKEN").as_deref(),
5270 Some("tok"),
5271 "an unrelated secret must survive"
5272 );
5273 #[cfg(unix)]
5274 {
5275 use std::os::unix::fs::PermissionsExt;
5276 for f in [&cfg_path, &dotenv] {
5277 let mode = std::fs::metadata(f).unwrap().permissions().mode() & 0o777;
5278 assert_eq!(mode, 0o600, "{}", f.display());
5279 }
5280 }
5281 }
5282
5283 #[test]
5284 fn trace_content_is_off_by_default_and_can_be_set() {
5285 assert!(!Config::default().agent.trace_content);
5286 let cfg = Config::from_toml_str(
5287 "[agent]
5288trace_content = true
5289",
5290 )
5291 .unwrap();
5292 assert!(cfg.agent.trace_content);
5293 }
5294
5295 #[test]
5296 fn an_output_schema_is_absent_until_somebody_asks_for_one() {
5297 assert_eq!(Config::default().agent.output_schema, None);
5300 let cfg = Config::from_toml_str(
5301 "[agent]
5302output_schema = \"schemas/plan.json\"
5303",
5304 )
5305 .unwrap();
5306 assert_eq!(
5307 cfg.agent.output_schema.as_deref(),
5308 Some("schemas/plan.json")
5309 );
5310 }
5311
5312 #[test]
5313 fn the_user_section_has_the_defaults_the_docs_promise() {
5314 let cfg = Config::default();
5315 assert_eq!(cfg.user.file, "USER.md");
5316 assert_eq!(cfg.user.memory_file, "MEMORY.md");
5317 assert_eq!(cfg.user.memory_budget_chars, 3000);
5318 assert_eq!(
5319 cfg.agent.context_file_max_chars,
5320 crate::context_files::DEFAULT_MAX_FILE_CHARS
5321 );
5322 assert_eq!(
5323 cfg.agent.context_files_budget_chars,
5324 crate::context_files::DEFAULT_BUDGET_CHARS
5325 );
5326 }
5327
5328 #[test]
5329 fn the_context_and_memory_budgets_can_be_set_in_the_file() {
5330 let cfg = Config::from_toml_str(
5331 "[agent]\ncontext_file_max_chars = 100\ncontext_files_budget_chars = 200\n\
5332 [user]\nfile = \"WHO.md\"\nmemory_file = \"FACTS.md\"\nmemory_budget_chars = 50\n",
5333 )
5334 .unwrap();
5335 assert_eq!(cfg.agent.context_file_max_chars, 100);
5336 assert_eq!(cfg.agent.context_files_budget_chars, 200);
5337 assert_eq!(cfg.user.file, "WHO.md");
5338 assert_eq!(cfg.user.memory_file, "FACTS.md");
5339 assert_eq!(cfg.user.memory_budget_chars, 50);
5340 }
5341
5342 #[test]
5343 fn the_default_profile_keeps_its_files_in_the_config_directory() {
5344 let env = |k: &str| match k {
5345 "HOME" => Some("/home/m".to_string()),
5346 _ => None,
5347 };
5348 let mut cfg = Config::default();
5349 assert_eq!(
5350 cfg.context_dir(&env),
5351 Some(PathBuf::from("/home/m/.eclipse"))
5352 );
5353 cfg.profile = Some("work".into());
5354 assert_eq!(
5355 cfg.context_dir(&env),
5356 Some(PathBuf::from("/home/m/.eclipse/profiles/work"))
5357 );
5358 }
5359
5360 #[test]
5361 fn scripts_live_under_the_profile_when_there_is_one_and_the_config_directory_otherwise() {
5362 let env = |k: &str| match k {
5363 "HOME" => Some("/home/m".to_string()),
5364 _ => None,
5365 };
5366 let mut cfg = Config::default();
5367 assert_eq!(
5368 cfg.scripts_dir(&env),
5369 Some(PathBuf::from("/home/m/.eclipse/scripts"))
5370 );
5371 cfg.profile = Some("work".into());
5372 assert_eq!(
5373 cfg.scripts_dir(&env),
5374 Some(PathBuf::from("/home/m/.eclipse/profiles/work/scripts"))
5375 );
5376 let no_home = |_: &str| None;
5377 assert_eq!(Config::default().scripts_dir(&no_home), None);
5378 }
5379
5380 #[test]
5381 fn a_relative_config_path_still_gives_an_absolute_scripts_directory() {
5382 let env = |k: &str| match k {
5383 "ECLIPSE_CONFIG" => Some("rel/config.toml".to_string()),
5384 _ => None,
5385 };
5386 let dir = Config::default().scripts_dir(&env).unwrap();
5387 assert!(dir.is_absolute(), "{}", dir.display());
5388 assert!(dir.ends_with("rel/scripts"), "{}", dir.display());
5389 }
5390
5391 #[test]
5392 fn the_script_tool_is_asked_about_by_default_and_the_policy_can_be_set_in_the_file() {
5393 assert_eq!(Config::default().tools.script, Policy::Ask);
5394 let cfg = Config::from_toml_str("[tools]\nscript = \"deny\"\n").unwrap();
5395 assert_eq!(cfg.tools.script, Policy::Deny);
5396 let starter = Config::from_toml_str(&super::tests::starter()).unwrap();
5397 assert_eq!(starter.tools.script, Policy::Ask);
5398 assert!(Config::from_toml_str("[tools]\nscript = \"yolo\"\n").is_err());
5399 }
5400
5401 #[test]
5402 fn sight_defaults_to_auto_with_no_route_and_no_cloud() {
5403 let cfg = Config::default();
5404 assert_eq!(cfg.vision.mode, VisionMode::Auto);
5405 assert_eq!(cfg.vision.route, "");
5406 assert!(!cfg.vision.allow_cloud);
5407 }
5408
5409 #[test]
5410 fn the_three_vision_modes_are_spelled_in_the_file_the_way_a_person_says_them() {
5411 for (text, mode) in [
5412 ("native", VisionMode::Native),
5413 ("text", VisionMode::Text),
5414 ("auto", VisionMode::Auto),
5415 ] {
5416 let cfg = Config::from_toml_str(&format!("[vision]\nmode = \"{text}\"\n")).unwrap();
5417 assert_eq!(cfg.vision.mode, mode, "{text}");
5418 }
5419 }
5420
5421 #[test]
5422 fn a_vision_mode_nobody_implements_is_a_load_error_that_lists_the_three() {
5423 let err = Config::from_toml_str("[vision]\nmode = \"telepathy\"\n").unwrap_err();
5424 let sentence = err.to_string();
5425 assert!(sentence.contains("telepathy"), "{sentence}");
5426 assert!(sentence.contains("native"), "{sentence}");
5427 assert!(sentence.contains("text"), "{sentence}");
5428 assert!(sentence.contains("auto"), "{sentence}");
5429 }
5430
5431 #[test]
5432 fn a_vision_route_that_is_not_a_route_is_refused_by_name() {
5433 let cfg = Config::from_toml_str(
5434 "[provider]\nbase_url = \"http://127.0.0.1:1/v1\"\nmodel = \"m\"\n\
5435 [vision]\nroute = \"sight\"\n",
5436 )
5437 .unwrap();
5438 let err = cfg.validate_routes().unwrap_err().to_string();
5439 assert!(err.contains("vision.route"), "{err}");
5440 assert!(err.contains("sight"), "{err}");
5441 assert!(err.contains("default"), "{err}");
5442 }
5443
5444 #[test]
5445 fn a_vision_route_that_exists_validates() {
5446 let cfg = Config::from_toml_str(
5447 "[provider]\nbase_url = \"http://127.0.0.1:1/v1\"\nmodel = \"m\"\n\
5448 [vision]\nroute = \"default\"\n",
5449 )
5450 .unwrap();
5451 cfg.validate_routes().unwrap();
5452 assert_eq!(cfg.vision.route, "default");
5453 }
5454
5455 #[test]
5456 fn the_skills_budget_has_its_documented_default_and_can_be_set_in_the_file() {
5457 assert_eq!(Config::default().skills.index_budget_chars, 4000);
5458 let cfg = Config::from_toml_str("[skills]\nindex_budget_chars = 250\n").unwrap();
5459 assert_eq!(cfg.skills.index_budget_chars, 250);
5460 assert!(starter().contains("[skills]"));
5461 let starter = Config::from_toml_str(&super::tests::starter()).unwrap();
5462 assert_eq!(starter.skills.index_budget_chars, 4000);
5463 }
5464
5465 #[test]
5466 fn the_redacted_config_shows_the_skills_section() {
5467 let mut cfg = Config::default();
5468 cfg.skills.index_budget_chars = 123;
5469 let shown = cfg.to_toml_redacted().unwrap();
5470 assert!(shown.contains("[skills]"), "{shown}");
5471 assert!(shown.contains("index_budget_chars = 123"), "{shown}");
5472 }
5473
5474 #[test]
5475 fn the_starter_writes_the_context_file_settings() {
5476 let text = starter();
5477 let cfg = Config::from_toml_str(&text).unwrap();
5478 assert_eq!(cfg.user.memory_file, "MEMORY.md");
5479 for key in ["context_files_budget_chars", "[user]", "USER.md"] {
5480 assert!(text.contains(key), "the shipped file names `{key}`");
5481 }
5482 }
5483
5484 const TWO_ROUTES: &str = "\
5487[provider]
5488fallback = [\"local\", \"big\"]
5489[[provider.route]]
5490name = \"local\"
5491base_url = \"http://127.0.0.1:8081/v1\"
5492model = \"small\"
5493[[provider.route]]
5494name = \"big\"
5495base_url = \"http://10.0.0.2:8000/v1\"
5496model = \"large\"
5497api_key = \"hunter2\"
5498timeout_secs = 30
5499";
5500
5501 fn parse(text: &str) -> Config {
5502 Config::from_toml_str(text).unwrap()
5503 }
5504
5505 fn refusal(text: &str) -> String {
5506 let c = parse(text);
5507 c.validate_routes()
5508 .and_then(|_| c.chain().map(|_| ()))
5509 .unwrap_err()
5510 .to_string()
5511 }
5512
5513 #[test]
5514 fn a_route_is_a_full_provider_config_and_inherits_nothing_from_provider() {
5515 let c = parse(
5516 "[provider]\nbase_url=\"http://d/v1\"\nmodel=\"dm\"\ntimeout_secs=7\n\
5517 [[provider.route]]\nname=\"r\"\nbase_url=\"http://r/v1\"\nmodel=\"rm\"\n",
5518 );
5519 let r = c.declared_routes();
5520 assert_eq!(
5521 r.iter().map(|r| r.name.as_str()).collect::<Vec<_>>(),
5522 ["default", "r"],
5523 "[provider] is the route called default"
5524 );
5525 assert_eq!(r[0].config.timeout_secs, 7);
5526 assert_eq!(
5527 r[1].config.timeout_secs, 120,
5528 "the route got the built-in default, not [provider]'s 7"
5529 );
5530 }
5531
5532 #[test]
5533 fn provider_may_be_omitted_when_fallback_names_a_route() {
5534 let c = parse(TWO_ROUTES);
5535 c.validate_routes().unwrap();
5536 let chain = c.chain().unwrap();
5537 assert_eq!(chain.source, ChainSource::Fallback);
5538 let names: Vec<_> = chain.routes.iter().map(|r| r.name.as_str()).collect();
5539 assert_eq!(names, ["local", "big"]);
5540 assert_eq!(chain.routes[1].config.timeout_secs, 30);
5541 assert!(
5542 c.declared_routes().iter().all(|r| r.name != "default"),
5543 "no phantom default route appears"
5544 );
5545 }
5546
5547 #[test]
5548 fn a_provider_endpoint_left_out_of_the_chain_is_refused_not_ignored() {
5549 let text = r#"
5553[provider]
5554base_url = "https://api.example.com/v1"
5555model = "gpt"
5556fallback = ["local"]
5557
5558[[provider.route]]
5559name = "local"
5560base_url = "http://127.0.0.1:8080/v1"
5561model = "qwen3-coder"
5562"#;
5563 let err = parse(text).validate_routes().unwrap_err().to_string();
5564 assert!(err.contains("would never be called"), "{err}");
5565 assert!(
5566 err.contains("Put `default` first"),
5567 "it says what to type: {err}"
5568 );
5569 }
5570
5571 #[test]
5572 fn listing_default_first_puts_the_provider_endpoint_back_in_front() {
5573 let text = r#"
5574[provider]
5575base_url = "https://api.example.com/v1"
5576model = "gpt"
5577fallback = ["default", "local"]
5578
5579[[provider.route]]
5580name = "local"
5581base_url = "http://127.0.0.1:8080/v1"
5582model = "qwen3-coder"
5583"#;
5584 let c = parse(text);
5585 c.validate_routes().unwrap();
5586 let chain = c.chain().unwrap();
5587 let names: Vec<_> = chain.routes.iter().map(|r| r.name.as_str()).collect();
5588 assert_eq!(names, ["default", "local"]);
5589 assert_eq!(chain.routes[0].config.model, "gpt");
5590 }
5591
5592 #[test]
5593 fn a_provider_block_of_tuning_keys_alone_does_not_become_a_route() {
5594 let text = "\
5598[provider]
5599max_retries = 0
5600fallback = [\"local\", \"big\"]
5601[[provider.route]]
5602name = \"local\"
5603base_url = \"http://127.0.0.1:8081/v1\"
5604model = \"small\"
5605[[provider.route]]
5606name = \"big\"
5607base_url = \"http://127.0.0.1:8082/v1\"
5608model = \"large\"
5609";
5610 let c = parse(text);
5611 c.validate_routes().unwrap();
5612 let names: Vec<String> = c.declared_routes().into_iter().map(|r| r.name).collect();
5613 assert_eq!(names, ["local", "big"], "no phantom default route");
5614
5615 let mut pinned = parse(text);
5616 let e = pinned.pin_route(Some("default"), &|_| None).unwrap_err();
5617 let e = e.to_string();
5618 assert!(
5619 e.contains("unknown route `default`") && e.contains("local, big"),
5620 "{e}"
5621 );
5622 assert!(!e.contains("provider.base_url"), "{e}");
5623 }
5624
5625 #[test]
5626 fn two_routes_with_the_same_name_are_refused_naming_it() {
5627 let e = refusal(
5628 "[[provider.route]]\nname=\"a\"\nbase_url=\"u\"\nmodel=\"m\"\n\
5629 [[provider.route]]\nname=\"a\"\nbase_url=\"u\"\nmodel=\"m\"\n",
5630 );
5631 assert!(e.contains("`a`") && e.contains("unique"), "{e}");
5632 }
5633
5634 #[test]
5635 fn a_route_with_an_empty_or_missing_name_is_refused_by_position() {
5636 let e = refusal("[[provider.route]]\nname=\" \"\nbase_url=\"u\"\nmodel=\"m\"\n");
5637 assert!(
5638 e.contains("provider.route #1") && e.contains("no name"),
5639 "{e}"
5640 );
5641 let e = refusal("[[provider.route]]\nbase_url=\"u\"\nmodel=\"m\"\n");
5642 assert!(e.contains("provider.route #1"), "{e}");
5643 }
5644
5645 #[test]
5646 fn a_route_named_default_is_refused_only_when_provider_is_also_set() {
5647 let route = "[[provider.route]]\nname=\"default\"\nbase_url=\"u\"\nmodel=\"m\"\n";
5648 let e = refusal(&format!("[provider]\nbase_url=\"x\"\nmodel=\"y\"\n{route}"));
5649 assert!(e.contains("`default`") && e.contains("[provider]"), "{e}");
5650 let c = parse(&format!("[provider]\nfallback=[\"default\"]\n{route}"));
5651 assert_eq!(c.chain().unwrap().routes[0].name, "default");
5652 }
5653
5654 #[test]
5655 fn a_route_without_base_url_or_model_is_refused_naming_the_route() {
5656 let e = refusal("[[provider.route]]\nname=\"nourl\"\nmodel=\"m\"\n");
5657 assert!(e.contains("`nourl`") && e.contains("base_url"), "{e}");
5658 let e = refusal("[[provider.route]]\nname=\"nomodel\"\nbase_url=\"u\"\n");
5659 assert!(e.contains("`nomodel`") && e.contains("model"), "{e}");
5660 }
5661
5662 #[test]
5663 fn a_route_does_not_inherit_a_missing_base_url_from_provider() {
5664 let e = refusal(
5665 "[provider]\nbase_url=\"http://d/v1\"\nmodel=\"dm\"\n\
5666 [[provider.route]]\nname=\"r\"\nmodel=\"m\"\n",
5667 );
5668 assert!(e.contains("`r`") && e.contains("does not inherit"), "{e}");
5669 }
5670
5671 #[test]
5672 fn fallback_naming_a_route_that_does_not_exist_lists_the_ones_that_do() {
5673 let e = refusal(&TWO_ROUTES.replace("\"big\"]", "\"cloud\"]"));
5674 assert!(e.contains("`cloud`"), "{e}");
5675 assert!(e.contains("local, big"), "{e}");
5676 }
5677
5678 #[test]
5679 fn an_empty_fallback_is_a_typo_not_a_policy() {
5680 let e = refusal("[provider]\nfallback = []\n");
5681 assert!(e.contains("provider.fallback is empty"), "{e}");
5682 }
5683
5684 #[test]
5685 fn a_fallback_that_lists_a_route_twice_is_refused() {
5686 let e = refusal(&TWO_ROUTES.replace("[\"local\", \"big\"]", "[\"local\", \"local\"]"));
5687 assert!(e.contains("`local` twice"), "{e}");
5688 }
5689
5690 #[test]
5691 fn a_fallback_or_route_table_inside_a_route_is_refused() {
5692 let e = refusal(
5693 "[[provider.route]]\nname=\"r\"\nbase_url=\"u\"\nmodel=\"m\"\nfallback=[\"r\"]\n",
5694 );
5695 assert!(e.contains("`r`") && e.contains("directly"), "{e}");
5696 }
5697
5698 const WITH_AUX: &str = "\
5699[provider]
5700base_url = \"http://d/v1\"
5701model = \"dm\"
5702aux = \"cheap\"
5703[[provider.route]]
5704name = \"cheap\"
5705base_url = \"http://c/v1\"
5706model = \"cm\"
5707";
5708
5709 #[test]
5710 fn aux_names_a_route_and_the_role_table_says_so() {
5711 let chain = parse(WITH_AUX).chain().unwrap();
5712 assert_eq!(chain.aux.as_ref().map(|r| r.name.as_str()), Some("cheap"));
5713 assert_eq!(chain.aux.unwrap().config.model, "cm");
5714 let roles = parse(WITH_AUX).chain().unwrap().roles();
5715 assert_eq!(roles.len(), 2, "only roles that exist get a row");
5716 assert_eq!(roles[0].to_string(), "judgement \u{2192} cheap");
5717 assert_eq!(
5718 roles[1].to_string(),
5719 "delegate \u{2192} default (no delegate route set)"
5720 );
5721 }
5722
5723 #[test]
5724 fn delegate_names_a_route_and_the_role_table_says_so() {
5725 let c = parse(&WITH_AUX.replace("aux = \"cheap\"", "delegate = \"cheap\""));
5726 let chain = c.chain().unwrap();
5727 assert_eq!(
5728 chain.delegate.as_ref().map(|r| r.name.as_str()),
5729 Some("cheap")
5730 );
5731 assert!(chain.aux.is_none());
5732 let roles = chain.roles();
5733 assert_eq!(
5734 roles[0].to_string(),
5735 "judgement \u{2192} default (no aux route set)"
5736 );
5737 assert_eq!(roles[1].to_string(), "delegate \u{2192} cheap");
5738 }
5739
5740 #[test]
5741 fn a_pin_overrules_the_aux_and_delegate_routes_and_the_role_table_says_pinned() {
5742 let mut c =
5745 parse(&WITH_AUX.replace("aux = \"cheap\"", "aux = \"cheap\"\ndelegate = \"cheap\""));
5746 c.pin_route(Some("cheap"), &|_| None).unwrap();
5747 let chain = c.chain().unwrap();
5748 assert_eq!(chain.source, ChainSource::Pinned);
5749 assert_eq!(
5750 chain.aux.as_ref().map(|r| r.name.as_str()),
5751 Some("cheap"),
5752 "the pinned route, not the key's own value"
5753 );
5754 assert_eq!(
5755 chain.delegate.as_ref().map(|r| r.name.as_str()),
5756 Some("cheap")
5757 );
5758 for role in chain.roles() {
5759 assert!(role.pinned, "{role} should be pinned");
5760 assert!(!role.set, "{role} should not claim the key decided it");
5761 assert_eq!(role.route, "cheap");
5762 assert!(role.to_string().ends_with("(pinned)"), "{role}");
5763 }
5764
5765 let c =
5767 parse(&WITH_AUX.replace("aux = \"cheap\"", "aux = \"cheap\"\ndelegate = \"cheap\""));
5768 let chain = c.chain().unwrap();
5769 assert!(chain.roles().iter().all(|r| r.set && !r.pinned));
5770 }
5771
5772 #[test]
5773 fn an_unknown_empty_or_nested_delegate_route_is_refused_with_the_routes_that_exist() {
5774 let e = refusal(&WITH_AUX.replace("aux = \"cheap\"", "delegate = \"ghost\""));
5775 assert!(
5776 e.contains("provider.delegate names `ghost`") && e.contains("default, cheap"),
5777 "{e}"
5778 );
5779 let c = parse(&WITH_AUX.replace("aux = \"cheap\"", "delegate = \"\""));
5781 c.validate_routes()
5782 .expect("an empty delegate is a config that loads");
5783 let e = refusal(
5784 "[[provider.route]]\nname=\"r\"\nbase_url=\"u\"\nmodel=\"m\"\ndelegate=\"r\"\n\
5785 [provider]\nfallback=[\"r\"]\n",
5786 );
5787 assert!(
5788 e.contains("`r`") && e.contains("`delegate`") && e.contains("directly"),
5789 "{e}"
5790 );
5791 let e = Config::from_toml_str("[provider]\ndelegate = 3\n").unwrap_err();
5792 assert!(e.contains("delegate"), "{e}");
5793 }
5794
5795 #[test]
5796 fn the_delegate_tool_is_asked_about_by_default_and_the_policy_can_be_set_in_the_file() {
5797 assert_eq!(Config::default().tools.delegate, Policy::Ask);
5798 let cfg = Config::from_toml_str("[tools]\ndelegate = \"deny\"\n").unwrap();
5799 assert_eq!(cfg.tools.delegate, Policy::Deny);
5800 let starter = Config::from_toml_str(&super::tests::starter()).unwrap();
5801 assert_eq!(starter.tools.delegate, Policy::Ask);
5802 assert!(Config::from_toml_str("[tools]\ndelegate = \"yolo\"\n").is_err());
5803 }
5804
5805 #[test]
5806 fn with_no_aux_the_summary_role_uses_the_selected_route_and_says_it_was_not_set() {
5807 let chain = parse(TWO_ROUTES).chain().unwrap();
5808 assert!(chain.aux.is_none());
5809 assert_eq!(
5810 chain.roles()[0].to_string(),
5811 "judgement \u{2192} local (no aux route set)"
5812 );
5813 let bare = parse("[provider]\nbase_url=\"u\"\nmodel=\"m\"\n");
5814 assert_eq!(
5815 bare.chain().unwrap().roles()[0].to_string(),
5816 "judgement \u{2192} default (no aux route set)"
5817 );
5818 }
5819
5820 #[test]
5821 fn an_unknown_aux_route_is_refused_listing_the_routes_that_exist() {
5822 let e = refusal(&WITH_AUX.replace("aux = \"cheap\"", "aux = \"ghost\""));
5823 assert!(
5824 e.contains("provider.aux names `ghost`") && e.contains("default, cheap"),
5825 "{e}"
5826 );
5827 let c = parse(&WITH_AUX.replace("aux = \"cheap\"", "aux = \"\""));
5831 c.validate_routes()
5832 .expect("an empty aux route is a config that loads");
5833 assert!(c.chain().unwrap().aux.is_none());
5834 }
5835
5836 #[test]
5837 fn aux_inside_a_route_is_refused_like_fallback_and_route() {
5838 let e = refusal(
5839 "[[provider.route]]\nname=\"r\"\nbase_url=\"u\"\nmodel=\"m\"\naux=\"r\"\n\
5840 [provider]\nfallback=[\"r\"]\n",
5841 );
5842 assert!(
5843 e.contains("`r`") && e.contains("`aux`") && e.contains("directly"),
5844 "{e}"
5845 );
5846 }
5847
5848 #[test]
5849 fn a_wrong_typed_aux_is_an_error_naming_the_key() {
5850 let e = Config::from_toml_str("[provider]\naux = 3\n").unwrap_err();
5851 assert!(e.contains("aux"), "{e}");
5852 }
5853
5854 #[test]
5855 fn aux_may_name_the_default_route_when_provider_is_one() {
5856 let c = parse(&WITH_AUX.replace("aux = \"cheap\"", "aux = \"default\""));
5857 assert_eq!(c.chain().unwrap().aux.unwrap().name, "default");
5858 let tuning_only = "[provider]\naux = \"default\"\nmax_retries = 1\n\
5859 [[provider.route]]\nname=\"r\"\nbase_url=\"u\"\nmodel=\"m\"\n";
5860 assert!(refusal(tuning_only).contains("Routes that exist: r"));
5861 }
5862
5863 #[test]
5864 fn a_wrong_typed_route_value_is_an_error_and_not_a_default() {
5865 let bad =
5866 "[[provider.route]]\nname=\"r\"\nbase_url=\"u\"\nmodel=\"m\"\ntimeout_secs=\"soon\"\n";
5867 let e = Config::from_toml_str(bad).unwrap_err();
5868 assert!(e.contains("timeout_secs") || e.contains("soon"), "{e}");
5869 let e = Config::from_toml_str("[provider]\nfallback = \"local\"\n").unwrap_err();
5870 assert!(e.contains("fallback") || e.contains("sequence"), "{e}");
5871 }
5872
5873 #[test]
5874 fn routes_with_no_fallback_and_no_pin_say_what_to_set() {
5875 let e = refusal("[[provider.route]]\nname=\"r\"\nbase_url=\"u\"\nmodel=\"m\"\n");
5876 assert!(
5877 e.contains("fallback") && e.contains("--route") && e.contains("r"),
5878 "{e}"
5879 );
5880 }
5881
5882 #[test]
5883 fn with_no_fallback_and_no_pin_the_chain_is_the_default_route_alone() {
5884 let c = parse(
5885 "[provider]\nbase_url=\"http://d/v1\"\nmodel=\"dm\"\n\
5886 [[provider.route]]\nname=\"r\"\nbase_url=\"u\"\nmodel=\"m\"\n",
5887 );
5888 let chain = c.chain().unwrap();
5889 assert_eq!(chain.source, ChainSource::Default);
5890 assert_eq!(chain.routes.len(), 1);
5891 assert_eq!(chain.routes[0].name, "default");
5892 let bare = parse("[provider]\nbase_url=\"http://d/v1\"\nmodel=\"dm\"\n");
5893 assert_eq!(bare.chain().unwrap().source, ChainSource::Default);
5894 }
5895
5896 #[test]
5897 fn a_bare_config_still_says_what_is_wrong_with_provider() {
5898 let e = Config::default()
5899 .require_provider()
5900 .unwrap_err()
5901 .to_string();
5902 assert!(e.contains("provider.base_url is not set"), "{e}");
5903 assert!(e.contains("eclipse config init"), "{e}");
5904 let c = parse("[provider]\nbase_url=\"u\"\n");
5905 assert!(c
5906 .require_provider()
5907 .unwrap_err()
5908 .to_string()
5909 .contains("provider.model is not set"));
5910 }
5911
5912 #[test]
5913 fn a_pin_selects_one_route_and_marks_the_chain_pinned() {
5914 let mut c = parse(TWO_ROUTES);
5915 c.pin_route(Some("big"), &env_of(&[])).unwrap();
5916 let chain = c.chain().unwrap();
5917 assert_eq!(chain.source, ChainSource::Pinned);
5918 assert_eq!(chain.routes.len(), 1);
5919 assert_eq!(chain.routes[0].name, "big");
5920 }
5921
5922 #[test]
5923 fn an_unknown_pin_lists_the_routes_that_exist() {
5924 let mut c = parse(TWO_ROUTES);
5925 let e = c
5926 .pin_route(Some("nope"), &env_of(&[]))
5927 .unwrap_err()
5928 .to_string();
5929 assert!(e.contains("`nope`") && e.contains("local, big"), "{e}");
5930 let e = c
5931 .pin_route(Some(" "), &env_of(&[]))
5932 .unwrap_err()
5933 .to_string();
5934 assert!(e.contains("--route needs a route name"), "{e}");
5935 }
5936
5937 #[test]
5938 fn eclipse_route_is_honoured_when_the_flag_is_absent_and_the_flag_wins() {
5939 let mut c = parse(TWO_ROUTES);
5940 c.pin_route(None, &env_of(&[("ECLIPSE_ROUTE", "big")]))
5941 .unwrap();
5942 assert_eq!(c.route_pin.as_deref(), Some("big"));
5943 c.pin_route(Some("local"), &env_of(&[("ECLIPSE_ROUTE", "big")]))
5944 .unwrap();
5945 assert_eq!(c.route_pin.as_deref(), Some("local"));
5946 let mut c = parse(TWO_ROUTES);
5947 c.dotenv
5948 .values
5949 .insert("ECLIPSE_ROUTE".into(), "local".into());
5950 c.pin_route(None, &env_of(&[])).unwrap();
5951 assert_eq!(
5952 c.route_pin.as_deref(),
5953 Some("local"),
5954 "the .env chain counts too"
5955 );
5956 let mut c = parse(TWO_ROUTES);
5957 c.pin_route(None, &env_of(&[])).unwrap();
5958 assert_eq!(c.route_pin, None);
5959 }
5960
5961 #[test]
5962 fn a_route_takes_its_key_from_its_own_api_key_env_and_eclipse_api_key_is_default_only() {
5963 let mut c = parse(
5964 "[provider]\nbase_url=\"http://d/v1\"\nmodel=\"dm\"\n\
5965 [[provider.route]]\nname=\"r\"\nbase_url=\"u\"\nmodel=\"m\"\napi_key_env=\"R_KEY\"\n",
5966 );
5967 c.apply_env(&env_of(&[
5968 ("R_KEY", "from-r"),
5969 ("ECLIPSE_API_KEY", "for-default"),
5970 ]));
5971 assert_eq!(c.provider.api_key.as_deref(), Some("for-default"));
5972 assert_eq!(
5973 c.provider.route[0].config.api_key.as_deref(),
5974 Some("from-r")
5975 );
5976
5977 let mut only_routes = parse(TWO_ROUTES);
5978 only_routes.apply_env(&env_of(&[("ECLIPSE_API_KEY", "stray")]));
5979 assert_eq!(
5980 only_routes.provider.api_key, None,
5981 "no phantom default route"
5982 );
5983 assert_eq!(only_routes.provider.route[0].config.api_key, None);
5984 }
5985
5986 #[test]
5987 fn the_redacted_config_hides_every_routes_key_and_round_trips() {
5988 let c = parse(TWO_ROUTES);
5989 let t = c.to_toml_redacted().unwrap();
5990 assert!(!t.contains("hunter2"), "{t}");
5991 assert!(
5992 t.contains("[[provider.route]]") && t.contains("<redacted>"),
5993 "{t}"
5994 );
5995 let back = parse(&t);
5996 assert_eq!(back.provider.fallback, c.provider.fallback);
5997 assert_eq!(back.provider.route.len(), 2);
5998 assert_eq!(back.provider.route[1].config.timeout_secs, 30);
5999 }
6000
6001 #[test]
6002 fn a_config_without_routes_prints_no_provider_route_keys() {
6003 let c = parse("[provider]\nbase_url=\"u\"\nmodel=\"m\"\n");
6006 let t = c.to_toml_redacted().unwrap();
6007 let parsed: toml::Value = toml::from_str(&t).unwrap();
6008 let provider = parsed.get("provider").expect("a provider table");
6009 for absent in ["route", "fallback", "aux", "delegate"] {
6010 assert!(
6011 provider.get(absent).is_none(),
6012 "`provider.{absent}` printed for a config with one route: {t}"
6013 );
6014 }
6015 }
6016
6017 #[test]
6018 fn a_bad_route_table_is_refused_when_the_config_is_loaded() {
6019 let tmp = tempfile::tempdir().unwrap();
6020 let path = tmp.path().join("c.toml");
6021 std::fs::write(&path, "[provider]\nfallback = [\"ghost\"]\n").unwrap();
6022 let e = Config::load_with(Some(&path), &env_of(&[]))
6023 .unwrap_err()
6024 .to_string();
6025 assert!(e.contains("`ghost`"), "{e}");
6026 }
6027
6028 #[test]
6029 fn context_policy_defaults_and_the_rail_it_derives() {
6030 let c = ContextPolicyConfig::default();
6031 assert!(
6032 c.judge,
6033 "the model half is the judgement pass, and it ships on: compile plus one bounded call"
6034 );
6035 assert_eq!(c.judge_timeout_secs, 20, "and it cannot hang the turn");
6036 assert_eq!(c.compact_at, 0.85);
6037 assert_eq!(c.protect_last_n, 20, "the tail keeps twenty turns");
6038 assert_eq!(c.window_tokens, 0, "no window is invented");
6039 assert_eq!(c.budget_for(0), 0, "no window, no rail");
6040 assert_eq!(c.budget_for(327_680), 278_528);
6041 let off = ContextPolicyConfig {
6042 compact_at: 0.0,
6043 ..c.clone()
6044 };
6045 assert_eq!(off.budget_for(327_680), 0, "compact_at = 0 is off");
6046 let half = ContextPolicyConfig {
6047 compact_at: 0.5,
6048 ..c
6049 };
6050 assert_eq!(half.budget_for(131_072), 65_536);
6051 }
6052
6053 #[test]
6054 fn a_compact_at_outside_the_window_is_a_config_error_naming_the_key() {
6055 for bad in ["1.5", "-0.2"] {
6056 let c = parse(&format!("[context]\ncompact_at = {bad}\n"));
6057 let err = c.context.validate().unwrap_err().to_string();
6058 assert!(
6059 err.contains("context.compact_at"),
6060 "{bad} must be named in the error: {err}"
6061 );
6062 }
6063 assert!(parse("[context]\ncompact_at = 0.6\n")
6064 .context
6065 .validate()
6066 .is_ok());
6067 assert!(parse("[context]\ncompact_at = 0\n")
6068 .context
6069 .validate()
6070 .is_ok());
6071 }
6072}
6073
6074#[cfg(test)]
6075mod mcp_editor_tests {
6076 use super::*;
6077 use crate::mcp::Spec;
6078
6079 fn spec(text: &str) -> Spec {
6080 toml::from_str(text).unwrap()
6081 }
6082
6083 fn add(spec: &Spec) -> String {
6084 let out = mcp_add(CONFIG, spec).unwrap();
6085 parse_text(&out).unwrap();
6087 out
6088 }
6089
6090 const CONFIG: &str = r#"# my config
6091[provider]
6092base_url = "http://127.0.0.1:8081/v1"
6093model = "m"
6094
6095# this comment belongs to the first entry
6096[[mcp]]
6097name = "first"
6098command = "one"
6099
6100# and this one to the second
6101[[mcp]]
6102name = "second"
6103command = "two"
6104policy = "allow"
6105"#;
6106
6107 #[test]
6108 fn an_added_entry_reads_back_and_leaves_the_comments_alone() {
6109 let out = add(&spec(
6110 "name = \"third\"\ncommand = \"three\"\nargs = [\"--x\"]\nprefix = \"t_\"\n",
6111 ));
6112 let cfg = parse_text(&out).unwrap();
6113 assert_eq!(
6114 cfg.mcp.iter().map(|s| s.name.as_str()).collect::<Vec<_>>(),
6115 ["first", "second", "third"]
6116 );
6117 let third = cfg.mcp.iter().find(|s| s.name == "third").unwrap();
6118 assert_eq!(third.args, ["--x"]);
6119 assert_eq!(third.prefix, "t_");
6120 for line in [
6122 "# my config",
6123 "# this comment belongs to the first entry",
6124 "# and this one to the second",
6125 ] {
6126 assert!(out.contains(line), "lost {line:?}:\n{out}");
6127 }
6128 assert!(
6129 out.contains("[[mcp]]\nname = \"first\"\ncommand = \"one\""),
6130 "{out}"
6131 );
6132 assert!(
6133 !out.contains("args = []"),
6134 "only what was set is written:\n{out}"
6135 );
6136 }
6137
6138 #[test]
6139 fn a_duplicate_name_is_refused_and_named_by_line() {
6140 let err = mcp_add(CONFIG, &spec("name = \"first\"\ncommand = \"again\"")).unwrap_err();
6141 assert!(err.contains("already declared at line 7"), "{err}");
6142 }
6143
6144 #[test]
6145 fn an_unusable_entry_is_refused_before_anything_is_written() {
6146 let err = mcp_add(
6148 CONFIG,
6149 &spec("name = \"bad\"\ntransport = \"http\"\ncommand = \"x\"\nurl = \"http://h/mcp\""),
6150 )
6151 .unwrap_err();
6152 assert!(err.starts_with("that entry is not usable"), "{err}");
6153 assert!(err.contains("belong to the stdio transport"), "{err}");
6154 }
6155
6156 #[test]
6157 fn remove_takes_the_named_block_and_the_blank_line_after_it() {
6158 let out = mcp_remove(CONFIG, "first").unwrap();
6159 let cfg = parse_text(&out).unwrap();
6160 assert_eq!(
6161 cfg.mcp.iter().map(|s| s.name.as_str()).collect::<Vec<_>>(),
6162 ["second"]
6163 );
6164 assert!(out.contains("# and this one to the second"), "{out}");
6166 assert!(!out.contains("name = \"first\""), "{out}");
6167 assert!(!out.contains("\n\n\n"), "no hole left behind:\n{out}");
6168 }
6169
6170 #[test]
6171 fn remove_says_what_the_file_does_declare() {
6172 let err = mcp_remove(CONFIG, "nope").unwrap_err();
6173 assert!(err.contains("declares first, second"), "{err}");
6174 let bare = "[provider]\nbase_url = \"http://d/v1\"\nmodel = \"m\"\n";
6175 let err = mcp_remove(bare, "nope").unwrap_err();
6176 assert!(err.contains("no `[[mcp]]` entry for `nope`"), "{err}");
6177 }
6178
6179 #[test]
6180 fn disable_flips_the_line_inside_its_own_block() {
6181 let off = mcp_set_disabled(CONFIG, "second", true).unwrap();
6182 let cfg = parse_text(&off).unwrap();
6183 assert!(
6184 cfg.mcp
6185 .iter()
6186 .find(|s| s.name == "second")
6187 .unwrap()
6188 .disabled
6189 );
6190 assert!(!cfg.mcp.iter().find(|s| s.name == "first").unwrap().disabled);
6191 let second_at = off.find("name = \"second\"").unwrap();
6193 let tail = &off[second_at..];
6194 assert!(tail.contains("disabled = true"), "{off}");
6195 assert!(tail.find("disabled").unwrap() < tail.find("\n[[").unwrap_or(tail.len()));
6196
6197 let on = mcp_set_disabled(&off, "second", false).unwrap();
6198 let cfg = parse_text(&on).unwrap();
6199 assert!(
6200 !cfg.mcp
6201 .iter()
6202 .find(|s| s.name == "second")
6203 .unwrap()
6204 .disabled
6205 );
6206 assert!(
6207 on.contains("disabled = false"),
6208 "said out loud, not deleted:\n{on}"
6209 );
6210 }
6211
6212 #[test]
6213 fn disable_on_an_entry_without_the_key_inserts_one() {
6214 let off = mcp_set_disabled(CONFIG, "first", true).unwrap();
6215 assert!(off.contains("command = \"one\"\ndisabled = true"), "{off}");
6216 assert!(parse_text(&off).unwrap().mcp[0].disabled);
6217 }
6218
6219 #[test]
6223 fn an_edit_changes_the_changed_line_and_leaves_every_other_byte_alone() {
6224 let out = mcp_update(CONFIG, "second", |entry| entry.prefix = "t_".into()).unwrap();
6225 parse_text(&out).unwrap();
6226 assert_eq!(
6227 out,
6228 CONFIG.replace(
6229 "command = \"two\"\npolicy = \"allow\"",
6230 "command = \"two\"\npolicy = \"allow\"\nprefix = \"t_\""
6231 ),
6232 "one added line, and not one other character moved:\n{out}"
6233 );
6234 }
6235
6236 #[test]
6239 fn an_edit_sets_and_clears_token_env_without_touching_the_rest() {
6240 let on = mcp_update(CONFIG, "second", |entry| {
6241 entry.token_env = Some("HA_TOKEN".into())
6242 })
6243 .unwrap();
6244 assert_eq!(
6245 on,
6246 CONFIG.replace(
6247 "command = \"two\"\npolicy = \"allow\"",
6248 "command = \"two\"\npolicy = \"allow\"\ntoken_env = \"HA_TOKEN\""
6249 ),
6250 "{on}"
6251 );
6252 let off = mcp_update(&on, "second", |entry| entry.token_env = None).unwrap();
6253 assert_eq!(
6254 off, CONFIG,
6255 "clearing a field removes its line and nothing else"
6256 );
6257 }
6258
6259 #[test]
6262 fn an_edit_keeps_a_comment_written_inside_the_block() {
6263 let inner = "[[mcp]]\nname = \"a\"\n# the endpoint is on the box\ncommand = \"x\"\n";
6264 let out = mcp_update(inner, "a", |entry| {
6265 entry.args = vec!["--y".into()];
6266 })
6267 .unwrap();
6268 assert_eq!(
6269 out,
6270 "[[mcp]]\nname = \"a\"\n# the endpoint is on the box\ncommand = \"x\"\n\
6271 args = [\"--y\"]\n",
6272 "{out}"
6273 );
6274 }
6275
6276 #[test]
6278 fn an_edit_refuses_a_rename_and_names_what_the_file_declares() {
6279 let err = mcp_update(CONFIG, "second", |entry| entry.name = "renamed".into()).unwrap_err();
6280 assert!(err.contains("an edit does not rename"), "{err}");
6281
6282 let err = mcp_update(CONFIG, "nope", |_| {}).unwrap_err();
6283 assert!(err.contains("declares first, second"), "{err}");
6284
6285 let err = mcp_update(CONFIG, "second", |entry| {
6287 entry.transport = crate::mcp::Transport::Http;
6288 entry.url = Some("http://h/mcp".into());
6289 })
6290 .unwrap_err();
6291 assert!(err.starts_with("that entry is not usable"), "{err}");
6292 assert!(err.contains("belong to the stdio transport"), "{err}");
6293 }
6294
6295 #[test]
6296 fn an_empty_file_gets_its_first_entry_cleanly() {
6297 let out = mcp_add("", &spec("name = \"only\"\ncommand = \"x\"")).unwrap();
6298 assert!(out.starts_with("[[mcp]]\n"), "{out:?}");
6299 assert_eq!(parse_text(&out).unwrap().mcp[0].name, "only");
6300 }
6301
6302 #[test]
6303 fn a_second_entry_is_separated_by_exactly_one_blank_line() {
6304 let out = add(&spec("name = \"third\"\ncommand = \"three\""));
6305 assert!(!out.contains("\n\n\n"), "{out}");
6306 assert!(
6307 out.contains("policy = \"allow\"\n\n[[mcp]]\nname = \"third\""),
6308 "{out}"
6309 );
6310 }
6311}