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
//! `!command` on the composer: a shell command run for the person at the keyboard.
//!
//! The point is what does *not* happen. A line beginning with `!` never becomes a user message, so
//! there is no assistant reply to it, no tool result, and nothing written to the session store:
//! `!git status` costs no tokens, cannot break role alternation, and cannot invalidate a prompt
//! cache. It is a convenience at the prompt, not a turn.
//!
//! Three rules are load-bearing:
//!
//! - **Only a leading bang.** `fix the bug!` is a prompt and reaches the agent untouched; a
//!   trailing bang is prose. `!!` is one literal `!`, which is the shell's own history expansion
//!   and the reason anyone types it.
//! - **Only where there is a keyboard.** [`refusal`] is checked by the two interactive surfaces;
//!   `eclipse run`, cron and the gateway never call this module at all, so a `!`-line arriving from
//!   a caller becomes text for the model. "Run what the caller typed" would otherwise be remote
//!   execution with a friendlier name.
//! - **Not the model's allowlist.** `[tools] shell_allowlist` constrains what the *model* may run;
//!   the human at the prompt is not the model, and a `!` command is not filtered by it. What does
//!   apply is everything that protects the machine: [`risk::danger`] refuses the commands that
//!   cannot be undone, `[tools] shell_isolate` wraps the run when bubblewrap is present, and the
//!   environment is rebuilt rather than inherited, so no provider key reaches a command typed at
//!   the prompt.

use std::ffi::OsString;
use std::path::Path;
use std::process::Stdio;
use std::sync::{Arc, Mutex};
use std::time::Duration;

use eclipse_core::risk;
use eclipse_core::sandbox::Sandbox;
use tokio::io::AsyncReadExt;

/// How long a `!` command may run before it is killed. This is interactive convenience, not a job
/// runner: anything that legitimately takes longer belongs in a terminal of its own, and a composer
/// that can be wedged by `!sleep 999` is a composer that cannot be trusted with the next keystroke.
pub const CEILING: Duration = Duration::from_secs(120);

/// How much output is kept. A command that prints a hundred thousand lines is not more useful than
/// the first sixty-four kilobytes of it, and the transcript is not the place to find out.
const KEPT: usize = 64 * 1024;

/// Where a line was typed, because that decides whether `!` means anything.
///
/// **There is deliberately no `Web`.** The dashboard decided this in `#283`, and the decision is in
/// the code twice: this enum has no variant for it, and `eclipse-web`'s `verb::bang_refusal` answers
/// a `!` line with a refusal instead of forwarding it. The reason a browser is not a keyboard here
/// is not squeamishness about shells — it is that a bang is a promise that somebody is typing *and
/// watching* what it prints, and the dashboard is one token, one machine, and whoever holds it. A
/// `Web` variant is the change that decision forbids; if it is ever wanted, the issue says what has
/// to come first (a `[web] bang` key off by default, the key named on the startup line, the run
/// isolated and cancellable) before anyone writes it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Surface {
    /// The full-screen interface.
    Tui,
    /// The plain line-based REPL.
    Repl,
    /// `eclipse run`: one prompt, no human following along.
    Run,
    /// A cron job: a stored prompt, running with nobody watching.
    Cron,
}

impl Surface {
    /// True where a person is typing and watching.
    pub fn keyboard(self) -> bool {
        matches!(self, Surface::Tui | Surface::Repl)
    }
}

/// Why a bang line is not run here, in the words the caller prints. `None` means it may run.
pub fn refusal(surface: Surface) -> Option<&'static str> {
    if surface.keyboard() {
        return None;
    }
    Some(
        "`!command` runs a shell command for the person at the keyboard, and this session has \
         nobody at one — the line was not run. Send it to the model as a prompt, or run it in a \
         terminal.",
    )
}

/// A line that is a command for the shell rather than for the model.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Bang {
    /// What to hand to `sh -c`, with the leading bang and any padding removed.
    pub script: String,
}

/// One typed line, classified.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Line<'a> {
    Bang(Bang),
    /// Anything else, borrowed rather than copied: the overwhelmingly common case.
    Prompt(&'a str),
}

/// Classify a line. A leading `!` (after any indentation) makes it a command; nothing else does.
pub fn parse(line: &str) -> Line<'_> {
    let trimmed = line.trim_start();
    let Some(rest) = trimmed.strip_prefix('!') else {
        return Line::Prompt(line);
    };
    // `!!` is a literal `!`: strip one bang and leave the other for the shell, which is what the
    // person typing `!!` meant. `!!ls` therefore runs `!ls`.
    let script = match rest.strip_prefix('!') {
        Some(after) => format!("!{after}"),
        None => rest.to_string(),
    };
    Line::Bang(Bang {
        script: script.trim().to_string(),
    })
}

/// How a bang command ended.
#[derive(Debug, Clone, Default)]
pub struct Ran {
    /// What it printed, stdout and stderr in the order they arrived, capped at [`KEPT`].
    pub output: String,
    /// The exit status; `None` when it was killed at the ceiling or never started.
    pub code: Option<i32>,
    /// It was still running at the ceiling and was killed.
    pub timed_out: bool,
    /// More was printed than was kept: the tail is missing, and the transcript says so.
    pub truncated: bool,
    /// It was not run, and why. Mutually exclusive with the fields above.
    pub refused: Option<String>,
}

impl Ran {
    /// The one line the transcript ends with: how it ended, and whether the output was cut.
    pub fn summary(&self) -> String {
        if let Some(why) = &self.refused {
            return format!("! not run: {why}");
        }
        if self.timed_out {
            return format!(
                "! killed after {}s — a bang command is for interactive use, not for jobs",
                CEILING.as_secs()
            );
        }
        let mut said = match self.code {
            Some(0) => "! exit 0".to_string(),
            Some(code) => format!("! exit {code}"),
            None => "! ended without an exit status".to_string(),
        };
        if self.truncated {
            said.push_str(" (output truncated at 64 KiB)");
        }
        said
    }
}

/// Run a bang command in `cwd`, under the sandbox and outside the model's allowances.
pub async fn run(script: &str, cwd: &Path, sandbox: &Sandbox) -> Ran {
    run_within(script, cwd, sandbox, CEILING).await
}

/// [`run`] with an explicit ceiling, so a test need not wait two minutes to prove one is enforced.
pub async fn run_within(script: &str, cwd: &Path, sandbox: &Sandbox, ceiling: Duration) -> Ran {
    if script.is_empty() {
        return Ran {
            refused: Some("usage: !command — everything after the bang goes to `sh -c`".into()),
            ..Ran::default()
        };
    }
    // The human typed it, so a confirmation prompt would be the interface arguing with its own
    // user. What cannot be undone is refused outright instead, with the reason: `!` is meant for
    // looking, and `!rm -rf /` is never something to discover afterwards.
    if let Some(why) = risk::danger(script) {
        return Ran {
            refused: Some(format!(
                "that {why}. Run it in your own shell if that is what you meant"
            )),
            ..Ran::default()
        };
    }

    let program = std::ffi::OsStr::new("sh");
    let args = [OsString::from("-c"), OsString::from(script)];
    let plan = match sandbox.plan(program, &args, cwd) {
        Ok(plan) => plan,
        Err(why) => {
            return Ran {
                refused: Some(why.to_string()),
                ..Ran::default()
            }
        }
    };

    let mut cmd = tokio::process::Command::new(&plan.program);
    cmd.args(&plan.args)
        .current_dir(cwd)
        // Rebuilt, not inherited: a provider key in the environment is for the agent to use, not
        // for a command the person typed to read back.
        .env_clear()
        .envs(environment(cwd))
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .kill_on_drop(true);
    let mut child = match cmd.spawn() {
        Ok(child) => child,
        Err(why) => {
            return Ran {
                refused: Some(format!("could not start `sh`: {why}")),
                ..Ran::default()
            }
        }
    };

    // One buffer for both pipes, appended under a lock: interleaving is the point of a merged
    // stream, and two buffers read one after the other would put every error after every line.
    let seen = Arc::new(Mutex::new(String::new()));
    let cut = Arc::new(std::sync::atomic::AtomicBool::new(false));
    let mut readers = Vec::new();
    for pipe in [
        child
            .stdout
            .take()
            .map(|p| Box::new(p) as Box<dyn tokio::io::AsyncRead + Unpin + Send>),
        child
            .stderr
            .take()
            .map(|p| Box::new(p) as Box<dyn tokio::io::AsyncRead + Unpin + Send>),
    ]
    .into_iter()
    .flatten()
    {
        let seen = Arc::clone(&seen);
        let cut = Arc::clone(&cut);
        readers.push(tokio::spawn(async move {
            let mut pipe = pipe;
            let mut buf = [0u8; 8192];
            loop {
                match pipe.read(&mut buf).await {
                    Ok(0) | Err(_) => break,
                    Ok(n) => {
                        let Ok(mut text) = seen.lock() else { break };
                        let room = KEPT.saturating_sub(text.len());
                        if room == 0 {
                            // Still drained, never kept: a full pipe would block the command.
                            cut.store(true, std::sync::atomic::Ordering::Relaxed);
                            continue;
                        }
                        let take = n.min(room);
                        if take < n {
                            cut.store(true, std::sync::atomic::Ordering::Relaxed);
                        }
                        // Lossy, because a command may print anything and the transcript is text.
                        text.push_str(&String::from_utf8_lossy(&buf[..take]));
                    }
                }
            }
        }));
    }

    let ended = tokio::time::timeout(ceiling, child.wait()).await;
    for reader in readers {
        let _ = reader.await;
    }
    let output = seen.lock().map(|t| t.clone()).unwrap_or_default();
    let truncated = cut.load(std::sync::atomic::Ordering::Relaxed);

    match ended {
        Ok(Ok(status)) => Ran {
            output: trim_trailing(&output),
            code: status.code(),
            truncated,
            ..Ran::default()
        },
        Ok(Err(why)) => Ran {
            output: trim_trailing(&output),
            truncated,
            refused: Some(format!("`sh` could not be waited on: {why}")),
            ..Ran::default()
        },
        Err(_) => {
            // The ceiling is the whole reason `!` is safe to type: kill, do not wait.
            let _ = child.start_kill();
            let _ = child.wait().await;
            Ran {
                output: trim_trailing(&output),
                timed_out: true,
                truncated,
                ..Ran::default()
            }
        }
    }
}

/// The environment a bang command gets: what a shell needs to work, and nothing the agent holds.
fn environment(cwd: &Path) -> Vec<(String, String)> {
    const KEEP: [&str; 12] = [
        "PATH", "HOME", "USER", "LOGNAME", "SHELL", "TERM", "TMPDIR", "TMP", "LANG", "LC_ALL",
        "LC_CTYPE", "TZ",
    ];
    let mut env: Vec<(String, String)> = KEEP
        .iter()
        .filter_map(|k| std::env::var(k).ok().map(|v| (k.to_string(), v)))
        .collect();
    env.push(("PWD".to_string(), cwd.display().to_string()));
    env
}

fn trim_trailing(text: &str) -> String {
    text.trim_end_matches(['\n', '\r']).to_string()
}

#[cfg(test)]
mod tests {
    use super::*;

    fn script_of(line: &str) -> Option<String> {
        match parse(line) {
            Line::Bang(b) => Some(b.script),
            Line::Prompt(_) => None,
        }
    }

    /// `#283`: the surfaces are a closed list, and the dashboard is not on it. This test exists so
    /// that adding a variant is a decision somebody typed rather than a variant that arrived —
    /// `Surface::Web` would make `keyboard()` true for a browser behind one shared token.
    #[test]
    fn only_the_two_surfaces_with_a_person_at_them_have_a_keyboard() {
        assert!(Surface::Tui.keyboard());
        assert!(Surface::Repl.keyboard());
        assert!(!Surface::Run.keyboard());
        assert!(!Surface::Cron.keyboard());
        assert!(refusal(Surface::Tui).is_none());
        assert!(refusal(Surface::Repl).is_none());
        // ...and the refusal a script meets names the shell and points somewhere it can be typed.
        let said = refusal(Surface::Run).unwrap();
        assert!(said.contains("nobody at one"), "{said}");
        assert!(said.contains("terminal"), "{said}");
    }

    #[test]
    fn a_leading_bang_is_a_command_and_a_trailing_one_is_prose() {
        assert_eq!(script_of("!ls"), Some("ls".into()));
        assert_eq!(script_of("!git status"), Some("git status".into()));
        // Padding after the bang is not part of the command.
        assert_eq!(script_of("!  ls -la"), Some("ls -la".into()));
        // Indented, still a command: leading space is not a decision.
        assert_eq!(script_of("   !pwd"), Some("pwd".into()));
        // A trailing bang is the person's own punctuation, and the model gets the whole line.
        assert_eq!(script_of("fix the bug!"), None);
        assert_eq!(script_of("what does `rm -rf /` do?"), None);
        assert_eq!(script_of(""), None);
        assert_eq!(script_of("/status"), None);
    }

    #[test]
    fn a_double_bang_is_one_literal_bang() {
        // `!!` is a history expansion, so the shell has to see one bang, not two.
        assert_eq!(script_of("!!"), Some("!".into()));
        assert_eq!(script_of("!!ls -la"), Some("!ls -la".into()));
        // Three is not a special case: strip one, leave `!!` to the shell.
        assert_eq!(script_of("!!!ls"), Some("!!ls".into()));
    }

    #[test]
    fn only_a_keyboard_surface_runs_one() {
        assert!(refusal(Surface::Tui).is_none());
        assert!(refusal(Surface::Repl).is_none());
        for surface in [Surface::Run, Surface::Cron] {
            let why = refusal(surface).expect("refused without a keyboard");
            assert!(why.contains("!command"), "{why}");
            assert!(why.contains("not run"), "{why}");
        }
    }

    #[test]
    fn an_empty_bang_says_how_to_use_it() {
        let ran = tokio::runtime::Runtime::new().unwrap().block_on(run(
            "",
            Path::new("/tmp"),
            &Sandbox::off(),
        ));
        let why = ran.refused.expect("refused");
        assert!(why.contains("usage: !command"), "{why}");
    }

    #[test]
    fn a_destructive_command_is_refused_rather_than_obeyed() {
        let ran = tokio::runtime::Runtime::new().unwrap().block_on(run(
            "rm -rf /",
            Path::new("/tmp"),
            &Sandbox::off(),
        ));
        let why = ran.refused.expect("refused");
        assert!(why.contains("deletes the filesystem"), "{why}");
        assert!(ran.output.is_empty(), "and nothing ran: {:?}", ran.output);
    }

    #[test]
    fn a_command_runs_and_reports_its_exit_code() {
        let rt = tokio::runtime::Runtime::new().unwrap();
        let ran = rt.block_on(run("echo hi", Path::new("/tmp"), &Sandbox::off()));
        assert_eq!(ran.output, "hi");
        assert_eq!(ran.code, Some(0));
        assert_eq!(ran.summary(), "! exit 0");

        let failed = rt.block_on(run("exit 3", Path::new("/tmp"), &Sandbox::off()));
        assert_eq!(failed.code, Some(3));
        assert!(failed.summary().contains("exit 3"), "{}", failed.summary());
    }

    #[test]
    fn both_streams_come_out_of_the_same_pipe() {
        let ran = tokio::runtime::Runtime::new().unwrap().block_on(run(
            "echo out; echo err >&2",
            Path::new("/tmp"),
            &Sandbox::off(),
        ));
        assert!(ran.output.contains("out"), "{:?}", ran.output);
        assert!(ran.output.contains("err"), "{:?}", ran.output);
    }

    #[test]
    fn a_hanging_command_is_killed_at_the_ceiling() {
        let ran = tokio::runtime::Runtime::new().unwrap().block_on(run_within(
            "sleep 5",
            Path::new("/tmp"),
            &Sandbox::off(),
            Duration::from_millis(200),
        ));
        assert!(ran.timed_out, "killed rather than waited for");
        assert_eq!(ran.code, None);
        assert!(ran.summary().contains("killed"), "{}", ran.summary());
    }

    #[test]
    fn provider_keys_do_not_reach_a_command_typed_at_the_prompt() {
        // Set in this process, and expected to be absent in the child: the environment is rebuilt
        // from an allowlist rather than inherited.
        std::env::set_var("DEEPSEEK_API_KEY", "sk-should-not-travel");
        let ran = tokio::runtime::Runtime::new().unwrap().block_on(run(
            "echo \"key=${DEEPSEEK_API_KEY:-none}\"",
            Path::new("/tmp"),
            &Sandbox::off(),
        ));
        assert_eq!(ran.output, "key=none", "{:?}", ran.output);
        std::env::remove_var("DEEPSEEK_API_KEY");
    }

    #[test]
    fn it_runs_in_the_directory_it_was_given() {
        let dir = tempfile::tempdir().unwrap();
        let ran = tokio::runtime::Runtime::new().unwrap().block_on(run(
            "pwd",
            dir.path(),
            &Sandbox::off(),
        ));
        assert_eq!(
            std::fs::canonicalize(&ran.output).unwrap(),
            std::fs::canonicalize(dir.path()).unwrap()
        );
    }

    #[test]
    fn output_stops_at_the_cap_and_says_so() {
        let ran = tokio::runtime::Runtime::new().unwrap().block_on(run(
            "yes eclipse | head -c 200000",
            Path::new("/tmp"),
            &Sandbox::off(),
        ));
        assert!(ran.output.len() <= KEPT, "{} bytes kept", ran.output.len());
        assert!(ran.truncated, "and it says so");
        assert!(ran.summary().contains("truncated"), "{}", ran.summary());
    }
}