"""Code Execution Engine""" import subprocess import sys import ast import re from typing import Dict, Optional, Any from dataclasses import dataclass @dataclass class ExecutionResult: """Code execution result container""" success: bool output: str error: Optional[str] = None execution_time: float = 0.0 class CodeExecutor: """Execute code in various programming languages""" SUPPORTED_LANGUAGES = ["python", "javascript", "typescript", "sql", "bash"] def __init__(self, timeout: int = 30, sandbox: bool = True): self.timeout = timeout self.sandbox = sandbox self.execution_count = 0 def execute(self, code: str, language: str = "python") -> ExecutionResult: """Execute code and return result""" if language not in self.SUPPORTED_LANGUAGES: return ExecutionResult( success=False, output="", error=f"Unsupported language: {language}", ) if self._contains_malicious_code(code): return ExecutionResult( success=False, output="", error="Potentially malicious code detected", ) self.execution_count += 1 if language == "python": return self._execute_python(code) elif language == "javascript": return self._execute_javascript(code) elif language == "sql": return self._execute_sql(code) elif language == "bash": return self._execute_bash(code) return ExecutionResult(success=False, output="", error="Execution failed") def _contains_malicious_code(self, code: str) -> bool: """Check for potentially malicious patterns""" dangerous_patterns = [ r"__import__\s*\(", r"exec\s*\(", r"eval\s*\(", r"subprocess\s*\(.*shell\s*=\s*True", r"os\.system\s*\(", r"shutil\.rmtree", r"open\s*\([^)]*['\"][wr]", ] for pattern in dangerous_patterns: if re.search(pattern, code): return True return False def _execute_python(self, code: str) -> ExecutionResult: """Execute Python code""" import time start_time = time.time() try: tree = ast.parse(code) namespace: Dict[str, Any] = {} exec(compile(tree, "", "exec"), namespace) output = self._capture_output(namespace) execution_time = time.time() - start_time return ExecutionResult( success=True, output=output, execution_time=execution_time ) except SyntaxError as e: return ExecutionResult( success=False, output="", error=f"Syntax Error: {e}", execution_time=time.time() - start_time, ) except Exception as e: return ExecutionResult( success=False, output="", error=f"Runtime Error: {e}", execution_time=time.time() - start_time, ) def _capture_output(self, namespace: Dict[str, Any]) -> str: """Capture relevant output from namespace""" output_lines = [] if "result" in namespace: output_lines.append(str(namespace["result"])) for key, value in namespace.items(): if key.startswith("output_"): output_lines.append(f"{key}: {value}") return "\n".join(output_lines) if output_lines else "Code executed successfully" def _execute_javascript(self, code: str) -> ExecutionResult: """Execute JavaScript code using Node.js""" import tempfile import time start_time = time.time() with tempfile.NamedTemporaryFile( mode="w", suffix=".js", delete=False ) as f: f.write(code) temp_file = f.name try: result = subprocess.run( ["node", temp_file], capture_output=True, text=True, timeout=self.timeout, ) if result.returncode == 0: return ExecutionResult( success=True, output=result.stdout, execution_time=time.time() - start_time, ) else: return ExecutionResult( success=False, output="", error=result.stderr, execution_time=time.time() - start_time, ) except subprocess.TimeoutExpired: return ExecutionResult( success=False, output="", error=f"Execution timed out after {self.timeout}s", execution_time=time.time() - start_time, ) except FileNotFoundError: return ExecutionResult( success=False, output="", error="Node.js not found. Please install Node.js to execute JavaScript.", execution_time=time.time() - start_time, ) finally: import os os.unlink(temp_file) def _execute_sql(self, code: str) -> ExecutionResult: """Execute SQL query""" import time start_time = time.time() return ExecutionResult( success=True, output=f"SQL query would be executed:\n{code}", execution_time=time.time() - start_time, ) def _execute_bash(self, code: str) -> ExecutionResult: """Execute bash command""" import time start_time = time.time() if self.sandbox: return ExecutionResult( success=False, output="", error="Bash execution is disabled in sandbox mode", execution_time=time.time() - start_time, ) try: result = subprocess.run( code, shell=True, capture_output=True, text=True, timeout=self.timeout ) return ExecutionResult( success=result.returncode == 0, output=result.stdout, error=result.stderr if result.returncode != 0 else None, execution_time=time.time() - start_time, ) except subprocess.TimeoutExpired: return ExecutionResult( success=False, output="", error=f"Command timed out after {self.timeout}s", execution_time=time.time() - start_time, ) def validate_syntax(self, code: str, language: str) -> tuple[bool, Optional[str]]: """Validate code syntax without execution""" if language == "python": try: ast.parse(code) return True, None except SyntaxError as e: return False, str(e) return True, None