-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathcode_assistant.py
More file actions
3068 lines (2523 loc) · 132 KB
/
code_assistant.py
File metadata and controls
3068 lines (2523 loc) · 132 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
"""
Code Assistant - A command-line interface for interacting with Ollama models
This script provides a command-line interface for interacting with Ollama models,
allowing users to ask questions, search the web, edit files, and run commands.
Features:
- Chat with Ollama models
- Search the web for information
- Edit files with AI assistance
- Run commands with AI guidance
- Create new empty files
- Switch between different Ollama models
- Display or hide AI "thinking" process
- Read specific line ranges from files using [filename:start-end] syntax
Usage:
python code_assistant.py [query]
Examples:
python code_assistant.py "Explain how async/await works in JavaScript"
python code_assistant.py "Search: latest developments in quantum computing"
python code_assistant.py "Edit: [main.py] Add error handling to the main function"
python code_assistant.py "Run: Write a script to sort files by extension"
python code_assistant.py "Create: [newfile.py]"
python code_assistant.py "Model: llama3"
python code_assistant.py "Show only lines 10-20 of my file [myfile.py:10-20]"
"""
import requests
import re
import json
import sys
import os
import difflib
import subprocess
import chardet # Import chardet at the module level
from pathlib import Path
from bs4 import BeautifulSoup
from urllib.parse import quote_plus, urlparse
from shutil import copyfile
from colorama import init, Fore, Style
# Initialize colorama for cross-platform color support
init()
# Configuration
OLLAMA_BASE_URL = "http://localhost:11434" # Base URL for Ollama server. Change this if your Ollama instance runs elsewhere.
OLLAMA_API_URL = OLLAMA_BASE_URL + "/api/chat"
DEFAULT_MODEL = "qwq" # Change to your preferred model
CURRENT_MODEL = DEFAULT_MODEL # Track the currently selected model
MAX_SEARCH_RESULTS = 5 # Maximum number of search results to include
MAX_URL_CONTENT_LENGTH = 10000 # Maximum characters to include from URL content
SHOW_THINKING = False # Default to hiding thinking blocks
MAX_THINKING_LENGTH = 5000 # Maximum length of thinking block to display
DEFAULT_TIMEOUT = 500 # Default timeout for LLM operations in seconds
WORKING_DIRECTORY = None # Working directory for file operations
# Command execution safety
SAFE_COMMAND_PREFIXES = ["python", "python3", "node", "npm", "git", "ls", "dir", "cd", "type", "cat", "make", "dotnet", "gradle", "mvn", "cargo", "rustc", "go", "test", "echo"]
DANGEROUS_COMMANDS = ["rm", "del", "sudo", "chmod", "chown", "mv", "cp", "rmdir", "rd", "format", "mkfs", "dd", ">", ">>"]
def check_ollama_connection():
"""Verify the Ollama server is running and accessible."""
try:
print("Checking Ollama connection...")
response = requests.get(OLLAMA_BASE_URL + "/api/tags", timeout=5)
# This will raise an HTTPError for status codes 4XX/5XX
response.raise_for_status()
data = response.json()
models = [model["name"] for model in data.get("models", [])]
if models:
print("Ollama connection successful. Available models:")
print(f"Available models: {', '.join(models)}")
for model in models:
print(f"- {model}")
else:
print("\nOllama is running but no models are available.")
print("\nTo use this tool, you need to pull a model first. Run this command:")
print("\n ollama pull <model_name>")
print("\nRecommended starter models:")
print("- llama3 (Meta's Llama 3 8B model)")
print("- mistral (Mistral AI's 7B model)")
print("- neural-chat (Intelligent Neural Labs 7B model)")
print("\nSee https://ollama.com/library for more options.")
print()
return True
except requests.exceptions.HTTPError as e:
# Handle HTTP error responses with detailed information
status_code = getattr(e.response, 'status_code', '?')
reason = getattr(e.response, 'reason', 'Unknown reason')
error_text = getattr(e.response, 'text', '')
print(f"\nError connecting to Ollama: HTTP {status_code} {reason}")
if error_text:
print(f"Details: {error_text}")
# Provide more specific guidance based on the status code
if status_code == 404:
print("\nThe Ollama API endpoint was not found. Please check your Ollama installation.")
elif status_code >= 500:
print("\nThe Ollama server encountered an internal error.")
print("Try restarting the Ollama server with 'ollama serve' in a separate terminal.")
print()
return False
except (requests.exceptions.ConnectionError, requests.exceptions.Timeout):
print("\nError: Cannot connect to Ollama. Please ensure Ollama is running.")
print("If not installed, download from: https://ollama.com/download")
print("After installation, run 'ollama serve' in a separate terminal.")
print()
return False
except Exception as e:
print(f"\nUnexpected error when checking Ollama connection: {e}")
print()
return False
def detect_file_encoding(file_path):
"""Detect the encoding of a file using a combination of BOM detection,
pattern analysis, and chardet for robust encoding detection.
Returns:
tuple: (encoding, bom) where bom is True if the file has a BOM
"""
# First check for BOM using binary mode
try:
with open(file_path, 'rb') as f:
# Read more bytes for better pattern detection
raw = f.read(32) # Read first 32 bytes for more reliable detection
# Empty file check
if not raw:
return 'utf-8', False
# Check for BOM markers - BOM detection is the most reliable method
if raw.startswith(b'\xef\xbb\xbf'): # UTF-8 BOM
return 'utf-8-sig', True
elif raw.startswith(b'\xff\xfe\x00\x00'): # UTF-32 LE BOM
return 'utf-32-le', True
elif raw.startswith(b'\x00\x00\xfe\xff'): # UTF-32 BE BOM
return 'utf-32-be', True
elif raw.startswith(b'\xff\xfe'): # UTF-16 LE BOM
return 'utf-16-le', True
elif raw.startswith(b'\xfe\xff'): # UTF-16 BE BOM
return 'utf-16-be', True
# No BOM found, use pattern detection for common encodings
# The order of these checks is important - check more specific patterns first
# Check for UTF-32 patterns (must be checked before UTF-16)
if len(raw) >= 16:
# UTF-32-LE pattern: every 4th byte is non-zero, others are zero
# Common for ASCII text in UTF-32-LE
utf32_le_pattern = True
for i in range(0, min(16, len(raw)), 4):
if i+3 < len(raw):
# Check if bytes follow the pattern: X 0 0 0 (for ASCII in UTF-32-LE)
if not (raw[i] != 0 and raw[i+1] == 0 and raw[i+2] == 0 and raw[i+3] == 0):
utf32_le_pattern = False
break
if utf32_le_pattern and len(raw) >= 8:
return 'utf-32-le', False
# UTF-32-BE pattern: first byte of each 4-byte group is zero
# Common for ASCII text in UTF-32-BE
utf32_be_pattern = True
for i in range(0, min(16, len(raw)), 4):
if i+3 < len(raw):
# Check if bytes follow the pattern: 0 0 0 X (for ASCII in UTF-32-BE)
if not (raw[i] == 0 and raw[i+1] == 0 and raw[i+2] == 0 and raw[i+3] != 0):
utf32_be_pattern = False
break
if utf32_be_pattern and len(raw) >= 8:
return 'utf-32-be', False
# Check for UTF-16 patterns - more strict checking to avoid false positives
if len(raw) >= 8:
# UTF-16-LE pattern: alternating non-zero and zero bytes for ASCII
utf16_le_pattern = True
zero_byte_count = 0
# Check if pattern generally follows: X 0 X 0 X 0 (for ASCII in UTF-16-LE)
for i in range(min(16, len(raw))):
if i % 2 == 1 and raw[i] == 0:
zero_byte_count += 1
# Check if at least half of even-indexed bytes are non-zero
# and most odd-indexed bytes are zero (for ASCII text)
non_zero_odd = sum(1 for i in range(0, min(16, len(raw)), 2) if raw[i] != 0)
if zero_byte_count >= 4 and non_zero_odd >= 3:
return 'utf-16-le', False
# UTF-16-BE pattern: zero byte followed by non-zero byte for ASCII
utf16_be_pattern = True
zero_byte_count = 0
# Check if pattern generally follows: 0 X 0 X 0 X (for ASCII in UTF-16-BE)
for i in range(min(16, len(raw))):
if i % 2 == 0 and raw[i] == 0:
zero_byte_count += 1
# Check if at least half of odd-indexed bytes are non-zero
# and most even-indexed bytes are zero (for ASCII text)
non_zero_even = sum(1 for i in range(1, min(16, len(raw)), 2) if raw[i] != 0)
if zero_byte_count >= 4 and non_zero_even >= 3:
return 'utf-16-be', False
# Rewind the file for chardet analysis
f.seek(0)
# Sample the first 4KB of the file for better detection
raw_data = f.read(4096)
# Use chardet for encoding detection when patterns aren't conclusive
try:
result = chardet.detect(raw_data)
encoding = result['encoding']
confidence = result['confidence']
if encoding:
if confidence < 0.7:
print(f"Warning: Low confidence ({confidence:.2f}) in detected encoding: {encoding}")
return encoding, False
except Exception as e:
print(f"Warning: Error using chardet: {e}")
# Fall back to the legacy method
return _legacy_detect_file_encoding(file_path)
except Exception as e:
print(f"Warning: Error detecting encoding: {e}")
# Default to UTF-8 if all detection methods fail
return 'utf-8', False
def _legacy_detect_file_encoding(file_path):
"""Legacy method to detect file encoding without chardet."""
# Try to detect encoding with these common types
encodings_to_try = ['utf-8', 'utf-8-sig', 'utf-16', 'utf-16-le', 'utf-16-be', 'latin-1', 'cp1252']
# Try each encoding
for encoding in encodings_to_try:
try:
with open(file_path, 'r', encoding=encoding) as f:
f.read()
# If we got here, the encoding worked
return encoding, encoding.endswith('-sig')
except UnicodeDecodeError:
continue
except Exception:
break
# Default to UTF-8 if we couldn't detect
return 'utf-8', False
def read_file_content(file_path, start_line=None, end_line=None):
"""
Read content from a file, handling potential errors and encoding issues.
Args:
file_path (str): Path to the file to read
start_line (int, optional): Starting line number (1-indexed)
end_line (int, optional): Ending line number (1-indexed)
Returns:
str: File content or None if file not found or error occurs
"""
try:
# Ensure the file path is within the working directory if set
if WORKING_DIRECTORY and not os.path.isabs(file_path):
file_path = os.path.join(WORKING_DIRECTORY, file_path)
elif WORKING_DIRECTORY and os.path.isabs(file_path):
# Check if the absolute path is within the working directory
if not os.path.abspath(file_path).startswith(WORKING_DIRECTORY):
error_msg = f"Error: File '{file_path}' is outside the working directory. Access denied."
print(f"{Fore.RED}{error_msg}{Style.RESET_ALL}")
return None
# Check if file exists
if not os.path.exists(file_path):
error_msg = f"Error: File '{file_path}' not found."
print(f"{Fore.RED}{error_msg}{Style.RESET_ALL}")
# Try to provide helpful suggestions
dir_path = os.path.dirname(file_path) or '.'
if os.path.exists(dir_path):
try:
similar_files = [f for f in os.listdir(dir_path)
if os.path.isfile(os.path.join(dir_path, f)) and
f.endswith(os.path.splitext(file_path)[1])]
if similar_files:
print(f"{Fore.YELLOW}Similar files in the directory:{Style.RESET_ALL}")
for f in similar_files[:5]: # Show up to 5 similar files
print(f"{Fore.YELLOW}- {f}{Style.RESET_ALL}")
if len(similar_files) > 5:
print(f"{Fore.YELLOW}... and {len(similar_files) - 5} more{Style.RESET_ALL}")
except Exception:
pass # Ignore errors in the suggestion logic
return None
# Check if file is readable
if not os.access(file_path, os.R_OK):
error_msg = f"Error: File '{file_path}' is not readable. Check file permissions."
print(f"{Fore.RED}{error_msg}{Style.RESET_ALL}")
return None
# Check file size
file_size = os.path.getsize(file_path)
if file_size > 10 * 1024 * 1024: # 10 MB
print(f"{Fore.YELLOW}Warning: File '{file_path}' is large ({file_size / 1024 / 1024:.2f} MB).{Style.RESET_ALL}")
print(f"{Fore.YELLOW}Reading large files may cause performance issues.{Style.RESET_ALL}")
try:
# Detect the encoding
encoding, has_bom = detect_file_encoding(file_path)
# Read the file with the detected encoding
with open(file_path, 'r', encoding=encoding) as file:
if start_line is None and end_line is None:
# Read the entire file
content = file.read()
else:
# Read specific lines
lines = file.readlines()
# Validate line numbers
total_lines = len(lines)
# Adjust for 1-indexed input to 0-indexed list
start_idx = max(0, (start_line or 1) - 1)
# If end_line is None, read to the end of the file
end_idx = min(total_lines, end_line) if end_line is not None else total_lines
# Warn if line numbers are out of range
if start_line and start_line > total_lines:
print(f"{Fore.YELLOW}Warning: Start line {start_line} is beyond the end of the file ({total_lines} lines).{Style.RESET_ALL}")
start_idx = 0
if end_line and end_line > total_lines:
print(f"{Fore.YELLOW}Warning: End line {end_line} is beyond the end of the file ({total_lines} lines). Reading to the end.{Style.RESET_ALL}")
# Extract the requested lines
selected_lines = lines[start_idx:end_idx]
content = ''.join(selected_lines)
# Add a note about the line range
line_info = f"Lines {start_idx + 1}-{end_idx} of {total_lines} total lines"
content = f"--- {line_info} ---\n{content}"
# Let the user know if we're using a non-standard encoding
if encoding.lower() not in ['utf-8', 'utf-8-sig', 'ascii']:
print(f"{Fore.CYAN}Note: File '{file_path}' was read with {encoding} encoding.{Style.RESET_ALL}")
return content
except UnicodeDecodeError as e:
print(f"{Fore.RED}Error: Failed to decode file '{file_path}' with {encoding} encoding.{Style.RESET_ALL}")
print(f"{Fore.YELLOW}Error details: {str(e)}{Style.RESET_ALL}")
# If all else fails, try binary mode as a last resort
try:
with open(file_path, 'rb') as file:
binary_content = file.read()
# Try to decode as latin-1 which can handle any byte value
print(f"{Fore.YELLOW}Using binary fallback with latin-1 encoding for '{file_path}'.{Style.RESET_ALL}")
print(f"{Fore.YELLOW}Some characters may not display correctly.{Style.RESET_ALL}")
return binary_content.decode('latin-1', errors='replace')
except Exception as e2:
error_type = type(e2).__name__
print(f"{Fore.RED}Error reading file in binary mode: {error_type} - {str(e2)}{Style.RESET_ALL}")
return None
except Exception as e:
error_type = type(e).__name__
print(f"{Fore.RED}Error reading file '{file_path}': {error_type} - {str(e)}{Style.RESET_ALL}")
# If all else fails, try binary mode as a last resort
try:
with open(file_path, 'rb') as file:
binary_content = file.read()
# Try to decode as latin-1 which can handle any byte value
print(f"{Fore.YELLOW}Using binary fallback with latin-1 encoding for '{file_path}'.{Style.RESET_ALL}")
print(f"{Fore.YELLOW}Some characters may not display correctly.{Style.RESET_ALL}")
return binary_content.decode('latin-1', errors='replace')
except Exception as e2:
error_type = type(e2).__name__
print(f"{Fore.RED}Error reading file in binary mode: {error_type} - {str(e2)}{Style.RESET_ALL}")
return None
except Exception as e:
error_type = type(e).__name__
print(f"{Fore.RED}Unexpected error accessing file '{file_path}': {error_type} - {str(e)}{Style.RESET_ALL}")
return None
def write_file_content(file_path, content, create_backup=True):
"""Write content to a file, preserving the original encoding."""
try:
# Ensure the file path is within the working directory if set
if WORKING_DIRECTORY and not os.path.isabs(file_path):
file_path = os.path.join(WORKING_DIRECTORY, file_path)
elif WORKING_DIRECTORY and os.path.isabs(file_path):
# Check if the absolute path is within the working directory
if not os.path.abspath(file_path).startswith(WORKING_DIRECTORY):
error_msg = f"Error: Cannot write to '{file_path}' as it is outside the working directory. Access denied."
print(f"{Fore.RED}{error_msg}{Style.RESET_ALL}")
return False
# Create parent directories if they don't exist
parent_dir = os.path.dirname(file_path)
if parent_dir and not os.path.exists(parent_dir):
os.makedirs(parent_dir)
print(f"{Fore.GREEN}Created directory: {parent_dir}{Style.RESET_ALL}")
# Get the file's original encoding if it exists
original_encoding = 'utf-8' # Default encoding
has_bom = False
if os.path.exists(file_path):
# Detect the existing encoding
original_encoding, has_bom = detect_file_encoding(file_path)
# Create a backup if requested
if create_backup:
backup_path = f"{file_path}.bak"
try:
copyfile(file_path, backup_path)
print(f"Created backup at {backup_path}")
except Exception as e:
print(f"Warning: Could not create backup: {e}")
# Write with detected encoding
with open(file_path, 'w', encoding=original_encoding) as file:
file.write(content)
# Log the encoding used
if original_encoding != 'utf-8' and original_encoding != 'utf-8-sig':
print(f"Note: File '{file_path}' was written with {original_encoding} encoding to match the original.")
return True
except Exception as e:
print(f"Error writing to file '{file_path}': {e}")
return False
def generate_colored_diff(original, modified, file_path):
"""Generate a colored diff between original and modified content."""
diff = difflib.unified_diff(
original.splitlines(),
modified.splitlines(),
fromfile=f'a/{file_path}',
tofile=f'b/{file_path}',
lineterm=''
)
colored_diff = []
for line in diff:
if line.startswith('+'):
colored_diff.append(f"{Fore.GREEN}{line}{Style.RESET_ALL}")
elif line.startswith('-'):
colored_diff.append(f"{Fore.RED}{line}{Style.RESET_ALL}")
elif line.startswith('^'):
colored_diff.append(f"{Fore.BLUE}{line}{Style.RESET_ALL}")
elif line.startswith('@'):
colored_diff.append(f"{Fore.CYAN}{line}{Style.RESET_ALL}")
else:
colored_diff.append(line)
return '\n'.join(colored_diff)
def get_edit_file_paths(query):
"""
Extract file paths from an edit query.
This function is maintained for backward compatibility.
It uses extract_file_paths_and_urls internally and returns just the file paths.
"""
# Use the new extract_file_paths_and_urls function
clean_query, file_items, _ = extract_file_paths_and_urls(query)
# Extract just the file paths from the file items
file_paths = []
for item in file_items:
if isinstance(item, tuple):
file_paths.append(item[0])
else:
file_paths.append(item)
return file_paths
def is_safe_command(command):
"""
Check if a command is likely safe to execute using a whitelist approach.
Returns:
tuple: (is_safe, reason) where is_safe is a boolean and reason is a string or None
"""
# Trim the command
command = command.strip()
# Check for command separators (;, &&, ||) which could chain dangerous commands
for separator in [';', '&&', '||']:
if separator in command:
# Split by separator and check each command separately
sep_commands = [cmd.strip() for cmd in command.split(separator)]
for i, cmd in enumerate(sep_commands):
is_safe, reason = is_safe_command(cmd)
if not is_safe:
return False, f"Unsafe command in chain (part {i+1}): {reason}"
return True, None
# Check for pipe operators which could chain dangerous commands
if '|' in command:
# Split by pipe and check each command separately
pipe_commands = [cmd.strip() for cmd in command.split('|')]
for i, cmd in enumerate(pipe_commands):
is_safe, reason = is_safe_command(cmd)
if not is_safe:
return False, f"Unsafe command in pipe (part {i+1}): {reason}"
return True, None
# Split the command to get the base command and arguments
# This handles quoted arguments correctly
try:
import shlex
parts = shlex.split(command)
except Exception:
return False, "Could not parse command safely"
if not parts:
return False, "Empty command"
base_cmd = parts[0].lower()
# Whitelist approach - only explicitly allowed commands are permitted
ALLOWED_COMMANDS = {
# Python commands with restrictions
"python": lambda args: _check_python_args(args),
"python3": lambda args: _check_python_args(args),
# File listing and navigation (safe)
"ls": lambda args: (True, None),
"dir": lambda args: (True, None),
"cd": lambda args: (True, None),
"pwd": lambda args: (True, None),
# File viewing and text processing (safe)
"cat": lambda args: _check_file_args(args),
"type": lambda args: _check_file_args(args),
"more": lambda args: _check_file_args(args),
"grep": lambda args: (True, None),
"findstr": lambda args: (True, None),
"find": lambda args: _check_find_args(args),
"sort": lambda args: (True, None),
"head": lambda args: (True, None),
"tail": lambda args: (True, None),
# Git commands with restrictions
"git": lambda args: _check_git_args(args),
# Package managers with restrictions
"npm": lambda args: _check_npm_args(args),
"pip": lambda args: _check_pip_args(args),
# Build tools (generally safe)
"make": lambda args: (True, None),
"dotnet": lambda args: (True, None),
"gradle": lambda args: (True, None),
"mvn": lambda args: (True, None),
"cargo": lambda args: (True, None),
# Programming language tools (generally safe)
"rustc": lambda args: (True, None),
"go": lambda args: (True, None),
# Testing and echo (safe)
"test": lambda args: (True, None),
"echo": lambda args: (True, None),
}
# Check if the base command is in our whitelist
if base_cmd not in ALLOWED_COMMANDS:
return False, f"Command '{base_cmd}' is not in the allowed list"
# Apply the specific checker for this command
args = parts[1:] if len(parts) > 1 else []
is_safe, reason = ALLOWED_COMMANDS[base_cmd](args)
return is_safe, reason
def _check_python_args(args):
"""Check if Python command arguments are safe."""
if not args:
return True, None
# Check for dangerous flags
dangerous_flags = ['-c', '--command']
for flag in dangerous_flags:
if flag in args:
return False, f"Python with '{flag}' flag is not allowed for security reasons"
# Check if the script file exists
if args and not args[0].startswith('-'):
script_path = args[0]
# For testing purposes, we'll allow non-existent scripts if they don't contain suspicious patterns
if '..' in script_path or script_path.startswith('/') or ':' in script_path:
return False, f"Python script path '{script_path}' contains suspicious patterns"
if os.path.exists(script_path):
# If the file exists, we could do additional checks here
# For example, scan the file content for dangerous imports
pass
return True, None
def _check_file_args(args):
"""Check if file-related command arguments are safe."""
# Block any argument containing path traversal attempts
for arg in args:
if '..' in arg:
return False, "Path traversal detected in arguments"
return True, None
def _check_git_args(args):
"""Check if git command arguments are safe."""
if not args:
return True, None
# Block potentially dangerous git commands
dangerous_git_cmds = ['clean', 'reset', 'push', 'filter-branch']
if args and args[0] in dangerous_git_cmds:
return False, f"Git command '{args[0]}' requires manual review"
return True, None
def _check_npm_args(args):
"""Check if npm command arguments are safe."""
if not args:
return True, None
# Block potentially dangerous npm commands
dangerous_npm_cmds = ['publish', 'unpublish', 'deprecate', 'access', 'adduser', 'login']
if args and args[0] in dangerous_npm_cmds:
return False, f"NPM command '{args[0]}' requires manual review"
return True, None
def _check_pip_args(args):
"""Check if pip command arguments are safe."""
if not args:
return True, None
# Block potentially dangerous pip commands
dangerous_pip_cmds = ['uninstall']
if args and args[0] in dangerous_pip_cmds:
return False, f"Pip command '{args[0]}' requires manual review"
return True, None
def _check_find_args(args):
"""Check if find command arguments are safe."""
# Block any argument containing potentially dangerous options
dangerous_options = ['-exec', '-delete']
for arg in args:
if arg in dangerous_options:
return False, f"Find with '{arg}' option is not allowed for security reasons"
return True, None
def execute_command(command):
"""Execute a command and return its output."""
try:
# Parse the command into arguments
import shlex
try:
args = shlex.split(command)
except Exception:
# If parsing fails, fall back to shell=True but with extra caution
return _execute_with_shell(command)
if not args:
return "Error: Empty command"
# Execute without shell when possible (more secure)
result = subprocess.run(
args,
shell=False,
capture_output=True,
text=True,
cwd=WORKING_DIRECTORY if WORKING_DIRECTORY else None
)
# Prepare output
output = ""
if result.stdout:
output += f"Standard Output:\n{result.stdout}\n"
if result.stderr:
output += f"Standard Error:\n{result.stderr}\n"
output += f"Exit Code: {result.returncode}"
return output
except Exception as e:
return f"Error executing command: {e}"
def _execute_with_shell(command):
"""Execute a command using shell=True as a fallback method."""
try:
# Run the command with shell=True (less secure, but handles complex commands)
result = subprocess.run(
command,
shell=True,
capture_output=True,
text=True,
cwd=WORKING_DIRECTORY if WORKING_DIRECTORY else None
)
# Prepare output
output = "Note: Command executed with shell=True (less secure)\n"
if result.stdout:
output += f"Standard Output:\n{result.stdout}\n"
if result.stderr:
output += f"Standard Error:\n{result.stderr}\n"
output += f"Exit Code: {result.returncode}"
return output
except Exception as e:
return f"Error executing command with shell: {e}"
def fetch_url_content(url):
"""Fetch and extract text content from a URL."""
try:
# Add scheme if missing
if not url.startswith(('http://', 'https://')):
url = 'https://' + url
print(f"Added https:// prefix to URL: {url}")
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
}
print(f"Fetching content from: {url}")
try:
response = requests.get(url, headers=headers, timeout=10)
except requests.exceptions.Timeout:
return f"Failed to fetch: Connection to {url} timed out after 10 seconds. The server might be slow or unavailable."
except requests.exceptions.ConnectionError:
return f"Failed to fetch: Could not establish a connection to {url}. Please check your internet connection or verify the URL is correct."
except requests.exceptions.TooManyRedirects:
return f"Failed to fetch: Too many redirects when accessing {url}. The URL might be in a redirect loop."
if response.status_code == 200:
# Try to determine content type
content_type = response.headers.get('Content-Type', '').lower()
print(f"Content type: {content_type}")
# If it's HTML, parse with BeautifulSoup
if 'text/html' in content_type:
try:
soup = BeautifulSoup(response.text, 'html.parser')
# Remove script and style elements
for script in soup(["script", "style"]):
script.extract()
# Get text and clean it up
text = soup.get_text(separator='\n')
lines = (line.strip() for line in text.splitlines())
text = '\n'.join(line for line in lines if line)
# Truncate if too long
if len(text) > MAX_URL_CONTENT_LENGTH:
text = text[:MAX_URL_CONTENT_LENGTH] + "... [content truncated]"
print(f"Content truncated to {MAX_URL_CONTENT_LENGTH} characters")
return text
except Exception as e:
print(f"Error parsing HTML content: {e}")
# Fall back to raw text if HTML parsing fails
text = response.text
if len(text) > MAX_URL_CONTENT_LENGTH:
text = text[:MAX_URL_CONTENT_LENGTH] + "... [content truncated]"
return text
else:
# For non-HTML content, just return the raw text
text = response.text
if len(text) > MAX_URL_CONTENT_LENGTH:
text = text[:MAX_URL_CONTENT_LENGTH] + "... [content truncated]"
print(f"Content truncated to {MAX_URL_CONTENT_LENGTH} characters")
return text
elif response.status_code == 404:
return f"Failed to fetch: The requested URL {url} was not found (404). Please check if the URL is correct."
elif response.status_code == 403:
return f"Failed to fetch: Access to {url} is forbidden (403). The website may be blocking automated access."
elif response.status_code == 500:
return f"Failed to fetch: The server at {url} encountered an internal error (500). Please try again later."
elif response.status_code == 429:
return f"Failed to fetch: Too many requests to {url} (429). The website is rate-limiting access."
else:
return f"Failed to fetch: {url}: HTTP status {response.status_code}"
except requests.exceptions.RequestException as e:
error_type = type(e).__name__
return f"Failed to fetch: Request failed for {url}: {error_type} - {str(e)}"
except Exception as e:
error_type = type(e).__name__
return f"Failed to fetch: Unexpected {error_type} when processing {url}: {str(e)}"
def duckduckgo_search(query, num_results=MAX_SEARCH_RESULTS):
"""Perform a web search using DuckDuckGo and return structured results."""
print(f"Searching the web for: {query}")
try:
# Use DuckDuckGo HTML search instead of API since their API is limited
search_url = f"https://html.duckduckgo.com/html/?q={quote_plus(query)}"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
}
response = requests.get(search_url, headers=headers, timeout=10)
if response.status_code != 200:
print(f"Search failed: HTTP status {response.status_code}")
return []
soup = BeautifulSoup(response.text, 'html.parser')
results = []
# Find search result elements
for result in soup.select('.result'):
title_elem = result.select_one('.result__title')
snippet_elem = result.select_one('.result__snippet')
url_elem = result.select_one('.result__url')
if title_elem and snippet_elem:
title = title_elem.get_text().strip()
snippet = snippet_elem.get_text().strip()
# Get URL from href if available
url = ""
if url_elem:
url = url_elem.get_text().strip()
elif title_elem.a and title_elem.a.get('href'):
href = title_elem.a.get('href')
if href.startswith('/'):
# Extract URL from DuckDuckGo redirect
match = re.search(r'uddg=([^&]+)', href)
if match:
url = match.group(1)
results.append({
'title': title,
'snippet': snippet,
'url': url
})
if len(results) >= num_results:
break
print(f"Found {len(results)} search results.")
return results
except Exception as e:
print(f"Error during web search: {e}")
return []
def extract_file_paths_and_urls(query):
"""
Extract file paths and URLs enclosed in square brackets from the query.
Supports line range specifications in the format [filename:start-end], [filename:start-], or [filename:-end].
"""
# Updated pattern to handle nested brackets
pattern = r'\[((?:[^\[\]]|\[(?:[^\[\]]|\[[^\[\]]*\])*\])*)\]'
matches = re.findall(pattern, query)
# Separate file paths and URLs
file_paths = []
urls = []
# Process matches first
for match in matches:
# Only process non-empty matches for file/url categorization
if match.strip():
# Check if it's a URL - must start with http/https or have a valid domain structure
if match.startswith(('http://', 'https://')) or (
# Check for domain-like structure (e.g. example.com/path)
# but exclude common file path patterns like ./path or ../path
not match.startswith(('./', '../')) and
'.' in match and
'/' in match and
not ':' in match and
# Look for domain-like structure (letters/numbers followed by dot)
re.search(r'^[a-zA-Z0-9][a-zA-Z0-9-]*\.[a-zA-Z]{2,}', match)
):
urls.append(match)
else:
# Check if there's a line range specification
if ':' in match:
parts = match.split(':', 1)
file_path = parts[0]
line_range = parts[1]
# Parse the line range
start_line = None
end_line = None
if '-' in line_range:
range_parts = line_range.split('-', 1)
# Handle start line
if range_parts[0].strip():
try:
start_line = int(range_parts[0].strip())
except ValueError:
print(f"Warning: Invalid start line number in '{match}', using default")
# Handle end line
if len(range_parts) > 1 and range_parts[1].strip():
try:
end_line = int(range_parts[1].strip())
except ValueError:
print(f"Warning: Invalid end line number in '{match}', using default")
else:
# Single line number
try:
start_line = int(line_range.strip())
end_line = start_line + 1 # Read just this one line
except ValueError:
print(f"Warning: Invalid line number in '{match}', using default")
file_paths.append((file_path, start_line, end_line))
else:
# No line range, just a file path
file_paths.append((match, None, None))
# Handle clean query by preserving empty brackets and maintaining spacing
clean_query = query
# Find all bracket positions
bracket_positions = []
stack = []
for i, char in enumerate(query):
if char == '[':
stack.append(i)
elif char == ']' and stack:
start = stack.pop()
bracket_positions.append((start, i + 1))
# Sort positions in reverse order to replace from end to start
bracket_positions.sort(reverse=True)
# Replace each bracketed section
for start, end in bracket_positions:
content = query[start + 1:end - 1]
if not content.strip(): # Empty brackets
clean_query = clean_query[:start] + '[]' + clean_query[end:]
else: # Non-empty brackets
# Check if we're next to punctuation
next_char = clean_query[end:end + 1] if end < len(clean_query) else ''
prev_char = clean_query[start - 1:start] if start > 0 else ''
# Add double spaces between words, single space around punctuation
if next_char in ',.:;' or prev_char in ',.:;':
clean_query = clean_query[:start] + ' ' + clean_query[end:]
else:
# Find the next non-space character
next_word = False
for i in range(end, len(clean_query)):
if clean_query[i].isalnum():
next_word = True
break
elif clean_query[i] in ',.:;':
next_word = False
break
# Find the previous non-space character
prev_word = False
for i in range(start - 1, -1, -1):
if clean_query[i].isalnum():
prev_word = True
break