This repository was archived by the owner on Mar 28, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagent.py
More file actions
3904 lines (3336 loc) · 165 KB
/
agent.py
File metadata and controls
3904 lines (3336 loc) · 165 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
import os
import base64
import time
import json
import requests
import re
import logging
import threading
import sqlite3
import csv
import random
import string
import hashlib
import uuid
from datetime import datetime, timedelta
from typing import Dict, List, Optional, Tuple, Any, Union, Callable
from dataclasses import dataclass, field
from concurrent.futures import ThreadPoolExecutor, as_completed
from dotenv import load_dotenv
from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.chrome.options import Options as ChromeOptions
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import (
TimeoutException, ElementClickInterceptedException,
ElementNotInteractableException, NoSuchElementException,
StaleElementReferenceException, WebDriverException,
JavascriptException, InvalidSessionIdException
)
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.remote.webelement import WebElement
from webdriver_manager.chrome import ChromeDriverManager
from PIL import Image, ImageDraw, ImageFont, ImageFilter, ImageEnhance, ImageOps
from io import BytesIO
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
import asyncio
import numpy as np
import cv2
import pickle
import yaml
import pandas as pd
import openpyxl
from urllib.parse import urlparse, parse_qs, urlencode
import subprocess
import platform
import psutil
import tempfile
import zipfile
import shutil
from pathlib import Path
import mimetypes
import websocket
import schedule
from functools import wraps, lru_cache
from collections import defaultdict, deque
import warnings
warnings.filterwarnings('ignore')
# Load environment variables
load_dotenv()
# Setup advanced logging
os.makedirs('logs', exist_ok=True)
os.makedirs('screenshots', exist_ok=True)
os.makedirs('downloads', exist_ok=True)
os.makedirs('data', exist_ok=True)
os.makedirs('reports', exist_ok=True)
# Configure advanced logging with multiple handlers
log_formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(funcName)s:%(lineno)d - %(message)s'
)
# File handler
file_handler = logging.FileHandler('logs/mega_browser_agent.log', encoding='utf-8')
file_handler.setFormatter(log_formatter)
file_handler.setLevel(logging.INFO)
# Console handler
console_handler = logging.StreamHandler()
console_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
console_handler.setLevel(logging.INFO)
# Error handler (separate file for errors)
error_handler = logging.FileHandler('logs/errors.log', encoding='utf-8')
error_handler.setFormatter(log_formatter)
error_handler.setLevel(logging.ERROR)
# Setup logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
logger.addHandler(file_handler)
logger.addHandler(console_handler)
logger.addHandler(error_handler)
# AI Configuration - Multi-Model Support
AI_CONFIGS = {
"typegpt": {
"api_key": os.getenv("TYPEGPT_API_KEY", "sk-qKyofcYMp98THwbRpRb4CBp5lQzSTC9iAX1E1rKhxedU4oYc"),
"endpoint": "https://api.typegpt.net/v1/chat/completions",
"model": "meta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8"
},
"openai": {
"api_key": os.getenv("OPENAI_API_KEY", ""),
"endpoint": "https://api.openai.com/v1/chat/completions",
"model": "gpt-4-turbo-preview"
},
"anthropic": {
"api_key": os.getenv("ANTHROPIC_API_KEY", ""),
"endpoint": "https://api.anthropic.com/v1/messages",
"model": "claude-3-opus-20240229"
},
"gemini": {
"api_key": os.getenv("GEMINI_API_KEY", ""),
"endpoint": "https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent",
"model": "gemini-pro"
}
}
# Default AI provider
DEFAULT_AI_PROVIDER = "typegpt"
API_KEY = AI_CONFIGS[DEFAULT_AI_PROVIDER]["api_key"]
API_ENDPOINT_URL = AI_CONFIGS[DEFAULT_AI_PROVIDER]["endpoint"]
MODEL_NAME = AI_CONFIGS[DEFAULT_AI_PROVIDER]["model"]
if not API_KEY or not API_ENDPOINT_URL:
logger.warning("Primary AI API key or base URL not found. Some AI features may be limited.")
@dataclass
class ElementInfo:
"""Advanced element information structure."""
id: int
element: Any
tag_name: str
label: str
element_type: str
is_visible: bool
is_clickable: bool
is_form_field: bool
coordinates: Tuple[int, int, int, int] # x, y, width, height
attributes: Dict[str, str]
text_content: str
confidence_score: float
@dataclass
class ActionResult:
"""Advanced action result structure."""
success: bool
action_type: str
message: str
duration: float
screenshot_path: Optional[str]
element_id: Optional[int]
error_details: Optional[str]
timestamp: datetime
retry_count: int = 0
metadata: Dict[str, Any] = field(default_factory=dict)
@dataclass
class AutomationTask:
"""Structure for automation tasks."""
name: str
steps: List[Dict[str, Any]]
conditions: Dict[str, Any] = field(default_factory=dict)
loops: int = 1
delay_between_loops: float = 0
on_error: str = "stop" # stop, continue, retry
max_retries: int = 3
timeout: float = 300
@dataclass
class NetworkRequest:
"""Structure for network request monitoring."""
url: str
method: str
status_code: int
response_time: float
headers: Dict[str, str]
body: Optional[str]
timestamp: datetime
@dataclass
class PerformanceMetrics:
"""Performance tracking structure."""
page_load_time: float
dom_ready_time: float
first_paint_time: float
memory_usage: float
cpu_usage: float
network_requests_count: int
javascript_errors: List[str]
timestamp: datetime
class CaptchaSolver:
"""Advanced CAPTCHA solving capabilities."""
def __init__(self):
self.providers = {
"2captcha": os.getenv("TWOCAPTCHA_API_KEY", ""),
"anticaptcha": os.getenv("ANTICAPTCHA_API_KEY", ""),
"capsolver": os.getenv("CAPSOLVER_API_KEY", "")
}
def solve_recaptcha_v2(self, site_key: str, page_url: str) -> Optional[str]:
"""Solve reCAPTCHA v2."""
if self.providers.get("2captcha"):
try:
# Implementation for 2captcha
api_key = self.providers["2captcha"]
solver_url = f"http://2captcha.com/in.php?key={api_key}&method=userrecaptcha&googlekey={site_key}&pageurl={page_url}"
response = requests.get(solver_url)
if "OK" in response.text:
captcha_id = response.text.split("|")[1]
time.sleep(20) # Wait for solving
result_url = f"http://2captcha.com/res.php?key={api_key}&action=get&id={captcha_id}"
for _ in range(10):
result = requests.get(result_url)
if "OK" in result.text:
return result.text.split("|")[1]
time.sleep(5)
except Exception as e:
logger.error(f"CAPTCHA solving failed: {e}")
return None
def solve_image_captcha(self, image_path: str) -> Optional[str]:
"""Solve image-based CAPTCHA using OCR."""
try:
import pytesseract
from PIL import Image
img = Image.open(image_path)
# Preprocess image for better OCR
img = img.convert('L') # Convert to grayscale
img = ImageEnhance.Contrast(img).enhance(2)
text = pytesseract.image_to_string(img, config='--psm 8 -c tessedit_char_whitelist=0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ')
return text.strip()
except Exception as e:
logger.error(f"Image CAPTCHA solving failed: {e}")
return None
class NetworkInterceptor:
"""Advanced network request interception and modification."""
def __init__(self, driver):
self.driver = driver
self.requests_log = []
self.blocked_urls = []
self.modified_headers = {}
def enable_network_logging(self):
"""Enable Chrome DevTools Protocol for network monitoring."""
caps = DesiredCapabilities.CHROME
caps['goog:loggingPrefs'] = {'performance': 'ALL'}
def intercept_requests(self, url_pattern: str = None, callback: Callable = None):
"""Intercept and optionally modify network requests."""
script = """
const originalFetch = window.fetch;
window.fetch = function(...args) {
console.log('Fetch intercepted:', args[0]);
if (window.interceptCallback) {
args = window.interceptCallback(args);
}
return originalFetch.apply(this, args);
};
const originalXHR = window.XMLHttpRequest.prototype.open;
window.XMLHttpRequest.prototype.open = function(method, url, ...rest) {
console.log('XHR intercepted:', method, url);
if (window.interceptCallback) {
[method, url] = window.interceptCallback([method, url]);
}
return originalXHR.apply(this, [method, url, ...rest]);
};
"""
self.driver.execute_script(script)
def block_requests(self, patterns: List[str]):
"""Block requests matching patterns."""
self.blocked_urls = patterns
block_script = f"""
window.blockedPatterns = {json.dumps(patterns)};
const originalFetch = window.fetch;
window.fetch = function(url, ...args) {{
for (let pattern of window.blockedPatterns) {{
if (url.includes(pattern)) {{
console.log('Blocked request:', url);
return Promise.reject(new Error('Request blocked'));
}}
}}
return originalFetch.apply(this, [url, ...args]);
}};
"""
self.driver.execute_script(block_script)
def get_network_logs(self) -> List[NetworkRequest]:
"""Get all network requests from browser logs."""
logs = self.driver.get_log('performance')
requests = []
for entry in logs:
log = json.loads(entry['message'])['message']
if 'Network.responseReceived' in log['method']:
response = log['params']['response']
requests.append(NetworkRequest(
url=response['url'],
method=response.get('requestMethod', 'GET'),
status_code=response['status'],
response_time=0, # Would need timing info
headers=response['headers'],
body=None,
timestamp=datetime.now()
))
return requests
class AdvancedDatabase:
"""Advanced database manager for browser agent."""
def __init__(self, db_path: str = "data/browser_agent.db"):
self.db_path = db_path
self.init_database()
def init_database(self):
"""Initialize database with all necessary tables."""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
# Actions history table
cursor.execute('''
CREATE TABLE IF NOT EXISTS actions_history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp TEXT NOT NULL,
action_type TEXT NOT NULL,
url TEXT,
element_id INTEGER,
parameters TEXT,
result TEXT,
duration REAL,
screenshot_path TEXT,
success BOOLEAN
)
''')
# Website data table
cursor.execute('''
CREATE TABLE IF NOT EXISTS website_data (
id INTEGER PRIMARY KEY AUTOINCREMENT,
url TEXT NOT NULL,
title TEXT,
description TEXT,
keywords TEXT,
elements_count INTEGER,
load_time REAL,
screenshot_path TEXT,
visit_timestamp TEXT
)
''')
# Form data table
cursor.execute('''
CREATE TABLE IF NOT EXISTS form_data (
id INTEGER PRIMARY KEY AUTOINCREMENT,
url TEXT NOT NULL,
form_name TEXT,
field_name TEXT,
field_value TEXT,
field_type TEXT,
timestamp TEXT
)
''')
# Search results table
cursor.execute('''
CREATE TABLE IF NOT EXISTS search_results (
id INTEGER PRIMARY KEY AUTOINCREMENT,
search_engine TEXT,
query TEXT,
results_count INTEGER,
top_result_title TEXT,
top_result_url TEXT,
timestamp TEXT
)
''')
conn.commit()
def log_action(self, action_result: ActionResult):
"""Log action to database."""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute('''
INSERT INTO actions_history
(timestamp, action_type, element_id, result, duration, screenshot_path, success)
VALUES (?, ?, ?, ?, ?, ?, ?)
''', (
action_result.timestamp.isoformat(),
action_result.action_type,
action_result.element_id,
action_result.message,
action_result.duration,
action_result.screenshot_path,
action_result.success
))
conn.commit()
class AdvancedEmailManager:
"""Advanced email management system."""
def __init__(self):
self.smtp_server = "smtp.gmail.com"
self.smtp_port = 587
def send_report(self, to_email: str, subject: str, body: str, attachments: List[str] = None):
"""Send email report with attachments."""
try:
msg = MIMEMultipart()
msg['From'] = os.getenv('EMAIL_FROM', 'browser.agent@example.com')
msg['To'] = to_email
msg['Subject'] = subject
msg.attach(MIMEText(body, 'html'))
# Add attachments
if attachments:
for file_path in attachments:
if os.path.exists(file_path):
with open(file_path, "rb") as attachment:
part = MIMEBase('application', 'octet-stream')
part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header(
'Content-Disposition',
f'attachment; filename= {os.path.basename(file_path)}',
)
msg.attach(part)
server = smtplib.SMTP(self.smtp_server, self.smtp_port)
server.starttls()
server.login(
os.getenv('EMAIL_USERNAME', ''),
os.getenv('EMAIL_PASSWORD', '')
)
server.send_message(msg)
server.quit()
logger.info(f"Email report sent successfully to {to_email}")
return True
except Exception as e:
logger.error(f"Failed to send email: {e}")
return False
class AdvancedReportGenerator:
"""Advanced report generation system."""
def __init__(self, db: AdvancedDatabase):
self.db = db
def generate_html_report(self, session_data: Dict) -> str:
"""Generate comprehensive HTML report."""
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
report_path = f"reports/session_report_{timestamp}.html"
html_content = f"""
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Browser Agent Session Report</title>
<style>
body {{ font-family: 'Arial', sans-serif; margin: 0; padding: 20px; background: #f5f5f5; }}
.container {{ max-width: 1200px; margin: 0 auto; background: white; padding: 30px; border-radius: 10px; box-shadow: 0 0 20px rgba(0,0,0,0.1); }}
.header {{ text-align: center; margin-bottom: 30px; }}
.header h1 {{ color: #333; margin-bottom: 10px; }}
.stats {{ display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 20px; margin-bottom: 30px; }}
.stat-card {{ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 20px; border-radius: 10px; text-align: center; }}
.stat-card h3 {{ margin: 0 0 10px 0; }}
.stat-card .number {{ font-size: 2em; font-weight: bold; }}
.timeline {{ margin-top: 30px; }}
.timeline-item {{ background: #f8f9fa; margin: 10px 0; padding: 15px; border-left: 4px solid #667eea; border-radius: 5px; }}
.success {{ border-left-color: #28a745; }}
.error {{ border-left-color: #dc3545; }}
.screenshot {{ max-width: 300px; border-radius: 5px; margin: 10px 0; }}
.footer {{ text-align: center; margin-top: 30px; color: #666; }}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>🤖 Browser Agent Session Report</h1>
<p>Generated on {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}</p>
</div>
<div class="stats">
<div class="stat-card">
<h3>Total Actions</h3>
<div class="number">{session_data.get('total_actions', 0)}</div>
</div>
<div class="stat-card">
<h3>Success Rate</h3>
<div class="number">{session_data.get('success_rate', 0)}%</div>
</div>
<div class="stat-card">
<h3>Websites Visited</h3>
<div class="number">{session_data.get('websites_visited', 0)}</div>
</div>
<div class="stat-card">
<h3>Total Duration</h3>
<div class="number">{session_data.get('total_duration', 0):.1f}s</div>
</div>
</div>
<div class="timeline">
<h2>Action Timeline</h2>
{self._generate_timeline_html(session_data.get('actions', []))}
</div>
<div class="footer">
<p>Generated by Mega Advanced Browser Agent v2.0</p>
</div>
</div>
</body>
</html>
"""
with open(report_path, 'w', encoding='utf-8') as f:
f.write(html_content)
logger.info(f"HTML report generated: {report_path}")
return report_path
def _generate_timeline_html(self, actions: List[ActionResult]) -> str:
"""Generate timeline HTML for actions."""
timeline_html = ""
for action in actions:
status_class = "success" if action.success else "error"
timeline_html += f"""
<div class="timeline-item {status_class}">
<strong>{action.action_type}</strong> - {action.message}
<br><small>{action.timestamp.strftime("%H:%M:%S")} | Duration: {action.duration:.2f}s</small>
{f'<br><img src="{action.screenshot_path}" class="screenshot" alt="Screenshot">' if action.screenshot_path else ''}
</div>
"""
return timeline_html
class ChatInterface:
"""Clean, minimal chat interface with modern speech bubble design for AI agent responses."""
def __init__(self):
self.bubble_id = f"ai-chat-bubble-{uuid.uuid4().hex[:8]}"
self.default_message = "AI assistant is ready to help you."
def create_chat_bubble(self, message: str = None, position: str = "top-left") -> str:
"""
Create a clean, minimal chat interface speech bubble for AI responses.
Modern flat UI design with precise styling as specified.
Args:
message: The AI response text to display
position: Position of the bubble (default "top-left" for AI avatar connection)
Returns:
JavaScript code to inject the chat bubble
"""
if not message:
message = self.default_message
# Split message into sentences to make first sentence bold
sentences = message.split('. ')
if len(sentences) > 1:
first_sentence = sentences[0] + '.'
remaining_text = '. '.join(sentences[1:])
formatted_message = f"<strong style='font-weight: 600;'>{first_sentence}</strong> {remaining_text}"
else:
formatted_message = f"<strong style='font-weight: 600;'>{message}</strong>"
# Position configurations - default to top-left for AI avatar connection
position_styles = {
"top-left": "top: 60px; left: 80px;", # Positioned to connect with AI avatar
"top-right": "top: 60px; right: 20px;",
"bottom-left": "bottom: 20px; left: 80px;",
"bottom-right": "bottom: 20px; right: 20px;"
}
# Pointer configurations - small triangular pointer at top-left
pointer_styles = {
"top-left": "top: -6px; left: 24px; border-bottom: 6px solid #ffffff; border-left: 6px solid transparent; border-right: 6px solid transparent; filter: drop-shadow(0 -1px 1px rgba(0, 0, 0, 0.05));",
"top-right": "top: -6px; right: 24px; border-bottom: 6px solid #ffffff; border-left: 6px solid transparent; border-right: 6px solid transparent; filter: drop-shadow(0 -1px 1px rgba(0, 0, 0, 0.05));",
"bottom-left": "bottom: -6px; left: 24px; border-top: 6px solid #ffffff; border-left: 6px solid transparent; border-right: 6px solid transparent; filter: drop-shadow(0 1px 1px rgba(0, 0, 0, 0.05));",
"bottom-right": "bottom: -6px; right: 24px; border-top: 6px solid #ffffff; border-left: 6px solid transparent; border-right: 6px solid transparent; filter: drop-shadow(0 1px 1px rgba(0, 0, 0, 0.05));"
}
position_css = position_styles.get(position, position_styles["top-left"])
pointer_css = pointer_styles.get(position, pointer_styles["top-left"])
bubble_js = f"""
// Remove existing bubble if any
const existingBubble = document.getElementById('{self.bubble_id}');
if (existingBubble) {{
existingBubble.remove();
}}
// Ensure standard Windows cursor is applied globally
document.body.style.cursor = 'default';
document.documentElement.style.cursor = 'default';
// Create chat bubble container with precise specifications
const chatBubble = document.createElement('div');
chatBubble.id = '{self.bubble_id}';
chatBubble.style.cssText = `
position: fixed;
{position_css}
max-width: 280px;
min-width: 180px;
background: #ffffff;
color: #4b5563;
padding: 14px 16px;
border-radius: 8px;
font-family: 'Inter', 'Arial', 'Segoe UI', -apple-system, BlinkMacSystemFont, sans-serif;
font-size: 14px;
line-height: 1.45;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08), 0 1px 4px rgba(0, 0, 0, 0.04);
z-index: 999999;
opacity: 0;
transform: translateY(-8px) scale(0.98);
transition: all 0.25s cubic-bezier(0.25, 0.46, 0.45, 0.94);
border: none;
cursor: default;
user-select: none;
font-weight: 400;
letter-spacing: -0.01em;
`;
// Create message content with balanced padding
chatBubble.innerHTML = `
<div style="
position: relative;
word-wrap: break-word;
line-height: 1.45;
margin: 0;
padding: 0;
color: #4b5563;
cursor: default;
">
{formatted_message}
</div>
<div style="
position: absolute;
{pointer_css}
width: 0;
height: 0;
"></div>
`;
document.body.appendChild(chatBubble);
// Animate bubble in with smooth entrance
setTimeout(() => {{
chatBubble.style.opacity = '1';
chatBubble.style.transform = 'translateY(0) scale(1)';
}}, 50);
// Create subtle hover effect for interactivity
chatBubble.addEventListener('mouseenter', function() {{
this.style.boxShadow = '0 3px 12px rgba(0, 0, 0, 0.1), 0 1px 6px rgba(0, 0, 0, 0.06)';
this.style.transform = 'translateY(-1px) scale(1)';
document.body.style.cursor = 'default';
}});
chatBubble.addEventListener('mouseleave', function() {{
this.style.boxShadow = '0 2px 8px rgba(0, 0, 0, 0.08), 0 1px 4px rgba(0, 0, 0, 0.04)';
this.style.transform = 'translateY(0) scale(1)';
document.body.style.cursor = 'default';
}});
// Auto-hide after delay (optional)
setTimeout(() => {{
if (document.getElementById('{self.bubble_id}')) {{
chatBubble.style.opacity = '0';
chatBubble.style.transform = 'translateY(-8px) scale(0.98)';
setTimeout(() => {{
if (chatBubble.parentNode) {{
chatBubble.parentNode.removeChild(chatBubble);
}}
}}, 250);
}}
}}, 8000);
"""
return bubble_js
def update_bubble_message(self, new_message: str) -> str:
"""
Update the message in an existing chat bubble.
Args:
new_message: New message to display
Returns:
JavaScript code to update the bubble
"""
# Split message into sentences to make first sentence bold
sentences = new_message.split('. ')
if len(sentences) > 1:
first_sentence = sentences[0] + '.'
remaining_text = '. '.join(sentences[1:])
formatted_message = f"<strong>{first_sentence}</strong> {remaining_text}"
else:
formatted_message = f"<strong>{new_message}</strong>"
update_js = f"""
const existingBubble = document.getElementById('{self.bubble_id}');
if (existingBubble) {{
const messageDiv = existingBubble.querySelector('div');
if (messageDiv) {{
messageDiv.innerHTML = `{formatted_message}`;
// Add subtle pulse animation for update
existingBubble.style.transform = 'scale(1.02)';
setTimeout(() => {{
existingBubble.style.transform = 'scale(1)';
}}, 150);
}}
}}
"""
return update_js
def remove_bubble(self) -> str:
"""
Remove the chat bubble with smooth animation.
Returns:
JavaScript code to remove the bubble
"""
remove_js = f"""
const bubble = document.getElementById('{self.bubble_id}');
if (bubble) {{
bubble.style.opacity = '0';
bubble.style.transform = 'translateY(-10px) scale(0.95)';
setTimeout(() => {{
if (bubble.parentNode) {{
bubble.parentNode.removeChild(bubble);
}}
}}, 300);
}}
"""
return remove_js
def create_typing_indicator(self, position: str = "top-left") -> str:
"""
Create a clean typing indicator bubble matching the main chat design.
Args:
position: Position of the bubble
Returns:
JavaScript code for typing indicator
"""
position_styles = {
"top-left": "top: 60px; left: 80px;",
"top-right": "top: 60px; right: 20px;",
"bottom-left": "bottom: 20px; left: 80px;",
"bottom-right": "bottom: 20px; right: 20px;"
}
position_css = position_styles.get(position, position_styles["top-left"])
typing_id = f"ai-typing-{uuid.uuid4().hex[:8]}"
typing_js = f"""
// Ensure standard cursor
document.body.style.cursor = 'default';
document.documentElement.style.cursor = 'default';
const typingBubble = document.createElement('div');
typingBubble.id = '{typing_id}';
typingBubble.style.cssText = `
position: fixed;
{position_css}
background: #ffffff;
color: #6b7280;
padding: 12px 16px;
border-radius: 8px;
font-family: 'Inter', 'Arial', 'Segoe UI', sans-serif;
font-size: 13px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08), 0 1px 4px rgba(0, 0, 0, 0.04);
z-index: 999999;
opacity: 0;
transform: scale(0.98);
transition: all 0.25s ease;
border: none;
cursor: default;
user-select: none;
letter-spacing: -0.01em;
`;
typingBubble.innerHTML = `
<div style="display: flex; align-items: center; gap: 8px; cursor: default;">
<div style="display: flex; gap: 3px;">
<div style="width: 5px; height: 5px; background: #9ca3af; border-radius: 50%; animation: typing 1.4s infinite;"></div>
<div style="width: 5px; height: 5px; background: #9ca3af; border-radius: 50%; animation: typing 1.4s infinite 0.2s;"></div>
<div style="width: 5px; height: 5px; background: #9ca3af; border-radius: 50%; animation: typing 1.4s infinite 0.4s;"></div>
</div>
<span style="color: #6b7280; font-weight: 400;">AI is thinking...</span>
</div>
`;
// Add CSS animation with smooth, subtle movement
const style = document.createElement('style');
style.textContent = `
@keyframes typing {{
0%, 60%, 100% {{
opacity: 0.4;
transform: scale(0.9);
}}
30% {{
opacity: 1;
transform: scale(1.1);
}}
}}
`;
document.head.appendChild(style);
document.body.appendChild(typingBubble);
setTimeout(() => {{
typingBubble.style.opacity = '1';
typingBubble.style.transform = 'scale(1)';
}}, 50);
// Return remove function
window.removeTypingIndicator = function() {{
const bubble = document.getElementById('{typing_id}');
if (bubble) {{
bubble.style.opacity = '0';
bubble.style.transform = 'scale(0.98)';
setTimeout(() => bubble.remove(), 250);
}}
}};
"""
return typing_js
def create_ai_avatar(self, position: str = "top-left") -> str:
"""
Create a simple AI avatar icon that the chat bubble connects to.
Args:
position: Position for the avatar
Returns:
JavaScript code to create the avatar
"""
avatar_id = f"ai-avatar-{uuid.uuid4().hex[:8]}"
# Position the avatar to the left of where the bubble appears
avatar_positions = {
"top-left": "top: 60px; left: 20px;",
"top-right": "top: 60px; right: 80px;",
"bottom-left": "bottom: 20px; left: 20px;",
"bottom-right": "bottom: 20px; right: 80px;"
}
avatar_css = avatar_positions.get(position, avatar_positions["top-left"])
avatar_js = f"""
// Remove existing avatar if any
const existingAvatar = document.getElementById('{avatar_id}');
if (existingAvatar) {{
existingAvatar.remove();
}}
// Create AI avatar
const aiAvatar = document.createElement('div');
aiAvatar.id = '{avatar_id}';
aiAvatar.style.cssText = `
position: fixed;
{avatar_css}
width: 40px;
height: 40px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
z-index: 999998;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
cursor: default;
user-select: none;
`;
aiAvatar.innerHTML = `
<span style="
color: white;
font-size: 16px;
font-weight: 600;
font-family: 'Inter', 'Arial', sans-serif;
cursor: default;
">AI</span>
`;
document.body.appendChild(aiAvatar);
// Store avatar for later removal
window.currentAiAvatar = '{avatar_id}';
"""
return avatar_js
def remove_ai_avatar(self) -> str:
"""Remove the AI avatar."""
remove_js = """
if (window.currentAiAvatar) {
const avatar = document.getElementById(window.currentAiAvatar);
if (avatar) {
avatar.remove();
}
delete window.currentAiAvatar;
}
"""
return remove_js
def ensure_standard_cursor(self) -> str:
"""Ensure the cursor is the standard Windows black arrow cursor."""
cursor_js = """
// Override any custom cursors and ensure standard Windows cursor
document.body.style.cursor = 'default';
document.documentElement.style.cursor = 'default';
// Apply to all elements that might have custom cursors
const allElements = document.querySelectorAll('*');
allElements.forEach(el => {
const computedStyle = window.getComputedStyle(el);
if (computedStyle.cursor !== 'default' &&
computedStyle.cursor !== 'pointer' &&
computedStyle.cursor !== 'text') {
el.style.cursor = 'default';
}
});
// Set default cursor for the entire page
const style = document.createElement('style');
style.textContent = `
*, *:before, *:after {
cursor: default !important;
}
a, button, [onclick], .clickable {
cursor: pointer !important;
}
input, textarea, [contenteditable] {
cursor: text !important;
}
`;
document.head.appendChild(style);
"""
return cursor_js
class MacroRecorder:
"""Record and replay browser automation macros."""
def __init__(self):
self.recording = False
self.macro_steps = []
self.saved_macros = {}
def start_recording(self, macro_name: str):
"""Start recording user actions."""
self.recording = True
self.macro_steps = []
self.current_macro_name = macro_name
logger.info(f"Started recording macro: {macro_name}")
def record_action(self, action_type: str, target: str, value: Any = None, wait_after: float = 0):
"""Record a single action."""
if self.recording:
step = {
"action": action_type,
"target": target,
"value": value,
"wait": wait_after,
"timestamp": datetime.now().isoformat()
}
self.macro_steps.append(step)
def stop_recording(self) -> Dict:
"""Stop recording and save macro."""
if self.recording:
self.recording = False