-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaction_executor.py
More file actions
349 lines (275 loc) · 12.6 KB
/
action_executor.py
File metadata and controls
349 lines (275 loc) · 12.6 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
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
341
342
343
344
345
346
347
348
349
"""Action executor for system operations with safety checks."""
import os
import subprocess
import shlex
from pathlib import Path
from typing import List, Optional, Dict, Any, Callable
import requests
from bs4 import BeautifulSoup
from loguru import logger
from config import settings
from whitelist_manager import WhitelistManager
class ActionExecutor:
"""Executes system actions with safety validation."""
def __init__(self, confirmation_callback: Optional[Callable[[str, str], tuple[bool, bool]]] = None):
self.allowed_dirs = settings.allowed_dirs_list
self.command_whitelist = settings.command_whitelist_list
self.whitelist_manager = WhitelistManager()
self.confirmation_callback = confirmation_callback
def _request_confirmation(self, category: str, action_description: str, item: str) -> tuple[bool, bool]:
"""
Request user confirmation for an action.
Args:
category: Whitelist category (file_operations, applications, web_urls)
action_description: Human-readable description of the action
item: The item to potentially whitelist
Returns:
Tuple of (execute_action, add_to_whitelist)
"""
# Check if already whitelisted
if self.whitelist_manager.is_whitelisted(category, item):
logger.info(f"Action auto-approved (whitelisted): {action_description}")
return (True, False)
# Request confirmation via callback
if self.confirmation_callback:
return self.confirmation_callback(action_description, item)
# Default: don't execute if no callback
logger.warning(f"No confirmation callback set, denying: {action_description}")
return (False, False)
def _is_path_allowed(self, path: Path) -> bool:
"""Check if a path is within allowed directories."""
try:
resolved_path = path.resolve()
# Check if path is under any allowed directory
for allowed_dir in self.allowed_dirs:
try:
resolved_path.relative_to(allowed_dir.resolve())
return True
except ValueError:
continue
logger.warning(f"Path not allowed: {path}")
return False
except Exception as e:
logger.error(f"Path validation error: {e}")
return False
def execute_file_operation(
self,
operation: str,
path: str,
content: Optional[str] = None
) -> str:
"""
Execute file system operations safely.
Args:
operation: Type of operation (create_file, read_file, etc.)
path: File or directory path
content: Content for write operations
Returns:
Result message
"""
logger.info(f"File operation: {operation} on {path}")
file_path = Path(path).expanduser()
# Validate path
if not self._is_path_allowed(file_path):
return f"Error: Path '{path}' is not in allowed directories"
# Request confirmation for destructive operations
if operation in ["delete_file", "create_file"]:
action_desc = f"{operation} on {file_path}"
whitelist_item = f"{operation}:{file_path.parent}"
execute, add_to_whitelist = self._request_confirmation(
"file_operations",
action_desc,
whitelist_item
)
if not execute:
return f"Action cancelled by user: {action_desc}"
if add_to_whitelist:
self.whitelist_manager.add_to_whitelist("file_operations", whitelist_item)
try:
if operation == "create_file":
# Create parent directories if needed
file_path.parent.mkdir(parents=True, exist_ok=True)
file_path.write_text(content or "")
return f"File created: {file_path}"
elif operation == "read_file":
if not file_path.exists():
return f"Error: File not found: {file_path}"
if not file_path.is_file():
return f"Error: Not a file: {file_path}"
content = file_path.read_text()
# Limit output size
if len(content) > 1000:
content = content[:1000] + "\n... (truncated)"
return f"File content:\n{content}"
elif operation == "delete_file":
if not file_path.exists():
return f"Error: Path not found: {file_path}"
if file_path.is_file():
file_path.unlink()
return f"File deleted: {file_path}"
else:
return f"Error: Not a file: {file_path} (use delete_directory for directories)"
elif operation == "create_directory":
file_path.mkdir(parents=True, exist_ok=True)
return f"Directory created: {file_path}"
elif operation == "list_directory":
if not file_path.exists():
return f"Error: Directory not found: {file_path}"
if not file_path.is_dir():
return f"Error: Not a directory: {file_path}"
items = list(file_path.iterdir())
items.sort()
# Format output
files = [f"📄 {item.name}" for item in items if item.is_file()]
dirs = [f"📁 {item.name}" for item in items if item.is_dir()]
all_items = dirs + files
if len(all_items) > 50:
all_items = all_items[:50] + ["... (truncated)"]
return f"Contents of {file_path}:\n" + "\n".join(all_items)
else:
return f"Error: Unknown operation: {operation}"
except Exception as e:
logger.error(f"File operation error: {e}")
return f"Error: {str(e)}"
def fetch_web_page(self, url: str) -> str:
"""
Fetch and extract text from a web page.
Args:
url: URL to fetch
Returns:
Extracted text content
"""
logger.info(f"Fetching web page: {url}")
# Request confirmation for web access
from urllib.parse import urlparse
domain = urlparse(url).netloc
action_desc = f"Fetch web page: {url}"
whitelist_item = domain
execute, add_to_whitelist = self._request_confirmation(
"web_urls",
action_desc,
whitelist_item
)
if not execute:
return f"Action cancelled by user: {action_desc}"
if add_to_whitelist:
self.whitelist_manager.add_to_whitelist("web_urls", whitelist_item)
try:
# Add timeout and user agent
headers = {
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36'
}
response = requests.get(url, headers=headers, timeout=10)
response.raise_for_status()
# Parse HTML
soup = BeautifulSoup(response.text, 'html.parser')
# Remove script and style elements
for script in soup(["script", "style"]):
script.decompose()
# Get text
text = soup.get_text()
# Clean up text
lines = (line.strip() for line in text.splitlines())
chunks = (phrase.strip() for line in lines for phrase in line.split(" "))
text = ' '.join(chunk for chunk in chunks if chunk)
# Limit size
if len(text) > 2000:
text = text[:2000] + "\n... (truncated)"
logger.info(f"Fetched {len(text)} characters from {url}")
return f"Content from {url}:\n{text}"
except Exception as e:
logger.error(f"Web fetch error: {e}")
return f"Error fetching web page: {str(e)}"
def launch_application(self, application: str, args: Optional[List[str]] = None) -> str:
"""
Launch an application or execute a whitelisted command.
Args:
application: Application name or command
args: Optional command arguments
Returns:
Result message
"""
logger.info(f"Launching application: {application}")
# Check if command is whitelisted
base_command = application.split()[0] if ' ' in application else application
if base_command not in self.command_whitelist:
return f"Error: Command '{base_command}' is not in whitelist"
# Request confirmation
cmd_with_args = f"{application} {' '.join(args)}" if args else application
action_desc = f"Launch: {cmd_with_args}"
whitelist_item = cmd_with_args
execute, add_to_whitelist = self._request_confirmation(
"applications",
action_desc,
whitelist_item
)
if not execute:
return f"Action cancelled by user: {action_desc}"
if add_to_whitelist:
self.whitelist_manager.add_to_whitelist("applications", whitelist_item)
try:
# Build command safely
cmd = [application]
if args:
cmd.extend(args)
# Execute in background for GUI applications
if base_command in ['code', 'firefox', 'nautilus', 'gedit']:
# Launch and detach
subprocess.Popen(
cmd,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
start_new_session=True
)
return f"Launched {application}"
else:
# Execute and capture output for CLI commands
result = subprocess.run(
cmd,
capture_output=True,
text=True,
timeout=5
)
output = result.stdout.strip()
if result.stderr:
output += f"\nErrors: {result.stderr.strip()}"
# Limit output
if len(output) > 1000:
output = output[:1000] + "\n... (truncated)"
return f"Command output:\n{output}" if output else f"Command executed: {application}"
except subprocess.TimeoutExpired:
return f"Error: Command timed out: {application}"
except Exception as e:
logger.error(f"Application launch error: {e}")
return f"Error launching application: {str(e)}"
def execute_tool_call(self, tool_call: Dict[str, Any]) -> str:
"""
Execute a tool call from the LLM.
Args:
tool_call: Tool call dict with function name and arguments
Returns:
Execution result
"""
function = tool_call.get("function", {})
function_name = function.get("name", "")
arguments = function.get("arguments", {})
logger.info(f"Executing tool: {function_name}")
try:
if function_name == "execute_file_operation":
return self.execute_file_operation(
operation=arguments.get("operation"),
path=arguments.get("path"),
content=arguments.get("content")
)
elif function_name == "fetch_web_page":
return self.fetch_web_page(arguments.get("url"))
elif function_name == "launch_application":
return self.launch_application(
application=arguments.get("application"),
args=arguments.get("args")
)
else:
return f"Error: Unknown tool: {function_name}"
except Exception as e:
logger.error(f"Tool execution error: {e}")
return f"Error executing tool: {str(e)}"