-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtask_manager.py
More file actions
2019 lines (1685 loc) · 81.3 KB
/
task_manager.py
File metadata and controls
2019 lines (1685 loc) · 81.3 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
# task_manager.py
import os
import subprocess
import asyncio
import logging
import webbrowser
import shutil
import pyautogui
from PIL import Image
from datetime import datetime
import time
import ai_engine
import pygetwindow as gw
import inspect
# from pywinauto import Desktop <-- Moved to function scope to avoid COM conflicts
from googlesearch import search
import requests
from bs4 import BeautifulSoup
import traceback
import json
import config
import ctypes
import web_automation
import pyperclip
import pythoncom
from types import SimpleNamespace
from skill_manager import skill_manager
import enhanced_system
import desktop_state
# logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
# Global callback for status updates (to be set by GUI)
status_callback = None
permission_callback = None
tool_execution_callback = None
stop_execution_flag = False
COMMAND_CACHE_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "command_cache.json")
COMMAND_CACHE = {}
CACHE_EXPIRY_HOURS = 24
CACHE_MAX_SIZE = 50
DANGEROUS_PATTERNS = [
(r"delete", r"(file|folder|directory)", "delete_file", "Deleting files or folders"),
(r"remove", r"(file|folder)", "delete_file", "Removing files or folders"),
(r"rm\s", r"-rf|-\s*recursion\s*force", "delete_recursive", "Deleting directories recursively"),
(r"shutdown", r".*", "shutdown_pc", "Shutting down the computer"),
(r"restart", r".*", "restart_pc", "Restarting the computer"),
(r"format", r".*", "format_disk", "Formatting a disk"),
(r"drop", r"(database|table|schema)", "drop_database", "Dropping database objects"),
(r"truncate", r"(table|database)", "truncate_table", "Truncating table/database"),
(r"alter", r"(table|database|system)", "alter_system", "Altering system configuration"),
(r"grant", r"(privilege|access|permission)", "grant_permission", "Granting system permissions"),
(r"revoke", r"(privilege|access|permission)", "revoke_permission", "Revoking system permissions"),
(r"exec", r"(system|shell|cmd|powershell)", "execute_shell", "Executing shell commands"),
(r"sendkeys", r".*", "send_keys", "Sending keyboard input to system"),
(r"kill", r"(process|task|program)", "kill_process", "Killing processes"),
(r"taskkill", r".*", "taskkill", "Force killing processes"),
(r"net\s+user", r".*", "net_user", "Managing system users"),
(r"reg\s+delete", r".*", "registry_delete", "Deleting from Windows Registry"),
(r"reg\s+add", r".*", "registry_add", "Adding to Windows Registry"),
]
SYSTEM_DIRS = [
r"C:\\Windows",
r"C:\\Program Files",
r"C:\\Program Files (x86)",
r"C:\\System32",
r"C:\\Boot",
r"C:\\Recovery",
]
import re as _re
class PermissionSystem:
_instance = None
def __init__(self):
self.permission_callback = None
self.dangerous_actions_log = []
self.auto_allow_safe = True
@classmethod
def get_instance(cls):
if cls._instance is None:
cls._instance = cls()
return cls._instance
def set_callback(self, callback):
self.permission_callback = callback
def is_dangerous(self, action: str, target: str = "") -> tuple:
for pattern, target_pattern, action_type, description in DANGEROUS_PATTERNS:
if _re.search(pattern, action, _re.IGNORECASE) and _re.search(target_pattern, target, _re.IGNORECASE):
return (True, action_type, description)
return (False, None, None)
def is_system_directory(self, path: str) -> bool:
path_lower = path.lower()
for sys_dir in SYSTEM_DIRS:
if path_lower.startswith(sys_dir.lower()):
return True
return False
def requires_permission(self, action: str, target: str = "", file_path: str = None) -> tuple:
dangerous, action_type, description = self.is_dangerous(action, target)
if dangerous:
return (True, action_type, description)
if file_path:
if self.is_system_directory(file_path):
return (True, "system_file_access", "Accessing system directories")
if file_path.startswith(".."):
return (True, "path_traversal", "Path traversal detected")
return (False, None, None)
def check_and_request(self, action: str, target: str = "", file_path: str = None) -> bool:
needs_perm, action_type, description = self.requires_permission(action, target, file_path)
if not needs_perm:
return True
if not description:
description = f"Action: {action}"
logging.warning(f"Dangerous action detected: {action_type} - {description}")
if self.permission_callback:
return self.permission_callback(description)
elif permission_callback:
return permission_callback(description)
else:
print(f"⚠️ DANGEROUS ACTION BLOCKED: {description}")
return False
_permission_system = PermissionSystem.get_instance()
def get_permission_system():
return _permission_system
EXPECTED_CACHE_ENTRY_KEYS = {"tool", "args", "result", "timestamp"}
SENSITIVE_CACHE_KEYS = {"password", "api_key", "secret", "token", "credential"}
def _validate_cache_entry(entry: dict, key: str) -> bool:
if not isinstance(entry, dict):
logging.warning(f"Cache entry '{key}' is not a dictionary - skipping")
return False
for k in EXPECTED_CACHE_ENTRY_KEYS:
if k not in entry:
logging.warning(f"Cache entry '{key}' missing required key '{k}' - skipping")
return False
for k, v in entry.items():
if k.lower() in SENSITIVE_CACHE_KEYS and isinstance(v, str) and len(v) > 0:
entry[k] = "***REDACTED***"
if isinstance(entry.get("args"), dict):
for k in list(entry["args"].keys()):
if k.lower() in SENSITIVE_CACHE_KEYS:
entry["args"][k] = "***REDACTED***"
return True
def load_command_cache():
global COMMAND_CACHE
if os.path.exists(COMMAND_CACHE_FILE):
try:
with open(COMMAND_CACHE_FILE, 'r') as f:
raw_data = f.read()
if not raw_data.strip().startswith('{'):
logging.warning("Cache file does not appear to be valid JSON - resetting cache")
COMMAND_CACHE = {}
return
data = json.loads(raw_data)
if not isinstance(data, dict):
logging.warning("Cache file root is not a dictionary - resetting cache")
COMMAND_CACHE = {}
return
current_time = time.time()
valid_cache = {}
sorted_items = []
for k, v in data.items():
if isinstance(v, dict) and "timestamp" in v:
sorted_items.append((k, v))
else:
v["timestamp"] = current_time
sorted_items.append((k, v))
sorted_items.sort(key=lambda x: x[1]["timestamp"])
for k, v in sorted_items:
if not _validate_cache_entry(v, k):
continue
if (current_time - v["timestamp"]) < (CACHE_EXPIRY_HOURS * 3600):
valid_cache[k] = v
if len(valid_cache) > CACHE_MAX_SIZE:
items = list(valid_cache.items())
valid_cache = dict(items[-CACHE_MAX_SIZE:])
COMMAND_CACHE = valid_cache
except Exception as e:
logging.error(f"Failed to load command cache: {e}")
COMMAND_CACHE = {}
def save_command_cache():
try:
with open(COMMAND_CACHE_FILE, 'w') as f:
json.dump(COMMAND_CACHE, f, indent=2)
except Exception as e:
logging.error(f"Failed to save command cache: {e}")
load_command_cache()
def set_status_callback(callback):
"""Sets the callback function for status updates."""
global status_callback
status_callback = callback
def set_permission_callback(callback):
"""Sets the callback function for user permission requests."""
global permission_callback
permission_callback = callback
def set_tool_execution_callback(callback):
"""Sets the callback for logging tool executions (Thought Bubble)."""
global tool_execution_callback
tool_execution_callback = callback
def log_tool_execution(tool_name, args):
"""Logs the tool execution to the GUI."""
if tool_execution_callback:
tool_execution_callback(tool_name, args)
def ask_user_permission(action_description: str) -> bool:
"""Asks the user for permission to execute a sensitive action."""
if permission_callback:
return permission_callback(action_description)
# Fallback to console input (or safe mode default deny)
# In a real headless mode, this might log and return False
print(f"⚠️ Safe Mode Permission Request: {action_description}")
return False
def stop_execution():
"""Signals the task manager to stop current execution."""
global stop_execution_flag
stop_execution_flag = True
update_status("🛑 Execution Stopping...")
def update_status(message: str):
"""Updates the UI status if a callback is registered."""
if status_callback:
status_callback(message)
task_queue = []
task_history = []
WORKSPACE_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "workspace")
if not os.path.exists(WORKSPACE_DIR):
os.makedirs(WORKSPACE_DIR)
def speak(text):
print(text)
# This will be overridden by gui.py to use the real speech engine
pass
def _maximize_target_window(target_title_hint: str = None):
"""Helper to maximize a specific window after launch using a polling loop.
Args:
target_title_hint: App name to look for in window title. If None, maximizes active window.
"""
start_time = time.time()
while time.time() - start_time < 5:
try:
if target_title_hint:
matching_windows = gw.getWindowsWithTitle(target_title_hint)
if matching_windows:
target_win = matching_windows[0]
target_win.maximize()
return
else:
win = gw.getActiveWindow()
if win:
win.maximize()
return
except:
pass
time.sleep(0.1)
def open_application(app_name: str):
"""Opens an application using robust path finding.
Args:
app_name: The name of the application to open (e.g., 'notepad', 'calculator', 'chrome').
"""
# Safe Mode Check
if config.SAFE_MODE:
if not ask_user_permission(f"Open application '{app_name}'?"):
return f"Action blocked by user in Safe Mode: Open {app_name}"
# 1. Try shutil.which (PATH)
path = shutil.which(app_name)
# 2. PowerShell "Get-StartApps" (Fast & Robust)
if not path:
try:
# Search for the app in the Start Menu index
ps_script = f"Get-StartApps | Where-Object {{ $_.Name -like '*{app_name}*' }} | Select-Object -First 1 -ExpandProperty AppID"
result = subprocess.run(["powershell", "-Command", ps_script], capture_output=True, text=True)
app_id = result.stdout.strip()
if app_id:
os.startfile(f"shell:AppsFolder\\{app_id}")
_maximize_target_window(app_name)
return f"Opened {app_name} via PowerShell."
except Exception:
pass
# 3. Common paths (Optimized: No os.walk on ProgramFiles)
# Just check direct existence if possible or skip.
# We can use glob for a shallow search if needed, but PowerShell usually finds it.
if path:
try:
if path.endswith(".lnk"):
os.startfile(path)
else:
subprocess.Popen([path])
_maximize_target_window(app_name)
return f"Opened {app_name} at {path}"
except Exception as e:
return f"Error opening {app_name}: {e}"
else:
return f"Application {app_name} not found. Try installing it or adding it to PATH."
def click_element_by_name(name: str):
"""
Clicks a UI element (Button, MenuItem, etc.) by its visible text using Accessibility APIs.
More robust than coordinate-based clicks.
Args:
name: The text/title of the element to click.
"""
try:
try:
from pywinauto import Desktop
app = Desktop(backend="uia")
active_window = app.window(active_only=True)
if not active_window.exists():
return "No active window found."
except Exception as e:
return f"Error connecting to active window: {e}"
try:
btn = active_window.child_window(title=name, control_type="Button").wrapper_object()
btn.click_input()
return f"Clicked button '{name}'."
except:
try:
elem = active_window.child_window(title=name).wrapper_object()
elem.click_input()
return f"Clicked element '{name}'."
except Exception as e:
return f"Element '{name}' not found in active window. Ensure the name is exact."
except Exception as e:
return f"Error using UI Automation: {e}"
async def smart_click_async(description: str, verify: bool = True) -> str:
"""
Smart click that tries methods in order of reliability and speed:
1. UIA (Accessibility APIs) - <10ms, deterministic
2. Desktop State cache - <5ms, cached element positions
3. CV Template Matching - <50ms, visual but fast
4. LLM Vision - 500ms-2s, last resort
Args:
description: Description of element to click (e.g., "Save", "Submit", "Chrome icon")
verify: Whether to verify click succeeded via state change
"""
import cv2
import numpy as np
update_status(f"🎯 Smart clicking: '{description}'")
ds = desktop_state.get_desktop_state()
ds.update(force=True)
if verify:
before_state = ds.get_state_summary()
elem = ds.find_element(description, fuzzy=True)
if elem and elem.center_x > 0 and elem.center_y > 0:
try:
pyautogui.click(elem.center_x, elem.center_y)
update_status(f"✅ UIA click: '{description}' at ({elem.center_x}, {elem.center_y})")
if verify:
await asyncio.sleep(0.15)
ds.update(force=True)
after_state = ds.get_state_summary()
if before_state != after_state:
return f"Clicked '{description}' via UIA at ({elem.center_x}, {elem.center_y})"
return f"Clicked '{description}' via UIA at ({elem.center_x}, {elem.center_y})"
except Exception as e:
logging.warning(f"UIA click failed: {e}")
screenshot_path = take_screenshot()
if isinstance(screenshot_path, str) and "Error" in screenshot_path:
return await vision_click_async(description)
try:
img = cv2.imread(screenshot_path)
if img is not None:
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
h, w = gray.shape
search_regions = [
(0, 0, w, h),
(0, 0, w//2, h//2),
(w//2, 0, w//2, h//2),
(0, h//2, w, h//2),
]
best_match = None
best_confidence = 0.0
for rx, ry, rw, rh in search_regions:
region = gray[ry:ry+rh, rx:rx+rw]
edges = cv2.Canny(region, 50, 150)
contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
x, y, cw, ch = cv2.boundingRect(contour)
if 20 < cw < 600 and 10 < ch < 150:
roi = region[max(0, y-5):y+ch+5, max(0, x-5):x+cw+5]
if roi.size > 0:
mean_val = roi.mean()
if mean_val > 180 or mean_val < 80:
confidence = min(1.0, (mean_val - 100) / 100)
if confidence > best_confidence:
best_confidence = confidence
best_match = (rx + x + cw//2, ry + y + ch//2)
if best_match and best_confidence > 0.5:
cx, cy = best_match
pyautogui.click(cx, cy)
update_status(f"✅ CV click: '{description}' at ({cx}, {cy})")
return f"Clicked '{description}' via CV at ({cx}, {cy})"
except Exception as e:
logging.warning(f"CV template matching failed: {e}")
update_status(f"👁️ Using vision AI for: '{description}'...")
return await vision_click_async(description)
def smart_click(description: str) -> str:
"""
Synchronous wrapper for smart click.
Tries UIA first, falls back to sync click_element_by_name or vision.
"""
try:
ds = desktop_state.get_desktop_state()
ds.update(force=True)
elem = ds.find_element(description, fuzzy=True)
if elem and elem.center_x > 0 and elem.center_y > 0:
pyautogui.click(elem.center_x, elem.center_y)
return f"Clicked '{description}' via UIA at ({elem.center_x}, {elem.center_y})"
elem = ds.click_element(elem) if elem else None
return click_element_by_name(description)
except Exception as e:
logging.warning(f"Smart click UIA failed: {e}")
return click_element_by_name(description)
def read_screen_text():
"""
Returns a structured list of visible text elements in the active window using UI Automation.
"""
try:
from pywinauto import Desktop
app = Desktop(backend="uia")
active_window = app.window(active_only=True)
if not active_window.exists():
return "No active window found."
# Dump the tree - simplified
# We iterate over immediate children to avoid huge dumps
children = active_window.children()
texts = []
for child in children:
txt = child.window_text()
if txt:
# Try to get more specific if it's a container
# But keep it simple for now
texts.append(f"[{child.element_type}]: {txt}")
if not texts:
return "No readable text found in active window."
return "\n".join(texts)
except Exception as e:
return f"Error reading screen text: {e}"
def organize_files_by_date(directory_path: str):
"""
Organizes files in a directory into folders by creation date (YYYY-MM-DD).
Example: 'C:\\MyDocs\\2023-10-27\\report.pdf'
"""
try:
if not os.path.exists(directory_path):
return f"Error: Directory {directory_path} not found."
files_moved = 0
for filename in os.listdir(directory_path):
file_path = os.path.join(directory_path, filename)
# Skip if it's a directory
if not os.path.isfile(file_path):
continue
# Get creation time
creation_time = os.path.getctime(file_path)
date_folder_name = datetime.fromtimestamp(creation_time).strftime('%Y-%m-%d')
target_folder = os.path.join(directory_path, date_folder_name)
# Create date folder if not exists
os.makedirs(target_folder, exist_ok=True)
# Move file
shutil.move(file_path, os.path.join(target_folder, filename))
files_moved += 1
return f"Successfully organized {files_moved} files in {directory_path} by date."
except Exception as e:
return f"Error organizing files: {e}"
def resize_image(image_path: str, width: int, height: int):
"""
Resizes an image to the specified dimensions using PIL.
"""
try:
if not os.path.exists(image_path):
return f"Error: Image {image_path} not found."
with Image.open(image_path) as img:
resized_img = img.resize((width, height))
resized_img.save(image_path)
return f"Resized {image_path} to {width}x{height}."
except Exception as e:
return f"Error resizing image: {e}"
def get_wifi_networks():
"""
Lists available WiFi networks using netsh.
"""
try:
# Use netsh on Windows
result = subprocess.run(["netsh", "wlan", "show", "networks"], capture_output=True, text=True)
if result.returncode != 0:
return f"Error running netsh: {result.stderr}"
return result.stdout
except Exception as e:
return f"Error getting WiFi networks: {e}"
def get_active_window_title():
"""Gets the title of the currently active window."""
try:
window = gw.getActiveWindow()
if window:
return f"Active Window: {window.title}"
return "Active Window: None"
except Exception as e:
return f"Error getting active window: {e}"
def deep_search(query: str):
"""Performs a deep search using Tavily, Serper, or fallback to scraping.
Args:
query: The search query.
"""
logging.info(f"Deep searching for: {query}")
# 1. Tavily API (Recommended)
tavily_key = os.environ.get("TAVILY_API_KEY")
if tavily_key:
try:
logging.info("Using Tavily API")
response = requests.post(
"https://api.tavily.com/search",
json={"api_key": tavily_key, "query": query, "search_depth": "basic", "include_answer": True},
timeout=10
)
response.raise_for_status()
data = response.json()
answer = data.get("answer", "")
results = data.get("results", [])
summary = f"Tavily Answer: {answer}\n\nSources:\n"
for res in results[:3]:
summary += f"- {res['title']} ({res['url']}): {res['content'][:200]}...\n"
return summary
except Exception as e:
logging.error(f"Tavily Search failed: {e}")
# 2. Serper API (Google)
serper_key = os.environ.get("SERPER_API_KEY")
if serper_key:
try:
logging.info("Using Serper API")
headers = {'X-API-KEY': serper_key, 'Content-Type': 'application/json'}
response = requests.post(
"https://google.serper.dev/search",
headers=headers,
json={"q": query},
timeout=10
)
response.raise_for_status()
data = response.json()
organic = data.get("organic", [])
summary = "Serper Results:\n"
for res in organic[:3]:
summary += f"- {res.get('title')} ({res.get('link')}): {res.get('snippet')}\n"
return summary
except Exception as e:
logging.error(f"Serper Search failed: {e}")
# 3. Fallback: Scraping (Google Search + BeautifulSoup)
try:
logging.info("Fallback: Scraping Google")
urls = []
# googlesearch-python returns a generator
for url in search(query, num_results=3, lang="en"):
urls.append(url)
summary = f"Search Results for '{query}':\n\n"
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'}
for url in urls:
try:
resp = requests.get(url, headers=headers, timeout=5)
soup = BeautifulSoup(resp.content, 'html.parser')
# Extract text properly
for script in soup(["script", "style", "nav", "footer", "header"]):
script.extract()
text = soup.get_text()
# Clean up whitespace
lines = (line.strip() for line in text.splitlines())
chunks = (phrase.strip() for line in lines for phrase in line.split(" "))
text = '\n'.join(chunk for chunk in chunks if chunk)
# Limit text length to avoid token overflow
summary += f"--- Source: {url} ---\n{text[:1000]}...\n\n"
except Exception as e:
summary += f"--- Source: {url} ---\nError fetching content: {e}\n\n"
return f"Research Summary based on {len(urls)} sources:\n{summary}\n\nINSTRUCTION: Synthesize a concise answer from the above."
except Exception as e:
return f"Deep Search Error: {e}"
def click_at_coordinates(x: int, y: int, button: str = "left"):
"""Clicks at the specified screen coordinates."""
if config.SAFE_MODE:
if not ask_user_permission(f"Click at ({x}, {y})?"):
return f"Action blocked by user: Click at ({x}, {y})"
try:
pyautogui.click(x, y, button=button)
return f"Clicked at ({x}, {y}) with {button} button."
except Exception as e:
return f"Error clicking: {e}"
def type_text(text: str):
"""Types text at the current cursor position."""
if config.SAFE_MODE:
short_text = (text[:20] + '...') if len(text) > 20 else text
if not ask_user_permission(f"Type text: '{short_text}'?"):
return f"Action blocked by user: Type text"
try:
pyautogui.write(text)
return f"Typed: {text}"
except Exception as e:
return f"Error typing: {e}"
def press_key(key: str):
"""Presses a specific key (e.g., 'enter', 'esc', 'win')."""
if config.SAFE_MODE:
if not ask_user_permission(f"Press key: {key}?"):
return f"Action blocked by user: Press key {key}"
try:
pyautogui.press(key)
return f"Pressed key: {key}"
except Exception as e:
return f"Error pressing key: {e}"
def take_screenshot():
"""Takes a screenshot and saves it to a temporary file.
Returns:
The path to the saved screenshot file.
"""
try:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"screenshot_{timestamp}.png"
screenshot = pyautogui.screenshot()
screenshot.save(filename)
return filename
except Exception as e:
return f"Error taking screenshot: {e}"
def open_website(url: str):
"""Opens a website in the default browser.
Can be used for direct URLs OR search queries.
Args:
url: The full URL (e.g. 'https://www.google.com/search?q=weather')
OR a domain (e.g. 'youtube.com').
"""
try:
if not url.startswith('http'):
url = 'https://' + url
webbrowser.open(url)
return f"Opened website: {url}"
except Exception as e:
return f"Error opening website: {e}"
import pyperclip
import pythoncom
import re
PROMPT_INJECTION_PATTERNS = [
r"(?i)ignore\s+(previous|all|your)\s+(instructions?|commands?)",
r"(?i)disregard\s+(previous|all|your)\s+(instructions?|commands?)",
r"(?i)you\s+are\s+(now|actually)\s+(jarvis|assistant|AI|BOT)",
r"(?i)forget\s+(everything|all|previous)\s+(you|instructions)",
r"(?i)new\s+instructions?:",
r"(?i)system\s+prompt:",
r"(?i)override\s+(security|restrictions?)",
r"(?i)jailbreak",
r"(?i) DAN\s+mode",
r"(?i)sudo\s+mode",
r"```system|```instructions|```prompt",
r"(?i)<\|(?:system|user|assistant)\|>",
r"(?i)\[INST\]\s*\[/INST\]",
r"<\s*script[^>]*>.*?</\s*script\s*>",
r"(?i)act\s+as\s+(?:a\s+)?new\s+(?:AI|assistant)",
]
_compiled_injection_patterns = [re.compile(p, re.IGNORECASE | re.DOTALL) for p in PROMPT_INJECTION_PATTERNS]
def _detect_prompt_injection(text: str) -> bool:
if not text:
return False
for pattern in _compiled_injection_patterns:
if pattern.search(text):
return True
return False
def _sanitize_clipboard_content(text: str) -> str:
if not text:
return ""
if _detect_prompt_injection(text):
logging.warning("Potential prompt injection detected in clipboard content - content will be masked")
return "[CLIPBOARD CONTENT REDACTED - Potential injection detected]"
if len(text) > 10000:
return text[:10000] + "... [truncated]"
return text
def read_clipboard():
"""Reads the current text content from the clipboard.
Returns:
The text currently stored in the clipboard.
"""
try:
pythoncom.CoInitialize()
try:
content = pyperclip.paste()
sanitized = _sanitize_clipboard_content(content)
if sanitized != content:
return f"Clipboard content: {sanitized}"
return f"Clipboard content: {sanitized}"
finally:
pythoncom.CoUninitialize()
except Exception as e:
return f"Error reading clipboard: {e}"
def write_to_clipboard(text: str):
"""Writes text to the system clipboard.
Args:
text: The text to copy to the clipboard.
"""
try:
# Clipboard access on worker threads requires COM initialization
pythoncom.CoInitialize()
try:
pyperclip.copy(text)
return "Text copied to clipboard."
finally:
pythoncom.CoUninitialize()
except Exception as e:
return f"Error writing to clipboard: {e}"
import ctypes
async def run_python_script(script_path: str):
"""Executes a Python script, with advanced self-healing.
Args:
script_path: The full path to the Python script to run.
"""
# Safe Mode Check
if config.SAFE_MODE:
if not ask_user_permission(f"Execute Python script:\n{script_path}?"):
return f"Action blocked by user: Run {script_path}"
try:
# Resolve path: Check workspace if not found in root/absolute
if not os.path.exists(script_path) and not os.path.isabs(script_path):
ws_path = os.path.join(WORKSPACE_DIR, script_path)
if os.path.exists(ws_path):
script_path = ws_path
# Safety check: Ensure it's a python file and exists
if not script_path.endswith('.py'):
return "Error: Can only execute .py files for safety."
if not os.path.exists(script_path):
return f"Error: File {script_path} not found."
# Security: Scan for dangerous patterns
try:
with open(script_path, 'r', encoding='utf-8') as f:
content = f.read()
critical_patterns = ["shutil.rmtree", "os.system('rm", "os.system(\"rm", "del /s", "format c:", "os.remove(r'C:\\Windows"]
if any(pattern in content for pattern in critical_patterns):
return f"Error: Security Block. Script contains potentially dangerous operations: {critical_patterns}"
except Exception as e:
return f"Error reading script for security check: {e}"
max_retries = 3
output_log = ""
for attempt in range(max_retries):
try:
# Read current content before run (in case it was modified)
with open(script_path, 'r', encoding='utf-8') as f:
current_code = f.read()
logging.info(f"Executing script {script_path} (Attempt {attempt+1}/{max_retries})")
# Run subprocess in thread to avoid blocking the asyncio loop
result = await asyncio.to_thread(
subprocess.run,
['python', script_path],
capture_output=True,
text=True,
timeout=30
)
output = result.stdout
error = result.stderr
if not error:
# Success!
output_log += f"\n--- Execution Success (Attempt {attempt+1}) ---\n{output}"
return f"Execution Result:\n{output_log}"
# Failure
output_log += f"\n--- Attempt {attempt+1} Failed ---\nOutput: {output}\nError: {error}\n"
# Update UI Status: Error Detected
update_status(f"🔴 Error Detected (Attempt {attempt+1})")
# Check for specific ModuleNotFoundError to fast-track install
if "ModuleNotFoundError" in error:
import re
match = re.search(r"No module named '(\w+)'", error)
if match:
missing_module = match.group(1)
logging.info(f"Installing missing module: {missing_module}")
update_status(f"📦 Installing Missing Module: {missing_module}")
speak(f"Missing module {missing_module} detected. Installing it now...")
install_res = install_python_library(missing_module) # Blocking is fine here
output_log += f"Installed {missing_module}: {install_res}\n"
continue # Retry immediately after install without rewriting code yet
# General Error -> Ask AI to fix
logging.info("Requesting AI fix for script error...")
# Context-Aware Error Handling: Screenshot + Visual Analysis (Only if first attempt failed)
if attempt > 0:
try:
screenshot_path = os.path.join(os.getcwd(), "error_context.png")
pyautogui.screenshot(screenshot_path)
update_status("📸 Analyzing Screen Context...")
error_explanation = await ai_engine.analyze_error_with_screenshot(error, screenshot_path)
if error_explanation:
speak(f"I see an error. {error_explanation}")
output_log += f"\n[Visual Analysis]: {error_explanation}\n"
except Exception as viz_e:
logging.error(f"Visual Error Analysis Failed: {viz_e}")
update_status(f"🟡 Analyzing Traceback & Patching Code...")
speak(f"Script error detected on attempt {attempt+1}. requesting AI fix...")
try:
fixed_code = await ai_engine.fix_code(current_code, error)
if fixed_code:
with open(script_path, 'w', encoding='utf-8') as f:
f.write(fixed_code)
output_log += "AI applied a fix. Retrying...\n"
update_status(f"🟢 Patch Applied. Retrying... 🚀")
speak("AI fix applied. Retrying execution...")
else:
output_log += "AI failed to generate a fix.\n"
update_status(f"❌ AI Fix Failed")
break # Stop if AI fails
except Exception as ai_e:
output_log += f"AI Fix Error: {ai_e}\n"
break
except subprocess.TimeoutExpired:
output_log += f"\nError: Script execution timed out (limit: 30s).\n"
break
except Exception as e:
output_log += f"\nError executing subprocess: {e}\n"
break
return f"Execution Failed after {max_retries} attempts.\nLog:\n{output_log}"
except Exception as e:
return f"Error executing script: {e}"
def install_python_library(library_name: str):
"""Installs a Python library using pip.
Args:
library_name: The name of the library to install (e.g., 'numpy', 'pandas').
"""
if config.SAFE_MODE:
if not ask_user_permission(f"Install library: {library_name}?"):
return f"Action blocked by user: Install {library_name}"
try:
# Security: Strict validation to prevent command injection
import re
if not re.match(r"^[a-zA-Z0-9_\-=.><]+$", library_name):
return "Error: Invalid library name. Only alphanumeric characters and standard version specifiers allowed."
result = subprocess.run(
['pip', 'install', library_name],
capture_output=True,
text=True,
timeout=120
)
if result.returncode == 0:
return f"Successfully installed {library_name}."
else:
return f"Error installing {library_name}:\n{result.stderr}"
except Exception as e:
return f"Error installing library: {e}"
def create_file(file_path: str, content: str = ""):
"""Creates a file at the specified path with optional content and opens it.
Args:
file_path: The path where the file should be created.
content: The text content to write to the file.
"""
perm_system = get_permission_system()
needs_perm, action_type, description = perm_system.requires_permission("create_file", file_path, file_path)
if needs_perm:
if not perm_system.check_and_request("create_file", file_path, file_path):
return f"Action blocked: {description or 'create file'}"
try: