Repository navigation
Expand file tree
/
Copy pathshell_command.py
More file actions
244 lines (206 loc) · 8.38 KB
/
Copy pathshell_command.py
File metadata and controls
244 lines (206 loc) · 8.38 KB
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
import asyncio
import shlex
import time
from collections.abc import Awaitable, Callable
from functools import wraps
from pathlib import Path
from typing import Any, cast
from loguru import logger
from pydantic_ai import Tool
from ..schemas import ShellCommandResult
# A strict list of commands the agent is allowed to execute.
COMMAND_ALLOWLIST = {
"ls",
"rg",
"cat",
"git",
"echo",
"pwd",
"pytest",
"mypy",
"ruff",
"uv",
"find",
"pre-commit",
# FS Modifying commands - Agent MUST ask for confirmation before using.
"rm",
"cp",
"mv",
"mkdir",
"rmdir",
}
# Git commands that require user confirmation
GIT_CONFIRMATION_COMMANDS = {
"add",
"commit",
"push",
"pull",
"merge",
"rebase",
"reset",
"checkout",
"branch",
"tag",
"stash",
"cherry-pick",
"revert",
}
def _is_dangerous_command(cmd_parts: list[str]) -> bool:
"""Checks for dangerous command patterns."""
command = cmd_parts[0]
return command == "rm" and "-rf" in cmd_parts
def _requires_confirmation(cmd_parts: list[str]) -> tuple[bool, str]:
"""
Checks if a command requires user confirmation.
Returns (requires_confirmation, reason).
"""
if not cmd_parts:
return False, ""
command = cmd_parts[0]
# File system modification commands
if command in {"rm", "cp", "mv", "mkdir", "rmdir"}:
return True, f"filesystem modification command '{command}'"
# Package management commands
if command == "uv":
return True, "package management command 'uv'"
# Git commands that modify state
if command == "git" and len(cmd_parts) > 1:
git_subcommand = cmd_parts[1]
if git_subcommand in GIT_CONFIRMATION_COMMANDS:
return True, f"git command 'git {git_subcommand}'"
return False, ""
def timing_decorator(
func: Callable[..., Awaitable[Any]],
) -> Callable[..., Awaitable[Any]]:
"""
A decorator that logs the execution time of the decorated asynchronous function.
"""
@wraps(func)
async def wrapper(*args: Any, **kwargs: Any) -> Any:
start_time = time.perf_counter()
result = await func(*args, **kwargs)
end_time = time.perf_counter()
execution_time = (end_time - start_time) * 1000 # Convert to milliseconds
logger.info(f"'{func.__qualname__}' executed in {execution_time:.2f}ms")
return result
return wrapper
class ShellCommander:
"""Service to execute shell commands."""
def __init__(self, project_root: str = ".", timeout: int = 30):
self.project_root = Path(project_root).resolve()
self.timeout = timeout
logger.info(f"ShellCommander initialized with root: {self.project_root}")
@timing_decorator
async def execute(
self, command: str, confirmed: bool = False
) -> ShellCommandResult:
"""
Execute a shell command and return the status code, stdout, and stderr.
"""
logger.info(f"Executing shell command: {command}")
try:
cmd_parts = shlex.split(command)
if not cmd_parts:
return ShellCommandResult(
return_code=-1, stdout="", stderr="Empty command provided."
)
# Security: Check if the command is in the allowlist
if cmd_parts[0] not in COMMAND_ALLOWLIST:
available_commands = ", ".join(sorted(COMMAND_ALLOWLIST))
suggestion = ""
if cmd_parts[0] == "grep":
suggestion = " Use 'rg' instead of 'grep' for text searching."
err_msg = f"Command '{cmd_parts[0]}' is not in the allowlist.{suggestion} Available commands: {available_commands}"
logger.error(err_msg)
return ShellCommandResult(return_code=-1, stdout="", stderr=err_msg)
# Security: Check for dangerous argument combinations
if _is_dangerous_command(cmd_parts):
err_msg = f"Rejected dangerous command: {' '.join(cmd_parts)}"
logger.error(err_msg)
return ShellCommandResult(return_code=-1, stdout="", stderr=err_msg)
# Check if command requires confirmation but wasn't pre-approved
requires_confirmation, reason = _requires_confirmation(cmd_parts)
if requires_confirmation and not confirmed:
# Return a special message that tells the agent to ask for confirmation
command_str = " ".join(cmd_parts)
confirmation_msg = f"I will run `{command_str}`. Do you approve? [y/n]"
logger.info(f"Command requires confirmation: {command_str}")
return ShellCommandResult(
return_code=-2, stdout=confirmation_msg, stderr=""
)
process = await asyncio.create_subprocess_exec(
*cmd_parts,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
cwd=self.project_root,
)
stdout, stderr = await asyncio.wait_for(
process.communicate(), timeout=self.timeout
)
stdout_str = stdout.decode("utf-8", errors="replace").strip()
stderr_str = stderr.decode("utf-8", errors="replace").strip()
logger.info(f"Return code: {process.returncode}")
if stdout_str:
logger.info(f"Stdout: {stdout_str}")
if stderr_str:
logger.warning(f"Stderr: {stderr_str}")
return ShellCommandResult(
return_code=(
process.returncode if process.returncode is not None else -1
),
stdout=stdout_str,
stderr=stderr_str,
)
except TimeoutError:
msg = f"Command '{command}' timed out after {self.timeout} seconds."
logger.error(msg)
try:
process.kill()
await process.wait()
logger.info("Process killed due to timeout.")
except ProcessLookupError:
logger.warning(
"Process already terminated when timeout kill was attempted."
)
return ShellCommandResult(return_code=-1, stdout="", stderr=msg)
except Exception as e:
logger.error(f"An error occurred while executing command: {e}")
return ShellCommandResult(return_code=-1, stdout="", stderr=str(e))
def create_shell_command_tool(shell_commander: ShellCommander) -> Tool:
"""Factory function to create the shell command tool."""
async def run_shell_command(
command: str, user_confirmed: bool = False
) -> ShellCommandResult:
"""
Executes a shell command from the approved allowlist only.
Args:
command: The shell command to execute
user_confirmed: Set to True if user has explicitly confirmed this command
AVAILABLE COMMANDS:
- File operations: ls, cat, find, pwd
- Text search: rg (ripgrep) - USE THIS INSTEAD OF grep
- Version control: git (some subcommands require confirmation)
- Testing: pytest, mypy, ruff
- Package management: uv (requires confirmation)
- File system: rm, cp, mv, mkdir, rmdir (require confirmation)
- Other: echo
IMPORTANT: Use 'rg' for text searching, NOT 'grep' (grep is not available).
COMMANDS REQUIRING USER CONFIRMATION:
- File system: rm, cp, mv, mkdir, rmdir
- Package management: uv (any subcommand)
- Git operations: add, commit, push, pull, merge, rebase, reset, checkout, branch, tag, stash, cherry-pick, revert
- Safe git commands (no confirmation needed): status, log, diff, show, ls-files, remote, config
For dangerous commands:
1. Call once to check if confirmation needed (will return error if required)
2. Ask user for approval
3. Call again with user_confirmed=True to execute
"""
return cast(
ShellCommandResult,
await shell_commander.execute(command, confirmed=user_confirmed),
)
return Tool(
function=run_shell_command,
name="execute_shell_command",
description="Executes shell commands from allowlist. For dangerous commands, call twice: first to check if confirmation needed, then with user_confirmed=True after getting approval.",
)