use anyhow::{bail, Context, Result};
use eclipse_core::config;
use std::io::{BufRead, Write};
use std::path::Path;
pub struct Target {
pub path: std::path::PathBuf,
pub base: Option<std::path::PathBuf>,
pub profile: Option<String>,
}
impl Target {
fn overlay(&self) -> bool {
self.profile.is_some()
}
}
pub struct Done {
pub dashboard: bool,
}
pub enum Outcome {
Wrote(Done),
Cancelled,
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Preset {
Standard,
ReadOnly,
Trusting,
}
impl Preset {
fn policies(self) -> [(&'static str, &'static str); 4] {
match self {
Preset::Standard => [
("read_file", "allow"),
("write_file", "ask"),
("shell", "ask"),
("fetch", "ask"),
],
Preset::ReadOnly => [
("read_file", "allow"),
("write_file", "deny"),
("shell", "deny"),
("fetch", "deny"),
],
Preset::Trusting => [
("read_file", "allow"),
("write_file", "allow"),
("shell", "allow"),
("fetch", "allow"),
],
}
}
fn label(self) -> &'static str {
match self {
Preset::Standard => "standard",
Preset::ReadOnly => "read-only",
Preset::Trusting => "trusting",
}
}
}
fn policy_word(p: config::Policy) -> &'static str {
match p {
config::Policy::Deny => "deny",
config::Policy::Ask => "ask",
config::Policy::Allow => "allow",
}
}
fn ask(prompt: &str, default: Option<&str>) -> Result<Option<String>> {
match default {
Some(d) if !d.is_empty() => print!("{prompt} [{d}]: "),
_ => print!("{prompt}: "),
}
std::io::stdout().flush().ok();
let mut line = String::new();
if std::io::stdin().lock().read_line(&mut line)? == 0 {
println!();
return Ok(None);
}
let answer = line.trim();
Ok(Some(match (answer.is_empty(), default) {
(true, Some(d)) => d.to_string(),
_ => answer.to_string(),
}))
}
fn ask_yes_no(prompt: &str, default: bool) -> Result<Option<bool>> {
let hint = if default { "Y/n" } else { "y/N" };
loop {
let Some(answer) = ask(&format!("{prompt} [{hint}]"), None)? else {
return Ok(None);
};
match answer.trim().to_ascii_lowercase().as_str() {
"" => return Ok(Some(default)),
"y" | "yes" => return Ok(Some(true)),
"n" | "no" => return Ok(Some(false)),
other => println!(" say y or n, not `{other}`"),
}
}
}
fn ask_choice(prompt: &str, labels: &[&str], default: usize) -> Result<Option<usize>> {
loop {
let Some(answer) = ask(prompt, Some(&(default + 1).to_string()))? else {
return Ok(None);
};
let a = answer.trim().to_ascii_lowercase();
if let Ok(n) = a.parse::<usize>() {
if n >= 1 && n <= labels.len() {
return Ok(Some(n - 1));
}
}
if let Some(i) = labels.iter().position(|l| *l == a) {
return Ok(Some(i));
}
println!(" pick 1-{} ({})", labels.len(), labels.join(", "));
}
}
pub fn confirm(prompt: &str, default: bool) -> Result<Option<bool>> {
ask_yes_no(prompt, default)
}
fn valid_url(url: &str) -> bool {
let rest = url
.strip_prefix("http://")
.or_else(|| url.strip_prefix("https://"));
matches!(rest, Some(r) if !r.trim().is_empty() && !r.starts_with('/'))
}
pub async fn run(target: &Target, verbose: bool) -> Result<Outcome> {
let config_path = &target.path;
let dotenv = config_path.parent().unwrap_or(Path::new(".")).join(".env");
let existing = std::fs::read_to_string(config_path).ok();
let base = match existing.clone() {
Some(text) => text,
None if target.overlay() => config::STARTER_PROFILE_CONFIG.to_string(),
None => config::starter_config()?,
};
let effective = config::Config::load_with_profile(
target.base.as_deref(),
target.profile.as_deref(),
&config::process_env,
)
.ok();
let current = |section: &str, key: &str| -> Option<String> {
match (&effective, section, key) {
(Some(c), "provider", "base_url") => Some(c.provider.base_url.clone()),
(Some(c), "provider", "model") => Some(c.provider.model.clone()),
(Some(c), "provider", "profile") => c.provider.profile.clone(),
(Some(c), "tools", key) => Some(
policy_word(match key {
"shell" => c.tools.shell,
"read_file" => c.tools.read_file,
"write_file" => c.tools.write_file,
_ => c.tools.fetch,
})
.to_string(),
),
_ => config::toml_value(&base, section, key),
}
.filter(|v| !v.is_empty())
};
let saved_key = config::dotenv_var(&dotenv, "ECLIPSE_API_KEY");
println!();
match (&target.profile, existing.is_none()) {
(Some(name), _) if target.overlay() => println!(
" Configuring profile `{name}` — written as an overlay, {} stays as it is.",
target
.base
.as_deref()
.map(|p| p.display().to_string())
.unwrap_or_else(|| "the base config".to_string())
),
(_, true) => println!(" eclipse is installed. A few questions and it runs."),
_ => println!(
" Reconfiguring {}. Enter keeps what is there.",
config_path.display()
),
}
let url_default = current("provider", "base_url")
.or_else(|| std::env::var("ECLIPSE_BASE_URL").ok())
.filter(|u| !u.is_empty());
let base_url = loop {
let Some(answer) = ask(
"\nModel server URL (OpenAI-compatible, up to the /v1)",
url_default.as_deref(),
)?
else {
return Ok(Outcome::Cancelled);
};
let a = answer.trim().trim_end_matches('/').to_string();
if valid_url(&a) {
break a;
}
println!(" that needs http:// or https://, e.g. http://127.0.0.1:8080/v1");
};
let keep_note = saved_key.as_ref().map(|_| "(keep the saved key)");
let Some(answer) = ask("\nAPI key (empty = none)", keep_note)? else {
return Ok(Outcome::Cancelled);
};
let typed_key = match answer.trim() {
"" => None,
"(keep the saved key)" => None,
t => Some(t.to_string()),
};
let key_to_use = typed_key.clone().or_else(|| saved_key.clone());
let (models, unreachable) = match eclipse_core::provider::list_models(
&base_url,
key_to_use.as_deref(),
std::time::Duration::from_secs(4),
)
.await
{
Ok(list) if !list.is_empty() => {
println!("\n {} says it serves:", base_url);
for (i, m) in list.iter().take(12).enumerate() {
println!(" {}) {m}", i + 1);
}
if list.len() > 12 {
println!(" ... and {} more", list.len() - 12);
}
(Some(list), None)
}
Ok(_) => {
println!("\n {base_url} answered but listed no models; type one by hand.");
(None, None)
}
Err(why) => {
println!("\n could not list models; type one by hand.");
(None, Some(why.to_string()))
}
};
let model = loop {
let Some(answer) = ask("Model", current("provider", "model").as_deref())? else {
return Ok(Outcome::Cancelled);
};
let a = answer.trim().to_string();
if a.is_empty() {
println!(" a model name is required");
continue;
}
match (&models, a.parse::<usize>()) {
(Some(list), Ok(n)) if n >= 1 && n <= list.len() => break list[n - 1].clone(),
_ => break a,
}
};
let profile_labels = ["openai", "llamacpp"];
let saved_profile = current("provider", "profile");
let profile_default = usize::from(saved_profile.as_deref() == Some("llamacpp"));
let Some(p) = ask_choice(
"\nWire profile (1 = any OpenAI-compatible server, 2 = llama.cpp)",
&profile_labels,
profile_default,
)?
else {
return Ok(Outcome::Cancelled);
};
let profile = match (&saved_profile, p == profile_default) {
(Some(saved), true) => saved.clone(),
_ => profile_labels[p].to_string(),
};
let presets = [Preset::Standard, Preset::ReadOnly, Preset::Trusting];
let preset_default = match current("tools", "shell").as_deref() {
Some("deny") => 1,
Some("allow") => 2,
_ => 0,
};
let Some(pi) = ask_choice(
"\nTool permissions (1 = ask before writes/shell/fetch, 2 = read-only, 3 = allow everything)",
&["standard", "read-only", "trusting"],
preset_default,
)?
else {
return Ok(Outcome::Cancelled);
};
let preset = presets[pi];
let rewrite_policies = pi != preset_default;
let dashboard = if target.overlay() {
false
} else {
let Some(answer) = ask_yes_no("\nSet up the local dashboard (eclipse-web)?", true)? else {
return Ok(Outcome::Cancelled);
};
answer
};
let mut text = base.clone();
text = config::toml_set_string(&text, "provider", "base_url", &base_url);
text = config::toml_set_string(&text, "provider", "model", &model);
text = config::toml_set_string(&text, "provider", "profile", &profile);
if key_to_use.is_some() {
text = config::toml_set_string(&text, "provider", "api_key_env", "ECLIPSE_API_KEY");
}
if rewrite_policies {
for (name, policy) in preset.policies() {
text = config::toml_set_string(&text, "tools", name, policy);
}
}
let parsed = config::parse_text(&text).context("the setup result does not parse")?;
if parsed.provider.base_url != base_url || parsed.provider.model != model {
bail!("the edited config does not read back as what was asked; nothing was written");
}
if let Some(dir) = config_path.parent() {
std::fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?;
}
config::save_config_text(config_path, &text)
.with_context(|| format!("writing {}", config_path.display()))?;
if let Some(key) = &typed_key {
config::save_dotenv_var(&dotenv, "ECLIPSE_API_KEY", key)
.with_context(|| format!("writing {}", dotenv.display()))?;
}
let mut made_token = false;
if !target.overlay() && config::dotenv_var(&dotenv, "ECLIPSE_WEB_AUTH_TOKEN").is_none() {
let token = eclipse_core::token::generate()?;
config::save_dotenv_var(&dotenv, "ECLIPSE_WEB_AUTH_TOKEN", &token)
.with_context(|| format!("writing {}", dotenv.display()))?;
made_token = true;
}
let saved = config::Config::load_with_profile(
target.base.as_deref(),
target.profile.as_deref(),
&config::process_env,
)
.ok();
if let Some(cfg) = saved
.as_ref()
.and_then(|c| c.memory_dir(&config::process_env))
{
match config::seed_context_files(&cfg) {
Ok(created) => {
for p in &created {
println!(" wrote {}", p.display());
}
}
Err(e) => println!(" could not seed context files ({e}); edit memory/ by hand"),
}
}
println!("\n Wrote {}", config_path.display());
println!(" server {base_url}");
println!(" model {model}");
println!(" profile {profile}");
if rewrite_policies {
println!(" tools {}", preset.label());
} else {
let kept: Vec<String> = ["read_file", "write_file", "shell", "fetch"]
.into_iter()
.filter_map(|name| current("tools", name).map(|p| format!("{name} {p}")))
.collect();
println!(" tools kept ({})", kept.join(", "));
}
println!(
" api key {}",
match (&typed_key, &saved_key) {
(Some(_), _) => "saved to .env",
(None, Some(_)) => "unchanged (already in .env)",
(None, None) => "none",
}
);
if dashboard {
println!(
" dashboard http://127.0.0.1:8787 — start it with `eclipse-web`{}",
if made_token {
" (token written to .env)"
} else {
""
}
);
} else if target.overlay() {
println!(" dashboard not set up here: it reads the base config, not a profile");
} else {
println!(" dashboard left alone (start it with `eclipse-web` if you change your mind)");
}
if let Some(why) = &unreachable {
println!(
" server not reachable right now{} — saved anyway",
if verbose {
format!(" ({why})")
} else {
String::new()
}
);
}
Ok(Outcome::Wrote(Done { dashboard }))
}