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}
53
54impl ExecuteCode {
55 pub fn new(
56 dir: PathBuf,
57 workspace: PathBuf,
58 timeout: Duration,
59 max_bytes: usize,
60 kill_grace: Duration,
61 ) -> Self {
62 Self {
63 dir,
64 workspace,
65 timeout,
66 max_bytes,
67 kill_grace,
68 }
69 }
70
71 fn target(&self) -> PathBuf {
74 use std::time::{SystemTime, UNIX_EPOCH};
75 let nanos = SystemTime::now()
76 .duration_since(UNIX_EPOCH)
77 .map(|d| d.as_nanos())
78 .unwrap_or(0);
79 self.dir
80 .join(format!(".exec-{}-{nanos}.sh", std::process::id()))
81 }
82}
83
84fn script_text(language: &str, code: &str) -> Result<String, ToolError> {
86 let shebang = LANGUAGES
87 .iter()
88 .find(|(name, _, _)| name.eq_ignore_ascii_case(language))
89 .map(|(_, shebang, _)| *shebang)
90 .ok_or_else(|| {
91 ToolError::InvalidArgs(format!(
92 "unknown language {language:?}; this tool runs {}",
93 LANGUAGES
94 .iter()
95 .map(|(name, _, _)| *name)
96 .collect::<Vec<_>>()
97 .join(", ")
98 ))
99 })?;
100 let mut text = String::with_capacity(shebang.len() + code.len() + 2);
101 text.push_str(shebang);
102 text.push('\n');
103 let body = code.trim_start_matches('\u{feff}');
105 let body = match body.strip_prefix("#!") {
106 Some(rest) => rest.split_once('\n').map(|(_, tail)| tail).unwrap_or(""),
107 None => body,
108 };
109 text.push_str(body);
110 if !text.ends_with('\n') {
111 text.push('\n');
112 }
113 Ok(text)
114}
115
116#[async_trait]
117impl Tool for ExecuteCode {
118 fn name(&self) -> &str {
119 "execute_code"
120 }
121
122 fn description(&self) -> &str {
123 "Run a short program you write here, in a temporary file that is deleted afterwards. For \
124 work a loop does better than many tool calls: read forty files look for those that \
125 disagree, rename nine, compute something. The code can call any tool with `eclipse tool \
126 <name> '{json}'`, which goes through the same policy and approvals as a direct call. \
127 Use `script` instead when the program should exist again next time."
128 }
129
130 fn parameters(&self) -> Value {
131 json!({"type":"object","properties":{
132 "code":{"type":"string","description":"The program. A shebang is optional; the one for `language` is added."},
133 "language":{"type":"string","description":"sh (default), bash, python or python3."},
134 "args":{"type":"array","items":{"type":"string"},"description":"Arguments passed to the program."}
135 },"required":["code"]})
136 }
137
138 fn describe_call(&self, args: &Value) -> String {
139 let code = args["code"].as_str().unwrap_or("");
140 let language = args["language"].as_str().unwrap_or(DEFAULT_LANGUAGE);
141 let first = code
142 .lines()
143 .find(|l| !l.trim().is_empty() && !l.trim_start().starts_with('#'))
144 .unwrap_or("")
145 .trim();
146 let chars = code.chars().count();
147 format!(
148 "execute_code {language}: {} line(s), {chars} chars — {}{}",
149 code.lines().count(),
150 crate::tools::truncate(first.to_string(), 60),
151 if first.len() > 60 || code.lines().count() > 1 {
152 "…"
153 } else {
154 ""
155 }
156 )
157 }
158
159 async fn call(&self, _args: Value) -> Result<String, ToolError> {
160 Err(ToolError::Failed(
161 "execute_code needs the registry, to answer the code's tool calls; it only runs \
162 inside a run"
163 .into(),
164 ))
165 }
166
167 async fn call_scoped(&self, args: Value, scope: &CallScope<'_>) -> Result<String, ToolError> {
168 let code = str_arg(&args, "code")?;
169 if code.trim().is_empty() {
170 return Err(ToolError::InvalidArgs("`code` is empty".into()));
171 }
172 let language = args["language"].as_str().unwrap_or(DEFAULT_LANGUAGE);
173 let script_args: Vec<String> = args["args"]
174 .as_array()
175 .map(|items| {
176 items
177 .iter()
178 .filter_map(|v| v.as_str().map(str::to_string))
179 .collect()
180 })
181 .unwrap_or_default();
182 let text = script_text(language, code)?;
183
184 std::fs::create_dir_all(&self.dir)
185 .map_err(|e| ToolError::Failed(format!("cannot create {}: {e}", self.dir.display())))?;
186 let path = self.target();
187 write_private(&path, &text)?;
188
189 let mut cmd = tokio::process::Command::from(crate::tools_script::command(
190 &self.dir,
191 &path,
192 &script_args,
193 ));
194 cmd.current_dir(&self.workspace);
195 let result = crate::tools_bridge::run_with_bridge(
196 cmd,
197 self.max_bytes,
198 self.timeout,
199 self.kill_grace,
200 scope,
201 )
202 .await;
203 let _ = std::fs::remove_file(&path);
206 result
207 }
208}
209
210fn write_private(path: &Path, text: &str) -> Result<(), ToolError> {
213 use std::io::Write;
214 let mut file = std::fs::OpenOptions::new()
215 .write(true)
216 .create_new(true)
217 .open(path)
218 .map_err(|e| ToolError::Failed(format!("cannot create {}: {e}", path.display())))?;
219 #[cfg(unix)]
220 {
221 use std::os::unix::fs::PermissionsExt;
222 file.set_permissions(std::fs::Permissions::from_mode(0o700))
223 .map_err(|e| {
224 ToolError::Failed(format!("cannot set mode on {}: {e}", path.display()))
225 })?;
226 }
227 file.write_all(text.as_bytes())
228 .map_err(|e| ToolError::Failed(format!("cannot write {}: {e}", path.display())))
229}
230
231#[cfg(test)]
232mod tests {
233 use super::*;
234
235 fn tool(dir: &Path) -> ExecuteCode {
236 ExecuteCode::new(
237 dir.to_path_buf(),
238 dir.to_path_buf(),
239 Duration::from_secs(20),
240 64 * 1024,
241 Duration::from_millis(500),
242 )
243 }
244
245 fn scope<'a>(
246 registry: &'a crate::tools::ToolRegistry,
247 run: &'a crate::tools::RunScope,
248 approver: &'a dyn crate::tools::Approver,
249 ) -> CallScope<'a> {
250 CallScope {
251 approver,
252 run,
253 registry,
254 call_id: None,
255 }
256 }
257
258 #[test]
259 fn the_shebang_comes_from_the_language_not_from_the_code() {
260 assert_eq!(
261 script_text("sh", "echo hi").unwrap(),
262 "#!/bin/sh\necho hi\n"
263 );
264 assert_eq!(
265 script_text("python", "print(1)").unwrap(),
266 "#!/usr/bin/env python3\nprint(1)\n"
267 );
268 assert_eq!(
270 script_text("sh", "#!/bin/bash\necho hi").unwrap(),
271 "#!/bin/sh\necho hi\n"
272 );
273 }
274
275 #[test]
276 fn an_unknown_language_is_refused_with_the_list_rather_than_guessed() {
277 let e = script_text("ruby", "puts 1").unwrap_err().to_string();
278 assert!(e.contains("unknown language"), "{e}");
279 assert!(e.contains("python3"), "the list is the fix: {e}");
280 }
281
282 #[tokio::test]
283 async fn code_runs_and_its_output_comes_back() {
284 let dir = tempfile::tempdir().unwrap();
285 let registry = crate::tools::ToolRegistry::new(4096);
286 let run = crate::tools::RunScope::default();
287 let s = scope(®istry, &run, &crate::tools::AllowAll);
288 let out = tool(dir.path())
289 .call_scoped(json!({"code": "echo hello from the code"}), &s)
290 .await
291 .unwrap();
292 assert!(out.contains("hello from the code"), "{out}");
293 assert!(out.contains("exit code: 0"), "{out}");
294 }
295
296 #[tokio::test]
297 async fn the_file_is_gone_afterwards() {
298 let dir = tempfile::tempdir().unwrap();
299 let registry = crate::tools::ToolRegistry::new(4096);
300 let run = crate::tools::RunScope::default();
301 let s = scope(®istry, &run, &crate::tools::AllowAll);
302 tool(dir.path())
303 .call_scoped(json!({"code": "true"}), &s)
304 .await
305 .unwrap();
306 let left: Vec<_> = std::fs::read_dir(dir.path()).unwrap().collect();
307 assert!(left.is_empty(), "{:?} left behind", left.len());
308 }
309
310 #[tokio::test]
311 async fn an_empty_program_is_refused_rather_than_run_for_nothing() {
312 let dir = tempfile::tempdir().unwrap();
313 let registry = crate::tools::ToolRegistry::new(4096);
314 let run = crate::tools::RunScope::default();
315 let s = scope(®istry, &run, &crate::tools::AllowAll);
316 let e = tool(dir.path())
317 .call_scoped(json!({"code": " "}), &s)
318 .await
319 .unwrap_err()
320 .to_string();
321 assert!(e.contains("empty"), "{e}");
322 }
323}