-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcli_agent.py
More file actions
executable file
·6110 lines (5304 loc) · 256 KB
/
Copy pathcli_agent.py
File metadata and controls
executable file
·6110 lines (5304 loc) · 256 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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import os
import sys
import logging
import argparse
import json
import requests
import asyncio
import time
import functools
import random
import uuid
import shutil
import glob
import fnmatch
import subprocess
import re
import inspect
import importlib
import pickle
import copy
from collections import deque
from datetime import datetime
import yaml # Added for config file loading
import numpy as np
from typing import Dict, List, Any, Optional, Tuple, Callable, Deque, Union
from rich.console import Console
from rich.markdown import Markdown
from rich.panel import Panel
from rich.prompt import Prompt
from rich.progress import Progress, SpinnerColumn, TextColumn, BarColumn, TimeElapsedColumn
from rich.table import Table
from rich import print as rprint
import openai
from openai import OpenAI
from dotenv import load_dotenv
# Import agent hooks and advanced visualizer
from agent_hooks import CLIAgentHooks
from data_visualizer import AdvancedDataVisualizer
from dynamic_agents import registry, AgentContext, execute_agent_command
# Load environment variables
load_dotenv()
# Set up logging (will be configured in main based on args)
logger = logging.getLogger("cli-agent")
# Rich console for better formatting
console = Console()
# Initialize OpenAI client
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
# Import weather tool template and script functions
from tool_templates import create_weather_tool
import weather_script
# Import Jina weather tool
from modules.jina_tools import jina_weather
class WeatherTools:
"""
Weather tools that can be used by the agent
"""
def __init__(self):
logger.info("Initializing weather tools")
self.api_key = os.getenv("OPENWEATHERMAP_API_KEY")
self.jina_api_key = os.getenv("JINA_API_KEY")
self.openai_api_key = os.getenv("OPENAI_API_KEY")
if not self.api_key:
logger.warning("OPENWEATHERMAP_API_KEY environment variable not set")
def get_weather(self, location, units="metric"):
"""
Get current weather for a location with enhanced error handling
Args:
location: City name or zip code
units: Units to use (metric, imperial)
Returns:
Weather data for the location with detailed error information if applicable
"""
logger.info(f"Getting weather for {location}")
# First try OpenWeatherMap API if API key is available
if self.api_key:
try:
# Use the comprehensive weather script with enhanced caching and error handling
weather_data = weather_script.get_current_weather(self.api_key, location, units)
# Check for error in response
if isinstance(weather_data, dict) and "error" in weather_data:
error_msg = weather_data.get("error")
status_code = weather_data.get("status_code", 500)
logger.error(f"OpenWeatherMap API error: {error_msg} (Status code: {status_code})")
# Handle specific errors
if status_code == 404:
# For location not found errors, try alternative formatting
# Sometimes "San Francisco, CA" works better as just "San Francisco"
if "," in location:
logger.info(f"Location not found, trying without state/country: {location.split(',')[0]}")
simplified_location = location.split(',')[0].strip()
return self.get_weather(simplified_location, units)
# Will fall through to fallback for other errors
elif weather_data and not isinstance(weather_data, dict):
# Get the summary for a clean response
summary = weather_data.get_summary()
# Format temperature and feels_like to 1 decimal place
if 'temperature' in summary:
summary['temperature'] = round(summary['temperature'], 1)
if 'feels_like' in summary:
summary['feels_like'] = round(summary['feels_like'], 1)
# Add more useful fields
if 'condition' in summary and summary['condition'] != 'Unknown':
# Add weather condition recommendations
if summary['condition'] == 'Rain':
summary['recommendation'] = "Take an umbrella"
elif summary['condition'] == 'Snow':
summary['recommendation'] = "Dress warmly and be careful on roads"
elif summary['condition'] == 'Clear' and summary.get('temperature', 0) > 30:
summary['recommendation'] = "Stay hydrated and use sunscreen"
elif summary['condition'] == 'Clear' and summary.get('temperature', 0) < 5:
summary['recommendation'] = "Dress warmly"
return {
"success": True,
"message": f"Weather data for {location}",
"data": summary,
"source": "OpenWeatherMap"
}
except Exception as e:
logger.error(f"Error getting weather from OpenWeatherMap: {e}")
# Will fall through to Jina fallback
# If OpenWeatherMap failed or no API key, use Jina web search as fallback
logger.info(f"Falling back to Jina web search for weather in {location}")
try:
# Use the Jina-based weather function
jina_result = jina_weather(location, token=self.jina_api_key, openai_key=self.openai_api_key)
if jina_result.get("success"):
weather_data = jina_result.get("data", {})
# Add geocoding information if available
try:
import geocoder
g = geocoder.osm(location)
if g.ok:
weather_data['geo'] = {
'lat': g.lat,
'lng': g.lng,
'country': g.country,
'state': g.state,
'city': g.city
}
except ImportError:
logger.warning("Geocoder package not available for enhanced location data")
return {
"success": True,
"message": f"Weather data for {location} (via web search)",
"data": weather_data,
"source": "Jina Web Search"
}
else:
return jina_result
except Exception as e:
logger.error(f"Error getting weather from Jina: {e}")
return {
"success": False,
"message": f"Unable to retrieve weather data for {location} from any source",
"error": str(e),
"data": None
}
def get_forecast(self, location, days=5, units="metric"):
"""
Get weather forecast for a location
Args:
location: City name or zip code
days: Number of days for forecast
units: Units to use (metric, imperial)
Returns:
Forecast data for the location
"""
logger.info(f"Getting forecast for {location}")
if not self.api_key:
return {
"success": False,
"message": "OpenWeatherMap API key not set. Please set the OPENWEATHERMAP_API_KEY environment variable.",
"data": None
}
try:
# Use the comprehensive weather script
forecast_data = weather_script.get_forecast(self.api_key, location, days, units)
if forecast_data:
# Get the summary for a clean response
summary = forecast_data.get_summary()
return {
"success": True,
"message": f"Forecast data for {location}",
"data": summary
}
else:
return {
"success": False,
"message": f"Could not retrieve forecast data for {location}",
"data": None
}
except Exception as e:
logger.error(f"Error getting forecast: {e}")
return {
"success": False,
"message": f"Error getting forecast: {str(e)}",
"data": None
}
class DataAnalysisTools:
"""
Tools for data analysis that can be used by the agent
"""
def __init__(self):
logger.info("Initializing data analysis tools")
self.visualizer = AdvancedDataVisualizer()
def load_csv(self, filepath: str) -> Dict:
"""Load a CSV file and return basic statistics"""
try:
import pandas as pd
# Load the data
df = pd.read_csv(filepath)
# Generate basic statistics
stats = {
"columns": list(df.columns),
"shape": df.shape,
"dtypes": {col: str(dtype) for col, dtype in df.dtypes.items()},
"head": df.head(5).to_dict(orient="records"),
"describe": df.describe().to_dict(),
"missing_values": df.isnull().sum().to_dict()
}
return {
"success": True,
"message": f"Successfully loaded CSV file with {df.shape[0]} rows and {df.shape[1]} columns",
"data": stats
}
except Exception as e:
logger.error(f"Error loading CSV file: {e}")
return {
"success": False,
"message": f"Error loading CSV file: {str(e)}",
"data": None
}
def plot_data(self, data: Dict, plot_type: str = "histogram",
x_column: str = None, y_column: str = None,
title: str = "Data Visualization") -> Dict:
"""Generate a plot from data and save it to a file"""
try:
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# Create a dataframe from the data
if isinstance(data, dict) and "head" in data:
# If data is from load_csv
df = pd.DataFrame(data["head"])
elif isinstance(data, list) and all(isinstance(item, dict) for item in data):
# If data is a list of dictionaries
df = pd.DataFrame(data)
else:
return {
"success": False,
"message": "Invalid data format for plotting",
"data": None
}
# Create the plot
plt.figure(figsize=(10, 6))
if plot_type == "histogram" and x_column:
sns.histplot(data=df, x=x_column)
elif plot_type == "scatter" and x_column and y_column:
sns.scatterplot(data=df, x=x_column, y=y_column)
elif plot_type == "bar" and x_column and y_column:
sns.barplot(data=df, x=x_column, y=y_column)
elif plot_type == "line" and x_column and y_column:
sns.lineplot(data=df, x=x_column, y=y_column)
elif plot_type == "heatmap":
sns.heatmap(df.corr(), annot=True, cmap="coolwarm")
else:
return {
"success": False,
"message": f"Invalid plot type or missing required columns for {plot_type}",
"data": None
}
plt.title(title)
plt.tight_layout()
# Save the plot
output_file = f"{plot_type}_{x_column}_{y_column if y_column else ''}.png"
plt.savefig(output_file)
plt.close()
return {
"success": True,
"message": f"Successfully created {plot_type} plot and saved to {output_file}",
"data": {
"file": output_file,
"plot_type": plot_type,
"x_column": x_column,
"y_column": y_column
}
}
except Exception as e:
logger.error(f"Error creating plot: {e}")
return {
"success": False,
"message": f"Error creating plot: {str(e)}",
"data": None
}
def analyze_text(self, text: str) -> Dict:
"""Perform basic text analysis"""
try:
# Basic text statistics
word_count = len(text.split())
char_count = len(text)
sentence_count = text.count('.') + text.count('!') + text.count('?')
# Word frequency
import re
from collections import Counter
words = re.findall(r'\b\w+\b', text.lower())
word_freq = Counter(words).most_common(10)
return {
"success": True,
"message": "Successfully analyzed text",
"data": {
"word_count": word_count,
"character_count": char_count,
"sentence_count": sentence_count,
"top_words": word_freq
}
}
except Exception as e:
logger.error(f"Error analyzing text: {e}")
return {
"success": False,
"message": f"Error analyzing text: {str(e)}",
"data": None
}
class ModalIntegration:
"""
Integration with Modal for running functions in the cloud
"""
def __init__(self, endpoint="https://arthurcolle--registry.modal.run"):
self.endpoint = endpoint
self.available = self._check_availability()
if self.available:
logger.info(f"Modal integration available at {endpoint}")
else:
logger.warning(f"Modal integration not available at {endpoint}")
def _check_availability(self) -> bool:
"""Check if Modal endpoint is available"""
try:
response = requests.get(self.endpoint, timeout=5)
return response.status_code == 200
except Exception:
return False
def list_functions(self) -> Dict:
"""List available functions in Modal"""
if not self.available:
return {
"success": False,
"message": "Modal integration not available",
"data": None
}
try:
response = requests.get(f"{self.endpoint}/functions")
if response.status_code == 200:
return {
"success": True,
"message": "Successfully retrieved Modal functions",
"data": response.json()
}
else:
return {
"success": False,
"message": f"Error retrieving Modal functions: {response.status_code}",
"data": None
}
except Exception as e:
logger.error(f"Error listing Modal functions: {e}")
return {
"success": False,
"message": f"Error listing Modal functions: {str(e)}",
"data": None
}
def call_function(self, function_name: str, params: Dict) -> Dict:
"""Call a function in Modal"""
if not self.available:
return {
"success": False,
"message": "Modal integration not available",
"data": None
}
try:
response = requests.post(
f"{self.endpoint}/functions/{function_name}",
json=params
)
if response.status_code == 200:
return {
"success": True,
"message": f"Successfully called Modal function {function_name}",
"data": response.json()
}
else:
return {
"success": False,
"message": f"Error calling Modal function: {response.status_code}",
"data": None
}
except Exception as e:
logger.error(f"Error calling Modal function: {e}")
return {
"success": False,
"message": f"Error calling Modal function: {str(e)}",
"data": None
}
class FileSystemTools:
"""
Advanced tools for interacting with the file system
Provides comprehensive file operations with safety checks and detailed metadata
"""
def __init__(self):
logger.info("Initializing advanced file system tools")
self.history = [] # Track file operations for potential undo
self.safe_mode = True # Safety mode to prevent destructive operations
def list_files(self, path: str = ".", pattern: str = "*", recursive: bool = False,
include_hidden: bool = False, sort_by: str = "name") -> Dict:
"""
List files in a directory with advanced filtering and sorting options
Args:
path: Directory path to list files from
pattern: Glob pattern to filter files
recursive: Whether to recursively list files in subdirectories
include_hidden: Whether to include hidden files (starting with .)
sort_by: How to sort results (name, size, modified, type)
"""
try:
# Normalize path
norm_path = os.path.normpath(os.path.expanduser(path))
# Get files matching pattern
if recursive:
matches = []
for root, dirnames, filenames in os.walk(norm_path):
for filename in filenames:
if fnmatch.fnmatch(filename, pattern):
if include_hidden or not filename.startswith('.'):
matches.append(os.path.join(root, filename))
# Add directories if requested
for dirname in dirnames:
if fnmatch.fnmatch(dirname, pattern):
if include_hidden or not dirname.startswith('.'):
matches.append(os.path.join(root, dirname))
files = matches
else:
files = glob.glob(os.path.join(norm_path, pattern))
if not include_hidden:
files = [f for f in files if not os.path.basename(f).startswith('.')]
# Get detailed file info
file_info = []
for file_path in files:
try:
stat = os.stat(file_path)
is_dir = os.path.isdir(file_path)
# Get file type and mime type
file_type = "directory" if is_dir else "file"
mime_type = None
if not is_dir:
try:
import magic
mime_type = magic.from_file(file_path, mime=True)
except ImportError:
# Fallback to simple extension-based detection
ext = os.path.splitext(file_path)[1].lower()
mime_map = {
'.txt': 'text/plain', '.py': 'text/x-python',
'.jpg': 'image/jpeg', '.png': 'image/png',
'.pdf': 'application/pdf', '.json': 'application/json'
}
mime_type = mime_map.get(ext, 'application/octet-stream')
# Calculate human-readable size
size_bytes = stat.st_size
for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
if size_bytes < 1024 or unit == 'TB':
human_size = f"{size_bytes:.2f} {unit}"
break
size_bytes /= 1024
file_info.append({
"name": os.path.basename(file_path),
"path": file_path,
"size": stat.st_size,
"human_size": human_size,
"modified": time.ctime(stat.st_mtime),
"modified_timestamp": stat.st_mtime,
"created": time.ctime(stat.st_ctime),
"created_timestamp": stat.st_ctime,
"accessed": time.ctime(stat.st_atime),
"is_dir": is_dir,
"type": file_type,
"mime_type": mime_type,
"permissions": oct(stat.st_mode)[-3:],
"owner": stat.st_uid,
"group": stat.st_gid
})
except Exception as e:
logger.warning(f"Error getting info for {file_path}: {e}")
# Sort results
if sort_by == "name":
file_info.sort(key=lambda x: x["name"])
elif sort_by == "size":
file_info.sort(key=lambda x: x["size"], reverse=True)
elif sort_by == "modified":
file_info.sort(key=lambda x: x["modified_timestamp"], reverse=True)
elif sort_by == "type":
file_info.sort(key=lambda x: (x["is_dir"], x["name"]), reverse=True)
# Add summary statistics
total_size = sum(item["size"] for item in file_info)
dir_count = sum(1 for item in file_info if item["is_dir"])
file_count = len(file_info) - dir_count
return {
"success": True,
"message": f"Found {len(file_info)} items matching pattern '{pattern}' in '{norm_path}'",
"data": {
"items": file_info,
"summary": {
"total_items": len(file_info),
"directories": dir_count,
"files": file_count,
"total_size": total_size,
"path": norm_path,
"pattern": pattern
}
}
}
except Exception as e:
logger.error(f"Error listing files: {e}")
return {
"success": False,
"message": f"Error listing files: {str(e)}",
"data": None
}
def read_file(self, filepath: str, max_size: int = 1024 * 1024,
encoding: str = 'utf-8', chunk_size: int = None,
line_numbers: bool = False, syntax_highlight: bool = False) -> Dict:
"""
Read the contents of a file with advanced options
Args:
filepath: Path to the file to read
max_size: Maximum file size in bytes
encoding: File encoding to use
chunk_size: If set, read only this many bytes
line_numbers: Whether to include line numbers
syntax_highlight: Whether to detect and include syntax highlighting info
"""
try:
# Normalize path
norm_path = os.path.normpath(os.path.expanduser(filepath))
# Check if file exists
if not os.path.exists(norm_path):
return {
"success": False,
"message": f"File not found: {norm_path}",
"data": None
}
# Check if it's a directory
if os.path.isdir(norm_path):
return {
"success": False,
"message": f"Cannot read directory as file: {norm_path}",
"data": None
}
# Check file size
file_size = os.path.getsize(norm_path)
if file_size > max_size:
return {
"success": False,
"message": f"File too large ({file_size} bytes). Max size is {max_size} bytes.",
"data": None
}
# Detect binary file
try:
is_binary = False
with open(norm_path, 'rb') as f:
chunk = f.read(1024)
if b'\0' in chunk: # Simple binary detection
is_binary = True
if is_binary:
# For binary files, return hex dump instead of text content
with open(norm_path, 'rb') as f:
binary_data = f.read(chunk_size or max_size)
hex_dump = ' '.join(f'{b:02x}' for b in binary_data[:100]) # First 100 bytes
return {
"success": True,
"message": f"Successfully read binary file: {norm_path} ({file_size} bytes)",
"data": {
"content": f"Binary file: first 100 bytes: {hex_dump}...",
"is_binary": True,
"size": file_size,
"path": norm_path,
"binary_preview": hex_dump
}
}
except Exception as e:
logger.warning(f"Error detecting binary file: {e}")
# Read file content
content = ""
if chunk_size:
with open(norm_path, 'r', encoding=encoding, errors='replace') as f:
content = f.read(chunk_size)
truncated = file_size > chunk_size
else:
with open(norm_path, 'r', encoding=encoding, errors='replace') as f:
content = f.read()
truncated = False
# Process content based on options
if line_numbers:
lines = content.splitlines()
content_with_lines = "\n".join(f"{i+1}: {line}" for i, line in enumerate(lines))
content = content_with_lines
# Detect file type for syntax highlighting
file_type = None
if syntax_highlight:
ext = os.path.splitext(norm_path)[1].lower()
file_type_map = {
'.py': 'python', '.js': 'javascript', '.html': 'html',
'.css': 'css', '.json': 'json', '.md': 'markdown',
'.xml': 'xml', '.yaml': 'yaml', '.yml': 'yaml',
'.sh': 'bash', '.bash': 'bash', '.sql': 'sql',
'.c': 'c', '.cpp': 'cpp', '.h': 'c', '.java': 'java'
}
file_type = file_type_map.get(ext)
# Get file metadata
stat = os.stat(norm_path)
return {
"success": True,
"message": f"Successfully read file: {norm_path} ({len(content)} bytes)",
"data": {
"content": content,
"size": file_size,
"path": norm_path,
"encoding": encoding,
"truncated": truncated,
"line_count": content.count('\n') + 1,
"modified": time.ctime(stat.st_mtime),
"file_type": file_type,
"is_binary": False
}
}
except UnicodeDecodeError:
# If we hit a decode error, try to read as binary
try:
with open(norm_path, 'rb') as f:
binary_data = f.read(100) # Just read a small preview
hex_dump = ' '.join(f'{b:02x}' for b in binary_data)
return {
"success": True,
"message": f"File appears to be binary: {norm_path}",
"data": {
"content": f"Binary file: first 100 bytes: {hex_dump}...",
"is_binary": True,
"size": file_size,
"path": norm_path,
"binary_preview": hex_dump
}
}
except Exception as e:
logger.error(f"Error reading binary file: {e}")
return {
"success": False,
"message": f"Error reading file: {str(e)}",
"data": None
}
except Exception as e:
logger.error(f"Error reading file: {e}")
return {
"success": False,
"message": f"Error reading file: {str(e)}",
"data": None
}
def write_file(self, filepath: str, content: str, overwrite: bool = False,
append: bool = False, encoding: str = 'utf-8',
create_backup: bool = False, mode: str = None) -> Dict:
"""
Write content to a file with advanced options
Args:
filepath: Path to the file to write
content: Content to write to the file
overwrite: Whether to overwrite existing files
append: Whether to append to existing files
encoding: File encoding to use
create_backup: Whether to create a backup of existing file
mode: File permissions mode (e.g., '644')
"""
try:
# Normalize path
norm_path = os.path.normpath(os.path.expanduser(filepath))
# Safety check for system directories
system_dirs = ['/bin', '/sbin', '/usr/bin', '/usr/sbin', '/etc/passwd', '/etc/shadow']
if any(norm_path.startswith(d) for d in system_dirs) and self.safe_mode:
return {
"success": False,
"message": f"Safety check: Cannot write to system directory: {norm_path}",
"data": None
}
# Check if file exists
file_exists = os.path.exists(norm_path)
# Handle existing file
if file_exists:
if not (overwrite or append):
return {
"success": False,
"message": f"File already exists: {norm_path}. Set overwrite=true to overwrite or append=true to append.",
"data": None
}
# Create backup if requested
if create_backup:
backup_path = f"{norm_path}.bak"
shutil.copy2(norm_path, backup_path)
logger.info(f"Created backup of {norm_path} at {backup_path}")
# Create directory if it doesn't exist
os.makedirs(os.path.dirname(os.path.abspath(norm_path)), exist_ok=True)
# Determine write mode
write_mode = 'a' if append else 'w'
# Write file
with open(norm_path, write_mode, encoding=encoding) as f:
f.write(content)
# Set file mode if specified
if mode:
try:
mode_int = int(mode, 8)
os.chmod(norm_path, mode_int)
except ValueError:
logger.warning(f"Invalid mode format: {mode}. Expected octal (e.g., '644')")
# Add to history for potential undo
operation = "append" if append else "write"
self.history.append({
"operation": operation,
"path": norm_path,
"timestamp": time.time(),
"size": len(content),
"backup": f"{norm_path}.bak" if create_backup else None
})
return {
"success": True,
"message": f"Successfully {operation}ed {len(content)} bytes to {norm_path}",
"data": {
"path": norm_path,
"size": len(content),
"operation": operation,
"backup": f"{norm_path}.bak" if create_backup else None
}
}
except Exception as e:
logger.error(f"Error writing file: {e}")
return {
"success": False,
"message": f"Error writing file: {str(e)}",
"data": None
}
def copy_file(self, source: str, destination: str, overwrite: bool = False) -> Dict:
"""Copy a file from source to destination"""
try:
# Normalize paths
norm_source = os.path.normpath(os.path.expanduser(source))
norm_dest = os.path.normpath(os.path.expanduser(destination))
# Check if source exists
if not os.path.exists(norm_source):
return {
"success": False,
"message": f"Source file not found: {norm_source}",
"data": None
}
# Check if destination exists and overwrite is False
if os.path.exists(norm_dest) and not overwrite:
return {
"success": False,
"message": f"Destination file already exists: {norm_dest}. Set overwrite=true to overwrite.",
"data": None
}
# Create destination directory if it doesn't exist
os.makedirs(os.path.dirname(os.path.abspath(norm_dest)), exist_ok=True)
# Copy file
shutil.copy2(norm_source, norm_dest)
return {
"success": True,
"message": f"Successfully copied {norm_source} to {norm_dest}",
"data": {
"source": norm_source,
"destination": norm_dest
}
}
except Exception as e:
logger.error(f"Error copying file: {e}")
return {
"success": False,
"message": f"Error copying file: {str(e)}",
"data": None
}
def delete_file(self, filepath: str, recursive: bool = False) -> Dict:
"""Delete a file or directory"""
try:
# Normalize path
norm_path = os.path.normpath(os.path.expanduser(filepath))
# Check if file exists
if not os.path.exists(norm_path):
return {
"success": False,
"message": f"File not found: {norm_path}",
"data": None
}
# Delete file or directory
if os.path.isdir(norm_path):
if recursive:
shutil.rmtree(norm_path)
else:
os.rmdir(norm_path)
else:
os.remove(norm_path)
return {
"success": True,
"message": f"Successfully deleted: {norm_path}",
"data": {
"path": norm_path,
"was_directory": os.path.isdir(norm_path)
}
}
except Exception as e:
logger.error(f"Error deleting file: {e}")
return {
"success": False,
"message": f"Error deleting file: {str(e)}",
"data": None
}
class CodingTools:
"""
Advanced tools for code execution and management with sandboxing and analysis
"""
def __init__(self):
logger.info("Initializing advanced coding tools")
self.temp_dir = os.path.join(os.getcwd(), "temp_code")
self.sandbox_dir = os.path.join(os.getcwd(), "sandbox")
self.history_dir = os.path.join(os.getcwd(), "code_history")
# Create necessary directories
for directory in [self.temp_dir, self.sandbox_dir, self.history_dir]:
os.makedirs(directory, exist_ok=True)
# Track execution history
self.execution_history = []
# Restricted commands that won't be allowed in shell execution
# Security Hint: Regularly review and update restricted commands and allowed imports.
# Consider finer-grained controls based on agent tasks or user roles.
self.restricted_commands = [
"rm -rf", "mkfs", "dd if=/dev/zero", ":(){ :|:& };:", # Fork bomb
"> /dev/sda", "chmod -R 777 /", "mv /* /dev/null"
]
# Default allowed imports for Python code
self.allowed_imports = {
"safe": ["math", "random", "datetime", "collections", "itertools",
"functools", "re", "json", "csv", "os.path", "time"],
"data_science": ["numpy", "pandas", "matplotlib", "seaborn", "sklearn"],
"standard_library": ["os", "sys", "subprocess", "pathlib", "shutil"],
"web": ["requests", "bs4", "urllib"],
"all": [] # Empty means no restrictions
}
# Current security level
self.security_level = "standard_library" # Default level
def set_security_level(self, level: str) -> Dict:
"""Set the security level for code execution"""
valid_levels = ["safe", "data_science", "standard_library", "web", "all"]
if level not in valid_levels:
return {
"success": False,
"message": f"Invalid security level: {level}. Valid levels are: {', '.join(valid_levels)}",
"data": None
}
self.security_level = level
return {
"success": True,
"message": f"Security level set to: {level}",
"data": {
"level": level,
"allowed_imports": self.allowed_imports[level] if level != "all" else "All imports allowed"
}
}
def _check_code_safety(self, code: str) -> Tuple[bool, str]:
"""Check if Python code is safe to execute"""
import ast
# Don't restrict if security level is 'all'
if self.security_level == "all":
return True, "No restrictions applied"
try:
# Parse the code
tree = ast.parse(code)
# Check for imports
imports = []
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for name in node.names:
imports.append(name.name.split('.')[0])
elif isinstance(node, ast.ImportFrom):