File size: 12,185 Bytes
070daf8 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 | """
Terminal/Bash Execution Tool - Execute shell commands with safety constraints
Language support: bash, sh, zsh, powershell (OS-dependent)
"""
import asyncio
import logging
import os
import shlex
from dataclasses import dataclass
from typing import Any, Dict, List, Optional
logger = logging.getLogger(__name__)
# Whitelist of allowed commands for security
ALLOWED_COMMANDS = {
"npm": {"allowed_args": ["install", "run", "build", "test", "start", "init", "update", "outdated"]},
"yarn": {"allowed_args": ["install", "run", "build", "test", "start", "init"]},
"pip": {"allowed_args": ["install", "uninstall", "list", "show", "freeze", "requirements"]},
"pip3": {"allowed_args": ["install", "uninstall", "list", "show", "freeze", "requirements"]},
"python": {"allowed_args": ["-m", "-c", "-v", "--version"]},
"python3": {"allowed_args": ["-m", "-c", "-v", "--version"]},
"git": {"allowed_args": ["clone", "commit", "push", "pull", "status", "log", "branch", "checkout", "add", "diff", "merge", "fetch", "remote"]},
"docker": {"allowed_args": ["build", "run", "ps", "stop", "start", "rm", "images", "pull", "push"]},
"curl": {"allowed_args": []}, # Allow curl for API requests and downloads
"wget": {"allowed_args": []},
"node": {"allowed_args": ["-v", "--version"]},
"cat": {"allowed_args": []},
"grep": {"allowed_args": ["-r", "-n", "-i", "-v", "-E"]},
"find": {"allowed_args": ["-name", "-type", "-size", "-mtime"]},
"ls": {"allowed_args": ["-la", "-l", "-a", "-h"]},
"cd": {"allowed_args": []},
"mkdir": {"allowed_args": ["-p"]},
"cp": {"allowed_args": ["-r", "-f"]},
"mv": {"allowed_args": []},
"echo": {"allowed_args": []},
"env": {"allowed_args": []},
"which": {"allowed_args": []},
"pwd": {"allowed_args": []},
"touch": {"allowed_args": []},
"head": {"allowed_args": ["-n"]},
"tail": {"allowed_args": ["-n", "-f"]},
"sort": {"allowed_args": []},
"uniq": {"allowed_args": []},
"wc": {"allowed_args": ["-l", "-w", "-c"]},
"tar": {"allowed_args": ["-czf", "-xzf", "-cvf", "-xvf"]},
"zip": {"allowed_args": ["-r"]},
"unzip": {"allowed_args": []},
}
# Commands that are completely disabled
DISABLED_COMMANDS = {
"sudo", "su", "rm", "rmdir", "mkfs", "fdisk", "dd", "format",
"shutdown", "reboot", "halt", "poweroff", "kill", "pkill",
"chmod", "chown", "chgrp", "passwd", "useradd", "userdel",
}
@dataclass
class TerminalResult:
"""Result of a terminal command execution"""
exit_code: int
stdout: str
stderr: str
success: bool
command: str
duration_ms: float
class TerminalExecutor:
"""
Execute shell commands with safety constraints.
"""
def __init__(self, cwd: Optional[str] = None, env_vars: Optional[Dict[str, str]] = None):
self.cwd = cwd or os.getcwd()
self.env_vars = {**os.environ, **(env_vars or {})}
def _validate_command(self, command: str) -> tuple[bool, Optional[str]]:
"""
Validate that the command is safe to execute.
Returns (is_valid, error_message)
"""
# Check for dangerous patterns
dangerous_patterns = [
";", "&&", "||", "|", ">", "<", "`", "$()",
]
# Split command to get base command
parts = shlex.split(command)
if not parts:
return False, "Empty command"
base_cmd = parts[0]
# Check if command is disabled
if base_cmd in DISABLED_COMMANDS:
return False, f"Command '{base_cmd}' is disabled for security reasons"
# Check if command is in whitelist
if base_cmd not in ALLOWED_COMMANDS:
return False, f"Command '{base_cmd}' is not in the allowed list"
# Check for shell operators that could be dangerous
for pattern in dangerous_patterns:
if pattern in command and pattern not in [">>", "<<"]:
# Allow some safe redirects but warn about others
if pattern in ["|", ";", "&&", "||"]:
return False, f"Shell operators like '{pattern}' are not allowed for security"
return True, None
async def execute_command(
self,
command: str,
timeout: int = 30,
sandbox: bool = True
) -> TerminalResult:
"""
Execute terminal command with:
- Timeout protection (prevent hanging)
- Output streaming (see results in real-time)
- Error capture (stderr + exit codes)
- Working directory context
- Environment variable injection
"""
start_time = asyncio.get_event_loop().time()
# Validate command if sandbox mode
if sandbox:
is_valid, error_msg = self._validate_command(command)
if not is_valid:
return TerminalResult(
exit_code=-1,
stdout="",
stderr=error_msg,
success=False,
command=command,
duration_ms=0
)
try:
# Execute with streaming output
process = await asyncio.create_subprocess_shell(
command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
cwd=self.cwd,
env=self.env_vars
)
try:
stdout, stderr = await asyncio.wait_for(
process.communicate(),
timeout=timeout
)
duration_ms = (asyncio.get_event_loop().time() - start_time) * 1000
return TerminalResult(
exit_code=process.returncode,
stdout=stdout.decode('utf-8', errors='replace'),
stderr=stderr.decode('utf-8', errors='replace'),
success=process.returncode == 0,
command=command,
duration_ms=duration_ms
)
except asyncio.TimeoutError:
process.kill()
await process.wait()
duration_ms = (asyncio.get_event_loop().time() - start_time) * 1000
return TerminalResult(
exit_code=-1,
stdout="",
stderr=f"Command timeout after {timeout}s",
success=False,
command=command,
duration_ms=duration_ms
)
except Exception as e:
duration_ms = (asyncio.get_event_loop().time() - start_time) * 1000
return TerminalResult(
exit_code=-1,
stdout="",
stderr=f"Execution error: {str(e)}",
success=False,
command=command,
duration_ms=duration_ms
)
async def stream_command(
self,
command: str,
timeout: int = 30
):
"""
Stream output line-by-line as it executes.
Yields (line_type, line_content) tuples.
"""
is_valid, error_msg = self._validate_command(command)
if not is_valid:
yield ("stderr", error_msg)
yield ("exit_code", -1)
return
try:
process = await asyncio.create_subprocess_shell(
command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
cwd=self.cwd,
env=self.env_vars
)
async def read_stream(stream, line_type):
while True:
try:
line = await asyncio.wait_for(stream.readline(), timeout=0.1)
if not line:
break
yield (line_type, line.decode('utf-8', errors='replace').rstrip())
except asyncio.TimeoutError:
continue
# Read both stdout and stderr concurrently
stdout_task = asyncio.create_task(
self._collect_stream(process.stdout, "stdout")
)
stderr_task = asyncio.create_task(
self._collect_stream(process.stderr, "stderr")
)
# Yield lines as they come
pending = {stdout_task, stderr_task}
while pending:
done, pending = await asyncio.wait(
pending, return_when=asyncio.FIRST_COMPLETED
)
for task in done:
for line_type, line in task.result():
yield (line_type, line)
# Wait for process to complete with timeout
try:
await asyncio.wait_for(process.wait(), timeout=timeout)
yield ("exit_code", process.returncode)
except asyncio.TimeoutError:
process.kill()
yield ("stderr", f"Command timeout after {timeout}s")
yield ("exit_code", -1)
except Exception as e:
yield ("stderr", f"Execution error: {str(e)}")
yield ("exit_code", -1)
async def _collect_stream(self, stream, line_type):
"""Helper to collect stream output"""
lines = []
while True:
line = await stream.readline()
if not line:
break
lines.append((line_type, line.decode('utf-8', errors='replace').rstrip()))
return lines
# Tool spec for LLM
TERMINAL_TOOL_SPEC = {
"name": "execute_terminal",
"description": (
"Execute bash/shell commands with safety constraints. "
"Use this to: run npm/yarn commands, git operations, docker commands, "
"file operations (ls, cat, grep, find), and system utilities. "
"Commands are validated against a whitelist for security. "
"Examples: 'npm install', 'git status', 'docker ps', 'ls -la', 'cat file.txt'"
),
"parameters": {
"type": "object",
"properties": {
"command": {
"type": "string",
"description": "The shell command to execute. Must be a whitelisted command.",
},
"timeout": {
"type": "number",
"description": "Maximum execution time in seconds (default: 30, max: 300)",
},
},
"required": ["command"],
},
}
async def execute_terminal_handler(arguments: Dict[str, Any]) -> tuple[str, bool]:
"""Handler for terminal command execution."""
try:
command = arguments.get("command", "").strip()
timeout = min(arguments.get("timeout", 30), 300) # Max 5 minutes
if not command:
return "Error: Command is required", False
logger.info(f"Executing terminal command: {command}")
executor = TerminalExecutor()
result = await executor.execute_command(command, timeout=timeout)
# Format output
output_lines = [
f"$ {result.command}",
"",
]
if result.stdout:
output_lines.append(result.stdout)
if result.stderr:
output_lines.append(f"[stderr] {result.stderr}")
output_lines.append("")
output_lines.append(f"Exit code: {result.exit_code}")
output_lines.append(f"Duration: {result.duration_ms:.0f}ms")
output = "\n".join(output_lines)
if result.success:
return f"✅ Command executed successfully\n{output}", True
else:
return f"❌ Command failed\n{output}", False
except Exception as e:
logger.error(f"Terminal execution error: {e}")
return f"❌ Error executing command: {str(e)}", False
|