hematite/tools/
code_sandbox.rs1use serde_json::Value;
9use std::io::Write;
10use std::process::{Command, Stdio};
11use std::time::Duration;
12
13const DEFAULT_TIMEOUT_SECS: u64 = 10;
14const MAX_TIMEOUT_SECS: u64 = 60;
15const MAX_OUTPUT_BYTES: usize = 16_384; pub async fn execute(args: &Value) -> Result<String, String> {
18 let language = args
19 .get("language")
20 .and_then(|v| v.as_str())
21 .unwrap_or("javascript")
22 .to_lowercase();
23
24 let code = args
25 .get("code")
26 .and_then(|v| v.as_str())
27 .ok_or("Missing required argument: 'code'")?;
28
29 let timeout_secs = args
30 .get("timeout_seconds")
31 .and_then(|v| v.as_u64())
32 .unwrap_or(DEFAULT_TIMEOUT_SECS)
33 .min(MAX_TIMEOUT_SECS);
34
35 match language.as_str() {
36 "javascript" | "typescript" | "js" | "ts" => run_deno(code, timeout_secs),
37 "python" | "python3" | "py" => run_python(code, timeout_secs),
38 other => Err(format!(
39 "Unsupported language: '{}'. Supported: javascript, typescript, python.",
40 other
41 )),
42 }
43}
44
45fn run_deno(code: &str, timeout_secs: u64) -> Result<String, String> {
48 let deno = find_deno().ok_or_else(|| {
49 "Deno not found. Hematite checks (in order): settings.json `deno_path`, \
50 LM Studio's bundled copy (~/.lmstudio/.internal/utils/deno.exe), system PATH. \
51 To install Deno globally: `winget install DenoLand.Deno` (Windows) or see https://deno.com. \
52 Or set `deno_path` in .hematite/settings.json to point to any Deno binary."
53 .to_string()
54 })?;
55
56 let mut child = Command::new(&deno)
57 .args([
58 "run",
59 "--allow-read=.", "--allow-write=.", "--deny-net", "--deny-sys", "--deny-env", "--deny-run", "--deny-ffi", "--no-prompt", "-", ])
69 .env("NO_COLOR", "true") .stdin(Stdio::piped())
71 .stdout(Stdio::piped())
72 .stderr(Stdio::piped())
73 .spawn()
74 .map_err(|e| format!("Failed to spawn Deno: {e}"))?;
75
76 write_stdin(&mut child, code)?;
77 collect_output(child, "deno", timeout_secs)
78}
79
80fn run_python(code: &str, timeout_secs: u64) -> Result<String, String> {
84 let python = find_python().ok_or_else(|| {
85 "Python not found. Hematite checks (in order): settings.json `python_path`, \
86 system PATH (python3, python), and 'py' launcher on Windows. \
87 To install Python: https://python.org or `winget install Python.Python.3`. \
88 Or set `python_path` in .hematite/settings.json to point to any Python binary."
89 .to_string()
90 })?;
91
92 let mut cmd = Command::new(&python);
93 if python == "py" {
94 cmd.arg("-3");
95 }
96 let child = cmd
97 .args([
98 "-c",
99 &wrap_python(code),
101 ])
102 .stdin(Stdio::null())
103 .stdout(Stdio::piped())
104 .stderr(Stdio::piped())
105 .env("PATH", "")
106 .env("PYTHONDONTWRITEBYTECODE", "1")
107 .env("PYTHONIOENCODING", "utf-8")
108 .spawn()
109 .map_err(|e| format!("Failed to spawn Python: {e}"))?;
110
111 collect_output(child, "python", timeout_secs)
112}
113
114fn wrap_python(code: &str) -> String {
117 format!(
118 r#"
119import sys
120
121# Block network access
122import socket as _socket
123_socket.socket = None # type: ignore
124
125# Block subprocess and os.system
126import os as _os
127_os.system = lambda *a, **k: (_ for _ in ()).throw(PermissionError("os.system blocked in sandbox"))
128_popen_orig = _os.popen
129_os.popen = lambda *a, **k: (_ for _ in ()).throw(PermissionError("os.popen blocked in sandbox"))
130
131# Block __import__ for subprocess
132_real_import = __builtins__.__import__ if hasattr(__builtins__, '__import__') else __import__
133def _safe_import(name, *args, **kwargs):
134 if name in ('subprocess', 'multiprocessing', 'pty', 'telnetlib', 'ftplib', 'smtplib', 'http', 'urllib', 'requests', 'httpx'):
135 raise ImportError(f"Module '{{name}}' is blocked in the sandbox.")
136 return _real_import(name, *args, **kwargs)
137import builtins
138builtins.__import__ = _safe_import
139
140# Run the actual code
141try:
142 exec(compile(r"""{code}""", "<sandbox>", "exec"))
143except Exception as e:
144 print(f"\nSandbox Execution Error: {{e}}", file=sys.stderr)
145 sys.exit(1)
146"#,
147 code = code.replace(r#"""""#, r#"\" \" \""#)
148 )
149}
150
151fn write_stdin(child: &mut std::process::Child, code: &str) -> Result<(), String> {
152 let mut stdin = child
153 .stdin
154 .take()
155 .ok_or("Failed to open stdin for sandbox process")?;
156 stdin
157 .write_all(code.as_bytes())
158 .map_err(|e| format!("Failed to write to sandbox stdin: {e}"))?;
159 drop(stdin); Ok(())
161}
162
163fn collect_output(
164 child: std::process::Child,
165 runtime: &str,
166 timeout_secs: u64,
167) -> Result<String, String> {
168 let timeout = Duration::from_secs(timeout_secs);
169 let start = std::time::Instant::now();
170
171 let output = std::thread::scope(|s| {
173 let handle = s.spawn(|| child.wait_with_output());
174 loop {
175 if start.elapsed() >= timeout {
176 return Err(format!(
177 "Sandbox timeout: process exceeded {}s and was killed.",
178 timeout_secs
179 ));
180 }
181 std::thread::sleep(Duration::from_millis(50));
182 if handle.is_finished() {
183 return handle
184 .join()
185 .map_err(|_| "Sandbox thread panicked.".to_string())?
186 .map_err(|e| format!("Failed to collect {runtime} output: {e}"));
187 }
188 }
189 })?;
190
191 let stdout = truncate(
192 &String::from_utf8_lossy(&output.stdout),
193 MAX_OUTPUT_BYTES / 2,
194 );
195 let stderr = truncate(
196 &String::from_utf8_lossy(&output.stderr),
197 MAX_OUTPUT_BYTES / 2,
198 );
199
200 if output.status.success() {
201 if stdout.trim().is_empty() && stderr.trim().is_empty() {
202 Ok("(no output)".to_string())
203 } else if stderr.trim().is_empty() {
204 Ok(stdout)
205 } else {
206 Ok(format!("{stdout}\n[stderr]\n{stderr}"))
207 }
208 } else {
209 let code = output
210 .status
211 .code()
212 .map(|c| c.to_string())
213 .unwrap_or_else(|| "?".to_string());
214 Err(format!(
215 "Exit code {code}\n{}\n{}",
216 stdout.trim(),
217 stderr.trim()
218 ))
219 }
220}
221
222fn truncate(s: &str, max: usize) -> String {
223 if s.len() <= max {
224 s.to_string()
225 } else {
226 format!("{}\n... [truncated]", &s[..max])
227 }
228}
229
230fn find_deno() -> Option<String> {
237 let config = crate::agent::config::load_config();
238 if let Some(path) = config.deno_path {
239 if std::path::Path::new(&path).exists() {
240 return Some(path);
241 }
242 }
243
244 let exe = if cfg!(windows) { "deno.exe" } else { "deno" };
245
246 if let Ok(home) = std::env::var("USERPROFILE").or_else(|_| std::env::var("HOME")) {
248 let standard = std::path::Path::new(&home)
249 .join(".deno")
250 .join("bin")
251 .join(exe);
252 if standard.exists() {
253 return Some(standard.to_string_lossy().into_owned());
254 }
255 }
256
257 if cfg!(windows) {
260 if let Ok(local_app) = std::env::var("LOCALAPPDATA") {
261 let winget_base = std::path::Path::new(&local_app)
262 .join("Microsoft")
263 .join("WinGet")
264 .join("Packages");
265 if let Ok(entries) = std::fs::read_dir(&winget_base) {
266 for entry in entries.flatten() {
267 let name = entry.file_name();
268 if name.to_string_lossy().starts_with("DenoLand.Deno") {
269 let candidate = entry.path().join("deno.exe");
270 if candidate.exists() {
271 return Some(candidate.to_string_lossy().into_owned());
272 }
273 }
274 }
275 }
276 }
277 }
278
279 let check = if cfg!(windows) {
281 Command::new("where").arg("deno").output()
282 } else {
283 Command::new("which").arg("deno").output()
284 };
285 if let Ok(out) = check {
286 if out.status.success() {
287 let resolved = String::from_utf8_lossy(&out.stdout)
289 .trim()
290 .lines()
291 .next()
292 .unwrap_or("deno")
293 .to_string();
294 return Some(resolved);
295 }
296 }
297
298 find_lmstudio_deno()
300}
301
302fn find_python() -> Option<String> {
303 let config = crate::agent::config::load_config();
304 if let Some(path) = config.python_path {
305 if std::path::Path::new(&path).exists() {
306 return Some(path);
307 }
308 }
309 find_executable(&["python3", "python", "py"])
310}
311
312fn find_executable(candidates: &[&str]) -> Option<String> {
314 for name in candidates {
315 let check = if cfg!(windows) {
316 Command::new("where").arg(name).output()
317 } else {
318 Command::new("which").arg(name).output()
319 };
320 if check.map(|o| o.status.success()).unwrap_or(false) {
321 return Some(name.to_string());
322 }
323 }
324 None
325}
326
327fn find_lmstudio_deno() -> Option<String> {
330 let home = std::env::var("USERPROFILE")
331 .or_else(|_| std::env::var("HOME"))
332 .ok()?;
333
334 let exe = if cfg!(windows) { "deno.exe" } else { "deno" };
335 let path = std::path::Path::new(&home)
336 .join(".lmstudio")
337 .join(".internal")
338 .join("utils")
339 .join(exe);
340
341 if path.exists() {
342 Some(path.to_string_lossy().into_owned())
343 } else {
344 None
345 }
346}