use crate::error::{Error, Result};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::fmt;
use std::path::{Path, PathBuf};
pub const APP_DIR: &str = "eclipse";
pub const CONFIG_VERSION: u32 = 1;
pub type EnvFn<'a> = &'a dyn Fn(&str) -> Option<String>;
pub fn process_env(key: &str) -> Option<String> {
std::env::var(key).ok().filter(|v| !v.is_empty())
}
pub(crate) fn home_dir(env: EnvFn) -> Option<PathBuf> {
env("HOME").map(PathBuf::from)
}
pub fn home_root(env: EnvFn) -> Option<PathBuf> {
if let Some(p) = env("ECLIPSE_HOME") {
if !p.is_empty() {
return Some(expand_tilde(Path::new(&p), env));
}
}
home_dir(env).map(|h| h.join(".eclipse"))
}
pub fn config_dir(env: EnvFn) -> Option<PathBuf> {
home_root(env)
}
pub fn state_dir(env: EnvFn) -> Option<PathBuf> {
home_root(env).map(|r| r.join("state"))
}
pub fn ensure_layout(root: &Path) -> std::io::Result<()> {
for dir in [
"",
"bin",
"memory",
"skills",
"plugins",
"profiles",
"workspace",
"state",
] {
let p = if dir.is_empty() {
root.to_path_buf()
} else {
root.join(dir)
};
std::fs::create_dir_all(&p)?;
}
Ok(())
}
pub const STARTER_AGENT_MD: &str = "# How to work here
# This file is injected into the system prompt on every run, along with USER.md and MEMORY.md.
# Edit the lines below to describe this project: conventions, commands, gotchas.
You are a direct, practical assistant. Read before acting, say what you are doing,
and keep a reply short unless it needs to be long. Use the workspace and tools to verify
what you are about to do, rather than describing it.
MEMORY.md is for facts about the user and their machines. A procedure — the steps, commands and
pitfalls for a kind of task — belongs in a skill: `skill_manage` writes one, and only its name and
description sit in the prompt until the task calls for it.
";
pub const STARTER_USER_MD: &str = "# Who the operator is
# This file is injected into the system prompt on every run. Describe the person who owns
# this install — who they are, what they do, and the preferences you should follow.
The operator is the person who owns this install. Edit this file with their name,
what they do, and standing preferences. Keep it short: this is who they are,
not a data dump.
";
pub fn seed_context_files(memory_dir: &Path) -> Result<Vec<PathBuf>> {
std::fs::create_dir_all(memory_dir).map_err(|e| Error::io(memory_dir, e))?;
let mut created = Vec::new();
for (name, body) in [
("AGENT.md", STARTER_AGENT_MD),
("USER.md", STARTER_USER_MD),
("MEMORY.md", ""),
] {
let path = memory_dir.join(name);
if path.exists() {
continue;
}
std::fs::write(&path, body).map_err(|e| Error::io(&path, e))?;
created.push(path);
}
Ok(created)
}
mod check;
pub mod migrate;
mod settings;
pub use check::{unknown_keys_in_file, UnknownKey};
pub use migrate::{baseline_path, plan as migration_plan, Change, Plan};
pub use settings::{
about, choices, parse_value, set_in_text, set_list_in_text, unset_in_text, Applies, Kind,
Setting,
};
pub fn config_path(env: EnvFn) -> Option<PathBuf> {
if let Some(p) = env("ECLIPSE_CONFIG") {
return Some(PathBuf::from(p));
}
config_dir(env).map(|d| d.join("config.toml"))
}
pub fn validate_profile_name(name: &str) -> Result<()> {
let ok = !name.is_empty()
&& name.len() <= 64
&& name
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');
if ok {
Ok(())
} else {
Err(Error::Config(format!("invalid profile name {name:?}")))
}
}
pub fn profile_dir(env: EnvFn, name: &str) -> Option<PathBuf> {
home_root(env).map(|d| d.join("profiles").join(name))
}
pub fn write_target(
root: Option<&Path>,
explicit: Option<&Path>,
base: Option<&Path>,
profile: Option<&str>,
) -> Option<PathBuf> {
if let Some(path) = explicit {
return Some(path.to_path_buf());
}
match profile {
None | Some("default") => base.map(Path::to_path_buf),
Some(name) => {
validate_profile_name(name).ok()?;
Some(root?.join("profiles").join(name).join("config.toml"))
}
}
}
pub fn state_dir_for(env: EnvFn, profile: Option<&str>) -> Option<PathBuf> {
match profile {
None | Some("default") => state_dir(env),
Some(name) => profile_dir(env, name).map(|d| d.join("state")),
}
}
fn expand_tilde(p: &Path, env: EnvFn) -> PathBuf {
if let Ok(rest) = p.strip_prefix("~") {
if let Some(h) = home_dir(env) {
return h.join(rest);
}
}
p.to_path_buf()
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum FetchHtml {
Text,
Raw,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ShellIsolate {
Off,
Process,
Fs,
}
impl std::fmt::Display for ShellIsolate {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
Self::Off => "off",
Self::Process => "process",
Self::Fs => "fs",
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Policy {
Deny,
Ask,
Allow,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum ShellAsk {
#[default]
Dangerous,
Always,
}
#[derive(Clone, Default, PartialEq, Eq)]
pub struct Dotenv {
pub files: Vec<PathBuf>,
pub values: BTreeMap<String, String>,
}
impl fmt::Debug for Dotenv {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Dotenv")
.field("files", &self.files)
.field("keys", &self.values.keys().collect::<Vec<_>>())
.finish()
}
}
impl Dotenv {
pub fn load(env: EnvFn<'_>, profile: Option<&str>) -> Result<Dotenv> {
let Some(dir) = config_dir(env) else {
return Ok(Dotenv::default());
};
let mut candidates = vec![dir.join(".env")];
if let Some(p) = profile {
validate_profile_name(p)?;
candidates.push(dir.join("profiles").join(p).join(".env"));
}
let mut values = BTreeMap::new();
let mut files = Vec::new();
for path in candidates {
if !path.exists() {
continue;
}
for assignment in crate::dotenv::load(&path)? {
if assignment.value.is_empty() {
values.remove(&assignment.key);
continue;
}
values.insert(assignment.key, assignment.value);
}
files.push(path);
}
Ok(Dotenv { files, values })
}
}
fn empty_is_none<'de, D>(d: D) -> std::result::Result<Option<String>, D::Error>
where
D: serde::Deserializer<'de>,
{
use serde::Deserialize;
Ok(Option::<String>::deserialize(d)?.filter(|v| !v.is_empty()))
}
#[derive(Clone, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct ProviderConfig {
pub base_url: String,
#[serde(deserialize_with = "empty_is_none")]
pub api_key: Option<String>,
#[serde(deserialize_with = "empty_is_none")]
pub api_key_env: Option<String>,
pub model: String,
pub temperature: Option<f64>,
pub timeout_secs: u64,
pub stream: bool,
pub max_retries: u32,
pub retry_after_send: bool,
pub retry_base_delay_ms: u64,
pub context_budget_tokens: usize,
pub max_tokens: Option<u32>,
#[serde(deserialize_with = "empty_is_none")]
pub profile: Option<String>,
pub top_p: Option<f64>,
pub seed: Option<i64>,
pub stop: Option<Vec<String>>,
#[serde(deserialize_with = "empty_is_none")]
pub reasoning_effort: Option<String>,
pub parallel_tool_calls: Option<bool>,
pub vision: Option<bool>,
pub tool_choice: Option<crate::hooks::ToolChoice>,
pub extra_body: Option<serde_json::Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub fallback: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(deserialize_with = "empty_is_none")]
pub aux: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(deserialize_with = "empty_is_none")]
pub delegate: Option<String>,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub route: Vec<RouteConfig>,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct RouteConfig {
pub name: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub max_parallel: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")]
pub group: Option<String>,
#[serde(flatten)]
pub config: ProviderConfig,
}
impl<'de> Deserialize<'de> for RouteConfig {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Self, D::Error> {
use serde::de::Error as _;
let mut table = toml::Table::deserialize(d)?;
let name = match table.remove("name") {
None => String::new(),
Some(toml::Value::String(name)) => name,
Some(other) => {
return Err(D::Error::custom(format!(
"provider.route `name` must be a string, got {}",
other.type_str()
)))
}
};
let label = if name.is_empty() {
"an unnamed route".to_string()
} else {
format!("route `{name}`")
};
let max_parallel = match table.remove("max_parallel") {
None => None,
Some(toml::Value::Integer(n)) if n >= 0 => Some(n as usize),
Some(other) => {
return Err(D::Error::custom(format!(
"{label}: `max_parallel` must be a positive integer, got {}",
other.type_str()
)))
}
};
let group = match table.remove("group") {
None => None,
Some(toml::Value::String(g)) if !g.trim().is_empty() => Some(g),
Some(_) => {
return Err(D::Error::custom(format!(
"{label}: `group` must be a non-empty string"
)))
}
};
let config = ProviderConfig::deserialize(toml::Value::Table(table))
.map_err(|e| D::Error::custom(format!("{label}: {e}")))?;
Ok(Self {
name,
max_parallel,
group,
config,
})
}
}
pub const DEFAULT_ROUTE: &str = "default";
impl ProviderConfig {
fn declares_connection(&self) -> bool {
!self.base_url.trim().is_empty()
|| !self.model.trim().is_empty()
|| self.api_key.is_some()
|| self.api_key_env.is_some()
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct NamedRoute {
pub name: String,
pub max_parallel: Option<usize>,
pub group: Option<String>,
pub config: ProviderConfig,
}
impl NamedRoute {
pub fn default_parallel(&self) -> usize {
let profile = self.config.profile.as_deref().unwrap_or("openai");
if profile.eq_ignore_ascii_case("openai") {
4
} else {
1
}
}
pub fn parallel(&self) -> usize {
self.max_parallel
.unwrap_or_else(|| self.default_parallel())
.max(1)
}
pub fn with_flare_shape(mut self, max_parallel: Option<usize>, group: Option<String>) -> Self {
self.max_parallel = max_parallel;
self.group = group;
self
}
fn new(name: &str, config: &ProviderConfig) -> Self {
let mut config = config.clone();
config.route.clear();
config.fallback = None;
config.aux = None;
config.delegate = None;
Self {
name: name.to_string(),
max_parallel: None,
group: None,
config,
}
}
fn require_endpoint(&self, source: ChainSource) -> Result<()> {
let plain = self.name == DEFAULT_ROUTE && source == ChainSource::Default;
let missing = |key: &str, hint: &str| {
Error::Config(if plain {
format!("provider.{key} is not set {hint}")
} else {
format!("route `{}` has no {key}", self.name)
})
};
if self.config.base_url.trim().is_empty() {
return Err(missing(
"base_url",
"(config file or ECLIPSE_BASE_URL); run `eclipse config init`",
));
}
if self.config.model.trim().is_empty() {
return Err(missing("model", "(config file or ECLIPSE_MODEL)"));
}
Ok(())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ChainSource {
Default,
Fallback,
Pinned,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Chain {
pub routes: Vec<NamedRoute>,
pub source: ChainSource,
pub aux: Option<NamedRoute>,
pub delegate: Option<NamedRoute>,
}
impl Chain {
pub fn roles(&self) -> Vec<crate::router::RoleRoute> {
crate::router::role_table(
self.aux.as_ref().map(|r| r.name.as_str()),
self.delegate.as_ref().map(|r| r.name.as_str()),
self.routes.first().map_or("", |r| r.name.as_str()),
self.source == ChainSource::Pinned,
)
}
}
fn apply_key_env(cfg: &mut ProviderConfig, env: EnvFn, explicit: Option<String>) {
if let Some(v) = explicit {
cfg.api_key = Some(v);
} else if let Some(name) = cfg.api_key_env.clone() {
if let Some(v) = env(&name) {
cfg.api_key = Some(v);
}
}
}
impl Default for ProviderConfig {
fn default() -> Self {
Self {
base_url: String::new(),
api_key: None,
api_key_env: None,
model: String::new(),
temperature: None,
timeout_secs: 120,
stream: true,
max_retries: 3,
retry_after_send: false,
retry_base_delay_ms: 2000,
context_budget_tokens: 0,
max_tokens: None,
profile: None,
top_p: None,
seed: None,
stop: None,
reasoning_effort: None,
parallel_tool_calls: None,
vision: None,
tool_choice: None,
extra_body: None,
fallback: None,
aux: None,
delegate: None,
route: Vec::new(),
}
}
}
impl fmt::Debug for ProviderConfig {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ProviderConfig")
.field(
"base_url",
&redact_url(&self.base_url).unwrap_or_else(|| self.base_url.clone()),
)
.field("api_key", &self.api_key.as_ref().map(|_| "<redacted>"))
.field("api_key_env", &self.api_key_env)
.field("model", &self.model)
.field("temperature", &self.temperature)
.field("timeout_secs", &self.timeout_secs)
.field("stream", &self.stream)
.field("max_retries", &self.max_retries)
.field("retry_after_send", &self.retry_after_send)
.field("retry_base_delay_ms", &self.retry_base_delay_ms)
.field("context_budget_tokens", &self.context_budget_tokens)
.field("vision", &self.vision)
.field("fallback", &self.fallback)
.field("aux", &self.aux)
.field("delegate", &self.delegate)
.field("route", &self.route)
.finish()
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct AgentConfig {
pub max_consecutive_malformed_tool_calls: usize,
pub system_prompt: String,
#[serde(
default = "unlimited_turns",
deserialize_with = "de_turn_limit",
serialize_with = "ser_turn_limit"
)]
pub max_iterations: usize,
#[serde(deserialize_with = "empty_is_none")]
pub output_schema: Option<String>,
pub context_file_max_chars: usize,
pub context_files_budget_chars: usize,
pub trace_content: bool,
pub prompt_blocks: crate::prompt_blocks::Choice,
}
fn unlimited_turns() -> usize {
usize::MAX
}
fn de_turn_limit<'de, D>(d: D) -> std::result::Result<usize, D::Error>
where
D: serde::Deserializer<'de>,
{
#[derive(serde::Deserialize)]
#[serde(untagged)]
enum Raw {
Number(i64),
Word(String),
}
let n = match Raw::deserialize(d)? {
Raw::Number(n) => n,
Raw::Word(word) => match word.trim().to_ascii_lowercase().as_str() {
"unlimited" | "none" | "null" | "inf" | "infinite" | "infinity" | "∞" => 0,
other => other.parse::<i64>().map_err(|_| {
serde::de::Error::custom(format!(
"`max_iterations` takes a whole number or `unlimited`, not `{other}`"
))
})?,
},
};
Ok(if n <= 0 {
unlimited_turns()
} else {
n as usize
})
}
fn ser_turn_limit<S>(value: &usize, s: S) -> std::result::Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
if *value == usize::MAX {
s.serialize_str("unlimited")
} else {
s.serialize_u64(*value as u64)
}
}
impl Default for AgentConfig {
fn default() -> Self {
Self {
system_prompt:
"You are a helpful personal assistant running locally on the user's machine. \
Use tools only when they are needed, and explain briefly what you did."
.into(),
max_iterations: unlimited_turns(),
output_schema: None,
max_consecutive_malformed_tool_calls: 0,
context_file_max_chars: crate::context_files::DEFAULT_MAX_FILE_CHARS,
context_files_budget_chars: crate::context_files::DEFAULT_BUDGET_CHARS,
trace_content: false,
prompt_blocks: crate::prompt_blocks::Choice::Auto,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct ToolsConfig {
pub workspace_root: Option<PathBuf>,
pub read_file: Policy,
pub search_files: Policy,
pub write_file: Policy,
#[serde(default = "default_rewrite_guard")]
pub rewrite_guard_bytes: usize,
pub patch: Policy,
pub memory: Policy,
pub shell: Policy,
pub fetch: Policy,
pub script: Policy,
pub execute_code: Policy,
pub delegate: Policy,
pub shell_ask: ShellAsk,
pub shell_timeout_secs: u64,
pub shell_allowlist: Vec<String>,
pub shell_isolate: ShellIsolate,
pub shell_isolate_writable: Vec<PathBuf>,
pub shell_isolate_hide: Vec<PathBuf>,
pub shell_isolate_network: bool,
pub fetch_timeout_secs: u64,
pub fetch_html: FetchHtml,
pub max_output_bytes: usize,
pub concurrency: usize,
pub disabled: Vec<String>,
#[serde(default = "default_deferred")]
pub deferred: Vec<String>,
pub tool_search: Policy,
pub tool_describe: Policy,
pub tool_call: Policy,
}
fn default_hidden_paths() -> Vec<PathBuf> {
["~/.ssh", "~/.gnupg", "~/.aws", "~/.hermes"]
.iter()
.map(PathBuf::from)
.collect()
}
fn default_deferred() -> Vec<String> {
vec!["plugin:mcp:*".to_string(), "config:mcp:*".to_string()]
}
fn default_rewrite_guard() -> usize {
32 * 1024
}
impl Default for ToolsConfig {
fn default() -> Self {
Self {
workspace_root: None,
read_file: Policy::Allow,
search_files: Policy::Allow,
write_file: Policy::Allow,
rewrite_guard_bytes: default_rewrite_guard(),
patch: Policy::Allow,
memory: Policy::Ask,
shell: Policy::Ask,
fetch: Policy::Ask,
script: Policy::Ask,
execute_code: Policy::Ask,
delegate: Policy::Ask,
shell_ask: ShellAsk::Dangerous,
shell_timeout_secs: 30,
shell_allowlist: Vec::new(),
shell_isolate: ShellIsolate::Process,
shell_isolate_writable: Vec::new(),
shell_isolate_hide: default_hidden_paths(),
shell_isolate_network: true,
fetch_timeout_secs: 20,
fetch_html: FetchHtml::Text,
max_output_bytes: 32 * 1024,
concurrency: 1,
disabled: Vec::new(),
deferred: default_deferred(),
tool_search: Policy::Allow,
tool_describe: Policy::Allow,
tool_call: Policy::Allow,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct SessionsConfig {
pub dir: Option<PathBuf>,
pub retention_keep_days: u64,
pub retention_keep_count: usize,
pub auto_prune: bool,
pub lock_wait_secs: u64,
pub autotitle: bool,
}
impl Default for SessionsConfig {
fn default() -> Self {
Self {
dir: None,
retention_keep_days: 0,
retention_keep_count: 0,
auto_prune: false,
lock_wait_secs: 30,
autotitle: true,
}
}
}
#[derive(Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct WebConfig {
pub host: String,
pub port: u16,
#[serde(deserialize_with = "empty_is_none")]
pub auth_token: Option<String>,
pub session_ttl_hours: u64,
#[serde(deserialize_with = "empty_is_none")]
pub default_profile: Option<String>,
}
impl Default for WebConfig {
fn default() -> Self {
Self {
host: "127.0.0.1".into(),
port: 8787,
auth_token: None,
session_ttl_hours: DEFAULT_SESSION_TTL_HOURS,
default_profile: None,
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct GatewayConfig {
pub check_interval_hours: u64,
#[serde(default = "default_api_session_ttl_hours")]
pub api_session_ttl_hours: u64,
}
pub fn default_api_session_ttl_hours() -> u64 {
24
}
impl Default for GatewayConfig {
fn default() -> Self {
Self {
check_interval_hours: 6,
api_session_ttl_hours: default_api_session_ttl_hours(),
}
}
}
pub const DEFAULT_SESSION_TTL_HOURS: u64 = 12;
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Approval {
#[default]
Ask,
Auto,
Smart,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct CliConfig {
pub color: Option<bool>,
pub markdown: Option<bool>,
pub approval: Approval,
pub history_size: usize,
pub clear_on_exit: ClearOnExit,
}
impl Default for CliConfig {
fn default() -> Self {
Self {
color: None,
markdown: None,
approval: Approval::Ask,
history_size: 1000,
clear_on_exit: ClearOnExit::Screen,
}
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ClearOnExit {
#[default]
Screen,
All,
Off,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum UpdateCheck {
#[default]
Daily,
Weekly,
Off,
}
impl UpdateCheck {
pub fn period_secs(self) -> Option<u64> {
match self {
UpdateCheck::Daily => Some(86_400),
UpdateCheck::Weekly => Some(7 * 86_400),
UpdateCheck::Off => None,
}
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Track {
#[default]
Release,
Develop,
}
impl Track {
pub fn label(self) -> &'static str {
match self {
Track::Release => "release",
Track::Develop => "develop",
}
}
pub fn branch(self) -> &'static str {
match self {
Track::Release => "main",
Track::Develop => "develop",
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct HooksConfig {
pub order: Vec<String>,
#[serde(flatten)]
pub settings: BTreeMap<String, toml::Value>,
}
impl Default for HooksConfig {
fn default() -> Self {
Self {
order: crate::hooks::DEFAULT_ORDER
.iter()
.map(|n| n.to_string())
.collect(),
settings: BTreeMap::new(),
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct UpdateConfig {
pub check: UpdateCheck,
pub track: Track,
#[serde(deserialize_with = "empty_is_none")]
pub remote: Option<String>,
#[serde(deserialize_with = "empty_is_none")]
pub releases: Option<String>,
}
impl fmt::Debug for WebConfig {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("WebConfig")
.field("host", &self.host)
.field("port", &self.port)
.field(
"auth_token",
&self.auth_token.as_ref().map(|_| "<redacted>"),
)
.finish()
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct AttachmentsConfig {
pub dir: Option<PathBuf>,
pub max_total_bytes: u64,
}
impl Default for AttachmentsConfig {
fn default() -> Self {
Self {
dir: None,
max_total_bytes: 2 * 1024 * 1024 * 1024,
}
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct Config {
pub config_version: u32,
pub provider: ProviderConfig,
pub agent: AgentConfig,
pub tools: ToolsConfig,
pub sessions: SessionsConfig,
pub attachments: AttachmentsConfig,
pub plugins: PluginsConfig,
pub web: WebConfig,
pub gateway: GatewayConfig,
pub cli: CliConfig,
pub update: UpdateConfig,
pub hooks: HooksConfig,
pub context: ContextPolicyConfig,
pub user: UserConfig,
pub skills: SkillsConfig,
pub vision: VisionConfig,
#[serde(skip)]
pub profile: Option<String>,
#[serde(skip)]
pub route_pin: Option<String>,
#[serde(skip)]
pub dotenv: Dotenv,
#[serde(default)]
pub mcp: Vec<crate::mcp::Spec>,
#[serde(skip)]
pub no_mcp: bool,
#[serde(default)]
pub flares: FlaresConfig,
#[serde(default)]
pub bots: std::collections::BTreeMap<String, BotConfig>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct FlaresConfig {
pub count: usize,
pub max_concurrent: usize,
pub max_iterations: usize,
pub total_iterations: usize,
pub total_tokens: Option<u64>,
}
impl Default for FlaresConfig {
fn default() -> Self {
Self {
count: 3,
max_concurrent: 4,
max_iterations: 6,
total_iterations: 24,
total_tokens: None,
}
}
}
impl FlaresConfig {
pub fn concurrency(&self) -> usize {
self.max_concurrent.max(1)
}
pub fn per_flare(&self) -> usize {
self.max_iterations.max(1)
}
pub fn budget(&self) -> usize {
self.total_iterations.max(1)
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct BotConfig {
pub instructions: Option<String>,
pub skills: Option<Vec<String>>,
pub memory: Option<String>,
pub adapter: Option<String>,
}
pub const BOT_ADAPTERS: &[&str] = &[];
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct ContextPolicyConfig {
pub compact_at: f64,
pub protect_last_n: usize,
pub judge: bool,
pub judge_timeout_secs: u64,
pub window_tokens: usize,
pub handoff_chars: usize,
}
impl Default for ContextPolicyConfig {
fn default() -> Self {
Self {
compact_at: 0.85,
protect_last_n: crate::context::DEFAULT_PROTECT_LAST_N,
judge: true,
judge_timeout_secs: 20,
window_tokens: 0,
handoff_chars: 6_000,
}
}
}
impl ContextPolicyConfig {
pub fn budget_for(&self, window_tokens: usize) -> usize {
if window_tokens == 0 || self.compact_at.is_nan() || self.compact_at <= 0.0 {
return 0;
}
(window_tokens as f64 * self.compact_at) as usize
}
pub fn validate(&self) -> Result<()> {
if !(0.0..=1.0).contains(&self.compact_at) {
return Err(Error::Config(format!(
"context.compact_at: {} is not a share of the window; use 0.85 for 85%, or 0 to \
turn the threshold off",
self.compact_at
)));
}
if self.handoff_chars < 200 {
return Err(Error::Config(format!(
"context.handoff_chars: {} is too small to compile a handoff; 200 is the floor \
and 6000 is the default",
self.handoff_chars
)));
}
Ok(())
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct UserConfig {
pub file: String,
pub memory_file: String,
pub memory_budget_chars: usize,
}
impl Default for UserConfig {
fn default() -> Self {
Self {
file: "USER.md".into(),
memory_file: "MEMORY.md".into(),
memory_budget_chars: crate::memory::DEFAULT_BUDGET_CHARS,
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct VisionConfig {
#[serde(default)]
pub mode: VisionMode,
#[serde(default)]
pub route: String,
#[serde(default)]
pub allow_cloud: bool,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum VisionMode {
Native,
Text,
#[default]
Auto,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct SkillsConfig {
pub index_budget_chars: usize,
}
impl Default for SkillsConfig {
fn default() -> Self {
Self {
index_budget_chars: crate::skills::DEFAULT_INDEX_BUDGET_CHARS,
}
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct PluginsConfig {
pub dir: Option<PathBuf>,
pub enabled: Vec<String>,
pub mcp_timeout_secs: Option<u64>,
}
impl Config {
pub fn load(explicit: Option<&Path>) -> Result<Config> {
Self::load_with(explicit, &process_env)
}
pub fn load_with(explicit: Option<&Path>, env: EnvFn) -> Result<Config> {
Self::load_with_profile(explicit, None, env)
}
pub fn load_with_profile(
explicit: Option<&Path>,
profile: Option<&str>,
env: EnvFn,
) -> Result<Config> {
let profile = profile
.map(str::to_string)
.or_else(|| env("ECLIPSE_PROFILE"))
.filter(|p| !p.trim().is_empty());
if let Some(name) = &profile {
validate_profile_name(name)?;
}
let dotenv = Dotenv::load(env, profile.as_deref())?;
let lookup = |k: &str| {
env(k).or_else(|| {
dotenv
.values
.get(k)
.filter(|v| !v.is_empty())
.map(String::as_str)
.map(str::to_string)
})
};
let lookup: EnvFn<'_> = &lookup;
let base_path = match explicit {
Some(p) => Some(p.to_path_buf()),
None => config_path(env).filter(|p| p.exists()),
};
let mut hooks_path = base_path.clone();
let mut value = match &base_path {
Some(p) => {
let mut parsed = read_toml(p)?;
crate::interpolate::in_value(&mut parsed, p, lookup)?;
parsed
}
None => toml::Value::try_from(Config::default())
.map_err(|e| Error::Config(e.to_string()))?,
};
if let Some(name) = &profile {
if let Some(dir) = profile_dir(env, name) {
let overlay = dir.join("config.toml");
if overlay.exists() {
let mut over = read_toml(&overlay)?;
crate::interpolate::in_value(&mut over, &overlay, lookup)?;
if over.get("hooks").is_some() {
hooks_path = Some(overlay.clone());
}
merge_toml(&mut value, over);
}
}
}
let mut cfg: Config = value
.try_into()
.map_err(|e: toml::de::Error| Error::Parse {
path: base_path.unwrap_or_else(|| PathBuf::from("<defaults>")),
message: e.to_string(),
})?;
cfg.profile = profile;
cfg.apply_env(lookup);
cfg.dotenv = dotenv;
cfg.validate_routes()?;
cfg.context.validate()?;
cfg.validate_bots()?;
crate::hooks::validate(&cfg.hooks).map_err(|message| Error::Parse {
path: hooks_path.unwrap_or_else(|| PathBuf::from("<defaults>")),
message,
})?;
Ok(cfg)
}
pub fn profile_name(&self) -> &str {
self.profile.as_deref().unwrap_or("default")
}
pub fn state_dir(&self, env: EnvFn) -> Result<PathBuf> {
state_dir_for(env, self.profile.as_deref())
.ok_or_else(|| Error::Config("cannot determine state dir: HOME is not set".into()))
}
pub fn plugins_dirs(&self, env: EnvFn) -> Vec<PathBuf> {
let mut out = Vec::new();
if let Some(name) = &self.profile {
if let Some(dir) = profile_dir(env, name) {
out.push(dir.join("plugins"));
}
}
let shared = match &self.plugins.dir {
Some(p) => expand_tilde(p, env),
None => match config_dir(env) {
Some(d) => d.join("plugins"),
None => return out,
},
};
if !out.contains(&shared) {
out.push(shared);
}
out
}
pub fn from_file(path: &Path) -> Result<Config> {
let text = std::fs::read_to_string(path).map_err(|e| Error::io(path, e))?;
Self::from_toml_str(&text).map_err(|message| Error::Parse {
path: path.to_path_buf(),
message,
})
}
pub fn from_toml_str(text: &str) -> std::result::Result<Config, String> {
toml::from_str(text).map_err(|e| e.to_string())
}
pub fn apply_env(&mut self, env: EnvFn) {
if let Some(v) = env("ECLIPSE_BASE_URL") {
self.provider.base_url = v;
}
if let Some(v) = env("ECLIPSE_MODEL") {
self.provider.model = v;
}
if self.provider.declares_connection() {
apply_key_env(&mut self.provider, env, env("ECLIPSE_API_KEY"));
}
for route in &mut self.provider.route {
apply_key_env(&mut route.config, env, None);
}
}
pub fn to_toml_redacted(&self) -> Result<String> {
let mut value = toml::Value::try_from(self).map_err(|e| Error::Config(e.to_string()))?;
redact(&mut value);
toml::to_string_pretty(&value).map_err(|e| Error::Config(e.to_string()))
}
pub fn require_provider(&self) -> Result<()> {
self.chain().map(|_| ())
}
pub fn declared_routes(&self) -> Vec<NamedRoute> {
let mut out = Vec::new();
if self.provider.route.is_empty() || self.provider.declares_connection() {
out.push(NamedRoute::new(DEFAULT_ROUTE, &self.provider));
}
out.extend(self.provider.route.iter().map(|r| {
NamedRoute::new(&r.name, &r.config).with_flare_shape(r.max_parallel, r.group.clone())
}));
out
}
pub fn route_names(&self) -> String {
let names: Vec<String> = self.declared_routes().into_iter().map(|r| r.name).collect();
if names.is_empty() {
"none".to_string()
} else {
names.join(", ")
}
}
pub fn validate_routes(&self) -> Result<()> {
let p = &self.provider;
let mut seen: Vec<&str> = Vec::new();
for (i, r) in p.route.iter().enumerate() {
let name = r.name.trim();
if name.is_empty() {
return Err(Error::Config(format!(
"provider.route #{} has no name; every [[provider.route]] needs `name = \"...\"`",
i + 1
)));
}
if seen.contains(&name) {
return Err(Error::Config(format!(
"two routes are named `{name}`; route names must be unique"
)));
}
seen.push(name);
if name == DEFAULT_ROUTE && p.declares_connection() {
return Err(Error::Config(format!(
"a route is named `{DEFAULT_ROUTE}`, but `[provider]` is also set and is the \
route of that name; rename the route, or move its settings out of [provider]"
)));
}
if r.config.fallback.is_some()
|| r.config.aux.is_some()
|| r.config.delegate.is_some()
|| !r.config.route.is_empty()
{
return Err(Error::Config(format!(
"route `{name}` has its own `fallback`, `aux`, `delegate` or `route`; those \
belong directly under [provider], not inside a route"
)));
}
if r.config.base_url.trim().is_empty() {
return Err(Error::Config(format!(
"route `{name}` has no base_url; a route is a complete provider \
configuration and does not inherit from [provider]"
)));
}
if r.config.model.trim().is_empty() {
return Err(Error::Config(format!(
"route `{name}` has no model; a route is a complete provider \
configuration and does not inherit from [provider]"
)));
}
}
if let Some(fallback) = &p.fallback {
if fallback.is_empty() {
return Err(Error::Config(
"provider.fallback is empty; name the routes to try in order, or remove the \
key to use `default` alone"
.into(),
));
}
let known: Vec<String> = self.declared_routes().into_iter().map(|r| r.name).collect();
let mut listed: Vec<&str> = Vec::new();
for name in fallback {
if !known.contains(name) {
return Err(Error::Config(format!(
"provider.fallback names `{name}`, which is not a route. Routes that \
exist: {}",
self.route_names()
)));
}
if listed.contains(&name.as_str()) {
return Err(Error::Config(format!(
"provider.fallback lists `{name}` twice; each route is tried at most \
once per run"
)));
}
listed.push(name);
}
if p.declares_connection() && !listed.contains(&DEFAULT_ROUTE) {
return Err(Error::Config(
"`[provider]` sets a connection, but provider.fallback is the whole chain \
and does not list `default`, so that endpoint would never be called. Put \
`default` first in `fallback`, or move the connection keys into a route \
and leave `[provider]` to `fallback` alone"
.into(),
));
}
}
if let Some(aux) = &p.aux {
if aux.trim().is_empty() {
return Err(Error::Config(
"provider.aux is empty; name the route that does housekeeping, or remove \
the key to use the route the run is on"
.into(),
));
}
if !self.declared_routes().iter().any(|r| &r.name == aux) {
return Err(Error::Config(format!(
"provider.aux names `{aux}`, which is not a route. Routes that exist: {}",
self.route_names()
)));
}
}
if let Some(delegate) = &p.delegate {
if delegate.trim().is_empty() {
return Err(Error::Config(
"provider.delegate is empty; name the route subagents run on, or remove \
the key to use the route the run is on"
.into(),
));
}
if !self.declared_routes().iter().any(|r| &r.name == delegate) {
return Err(Error::Config(format!(
"provider.delegate names `{delegate}`, which is not a route. Routes that \
exist: {}",
self.route_names()
)));
}
}
let vision_route = self.vision.route.trim();
if !vision_route.is_empty()
&& !self
.declared_routes()
.iter()
.any(|r| r.name == vision_route)
{
return Err(Error::Config(format!(
"vision.route names `{vision_route}`, which is not a route. Routes that exist: {}",
self.route_names()
)));
}
Ok(())
}
pub fn pin_route(&mut self, flag: Option<&str>, env: EnvFn) -> Result<()> {
let wanted = match flag {
Some(name) if name.trim().is_empty() => {
return Err(Error::Config(
"--route needs a route name; `eclipse config show` lists them".into(),
))
}
Some(name) => Some(name.trim().to_string()),
None => env("ECLIPSE_ROUTE")
.or_else(|| self.dotenv.values.get("ECLIPSE_ROUTE").cloned())
.map(|v| v.trim().to_string())
.filter(|v| !v.is_empty()),
};
if let Some(name) = &wanted {
if !self.declared_routes().iter().any(|r| &r.name == name) {
return Err(self.unknown_route(name));
}
}
self.route_pin = wanted;
Ok(())
}
fn unknown_route(&self, name: &str) -> Error {
Error::Config(format!(
"unknown route `{name}`. Routes that exist: {}",
self.route_names()
))
}
pub fn chain(&self) -> Result<Chain> {
self.validate_routes()?;
let all = self.declared_routes();
let find = |name: &str| all.iter().find(|r| r.name == name).cloned();
let (routes, source) = if let Some(pin) = &self.route_pin {
let route = find(pin).ok_or_else(|| self.unknown_route(pin))?;
(vec![route], ChainSource::Pinned)
} else if let Some(fallback) = &self.provider.fallback {
let routes = fallback.iter().filter_map(|n| find(n)).collect();
(routes, ChainSource::Fallback)
} else if self.provider.declares_connection() || self.provider.route.is_empty() {
(
vec![NamedRoute::new(DEFAULT_ROUTE, &self.provider)],
ChainSource::Default,
)
} else {
return Err(Error::Config(format!(
"routes are declared but nothing says which to use: set `[provider] fallback = \
[...]`, or pass --route NAME. Routes that exist: {}",
self.route_names()
)));
};
for route in &routes {
route.require_endpoint(source)?;
}
let pinned = source == ChainSource::Pinned;
let only = routes.first().cloned();
let (aux, delegate) = if pinned {
(only.clone(), only)
} else {
(
self.provider.aux.as_deref().and_then(find),
self.provider.delegate.as_deref().and_then(find),
)
};
if let Some(aux) = &aux {
aux.require_endpoint(source)?;
}
if let Some(delegate) = &delegate {
delegate.require_endpoint(source)?;
}
Ok(Chain {
routes,
source,
aux,
delegate,
})
}
pub fn sessions_dir(&self, env: EnvFn) -> Result<PathBuf> {
if let Some(d) = &self.sessions.dir {
return Ok(expand_tilde(d, env));
}
Ok(self.state_dir(env)?.join("sessions"))
}
pub fn validate_bots(&self) -> Result<()> {
for name in self.bots.keys() {
let ok = !name.is_empty()
&& name.len() <= 32
&& name
.chars()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-' || c == '_');
if !ok {
return Err(Error::Config(format!(
"bots.{name}: a bot name is lowercase letters, digits, `-` and `_`, at most \
32 of them — it becomes part of a session's `origin` and a URL"
)));
}
}
Ok(())
}
pub fn bot_file(&self, env: EnvFn, path: &str) -> Option<PathBuf> {
let path = expand_tilde(Path::new(path), env);
if path.is_absolute() {
Some(path)
} else {
self.context_dir(env).map(|dir| dir.join(path))
}
}
pub fn bot_memory(&self, env: EnvFn, name: &str, bot: &BotConfig) -> Option<PathBuf> {
match bot.memory.as_deref().filter(|m| !m.trim().is_empty()) {
Some(m) => self.bot_file(env, m),
None => self
.memory_dir(env)
.map(|dir| dir.join("bots").join(name).join(&self.user.memory_file)),
}
}
pub fn attachments_dir(&self, env: EnvFn) -> Option<PathBuf> {
if let Some(dir) = &self.attachments.dir {
return Some(expand_tilde(dir, env));
}
self.state_dir(env).ok().map(|d| d.join("attachments"))
}
pub fn where_am_i(&self, env: EnvFn, loaded: Option<&Path>) -> Where {
let overlay = self
.profile
.as_deref()
.filter(|name| *name != "default")
.and_then(|name| profile_dir(env, name))
.map(|dir| dir.join("config.toml"))
.filter(|path| path.exists());
Where {
profile: self.profile.clone(),
config: loaded.map(Path::to_path_buf).or_else(|| config_path(env)),
overlay,
home: home_root(env),
sessions: self.sessions_dir(env).ok(),
}
}
pub fn context_dir(&self, env: EnvFn) -> Option<PathBuf> {
match &self.profile {
Some(name) => profile_dir(env, name),
None => config_path(env)
.and_then(|p| p.parent().map(Path::to_path_buf))
.or_else(|| config_dir(env)),
}
}
pub fn scripts_dir(&self, env: EnvFn) -> Option<PathBuf> {
let dir = self.context_dir(env)?.join("scripts");
if dir.is_absolute() {
return Some(dir);
}
std::env::current_dir().ok().map(|cwd| cwd.join(dir))
}
pub fn memory_dir(&self, env: EnvFn) -> Option<PathBuf> {
self.context_dir(env).map(|d| d.join("memory"))
}
pub fn global_context_dir(&self, env: EnvFn) -> Option<PathBuf> {
config_path(env)
.and_then(|p| p.parent().map(Path::to_path_buf))
.or_else(|| config_dir(env))
}
pub fn home(&self, env: EnvFn) -> Option<PathBuf> {
home_dir(env)
}
pub fn workspace_root(&self, env: EnvFn) -> PathBuf {
match &self.tools.workspace_root {
Some(p) => expand_tilde(p, env),
None => std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Where {
pub profile: Option<String>,
pub config: Option<PathBuf>,
pub overlay: Option<PathBuf>,
pub home: Option<PathBuf>,
pub sessions: Option<PathBuf>,
}
impl Where {
pub fn name(&self) -> &str {
self.profile.as_deref().unwrap_or("default")
}
pub fn is_default(&self) -> bool {
matches!(self.profile.as_deref(), None | Some("default"))
}
}
fn read_toml(path: &Path) -> Result<toml::Value> {
let text = std::fs::read_to_string(path).map_err(|e| Error::io(path, e))?;
toml::from_str::<toml::Value>(&text).map_err(|message| Error::Parse {
path: path.to_path_buf(),
message: message.to_string(),
})
}
fn merge_toml(base: &mut toml::Value, over: toml::Value) {
match (base, over) {
(toml::Value::Table(base), toml::Value::Table(over)) => {
for (key, value) in over {
match base.get_mut(&key) {
Some(slot) => merge_toml(slot, value),
None => {
base.insert(key, value);
}
}
}
}
(slot, over) => *slot = over,
}
}
fn redact(value: &mut toml::Value) {
match value {
toml::Value::Table(table) => {
for (key, slot) in table.iter_mut() {
if is_secret_key(key) && matches!(slot, toml::Value::String(s) if !s.is_empty()) {
*slot = toml::Value::String("<redacted>".into());
continue;
}
if is_url_key(key) {
if let toml::Value::String(url) = slot {
if let Some(clean) = redact_url(url) {
*slot = toml::Value::String(clean);
continue;
}
}
}
redact(slot);
}
}
toml::Value::Array(items) => items.iter_mut().for_each(redact),
_ => {}
}
}
pub(crate) fn is_secret_key(key: &str) -> bool {
let k = key.to_ascii_lowercase();
if k.ends_with("_env") {
return false;
}
const COUNTS: &[&str] = &[
"_tokens",
"_chars",
"_secs",
"_ms",
"_count",
"_size",
"_hours",
"_days",
"_bytes",
"_iterations",
"_call",
];
if COUNTS.iter().any(|suffix| k.ends_with(suffix)) {
return false;
}
k == "api_key"
|| k.ends_with("_key")
|| k.contains("token")
|| k.contains("secret")
|| k.contains("password")
}
fn is_url_key(key: &str) -> bool {
let k = key.to_ascii_lowercase();
k.ends_with("_url") || k == "url" || k == "remote" || k == "releases"
}
pub(crate) fn redact_url(text: &str) -> Option<String> {
let (body, fragment) = match text.split_once('#') {
Some((b, f)) => (b, Some(f)),
None => (text, None),
};
let (before_query, query) = match body.split_once('?') {
Some((b, q)) => (b, Some(q)),
None => (body, None),
};
let mut changed = false;
let head = match before_query.find("://") {
Some(scheme_end) => {
let start = scheme_end + 3;
let rest = &before_query[start..];
let authority_end = rest.find('/').unwrap_or(rest.len());
match rest[..authority_end].rfind('@') {
Some(at) => {
changed = true;
format!("{}{}<redacted>{}", &before_query[..start], "", &rest[at..])
}
None => before_query.to_string(),
}
}
None => before_query.to_string(),
};
let query = query.map(|q| {
let pairs: Vec<String> = q
.split('&')
.map(|pair| {
let name = pair.split_once('=').map(|(n, _)| n).unwrap_or(pair);
if !name.is_empty() && is_secret_key(name) {
changed = true;
format!("{name}=<redacted>")
} else {
pair.to_string()
}
})
.collect();
pairs.join("&")
});
if !changed {
return None;
}
let mut out = head;
if let Some(q) = query {
out.push('?');
out.push_str(&q);
}
if let Some(f) = fragment {
out.push('#');
out.push_str(f);
}
Some(out)
}
const SHIPPED_SPELLING: &[(&str, &str, &str)] = &[
("provider", "api_key", "${OPENAI_API_KEY:-}"),
("provider", "api_key_env", ""),
("provider", "profile", ""),
(
"provider",
"reasoning_effort",
crate::reasoning::SHIPPED_DEFAULT,
),
("provider", "aux", ""),
("provider", "delegate", ""),
("agent", "output_schema", ""),
("web", "auth_token", "${ECLIPSE_WEB_AUTH_TOKEN:-}"),
("web", "default_profile", ""),
("update", "remote", ""),
("update", "releases", ""),
("tools", "write_file", "ask"),
("tools", "patch", "ask"),
];
fn shipped_text(spelling: &str) -> String {
toml::Value::String(spelling.to_string()).to_string()
}
const SECTION_ORDER: &[&str] = &[
"provider",
"agent",
"tools",
"flares",
"sessions",
"attachments",
"context",
"plugins",
"cli",
"web",
"gateway",
"update",
"hooks",
"user",
"skills",
"vision",
];
pub fn starter_config() -> Result<String> {
let defaults = toml::Value::try_from(Config::default())
.map_err(|e| Error::Config(format!("the default config does not serialise: {e}")))?;
let mut out = String::with_capacity(8 * 1024);
out.push_str("# Every setting this build reads, and nothing else.\n");
out.push_str("# What one does, and what it accepts: `eclipse config docs`.\n");
out.push_str("# A commented key is not in use; an empty value means the same.\n");
out.push_str(&format!("config_version = {CONFIG_VERSION}\n"));
for section in SECTION_ORDER {
out.push_str(&format!("\n[{section}]\n"));
let table = defaults.get(*section).and_then(toml::Value::as_table);
let mut lines: Vec<(String, String)> = Vec::new();
let mut nested: Vec<&str> = Vec::new();
if let Some(table) = table {
for (key, value) in table {
match value {
toml::Value::Table(_) => nested.push(key.as_str()),
other => {
let shipped = SHIPPED_SPELLING
.iter()
.find(|(s, k, _)| s == section && k == key)
.map(|(_, _, spelling)| shipped_text(spelling));
lines.push((key.clone(), shipped.unwrap_or_else(|| other.to_string())));
}
}
}
}
for (abs_section, key, _) in settings::ABSENT_BY_DEFAULT {
if abs_section == section && !lines.iter().any(|(k, _)| k == key) {
let shipped = SHIPPED_SPELLING
.iter()
.find(|(s, k, _)| s == section && k == key)
.map(|(_, _, spelling)| shipped_text(spelling));
lines.push(((*key).to_string(), shipped.unwrap_or_default()));
}
}
lines.sort();
for (key, text) in lines {
if text.is_empty() {
out.push_str(&format!("# {key} =\n"));
} else {
out.push_str(&format!("{key} = {text}\n"));
}
}
nested.sort();
for key in nested {
let Some(sub) = table.and_then(|t| t.get(key)) else {
continue;
};
let mut wrapped = toml::map::Map::new();
wrapped.insert(key.to_string(), sub.clone());
if let Ok(text) = toml::to_string(&toml::Value::Table(wrapped)) {
out.push('\n');
out.push_str(&text);
}
}
if *section == "hooks" {
let default_hooks = Config::default().hooks;
for name in &default_hooks.order {
if default_hooks.settings.contains_key(name) {
continue;
}
let Some(info) = crate::hooks::SHIPPED.iter().find(|h| h.name == name) else {
continue;
};
out.push_str(&format!("\n[hooks.{name}]\n"));
let mut keys = info.settings.to_vec();
keys.sort_unstable();
for key in keys {
out.push_str(&format!("# {key} =\n"));
}
}
}
}
Ok(out)
}
pub const ENV_TEMPLATE: &[&str] = &[
"ECLIPSE_BASE_URL",
"ECLIPSE_MODEL",
"ECLIPSE_API_KEY",
"ECLIPSE_REASONING_EFFORT",
"ECLIPSE_ROUTE",
"OPENAI_API_KEY",
"ECLIPSE_WEB_AUTH_TOKEN",
"ECLIPSE_WEB_USER",
"ECLIPSE_WEB_PASSWORD_HASH",
];
pub const ENV_ABOUT: &[(&str, &str)] = &[
("ECLIPSE_BASE_URL", "The provider's base URL, up to and including the version: it beats `[provider] base_url` for this process only"),
("ECLIPSE_MODEL", "The model name to ask for, beating `[provider] model`; the same as `--model`"),
("ECLIPSE_API_KEY", "The provider's key, resolved by `api_key = \"${ECLIPSE_API_KEY}\"`; never put the key itself in `config.toml`"),
("ECLIPSE_REASONING_EFFORT", "The reasoning level for this process: none, minimal, low, medium, high, xhigh, max"),
("ECLIPSE_ROUTE", "Pin one named route and never fall back from it, the same as `--route`"),
("OPENAI_API_KEY", "The variable the shipped `provider.api_key` line refers to; any name works, this one is the convention"),
("ECLIPSE_WEB_AUTH_TOKEN", "The dashboard's bearer token, generated by `config init`; the dashboard refuses to start without it"),
("ECLIPSE_WEB_USER", "The dashboard's sign-in name, when it asks for a name and a password instead of the token"),
("ECLIPSE_WEB_PASSWORD_HASH", "That password, as `eclipse web passwd` writes it: `pbkdf2-sha256$<iterations>$<salt>$<digest>`"),
("ECLIPSE_HOME", "The one directory everything lives in (`~/.eclipse` otherwise). Read from the shell, never from this file"),
("ECLIPSE_CONFIG", "The config file to read (`<home>/config.toml` otherwise). Read from the shell, never from this file"),
("ECLIPSE_PROFILE", "The profile to load, the same as `--profile`. Read from the shell, never from this file"),
("ECLIPSE_BIN", "The `eclipse` binary a spawned job should use; this tool sets it, and only a test overrides it"),
("ECLIPSE_ARGS", "The JSON arguments of the tool call a plugin or MCP server is being asked about; set by this tool"),
("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"),
("ECLIPSE_TOOL", "The tool name a bridged call is for; set by this tool"),
("ECLIPSE_TOOL_SOCKET", "Where a script or plugin calls back into the running agent; set by this tool"),
("ECLIPSE_WORKSPACE", "The workspace root, given to a child process; set by this tool from `[tools] workspace_root`"),
("ECLIPSE_PLUGIN_DIR", "The plugin directory, given to a child process; set by this tool"),
("ECLIPSE_SCRIPTS_DIR", "The scripts directory, given to a child process; set by this tool"),
];
pub fn env_about(name: &str) -> &'static str {
ENV_ABOUT
.iter()
.find(|(n, _)| *n == name)
.map(|(_, about)| *about)
.unwrap_or("")
}
pub const ENV_SHELL_ONLY: &[&str] = &["ECLIPSE_HOME", "ECLIPSE_CONFIG", "ECLIPSE_PROFILE"];
pub const ENV_INTERNAL: &[&str] = &[
"ECLIPSE_BIN",
"ECLIPSE_ARGS",
"ECLIPSE_ARGS_BYTES",
"ECLIPSE_TOOL",
"ECLIPSE_TOOL_SOCKET",
"ECLIPSE_WORKSPACE",
"ECLIPSE_PLUGIN_DIR",
"ECLIPSE_SCRIPTS_DIR",
];
pub fn starter_env(token: &str) -> String {
let mut out = String::with_capacity(1024);
out.push_str("# Secrets and per-host overrides. The shell beats this file. Mode 0600.\n");
out.push_str("# Every variable this build reads; an empty value is not set. `eclipse config docs` explains each.\n");
for name in ENV_TEMPLATE {
if *name == "ECLIPSE_WEB_AUTH_TOKEN" {
out.push_str(&format!("{name}={token}\n"));
} else {
out.push_str(&format!("{name}=\n"));
}
}
out
}
pub const STARTER_PROFILE_CONFIG: &str = r#"# A profile overlay: keys here replace the base config's, and a key left out follows it.
# Examples are commented out on purpose — an empty value here *replaces* the base value.
[provider]
# base_url = "http://127.0.0.1:8080/v1"
# model = "qwen3-coder:30b"
# profile = "llamacpp"
[tools]
# shell = "ask"
"#;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InitReport {
pub config: PathBuf,
pub dotenv: PathBuf,
pub dotenv_written: bool,
}
pub fn write_starter_config(path: &Path, force: bool, env: EnvFn) -> Result<InitReport> {
if path.exists() && !force {
return Err(Error::Config(format!(
"{} already exists (use --force to overwrite)",
path.display()
)));
}
let dir = path.parent().unwrap_or(Path::new("."));
std::fs::create_dir_all(dir).map_err(|e| Error::io(dir, e))?;
write_private(path, &starter_config()?)?;
let secrets_dir = config_dir(env).unwrap_or_else(|| dir.to_path_buf());
std::fs::create_dir_all(&secrets_dir).map_err(|e| Error::io(&secrets_dir, e))?;
let dotenv = secrets_dir.join(".env");
let mut dotenv_written = false;
if !dotenv.exists() {
let token = crate::token::generate()?;
write_private(&dotenv, &starter_env(&token))?;
dotenv_written = true;
}
let _ = migrate::write_baseline(path);
Ok(InitReport {
config: path.to_path_buf(),
dotenv,
dotenv_written,
})
}
pub fn toml_value(text: &str, section: &str, key: &str) -> Option<String> {
let mut in_section = false;
for line in text.lines() {
let trimmed = line.trim();
if let Some(name) = section_header(trimmed) {
in_section = name == section;
continue;
}
if !in_section || trimmed.starts_with('#') {
continue;
}
if let Some((k, v)) = key_value(trimmed) {
if k == key {
return Some(v);
}
}
}
None
}
pub fn toml_set_string(text: &str, section: &str, key: &str, value: &str) -> String {
toml_set_value(text, section, key, &format!("\"{}\"", escape_toml(value)))
}
pub fn toml_set_value(text: &str, section: &str, key: &str, value: &str) -> String {
place_line(text, section, key, &format!("{key} = {value}"))
}
struct McpSpan {
name: Option<String>,
start: usize,
end: usize,
}
fn is_table_header(trimmed: &str) -> bool {
trimmed.starts_with('[')
}
fn mcp_spans(lines: &[String]) -> Vec<McpSpan> {
let mut spans: Vec<McpSpan> = Vec::new();
let mut open: Option<usize> = None;
let mut closed_by_header = true;
for (i, line) in lines.iter().enumerate() {
let trimmed = line.trim();
if open.is_some() && is_table_header(trimmed) {
if let Some(start) = open.take() {
spans.push(McpSpan {
name: None,
start,
end: i,
});
closed_by_header = true;
}
}
if trimmed == "[[mcp]]" {
open = Some(i);
}
}
if let Some(start) = open {
spans.push(McpSpan {
name: None,
start,
end: lines.len(),
});
closed_by_header = false;
}
let count = spans.len();
for (i, span) in spans.iter_mut().enumerate() {
let at_eof = i + 1 == count && !closed_by_header;
while span.end > span.start + 1 {
let tail = lines[span.end - 1].trim();
let belongs_to_next = !at_eof && (tail.is_empty() || tail.starts_with('#'));
if tail.is_empty() || belongs_to_next {
span.end -= 1;
} else {
break;
}
}
}
for span in &mut spans {
let body = lines[span.start + 1..span.end].join("\n");
span.name = toml::from_str::<crate::mcp::Spec>(&body)
.ok()
.map(|spec| spec.name);
}
spans
}
fn tidy_blanks(lines: Vec<String>) -> Vec<String> {
let mut end = lines.len();
while end > 0 && lines[end - 1].trim().is_empty() {
end -= 1;
}
let mut out: Vec<String> = Vec::with_capacity(end);
let mut blanks = 0;
for line in &lines[..end] {
if line.trim().is_empty() {
blanks += 1;
if blanks > 1 {
continue;
}
} else {
blanks = 0;
}
out.push(line.clone());
}
out
}
fn render_mcp_entry(entry: &crate::mcp::Spec) -> String {
let quote = |s: &str| toml::Value::String(s.to_string()).to_string();
let mut out = String::from("[[mcp]]\n");
out.push_str(&format!("name = {}\n", quote(&entry.name)));
if entry.transport == crate::mcp::Transport::Http {
out.push_str("transport = \"http\"\n");
}
if !entry.command.is_empty() {
out.push_str(&format!("command = {}\n", quote(&entry.command)));
}
if !entry.args.is_empty() {
let args: Vec<String> = entry.args.iter().map(|a| quote(a)).collect();
out.push_str(&format!("args = [{}]\n", args.join(", ")));
}
if let Some(url) = &entry.url {
out.push_str(&format!("url = {}\n", quote(url)));
}
if let Some(var) = &entry.token_env {
out.push_str(&format!("token_env = {}\n", quote(var)));
}
if entry.cwd != crate::plugins::Cwd::default() {
let cwd = match entry.cwd {
crate::plugins::Cwd::Workspace => "workspace",
crate::plugins::Cwd::Plugin => "plugin",
};
out.push_str(&format!("cwd = \"{cwd}\"\n"));
}
if let Some(secs) = entry.timeout_secs {
out.push_str(&format!("timeout_secs = {secs}\n"));
}
if entry.policy != Policy::Ask {
let policy = match entry.policy {
Policy::Deny => "deny",
Policy::Ask => "ask",
Policy::Allow => "allow",
};
out.push_str(&format!("policy = \"{policy}\"\n"));
}
if !entry.policies.is_empty() {
let pairs: Vec<String> = entry
.policies
.iter()
.map(|(tool, policy)| {
let policy = match policy {
Policy::Deny => "deny",
Policy::Ask => "ask",
Policy::Allow => "allow",
};
format!("{tool} = \"{policy}\"")
})
.collect();
out.push_str(&format!("policies = {{ {} }}\n", pairs.join(", ")));
}
if !entry.prefix.is_empty() {
out.push_str(&format!("prefix = {}\n", quote(&entry.prefix)));
}
if !entry.env.is_empty() {
let env: Vec<String> = entry.env.iter().map(|e| quote(e)).collect();
out.push_str(&format!("env = [{}]\n", env.join(", ")));
}
if entry.override_builtin {
out.push_str("override = true\n");
}
if entry.disabled {
out.push_str("disabled = true\n");
}
out
}
pub fn mcp_add(text: &str, entry: &crate::mcp::Spec) -> std::result::Result<String, String> {
entry
.validate()
.map_err(|why| format!("that entry is not usable, so nothing was saved: {why}"))?;
let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
let spans = mcp_spans(&lines);
if let Some(existing) = spans
.iter()
.find(|s| s.name.as_deref() == Some(&entry.name))
{
return Err(format!(
"`{}` is already declared at line {} — `eclipse mcp remove {}` first, or edit that entry",
entry.name,
existing.start + 1,
entry.name
));
}
let rendered = render_mcp_entry(entry);
match spans.last() {
Some(last) => {
let at = last.end;
let mut fresh: Vec<String> = Vec::new();
if at > 0 && !lines[at - 1].trim().is_empty() {
fresh.push(String::new());
}
fresh.extend(rendered.lines().map(str::to_string));
lines.splice(at..at, fresh);
}
None => {
if lines.last().is_some_and(|l| !l.trim().is_empty()) {
lines.push(String::new());
}
lines.extend(rendered.lines().map(str::to_string));
}
}
let out = join_lines(tidy_blanks(lines));
readback_mcp(&out, &entry.name, |spec| spec == entry)
}
pub fn mcp_remove(text: &str, name: &str) -> std::result::Result<String, String> {
let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
let spans = mcp_spans(&lines);
let Some(span) = spans.iter().find(|s| s.name.as_deref() == Some(name)) else {
let known: Vec<&str> = spans.iter().filter_map(|s| s.name.as_deref()).collect();
return Err(if known.is_empty() {
format!("no `[[mcp]]` entry for `{name}` in this file")
} else {
format!(
"no `[[mcp]]` entry for `{name}`; this file declares {}",
known.join(", ")
)
});
};
let mut start = span.start;
while start > 0 && lines[start - 1].trim_start().starts_with('#') {
start -= 1;
}
let mut end = span.end;
if end < lines.len() && lines[end].trim().is_empty() {
end += 1;
}
lines.drain(start..end);
readback_mcp_absent(&join_lines(tidy_blanks(lines)), name)
}
pub fn mcp_set_disabled(
text: &str,
name: &str,
disabled: bool,
) -> std::result::Result<String, String> {
let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
let spans = mcp_spans(&lines);
let Some(span) = spans.iter().find(|s| s.name.as_deref() == Some(name)) else {
return Err(format!("no `[[mcp]]` entry for `{name}` in this file"));
};
let line = if disabled {
"disabled = true".to_string()
} else {
"disabled = false".to_string()
};
let body = span.start + 1..span.end;
match lines[body.clone()].iter().position(|l| {
l.trim_start()
.strip_prefix("disabled")
.is_some_and(|rest| rest.trim_start().starts_with('='))
}) {
Some(offset) => lines[span.start + 1 + offset] = line,
None => lines.insert(span.end, line),
}
readback_mcp(&join_lines(lines), name, |spec| spec.disabled == disabled)
}
pub fn mcp_update(
text: &str,
name: &str,
change: impl FnOnce(&mut crate::mcp::Spec),
) -> std::result::Result<String, String> {
let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
let spans = mcp_spans(&lines);
let Some(span) = spans.iter().find(|s| s.name.as_deref() == Some(name)) else {
let known: Vec<&str> = spans.iter().filter_map(|s| s.name.as_deref()).collect();
return Err(if known.is_empty() {
format!("no `[[mcp]]` entry for `{name}` in this file")
} else {
format!(
"no `[[mcp]]` entry for `{name}`; this file declares {}",
known.join(", ")
)
});
};
let body = lines[span.start + 1..span.end].join("\n");
let before: crate::mcp::Spec = toml::from_str(&body).map_err(|e| {
format!(
"the entry for `{name}` at line {} does not read as it stands, so nothing was saved: {}",
span.start + 1,
crate::config::settings::one_line(&e.to_string())
)
})?;
let mut after = before.clone();
change(&mut after);
if after.name != name {
return Err(format!(
"an edit does not rename: `{name}` stays `{name}` — remove the entry and add the new \
name instead"
));
}
after
.validate()
.map_err(|why| format!("that entry is not usable, so nothing was saved: {why}"))?;
let rendered = |spec: &crate::mcp::Spec| -> BTreeMap<String, String> {
render_mcp_entry(spec)
.lines()
.skip(1) .filter_map(|line| key_of(line).map(|key| (key, line.to_string())))
.collect()
};
let (old, new) = (rendered(&before), rendered(&after));
let (mut start, mut end) = (span.start + 1, span.end);
let block: Vec<String> = lines[start..end].to_vec();
let mut rebuilt: Vec<String> = Vec::new();
let mut seen: Vec<String> = Vec::new();
let mut i = 0;
while i < block.len() {
let line = &block[i];
let trimmed = line.trim();
if trimmed.is_empty() || trimmed.starts_with('#') {
rebuilt.push(line.clone());
i += 1;
continue;
}
let first = i;
let mut depth = bracket_depth(line);
i += 1;
while depth > 0 && i < block.len() {
depth += bracket_depth(&block[i]);
i += 1;
}
match key_of(&block[first]) {
Some(key) => {
seen.push(key.clone());
match (old.get(&key), new.get(&key)) {
(Some(was), Some(is)) if was == is => {
rebuilt.extend(block[first..i].iter().cloned())
}
(_, Some(is)) => rebuilt.push(is.clone()),
(_, None) => {}
}
}
None => rebuilt.extend(block[first..i].iter().cloned()),
}
}
for (key, line) in &new {
if !seen.contains(key) {
rebuilt.push(line.clone());
}
}
start = start.min(lines.len());
end = end.min(lines.len());
lines.splice(start..end, rebuilt);
let out = join_lines(lines);
readback_mcp(&out, name, |spec| spec == &after)
}
fn key_of(line: &str) -> Option<String> {
let trimmed = line.trim();
if trimmed.starts_with('#') {
return None;
}
let (key, _) = trimmed.split_once('=')?;
let key = key.trim();
let plain = !key.is_empty()
&& !key.contains(char::is_whitespace)
&& key
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-');
plain.then(|| key.to_string())
}
fn bracket_depth(line: &str) -> i32 {
let mut depth = 0;
let mut quote: Option<char> = None;
let mut escaped = false;
for c in line.chars() {
if let Some(q) = quote {
if escaped {
escaped = false;
} else if c == '\\' {
escaped = true;
} else if c == q {
quote = None;
}
continue;
}
match c {
'"' | '\'' => quote = Some(c),
'[' | '{' => depth += 1,
']' | '}' => depth -= 1,
'#' => break, _ => {}
}
}
depth
}
fn readback_mcp(
text: &str,
name: &str,
ok: impl Fn(&crate::mcp::Spec) -> bool,
) -> std::result::Result<String, String> {
let cfg = parse_text(text).map_err(|e| {
format!(
"that would not load, so nothing was saved: {}",
settings::one_line(&e.to_string())
)
})?;
match cfg.mcp.iter().find(|s| s.name == name) {
Some(spec) if ok(spec) => Ok(text.to_string()),
Some(_) => {
Err("the file would not read that entry back as written; nothing was saved".into())
}
None => Err(format!(
"the edit lost `{name}` on the way back in; nothing was saved"
)),
}
}
fn readback_mcp_absent(text: &str, name: &str) -> std::result::Result<String, String> {
let cfg = parse_text(text).map_err(|e| {
format!(
"that would not load, so nothing was saved: {}",
settings::one_line(&e.to_string())
)
})?;
if cfg.mcp.iter().any(|s| s.name == name) {
return Err(format!("`{name}` survived the removal; nothing was saved"));
}
Ok(text.to_string())
}
fn place_line(text: &str, section: &str, key: &str, replacement: &str) -> String {
let quoted = replacement.to_string();
let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
let mut in_section = false;
let mut header_at: Option<usize> = None;
let mut commented_at: Option<usize> = None;
for (i, line) in lines.iter().enumerate() {
let trimmed = line.trim();
if let Some(name) = section_header(trimmed) {
in_section = name == section;
if in_section && header_at.is_none() {
header_at = Some(i);
}
continue;
}
if !in_section {
continue;
}
if let Some((k, _)) = key_value(trimmed) {
if k == key {
lines[i] = quoted;
return join_lines(lines);
}
} else if let Some(rest) = trimmed.strip_prefix('#') {
if let Some((k, _)) = key_value(rest.trim()) {
if k == key && commented_at.is_none() {
commented_at = Some(i);
}
}
}
}
match (header_at, commented_at) {
(_, Some(i)) => lines[i] = quoted,
(Some(i), None) => lines.insert(i + 1, quoted),
(None, None) => {
lines.push(String::new());
lines.push(format!("[{section}]"));
lines.push(quoted);
}
}
join_lines(lines)
}
pub fn comment_in_text(text: &str, section: &str, key: &str) -> String {
place_line(text, section, key, &format!("# {key} ="))
}
pub fn stamp_version(text: &str, version: u32) -> std::result::Result<String, String> {
let line = format!("config_version = {version}");
let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
if let Some(at) = lines.iter().position(|l| {
l.trim_start()
.strip_prefix("config_version")
.is_some_and(|rest| rest.trim_start().starts_with('='))
}) {
lines[at] = line;
} else {
let first_table = lines
.iter()
.position(|l| section_header(l.trim()).is_some())
.unwrap_or(lines.len());
let mut insert_at = 0;
while insert_at < first_table
&& (lines[insert_at].trim_start().starts_with('#')
|| lines[insert_at].trim().is_empty())
{
insert_at += 1;
}
lines.insert(insert_at, String::new());
lines.insert(insert_at, line);
while insert_at > 0 && lines[insert_at - 1].trim().is_empty() {
lines.remove(insert_at - 1);
insert_at -= 1;
}
}
let out = join_lines(lines);
parse_text(&out).map_err(|e| format!("stamping the version would not load: {e}"))?;
Ok(out)
}
pub fn toml_comment_out(text: &str, section: &str, key: &str) -> String {
let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
let mut in_section = false;
for line in lines.iter_mut() {
let trimmed = line.trim();
if let Some(name) = section_header(trimmed) {
in_section = name == section;
continue;
}
if !in_section || trimmed.starts_with('#') {
continue;
}
if let Some((k, _)) = key_value(trimmed) {
if k == key {
let indent: String = line.chars().take_while(|c| c.is_whitespace()).collect();
*line = format!("{indent}# {trimmed}");
return join_lines(lines);
}
}
}
join_lines(lines)
}
pub(crate) fn section_header(trimmed: &str) -> Option<&str> {
if trimmed.starts_with("[[") {
return None;
}
let rest = trimmed.strip_prefix('[')?;
let name = rest.strip_suffix(']')?;
if name.contains(['[', ']']) || name.trim() != name || name.is_empty() {
return None;
}
Some(name)
}
pub(crate) fn key_value(trimmed: &str) -> Option<(&str, String)> {
let (k, v) = trimmed.split_once('=')?;
let k = k.trim();
if k.is_empty() || k.contains([' ', '"', '\\']) {
return None;
}
let v = v.trim();
let unquoted = match v.strip_prefix('"').and_then(|r| r.strip_suffix('"')) {
Some(inner) => inner.replace("\\\"", "\"").replace("\\\\", "\\"),
None => v.to_string(),
};
Some((k, unquoted))
}
fn escape_toml(value: &str) -> String {
value.replace('\\', "\\\\").replace('"', "\\\"")
}
fn join_lines(lines: Vec<String>) -> String {
let mut out = lines.join("\n");
if !out.ends_with('\n') {
out.push('\n');
}
out
}
pub fn save_config_text(path: &Path, text: &str) -> Result<()> {
write_private(path, text)
}
pub fn parse_text(text: &str) -> Result<Config> {
let cfg: Config =
toml::from_str(text).map_err(|e| Error::Config(format!("invalid config: {e}")))?;
crate::hooks::validate(&cfg.hooks)
.map_err(|e| Error::Config(format!("invalid config: {e}")))?;
Ok(cfg)
}
pub fn save_dotenv_var(path: &Path, key: &str, value: &str) -> Result<()> {
if key.contains(['\n', '\r']) || value.contains(['\n', '\r']) {
return Err(Error::Config(format!(
"{key:?} cannot be written to {}: a line break in a key or a value would make a second \
assignment",
path.display()
)));
}
let existing = match std::fs::read(path) {
Ok(bytes) => String::from_utf8(bytes).map_err(|_| {
Error::Config(format!(
"{}: not valid UTF-8, so nothing was written — repair or remove it by hand",
path.display()
))
})?,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
Err(e) => {
return Err(Error::Config(format!(
"{}: {e}, so nothing was written — whatever else is in it is untouched",
path.display()
)))
}
};
let line = format!("{key}={value}");
let mut out = String::new();
let mut replaced = false;
for l in existing.lines() {
let is_key = l
.trim_start()
.strip_prefix(key)
.map(|rest| rest.starts_with('='))
.unwrap_or(false);
if is_key {
out.push_str(&line);
out.push('\n');
replaced = true;
} else {
out.push_str(l);
out.push('\n');
}
}
if !replaced {
if !out.is_empty() && !out.ends_with('\n') {
out.push('\n');
}
out.push_str(&line);
out.push('\n');
}
write_private(path, &out)?;
let back = crate::dotenv::load(path)
.map_err(|e| Error::Config(format!("{}: {e}", path.display())))?
.into_iter()
.rfind(|a| a.key == key)
.map(|a| a.value);
match back {
Some(got) if got == value => Ok(()),
Some(got) => Err(Error::Config(format!(
"{}: {key} was written but reads back as {got:?}, not {value:?}; the rest of the file is \
intact, so fix that line by hand",
path.display()
))),
None => Err(Error::Config(format!(
"{}: {key} was written but the loader does not see it",
path.display()
))),
}
}
pub fn dotenv_var(path: &Path, key: &str) -> Option<String> {
crate::dotenv::load(path)
.ok()?
.into_iter()
.rfind(|a| a.key == key)
.map(|a| a.value)
.filter(|value| !value.is_empty())
}
pub(crate) fn write_private(path: &Path, text: &str) -> Result<()> {
crate::atomic::write_file_atomically(path, text).map_err(|e| Error::io(path, e))
}
#[test]
fn writing_the_empty_value_proves_itself_by_reading_back_as_unset() {
let text = starter_config().unwrap();
let without = settings::unset_in_text(&text, "agent.output_schema").expect("known key");
assert_eq!(
Config::from_toml_str(&without).unwrap().agent.output_schema,
None
);
let back = settings::set_in_text(
&without,
"agent.output_schema",
&toml::Value::String(String::new()),
)
.expect("an empty value can be written");
assert!(back.contains("output_schema = \"\""), "{back}");
assert_eq!(
Config::from_toml_str(&back).unwrap().agent.output_schema,
None,
"and it reads as unset, which is what it means"
);
assert_eq!(
toml_value(&back, "agent", "output_schema"),
Some(String::new()),
"the line is there; what it holds is nothing"
);
}
#[cfg(test)]
mod tests {
#[test]
fn a_route_can_say_how_many_flares_it_holds() {
let cfg = Config::from_toml_str(
r#"
[provider]
fallback = ["local", "cloud"]
[[provider.route]]
name = "local"
base_url = "http://127.0.0.1:8080/v1"
model = "qwen"
profile = "llamacpp"
group = "gpu0"
max_parallel = 2
[[provider.route]]
name = "cloud"
base_url = "https://api.example.com/v1"
model = "big"
"#,
)
.unwrap();
let routes = cfg.declared_routes();
let local = routes.iter().find(|r| r.name == "local").unwrap();
assert_eq!(local.parallel(), 2, "the route said two slots");
assert_eq!(local.group.as_deref(), Some("gpu0"));
let cloud = routes.iter().find(|r| r.name == "cloud").unwrap();
assert_eq!(cloud.parallel(), 4, "an openai route defaults to four");
assert!(cloud.group.is_none());
assert_eq!(
local.default_parallel(),
1,
"llamacpp serves one model at a time"
);
let zero = Config::from_toml_str(
r#"
[[provider.route]]
name = "local"
base_url = "http://127.0.0.1:8080/v1"
model = "qwen"
max_parallel = 0
"#,
)
.unwrap();
assert_eq!(zero.declared_routes()[0].parallel(), 1);
let bad = Config::from_toml_str(
r#"
[[provider.route]]
name = "local"
base_url = "http://127.0.0.1:8080/v1"
model = "qwen"
max_parallel = "two"
"#,
)
.unwrap_err()
.to_string();
assert!(bad.contains("route `local`"), "{bad}");
assert!(bad.contains("max_parallel"), "{bad}");
}
#[test]
fn flares_default_to_three_on_one_local_slot() {
let cfg = Config::from_toml_str("").unwrap();
assert_eq!(cfg.flares.count, 3, "the local default");
assert_eq!(cfg.flares.concurrency(), 4);
assert_eq!(cfg.flares.per_flare(), 6);
assert_eq!(cfg.flares.budget(), 24);
let cfg = Config::from_toml_str(
r#"
[flares]
count = 5
max_concurrent = 0
max_iterations = 0
total_iterations = 2
"#,
)
.unwrap();
assert_eq!(cfg.flares.count, 5);
assert_eq!(cfg.flares.concurrency(), 1);
assert_eq!(cfg.flares.per_flare(), 1);
assert_eq!(cfg.flares.budget(), 2);
}
use super::*;
use std::collections::HashMap;
fn starter() -> String {
starter_config().expect("the starter config generates")
}
fn env_of(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> {
let m: HashMap<String, String> = pairs
.iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect();
move |k| m.get(k).cloned()
}
fn load_hooks(text: &str) -> std::result::Result<Config, String> {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("config.toml");
std::fs::write(&path, text).unwrap();
let env = env_of(&[("HOME", tmp.path().to_str().unwrap())]);
Config::load_with_profile(Some(&path), None, &env).map_err(|e| e.to_string())
}
#[test]
fn the_memory_and_the_filter_are_on_by_default_when_there_is_no_hooks_section() {
let want = crate::hooks::DEFAULT_ORDER;
let c = load_hooks("[agent]\nmax_iterations = 3\n").unwrap();
assert_eq!(c.hooks.order, want);
assert_eq!(Config::default().hooks.order, want);
let c = load_hooks("").unwrap();
assert_eq!(c.hooks.order, want);
assert!(
!want.contains(&"recall-sessions"),
"a new session is a new session: recall is opt-in, and `session_search` is how the \
agent reaches the archive"
);
}
#[test]
fn an_empty_order_turns_every_hook_off() {
let c = load_hooks("[hooks]\norder = []\n").unwrap();
assert!(c.hooks.order.is_empty());
}
#[test]
fn a_settings_table_alone_keeps_the_default_order() {
let c = load_hooks("[hooks.redact-secrets]\nallow = [\"fixture-key\"]\n").unwrap();
assert_eq!(c.hooks.order, crate::hooks::DEFAULT_ORDER);
}
#[test]
fn a_hook_name_this_build_does_not_have_is_refused_and_the_real_ones_are_listed() {
let err =
load_hooks("[hooks]\norder = [\"redact-secrets\", \"redact-secret\"]\n").unwrap_err();
assert!(err.contains("`redact-secret`"), "{err}");
assert!(
err.contains("Hooks that exist: recall-sessions, redact-secrets"),
"{err}"
);
assert!(err.contains("config.toml"), "the file is named: {err}");
}
#[test]
fn a_settings_table_for_a_hook_that_is_not_in_order_is_refused() {
let err =
load_hooks("[hooks]\norder = []\n[hooks.redact-secrets]\nallow = []\n").unwrap_err();
assert!(err.contains("[hooks.redact-secrets]"), "{err}");
assert!(err.contains("never run"), "{err}");
assert!(err.contains("Add \"redact-secrets\" to order"), "{err}");
}
#[test]
fn a_settings_table_for_a_hook_that_does_not_exist_is_refused() {
let err = load_hooks("[hooks.nope]\nx = 1\n").unwrap_err();
assert!(err.contains("[hooks.nope]"), "{err}");
assert!(err.contains("Hooks that exist"), "{err}");
}
#[test]
fn an_unknown_key_in_a_hooks_table_is_refused_and_the_known_ones_are_listed() {
let err = load_hooks("[hooks.redact-secrets]\nalow = [\"x\"]\n").unwrap_err();
assert!(err.contains("unknown key `alow`"), "{err}");
assert!(err.contains("accepts: allow"), "{err}");
}
#[test]
fn a_stray_key_directly_under_hooks_is_refused() {
let err = load_hooks("[hooks]\nenabled = true\n").unwrap_err();
assert!(err.contains("`enabled`"), "{err}");
assert!(err.contains("`order`"), "{err}");
}
#[test]
fn a_hook_listed_twice_and_a_malformed_allow_list_are_refused() {
let err =
load_hooks("[hooks]\norder = [\"redact-secrets\", \"redact-secrets\"]\n").unwrap_err();
assert!(err.contains("twice"), "{err}");
let err = load_hooks("[hooks.redact-secrets]\nallow = \"x\"\n").unwrap_err();
assert!(err.contains("must be a list of strings"), "{err}");
let err = load_hooks("[hooks.redact-secrets]\nallow = [\"\"]\n").unwrap_err();
assert!(err.contains("empty string"), "{err}");
let err = load_hooks("[hooks.redact-secrets]\nallow = [1]\n").unwrap_err();
assert!(err.contains("only strings"), "{err}");
}
#[test]
fn a_profile_overlay_that_breaks_the_hooks_section_is_blamed_on_the_overlay() {
let tmp = tempfile::tempdir().unwrap();
let home = tmp.path().join("home");
let dir = home.join(".eclipse");
std::fs::create_dir_all(dir.join("profiles/work")).unwrap();
std::fs::write(
dir.join("config.toml"),
"[hooks]\norder = [\"redact-secrets\"]\n",
)
.unwrap();
std::fs::write(
dir.join("profiles/work/config.toml"),
"[hooks]\norder = [\"typo\"]\n",
)
.unwrap();
let env = env_of(&[("HOME", home.to_str().unwrap())]);
let err = Config::load_with_profile(None, Some("work"), &env)
.unwrap_err()
.to_string();
assert!(err.contains("profiles/work/config.toml"), "{err}");
assert!(err.contains("`typo`"), "{err}");
}
#[test]
fn an_empty_value_is_not_a_value_in_the_dotenv() {
let dir = tempfile::tempdir().unwrap();
let home = dir.path();
std::fs::create_dir_all(home.join(".eclipse")).unwrap();
let path = home.join(".eclipse/.env");
std::fs::write(
&path,
"ECLIPSE_API_KEY=\nECLIPSE_MODEL=m\nECLIPSE_WEB_AUTH_TOKEN=\n",
)
.unwrap();
let home_s = home.to_str().unwrap().to_string();
let env = env_of(&[("HOME", &home_s)]);
let loaded = Dotenv::load(&env, None).unwrap();
assert_eq!(
loaded.values.get("ECLIPSE_MODEL").map(String::as_str),
Some("m")
);
assert!(
!loaded.values.contains_key("ECLIPSE_API_KEY"),
"an empty assignment is absent: {:?}",
loaded.values.keys().collect::<Vec<_>>()
);
assert!(!loaded.values.contains_key("ECLIPSE_WEB_AUTH_TOKEN"));
}
#[test]
fn a_later_empty_assignment_unsets_an_earlier_one() {
let dir = tempfile::tempdir().unwrap();
let home = dir.path();
std::fs::create_dir_all(home.join(".eclipse").join("profiles/work")).unwrap();
std::fs::write(home.join(".eclipse/.env"), "ECLIPSE_MODEL=big\n").unwrap();
std::fs::write(home.join(".eclipse/profiles/work/.env"), "ECLIPSE_MODEL=\n").unwrap();
let home_s = home.to_str().unwrap().to_string();
let env = env_of(&[("HOME", &home_s)]);
let loaded = Dotenv::load(&env, Some("work")).unwrap();
assert_eq!(loaded.files.len(), 2);
assert_eq!(loaded.values.get("ECLIPSE_MODEL"), None);
}
#[test]
fn the_starter_env_lists_every_variable_and_sets_none_of_them() {
let text = starter_env("tok");
for name in ENV_TEMPLATE {
assert!(
text.contains(&format!("\n{name}=")),
"`{name}` is in the shipped .env"
);
}
for line in text.lines().filter(|l| !l.starts_with('#')) {
let (name, value) = line.split_once('=').expect("KEY=VALUE");
if name == "ECLIPSE_WEB_AUTH_TOKEN" {
assert_eq!(value, "tok", "the one value a first install cannot invent");
} else {
assert!(value.is_empty(), "`{name}` ships unset, found `{value}`");
}
}
}
#[test]
fn every_environment_variable_the_build_reads_is_classified() {
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("..");
let mut seen = Vec::new();
let mut dirs = vec![
root.join("eclipse-core/src"),
root.join("eclipse-cli/src"),
root.join("eclipse-web/src"),
];
while let Some(dir) = dirs.pop() {
let Ok(entries) = std::fs::read_dir(&dir) else {
continue;
};
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
dirs.push(path);
continue;
}
if path.extension().and_then(|e| e.to_str()) != Some("rs") {
continue;
}
let text = std::fs::read_to_string(&path).unwrap_or_default();
for name in env_names(&text) {
if !seen.contains(&name) {
seen.push(name);
}
}
}
}
assert!(seen.len() > 10, "the scan found the variables: {seen:?}");
for name in &seen {
let known = ENV_TEMPLATE.contains(&name.as_str())
|| ENV_SHELL_ONLY.contains(&name.as_str())
|| ENV_INTERNAL.contains(&name.as_str());
assert!(
known,
"`{name}` is read by the build and is in none of ENV_TEMPLATE, ENV_SHELL_ONLY, ENV_INTERNAL"
);
}
let shipped = starter();
for name in ENV_TEMPLATE {
let read = seen.iter().any(|s| s == name);
let interpolated = shipped.contains(&format!("${{{name}"));
assert!(
read || interpolated,
"`{name}` is in the shipped .env and nothing reads or interpolates it"
);
}
}
#[test]
fn every_classified_variable_has_a_description() {
let classified: Vec<&str> = ENV_TEMPLATE
.iter()
.chain(ENV_SHELL_ONLY)
.chain(ENV_INTERNAL)
.copied()
.collect();
for name in &classified {
assert!(
!env_about(name).is_empty(),
"`{name}` is classified and has no line in ENV_ABOUT"
);
}
for (name, about) in ENV_ABOUT {
assert!(
classified.contains(name),
"ENV_ABOUT explains `{name}`, which the build does not read"
);
assert!(
about.len() > 30 && !about.ends_with('.'),
"one sentence, no full stop: {about}"
);
}
}
fn env_names(text: &str) -> Vec<String> {
let mut out = Vec::new();
let mut rest = text;
while let Some(at) = rest.find("\"ECLIPSE_") {
let after = &rest[at + 1..];
let Some(end) = after.find('"') else {
break;
};
let name = &after[..end];
let complete = name
.chars()
.last()
.is_some_and(|c| c.is_ascii_uppercase() || c.is_ascii_digit());
if complete
&& name
.chars()
.all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')
{
out.push(name.to_string());
}
rest = &after[end + 1..];
}
out
}
#[test]
fn an_empty_optional_string_loads_as_unset() {
let c = Config::from_toml_str(
"[provider]\napi_key = \"\"\napi_key_env = \"\"\nmodel = \"m\"\n[web]\nauth_token = \"\"\n",
)
.unwrap();
assert_eq!(c.provider.api_key, None);
assert_eq!(c.provider.api_key_env, None);
assert_eq!(c.web.auth_token, None);
assert_eq!(c.provider.model, "m");
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("config.toml");
std::fs::write(&path, "[provider]\napi_key = \"${NOT_SET_ANYWHERE:-}\"\n").unwrap();
let from_var = Config::load_with(Some(&path), &env_of(&[])).unwrap();
assert_eq!(
from_var.provider.api_key, None,
"an absent variable is no key"
);
}
#[test]
fn the_starter_config_carries_every_setting_the_build_reads() {
let text = starter();
let c = parse_text(&text).unwrap();
let settings = Config::default().settings();
assert!(
settings.len() > 80,
"the catalogue is the yardstick: {settings:?}"
);
for setting in &settings {
let key = setting.key.clone();
let present = text.lines().any(|l| {
l.trim_start_matches("# ")
.trim_start()
.starts_with(&format!("{key} ="))
});
assert!(
present,
"[{}] `{key}` is missing from the shipped file:\n{text}",
setting.section
);
}
for line in text.lines().filter(|l| l.starts_with('#')) {
assert!(
line.starts_with("# ") && line[2..].contains(" =") || line.len() < 120,
"a comment in the settings file should be a key, not a sentence: {line}"
);
}
let prose = text
.lines()
.filter(|l| l.starts_with('#') && !l[1..].trim_start().contains(" ="))
.count();
assert!(prose <= 3, "only the three header lines: {prose}");
assert_eq!(c.hooks.order, crate::hooks::DEFAULT_ORDER);
assert_eq!(c.hooks.order, Config::default().hooks.order);
assert!(c.hooks.settings.contains_key("redact-secrets"));
crate::hooks::validate(&c.hooks).expect("the starter config's hooks validate");
assert!(
!c.hooks.settings.contains_key("recall-sessions"),
"a settings table for a hook that is not in `order` cannot run"
);
let value: toml::Value = toml::from_str(&text).unwrap();
let unknown = c.unknown_keys(&value);
assert!(
unknown.is_empty(),
"unknown keys in the shipped file: {unknown:?}"
);
assert_eq!(
c.config_version, CONFIG_VERSION,
"the file stamps its shape"
);
}
#[test]
fn config_show_scrubs_credentials_carried_in_an_mcp_url() {
let c = Config::from_toml_str(
"[provider]\nbase_url = \"http://127.0.0.1:1/v1\"\n\n\
[[mcp]]\nname = \"gh\"\ntransport = \"http\"\n\
url = \"https://user:pw@example.test/mcp?token=abc&limit=5\"\n\n\
[[mcp]]\nname = \"plain\"\ntransport = \"http\"\n\
url = \"https://example.test/mcp\"\n",
)
.unwrap();
let shown = c.to_toml_redacted().unwrap();
assert!(!shown.contains("pw"), "the password is gone: {shown}");
assert!(!shown.contains("abc"), "the token is gone: {shown}");
assert!(
shown.contains("https://<redacted>@example.test/mcp"),
"the shape is kept, the credentials are not: {shown}"
);
assert!(
shown.contains("token=<redacted>"),
"the parameter name stays, its value does not: {shown}"
);
assert!(
shown.contains("limit=5"),
"a parameter that is not a secret is not touched: {shown}"
);
assert!(
shown.contains("url = \"https://example.test/mcp\""),
"an endpoint with no credentials in it reads exactly as written: {shown}"
);
}
#[test]
fn the_hooks_section_survives_a_round_trip_through_the_redacted_printout() {
let c = load_hooks(
"[hooks]\norder = [\"redact-secrets\"]\n[hooks.redact-secrets]\nallow = [\"fx\"]\n",
)
.unwrap();
let shown = c.to_toml_redacted().unwrap();
let again = Config::from_toml_str(&shown).unwrap();
assert_eq!(again.hooks, c.hooks);
}
#[test]
fn defaults_have_no_endpoint_or_key() {
let c = Config::default();
assert!(c.provider.base_url.is_empty());
assert!(c.provider.api_key.is_none());
assert!(c.require_provider().is_err());
assert_eq!(c.tools.write_file, Policy::Allow);
assert_eq!(c.tools.shell, Policy::Ask);
assert_eq!(c.tools.shell_ask, ShellAsk::Dangerous);
}
#[test]
fn cli_section_defaults_and_parses() {
let d = Config::from_toml_str("").unwrap().cli;
assert_eq!(d.color, None);
assert_eq!(d.markdown, None);
assert_eq!(d.approval, Approval::Ask);
assert_eq!(d.history_size, 1000);
let c = Config::from_toml_str(
"[cli]\ncolor = false\nmarkdown = true\napproval = \"auto\"\nhistory_size = 50\n",
)
.unwrap()
.cli;
assert_eq!(c.color, Some(false));
assert_eq!(c.markdown, Some(true));
assert_eq!(c.approval, Approval::Auto);
assert_eq!(c.history_size, 50);
}
#[test]
fn an_unknown_approval_is_an_error_rather_than_a_silent_ask() {
let err = Config::from_toml_str("[cli]\napproval = \"sometimes\"\n").unwrap_err();
assert!(err.contains("approval"), "{err}");
}
#[test]
fn web_section_parses_its_ttl_and_default_profile() {
let d = Config::from_toml_str("").unwrap().web;
assert_eq!(d.session_ttl_hours, DEFAULT_SESSION_TTL_HOURS);
assert_eq!(d.default_profile, None);
let w = Config::from_toml_str("[web]\nsession_ttl_hours = 1\ndefault_profile = \"work\"\n")
.unwrap()
.web;
assert_eq!(w.session_ttl_hours, 1);
assert_eq!(w.default_profile.as_deref(), Some("work"));
}
#[test]
fn the_starter_config_loads_without_a_dotenv_and_leaves_the_token_unset() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("config.toml");
std::fs::write(&path, starter()).unwrap();
let c = Config::load_with(Some(&path), &|_| None)
.expect("the starter config loads with no .env at all");
assert_eq!(
c.web.auth_token, None,
"an unset token loads as no token, not as a load error and not as an empty secret"
);
assert_eq!(c.provider.model, Config::default().provider.model);
}
#[test]
fn starter_config_parses_and_matches_defaults() {
let c = Config::from_toml_str(&starter()).unwrap();
let d = Config::default();
assert_eq!(c.tools.read_file, d.tools.read_file);
assert_eq!(c.tools.fetch, d.tools.fetch);
assert_eq!(c.web.port, d.web.port);
assert!(c.provider.base_url.is_empty());
}
#[test]
fn partial_file_fills_defaults() {
let c = Config::from_toml_str(
"[provider]\nbase_url=\"http://x/v1\"\nmodel=\"m\"\n[tools]\nshell=\"deny\"\n",
)
.unwrap();
assert_eq!(c.provider.base_url, "http://x/v1");
assert_eq!(c.tools.shell, Policy::Deny);
assert_eq!(c.tools.write_file, Policy::Allow);
assert_eq!(
c.agent.max_iterations,
usize::MAX,
"no cap unless the box asks for one"
);
assert!(c.require_provider().is_ok());
for word in ["unlimited", "none", "inf", "0", "-1"] {
let raw = format!("[agent]\nmax_iterations = {word}\n");
let raw = if word.parse::<i64>().is_ok() {
raw
} else {
format!("[agent]\nmax_iterations = \"{word}\"\n")
};
let c = Config::from_toml_str(&raw).unwrap();
assert_eq!(c.agent.max_iterations, usize::MAX, "`{word}` means no cap");
}
let c = Config::from_toml_str("[agent]\nmax_iterations = 12\n").unwrap();
assert_eq!(c.agent.max_iterations, 12, "a number is a cap");
let words = Config::from_toml_str("[agent]\nmax_iterations = \"unlimited\"\n").unwrap();
let printed = toml::to_string(&words).unwrap();
assert!(
printed.contains("max_iterations = \"unlimited\""),
"the schema says the word, not a length: {printed}"
);
let refused = Config::from_toml_str("[agent]\nmax_iterations = \"plenty\"\n");
assert!(
refused.is_err(),
"a word that is not one of ours is an error"
);
}
#[test]
fn unknown_policy_is_rejected() {
assert!(Config::from_toml_str("[tools]\nshell=\"yolo\"\n").is_err());
}
#[test]
fn env_overrides_file() {
let dir = tempfile::tempdir().unwrap();
let p = dir.path().join("c.toml");
std::fs::write(
&p,
"[provider]\nbase_url=\"http://file/v1\"\nmodel=\"file-model\"\napi_key=\"file-key\"\n",
)
.unwrap();
let env = env_of(&[
("ECLIPSE_BASE_URL", "http://env/v1"),
("ECLIPSE_API_KEY", "env-key"),
]);
let c = Config::load_with(Some(&p), &env).unwrap();
assert_eq!(c.provider.base_url, "http://env/v1");
assert_eq!(c.provider.model, "file-model");
assert_eq!(c.provider.api_key.as_deref(), Some("env-key"));
}
#[test]
fn api_key_env_indirection() {
let env = env_of(&[("MY_KEY", "secret")]);
let mut c = Config::from_toml_str("[provider]\napi_key_env=\"MY_KEY\"\n").unwrap();
c.apply_env(&env);
assert_eq!(c.provider.api_key.as_deref(), Some("secret"));
}
#[test]
fn debug_redacts_api_key() {
let mut c = Config::default();
c.provider.api_key = Some("hunter2".into());
assert!(!format!("{c:?}").contains("hunter2"));
}
#[test]
fn debug_and_redacted_toml_hide_web_token() {
let mut c = Config::default();
c.web.auth_token = Some("s3cret-token-value".into());
assert!(!format!("{c:?}").contains("s3cret"));
assert!(!c.to_toml_redacted().unwrap().contains("s3cret"));
}
#[test]
fn debug_never_prints_a_dotenv_value() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("root");
std::fs::create_dir_all(&root).unwrap();
std::fs::write(
root.join(".env"),
"ECLIPSE_API_KEY=dotenvvalue123\nMY_PRIVATE_MIRROR=mirrorvalue456\n",
)
.unwrap();
let cfg_path = root.join("config.toml");
std::fs::write(
&cfg_path,
"[provider]\nbase_url = \"http://127.0.0.1:9/v1\"\nmodel = \"m\"\napi_key = \"${ECLIPSE_API_KEY}\"\n",
)
.unwrap();
let env = env_of(&[
("ECLIPSE_HOME", root.to_str().unwrap()),
("HOME", dir.path().to_str().unwrap()),
]);
let cfg = Config::load_with_profile(Some(&cfg_path), None, &env).unwrap();
let debug = format!("{cfg:?}");
assert!(
!debug.contains("dotenvvalue123") && !debug.contains("mirrorvalue456"),
"the .env values must never be printed: {debug}"
);
assert!(debug.contains("ECLIPSE_API_KEY"), "{debug}");
assert!(debug.contains("Dotenv"), "{debug}");
assert_eq!(cfg.provider.api_key.as_deref(), Some("dotenvvalue123"));
}
#[test]
fn redacted_toml_hides_key_and_round_trips() {
let mut c = Config::default();
c.provider.api_key = Some("hunter2".into());
c.provider.model = "m".into();
let t = c.to_toml_redacted().unwrap();
assert!(!t.contains("hunter2"));
assert_eq!(Config::from_toml_str(&t).unwrap().provider.model, "m");
}
#[test]
fn the_update_track_names_a_branch_and_takes_two_words() {
assert_eq!(Config::default().update.track, Track::Release);
assert_eq!(Track::Release.branch(), "main");
assert_eq!(Track::Develop.branch(), "develop");
let cfg = Config::from_toml_str("[update]\ntrack = \"develop\"\n").unwrap();
assert_eq!(cfg.update.track, Track::Develop);
assert_eq!(cfg.update.track.label(), "develop");
let err = Config::from_toml_str("[update]\ntrack = \"main\"\n")
.unwrap_err()
.to_string();
assert!(
err.contains("main") && err.contains("develop"),
"the refusal lists the words it takes: {err}"
);
}
#[test]
fn a_url_keeps_its_shape_and_loses_its_secrets() {
let mut c = Config::default();
c.provider.base_url = "https://user:hunter2@gw.internal/v1".into();
c.update.remote =
Some("https://mirror.internal/releases?access_token=abc123&page=2".into());
c.update.releases = Some("https://mirror.internal/api#frag".into());
let t = c.to_toml_redacted().unwrap();
assert!(
!t.contains("hunter2") && !t.contains("abc123"),
"the secrets are gone: {t}"
);
assert!(
t.contains("https://<redacted>@gw.internal/v1"),
"the userinfo is replaced, not the URL: {t}"
);
assert!(
t.contains("access_token=<redacted>&page=2"),
"the secret parameter keeps its name and loses its value: {t}"
);
assert!(t.contains("https://mirror.internal/api#frag"), "{t}");
let debug = format!("{c:?}");
assert!(!debug.contains("hunter2"), "{debug}");
let plain = Config::default();
assert!(plain
.to_toml_redacted()
.unwrap()
.contains(&plain.provider.base_url));
}
#[test]
fn one_root_layout() {
let env = env_of(&[("HOME", "/home/u")]);
assert_eq!(
config_path(&env).unwrap(),
PathBuf::from("/home/u/.eclipse/config.toml")
);
assert_eq!(
Config::default().sessions_dir(&env).unwrap(),
PathBuf::from("/home/u/.eclipse/state/sessions")
);
assert_eq!(
Config::default().memory_dir(&env).unwrap(),
PathBuf::from("/home/u/.eclipse/memory")
);
let env = env_of(&[
("HOME", "/home/u"),
("XDG_CONFIG_HOME", "/x/cfg"),
("XDG_STATE_HOME", "/x/state"),
]);
assert_eq!(
config_path(&env).unwrap(),
PathBuf::from("/home/u/.eclipse/config.toml")
);
let env = env_of(&[("HOME", "/home/u"), ("ECLIPSE_HOME", "/opt/ecl")]);
assert_eq!(
config_path(&env).unwrap(),
PathBuf::from("/opt/ecl/config.toml")
);
}
#[test]
fn missing_default_file_is_ok_but_explicit_missing_is_error() {
let dir = tempfile::tempdir().unwrap();
let env = env_of(&[("HOME", dir.path().to_str().unwrap())]);
assert!(Config::load_with(None, &env).is_ok());
assert!(Config::load_with(Some(&dir.path().join("nope.toml")), &env).is_err());
}
#[test]
fn auto_prune_is_off_by_default_and_can_be_enabled() {
assert!(!Config::default().sessions.auto_prune);
let c = Config::from_toml_str("[sessions]\nauto_prune = true\nretention_keep_count = 5\n")
.unwrap();
assert!(c.sessions.auto_prune);
assert_eq!(c.sessions.retention_keep_count, 5);
}
#[test]
fn sessions_dir_expands_tilde() {
let env = env_of(&[("HOME", "/home/u")]);
let mut c = Config::default();
c.sessions.dir = Some("~/s".into());
assert_eq!(c.sessions_dir(&env).unwrap(), PathBuf::from("/home/u/s"));
}
#[test]
fn config_init_writes_a_private_dotenv_and_the_config_refers_to_it() {
let dir = tempfile::tempdir().unwrap();
let p = dir.path().join("a/b/config.toml");
let env = env_of(&[("ECLIPSE_HOME", dir.path().to_str().unwrap())]);
let report = write_starter_config(&p, false, &env).unwrap();
assert!(report.dotenv_written);
assert_eq!(
report.dotenv,
dir.path().join(".env"),
"the .env goes where the loader reads it, not beside a config elsewhere"
);
let dotenv = std::fs::read_to_string(&report.dotenv).unwrap();
let token = dotenv
.lines()
.find_map(|l| l.strip_prefix("ECLIPSE_WEB_AUTH_TOKEN="))
.expect("the token lives in .env");
assert_eq!(token.len(), 64, "a generated token, not a placeholder");
assert!(token.bytes().all(|b| b.is_ascii_hexdigit()));
assert!(
!std::fs::read_to_string(&p).unwrap().contains(token),
"the config carries the reference, never the secret"
);
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
for f in [&p, &report.dotenv] {
assert_eq!(f.metadata().unwrap().permissions().mode() & 0o777, 0o600);
}
}
let root = dir.path().join("root");
let cfg_dir = root.clone();
std::fs::create_dir_all(&cfg_dir).unwrap();
let real = cfg_dir.join("config.toml");
let env = env_of(&[
("ECLIPSE_HOME", root.to_str().unwrap()),
("HOME", dir.path().to_str().unwrap()),
]);
let written = write_starter_config(&real, false, &env).unwrap();
let cfg = Config::load_with_profile(Some(&real), None, &env).unwrap();
let token = std::fs::read_to_string(&written.dotenv)
.unwrap()
.lines()
.find_map(|l| {
l.strip_prefix("ECLIPSE_WEB_AUTH_TOKEN=")
.map(str::to_string)
})
.unwrap();
assert_eq!(cfg.web.auth_token.as_deref(), Some(token.as_str()));
assert_eq!(cfg.dotenv.files, vec![written.dotenv]);
}
#[test]
fn an_empty_dotenv_value_is_absent_not_an_empty_override() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("root");
std::fs::create_dir_all(&root).unwrap();
std::fs::write(
root.join(".env"),
"ECLIPSE_API_KEY=\nECLIPSE_MODEL=\nECLIPSE_BASE_URL=\n",
)
.unwrap();
let cfg_path = root.join("config.toml");
std::fs::write(
&cfg_path,
"[provider]\napi_key = \"sk-from-the-file\"\nmodel = \"keep-me\"\n\
base_url = \"http://127.0.0.1:9999/v1\"\n",
)
.unwrap();
let env = env_of(&[
("ECLIPSE_HOME", root.to_str().unwrap()),
("HOME", dir.path().to_str().unwrap()),
]);
let cfg = Config::load_with_profile(Some(&cfg_path), None, &env).unwrap();
assert_eq!(
cfg.provider.api_key.as_deref(),
Some("sk-from-the-file"),
"an empty .env value must not blank the key"
);
assert_eq!(cfg.provider.model, "keep-me", "nor the model");
assert_eq!(
cfg.provider.base_url, "http://127.0.0.1:9999/v1",
"nor the base URL"
);
}
#[test]
fn context_files_are_seeded_and_existing_ones_are_kept() {
let tmp = tempfile::tempdir().unwrap();
let memory = tmp.path().join("memory");
let created = seed_context_files(&memory).unwrap();
assert_eq!(created.len(), 3, "AGENT, USER, MEMORY: {created:?}");
assert!(memory.join("AGENT.md").exists());
assert!(memory.join("USER.md").exists());
assert!(memory.join("MEMORY.md").exists());
assert_eq!(
std::fs::read_to_string(memory.join("MEMORY.md")).unwrap(),
""
);
let created = seed_context_files(&memory).unwrap();
assert!(
created.is_empty(),
"existing files are left alone: {created:?}"
);
let written = [
("AGENT.md", "run make, no cargo test\n"),
("USER.md", "I am the operator; keep it short\n"),
("MEMORY.md", "- one durable fact\n"),
];
for (name, body) in written {
std::fs::write(memory.join(name), body).unwrap();
}
let created = seed_context_files(&memory).unwrap();
assert!(created.is_empty(), "{created:?}");
for (name, body) in written {
assert_eq!(
std::fs::read_to_string(memory.join(name)).unwrap(),
body,
"{name} was rewritten"
);
}
}
#[test]
fn a_new_profile_is_a_first_install_and_an_existing_one_is_never_rewritten() {
let tmp = tempfile::tempdir().unwrap();
let base = tmp.path().join("memory");
let lived_in = tmp.path().join("profiles/work/memory");
let fresh = tmp.path().join("profiles/lab/memory");
assert_eq!(seed_context_files(&base).unwrap().len(), 3);
std::fs::write(base.join("USER.md"), "the operator\n").unwrap();
std::fs::create_dir_all(&lived_in).unwrap();
for name in ["AGENT.md", "USER.md", "MEMORY.md"] {
std::fs::write(lived_in.join(name), format!("{name} as it was lived in\n")).unwrap();
}
assert!(
seed_context_files(&lived_in).unwrap().is_empty(),
"an existing profile's files are not rewritten"
);
assert_eq!(
seed_context_files(&fresh).unwrap().len(),
3,
"a profile that has never been used is a first install"
);
assert_eq!(
std::fs::read_to_string(base.join("USER.md")).unwrap(),
"the operator\n"
);
for name in ["AGENT.md", "USER.md", "MEMORY.md"] {
assert_eq!(
std::fs::read_to_string(lived_in.join(name)).unwrap(),
format!("{name} as it was lived in\n")
);
}
}
#[test]
fn config_init_puts_the_dotenv_where_a_start_with_that_config_will_read_it() {
let dir = tempfile::tempdir().unwrap();
let home = dir.path().join("home");
std::fs::create_dir_all(&home).unwrap();
let elsewhere = dir.path().join("other");
let path = elsewhere.join("config.toml");
let env = env_of(&[
("ECLIPSE_HOME", home.to_str().unwrap()),
("HOME", dir.path().to_str().unwrap()),
]);
let report = write_starter_config(&path, false, &env).unwrap();
let token = std::fs::read_to_string(&report.dotenv)
.unwrap()
.lines()
.find_map(|l| l.strip_prefix("ECLIPSE_WEB_AUTH_TOKEN="))
.expect("the token lives in .env")
.to_string();
assert_eq!(report.dotenv, home.join(".env"));
let cfg = Config::load_with_profile(Some(&path), None, &env).unwrap();
assert_eq!(
cfg.web.auth_token.as_deref(),
Some(token.as_str()),
"the token `config init` reported is the token the next start reads"
);
}
#[test]
fn config_init_refuses_to_overwrite_a_config_without_force() {
let dir = tempfile::tempdir().unwrap();
let p = dir.path().join("c/config.toml");
let env = env_of(&[("ECLIPSE_HOME", dir.path().to_str().unwrap())]);
write_starter_config(&p, false, &env).unwrap();
assert!(write_starter_config(&p, false, &env).is_err());
}
#[test]
fn config_init_never_overwrites_an_existing_dotenv() {
let dir = tempfile::tempdir().unwrap();
let p = dir.path().join("d/config.toml");
let env = env_of(&[("ECLIPSE_HOME", dir.path().to_str().unwrap())]);
let first = write_starter_config(&p, false, &env).unwrap();
let before = std::fs::read_to_string(&first.dotenv).unwrap();
let again = write_starter_config(&p, true, &env).unwrap();
assert!(!again.dotenv_written);
assert_eq!(std::fs::read_to_string(&again.dotenv).unwrap(), before);
}
#[test]
fn a_profile_overlay_merges_over_the_base_config() {
let tmp = tempfile::tempdir().unwrap();
let home = tmp.path().join("home");
let cfg_dir = home.join(".eclipse");
std::fs::create_dir_all(cfg_dir.join("profiles/work")).unwrap();
std::fs::write(
cfg_dir.join("config.toml"),
"[provider]\nbase_url = \"http://base/v1\"\nmodel = \"base-model\"\n\
temperature = 0.2\n[agent]\nmax_iterations = 7\n",
)
.unwrap();
std::fs::write(
cfg_dir.join("profiles/work/config.toml"),
"[provider]\nmodel = \"work-model\"\n",
)
.unwrap();
let env = env_of(&[("HOME", home.to_str().unwrap())]);
let base = Config::load_with(None, &env).unwrap();
assert_eq!(base.provider.model, "base-model");
assert_eq!(base.profile_name(), "default");
let work = Config::load_with_profile(None, Some("work"), &env).unwrap();
assert_eq!(work.provider.model, "work-model");
assert_eq!(work.provider.base_url, "http://base/v1");
assert_eq!(work.provider.temperature, Some(0.2));
assert_eq!(work.agent.max_iterations, 7);
assert_eq!(work.profile_name(), "work");
assert_eq!(
work.sessions_dir(&env).unwrap(),
home.join(".eclipse/profiles/work/state/sessions")
);
assert_eq!(
base.sessions_dir(&env).unwrap(),
home.join(".eclipse/state/sessions")
);
assert_eq!(
work.state_dir(&env).unwrap(),
home.join(".eclipse/profiles/work/state")
);
}
#[test]
fn the_profile_comes_from_the_environment_and_the_argument_wins() {
let tmp = tempfile::tempdir().unwrap();
let home = tmp.path().join("home");
std::fs::create_dir_all(home.join(".eclipse/profiles/env")).unwrap();
std::fs::write(
home.join(".eclipse/profiles/env/config.toml"),
"[agent]\nmax_iterations = 3\n",
)
.unwrap();
let env = env_of(&[("HOME", home.to_str().unwrap()), ("ECLIPSE_PROFILE", "env")]);
let from_env = Config::load_with(None, &env).unwrap();
assert_eq!(from_env.profile_name(), "env");
assert_eq!(from_env.agent.max_iterations, 3);
let explicit = Config::load_with_profile(None, Some("other"), &env).unwrap();
assert_eq!(explicit.profile_name(), "other");
assert_eq!(explicit.agent.max_iterations, usize::MAX);
}
#[test]
fn the_default_profile_keeps_the_plain_state_directory() {
let env = env_of(&[("HOME", "/home/u")]);
assert_eq!(
state_dir_for(&env, Some("default")).unwrap(),
PathBuf::from("/home/u/.eclipse/state")
);
assert_eq!(
state_dir_for(&env, None).unwrap(),
PathBuf::from("/home/u/.eclipse/state")
);
assert_eq!(
state_dir_for(&env, Some("work")).unwrap(),
PathBuf::from("/home/u/.eclipse/profiles/work/state")
);
}
#[test]
fn a_profile_name_must_be_a_safe_directory_name() {
for bad in ["", "../etc", "a/b", "sp ace"] {
assert!(
validate_profile_name(bad).is_err(),
"{bad:?} should be rejected"
);
}
assert!(validate_profile_name("work-2026_x").is_ok());
let env = env_of(&[("HOME", "/home/u")]);
assert!(Config::load_with_profile(None, Some("../evil"), &env).is_err());
}
#[test]
fn plugin_directories_put_the_profile_first() {
let tmp = tempfile::tempdir().unwrap();
let home = tmp.path().join("home");
std::fs::create_dir_all(home.join(".eclipse")).unwrap();
let env = env_of(&[("HOME", home.to_str().unwrap())]);
let mut cfg = Config::default();
let default_dirs = cfg.plugins_dirs(&env);
assert_eq!(
default_dirs,
vec![home.join(".eclipse/plugins")],
"the default profile has no profile plugin dir"
);
cfg.profile = Some("work".into());
let dirs = cfg.plugins_dirs(&env);
assert_eq!(dirs.len(), 2);
assert_eq!(dirs[0], home.join(".eclipse/profiles/work/plugins"));
assert_eq!(dirs[1], home.join(".eclipse/plugins"));
cfg.plugins.dir = Some("~/elsewhere/plugins".into());
assert_eq!(cfg.plugins_dirs(&env)[1], home.join("elsewhere/plugins"));
}
#[test]
fn plugins_are_off_until_named() {
let cfg = Config::default();
assert!(cfg.plugins.enabled.is_empty());
assert!(cfg.plugins.dir.is_none());
let parsed = Config::from_toml_str("[plugins]\nenabled = [\"a\", \"b\"]\n").unwrap();
assert_eq!(parsed.plugins.enabled, ["a", "b"]);
}
#[test]
fn setting_a_key_fills_the_empty_value_and_keeps_every_other_line() {
let text = toml_set_string(&starter(), "provider", "base_url", "http://h:1/v1");
let text = toml_set_string(&text, "provider", "model", "some-model");
assert!(text.contains("base_url = \"http://h:1/v1\""), "{text}");
assert!(text.contains("model = \"some-model\""), "{text}");
assert!(text.contains("# Every setting this build reads"));
assert!(text.contains("[agent]"));
assert!(
!text.contains("base_url = \"\""),
"the empty blank must be gone: {text}"
);
let cfg: Config = toml::from_str(&text).expect("edited config must parse");
assert_eq!(cfg.provider.base_url, "http://h:1/v1");
assert_eq!(cfg.provider.model, "some-model");
}
#[test]
fn setting_a_key_turns_a_commented_template_line_into_the_real_one() {
let text = toml_set_string(&starter(), "provider", "profile", "llamacpp");
assert!(text.contains("\nprofile = \"llamacpp\""), "{text}");
assert_eq!(
text.matches("\nprofile = ").count(),
1,
"no duplicate key (the commented [web] default_profile is a different key): {text}"
);
let cfg: Config = toml::from_str(&text).unwrap();
assert_eq!(cfg.provider.profile.as_deref(), Some("llamacpp"));
}
#[test]
fn setting_a_key_does_not_reach_into_another_section_with_the_same_name() {
let text = toml_set_string(&starter(), "sessions", "dir", "/tmp/sessions-here");
let cfg: Config = toml::from_str(&text).unwrap();
assert_eq!(
cfg.sessions.dir.as_deref(),
Some(std::path::Path::new("/tmp/sessions-here"))
);
assert_eq!(cfg.plugins.dir, None, "{text}");
}
#[test]
fn setting_a_key_in_a_missing_section_adds_the_section() {
let text = toml_set_string("[agent]\nmax_iterations = 5\n", "web", "host", "0.0.0.0");
let cfg: Config = toml::from_str(&text).unwrap();
assert_eq!(cfg.web.host, "0.0.0.0");
assert_eq!(cfg.agent.max_iterations, 5);
}
#[test]
fn reading_a_key_sees_the_live_line_and_not_the_commented_one() {
let text = starter();
assert_eq!(
toml_value(&text, "provider", "base_url"),
Some(String::new())
);
assert_eq!(toml_value(&text, "provider", "temperature"), None);
assert!(text.contains("# temperature ="), "{text}");
assert_eq!(
toml_value(&text, "agent", "max_iterations"),
Some("unlimited".to_string()),
"the cap is written, and its off value is the word `unlimited`"
);
}
#[test]
fn a_dotenv_that_cannot_be_read_is_not_treated_as_an_empty_one() {
let dir = tempfile::tempdir().unwrap();
let dotenv = dir.path().join(".env");
std::fs::create_dir(&dotenv).unwrap();
std::fs::write(dotenv.join("ECLIPSE_WEB_AUTH_TOKEN"), "still here").unwrap();
let err = save_dotenv_var(&dotenv, "ECLIPSE_API_KEY", "sk-1").unwrap_err();
let said = err.to_string();
assert!(
said.contains("nothing was written"),
"the refusal says the file is untouched: {said}"
);
assert!(
dotenv.is_dir(),
"a failed save must not have replaced the path"
);
assert_eq!(
std::fs::read_to_string(dotenv.join("ECLIPSE_WEB_AUTH_TOKEN")).unwrap(),
"still here",
"and nothing under it was touched"
);
}
#[test]
fn a_line_break_in_a_value_is_refused_before_it_writes() {
let dir = tempfile::tempdir().unwrap();
let dotenv = dir.path().join(".env");
std::fs::write(&dotenv, "ECLIPSE_WEB_AUTH_TOKEN=tok\n").unwrap();
let err = save_dotenv_var(&dotenv, "ECLIPSE_API_KEY", "sk-1\nECLIPSE_ADMIN=1").unwrap_err();
assert!(err.to_string().contains("second assignment"), "{err}");
assert_eq!(
std::fs::read_to_string(&dotenv).unwrap(),
"ECLIPSE_WEB_AUTH_TOKEN=tok\n",
"a refused save leaves the file byte for byte"
);
}
#[test]
fn a_save_keeps_every_other_line_and_the_loader_still_reads_them() {
let dir = tempfile::tempdir().unwrap();
let dotenv = dir.path().join(".env");
let before = "# secrets\n\
export ECLIPSE_WEB_USER='max h'\n\
ECLIPSE_WEB_PASSWORD_HASH=\"pbkdf2$abc\"\n\
ECLIPSE_API_KEY=first\n\
ECLIPSE_API_KEY=second\n";
std::fs::write(&dotenv, before).unwrap();
save_dotenv_var(&dotenv, "ECLIPSE_WEB_AUTH_TOKEN", "tok").unwrap();
let after = std::fs::read_to_string(&dotenv).unwrap();
for line in before.lines() {
assert!(after.contains(line), "{line:?} did not survive:\n{after}");
}
assert!(after.contains("ECLIPSE_WEB_AUTH_TOKEN=tok"), "{after}");
}
#[test]
fn dotenv_var_answers_what_the_loader_answers() {
let dir = tempfile::tempdir().unwrap();
let dotenv = dir.path().join(".env");
std::fs::write(
&dotenv,
"A=first\nA=second\nexport B='quoted value'\nC=\"also quoted\"\nD=\n",
)
.unwrap();
assert_eq!(
dotenv_var(&dotenv, "A").as_deref(),
Some("second"),
"the loader is last-wins, so the reader is too"
);
assert_eq!(dotenv_var(&dotenv, "B").as_deref(), Some("quoted value"));
assert_eq!(dotenv_var(&dotenv, "C").as_deref(), Some("also quoted"));
assert_eq!(
dotenv_var(&dotenv, "D"),
None,
"an empty value is absence, as everywhere else"
);
assert_eq!(dotenv_var(&dotenv, "MISSING"), None);
}
#[test]
fn a_config_written_by_setup_is_private_and_a_dotenv_keeps_its_other_lines() {
let dir = tempfile::tempdir().unwrap();
let cfg_path = dir.path().join("config.toml");
let dotenv = dir.path().join(".env");
save_config_text(&cfg_path, "[provider]\nbase_url = \"h\"\n").unwrap();
save_dotenv_var(&dotenv, "ECLIPSE_WEB_AUTH_TOKEN", "tok").unwrap();
save_dotenv_var(&dotenv, "ECLIPSE_API_KEY", "sk-1").unwrap();
save_dotenv_var(&dotenv, "ECLIPSE_API_KEY", "sk-2").unwrap();
let body = std::fs::read_to_string(&dotenv).unwrap();
assert_eq!(body.matches("ECLIPSE_API_KEY").count(), 1, "{body}");
assert_eq!(
dotenv_var(&dotenv, "ECLIPSE_API_KEY").as_deref(),
Some("sk-2")
);
assert_eq!(
dotenv_var(&dotenv, "ECLIPSE_WEB_AUTH_TOKEN").as_deref(),
Some("tok"),
"an unrelated secret must survive"
);
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
for f in [&cfg_path, &dotenv] {
let mode = std::fs::metadata(f).unwrap().permissions().mode() & 0o777;
assert_eq!(mode, 0o600, "{}", f.display());
}
}
}
#[test]
fn trace_content_is_off_by_default_and_can_be_set() {
assert!(!Config::default().agent.trace_content);
let cfg = Config::from_toml_str(
"[agent]
trace_content = true
",
)
.unwrap();
assert!(cfg.agent.trace_content);
}
#[test]
fn an_output_schema_is_absent_until_somebody_asks_for_one() {
assert_eq!(Config::default().agent.output_schema, None);
let cfg = Config::from_toml_str(
"[agent]
output_schema = \"schemas/plan.json\"
",
)
.unwrap();
assert_eq!(
cfg.agent.output_schema.as_deref(),
Some("schemas/plan.json")
);
}
#[test]
fn the_user_section_has_the_defaults_the_docs_promise() {
let cfg = Config::default();
assert_eq!(cfg.user.file, "USER.md");
assert_eq!(cfg.user.memory_file, "MEMORY.md");
assert_eq!(cfg.user.memory_budget_chars, 3000);
assert_eq!(
cfg.agent.context_file_max_chars,
crate::context_files::DEFAULT_MAX_FILE_CHARS
);
assert_eq!(
cfg.agent.context_files_budget_chars,
crate::context_files::DEFAULT_BUDGET_CHARS
);
}
#[test]
fn the_context_and_memory_budgets_can_be_set_in_the_file() {
let cfg = Config::from_toml_str(
"[agent]\ncontext_file_max_chars = 100\ncontext_files_budget_chars = 200\n\
[user]\nfile = \"WHO.md\"\nmemory_file = \"FACTS.md\"\nmemory_budget_chars = 50\n",
)
.unwrap();
assert_eq!(cfg.agent.context_file_max_chars, 100);
assert_eq!(cfg.agent.context_files_budget_chars, 200);
assert_eq!(cfg.user.file, "WHO.md");
assert_eq!(cfg.user.memory_file, "FACTS.md");
assert_eq!(cfg.user.memory_budget_chars, 50);
}
#[test]
fn the_default_profile_keeps_its_files_in_the_config_directory() {
let env = |k: &str| match k {
"HOME" => Some("/home/m".to_string()),
_ => None,
};
let mut cfg = Config::default();
assert_eq!(
cfg.context_dir(&env),
Some(PathBuf::from("/home/m/.eclipse"))
);
cfg.profile = Some("work".into());
assert_eq!(
cfg.context_dir(&env),
Some(PathBuf::from("/home/m/.eclipse/profiles/work"))
);
}
#[test]
fn scripts_live_under_the_profile_when_there_is_one_and_the_config_directory_otherwise() {
let env = |k: &str| match k {
"HOME" => Some("/home/m".to_string()),
_ => None,
};
let mut cfg = Config::default();
assert_eq!(
cfg.scripts_dir(&env),
Some(PathBuf::from("/home/m/.eclipse/scripts"))
);
cfg.profile = Some("work".into());
assert_eq!(
cfg.scripts_dir(&env),
Some(PathBuf::from("/home/m/.eclipse/profiles/work/scripts"))
);
let no_home = |_: &str| None;
assert_eq!(Config::default().scripts_dir(&no_home), None);
}
#[test]
fn a_relative_config_path_still_gives_an_absolute_scripts_directory() {
let env = |k: &str| match k {
"ECLIPSE_CONFIG" => Some("rel/config.toml".to_string()),
_ => None,
};
let dir = Config::default().scripts_dir(&env).unwrap();
assert!(dir.is_absolute(), "{}", dir.display());
assert!(dir.ends_with("rel/scripts"), "{}", dir.display());
}
#[test]
fn the_script_tool_is_asked_about_by_default_and_the_policy_can_be_set_in_the_file() {
assert_eq!(Config::default().tools.script, Policy::Ask);
let cfg = Config::from_toml_str("[tools]\nscript = \"deny\"\n").unwrap();
assert_eq!(cfg.tools.script, Policy::Deny);
let starter = Config::from_toml_str(&super::tests::starter()).unwrap();
assert_eq!(starter.tools.script, Policy::Ask);
assert!(Config::from_toml_str("[tools]\nscript = \"yolo\"\n").is_err());
}
#[test]
fn sight_defaults_to_auto_with_no_route_and_no_cloud() {
let cfg = Config::default();
assert_eq!(cfg.vision.mode, VisionMode::Auto);
assert_eq!(cfg.vision.route, "");
assert!(!cfg.vision.allow_cloud);
}
#[test]
fn the_three_vision_modes_are_spelled_in_the_file_the_way_a_person_says_them() {
for (text, mode) in [
("native", VisionMode::Native),
("text", VisionMode::Text),
("auto", VisionMode::Auto),
] {
let cfg = Config::from_toml_str(&format!("[vision]\nmode = \"{text}\"\n")).unwrap();
assert_eq!(cfg.vision.mode, mode, "{text}");
}
}
#[test]
fn a_vision_mode_nobody_implements_is_a_load_error_that_lists_the_three() {
let err = Config::from_toml_str("[vision]\nmode = \"telepathy\"\n").unwrap_err();
let sentence = err.to_string();
assert!(sentence.contains("telepathy"), "{sentence}");
assert!(sentence.contains("native"), "{sentence}");
assert!(sentence.contains("text"), "{sentence}");
assert!(sentence.contains("auto"), "{sentence}");
}
#[test]
fn a_vision_route_that_is_not_a_route_is_refused_by_name() {
let cfg = Config::from_toml_str(
"[provider]\nbase_url = \"http://127.0.0.1:1/v1\"\nmodel = \"m\"\n\
[vision]\nroute = \"sight\"\n",
)
.unwrap();
let err = cfg.validate_routes().unwrap_err().to_string();
assert!(err.contains("vision.route"), "{err}");
assert!(err.contains("sight"), "{err}");
assert!(err.contains("default"), "{err}");
}
#[test]
fn a_vision_route_that_exists_validates() {
let cfg = Config::from_toml_str(
"[provider]\nbase_url = \"http://127.0.0.1:1/v1\"\nmodel = \"m\"\n\
[vision]\nroute = \"default\"\n",
)
.unwrap();
cfg.validate_routes().unwrap();
assert_eq!(cfg.vision.route, "default");
}
#[test]
fn the_skills_budget_has_its_documented_default_and_can_be_set_in_the_file() {
assert_eq!(Config::default().skills.index_budget_chars, 4000);
let cfg = Config::from_toml_str("[skills]\nindex_budget_chars = 250\n").unwrap();
assert_eq!(cfg.skills.index_budget_chars, 250);
assert!(starter().contains("[skills]"));
let starter = Config::from_toml_str(&super::tests::starter()).unwrap();
assert_eq!(starter.skills.index_budget_chars, 4000);
}
#[test]
fn the_redacted_config_shows_the_skills_section() {
let mut cfg = Config::default();
cfg.skills.index_budget_chars = 123;
let shown = cfg.to_toml_redacted().unwrap();
assert!(shown.contains("[skills]"), "{shown}");
assert!(shown.contains("index_budget_chars = 123"), "{shown}");
}
#[test]
fn the_starter_writes_the_context_file_settings() {
let text = starter();
let cfg = Config::from_toml_str(&text).unwrap();
assert_eq!(cfg.user.memory_file, "MEMORY.md");
for key in ["context_files_budget_chars", "[user]", "USER.md"] {
assert!(text.contains(key), "the shipped file names `{key}`");
}
}
const TWO_ROUTES: &str = "\
[provider]
fallback = [\"local\", \"big\"]
[[provider.route]]
name = \"local\"
base_url = \"http://127.0.0.1:8081/v1\"
model = \"small\"
[[provider.route]]
name = \"big\"
base_url = \"http://10.0.0.2:8000/v1\"
model = \"large\"
api_key = \"hunter2\"
timeout_secs = 30
";
fn parse(text: &str) -> Config {
Config::from_toml_str(text).unwrap()
}
fn refusal(text: &str) -> String {
let c = parse(text);
c.validate_routes()
.and_then(|_| c.chain().map(|_| ()))
.unwrap_err()
.to_string()
}
#[test]
fn a_route_is_a_full_provider_config_and_inherits_nothing_from_provider() {
let c = parse(
"[provider]\nbase_url=\"http://d/v1\"\nmodel=\"dm\"\ntimeout_secs=7\n\
[[provider.route]]\nname=\"r\"\nbase_url=\"http://r/v1\"\nmodel=\"rm\"\n",
);
let r = c.declared_routes();
assert_eq!(
r.iter().map(|r| r.name.as_str()).collect::<Vec<_>>(),
["default", "r"],
"[provider] is the route called default"
);
assert_eq!(r[0].config.timeout_secs, 7);
assert_eq!(
r[1].config.timeout_secs, 120,
"the route got the built-in default, not [provider]'s 7"
);
}
#[test]
fn provider_may_be_omitted_when_fallback_names_a_route() {
let c = parse(TWO_ROUTES);
c.validate_routes().unwrap();
let chain = c.chain().unwrap();
assert_eq!(chain.source, ChainSource::Fallback);
let names: Vec<_> = chain.routes.iter().map(|r| r.name.as_str()).collect();
assert_eq!(names, ["local", "big"]);
assert_eq!(chain.routes[1].config.timeout_secs, 30);
assert!(
c.declared_routes().iter().all(|r| r.name != "default"),
"no phantom default route appears"
);
}
#[test]
fn a_provider_endpoint_left_out_of_the_chain_is_refused_not_ignored() {
let text = r#"
[provider]
base_url = "https://api.example.com/v1"
model = "gpt"
fallback = ["local"]
[[provider.route]]
name = "local"
base_url = "http://127.0.0.1:8080/v1"
model = "qwen3-coder"
"#;
let err = parse(text).validate_routes().unwrap_err().to_string();
assert!(err.contains("would never be called"), "{err}");
assert!(
err.contains("Put `default` first"),
"it says what to type: {err}"
);
}
#[test]
fn listing_default_first_puts_the_provider_endpoint_back_in_front() {
let text = r#"
[provider]
base_url = "https://api.example.com/v1"
model = "gpt"
fallback = ["default", "local"]
[[provider.route]]
name = "local"
base_url = "http://127.0.0.1:8080/v1"
model = "qwen3-coder"
"#;
let c = parse(text);
c.validate_routes().unwrap();
let chain = c.chain().unwrap();
let names: Vec<_> = chain.routes.iter().map(|r| r.name.as_str()).collect();
assert_eq!(names, ["default", "local"]);
assert_eq!(chain.routes[0].config.model, "gpt");
}
#[test]
fn a_provider_block_of_tuning_keys_alone_does_not_become_a_route() {
let text = "\
[provider]
max_retries = 0
fallback = [\"local\", \"big\"]
[[provider.route]]
name = \"local\"
base_url = \"http://127.0.0.1:8081/v1\"
model = \"small\"
[[provider.route]]
name = \"big\"
base_url = \"http://127.0.0.1:8082/v1\"
model = \"large\"
";
let c = parse(text);
c.validate_routes().unwrap();
let names: Vec<String> = c.declared_routes().into_iter().map(|r| r.name).collect();
assert_eq!(names, ["local", "big"], "no phantom default route");
let mut pinned = parse(text);
let e = pinned.pin_route(Some("default"), &|_| None).unwrap_err();
let e = e.to_string();
assert!(
e.contains("unknown route `default`") && e.contains("local, big"),
"{e}"
);
assert!(!e.contains("provider.base_url"), "{e}");
}
#[test]
fn two_routes_with_the_same_name_are_refused_naming_it() {
let e = refusal(
"[[provider.route]]\nname=\"a\"\nbase_url=\"u\"\nmodel=\"m\"\n\
[[provider.route]]\nname=\"a\"\nbase_url=\"u\"\nmodel=\"m\"\n",
);
assert!(e.contains("`a`") && e.contains("unique"), "{e}");
}
#[test]
fn a_route_with_an_empty_or_missing_name_is_refused_by_position() {
let e = refusal("[[provider.route]]\nname=\" \"\nbase_url=\"u\"\nmodel=\"m\"\n");
assert!(
e.contains("provider.route #1") && e.contains("no name"),
"{e}"
);
let e = refusal("[[provider.route]]\nbase_url=\"u\"\nmodel=\"m\"\n");
assert!(e.contains("provider.route #1"), "{e}");
}
#[test]
fn a_route_named_default_is_refused_only_when_provider_is_also_set() {
let route = "[[provider.route]]\nname=\"default\"\nbase_url=\"u\"\nmodel=\"m\"\n";
let e = refusal(&format!("[provider]\nbase_url=\"x\"\nmodel=\"y\"\n{route}"));
assert!(e.contains("`default`") && e.contains("[provider]"), "{e}");
let c = parse(&format!("[provider]\nfallback=[\"default\"]\n{route}"));
assert_eq!(c.chain().unwrap().routes[0].name, "default");
}
#[test]
fn a_route_without_base_url_or_model_is_refused_naming_the_route() {
let e = refusal("[[provider.route]]\nname=\"nourl\"\nmodel=\"m\"\n");
assert!(e.contains("`nourl`") && e.contains("base_url"), "{e}");
let e = refusal("[[provider.route]]\nname=\"nomodel\"\nbase_url=\"u\"\n");
assert!(e.contains("`nomodel`") && e.contains("model"), "{e}");
}
#[test]
fn a_route_does_not_inherit_a_missing_base_url_from_provider() {
let e = refusal(
"[provider]\nbase_url=\"http://d/v1\"\nmodel=\"dm\"\n\
[[provider.route]]\nname=\"r\"\nmodel=\"m\"\n",
);
assert!(e.contains("`r`") && e.contains("does not inherit"), "{e}");
}
#[test]
fn fallback_naming_a_route_that_does_not_exist_lists_the_ones_that_do() {
let e = refusal(&TWO_ROUTES.replace("\"big\"]", "\"cloud\"]"));
assert!(e.contains("`cloud`"), "{e}");
assert!(e.contains("local, big"), "{e}");
}
#[test]
fn an_empty_fallback_is_a_typo_not_a_policy() {
let e = refusal("[provider]\nfallback = []\n");
assert!(e.contains("provider.fallback is empty"), "{e}");
}
#[test]
fn a_fallback_that_lists_a_route_twice_is_refused() {
let e = refusal(&TWO_ROUTES.replace("[\"local\", \"big\"]", "[\"local\", \"local\"]"));
assert!(e.contains("`local` twice"), "{e}");
}
#[test]
fn a_fallback_or_route_table_inside_a_route_is_refused() {
let e = refusal(
"[[provider.route]]\nname=\"r\"\nbase_url=\"u\"\nmodel=\"m\"\nfallback=[\"r\"]\n",
);
assert!(e.contains("`r`") && e.contains("directly"), "{e}");
}
const WITH_AUX: &str = "\
[provider]
base_url = \"http://d/v1\"
model = \"dm\"
aux = \"cheap\"
[[provider.route]]
name = \"cheap\"
base_url = \"http://c/v1\"
model = \"cm\"
";
#[test]
fn aux_names_a_route_and_the_role_table_says_so() {
let chain = parse(WITH_AUX).chain().unwrap();
assert_eq!(chain.aux.as_ref().map(|r| r.name.as_str()), Some("cheap"));
assert_eq!(chain.aux.unwrap().config.model, "cm");
let roles = parse(WITH_AUX).chain().unwrap().roles();
assert_eq!(roles.len(), 2, "only roles that exist get a row");
assert_eq!(roles[0].to_string(), "judgement \u{2192} cheap");
assert_eq!(
roles[1].to_string(),
"delegate \u{2192} default (no delegate route set)"
);
}
#[test]
fn delegate_names_a_route_and_the_role_table_says_so() {
let c = parse(&WITH_AUX.replace("aux = \"cheap\"", "delegate = \"cheap\""));
let chain = c.chain().unwrap();
assert_eq!(
chain.delegate.as_ref().map(|r| r.name.as_str()),
Some("cheap")
);
assert!(chain.aux.is_none());
let roles = chain.roles();
assert_eq!(
roles[0].to_string(),
"judgement \u{2192} default (no aux route set)"
);
assert_eq!(roles[1].to_string(), "delegate \u{2192} cheap");
}
#[test]
fn a_pin_overrules_the_aux_and_delegate_routes_and_the_role_table_says_pinned() {
let mut c =
parse(&WITH_AUX.replace("aux = \"cheap\"", "aux = \"cheap\"\ndelegate = \"cheap\""));
c.pin_route(Some("cheap"), &|_| None).unwrap();
let chain = c.chain().unwrap();
assert_eq!(chain.source, ChainSource::Pinned);
assert_eq!(
chain.aux.as_ref().map(|r| r.name.as_str()),
Some("cheap"),
"the pinned route, not the key's own value"
);
assert_eq!(
chain.delegate.as_ref().map(|r| r.name.as_str()),
Some("cheap")
);
for role in chain.roles() {
assert!(role.pinned, "{role} should be pinned");
assert!(!role.set, "{role} should not claim the key decided it");
assert_eq!(role.route, "cheap");
assert!(role.to_string().ends_with("(pinned)"), "{role}");
}
let c =
parse(&WITH_AUX.replace("aux = \"cheap\"", "aux = \"cheap\"\ndelegate = \"cheap\""));
let chain = c.chain().unwrap();
assert!(chain.roles().iter().all(|r| r.set && !r.pinned));
}
#[test]
fn an_unknown_empty_or_nested_delegate_route_is_refused_with_the_routes_that_exist() {
let e = refusal(&WITH_AUX.replace("aux = \"cheap\"", "delegate = \"ghost\""));
assert!(
e.contains("provider.delegate names `ghost`") && e.contains("default, cheap"),
"{e}"
);
let c = parse(&WITH_AUX.replace("aux = \"cheap\"", "delegate = \"\""));
c.validate_routes()
.expect("an empty delegate is a config that loads");
let e = refusal(
"[[provider.route]]\nname=\"r\"\nbase_url=\"u\"\nmodel=\"m\"\ndelegate=\"r\"\n\
[provider]\nfallback=[\"r\"]\n",
);
assert!(
e.contains("`r`") && e.contains("`delegate`") && e.contains("directly"),
"{e}"
);
let e = Config::from_toml_str("[provider]\ndelegate = 3\n").unwrap_err();
assert!(e.contains("delegate"), "{e}");
}
#[test]
fn the_delegate_tool_is_asked_about_by_default_and_the_policy_can_be_set_in_the_file() {
assert_eq!(Config::default().tools.delegate, Policy::Ask);
let cfg = Config::from_toml_str("[tools]\ndelegate = \"deny\"\n").unwrap();
assert_eq!(cfg.tools.delegate, Policy::Deny);
let starter = Config::from_toml_str(&super::tests::starter()).unwrap();
assert_eq!(starter.tools.delegate, Policy::Ask);
assert!(Config::from_toml_str("[tools]\ndelegate = \"yolo\"\n").is_err());
}
#[test]
fn with_no_aux_the_summary_role_uses_the_selected_route_and_says_it_was_not_set() {
let chain = parse(TWO_ROUTES).chain().unwrap();
assert!(chain.aux.is_none());
assert_eq!(
chain.roles()[0].to_string(),
"judgement \u{2192} local (no aux route set)"
);
let bare = parse("[provider]\nbase_url=\"u\"\nmodel=\"m\"\n");
assert_eq!(
bare.chain().unwrap().roles()[0].to_string(),
"judgement \u{2192} default (no aux route set)"
);
}
#[test]
fn an_unknown_aux_route_is_refused_listing_the_routes_that_exist() {
let e = refusal(&WITH_AUX.replace("aux = \"cheap\"", "aux = \"ghost\""));
assert!(
e.contains("provider.aux names `ghost`") && e.contains("default, cheap"),
"{e}"
);
let c = parse(&WITH_AUX.replace("aux = \"cheap\"", "aux = \"\""));
c.validate_routes()
.expect("an empty aux route is a config that loads");
assert!(c.chain().unwrap().aux.is_none());
}
#[test]
fn aux_inside_a_route_is_refused_like_fallback_and_route() {
let e = refusal(
"[[provider.route]]\nname=\"r\"\nbase_url=\"u\"\nmodel=\"m\"\naux=\"r\"\n\
[provider]\nfallback=[\"r\"]\n",
);
assert!(
e.contains("`r`") && e.contains("`aux`") && e.contains("directly"),
"{e}"
);
}
#[test]
fn a_wrong_typed_aux_is_an_error_naming_the_key() {
let e = Config::from_toml_str("[provider]\naux = 3\n").unwrap_err();
assert!(e.contains("aux"), "{e}");
}
#[test]
fn aux_may_name_the_default_route_when_provider_is_one() {
let c = parse(&WITH_AUX.replace("aux = \"cheap\"", "aux = \"default\""));
assert_eq!(c.chain().unwrap().aux.unwrap().name, "default");
let tuning_only = "[provider]\naux = \"default\"\nmax_retries = 1\n\
[[provider.route]]\nname=\"r\"\nbase_url=\"u\"\nmodel=\"m\"\n";
assert!(refusal(tuning_only).contains("Routes that exist: r"));
}
#[test]
fn a_wrong_typed_route_value_is_an_error_and_not_a_default() {
let bad =
"[[provider.route]]\nname=\"r\"\nbase_url=\"u\"\nmodel=\"m\"\ntimeout_secs=\"soon\"\n";
let e = Config::from_toml_str(bad).unwrap_err();
assert!(e.contains("timeout_secs") || e.contains("soon"), "{e}");
let e = Config::from_toml_str("[provider]\nfallback = \"local\"\n").unwrap_err();
assert!(e.contains("fallback") || e.contains("sequence"), "{e}");
}
#[test]
fn routes_with_no_fallback_and_no_pin_say_what_to_set() {
let e = refusal("[[provider.route]]\nname=\"r\"\nbase_url=\"u\"\nmodel=\"m\"\n");
assert!(
e.contains("fallback") && e.contains("--route") && e.contains("r"),
"{e}"
);
}
#[test]
fn with_no_fallback_and_no_pin_the_chain_is_the_default_route_alone() {
let c = parse(
"[provider]\nbase_url=\"http://d/v1\"\nmodel=\"dm\"\n\
[[provider.route]]\nname=\"r\"\nbase_url=\"u\"\nmodel=\"m\"\n",
);
let chain = c.chain().unwrap();
assert_eq!(chain.source, ChainSource::Default);
assert_eq!(chain.routes.len(), 1);
assert_eq!(chain.routes[0].name, "default");
let bare = parse("[provider]\nbase_url=\"http://d/v1\"\nmodel=\"dm\"\n");
assert_eq!(bare.chain().unwrap().source, ChainSource::Default);
}
#[test]
fn a_bare_config_still_says_what_is_wrong_with_provider() {
let e = Config::default()
.require_provider()
.unwrap_err()
.to_string();
assert!(e.contains("provider.base_url is not set"), "{e}");
assert!(e.contains("eclipse config init"), "{e}");
let c = parse("[provider]\nbase_url=\"u\"\n");
assert!(c
.require_provider()
.unwrap_err()
.to_string()
.contains("provider.model is not set"));
}
#[test]
fn a_pin_selects_one_route_and_marks_the_chain_pinned() {
let mut c = parse(TWO_ROUTES);
c.pin_route(Some("big"), &env_of(&[])).unwrap();
let chain = c.chain().unwrap();
assert_eq!(chain.source, ChainSource::Pinned);
assert_eq!(chain.routes.len(), 1);
assert_eq!(chain.routes[0].name, "big");
}
#[test]
fn an_unknown_pin_lists_the_routes_that_exist() {
let mut c = parse(TWO_ROUTES);
let e = c
.pin_route(Some("nope"), &env_of(&[]))
.unwrap_err()
.to_string();
assert!(e.contains("`nope`") && e.contains("local, big"), "{e}");
let e = c
.pin_route(Some(" "), &env_of(&[]))
.unwrap_err()
.to_string();
assert!(e.contains("--route needs a route name"), "{e}");
}
#[test]
fn eclipse_route_is_honoured_when_the_flag_is_absent_and_the_flag_wins() {
let mut c = parse(TWO_ROUTES);
c.pin_route(None, &env_of(&[("ECLIPSE_ROUTE", "big")]))
.unwrap();
assert_eq!(c.route_pin.as_deref(), Some("big"));
c.pin_route(Some("local"), &env_of(&[("ECLIPSE_ROUTE", "big")]))
.unwrap();
assert_eq!(c.route_pin.as_deref(), Some("local"));
let mut c = parse(TWO_ROUTES);
c.dotenv
.values
.insert("ECLIPSE_ROUTE".into(), "local".into());
c.pin_route(None, &env_of(&[])).unwrap();
assert_eq!(
c.route_pin.as_deref(),
Some("local"),
"the .env chain counts too"
);
let mut c = parse(TWO_ROUTES);
c.pin_route(None, &env_of(&[])).unwrap();
assert_eq!(c.route_pin, None);
}
#[test]
fn a_route_takes_its_key_from_its_own_api_key_env_and_eclipse_api_key_is_default_only() {
let mut c = parse(
"[provider]\nbase_url=\"http://d/v1\"\nmodel=\"dm\"\n\
[[provider.route]]\nname=\"r\"\nbase_url=\"u\"\nmodel=\"m\"\napi_key_env=\"R_KEY\"\n",
);
c.apply_env(&env_of(&[
("R_KEY", "from-r"),
("ECLIPSE_API_KEY", "for-default"),
]));
assert_eq!(c.provider.api_key.as_deref(), Some("for-default"));
assert_eq!(
c.provider.route[0].config.api_key.as_deref(),
Some("from-r")
);
let mut only_routes = parse(TWO_ROUTES);
only_routes.apply_env(&env_of(&[("ECLIPSE_API_KEY", "stray")]));
assert_eq!(
only_routes.provider.api_key, None,
"no phantom default route"
);
assert_eq!(only_routes.provider.route[0].config.api_key, None);
}
#[test]
fn the_redacted_config_hides_every_routes_key_and_round_trips() {
let c = parse(TWO_ROUTES);
let t = c.to_toml_redacted().unwrap();
assert!(!t.contains("hunter2"), "{t}");
assert!(
t.contains("[[provider.route]]") && t.contains("<redacted>"),
"{t}"
);
let back = parse(&t);
assert_eq!(back.provider.fallback, c.provider.fallback);
assert_eq!(back.provider.route.len(), 2);
assert_eq!(back.provider.route[1].config.timeout_secs, 30);
}
#[test]
fn a_config_without_routes_prints_no_provider_route_keys() {
let c = parse("[provider]\nbase_url=\"u\"\nmodel=\"m\"\n");
let t = c.to_toml_redacted().unwrap();
let parsed: toml::Value = toml::from_str(&t).unwrap();
let provider = parsed.get("provider").expect("a provider table");
for absent in ["route", "fallback", "aux", "delegate"] {
assert!(
provider.get(absent).is_none(),
"`provider.{absent}` printed for a config with one route: {t}"
);
}
}
#[test]
fn a_bad_route_table_is_refused_when_the_config_is_loaded() {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("c.toml");
std::fs::write(&path, "[provider]\nfallback = [\"ghost\"]\n").unwrap();
let e = Config::load_with(Some(&path), &env_of(&[]))
.unwrap_err()
.to_string();
assert!(e.contains("`ghost`"), "{e}");
}
#[test]
fn context_policy_defaults_and_the_rail_it_derives() {
let c = ContextPolicyConfig::default();
assert!(
c.judge,
"the model half is the judgement pass, and it ships on: compile plus one bounded call"
);
assert_eq!(c.judge_timeout_secs, 20, "and it cannot hang the turn");
assert_eq!(c.compact_at, 0.85);
assert_eq!(c.protect_last_n, 20, "the tail keeps twenty turns");
assert_eq!(c.window_tokens, 0, "no window is invented");
assert_eq!(c.budget_for(0), 0, "no window, no rail");
assert_eq!(c.budget_for(327_680), 278_528);
let off = ContextPolicyConfig {
compact_at: 0.0,
..c.clone()
};
assert_eq!(off.budget_for(327_680), 0, "compact_at = 0 is off");
let half = ContextPolicyConfig {
compact_at: 0.5,
..c
};
assert_eq!(half.budget_for(131_072), 65_536);
}
#[test]
fn a_compact_at_outside_the_window_is_a_config_error_naming_the_key() {
for bad in ["1.5", "-0.2"] {
let c = parse(&format!("[context]\ncompact_at = {bad}\n"));
let err = c.context.validate().unwrap_err().to_string();
assert!(
err.contains("context.compact_at"),
"{bad} must be named in the error: {err}"
);
}
assert!(parse("[context]\ncompact_at = 0.6\n")
.context
.validate()
.is_ok());
assert!(parse("[context]\ncompact_at = 0\n")
.context
.validate()
.is_ok());
}
}
#[cfg(test)]
mod mcp_editor_tests {
use super::*;
use crate::mcp::Spec;
fn spec(text: &str) -> Spec {
toml::from_str(text).unwrap()
}
fn add(spec: &Spec) -> String {
let out = mcp_add(CONFIG, spec).unwrap();
parse_text(&out).unwrap();
out
}
const CONFIG: &str = r#"# my config
[provider]
base_url = "http://127.0.0.1:8081/v1"
model = "m"
# this comment belongs to the first entry
[[mcp]]
name = "first"
command = "one"
# and this one to the second
[[mcp]]
name = "second"
command = "two"
policy = "allow"
"#;
#[test]
fn an_added_entry_reads_back_and_leaves_the_comments_alone() {
let out = add(&spec(
"name = \"third\"\ncommand = \"three\"\nargs = [\"--x\"]\nprefix = \"t_\"\n",
));
let cfg = parse_text(&out).unwrap();
assert_eq!(
cfg.mcp.iter().map(|s| s.name.as_str()).collect::<Vec<_>>(),
["first", "second", "third"]
);
let third = cfg.mcp.iter().find(|s| s.name == "third").unwrap();
assert_eq!(third.args, ["--x"]);
assert_eq!(third.prefix, "t_");
for line in [
"# my config",
"# this comment belongs to the first entry",
"# and this one to the second",
] {
assert!(out.contains(line), "lost {line:?}:\n{out}");
}
assert!(
out.contains("[[mcp]]\nname = \"first\"\ncommand = \"one\""),
"{out}"
);
assert!(
!out.contains("args = []"),
"only what was set is written:\n{out}"
);
}
#[test]
fn a_duplicate_name_is_refused_and_named_by_line() {
let err = mcp_add(CONFIG, &spec("name = \"first\"\ncommand = \"again\"")).unwrap_err();
assert!(err.contains("already declared at line 7"), "{err}");
}
#[test]
fn an_unusable_entry_is_refused_before_anything_is_written() {
let err = mcp_add(
CONFIG,
&spec("name = \"bad\"\ntransport = \"http\"\ncommand = \"x\"\nurl = \"http://h/mcp\""),
)
.unwrap_err();
assert!(err.starts_with("that entry is not usable"), "{err}");
assert!(err.contains("belong to the stdio transport"), "{err}");
}
#[test]
fn remove_takes_the_named_block_and_the_blank_line_after_it() {
let out = mcp_remove(CONFIG, "first").unwrap();
let cfg = parse_text(&out).unwrap();
assert_eq!(
cfg.mcp.iter().map(|s| s.name.as_str()).collect::<Vec<_>>(),
["second"]
);
assert!(out.contains("# and this one to the second"), "{out}");
assert!(!out.contains("name = \"first\""), "{out}");
assert!(!out.contains("\n\n\n"), "no hole left behind:\n{out}");
}
#[test]
fn remove_says_what_the_file_does_declare() {
let err = mcp_remove(CONFIG, "nope").unwrap_err();
assert!(err.contains("declares first, second"), "{err}");
let bare = "[provider]\nbase_url = \"http://d/v1\"\nmodel = \"m\"\n";
let err = mcp_remove(bare, "nope").unwrap_err();
assert!(err.contains("no `[[mcp]]` entry for `nope`"), "{err}");
}
#[test]
fn disable_flips_the_line_inside_its_own_block() {
let off = mcp_set_disabled(CONFIG, "second", true).unwrap();
let cfg = parse_text(&off).unwrap();
assert!(
cfg.mcp
.iter()
.find(|s| s.name == "second")
.unwrap()
.disabled
);
assert!(!cfg.mcp.iter().find(|s| s.name == "first").unwrap().disabled);
let second_at = off.find("name = \"second\"").unwrap();
let tail = &off[second_at..];
assert!(tail.contains("disabled = true"), "{off}");
assert!(tail.find("disabled").unwrap() < tail.find("\n[[").unwrap_or(tail.len()));
let on = mcp_set_disabled(&off, "second", false).unwrap();
let cfg = parse_text(&on).unwrap();
assert!(
!cfg.mcp
.iter()
.find(|s| s.name == "second")
.unwrap()
.disabled
);
assert!(
on.contains("disabled = false"),
"said out loud, not deleted:\n{on}"
);
}
#[test]
fn disable_on_an_entry_without_the_key_inserts_one() {
let off = mcp_set_disabled(CONFIG, "first", true).unwrap();
assert!(off.contains("command = \"one\"\ndisabled = true"), "{off}");
assert!(parse_text(&off).unwrap().mcp[0].disabled);
}
#[test]
fn an_edit_changes_the_changed_line_and_leaves_every_other_byte_alone() {
let out = mcp_update(CONFIG, "second", |entry| entry.prefix = "t_".into()).unwrap();
parse_text(&out).unwrap();
assert_eq!(
out,
CONFIG.replace(
"command = \"two\"\npolicy = \"allow\"",
"command = \"two\"\npolicy = \"allow\"\nprefix = \"t_\""
),
"one added line, and not one other character moved:\n{out}"
);
}
#[test]
fn an_edit_sets_and_clears_token_env_without_touching_the_rest() {
let on = mcp_update(CONFIG, "second", |entry| {
entry.token_env = Some("HA_TOKEN".into())
})
.unwrap();
assert_eq!(
on,
CONFIG.replace(
"command = \"two\"\npolicy = \"allow\"",
"command = \"two\"\npolicy = \"allow\"\ntoken_env = \"HA_TOKEN\""
),
"{on}"
);
let off = mcp_update(&on, "second", |entry| entry.token_env = None).unwrap();
assert_eq!(
off, CONFIG,
"clearing a field removes its line and nothing else"
);
}
#[test]
fn an_edit_keeps_a_comment_written_inside_the_block() {
let inner = "[[mcp]]\nname = \"a\"\n# the endpoint is on the box\ncommand = \"x\"\n";
let out = mcp_update(inner, "a", |entry| {
entry.args = vec!["--y".into()];
})
.unwrap();
assert_eq!(
out,
"[[mcp]]\nname = \"a\"\n# the endpoint is on the box\ncommand = \"x\"\n\
args = [\"--y\"]\n",
"{out}"
);
}
#[test]
fn an_edit_refuses_a_rename_and_names_what_the_file_declares() {
let err = mcp_update(CONFIG, "second", |entry| entry.name = "renamed".into()).unwrap_err();
assert!(err.contains("an edit does not rename"), "{err}");
let err = mcp_update(CONFIG, "nope", |_| {}).unwrap_err();
assert!(err.contains("declares first, second"), "{err}");
let err = mcp_update(CONFIG, "second", |entry| {
entry.transport = crate::mcp::Transport::Http;
entry.url = Some("http://h/mcp".into());
})
.unwrap_err();
assert!(err.starts_with("that entry is not usable"), "{err}");
assert!(err.contains("belong to the stdio transport"), "{err}");
}
#[test]
fn an_empty_file_gets_its_first_entry_cleanly() {
let out = mcp_add("", &spec("name = \"only\"\ncommand = \"x\"")).unwrap();
assert!(out.starts_with("[[mcp]]\n"), "{out:?}");
assert_eq!(parse_text(&out).unwrap().mcp[0].name, "only");
}
#[test]
fn a_second_entry_is_separated_by_exactly_one_blank_line() {
let out = add(&spec("name = \"third\"\ncommand = \"three\""));
assert!(!out.contains("\n\n\n"), "{out}");
assert!(
out.contains("policy = \"allow\"\n\n[[mcp]]\nname = \"third\""),
"{out}"
);
}
}