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(
44 path: &str,
45 intent: Option<&str>,
46 project_root: Option<&str>,
47) -> (String, ShellOutcome) {
48 let root = match project_root {
49 Some(root) => std::path::PathBuf::from(root),
50 None => match std::env::current_dir() {
51 Ok(root) => root,
52 Err(_) => return ("Source project unavailable".into(), ShellOutcome::Blocked),
53 },
54 };
55 let result =
56 crate::core::policy::runtime::with_project_source_view(&root.to_string_lossy(), || {
57 handle_file_in_view(path, intent, &root)
58 });
59 match result {
60 Ok((text, outcome, authority)) => {
61 if let Some(authority) = authority {
62 authority.publish();
63 }
64 (text, outcome)
65 }
66 Err(_) => (
67 "File processing withheld: source authority changed or could not be verified.".into(),
68 ShellOutcome::Blocked,
69 ),
70 }
71}
72
73fn handle_file_in_view(
74 path: &str,
75 intent: Option<&str>,
76 root: &std::path::Path,
77) -> (
78 String,
79 ShellOutcome,
80 Option<crate::core::archive::authority::ArchiveAuthority>,
81) {
82 let mut remaining = crate::core::limits::max_read_bytes();
83 let read = match crate::tools::ctx_read::read_file_for_tool_rooted_with_path(
84 path,
85 &root.to_string_lossy(),
86 "ctx_execute",
87 &mut remaining,
88 ) {
89 Ok(content) => content,
90 Err(error) => {
91 return (
92 format!("File processing refused: {error}"),
93 ShellOutcome::Blocked,
94 None,
95 );
96 }
97 };
98 let authority = crate::core::archive::authority::ArchiveAuthority::file(
99 root,
100 &read.canonical_path,
101 "ctx_execute",
102 &read.content,
103 );
104 (
105 summarize_file_content(&read.content, intent),
106 ShellOutcome::Exit(0),
107 authority,
108 )
109}
110
111fn summarize_file_content(content: &str, intent: Option<&str>) -> String {
112 let lines = content.lines();
113 let count = lines.clone().count();
114 let mut output = format!(
115 "Admitted text: {count} lines, {} bytes, {} words (after decoding and filtering)\n",
116 content.len(),
117 content.split_whitespace().count(),
118 );
119 if let Some(intent) = intent {
120 output.push_str(&format!("Intent: {}\n", sanitize_intent(intent)));
121 }
122 let append = |output: &mut String, line: &str| {
125 if let Some((end, _)) = line.char_indices().nth(1024) {
126 output.push_str(&line[..end]);
127 output.push_str(" [line truncated]");
128 } else {
129 output.push_str(line);
130 }
131 output.push('\n');
132 };
133 if count <= 6 {
134 for line in lines {
135 append(&mut output, line);
136 }
137 } else {
138 for line in lines.clone().take(3) {
139 append(&mut output, line);
140 }
141 output.push_str(&format!("... {} middle lines omitted ...\n", count - 6));
142 let tail: Vec<_> = lines.rev().take(3).collect();
143 for line in tail.into_iter().rev() {
144 append(&mut output, line);
145 }
146 }
147 output
148}
149
150pub fn handle_batch(items: &[(String, String)]) -> (String, ShellOutcome) {
154 for (index, (language, code)) in items.iter().enumerate() {
155 if language.eq_ignore_ascii_case("shell")
156 && let Err(message) = crate::core::shell_allowlist::check_shell_allowlist(code)
157 {
158 return (
159 format!(
160 "batch item {} blocked by shell policy:\n{message}",
161 index + 1
162 ),
163 ShellOutcome::Blocked,
164 );
165 }
166 }
167 let results = sandbox::batch_execute(items);
168 let mut output = Vec::new();
169
170 for (i, result) in results.iter().enumerate() {
171 let label = format!("[{}/{}] {}", i + 1, results.len(), result.language);
172 if result.exit_code == 0 {
173 let stdout = result.stdout.trim();
174 if stdout.is_empty() {
175 output.push(format!("{label}: (no output) [{} ms]", result.duration_ms));
176 } else {
177 output.push(format!("{label}: {stdout} [{} ms]", result.duration_ms));
178 }
179 } else {
180 let stderr = result.stderr.trim();
181 output.push(format!(
182 "{label}: EXIT {} — {stderr} [{} ms]",
183 result.exit_code, result.duration_ms
184 ));
185 }
186 }
187
188 let total_ms: u64 = results.iter().map(|r| r.duration_ms).sum();
189 output.push(format!("\n{} tasks, {} ms total", results.len(), total_ms));
190 let first_failure = results
191 .iter()
192 .map(|r| r.exit_code)
193 .find(|c| *c != 0)
194 .unwrap_or(0);
195 (output.join("\n"), ShellOutcome::Exit(first_failure))
196}
197
198fn format_result(result: &SandboxResult, intent: Option<&str>) -> String {
199 let mut parts = Vec::new();
200
201 if result.exit_code == 0 {
202 let stdout = result.stdout.trim();
203 if stdout.is_empty() {
204 parts.push("(no output)".to_string());
205 } else {
206 let raw_tokens = count_tokens(stdout);
207 parts.push(stdout.to_string());
208
209 if let Some(intent_desc) = intent
210 && raw_tokens > 50
211 {
212 parts.push(format!("[intent: {intent_desc}]"));
213 }
214 }
215 } else {
216 if !result.stdout.is_empty() {
217 parts.push(result.stdout.trim().to_string());
218 }
219 parts.push(format!(
220 "EXIT {} — {}",
221 result.exit_code,
222 result.stderr.trim()
223 ));
224 }
225
226 parts.push(format!("[{} | {} ms]", result.language, result.duration_ms));
227 parts.join("\n")
228}
229
230fn sanitize_intent(raw: &str) -> String {
231 raw.chars()
232 .filter(|c| c.is_alphanumeric() || *c == ' ' || *c == '-' || *c == '_' || *c == '.')
233 .take(200)
234 .collect()
235}
236
237#[cfg(test)]
238mod tests {
239 use super::*;
240
241 #[test]
242 fn handle_simple_python() {
243 let _lock = crate::core::data_dir::test_env_lock();
244 let (result, outcome) = handle("python", "print(2 + 2)", None, None);
245 assert!(result.contains('4'));
246 assert!(result.contains("python"));
247 assert_eq!(outcome, ShellOutcome::Exit(0), "success must report exit 0");
248 }
249
250 #[test]
251 fn handle_with_intent() {
252 let _lock = crate::core::data_dir::test_env_lock();
253 let (result, _) = handle(
254 "python",
255 "print('found 5 errors')",
256 Some("count errors"),
257 None,
258 );
259 assert!(result.contains("found 5 errors"));
260 }
261
262 #[test]
263 fn handle_error_shows_stderr() {
264 let _lock = crate::core::data_dir::test_env_lock();
265 let (result, outcome) = handle("python", "raise Exception('boom')", None, None);
266 assert!(result.contains("EXIT"));
267 assert!(result.contains("boom"));
268 assert!(
269 outcome.is_error(),
270 "non-zero sandbox exit must surface as a tool error (#389)"
271 );
272 }
273
274 #[test]
275 #[serial_test::serial]
276 fn shell_execution_cannot_bypass_ctx_shell_allowlist() {
277 let _env_lock = crate::core::data_dir::test_env_lock();
282 crate::test_env::set_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE", "echo");
283 let (result, outcome) = handle("shell", "definitely_not_allowed_command", None, None);
284 crate::test_env::remove_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE");
285 assert_eq!(outcome, ShellOutcome::Blocked);
286 assert!(
287 result.contains("shell allowlist"),
288 "unexpected result: {result}"
289 );
290 }
291
292 #[test]
293 #[serial_test::serial]
294 fn shell_batch_is_preflighted_before_any_item_runs() {
295 let _env_lock = crate::core::data_dir::test_env_lock();
296 crate::test_env::set_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE", "echo");
297 let items = vec![
298 ("shell".to_string(), "echo safe".to_string()),
299 (
300 "shell".to_string(),
301 "definitely_not_allowed_command".to_string(),
302 ),
303 ];
304 let (result, outcome) = handle_batch(&items);
305 crate::test_env::remove_var("LEAN_CTX_SHELL_ALLOWLIST_OVERRIDE");
306 assert_eq!(outcome, ShellOutcome::Blocked);
307 assert!(result.contains("batch item 2 blocked"));
308 }
309
310 #[test]
311 #[cfg(not(target_os = "windows"))]
312 fn batch_multiple_tasks() {
313 let _lock = crate::core::data_dir::test_env_lock();
314 let items = vec![
315 ("python".to_string(), "print('task1')".to_string()),
316 ("shell".to_string(), "echo task2".to_string()),
317 ];
318 let (result, outcome) = handle_batch(&items);
319 assert!(result.contains("task1"));
320 assert!(result.contains("task2"));
321 assert!(result.contains("2 tasks"));
322 assert_eq!(outcome, ShellOutcome::Exit(0), "all tasks succeeded");
323 }
324
325 #[test]
326 #[cfg(not(target_os = "windows"))]
327 fn batch_with_failing_task_reports_failure() {
328 let _lock = crate::core::data_dir::test_env_lock();
329 let items = vec![
330 ("python".to_string(), "print('ok')".to_string()),
331 ("python".to_string(), "raise SystemExit(3)".to_string()),
332 ];
333 let (_, outcome) = handle_batch(&items);
334 assert_eq!(
335 outcome,
336 ShellOutcome::Exit(3),
337 "one failing task marks the whole batch as failed (#389)"
338 );
339 }
340
341 #[test]
342 fn handle_file_precondition_failure_is_blocked() {
343 let (result, outcome) = handle_file("/nonexistent/definitely-missing.py", None, None);
344 assert!(outcome.is_error(), "precondition failures are tool errors");
345 assert_eq!(outcome, ShellOutcome::Blocked, "nothing was executed");
346 assert!(!result.is_empty());
347 }
348}
349
350#[cfg(test)]
351#[path = "ctx_execute_file_tests.rs"]
352mod file_tests;