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
979fn default_hidden_paths() -> Vec<PathBuf> {
986 ["~/.ssh", "~/.gnupg", "~/.aws", "~/.hermes"]
987 .iter()
988 .map(PathBuf::from)
989 .collect()
990}
991
992fn default_deferred() -> Vec<String> {
1000 vec!["plugin:mcp:*".to_string(), "config:mcp:*".to_string()]
1001}
1002
1003fn default_rewrite_guard() -> usize {
1004 32 * 1024
1005}
1006
1007impl Default for ToolsConfig {
1008 fn default() -> Self {
1009 Self {
1010 workspace_root: None,
1011 read_file: Policy::Allow,
1012 search_files: Policy::Allow,
1013 write_file: Policy::Allow,
1017 rewrite_guard_bytes: default_rewrite_guard(),
1018 patch: Policy::Allow,
1019 memory: Policy::Ask,
1020 shell: Policy::Ask,
1021 fetch: Policy::Ask,
1022 script: Policy::Ask,
1023 execute_code: Policy::Ask,
1024 delegate: Policy::Ask,
1025 shell_ask: ShellAsk::Dangerous,
1026 shell_timeout_secs: 30,
1027 shell_allowlist: Vec::new(),
1028 shell_isolate: ShellIsolate::Process,
1029 shell_isolate_writable: Vec::new(),
1030 shell_isolate_hide: default_hidden_paths(),
1031 shell_isolate_network: true,
1032 fetch_timeout_secs: 20,
1033 fetch_html: FetchHtml::Text,
1034 max_output_bytes: 32 * 1024,
1035 concurrency: 1,
1036 disabled: Vec::new(),
1037 deferred: default_deferred(),
1038 tool_search: Policy::Allow,
1039 tool_describe: Policy::Allow,
1040 tool_call: Policy::Allow,
1041 }
1042 }
1043}
1044
1045#[derive(Debug, Clone, Serialize, Deserialize)]
1046#[serde(default)]
1047pub struct SessionsConfig {
1048 pub dir: Option<PathBuf>,
1050 pub retention_keep_days: u64,
1053 pub retention_keep_count: usize,
1056 pub auto_prune: bool,
1061 pub lock_wait_secs: u64,
1064 pub autotitle: bool,
1068}
1069
1070impl Default for SessionsConfig {
1071 fn default() -> Self {
1072 Self {
1073 dir: None,
1074 retention_keep_days: 0,
1075 retention_keep_count: 0,
1076 auto_prune: false,
1077 lock_wait_secs: 30,
1078 autotitle: true,
1079 }
1080 }
1081}
1082
1083#[derive(Clone, Serialize, Deserialize)]
1084#[serde(default)]
1085pub struct WebConfig {
1086 pub host: String,
1087 pub port: u16,
1088 #[serde(deserialize_with = "empty_is_none")]
1091 pub auth_token: Option<String>,
1092 pub session_ttl_hours: u64,
1095 #[serde(deserialize_with = "empty_is_none")]
1098 pub default_profile: Option<String>,
1099}
1100
1101impl Default for WebConfig {
1102 fn default() -> Self {
1103 Self {
1104 host: "127.0.0.1".into(),
1105 port: 8787,
1106 auth_token: None,
1107 session_ttl_hours: DEFAULT_SESSION_TTL_HOURS,
1108 default_profile: None,
1109 }
1110 }
1111}
1112
1113#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1115#[serde(default)]
1116pub struct GatewayConfig {
1117 pub check_interval_hours: u64,
1121 #[serde(default = "default_api_session_ttl_hours")]
1125 pub api_session_ttl_hours: u64,
1126}
1127
1128pub fn default_api_session_ttl_hours() -> u64 {
1129 24
1130}
1131
1132impl Default for GatewayConfig {
1133 fn default() -> Self {
1134 Self {
1135 check_interval_hours: 6,
1136 api_session_ttl_hours: default_api_session_ttl_hours(),
1137 }
1138 }
1139}
1140
1141pub const DEFAULT_SESSION_TTL_HOURS: u64 = 12;
1143
1144#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
1146#[serde(rename_all = "lowercase")]
1147pub enum Approval {
1148 #[default]
1150 Ask,
1151 Auto,
1153 Smart,
1159}
1160
1161#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1164#[serde(default)]
1165pub struct CliConfig {
1166 pub color: Option<bool>,
1168 pub markdown: Option<bool>,
1170 pub approval: Approval,
1173 pub history_size: usize,
1175 pub clear_on_exit: ClearOnExit,
1177}
1178
1179impl Default for CliConfig {
1180 fn default() -> Self {
1181 Self {
1182 color: None,
1183 markdown: None,
1184 approval: Approval::Ask,
1185 history_size: 1000,
1187 clear_on_exit: ClearOnExit::Screen,
1188 }
1189 }
1190}
1191
1192#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
1198#[serde(rename_all = "lowercase")]
1199pub enum ClearOnExit {
1200 #[default]
1203 Screen,
1204 All,
1206 Off,
1208}
1209
1210#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
1212#[serde(rename_all = "lowercase")]
1213pub enum UpdateCheck {
1214 #[default]
1216 Daily,
1217 Weekly,
1218 Off,
1220}
1221
1222impl UpdateCheck {
1223 pub fn period_secs(self) -> Option<u64> {
1225 match self {
1226 UpdateCheck::Daily => Some(86_400),
1227 UpdateCheck::Weekly => Some(7 * 86_400),
1228 UpdateCheck::Off => None,
1229 }
1230 }
1231}
1232
1233#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
1240#[serde(rename_all = "lowercase")]
1241pub enum Track {
1242 #[default]
1245 Release,
1246 Develop,
1248}
1249
1250impl Track {
1251 pub fn label(self) -> &'static str {
1253 match self {
1254 Track::Release => "release",
1255 Track::Develop => "develop",
1256 }
1257 }
1258
1259 pub fn branch(self) -> &'static str {
1262 match self {
1263 Track::Release => "main",
1264 Track::Develop => "develop",
1265 }
1266 }
1267}
1268
1269#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1275#[serde(default)]
1276pub struct HooksConfig {
1277 pub order: Vec<String>,
1278 #[serde(flatten)]
1281 pub settings: BTreeMap<String, toml::Value>,
1282}
1283
1284impl Default for HooksConfig {
1285 fn default() -> Self {
1286 Self {
1287 order: crate::hooks::DEFAULT_ORDER
1288 .iter()
1289 .map(|n| n.to_string())
1290 .collect(),
1291 settings: BTreeMap::new(),
1292 }
1293 }
1294}
1295
1296#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1299#[serde(default)]
1300pub struct UpdateConfig {
1301 pub check: UpdateCheck,
1302 pub track: Track,
1308 #[serde(deserialize_with = "empty_is_none")]
1313 pub remote: Option<String>,
1314 #[serde(deserialize_with = "empty_is_none")]
1319 pub releases: Option<String>,
1320}
1321
1322impl fmt::Debug for WebConfig {
1323 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1324 f.debug_struct("WebConfig")
1325 .field("host", &self.host)
1326 .field("port", &self.port)
1327 .field(
1328 "auth_token",
1329 &self.auth_token.as_ref().map(|_| "<redacted>"),
1330 )
1331 .finish()
1332 }
1333}
1334
1335#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1341#[serde(default)]
1342pub struct AttachmentsConfig {
1343 pub dir: Option<PathBuf>,
1347 pub max_total_bytes: u64,
1351}
1352
1353impl Default for AttachmentsConfig {
1354 fn default() -> Self {
1355 Self {
1356 dir: None,
1357 max_total_bytes: 2 * 1024 * 1024 * 1024,
1358 }
1359 }
1360}
1361
1362#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1363#[serde(default)]
1364pub struct Config {
1365 pub config_version: u32,
1372 pub provider: ProviderConfig,
1373 pub agent: AgentConfig,
1374 pub tools: ToolsConfig,
1375 pub sessions: SessionsConfig,
1376 pub attachments: AttachmentsConfig,
1377 pub plugins: PluginsConfig,
1378 pub web: WebConfig,
1379 pub gateway: GatewayConfig,
1380 pub cli: CliConfig,
1381 pub update: UpdateConfig,
1382 pub hooks: HooksConfig,
1383 pub context: ContextPolicyConfig,
1384 pub user: UserConfig,
1385 pub skills: SkillsConfig,
1386 pub vision: VisionConfig,
1387 #[serde(skip)]
1390 pub profile: Option<String>,
1391 #[serde(skip)]
1394 pub route_pin: Option<String>,
1395 #[serde(skip)]
1398 pub dotenv: Dotenv,
1399 #[serde(default)]
1404 pub mcp: Vec<crate::mcp::Spec>,
1405 #[serde(skip)]
1409 pub no_mcp: bool,
1410 #[serde(default)]
1412 pub flares: FlaresConfig,
1413 #[serde(default)]
1417 pub bots: std::collections::BTreeMap<String, BotConfig>,
1418}
1419
1420#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1426#[serde(default)]
1427pub struct FlaresConfig {
1428 pub count: usize,
1431 pub max_concurrent: usize,
1433 pub max_iterations: usize,
1435 pub total_iterations: usize,
1438 pub total_tokens: Option<u64>,
1440}
1441
1442impl Default for FlaresConfig {
1443 fn default() -> Self {
1444 Self {
1445 count: 3,
1446 max_concurrent: 4,
1447 max_iterations: 6,
1448 total_iterations: 24,
1449 total_tokens: None,
1450 }
1451 }
1452}
1453
1454impl FlaresConfig {
1455 pub fn concurrency(&self) -> usize {
1458 self.max_concurrent.max(1)
1459 }
1460
1461 pub fn per_flare(&self) -> usize {
1463 self.max_iterations.max(1)
1464 }
1465
1466 pub fn budget(&self) -> usize {
1470 self.total_iterations.max(1)
1471 }
1472}
1473
1474#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1481#[serde(default)]
1482pub struct BotConfig {
1483 pub instructions: Option<String>,
1487 pub skills: Option<Vec<String>>,
1491 pub memory: Option<String>,
1495 pub adapter: Option<String>,
1498}
1499
1500pub const BOT_ADAPTERS: &[&str] = &[];
1504
1505#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1508#[serde(default)]
1509pub struct ContextPolicyConfig {
1510 pub compact_at: f64,
1513 pub protect_last_n: usize,
1515 pub judge: bool,
1519 pub judge_timeout_secs: u64,
1521 pub window_tokens: usize,
1524 pub handoff_chars: usize,
1527}
1528
1529impl Default for ContextPolicyConfig {
1530 fn default() -> Self {
1531 Self {
1532 compact_at: 0.85,
1533 protect_last_n: crate::context::DEFAULT_PROTECT_LAST_N,
1534 judge: true,
1535 judge_timeout_secs: 20,
1536 window_tokens: 0,
1537 handoff_chars: 6_000,
1538 }
1539 }
1540}
1541
1542impl ContextPolicyConfig {
1543 pub fn budget_for(&self, window_tokens: usize) -> usize {
1545 if window_tokens == 0 || self.compact_at.is_nan() || self.compact_at <= 0.0 {
1546 return 0;
1547 }
1548 (window_tokens as f64 * self.compact_at) as usize
1549 }
1550
1551 pub fn validate(&self) -> Result<()> {
1554 if !(0.0..=1.0).contains(&self.compact_at) {
1555 return Err(Error::Config(format!(
1556 "context.compact_at: {} is not a share of the window; use 0.85 for 85%, or 0 to \
1557 turn the threshold off",
1558 self.compact_at
1559 )));
1560 }
1561 if self.handoff_chars < 200 {
1562 return Err(Error::Config(format!(
1563 "context.handoff_chars: {} is too small to compile a handoff; 200 is the floor \
1564 and 6000 is the default",
1565 self.handoff_chars
1566 )));
1567 }
1568 Ok(())
1569 }
1570}
1571
1572#[derive(Debug, Clone, Serialize, Deserialize)]
1574#[serde(default)]
1575pub struct UserConfig {
1576 pub file: String,
1578 pub memory_file: String,
1580 pub memory_budget_chars: usize,
1583}
1584
1585impl Default for UserConfig {
1586 fn default() -> Self {
1587 Self {
1588 file: "USER.md".into(),
1589 memory_file: "MEMORY.md".into(),
1590 memory_budget_chars: crate::memory::DEFAULT_BUDGET_CHARS,
1591 }
1592 }
1593}
1594
1595#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1602#[serde(default)]
1603pub struct VisionConfig {
1604 #[serde(default)]
1607 pub mode: VisionMode,
1608 #[serde(default)]
1611 pub route: String,
1612 #[serde(default)]
1615 pub allow_cloud: bool,
1616}
1617
1618#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
1620#[serde(rename_all = "lowercase")]
1621pub enum VisionMode {
1622 Native,
1624 Text,
1626 #[default]
1628 Auto,
1629}
1630
1631#[derive(Debug, Clone, Serialize, Deserialize)]
1632#[serde(default)]
1633pub struct SkillsConfig {
1634 pub index_budget_chars: usize,
1637}
1638
1639impl Default for SkillsConfig {
1640 fn default() -> Self {
1641 Self {
1642 index_budget_chars: crate::skills::DEFAULT_INDEX_BUDGET_CHARS,
1643 }
1644 }
1645}
1646
1647#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1649#[serde(default)]
1650pub struct PluginsConfig {
1651 pub dir: Option<PathBuf>,
1654 pub enabled: Vec<String>,
1656 pub mcp_timeout_secs: Option<u64>,
1659}
1660
1661impl Config {
1662 pub fn load(explicit: Option<&Path>) -> Result<Config> {
1665 Self::load_with(explicit, &process_env)
1666 }
1667
1668 pub fn load_with(explicit: Option<&Path>, env: EnvFn) -> Result<Config> {
1669 Self::load_with_profile(explicit, None, env)
1670 }
1671
1672 pub fn load_with_profile(
1681 explicit: Option<&Path>,
1682 profile: Option<&str>,
1683 env: EnvFn,
1684 ) -> Result<Config> {
1685 let profile = profile
1686 .map(str::to_string)
1687 .or_else(|| env("ECLIPSE_PROFILE"))
1688 .filter(|p| !p.trim().is_empty());
1689 if let Some(name) = &profile {
1690 validate_profile_name(name)?;
1691 }
1692 let dotenv = Dotenv::load(env, profile.as_deref())?;
1695 let lookup = |k: &str| {
1701 env(k).or_else(|| {
1702 dotenv
1703 .values
1704 .get(k)
1705 .filter(|v| !v.is_empty())
1706 .map(String::as_str)
1707 .map(str::to_string)
1708 })
1709 };
1710 let lookup: EnvFn<'_> = &lookup;
1711
1712 let base_path = match explicit {
1713 Some(p) => Some(p.to_path_buf()),
1714 None => config_path(env).filter(|p| p.exists()),
1715 };
1716 let mut hooks_path = base_path.clone();
1718 let mut value = match &base_path {
1719 Some(p) => {
1720 let mut parsed = read_toml(p)?;
1721 crate::interpolate::in_value(&mut parsed, p, lookup)?;
1722 parsed
1723 }
1724 None => toml::Value::try_from(Config::default())
1725 .map_err(|e| Error::Config(e.to_string()))?,
1726 };
1727 if let Some(name) = &profile {
1728 if let Some(dir) = profile_dir(env, name) {
1729 let overlay = dir.join("config.toml");
1730 if overlay.exists() {
1731 let mut over = read_toml(&overlay)?;
1732 crate::interpolate::in_value(&mut over, &overlay, lookup)?;
1735 if over.get("hooks").is_some() {
1736 hooks_path = Some(overlay.clone());
1737 }
1738 merge_toml(&mut value, over);
1739 }
1740 }
1741 }
1742 let mut cfg: Config = value
1743 .try_into()
1744 .map_err(|e: toml::de::Error| Error::Parse {
1745 path: base_path.unwrap_or_else(|| PathBuf::from("<defaults>")),
1746 message: e.to_string(),
1747 })?;
1748 cfg.profile = profile;
1749 cfg.apply_env(lookup);
1750 cfg.dotenv = dotenv;
1751 cfg.validate_routes()?;
1754 cfg.context.validate()?;
1755 cfg.validate_bots()?;
1758 crate::hooks::validate(&cfg.hooks).map_err(|message| Error::Parse {
1759 path: hooks_path.unwrap_or_else(|| PathBuf::from("<defaults>")),
1760 message,
1761 })?;
1762 Ok(cfg)
1763 }
1764
1765 pub fn profile_name(&self) -> &str {
1767 self.profile.as_deref().unwrap_or("default")
1768 }
1769
1770 pub fn state_dir(&self, env: EnvFn) -> Result<PathBuf> {
1772 state_dir_for(env, self.profile.as_deref())
1773 .ok_or_else(|| Error::Config("cannot determine state dir: HOME is not set".into()))
1774 }
1775
1776 pub fn plugins_dirs(&self, env: EnvFn) -> Vec<PathBuf> {
1780 let mut out = Vec::new();
1781 if let Some(name) = &self.profile {
1782 if let Some(dir) = profile_dir(env, name) {
1783 out.push(dir.join("plugins"));
1784 }
1785 }
1786 let shared = match &self.plugins.dir {
1787 Some(p) => expand_tilde(p, env),
1788 None => match config_dir(env) {
1789 Some(d) => d.join("plugins"),
1790 None => return out,
1791 },
1792 };
1793 if !out.contains(&shared) {
1794 out.push(shared);
1795 }
1796 out
1797 }
1798
1799 pub fn from_file(path: &Path) -> Result<Config> {
1800 let text = std::fs::read_to_string(path).map_err(|e| Error::io(path, e))?;
1801 Self::from_toml_str(&text).map_err(|message| Error::Parse {
1802 path: path.to_path_buf(),
1803 message,
1804 })
1805 }
1806
1807 pub fn from_toml_str(text: &str) -> std::result::Result<Config, String> {
1808 toml::from_str(text).map_err(|e| e.to_string())
1809 }
1810
1811 pub fn apply_env(&mut self, env: EnvFn) {
1817 if let Some(v) = env("ECLIPSE_BASE_URL") {
1818 self.provider.base_url = v;
1819 }
1820 if let Some(v) = env("ECLIPSE_MODEL") {
1821 self.provider.model = v;
1822 }
1823 if self.provider.declares_connection() {
1826 apply_key_env(&mut self.provider, env, env("ECLIPSE_API_KEY"));
1827 }
1828 for route in &mut self.provider.route {
1829 apply_key_env(&mut route.config, env, None);
1830 }
1831 }
1832
1833 pub fn to_toml_redacted(&self) -> Result<String> {
1839 let mut value = toml::Value::try_from(self).map_err(|e| Error::Config(e.to_string()))?;
1840 redact(&mut value);
1841 toml::to_string_pretty(&value).map_err(|e| Error::Config(e.to_string()))
1842 }
1843
1844 pub fn require_provider(&self) -> Result<()> {
1846 self.chain().map(|_| ())
1847 }
1848
1849 pub fn declared_routes(&self) -> Vec<NamedRoute> {
1854 let mut out = Vec::new();
1855 if self.provider.route.is_empty() || self.provider.declares_connection() {
1856 out.push(NamedRoute::new(DEFAULT_ROUTE, &self.provider));
1857 }
1858 out.extend(self.provider.route.iter().map(|r| {
1859 NamedRoute::new(&r.name, &r.config).with_flare_shape(r.max_parallel, r.group.clone())
1860 }));
1861 out
1862 }
1863
1864 pub fn route_names(&self) -> String {
1866 let names: Vec<String> = self.declared_routes().into_iter().map(|r| r.name).collect();
1867 if names.is_empty() {
1868 "none".to_string()
1869 } else {
1870 names.join(", ")
1871 }
1872 }
1873
1874 pub fn validate_routes(&self) -> Result<()> {
1881 let p = &self.provider;
1882 let mut seen: Vec<&str> = Vec::new();
1883 for (i, r) in p.route.iter().enumerate() {
1884 let name = r.name.trim();
1885 if name.is_empty() {
1886 return Err(Error::Config(format!(
1887 "provider.route #{} has no name; every [[provider.route]] needs `name = \"...\"`",
1888 i + 1
1889 )));
1890 }
1891 if seen.contains(&name) {
1892 return Err(Error::Config(format!(
1893 "two routes are named `{name}`; route names must be unique"
1894 )));
1895 }
1896 seen.push(name);
1897 if name == DEFAULT_ROUTE && p.declares_connection() {
1898 return Err(Error::Config(format!(
1899 "a route is named `{DEFAULT_ROUTE}`, but `[provider]` is also set and is the \
1900 route of that name; rename the route, or move its settings out of [provider]"
1901 )));
1902 }
1903 if r.config.fallback.is_some()
1904 || r.config.aux.is_some()
1905 || r.config.delegate.is_some()
1906 || !r.config.route.is_empty()
1907 {
1908 return Err(Error::Config(format!(
1909 "route `{name}` has its own `fallback`, `aux`, `delegate` or `route`; those \
1910 belong directly under [provider], not inside a route"
1911 )));
1912 }
1913 if r.config.base_url.trim().is_empty() {
1914 return Err(Error::Config(format!(
1915 "route `{name}` has no base_url; a route is a complete provider \
1916 configuration and does not inherit from [provider]"
1917 )));
1918 }
1919 if r.config.model.trim().is_empty() {
1920 return Err(Error::Config(format!(
1921 "route `{name}` has no model; a route is a complete provider \
1922 configuration and does not inherit from [provider]"
1923 )));
1924 }
1925 }
1926 if let Some(fallback) = &p.fallback {
1927 if fallback.is_empty() {
1928 return Err(Error::Config(
1929 "provider.fallback is empty; name the routes to try in order, or remove the \
1930 key to use `default` alone"
1931 .into(),
1932 ));
1933 }
1934 let known: Vec<String> = self.declared_routes().into_iter().map(|r| r.name).collect();
1935 let mut listed: Vec<&str> = Vec::new();
1936 for name in fallback {
1937 if !known.contains(name) {
1938 return Err(Error::Config(format!(
1939 "provider.fallback names `{name}`, which is not a route. Routes that \
1940 exist: {}",
1941 self.route_names()
1942 )));
1943 }
1944 if listed.contains(&name.as_str()) {
1945 return Err(Error::Config(format!(
1946 "provider.fallback lists `{name}` twice; each route is tried at most \
1947 once per run"
1948 )));
1949 }
1950 listed.push(name);
1951 }
1952 if p.declares_connection() && !listed.contains(&DEFAULT_ROUTE) {
1957 return Err(Error::Config(
1958 "`[provider]` sets a connection, but provider.fallback is the whole chain \
1959 and does not list `default`, so that endpoint would never be called. Put \
1960 `default` first in `fallback`, or move the connection keys into a route \
1961 and leave `[provider]` to `fallback` alone"
1962 .into(),
1963 ));
1964 }
1965 }
1966 if let Some(aux) = &p.aux {
1967 if aux.trim().is_empty() {
1968 return Err(Error::Config(
1969 "provider.aux is empty; name the route that does housekeeping, or remove \
1970 the key to use the route the run is on"
1971 .into(),
1972 ));
1973 }
1974 if !self.declared_routes().iter().any(|r| &r.name == aux) {
1975 return Err(Error::Config(format!(
1976 "provider.aux names `{aux}`, which is not a route. Routes that exist: {}",
1977 self.route_names()
1978 )));
1979 }
1980 }
1981 if let Some(delegate) = &p.delegate {
1982 if delegate.trim().is_empty() {
1983 return Err(Error::Config(
1984 "provider.delegate is empty; name the route subagents run on, or remove \
1985 the key to use the route the run is on"
1986 .into(),
1987 ));
1988 }
1989 if !self.declared_routes().iter().any(|r| &r.name == delegate) {
1990 return Err(Error::Config(format!(
1991 "provider.delegate names `{delegate}`, which is not a route. Routes that \
1992 exist: {}",
1993 self.route_names()
1994 )));
1995 }
1996 }
1997 let vision_route = self.vision.route.trim();
2001 if !vision_route.is_empty()
2002 && !self
2003 .declared_routes()
2004 .iter()
2005 .any(|r| r.name == vision_route)
2006 {
2007 return Err(Error::Config(format!(
2008 "vision.route names `{vision_route}`, which is not a route. Routes that exist: {}",
2009 self.route_names()
2010 )));
2011 }
2012 Ok(())
2013 }
2014
2015 pub fn pin_route(&mut self, flag: Option<&str>, env: EnvFn) -> Result<()> {
2021 let wanted = match flag {
2022 Some(name) if name.trim().is_empty() => {
2023 return Err(Error::Config(
2024 "--route needs a route name; `eclipse config show` lists them".into(),
2025 ))
2026 }
2027 Some(name) => Some(name.trim().to_string()),
2028 None => env("ECLIPSE_ROUTE")
2029 .or_else(|| self.dotenv.values.get("ECLIPSE_ROUTE").cloned())
2030 .map(|v| v.trim().to_string())
2031 .filter(|v| !v.is_empty()),
2032 };
2033 if let Some(name) = &wanted {
2034 if !self.declared_routes().iter().any(|r| &r.name == name) {
2035 return Err(self.unknown_route(name));
2036 }
2037 }
2038 self.route_pin = wanted;
2039 Ok(())
2040 }
2041
2042 fn unknown_route(&self, name: &str) -> Error {
2043 Error::Config(format!(
2044 "unknown route `{name}`. Routes that exist: {}",
2045 self.route_names()
2046 ))
2047 }
2048
2049 pub fn chain(&self) -> Result<Chain> {
2055 self.validate_routes()?;
2056 let all = self.declared_routes();
2057 let find = |name: &str| all.iter().find(|r| r.name == name).cloned();
2058 let (routes, source) = if let Some(pin) = &self.route_pin {
2059 let route = find(pin).ok_or_else(|| self.unknown_route(pin))?;
2060 (vec![route], ChainSource::Pinned)
2061 } else if let Some(fallback) = &self.provider.fallback {
2062 let routes = fallback.iter().filter_map(|n| find(n)).collect();
2064 (routes, ChainSource::Fallback)
2065 } else if self.provider.declares_connection() || self.provider.route.is_empty() {
2066 (
2067 vec![NamedRoute::new(DEFAULT_ROUTE, &self.provider)],
2068 ChainSource::Default,
2069 )
2070 } else {
2071 return Err(Error::Config(format!(
2072 "routes are declared but nothing says which to use: set `[provider] fallback = \
2073 [...]`, or pass --route NAME. Routes that exist: {}",
2074 self.route_names()
2075 )));
2076 };
2077 for route in &routes {
2078 route.require_endpoint(source)?;
2079 }
2080 let pinned = source == ChainSource::Pinned;
2085 let only = routes.first().cloned();
2086 let (aux, delegate) = if pinned {
2087 (only.clone(), only)
2088 } else {
2089 (
2090 self.provider.aux.as_deref().and_then(find),
2091 self.provider.delegate.as_deref().and_then(find),
2092 )
2093 };
2094 if let Some(aux) = &aux {
2095 aux.require_endpoint(source)?;
2096 }
2097 if let Some(delegate) = &delegate {
2098 delegate.require_endpoint(source)?;
2099 }
2100 Ok(Chain {
2101 routes,
2102 source,
2103 aux,
2104 delegate,
2105 })
2106 }
2107
2108 pub fn sessions_dir(&self, env: EnvFn) -> Result<PathBuf> {
2109 if let Some(d) = &self.sessions.dir {
2110 return Ok(expand_tilde(d, env));
2111 }
2112 Ok(self.state_dir(env)?.join("sessions"))
2113 }
2114
2115 pub fn validate_bots(&self) -> Result<()> {
2122 for name in self.bots.keys() {
2123 let ok = !name.is_empty()
2124 && name.len() <= 32
2125 && name
2126 .chars()
2127 .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-' || c == '_');
2128 if !ok {
2129 return Err(Error::Config(format!(
2130 "bots.{name}: a bot name is lowercase letters, digits, `-` and `_`, at most \
2131 32 of them — it becomes part of a session's `origin` and a URL"
2132 )));
2133 }
2134 }
2135 Ok(())
2136 }
2137
2138 pub fn bot_file(&self, env: EnvFn, path: &str) -> Option<PathBuf> {
2141 let path = expand_tilde(Path::new(path), env);
2142 if path.is_absolute() {
2143 Some(path)
2144 } else {
2145 self.context_dir(env).map(|dir| dir.join(path))
2146 }
2147 }
2148
2149 pub fn bot_memory(&self, env: EnvFn, name: &str, bot: &BotConfig) -> Option<PathBuf> {
2153 match bot.memory.as_deref().filter(|m| !m.trim().is_empty()) {
2154 Some(m) => self.bot_file(env, m),
2155 None => self
2156 .memory_dir(env)
2157 .map(|dir| dir.join("bots").join(name).join(&self.user.memory_file)),
2158 }
2159 }
2160
2161 pub fn attachments_dir(&self, env: EnvFn) -> Option<PathBuf> {
2166 if let Some(dir) = &self.attachments.dir {
2167 return Some(expand_tilde(dir, env));
2168 }
2169 self.state_dir(env).ok().map(|d| d.join("attachments"))
2170 }
2171
2172 pub fn where_am_i(&self, env: EnvFn, loaded: Option<&Path>) -> Where {
2181 let overlay = self
2182 .profile
2183 .as_deref()
2184 .filter(|name| *name != "default")
2185 .and_then(|name| profile_dir(env, name))
2186 .map(|dir| dir.join("config.toml"))
2187 .filter(|path| path.exists());
2188 Where {
2189 profile: self.profile.clone(),
2190 config: loaded.map(Path::to_path_buf).or_else(|| config_path(env)),
2191 overlay,
2192 home: home_root(env),
2193 sessions: self.sessions_dir(env).ok(),
2194 }
2195 }
2196
2197 pub fn context_dir(&self, env: EnvFn) -> Option<PathBuf> {
2200 match &self.profile {
2201 Some(name) => profile_dir(env, name),
2202 None => config_path(env)
2203 .and_then(|p| p.parent().map(Path::to_path_buf))
2204 .or_else(|| config_dir(env)),
2205 }
2206 }
2207
2208 pub fn scripts_dir(&self, env: EnvFn) -> Option<PathBuf> {
2217 let dir = self.context_dir(env)?.join("scripts");
2218 if dir.is_absolute() {
2219 return Some(dir);
2220 }
2221 std::env::current_dir().ok().map(|cwd| cwd.join(dir))
2222 }
2223
2224 pub fn memory_dir(&self, env: EnvFn) -> Option<PathBuf> {
2232 self.context_dir(env).map(|d| d.join("memory"))
2233 }
2234
2235 pub fn global_context_dir(&self, env: EnvFn) -> Option<PathBuf> {
2237 config_path(env)
2238 .and_then(|p| p.parent().map(Path::to_path_buf))
2239 .or_else(|| config_dir(env))
2240 }
2241
2242 pub fn home(&self, env: EnvFn) -> Option<PathBuf> {
2243 home_dir(env)
2244 }
2245
2246 pub fn workspace_root(&self, env: EnvFn) -> PathBuf {
2247 match &self.tools.workspace_root {
2248 Some(p) => expand_tilde(p, env),
2249 None => std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
2250 }
2251 }
2252}
2253
2254#[derive(Debug, Clone, Default, PartialEq, Eq)]
2260pub struct Where {
2261 pub profile: Option<String>,
2263 pub config: Option<PathBuf>,
2266 pub overlay: Option<PathBuf>,
2268 pub home: Option<PathBuf>,
2270 pub sessions: Option<PathBuf>,
2272}
2273
2274impl Where {
2275 pub fn name(&self) -> &str {
2277 self.profile.as_deref().unwrap_or("default")
2278 }
2279
2280 pub fn is_default(&self) -> bool {
2283 matches!(self.profile.as_deref(), None | Some("default"))
2284 }
2285}
2286
2287fn read_toml(path: &Path) -> Result<toml::Value> {
2289 let text = std::fs::read_to_string(path).map_err(|e| Error::io(path, e))?;
2290 toml::from_str::<toml::Value>(&text).map_err(|message| Error::Parse {
2291 path: path.to_path_buf(),
2292 message: message.to_string(),
2293 })
2294}
2295
2296fn merge_toml(base: &mut toml::Value, over: toml::Value) {
2298 match (base, over) {
2299 (toml::Value::Table(base), toml::Value::Table(over)) => {
2300 for (key, value) in over {
2301 match base.get_mut(&key) {
2302 Some(slot) => merge_toml(slot, value),
2303 None => {
2304 base.insert(key, value);
2305 }
2306 }
2307 }
2308 }
2309 (slot, over) => *slot = over,
2310 }
2311}
2312
2313fn redact(value: &mut toml::Value) {
2315 match value {
2316 toml::Value::Table(table) => {
2317 for (key, slot) in table.iter_mut() {
2318 if is_secret_key(key) && matches!(slot, toml::Value::String(s) if !s.is_empty()) {
2319 *slot = toml::Value::String("<redacted>".into());
2320 continue;
2321 }
2322 if is_url_key(key) {
2323 if let toml::Value::String(url) = slot {
2324 if let Some(clean) = redact_url(url) {
2325 *slot = toml::Value::String(clean);
2326 continue;
2327 }
2328 }
2329 }
2330 redact(slot);
2331 }
2332 }
2333 toml::Value::Array(items) => items.iter_mut().for_each(redact),
2334 _ => {}
2335 }
2336}
2337
2338pub(crate) fn is_secret_key(key: &str) -> bool {
2342 let k = key.to_ascii_lowercase();
2343 if k.ends_with("_env") {
2344 return false;
2345 }
2346 const COUNTS: &[&str] = &[
2349 "_tokens",
2350 "_chars",
2351 "_secs",
2352 "_ms",
2353 "_count",
2354 "_size",
2355 "_hours",
2356 "_days",
2357 "_bytes",
2358 "_iterations",
2359 "_call",
2360 ];
2361 if COUNTS.iter().any(|suffix| k.ends_with(suffix)) {
2362 return false;
2363 }
2364 k == "api_key"
2365 || k.ends_with("_key")
2366 || k.contains("token")
2367 || k.contains("secret")
2368 || k.contains("password")
2369}
2370
2371fn is_url_key(key: &str) -> bool {
2380 let k = key.to_ascii_lowercase();
2381 k.ends_with("_url") || k == "url" || k == "remote" || k == "releases"
2382}
2383
2384pub(crate) fn redact_url(text: &str) -> Option<String> {
2391 let (body, fragment) = match text.split_once('#') {
2392 Some((b, f)) => (b, Some(f)),
2393 None => (text, None),
2394 };
2395 let (before_query, query) = match body.split_once('?') {
2396 Some((b, q)) => (b, Some(q)),
2397 None => (body, None),
2398 };
2399 let mut changed = false;
2400
2401 let head = match before_query.find("://") {
2404 Some(scheme_end) => {
2405 let start = scheme_end + 3;
2406 let rest = &before_query[start..];
2407 let authority_end = rest.find('/').unwrap_or(rest.len());
2408 match rest[..authority_end].rfind('@') {
2409 Some(at) => {
2410 changed = true;
2411 format!("{}{}<redacted>{}", &before_query[..start], "", &rest[at..])
2412 }
2413 None => before_query.to_string(),
2414 }
2415 }
2416 None => before_query.to_string(),
2417 };
2418
2419 let query = query.map(|q| {
2420 let pairs: Vec<String> = q
2421 .split('&')
2422 .map(|pair| {
2423 let name = pair.split_once('=').map(|(n, _)| n).unwrap_or(pair);
2424 if !name.is_empty() && is_secret_key(name) {
2425 changed = true;
2426 format!("{name}=<redacted>")
2427 } else {
2428 pair.to_string()
2429 }
2430 })
2431 .collect();
2432 pairs.join("&")
2433 });
2434
2435 if !changed {
2436 return None;
2437 }
2438 let mut out = head;
2439 if let Some(q) = query {
2440 out.push('?');
2441 out.push_str(&q);
2442 }
2443 if let Some(f) = fragment {
2444 out.push('#');
2445 out.push_str(f);
2446 }
2447 Some(out)
2448}
2449
2450const SHIPPED_SPELLING: &[(&str, &str, &str)] = &[
2467 ("provider", "api_key", "${OPENAI_API_KEY:-}"),
2468 ("provider", "api_key_env", ""),
2469 ("provider", "profile", ""),
2470 (
2471 "provider",
2472 "reasoning_effort",
2473 crate::reasoning::SHIPPED_DEFAULT,
2474 ),
2475 ("provider", "aux", ""),
2476 ("provider", "delegate", ""),
2477 ("agent", "output_schema", ""),
2478 ("web", "auth_token", "${ECLIPSE_WEB_AUTH_TOKEN:-}"),
2479 ("web", "default_profile", ""),
2480 ("update", "remote", ""),
2481 ("update", "releases", ""),
2482 ("tools", "write_file", "ask"),
2486 ("tools", "patch", "ask"),
2487];
2488
2489fn shipped_text(spelling: &str) -> String {
2492 toml::Value::String(spelling.to_string()).to_string()
2493}
2494
2495const SECTION_ORDER: &[&str] = &[
2497 "provider",
2498 "agent",
2499 "tools",
2500 "flares",
2501 "sessions",
2502 "attachments",
2503 "context",
2504 "plugins",
2505 "cli",
2506 "web",
2507 "gateway",
2508 "update",
2509 "hooks",
2510 "user",
2511 "skills",
2512 "vision",
2513];
2514
2515pub fn starter_config() -> Result<String> {
2539 let defaults = toml::Value::try_from(Config::default())
2540 .map_err(|e| Error::Config(format!("the default config does not serialise: {e}")))?;
2541 let mut out = String::with_capacity(8 * 1024);
2542 out.push_str("# Every setting this build reads, and nothing else.\n");
2543 out.push_str("# What one does, and what it accepts: `eclipse config docs`.\n");
2544 out.push_str("# A commented key is not in use; an empty value means the same.\n");
2545 out.push_str(&format!("config_version = {CONFIG_VERSION}\n"));
2546 for section in SECTION_ORDER {
2547 out.push_str(&format!("\n[{section}]\n"));
2548 let table = defaults.get(*section).and_then(toml::Value::as_table);
2549 let mut lines: Vec<(String, String)> = Vec::new();
2550 let mut nested: Vec<&str> = Vec::new();
2551 if let Some(table) = table {
2552 for (key, value) in table {
2553 match value {
2554 toml::Value::Table(_) => nested.push(key.as_str()),
2555 other => {
2556 let shipped = SHIPPED_SPELLING
2557 .iter()
2558 .find(|(s, k, _)| s == section && k == key)
2559 .map(|(_, _, spelling)| shipped_text(spelling));
2560 lines.push((key.clone(), shipped.unwrap_or_else(|| other.to_string())));
2561 }
2562 }
2563 }
2564 }
2565 for (abs_section, key, _) in settings::ABSENT_BY_DEFAULT {
2568 if abs_section == section && !lines.iter().any(|(k, _)| k == key) {
2569 let shipped = SHIPPED_SPELLING
2570 .iter()
2571 .find(|(s, k, _)| s == section && k == key)
2572 .map(|(_, _, spelling)| shipped_text(spelling));
2573 lines.push(((*key).to_string(), shipped.unwrap_or_default()));
2574 }
2575 }
2576 lines.sort();
2577 for (key, text) in lines {
2578 if text.is_empty() {
2579 out.push_str(&format!("# {key} =\n"));
2580 } else {
2581 out.push_str(&format!("{key} = {text}\n"));
2582 }
2583 }
2584 nested.sort();
2588 for key in nested {
2589 let Some(sub) = table.and_then(|t| t.get(key)) else {
2590 continue;
2591 };
2592 let mut wrapped = toml::map::Map::new();
2593 wrapped.insert(key.to_string(), sub.clone());
2594 if let Ok(text) = toml::to_string(&toml::Value::Table(wrapped)) {
2595 out.push('\n');
2596 out.push_str(&text);
2597 }
2598 }
2599 if *section == "hooks" {
2604 let default_hooks = Config::default().hooks;
2605 for name in &default_hooks.order {
2606 if default_hooks.settings.contains_key(name) {
2607 continue;
2608 }
2609 let Some(info) = crate::hooks::SHIPPED.iter().find(|h| h.name == name) else {
2610 continue;
2611 };
2612 out.push_str(&format!("\n[hooks.{name}]\n"));
2613 let mut keys = info.settings.to_vec();
2614 keys.sort_unstable();
2615 for key in keys {
2616 out.push_str(&format!("# {key} =\n"));
2617 }
2618 }
2619 }
2620 }
2621 Ok(out)
2622}
2623
2624pub const ENV_TEMPLATE: &[&str] = &[
2634 "ECLIPSE_BASE_URL",
2635 "ECLIPSE_MODEL",
2636 "ECLIPSE_API_KEY",
2637 "ECLIPSE_REASONING_EFFORT",
2638 "ECLIPSE_ROUTE",
2639 "OPENAI_API_KEY",
2640 "ECLIPSE_WEB_AUTH_TOKEN",
2641 "ECLIPSE_WEB_USER",
2642 "ECLIPSE_WEB_PASSWORD_HASH",
2643];
2644
2645pub const ENV_ABOUT: &[(&str, &str)] = &[
2651 ("ECLIPSE_BASE_URL", "The provider's base URL, up to and including the version: it beats `[provider] base_url` for this process only"),
2652 ("ECLIPSE_MODEL", "The model name to ask for, beating `[provider] model`; the same as `--model`"),
2653 ("ECLIPSE_API_KEY", "The provider's key, resolved by `api_key = \"${ECLIPSE_API_KEY}\"`; never put the key itself in `config.toml`"),
2654 ("ECLIPSE_REASONING_EFFORT", "The reasoning level for this process: none, minimal, low, medium, high, xhigh, max"),
2655 ("ECLIPSE_ROUTE", "Pin one named route and never fall back from it, the same as `--route`"),
2656 ("OPENAI_API_KEY", "The variable the shipped `provider.api_key` line refers to; any name works, this one is the convention"),
2657 ("ECLIPSE_WEB_AUTH_TOKEN", "The dashboard's bearer token, generated by `config init`; the dashboard refuses to start without it"),
2658 ("ECLIPSE_WEB_USER", "The dashboard's sign-in name, when it asks for a name and a password instead of the token"),
2659 ("ECLIPSE_WEB_PASSWORD_HASH", "That password, as `eclipse web passwd` writes it: `pbkdf2-sha256$<iterations>$<salt>$<digest>`"),
2660 ("ECLIPSE_HOME", "The one directory everything lives in (`~/.eclipse` otherwise). Read from the shell, never from this file"),
2661 ("ECLIPSE_CONFIG", "The config file to read (`<home>/config.toml` otherwise). Read from the shell, never from this file"),
2662 ("ECLIPSE_PROFILE", "The profile to load, the same as `--profile`. Read from the shell, never from this file"),
2663 ("ECLIPSE_BIN", "The `eclipse` binary a spawned job should use; this tool sets it, and only a test overrides it"),
2664 ("ECLIPSE_ARGS", "The JSON arguments of the tool call a plugin or MCP server is being asked about; set by this tool"),
2665 ("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"),
2666 ("ECLIPSE_TOOL", "The tool name a bridged call is for; set by this tool"),
2667 ("ECLIPSE_TOOL_SOCKET", "Where a script or plugin calls back into the running agent; set by this tool"),
2668 ("ECLIPSE_WORKSPACE", "The workspace root, given to a child process; set by this tool from `[tools] workspace_root`"),
2669 ("ECLIPSE_PLUGIN_DIR", "The plugin directory, given to a child process; set by this tool"),
2670 ("ECLIPSE_SCRIPTS_DIR", "The scripts directory, given to a child process; set by this tool"),
2671];
2672
2673pub fn env_about(name: &str) -> &'static str {
2675 ENV_ABOUT
2676 .iter()
2677 .find(|(n, _)| *n == name)
2678 .map(|(_, about)| *about)
2679 .unwrap_or("")
2680}
2681
2682pub const ENV_SHELL_ONLY: &[&str] = &["ECLIPSE_HOME", "ECLIPSE_CONFIG", "ECLIPSE_PROFILE"];
2685
2686pub const ENV_INTERNAL: &[&str] = &[
2689 "ECLIPSE_BIN",
2690 "ECLIPSE_ARGS",
2691 "ECLIPSE_ARGS_BYTES",
2692 "ECLIPSE_TOOL",
2693 "ECLIPSE_TOOL_SOCKET",
2694 "ECLIPSE_WORKSPACE",
2695 "ECLIPSE_PLUGIN_DIR",
2696 "ECLIPSE_SCRIPTS_DIR",
2697];
2698
2699pub fn starter_env(token: &str) -> String {
2704 let mut out = String::with_capacity(1024);
2705 out.push_str("# Secrets and per-host overrides. The shell beats this file. Mode 0600.\n");
2706 out.push_str("# Every variable this build reads; an empty value is not set. `eclipse config docs` explains each.\n");
2707 for name in ENV_TEMPLATE {
2708 if *name == "ECLIPSE_WEB_AUTH_TOKEN" {
2709 out.push_str(&format!("{name}={token}\n"));
2710 } else {
2711 out.push_str(&format!("{name}=\n"));
2712 }
2713 }
2714 out
2715}
2716
2717pub const STARTER_PROFILE_CONFIG: &str = r#"# A profile overlay: keys here replace the base config's, and a key left out follows it.
2721# Examples are commented out on purpose — an empty value here *replaces* the base value.
2722
2723[provider]
2724# base_url = "http://127.0.0.1:8080/v1"
2725# model = "qwen3-coder:30b"
2726# profile = "llamacpp"
2727
2728[tools]
2729# shell = "ask"
2730"#;
2731
2732#[derive(Debug, Clone, PartialEq, Eq)]
2734pub struct InitReport {
2735 pub config: PathBuf,
2736 pub dotenv: PathBuf,
2737 pub dotenv_written: bool,
2740}
2741
2742pub fn write_starter_config(path: &Path, force: bool, env: EnvFn) -> Result<InitReport> {
2755 if path.exists() && !force {
2756 return Err(Error::Config(format!(
2757 "{} already exists (use --force to overwrite)",
2758 path.display()
2759 )));
2760 }
2761 let dir = path.parent().unwrap_or(Path::new("."));
2762 std::fs::create_dir_all(dir).map_err(|e| Error::io(dir, e))?;
2763 write_private(path, &starter_config()?)?;
2764
2765 let secrets_dir = config_dir(env).unwrap_or_else(|| dir.to_path_buf());
2766 std::fs::create_dir_all(&secrets_dir).map_err(|e| Error::io(&secrets_dir, e))?;
2767 let dotenv = secrets_dir.join(".env");
2768 let mut dotenv_written = false;
2769 if !dotenv.exists() {
2770 let token = crate::token::generate()?;
2771 write_private(&dotenv, &starter_env(&token))?;
2772 dotenv_written = true;
2773 }
2774 let _ = migrate::write_baseline(path);
2778 Ok(InitReport {
2779 config: path.to_path_buf(),
2780 dotenv,
2781 dotenv_written,
2782 })
2783}
2784
2785pub fn toml_value(text: &str, section: &str, key: &str) -> Option<String> {
2788 let mut in_section = false;
2789 for line in text.lines() {
2790 let trimmed = line.trim();
2791 if let Some(name) = section_header(trimmed) {
2792 in_section = name == section;
2793 continue;
2794 }
2795 if !in_section || trimmed.starts_with('#') {
2796 continue;
2797 }
2798 if let Some((k, v)) = key_value(trimmed) {
2799 if k == key {
2800 return Some(v);
2801 }
2802 }
2803 }
2804 None
2805}
2806
2807pub fn toml_set_string(text: &str, section: &str, key: &str, value: &str) -> String {
2815 toml_set_value(text, section, key, &format!("\"{}\"", escape_toml(value)))
2816}
2817
2818pub fn toml_set_value(text: &str, section: &str, key: &str, value: &str) -> String {
2821 place_line(text, section, key, &format!("{key} = {value}"))
2822}
2823
2824struct McpSpan {
2837 name: Option<String>,
2838 start: usize,
2839 end: usize,
2840}
2841
2842fn is_table_header(trimmed: &str) -> bool {
2843 trimmed.starts_with('[')
2844}
2845
2846fn mcp_spans(lines: &[String]) -> Vec<McpSpan> {
2847 let mut spans: Vec<McpSpan> = Vec::new();
2848 let mut open: Option<usize> = None;
2849 let mut closed_by_header = true;
2850 for (i, line) in lines.iter().enumerate() {
2851 let trimmed = line.trim();
2852 if open.is_some() && is_table_header(trimmed) {
2853 if let Some(start) = open.take() {
2854 spans.push(McpSpan {
2855 name: None,
2856 start,
2857 end: i,
2858 });
2859 closed_by_header = true;
2860 }
2861 }
2862 if trimmed == "[[mcp]]" {
2863 open = Some(i);
2864 }
2865 }
2866 if let Some(start) = open {
2867 spans.push(McpSpan {
2868 name: None,
2869 start,
2870 end: lines.len(),
2871 });
2872 closed_by_header = false;
2873 }
2874 let count = spans.len();
2880 for (i, span) in spans.iter_mut().enumerate() {
2881 let at_eof = i + 1 == count && !closed_by_header;
2882 while span.end > span.start + 1 {
2883 let tail = lines[span.end - 1].trim();
2884 let belongs_to_next = !at_eof && (tail.is_empty() || tail.starts_with('#'));
2885 if tail.is_empty() || belongs_to_next {
2886 span.end -= 1;
2887 } else {
2888 break;
2889 }
2890 }
2891 }
2892 for span in &mut spans {
2893 let body = lines[span.start + 1..span.end].join("\n");
2894 span.name = toml::from_str::<crate::mcp::Spec>(&body)
2895 .ok()
2896 .map(|spec| spec.name);
2897 }
2898 spans
2899}
2900
2901fn tidy_blanks(lines: Vec<String>) -> Vec<String> {
2904 let mut end = lines.len();
2905 while end > 0 && lines[end - 1].trim().is_empty() {
2906 end -= 1;
2907 }
2908 let mut out: Vec<String> = Vec::with_capacity(end);
2909 let mut blanks = 0;
2910 for line in &lines[..end] {
2911 if line.trim().is_empty() {
2912 blanks += 1;
2913 if blanks > 1 {
2914 continue;
2915 }
2916 } else {
2917 blanks = 0;
2918 }
2919 out.push(line.clone());
2920 }
2921 out
2922}
2923
2924fn render_mcp_entry(entry: &crate::mcp::Spec) -> String {
2928 let quote = |s: &str| toml::Value::String(s.to_string()).to_string();
2929 let mut out = String::from("[[mcp]]\n");
2930 out.push_str(&format!("name = {}\n", quote(&entry.name)));
2931 if entry.transport == crate::mcp::Transport::Http {
2932 out.push_str("transport = \"http\"\n");
2933 }
2934 if !entry.command.is_empty() {
2935 out.push_str(&format!("command = {}\n", quote(&entry.command)));
2936 }
2937 if !entry.args.is_empty() {
2938 let args: Vec<String> = entry.args.iter().map(|a| quote(a)).collect();
2939 out.push_str(&format!("args = [{}]\n", args.join(", ")));
2940 }
2941 if let Some(url) = &entry.url {
2942 out.push_str(&format!("url = {}\n", quote(url)));
2943 }
2944 if let Some(var) = &entry.token_env {
2945 out.push_str(&format!("token_env = {}\n", quote(var)));
2946 }
2947 if entry.cwd != crate::plugins::Cwd::default() {
2948 let cwd = match entry.cwd {
2949 crate::plugins::Cwd::Workspace => "workspace",
2950 crate::plugins::Cwd::Plugin => "plugin",
2951 };
2952 out.push_str(&format!("cwd = \"{cwd}\"\n"));
2953 }
2954 if let Some(secs) = entry.timeout_secs {
2955 out.push_str(&format!("timeout_secs = {secs}\n"));
2956 }
2957 if entry.policy != Policy::Ask {
2958 let policy = match entry.policy {
2959 Policy::Deny => "deny",
2960 Policy::Ask => "ask",
2961 Policy::Allow => "allow",
2962 };
2963 out.push_str(&format!("policy = \"{policy}\"\n"));
2964 }
2965 if !entry.policies.is_empty() {
2966 let pairs: Vec<String> = entry
2967 .policies
2968 .iter()
2969 .map(|(tool, policy)| {
2970 let policy = match policy {
2971 Policy::Deny => "deny",
2972 Policy::Ask => "ask",
2973 Policy::Allow => "allow",
2974 };
2975 format!("{tool} = \"{policy}\"")
2976 })
2977 .collect();
2978 out.push_str(&format!("policies = {{ {} }}\n", pairs.join(", ")));
2979 }
2980 if !entry.prefix.is_empty() {
2981 out.push_str(&format!("prefix = {}\n", quote(&entry.prefix)));
2982 }
2983 if !entry.env.is_empty() {
2984 let env: Vec<String> = entry.env.iter().map(|e| quote(e)).collect();
2985 out.push_str(&format!("env = [{}]\n", env.join(", ")));
2986 }
2987 if entry.override_builtin {
2988 out.push_str("override = true\n");
2989 }
2990 if entry.disabled {
2991 out.push_str("disabled = true\n");
2992 }
2993 out
2994}
2995
2996pub fn mcp_add(text: &str, entry: &crate::mcp::Spec) -> std::result::Result<String, String> {
2998 entry
2999 .validate()
3000 .map_err(|why| format!("that entry is not usable, so nothing was saved: {why}"))?;
3001 let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
3002 let spans = mcp_spans(&lines);
3003 if let Some(existing) = spans
3004 .iter()
3005 .find(|s| s.name.as_deref() == Some(&entry.name))
3006 {
3007 return Err(format!(
3008 "`{}` is already declared at line {} — `eclipse mcp remove {}` first, or edit that entry",
3009 entry.name,
3010 existing.start + 1,
3011 entry.name
3012 ));
3013 }
3014 let rendered = render_mcp_entry(entry);
3015 match spans.last() {
3016 Some(last) => {
3017 let at = last.end;
3018 let mut fresh: Vec<String> = Vec::new();
3019 if at > 0 && !lines[at - 1].trim().is_empty() {
3021 fresh.push(String::new());
3022 }
3023 fresh.extend(rendered.lines().map(str::to_string));
3024 lines.splice(at..at, fresh);
3025 }
3026 None => {
3027 if lines.last().is_some_and(|l| !l.trim().is_empty()) {
3028 lines.push(String::new());
3029 }
3030 lines.extend(rendered.lines().map(str::to_string));
3031 }
3032 }
3033 let out = join_lines(tidy_blanks(lines));
3034 readback_mcp(&out, &entry.name, |spec| spec == entry)
3035}
3036
3037pub fn mcp_remove(text: &str, name: &str) -> std::result::Result<String, String> {
3039 let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
3040 let spans = mcp_spans(&lines);
3041 let Some(span) = spans.iter().find(|s| s.name.as_deref() == Some(name)) else {
3042 let known: Vec<&str> = spans.iter().filter_map(|s| s.name.as_deref()).collect();
3043 return Err(if known.is_empty() {
3044 format!("no `[[mcp]]` entry for `{name}` in this file")
3045 } else {
3046 format!(
3047 "no `[[mcp]]` entry for `{name}`; this file declares {}",
3048 known.join(", ")
3049 )
3050 });
3051 };
3052 let mut start = span.start;
3055 while start > 0 && lines[start - 1].trim_start().starts_with('#') {
3056 start -= 1;
3057 }
3058 let mut end = span.end;
3061 if end < lines.len() && lines[end].trim().is_empty() {
3062 end += 1;
3063 }
3064 lines.drain(start..end);
3065 readback_mcp_absent(&join_lines(tidy_blanks(lines)), name)
3066}
3067
3068pub fn mcp_set_disabled(
3070 text: &str,
3071 name: &str,
3072 disabled: bool,
3073) -> std::result::Result<String, String> {
3074 let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
3075 let spans = mcp_spans(&lines);
3076 let Some(span) = spans.iter().find(|s| s.name.as_deref() == Some(name)) else {
3077 return Err(format!("no `[[mcp]]` entry for `{name}` in this file"));
3078 };
3079 let line = if disabled {
3080 "disabled = true".to_string()
3081 } else {
3082 "disabled = false".to_string()
3085 };
3086 let body = span.start + 1..span.end;
3087 match lines[body.clone()].iter().position(|l| {
3088 l.trim_start()
3089 .strip_prefix("disabled")
3090 .is_some_and(|rest| rest.trim_start().starts_with('='))
3091 }) {
3092 Some(offset) => lines[span.start + 1 + offset] = line,
3093 None => lines.insert(span.end, line),
3094 }
3095 readback_mcp(&join_lines(lines), name, |spec| spec.disabled == disabled)
3096}
3097
3098pub fn mcp_update(
3107 text: &str,
3108 name: &str,
3109 change: impl FnOnce(&mut crate::mcp::Spec),
3110) -> std::result::Result<String, String> {
3111 let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
3112 let spans = mcp_spans(&lines);
3113 let Some(span) = spans.iter().find(|s| s.name.as_deref() == Some(name)) else {
3114 let known: Vec<&str> = spans.iter().filter_map(|s| s.name.as_deref()).collect();
3115 return Err(if known.is_empty() {
3116 format!("no `[[mcp]]` entry for `{name}` in this file")
3117 } else {
3118 format!(
3119 "no `[[mcp]]` entry for `{name}`; this file declares {}",
3120 known.join(", ")
3121 )
3122 });
3123 };
3124 let body = lines[span.start + 1..span.end].join("\n");
3125 let before: crate::mcp::Spec = toml::from_str(&body).map_err(|e| {
3126 format!(
3127 "the entry for `{name}` at line {} does not read as it stands, so nothing was saved: {}",
3128 span.start + 1,
3129 crate::config::settings::one_line(&e.to_string())
3130 )
3131 })?;
3132 let mut after = before.clone();
3133 change(&mut after);
3134 if after.name != name {
3135 return Err(format!(
3136 "an edit does not rename: `{name}` stays `{name}` — remove the entry and add the new \
3137 name instead"
3138 ));
3139 }
3140 after
3141 .validate()
3142 .map_err(|why| format!("that entry is not usable, so nothing was saved: {why}"))?;
3143 let rendered = |spec: &crate::mcp::Spec| -> BTreeMap<String, String> {
3144 render_mcp_entry(spec)
3145 .lines()
3146 .skip(1) .filter_map(|line| key_of(line).map(|key| (key, line.to_string())))
3148 .collect()
3149 };
3150 let (old, new) = (rendered(&before), rendered(&after));
3151 let (mut start, mut end) = (span.start + 1, span.end);
3152 let block: Vec<String> = lines[start..end].to_vec();
3155 let mut rebuilt: Vec<String> = Vec::new();
3156 let mut seen: Vec<String> = Vec::new();
3157 let mut i = 0;
3158 while i < block.len() {
3159 let line = &block[i];
3160 let trimmed = line.trim();
3161 if trimmed.is_empty() || trimmed.starts_with('#') {
3162 rebuilt.push(line.clone());
3163 i += 1;
3164 continue;
3165 }
3166 let first = i;
3167 let mut depth = bracket_depth(line);
3168 i += 1;
3169 while depth > 0 && i < block.len() {
3170 depth += bracket_depth(&block[i]);
3171 i += 1;
3172 }
3173 match key_of(&block[first]) {
3174 Some(key) => {
3175 seen.push(key.clone());
3176 match (old.get(&key), new.get(&key)) {
3177 (Some(was), Some(is)) if was == is => {
3179 rebuilt.extend(block[first..i].iter().cloned())
3180 }
3181 (_, Some(is)) => rebuilt.push(is.clone()),
3182 (_, None) => {}
3184 }
3185 }
3186 None => rebuilt.extend(block[first..i].iter().cloned()),
3188 }
3189 }
3190 for (key, line) in &new {
3191 if !seen.contains(key) {
3192 rebuilt.push(line.clone());
3193 }
3194 }
3195 start = start.min(lines.len());
3196 end = end.min(lines.len());
3197 lines.splice(start..end, rebuilt);
3198 let out = join_lines(lines);
3199 readback_mcp(&out, name, |spec| spec == &after)
3200}
3201
3202fn key_of(line: &str) -> Option<String> {
3204 let trimmed = line.trim();
3205 if trimmed.starts_with('#') {
3206 return None;
3207 }
3208 let (key, _) = trimmed.split_once('=')?;
3209 let key = key.trim();
3210 let plain = !key.is_empty()
3211 && !key.contains(char::is_whitespace)
3212 && key
3213 .chars()
3214 .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-');
3215 plain.then(|| key.to_string())
3216}
3217
3218fn bracket_depth(line: &str) -> i32 {
3221 let mut depth = 0;
3222 let mut quote: Option<char> = None;
3223 let mut escaped = false;
3224 for c in line.chars() {
3225 if let Some(q) = quote {
3226 if escaped {
3227 escaped = false;
3228 } else if c == '\\' {
3229 escaped = true;
3230 } else if c == q {
3231 quote = None;
3232 }
3233 continue;
3234 }
3235 match c {
3236 '"' | '\'' => quote = Some(c),
3237 '[' | '{' => depth += 1,
3238 ']' | '}' => depth -= 1,
3239 '#' => break, _ => {}
3241 }
3242 }
3243 depth
3244}
3245
3246fn readback_mcp(
3249 text: &str,
3250 name: &str,
3251 ok: impl Fn(&crate::mcp::Spec) -> bool,
3252) -> std::result::Result<String, String> {
3253 let cfg = parse_text(text).map_err(|e| {
3254 format!(
3255 "that would not load, so nothing was saved: {}",
3256 settings::one_line(&e.to_string())
3257 )
3258 })?;
3259 match cfg.mcp.iter().find(|s| s.name == name) {
3260 Some(spec) if ok(spec) => Ok(text.to_string()),
3261 Some(_) => {
3262 Err("the file would not read that entry back as written; nothing was saved".into())
3263 }
3264 None => Err(format!(
3265 "the edit lost `{name}` on the way back in; nothing was saved"
3266 )),
3267 }
3268}
3269
3270fn readback_mcp_absent(text: &str, name: &str) -> std::result::Result<String, String> {
3271 let cfg = parse_text(text).map_err(|e| {
3272 format!(
3273 "that would not load, so nothing was saved: {}",
3274 settings::one_line(&e.to_string())
3275 )
3276 })?;
3277 if cfg.mcp.iter().any(|s| s.name == name) {
3278 return Err(format!("`{name}` survived the removal; nothing was saved"));
3279 }
3280 Ok(text.to_string())
3281}
3282
3283fn place_line(text: &str, section: &str, key: &str, replacement: &str) -> String {
3289 let quoted = replacement.to_string();
3290 let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
3291 let mut in_section = false;
3292 let mut header_at: Option<usize> = None;
3293 let mut commented_at: Option<usize> = None;
3294 for (i, line) in lines.iter().enumerate() {
3295 let trimmed = line.trim();
3296 if let Some(name) = section_header(trimmed) {
3297 in_section = name == section;
3298 if in_section && header_at.is_none() {
3299 header_at = Some(i);
3300 }
3301 continue;
3302 }
3303 if !in_section {
3304 continue;
3305 }
3306 if let Some((k, _)) = key_value(trimmed) {
3307 if k == key {
3308 lines[i] = quoted;
3309 return join_lines(lines);
3310 }
3311 } else if let Some(rest) = trimmed.strip_prefix('#') {
3312 if let Some((k, _)) = key_value(rest.trim()) {
3314 if k == key && commented_at.is_none() {
3315 commented_at = Some(i);
3316 }
3317 }
3318 }
3319 }
3320 match (header_at, commented_at) {
3321 (_, Some(i)) => lines[i] = quoted,
3322 (Some(i), None) => lines.insert(i + 1, quoted),
3323 (None, None) => {
3324 lines.push(String::new());
3325 lines.push(format!("[{section}]"));
3326 lines.push(quoted);
3327 }
3328 }
3329 join_lines(lines)
3330}
3331
3332pub fn comment_in_text(text: &str, section: &str, key: &str) -> String {
3338 place_line(text, section, key, &format!("# {key} ="))
3339}
3340
3341pub fn stamp_version(text: &str, version: u32) -> std::result::Result<String, String> {
3346 let line = format!("config_version = {version}");
3347 let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
3348 if let Some(at) = lines.iter().position(|l| {
3349 l.trim_start()
3350 .strip_prefix("config_version")
3351 .is_some_and(|rest| rest.trim_start().starts_with('='))
3352 }) {
3353 lines[at] = line;
3354 } else {
3355 let first_table = lines
3360 .iter()
3361 .position(|l| section_header(l.trim()).is_some())
3362 .unwrap_or(lines.len());
3363 let mut insert_at = 0;
3364 while insert_at < first_table
3365 && (lines[insert_at].trim_start().starts_with('#')
3366 || lines[insert_at].trim().is_empty())
3367 {
3368 insert_at += 1;
3369 }
3370 lines.insert(insert_at, String::new());
3371 lines.insert(insert_at, line);
3372 while insert_at > 0 && lines[insert_at - 1].trim().is_empty() {
3373 lines.remove(insert_at - 1);
3374 insert_at -= 1;
3375 }
3376 }
3377 let out = join_lines(lines);
3378 parse_text(&out).map_err(|e| format!("stamping the version would not load: {e}"))?;
3380 Ok(out)
3381}
3382
3383pub fn toml_comment_out(text: &str, section: &str, key: &str) -> String {
3389 let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
3390 let mut in_section = false;
3391 for line in lines.iter_mut() {
3392 let trimmed = line.trim();
3393 if let Some(name) = section_header(trimmed) {
3394 in_section = name == section;
3395 continue;
3396 }
3397 if !in_section || trimmed.starts_with('#') {
3398 continue;
3399 }
3400 if let Some((k, _)) = key_value(trimmed) {
3401 if k == key {
3402 let indent: String = line.chars().take_while(|c| c.is_whitespace()).collect();
3403 *line = format!("{indent}# {trimmed}");
3404 return join_lines(lines);
3405 }
3406 }
3407 }
3408 join_lines(lines)
3409}
3410
3411pub(crate) fn section_header(trimmed: &str) -> Option<&str> {
3414 if trimmed.starts_with("[[") {
3415 return None;
3416 }
3417 let rest = trimmed.strip_prefix('[')?;
3418 let name = rest.strip_suffix(']')?;
3419 if name.contains(['[', ']']) || name.trim() != name || name.is_empty() {
3420 return None;
3421 }
3422 Some(name)
3423}
3424
3425pub(crate) fn key_value(trimmed: &str) -> Option<(&str, String)> {
3428 let (k, v) = trimmed.split_once('=')?;
3429 let k = k.trim();
3430 if k.is_empty() || k.contains([' ', '"', '\\']) {
3431 return None;
3432 }
3433 let v = v.trim();
3434 let unquoted = match v.strip_prefix('"').and_then(|r| r.strip_suffix('"')) {
3435 Some(inner) => inner.replace("\\\"", "\"").replace("\\\\", "\\"),
3436 None => v.to_string(),
3437 };
3438 Some((k, unquoted))
3439}
3440
3441fn escape_toml(value: &str) -> String {
3442 value.replace('\\', "\\\\").replace('"', "\\\"")
3443}
3444
3445fn join_lines(lines: Vec<String>) -> String {
3446 let mut out = lines.join("\n");
3447 if !out.ends_with('\n') {
3448 out.push('\n');
3449 }
3450 out
3451}
3452
3453pub fn save_config_text(path: &Path, text: &str) -> Result<()> {
3457 write_private(path, text)
3458}
3459
3460pub fn parse_text(text: &str) -> Result<Config> {
3463 let cfg: Config =
3464 toml::from_str(text).map_err(|e| Error::Config(format!("invalid config: {e}")))?;
3465 crate::hooks::validate(&cfg.hooks)
3466 .map_err(|e| Error::Config(format!("invalid config: {e}")))?;
3467 Ok(cfg)
3468}
3469
3470pub fn save_dotenv_var(path: &Path, key: &str, value: &str) -> Result<()> {
3474 if key.contains(['\n', '\r']) || value.contains(['\n', '\r']) {
3477 return Err(Error::Config(format!(
3478 "{key:?} cannot be written to {}: a line break in a key or a value would make a second \
3479 assignment",
3480 path.display()
3481 )));
3482 }
3483 let existing = match std::fs::read(path) {
3487 Ok(bytes) => String::from_utf8(bytes).map_err(|_| {
3488 Error::Config(format!(
3489 "{}: not valid UTF-8, so nothing was written — repair or remove it by hand",
3490 path.display()
3491 ))
3492 })?,
3493 Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
3494 Err(e) => {
3495 return Err(Error::Config(format!(
3496 "{}: {e}, so nothing was written — whatever else is in it is untouched",
3497 path.display()
3498 )))
3499 }
3500 };
3501 let line = format!("{key}={value}");
3502 let mut out = String::new();
3503 let mut replaced = false;
3504 for l in existing.lines() {
3505 let is_key = l
3506 .trim_start()
3507 .strip_prefix(key)
3508 .map(|rest| rest.starts_with('='))
3509 .unwrap_or(false);
3510 if is_key {
3511 out.push_str(&line);
3512 out.push('\n');
3513 replaced = true;
3514 } else {
3515 out.push_str(l);
3516 out.push('\n');
3517 }
3518 }
3519 if !replaced {
3520 if !out.is_empty() && !out.ends_with('\n') {
3521 out.push('\n');
3522 }
3523 out.push_str(&line);
3524 out.push('\n');
3525 }
3526 write_private(path, &out)?;
3527 let back = crate::dotenv::load(path)
3531 .map_err(|e| Error::Config(format!("{}: {e}", path.display())))?
3532 .into_iter()
3533 .rfind(|a| a.key == key)
3534 .map(|a| a.value);
3535 match back {
3536 Some(got) if got == value => Ok(()),
3537 Some(got) => Err(Error::Config(format!(
3538 "{}: {key} was written but reads back as {got:?}, not {value:?}; the rest of the file is \
3539 intact, so fix that line by hand",
3540 path.display()
3541 ))),
3542 None => Err(Error::Config(format!(
3543 "{}: {key} was written but the loader does not see it",
3544 path.display()
3545 ))),
3546 }
3547}
3548
3549pub fn dotenv_var(path: &Path, key: &str) -> Option<String> {
3557 crate::dotenv::load(path)
3558 .ok()?
3559 .into_iter()
3560 .rfind(|a| a.key == key)
3561 .map(|a| a.value)
3562 .filter(|value| !value.is_empty())
3563}
3564
3565pub(crate) fn write_private(path: &Path, text: &str) -> Result<()> {
3568 crate::atomic::write_file_atomically(path, text).map_err(|e| Error::io(path, e))
3573}
3574
3575#[test]
3576fn writing_the_empty_value_proves_itself_by_reading_back_as_unset() {
3577 let text = starter_config().unwrap();
3582 let without = settings::unset_in_text(&text, "agent.output_schema").expect("known key");
3583 assert_eq!(
3584 Config::from_toml_str(&without).unwrap().agent.output_schema,
3585 None
3586 );
3587 let back = settings::set_in_text(
3588 &without,
3589 "agent.output_schema",
3590 &toml::Value::String(String::new()),
3591 )
3592 .expect("an empty value can be written");
3593 assert!(back.contains("output_schema = \"\""), "{back}");
3594 assert_eq!(
3595 Config::from_toml_str(&back).unwrap().agent.output_schema,
3596 None,
3597 "and it reads as unset, which is what it means"
3598 );
3599 assert_eq!(
3600 toml_value(&back, "agent", "output_schema"),
3601 Some(String::new()),
3602 "the line is there; what it holds is nothing"
3603 );
3604}
3605
3606#[cfg(test)]
3607mod tests {
3608 #[test]
3615 fn a_route_can_say_how_many_flares_it_holds() {
3616 let cfg = Config::from_toml_str(
3617 r#"
3618[provider]
3619fallback = ["local", "cloud"]
3620
3621[[provider.route]]
3622name = "local"
3623base_url = "http://127.0.0.1:8080/v1"
3624model = "qwen"
3625profile = "llamacpp"
3626group = "gpu0"
3627max_parallel = 2
3628
3629[[provider.route]]
3630name = "cloud"
3631base_url = "https://api.example.com/v1"
3632model = "big"
3633"#,
3634 )
3635 .unwrap();
3636 let routes = cfg.declared_routes();
3637 let local = routes.iter().find(|r| r.name == "local").unwrap();
3638 assert_eq!(local.parallel(), 2, "the route said two slots");
3639 assert_eq!(local.group.as_deref(), Some("gpu0"));
3640 let cloud = routes.iter().find(|r| r.name == "cloud").unwrap();
3641 assert_eq!(cloud.parallel(), 4, "an openai route defaults to four");
3643 assert!(cloud.group.is_none());
3644 assert_eq!(
3645 local.default_parallel(),
3646 1,
3647 "llamacpp serves one model at a time"
3648 );
3649
3650 let zero = Config::from_toml_str(
3653 r#"
3654[[provider.route]]
3655name = "local"
3656base_url = "http://127.0.0.1:8080/v1"
3657model = "qwen"
3658max_parallel = 0
3659"#,
3660 )
3661 .unwrap();
3662 assert_eq!(zero.declared_routes()[0].parallel(), 1);
3663
3664 let bad = Config::from_toml_str(
3666 r#"
3667[[provider.route]]
3668name = "local"
3669base_url = "http://127.0.0.1:8080/v1"
3670model = "qwen"
3671max_parallel = "two"
3672"#,
3673 )
3674 .unwrap_err()
3675 .to_string();
3676 assert!(bad.contains("route `local`"), "{bad}");
3677 assert!(bad.contains("max_parallel"), "{bad}");
3678 }
3679
3680 #[test]
3681 fn flares_default_to_three_on_one_local_slot() {
3682 let cfg = Config::from_toml_str("").unwrap();
3683 assert_eq!(cfg.flares.count, 3, "the local default");
3684 assert_eq!(cfg.flares.concurrency(), 4);
3685 assert_eq!(cfg.flares.per_flare(), 6);
3686 assert_eq!(cfg.flares.budget(), 24);
3687
3688 let cfg = Config::from_toml_str(
3689 r#"
3690[flares]
3691count = 5
3692max_concurrent = 0
3693max_iterations = 0
3694total_iterations = 2
3695"#,
3696 )
3697 .unwrap();
3698 assert_eq!(cfg.flares.count, 5);
3699 assert_eq!(cfg.flares.concurrency(), 1);
3702 assert_eq!(cfg.flares.per_flare(), 1);
3703 assert_eq!(cfg.flares.budget(), 2);
3704 }
3705
3706 use super::*;
3707 use std::collections::HashMap;
3708
3709 fn starter() -> String {
3711 starter_config().expect("the starter config generates")
3712 }
3713
3714 fn env_of(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> {
3715 let m: HashMap<String, String> = pairs
3716 .iter()
3717 .map(|(k, v)| (k.to_string(), v.to_string()))
3718 .collect();
3719 move |k| m.get(k).cloned()
3720 }
3721
3722 fn load_hooks(text: &str) -> std::result::Result<Config, String> {
3724 let tmp = tempfile::tempdir().unwrap();
3725 let path = tmp.path().join("config.toml");
3726 std::fs::write(&path, text).unwrap();
3727 let env = env_of(&[("HOME", tmp.path().to_str().unwrap())]);
3728 Config::load_with_profile(Some(&path), None, &env).map_err(|e| e.to_string())
3729 }
3730
3731 #[test]
3732 fn the_memory_and_the_filter_are_on_by_default_when_there_is_no_hooks_section() {
3733 let want = crate::hooks::DEFAULT_ORDER;
3734 let c = load_hooks("[agent]\nmax_iterations = 3\n").unwrap();
3735 assert_eq!(c.hooks.order, want);
3736 assert_eq!(Config::default().hooks.order, want);
3737 let c = load_hooks("").unwrap();
3738 assert_eq!(c.hooks.order, want);
3739 assert!(
3740 !want.contains(&"recall-sessions"),
3741 "a new session is a new session: recall is opt-in, and `session_search` is how the \
3742 agent reaches the archive"
3743 );
3744 }
3745
3746 #[test]
3747 fn an_empty_order_turns_every_hook_off() {
3748 let c = load_hooks("[hooks]\norder = []\n").unwrap();
3749 assert!(c.hooks.order.is_empty());
3750 }
3751
3752 #[test]
3753 fn a_settings_table_alone_keeps_the_default_order() {
3754 let c = load_hooks("[hooks.redact-secrets]\nallow = [\"fixture-key\"]\n").unwrap();
3755 assert_eq!(c.hooks.order, crate::hooks::DEFAULT_ORDER);
3756 }
3757
3758 #[test]
3759 fn a_hook_name_this_build_does_not_have_is_refused_and_the_real_ones_are_listed() {
3760 let err =
3761 load_hooks("[hooks]\norder = [\"redact-secrets\", \"redact-secret\"]\n").unwrap_err();
3762 assert!(err.contains("`redact-secret`"), "{err}");
3763 assert!(
3764 err.contains("Hooks that exist: recall-sessions, redact-secrets"),
3765 "{err}"
3766 );
3767 assert!(err.contains("config.toml"), "the file is named: {err}");
3768 }
3769
3770 #[test]
3771 fn a_settings_table_for_a_hook_that_is_not_in_order_is_refused() {
3772 let err =
3773 load_hooks("[hooks]\norder = []\n[hooks.redact-secrets]\nallow = []\n").unwrap_err();
3774 assert!(err.contains("[hooks.redact-secrets]"), "{err}");
3775 assert!(err.contains("never run"), "{err}");
3776 assert!(err.contains("Add \"redact-secrets\" to order"), "{err}");
3777 }
3778
3779 #[test]
3780 fn a_settings_table_for_a_hook_that_does_not_exist_is_refused() {
3781 let err = load_hooks("[hooks.nope]\nx = 1\n").unwrap_err();
3782 assert!(err.contains("[hooks.nope]"), "{err}");
3783 assert!(err.contains("Hooks that exist"), "{err}");
3784 }
3785
3786 #[test]
3787 fn an_unknown_key_in_a_hooks_table_is_refused_and_the_known_ones_are_listed() {
3788 let err = load_hooks("[hooks.redact-secrets]\nalow = [\"x\"]\n").unwrap_err();
3789 assert!(err.contains("unknown key `alow`"), "{err}");
3790 assert!(err.contains("accepts: allow"), "{err}");
3791 }
3792
3793 #[test]
3794 fn a_stray_key_directly_under_hooks_is_refused() {
3795 let err = load_hooks("[hooks]\nenabled = true\n").unwrap_err();
3796 assert!(err.contains("`enabled`"), "{err}");
3797 assert!(err.contains("`order`"), "{err}");
3798 }
3799
3800 #[test]
3801 fn a_hook_listed_twice_and_a_malformed_allow_list_are_refused() {
3802 let err =
3803 load_hooks("[hooks]\norder = [\"redact-secrets\", \"redact-secrets\"]\n").unwrap_err();
3804 assert!(err.contains("twice"), "{err}");
3805 let err = load_hooks("[hooks.redact-secrets]\nallow = \"x\"\n").unwrap_err();
3806 assert!(err.contains("must be a list of strings"), "{err}");
3807 let err = load_hooks("[hooks.redact-secrets]\nallow = [\"\"]\n").unwrap_err();
3808 assert!(err.contains("empty string"), "{err}");
3809 let err = load_hooks("[hooks.redact-secrets]\nallow = [1]\n").unwrap_err();
3810 assert!(err.contains("only strings"), "{err}");
3811 }
3812
3813 #[test]
3814 fn a_profile_overlay_that_breaks_the_hooks_section_is_blamed_on_the_overlay() {
3815 let tmp = tempfile::tempdir().unwrap();
3816 let home = tmp.path().join("home");
3817 let dir = home.join(".eclipse");
3818 std::fs::create_dir_all(dir.join("profiles/work")).unwrap();
3819 std::fs::write(
3820 dir.join("config.toml"),
3821 "[hooks]\norder = [\"redact-secrets\"]\n",
3822 )
3823 .unwrap();
3824 std::fs::write(
3825 dir.join("profiles/work/config.toml"),
3826 "[hooks]\norder = [\"typo\"]\n",
3827 )
3828 .unwrap();
3829 let env = env_of(&[("HOME", home.to_str().unwrap())]);
3830 let err = Config::load_with_profile(None, Some("work"), &env)
3831 .unwrap_err()
3832 .to_string();
3833 assert!(err.contains("profiles/work/config.toml"), "{err}");
3834 assert!(err.contains("`typo`"), "{err}");
3835 }
3836
3837 #[test]
3841 fn an_empty_value_is_not_a_value_in_the_dotenv() {
3842 let dir = tempfile::tempdir().unwrap();
3843 let home = dir.path();
3844 std::fs::create_dir_all(home.join(".eclipse")).unwrap();
3845 let path = home.join(".eclipse/.env");
3846 std::fs::write(
3847 &path,
3848 "ECLIPSE_API_KEY=\nECLIPSE_MODEL=m\nECLIPSE_WEB_AUTH_TOKEN=\n",
3849 )
3850 .unwrap();
3851 let home_s = home.to_str().unwrap().to_string();
3852 let env = env_of(&[("HOME", &home_s)]);
3853 let loaded = Dotenv::load(&env, None).unwrap();
3854 assert_eq!(
3855 loaded.values.get("ECLIPSE_MODEL").map(String::as_str),
3856 Some("m")
3857 );
3858 assert!(
3859 !loaded.values.contains_key("ECLIPSE_API_KEY"),
3860 "an empty assignment is absent: {:?}",
3861 loaded.values.keys().collect::<Vec<_>>()
3862 );
3863 assert!(!loaded.values.contains_key("ECLIPSE_WEB_AUTH_TOKEN"));
3864 }
3865
3866 #[test]
3869 fn a_later_empty_assignment_unsets_an_earlier_one() {
3870 let dir = tempfile::tempdir().unwrap();
3871 let home = dir.path();
3872 std::fs::create_dir_all(home.join(".eclipse").join("profiles/work")).unwrap();
3873 std::fs::write(home.join(".eclipse/.env"), "ECLIPSE_MODEL=big\n").unwrap();
3874 std::fs::write(home.join(".eclipse/profiles/work/.env"), "ECLIPSE_MODEL=\n").unwrap();
3875 let home_s = home.to_str().unwrap().to_string();
3876 let env = env_of(&[("HOME", &home_s)]);
3877 let loaded = Dotenv::load(&env, Some("work")).unwrap();
3878 assert_eq!(loaded.files.len(), 2);
3879 assert_eq!(loaded.values.get("ECLIPSE_MODEL"), None);
3880 }
3881
3882 #[test]
3885 fn the_starter_env_lists_every_variable_and_sets_none_of_them() {
3886 let text = starter_env("tok");
3887 for name in ENV_TEMPLATE {
3888 assert!(
3889 text.contains(&format!("\n{name}=")),
3890 "`{name}` is in the shipped .env"
3891 );
3892 }
3893 for line in text.lines().filter(|l| !l.starts_with('#')) {
3894 let (name, value) = line.split_once('=').expect("KEY=VALUE");
3895 if name == "ECLIPSE_WEB_AUTH_TOKEN" {
3896 assert_eq!(value, "tok", "the one value a first install cannot invent");
3897 } else {
3898 assert!(value.is_empty(), "`{name}` ships unset, found `{value}`");
3899 }
3900 }
3901 }
3902
3903 #[test]
3907 fn every_environment_variable_the_build_reads_is_classified() {
3908 let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("..");
3909 let mut seen = Vec::new();
3910 let mut dirs = vec![
3911 root.join("eclipse-core/src"),
3912 root.join("eclipse-cli/src"),
3913 root.join("eclipse-web/src"),
3914 ];
3915 while let Some(dir) = dirs.pop() {
3916 let Ok(entries) = std::fs::read_dir(&dir) else {
3917 continue;
3918 };
3919 for entry in entries.flatten() {
3920 let path = entry.path();
3921 if path.is_dir() {
3922 dirs.push(path);
3923 continue;
3924 }
3925 if path.extension().and_then(|e| e.to_str()) != Some("rs") {
3926 continue;
3927 }
3928 let text = std::fs::read_to_string(&path).unwrap_or_default();
3929 for name in env_names(&text) {
3930 if !seen.contains(&name) {
3931 seen.push(name);
3932 }
3933 }
3934 }
3935 }
3936 assert!(seen.len() > 10, "the scan found the variables: {seen:?}");
3937 for name in &seen {
3938 let known = ENV_TEMPLATE.contains(&name.as_str())
3939 || ENV_SHELL_ONLY.contains(&name.as_str())
3940 || ENV_INTERNAL.contains(&name.as_str());
3941 assert!(
3942 known,
3943 "`{name}` is read by the build and is in none of ENV_TEMPLATE, ENV_SHELL_ONLY, ENV_INTERNAL"
3944 );
3945 }
3946 let shipped = starter();
3950 for name in ENV_TEMPLATE {
3951 let read = seen.iter().any(|s| s == name);
3952 let interpolated = shipped.contains(&format!("${{{name}"));
3953 assert!(
3954 read || interpolated,
3955 "`{name}` is in the shipped .env and nothing reads or interpolates it"
3956 );
3957 }
3958 }
3959
3960 #[test]
3964 fn every_classified_variable_has_a_description() {
3965 let classified: Vec<&str> = ENV_TEMPLATE
3966 .iter()
3967 .chain(ENV_SHELL_ONLY)
3968 .chain(ENV_INTERNAL)
3969 .copied()
3970 .collect();
3971 for name in &classified {
3972 assert!(
3973 !env_about(name).is_empty(),
3974 "`{name}` is classified and has no line in ENV_ABOUT"
3975 );
3976 }
3977 for (name, about) in ENV_ABOUT {
3978 assert!(
3979 classified.contains(name),
3980 "ENV_ABOUT explains `{name}`, which the build does not read"
3981 );
3982 assert!(
3983 about.len() > 30 && !about.ends_with('.'),
3984 "one sentence, no full stop: {about}"
3985 );
3986 }
3987 }
3988
3989 fn env_names(text: &str) -> Vec<String> {
3992 let mut out = Vec::new();
3993 let mut rest = text;
3994 while let Some(at) = rest.find("\"ECLIPSE_") {
3995 let after = &rest[at + 1..];
3996 let Some(end) = after.find('"') else {
3997 break;
3998 };
3999 let name = &after[..end];
4000 let complete = name
4003 .chars()
4004 .last()
4005 .is_some_and(|c| c.is_ascii_uppercase() || c.is_ascii_digit());
4006 if complete
4007 && name
4008 .chars()
4009 .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')
4010 {
4011 out.push(name.to_string());
4012 }
4013 rest = &after[end + 1..];
4014 }
4015 out
4016 }
4017
4018 #[test]
4019 fn an_empty_optional_string_loads_as_unset() {
4020 let c = Config::from_toml_str(
4023 "[provider]\napi_key = \"\"\napi_key_env = \"\"\nmodel = \"m\"\n[web]\nauth_token = \"\"\n",
4024 )
4025 .unwrap();
4026 assert_eq!(c.provider.api_key, None);
4027 assert_eq!(c.provider.api_key_env, None);
4028 assert_eq!(c.web.auth_token, None);
4029 assert_eq!(c.provider.model, "m");
4031 let dir = tempfile::tempdir().unwrap();
4034 let path = dir.path().join("config.toml");
4035 std::fs::write(&path, "[provider]\napi_key = \"${NOT_SET_ANYWHERE:-}\"\n").unwrap();
4036 let from_var = Config::load_with(Some(&path), &env_of(&[])).unwrap();
4037 assert_eq!(
4038 from_var.provider.api_key, None,
4039 "an absent variable is no key"
4040 );
4041 }
4042
4043 #[test]
4047 fn the_starter_config_carries_every_setting_the_build_reads() {
4048 let text = starter();
4049 let c = parse_text(&text).unwrap();
4050 let settings = Config::default().settings();
4051 assert!(
4052 settings.len() > 80,
4053 "the catalogue is the yardstick: {settings:?}"
4054 );
4055 for setting in &settings {
4056 let key = setting.key.clone();
4057 let present = text.lines().any(|l| {
4058 l.trim_start_matches("# ")
4059 .trim_start()
4060 .starts_with(&format!("{key} ="))
4061 });
4062 assert!(
4063 present,
4064 "[{}] `{key}` is missing from the shipped file:\n{text}",
4065 setting.section
4066 );
4067 }
4068 for line in text.lines().filter(|l| l.starts_with('#')) {
4071 assert!(
4072 line.starts_with("# ") && line[2..].contains(" =") || line.len() < 120,
4073 "a comment in the settings file should be a key, not a sentence: {line}"
4074 );
4075 }
4076 let prose = text
4077 .lines()
4078 .filter(|l| l.starts_with('#') && !l[1..].trim_start().contains(" ="))
4079 .count();
4080 assert!(prose <= 3, "only the three header lines: {prose}");
4081 assert_eq!(c.hooks.order, crate::hooks::DEFAULT_ORDER);
4083 assert_eq!(c.hooks.order, Config::default().hooks.order);
4084 assert!(c.hooks.settings.contains_key("redact-secrets"));
4085 crate::hooks::validate(&c.hooks).expect("the starter config's hooks validate");
4086 assert!(
4087 !c.hooks.settings.contains_key("recall-sessions"),
4088 "a settings table for a hook that is not in `order` cannot run"
4089 );
4090 let value: toml::Value = toml::from_str(&text).unwrap();
4093 let unknown = c.unknown_keys(&value);
4094 assert!(
4095 unknown.is_empty(),
4096 "unknown keys in the shipped file: {unknown:?}"
4097 );
4098 assert_eq!(
4099 c.config_version, CONFIG_VERSION,
4100 "the file stamps its shape"
4101 );
4102 }
4103
4104 #[test]
4108 fn config_show_scrubs_credentials_carried_in_an_mcp_url() {
4109 let c = Config::from_toml_str(
4110 "[provider]\nbase_url = \"http://127.0.0.1:1/v1\"\n\n\
4111 [[mcp]]\nname = \"gh\"\ntransport = \"http\"\n\
4112 url = \"https://user:pw@example.test/mcp?token=abc&limit=5\"\n\n\
4113 [[mcp]]\nname = \"plain\"\ntransport = \"http\"\n\
4114 url = \"https://example.test/mcp\"\n",
4115 )
4116 .unwrap();
4117 let shown = c.to_toml_redacted().unwrap();
4118 assert!(!shown.contains("pw"), "the password is gone: {shown}");
4119 assert!(!shown.contains("abc"), "the token is gone: {shown}");
4120 assert!(
4121 shown.contains("https://<redacted>@example.test/mcp"),
4122 "the shape is kept, the credentials are not: {shown}"
4123 );
4124 assert!(
4125 shown.contains("token=<redacted>"),
4126 "the parameter name stays, its value does not: {shown}"
4127 );
4128 assert!(
4129 shown.contains("limit=5"),
4130 "a parameter that is not a secret is not touched: {shown}"
4131 );
4132 assert!(
4133 shown.contains("url = \"https://example.test/mcp\""),
4134 "an endpoint with no credentials in it reads exactly as written: {shown}"
4135 );
4136 }
4137
4138 #[test]
4139 fn the_hooks_section_survives_a_round_trip_through_the_redacted_printout() {
4140 let c = load_hooks(
4141 "[hooks]\norder = [\"redact-secrets\"]\n[hooks.redact-secrets]\nallow = [\"fx\"]\n",
4142 )
4143 .unwrap();
4144 let shown = c.to_toml_redacted().unwrap();
4145 let again = Config::from_toml_str(&shown).unwrap();
4146 assert_eq!(again.hooks, c.hooks);
4147 }
4148
4149 #[test]
4150 fn defaults_have_no_endpoint_or_key() {
4151 let c = Config::default();
4152 assert!(c.provider.base_url.is_empty());
4153 assert!(c.provider.api_key.is_none());
4154 assert!(c.require_provider().is_err());
4155 assert_eq!(c.tools.write_file, Policy::Allow);
4158 assert_eq!(c.tools.shell, Policy::Ask);
4159 assert_eq!(c.tools.shell_ask, ShellAsk::Dangerous);
4160 }
4161
4162 #[test]
4163 fn cli_section_defaults_and_parses() {
4164 let d = Config::from_toml_str("").unwrap().cli;
4166 assert_eq!(d.color, None);
4167 assert_eq!(d.markdown, None);
4168 assert_eq!(d.approval, Approval::Ask);
4169 assert_eq!(d.history_size, 1000);
4170
4171 let c = Config::from_toml_str(
4172 "[cli]\ncolor = false\nmarkdown = true\napproval = \"auto\"\nhistory_size = 50\n",
4173 )
4174 .unwrap()
4175 .cli;
4176 assert_eq!(c.color, Some(false));
4177 assert_eq!(c.markdown, Some(true));
4178 assert_eq!(c.approval, Approval::Auto);
4179 assert_eq!(c.history_size, 50);
4180 }
4181
4182 #[test]
4183 fn an_unknown_approval_is_an_error_rather_than_a_silent_ask() {
4184 let err = Config::from_toml_str("[cli]\napproval = \"sometimes\"\n").unwrap_err();
4187 assert!(err.contains("approval"), "{err}");
4188 }
4189
4190 #[test]
4191 fn web_section_parses_its_ttl_and_default_profile() {
4192 let d = Config::from_toml_str("").unwrap().web;
4193 assert_eq!(d.session_ttl_hours, DEFAULT_SESSION_TTL_HOURS);
4194 assert_eq!(d.default_profile, None);
4195
4196 let w = Config::from_toml_str("[web]\nsession_ttl_hours = 1\ndefault_profile = \"work\"\n")
4197 .unwrap()
4198 .web;
4199 assert_eq!(w.session_ttl_hours, 1);
4200 assert_eq!(w.default_profile.as_deref(), Some("work"));
4201 }
4202
4203 #[test]
4207 fn the_starter_config_loads_without_a_dotenv_and_leaves_the_token_unset() {
4208 let dir = tempfile::tempdir().unwrap();
4209 let path = dir.path().join("config.toml");
4210 std::fs::write(&path, starter()).unwrap();
4211 let c = Config::load_with(Some(&path), &|_| None)
4214 .expect("the starter config loads with no .env at all");
4215 assert_eq!(
4216 c.web.auth_token, None,
4217 "an unset token loads as no token, not as a load error and not as an empty secret"
4218 );
4219 assert_eq!(c.provider.model, Config::default().provider.model);
4220 }
4221
4222 #[test]
4223 fn starter_config_parses_and_matches_defaults() {
4224 let c = Config::from_toml_str(&starter()).unwrap();
4225 let d = Config::default();
4226 assert_eq!(c.tools.read_file, d.tools.read_file);
4227 assert_eq!(c.tools.fetch, d.tools.fetch);
4228 assert_eq!(c.web.port, d.web.port);
4229 assert!(c.provider.base_url.is_empty());
4230 }
4231
4232 #[test]
4233 fn partial_file_fills_defaults() {
4234 let c = Config::from_toml_str(
4235 "[provider]\nbase_url=\"http://x/v1\"\nmodel=\"m\"\n[tools]\nshell=\"deny\"\n",
4236 )
4237 .unwrap();
4238 assert_eq!(c.provider.base_url, "http://x/v1");
4239 assert_eq!(c.tools.shell, Policy::Deny);
4240 assert_eq!(c.tools.write_file, Policy::Allow);
4241 assert_eq!(
4242 c.agent.max_iterations,
4243 usize::MAX,
4244 "no cap unless the box asks for one"
4245 );
4246 assert!(c.require_provider().is_ok());
4247
4248 for word in ["unlimited", "none", "inf", "0", "-1"] {
4249 let raw = format!("[agent]\nmax_iterations = {word}\n");
4250 let raw = if word.parse::<i64>().is_ok() {
4251 raw
4252 } else {
4253 format!("[agent]\nmax_iterations = \"{word}\"\n")
4254 };
4255 let c = Config::from_toml_str(&raw).unwrap();
4256 assert_eq!(c.agent.max_iterations, usize::MAX, "`{word}` means no cap");
4257 }
4258
4259 let c = Config::from_toml_str("[agent]\nmax_iterations = 12\n").unwrap();
4260 assert_eq!(c.agent.max_iterations, 12, "a number is a cap");
4261
4262 let words = Config::from_toml_str("[agent]\nmax_iterations = \"unlimited\"\n").unwrap();
4263 let printed = toml::to_string(&words).unwrap();
4264 assert!(
4265 printed.contains("max_iterations = \"unlimited\""),
4266 "the schema says the word, not a length: {printed}"
4267 );
4268
4269 let refused = Config::from_toml_str("[agent]\nmax_iterations = \"plenty\"\n");
4270 assert!(
4271 refused.is_err(),
4272 "a word that is not one of ours is an error"
4273 );
4274 }
4275
4276 #[test]
4277 fn unknown_policy_is_rejected() {
4278 assert!(Config::from_toml_str("[tools]\nshell=\"yolo\"\n").is_err());
4279 }
4280
4281 #[test]
4282 fn env_overrides_file() {
4283 let dir = tempfile::tempdir().unwrap();
4284 let p = dir.path().join("c.toml");
4285 std::fs::write(
4286 &p,
4287 "[provider]\nbase_url=\"http://file/v1\"\nmodel=\"file-model\"\napi_key=\"file-key\"\n",
4288 )
4289 .unwrap();
4290 let env = env_of(&[
4291 ("ECLIPSE_BASE_URL", "http://env/v1"),
4292 ("ECLIPSE_API_KEY", "env-key"),
4293 ]);
4294 let c = Config::load_with(Some(&p), &env).unwrap();
4295 assert_eq!(c.provider.base_url, "http://env/v1");
4296 assert_eq!(c.provider.model, "file-model");
4297 assert_eq!(c.provider.api_key.as_deref(), Some("env-key"));
4298 }
4299
4300 #[test]
4301 fn api_key_env_indirection() {
4302 let env = env_of(&[("MY_KEY", "secret")]);
4303 let mut c = Config::from_toml_str("[provider]\napi_key_env=\"MY_KEY\"\n").unwrap();
4304 c.apply_env(&env);
4305 assert_eq!(c.provider.api_key.as_deref(), Some("secret"));
4306 }
4307
4308 #[test]
4309 fn debug_redacts_api_key() {
4310 let mut c = Config::default();
4311 c.provider.api_key = Some("hunter2".into());
4312 assert!(!format!("{c:?}").contains("hunter2"));
4313 }
4314
4315 #[test]
4316 fn debug_and_redacted_toml_hide_web_token() {
4317 let mut c = Config::default();
4318 c.web.auth_token = Some("s3cret-token-value".into());
4319 assert!(!format!("{c:?}").contains("s3cret"));
4320 assert!(!c.to_toml_redacted().unwrap().contains("s3cret"));
4321 }
4322
4323 #[test]
4327 fn debug_never_prints_a_dotenv_value() {
4328 let dir = tempfile::tempdir().unwrap();
4329 let root = dir.path().join("root");
4330 std::fs::create_dir_all(&root).unwrap();
4331 std::fs::write(
4332 root.join(".env"),
4333 "ECLIPSE_API_KEY=dotenvvalue123\nMY_PRIVATE_MIRROR=mirrorvalue456\n",
4334 )
4335 .unwrap();
4336 let cfg_path = root.join("config.toml");
4337 std::fs::write(
4338 &cfg_path,
4339 "[provider]\nbase_url = \"http://127.0.0.1:9/v1\"\nmodel = \"m\"\napi_key = \"${ECLIPSE_API_KEY}\"\n",
4340 )
4341 .unwrap();
4342 let env = env_of(&[
4343 ("ECLIPSE_HOME", root.to_str().unwrap()),
4344 ("HOME", dir.path().to_str().unwrap()),
4345 ]);
4346
4347 let cfg = Config::load_with_profile(Some(&cfg_path), None, &env).unwrap();
4348 let debug = format!("{cfg:?}");
4349 assert!(
4350 !debug.contains("dotenvvalue123") && !debug.contains("mirrorvalue456"),
4351 "the .env values must never be printed: {debug}"
4352 );
4353 assert!(debug.contains("ECLIPSE_API_KEY"), "{debug}");
4354 assert!(debug.contains("Dotenv"), "{debug}");
4355 assert_eq!(cfg.provider.api_key.as_deref(), Some("dotenvvalue123"));
4357 }
4358
4359 #[test]
4360 fn redacted_toml_hides_key_and_round_trips() {
4361 let mut c = Config::default();
4362 c.provider.api_key = Some("hunter2".into());
4363 c.provider.model = "m".into();
4364 let t = c.to_toml_redacted().unwrap();
4365 assert!(!t.contains("hunter2"));
4366 assert_eq!(Config::from_toml_str(&t).unwrap().provider.model, "m");
4367 }
4368
4369 #[test]
4373 fn the_update_track_names_a_branch_and_takes_two_words() {
4374 assert_eq!(Config::default().update.track, Track::Release);
4375 assert_eq!(Track::Release.branch(), "main");
4376 assert_eq!(Track::Develop.branch(), "develop");
4377 let cfg = Config::from_toml_str("[update]\ntrack = \"develop\"\n").unwrap();
4378 assert_eq!(cfg.update.track, Track::Develop);
4379 assert_eq!(cfg.update.track.label(), "develop");
4380 let err = Config::from_toml_str("[update]\ntrack = \"main\"\n")
4381 .unwrap_err()
4382 .to_string();
4383 assert!(
4384 err.contains("main") && err.contains("develop"),
4385 "the refusal lists the words it takes: {err}"
4386 );
4387 }
4388
4389 #[test]
4392 fn a_url_keeps_its_shape_and_loses_its_secrets() {
4393 let mut c = Config::default();
4394 c.provider.base_url = "https://user:hunter2@gw.internal/v1".into();
4395 c.update.remote =
4396 Some("https://mirror.internal/releases?access_token=abc123&page=2".into());
4397 c.update.releases = Some("https://mirror.internal/api#frag".into());
4398
4399 let t = c.to_toml_redacted().unwrap();
4400 assert!(
4401 !t.contains("hunter2") && !t.contains("abc123"),
4402 "the secrets are gone: {t}"
4403 );
4404 assert!(
4406 t.contains("https://<redacted>@gw.internal/v1"),
4407 "the userinfo is replaced, not the URL: {t}"
4408 );
4409 assert!(
4410 t.contains("access_token=<redacted>&page=2"),
4411 "the secret parameter keeps its name and loses its value: {t}"
4412 );
4413 assert!(t.contains("https://mirror.internal/api#frag"), "{t}");
4414
4415 let debug = format!("{c:?}");
4417 assert!(!debug.contains("hunter2"), "{debug}");
4418
4419 let plain = Config::default();
4421 assert!(plain
4422 .to_toml_redacted()
4423 .unwrap()
4424 .contains(&plain.provider.base_url));
4425 }
4426
4427 #[test]
4428 fn one_root_layout() {
4429 let env = env_of(&[("HOME", "/home/u")]);
4431 assert_eq!(
4432 config_path(&env).unwrap(),
4433 PathBuf::from("/home/u/.eclipse/config.toml")
4434 );
4435 assert_eq!(
4436 Config::default().sessions_dir(&env).unwrap(),
4437 PathBuf::from("/home/u/.eclipse/state/sessions")
4438 );
4439 assert_eq!(
4440 Config::default().memory_dir(&env).unwrap(),
4441 PathBuf::from("/home/u/.eclipse/memory")
4442 );
4443 let env = env_of(&[
4446 ("HOME", "/home/u"),
4447 ("XDG_CONFIG_HOME", "/x/cfg"),
4448 ("XDG_STATE_HOME", "/x/state"),
4449 ]);
4450 assert_eq!(
4451 config_path(&env).unwrap(),
4452 PathBuf::from("/home/u/.eclipse/config.toml")
4453 );
4454 let env = env_of(&[("HOME", "/home/u"), ("ECLIPSE_HOME", "/opt/ecl")]);
4456 assert_eq!(
4457 config_path(&env).unwrap(),
4458 PathBuf::from("/opt/ecl/config.toml")
4459 );
4460 }
4461
4462 #[test]
4463 fn missing_default_file_is_ok_but_explicit_missing_is_error() {
4464 let dir = tempfile::tempdir().unwrap();
4465 let env = env_of(&[("HOME", dir.path().to_str().unwrap())]);
4466 assert!(Config::load_with(None, &env).is_ok());
4467 assert!(Config::load_with(Some(&dir.path().join("nope.toml")), &env).is_err());
4468 }
4469
4470 #[test]
4471 fn auto_prune_is_off_by_default_and_can_be_enabled() {
4472 assert!(!Config::default().sessions.auto_prune);
4473 let c = Config::from_toml_str("[sessions]\nauto_prune = true\nretention_keep_count = 5\n")
4474 .unwrap();
4475 assert!(c.sessions.auto_prune);
4476 assert_eq!(c.sessions.retention_keep_count, 5);
4477 }
4478
4479 #[test]
4480 fn sessions_dir_expands_tilde() {
4481 let env = env_of(&[("HOME", "/home/u")]);
4482 let mut c = Config::default();
4483 c.sessions.dir = Some("~/s".into());
4484 assert_eq!(c.sessions_dir(&env).unwrap(), PathBuf::from("/home/u/s"));
4485 }
4486
4487 #[test]
4488 fn config_init_writes_a_private_dotenv_and_the_config_refers_to_it() {
4489 let dir = tempfile::tempdir().unwrap();
4490 let p = dir.path().join("a/b/config.toml");
4491 let env = env_of(&[("ECLIPSE_HOME", dir.path().to_str().unwrap())]);
4492 let report = write_starter_config(&p, false, &env).unwrap();
4493 assert!(report.dotenv_written);
4494 assert_eq!(
4495 report.dotenv,
4496 dir.path().join(".env"),
4497 "the .env goes where the loader reads it, not beside a config elsewhere"
4498 );
4499
4500 let dotenv = std::fs::read_to_string(&report.dotenv).unwrap();
4501 let token = dotenv
4502 .lines()
4503 .find_map(|l| l.strip_prefix("ECLIPSE_WEB_AUTH_TOKEN="))
4504 .expect("the token lives in .env");
4505 assert_eq!(token.len(), 64, "a generated token, not a placeholder");
4506 assert!(token.bytes().all(|b| b.is_ascii_hexdigit()));
4507 assert!(
4508 !std::fs::read_to_string(&p).unwrap().contains(token),
4509 "the config carries the reference, never the secret"
4510 );
4511
4512 #[cfg(unix)]
4513 {
4514 use std::os::unix::fs::PermissionsExt;
4515 for f in [&p, &report.dotenv] {
4516 assert_eq!(f.metadata().unwrap().permissions().mode() & 0o777, 0o600);
4517 }
4518 }
4519
4520 let root = dir.path().join("root");
4523 let cfg_dir = root.clone();
4524 std::fs::create_dir_all(&cfg_dir).unwrap();
4525 let real = cfg_dir.join("config.toml");
4526 let env = env_of(&[
4527 ("ECLIPSE_HOME", root.to_str().unwrap()),
4528 ("HOME", dir.path().to_str().unwrap()),
4529 ]);
4530 let written = write_starter_config(&real, false, &env).unwrap();
4531 let cfg = Config::load_with_profile(Some(&real), None, &env).unwrap();
4532 let token = std::fs::read_to_string(&written.dotenv)
4533 .unwrap()
4534 .lines()
4535 .find_map(|l| {
4536 l.strip_prefix("ECLIPSE_WEB_AUTH_TOKEN=")
4537 .map(str::to_string)
4538 })
4539 .unwrap();
4540 assert_eq!(cfg.web.auth_token.as_deref(), Some(token.as_str()));
4541 assert_eq!(cfg.dotenv.files, vec![written.dotenv]);
4542 }
4543
4544 #[test]
4548 fn an_empty_dotenv_value_is_absent_not_an_empty_override() {
4549 let dir = tempfile::tempdir().unwrap();
4550 let root = dir.path().join("root");
4551 std::fs::create_dir_all(&root).unwrap();
4552 std::fs::write(
4553 root.join(".env"),
4554 "ECLIPSE_API_KEY=\nECLIPSE_MODEL=\nECLIPSE_BASE_URL=\n",
4555 )
4556 .unwrap();
4557 let cfg_path = root.join("config.toml");
4558 std::fs::write(
4559 &cfg_path,
4560 "[provider]\napi_key = \"sk-from-the-file\"\nmodel = \"keep-me\"\n\
4561 base_url = \"http://127.0.0.1:9999/v1\"\n",
4562 )
4563 .unwrap();
4564 let env = env_of(&[
4565 ("ECLIPSE_HOME", root.to_str().unwrap()),
4566 ("HOME", dir.path().to_str().unwrap()),
4567 ]);
4568
4569 let cfg = Config::load_with_profile(Some(&cfg_path), None, &env).unwrap();
4570 assert_eq!(
4571 cfg.provider.api_key.as_deref(),
4572 Some("sk-from-the-file"),
4573 "an empty .env value must not blank the key"
4574 );
4575 assert_eq!(cfg.provider.model, "keep-me", "nor the model");
4576 assert_eq!(
4577 cfg.provider.base_url, "http://127.0.0.1:9999/v1",
4578 "nor the base URL"
4579 );
4580 }
4581
4582 #[test]
4583 fn context_files_are_seeded_and_existing_ones_are_kept() {
4584 let tmp = tempfile::tempdir().unwrap();
4585 let memory = tmp.path().join("memory");
4586 let created = seed_context_files(&memory).unwrap();
4587 assert_eq!(created.len(), 3, "AGENT, USER, MEMORY: {created:?}");
4588 assert!(memory.join("AGENT.md").exists());
4589 assert!(memory.join("USER.md").exists());
4590 assert!(memory.join("MEMORY.md").exists());
4591 assert_eq!(
4592 std::fs::read_to_string(memory.join("MEMORY.md")).unwrap(),
4593 ""
4594 );
4595
4596 let created = seed_context_files(&memory).unwrap();
4598 assert!(
4599 created.is_empty(),
4600 "existing files are left alone: {created:?}"
4601 );
4602
4603 let written = [
4607 ("AGENT.md", "run make, no cargo test\n"),
4608 ("USER.md", "I am the operator; keep it short\n"),
4609 ("MEMORY.md", "- one durable fact\n"),
4610 ];
4611 for (name, body) in written {
4612 std::fs::write(memory.join(name), body).unwrap();
4613 }
4614 let created = seed_context_files(&memory).unwrap();
4615 assert!(created.is_empty(), "{created:?}");
4616 for (name, body) in written {
4617 assert_eq!(
4618 std::fs::read_to_string(memory.join(name)).unwrap(),
4619 body,
4620 "{name} was rewritten"
4621 );
4622 }
4623 }
4624
4625 #[test]
4630 fn a_new_profile_is_a_first_install_and_an_existing_one_is_never_rewritten() {
4631 let tmp = tempfile::tempdir().unwrap();
4632 let base = tmp.path().join("memory");
4633 let lived_in = tmp.path().join("profiles/work/memory");
4634 let fresh = tmp.path().join("profiles/lab/memory");
4635
4636 assert_eq!(seed_context_files(&base).unwrap().len(), 3);
4637 std::fs::write(base.join("USER.md"), "the operator\n").unwrap();
4638
4639 std::fs::create_dir_all(&lived_in).unwrap();
4640 for name in ["AGENT.md", "USER.md", "MEMORY.md"] {
4641 std::fs::write(lived_in.join(name), format!("{name} as it was lived in\n")).unwrap();
4642 }
4643
4644 assert!(
4645 seed_context_files(&lived_in).unwrap().is_empty(),
4646 "an existing profile's files are not rewritten"
4647 );
4648 assert_eq!(
4649 seed_context_files(&fresh).unwrap().len(),
4650 3,
4651 "a profile that has never been used is a first install"
4652 );
4653
4654 assert_eq!(
4655 std::fs::read_to_string(base.join("USER.md")).unwrap(),
4656 "the operator\n"
4657 );
4658 for name in ["AGENT.md", "USER.md", "MEMORY.md"] {
4659 assert_eq!(
4660 std::fs::read_to_string(lived_in.join(name)).unwrap(),
4661 format!("{name} as it was lived in\n")
4662 );
4663 }
4664 }
4665
4666 #[test]
4670 fn config_init_puts_the_dotenv_where_a_start_with_that_config_will_read_it() {
4671 let dir = tempfile::tempdir().unwrap();
4672 let home = dir.path().join("home");
4673 std::fs::create_dir_all(&home).unwrap();
4674 let elsewhere = dir.path().join("other");
4675 let path = elsewhere.join("config.toml");
4676 let env = env_of(&[
4677 ("ECLIPSE_HOME", home.to_str().unwrap()),
4678 ("HOME", dir.path().to_str().unwrap()),
4679 ]);
4680
4681 let report = write_starter_config(&path, false, &env).unwrap();
4682 let token = std::fs::read_to_string(&report.dotenv)
4683 .unwrap()
4684 .lines()
4685 .find_map(|l| l.strip_prefix("ECLIPSE_WEB_AUTH_TOKEN="))
4686 .expect("the token lives in .env")
4687 .to_string();
4688 assert_eq!(report.dotenv, home.join(".env"));
4689
4690 let cfg = Config::load_with_profile(Some(&path), None, &env).unwrap();
4691 assert_eq!(
4692 cfg.web.auth_token.as_deref(),
4693 Some(token.as_str()),
4694 "the token `config init` reported is the token the next start reads"
4695 );
4696 }
4697
4698 #[test]
4699 fn config_init_refuses_to_overwrite_a_config_without_force() {
4700 let dir = tempfile::tempdir().unwrap();
4701 let p = dir.path().join("c/config.toml");
4702 let env = env_of(&[("ECLIPSE_HOME", dir.path().to_str().unwrap())]);
4703 write_starter_config(&p, false, &env).unwrap();
4704 assert!(write_starter_config(&p, false, &env).is_err());
4705 }
4706
4707 #[test]
4708 fn config_init_never_overwrites_an_existing_dotenv() {
4709 let dir = tempfile::tempdir().unwrap();
4710 let p = dir.path().join("d/config.toml");
4711 let env = env_of(&[("ECLIPSE_HOME", dir.path().to_str().unwrap())]);
4712 let first = write_starter_config(&p, false, &env).unwrap();
4713 let before = std::fs::read_to_string(&first.dotenv).unwrap();
4714
4715 let again = write_starter_config(&p, true, &env).unwrap();
4717 assert!(!again.dotenv_written);
4718 assert_eq!(std::fs::read_to_string(&again.dotenv).unwrap(), before);
4719 }
4720
4721 #[test]
4722 fn a_profile_overlay_merges_over_the_base_config() {
4723 let tmp = tempfile::tempdir().unwrap();
4724 let home = tmp.path().join("home");
4725 let cfg_dir = home.join(".eclipse");
4726 std::fs::create_dir_all(cfg_dir.join("profiles/work")).unwrap();
4727 std::fs::write(
4728 cfg_dir.join("config.toml"),
4729 "[provider]\nbase_url = \"http://base/v1\"\nmodel = \"base-model\"\n\
4730 temperature = 0.2\n[agent]\nmax_iterations = 7\n",
4731 )
4732 .unwrap();
4733 std::fs::write(
4734 cfg_dir.join("profiles/work/config.toml"),
4735 "[provider]\nmodel = \"work-model\"\n",
4736 )
4737 .unwrap();
4738 let env = env_of(&[("HOME", home.to_str().unwrap())]);
4739
4740 let base = Config::load_with(None, &env).unwrap();
4741 assert_eq!(base.provider.model, "base-model");
4742 assert_eq!(base.profile_name(), "default");
4743
4744 let work = Config::load_with_profile(None, Some("work"), &env).unwrap();
4745 assert_eq!(work.provider.model, "work-model");
4747 assert_eq!(work.provider.base_url, "http://base/v1");
4748 assert_eq!(work.provider.temperature, Some(0.2));
4749 assert_eq!(work.agent.max_iterations, 7);
4750 assert_eq!(work.profile_name(), "work");
4751 assert_eq!(
4753 work.sessions_dir(&env).unwrap(),
4754 home.join(".eclipse/profiles/work/state/sessions")
4755 );
4756 assert_eq!(
4757 base.sessions_dir(&env).unwrap(),
4758 home.join(".eclipse/state/sessions")
4759 );
4760 assert_eq!(
4761 work.state_dir(&env).unwrap(),
4762 home.join(".eclipse/profiles/work/state")
4763 );
4764 }
4765
4766 #[test]
4767 fn the_profile_comes_from_the_environment_and_the_argument_wins() {
4768 let tmp = tempfile::tempdir().unwrap();
4769 let home = tmp.path().join("home");
4770 std::fs::create_dir_all(home.join(".eclipse/profiles/env")).unwrap();
4771 std::fs::write(
4772 home.join(".eclipse/profiles/env/config.toml"),
4773 "[agent]\nmax_iterations = 3\n",
4774 )
4775 .unwrap();
4776 let env = env_of(&[("HOME", home.to_str().unwrap()), ("ECLIPSE_PROFILE", "env")]);
4777 let from_env = Config::load_with(None, &env).unwrap();
4778 assert_eq!(from_env.profile_name(), "env");
4779 assert_eq!(from_env.agent.max_iterations, 3);
4780
4781 let explicit = Config::load_with_profile(None, Some("other"), &env).unwrap();
4782 assert_eq!(explicit.profile_name(), "other");
4783 assert_eq!(explicit.agent.max_iterations, usize::MAX);
4785 }
4786
4787 #[test]
4788 fn the_default_profile_keeps_the_plain_state_directory() {
4789 let env = env_of(&[("HOME", "/home/u")]);
4790 assert_eq!(
4791 state_dir_for(&env, Some("default")).unwrap(),
4792 PathBuf::from("/home/u/.eclipse/state")
4793 );
4794 assert_eq!(
4795 state_dir_for(&env, None).unwrap(),
4796 PathBuf::from("/home/u/.eclipse/state")
4797 );
4798 assert_eq!(
4799 state_dir_for(&env, Some("work")).unwrap(),
4800 PathBuf::from("/home/u/.eclipse/profiles/work/state")
4801 );
4802 }
4803
4804 #[test]
4805 fn a_profile_name_must_be_a_safe_directory_name() {
4806 for bad in ["", "../etc", "a/b", "sp ace"] {
4807 assert!(
4808 validate_profile_name(bad).is_err(),
4809 "{bad:?} should be rejected"
4810 );
4811 }
4812 assert!(validate_profile_name("work-2026_x").is_ok());
4813 let env = env_of(&[("HOME", "/home/u")]);
4814 assert!(Config::load_with_profile(None, Some("../evil"), &env).is_err());
4815 }
4816
4817 #[test]
4818 fn plugin_directories_put_the_profile_first() {
4819 let tmp = tempfile::tempdir().unwrap();
4820 let home = tmp.path().join("home");
4821 std::fs::create_dir_all(home.join(".eclipse")).unwrap();
4822 let env = env_of(&[("HOME", home.to_str().unwrap())]);
4823 let mut cfg = Config::default();
4824 let default_dirs = cfg.plugins_dirs(&env);
4825 assert_eq!(
4826 default_dirs,
4827 vec![home.join(".eclipse/plugins")],
4828 "the default profile has no profile plugin dir"
4829 );
4830
4831 cfg.profile = Some("work".into());
4832 let dirs = cfg.plugins_dirs(&env);
4833 assert_eq!(dirs.len(), 2);
4834 assert_eq!(dirs[0], home.join(".eclipse/profiles/work/plugins"));
4835 assert_eq!(dirs[1], home.join(".eclipse/plugins"));
4836
4837 cfg.plugins.dir = Some("~/elsewhere/plugins".into());
4838 assert_eq!(cfg.plugins_dirs(&env)[1], home.join("elsewhere/plugins"));
4839 }
4840
4841 #[test]
4842 fn plugins_are_off_until_named() {
4843 let cfg = Config::default();
4844 assert!(cfg.plugins.enabled.is_empty());
4845 assert!(cfg.plugins.dir.is_none());
4846 let parsed = Config::from_toml_str("[plugins]\nenabled = [\"a\", \"b\"]\n").unwrap();
4847 assert_eq!(parsed.plugins.enabled, ["a", "b"]);
4848 }
4849
4850 #[test]
4853 fn setting_a_key_fills_the_empty_value_and_keeps_every_other_line() {
4854 let text = toml_set_string(&starter(), "provider", "base_url", "http://h:1/v1");
4855 let text = toml_set_string(&text, "provider", "model", "some-model");
4856 assert!(text.contains("base_url = \"http://h:1/v1\""), "{text}");
4857 assert!(text.contains("model = \"some-model\""), "{text}");
4858 assert!(text.contains("# Every setting this build reads"));
4860 assert!(text.contains("[agent]"));
4861 assert!(
4862 !text.contains("base_url = \"\""),
4863 "the empty blank must be gone: {text}"
4864 );
4865 let cfg: Config = toml::from_str(&text).expect("edited config must parse");
4867 assert_eq!(cfg.provider.base_url, "http://h:1/v1");
4868 assert_eq!(cfg.provider.model, "some-model");
4869 }
4870
4871 #[test]
4872 fn setting_a_key_turns_a_commented_template_line_into_the_real_one() {
4873 let text = toml_set_string(&starter(), "provider", "profile", "llamacpp");
4874 assert!(text.contains("\nprofile = \"llamacpp\""), "{text}");
4875 assert_eq!(
4876 text.matches("\nprofile = ").count(),
4877 1,
4878 "no duplicate key (the commented [web] default_profile is a different key): {text}"
4879 );
4880 let cfg: Config = toml::from_str(&text).unwrap();
4881 assert_eq!(cfg.provider.profile.as_deref(), Some("llamacpp"));
4882 }
4883
4884 #[test]
4885 fn setting_a_key_does_not_reach_into_another_section_with_the_same_name() {
4886 let text = toml_set_string(&starter(), "sessions", "dir", "/tmp/sessions-here");
4888 let cfg: Config = toml::from_str(&text).unwrap();
4889 assert_eq!(
4890 cfg.sessions.dir.as_deref(),
4891 Some(std::path::Path::new("/tmp/sessions-here"))
4892 );
4893 assert_eq!(cfg.plugins.dir, None, "{text}");
4894 }
4895
4896 #[test]
4897 fn setting_a_key_in_a_missing_section_adds_the_section() {
4898 let text = toml_set_string("[agent]\nmax_iterations = 5\n", "web", "host", "0.0.0.0");
4899 let cfg: Config = toml::from_str(&text).unwrap();
4900 assert_eq!(cfg.web.host, "0.0.0.0");
4901 assert_eq!(cfg.agent.max_iterations, 5);
4902 }
4903
4904 #[test]
4905 fn reading_a_key_sees_the_live_line_and_not_the_commented_one() {
4906 let text = starter();
4907 assert_eq!(
4908 toml_value(&text, "provider", "base_url"),
4909 Some(String::new())
4910 );
4911 assert_eq!(toml_value(&text, "provider", "temperature"), None);
4915 assert!(text.contains("# temperature ="), "{text}");
4916 assert_eq!(
4917 toml_value(&text, "agent", "max_iterations"),
4918 Some("unlimited".to_string()),
4919 "the cap is written, and its off value is the word `unlimited`"
4920 );
4921 }
4922
4923 #[test]
4927 fn a_dotenv_that_cannot_be_read_is_not_treated_as_an_empty_one() {
4928 let dir = tempfile::tempdir().unwrap();
4929 let dotenv = dir.path().join(".env");
4930 std::fs::create_dir(&dotenv).unwrap();
4931 std::fs::write(dotenv.join("ECLIPSE_WEB_AUTH_TOKEN"), "still here").unwrap();
4932
4933 let err = save_dotenv_var(&dotenv, "ECLIPSE_API_KEY", "sk-1").unwrap_err();
4934 let said = err.to_string();
4935 assert!(
4936 said.contains("nothing was written"),
4937 "the refusal says the file is untouched: {said}"
4938 );
4939 assert!(
4940 dotenv.is_dir(),
4941 "a failed save must not have replaced the path"
4942 );
4943 assert_eq!(
4944 std::fs::read_to_string(dotenv.join("ECLIPSE_WEB_AUTH_TOKEN")).unwrap(),
4945 "still here",
4946 "and nothing under it was touched"
4947 );
4948 }
4949
4950 #[test]
4952 fn a_line_break_in_a_value_is_refused_before_it_writes() {
4953 let dir = tempfile::tempdir().unwrap();
4954 let dotenv = dir.path().join(".env");
4955 std::fs::write(&dotenv, "ECLIPSE_WEB_AUTH_TOKEN=tok\n").unwrap();
4956
4957 let err = save_dotenv_var(&dotenv, "ECLIPSE_API_KEY", "sk-1\nECLIPSE_ADMIN=1").unwrap_err();
4958 assert!(err.to_string().contains("second assignment"), "{err}");
4959 assert_eq!(
4960 std::fs::read_to_string(&dotenv).unwrap(),
4961 "ECLIPSE_WEB_AUTH_TOKEN=tok\n",
4962 "a refused save leaves the file byte for byte"
4963 );
4964 }
4965
4966 #[test]
4969 fn a_save_keeps_every_other_line_and_the_loader_still_reads_them() {
4970 let dir = tempfile::tempdir().unwrap();
4971 let dotenv = dir.path().join(".env");
4972 let before = "# secrets\n\
4973 export ECLIPSE_WEB_USER='max h'\n\
4974 ECLIPSE_WEB_PASSWORD_HASH=\"pbkdf2$abc\"\n\
4975 ECLIPSE_API_KEY=first\n\
4976 ECLIPSE_API_KEY=second\n";
4977 std::fs::write(&dotenv, before).unwrap();
4978
4979 save_dotenv_var(&dotenv, "ECLIPSE_WEB_AUTH_TOKEN", "tok").unwrap();
4980
4981 let after = std::fs::read_to_string(&dotenv).unwrap();
4982 for line in before.lines() {
4983 assert!(after.contains(line), "{line:?} did not survive:\n{after}");
4984 }
4985 assert!(after.contains("ECLIPSE_WEB_AUTH_TOKEN=tok"), "{after}");
4986 }
4987
4988 #[test]
4991 fn dotenv_var_answers_what_the_loader_answers() {
4992 let dir = tempfile::tempdir().unwrap();
4993 let dotenv = dir.path().join(".env");
4994 std::fs::write(
4995 &dotenv,
4996 "A=first\nA=second\nexport B='quoted value'\nC=\"also quoted\"\nD=\n",
4997 )
4998 .unwrap();
4999
5000 assert_eq!(
5001 dotenv_var(&dotenv, "A").as_deref(),
5002 Some("second"),
5003 "the loader is last-wins, so the reader is too"
5004 );
5005 assert_eq!(dotenv_var(&dotenv, "B").as_deref(), Some("quoted value"));
5006 assert_eq!(dotenv_var(&dotenv, "C").as_deref(), Some("also quoted"));
5007 assert_eq!(
5008 dotenv_var(&dotenv, "D"),
5009 None,
5010 "an empty value is absence, as everywhere else"
5011 );
5012 assert_eq!(dotenv_var(&dotenv, "MISSING"), None);
5013 }
5014
5015 #[test]
5016 fn a_config_written_by_setup_is_private_and_a_dotenv_keeps_its_other_lines() {
5017 let dir = tempfile::tempdir().unwrap();
5018 let cfg_path = dir.path().join("config.toml");
5019 let dotenv = dir.path().join(".env");
5020 save_config_text(&cfg_path, "[provider]\nbase_url = \"h\"\n").unwrap();
5021 save_dotenv_var(&dotenv, "ECLIPSE_WEB_AUTH_TOKEN", "tok").unwrap();
5022 save_dotenv_var(&dotenv, "ECLIPSE_API_KEY", "sk-1").unwrap();
5023 save_dotenv_var(&dotenv, "ECLIPSE_API_KEY", "sk-2").unwrap();
5024 let body = std::fs::read_to_string(&dotenv).unwrap();
5025 assert_eq!(body.matches("ECLIPSE_API_KEY").count(), 1, "{body}");
5026 assert_eq!(
5027 dotenv_var(&dotenv, "ECLIPSE_API_KEY").as_deref(),
5028 Some("sk-2")
5029 );
5030 assert_eq!(
5031 dotenv_var(&dotenv, "ECLIPSE_WEB_AUTH_TOKEN").as_deref(),
5032 Some("tok"),
5033 "an unrelated secret must survive"
5034 );
5035 #[cfg(unix)]
5036 {
5037 use std::os::unix::fs::PermissionsExt;
5038 for f in [&cfg_path, &dotenv] {
5039 let mode = std::fs::metadata(f).unwrap().permissions().mode() & 0o777;
5040 assert_eq!(mode, 0o600, "{}", f.display());
5041 }
5042 }
5043 }
5044
5045 #[test]
5046 fn trace_content_is_off_by_default_and_can_be_set() {
5047 assert!(!Config::default().agent.trace_content);
5048 let cfg = Config::from_toml_str(
5049 "[agent]
5050trace_content = true
5051",
5052 )
5053 .unwrap();
5054 assert!(cfg.agent.trace_content);
5055 }
5056
5057 #[test]
5058 fn an_output_schema_is_absent_until_somebody_asks_for_one() {
5059 assert_eq!(Config::default().agent.output_schema, None);
5062 let cfg = Config::from_toml_str(
5063 "[agent]
5064output_schema = \"schemas/plan.json\"
5065",
5066 )
5067 .unwrap();
5068 assert_eq!(
5069 cfg.agent.output_schema.as_deref(),
5070 Some("schemas/plan.json")
5071 );
5072 }
5073
5074 #[test]
5075 fn the_user_section_has_the_defaults_the_docs_promise() {
5076 let cfg = Config::default();
5077 assert_eq!(cfg.user.file, "USER.md");
5078 assert_eq!(cfg.user.memory_file, "MEMORY.md");
5079 assert_eq!(cfg.user.memory_budget_chars, 3000);
5080 assert_eq!(
5081 cfg.agent.context_file_max_chars,
5082 crate::context_files::DEFAULT_MAX_FILE_CHARS
5083 );
5084 assert_eq!(
5085 cfg.agent.context_files_budget_chars,
5086 crate::context_files::DEFAULT_BUDGET_CHARS
5087 );
5088 }
5089
5090 #[test]
5091 fn the_context_and_memory_budgets_can_be_set_in_the_file() {
5092 let cfg = Config::from_toml_str(
5093 "[agent]\ncontext_file_max_chars = 100\ncontext_files_budget_chars = 200\n\
5094 [user]\nfile = \"WHO.md\"\nmemory_file = \"FACTS.md\"\nmemory_budget_chars = 50\n",
5095 )
5096 .unwrap();
5097 assert_eq!(cfg.agent.context_file_max_chars, 100);
5098 assert_eq!(cfg.agent.context_files_budget_chars, 200);
5099 assert_eq!(cfg.user.file, "WHO.md");
5100 assert_eq!(cfg.user.memory_file, "FACTS.md");
5101 assert_eq!(cfg.user.memory_budget_chars, 50);
5102 }
5103
5104 #[test]
5105 fn the_default_profile_keeps_its_files_in_the_config_directory() {
5106 let env = |k: &str| match k {
5107 "HOME" => Some("/home/m".to_string()),
5108 _ => None,
5109 };
5110 let mut cfg = Config::default();
5111 assert_eq!(
5112 cfg.context_dir(&env),
5113 Some(PathBuf::from("/home/m/.eclipse"))
5114 );
5115 cfg.profile = Some("work".into());
5116 assert_eq!(
5117 cfg.context_dir(&env),
5118 Some(PathBuf::from("/home/m/.eclipse/profiles/work"))
5119 );
5120 }
5121
5122 #[test]
5123 fn scripts_live_under_the_profile_when_there_is_one_and_the_config_directory_otherwise() {
5124 let env = |k: &str| match k {
5125 "HOME" => Some("/home/m".to_string()),
5126 _ => None,
5127 };
5128 let mut cfg = Config::default();
5129 assert_eq!(
5130 cfg.scripts_dir(&env),
5131 Some(PathBuf::from("/home/m/.eclipse/scripts"))
5132 );
5133 cfg.profile = Some("work".into());
5134 assert_eq!(
5135 cfg.scripts_dir(&env),
5136 Some(PathBuf::from("/home/m/.eclipse/profiles/work/scripts"))
5137 );
5138 let no_home = |_: &str| None;
5139 assert_eq!(Config::default().scripts_dir(&no_home), None);
5140 }
5141
5142 #[test]
5143 fn a_relative_config_path_still_gives_an_absolute_scripts_directory() {
5144 let env = |k: &str| match k {
5145 "ECLIPSE_CONFIG" => Some("rel/config.toml".to_string()),
5146 _ => None,
5147 };
5148 let dir = Config::default().scripts_dir(&env).unwrap();
5149 assert!(dir.is_absolute(), "{}", dir.display());
5150 assert!(dir.ends_with("rel/scripts"), "{}", dir.display());
5151 }
5152
5153 #[test]
5154 fn the_script_tool_is_asked_about_by_default_and_the_policy_can_be_set_in_the_file() {
5155 assert_eq!(Config::default().tools.script, Policy::Ask);
5156 let cfg = Config::from_toml_str("[tools]\nscript = \"deny\"\n").unwrap();
5157 assert_eq!(cfg.tools.script, Policy::Deny);
5158 let starter = Config::from_toml_str(&super::tests::starter()).unwrap();
5159 assert_eq!(starter.tools.script, Policy::Ask);
5160 assert!(Config::from_toml_str("[tools]\nscript = \"yolo\"\n").is_err());
5161 }
5162
5163 #[test]
5164 fn sight_defaults_to_auto_with_no_route_and_no_cloud() {
5165 let cfg = Config::default();
5166 assert_eq!(cfg.vision.mode, VisionMode::Auto);
5167 assert_eq!(cfg.vision.route, "");
5168 assert!(!cfg.vision.allow_cloud);
5169 }
5170
5171 #[test]
5172 fn the_three_vision_modes_are_spelled_in_the_file_the_way_a_person_says_them() {
5173 for (text, mode) in [
5174 ("native", VisionMode::Native),
5175 ("text", VisionMode::Text),
5176 ("auto", VisionMode::Auto),
5177 ] {
5178 let cfg = Config::from_toml_str(&format!("[vision]\nmode = \"{text}\"\n")).unwrap();
5179 assert_eq!(cfg.vision.mode, mode, "{text}");
5180 }
5181 }
5182
5183 #[test]
5184 fn a_vision_mode_nobody_implements_is_a_load_error_that_lists_the_three() {
5185 let err = Config::from_toml_str("[vision]\nmode = \"telepathy\"\n").unwrap_err();
5186 let sentence = err.to_string();
5187 assert!(sentence.contains("telepathy"), "{sentence}");
5188 assert!(sentence.contains("native"), "{sentence}");
5189 assert!(sentence.contains("text"), "{sentence}");
5190 assert!(sentence.contains("auto"), "{sentence}");
5191 }
5192
5193 #[test]
5194 fn a_vision_route_that_is_not_a_route_is_refused_by_name() {
5195 let cfg = Config::from_toml_str(
5196 "[provider]\nbase_url = \"http://127.0.0.1:1/v1\"\nmodel = \"m\"\n\
5197 [vision]\nroute = \"sight\"\n",
5198 )
5199 .unwrap();
5200 let err = cfg.validate_routes().unwrap_err().to_string();
5201 assert!(err.contains("vision.route"), "{err}");
5202 assert!(err.contains("sight"), "{err}");
5203 assert!(err.contains("default"), "{err}");
5204 }
5205
5206 #[test]
5207 fn a_vision_route_that_exists_validates() {
5208 let cfg = Config::from_toml_str(
5209 "[provider]\nbase_url = \"http://127.0.0.1:1/v1\"\nmodel = \"m\"\n\
5210 [vision]\nroute = \"default\"\n",
5211 )
5212 .unwrap();
5213 cfg.validate_routes().unwrap();
5214 assert_eq!(cfg.vision.route, "default");
5215 }
5216
5217 #[test]
5218 fn the_skills_budget_has_its_documented_default_and_can_be_set_in_the_file() {
5219 assert_eq!(Config::default().skills.index_budget_chars, 4000);
5220 let cfg = Config::from_toml_str("[skills]\nindex_budget_chars = 250\n").unwrap();
5221 assert_eq!(cfg.skills.index_budget_chars, 250);
5222 assert!(starter().contains("[skills]"));
5223 let starter = Config::from_toml_str(&super::tests::starter()).unwrap();
5224 assert_eq!(starter.skills.index_budget_chars, 4000);
5225 }
5226
5227 #[test]
5228 fn the_redacted_config_shows_the_skills_section() {
5229 let mut cfg = Config::default();
5230 cfg.skills.index_budget_chars = 123;
5231 let shown = cfg.to_toml_redacted().unwrap();
5232 assert!(shown.contains("[skills]"), "{shown}");
5233 assert!(shown.contains("index_budget_chars = 123"), "{shown}");
5234 }
5235
5236 #[test]
5237 fn the_starter_writes_the_context_file_settings() {
5238 let text = starter();
5239 let cfg = Config::from_toml_str(&text).unwrap();
5240 assert_eq!(cfg.user.memory_file, "MEMORY.md");
5241 for key in ["context_files_budget_chars", "[user]", "USER.md"] {
5242 assert!(text.contains(key), "the shipped file names `{key}`");
5243 }
5244 }
5245
5246 const TWO_ROUTES: &str = "\
5249[provider]
5250fallback = [\"local\", \"big\"]
5251[[provider.route]]
5252name = \"local\"
5253base_url = \"http://127.0.0.1:8081/v1\"
5254model = \"small\"
5255[[provider.route]]
5256name = \"big\"
5257base_url = \"http://10.0.0.2:8000/v1\"
5258model = \"large\"
5259api_key = \"hunter2\"
5260timeout_secs = 30
5261";
5262
5263 fn parse(text: &str) -> Config {
5264 Config::from_toml_str(text).unwrap()
5265 }
5266
5267 fn refusal(text: &str) -> String {
5268 let c = parse(text);
5269 c.validate_routes()
5270 .and_then(|_| c.chain().map(|_| ()))
5271 .unwrap_err()
5272 .to_string()
5273 }
5274
5275 #[test]
5276 fn a_route_is_a_full_provider_config_and_inherits_nothing_from_provider() {
5277 let c = parse(
5278 "[provider]\nbase_url=\"http://d/v1\"\nmodel=\"dm\"\ntimeout_secs=7\n\
5279 [[provider.route]]\nname=\"r\"\nbase_url=\"http://r/v1\"\nmodel=\"rm\"\n",
5280 );
5281 let r = c.declared_routes();
5282 assert_eq!(
5283 r.iter().map(|r| r.name.as_str()).collect::<Vec<_>>(),
5284 ["default", "r"],
5285 "[provider] is the route called default"
5286 );
5287 assert_eq!(r[0].config.timeout_secs, 7);
5288 assert_eq!(
5289 r[1].config.timeout_secs, 120,
5290 "the route got the built-in default, not [provider]'s 7"
5291 );
5292 }
5293
5294 #[test]
5295 fn provider_may_be_omitted_when_fallback_names_a_route() {
5296 let c = parse(TWO_ROUTES);
5297 c.validate_routes().unwrap();
5298 let chain = c.chain().unwrap();
5299 assert_eq!(chain.source, ChainSource::Fallback);
5300 let names: Vec<_> = chain.routes.iter().map(|r| r.name.as_str()).collect();
5301 assert_eq!(names, ["local", "big"]);
5302 assert_eq!(chain.routes[1].config.timeout_secs, 30);
5303 assert!(
5304 c.declared_routes().iter().all(|r| r.name != "default"),
5305 "no phantom default route appears"
5306 );
5307 }
5308
5309 #[test]
5310 fn a_provider_endpoint_left_out_of_the_chain_is_refused_not_ignored() {
5311 let text = r#"
5315[provider]
5316base_url = "https://api.example.com/v1"
5317model = "gpt"
5318fallback = ["local"]
5319
5320[[provider.route]]
5321name = "local"
5322base_url = "http://127.0.0.1:8080/v1"
5323model = "qwen3-coder"
5324"#;
5325 let err = parse(text).validate_routes().unwrap_err().to_string();
5326 assert!(err.contains("would never be called"), "{err}");
5327 assert!(
5328 err.contains("Put `default` first"),
5329 "it says what to type: {err}"
5330 );
5331 }
5332
5333 #[test]
5334 fn listing_default_first_puts_the_provider_endpoint_back_in_front() {
5335 let text = r#"
5336[provider]
5337base_url = "https://api.example.com/v1"
5338model = "gpt"
5339fallback = ["default", "local"]
5340
5341[[provider.route]]
5342name = "local"
5343base_url = "http://127.0.0.1:8080/v1"
5344model = "qwen3-coder"
5345"#;
5346 let c = parse(text);
5347 c.validate_routes().unwrap();
5348 let chain = c.chain().unwrap();
5349 let names: Vec<_> = chain.routes.iter().map(|r| r.name.as_str()).collect();
5350 assert_eq!(names, ["default", "local"]);
5351 assert_eq!(chain.routes[0].config.model, "gpt");
5352 }
5353
5354 #[test]
5355 fn a_provider_block_of_tuning_keys_alone_does_not_become_a_route() {
5356 let text = "\
5360[provider]
5361max_retries = 0
5362fallback = [\"local\", \"big\"]
5363[[provider.route]]
5364name = \"local\"
5365base_url = \"http://127.0.0.1:8081/v1\"
5366model = \"small\"
5367[[provider.route]]
5368name = \"big\"
5369base_url = \"http://127.0.0.1:8082/v1\"
5370model = \"large\"
5371";
5372 let c = parse(text);
5373 c.validate_routes().unwrap();
5374 let names: Vec<String> = c.declared_routes().into_iter().map(|r| r.name).collect();
5375 assert_eq!(names, ["local", "big"], "no phantom default route");
5376
5377 let mut pinned = parse(text);
5378 let e = pinned.pin_route(Some("default"), &|_| None).unwrap_err();
5379 let e = e.to_string();
5380 assert!(
5381 e.contains("unknown route `default`") && e.contains("local, big"),
5382 "{e}"
5383 );
5384 assert!(!e.contains("provider.base_url"), "{e}");
5385 }
5386
5387 #[test]
5388 fn two_routes_with_the_same_name_are_refused_naming_it() {
5389 let e = refusal(
5390 "[[provider.route]]\nname=\"a\"\nbase_url=\"u\"\nmodel=\"m\"\n\
5391 [[provider.route]]\nname=\"a\"\nbase_url=\"u\"\nmodel=\"m\"\n",
5392 );
5393 assert!(e.contains("`a`") && e.contains("unique"), "{e}");
5394 }
5395
5396 #[test]
5397 fn a_route_with_an_empty_or_missing_name_is_refused_by_position() {
5398 let e = refusal("[[provider.route]]\nname=\" \"\nbase_url=\"u\"\nmodel=\"m\"\n");
5399 assert!(
5400 e.contains("provider.route #1") && e.contains("no name"),
5401 "{e}"
5402 );
5403 let e = refusal("[[provider.route]]\nbase_url=\"u\"\nmodel=\"m\"\n");
5404 assert!(e.contains("provider.route #1"), "{e}");
5405 }
5406
5407 #[test]
5408 fn a_route_named_default_is_refused_only_when_provider_is_also_set() {
5409 let route = "[[provider.route]]\nname=\"default\"\nbase_url=\"u\"\nmodel=\"m\"\n";
5410 let e = refusal(&format!("[provider]\nbase_url=\"x\"\nmodel=\"y\"\n{route}"));
5411 assert!(e.contains("`default`") && e.contains("[provider]"), "{e}");
5412 let c = parse(&format!("[provider]\nfallback=[\"default\"]\n{route}"));
5413 assert_eq!(c.chain().unwrap().routes[0].name, "default");
5414 }
5415
5416 #[test]
5417 fn a_route_without_base_url_or_model_is_refused_naming_the_route() {
5418 let e = refusal("[[provider.route]]\nname=\"nourl\"\nmodel=\"m\"\n");
5419 assert!(e.contains("`nourl`") && e.contains("base_url"), "{e}");
5420 let e = refusal("[[provider.route]]\nname=\"nomodel\"\nbase_url=\"u\"\n");
5421 assert!(e.contains("`nomodel`") && e.contains("model"), "{e}");
5422 }
5423
5424 #[test]
5425 fn a_route_does_not_inherit_a_missing_base_url_from_provider() {
5426 let e = refusal(
5427 "[provider]\nbase_url=\"http://d/v1\"\nmodel=\"dm\"\n\
5428 [[provider.route]]\nname=\"r\"\nmodel=\"m\"\n",
5429 );
5430 assert!(e.contains("`r`") && e.contains("does not inherit"), "{e}");
5431 }
5432
5433 #[test]
5434 fn fallback_naming_a_route_that_does_not_exist_lists_the_ones_that_do() {
5435 let e = refusal(&TWO_ROUTES.replace("\"big\"]", "\"cloud\"]"));
5436 assert!(e.contains("`cloud`"), "{e}");
5437 assert!(e.contains("local, big"), "{e}");
5438 }
5439
5440 #[test]
5441 fn an_empty_fallback_is_a_typo_not_a_policy() {
5442 let e = refusal("[provider]\nfallback = []\n");
5443 assert!(e.contains("provider.fallback is empty"), "{e}");
5444 }
5445
5446 #[test]
5447 fn a_fallback_that_lists_a_route_twice_is_refused() {
5448 let e = refusal(&TWO_ROUTES.replace("[\"local\", \"big\"]", "[\"local\", \"local\"]"));
5449 assert!(e.contains("`local` twice"), "{e}");
5450 }
5451
5452 #[test]
5453 fn a_fallback_or_route_table_inside_a_route_is_refused() {
5454 let e = refusal(
5455 "[[provider.route]]\nname=\"r\"\nbase_url=\"u\"\nmodel=\"m\"\nfallback=[\"r\"]\n",
5456 );
5457 assert!(e.contains("`r`") && e.contains("directly"), "{e}");
5458 }
5459
5460 const WITH_AUX: &str = "\
5461[provider]
5462base_url = \"http://d/v1\"
5463model = \"dm\"
5464aux = \"cheap\"
5465[[provider.route]]
5466name = \"cheap\"
5467base_url = \"http://c/v1\"
5468model = \"cm\"
5469";
5470
5471 #[test]
5472 fn aux_names_a_route_and_the_role_table_says_so() {
5473 let chain = parse(WITH_AUX).chain().unwrap();
5474 assert_eq!(chain.aux.as_ref().map(|r| r.name.as_str()), Some("cheap"));
5475 assert_eq!(chain.aux.unwrap().config.model, "cm");
5476 let roles = parse(WITH_AUX).chain().unwrap().roles();
5477 assert_eq!(roles.len(), 2, "only roles that exist get a row");
5478 assert_eq!(roles[0].to_string(), "judgement \u{2192} cheap");
5479 assert_eq!(
5480 roles[1].to_string(),
5481 "delegate \u{2192} default (no delegate route set)"
5482 );
5483 }
5484
5485 #[test]
5486 fn delegate_names_a_route_and_the_role_table_says_so() {
5487 let c = parse(&WITH_AUX.replace("aux = \"cheap\"", "delegate = \"cheap\""));
5488 let chain = c.chain().unwrap();
5489 assert_eq!(
5490 chain.delegate.as_ref().map(|r| r.name.as_str()),
5491 Some("cheap")
5492 );
5493 assert!(chain.aux.is_none());
5494 let roles = chain.roles();
5495 assert_eq!(
5496 roles[0].to_string(),
5497 "judgement \u{2192} default (no aux route set)"
5498 );
5499 assert_eq!(roles[1].to_string(), "delegate \u{2192} cheap");
5500 }
5501
5502 #[test]
5503 fn a_pin_overrules_the_aux_and_delegate_routes_and_the_role_table_says_pinned() {
5504 let mut c =
5507 parse(&WITH_AUX.replace("aux = \"cheap\"", "aux = \"cheap\"\ndelegate = \"cheap\""));
5508 c.pin_route(Some("cheap"), &|_| None).unwrap();
5509 let chain = c.chain().unwrap();
5510 assert_eq!(chain.source, ChainSource::Pinned);
5511 assert_eq!(
5512 chain.aux.as_ref().map(|r| r.name.as_str()),
5513 Some("cheap"),
5514 "the pinned route, not the key's own value"
5515 );
5516 assert_eq!(
5517 chain.delegate.as_ref().map(|r| r.name.as_str()),
5518 Some("cheap")
5519 );
5520 for role in chain.roles() {
5521 assert!(role.pinned, "{role} should be pinned");
5522 assert!(!role.set, "{role} should not claim the key decided it");
5523 assert_eq!(role.route, "cheap");
5524 assert!(role.to_string().ends_with("(pinned)"), "{role}");
5525 }
5526
5527 let c =
5529 parse(&WITH_AUX.replace("aux = \"cheap\"", "aux = \"cheap\"\ndelegate = \"cheap\""));
5530 let chain = c.chain().unwrap();
5531 assert!(chain.roles().iter().all(|r| r.set && !r.pinned));
5532 }
5533
5534 #[test]
5535 fn an_unknown_empty_or_nested_delegate_route_is_refused_with_the_routes_that_exist() {
5536 let e = refusal(&WITH_AUX.replace("aux = \"cheap\"", "delegate = \"ghost\""));
5537 assert!(
5538 e.contains("provider.delegate names `ghost`") && e.contains("default, cheap"),
5539 "{e}"
5540 );
5541 let c = parse(&WITH_AUX.replace("aux = \"cheap\"", "delegate = \"\""));
5543 c.validate_routes()
5544 .expect("an empty delegate is a config that loads");
5545 let e = refusal(
5546 "[[provider.route]]\nname=\"r\"\nbase_url=\"u\"\nmodel=\"m\"\ndelegate=\"r\"\n\
5547 [provider]\nfallback=[\"r\"]\n",
5548 );
5549 assert!(
5550 e.contains("`r`") && e.contains("`delegate`") && e.contains("directly"),
5551 "{e}"
5552 );
5553 let e = Config::from_toml_str("[provider]\ndelegate = 3\n").unwrap_err();
5554 assert!(e.contains("delegate"), "{e}");
5555 }
5556
5557 #[test]
5558 fn the_delegate_tool_is_asked_about_by_default_and_the_policy_can_be_set_in_the_file() {
5559 assert_eq!(Config::default().tools.delegate, Policy::Ask);
5560 let cfg = Config::from_toml_str("[tools]\ndelegate = \"deny\"\n").unwrap();
5561 assert_eq!(cfg.tools.delegate, Policy::Deny);
5562 let starter = Config::from_toml_str(&super::tests::starter()).unwrap();
5563 assert_eq!(starter.tools.delegate, Policy::Ask);
5564 assert!(Config::from_toml_str("[tools]\ndelegate = \"yolo\"\n").is_err());
5565 }
5566
5567 #[test]
5568 fn with_no_aux_the_summary_role_uses_the_selected_route_and_says_it_was_not_set() {
5569 let chain = parse(TWO_ROUTES).chain().unwrap();
5570 assert!(chain.aux.is_none());
5571 assert_eq!(
5572 chain.roles()[0].to_string(),
5573 "judgement \u{2192} local (no aux route set)"
5574 );
5575 let bare = parse("[provider]\nbase_url=\"u\"\nmodel=\"m\"\n");
5576 assert_eq!(
5577 bare.chain().unwrap().roles()[0].to_string(),
5578 "judgement \u{2192} default (no aux route set)"
5579 );
5580 }
5581
5582 #[test]
5583 fn an_unknown_aux_route_is_refused_listing_the_routes_that_exist() {
5584 let e = refusal(&WITH_AUX.replace("aux = \"cheap\"", "aux = \"ghost\""));
5585 assert!(
5586 e.contains("provider.aux names `ghost`") && e.contains("default, cheap"),
5587 "{e}"
5588 );
5589 let c = parse(&WITH_AUX.replace("aux = \"cheap\"", "aux = \"\""));
5593 c.validate_routes()
5594 .expect("an empty aux route is a config that loads");
5595 assert!(c.chain().unwrap().aux.is_none());
5596 }
5597
5598 #[test]
5599 fn aux_inside_a_route_is_refused_like_fallback_and_route() {
5600 let e = refusal(
5601 "[[provider.route]]\nname=\"r\"\nbase_url=\"u\"\nmodel=\"m\"\naux=\"r\"\n\
5602 [provider]\nfallback=[\"r\"]\n",
5603 );
5604 assert!(
5605 e.contains("`r`") && e.contains("`aux`") && e.contains("directly"),
5606 "{e}"
5607 );
5608 }
5609
5610 #[test]
5611 fn a_wrong_typed_aux_is_an_error_naming_the_key() {
5612 let e = Config::from_toml_str("[provider]\naux = 3\n").unwrap_err();
5613 assert!(e.contains("aux"), "{e}");
5614 }
5615
5616 #[test]
5617 fn aux_may_name_the_default_route_when_provider_is_one() {
5618 let c = parse(&WITH_AUX.replace("aux = \"cheap\"", "aux = \"default\""));
5619 assert_eq!(c.chain().unwrap().aux.unwrap().name, "default");
5620 let tuning_only = "[provider]\naux = \"default\"\nmax_retries = 1\n\
5621 [[provider.route]]\nname=\"r\"\nbase_url=\"u\"\nmodel=\"m\"\n";
5622 assert!(refusal(tuning_only).contains("Routes that exist: r"));
5623 }
5624
5625 #[test]
5626 fn a_wrong_typed_route_value_is_an_error_and_not_a_default() {
5627 let bad =
5628 "[[provider.route]]\nname=\"r\"\nbase_url=\"u\"\nmodel=\"m\"\ntimeout_secs=\"soon\"\n";
5629 let e = Config::from_toml_str(bad).unwrap_err();
5630 assert!(e.contains("timeout_secs") || e.contains("soon"), "{e}");
5631 let e = Config::from_toml_str("[provider]\nfallback = \"local\"\n").unwrap_err();
5632 assert!(e.contains("fallback") || e.contains("sequence"), "{e}");
5633 }
5634
5635 #[test]
5636 fn routes_with_no_fallback_and_no_pin_say_what_to_set() {
5637 let e = refusal("[[provider.route]]\nname=\"r\"\nbase_url=\"u\"\nmodel=\"m\"\n");
5638 assert!(
5639 e.contains("fallback") && e.contains("--route") && e.contains("r"),
5640 "{e}"
5641 );
5642 }
5643
5644 #[test]
5645 fn with_no_fallback_and_no_pin_the_chain_is_the_default_route_alone() {
5646 let c = parse(
5647 "[provider]\nbase_url=\"http://d/v1\"\nmodel=\"dm\"\n\
5648 [[provider.route]]\nname=\"r\"\nbase_url=\"u\"\nmodel=\"m\"\n",
5649 );
5650 let chain = c.chain().unwrap();
5651 assert_eq!(chain.source, ChainSource::Default);
5652 assert_eq!(chain.routes.len(), 1);
5653 assert_eq!(chain.routes[0].name, "default");
5654 let bare = parse("[provider]\nbase_url=\"http://d/v1\"\nmodel=\"dm\"\n");
5655 assert_eq!(bare.chain().unwrap().source, ChainSource::Default);
5656 }
5657
5658 #[test]
5659 fn a_bare_config_still_says_what_is_wrong_with_provider() {
5660 let e = Config::default()
5661 .require_provider()
5662 .unwrap_err()
5663 .to_string();
5664 assert!(e.contains("provider.base_url is not set"), "{e}");
5665 assert!(e.contains("eclipse config init"), "{e}");
5666 let c = parse("[provider]\nbase_url=\"u\"\n");
5667 assert!(c
5668 .require_provider()
5669 .unwrap_err()
5670 .to_string()
5671 .contains("provider.model is not set"));
5672 }
5673
5674 #[test]
5675 fn a_pin_selects_one_route_and_marks_the_chain_pinned() {
5676 let mut c = parse(TWO_ROUTES);
5677 c.pin_route(Some("big"), &env_of(&[])).unwrap();
5678 let chain = c.chain().unwrap();
5679 assert_eq!(chain.source, ChainSource::Pinned);
5680 assert_eq!(chain.routes.len(), 1);
5681 assert_eq!(chain.routes[0].name, "big");
5682 }
5683
5684 #[test]
5685 fn an_unknown_pin_lists_the_routes_that_exist() {
5686 let mut c = parse(TWO_ROUTES);
5687 let e = c
5688 .pin_route(Some("nope"), &env_of(&[]))
5689 .unwrap_err()
5690 .to_string();
5691 assert!(e.contains("`nope`") && e.contains("local, big"), "{e}");
5692 let e = c
5693 .pin_route(Some(" "), &env_of(&[]))
5694 .unwrap_err()
5695 .to_string();
5696 assert!(e.contains("--route needs a route name"), "{e}");
5697 }
5698
5699 #[test]
5700 fn eclipse_route_is_honoured_when_the_flag_is_absent_and_the_flag_wins() {
5701 let mut c = parse(TWO_ROUTES);
5702 c.pin_route(None, &env_of(&[("ECLIPSE_ROUTE", "big")]))
5703 .unwrap();
5704 assert_eq!(c.route_pin.as_deref(), Some("big"));
5705 c.pin_route(Some("local"), &env_of(&[("ECLIPSE_ROUTE", "big")]))
5706 .unwrap();
5707 assert_eq!(c.route_pin.as_deref(), Some("local"));
5708 let mut c = parse(TWO_ROUTES);
5709 c.dotenv
5710 .values
5711 .insert("ECLIPSE_ROUTE".into(), "local".into());
5712 c.pin_route(None, &env_of(&[])).unwrap();
5713 assert_eq!(
5714 c.route_pin.as_deref(),
5715 Some("local"),
5716 "the .env chain counts too"
5717 );
5718 let mut c = parse(TWO_ROUTES);
5719 c.pin_route(None, &env_of(&[])).unwrap();
5720 assert_eq!(c.route_pin, None);
5721 }
5722
5723 #[test]
5724 fn a_route_takes_its_key_from_its_own_api_key_env_and_eclipse_api_key_is_default_only() {
5725 let mut c = parse(
5726 "[provider]\nbase_url=\"http://d/v1\"\nmodel=\"dm\"\n\
5727 [[provider.route]]\nname=\"r\"\nbase_url=\"u\"\nmodel=\"m\"\napi_key_env=\"R_KEY\"\n",
5728 );
5729 c.apply_env(&env_of(&[
5730 ("R_KEY", "from-r"),
5731 ("ECLIPSE_API_KEY", "for-default"),
5732 ]));
5733 assert_eq!(c.provider.api_key.as_deref(), Some("for-default"));
5734 assert_eq!(
5735 c.provider.route[0].config.api_key.as_deref(),
5736 Some("from-r")
5737 );
5738
5739 let mut only_routes = parse(TWO_ROUTES);
5740 only_routes.apply_env(&env_of(&[("ECLIPSE_API_KEY", "stray")]));
5741 assert_eq!(
5742 only_routes.provider.api_key, None,
5743 "no phantom default route"
5744 );
5745 assert_eq!(only_routes.provider.route[0].config.api_key, None);
5746 }
5747
5748 #[test]
5749 fn the_redacted_config_hides_every_routes_key_and_round_trips() {
5750 let c = parse(TWO_ROUTES);
5751 let t = c.to_toml_redacted().unwrap();
5752 assert!(!t.contains("hunter2"), "{t}");
5753 assert!(
5754 t.contains("[[provider.route]]") && t.contains("<redacted>"),
5755 "{t}"
5756 );
5757 let back = parse(&t);
5758 assert_eq!(back.provider.fallback, c.provider.fallback);
5759 assert_eq!(back.provider.route.len(), 2);
5760 assert_eq!(back.provider.route[1].config.timeout_secs, 30);
5761 }
5762
5763 #[test]
5764 fn a_config_without_routes_prints_no_provider_route_keys() {
5765 let c = parse("[provider]\nbase_url=\"u\"\nmodel=\"m\"\n");
5768 let t = c.to_toml_redacted().unwrap();
5769 let parsed: toml::Value = toml::from_str(&t).unwrap();
5770 let provider = parsed.get("provider").expect("a provider table");
5771 for absent in ["route", "fallback", "aux", "delegate"] {
5772 assert!(
5773 provider.get(absent).is_none(),
5774 "`provider.{absent}` printed for a config with one route: {t}"
5775 );
5776 }
5777 }
5778
5779 #[test]
5780 fn a_bad_route_table_is_refused_when_the_config_is_loaded() {
5781 let tmp = tempfile::tempdir().unwrap();
5782 let path = tmp.path().join("c.toml");
5783 std::fs::write(&path, "[provider]\nfallback = [\"ghost\"]\n").unwrap();
5784 let e = Config::load_with(Some(&path), &env_of(&[]))
5785 .unwrap_err()
5786 .to_string();
5787 assert!(e.contains("`ghost`"), "{e}");
5788 }
5789
5790 #[test]
5791 fn context_policy_defaults_and_the_rail_it_derives() {
5792 let c = ContextPolicyConfig::default();
5793 assert!(
5794 c.judge,
5795 "the model half is the judgement pass, and it ships on: compile plus one bounded call"
5796 );
5797 assert_eq!(c.judge_timeout_secs, 20, "and it cannot hang the turn");
5798 assert_eq!(c.compact_at, 0.85);
5799 assert_eq!(c.protect_last_n, 20, "the tail keeps twenty turns");
5800 assert_eq!(c.window_tokens, 0, "no window is invented");
5801 assert_eq!(c.budget_for(0), 0, "no window, no rail");
5802 assert_eq!(c.budget_for(327_680), 278_528);
5803 let off = ContextPolicyConfig {
5804 compact_at: 0.0,
5805 ..c.clone()
5806 };
5807 assert_eq!(off.budget_for(327_680), 0, "compact_at = 0 is off");
5808 let half = ContextPolicyConfig {
5809 compact_at: 0.5,
5810 ..c
5811 };
5812 assert_eq!(half.budget_for(131_072), 65_536);
5813 }
5814
5815 #[test]
5816 fn a_compact_at_outside_the_window_is_a_config_error_naming_the_key() {
5817 for bad in ["1.5", "-0.2"] {
5818 let c = parse(&format!("[context]\ncompact_at = {bad}\n"));
5819 let err = c.context.validate().unwrap_err().to_string();
5820 assert!(
5821 err.contains("context.compact_at"),
5822 "{bad} must be named in the error: {err}"
5823 );
5824 }
5825 assert!(parse("[context]\ncompact_at = 0.6\n")
5826 .context
5827 .validate()
5828 .is_ok());
5829 assert!(parse("[context]\ncompact_at = 0\n")
5830 .context
5831 .validate()
5832 .is_ok());
5833 }
5834}
5835
5836#[cfg(test)]
5837mod mcp_editor_tests {
5838 use super::*;
5839 use crate::mcp::Spec;
5840
5841 fn spec(text: &str) -> Spec {
5842 toml::from_str(text).unwrap()
5843 }
5844
5845 fn add(spec: &Spec) -> String {
5846 let out = mcp_add(CONFIG, spec).unwrap();
5847 parse_text(&out).unwrap();
5849 out
5850 }
5851
5852 const CONFIG: &str = r#"# my config
5853[provider]
5854base_url = "http://127.0.0.1:8081/v1"
5855model = "m"
5856
5857# this comment belongs to the first entry
5858[[mcp]]
5859name = "first"
5860command = "one"
5861
5862# and this one to the second
5863[[mcp]]
5864name = "second"
5865command = "two"
5866policy = "allow"
5867"#;
5868
5869 #[test]
5870 fn an_added_entry_reads_back_and_leaves_the_comments_alone() {
5871 let out = add(&spec(
5872 "name = \"third\"\ncommand = \"three\"\nargs = [\"--x\"]\nprefix = \"t_\"\n",
5873 ));
5874 let cfg = parse_text(&out).unwrap();
5875 assert_eq!(
5876 cfg.mcp.iter().map(|s| s.name.as_str()).collect::<Vec<_>>(),
5877 ["first", "second", "third"]
5878 );
5879 let third = cfg.mcp.iter().find(|s| s.name == "third").unwrap();
5880 assert_eq!(third.args, ["--x"]);
5881 assert_eq!(third.prefix, "t_");
5882 for line in [
5884 "# my config",
5885 "# this comment belongs to the first entry",
5886 "# and this one to the second",
5887 ] {
5888 assert!(out.contains(line), "lost {line:?}:\n{out}");
5889 }
5890 assert!(
5891 out.contains("[[mcp]]\nname = \"first\"\ncommand = \"one\""),
5892 "{out}"
5893 );
5894 assert!(
5895 !out.contains("args = []"),
5896 "only what was set is written:\n{out}"
5897 );
5898 }
5899
5900 #[test]
5901 fn a_duplicate_name_is_refused_and_named_by_line() {
5902 let err = mcp_add(CONFIG, &spec("name = \"first\"\ncommand = \"again\"")).unwrap_err();
5903 assert!(err.contains("already declared at line 7"), "{err}");
5904 }
5905
5906 #[test]
5907 fn an_unusable_entry_is_refused_before_anything_is_written() {
5908 let err = mcp_add(
5910 CONFIG,
5911 &spec("name = \"bad\"\ntransport = \"http\"\ncommand = \"x\"\nurl = \"http://h/mcp\""),
5912 )
5913 .unwrap_err();
5914 assert!(err.starts_with("that entry is not usable"), "{err}");
5915 assert!(err.contains("belong to the stdio transport"), "{err}");
5916 }
5917
5918 #[test]
5919 fn remove_takes_the_named_block_and_the_blank_line_after_it() {
5920 let out = mcp_remove(CONFIG, "first").unwrap();
5921 let cfg = parse_text(&out).unwrap();
5922 assert_eq!(
5923 cfg.mcp.iter().map(|s| s.name.as_str()).collect::<Vec<_>>(),
5924 ["second"]
5925 );
5926 assert!(out.contains("# and this one to the second"), "{out}");
5928 assert!(!out.contains("name = \"first\""), "{out}");
5929 assert!(!out.contains("\n\n\n"), "no hole left behind:\n{out}");
5930 }
5931
5932 #[test]
5933 fn remove_says_what_the_file_does_declare() {
5934 let err = mcp_remove(CONFIG, "nope").unwrap_err();
5935 assert!(err.contains("declares first, second"), "{err}");
5936 let bare = "[provider]\nbase_url = \"http://d/v1\"\nmodel = \"m\"\n";
5937 let err = mcp_remove(bare, "nope").unwrap_err();
5938 assert!(err.contains("no `[[mcp]]` entry for `nope`"), "{err}");
5939 }
5940
5941 #[test]
5942 fn disable_flips_the_line_inside_its_own_block() {
5943 let off = mcp_set_disabled(CONFIG, "second", true).unwrap();
5944 let cfg = parse_text(&off).unwrap();
5945 assert!(
5946 cfg.mcp
5947 .iter()
5948 .find(|s| s.name == "second")
5949 .unwrap()
5950 .disabled
5951 );
5952 assert!(!cfg.mcp.iter().find(|s| s.name == "first").unwrap().disabled);
5953 let second_at = off.find("name = \"second\"").unwrap();
5955 let tail = &off[second_at..];
5956 assert!(tail.contains("disabled = true"), "{off}");
5957 assert!(tail.find("disabled").unwrap() < tail.find("\n[[").unwrap_or(tail.len()));
5958
5959 let on = mcp_set_disabled(&off, "second", false).unwrap();
5960 let cfg = parse_text(&on).unwrap();
5961 assert!(
5962 !cfg.mcp
5963 .iter()
5964 .find(|s| s.name == "second")
5965 .unwrap()
5966 .disabled
5967 );
5968 assert!(
5969 on.contains("disabled = false"),
5970 "said out loud, not deleted:\n{on}"
5971 );
5972 }
5973
5974 #[test]
5975 fn disable_on_an_entry_without_the_key_inserts_one() {
5976 let off = mcp_set_disabled(CONFIG, "first", true).unwrap();
5977 assert!(off.contains("command = \"one\"\ndisabled = true"), "{off}");
5978 assert!(parse_text(&off).unwrap().mcp[0].disabled);
5979 }
5980
5981 #[test]
5985 fn an_edit_changes_the_changed_line_and_leaves_every_other_byte_alone() {
5986 let out = mcp_update(CONFIG, "second", |entry| entry.prefix = "t_".into()).unwrap();
5987 parse_text(&out).unwrap();
5988 assert_eq!(
5989 out,
5990 CONFIG.replace(
5991 "command = \"two\"\npolicy = \"allow\"",
5992 "command = \"two\"\npolicy = \"allow\"\nprefix = \"t_\""
5993 ),
5994 "one added line, and not one other character moved:\n{out}"
5995 );
5996 }
5997
5998 #[test]
6001 fn an_edit_sets_and_clears_token_env_without_touching_the_rest() {
6002 let on = mcp_update(CONFIG, "second", |entry| {
6003 entry.token_env = Some("HA_TOKEN".into())
6004 })
6005 .unwrap();
6006 assert_eq!(
6007 on,
6008 CONFIG.replace(
6009 "command = \"two\"\npolicy = \"allow\"",
6010 "command = \"two\"\npolicy = \"allow\"\ntoken_env = \"HA_TOKEN\""
6011 ),
6012 "{on}"
6013 );
6014 let off = mcp_update(&on, "second", |entry| entry.token_env = None).unwrap();
6015 assert_eq!(
6016 off, CONFIG,
6017 "clearing a field removes its line and nothing else"
6018 );
6019 }
6020
6021 #[test]
6024 fn an_edit_keeps_a_comment_written_inside_the_block() {
6025 let inner = "[[mcp]]\nname = \"a\"\n# the endpoint is on the box\ncommand = \"x\"\n";
6026 let out = mcp_update(inner, "a", |entry| {
6027 entry.args = vec!["--y".into()];
6028 })
6029 .unwrap();
6030 assert_eq!(
6031 out,
6032 "[[mcp]]\nname = \"a\"\n# the endpoint is on the box\ncommand = \"x\"\n\
6033 args = [\"--y\"]\n",
6034 "{out}"
6035 );
6036 }
6037
6038 #[test]
6040 fn an_edit_refuses_a_rename_and_names_what_the_file_declares() {
6041 let err = mcp_update(CONFIG, "second", |entry| entry.name = "renamed".into()).unwrap_err();
6042 assert!(err.contains("an edit does not rename"), "{err}");
6043
6044 let err = mcp_update(CONFIG, "nope", |_| {}).unwrap_err();
6045 assert!(err.contains("declares first, second"), "{err}");
6046
6047 let err = mcp_update(CONFIG, "second", |entry| {
6049 entry.transport = crate::mcp::Transport::Http;
6050 entry.url = Some("http://h/mcp".into());
6051 })
6052 .unwrap_err();
6053 assert!(err.starts_with("that entry is not usable"), "{err}");
6054 assert!(err.contains("belong to the stdio transport"), "{err}");
6055 }
6056
6057 #[test]
6058 fn an_empty_file_gets_its_first_entry_cleanly() {
6059 let out = mcp_add("", &spec("name = \"only\"\ncommand = \"x\"")).unwrap();
6060 assert!(out.starts_with("[[mcp]]\n"), "{out:?}");
6061 assert_eq!(parse_text(&out).unwrap().mcp[0].name, "only");
6062 }
6063
6064 #[test]
6065 fn a_second_entry_is_separated_by_exactly_one_blank_line() {
6066 let out = add(&spec("name = \"third\"\ncommand = \"three\""));
6067 assert!(!out.contains("\n\n\n"), "{out}");
6068 assert!(
6069 out.contains("policy = \"allow\"\n\n[[mcp]]\nname = \"third\""),
6070 "{out}"
6071 );
6072 }
6073}