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 state_dir_for(env: EnvFn, profile: Option<&str>) -> Option<PathBuf> {
208 match profile {
209 None | Some("default") => state_dir(env),
210 Some(name) => profile_dir(env, name).map(|d| d.join("state")),
211 }
212}
213
214fn expand_tilde(p: &Path, env: EnvFn) -> PathBuf {
215 if let Ok(rest) = p.strip_prefix("~") {
216 if let Some(h) = home_dir(env) {
217 return h.join(rest);
218 }
219 }
220 p.to_path_buf()
221}
222
223#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
226#[serde(rename_all = "lowercase")]
227pub enum FetchHtml {
228 Text,
230 Raw,
232}
233
234#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
236#[serde(rename_all = "lowercase")]
237pub enum ShellIsolate {
238 Off,
240 Process,
243 Fs,
247}
248
249impl std::fmt::Display for ShellIsolate {
250 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
251 f.write_str(match self {
252 Self::Off => "off",
253 Self::Process => "process",
254 Self::Fs => "fs",
255 })
256 }
257}
258
259#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
260#[serde(rename_all = "lowercase")]
261pub enum Policy {
262 Deny,
264 Ask,
268 Allow,
270}
271
272#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
274#[serde(rename_all = "lowercase")]
275pub enum ShellAsk {
276 #[default]
278 Dangerous,
279 Always,
282}
283
284#[derive(Clone, Default, PartialEq, Eq)]
294pub struct Dotenv {
295 pub files: Vec<PathBuf>,
297 pub values: BTreeMap<String, String>,
298}
299
300impl fmt::Debug for Dotenv {
301 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
302 f.debug_struct("Dotenv")
307 .field("files", &self.files)
308 .field("keys", &self.values.keys().collect::<Vec<_>>())
309 .finish()
310 }
311}
312
313impl Dotenv {
314 pub fn load(env: EnvFn<'_>, profile: Option<&str>) -> Result<Dotenv> {
316 let Some(dir) = config_dir(env) else {
317 return Ok(Dotenv::default());
318 };
319 let mut candidates = vec![dir.join(".env")];
320 if let Some(p) = profile {
321 validate_profile_name(p)?;
322 candidates.push(dir.join("profiles").join(p).join(".env"));
323 }
324 let mut values = BTreeMap::new();
325 let mut files = Vec::new();
326 for path in candidates {
327 if !path.exists() {
328 continue;
329 }
330 for assignment in crate::dotenv::load(&path)? {
336 if assignment.value.is_empty() {
337 values.remove(&assignment.key);
338 continue;
339 }
340 values.insert(assignment.key, assignment.value);
341 }
342 files.push(path);
343 }
344 Ok(Dotenv { files, values })
345 }
346}
347
348fn empty_is_none<'de, D>(d: D) -> std::result::Result<Option<String>, D::Error>
357where
358 D: serde::Deserializer<'de>,
359{
360 use serde::Deserialize;
361 Ok(Option::<String>::deserialize(d)?.filter(|v| !v.is_empty()))
362}
363
364#[derive(Clone, PartialEq, Serialize, Deserialize)]
365#[serde(default)]
366pub struct ProviderConfig {
367 pub base_url: String,
369 #[serde(deserialize_with = "empty_is_none")]
371 pub api_key: Option<String>,
372 #[serde(deserialize_with = "empty_is_none")]
374 pub api_key_env: Option<String>,
375 pub model: String,
376 pub temperature: Option<f64>,
377 pub timeout_secs: u64,
378 pub stream: bool,
381 pub max_retries: u32,
390 pub retry_after_send: bool,
395 pub retry_base_delay_ms: u64,
396 pub context_budget_tokens: usize,
400 pub max_tokens: Option<u32>,
403 #[serde(deserialize_with = "empty_is_none")]
406 pub profile: Option<String>,
407 pub top_p: Option<f64>,
410 pub seed: Option<i64>,
412 pub stop: Option<Vec<String>>,
414 #[serde(deserialize_with = "empty_is_none")]
419 pub reasoning_effort: Option<String>,
420 pub parallel_tool_calls: Option<bool>,
422 pub vision: Option<bool>,
427 pub tool_choice: Option<crate::hooks::ToolChoice>,
430 pub extra_body: Option<serde_json::Value>,
434 #[serde(skip_serializing_if = "Option::is_none")]
438 pub fallback: Option<Vec<String>>,
439 #[serde(skip_serializing_if = "Option::is_none")]
443 #[serde(deserialize_with = "empty_is_none")]
444 pub aux: Option<String>,
445 #[serde(skip_serializing_if = "Option::is_none")]
449 #[serde(deserialize_with = "empty_is_none")]
450 pub delegate: Option<String>,
451 #[serde(skip_serializing_if = "Vec::is_empty")]
454 pub route: Vec<RouteConfig>,
455}
456
457#[derive(Debug, Clone, PartialEq, Serialize)]
463pub struct RouteConfig {
464 pub name: String,
466 #[serde(skip_serializing_if = "Option::is_none")]
472 pub max_parallel: Option<usize>,
473 #[serde(skip_serializing_if = "Option::is_none")]
478 pub group: Option<String>,
479 #[serde(flatten)]
480 pub config: ProviderConfig,
481}
482
483impl<'de> Deserialize<'de> for RouteConfig {
487 fn deserialize<D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Self, D::Error> {
488 use serde::de::Error as _;
489 let mut table = toml::Table::deserialize(d)?;
490 let name = match table.remove("name") {
491 None => String::new(),
492 Some(toml::Value::String(name)) => name,
493 Some(other) => {
494 return Err(D::Error::custom(format!(
495 "provider.route `name` must be a string, got {}",
496 other.type_str()
497 )))
498 }
499 };
500 let label = if name.is_empty() {
501 "an unnamed route".to_string()
502 } else {
503 format!("route `{name}`")
504 };
505 let max_parallel = match table.remove("max_parallel") {
509 None => None,
510 Some(toml::Value::Integer(n)) if n >= 0 => Some(n as usize),
511 Some(other) => {
512 return Err(D::Error::custom(format!(
513 "{label}: `max_parallel` must be a positive integer, got {}",
514 other.type_str()
515 )))
516 }
517 };
518 let group = match table.remove("group") {
519 None => None,
520 Some(toml::Value::String(g)) if !g.trim().is_empty() => Some(g),
521 Some(_) => {
522 return Err(D::Error::custom(format!(
523 "{label}: `group` must be a non-empty string"
524 )))
525 }
526 };
527 let config = ProviderConfig::deserialize(toml::Value::Table(table))
528 .map_err(|e| D::Error::custom(format!("{label}: {e}")))?;
529 Ok(Self {
530 name,
531 max_parallel,
532 group,
533 config,
534 })
535 }
536}
537
538pub const DEFAULT_ROUTE: &str = "default";
540
541impl ProviderConfig {
542 fn declares_connection(&self) -> bool {
551 !self.base_url.trim().is_empty()
552 || !self.model.trim().is_empty()
553 || self.api_key.is_some()
554 || self.api_key_env.is_some()
555 }
556}
557
558#[derive(Debug, Clone, PartialEq)]
561pub struct NamedRoute {
562 pub name: String,
563 pub max_parallel: Option<usize>,
565 pub group: Option<String>,
567 pub config: ProviderConfig,
568}
569
570impl NamedRoute {
571 pub fn default_parallel(&self) -> usize {
576 let profile = self.config.profile.as_deref().unwrap_or("openai");
577 if profile.eq_ignore_ascii_case("openai") {
578 4
579 } else {
580 1
581 }
582 }
583
584 pub fn parallel(&self) -> usize {
586 self.max_parallel
587 .unwrap_or_else(|| self.default_parallel())
588 .max(1)
589 }
590
591 pub fn with_flare_shape(mut self, max_parallel: Option<usize>, group: Option<String>) -> Self {
594 self.max_parallel = max_parallel;
595 self.group = group;
596 self
597 }
598
599 fn new(name: &str, config: &ProviderConfig) -> Self {
600 let mut config = config.clone();
601 config.route.clear();
602 config.fallback = None;
603 config.aux = None;
604 config.delegate = None;
605 Self {
606 name: name.to_string(),
607 max_parallel: None,
608 group: None,
609 config,
610 }
611 }
612
613 fn require_endpoint(&self, source: ChainSource) -> Result<()> {
615 let plain = self.name == DEFAULT_ROUTE && source == ChainSource::Default;
616 let missing = |key: &str, hint: &str| {
617 Error::Config(if plain {
618 format!("provider.{key} is not set {hint}")
619 } else {
620 format!("route `{}` has no {key}", self.name)
621 })
622 };
623 if self.config.base_url.trim().is_empty() {
624 return Err(missing(
625 "base_url",
626 "(config file or ECLIPSE_BASE_URL); run `eclipse config init`",
627 ));
628 }
629 if self.config.model.trim().is_empty() {
630 return Err(missing("model", "(config file or ECLIPSE_MODEL)"));
631 }
632 Ok(())
633 }
634}
635
636#[derive(Debug, Clone, Copy, PartialEq, Eq)]
638pub enum ChainSource {
639 Default,
641 Fallback,
643 Pinned,
645}
646
647#[derive(Debug, Clone, PartialEq)]
649pub struct Chain {
650 pub routes: Vec<NamedRoute>,
651 pub source: ChainSource,
652 pub aux: Option<NamedRoute>,
654 pub delegate: Option<NamedRoute>,
656}
657
658impl Chain {
659 pub fn roles(&self) -> Vec<crate::router::RoleRoute> {
661 crate::router::role_table(
662 self.aux.as_ref().map(|r| r.name.as_str()),
663 self.delegate.as_ref().map(|r| r.name.as_str()),
664 self.routes.first().map_or("", |r| r.name.as_str()),
665 self.source == ChainSource::Pinned,
666 )
667 }
668}
669
670fn apply_key_env(cfg: &mut ProviderConfig, env: EnvFn, explicit: Option<String>) {
673 if let Some(v) = explicit {
674 cfg.api_key = Some(v);
675 } else if let Some(name) = cfg.api_key_env.clone() {
676 if let Some(v) = env(&name) {
677 cfg.api_key = Some(v);
678 }
679 }
680}
681
682impl Default for ProviderConfig {
683 fn default() -> Self {
684 Self {
685 base_url: String::new(),
686 api_key: None,
687 api_key_env: None,
688 model: String::new(),
689 temperature: None,
690 timeout_secs: 120,
691 stream: true,
692 max_retries: 3,
693 retry_after_send: false,
694 retry_base_delay_ms: 2000,
695 context_budget_tokens: 0,
696 max_tokens: None,
697 profile: None,
698 top_p: None,
699 seed: None,
700 stop: None,
701 reasoning_effort: None,
702 parallel_tool_calls: None,
703 vision: None,
704 tool_choice: None,
705 extra_body: None,
706 fallback: None,
707 aux: None,
708 delegate: None,
709 route: Vec::new(),
710 }
711 }
712}
713
714impl fmt::Debug for ProviderConfig {
715 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
716 f.debug_struct("ProviderConfig")
717 .field(
720 "base_url",
721 &redact_url(&self.base_url).unwrap_or_else(|| self.base_url.clone()),
722 )
723 .field("api_key", &self.api_key.as_ref().map(|_| "<redacted>"))
724 .field("api_key_env", &self.api_key_env)
725 .field("model", &self.model)
726 .field("temperature", &self.temperature)
727 .field("timeout_secs", &self.timeout_secs)
728 .field("stream", &self.stream)
729 .field("max_retries", &self.max_retries)
730 .field("retry_after_send", &self.retry_after_send)
731 .field("retry_base_delay_ms", &self.retry_base_delay_ms)
732 .field("context_budget_tokens", &self.context_budget_tokens)
733 .field("vision", &self.vision)
734 .field("fallback", &self.fallback)
735 .field("aux", &self.aux)
736 .field("delegate", &self.delegate)
737 .field("route", &self.route)
738 .finish()
739 }
740}
741
742#[derive(Debug, Clone, Serialize, Deserialize)]
743#[serde(default)]
744pub struct AgentConfig {
745 pub max_consecutive_malformed_tool_calls: usize,
749 pub system_prompt: String,
750 #[serde(
755 default = "unlimited_turns",
756 deserialize_with = "de_turn_limit",
757 serialize_with = "ser_turn_limit"
758 )]
759 pub max_iterations: usize,
760 #[serde(deserialize_with = "empty_is_none")]
764 pub output_schema: Option<String>,
765 pub context_file_max_chars: usize,
768 pub context_files_budget_chars: usize,
771 pub trace_content: bool,
774 pub prompt_blocks: crate::prompt_blocks::Choice,
778}
779
780fn unlimited_turns() -> usize {
783 usize::MAX
784}
785
786fn de_turn_limit<'de, D>(d: D) -> std::result::Result<usize, D::Error>
790where
791 D: serde::Deserializer<'de>,
792{
793 #[derive(serde::Deserialize)]
794 #[serde(untagged)]
795 enum Raw {
796 Number(i64),
797 Word(String),
798 }
799 let n = match Raw::deserialize(d)? {
800 Raw::Number(n) => n,
801 Raw::Word(word) => match word.trim().to_ascii_lowercase().as_str() {
802 "unlimited" | "none" | "null" | "inf" | "infinite" | "infinity" | "∞" => 0,
803 other => other.parse::<i64>().map_err(|_| {
804 serde::de::Error::custom(format!(
805 "`max_iterations` takes a whole number or `unlimited`, not `{other}`"
806 ))
807 })?,
808 },
809 };
810 Ok(if n <= 0 {
811 unlimited_turns()
812 } else {
813 n as usize
814 })
815}
816
817fn ser_turn_limit<S>(value: &usize, s: S) -> std::result::Result<S::Ok, S::Error>
820where
821 S: serde::Serializer,
822{
823 if *value == usize::MAX {
824 s.serialize_str("unlimited")
825 } else {
826 s.serialize_u64(*value as u64)
827 }
828}
829
830impl Default for AgentConfig {
831 fn default() -> Self {
832 Self {
833 system_prompt:
834 "You are a helpful personal assistant running locally on the user's machine. \
835Use tools only when they are needed, and explain briefly what you did."
836 .into(),
837 max_iterations: unlimited_turns(),
838 output_schema: None,
839 max_consecutive_malformed_tool_calls: 0,
840 context_file_max_chars: crate::context_files::DEFAULT_MAX_FILE_CHARS,
841 context_files_budget_chars: crate::context_files::DEFAULT_BUDGET_CHARS,
842 trace_content: false,
843 prompt_blocks: crate::prompt_blocks::Choice::Auto,
844 }
845 }
846}
847
848#[derive(Debug, Clone, Serialize, Deserialize)]
849#[serde(default)]
850pub struct ToolsConfig {
851 pub workspace_root: Option<PathBuf>,
853 pub read_file: Policy,
854 pub search_files: Policy,
858 pub write_file: Policy,
859 #[serde(default = "default_rewrite_guard")]
864 pub rewrite_guard_bytes: usize,
865 pub patch: Policy,
868 pub memory: Policy,
873 pub shell: Policy,
874 pub fetch: Policy,
875 pub script: Policy,
879 pub execute_code: Policy,
884 pub delegate: Policy,
888 pub shell_ask: ShellAsk,
892 pub shell_timeout_secs: u64,
893 pub shell_allowlist: Vec<String>,
895 pub shell_isolate: ShellIsolate,
900 pub shell_isolate_writable: Vec<PathBuf>,
903 pub shell_isolate_hide: Vec<PathBuf>,
906 pub shell_isolate_network: bool,
909 pub fetch_timeout_secs: u64,
910 pub fetch_html: FetchHtml,
913 pub max_output_bytes: usize,
915 pub concurrency: usize,
919 pub disabled: Vec<String>,
923 #[serde(default = "default_deferred")]
936 pub deferred: Vec<String>,
937 pub tool_search: Policy,
942 pub tool_describe: Policy,
943 pub tool_call: Policy,
944}
945
946fn default_hidden_paths() -> Vec<PathBuf> {
953 ["~/.ssh", "~/.gnupg", "~/.aws", "~/.hermes"]
954 .iter()
955 .map(PathBuf::from)
956 .collect()
957}
958
959fn default_deferred() -> Vec<String> {
967 vec!["plugin:mcp:*".to_string(), "config:mcp:*".to_string()]
968}
969
970fn default_rewrite_guard() -> usize {
971 32 * 1024
972}
973
974impl Default for ToolsConfig {
975 fn default() -> Self {
976 Self {
977 workspace_root: None,
978 read_file: Policy::Allow,
979 search_files: Policy::Allow,
980 write_file: Policy::Allow,
984 rewrite_guard_bytes: default_rewrite_guard(),
985 patch: Policy::Allow,
986 memory: Policy::Ask,
987 shell: Policy::Ask,
988 fetch: Policy::Ask,
989 script: Policy::Ask,
990 execute_code: Policy::Ask,
991 delegate: Policy::Ask,
992 shell_ask: ShellAsk::Dangerous,
993 shell_timeout_secs: 30,
994 shell_allowlist: Vec::new(),
995 shell_isolate: ShellIsolate::Process,
996 shell_isolate_writable: Vec::new(),
997 shell_isolate_hide: default_hidden_paths(),
998 shell_isolate_network: true,
999 fetch_timeout_secs: 20,
1000 fetch_html: FetchHtml::Text,
1001 max_output_bytes: 32 * 1024,
1002 concurrency: 1,
1003 disabled: Vec::new(),
1004 deferred: default_deferred(),
1005 tool_search: Policy::Allow,
1006 tool_describe: Policy::Allow,
1007 tool_call: Policy::Allow,
1008 }
1009 }
1010}
1011
1012#[derive(Debug, Clone, Serialize, Deserialize)]
1013#[serde(default)]
1014pub struct SessionsConfig {
1015 pub dir: Option<PathBuf>,
1017 pub retention_keep_days: u64,
1020 pub retention_keep_count: usize,
1023 pub auto_prune: bool,
1028 pub lock_wait_secs: u64,
1031 pub autotitle: bool,
1035}
1036
1037impl Default for SessionsConfig {
1038 fn default() -> Self {
1039 Self {
1040 dir: None,
1041 retention_keep_days: 0,
1042 retention_keep_count: 0,
1043 auto_prune: false,
1044 lock_wait_secs: 30,
1045 autotitle: true,
1046 }
1047 }
1048}
1049
1050#[derive(Clone, Serialize, Deserialize)]
1051#[serde(default)]
1052pub struct WebConfig {
1053 pub host: String,
1054 pub port: u16,
1055 #[serde(deserialize_with = "empty_is_none")]
1058 pub auth_token: Option<String>,
1059 pub session_ttl_hours: u64,
1062 #[serde(deserialize_with = "empty_is_none")]
1065 pub default_profile: Option<String>,
1066}
1067
1068impl Default for WebConfig {
1069 fn default() -> Self {
1070 Self {
1071 host: "127.0.0.1".into(),
1072 port: 8787,
1073 auth_token: None,
1074 session_ttl_hours: DEFAULT_SESSION_TTL_HOURS,
1075 default_profile: None,
1076 }
1077 }
1078}
1079
1080#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1082#[serde(default)]
1083pub struct GatewayConfig {
1084 pub check_interval_hours: u64,
1088 #[serde(default = "default_api_session_ttl_hours")]
1092 pub api_session_ttl_hours: u64,
1093}
1094
1095pub fn default_api_session_ttl_hours() -> u64 {
1096 24
1097}
1098
1099impl Default for GatewayConfig {
1100 fn default() -> Self {
1101 Self {
1102 check_interval_hours: 6,
1103 api_session_ttl_hours: default_api_session_ttl_hours(),
1104 }
1105 }
1106}
1107
1108pub const DEFAULT_SESSION_TTL_HOURS: u64 = 12;
1110
1111#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
1113#[serde(rename_all = "lowercase")]
1114pub enum Approval {
1115 #[default]
1117 Ask,
1118 Auto,
1120 Smart,
1126}
1127
1128#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1131#[serde(default)]
1132pub struct CliConfig {
1133 pub color: Option<bool>,
1135 pub markdown: Option<bool>,
1137 pub approval: Approval,
1140 pub history_size: usize,
1142 pub clear_on_exit: ClearOnExit,
1144}
1145
1146impl Default for CliConfig {
1147 fn default() -> Self {
1148 Self {
1149 color: None,
1150 markdown: None,
1151 approval: Approval::Ask,
1152 history_size: 1000,
1154 clear_on_exit: ClearOnExit::Screen,
1155 }
1156 }
1157}
1158
1159#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
1165#[serde(rename_all = "lowercase")]
1166pub enum ClearOnExit {
1167 #[default]
1170 Screen,
1171 All,
1173 Off,
1175}
1176
1177#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
1179#[serde(rename_all = "lowercase")]
1180pub enum UpdateCheck {
1181 #[default]
1183 Daily,
1184 Weekly,
1185 Off,
1187}
1188
1189impl UpdateCheck {
1190 pub fn period_secs(self) -> Option<u64> {
1192 match self {
1193 UpdateCheck::Daily => Some(86_400),
1194 UpdateCheck::Weekly => Some(7 * 86_400),
1195 UpdateCheck::Off => None,
1196 }
1197 }
1198}
1199
1200#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
1207#[serde(rename_all = "lowercase")]
1208pub enum Track {
1209 #[default]
1212 Release,
1213 Develop,
1215}
1216
1217impl Track {
1218 pub fn label(self) -> &'static str {
1220 match self {
1221 Track::Release => "release",
1222 Track::Develop => "develop",
1223 }
1224 }
1225
1226 pub fn branch(self) -> &'static str {
1229 match self {
1230 Track::Release => "main",
1231 Track::Develop => "develop",
1232 }
1233 }
1234}
1235
1236#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1242#[serde(default)]
1243pub struct HooksConfig {
1244 pub order: Vec<String>,
1245 #[serde(flatten)]
1248 pub settings: BTreeMap<String, toml::Value>,
1249}
1250
1251impl Default for HooksConfig {
1252 fn default() -> Self {
1253 Self {
1254 order: crate::hooks::DEFAULT_ORDER
1255 .iter()
1256 .map(|n| n.to_string())
1257 .collect(),
1258 settings: BTreeMap::new(),
1259 }
1260 }
1261}
1262
1263#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1266#[serde(default)]
1267pub struct UpdateConfig {
1268 pub check: UpdateCheck,
1269 pub track: Track,
1275 #[serde(deserialize_with = "empty_is_none")]
1280 pub remote: Option<String>,
1281 #[serde(deserialize_with = "empty_is_none")]
1286 pub releases: Option<String>,
1287}
1288
1289impl fmt::Debug for WebConfig {
1290 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1291 f.debug_struct("WebConfig")
1292 .field("host", &self.host)
1293 .field("port", &self.port)
1294 .field(
1295 "auth_token",
1296 &self.auth_token.as_ref().map(|_| "<redacted>"),
1297 )
1298 .finish()
1299 }
1300}
1301
1302#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1308#[serde(default)]
1309pub struct AttachmentsConfig {
1310 pub dir: Option<PathBuf>,
1314 pub max_total_bytes: u64,
1318}
1319
1320impl Default for AttachmentsConfig {
1321 fn default() -> Self {
1322 Self {
1323 dir: None,
1324 max_total_bytes: 2 * 1024 * 1024 * 1024,
1325 }
1326 }
1327}
1328
1329#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1330#[serde(default)]
1331pub struct Config {
1332 pub config_version: u32,
1339 pub provider: ProviderConfig,
1340 pub agent: AgentConfig,
1341 pub tools: ToolsConfig,
1342 pub sessions: SessionsConfig,
1343 pub attachments: AttachmentsConfig,
1344 pub plugins: PluginsConfig,
1345 pub web: WebConfig,
1346 pub gateway: GatewayConfig,
1347 pub cli: CliConfig,
1348 pub update: UpdateConfig,
1349 pub hooks: HooksConfig,
1350 pub context: ContextPolicyConfig,
1351 pub user: UserConfig,
1352 pub skills: SkillsConfig,
1353 pub vision: VisionConfig,
1354 #[serde(skip)]
1357 pub profile: Option<String>,
1358 #[serde(skip)]
1361 pub route_pin: Option<String>,
1362 #[serde(skip)]
1365 pub dotenv: Dotenv,
1366 #[serde(default)]
1371 pub mcp: Vec<crate::mcp::Spec>,
1372 #[serde(skip)]
1376 pub no_mcp: bool,
1377 #[serde(default)]
1379 pub flares: FlaresConfig,
1380 #[serde(default)]
1384 pub bots: std::collections::BTreeMap<String, BotConfig>,
1385}
1386
1387#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1393#[serde(default)]
1394pub struct FlaresConfig {
1395 pub count: usize,
1398 pub max_concurrent: usize,
1400 pub max_iterations: usize,
1402 pub total_iterations: usize,
1405 pub total_tokens: Option<u64>,
1407}
1408
1409impl Default for FlaresConfig {
1410 fn default() -> Self {
1411 Self {
1412 count: 3,
1413 max_concurrent: 4,
1414 max_iterations: 6,
1415 total_iterations: 24,
1416 total_tokens: None,
1417 }
1418 }
1419}
1420
1421impl FlaresConfig {
1422 pub fn concurrency(&self) -> usize {
1425 self.max_concurrent.max(1)
1426 }
1427
1428 pub fn per_flare(&self) -> usize {
1430 self.max_iterations.max(1)
1431 }
1432
1433 pub fn budget(&self) -> usize {
1437 self.total_iterations.max(1)
1438 }
1439}
1440
1441#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1448#[serde(default)]
1449pub struct BotConfig {
1450 pub instructions: Option<String>,
1454 pub skills: Option<Vec<String>>,
1458 pub memory: Option<String>,
1462 pub adapter: Option<String>,
1465}
1466
1467pub const BOT_ADAPTERS: &[&str] = &[];
1471
1472#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1475#[serde(default)]
1476pub struct ContextPolicyConfig {
1477 pub compact_at: f64,
1480 pub protect_last_n: usize,
1482 pub judge: bool,
1486 pub judge_timeout_secs: u64,
1488 pub window_tokens: usize,
1491 pub handoff_chars: usize,
1494}
1495
1496impl Default for ContextPolicyConfig {
1497 fn default() -> Self {
1498 Self {
1499 compact_at: 0.85,
1500 protect_last_n: crate::context::DEFAULT_PROTECT_LAST_N,
1501 judge: true,
1502 judge_timeout_secs: 20,
1503 window_tokens: 0,
1504 handoff_chars: 6_000,
1505 }
1506 }
1507}
1508
1509impl ContextPolicyConfig {
1510 pub fn budget_for(&self, window_tokens: usize) -> usize {
1512 if window_tokens == 0 || self.compact_at.is_nan() || self.compact_at <= 0.0 {
1513 return 0;
1514 }
1515 (window_tokens as f64 * self.compact_at) as usize
1516 }
1517
1518 pub fn validate(&self) -> Result<()> {
1521 if !(0.0..=1.0).contains(&self.compact_at) {
1522 return Err(Error::Config(format!(
1523 "context.compact_at: {} is not a share of the window; use 0.85 for 85%, or 0 to \
1524 turn the threshold off",
1525 self.compact_at
1526 )));
1527 }
1528 if self.handoff_chars < 200 {
1529 return Err(Error::Config(format!(
1530 "context.handoff_chars: {} is too small to compile a handoff; 200 is the floor \
1531 and 6000 is the default",
1532 self.handoff_chars
1533 )));
1534 }
1535 Ok(())
1536 }
1537}
1538
1539#[derive(Debug, Clone, Serialize, Deserialize)]
1541#[serde(default)]
1542pub struct UserConfig {
1543 pub file: String,
1545 pub memory_file: String,
1547 pub memory_budget_chars: usize,
1550}
1551
1552impl Default for UserConfig {
1553 fn default() -> Self {
1554 Self {
1555 file: "USER.md".into(),
1556 memory_file: "MEMORY.md".into(),
1557 memory_budget_chars: crate::memory::DEFAULT_BUDGET_CHARS,
1558 }
1559 }
1560}
1561
1562#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1569#[serde(default)]
1570pub struct VisionConfig {
1571 #[serde(default)]
1574 pub mode: VisionMode,
1575 #[serde(default)]
1578 pub route: String,
1579 #[serde(default)]
1582 pub allow_cloud: bool,
1583}
1584
1585#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
1587#[serde(rename_all = "lowercase")]
1588pub enum VisionMode {
1589 Native,
1591 Text,
1593 #[default]
1595 Auto,
1596}
1597
1598#[derive(Debug, Clone, Serialize, Deserialize)]
1599#[serde(default)]
1600pub struct SkillsConfig {
1601 pub index_budget_chars: usize,
1604}
1605
1606impl Default for SkillsConfig {
1607 fn default() -> Self {
1608 Self {
1609 index_budget_chars: crate::skills::DEFAULT_INDEX_BUDGET_CHARS,
1610 }
1611 }
1612}
1613
1614#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1616#[serde(default)]
1617pub struct PluginsConfig {
1618 pub dir: Option<PathBuf>,
1621 pub enabled: Vec<String>,
1623 pub mcp_timeout_secs: Option<u64>,
1626}
1627
1628impl Config {
1629 pub fn load(explicit: Option<&Path>) -> Result<Config> {
1632 Self::load_with(explicit, &process_env)
1633 }
1634
1635 pub fn load_with(explicit: Option<&Path>, env: EnvFn) -> Result<Config> {
1636 Self::load_with_profile(explicit, None, env)
1637 }
1638
1639 pub fn load_with_profile(
1648 explicit: Option<&Path>,
1649 profile: Option<&str>,
1650 env: EnvFn,
1651 ) -> Result<Config> {
1652 let profile = profile
1653 .map(str::to_string)
1654 .or_else(|| env("ECLIPSE_PROFILE"))
1655 .filter(|p| !p.trim().is_empty());
1656 if let Some(name) = &profile {
1657 validate_profile_name(name)?;
1658 }
1659 let dotenv = Dotenv::load(env, profile.as_deref())?;
1662 let lookup = |k: &str| {
1668 env(k).or_else(|| {
1669 dotenv
1670 .values
1671 .get(k)
1672 .filter(|v| !v.is_empty())
1673 .map(String::as_str)
1674 .map(str::to_string)
1675 })
1676 };
1677 let lookup: EnvFn<'_> = &lookup;
1678
1679 let base_path = match explicit {
1680 Some(p) => Some(p.to_path_buf()),
1681 None => config_path(env).filter(|p| p.exists()),
1682 };
1683 let mut hooks_path = base_path.clone();
1685 let mut value = match &base_path {
1686 Some(p) => {
1687 let mut parsed = read_toml(p)?;
1688 crate::interpolate::in_value(&mut parsed, p, lookup)?;
1689 parsed
1690 }
1691 None => toml::Value::try_from(Config::default())
1692 .map_err(|e| Error::Config(e.to_string()))?,
1693 };
1694 if let Some(name) = &profile {
1695 if let Some(dir) = profile_dir(env, name) {
1696 let overlay = dir.join("config.toml");
1697 if overlay.exists() {
1698 let mut over = read_toml(&overlay)?;
1699 crate::interpolate::in_value(&mut over, &overlay, lookup)?;
1702 if over.get("hooks").is_some() {
1703 hooks_path = Some(overlay.clone());
1704 }
1705 merge_toml(&mut value, over);
1706 }
1707 }
1708 }
1709 let mut cfg: Config = value
1710 .try_into()
1711 .map_err(|e: toml::de::Error| Error::Parse {
1712 path: base_path.unwrap_or_else(|| PathBuf::from("<defaults>")),
1713 message: e.to_string(),
1714 })?;
1715 cfg.profile = profile;
1716 cfg.apply_env(lookup);
1717 cfg.dotenv = dotenv;
1718 cfg.validate_routes()?;
1721 cfg.context.validate()?;
1722 cfg.validate_bots()?;
1725 crate::hooks::validate(&cfg.hooks).map_err(|message| Error::Parse {
1726 path: hooks_path.unwrap_or_else(|| PathBuf::from("<defaults>")),
1727 message,
1728 })?;
1729 Ok(cfg)
1730 }
1731
1732 pub fn profile_name(&self) -> &str {
1734 self.profile.as_deref().unwrap_or("default")
1735 }
1736
1737 pub fn state_dir(&self, env: EnvFn) -> Result<PathBuf> {
1739 state_dir_for(env, self.profile.as_deref())
1740 .ok_or_else(|| Error::Config("cannot determine state dir: HOME is not set".into()))
1741 }
1742
1743 pub fn plugins_dirs(&self, env: EnvFn) -> Vec<PathBuf> {
1747 let mut out = Vec::new();
1748 if let Some(name) = &self.profile {
1749 if let Some(dir) = profile_dir(env, name) {
1750 out.push(dir.join("plugins"));
1751 }
1752 }
1753 let shared = match &self.plugins.dir {
1754 Some(p) => expand_tilde(p, env),
1755 None => match config_dir(env) {
1756 Some(d) => d.join("plugins"),
1757 None => return out,
1758 },
1759 };
1760 if !out.contains(&shared) {
1761 out.push(shared);
1762 }
1763 out
1764 }
1765
1766 pub fn from_file(path: &Path) -> Result<Config> {
1767 let text = std::fs::read_to_string(path).map_err(|e| Error::io(path, e))?;
1768 Self::from_toml_str(&text).map_err(|message| Error::Parse {
1769 path: path.to_path_buf(),
1770 message,
1771 })
1772 }
1773
1774 pub fn from_toml_str(text: &str) -> std::result::Result<Config, String> {
1775 toml::from_str(text).map_err(|e| e.to_string())
1776 }
1777
1778 pub fn apply_env(&mut self, env: EnvFn) {
1784 if let Some(v) = env("ECLIPSE_BASE_URL") {
1785 self.provider.base_url = v;
1786 }
1787 if let Some(v) = env("ECLIPSE_MODEL") {
1788 self.provider.model = v;
1789 }
1790 if self.provider.declares_connection() {
1793 apply_key_env(&mut self.provider, env, env("ECLIPSE_API_KEY"));
1794 }
1795 for route in &mut self.provider.route {
1796 apply_key_env(&mut route.config, env, None);
1797 }
1798 }
1799
1800 pub fn to_toml_redacted(&self) -> Result<String> {
1806 let mut value = toml::Value::try_from(self).map_err(|e| Error::Config(e.to_string()))?;
1807 redact(&mut value);
1808 toml::to_string_pretty(&value).map_err(|e| Error::Config(e.to_string()))
1809 }
1810
1811 pub fn require_provider(&self) -> Result<()> {
1813 self.chain().map(|_| ())
1814 }
1815
1816 pub fn declared_routes(&self) -> Vec<NamedRoute> {
1821 let mut out = Vec::new();
1822 if self.provider.route.is_empty() || self.provider.declares_connection() {
1823 out.push(NamedRoute::new(DEFAULT_ROUTE, &self.provider));
1824 }
1825 out.extend(self.provider.route.iter().map(|r| {
1826 NamedRoute::new(&r.name, &r.config).with_flare_shape(r.max_parallel, r.group.clone())
1827 }));
1828 out
1829 }
1830
1831 pub fn route_names(&self) -> String {
1833 let names: Vec<String> = self.declared_routes().into_iter().map(|r| r.name).collect();
1834 if names.is_empty() {
1835 "none".to_string()
1836 } else {
1837 names.join(", ")
1838 }
1839 }
1840
1841 pub fn validate_routes(&self) -> Result<()> {
1848 let p = &self.provider;
1849 let mut seen: Vec<&str> = Vec::new();
1850 for (i, r) in p.route.iter().enumerate() {
1851 let name = r.name.trim();
1852 if name.is_empty() {
1853 return Err(Error::Config(format!(
1854 "provider.route #{} has no name; every [[provider.route]] needs `name = \"...\"`",
1855 i + 1
1856 )));
1857 }
1858 if seen.contains(&name) {
1859 return Err(Error::Config(format!(
1860 "two routes are named `{name}`; route names must be unique"
1861 )));
1862 }
1863 seen.push(name);
1864 if name == DEFAULT_ROUTE && p.declares_connection() {
1865 return Err(Error::Config(format!(
1866 "a route is named `{DEFAULT_ROUTE}`, but `[provider]` is also set and is the \
1867 route of that name; rename the route, or move its settings out of [provider]"
1868 )));
1869 }
1870 if r.config.fallback.is_some()
1871 || r.config.aux.is_some()
1872 || r.config.delegate.is_some()
1873 || !r.config.route.is_empty()
1874 {
1875 return Err(Error::Config(format!(
1876 "route `{name}` has its own `fallback`, `aux`, `delegate` or `route`; those \
1877 belong directly under [provider], not inside a route"
1878 )));
1879 }
1880 if r.config.base_url.trim().is_empty() {
1881 return Err(Error::Config(format!(
1882 "route `{name}` has no base_url; a route is a complete provider \
1883 configuration and does not inherit from [provider]"
1884 )));
1885 }
1886 if r.config.model.trim().is_empty() {
1887 return Err(Error::Config(format!(
1888 "route `{name}` has no model; a route is a complete provider \
1889 configuration and does not inherit from [provider]"
1890 )));
1891 }
1892 }
1893 if let Some(fallback) = &p.fallback {
1894 if fallback.is_empty() {
1895 return Err(Error::Config(
1896 "provider.fallback is empty; name the routes to try in order, or remove the \
1897 key to use `default` alone"
1898 .into(),
1899 ));
1900 }
1901 let known: Vec<String> = self.declared_routes().into_iter().map(|r| r.name).collect();
1902 let mut listed: Vec<&str> = Vec::new();
1903 for name in fallback {
1904 if !known.contains(name) {
1905 return Err(Error::Config(format!(
1906 "provider.fallback names `{name}`, which is not a route. Routes that \
1907 exist: {}",
1908 self.route_names()
1909 )));
1910 }
1911 if listed.contains(&name.as_str()) {
1912 return Err(Error::Config(format!(
1913 "provider.fallback lists `{name}` twice; each route is tried at most \
1914 once per run"
1915 )));
1916 }
1917 listed.push(name);
1918 }
1919 if p.declares_connection() && !listed.contains(&DEFAULT_ROUTE) {
1924 return Err(Error::Config(
1925 "`[provider]` sets a connection, but provider.fallback is the whole chain \
1926 and does not list `default`, so that endpoint would never be called. Put \
1927 `default` first in `fallback`, or move the connection keys into a route \
1928 and leave `[provider]` to `fallback` alone"
1929 .into(),
1930 ));
1931 }
1932 }
1933 if let Some(aux) = &p.aux {
1934 if aux.trim().is_empty() {
1935 return Err(Error::Config(
1936 "provider.aux is empty; name the route that does housekeeping, or remove \
1937 the key to use the route the run is on"
1938 .into(),
1939 ));
1940 }
1941 if !self.declared_routes().iter().any(|r| &r.name == aux) {
1942 return Err(Error::Config(format!(
1943 "provider.aux names `{aux}`, which is not a route. Routes that exist: {}",
1944 self.route_names()
1945 )));
1946 }
1947 }
1948 if let Some(delegate) = &p.delegate {
1949 if delegate.trim().is_empty() {
1950 return Err(Error::Config(
1951 "provider.delegate is empty; name the route subagents run on, or remove \
1952 the key to use the route the run is on"
1953 .into(),
1954 ));
1955 }
1956 if !self.declared_routes().iter().any(|r| &r.name == delegate) {
1957 return Err(Error::Config(format!(
1958 "provider.delegate names `{delegate}`, which is not a route. Routes that \
1959 exist: {}",
1960 self.route_names()
1961 )));
1962 }
1963 }
1964 let vision_route = self.vision.route.trim();
1968 if !vision_route.is_empty()
1969 && !self
1970 .declared_routes()
1971 .iter()
1972 .any(|r| r.name == vision_route)
1973 {
1974 return Err(Error::Config(format!(
1975 "vision.route names `{vision_route}`, which is not a route. Routes that exist: {}",
1976 self.route_names()
1977 )));
1978 }
1979 Ok(())
1980 }
1981
1982 pub fn pin_route(&mut self, flag: Option<&str>, env: EnvFn) -> Result<()> {
1988 let wanted = match flag {
1989 Some(name) if name.trim().is_empty() => {
1990 return Err(Error::Config(
1991 "--route needs a route name; `eclipse config show` lists them".into(),
1992 ))
1993 }
1994 Some(name) => Some(name.trim().to_string()),
1995 None => env("ECLIPSE_ROUTE")
1996 .or_else(|| self.dotenv.values.get("ECLIPSE_ROUTE").cloned())
1997 .map(|v| v.trim().to_string())
1998 .filter(|v| !v.is_empty()),
1999 };
2000 if let Some(name) = &wanted {
2001 if !self.declared_routes().iter().any(|r| &r.name == name) {
2002 return Err(self.unknown_route(name));
2003 }
2004 }
2005 self.route_pin = wanted;
2006 Ok(())
2007 }
2008
2009 fn unknown_route(&self, name: &str) -> Error {
2010 Error::Config(format!(
2011 "unknown route `{name}`. Routes that exist: {}",
2012 self.route_names()
2013 ))
2014 }
2015
2016 pub fn chain(&self) -> Result<Chain> {
2022 self.validate_routes()?;
2023 let all = self.declared_routes();
2024 let find = |name: &str| all.iter().find(|r| r.name == name).cloned();
2025 let (routes, source) = if let Some(pin) = &self.route_pin {
2026 let route = find(pin).ok_or_else(|| self.unknown_route(pin))?;
2027 (vec![route], ChainSource::Pinned)
2028 } else if let Some(fallback) = &self.provider.fallback {
2029 let routes = fallback.iter().filter_map(|n| find(n)).collect();
2031 (routes, ChainSource::Fallback)
2032 } else if self.provider.declares_connection() || self.provider.route.is_empty() {
2033 (
2034 vec![NamedRoute::new(DEFAULT_ROUTE, &self.provider)],
2035 ChainSource::Default,
2036 )
2037 } else {
2038 return Err(Error::Config(format!(
2039 "routes are declared but nothing says which to use: set `[provider] fallback = \
2040 [...]`, or pass --route NAME. Routes that exist: {}",
2041 self.route_names()
2042 )));
2043 };
2044 for route in &routes {
2045 route.require_endpoint(source)?;
2046 }
2047 let pinned = source == ChainSource::Pinned;
2052 let only = routes.first().cloned();
2053 let (aux, delegate) = if pinned {
2054 (only.clone(), only)
2055 } else {
2056 (
2057 self.provider.aux.as_deref().and_then(find),
2058 self.provider.delegate.as_deref().and_then(find),
2059 )
2060 };
2061 if let Some(aux) = &aux {
2062 aux.require_endpoint(source)?;
2063 }
2064 if let Some(delegate) = &delegate {
2065 delegate.require_endpoint(source)?;
2066 }
2067 Ok(Chain {
2068 routes,
2069 source,
2070 aux,
2071 delegate,
2072 })
2073 }
2074
2075 pub fn sessions_dir(&self, env: EnvFn) -> Result<PathBuf> {
2076 if let Some(d) = &self.sessions.dir {
2077 return Ok(expand_tilde(d, env));
2078 }
2079 Ok(self.state_dir(env)?.join("sessions"))
2080 }
2081
2082 pub fn validate_bots(&self) -> Result<()> {
2089 for name in self.bots.keys() {
2090 let ok = !name.is_empty()
2091 && name.len() <= 32
2092 && name
2093 .chars()
2094 .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-' || c == '_');
2095 if !ok {
2096 return Err(Error::Config(format!(
2097 "bots.{name}: a bot name is lowercase letters, digits, `-` and `_`, at most \
2098 32 of them — it becomes part of a session's `origin` and a URL"
2099 )));
2100 }
2101 }
2102 Ok(())
2103 }
2104
2105 pub fn bot_file(&self, env: EnvFn, path: &str) -> Option<PathBuf> {
2108 let path = expand_tilde(Path::new(path), env);
2109 if path.is_absolute() {
2110 Some(path)
2111 } else {
2112 self.context_dir(env).map(|dir| dir.join(path))
2113 }
2114 }
2115
2116 pub fn bot_memory(&self, env: EnvFn, name: &str, bot: &BotConfig) -> Option<PathBuf> {
2120 match bot.memory.as_deref().filter(|m| !m.trim().is_empty()) {
2121 Some(m) => self.bot_file(env, m),
2122 None => self
2123 .memory_dir(env)
2124 .map(|dir| dir.join("bots").join(name).join(&self.user.memory_file)),
2125 }
2126 }
2127
2128 pub fn attachments_dir(&self, env: EnvFn) -> Option<PathBuf> {
2133 if let Some(dir) = &self.attachments.dir {
2134 return Some(expand_tilde(dir, env));
2135 }
2136 self.state_dir(env).ok().map(|d| d.join("attachments"))
2137 }
2138
2139 pub fn where_am_i(&self, env: EnvFn, loaded: Option<&Path>) -> Where {
2148 let overlay = self
2149 .profile
2150 .as_deref()
2151 .filter(|name| *name != "default")
2152 .and_then(|name| profile_dir(env, name))
2153 .map(|dir| dir.join("config.toml"))
2154 .filter(|path| path.exists());
2155 Where {
2156 profile: self.profile.clone(),
2157 config: loaded.map(Path::to_path_buf).or_else(|| config_path(env)),
2158 overlay,
2159 home: home_root(env),
2160 sessions: self.sessions_dir(env).ok(),
2161 }
2162 }
2163
2164 pub fn context_dir(&self, env: EnvFn) -> Option<PathBuf> {
2167 match &self.profile {
2168 Some(name) => profile_dir(env, name),
2169 None => config_path(env)
2170 .and_then(|p| p.parent().map(Path::to_path_buf))
2171 .or_else(|| config_dir(env)),
2172 }
2173 }
2174
2175 pub fn scripts_dir(&self, env: EnvFn) -> Option<PathBuf> {
2184 let dir = self.context_dir(env)?.join("scripts");
2185 if dir.is_absolute() {
2186 return Some(dir);
2187 }
2188 std::env::current_dir().ok().map(|cwd| cwd.join(dir))
2189 }
2190
2191 pub fn memory_dir(&self, env: EnvFn) -> Option<PathBuf> {
2199 self.context_dir(env).map(|d| d.join("memory"))
2200 }
2201
2202 pub fn global_context_dir(&self, env: EnvFn) -> Option<PathBuf> {
2204 config_path(env)
2205 .and_then(|p| p.parent().map(Path::to_path_buf))
2206 .or_else(|| config_dir(env))
2207 }
2208
2209 pub fn home(&self, env: EnvFn) -> Option<PathBuf> {
2210 home_dir(env)
2211 }
2212
2213 pub fn workspace_root(&self, env: EnvFn) -> PathBuf {
2214 match &self.tools.workspace_root {
2215 Some(p) => expand_tilde(p, env),
2216 None => std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
2217 }
2218 }
2219}
2220
2221#[derive(Debug, Clone, Default, PartialEq, Eq)]
2227pub struct Where {
2228 pub profile: Option<String>,
2230 pub config: Option<PathBuf>,
2233 pub overlay: Option<PathBuf>,
2235 pub home: Option<PathBuf>,
2237 pub sessions: Option<PathBuf>,
2239}
2240
2241impl Where {
2242 pub fn name(&self) -> &str {
2244 self.profile.as_deref().unwrap_or("default")
2245 }
2246
2247 pub fn is_default(&self) -> bool {
2250 matches!(self.profile.as_deref(), None | Some("default"))
2251 }
2252}
2253
2254fn read_toml(path: &Path) -> Result<toml::Value> {
2256 let text = std::fs::read_to_string(path).map_err(|e| Error::io(path, e))?;
2257 toml::from_str::<toml::Value>(&text).map_err(|message| Error::Parse {
2258 path: path.to_path_buf(),
2259 message: message.to_string(),
2260 })
2261}
2262
2263fn merge_toml(base: &mut toml::Value, over: toml::Value) {
2265 match (base, over) {
2266 (toml::Value::Table(base), toml::Value::Table(over)) => {
2267 for (key, value) in over {
2268 match base.get_mut(&key) {
2269 Some(slot) => merge_toml(slot, value),
2270 None => {
2271 base.insert(key, value);
2272 }
2273 }
2274 }
2275 }
2276 (slot, over) => *slot = over,
2277 }
2278}
2279
2280fn redact(value: &mut toml::Value) {
2282 match value {
2283 toml::Value::Table(table) => {
2284 for (key, slot) in table.iter_mut() {
2285 if is_secret_key(key) && matches!(slot, toml::Value::String(s) if !s.is_empty()) {
2286 *slot = toml::Value::String("<redacted>".into());
2287 continue;
2288 }
2289 if is_url_key(key) {
2290 if let toml::Value::String(url) = slot {
2291 if let Some(clean) = redact_url(url) {
2292 *slot = toml::Value::String(clean);
2293 continue;
2294 }
2295 }
2296 }
2297 redact(slot);
2298 }
2299 }
2300 toml::Value::Array(items) => items.iter_mut().for_each(redact),
2301 _ => {}
2302 }
2303}
2304
2305pub(crate) fn is_secret_key(key: &str) -> bool {
2309 let k = key.to_ascii_lowercase();
2310 if k.ends_with("_env") {
2311 return false;
2312 }
2313 const COUNTS: &[&str] = &[
2316 "_tokens",
2317 "_chars",
2318 "_secs",
2319 "_ms",
2320 "_count",
2321 "_size",
2322 "_hours",
2323 "_days",
2324 "_bytes",
2325 "_iterations",
2326 "_call",
2327 ];
2328 if COUNTS.iter().any(|suffix| k.ends_with(suffix)) {
2329 return false;
2330 }
2331 k == "api_key"
2332 || k.ends_with("_key")
2333 || k.contains("token")
2334 || k.contains("secret")
2335 || k.contains("password")
2336}
2337
2338fn is_url_key(key: &str) -> bool {
2342 let k = key.to_ascii_lowercase();
2343 k.ends_with("_url") || k == "remote" || k == "releases"
2344}
2345
2346fn redact_url(text: &str) -> Option<String> {
2353 let (body, fragment) = match text.split_once('#') {
2354 Some((b, f)) => (b, Some(f)),
2355 None => (text, None),
2356 };
2357 let (before_query, query) = match body.split_once('?') {
2358 Some((b, q)) => (b, Some(q)),
2359 None => (body, None),
2360 };
2361 let mut changed = false;
2362
2363 let head = match before_query.find("://") {
2366 Some(scheme_end) => {
2367 let start = scheme_end + 3;
2368 let rest = &before_query[start..];
2369 let authority_end = rest.find('/').unwrap_or(rest.len());
2370 match rest[..authority_end].rfind('@') {
2371 Some(at) => {
2372 changed = true;
2373 format!("{}{}<redacted>{}", &before_query[..start], "", &rest[at..])
2374 }
2375 None => before_query.to_string(),
2376 }
2377 }
2378 None => before_query.to_string(),
2379 };
2380
2381 let query = query.map(|q| {
2382 let pairs: Vec<String> = q
2383 .split('&')
2384 .map(|pair| {
2385 let name = pair.split_once('=').map(|(n, _)| n).unwrap_or(pair);
2386 if !name.is_empty() && is_secret_key(name) {
2387 changed = true;
2388 format!("{name}=<redacted>")
2389 } else {
2390 pair.to_string()
2391 }
2392 })
2393 .collect();
2394 pairs.join("&")
2395 });
2396
2397 if !changed {
2398 return None;
2399 }
2400 let mut out = head;
2401 if let Some(q) = query {
2402 out.push('?');
2403 out.push_str(&q);
2404 }
2405 if let Some(f) = fragment {
2406 out.push('#');
2407 out.push_str(f);
2408 }
2409 Some(out)
2410}
2411
2412const SHIPPED_SPELLING: &[(&str, &str, &str)] = &[
2429 ("provider", "api_key", "${OPENAI_API_KEY:-}"),
2430 ("provider", "api_key_env", ""),
2431 ("provider", "profile", ""),
2432 (
2433 "provider",
2434 "reasoning_effort",
2435 crate::reasoning::SHIPPED_DEFAULT,
2436 ),
2437 ("provider", "aux", ""),
2438 ("provider", "delegate", ""),
2439 ("agent", "output_schema", ""),
2440 ("web", "auth_token", "${ECLIPSE_WEB_AUTH_TOKEN:-}"),
2441 ("web", "default_profile", ""),
2442 ("update", "remote", ""),
2443 ("update", "releases", ""),
2444 ("tools", "write_file", "ask"),
2448 ("tools", "patch", "ask"),
2449];
2450
2451fn shipped_text(spelling: &str) -> String {
2454 toml::Value::String(spelling.to_string()).to_string()
2455}
2456
2457const SECTION_ORDER: &[&str] = &[
2459 "provider",
2460 "agent",
2461 "tools",
2462 "flares",
2463 "sessions",
2464 "attachments",
2465 "context",
2466 "plugins",
2467 "cli",
2468 "web",
2469 "gateway",
2470 "update",
2471 "hooks",
2472 "user",
2473 "skills",
2474 "vision",
2475];
2476
2477pub fn starter_config() -> Result<String> {
2501 let defaults = toml::Value::try_from(Config::default())
2502 .map_err(|e| Error::Config(format!("the default config does not serialise: {e}")))?;
2503 let mut out = String::with_capacity(8 * 1024);
2504 out.push_str("# Every setting this build reads, and nothing else.\n");
2505 out.push_str("# What one does, and what it accepts: `eclipse config docs`.\n");
2506 out.push_str("# A commented key is not in use; an empty value means the same.\n");
2507 out.push_str(&format!("config_version = {CONFIG_VERSION}\n"));
2508 for section in SECTION_ORDER {
2509 out.push_str(&format!("\n[{section}]\n"));
2510 let table = defaults.get(*section).and_then(toml::Value::as_table);
2511 let mut lines: Vec<(String, String)> = Vec::new();
2512 let mut nested: Vec<&str> = Vec::new();
2513 if let Some(table) = table {
2514 for (key, value) in table {
2515 match value {
2516 toml::Value::Table(_) => nested.push(key.as_str()),
2517 other => {
2518 let shipped = SHIPPED_SPELLING
2519 .iter()
2520 .find(|(s, k, _)| s == section && k == key)
2521 .map(|(_, _, spelling)| shipped_text(spelling));
2522 lines.push((key.clone(), shipped.unwrap_or_else(|| other.to_string())));
2523 }
2524 }
2525 }
2526 }
2527 for (abs_section, key, _) in settings::ABSENT_BY_DEFAULT {
2530 if abs_section == section && !lines.iter().any(|(k, _)| k == key) {
2531 let shipped = SHIPPED_SPELLING
2532 .iter()
2533 .find(|(s, k, _)| s == section && k == key)
2534 .map(|(_, _, spelling)| shipped_text(spelling));
2535 lines.push(((*key).to_string(), shipped.unwrap_or_default()));
2536 }
2537 }
2538 lines.sort();
2539 for (key, text) in lines {
2540 if text.is_empty() {
2541 out.push_str(&format!("# {key} =\n"));
2542 } else {
2543 out.push_str(&format!("{key} = {text}\n"));
2544 }
2545 }
2546 nested.sort();
2550 for key in nested {
2551 let Some(sub) = table.and_then(|t| t.get(key)) else {
2552 continue;
2553 };
2554 let mut wrapped = toml::map::Map::new();
2555 wrapped.insert(key.to_string(), sub.clone());
2556 if let Ok(text) = toml::to_string(&toml::Value::Table(wrapped)) {
2557 out.push('\n');
2558 out.push_str(&text);
2559 }
2560 }
2561 if *section == "hooks" {
2566 let default_hooks = Config::default().hooks;
2567 for name in &default_hooks.order {
2568 if default_hooks.settings.contains_key(name) {
2569 continue;
2570 }
2571 let Some(info) = crate::hooks::SHIPPED.iter().find(|h| h.name == name) else {
2572 continue;
2573 };
2574 out.push_str(&format!("\n[hooks.{name}]\n"));
2575 let mut keys = info.settings.to_vec();
2576 keys.sort_unstable();
2577 for key in keys {
2578 out.push_str(&format!("# {key} =\n"));
2579 }
2580 }
2581 }
2582 }
2583 Ok(out)
2584}
2585
2586pub const ENV_TEMPLATE: &[&str] = &[
2596 "ECLIPSE_BASE_URL",
2597 "ECLIPSE_MODEL",
2598 "ECLIPSE_API_KEY",
2599 "ECLIPSE_REASONING_EFFORT",
2600 "ECLIPSE_ROUTE",
2601 "OPENAI_API_KEY",
2602 "ECLIPSE_WEB_AUTH_TOKEN",
2603 "ECLIPSE_WEB_USER",
2604 "ECLIPSE_WEB_PASSWORD_HASH",
2605];
2606
2607pub const ENV_ABOUT: &[(&str, &str)] = &[
2613 ("ECLIPSE_BASE_URL", "The provider's base URL, up to and including the version: it beats `[provider] base_url` for this process only"),
2614 ("ECLIPSE_MODEL", "The model name to ask for, beating `[provider] model`; the same as `--model`"),
2615 ("ECLIPSE_API_KEY", "The provider's key, resolved by `api_key = \"${ECLIPSE_API_KEY}\"`; never put the key itself in `config.toml`"),
2616 ("ECLIPSE_REASONING_EFFORT", "The reasoning level for this process: none, minimal, low, medium, high, xhigh, max"),
2617 ("ECLIPSE_ROUTE", "Pin one named route and never fall back from it, the same as `--route`"),
2618 ("OPENAI_API_KEY", "The variable the shipped `provider.api_key` line refers to; any name works, this one is the convention"),
2619 ("ECLIPSE_WEB_AUTH_TOKEN", "The dashboard's bearer token, generated by `config init`; the dashboard refuses to start without it"),
2620 ("ECLIPSE_WEB_USER", "The dashboard's sign-in name, when it asks for a name and a password instead of the token"),
2621 ("ECLIPSE_WEB_PASSWORD_HASH", "That password, as `eclipse web passwd` writes it: `pbkdf2-sha256$<iterations>$<salt>$<digest>`"),
2622 ("ECLIPSE_HOME", "The one directory everything lives in (`~/.eclipse` otherwise). Read from the shell, never from this file"),
2623 ("ECLIPSE_CONFIG", "The config file to read (`<home>/config.toml` otherwise). Read from the shell, never from this file"),
2624 ("ECLIPSE_PROFILE", "The profile to load, the same as `--profile`. Read from the shell, never from this file"),
2625 ("ECLIPSE_BIN", "The `eclipse` binary a spawned job should use; this tool sets it, and only a test overrides it"),
2626 ("ECLIPSE_ARGS", "The JSON arguments of the tool call a plugin or MCP server is being asked about; set by this tool"),
2627 ("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"),
2628 ("ECLIPSE_TOOL", "The tool name a bridged call is for; set by this tool"),
2629 ("ECLIPSE_TOOL_SOCKET", "Where a script or plugin calls back into the running agent; set by this tool"),
2630 ("ECLIPSE_WORKSPACE", "The workspace root, given to a child process; set by this tool from `[tools] workspace_root`"),
2631 ("ECLIPSE_PLUGIN_DIR", "The plugin directory, given to a child process; set by this tool"),
2632 ("ECLIPSE_SCRIPTS_DIR", "The scripts directory, given to a child process; set by this tool"),
2633];
2634
2635pub fn env_about(name: &str) -> &'static str {
2637 ENV_ABOUT
2638 .iter()
2639 .find(|(n, _)| *n == name)
2640 .map(|(_, about)| *about)
2641 .unwrap_or("")
2642}
2643
2644pub const ENV_SHELL_ONLY: &[&str] = &["ECLIPSE_HOME", "ECLIPSE_CONFIG", "ECLIPSE_PROFILE"];
2647
2648pub const ENV_INTERNAL: &[&str] = &[
2651 "ECLIPSE_BIN",
2652 "ECLIPSE_ARGS",
2653 "ECLIPSE_ARGS_BYTES",
2654 "ECLIPSE_TOOL",
2655 "ECLIPSE_TOOL_SOCKET",
2656 "ECLIPSE_WORKSPACE",
2657 "ECLIPSE_PLUGIN_DIR",
2658 "ECLIPSE_SCRIPTS_DIR",
2659];
2660
2661pub fn starter_env(token: &str) -> String {
2666 let mut out = String::with_capacity(1024);
2667 out.push_str("# Secrets and per-host overrides. The shell beats this file. Mode 0600.\n");
2668 out.push_str("# Every variable this build reads; an empty value is not set. `eclipse config docs` explains each.\n");
2669 for name in ENV_TEMPLATE {
2670 if *name == "ECLIPSE_WEB_AUTH_TOKEN" {
2671 out.push_str(&format!("{name}={token}\n"));
2672 } else {
2673 out.push_str(&format!("{name}=\n"));
2674 }
2675 }
2676 out
2677}
2678
2679pub const STARTER_PROFILE_CONFIG: &str = r#"# A profile overlay: keys here replace the base config's, and a key left out follows it.
2683# Examples are commented out on purpose — an empty value here *replaces* the base value.
2684
2685[provider]
2686# base_url = "http://127.0.0.1:8080/v1"
2687# model = "qwen3-coder:30b"
2688# profile = "llamacpp"
2689
2690[tools]
2691# shell = "ask"
2692"#;
2693
2694#[derive(Debug, Clone, PartialEq, Eq)]
2696pub struct InitReport {
2697 pub config: PathBuf,
2698 pub dotenv: PathBuf,
2699 pub dotenv_written: bool,
2702}
2703
2704pub fn write_starter_config(path: &Path, force: bool, env: EnvFn) -> Result<InitReport> {
2717 if path.exists() && !force {
2718 return Err(Error::Config(format!(
2719 "{} already exists (use --force to overwrite)",
2720 path.display()
2721 )));
2722 }
2723 let dir = path.parent().unwrap_or(Path::new("."));
2724 std::fs::create_dir_all(dir).map_err(|e| Error::io(dir, e))?;
2725 write_private(path, &starter_config()?)?;
2726
2727 let secrets_dir = config_dir(env).unwrap_or_else(|| dir.to_path_buf());
2728 std::fs::create_dir_all(&secrets_dir).map_err(|e| Error::io(&secrets_dir, e))?;
2729 let dotenv = secrets_dir.join(".env");
2730 let mut dotenv_written = false;
2731 if !dotenv.exists() {
2732 let token = crate::token::generate()?;
2733 write_private(&dotenv, &starter_env(&token))?;
2734 dotenv_written = true;
2735 }
2736 let _ = migrate::write_baseline(path);
2740 Ok(InitReport {
2741 config: path.to_path_buf(),
2742 dotenv,
2743 dotenv_written,
2744 })
2745}
2746
2747pub fn toml_value(text: &str, section: &str, key: &str) -> Option<String> {
2750 let mut in_section = false;
2751 for line in text.lines() {
2752 let trimmed = line.trim();
2753 if let Some(name) = section_header(trimmed) {
2754 in_section = name == section;
2755 continue;
2756 }
2757 if !in_section || trimmed.starts_with('#') {
2758 continue;
2759 }
2760 if let Some((k, v)) = key_value(trimmed) {
2761 if k == key {
2762 return Some(v);
2763 }
2764 }
2765 }
2766 None
2767}
2768
2769pub fn toml_set_string(text: &str, section: &str, key: &str, value: &str) -> String {
2777 toml_set_value(text, section, key, &format!("\"{}\"", escape_toml(value)))
2778}
2779
2780pub fn toml_set_value(text: &str, section: &str, key: &str, value: &str) -> String {
2783 place_line(text, section, key, &format!("{key} = {value}"))
2784}
2785
2786struct McpSpan {
2799 name: Option<String>,
2800 start: usize,
2801 end: usize,
2802}
2803
2804fn is_table_header(trimmed: &str) -> bool {
2805 trimmed.starts_with('[')
2806}
2807
2808fn mcp_spans(lines: &[String]) -> Vec<McpSpan> {
2809 let mut spans: Vec<McpSpan> = Vec::new();
2810 let mut open: Option<usize> = None;
2811 let mut closed_by_header = true;
2812 for (i, line) in lines.iter().enumerate() {
2813 let trimmed = line.trim();
2814 if open.is_some() && is_table_header(trimmed) {
2815 if let Some(start) = open.take() {
2816 spans.push(McpSpan {
2817 name: None,
2818 start,
2819 end: i,
2820 });
2821 closed_by_header = true;
2822 }
2823 }
2824 if trimmed == "[[mcp]]" {
2825 open = Some(i);
2826 }
2827 }
2828 if let Some(start) = open {
2829 spans.push(McpSpan {
2830 name: None,
2831 start,
2832 end: lines.len(),
2833 });
2834 closed_by_header = false;
2835 }
2836 let count = spans.len();
2842 for (i, span) in spans.iter_mut().enumerate() {
2843 let at_eof = i + 1 == count && !closed_by_header;
2844 while span.end > span.start + 1 {
2845 let tail = lines[span.end - 1].trim();
2846 let belongs_to_next = !at_eof && (tail.is_empty() || tail.starts_with('#'));
2847 if tail.is_empty() || belongs_to_next {
2848 span.end -= 1;
2849 } else {
2850 break;
2851 }
2852 }
2853 }
2854 for span in &mut spans {
2855 let body = lines[span.start + 1..span.end].join("\n");
2856 span.name = toml::from_str::<crate::mcp::Spec>(&body)
2857 .ok()
2858 .map(|spec| spec.name);
2859 }
2860 spans
2861}
2862
2863fn tidy_blanks(lines: Vec<String>) -> Vec<String> {
2866 let mut end = lines.len();
2867 while end > 0 && lines[end - 1].trim().is_empty() {
2868 end -= 1;
2869 }
2870 let mut out: Vec<String> = Vec::with_capacity(end);
2871 let mut blanks = 0;
2872 for line in &lines[..end] {
2873 if line.trim().is_empty() {
2874 blanks += 1;
2875 if blanks > 1 {
2876 continue;
2877 }
2878 } else {
2879 blanks = 0;
2880 }
2881 out.push(line.clone());
2882 }
2883 out
2884}
2885
2886fn render_mcp_entry(entry: &crate::mcp::Spec) -> String {
2890 let quote = |s: &str| toml::Value::String(s.to_string()).to_string();
2891 let mut out = String::from("[[mcp]]\n");
2892 out.push_str(&format!("name = {}\n", quote(&entry.name)));
2893 if entry.transport == crate::mcp::Transport::Http {
2894 out.push_str("transport = \"http\"\n");
2895 }
2896 if !entry.command.is_empty() {
2897 out.push_str(&format!("command = {}\n", quote(&entry.command)));
2898 }
2899 if !entry.args.is_empty() {
2900 let args: Vec<String> = entry.args.iter().map(|a| quote(a)).collect();
2901 out.push_str(&format!("args = [{}]\n", args.join(", ")));
2902 }
2903 if let Some(url) = &entry.url {
2904 out.push_str(&format!("url = {}\n", quote(url)));
2905 }
2906 if let Some(var) = &entry.token_env {
2907 out.push_str(&format!("token_env = {}\n", quote(var)));
2908 }
2909 if entry.cwd != crate::plugins::Cwd::default() {
2910 let cwd = match entry.cwd {
2911 crate::plugins::Cwd::Workspace => "workspace",
2912 crate::plugins::Cwd::Plugin => "plugin",
2913 };
2914 out.push_str(&format!("cwd = \"{cwd}\"\n"));
2915 }
2916 if let Some(secs) = entry.timeout_secs {
2917 out.push_str(&format!("timeout_secs = {secs}\n"));
2918 }
2919 if entry.policy != Policy::Ask {
2920 let policy = match entry.policy {
2921 Policy::Deny => "deny",
2922 Policy::Ask => "ask",
2923 Policy::Allow => "allow",
2924 };
2925 out.push_str(&format!("policy = \"{policy}\"\n"));
2926 }
2927 if !entry.policies.is_empty() {
2928 let pairs: Vec<String> = entry
2929 .policies
2930 .iter()
2931 .map(|(tool, policy)| {
2932 let policy = match policy {
2933 Policy::Deny => "deny",
2934 Policy::Ask => "ask",
2935 Policy::Allow => "allow",
2936 };
2937 format!("{tool} = \"{policy}\"")
2938 })
2939 .collect();
2940 out.push_str(&format!("policies = {{ {} }}\n", pairs.join(", ")));
2941 }
2942 if !entry.prefix.is_empty() {
2943 out.push_str(&format!("prefix = {}\n", quote(&entry.prefix)));
2944 }
2945 if !entry.env.is_empty() {
2946 let env: Vec<String> = entry.env.iter().map(|e| quote(e)).collect();
2947 out.push_str(&format!("env = [{}]\n", env.join(", ")));
2948 }
2949 if entry.override_builtin {
2950 out.push_str("override = true\n");
2951 }
2952 if entry.disabled {
2953 out.push_str("disabled = true\n");
2954 }
2955 out
2956}
2957
2958pub fn mcp_add(text: &str, entry: &crate::mcp::Spec) -> std::result::Result<String, String> {
2960 entry
2961 .validate()
2962 .map_err(|why| format!("that entry is not usable, so nothing was saved: {why}"))?;
2963 let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
2964 let spans = mcp_spans(&lines);
2965 if let Some(existing) = spans
2966 .iter()
2967 .find(|s| s.name.as_deref() == Some(&entry.name))
2968 {
2969 return Err(format!(
2970 "`{}` is already declared at line {} — `eclipse mcp remove {}` first, or edit that entry",
2971 entry.name,
2972 existing.start + 1,
2973 entry.name
2974 ));
2975 }
2976 let rendered = render_mcp_entry(entry);
2977 match spans.last() {
2978 Some(last) => {
2979 let at = last.end;
2980 let mut fresh: Vec<String> = Vec::new();
2981 if at > 0 && !lines[at - 1].trim().is_empty() {
2983 fresh.push(String::new());
2984 }
2985 fresh.extend(rendered.lines().map(str::to_string));
2986 lines.splice(at..at, fresh);
2987 }
2988 None => {
2989 if lines.last().is_some_and(|l| !l.trim().is_empty()) {
2990 lines.push(String::new());
2991 }
2992 lines.extend(rendered.lines().map(str::to_string));
2993 }
2994 }
2995 let out = join_lines(tidy_blanks(lines));
2996 readback_mcp(&out, &entry.name, |spec| spec == entry)
2997}
2998
2999pub fn mcp_remove(text: &str, name: &str) -> std::result::Result<String, String> {
3001 let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
3002 let spans = mcp_spans(&lines);
3003 let Some(span) = spans.iter().find(|s| s.name.as_deref() == Some(name)) else {
3004 let known: Vec<&str> = spans.iter().filter_map(|s| s.name.as_deref()).collect();
3005 return Err(if known.is_empty() {
3006 format!("no `[[mcp]]` entry for `{name}` in this file")
3007 } else {
3008 format!(
3009 "no `[[mcp]]` entry for `{name}`; this file declares {}",
3010 known.join(", ")
3011 )
3012 });
3013 };
3014 let mut start = span.start;
3017 while start > 0 && lines[start - 1].trim_start().starts_with('#') {
3018 start -= 1;
3019 }
3020 let mut end = span.end;
3023 if end < lines.len() && lines[end].trim().is_empty() {
3024 end += 1;
3025 }
3026 lines.drain(start..end);
3027 readback_mcp_absent(&join_lines(tidy_blanks(lines)), name)
3028}
3029
3030pub fn mcp_set_disabled(
3032 text: &str,
3033 name: &str,
3034 disabled: bool,
3035) -> std::result::Result<String, String> {
3036 let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
3037 let spans = mcp_spans(&lines);
3038 let Some(span) = spans.iter().find(|s| s.name.as_deref() == Some(name)) else {
3039 return Err(format!("no `[[mcp]]` entry for `{name}` in this file"));
3040 };
3041 let line = if disabled {
3042 "disabled = true".to_string()
3043 } else {
3044 "disabled = false".to_string()
3047 };
3048 let body = span.start + 1..span.end;
3049 match lines[body.clone()].iter().position(|l| {
3050 l.trim_start()
3051 .strip_prefix("disabled")
3052 .is_some_and(|rest| rest.trim_start().starts_with('='))
3053 }) {
3054 Some(offset) => lines[span.start + 1 + offset] = line,
3055 None => lines.insert(span.end, line),
3056 }
3057 readback_mcp(&join_lines(lines), name, |spec| spec.disabled == disabled)
3058}
3059
3060pub fn mcp_update(
3069 text: &str,
3070 name: &str,
3071 change: impl FnOnce(&mut crate::mcp::Spec),
3072) -> std::result::Result<String, String> {
3073 let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
3074 let spans = mcp_spans(&lines);
3075 let Some(span) = spans.iter().find(|s| s.name.as_deref() == Some(name)) else {
3076 let known: Vec<&str> = spans.iter().filter_map(|s| s.name.as_deref()).collect();
3077 return Err(if known.is_empty() {
3078 format!("no `[[mcp]]` entry for `{name}` in this file")
3079 } else {
3080 format!(
3081 "no `[[mcp]]` entry for `{name}`; this file declares {}",
3082 known.join(", ")
3083 )
3084 });
3085 };
3086 let body = lines[span.start + 1..span.end].join("\n");
3087 let before: crate::mcp::Spec = toml::from_str(&body).map_err(|e| {
3088 format!(
3089 "the entry for `{name}` at line {} does not read as it stands, so nothing was saved: {}",
3090 span.start + 1,
3091 crate::config::settings::one_line(&e.to_string())
3092 )
3093 })?;
3094 let mut after = before.clone();
3095 change(&mut after);
3096 if after.name != name {
3097 return Err(format!(
3098 "an edit does not rename: `{name}` stays `{name}` — remove the entry and add the new \
3099 name instead"
3100 ));
3101 }
3102 after
3103 .validate()
3104 .map_err(|why| format!("that entry is not usable, so nothing was saved: {why}"))?;
3105 let rendered = |spec: &crate::mcp::Spec| -> BTreeMap<String, String> {
3106 render_mcp_entry(spec)
3107 .lines()
3108 .skip(1) .filter_map(|line| key_of(line).map(|key| (key, line.to_string())))
3110 .collect()
3111 };
3112 let (old, new) = (rendered(&before), rendered(&after));
3113 let (mut start, mut end) = (span.start + 1, span.end);
3114 let block: Vec<String> = lines[start..end].to_vec();
3117 let mut rebuilt: Vec<String> = Vec::new();
3118 let mut seen: Vec<String> = Vec::new();
3119 let mut i = 0;
3120 while i < block.len() {
3121 let line = &block[i];
3122 let trimmed = line.trim();
3123 if trimmed.is_empty() || trimmed.starts_with('#') {
3124 rebuilt.push(line.clone());
3125 i += 1;
3126 continue;
3127 }
3128 let first = i;
3129 let mut depth = bracket_depth(line);
3130 i += 1;
3131 while depth > 0 && i < block.len() {
3132 depth += bracket_depth(&block[i]);
3133 i += 1;
3134 }
3135 match key_of(&block[first]) {
3136 Some(key) => {
3137 seen.push(key.clone());
3138 match (old.get(&key), new.get(&key)) {
3139 (Some(was), Some(is)) if was == is => {
3141 rebuilt.extend(block[first..i].iter().cloned())
3142 }
3143 (_, Some(is)) => rebuilt.push(is.clone()),
3144 (_, None) => {}
3146 }
3147 }
3148 None => rebuilt.extend(block[first..i].iter().cloned()),
3150 }
3151 }
3152 for (key, line) in &new {
3153 if !seen.contains(key) {
3154 rebuilt.push(line.clone());
3155 }
3156 }
3157 start = start.min(lines.len());
3158 end = end.min(lines.len());
3159 lines.splice(start..end, rebuilt);
3160 let out = join_lines(lines);
3161 readback_mcp(&out, name, |spec| spec == &after)
3162}
3163
3164fn key_of(line: &str) -> Option<String> {
3166 let trimmed = line.trim();
3167 if trimmed.starts_with('#') {
3168 return None;
3169 }
3170 let (key, _) = trimmed.split_once('=')?;
3171 let key = key.trim();
3172 let plain = !key.is_empty()
3173 && !key.contains(char::is_whitespace)
3174 && key
3175 .chars()
3176 .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-');
3177 plain.then(|| key.to_string())
3178}
3179
3180fn bracket_depth(line: &str) -> i32 {
3183 let mut depth = 0;
3184 let mut quote: Option<char> = None;
3185 let mut escaped = false;
3186 for c in line.chars() {
3187 if let Some(q) = quote {
3188 if escaped {
3189 escaped = false;
3190 } else if c == '\\' {
3191 escaped = true;
3192 } else if c == q {
3193 quote = None;
3194 }
3195 continue;
3196 }
3197 match c {
3198 '"' | '\'' => quote = Some(c),
3199 '[' | '{' => depth += 1,
3200 ']' | '}' => depth -= 1,
3201 '#' => break, _ => {}
3203 }
3204 }
3205 depth
3206}
3207
3208fn readback_mcp(
3211 text: &str,
3212 name: &str,
3213 ok: impl Fn(&crate::mcp::Spec) -> bool,
3214) -> std::result::Result<String, String> {
3215 let cfg = parse_text(text).map_err(|e| {
3216 format!(
3217 "that would not load, so nothing was saved: {}",
3218 settings::one_line(&e.to_string())
3219 )
3220 })?;
3221 match cfg.mcp.iter().find(|s| s.name == name) {
3222 Some(spec) if ok(spec) => Ok(text.to_string()),
3223 Some(_) => {
3224 Err("the file would not read that entry back as written; nothing was saved".into())
3225 }
3226 None => Err(format!(
3227 "the edit lost `{name}` on the way back in; nothing was saved"
3228 )),
3229 }
3230}
3231
3232fn readback_mcp_absent(text: &str, name: &str) -> std::result::Result<String, String> {
3233 let cfg = parse_text(text).map_err(|e| {
3234 format!(
3235 "that would not load, so nothing was saved: {}",
3236 settings::one_line(&e.to_string())
3237 )
3238 })?;
3239 if cfg.mcp.iter().any(|s| s.name == name) {
3240 return Err(format!("`{name}` survived the removal; nothing was saved"));
3241 }
3242 Ok(text.to_string())
3243}
3244
3245fn place_line(text: &str, section: &str, key: &str, replacement: &str) -> String {
3251 let quoted = replacement.to_string();
3252 let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
3253 let mut in_section = false;
3254 let mut header_at: Option<usize> = None;
3255 let mut commented_at: Option<usize> = None;
3256 for (i, line) in lines.iter().enumerate() {
3257 let trimmed = line.trim();
3258 if let Some(name) = section_header(trimmed) {
3259 in_section = name == section;
3260 if in_section && header_at.is_none() {
3261 header_at = Some(i);
3262 }
3263 continue;
3264 }
3265 if !in_section {
3266 continue;
3267 }
3268 if let Some((k, _)) = key_value(trimmed) {
3269 if k == key {
3270 lines[i] = quoted;
3271 return join_lines(lines);
3272 }
3273 } else if let Some(rest) = trimmed.strip_prefix('#') {
3274 if let Some((k, _)) = key_value(rest.trim()) {
3276 if k == key && commented_at.is_none() {
3277 commented_at = Some(i);
3278 }
3279 }
3280 }
3281 }
3282 match (header_at, commented_at) {
3283 (_, Some(i)) => lines[i] = quoted,
3284 (Some(i), None) => lines.insert(i + 1, quoted),
3285 (None, None) => {
3286 lines.push(String::new());
3287 lines.push(format!("[{section}]"));
3288 lines.push(quoted);
3289 }
3290 }
3291 join_lines(lines)
3292}
3293
3294pub fn comment_in_text(text: &str, section: &str, key: &str) -> String {
3300 place_line(text, section, key, &format!("# {key} ="))
3301}
3302
3303pub fn stamp_version(text: &str, version: u32) -> std::result::Result<String, String> {
3308 let line = format!("config_version = {version}");
3309 let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
3310 if let Some(at) = lines.iter().position(|l| {
3311 l.trim_start()
3312 .strip_prefix("config_version")
3313 .is_some_and(|rest| rest.trim_start().starts_with('='))
3314 }) {
3315 lines[at] = line;
3316 } else {
3317 let first_table = lines
3322 .iter()
3323 .position(|l| section_header(l.trim()).is_some())
3324 .unwrap_or(lines.len());
3325 let mut insert_at = 0;
3326 while insert_at < first_table
3327 && (lines[insert_at].trim_start().starts_with('#')
3328 || lines[insert_at].trim().is_empty())
3329 {
3330 insert_at += 1;
3331 }
3332 lines.insert(insert_at, String::new());
3333 lines.insert(insert_at, line);
3334 while insert_at > 0 && lines[insert_at - 1].trim().is_empty() {
3335 lines.remove(insert_at - 1);
3336 insert_at -= 1;
3337 }
3338 }
3339 let out = join_lines(lines);
3340 parse_text(&out).map_err(|e| format!("stamping the version would not load: {e}"))?;
3342 Ok(out)
3343}
3344
3345pub fn toml_comment_out(text: &str, section: &str, key: &str) -> String {
3351 let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
3352 let mut in_section = false;
3353 for line in lines.iter_mut() {
3354 let trimmed = line.trim();
3355 if let Some(name) = section_header(trimmed) {
3356 in_section = name == section;
3357 continue;
3358 }
3359 if !in_section || trimmed.starts_with('#') {
3360 continue;
3361 }
3362 if let Some((k, _)) = key_value(trimmed) {
3363 if k == key {
3364 let indent: String = line.chars().take_while(|c| c.is_whitespace()).collect();
3365 *line = format!("{indent}# {trimmed}");
3366 return join_lines(lines);
3367 }
3368 }
3369 }
3370 join_lines(lines)
3371}
3372
3373pub(crate) fn section_header(trimmed: &str) -> Option<&str> {
3376 if trimmed.starts_with("[[") {
3377 return None;
3378 }
3379 let rest = trimmed.strip_prefix('[')?;
3380 let name = rest.strip_suffix(']')?;
3381 if name.contains(['[', ']']) || name.trim() != name || name.is_empty() {
3382 return None;
3383 }
3384 Some(name)
3385}
3386
3387pub(crate) fn key_value(trimmed: &str) -> Option<(&str, String)> {
3390 let (k, v) = trimmed.split_once('=')?;
3391 let k = k.trim();
3392 if k.is_empty() || k.contains([' ', '"', '\\']) {
3393 return None;
3394 }
3395 let v = v.trim();
3396 let unquoted = match v.strip_prefix('"').and_then(|r| r.strip_suffix('"')) {
3397 Some(inner) => inner.replace("\\\"", "\"").replace("\\\\", "\\"),
3398 None => v.to_string(),
3399 };
3400 Some((k, unquoted))
3401}
3402
3403fn escape_toml(value: &str) -> String {
3404 value.replace('\\', "\\\\").replace('"', "\\\"")
3405}
3406
3407fn join_lines(lines: Vec<String>) -> String {
3408 let mut out = lines.join("\n");
3409 if !out.ends_with('\n') {
3410 out.push('\n');
3411 }
3412 out
3413}
3414
3415pub fn save_config_text(path: &Path, text: &str) -> Result<()> {
3419 write_private(path, text)
3420}
3421
3422pub fn parse_text(text: &str) -> Result<Config> {
3425 let cfg: Config =
3426 toml::from_str(text).map_err(|e| Error::Config(format!("invalid config: {e}")))?;
3427 crate::hooks::validate(&cfg.hooks)
3428 .map_err(|e| Error::Config(format!("invalid config: {e}")))?;
3429 Ok(cfg)
3430}
3431
3432pub fn save_dotenv_var(path: &Path, key: &str, value: &str) -> Result<()> {
3436 let existing = std::fs::read_to_string(path).unwrap_or_default();
3437 let line = format!("{key}={value}");
3438 let mut out = String::new();
3439 let mut replaced = false;
3440 for l in existing.lines() {
3441 let is_key = l
3442 .trim_start()
3443 .strip_prefix(key)
3444 .map(|rest| rest.starts_with('='))
3445 .unwrap_or(false);
3446 if is_key {
3447 out.push_str(&line);
3448 out.push('\n');
3449 replaced = true;
3450 } else {
3451 out.push_str(l);
3452 out.push('\n');
3453 }
3454 }
3455 if !replaced {
3456 if !out.is_empty() && !out.ends_with('\n') {
3457 out.push('\n');
3458 }
3459 out.push_str(&line);
3460 out.push('\n');
3461 }
3462 write_private(path, &out)
3463}
3464
3465pub fn dotenv_var(path: &Path, key: &str) -> Option<String> {
3467 std::fs::read_to_string(path).ok()?.lines().find_map(|l| {
3468 let rest = l.trim_start().strip_prefix(key)?;
3469 let value = rest.strip_prefix('=')?;
3470 Some(value.trim().to_string())
3471 })
3472}
3473
3474pub(crate) fn write_private(path: &Path, text: &str) -> Result<()> {
3477 crate::atomic::write_file_atomically(path, text).map_err(|e| Error::io(path, e))
3482}
3483
3484#[test]
3485fn writing_the_empty_value_proves_itself_by_reading_back_as_unset() {
3486 let text = starter_config().unwrap();
3491 let without = settings::unset_in_text(&text, "agent.output_schema").expect("known key");
3492 assert_eq!(
3493 Config::from_toml_str(&without).unwrap().agent.output_schema,
3494 None
3495 );
3496 let back = settings::set_in_text(
3497 &without,
3498 "agent.output_schema",
3499 &toml::Value::String(String::new()),
3500 )
3501 .expect("an empty value can be written");
3502 assert!(back.contains("output_schema = \"\""), "{back}");
3503 assert_eq!(
3504 Config::from_toml_str(&back).unwrap().agent.output_schema,
3505 None,
3506 "and it reads as unset, which is what it means"
3507 );
3508 assert_eq!(
3509 toml_value(&back, "agent", "output_schema"),
3510 Some(String::new()),
3511 "the line is there; what it holds is nothing"
3512 );
3513}
3514
3515#[cfg(test)]
3516mod tests {
3517 #[test]
3524 fn a_route_can_say_how_many_flares_it_holds() {
3525 let cfg = Config::from_toml_str(
3526 r#"
3527[provider]
3528fallback = ["local", "cloud"]
3529
3530[[provider.route]]
3531name = "local"
3532base_url = "http://127.0.0.1:8080/v1"
3533model = "qwen"
3534profile = "llamacpp"
3535group = "gpu0"
3536max_parallel = 2
3537
3538[[provider.route]]
3539name = "cloud"
3540base_url = "https://api.example.com/v1"
3541model = "big"
3542"#,
3543 )
3544 .unwrap();
3545 let routes = cfg.declared_routes();
3546 let local = routes.iter().find(|r| r.name == "local").unwrap();
3547 assert_eq!(local.parallel(), 2, "the route said two slots");
3548 assert_eq!(local.group.as_deref(), Some("gpu0"));
3549 let cloud = routes.iter().find(|r| r.name == "cloud").unwrap();
3550 assert_eq!(cloud.parallel(), 4, "an openai route defaults to four");
3552 assert!(cloud.group.is_none());
3553 assert_eq!(
3554 local.default_parallel(),
3555 1,
3556 "llamacpp serves one model at a time"
3557 );
3558
3559 let zero = Config::from_toml_str(
3562 r#"
3563[[provider.route]]
3564name = "local"
3565base_url = "http://127.0.0.1:8080/v1"
3566model = "qwen"
3567max_parallel = 0
3568"#,
3569 )
3570 .unwrap();
3571 assert_eq!(zero.declared_routes()[0].parallel(), 1);
3572
3573 let bad = Config::from_toml_str(
3575 r#"
3576[[provider.route]]
3577name = "local"
3578base_url = "http://127.0.0.1:8080/v1"
3579model = "qwen"
3580max_parallel = "two"
3581"#,
3582 )
3583 .unwrap_err()
3584 .to_string();
3585 assert!(bad.contains("route `local`"), "{bad}");
3586 assert!(bad.contains("max_parallel"), "{bad}");
3587 }
3588
3589 #[test]
3590 fn flares_default_to_three_on_one_local_slot() {
3591 let cfg = Config::from_toml_str("").unwrap();
3592 assert_eq!(cfg.flares.count, 3, "the local default");
3593 assert_eq!(cfg.flares.concurrency(), 4);
3594 assert_eq!(cfg.flares.per_flare(), 6);
3595 assert_eq!(cfg.flares.budget(), 24);
3596
3597 let cfg = Config::from_toml_str(
3598 r#"
3599[flares]
3600count = 5
3601max_concurrent = 0
3602max_iterations = 0
3603total_iterations = 2
3604"#,
3605 )
3606 .unwrap();
3607 assert_eq!(cfg.flares.count, 5);
3608 assert_eq!(cfg.flares.concurrency(), 1);
3611 assert_eq!(cfg.flares.per_flare(), 1);
3612 assert_eq!(cfg.flares.budget(), 2);
3613 }
3614
3615 use super::*;
3616 use std::collections::HashMap;
3617
3618 fn starter() -> String {
3620 starter_config().expect("the starter config generates")
3621 }
3622
3623 fn env_of(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> {
3624 let m: HashMap<String, String> = pairs
3625 .iter()
3626 .map(|(k, v)| (k.to_string(), v.to_string()))
3627 .collect();
3628 move |k| m.get(k).cloned()
3629 }
3630
3631 fn load_hooks(text: &str) -> std::result::Result<Config, String> {
3633 let tmp = tempfile::tempdir().unwrap();
3634 let path = tmp.path().join("config.toml");
3635 std::fs::write(&path, text).unwrap();
3636 let env = env_of(&[("HOME", tmp.path().to_str().unwrap())]);
3637 Config::load_with_profile(Some(&path), None, &env).map_err(|e| e.to_string())
3638 }
3639
3640 #[test]
3641 fn the_memory_and_the_filter_are_on_by_default_when_there_is_no_hooks_section() {
3642 let want = crate::hooks::DEFAULT_ORDER;
3643 let c = load_hooks("[agent]\nmax_iterations = 3\n").unwrap();
3644 assert_eq!(c.hooks.order, want);
3645 assert_eq!(Config::default().hooks.order, want);
3646 let c = load_hooks("").unwrap();
3647 assert_eq!(c.hooks.order, want);
3648 assert!(
3649 !want.contains(&"recall-sessions"),
3650 "a new session is a new session: recall is opt-in, and `session_search` is how the \
3651 agent reaches the archive"
3652 );
3653 }
3654
3655 #[test]
3656 fn an_empty_order_turns_every_hook_off() {
3657 let c = load_hooks("[hooks]\norder = []\n").unwrap();
3658 assert!(c.hooks.order.is_empty());
3659 }
3660
3661 #[test]
3662 fn a_settings_table_alone_keeps_the_default_order() {
3663 let c = load_hooks("[hooks.redact-secrets]\nallow = [\"fixture-key\"]\n").unwrap();
3664 assert_eq!(c.hooks.order, crate::hooks::DEFAULT_ORDER);
3665 }
3666
3667 #[test]
3668 fn a_hook_name_this_build_does_not_have_is_refused_and_the_real_ones_are_listed() {
3669 let err =
3670 load_hooks("[hooks]\norder = [\"redact-secrets\", \"redact-secret\"]\n").unwrap_err();
3671 assert!(err.contains("`redact-secret`"), "{err}");
3672 assert!(
3673 err.contains("Hooks that exist: recall-sessions, redact-secrets"),
3674 "{err}"
3675 );
3676 assert!(err.contains("config.toml"), "the file is named: {err}");
3677 }
3678
3679 #[test]
3680 fn a_settings_table_for_a_hook_that_is_not_in_order_is_refused() {
3681 let err =
3682 load_hooks("[hooks]\norder = []\n[hooks.redact-secrets]\nallow = []\n").unwrap_err();
3683 assert!(err.contains("[hooks.redact-secrets]"), "{err}");
3684 assert!(err.contains("never run"), "{err}");
3685 assert!(err.contains("Add \"redact-secrets\" to order"), "{err}");
3686 }
3687
3688 #[test]
3689 fn a_settings_table_for_a_hook_that_does_not_exist_is_refused() {
3690 let err = load_hooks("[hooks.nope]\nx = 1\n").unwrap_err();
3691 assert!(err.contains("[hooks.nope]"), "{err}");
3692 assert!(err.contains("Hooks that exist"), "{err}");
3693 }
3694
3695 #[test]
3696 fn an_unknown_key_in_a_hooks_table_is_refused_and_the_known_ones_are_listed() {
3697 let err = load_hooks("[hooks.redact-secrets]\nalow = [\"x\"]\n").unwrap_err();
3698 assert!(err.contains("unknown key `alow`"), "{err}");
3699 assert!(err.contains("accepts: allow"), "{err}");
3700 }
3701
3702 #[test]
3703 fn a_stray_key_directly_under_hooks_is_refused() {
3704 let err = load_hooks("[hooks]\nenabled = true\n").unwrap_err();
3705 assert!(err.contains("`enabled`"), "{err}");
3706 assert!(err.contains("`order`"), "{err}");
3707 }
3708
3709 #[test]
3710 fn a_hook_listed_twice_and_a_malformed_allow_list_are_refused() {
3711 let err =
3712 load_hooks("[hooks]\norder = [\"redact-secrets\", \"redact-secrets\"]\n").unwrap_err();
3713 assert!(err.contains("twice"), "{err}");
3714 let err = load_hooks("[hooks.redact-secrets]\nallow = \"x\"\n").unwrap_err();
3715 assert!(err.contains("must be a list of strings"), "{err}");
3716 let err = load_hooks("[hooks.redact-secrets]\nallow = [\"\"]\n").unwrap_err();
3717 assert!(err.contains("empty string"), "{err}");
3718 let err = load_hooks("[hooks.redact-secrets]\nallow = [1]\n").unwrap_err();
3719 assert!(err.contains("only strings"), "{err}");
3720 }
3721
3722 #[test]
3723 fn a_profile_overlay_that_breaks_the_hooks_section_is_blamed_on_the_overlay() {
3724 let tmp = tempfile::tempdir().unwrap();
3725 let home = tmp.path().join("home");
3726 let dir = home.join(".eclipse");
3727 std::fs::create_dir_all(dir.join("profiles/work")).unwrap();
3728 std::fs::write(
3729 dir.join("config.toml"),
3730 "[hooks]\norder = [\"redact-secrets\"]\n",
3731 )
3732 .unwrap();
3733 std::fs::write(
3734 dir.join("profiles/work/config.toml"),
3735 "[hooks]\norder = [\"typo\"]\n",
3736 )
3737 .unwrap();
3738 let env = env_of(&[("HOME", home.to_str().unwrap())]);
3739 let err = Config::load_with_profile(None, Some("work"), &env)
3740 .unwrap_err()
3741 .to_string();
3742 assert!(err.contains("profiles/work/config.toml"), "{err}");
3743 assert!(err.contains("`typo`"), "{err}");
3744 }
3745
3746 #[test]
3750 fn an_empty_value_is_not_a_value_in_the_dotenv() {
3751 let dir = tempfile::tempdir().unwrap();
3752 let home = dir.path();
3753 std::fs::create_dir_all(home.join(".eclipse")).unwrap();
3754 let path = home.join(".eclipse/.env");
3755 std::fs::write(
3756 &path,
3757 "ECLIPSE_API_KEY=\nECLIPSE_MODEL=m\nECLIPSE_WEB_AUTH_TOKEN=\n",
3758 )
3759 .unwrap();
3760 let home_s = home.to_str().unwrap().to_string();
3761 let env = env_of(&[("HOME", &home_s)]);
3762 let loaded = Dotenv::load(&env, None).unwrap();
3763 assert_eq!(
3764 loaded.values.get("ECLIPSE_MODEL").map(String::as_str),
3765 Some("m")
3766 );
3767 assert!(
3768 !loaded.values.contains_key("ECLIPSE_API_KEY"),
3769 "an empty assignment is absent: {:?}",
3770 loaded.values.keys().collect::<Vec<_>>()
3771 );
3772 assert!(!loaded.values.contains_key("ECLIPSE_WEB_AUTH_TOKEN"));
3773 }
3774
3775 #[test]
3778 fn a_later_empty_assignment_unsets_an_earlier_one() {
3779 let dir = tempfile::tempdir().unwrap();
3780 let home = dir.path();
3781 std::fs::create_dir_all(home.join(".eclipse").join("profiles/work")).unwrap();
3782 std::fs::write(home.join(".eclipse/.env"), "ECLIPSE_MODEL=big\n").unwrap();
3783 std::fs::write(home.join(".eclipse/profiles/work/.env"), "ECLIPSE_MODEL=\n").unwrap();
3784 let home_s = home.to_str().unwrap().to_string();
3785 let env = env_of(&[("HOME", &home_s)]);
3786 let loaded = Dotenv::load(&env, Some("work")).unwrap();
3787 assert_eq!(loaded.files.len(), 2);
3788 assert_eq!(loaded.values.get("ECLIPSE_MODEL"), None);
3789 }
3790
3791 #[test]
3794 fn the_starter_env_lists_every_variable_and_sets_none_of_them() {
3795 let text = starter_env("tok");
3796 for name in ENV_TEMPLATE {
3797 assert!(
3798 text.contains(&format!("\n{name}=")),
3799 "`{name}` is in the shipped .env"
3800 );
3801 }
3802 for line in text.lines().filter(|l| !l.starts_with('#')) {
3803 let (name, value) = line.split_once('=').expect("KEY=VALUE");
3804 if name == "ECLIPSE_WEB_AUTH_TOKEN" {
3805 assert_eq!(value, "tok", "the one value a first install cannot invent");
3806 } else {
3807 assert!(value.is_empty(), "`{name}` ships unset, found `{value}`");
3808 }
3809 }
3810 }
3811
3812 #[test]
3816 fn every_environment_variable_the_build_reads_is_classified() {
3817 let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("..");
3818 let mut seen = Vec::new();
3819 let mut dirs = vec![
3820 root.join("eclipse-core/src"),
3821 root.join("eclipse-cli/src"),
3822 root.join("eclipse-web/src"),
3823 ];
3824 while let Some(dir) = dirs.pop() {
3825 let Ok(entries) = std::fs::read_dir(&dir) else {
3826 continue;
3827 };
3828 for entry in entries.flatten() {
3829 let path = entry.path();
3830 if path.is_dir() {
3831 dirs.push(path);
3832 continue;
3833 }
3834 if path.extension().and_then(|e| e.to_str()) != Some("rs") {
3835 continue;
3836 }
3837 let text = std::fs::read_to_string(&path).unwrap_or_default();
3838 for name in env_names(&text) {
3839 if !seen.contains(&name) {
3840 seen.push(name);
3841 }
3842 }
3843 }
3844 }
3845 assert!(seen.len() > 10, "the scan found the variables: {seen:?}");
3846 for name in &seen {
3847 let known = ENV_TEMPLATE.contains(&name.as_str())
3848 || ENV_SHELL_ONLY.contains(&name.as_str())
3849 || ENV_INTERNAL.contains(&name.as_str());
3850 assert!(
3851 known,
3852 "`{name}` is read by the build and is in none of ENV_TEMPLATE, ENV_SHELL_ONLY, ENV_INTERNAL"
3853 );
3854 }
3855 let shipped = starter();
3859 for name in ENV_TEMPLATE {
3860 let read = seen.iter().any(|s| s == name);
3861 let interpolated = shipped.contains(&format!("${{{name}"));
3862 assert!(
3863 read || interpolated,
3864 "`{name}` is in the shipped .env and nothing reads or interpolates it"
3865 );
3866 }
3867 }
3868
3869 #[test]
3873 fn every_classified_variable_has_a_description() {
3874 let classified: Vec<&str> = ENV_TEMPLATE
3875 .iter()
3876 .chain(ENV_SHELL_ONLY)
3877 .chain(ENV_INTERNAL)
3878 .copied()
3879 .collect();
3880 for name in &classified {
3881 assert!(
3882 !env_about(name).is_empty(),
3883 "`{name}` is classified and has no line in ENV_ABOUT"
3884 );
3885 }
3886 for (name, about) in ENV_ABOUT {
3887 assert!(
3888 classified.contains(name),
3889 "ENV_ABOUT explains `{name}`, which the build does not read"
3890 );
3891 assert!(
3892 about.len() > 30 && !about.ends_with('.'),
3893 "one sentence, no full stop: {about}"
3894 );
3895 }
3896 }
3897
3898 fn env_names(text: &str) -> Vec<String> {
3901 let mut out = Vec::new();
3902 let mut rest = text;
3903 while let Some(at) = rest.find("\"ECLIPSE_") {
3904 let after = &rest[at + 1..];
3905 let Some(end) = after.find('"') else {
3906 break;
3907 };
3908 let name = &after[..end];
3909 let complete = name
3912 .chars()
3913 .last()
3914 .is_some_and(|c| c.is_ascii_uppercase() || c.is_ascii_digit());
3915 if complete
3916 && name
3917 .chars()
3918 .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')
3919 {
3920 out.push(name.to_string());
3921 }
3922 rest = &after[end + 1..];
3923 }
3924 out
3925 }
3926
3927 #[test]
3928 fn an_empty_optional_string_loads_as_unset() {
3929 let c = Config::from_toml_str(
3932 "[provider]\napi_key = \"\"\napi_key_env = \"\"\nmodel = \"m\"\n[web]\nauth_token = \"\"\n",
3933 )
3934 .unwrap();
3935 assert_eq!(c.provider.api_key, None);
3936 assert_eq!(c.provider.api_key_env, None);
3937 assert_eq!(c.web.auth_token, None);
3938 assert_eq!(c.provider.model, "m");
3940 let dir = tempfile::tempdir().unwrap();
3943 let path = dir.path().join("config.toml");
3944 std::fs::write(&path, "[provider]\napi_key = \"${NOT_SET_ANYWHERE:-}\"\n").unwrap();
3945 let from_var = Config::load_with(Some(&path), &env_of(&[])).unwrap();
3946 assert_eq!(
3947 from_var.provider.api_key, None,
3948 "an absent variable is no key"
3949 );
3950 }
3951
3952 #[test]
3956 fn the_starter_config_carries_every_setting_the_build_reads() {
3957 let text = starter();
3958 let c = parse_text(&text).unwrap();
3959 let settings = Config::default().settings();
3960 assert!(
3961 settings.len() > 80,
3962 "the catalogue is the yardstick: {settings:?}"
3963 );
3964 for setting in &settings {
3965 let key = setting.key.clone();
3966 let present = text.lines().any(|l| {
3967 l.trim_start_matches("# ")
3968 .trim_start()
3969 .starts_with(&format!("{key} ="))
3970 });
3971 assert!(
3972 present,
3973 "[{}] `{key}` is missing from the shipped file:\n{text}",
3974 setting.section
3975 );
3976 }
3977 for line in text.lines().filter(|l| l.starts_with('#')) {
3980 assert!(
3981 line.starts_with("# ") && line[2..].contains(" =") || line.len() < 120,
3982 "a comment in the settings file should be a key, not a sentence: {line}"
3983 );
3984 }
3985 let prose = text
3986 .lines()
3987 .filter(|l| l.starts_with('#') && !l[1..].trim_start().contains(" ="))
3988 .count();
3989 assert!(prose <= 3, "only the three header lines: {prose}");
3990 assert_eq!(c.hooks.order, crate::hooks::DEFAULT_ORDER);
3992 assert_eq!(c.hooks.order, Config::default().hooks.order);
3993 assert!(c.hooks.settings.contains_key("redact-secrets"));
3994 crate::hooks::validate(&c.hooks).expect("the starter config's hooks validate");
3995 assert!(
3996 !c.hooks.settings.contains_key("recall-sessions"),
3997 "a settings table for a hook that is not in `order` cannot run"
3998 );
3999 let value: toml::Value = toml::from_str(&text).unwrap();
4002 let unknown = c.unknown_keys(&value);
4003 assert!(
4004 unknown.is_empty(),
4005 "unknown keys in the shipped file: {unknown:?}"
4006 );
4007 assert_eq!(
4008 c.config_version, CONFIG_VERSION,
4009 "the file stamps its shape"
4010 );
4011 }
4012
4013 #[test]
4014 fn the_hooks_section_survives_a_round_trip_through_the_redacted_printout() {
4015 let c = load_hooks(
4016 "[hooks]\norder = [\"redact-secrets\"]\n[hooks.redact-secrets]\nallow = [\"fx\"]\n",
4017 )
4018 .unwrap();
4019 let shown = c.to_toml_redacted().unwrap();
4020 let again = Config::from_toml_str(&shown).unwrap();
4021 assert_eq!(again.hooks, c.hooks);
4022 }
4023
4024 #[test]
4025 fn defaults_have_no_endpoint_or_key() {
4026 let c = Config::default();
4027 assert!(c.provider.base_url.is_empty());
4028 assert!(c.provider.api_key.is_none());
4029 assert!(c.require_provider().is_err());
4030 assert_eq!(c.tools.write_file, Policy::Allow);
4033 assert_eq!(c.tools.shell, Policy::Ask);
4034 assert_eq!(c.tools.shell_ask, ShellAsk::Dangerous);
4035 }
4036
4037 #[test]
4038 fn cli_section_defaults_and_parses() {
4039 let d = Config::from_toml_str("").unwrap().cli;
4041 assert_eq!(d.color, None);
4042 assert_eq!(d.markdown, None);
4043 assert_eq!(d.approval, Approval::Ask);
4044 assert_eq!(d.history_size, 1000);
4045
4046 let c = Config::from_toml_str(
4047 "[cli]\ncolor = false\nmarkdown = true\napproval = \"auto\"\nhistory_size = 50\n",
4048 )
4049 .unwrap()
4050 .cli;
4051 assert_eq!(c.color, Some(false));
4052 assert_eq!(c.markdown, Some(true));
4053 assert_eq!(c.approval, Approval::Auto);
4054 assert_eq!(c.history_size, 50);
4055 }
4056
4057 #[test]
4058 fn an_unknown_approval_is_an_error_rather_than_a_silent_ask() {
4059 let err = Config::from_toml_str("[cli]\napproval = \"sometimes\"\n").unwrap_err();
4062 assert!(err.contains("approval"), "{err}");
4063 }
4064
4065 #[test]
4066 fn web_section_parses_its_ttl_and_default_profile() {
4067 let d = Config::from_toml_str("").unwrap().web;
4068 assert_eq!(d.session_ttl_hours, DEFAULT_SESSION_TTL_HOURS);
4069 assert_eq!(d.default_profile, None);
4070
4071 let w = Config::from_toml_str("[web]\nsession_ttl_hours = 1\ndefault_profile = \"work\"\n")
4072 .unwrap()
4073 .web;
4074 assert_eq!(w.session_ttl_hours, 1);
4075 assert_eq!(w.default_profile.as_deref(), Some("work"));
4076 }
4077
4078 #[test]
4082 fn the_starter_config_loads_without_a_dotenv_and_leaves_the_token_unset() {
4083 let dir = tempfile::tempdir().unwrap();
4084 let path = dir.path().join("config.toml");
4085 std::fs::write(&path, starter()).unwrap();
4086 let c = Config::load_with(Some(&path), &|_| None)
4089 .expect("the starter config loads with no .env at all");
4090 assert_eq!(
4091 c.web.auth_token, None,
4092 "an unset token loads as no token, not as a load error and not as an empty secret"
4093 );
4094 assert_eq!(c.provider.model, Config::default().provider.model);
4095 }
4096
4097 #[test]
4098 fn starter_config_parses_and_matches_defaults() {
4099 let c = Config::from_toml_str(&starter()).unwrap();
4100 let d = Config::default();
4101 assert_eq!(c.tools.read_file, d.tools.read_file);
4102 assert_eq!(c.tools.fetch, d.tools.fetch);
4103 assert_eq!(c.web.port, d.web.port);
4104 assert!(c.provider.base_url.is_empty());
4105 }
4106
4107 #[test]
4108 fn partial_file_fills_defaults() {
4109 let c = Config::from_toml_str(
4110 "[provider]\nbase_url=\"http://x/v1\"\nmodel=\"m\"\n[tools]\nshell=\"deny\"\n",
4111 )
4112 .unwrap();
4113 assert_eq!(c.provider.base_url, "http://x/v1");
4114 assert_eq!(c.tools.shell, Policy::Deny);
4115 assert_eq!(c.tools.write_file, Policy::Allow);
4116 assert_eq!(
4117 c.agent.max_iterations,
4118 usize::MAX,
4119 "no cap unless the box asks for one"
4120 );
4121 assert!(c.require_provider().is_ok());
4122
4123 for word in ["unlimited", "none", "inf", "0", "-1"] {
4124 let raw = format!("[agent]\nmax_iterations = {word}\n");
4125 let raw = if word.parse::<i64>().is_ok() {
4126 raw
4127 } else {
4128 format!("[agent]\nmax_iterations = \"{word}\"\n")
4129 };
4130 let c = Config::from_toml_str(&raw).unwrap();
4131 assert_eq!(c.agent.max_iterations, usize::MAX, "`{word}` means no cap");
4132 }
4133
4134 let c = Config::from_toml_str("[agent]\nmax_iterations = 12\n").unwrap();
4135 assert_eq!(c.agent.max_iterations, 12, "a number is a cap");
4136
4137 let words = Config::from_toml_str("[agent]\nmax_iterations = \"unlimited\"\n").unwrap();
4138 let printed = toml::to_string(&words).unwrap();
4139 assert!(
4140 printed.contains("max_iterations = \"unlimited\""),
4141 "the schema says the word, not a length: {printed}"
4142 );
4143
4144 let refused = Config::from_toml_str("[agent]\nmax_iterations = \"plenty\"\n");
4145 assert!(
4146 refused.is_err(),
4147 "a word that is not one of ours is an error"
4148 );
4149 }
4150
4151 #[test]
4152 fn unknown_policy_is_rejected() {
4153 assert!(Config::from_toml_str("[tools]\nshell=\"yolo\"\n").is_err());
4154 }
4155
4156 #[test]
4157 fn env_overrides_file() {
4158 let dir = tempfile::tempdir().unwrap();
4159 let p = dir.path().join("c.toml");
4160 std::fs::write(
4161 &p,
4162 "[provider]\nbase_url=\"http://file/v1\"\nmodel=\"file-model\"\napi_key=\"file-key\"\n",
4163 )
4164 .unwrap();
4165 let env = env_of(&[
4166 ("ECLIPSE_BASE_URL", "http://env/v1"),
4167 ("ECLIPSE_API_KEY", "env-key"),
4168 ]);
4169 let c = Config::load_with(Some(&p), &env).unwrap();
4170 assert_eq!(c.provider.base_url, "http://env/v1");
4171 assert_eq!(c.provider.model, "file-model");
4172 assert_eq!(c.provider.api_key.as_deref(), Some("env-key"));
4173 }
4174
4175 #[test]
4176 fn api_key_env_indirection() {
4177 let env = env_of(&[("MY_KEY", "secret")]);
4178 let mut c = Config::from_toml_str("[provider]\napi_key_env=\"MY_KEY\"\n").unwrap();
4179 c.apply_env(&env);
4180 assert_eq!(c.provider.api_key.as_deref(), Some("secret"));
4181 }
4182
4183 #[test]
4184 fn debug_redacts_api_key() {
4185 let mut c = Config::default();
4186 c.provider.api_key = Some("hunter2".into());
4187 assert!(!format!("{c:?}").contains("hunter2"));
4188 }
4189
4190 #[test]
4191 fn debug_and_redacted_toml_hide_web_token() {
4192 let mut c = Config::default();
4193 c.web.auth_token = Some("s3cret-token-value".into());
4194 assert!(!format!("{c:?}").contains("s3cret"));
4195 assert!(!c.to_toml_redacted().unwrap().contains("s3cret"));
4196 }
4197
4198 #[test]
4202 fn debug_never_prints_a_dotenv_value() {
4203 let dir = tempfile::tempdir().unwrap();
4204 let root = dir.path().join("root");
4205 std::fs::create_dir_all(&root).unwrap();
4206 std::fs::write(
4207 root.join(".env"),
4208 "ECLIPSE_API_KEY=dotenvvalue123\nMY_PRIVATE_MIRROR=mirrorvalue456\n",
4209 )
4210 .unwrap();
4211 let cfg_path = root.join("config.toml");
4212 std::fs::write(
4213 &cfg_path,
4214 "[provider]\nbase_url = \"http://127.0.0.1:9/v1\"\nmodel = \"m\"\napi_key = \"${ECLIPSE_API_KEY}\"\n",
4215 )
4216 .unwrap();
4217 let env = env_of(&[
4218 ("ECLIPSE_HOME", root.to_str().unwrap()),
4219 ("HOME", dir.path().to_str().unwrap()),
4220 ]);
4221
4222 let cfg = Config::load_with_profile(Some(&cfg_path), None, &env).unwrap();
4223 let debug = format!("{cfg:?}");
4224 assert!(
4225 !debug.contains("dotenvvalue123") && !debug.contains("mirrorvalue456"),
4226 "the .env values must never be printed: {debug}"
4227 );
4228 assert!(debug.contains("ECLIPSE_API_KEY"), "{debug}");
4229 assert!(debug.contains("Dotenv"), "{debug}");
4230 assert_eq!(cfg.provider.api_key.as_deref(), Some("dotenvvalue123"));
4232 }
4233
4234 #[test]
4235 fn redacted_toml_hides_key_and_round_trips() {
4236 let mut c = Config::default();
4237 c.provider.api_key = Some("hunter2".into());
4238 c.provider.model = "m".into();
4239 let t = c.to_toml_redacted().unwrap();
4240 assert!(!t.contains("hunter2"));
4241 assert_eq!(Config::from_toml_str(&t).unwrap().provider.model, "m");
4242 }
4243
4244 #[test]
4248 fn the_update_track_names_a_branch_and_takes_two_words() {
4249 assert_eq!(Config::default().update.track, Track::Release);
4250 assert_eq!(Track::Release.branch(), "main");
4251 assert_eq!(Track::Develop.branch(), "develop");
4252 let cfg = Config::from_toml_str("[update]\ntrack = \"develop\"\n").unwrap();
4253 assert_eq!(cfg.update.track, Track::Develop);
4254 assert_eq!(cfg.update.track.label(), "develop");
4255 let err = Config::from_toml_str("[update]\ntrack = \"main\"\n")
4256 .unwrap_err()
4257 .to_string();
4258 assert!(
4259 err.contains("main") && err.contains("develop"),
4260 "the refusal lists the words it takes: {err}"
4261 );
4262 }
4263
4264 #[test]
4267 fn a_url_keeps_its_shape_and_loses_its_secrets() {
4268 let mut c = Config::default();
4269 c.provider.base_url = "https://user:hunter2@gw.internal/v1".into();
4270 c.update.remote =
4271 Some("https://mirror.internal/releases?access_token=abc123&page=2".into());
4272 c.update.releases = Some("https://mirror.internal/api#frag".into());
4273
4274 let t = c.to_toml_redacted().unwrap();
4275 assert!(
4276 !t.contains("hunter2") && !t.contains("abc123"),
4277 "the secrets are gone: {t}"
4278 );
4279 assert!(
4281 t.contains("https://<redacted>@gw.internal/v1"),
4282 "the userinfo is replaced, not the URL: {t}"
4283 );
4284 assert!(
4285 t.contains("access_token=<redacted>&page=2"),
4286 "the secret parameter keeps its name and loses its value: {t}"
4287 );
4288 assert!(t.contains("https://mirror.internal/api#frag"), "{t}");
4289
4290 let debug = format!("{c:?}");
4292 assert!(!debug.contains("hunter2"), "{debug}");
4293
4294 let plain = Config::default();
4296 assert!(plain
4297 .to_toml_redacted()
4298 .unwrap()
4299 .contains(&plain.provider.base_url));
4300 }
4301
4302 #[test]
4303 fn one_root_layout() {
4304 let env = env_of(&[("HOME", "/home/u")]);
4306 assert_eq!(
4307 config_path(&env).unwrap(),
4308 PathBuf::from("/home/u/.eclipse/config.toml")
4309 );
4310 assert_eq!(
4311 Config::default().sessions_dir(&env).unwrap(),
4312 PathBuf::from("/home/u/.eclipse/state/sessions")
4313 );
4314 assert_eq!(
4315 Config::default().memory_dir(&env).unwrap(),
4316 PathBuf::from("/home/u/.eclipse/memory")
4317 );
4318 let env = env_of(&[
4321 ("HOME", "/home/u"),
4322 ("XDG_CONFIG_HOME", "/x/cfg"),
4323 ("XDG_STATE_HOME", "/x/state"),
4324 ]);
4325 assert_eq!(
4326 config_path(&env).unwrap(),
4327 PathBuf::from("/home/u/.eclipse/config.toml")
4328 );
4329 let env = env_of(&[("HOME", "/home/u"), ("ECLIPSE_HOME", "/opt/ecl")]);
4331 assert_eq!(
4332 config_path(&env).unwrap(),
4333 PathBuf::from("/opt/ecl/config.toml")
4334 );
4335 }
4336
4337 #[test]
4338 fn missing_default_file_is_ok_but_explicit_missing_is_error() {
4339 let dir = tempfile::tempdir().unwrap();
4340 let env = env_of(&[("HOME", dir.path().to_str().unwrap())]);
4341 assert!(Config::load_with(None, &env).is_ok());
4342 assert!(Config::load_with(Some(&dir.path().join("nope.toml")), &env).is_err());
4343 }
4344
4345 #[test]
4346 fn auto_prune_is_off_by_default_and_can_be_enabled() {
4347 assert!(!Config::default().sessions.auto_prune);
4348 let c = Config::from_toml_str("[sessions]\nauto_prune = true\nretention_keep_count = 5\n")
4349 .unwrap();
4350 assert!(c.sessions.auto_prune);
4351 assert_eq!(c.sessions.retention_keep_count, 5);
4352 }
4353
4354 #[test]
4355 fn sessions_dir_expands_tilde() {
4356 let env = env_of(&[("HOME", "/home/u")]);
4357 let mut c = Config::default();
4358 c.sessions.dir = Some("~/s".into());
4359 assert_eq!(c.sessions_dir(&env).unwrap(), PathBuf::from("/home/u/s"));
4360 }
4361
4362 #[test]
4363 fn config_init_writes_a_private_dotenv_and_the_config_refers_to_it() {
4364 let dir = tempfile::tempdir().unwrap();
4365 let p = dir.path().join("a/b/config.toml");
4366 let env = env_of(&[("ECLIPSE_HOME", dir.path().to_str().unwrap())]);
4367 let report = write_starter_config(&p, false, &env).unwrap();
4368 assert!(report.dotenv_written);
4369 assert_eq!(
4370 report.dotenv,
4371 dir.path().join(".env"),
4372 "the .env goes where the loader reads it, not beside a config elsewhere"
4373 );
4374
4375 let dotenv = std::fs::read_to_string(&report.dotenv).unwrap();
4376 let token = dotenv
4377 .lines()
4378 .find_map(|l| l.strip_prefix("ECLIPSE_WEB_AUTH_TOKEN="))
4379 .expect("the token lives in .env");
4380 assert_eq!(token.len(), 64, "a generated token, not a placeholder");
4381 assert!(token.bytes().all(|b| b.is_ascii_hexdigit()));
4382 assert!(
4383 !std::fs::read_to_string(&p).unwrap().contains(token),
4384 "the config carries the reference, never the secret"
4385 );
4386
4387 #[cfg(unix)]
4388 {
4389 use std::os::unix::fs::PermissionsExt;
4390 for f in [&p, &report.dotenv] {
4391 assert_eq!(f.metadata().unwrap().permissions().mode() & 0o777, 0o600);
4392 }
4393 }
4394
4395 let root = dir.path().join("root");
4398 let cfg_dir = root.clone();
4399 std::fs::create_dir_all(&cfg_dir).unwrap();
4400 let real = cfg_dir.join("config.toml");
4401 let env = env_of(&[
4402 ("ECLIPSE_HOME", root.to_str().unwrap()),
4403 ("HOME", dir.path().to_str().unwrap()),
4404 ]);
4405 let written = write_starter_config(&real, false, &env).unwrap();
4406 let cfg = Config::load_with_profile(Some(&real), None, &env).unwrap();
4407 let token = std::fs::read_to_string(&written.dotenv)
4408 .unwrap()
4409 .lines()
4410 .find_map(|l| {
4411 l.strip_prefix("ECLIPSE_WEB_AUTH_TOKEN=")
4412 .map(str::to_string)
4413 })
4414 .unwrap();
4415 assert_eq!(cfg.web.auth_token.as_deref(), Some(token.as_str()));
4416 assert_eq!(cfg.dotenv.files, vec![written.dotenv]);
4417 }
4418
4419 #[test]
4423 fn an_empty_dotenv_value_is_absent_not_an_empty_override() {
4424 let dir = tempfile::tempdir().unwrap();
4425 let root = dir.path().join("root");
4426 std::fs::create_dir_all(&root).unwrap();
4427 std::fs::write(
4428 root.join(".env"),
4429 "ECLIPSE_API_KEY=\nECLIPSE_MODEL=\nECLIPSE_BASE_URL=\n",
4430 )
4431 .unwrap();
4432 let cfg_path = root.join("config.toml");
4433 std::fs::write(
4434 &cfg_path,
4435 "[provider]\napi_key = \"sk-from-the-file\"\nmodel = \"keep-me\"\n\
4436 base_url = \"http://127.0.0.1:9999/v1\"\n",
4437 )
4438 .unwrap();
4439 let env = env_of(&[
4440 ("ECLIPSE_HOME", root.to_str().unwrap()),
4441 ("HOME", dir.path().to_str().unwrap()),
4442 ]);
4443
4444 let cfg = Config::load_with_profile(Some(&cfg_path), None, &env).unwrap();
4445 assert_eq!(
4446 cfg.provider.api_key.as_deref(),
4447 Some("sk-from-the-file"),
4448 "an empty .env value must not blank the key"
4449 );
4450 assert_eq!(cfg.provider.model, "keep-me", "nor the model");
4451 assert_eq!(
4452 cfg.provider.base_url, "http://127.0.0.1:9999/v1",
4453 "nor the base URL"
4454 );
4455 }
4456
4457 #[test]
4458 fn context_files_are_seeded_and_existing_ones_are_kept() {
4459 let tmp = tempfile::tempdir().unwrap();
4460 let memory = tmp.path().join("memory");
4461 let created = seed_context_files(&memory).unwrap();
4462 assert_eq!(created.len(), 3, "AGENT, USER, MEMORY: {created:?}");
4463 assert!(memory.join("AGENT.md").exists());
4464 assert!(memory.join("USER.md").exists());
4465 assert!(memory.join("MEMORY.md").exists());
4466 assert_eq!(
4467 std::fs::read_to_string(memory.join("MEMORY.md")).unwrap(),
4468 ""
4469 );
4470
4471 let created = seed_context_files(&memory).unwrap();
4473 assert!(
4474 created.is_empty(),
4475 "existing files are left alone: {created:?}"
4476 );
4477
4478 let written = [
4482 ("AGENT.md", "run make, no cargo test\n"),
4483 ("USER.md", "I am the operator; keep it short\n"),
4484 ("MEMORY.md", "- one durable fact\n"),
4485 ];
4486 for (name, body) in written {
4487 std::fs::write(memory.join(name), body).unwrap();
4488 }
4489 let created = seed_context_files(&memory).unwrap();
4490 assert!(created.is_empty(), "{created:?}");
4491 for (name, body) in written {
4492 assert_eq!(
4493 std::fs::read_to_string(memory.join(name)).unwrap(),
4494 body,
4495 "{name} was rewritten"
4496 );
4497 }
4498 }
4499
4500 #[test]
4505 fn a_new_profile_is_a_first_install_and_an_existing_one_is_never_rewritten() {
4506 let tmp = tempfile::tempdir().unwrap();
4507 let base = tmp.path().join("memory");
4508 let lived_in = tmp.path().join("profiles/work/memory");
4509 let fresh = tmp.path().join("profiles/lab/memory");
4510
4511 assert_eq!(seed_context_files(&base).unwrap().len(), 3);
4512 std::fs::write(base.join("USER.md"), "the operator\n").unwrap();
4513
4514 std::fs::create_dir_all(&lived_in).unwrap();
4515 for name in ["AGENT.md", "USER.md", "MEMORY.md"] {
4516 std::fs::write(lived_in.join(name), format!("{name} as it was lived in\n")).unwrap();
4517 }
4518
4519 assert!(
4520 seed_context_files(&lived_in).unwrap().is_empty(),
4521 "an existing profile's files are not rewritten"
4522 );
4523 assert_eq!(
4524 seed_context_files(&fresh).unwrap().len(),
4525 3,
4526 "a profile that has never been used is a first install"
4527 );
4528
4529 assert_eq!(
4530 std::fs::read_to_string(base.join("USER.md")).unwrap(),
4531 "the operator\n"
4532 );
4533 for name in ["AGENT.md", "USER.md", "MEMORY.md"] {
4534 assert_eq!(
4535 std::fs::read_to_string(lived_in.join(name)).unwrap(),
4536 format!("{name} as it was lived in\n")
4537 );
4538 }
4539 }
4540
4541 #[test]
4545 fn config_init_puts_the_dotenv_where_a_start_with_that_config_will_read_it() {
4546 let dir = tempfile::tempdir().unwrap();
4547 let home = dir.path().join("home");
4548 std::fs::create_dir_all(&home).unwrap();
4549 let elsewhere = dir.path().join("other");
4550 let path = elsewhere.join("config.toml");
4551 let env = env_of(&[
4552 ("ECLIPSE_HOME", home.to_str().unwrap()),
4553 ("HOME", dir.path().to_str().unwrap()),
4554 ]);
4555
4556 let report = write_starter_config(&path, false, &env).unwrap();
4557 let token = std::fs::read_to_string(&report.dotenv)
4558 .unwrap()
4559 .lines()
4560 .find_map(|l| l.strip_prefix("ECLIPSE_WEB_AUTH_TOKEN="))
4561 .expect("the token lives in .env")
4562 .to_string();
4563 assert_eq!(report.dotenv, home.join(".env"));
4564
4565 let cfg = Config::load_with_profile(Some(&path), None, &env).unwrap();
4566 assert_eq!(
4567 cfg.web.auth_token.as_deref(),
4568 Some(token.as_str()),
4569 "the token `config init` reported is the token the next start reads"
4570 );
4571 }
4572
4573 #[test]
4574 fn config_init_refuses_to_overwrite_a_config_without_force() {
4575 let dir = tempfile::tempdir().unwrap();
4576 let p = dir.path().join("c/config.toml");
4577 let env = env_of(&[("ECLIPSE_HOME", dir.path().to_str().unwrap())]);
4578 write_starter_config(&p, false, &env).unwrap();
4579 assert!(write_starter_config(&p, false, &env).is_err());
4580 }
4581
4582 #[test]
4583 fn config_init_never_overwrites_an_existing_dotenv() {
4584 let dir = tempfile::tempdir().unwrap();
4585 let p = dir.path().join("d/config.toml");
4586 let env = env_of(&[("ECLIPSE_HOME", dir.path().to_str().unwrap())]);
4587 let first = write_starter_config(&p, false, &env).unwrap();
4588 let before = std::fs::read_to_string(&first.dotenv).unwrap();
4589
4590 let again = write_starter_config(&p, true, &env).unwrap();
4592 assert!(!again.dotenv_written);
4593 assert_eq!(std::fs::read_to_string(&again.dotenv).unwrap(), before);
4594 }
4595
4596 #[test]
4597 fn a_profile_overlay_merges_over_the_base_config() {
4598 let tmp = tempfile::tempdir().unwrap();
4599 let home = tmp.path().join("home");
4600 let cfg_dir = home.join(".eclipse");
4601 std::fs::create_dir_all(cfg_dir.join("profiles/work")).unwrap();
4602 std::fs::write(
4603 cfg_dir.join("config.toml"),
4604 "[provider]\nbase_url = \"http://base/v1\"\nmodel = \"base-model\"\n\
4605 temperature = 0.2\n[agent]\nmax_iterations = 7\n",
4606 )
4607 .unwrap();
4608 std::fs::write(
4609 cfg_dir.join("profiles/work/config.toml"),
4610 "[provider]\nmodel = \"work-model\"\n",
4611 )
4612 .unwrap();
4613 let env = env_of(&[("HOME", home.to_str().unwrap())]);
4614
4615 let base = Config::load_with(None, &env).unwrap();
4616 assert_eq!(base.provider.model, "base-model");
4617 assert_eq!(base.profile_name(), "default");
4618
4619 let work = Config::load_with_profile(None, Some("work"), &env).unwrap();
4620 assert_eq!(work.provider.model, "work-model");
4622 assert_eq!(work.provider.base_url, "http://base/v1");
4623 assert_eq!(work.provider.temperature, Some(0.2));
4624 assert_eq!(work.agent.max_iterations, 7);
4625 assert_eq!(work.profile_name(), "work");
4626 assert_eq!(
4628 work.sessions_dir(&env).unwrap(),
4629 home.join(".eclipse/profiles/work/state/sessions")
4630 );
4631 assert_eq!(
4632 base.sessions_dir(&env).unwrap(),
4633 home.join(".eclipse/state/sessions")
4634 );
4635 assert_eq!(
4636 work.state_dir(&env).unwrap(),
4637 home.join(".eclipse/profiles/work/state")
4638 );
4639 }
4640
4641 #[test]
4642 fn the_profile_comes_from_the_environment_and_the_argument_wins() {
4643 let tmp = tempfile::tempdir().unwrap();
4644 let home = tmp.path().join("home");
4645 std::fs::create_dir_all(home.join(".eclipse/profiles/env")).unwrap();
4646 std::fs::write(
4647 home.join(".eclipse/profiles/env/config.toml"),
4648 "[agent]\nmax_iterations = 3\n",
4649 )
4650 .unwrap();
4651 let env = env_of(&[("HOME", home.to_str().unwrap()), ("ECLIPSE_PROFILE", "env")]);
4652 let from_env = Config::load_with(None, &env).unwrap();
4653 assert_eq!(from_env.profile_name(), "env");
4654 assert_eq!(from_env.agent.max_iterations, 3);
4655
4656 let explicit = Config::load_with_profile(None, Some("other"), &env).unwrap();
4657 assert_eq!(explicit.profile_name(), "other");
4658 assert_eq!(explicit.agent.max_iterations, usize::MAX);
4660 }
4661
4662 #[test]
4663 fn the_default_profile_keeps_the_plain_state_directory() {
4664 let env = env_of(&[("HOME", "/home/u")]);
4665 assert_eq!(
4666 state_dir_for(&env, Some("default")).unwrap(),
4667 PathBuf::from("/home/u/.eclipse/state")
4668 );
4669 assert_eq!(
4670 state_dir_for(&env, None).unwrap(),
4671 PathBuf::from("/home/u/.eclipse/state")
4672 );
4673 assert_eq!(
4674 state_dir_for(&env, Some("work")).unwrap(),
4675 PathBuf::from("/home/u/.eclipse/profiles/work/state")
4676 );
4677 }
4678
4679 #[test]
4680 fn a_profile_name_must_be_a_safe_directory_name() {
4681 for bad in ["", "../etc", "a/b", "sp ace"] {
4682 assert!(
4683 validate_profile_name(bad).is_err(),
4684 "{bad:?} should be rejected"
4685 );
4686 }
4687 assert!(validate_profile_name("work-2026_x").is_ok());
4688 let env = env_of(&[("HOME", "/home/u")]);
4689 assert!(Config::load_with_profile(None, Some("../evil"), &env).is_err());
4690 }
4691
4692 #[test]
4693 fn plugin_directories_put_the_profile_first() {
4694 let tmp = tempfile::tempdir().unwrap();
4695 let home = tmp.path().join("home");
4696 std::fs::create_dir_all(home.join(".eclipse")).unwrap();
4697 let env = env_of(&[("HOME", home.to_str().unwrap())]);
4698 let mut cfg = Config::default();
4699 let default_dirs = cfg.plugins_dirs(&env);
4700 assert_eq!(
4701 default_dirs,
4702 vec![home.join(".eclipse/plugins")],
4703 "the default profile has no profile plugin dir"
4704 );
4705
4706 cfg.profile = Some("work".into());
4707 let dirs = cfg.plugins_dirs(&env);
4708 assert_eq!(dirs.len(), 2);
4709 assert_eq!(dirs[0], home.join(".eclipse/profiles/work/plugins"));
4710 assert_eq!(dirs[1], home.join(".eclipse/plugins"));
4711
4712 cfg.plugins.dir = Some("~/elsewhere/plugins".into());
4713 assert_eq!(cfg.plugins_dirs(&env)[1], home.join("elsewhere/plugins"));
4714 }
4715
4716 #[test]
4717 fn plugins_are_off_until_named() {
4718 let cfg = Config::default();
4719 assert!(cfg.plugins.enabled.is_empty());
4720 assert!(cfg.plugins.dir.is_none());
4721 let parsed = Config::from_toml_str("[plugins]\nenabled = [\"a\", \"b\"]\n").unwrap();
4722 assert_eq!(parsed.plugins.enabled, ["a", "b"]);
4723 }
4724
4725 #[test]
4728 fn setting_a_key_fills_the_empty_value_and_keeps_every_other_line() {
4729 let text = toml_set_string(&starter(), "provider", "base_url", "http://h:1/v1");
4730 let text = toml_set_string(&text, "provider", "model", "some-model");
4731 assert!(text.contains("base_url = \"http://h:1/v1\""), "{text}");
4732 assert!(text.contains("model = \"some-model\""), "{text}");
4733 assert!(text.contains("# Every setting this build reads"));
4735 assert!(text.contains("[agent]"));
4736 assert!(
4737 !text.contains("base_url = \"\""),
4738 "the empty blank must be gone: {text}"
4739 );
4740 let cfg: Config = toml::from_str(&text).expect("edited config must parse");
4742 assert_eq!(cfg.provider.base_url, "http://h:1/v1");
4743 assert_eq!(cfg.provider.model, "some-model");
4744 }
4745
4746 #[test]
4747 fn setting_a_key_turns_a_commented_template_line_into_the_real_one() {
4748 let text = toml_set_string(&starter(), "provider", "profile", "llamacpp");
4749 assert!(text.contains("\nprofile = \"llamacpp\""), "{text}");
4750 assert_eq!(
4751 text.matches("\nprofile = ").count(),
4752 1,
4753 "no duplicate key (the commented [web] default_profile is a different key): {text}"
4754 );
4755 let cfg: Config = toml::from_str(&text).unwrap();
4756 assert_eq!(cfg.provider.profile.as_deref(), Some("llamacpp"));
4757 }
4758
4759 #[test]
4760 fn setting_a_key_does_not_reach_into_another_section_with_the_same_name() {
4761 let text = toml_set_string(&starter(), "sessions", "dir", "/tmp/sessions-here");
4763 let cfg: Config = toml::from_str(&text).unwrap();
4764 assert_eq!(
4765 cfg.sessions.dir.as_deref(),
4766 Some(std::path::Path::new("/tmp/sessions-here"))
4767 );
4768 assert_eq!(cfg.plugins.dir, None, "{text}");
4769 }
4770
4771 #[test]
4772 fn setting_a_key_in_a_missing_section_adds_the_section() {
4773 let text = toml_set_string("[agent]\nmax_iterations = 5\n", "web", "host", "0.0.0.0");
4774 let cfg: Config = toml::from_str(&text).unwrap();
4775 assert_eq!(cfg.web.host, "0.0.0.0");
4776 assert_eq!(cfg.agent.max_iterations, 5);
4777 }
4778
4779 #[test]
4780 fn reading_a_key_sees_the_live_line_and_not_the_commented_one() {
4781 let text = starter();
4782 assert_eq!(
4783 toml_value(&text, "provider", "base_url"),
4784 Some(String::new())
4785 );
4786 assert_eq!(toml_value(&text, "provider", "temperature"), None);
4790 assert!(text.contains("# temperature ="), "{text}");
4791 assert_eq!(
4792 toml_value(&text, "agent", "max_iterations"),
4793 Some("unlimited".to_string()),
4794 "the cap is written, and its off value is the word `unlimited`"
4795 );
4796 }
4797
4798 #[test]
4799 fn a_config_written_by_setup_is_private_and_a_dotenv_keeps_its_other_lines() {
4800 let dir = tempfile::tempdir().unwrap();
4801 let cfg_path = dir.path().join("config.toml");
4802 let dotenv = dir.path().join(".env");
4803 save_config_text(&cfg_path, "[provider]\nbase_url = \"h\"\n").unwrap();
4804 save_dotenv_var(&dotenv, "ECLIPSE_WEB_AUTH_TOKEN", "tok").unwrap();
4805 save_dotenv_var(&dotenv, "ECLIPSE_API_KEY", "sk-1").unwrap();
4806 save_dotenv_var(&dotenv, "ECLIPSE_API_KEY", "sk-2").unwrap();
4807 let body = std::fs::read_to_string(&dotenv).unwrap();
4808 assert_eq!(body.matches("ECLIPSE_API_KEY").count(), 1, "{body}");
4809 assert_eq!(
4810 dotenv_var(&dotenv, "ECLIPSE_API_KEY").as_deref(),
4811 Some("sk-2")
4812 );
4813 assert_eq!(
4814 dotenv_var(&dotenv, "ECLIPSE_WEB_AUTH_TOKEN").as_deref(),
4815 Some("tok"),
4816 "an unrelated secret must survive"
4817 );
4818 #[cfg(unix)]
4819 {
4820 use std::os::unix::fs::PermissionsExt;
4821 for f in [&cfg_path, &dotenv] {
4822 let mode = std::fs::metadata(f).unwrap().permissions().mode() & 0o777;
4823 assert_eq!(mode, 0o600, "{}", f.display());
4824 }
4825 }
4826 }
4827
4828 #[test]
4829 fn trace_content_is_off_by_default_and_can_be_set() {
4830 assert!(!Config::default().agent.trace_content);
4831 let cfg = Config::from_toml_str(
4832 "[agent]
4833trace_content = true
4834",
4835 )
4836 .unwrap();
4837 assert!(cfg.agent.trace_content);
4838 }
4839
4840 #[test]
4841 fn an_output_schema_is_absent_until_somebody_asks_for_one() {
4842 assert_eq!(Config::default().agent.output_schema, None);
4845 let cfg = Config::from_toml_str(
4846 "[agent]
4847output_schema = \"schemas/plan.json\"
4848",
4849 )
4850 .unwrap();
4851 assert_eq!(
4852 cfg.agent.output_schema.as_deref(),
4853 Some("schemas/plan.json")
4854 );
4855 }
4856
4857 #[test]
4858 fn the_user_section_has_the_defaults_the_docs_promise() {
4859 let cfg = Config::default();
4860 assert_eq!(cfg.user.file, "USER.md");
4861 assert_eq!(cfg.user.memory_file, "MEMORY.md");
4862 assert_eq!(cfg.user.memory_budget_chars, 3000);
4863 assert_eq!(
4864 cfg.agent.context_file_max_chars,
4865 crate::context_files::DEFAULT_MAX_FILE_CHARS
4866 );
4867 assert_eq!(
4868 cfg.agent.context_files_budget_chars,
4869 crate::context_files::DEFAULT_BUDGET_CHARS
4870 );
4871 }
4872
4873 #[test]
4874 fn the_context_and_memory_budgets_can_be_set_in_the_file() {
4875 let cfg = Config::from_toml_str(
4876 "[agent]\ncontext_file_max_chars = 100\ncontext_files_budget_chars = 200\n\
4877 [user]\nfile = \"WHO.md\"\nmemory_file = \"FACTS.md\"\nmemory_budget_chars = 50\n",
4878 )
4879 .unwrap();
4880 assert_eq!(cfg.agent.context_file_max_chars, 100);
4881 assert_eq!(cfg.agent.context_files_budget_chars, 200);
4882 assert_eq!(cfg.user.file, "WHO.md");
4883 assert_eq!(cfg.user.memory_file, "FACTS.md");
4884 assert_eq!(cfg.user.memory_budget_chars, 50);
4885 }
4886
4887 #[test]
4888 fn the_default_profile_keeps_its_files_in_the_config_directory() {
4889 let env = |k: &str| match k {
4890 "HOME" => Some("/home/m".to_string()),
4891 _ => None,
4892 };
4893 let mut cfg = Config::default();
4894 assert_eq!(
4895 cfg.context_dir(&env),
4896 Some(PathBuf::from("/home/m/.eclipse"))
4897 );
4898 cfg.profile = Some("work".into());
4899 assert_eq!(
4900 cfg.context_dir(&env),
4901 Some(PathBuf::from("/home/m/.eclipse/profiles/work"))
4902 );
4903 }
4904
4905 #[test]
4906 fn scripts_live_under_the_profile_when_there_is_one_and_the_config_directory_otherwise() {
4907 let env = |k: &str| match k {
4908 "HOME" => Some("/home/m".to_string()),
4909 _ => None,
4910 };
4911 let mut cfg = Config::default();
4912 assert_eq!(
4913 cfg.scripts_dir(&env),
4914 Some(PathBuf::from("/home/m/.eclipse/scripts"))
4915 );
4916 cfg.profile = Some("work".into());
4917 assert_eq!(
4918 cfg.scripts_dir(&env),
4919 Some(PathBuf::from("/home/m/.eclipse/profiles/work/scripts"))
4920 );
4921 let no_home = |_: &str| None;
4922 assert_eq!(Config::default().scripts_dir(&no_home), None);
4923 }
4924
4925 #[test]
4926 fn a_relative_config_path_still_gives_an_absolute_scripts_directory() {
4927 let env = |k: &str| match k {
4928 "ECLIPSE_CONFIG" => Some("rel/config.toml".to_string()),
4929 _ => None,
4930 };
4931 let dir = Config::default().scripts_dir(&env).unwrap();
4932 assert!(dir.is_absolute(), "{}", dir.display());
4933 assert!(dir.ends_with("rel/scripts"), "{}", dir.display());
4934 }
4935
4936 #[test]
4937 fn the_script_tool_is_asked_about_by_default_and_the_policy_can_be_set_in_the_file() {
4938 assert_eq!(Config::default().tools.script, Policy::Ask);
4939 let cfg = Config::from_toml_str("[tools]\nscript = \"deny\"\n").unwrap();
4940 assert_eq!(cfg.tools.script, Policy::Deny);
4941 let starter = Config::from_toml_str(&super::tests::starter()).unwrap();
4942 assert_eq!(starter.tools.script, Policy::Ask);
4943 assert!(Config::from_toml_str("[tools]\nscript = \"yolo\"\n").is_err());
4944 }
4945
4946 #[test]
4947 fn sight_defaults_to_auto_with_no_route_and_no_cloud() {
4948 let cfg = Config::default();
4949 assert_eq!(cfg.vision.mode, VisionMode::Auto);
4950 assert_eq!(cfg.vision.route, "");
4951 assert!(!cfg.vision.allow_cloud);
4952 }
4953
4954 #[test]
4955 fn the_three_vision_modes_are_spelled_in_the_file_the_way_a_person_says_them() {
4956 for (text, mode) in [
4957 ("native", VisionMode::Native),
4958 ("text", VisionMode::Text),
4959 ("auto", VisionMode::Auto),
4960 ] {
4961 let cfg = Config::from_toml_str(&format!("[vision]\nmode = \"{text}\"\n")).unwrap();
4962 assert_eq!(cfg.vision.mode, mode, "{text}");
4963 }
4964 }
4965
4966 #[test]
4967 fn a_vision_mode_nobody_implements_is_a_load_error_that_lists_the_three() {
4968 let err = Config::from_toml_str("[vision]\nmode = \"telepathy\"\n").unwrap_err();
4969 let sentence = err.to_string();
4970 assert!(sentence.contains("telepathy"), "{sentence}");
4971 assert!(sentence.contains("native"), "{sentence}");
4972 assert!(sentence.contains("text"), "{sentence}");
4973 assert!(sentence.contains("auto"), "{sentence}");
4974 }
4975
4976 #[test]
4977 fn a_vision_route_that_is_not_a_route_is_refused_by_name() {
4978 let cfg = Config::from_toml_str(
4979 "[provider]\nbase_url = \"http://127.0.0.1:1/v1\"\nmodel = \"m\"\n\
4980 [vision]\nroute = \"sight\"\n",
4981 )
4982 .unwrap();
4983 let err = cfg.validate_routes().unwrap_err().to_string();
4984 assert!(err.contains("vision.route"), "{err}");
4985 assert!(err.contains("sight"), "{err}");
4986 assert!(err.contains("default"), "{err}");
4987 }
4988
4989 #[test]
4990 fn a_vision_route_that_exists_validates() {
4991 let cfg = Config::from_toml_str(
4992 "[provider]\nbase_url = \"http://127.0.0.1:1/v1\"\nmodel = \"m\"\n\
4993 [vision]\nroute = \"default\"\n",
4994 )
4995 .unwrap();
4996 cfg.validate_routes().unwrap();
4997 assert_eq!(cfg.vision.route, "default");
4998 }
4999
5000 #[test]
5001 fn the_skills_budget_has_its_documented_default_and_can_be_set_in_the_file() {
5002 assert_eq!(Config::default().skills.index_budget_chars, 4000);
5003 let cfg = Config::from_toml_str("[skills]\nindex_budget_chars = 250\n").unwrap();
5004 assert_eq!(cfg.skills.index_budget_chars, 250);
5005 assert!(starter().contains("[skills]"));
5006 let starter = Config::from_toml_str(&super::tests::starter()).unwrap();
5007 assert_eq!(starter.skills.index_budget_chars, 4000);
5008 }
5009
5010 #[test]
5011 fn the_redacted_config_shows_the_skills_section() {
5012 let mut cfg = Config::default();
5013 cfg.skills.index_budget_chars = 123;
5014 let shown = cfg.to_toml_redacted().unwrap();
5015 assert!(shown.contains("[skills]"), "{shown}");
5016 assert!(shown.contains("index_budget_chars = 123"), "{shown}");
5017 }
5018
5019 #[test]
5020 fn the_starter_writes_the_context_file_settings() {
5021 let text = starter();
5022 let cfg = Config::from_toml_str(&text).unwrap();
5023 assert_eq!(cfg.user.memory_file, "MEMORY.md");
5024 for key in ["context_files_budget_chars", "[user]", "USER.md"] {
5025 assert!(text.contains(key), "the shipped file names `{key}`");
5026 }
5027 }
5028
5029 const TWO_ROUTES: &str = "\
5032[provider]
5033fallback = [\"local\", \"big\"]
5034[[provider.route]]
5035name = \"local\"
5036base_url = \"http://127.0.0.1:8081/v1\"
5037model = \"small\"
5038[[provider.route]]
5039name = \"big\"
5040base_url = \"http://10.0.0.2:8000/v1\"
5041model = \"large\"
5042api_key = \"hunter2\"
5043timeout_secs = 30
5044";
5045
5046 fn parse(text: &str) -> Config {
5047 Config::from_toml_str(text).unwrap()
5048 }
5049
5050 fn refusal(text: &str) -> String {
5051 let c = parse(text);
5052 c.validate_routes()
5053 .and_then(|_| c.chain().map(|_| ()))
5054 .unwrap_err()
5055 .to_string()
5056 }
5057
5058 #[test]
5059 fn a_route_is_a_full_provider_config_and_inherits_nothing_from_provider() {
5060 let c = parse(
5061 "[provider]\nbase_url=\"http://d/v1\"\nmodel=\"dm\"\ntimeout_secs=7\n\
5062 [[provider.route]]\nname=\"r\"\nbase_url=\"http://r/v1\"\nmodel=\"rm\"\n",
5063 );
5064 let r = c.declared_routes();
5065 assert_eq!(
5066 r.iter().map(|r| r.name.as_str()).collect::<Vec<_>>(),
5067 ["default", "r"],
5068 "[provider] is the route called default"
5069 );
5070 assert_eq!(r[0].config.timeout_secs, 7);
5071 assert_eq!(
5072 r[1].config.timeout_secs, 120,
5073 "the route got the built-in default, not [provider]'s 7"
5074 );
5075 }
5076
5077 #[test]
5078 fn provider_may_be_omitted_when_fallback_names_a_route() {
5079 let c = parse(TWO_ROUTES);
5080 c.validate_routes().unwrap();
5081 let chain = c.chain().unwrap();
5082 assert_eq!(chain.source, ChainSource::Fallback);
5083 let names: Vec<_> = chain.routes.iter().map(|r| r.name.as_str()).collect();
5084 assert_eq!(names, ["local", "big"]);
5085 assert_eq!(chain.routes[1].config.timeout_secs, 30);
5086 assert!(
5087 c.declared_routes().iter().all(|r| r.name != "default"),
5088 "no phantom default route appears"
5089 );
5090 }
5091
5092 #[test]
5093 fn a_provider_endpoint_left_out_of_the_chain_is_refused_not_ignored() {
5094 let text = r#"
5098[provider]
5099base_url = "https://api.example.com/v1"
5100model = "gpt"
5101fallback = ["local"]
5102
5103[[provider.route]]
5104name = "local"
5105base_url = "http://127.0.0.1:8080/v1"
5106model = "qwen3-coder"
5107"#;
5108 let err = parse(text).validate_routes().unwrap_err().to_string();
5109 assert!(err.contains("would never be called"), "{err}");
5110 assert!(
5111 err.contains("Put `default` first"),
5112 "it says what to type: {err}"
5113 );
5114 }
5115
5116 #[test]
5117 fn listing_default_first_puts_the_provider_endpoint_back_in_front() {
5118 let text = r#"
5119[provider]
5120base_url = "https://api.example.com/v1"
5121model = "gpt"
5122fallback = ["default", "local"]
5123
5124[[provider.route]]
5125name = "local"
5126base_url = "http://127.0.0.1:8080/v1"
5127model = "qwen3-coder"
5128"#;
5129 let c = parse(text);
5130 c.validate_routes().unwrap();
5131 let chain = c.chain().unwrap();
5132 let names: Vec<_> = chain.routes.iter().map(|r| r.name.as_str()).collect();
5133 assert_eq!(names, ["default", "local"]);
5134 assert_eq!(chain.routes[0].config.model, "gpt");
5135 }
5136
5137 #[test]
5138 fn a_provider_block_of_tuning_keys_alone_does_not_become_a_route() {
5139 let text = "\
5143[provider]
5144max_retries = 0
5145fallback = [\"local\", \"big\"]
5146[[provider.route]]
5147name = \"local\"
5148base_url = \"http://127.0.0.1:8081/v1\"
5149model = \"small\"
5150[[provider.route]]
5151name = \"big\"
5152base_url = \"http://127.0.0.1:8082/v1\"
5153model = \"large\"
5154";
5155 let c = parse(text);
5156 c.validate_routes().unwrap();
5157 let names: Vec<String> = c.declared_routes().into_iter().map(|r| r.name).collect();
5158 assert_eq!(names, ["local", "big"], "no phantom default route");
5159
5160 let mut pinned = parse(text);
5161 let e = pinned.pin_route(Some("default"), &|_| None).unwrap_err();
5162 let e = e.to_string();
5163 assert!(
5164 e.contains("unknown route `default`") && e.contains("local, big"),
5165 "{e}"
5166 );
5167 assert!(!e.contains("provider.base_url"), "{e}");
5168 }
5169
5170 #[test]
5171 fn two_routes_with_the_same_name_are_refused_naming_it() {
5172 let e = refusal(
5173 "[[provider.route]]\nname=\"a\"\nbase_url=\"u\"\nmodel=\"m\"\n\
5174 [[provider.route]]\nname=\"a\"\nbase_url=\"u\"\nmodel=\"m\"\n",
5175 );
5176 assert!(e.contains("`a`") && e.contains("unique"), "{e}");
5177 }
5178
5179 #[test]
5180 fn a_route_with_an_empty_or_missing_name_is_refused_by_position() {
5181 let e = refusal("[[provider.route]]\nname=\" \"\nbase_url=\"u\"\nmodel=\"m\"\n");
5182 assert!(
5183 e.contains("provider.route #1") && e.contains("no name"),
5184 "{e}"
5185 );
5186 let e = refusal("[[provider.route]]\nbase_url=\"u\"\nmodel=\"m\"\n");
5187 assert!(e.contains("provider.route #1"), "{e}");
5188 }
5189
5190 #[test]
5191 fn a_route_named_default_is_refused_only_when_provider_is_also_set() {
5192 let route = "[[provider.route]]\nname=\"default\"\nbase_url=\"u\"\nmodel=\"m\"\n";
5193 let e = refusal(&format!("[provider]\nbase_url=\"x\"\nmodel=\"y\"\n{route}"));
5194 assert!(e.contains("`default`") && e.contains("[provider]"), "{e}");
5195 let c = parse(&format!("[provider]\nfallback=[\"default\"]\n{route}"));
5196 assert_eq!(c.chain().unwrap().routes[0].name, "default");
5197 }
5198
5199 #[test]
5200 fn a_route_without_base_url_or_model_is_refused_naming_the_route() {
5201 let e = refusal("[[provider.route]]\nname=\"nourl\"\nmodel=\"m\"\n");
5202 assert!(e.contains("`nourl`") && e.contains("base_url"), "{e}");
5203 let e = refusal("[[provider.route]]\nname=\"nomodel\"\nbase_url=\"u\"\n");
5204 assert!(e.contains("`nomodel`") && e.contains("model"), "{e}");
5205 }
5206
5207 #[test]
5208 fn a_route_does_not_inherit_a_missing_base_url_from_provider() {
5209 let e = refusal(
5210 "[provider]\nbase_url=\"http://d/v1\"\nmodel=\"dm\"\n\
5211 [[provider.route]]\nname=\"r\"\nmodel=\"m\"\n",
5212 );
5213 assert!(e.contains("`r`") && e.contains("does not inherit"), "{e}");
5214 }
5215
5216 #[test]
5217 fn fallback_naming_a_route_that_does_not_exist_lists_the_ones_that_do() {
5218 let e = refusal(&TWO_ROUTES.replace("\"big\"]", "\"cloud\"]"));
5219 assert!(e.contains("`cloud`"), "{e}");
5220 assert!(e.contains("local, big"), "{e}");
5221 }
5222
5223 #[test]
5224 fn an_empty_fallback_is_a_typo_not_a_policy() {
5225 let e = refusal("[provider]\nfallback = []\n");
5226 assert!(e.contains("provider.fallback is empty"), "{e}");
5227 }
5228
5229 #[test]
5230 fn a_fallback_that_lists_a_route_twice_is_refused() {
5231 let e = refusal(&TWO_ROUTES.replace("[\"local\", \"big\"]", "[\"local\", \"local\"]"));
5232 assert!(e.contains("`local` twice"), "{e}");
5233 }
5234
5235 #[test]
5236 fn a_fallback_or_route_table_inside_a_route_is_refused() {
5237 let e = refusal(
5238 "[[provider.route]]\nname=\"r\"\nbase_url=\"u\"\nmodel=\"m\"\nfallback=[\"r\"]\n",
5239 );
5240 assert!(e.contains("`r`") && e.contains("directly"), "{e}");
5241 }
5242
5243 const WITH_AUX: &str = "\
5244[provider]
5245base_url = \"http://d/v1\"
5246model = \"dm\"
5247aux = \"cheap\"
5248[[provider.route]]
5249name = \"cheap\"
5250base_url = \"http://c/v1\"
5251model = \"cm\"
5252";
5253
5254 #[test]
5255 fn aux_names_a_route_and_the_role_table_says_so() {
5256 let chain = parse(WITH_AUX).chain().unwrap();
5257 assert_eq!(chain.aux.as_ref().map(|r| r.name.as_str()), Some("cheap"));
5258 assert_eq!(chain.aux.unwrap().config.model, "cm");
5259 let roles = parse(WITH_AUX).chain().unwrap().roles();
5260 assert_eq!(roles.len(), 2, "only roles that exist get a row");
5261 assert_eq!(roles[0].to_string(), "judgement \u{2192} cheap");
5262 assert_eq!(
5263 roles[1].to_string(),
5264 "delegate \u{2192} default (no delegate route set)"
5265 );
5266 }
5267
5268 #[test]
5269 fn delegate_names_a_route_and_the_role_table_says_so() {
5270 let c = parse(&WITH_AUX.replace("aux = \"cheap\"", "delegate = \"cheap\""));
5271 let chain = c.chain().unwrap();
5272 assert_eq!(
5273 chain.delegate.as_ref().map(|r| r.name.as_str()),
5274 Some("cheap")
5275 );
5276 assert!(chain.aux.is_none());
5277 let roles = chain.roles();
5278 assert_eq!(
5279 roles[0].to_string(),
5280 "judgement \u{2192} default (no aux route set)"
5281 );
5282 assert_eq!(roles[1].to_string(), "delegate \u{2192} cheap");
5283 }
5284
5285 #[test]
5286 fn a_pin_overrules_the_aux_and_delegate_routes_and_the_role_table_says_pinned() {
5287 let mut c =
5290 parse(&WITH_AUX.replace("aux = \"cheap\"", "aux = \"cheap\"\ndelegate = \"cheap\""));
5291 c.pin_route(Some("cheap"), &|_| None).unwrap();
5292 let chain = c.chain().unwrap();
5293 assert_eq!(chain.source, ChainSource::Pinned);
5294 assert_eq!(
5295 chain.aux.as_ref().map(|r| r.name.as_str()),
5296 Some("cheap"),
5297 "the pinned route, not the key's own value"
5298 );
5299 assert_eq!(
5300 chain.delegate.as_ref().map(|r| r.name.as_str()),
5301 Some("cheap")
5302 );
5303 for role in chain.roles() {
5304 assert!(role.pinned, "{role} should be pinned");
5305 assert!(!role.set, "{role} should not claim the key decided it");
5306 assert_eq!(role.route, "cheap");
5307 assert!(role.to_string().ends_with("(pinned)"), "{role}");
5308 }
5309
5310 let c =
5312 parse(&WITH_AUX.replace("aux = \"cheap\"", "aux = \"cheap\"\ndelegate = \"cheap\""));
5313 let chain = c.chain().unwrap();
5314 assert!(chain.roles().iter().all(|r| r.set && !r.pinned));
5315 }
5316
5317 #[test]
5318 fn an_unknown_empty_or_nested_delegate_route_is_refused_with_the_routes_that_exist() {
5319 let e = refusal(&WITH_AUX.replace("aux = \"cheap\"", "delegate = \"ghost\""));
5320 assert!(
5321 e.contains("provider.delegate names `ghost`") && e.contains("default, cheap"),
5322 "{e}"
5323 );
5324 let c = parse(&WITH_AUX.replace("aux = \"cheap\"", "delegate = \"\""));
5326 c.validate_routes()
5327 .expect("an empty delegate is a config that loads");
5328 let e = refusal(
5329 "[[provider.route]]\nname=\"r\"\nbase_url=\"u\"\nmodel=\"m\"\ndelegate=\"r\"\n\
5330 [provider]\nfallback=[\"r\"]\n",
5331 );
5332 assert!(
5333 e.contains("`r`") && e.contains("`delegate`") && e.contains("directly"),
5334 "{e}"
5335 );
5336 let e = Config::from_toml_str("[provider]\ndelegate = 3\n").unwrap_err();
5337 assert!(e.contains("delegate"), "{e}");
5338 }
5339
5340 #[test]
5341 fn the_delegate_tool_is_asked_about_by_default_and_the_policy_can_be_set_in_the_file() {
5342 assert_eq!(Config::default().tools.delegate, Policy::Ask);
5343 let cfg = Config::from_toml_str("[tools]\ndelegate = \"deny\"\n").unwrap();
5344 assert_eq!(cfg.tools.delegate, Policy::Deny);
5345 let starter = Config::from_toml_str(&super::tests::starter()).unwrap();
5346 assert_eq!(starter.tools.delegate, Policy::Ask);
5347 assert!(Config::from_toml_str("[tools]\ndelegate = \"yolo\"\n").is_err());
5348 }
5349
5350 #[test]
5351 fn with_no_aux_the_summary_role_uses_the_selected_route_and_says_it_was_not_set() {
5352 let chain = parse(TWO_ROUTES).chain().unwrap();
5353 assert!(chain.aux.is_none());
5354 assert_eq!(
5355 chain.roles()[0].to_string(),
5356 "judgement \u{2192} local (no aux route set)"
5357 );
5358 let bare = parse("[provider]\nbase_url=\"u\"\nmodel=\"m\"\n");
5359 assert_eq!(
5360 bare.chain().unwrap().roles()[0].to_string(),
5361 "judgement \u{2192} default (no aux route set)"
5362 );
5363 }
5364
5365 #[test]
5366 fn an_unknown_aux_route_is_refused_listing_the_routes_that_exist() {
5367 let e = refusal(&WITH_AUX.replace("aux = \"cheap\"", "aux = \"ghost\""));
5368 assert!(
5369 e.contains("provider.aux names `ghost`") && e.contains("default, cheap"),
5370 "{e}"
5371 );
5372 let c = parse(&WITH_AUX.replace("aux = \"cheap\"", "aux = \"\""));
5376 c.validate_routes()
5377 .expect("an empty aux route is a config that loads");
5378 assert!(c.chain().unwrap().aux.is_none());
5379 }
5380
5381 #[test]
5382 fn aux_inside_a_route_is_refused_like_fallback_and_route() {
5383 let e = refusal(
5384 "[[provider.route]]\nname=\"r\"\nbase_url=\"u\"\nmodel=\"m\"\naux=\"r\"\n\
5385 [provider]\nfallback=[\"r\"]\n",
5386 );
5387 assert!(
5388 e.contains("`r`") && e.contains("`aux`") && e.contains("directly"),
5389 "{e}"
5390 );
5391 }
5392
5393 #[test]
5394 fn a_wrong_typed_aux_is_an_error_naming_the_key() {
5395 let e = Config::from_toml_str("[provider]\naux = 3\n").unwrap_err();
5396 assert!(e.contains("aux"), "{e}");
5397 }
5398
5399 #[test]
5400 fn aux_may_name_the_default_route_when_provider_is_one() {
5401 let c = parse(&WITH_AUX.replace("aux = \"cheap\"", "aux = \"default\""));
5402 assert_eq!(c.chain().unwrap().aux.unwrap().name, "default");
5403 let tuning_only = "[provider]\naux = \"default\"\nmax_retries = 1\n\
5404 [[provider.route]]\nname=\"r\"\nbase_url=\"u\"\nmodel=\"m\"\n";
5405 assert!(refusal(tuning_only).contains("Routes that exist: r"));
5406 }
5407
5408 #[test]
5409 fn a_wrong_typed_route_value_is_an_error_and_not_a_default() {
5410 let bad =
5411 "[[provider.route]]\nname=\"r\"\nbase_url=\"u\"\nmodel=\"m\"\ntimeout_secs=\"soon\"\n";
5412 let e = Config::from_toml_str(bad).unwrap_err();
5413 assert!(e.contains("timeout_secs") || e.contains("soon"), "{e}");
5414 let e = Config::from_toml_str("[provider]\nfallback = \"local\"\n").unwrap_err();
5415 assert!(e.contains("fallback") || e.contains("sequence"), "{e}");
5416 }
5417
5418 #[test]
5419 fn routes_with_no_fallback_and_no_pin_say_what_to_set() {
5420 let e = refusal("[[provider.route]]\nname=\"r\"\nbase_url=\"u\"\nmodel=\"m\"\n");
5421 assert!(
5422 e.contains("fallback") && e.contains("--route") && e.contains("r"),
5423 "{e}"
5424 );
5425 }
5426
5427 #[test]
5428 fn with_no_fallback_and_no_pin_the_chain_is_the_default_route_alone() {
5429 let c = parse(
5430 "[provider]\nbase_url=\"http://d/v1\"\nmodel=\"dm\"\n\
5431 [[provider.route]]\nname=\"r\"\nbase_url=\"u\"\nmodel=\"m\"\n",
5432 );
5433 let chain = c.chain().unwrap();
5434 assert_eq!(chain.source, ChainSource::Default);
5435 assert_eq!(chain.routes.len(), 1);
5436 assert_eq!(chain.routes[0].name, "default");
5437 let bare = parse("[provider]\nbase_url=\"http://d/v1\"\nmodel=\"dm\"\n");
5438 assert_eq!(bare.chain().unwrap().source, ChainSource::Default);
5439 }
5440
5441 #[test]
5442 fn a_bare_config_still_says_what_is_wrong_with_provider() {
5443 let e = Config::default()
5444 .require_provider()
5445 .unwrap_err()
5446 .to_string();
5447 assert!(e.contains("provider.base_url is not set"), "{e}");
5448 assert!(e.contains("eclipse config init"), "{e}");
5449 let c = parse("[provider]\nbase_url=\"u\"\n");
5450 assert!(c
5451 .require_provider()
5452 .unwrap_err()
5453 .to_string()
5454 .contains("provider.model is not set"));
5455 }
5456
5457 #[test]
5458 fn a_pin_selects_one_route_and_marks_the_chain_pinned() {
5459 let mut c = parse(TWO_ROUTES);
5460 c.pin_route(Some("big"), &env_of(&[])).unwrap();
5461 let chain = c.chain().unwrap();
5462 assert_eq!(chain.source, ChainSource::Pinned);
5463 assert_eq!(chain.routes.len(), 1);
5464 assert_eq!(chain.routes[0].name, "big");
5465 }
5466
5467 #[test]
5468 fn an_unknown_pin_lists_the_routes_that_exist() {
5469 let mut c = parse(TWO_ROUTES);
5470 let e = c
5471 .pin_route(Some("nope"), &env_of(&[]))
5472 .unwrap_err()
5473 .to_string();
5474 assert!(e.contains("`nope`") && e.contains("local, big"), "{e}");
5475 let e = c
5476 .pin_route(Some(" "), &env_of(&[]))
5477 .unwrap_err()
5478 .to_string();
5479 assert!(e.contains("--route needs a route name"), "{e}");
5480 }
5481
5482 #[test]
5483 fn eclipse_route_is_honoured_when_the_flag_is_absent_and_the_flag_wins() {
5484 let mut c = parse(TWO_ROUTES);
5485 c.pin_route(None, &env_of(&[("ECLIPSE_ROUTE", "big")]))
5486 .unwrap();
5487 assert_eq!(c.route_pin.as_deref(), Some("big"));
5488 c.pin_route(Some("local"), &env_of(&[("ECLIPSE_ROUTE", "big")]))
5489 .unwrap();
5490 assert_eq!(c.route_pin.as_deref(), Some("local"));
5491 let mut c = parse(TWO_ROUTES);
5492 c.dotenv
5493 .values
5494 .insert("ECLIPSE_ROUTE".into(), "local".into());
5495 c.pin_route(None, &env_of(&[])).unwrap();
5496 assert_eq!(
5497 c.route_pin.as_deref(),
5498 Some("local"),
5499 "the .env chain counts too"
5500 );
5501 let mut c = parse(TWO_ROUTES);
5502 c.pin_route(None, &env_of(&[])).unwrap();
5503 assert_eq!(c.route_pin, None);
5504 }
5505
5506 #[test]
5507 fn a_route_takes_its_key_from_its_own_api_key_env_and_eclipse_api_key_is_default_only() {
5508 let mut c = parse(
5509 "[provider]\nbase_url=\"http://d/v1\"\nmodel=\"dm\"\n\
5510 [[provider.route]]\nname=\"r\"\nbase_url=\"u\"\nmodel=\"m\"\napi_key_env=\"R_KEY\"\n",
5511 );
5512 c.apply_env(&env_of(&[
5513 ("R_KEY", "from-r"),
5514 ("ECLIPSE_API_KEY", "for-default"),
5515 ]));
5516 assert_eq!(c.provider.api_key.as_deref(), Some("for-default"));
5517 assert_eq!(
5518 c.provider.route[0].config.api_key.as_deref(),
5519 Some("from-r")
5520 );
5521
5522 let mut only_routes = parse(TWO_ROUTES);
5523 only_routes.apply_env(&env_of(&[("ECLIPSE_API_KEY", "stray")]));
5524 assert_eq!(
5525 only_routes.provider.api_key, None,
5526 "no phantom default route"
5527 );
5528 assert_eq!(only_routes.provider.route[0].config.api_key, None);
5529 }
5530
5531 #[test]
5532 fn the_redacted_config_hides_every_routes_key_and_round_trips() {
5533 let c = parse(TWO_ROUTES);
5534 let t = c.to_toml_redacted().unwrap();
5535 assert!(!t.contains("hunter2"), "{t}");
5536 assert!(
5537 t.contains("[[provider.route]]") && t.contains("<redacted>"),
5538 "{t}"
5539 );
5540 let back = parse(&t);
5541 assert_eq!(back.provider.fallback, c.provider.fallback);
5542 assert_eq!(back.provider.route.len(), 2);
5543 assert_eq!(back.provider.route[1].config.timeout_secs, 30);
5544 }
5545
5546 #[test]
5547 fn a_config_without_routes_prints_no_provider_route_keys() {
5548 let c = parse("[provider]\nbase_url=\"u\"\nmodel=\"m\"\n");
5551 let t = c.to_toml_redacted().unwrap();
5552 let parsed: toml::Value = toml::from_str(&t).unwrap();
5553 let provider = parsed.get("provider").expect("a provider table");
5554 for absent in ["route", "fallback", "aux", "delegate"] {
5555 assert!(
5556 provider.get(absent).is_none(),
5557 "`provider.{absent}` printed for a config with one route: {t}"
5558 );
5559 }
5560 }
5561
5562 #[test]
5563 fn a_bad_route_table_is_refused_when_the_config_is_loaded() {
5564 let tmp = tempfile::tempdir().unwrap();
5565 let path = tmp.path().join("c.toml");
5566 std::fs::write(&path, "[provider]\nfallback = [\"ghost\"]\n").unwrap();
5567 let e = Config::load_with(Some(&path), &env_of(&[]))
5568 .unwrap_err()
5569 .to_string();
5570 assert!(e.contains("`ghost`"), "{e}");
5571 }
5572
5573 #[test]
5574 fn context_policy_defaults_and_the_rail_it_derives() {
5575 let c = ContextPolicyConfig::default();
5576 assert!(
5577 c.judge,
5578 "the model half is the judgement pass, and it ships on: compile plus one bounded call"
5579 );
5580 assert_eq!(c.judge_timeout_secs, 20, "and it cannot hang the turn");
5581 assert_eq!(c.compact_at, 0.85);
5582 assert_eq!(c.protect_last_n, 20, "the tail keeps twenty turns");
5583 assert_eq!(c.window_tokens, 0, "no window is invented");
5584 assert_eq!(c.budget_for(0), 0, "no window, no rail");
5585 assert_eq!(c.budget_for(327_680), 278_528);
5586 let off = ContextPolicyConfig {
5587 compact_at: 0.0,
5588 ..c.clone()
5589 };
5590 assert_eq!(off.budget_for(327_680), 0, "compact_at = 0 is off");
5591 let half = ContextPolicyConfig {
5592 compact_at: 0.5,
5593 ..c
5594 };
5595 assert_eq!(half.budget_for(131_072), 65_536);
5596 }
5597
5598 #[test]
5599 fn a_compact_at_outside_the_window_is_a_config_error_naming_the_key() {
5600 for bad in ["1.5", "-0.2"] {
5601 let c = parse(&format!("[context]\ncompact_at = {bad}\n"));
5602 let err = c.context.validate().unwrap_err().to_string();
5603 assert!(
5604 err.contains("context.compact_at"),
5605 "{bad} must be named in the error: {err}"
5606 );
5607 }
5608 assert!(parse("[context]\ncompact_at = 0.6\n")
5609 .context
5610 .validate()
5611 .is_ok());
5612 assert!(parse("[context]\ncompact_at = 0\n")
5613 .context
5614 .validate()
5615 .is_ok());
5616 }
5617}
5618
5619#[cfg(test)]
5620mod mcp_editor_tests {
5621 use super::*;
5622 use crate::mcp::Spec;
5623
5624 fn spec(text: &str) -> Spec {
5625 toml::from_str(text).unwrap()
5626 }
5627
5628 fn add(spec: &Spec) -> String {
5629 let out = mcp_add(CONFIG, spec).unwrap();
5630 parse_text(&out).unwrap();
5632 out
5633 }
5634
5635 const CONFIG: &str = r#"# my config
5636[provider]
5637base_url = "http://127.0.0.1:8081/v1"
5638model = "m"
5639
5640# this comment belongs to the first entry
5641[[mcp]]
5642name = "first"
5643command = "one"
5644
5645# and this one to the second
5646[[mcp]]
5647name = "second"
5648command = "two"
5649policy = "allow"
5650"#;
5651
5652 #[test]
5653 fn an_added_entry_reads_back_and_leaves_the_comments_alone() {
5654 let out = add(&spec(
5655 "name = \"third\"\ncommand = \"three\"\nargs = [\"--x\"]\nprefix = \"t_\"\n",
5656 ));
5657 let cfg = parse_text(&out).unwrap();
5658 assert_eq!(
5659 cfg.mcp.iter().map(|s| s.name.as_str()).collect::<Vec<_>>(),
5660 ["first", "second", "third"]
5661 );
5662 let third = cfg.mcp.iter().find(|s| s.name == "third").unwrap();
5663 assert_eq!(third.args, ["--x"]);
5664 assert_eq!(third.prefix, "t_");
5665 for line in [
5667 "# my config",
5668 "# this comment belongs to the first entry",
5669 "# and this one to the second",
5670 ] {
5671 assert!(out.contains(line), "lost {line:?}:\n{out}");
5672 }
5673 assert!(
5674 out.contains("[[mcp]]\nname = \"first\"\ncommand = \"one\""),
5675 "{out}"
5676 );
5677 assert!(
5678 !out.contains("args = []"),
5679 "only what was set is written:\n{out}"
5680 );
5681 }
5682
5683 #[test]
5684 fn a_duplicate_name_is_refused_and_named_by_line() {
5685 let err = mcp_add(CONFIG, &spec("name = \"first\"\ncommand = \"again\"")).unwrap_err();
5686 assert!(err.contains("already declared at line 7"), "{err}");
5687 }
5688
5689 #[test]
5690 fn an_unusable_entry_is_refused_before_anything_is_written() {
5691 let err = mcp_add(
5693 CONFIG,
5694 &spec("name = \"bad\"\ntransport = \"http\"\ncommand = \"x\"\nurl = \"http://h/mcp\""),
5695 )
5696 .unwrap_err();
5697 assert!(err.starts_with("that entry is not usable"), "{err}");
5698 assert!(err.contains("belong to the stdio transport"), "{err}");
5699 }
5700
5701 #[test]
5702 fn remove_takes_the_named_block_and_the_blank_line_after_it() {
5703 let out = mcp_remove(CONFIG, "first").unwrap();
5704 let cfg = parse_text(&out).unwrap();
5705 assert_eq!(
5706 cfg.mcp.iter().map(|s| s.name.as_str()).collect::<Vec<_>>(),
5707 ["second"]
5708 );
5709 assert!(out.contains("# and this one to the second"), "{out}");
5711 assert!(!out.contains("name = \"first\""), "{out}");
5712 assert!(!out.contains("\n\n\n"), "no hole left behind:\n{out}");
5713 }
5714
5715 #[test]
5716 fn remove_says_what_the_file_does_declare() {
5717 let err = mcp_remove(CONFIG, "nope").unwrap_err();
5718 assert!(err.contains("declares first, second"), "{err}");
5719 let bare = "[provider]\nbase_url = \"http://d/v1\"\nmodel = \"m\"\n";
5720 let err = mcp_remove(bare, "nope").unwrap_err();
5721 assert!(err.contains("no `[[mcp]]` entry for `nope`"), "{err}");
5722 }
5723
5724 #[test]
5725 fn disable_flips_the_line_inside_its_own_block() {
5726 let off = mcp_set_disabled(CONFIG, "second", true).unwrap();
5727 let cfg = parse_text(&off).unwrap();
5728 assert!(
5729 cfg.mcp
5730 .iter()
5731 .find(|s| s.name == "second")
5732 .unwrap()
5733 .disabled
5734 );
5735 assert!(!cfg.mcp.iter().find(|s| s.name == "first").unwrap().disabled);
5736 let second_at = off.find("name = \"second\"").unwrap();
5738 let tail = &off[second_at..];
5739 assert!(tail.contains("disabled = true"), "{off}");
5740 assert!(tail.find("disabled").unwrap() < tail.find("\n[[").unwrap_or(tail.len()));
5741
5742 let on = mcp_set_disabled(&off, "second", false).unwrap();
5743 let cfg = parse_text(&on).unwrap();
5744 assert!(
5745 !cfg.mcp
5746 .iter()
5747 .find(|s| s.name == "second")
5748 .unwrap()
5749 .disabled
5750 );
5751 assert!(
5752 on.contains("disabled = false"),
5753 "said out loud, not deleted:\n{on}"
5754 );
5755 }
5756
5757 #[test]
5758 fn disable_on_an_entry_without_the_key_inserts_one() {
5759 let off = mcp_set_disabled(CONFIG, "first", true).unwrap();
5760 assert!(off.contains("command = \"one\"\ndisabled = true"), "{off}");
5761 assert!(parse_text(&off).unwrap().mcp[0].disabled);
5762 }
5763
5764 #[test]
5768 fn an_edit_changes_the_changed_line_and_leaves_every_other_byte_alone() {
5769 let out = mcp_update(CONFIG, "second", |entry| entry.prefix = "t_".into()).unwrap();
5770 parse_text(&out).unwrap();
5771 assert_eq!(
5772 out,
5773 CONFIG.replace(
5774 "command = \"two\"\npolicy = \"allow\"",
5775 "command = \"two\"\npolicy = \"allow\"\nprefix = \"t_\""
5776 ),
5777 "one added line, and not one other character moved:\n{out}"
5778 );
5779 }
5780
5781 #[test]
5784 fn an_edit_sets_and_clears_token_env_without_touching_the_rest() {
5785 let on = mcp_update(CONFIG, "second", |entry| {
5786 entry.token_env = Some("HA_TOKEN".into())
5787 })
5788 .unwrap();
5789 assert_eq!(
5790 on,
5791 CONFIG.replace(
5792 "command = \"two\"\npolicy = \"allow\"",
5793 "command = \"two\"\npolicy = \"allow\"\ntoken_env = \"HA_TOKEN\""
5794 ),
5795 "{on}"
5796 );
5797 let off = mcp_update(&on, "second", |entry| entry.token_env = None).unwrap();
5798 assert_eq!(
5799 off, CONFIG,
5800 "clearing a field removes its line and nothing else"
5801 );
5802 }
5803
5804 #[test]
5807 fn an_edit_keeps_a_comment_written_inside_the_block() {
5808 let inner = "[[mcp]]\nname = \"a\"\n# the endpoint is on the box\ncommand = \"x\"\n";
5809 let out = mcp_update(inner, "a", |entry| {
5810 entry.args = vec!["--y".into()];
5811 })
5812 .unwrap();
5813 assert_eq!(
5814 out,
5815 "[[mcp]]\nname = \"a\"\n# the endpoint is on the box\ncommand = \"x\"\n\
5816 args = [\"--y\"]\n",
5817 "{out}"
5818 );
5819 }
5820
5821 #[test]
5823 fn an_edit_refuses_a_rename_and_names_what_the_file_declares() {
5824 let err = mcp_update(CONFIG, "second", |entry| entry.name = "renamed".into()).unwrap_err();
5825 assert!(err.contains("an edit does not rename"), "{err}");
5826
5827 let err = mcp_update(CONFIG, "nope", |_| {}).unwrap_err();
5828 assert!(err.contains("declares first, second"), "{err}");
5829
5830 let err = mcp_update(CONFIG, "second", |entry| {
5832 entry.transport = crate::mcp::Transport::Http;
5833 entry.url = Some("http://h/mcp".into());
5834 })
5835 .unwrap_err();
5836 assert!(err.starts_with("that entry is not usable"), "{err}");
5837 assert!(err.contains("belong to the stdio transport"), "{err}");
5838 }
5839
5840 #[test]
5841 fn an_empty_file_gets_its_first_entry_cleanly() {
5842 let out = mcp_add("", &spec("name = \"only\"\ncommand = \"x\"")).unwrap();
5843 assert!(out.starts_with("[[mcp]]\n"), "{out:?}");
5844 assert_eq!(parse_text(&out).unwrap().mcp[0].name, "only");
5845 }
5846
5847 #[test]
5848 fn a_second_entry_is_separated_by_exactly_one_blank_line() {
5849 let out = add(&spec("name = \"third\"\ncommand = \"three\""));
5850 assert!(!out.contains("\n\n\n"), "{out}");
5851 assert!(
5852 out.contains("policy = \"allow\"\n\n[[mcp]]\nname = \"third\""),
5853 "{out}"
5854 );
5855 }
5856}