eclipse-core 0.13.1

Core library for eclipse: providers, tools, sessions, config, runtime
Documentation
//! The `execute_code` tool: code the model writes for one job and does not keep.
//!
//! `script` is for a program that earns a name — a workflow run again next week. `execute_code`
//! is for the other half: read these forty files and tell me which disagree, rename nine things,
//! compute a checksum. Making the model name it, write it, `chmod` it and delete it is four calls
//! and a directory it has to clean up; here it is one call that leaves nothing behind.
//!
//! **The code is a file, not an eval loop.** It is written to the scripts directory (which is
//! already the one place the agent may write an executable, mode 0700 while it exists) and run
//! through the same process path as `script`: same timeout, same process-group kill, same output
//! cap. The name is generated and the file removed afterwards, so a `execute_code` cannot collide
//! with a real script's name — and cannot be called again by name, which is the difference
//! between it and `script`.
//!
//! What it can *reach* is the point: the run has a tool bridge ([`crate::tools_bridge`]), so the
//! code can call `eclipse tool patch '{…}'` and the call is dispatched through the registry like
//! any other. A hundred edits can be a shell loop instead of a hundred round trips, each of which
//! would re-send the conversation.

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;

/// Languages this tool will run, and the shebang each becomes.
///
/// A closed list, deliberately. The model names a language it knows rather than inventing an
/// interpreter path, and an unknown name is refused with the list rather than guessed at — the
/// one guess that would be a privilege escalation is "run this file with whatever it says".
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"),
];

/// The default when `language` is not given: the one interpreter a Unix host is certain to have.
const DEFAULT_LANGUAGE: &str = "sh";

pub struct ExecuteCode {
    /// Where the temporary file goes: the scripts directory, the one place the agent may put an
    /// executable.
    dir: PathBuf,
    /// Where the program *runs*, which is the workspace. `script` runs from its own directory
    /// because a script addresses its neighbours; inline code addresses the user's project, and
    /// a program that quietly wrote `notes.txt` into a config directory would be a surprise.
    workspace: PathBuf,
    timeout: Duration,
    max_bytes: usize,
    kill_grace: Duration,
}

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,
        }
    }

    /// Where the file goes, and what to call it. A generated name so that two runs cannot
    /// collide and so that the leftovers of a killed run cannot be mistaken for a script.
    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()))
    }
}

/// The file to run: the shebang for `language`, then the code, ending in a newline.
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');
    // A `#!` the caller wrote is not repeated: the shebang above is the one that runs.
    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 mut cmd = tokio::process::Command::from(crate::tools_script::command(
            &self.dir,
            &path,
            &script_args,
        ));
        cmd.current_dir(&self.workspace);
        let result = crate::tools_bridge::run_with_bridge(
            cmd,
            self.max_bytes,
            self.timeout,
            self.kill_grace,
            scope,
        )
        .await;
        // Removed whether or not it ran: the point of this tool over `script` is that nothing is
        // left behind for the next listing to describe.
        let _ = std::fs::remove_file(&path);
        result
    }
}

/// Write an executable that nobody else can read. Mode 0700 from the moment it exists: `write`
/// then `chmod` leaves a window in which the file is world-readable.
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"
        );
        // A shebang the caller wrote is not repeated: one interpreter, the one we chose.
        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(&registry, &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(&registry, &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 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(&registry, &run, &crate::tools::AllowAll);
        let e = tool(dir.path())
            .call_scoped(json!({"code": "   "}), &s)
            .await
            .unwrap_err()
            .to_string();
        assert!(e.contains("empty"), "{e}");
    }
}