Genisi / agent /tools /shell.py
AnesKAM's picture
Create agent/tools/shell.py
bb88361 verified
Raw History Blame Contribute Delete
7.21 kB
"""
Shell Execution Tool - Safe command execution for the Agent
"""
import asyncio
import subprocess
import json
import os
import shlex
from typing import Dict, Any, List, Optional
from pathlib import Path
class ShellExecutionTool:
"""Safe shell execution with security restrictions"""
# Commands that are NEVER allowed
BLOCKED_COMMANDS = {
'rm -rf /', 'rm -rf /*', 'format c:', 'del /f /s /q',
'shutdown', 'reboot', 'init 0', 'halt', 'poweroff',
'dd if=/dev/zero', 'mkfs', 'fdisk', 'parted',
':(){ :|:& };:', 'fork bomb'
}
# Command patterns that need confirmation
DANGEROUS_PATTERNS = [
r'rm\s+-rf',
r'sudo\s+',
r'chmod\s+777',
r'chown\s+',
r'>\s*/etc/',
r'curl\s+.*\|\s*(ba)?sh',
r'wget\s+.*\|\s*(ba)?sh',
r'pip\s+install\s+--index-url',
]
# Allowed command prefixes (whitelist)
ALLOWED_PREFIXES = {
'ls', 'dir', 'cd', 'pwd', 'cat', 'type', 'head', 'tail',
'grep', 'find', 'rg', 'awk', 'sed', 'sort', 'uniq',
'python', 'python3', 'pip', 'pip3', 'node', 'npm', 'npx',
'git', 'docker', 'docker-compose', 'make', 'cargo',
'pytest', 'jest', 'mocha', 'vitest', 'unittest',
'curl', 'wget', 'echo', 'printf', 'date', 'whoami',
'mkdir', 'touch', 'cp', 'mv', 'tree', 'wc', 'diff',
'tar', 'zip', 'unzip', 'gzip', 'gunzip',
'black', 'flake8', 'pylint', 'mypy', 'ruff',
'prettier', 'eslint', 'tsc',
}
def __init__(self, workspace_root: str = "./workspace"):
self.workspace_root = Path(workspace_root).resolve()
self.timeout = 30 # seconds
self.max_output_size = 10000 # characters
def _validate_command(self, command: str) -> Dict[str, Any]:
"""Validate command for security"""
command_lower = command.lower().strip()
# Check blocked commands
for blocked in self.BLOCKED_COMMANDS:
if blocked in command_lower:
return {"safe": False, "reason": f"Blocked command: {blocked}"}
# Check dangerous patterns
import re
for pattern in self.DANGEROUS_PATTERNS:
if re.search(pattern, command_lower):
return {"safe": False, "reason": f"Dangerous pattern: {pattern}"}
# Check if command starts with allowed prefix
first_word = command_lower.split()[0] if command_lower else ""
if first_word not in self.ALLOWED_PREFIXES:
return {"safe": False, "reason": f"Command not in whitelist: {first_word}"}
return {"safe": True, "reason": "OK"}
async def execute(self, command: str, cwd: Optional[str] = None, timeout: Optional[int] = None) -> Dict[str, Any]:
"""Execute a shell command safely"""
# Validate command
validation = self._validate_command(command)
if not validation["safe"]:
return {
"success": False,
"error": f"Security check failed: {validation['reason']}",
"command": command
}
# Set working directory
work_dir = cwd or str(self.workspace_root)
work_path = Path(work_dir).resolve()
# Ensure we're within workspace
try:
work_path.relative_to(self.workspace_root)
except ValueError:
return {"success": False, "error": "Working directory outside workspace"}
timeout = timeout or self.timeout
try:
# Execute command
process = await asyncio.create_subprocess_shell(
command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
cwd=str(work_path),
env={**os.environ, "PYTHONUNBUFFERED": "1"}
)
try:
stdout, stderr = await asyncio.wait_for(
process.communicate(),
timeout=timeout
)
except asyncio.TimeoutError:
process.kill()
return {
"success": False,
"error": f"Command timed out after {timeout}s",
"command": command
}
# Decode output
stdout_str = stdout.decode('utf-8', errors='replace')[:self.max_output_size]
stderr_str = stderr.decode('utf-8', errors='replace')[:self.max_output_size]
return {
"success": process.returncode == 0,
"exit_code": process.returncode,
"stdout": stdout_str,
"stderr": stderr_str,
"command": command,
"working_directory": str(work_path)
}
except Exception as e:
return {
"success": False,
"error": f"Execution failed: {str(e)}",
"command": command
}
async def run_python(self, code: str, timeout: int = 30) -> Dict[str, Any]:
"""Execute Python code directly"""
import tempfile
# Write code to temporary file
with tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=False, dir=self.workspace_root) as f:
f.write(code)
temp_file = f.name
try:
result = await self.execute(f"python {temp_file}", timeout=timeout)
return result
finally:
# Cleanup
try:
os.unlink(temp_file)
except:
pass
async def run_tests(self, framework: str = "pytest", pattern: str = "test_*.py") -> Dict[str, Any]:
"""Run test suite"""
commands = {
"pytest": f"pytest {pattern} -v --tb=short",
"jest": f"npx jest {pattern}",
"vitest": f"npx vitest run {pattern}",
"mocha": f"npx mocha {pattern}",
"unittest": f"python -m unittest discover -p '{pattern}'",
}
command = commands.get(framework)
if not command:
return {"success": False, "error": f"Unknown framework: {framework}"}
return await self.execute(command, timeout=120)
async def install_package(self, package: str, package_manager: str = "pip") -> Dict[str, Any]:
"""Install a package"""
# Validate package name (prevent injection)
import re
if not re.match(r'^[a-zA-Z0-9\-_\.]+$', package):
return {"success": False, "error": "Invalid package name"}
commands = {
"pip": f"pip install {package}",
"npm": f"npm install {package}",
"yarn": f"yarn add {package}",
"cargo": f"cargo add {package}",
"gem": f"gem install {package}",
}
command = commands.get(package_manager)
if not command:
return {"success": False, "error": f"Unknown package manager: {package_manager}"}
return await self.execute(command, timeout=300)