use crate::tools::{str_arg, CallScope, Tool, ToolError};
use async_trait::async_trait;
use serde_json::{json, Value};
use std::path::{Path, PathBuf};
use std::time::Duration;
const LANGUAGES: &[(&str, &str, &str)] = &[
("sh", "#!/bin/sh", "a.sh"),
("bash", "#!/usr/bin/env bash", "a.bash"),
("python", "#!/usr/bin/env python3", "a.py"),
("python3", "#!/usr/bin/env python3", "a.py"),
];
const DEFAULT_LANGUAGE: &str = "sh";
pub struct ExecuteCode {
dir: PathBuf,
workspace: PathBuf,
timeout: Duration,
max_bytes: usize,
kill_grace: Duration,
sandbox: crate::sandbox::Sandbox,
}
impl ExecuteCode {
pub fn new(
dir: PathBuf,
workspace: PathBuf,
timeout: Duration,
max_bytes: usize,
kill_grace: Duration,
) -> Self {
Self {
dir,
workspace,
timeout,
max_bytes,
kill_grace,
sandbox: crate::sandbox::Sandbox::off(),
}
}
pub fn with_sandbox(mut self, sandbox: crate::sandbox::Sandbox) -> Self {
self.sandbox = sandbox;
self
}
fn target(&self) -> PathBuf {
use std::time::{SystemTime, UNIX_EPOCH};
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0);
self.dir
.join(format!(".exec-{}-{nanos}.sh", std::process::id()))
}
}
fn script_text(language: &str, code: &str) -> Result<String, ToolError> {
let shebang = LANGUAGES
.iter()
.find(|(name, _, _)| name.eq_ignore_ascii_case(language))
.map(|(_, shebang, _)| *shebang)
.ok_or_else(|| {
ToolError::InvalidArgs(format!(
"unknown language {language:?}; this tool runs {}",
LANGUAGES
.iter()
.map(|(name, _, _)| *name)
.collect::<Vec<_>>()
.join(", ")
))
})?;
let mut text = String::with_capacity(shebang.len() + code.len() + 2);
text.push_str(shebang);
text.push('\n');
let body = code.trim_start_matches('\u{feff}');
let body = match body.strip_prefix("#!") {
Some(rest) => rest.split_once('\n').map(|(_, tail)| tail).unwrap_or(""),
None => body,
};
text.push_str(body);
if !text.ends_with('\n') {
text.push('\n');
}
Ok(text)
}
#[async_trait]
impl Tool for ExecuteCode {
fn name(&self) -> &str {
"execute_code"
}
fn description(&self) -> &str {
"Run a short program you write here, in a temporary file that is deleted afterwards. For \
work a loop does better than many tool calls: read forty files look for those that \
disagree, rename nine, compute something. The code can call any tool with `eclipse tool \
<name> '{json}'`, which goes through the same policy and approvals as a direct call. \
Use `script` instead when the program should exist again next time."
}
fn parameters(&self) -> Value {
json!({"type":"object","properties":{
"code":{"type":"string","description":"The program. A shebang is optional; the one for `language` is added."},
"language":{"type":"string","description":"sh (default), bash, python or python3."},
"args":{"type":"array","items":{"type":"string"},"description":"Arguments passed to the program."}
},"required":["code"]})
}
fn describe_call(&self, args: &Value) -> String {
let code = args["code"].as_str().unwrap_or("");
let language = args["language"].as_str().unwrap_or(DEFAULT_LANGUAGE);
let first = code
.lines()
.find(|l| !l.trim().is_empty() && !l.trim_start().starts_with('#'))
.unwrap_or("")
.trim();
let chars = code.chars().count();
format!(
"execute_code {language}: {} line(s), {chars} chars — {}{}",
code.lines().count(),
crate::tools::truncate(first.to_string(), 60),
if first.len() > 60 || code.lines().count() > 1 {
"…"
} else {
""
}
)
}
async fn call(&self, _args: Value) -> Result<String, ToolError> {
Err(ToolError::Failed(
"execute_code needs the registry, to answer the code's tool calls; it only runs \
inside a run"
.into(),
))
}
async fn call_scoped(&self, args: Value, scope: &CallScope<'_>) -> Result<String, ToolError> {
let code = str_arg(&args, "code")?;
if code.trim().is_empty() {
return Err(ToolError::InvalidArgs("`code` is empty".into()));
}
let language = args["language"].as_str().unwrap_or(DEFAULT_LANGUAGE);
let script_args: Vec<String> = args["args"]
.as_array()
.map(|items| {
items
.iter()
.filter_map(|v| v.as_str().map(str::to_string))
.collect()
})
.unwrap_or_default();
let text = script_text(language, code)?;
std::fs::create_dir_all(&self.dir)
.map_err(|e| ToolError::Failed(format!("cannot create {}: {e}", self.dir.display())))?;
let path = self.target();
write_private(&path, &text)?;
let argv: Vec<std::ffi::OsString> =
script_args.iter().map(std::ffi::OsString::from).collect();
let bridge = crate::tools_bridge::Bridge::bind()?;
let plan = self.sandbox.plan_with(
path.as_os_str(),
&argv,
&self.workspace,
&[bridge.dir().to_path_buf()],
);
let plan = match plan {
Ok(plan) => plan,
Err(why) => {
let _ = std::fs::remove_file(&path);
return Err(why);
}
};
let mut cmd = tokio::process::Command::new(&plan.program);
cmd.args(&plan.args);
cmd.current_dir(&self.workspace);
crate::tools_script::apply_env(&mut cmd, &self.dir);
let result = crate::tools_bridge::run_with_bridge(
cmd,
&bridge,
self.max_bytes,
self.timeout,
self.kill_grace,
scope,
)
.await;
let _ = std::fs::remove_file(&path);
result
}
}
fn write_private(path: &Path, text: &str) -> Result<(), ToolError> {
use std::io::Write;
let mut file = std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(path)
.map_err(|e| ToolError::Failed(format!("cannot create {}: {e}", path.display())))?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
file.set_permissions(std::fs::Permissions::from_mode(0o700))
.map_err(|e| {
ToolError::Failed(format!("cannot set mode on {}: {e}", path.display()))
})?;
}
file.write_all(text.as_bytes())
.map_err(|e| ToolError::Failed(format!("cannot write {}: {e}", path.display())))
}
#[cfg(test)]
mod tests {
use super::*;
fn tool(dir: &Path) -> ExecuteCode {
ExecuteCode::new(
dir.to_path_buf(),
dir.to_path_buf(),
Duration::from_secs(20),
64 * 1024,
Duration::from_millis(500),
)
}
fn scope<'a>(
registry: &'a crate::tools::ToolRegistry,
run: &'a crate::tools::RunScope,
approver: &'a dyn crate::tools::Approver,
) -> CallScope<'a> {
CallScope {
approver,
run,
registry,
call_id: None,
}
}
#[test]
fn the_shebang_comes_from_the_language_not_from_the_code() {
assert_eq!(
script_text("sh", "echo hi").unwrap(),
"#!/bin/sh\necho hi\n"
);
assert_eq!(
script_text("python", "print(1)").unwrap(),
"#!/usr/bin/env python3\nprint(1)\n"
);
assert_eq!(
script_text("sh", "#!/bin/bash\necho hi").unwrap(),
"#!/bin/sh\necho hi\n"
);
}
#[test]
fn an_unknown_language_is_refused_with_the_list_rather_than_guessed() {
let e = script_text("ruby", "puts 1").unwrap_err().to_string();
assert!(e.contains("unknown language"), "{e}");
assert!(e.contains("python3"), "the list is the fix: {e}");
}
#[tokio::test]
async fn code_runs_and_its_output_comes_back() {
let dir = tempfile::tempdir().unwrap();
let registry = crate::tools::ToolRegistry::new(4096);
let run = crate::tools::RunScope::default();
let s = scope(®istry, &run, &crate::tools::AllowAll);
let out = tool(dir.path())
.call_scoped(json!({"code": "echo hello from the code"}), &s)
.await
.unwrap();
assert!(out.contains("hello from the code"), "{out}");
assert!(out.contains("exit code: 0"), "{out}");
}
#[tokio::test]
async fn the_file_is_gone_afterwards() {
let dir = tempfile::tempdir().unwrap();
let registry = crate::tools::ToolRegistry::new(4096);
let run = crate::tools::RunScope::default();
let s = scope(®istry, &run, &crate::tools::AllowAll);
tool(dir.path())
.call_scoped(json!({"code": "true"}), &s)
.await
.unwrap();
let left: Vec<_> = std::fs::read_dir(dir.path()).unwrap().collect();
assert!(left.is_empty(), "{:?} left behind", left.len());
}
#[tokio::test]
async fn a_read_only_promise_without_bubblewrap_refuses_instead_of_running() {
let dir = tempfile::tempdir().unwrap();
let marker = dir.path().join("ran");
let registry = crate::tools::ToolRegistry::new(4096);
let run = crate::tools::RunScope::default();
let s = scope(®istry, &run, &crate::tools::AllowAll);
let e = tool(dir.path())
.with_sandbox(crate::sandbox::Sandbox::without_bwrap(
crate::config::ShellIsolate::Fs,
))
.call_scoped(json!({"code": format!("touch {}", marker.display())}), &s)
.await
.unwrap_err()
.to_string();
assert!(e.contains("which is not on PATH"), "{e}");
assert!(!marker.exists(), "the code must not have run");
let left: Vec<_> = std::fs::read_dir(dir.path()).unwrap().collect();
assert!(left.is_empty(), "{} left behind", left.len());
}
#[tokio::test]
async fn an_empty_program_is_refused_rather_than_run_for_nothing() {
let dir = tempfile::tempdir().unwrap();
let registry = crate::tools::ToolRegistry::new(4096);
let run = crate::tools::RunScope::default();
let s = scope(®istry, &run, &crate::tools::AllowAll);
let e = tool(dir.path())
.call_scoped(json!({"code": " "}), &s)
.await
.unwrap_err()
.to_string();
assert!(e.contains("empty"), "{e}");
}
}