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;
pub const CEILING: Duration = Duration::from_secs(120);
const KEPT: usize = 64 * 1024;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Surface {
Tui,
Repl,
Run,
Cron,
}
impl Surface {
pub fn keyboard(self) -> bool {
matches!(self, Surface::Tui | Surface::Repl)
}
}
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.",
)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Bang {
pub script: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Line<'a> {
Bang(Bang),
Prompt(&'a str),
}
pub fn parse(line: &str) -> Line<'_> {
let trimmed = line.trim_start();
let Some(rest) = trimmed.strip_prefix('!') else {
return Line::Prompt(line);
};
let script = match rest.strip_prefix('!') {
Some(after) => format!("!{after}"),
None => rest.to_string(),
};
Line::Bang(Bang {
script: script.trim().to_string(),
})
}
#[derive(Debug, Clone, Default)]
pub struct Ran {
pub output: String,
pub code: Option<i32>,
pub timed_out: bool,
pub truncated: bool,
pub refused: Option<String>,
}
impl Ran {
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
}
}
pub async fn run(script: &str, cwd: &Path, sandbox: &Sandbox) -> Ran {
run_within(script, cwd, sandbox, CEILING).await
}
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()
};
}
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)
.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()
}
}
};
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 {
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);
}
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(_) => {
let _ = child.start_kill();
let _ = child.wait().await;
Ran {
output: trim_trailing(&output),
timed_out: true,
truncated,
..Ran::default()
}
}
}
}
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,
}
}
#[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());
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()));
assert_eq!(script_of("! ls -la"), Some("ls -la".into()));
assert_eq!(script_of(" !pwd"), Some("pwd".into()));
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() {
assert_eq!(script_of("!!"), Some("!".into()));
assert_eq!(script_of("!!ls -la"), Some("!ls -la".into()));
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() {
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());
}
}