Skip to main content

eclipse_core/
tools_exec.rs

1//! The `execute_code` tool: code the model writes for one job and does not keep.
2//!
3//! `script` is for a program that earns a name — a workflow run again next week. `execute_code`
4//! is for the other half: read these forty files and tell me which disagree, rename nine things,
5//! compute a checksum. Making the model name it, write it, `chmod` it and delete it is four calls
6//! and a directory it has to clean up; here it is one call that leaves nothing behind.
7//!
8//! **The code is a file, not an eval loop.** It is written to the scripts directory (which is
9//! already the one place the agent may write an executable, mode 0700 while it exists) and run
10//! through the same process path as `script`: same timeout, same process-group kill, same output
11//! cap. The name is generated and the file removed afterwards, so a `execute_code` cannot collide
12//! with a real script's name — and cannot be called again by name, which is the difference
13//! between it and `script`.
14//!
15//! What it can *reach* is the point: the run has a tool bridge ([`crate::tools_bridge`]), so the
16//! code can call `eclipse tool patch '{…}'` and the call is dispatched through the registry like
17//! any other. A hundred edits can be a shell loop instead of a hundred round trips, each of which
18//! would re-send the conversation.
19
20use crate::tools::{str_arg, CallScope, Tool, ToolError};
21use async_trait::async_trait;
22use serde_json::{json, Value};
23use std::path::{Path, PathBuf};
24use std::time::Duration;
25
26/// Languages this tool will run, and the shebang each becomes.
27///
28/// A closed list, deliberately. The model names a language it knows rather than inventing an
29/// interpreter path, and an unknown name is refused with the list rather than guessed at — the
30/// one guess that would be a privilege escalation is "run this file with whatever it says".
31const LANGUAGES: &[(&str, &str, &str)] = &[
32    ("sh", "#!/bin/sh", "a.sh"),
33    ("bash", "#!/usr/bin/env bash", "a.bash"),
34    ("python", "#!/usr/bin/env python3", "a.py"),
35    ("python3", "#!/usr/bin/env python3", "a.py"),
36];
37
38/// The default when `language` is not given: the one interpreter a Unix host is certain to have.
39const DEFAULT_LANGUAGE: &str = "sh";
40
41pub struct ExecuteCode {
42    /// Where the temporary file goes: the scripts directory, the one place the agent may put an
43    /// executable.
44    dir: PathBuf,
45    /// Where the program *runs*, which is the workspace. `script` runs from its own directory
46    /// because a script addresses its neighbours; inline code addresses the user's project, and
47    /// a program that quietly wrote `notes.txt` into a config directory would be a surprise.
48    workspace: PathBuf,
49    timeout: Duration,
50    max_bytes: usize,
51    kill_grace: Duration,
52    /// The policy `shell` enforces, so code the agent writes runs under the same containment
53    /// (#550). `off` until a registry hands in the profile's own sandbox.
54    sandbox: crate::sandbox::Sandbox,
55}
56
57impl ExecuteCode {
58    pub fn new(
59        dir: PathBuf,
60        workspace: PathBuf,
61        timeout: Duration,
62        max_bytes: usize,
63        kill_grace: Duration,
64    ) -> Self {
65        Self {
66            dir,
67            workspace,
68            timeout,
69            max_bytes,
70            kill_grace,
71            sandbox: crate::sandbox::Sandbox::off(),
72        }
73    }
74
75    /// Run this tool's code under the same sandbox the `shell` tool got (#550).
76    pub fn with_sandbox(mut self, sandbox: crate::sandbox::Sandbox) -> Self {
77        self.sandbox = sandbox;
78        self
79    }
80
81    /// Where the file goes, and what to call it. A generated name so that two runs cannot
82    /// collide and so that the leftovers of a killed run cannot be mistaken for a script.
83    fn target(&self) -> PathBuf {
84        use std::time::{SystemTime, UNIX_EPOCH};
85        let nanos = SystemTime::now()
86            .duration_since(UNIX_EPOCH)
87            .map(|d| d.as_nanos())
88            .unwrap_or(0);
89        self.dir
90            .join(format!(".exec-{}-{nanos}.sh", std::process::id()))
91    }
92}
93
94/// The file to run: the shebang for `language`, then the code, ending in a newline.
95fn script_text(language: &str, code: &str) -> Result<String, ToolError> {
96    let shebang = LANGUAGES
97        .iter()
98        .find(|(name, _, _)| name.eq_ignore_ascii_case(language))
99        .map(|(_, shebang, _)| *shebang)
100        .ok_or_else(|| {
101            ToolError::InvalidArgs(format!(
102                "unknown language {language:?}; this tool runs {}",
103                LANGUAGES
104                    .iter()
105                    .map(|(name, _, _)| *name)
106                    .collect::<Vec<_>>()
107                    .join(", ")
108            ))
109        })?;
110    let mut text = String::with_capacity(shebang.len() + code.len() + 2);
111    text.push_str(shebang);
112    text.push('\n');
113    // A `#!` the caller wrote is not repeated: the shebang above is the one that runs.
114    let body = code.trim_start_matches('\u{feff}');
115    let body = match body.strip_prefix("#!") {
116        Some(rest) => rest.split_once('\n').map(|(_, tail)| tail).unwrap_or(""),
117        None => body,
118    };
119    text.push_str(body);
120    if !text.ends_with('\n') {
121        text.push('\n');
122    }
123    Ok(text)
124}
125
126#[async_trait]
127impl Tool for ExecuteCode {
128    fn name(&self) -> &str {
129        "execute_code"
130    }
131
132    fn description(&self) -> &str {
133        "Run a short program you write here, in a temporary file that is deleted afterwards. For \
134         work a loop does better than many tool calls: read forty files look for those that \
135         disagree, rename nine, compute something. The code can call any tool with `eclipse tool \
136         <name> '{json}'`, which goes through the same policy and approvals as a direct call. \
137         Use `script` instead when the program should exist again next time."
138    }
139
140    fn parameters(&self) -> Value {
141        json!({"type":"object","properties":{
142            "code":{"type":"string","description":"The program. A shebang is optional; the one for `language` is added."},
143            "language":{"type":"string","description":"sh (default), bash, python or python3."},
144            "args":{"type":"array","items":{"type":"string"},"description":"Arguments passed to the program."}
145        },"required":["code"]})
146    }
147
148    fn describe_call(&self, args: &Value) -> String {
149        let code = args["code"].as_str().unwrap_or("");
150        let language = args["language"].as_str().unwrap_or(DEFAULT_LANGUAGE);
151        let first = code
152            .lines()
153            .find(|l| !l.trim().is_empty() && !l.trim_start().starts_with('#'))
154            .unwrap_or("")
155            .trim();
156        let chars = code.chars().count();
157        format!(
158            "execute_code {language}: {} line(s), {chars} chars — {}{}",
159            code.lines().count(),
160            crate::tools::truncate(first.to_string(), 60),
161            if first.len() > 60 || code.lines().count() > 1 {
162                "…"
163            } else {
164                ""
165            }
166        )
167    }
168
169    async fn call(&self, _args: Value) -> Result<String, ToolError> {
170        Err(ToolError::Failed(
171            "execute_code needs the registry, to answer the code's tool calls; it only runs \
172             inside a run"
173                .into(),
174        ))
175    }
176
177    async fn call_scoped(&self, args: Value, scope: &CallScope<'_>) -> Result<String, ToolError> {
178        let code = str_arg(&args, "code")?;
179        if code.trim().is_empty() {
180            return Err(ToolError::InvalidArgs("`code` is empty".into()));
181        }
182        let language = args["language"].as_str().unwrap_or(DEFAULT_LANGUAGE);
183        let script_args: Vec<String> = args["args"]
184            .as_array()
185            .map(|items| {
186                items
187                    .iter()
188                    .filter_map(|v| v.as_str().map(str::to_string))
189                    .collect()
190            })
191            .unwrap_or_default();
192        let text = script_text(language, code)?;
193
194        std::fs::create_dir_all(&self.dir)
195            .map_err(|e| ToolError::Failed(format!("cannot create {}: {e}", self.dir.display())))?;
196        let path = self.target();
197        write_private(&path, &text)?;
198
199        // The same policy `shell` gets, planned against the directory the code will run in
200        // (#550): under `fs` this either wraps the run in bubblewrap or refuses, and under
201        // `process` it scopes the process tree. A retry after `ETXTBSY` rebuilds this plan.
202        let argv: Vec<std::ffi::OsString> =
203            script_args.iter().map(std::ffi::OsString::from).collect();
204        // The bridge is bound before the plan so the run can mount its directory: under
205        // `shell_isolate = "fs"` the child gets a fresh `/tmp` and would not see it (#550).
206        let bridge = crate::tools_bridge::Bridge::bind()?;
207        let plan = self.sandbox.plan_with(
208            path.as_os_str(),
209            &argv,
210            &self.workspace,
211            &[bridge.dir().to_path_buf()],
212        );
213        let plan = match plan {
214            Ok(plan) => plan,
215            Err(why) => {
216                // The temp file is removed either way: the next call gets a fresh name, and a
217                // refusal must not leave an executable behind.
218                let _ = std::fs::remove_file(&path);
219                return Err(why);
220            }
221        };
222        let mut cmd = tokio::process::Command::new(&plan.program);
223        cmd.args(&plan.args);
224        cmd.current_dir(&self.workspace);
225        crate::tools_script::apply_env(&mut cmd, &self.dir);
226        let result = crate::tools_bridge::run_with_bridge(
227            cmd,
228            &bridge,
229            self.max_bytes,
230            self.timeout,
231            self.kill_grace,
232            scope,
233        )
234        .await;
235        // Removed whether or not it ran: the point of this tool over `script` is that nothing is
236        // left behind for the next listing to describe.
237        let _ = std::fs::remove_file(&path);
238        result
239    }
240}
241
242/// Write an executable that nobody else can read. Mode 0700 from the moment it exists: `write`
243/// then `chmod` leaves a window in which the file is world-readable.
244fn write_private(path: &Path, text: &str) -> Result<(), ToolError> {
245    use std::io::Write;
246    let mut file = std::fs::OpenOptions::new()
247        .write(true)
248        .create_new(true)
249        .open(path)
250        .map_err(|e| ToolError::Failed(format!("cannot create {}: {e}", path.display())))?;
251    #[cfg(unix)]
252    {
253        use std::os::unix::fs::PermissionsExt;
254        file.set_permissions(std::fs::Permissions::from_mode(0o700))
255            .map_err(|e| {
256                ToolError::Failed(format!("cannot set mode on {}: {e}", path.display()))
257            })?;
258    }
259    file.write_all(text.as_bytes())
260        .map_err(|e| ToolError::Failed(format!("cannot write {}: {e}", path.display())))
261}
262
263#[cfg(test)]
264mod tests {
265    use super::*;
266
267    fn tool(dir: &Path) -> ExecuteCode {
268        ExecuteCode::new(
269            dir.to_path_buf(),
270            dir.to_path_buf(),
271            Duration::from_secs(20),
272            64 * 1024,
273            Duration::from_millis(500),
274        )
275    }
276
277    fn scope<'a>(
278        registry: &'a crate::tools::ToolRegistry,
279        run: &'a crate::tools::RunScope,
280        approver: &'a dyn crate::tools::Approver,
281    ) -> CallScope<'a> {
282        CallScope {
283            approver,
284            run,
285            registry,
286            call_id: None,
287        }
288    }
289
290    #[test]
291    fn the_shebang_comes_from_the_language_not_from_the_code() {
292        assert_eq!(
293            script_text("sh", "echo hi").unwrap(),
294            "#!/bin/sh\necho hi\n"
295        );
296        assert_eq!(
297            script_text("python", "print(1)").unwrap(),
298            "#!/usr/bin/env python3\nprint(1)\n"
299        );
300        // A shebang the caller wrote is not repeated: one interpreter, the one we chose.
301        assert_eq!(
302            script_text("sh", "#!/bin/bash\necho hi").unwrap(),
303            "#!/bin/sh\necho hi\n"
304        );
305    }
306
307    #[test]
308    fn an_unknown_language_is_refused_with_the_list_rather_than_guessed() {
309        let e = script_text("ruby", "puts 1").unwrap_err().to_string();
310        assert!(e.contains("unknown language"), "{e}");
311        assert!(e.contains("python3"), "the list is the fix: {e}");
312    }
313
314    #[tokio::test]
315    async fn code_runs_and_its_output_comes_back() {
316        let dir = tempfile::tempdir().unwrap();
317        let registry = crate::tools::ToolRegistry::new(4096);
318        let run = crate::tools::RunScope::default();
319        let s = scope(&registry, &run, &crate::tools::AllowAll);
320        let out = tool(dir.path())
321            .call_scoped(json!({"code": "echo hello from the code"}), &s)
322            .await
323            .unwrap();
324        assert!(out.contains("hello from the code"), "{out}");
325        assert!(out.contains("exit code: 0"), "{out}");
326    }
327
328    #[tokio::test]
329    async fn the_file_is_gone_afterwards() {
330        let dir = tempfile::tempdir().unwrap();
331        let registry = crate::tools::ToolRegistry::new(4096);
332        let run = crate::tools::RunScope::default();
333        let s = scope(&registry, &run, &crate::tools::AllowAll);
334        tool(dir.path())
335            .call_scoped(json!({"code": "true"}), &s)
336            .await
337            .unwrap();
338        let left: Vec<_> = std::fs::read_dir(dir.path()).unwrap().collect();
339        assert!(left.is_empty(), "{:?} left behind", left.len());
340    }
341
342    #[tokio::test]
343    async fn a_read_only_promise_without_bubblewrap_refuses_instead_of_running() {
344        // The same axis as `shell`: `fs` without bubblewrap must refuse, because a read-only
345        // promise kept halfway is a lie about the machine. `execute_code` never saw the sandbox,
346        // so it ran the code anyway (#550).
347        let dir = tempfile::tempdir().unwrap();
348        let marker = dir.path().join("ran");
349        let registry = crate::tools::ToolRegistry::new(4096);
350        let run = crate::tools::RunScope::default();
351        let s = scope(&registry, &run, &crate::tools::AllowAll);
352        let e = tool(dir.path())
353            .with_sandbox(crate::sandbox::Sandbox::without_bwrap(
354                crate::config::ShellIsolate::Fs,
355            ))
356            .call_scoped(json!({"code": format!("touch {}", marker.display())}), &s)
357            .await
358            .unwrap_err()
359            .to_string();
360        assert!(e.contains("which is not on PATH"), "{e}");
361        assert!(!marker.exists(), "the code must not have run");
362        // And the refusal leaves no executable behind, because the next call gets a new name.
363        let left: Vec<_> = std::fs::read_dir(dir.path()).unwrap().collect();
364        assert!(left.is_empty(), "{} left behind", left.len());
365    }
366
367    #[tokio::test]
368    async fn an_empty_program_is_refused_rather_than_run_for_nothing() {
369        let dir = tempfile::tempdir().unwrap();
370        let registry = crate::tools::ToolRegistry::new(4096);
371        let run = crate::tools::RunScope::default();
372        let s = scope(&registry, &run, &crate::tools::AllowAll);
373        let e = tool(dir.path())
374            .call_scoped(json!({"code": "   "}), &s)
375            .await
376            .unwrap_err()
377            .to_string();
378        assert!(e.contains("empty"), "{e}");
379    }
380}