1use crate::core::sandbox::{self, SandboxResult};
2use crate::core::tokens::count_tokens;
3use crate::server::tool_trait::ShellOutcome;
4
5pub fn handle(
9 language: &str,
10 code: &str,
11 intent: Option<&str>,
12 timeout: Option<u64>,
13) -> (String, ShellOutcome) {
14 handle_in(language, code, intent, timeout, None)
15}
16
17pub fn handle_in(
23 language: &str,
24 code: &str,
25 intent: Option<&str>,
26 timeout: Option<u64>,
27 cwd: Option<&std::path::Path>,
28) -> (String, ShellOutcome) {
29 if language.eq_ignore_ascii_case("shell")
30 && let Err(message) = crate::core::shell_allowlist::check_shell_allowlist(code)
31 {
32 return (message.to_string(), ShellOutcome::Blocked);
33 }
34 let result = sandbox::execute_in(language, code, timeout, cwd);
35 (
36 format_result(&result, intent),
37 ShellOutcome::Exit(result.exit_code),
38 )
39}
40
41pub fn handle_file(
47 path: &str,
48 intent: Option<&str>,
49 project_root: Option<&str>,
50) -> (String, ShellOutcome) {
51 let jail_root = match project_root {
52 Some(r) => std::path::PathBuf::from(r),
53 None => std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from(".")),
54 };
55 let candidate = std::path::Path::new(path);
56 let jailed = match crate::core::pathjail::jail_path(candidate, &jail_root) {
57 Ok(p) => p,
58 Err(e) => return (format!("Path rejected: {e}"), ShellOutcome::Blocked),
59 };
60 let path_str = jailed.to_string_lossy();
61
62 let cap = crate::core::limits::max_read_bytes();
63 let meta = match std::fs::metadata(&*jailed) {
64 Ok(m) => m,
65 Err(e) => {
66 return (
67 format!("Error reading {path_str}: {e}"),
68 ShellOutcome::Blocked,
69 );
70 }
71 };
72 if meta.len() > cap as u64 {
73 return (
74 format!(
75 "File too large ({} bytes, limit {cap} bytes). Use a line-range read instead.",
76 meta.len()
77 ),
78 ShellOutcome::Blocked,
79 );
80 }
81 let content = match std::fs::read_to_string(&*jailed) {
82 Ok(c) => c,
83 Err(e) => {
84 return (
85 format!("Error reading {path_str}: {e}"),
86 ShellOutcome::Blocked,
87 );
88 }
89 };
90
91 let language = detect_language_from_extension(path);
92 let code = build_file_processing_script(&language, &content, intent);
93 let result = sandbox::execute(&language, &code, None);
94 (
95 format_result(&result, intent),
96 ShellOutcome::Exit(result.exit_code),
97 )
98}
99
100pub fn handle_batch(items: &[(String, String)]) -> (String, ShellOutcome) {
104 for (index, (language, code)) in items.iter().enumerate() {
105 if language.eq_ignore_ascii_case("shell")
106 && let Err(message) = crate::core::shell_allowlist::check_shell_allowlist(code)
107 {
108 return (
109 format!(
110 "batch item {} blocked by shell policy:\n{message}",
111 index + 1
112 ),
113 ShellOutcome::Blocked,
114 );
115 }
116 }
117 let results = sandbox::batch_execute(items);
118 let mut output = Vec::new();
119
120 for (i, result) in results.iter().enumerate() {
121 let label = format!("[{}/{}] {}", i + 1, results.len(), result.language);
122 if result.exit_code == 0 {
123 let stdout = result.stdout.trim();
124 if stdout.is_empty() {
125 output.push(format!("{label}: (no output) [{} ms]", result.duration_ms));
126 } else {
127 output.push(format!("{label}: {stdout} [{} ms]", result.duration_ms));
128 }
129 } else {
130 let stderr = result.stderr.trim();
131 output.push(format!(
132 "{label}: EXIT {} — {stderr} [{} ms]",
133 result.exit_code, result.duration_ms
134 ));
135 }
136 }
137
138 let total_ms: u64 = results.iter().map(|r| r.duration_ms).sum();
139 output.push(format!("\n{} tasks, {} ms total", results.len(), total_ms));
140 let first_failure = results
141 .iter()
142 .map(|r| r.exit_code)
143 .find(|c| *c != 0)
144 .unwrap_or(0);
145 (output.join("\n"), ShellOutcome::Exit(first_failure))
146}
147
148fn format_result(result: &SandboxResult, intent: Option<&str>) -> String {
149 let mut parts = Vec::new();
150
151 if result.exit_code == 0 {
152 let stdout = result.stdout.trim();
153 if stdout.is_empty() {
154 parts.push("(no output)".to_string());
155 } else {
156 let raw_tokens = count_tokens(stdout);
157 parts.push(stdout.to_string());
158
159 if let Some(intent_desc) = intent
160 && raw_tokens > 50
161 {
162 parts.push(format!("[intent: {intent_desc}]"));
163 }
164 }
165 } else {
166 if !result.stdout.is_empty() {
167 parts.push(result.stdout.trim().to_string());
168 }
169 parts.push(format!(
170 "EXIT {} — {}",
171 result.exit_code,
172 result.stderr.trim()
173 ));
174 }
175
176 parts.push(format!("[{} | {} ms]", result.language, result.duration_ms));
177 parts.join("\n")
178}
179
180fn detect_language_from_extension(path: &str) -> String {
181 let ext = path.rsplit('.').next().unwrap_or("");
182 match ext {
183 "js" | "mjs" | "cjs" => "javascript",
184 "ts" | "mts" | "cts" => "typescript",
185 "py" | "json" | "csv" | "log" | "txt" | "xml" | "yaml" | "yml" | "md" | "html" => "python",
186 "rb" => "ruby",
187 "go" => "go",
188 "rs" => "rust",
189 "php" => "php",
190 "pl" => "perl",
191 "r" | "R" => "r",
192 "ex" | "exs" => "elixir",
193 _ => "shell",
194 }
195 .to_string()
196}
197
198fn sanitize_intent(raw: &str) -> String {
199 raw.chars()
200 .filter(|c| c.is_alphanumeric() || *c == ' ' || *c == '-' || *c == '_' || *c == '.')
201 .take(200)
202 .collect()
203}
204
205fn escape_for_python_raw(path: &str) -> String {
208 path.replace('"', r#"\" + '"' + r""#)
209}
210
211fn escape_for_shell_dq(path: &str) -> String {
214 let mut out = String::with_capacity(path.len());
215 for ch in path.chars() {
216 match ch {
217 '$' | '`' | '"' | '\\' => {
218 out.push('\\');
219 out.push(ch);
220 }
221 _ => out.push(ch),
222 }
223 }
224 out
225}
226
227fn build_file_processing_script(language: &str, content: &str, intent: Option<&str>) -> String {
228 let Ok(tmp) = tempfile::Builder::new()
229 .prefix("lean-ctx-exec-")
230 .suffix(".dat")
231 .tempfile()
232 else {
233 return "echo 'lean-ctx: failed to create temp file'".to_string();
234 };
235 let _ = std::fs::write(tmp.path(), content);
236 let tmp_path = tmp.path().to_string_lossy().to_string();
237 let _keep = tmp.into_temp_path();
238 let intent_str = sanitize_intent(intent.unwrap_or("summarize the content"));
239
240 if language == "python" {
241 let py_path = escape_for_python_raw(&tmp_path);
242 format!(
243 r#"
244 import os
245
246 with open(r"{py_path}", "r", encoding="utf-8") as f:
247 data = f.read()
248 os.remove(r"{py_path}")
249
250 lines = data.strip().split('\n')
251 total_lines = len(lines)
252 total_bytes = len(data.encode('utf-8'))
253
254 word_count = sum(len(line.split()) for line in lines)
255
256 print(f"{{total_lines}} lines, {{total_bytes}} bytes, {{word_count}} words")
257 print("Intent: {intent_str}")
258
259 if total_lines > 10:
260 print(f"First 3: {{lines[:3]}}")
261 print(f"Last 3: {{lines[-3:]}}")
262 "#
263 )
264 } else {
265 let sh_path = escape_for_shell_dq(&tmp_path);
266 format!(
267 r#"
268 data=$(cat "{sh_path}")
269 rm -f "{sh_path}"
270 lines=$(echo "$data" | wc -l | tr -d ' ')
271 bytes=$(echo "$data" | wc -c | tr -d ' ')
272 echo "$lines lines, $bytes bytes"
273 echo 'Intent: {intent_str}'
274 echo "$data" | head -3
275 echo "..."
276 echo "$data" | tail -3
277 "#
278 )
279 }
280}
281
282#[cfg(test)]
283mod tests {
284 use super::*;
285
286 #[test]
287 fn handle_simple_python() {
288 let (result, outcome) = handle("python", "print(2 + 2)", None, None);
289 assert!(result.contains('4'));
290 assert!(result.contains("python"));
291 assert_eq!(outcome, ShellOutcome::Exit(0), "success must report exit 0");
292 }
293
294 #[test]
295 fn handle_with_intent() {
296 let (result, _) = handle(
297 "python",
298 "print('found 5 errors')",
299 Some("count errors"),
300 None,
301 );
302 assert!(result.contains("found 5 errors"));
303 }
304
305 #[test]
306 fn handle_error_shows_stderr() {
307 let (result, outcome) = handle("python", "raise Exception('boom')", None, None);
308 assert!(result.contains("EXIT"));
309 assert!(result.contains("boom"));
310 assert!(
311 outcome.is_error(),
312 "non-zero sandbox exit must surface as a tool error (#389)"
313 );
314 }
315
316 #[test]
317 #[serial_test::serial]
318 fn shell_execution_cannot_bypass_ctx_shell_allowlist() {
319 let _env_lock = crate::core::data_dir::test_env_lock();
324 crate::test_env::set_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE", "echo");
325 let (result, outcome) = handle("shell", "definitely_not_allowed_command", None, None);
326 crate::test_env::remove_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE");
327 assert_eq!(outcome, ShellOutcome::Blocked);
328 assert!(
329 result.contains("shell allowlist"),
330 "unexpected result: {result}"
331 );
332 }
333
334 #[test]
335 #[serial_test::serial]
336 fn shell_batch_is_preflighted_before_any_item_runs() {
337 let _env_lock = crate::core::data_dir::test_env_lock();
338 crate::test_env::set_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE", "echo");
339 let items = vec![
340 ("shell".to_string(), "echo safe".to_string()),
341 (
342 "shell".to_string(),
343 "definitely_not_allowed_command".to_string(),
344 ),
345 ];
346 let (result, outcome) = handle_batch(&items);
347 crate::test_env::remove_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE");
348 assert_eq!(outcome, ShellOutcome::Blocked);
349 assert!(result.contains("batch item 2 blocked"));
350 }
351
352 #[test]
353 fn detect_language_from_path() {
354 assert_eq!(detect_language_from_extension("test.py"), "python");
355 assert_eq!(detect_language_from_extension("test.js"), "javascript");
356 assert_eq!(detect_language_from_extension("test.rs"), "rust");
357 assert_eq!(detect_language_from_extension("test.csv"), "python");
358 assert_eq!(detect_language_from_extension("test.log"), "python");
359 }
360
361 #[test]
362 fn escape_shell_dq_handles_special_chars() {
363 assert_eq!(escape_for_shell_dq(r"C:\tmp\file"), r"C:\\tmp\\file");
364 assert_eq!(escape_for_shell_dq("/tmp/normal"), "/tmp/normal");
365 assert_eq!(escape_for_shell_dq("path with $VAR"), r"path with \$VAR");
366 assert_eq!(escape_for_shell_dq(r#"path"quote"#), r#"path\"quote"#);
367 assert_eq!(escape_for_shell_dq("has `backtick`"), r"has \`backtick\`");
368 }
369
370 #[test]
371 fn escape_python_raw_handles_quotes() {
372 assert_eq!(escape_for_python_raw("/tmp/normal"), "/tmp/normal");
373 assert_eq!(escape_for_python_raw(r"C:\Users\test"), r"C:\Users\test");
374 }
375
376 #[test]
377 fn script_with_spaces_in_path() {
378 let script = build_file_processing_script("shell", "test data", None);
379 let lines: Vec<&str> = script.lines().collect();
380 for line in &lines {
381 if line.contains("cat ") || line.contains("rm -f") {
382 assert!(
383 line.contains('"'),
384 "path must be double-quoted in shell script: {line}"
385 );
386 }
387 }
388 }
389
390 #[test]
391 #[cfg(not(target_os = "windows"))]
392 fn batch_multiple_tasks() {
393 let items = vec![
394 ("python".to_string(), "print('task1')".to_string()),
395 ("shell".to_string(), "echo task2".to_string()),
396 ];
397 let (result, outcome) = handle_batch(&items);
398 assert!(result.contains("task1"));
399 assert!(result.contains("task2"));
400 assert!(result.contains("2 tasks"));
401 assert_eq!(outcome, ShellOutcome::Exit(0), "all tasks succeeded");
402 }
403
404 #[test]
405 #[cfg(not(target_os = "windows"))]
406 fn batch_with_failing_task_reports_failure() {
407 let items = vec![
408 ("python".to_string(), "print('ok')".to_string()),
409 ("python".to_string(), "raise SystemExit(3)".to_string()),
410 ];
411 let (_, outcome) = handle_batch(&items);
412 assert_eq!(
413 outcome,
414 ShellOutcome::Exit(3),
415 "one failing task marks the whole batch as failed (#389)"
416 );
417 }
418
419 #[test]
420 fn handle_file_precondition_failure_is_blocked() {
421 let (result, outcome) = handle_file("/nonexistent/definitely-missing.py", None, None);
422 assert!(outcome.is_error(), "precondition failures are tool errors");
423 assert_eq!(outcome, ShellOutcome::Blocked, "nothing was executed");
424 assert!(!result.is_empty());
425 }
426}