1use 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
26const 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
38const DEFAULT_LANGUAGE: &str = "sh";
40
41pub struct ExecuteCode {
42 dir: PathBuf,
45 workspace: PathBuf,
49 timeout: Duration,
50 max_bytes: usize,
51 kill_grace: Duration,
52 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 pub fn with_sandbox(mut self, sandbox: crate::sandbox::Sandbox) -> Self {
77 self.sandbox = sandbox;
78 self
79 }
80
81 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
94fn 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 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 let argv: Vec<std::ffi::OsString> =
203 script_args.iter().map(std::ffi::OsString::from).collect();
204 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 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 let _ = std::fs::remove_file(&path);
238 result
239 }
240}
241
242fn 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 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(®istry, &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(®istry, &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 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(®istry, &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 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(®istry, &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}