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 mut builder = cmd.args([
100 "-c",
101 &wrap_python(code),
103 ]);
104 builder = builder
105 .stdin(Stdio::null())
106 .stdout(Stdio::piped())
107 .stderr(Stdio::piped())
108 .env_clear()
109 .env("PYTHONDONTWRITEBYTECODE", "1")
110 .env("PYTHONIOENCODING", "utf-8");
111
112 #[cfg(target_os = "windows")]
115 {
116 if let Ok(v) = std::env::var("SYSTEMROOT") {
117 builder = builder.env("SYSTEMROOT", v);
118 }
119 if let Ok(v) = std::env::var("TEMP") {
120 builder = builder.env("TEMP", v);
121 }
122 if let Ok(v) = std::env::var("TMP") {
123 builder = builder.env("TMP", v);
124 }
125 }
126 #[cfg(not(target_os = "windows"))]
127 {
128 if let Ok(v) = std::env::var("TMPDIR") {
129 builder = builder.env("TMPDIR", v);
130 }
131 }
132
133 let child = builder
134 .spawn()
135 .map_err(|e| format!("Failed to spawn Python: {e}"))?;
136
137 collect_output(child, "python", timeout_secs)
138}
139
140fn wrap_python(code: &str) -> String {
143 format!(
144 r#"
145import sys
146
147# Block network access
148import socket as _socket
149_socket.socket = None # type: ignore
150
151# Block subprocess and os.system
152import os as _os
153_os.system = lambda *a, **k: (_ for _ in ()).throw(PermissionError("os.system blocked in sandbox"))
154_popen_orig = _os.popen
155_os.popen = lambda *a, **k: (_ for _ in ()).throw(PermissionError("os.popen blocked in sandbox"))
156
157# Block __import__ for subprocess
158_real_import = __builtins__.__import__ if hasattr(__builtins__, '__import__') else __import__
159def _safe_import(name, *args, **kwargs):
160 if name in ('subprocess', 'multiprocessing', 'pty', 'telnetlib', 'ftplib', 'smtplib', 'http', 'urllib', 'requests', 'httpx'):
161 raise ImportError(f"Module '{{name}}' is blocked in the sandbox.")
162 return _real_import(name, *args, **kwargs)
163import builtins
164builtins.__import__ = _safe_import
165
166# Run the actual code
167try:
168 exec(compile(r"""{code}""", "<sandbox>", "exec"))
169except Exception as e:
170 print(f"\nSandbox Execution Error: {{e}}", file=sys.stderr)
171 sys.exit(1)
172"#,
173 code = code.replace(r#"""""#, r#"\" \" \""#)
174 )
175}
176
177fn write_stdin(child: &mut std::process::Child, code: &str) -> Result<(), String> {
178 let mut stdin = child
179 .stdin
180 .take()
181 .ok_or("Failed to open stdin for sandbox process")?;
182 stdin
183 .write_all(code.as_bytes())
184 .map_err(|e| format!("Failed to write to sandbox stdin: {e}"))?;
185 drop(stdin); Ok(())
187}
188
189fn collect_output(
190 child: std::process::Child,
191 runtime: &str,
192 timeout_secs: u64,
193) -> Result<String, String> {
194 let timeout = Duration::from_secs(timeout_secs);
195 let start = std::time::Instant::now();
196
197 let output = std::thread::scope(|s| {
199 let handle = s.spawn(|| child.wait_with_output());
200 loop {
201 if start.elapsed() >= timeout {
202 return Err(format!(
203 "Sandbox timeout: process exceeded {}s and was killed.",
204 timeout_secs
205 ));
206 }
207 std::thread::sleep(Duration::from_millis(50));
208 if handle.is_finished() {
209 return handle
210 .join()
211 .map_err(|_| "Sandbox thread panicked.".to_string())?
212 .map_err(|e| format!("Failed to collect {runtime} output: {e}"));
213 }
214 }
215 })?;
216
217 let stdout = truncate(
218 &String::from_utf8_lossy(&output.stdout),
219 MAX_OUTPUT_BYTES / 2,
220 );
221 let stderr = truncate(
222 &String::from_utf8_lossy(&output.stderr),
223 MAX_OUTPUT_BYTES / 2,
224 );
225
226 if output.status.success() {
227 if stdout.trim().is_empty() && stderr.trim().is_empty() {
228 Ok("(no output)".to_string())
229 } else if stderr.trim().is_empty() {
230 Ok(stdout)
231 } else {
232 Ok(format!("{stdout}\n[stderr]\n{stderr}"))
233 }
234 } else {
235 let code = output
236 .status
237 .code()
238 .map(|c| c.to_string())
239 .unwrap_or_else(|| "?".to_string());
240 Err(format!(
241 "Exit code {code}\n{}\n{}",
242 stdout.trim(),
243 stderr.trim()
244 ))
245 }
246}
247
248fn truncate(s: &str, max: usize) -> String {
249 if s.len() <= max {
250 s.to_string()
251 } else {
252 format!("{}\n... [truncated]", &s[..max])
253 }
254}
255
256fn find_deno() -> Option<String> {
263 let config = crate::agent::config::load_config();
264 if let Some(path) = config.deno_path {
265 if std::path::Path::new(&path).exists() {
266 return Some(path);
267 }
268 }
269
270 let exe = if cfg!(windows) { "deno.exe" } else { "deno" };
271
272 if let Ok(home) = std::env::var("USERPROFILE").or_else(|_| std::env::var("HOME")) {
274 let standard = std::path::Path::new(&home)
275 .join(".deno")
276 .join("bin")
277 .join(exe);
278 if standard.exists() {
279 return Some(standard.to_string_lossy().into_owned());
280 }
281 }
282
283 if cfg!(windows) {
286 if let Ok(local_app) = std::env::var("LOCALAPPDATA") {
287 let winget_base = std::path::Path::new(&local_app)
288 .join("Microsoft")
289 .join("WinGet")
290 .join("Packages");
291 if let Ok(entries) = std::fs::read_dir(&winget_base) {
292 for entry in entries.flatten() {
293 let name = entry.file_name();
294 if name.to_string_lossy().starts_with("DenoLand.Deno") {
295 let candidate = entry.path().join("deno.exe");
296 if candidate.exists() {
297 return Some(candidate.to_string_lossy().into_owned());
298 }
299 }
300 }
301 }
302 }
303 }
304
305 let check = if cfg!(windows) {
307 Command::new("where").arg("deno").output()
308 } else {
309 Command::new("which").arg("deno").output()
310 };
311 if let Ok(out) = check {
312 if out.status.success() {
313 let resolved = String::from_utf8_lossy(&out.stdout)
315 .trim()
316 .lines()
317 .next()
318 .unwrap_or("deno")
319 .to_string();
320 return Some(resolved);
321 }
322 }
323
324 find_lmstudio_deno()
326}
327
328fn find_python() -> Option<String> {
329 let config = crate::agent::config::load_config();
330 if let Some(path) = config.python_path {
331 if std::path::Path::new(&path).exists() {
332 return Some(path);
333 }
334 }
335 find_executable(&["python3", "python", "py"])
336}
337
338fn find_executable(candidates: &[&str]) -> Option<String> {
340 for name in candidates {
341 let check = if cfg!(windows) {
342 Command::new("where").arg(name).output()
343 } else {
344 Command::new("which").arg(name).output()
345 };
346 if check.map(|o| o.status.success()).unwrap_or(false) {
347 return Some(name.to_string());
348 }
349 }
350 None
351}
352
353fn find_lmstudio_deno() -> Option<String> {
356 let home = std::env::var("USERPROFILE")
357 .or_else(|_| std::env::var("HOME"))
358 .ok()?;
359
360 let exe = if cfg!(windows) { "deno.exe" } else { "deno" };
361 let path = std::path::Path::new(&home)
362 .join(".lmstudio")
363 .join(".internal")
364 .join("utils")
365 .join(exe);
366
367 if path.exists() {
368 Some(path.to_string_lossy().into_owned())
369 } else {
370 None
371 }
372}