eclipse-cli 0.13.4

Command-line interface for eclipse
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
//! The first five minutes.
//!
//! `eclipse setup` is the front door: it asks the questions a working install needs — which
//! model server, which model, a key if the server wants one, how much the tools may do, and
//! whether the local dashboard is wanted — and writes them into the config the rest of the
//! program reads. Bare `eclipse` on an install with no provider offers it, so `install.sh`
//! plus one answer gets you into a running TUI.
//!
//! What it does not do, on purpose: it never starts a server, never prints a secret back, and
//! never rewrites a line it did not ask about. Every question defaults to the current value,
//! so a second run changes one thing and leaves the rest alone.
//!
//! Output goes to stdout and input comes from stdin, one line at a time. With no stdin at all
//! it says so and writes nothing: a half-written config is worse than none.

use anyhow::{bail, Context, Result};
use eclipse_core::config;
use std::io::{BufRead, Write};
use std::path::Path;

/// The file the wizard writes. The main config by default; a named profile's overlay when
/// `--profile` names one, in which case the base config is untouched and the overlay is what
/// the loader merges on top of it.
pub struct Target {
    /// The file written.
    pub path: std::path::PathBuf,
    /// The base config this overlay is merged over; `None` writes the main config.
    pub base: Option<std::path::PathBuf>,
    /// The profile this overlay belongs to.
    pub profile: Option<String>,
}

impl Target {
    fn overlay(&self) -> bool {
        self.profile.is_some()
    }
}

/// Enough for the caller to say what to do next. Everything the wizard wants to tell the
/// user it has already printed — this is not a second summary.
pub struct Done {
    pub dashboard: bool,
}

pub enum Outcome {
    Wrote(Done),
    /// No input (EOF, or nothing left to read). Nothing was written.
    Cancelled,
}

/// How much the model may do without asking.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Preset {
    Standard,
    ReadOnly,
    Trusting,
}

impl Preset {
    fn policies(self) -> [(&'static str, &'static str); 4] {
        match self {
            // The defaults the starter config ships with.
            Preset::Standard => [
                ("read_file", "allow"),
                ("write_file", "ask"),
                ("shell", "ask"),
                ("fetch", "ask"),
            ],
            // A guard rail for a first run with a model you do not trust yet.
            Preset::ReadOnly => [
                ("read_file", "allow"),
                ("write_file", "deny"),
                ("shell", "deny"),
                ("fetch", "deny"),
            ],
            // Everything runs: only for a workspace and a model you trust completely.
            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",
        }
    }
}

/// The word a policy is written as — in the config file, and in this wizard's summary.
fn policy_word(p: config::Policy) -> &'static str {
    match p {
        config::Policy::Deny => "deny",
        config::Policy::Ask => "ask",
        config::Policy::Allow => "allow",
    }
}

/// One answered question, or `None` when stdin ended (Ctrl-D, or a script that gave fewer
/// answers than the wizard asked for).
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(),
    }))
}

/// `[Y/n]` / `[y/N]`, with the default taken on an empty line.
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}`"),
        }
    }
}

/// Ask until the answer names one of `labels` (by number or by word), then return its index.
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(", "));
    }
}

/// A yes/no question for the caller (bare `eclipse`: "set it up now?").
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('/'))
}

/// Run the wizard. Writes only once every answer is in and the result parses as a config.
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();
    // A first run starts from the starter config, comments and all: the file the user ends up
    // reading should be the documented one, not a three-line minimum. A profile gets the
    // overlay starter instead — restating the base's every default would pin them.
    let base = match existing.clone() {
        Some(text) => text,
        None if target.overlay() => config::STARTER_PROFILE_CONFIG.to_string(),
        None => config::starter_config()?,
    };
    // The defaults are the *effective* values: for a profile that means base + overlay, so
    // Enter keeps what the program would actually use rather than what this file repeats.
    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())
    };
    // No `.filter` here: an empty value in `.env` is already absent (one rule, in `Dotenv::load`).
    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()
        ),
    }

    // 1. Where the model lives.
    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");
    };

    // 2. A key, if the server wants one. Asked before the model so the model list can use it.
    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,
        // That default is a note, not a value: enter means "keep what is in .env".
        "(keep the saved key)" => None,
        t => Some(t.to_string()),
    };
    let key_to_use = typed_key.clone().or_else(|| saved_key.clone());

    // 3. Which model. Offer the server's own list when it answers.
    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;
        }
        // A number picks from the list just printed; anything else is taken as written.
        match (&models, a.parse::<usize>()) {
            (Some(list), Ok(n)) if n >= 1 && n <= list.len() => break list[n - 1].clone(),
            _ => break a,
        }
    };

    // 4. Wire profile: how the request is spelled for this backend.
    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);
    };
    // Enter is not an answer. `[provider] profile` also accepts a name a plugin declares, and
    // this question can only offer the two this build knows, so writing the label back replaced
    // a working profile with `openai` on a second run (#586).
    let profile = match (&saved_profile, p == profile_default) {
        (Some(saved), true) => saved.clone(),
        _ => profile_labels[p].to_string(),
    };

    // 5. How much the model may do on its own.
    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];
    // A preset is a decision; Enter is not. The default is derived from `tools.shell` alone, so
    // the other three policies in `Preset::policies` are guessed from one value — writing them all
    // flattened a hand-set `deny` back to `ask` on a second run (#586). Accepting the offered
    // preset leaves every policy as the file has it; choosing a different one still writes all
    // four, because that is what choosing a preset means.
    let rewrite_policies = pi != preset_default;

    // 6. The dashboard is a second binary; this only decides whether it is set up. It reads
    // the base config, so a profile has nothing to say about it.
    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
    };

    // Nothing is written until the whole result loads the way the real loader loads it.
    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() {
        // The secret stays in .env; the config only names the variable, so the file remains
        // safe to paste into a bug report.
        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);
        }
    }
    // Nothing is written until the result parses the way the loader parses a file. For a
    // profile the overlay wins over the base, so a key the overlay carries is the key the
    // merged view ends up with — this check is the whole guarantee.
    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()))?;
    }
    // The starter config refers to `${ECLIPSE_WEB_AUTH_TOKEN}`, so a missing token makes the
    // whole config unloadable — "no dashboard" must not mean "eclipse refuses to start". The
    // token is written either way; the answer only decides what the wizard sets up and says.
    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;
    }

    // Seed the context files (AGENT.md, USER.md, MEMORY.md) in the effective profile's memory
    // directory: an install whose agent cannot say who it is talking to is not finished.
    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 {
        // Nothing was rewritten, so the preset's name would describe a guess and not the file.
        // Say what is actually in force instead (#586).
        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 }))
}