-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSebas.py
More file actions
1918 lines (1531 loc) · 69.9 KB
/
Sebas.py
File metadata and controls
1918 lines (1531 loc) · 69.9 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 time
import threading
import logging
import json
import hashlib
import asyncio
from datetime import datetime
from typing import Dict, List, Any, Optional
from dataclasses import dataclass, field
from enum import Enum
import tkinter as tk
from tkinter import font, scrolledtext, messagebox, filedialog
import pyautogui
import keyboard
from PIL import Image, ImageChops
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import google.generativeai as genai
from dotenv import load_dotenv
import re
from collections import deque
from PIL import Image, ImageChops, ImageStat
import uuid
import speech_recognition as sr
import pyttsx3
load_dotenv()
# LOGGING & OBSERVABILITY
class MetricsCollector:
"""Centralized metrics collection for observability"""
def __init__(self):
self.metrics = {
"agent_calls": 0,
"successful_analyses": 0,
"failed_analyses": 0,
"cache_hits": 0,
"cache_misses": 0,
"avg_response_time": [],
"tool_usage": {},
"agent_performance": {}
}
self.lock = threading.Lock()
def record_metric(self, metric_name: str, value: Any):
with self.lock:
if metric_name in self.metrics:
if isinstance(self.metrics[metric_name], list):
self.metrics[metric_name].append(value)
elif isinstance(self.metrics[metric_name], dict):
if isinstance(value, tuple):
key, val = value
self.metrics[metric_name][key] = val
else:
self.metrics[metric_name] += value
def get_metrics(self) -> Dict:
with self.lock:
return self.metrics.copy()
def export_metrics(self, filepath: str = "metrics.json"):
with open(filepath, 'w') as f:
json.dump(self.get_metrics(), f, indent=2)
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - [%(threadName)s] - %(message)s',
handlers=[
logging.FileHandler('sebastian_multi_agent.log', encoding='utf-8'),
logging.StreamHandler()
]
)
# MAIN ENTRY POINT
SORTING_CONFIG_FILE = "sorting_rules.json"
WATCH_FOLDER = r"E:\Sebas"
CONFIG_FILE = "sebastian_config.json"
MEMORY_BANK_FILE = "memory_bank.json"
SESSION_FILE = "sessions.json"
def load_config():
defaults = {
"stability_threshold": 10.0,
"analysis_cooldown": 5.0,
"window_position": [1300, 50],
"window_size": [500, 600],
"screen_check_interval": 0.15,
"screenshot_quality": (100, 100),
"change_threshold": 0.005,
"auto_edit_enabled": True,
"save_folder": "./sebastian_fixes/",
"confirm_apply": True,
"detect_editor": "vscode",
"max_memory_entries": 100,
"context_window_size": 50000,
"enable_mcp": True,
"enable_parallel_agents": True,
"agent_timeout": 30,
"voice_enabled": True
}
try:
if os.path.exists(CONFIG_FILE):
with open(CONFIG_FILE, 'r') as f:
return {**defaults, **json.load(f)}
except Exception as e:
logging.warning(f"Config load failed: {e}")
return defaults
config = load_config()
os.makedirs(config["save_folder"], exist_ok=True)
metrics = MetricsCollector()
# API CONFIGURATION
API_KEY = os.getenv("GOOGLE_API_KEY") or os.getenv("GEMINI_API_KEY")
if not API_KEY:
logging.error("API Key not found")
print("\n❌ SETUP ERROR: Create a .env file with GOOGLE_API_KEY='your_key'")
try:
if API_KEY:
genai.configure(api_key=API_KEY)
MODEL_NAME = 'models/gemini-2.0-flash'
model = genai.GenerativeModel(MODEL_NAME)
logging.info(f"API configured: {MODEL_NAME}")
except Exception as e:
logging.error(f"API config failed: {e}")
# WATCHDOG & FILE SORTING SYSTEM
import shutil
observer = None
watchdog_thread = None
watchdog_running = False
class FileOrganizerHandler(FileSystemEventHandler):
def __init__(self):
self.rules = self.load_rules()
self.processing_lock = threading.Lock()
def load_rules(self):
if os.path.exists(SORTING_CONFIG_FILE):
try:
with open(SORTING_CONFIG_FILE, 'r') as f:
rules = json.load(f)
print(f"✅ Rules Loaded: {len(rules)} categories.")
return rules
except Exception as e:
print(f"❌ Error reading JSON: {e}")
return {}
else:
print(f"⚠️ {SORTING_CONFIG_FILE} NOT FOUND. Sorting will not work.")
return {}
# Triggers for any event
def on_created(self, event):
if not event.is_directory: self.organize_file(event.src_path, "Created")
def on_moved(self, event):
if not event.is_directory: self.organize_file(event.dest_path, "Renamed")
def on_modified(self, event):
if not event.is_directory: self.organize_file(event.src_path, "Modified")
def organize_file(self, filepath, event_type):
filename = os.path.basename(filepath)
if filename.startswith("~") or filename.endswith(".tmp") or filename == "sorting_rules.json":
return
print(f"\n🔔 EVENT: {event_type} detected on: {filename}")
if not self.rules:
print("❌ STOPPING: No sorting rules loaded.")
return
try:
time.sleep(1.0)
if not os.path.exists(filepath):
print("❌ STOPPING: File disappeared before processing.")
return
if "new text document" in filename.lower() or "new folder" in filename.lower():
print("⏳ PAUSED: Ignoring 'New Text Document' (waiting for rename)")
return
base_dir = os.path.dirname(filepath)
norm_base = os.path.normpath(base_dir).lower()
norm_watch = os.path.normpath(WATCH_FOLDER).lower()
if norm_base != norm_watch:
print(f"⛔ IGNORED: File is in a subfolder, not the root.")
print(f" File location: {norm_base}")
print(f" Watch folder: {norm_watch}")
return
_, ext = os.path.splitext(filename)
ext = ext.lower()
filename_lower = filename.lower()
target_folder = "Others"
found_match = False
for folder, criteria_list in self.rules.items():
for criteria in criteria_list:
criteria = criteria.lower()
if criteria.startswith('.'):
if ext == criteria:
target_folder = folder
found_match = True
print(f" MATCH FOUND: Extension {ext} -> {folder}")
break
else:
if criteria in filename_lower:
target_folder = folder
found_match = True
print(f" MATCH FOUND: Keyword '{criteria}' -> {folder}")
break
if found_match: break
if not found_match:
print(f" NO MATCH: Defaulting to 'Others'")
target_path = os.path.join(base_dir, target_folder)
os.makedirs(target_path, exist_ok=True)
dest_path = os.path.join(target_path, filename)
base_name, extension = os.path.splitext(filename)
counter = 1
while os.path.exists(dest_path):
dest_path = os.path.join(target_path, f"{base_name}_{counter}{extension}")
counter += 1
shutil.move(filepath, dest_path)
print(f"✅ SUCCESS: Moved to {target_folder}")
except Exception as e:
print(f"❌ ERROR: {e}")
def watchdog_worker():
"""Background thread worker that keeps observer alive"""
global observer, watchdog_running
try:
event_handler = FileOrganizerHandler()
if not event_handler.rules:
logging.error("❌ No sorting rules loaded - watchdog cannot start")
print("❌ File sorting disabled: sorting_rules.json not found or empty")
watchdog_running = False
return
observer = Observer()
observer.schedule(event_handler, WATCH_FOLDER, recursive=False)
observer.start()
logging.info(f"✅ Watchdog active: {WATCH_FOLDER}")
print(f"👀 Watching: {WATCH_FOLDER}")
print(f"📋 Loaded {len(event_handler.rules)} sorting categories")
while watchdog_running:
time.sleep(1)
observer.stop()
observer.join()
logging.info("🛑 Watchdog stopped gracefully")
print("🛑 File sorting stopped")
except Exception as e:
logging.error(f"❌ Watchdog thread error: {e}", exc_info=True)
print(f"❌ Watchdog failed: {e}")
watchdog_running = False
def start_watchdog():
"""Starts the file system observer in a background thread"""
global watchdog_thread, watchdog_running
if not os.path.exists(WATCH_FOLDER):
try:
os.makedirs(WATCH_FOLDER)
print(f"📁 Created folder: {WATCH_FOLDER}")
logging.info(f"Created watch folder: {WATCH_FOLDER}")
except Exception as e:
print(f"❌ Could not create folder {WATCH_FOLDER}: {e}")
logging.error(f"Failed to create watch folder: {e}")
return False
if watchdog_running:
logging.warning("⚠️ Watchdog already running")
return True
watchdog_running = True
watchdog_thread = threading.Thread(target=watchdog_worker, daemon=True, name="WatchdogThread")
watchdog_thread.start()
time.sleep(0.5)
return watchdog_running
def stop_watchdog():
"""Stops the watchdog observer gracefully"""
global watchdog_running, observer
if not watchdog_running:
return
logging.info("Stopping watchdog...")
watchdog_running = False
if watchdog_thread and watchdog_thread.is_alive():
watchdog_thread.join(timeout=3)
logging.info("Watchdog stopped")
# VOICE ASSISTANT SYSTEM
class VoiceHandler:
"""Handles Text-to-Speech and Speech-to-Text operations"""
def __init__(self):
self.recognizer = sr.Recognizer()
self.engine = pyttsx3.init()
self.is_listening = False
self.setup_voice()
def setup_voice(self):
"""Configure TTS engine for Sebastian's persona"""
try:
voices = self.engine.getProperty('voices')
self.engine.setProperty('voice', voices[0].id)
self.engine.setProperty('rate', 160)
self.engine.setProperty('volume', 0.9)
except Exception as e:
logging.error(f"Voice setup error: {e}")
def speak(self, text):
"""Non-blocking speak function"""
def _speak_thread():
try:
engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[0].id)
engine.setProperty('rate', 160)
engine.say(text)
engine.runAndWait()
except Exception as e:
logging.error(f"Speech error: {e}")
threading.Thread(target=_speak_thread, daemon=True).start()
def listen_for_command(self):
"""One-shot listening for commands"""
with sr.Microphone() as source:
logging.info("Listening for voice command...")
try:
self.recognizer.adjust_for_ambient_noise(source, duration=0.5)
self.recognizer.pause_threshold = 1.0
audio = self.recognizer.listen(source, timeout=8, phrase_time_limit=15)
self.recognizer.energy_threshold = 4000
self.recognizer.dynamic_energy_threshold = True
command = self.recognizer.recognize_google(audio)
return command.lower()
except sr.WaitTimeoutError:
return None
except sr.UnknownValueError:
return None
except Exception as e:
logging.error(f"Listen error: {e}")
return None
voice_handler = VoiceHandler()
# AGENT TYPES & ENUMS
class AgentType(Enum):
CODE_ANALYZER = "code_analyzer"
BUG_DETECTOR = "bug_detector"
FIX_GENERATOR = "fix_generator"
SECURITY_AUDITOR = "security_auditor"
PERFORMANCE_OPTIMIZER = "performance_optimizer"
DOCUMENTATION_WRITER = "documentation_writer"
ORCHESTRATOR = "orchestrator"
class AgentStatus(Enum):
IDLE = "idle"
RUNNING = "running"
COMPLETED = "completed"
FAILED = "failed"
PAUSED = "paused"
# MEMORY BANK - Long Term Memory
class MemoryBank:
"""Persistent long-term memory storage for agents"""
def __init__(self, filepath: str = MEMORY_BANK_FILE):
self.filepath = filepath
self.memories: List[Dict] = []
self.load()
def load(self):
if os.path.exists(self.filepath):
try:
with open(self.filepath, 'r') as f:
self.memories = json.load(f)
logging.info(f"Loaded {len(self.memories)} memories")
except Exception as e:
logging.error(f"Failed to load memory bank: {e}")
def save(self):
try:
with open(self.filepath, 'w') as f:
json.dump(self.memories, f, indent=2)
except Exception as e:
logging.error(f"Failed to save memory bank: {e}")
def add_memory(self, content: str, tags: List[str], metadata: Dict = None):
memory = {
"id": str(uuid.uuid4()),
"content": content,
"tags": tags,
"timestamp": datetime.now().isoformat(),
"metadata": metadata or {}
}
self.memories.append(memory)
if len(self.memories) > config["max_memory_entries"]:
self.memories = self.memories[-config["max_memory_entries"]:]
self.save()
logging.info(f"Memory added: {memory['id']}")
def search(self, query: str = None, tags: List[str] = None, limit: int = 10) -> List[Dict]:
results = self.memories
if tags:
results = [m for m in results if any(tag in m.get('tags', []) for tag in tags)]
if query:
results = [m for m in results if query.lower() in m['content'].lower()]
return sorted(results, key=lambda x: x['timestamp'], reverse=True)[:limit]
def get_context_summary(self, limit: int = 5) -> str:
recent = self.memories[-limit:]
summary = "Recent Context:\n"
for mem in recent:
summary += f"- [{', '.join(mem['tags'])}] {mem['content'][:100]}...\n"
return summary
# SESSION MANAGEMENT
@dataclass
class Session:
session_id: str
created_at: datetime
last_active: datetime
state: Dict = field(default_factory=dict)
history: List[Dict] = field(default_factory=list)
class InMemorySessionService:
"""Manages agent sessions and state"""
def __init__(self, filepath: str = SESSION_FILE):
self.filepath = filepath
self.sessions: Dict[str, Session] = {}
self.current_session_id: Optional[str] = None
self.load()
def load(self):
if os.path.exists(self.filepath):
try:
with open(self.filepath, 'r') as f:
data = json.load(f)
for sid, sdata in data.items():
self.sessions[sid] = Session(
session_id=sid,
created_at=datetime.fromisoformat(sdata['created_at']),
last_active=datetime.fromisoformat(sdata['last_active']),
state=sdata.get('state', {}),
history=sdata.get('history', [])
)
logging.info(f"Loaded {len(self.sessions)} sessions")
except Exception as e:
logging.error(f"Failed to load sessions: {e}")
def save(self):
try:
data = {}
for sid, session in self.sessions.items():
data[sid] = {
'created_at': session.created_at.isoformat(),
'last_active': session.last_active.isoformat(),
'state': session.state,
'history': session.history
}
with open(self.filepath, 'w') as f:
json.dump(data, f, indent=2)
except Exception as e:
logging.error(f"Failed to save sessions: {e}")
def create_session(self) -> str:
session_id = str(uuid.uuid4())
self.sessions[session_id] = Session(
session_id=session_id,
created_at=datetime.now(),
last_active=datetime.now()
)
self.current_session_id = session_id
self.save()
logging.info(f"Created session: {session_id}")
return session_id
def get_session(self, session_id: str) -> Optional[Session]:
return self.sessions.get(session_id)
def update_session(self, session_id: str, state: Dict = None, history_entry: Dict = None):
if session_id in self.sessions:
session = self.sessions[session_id]
session.last_active = datetime.now()
if state:
session.state.update(state)
if history_entry:
session.history.append(history_entry)
self.save()
def pause_session(self, session_id: str):
if session_id in self.sessions:
self.sessions[session_id].state['paused'] = True
self.save()
def resume_session(self, session_id: str):
if session_id in self.sessions:
self.sessions[session_id].state['paused'] = False
self.save()
# CONTEXT ENGINEERING - Context Compaction
class ContextManager:
"""Manages context window and performs compaction"""
def __init__(self, max_tokens: int = 50000):
self.max_tokens = max_tokens
self.context_buffer = deque(maxlen=100)
def estimate_tokens(self, text: str) -> int:
return len(text) // 4
def add_context(self, content: str, priority: int = 1):
self.context_buffer.append({
'content': content,
'priority': priority,
'timestamp': time.time(),
'tokens': self.estimate_tokens(content)
})
def compact_context(self) -> str:
"""Intelligently compact context to fit within token limit"""
total_tokens = sum(item['tokens'] for item in self.context_buffer)
if total_tokens <= self.max_tokens:
return "\n".join(item['content'] for item in self.context_buffer)
sorted_items = sorted(
self.context_buffer,
key=lambda x: (x['priority'], x['timestamp']),
reverse=True
)
compacted = []
current_tokens = 0
for item in sorted_items:
if current_tokens + item['tokens'] <= self.max_tokens * 0.9:
compacted.append(item['content'])
current_tokens += item['tokens']
else:
remaining = [i['content'] for i in sorted_items if i not in compacted]
if remaining:
summary = f"[Compacted {len(remaining)} older entries]"
compacted.append(summary)
break
return "\n".join(compacted)
# TOOLS SYSTEM
class Tool:
"""Base class for agent tools"""
def __init__(self, name: str, description: str):
self.name = name
self.description = description
self.logger = logging.getLogger(f"Tool.{name}")
async def execute(self, *args, **kwargs) -> Any:
raise NotImplementedError
class FileAnalyzerTool(Tool):
def __init__(self):
super().__init__("file_analyzer", "Analyzes code files for issues")
async def execute(self, filepath: str) -> Dict:
try:
with open(filepath, 'r') as f:
content = f.read()
lines = content.split('\n')
metrics.record_metric("tool_usage", (self.name, 1))
return {
"filepath": filepath,
"lines": len(lines),
"size": len(content),
"content": content[:5000]
}
except Exception as e:
self.logger.error(f"File analysis failed: {e}")
return {"error": str(e)}
class CodeExecutionTool(Tool):
def __init__(self):
super().__init__("code_execution", "Executes safe code snippets")
async def execute(self, code: str, language: str = "python") -> Dict:
self.logger.info(f"Code execution requested: {language}")
metrics.record_metric("tool_usage", (self.name, 1))
return {"status": "simulated", "output": "Execution feature pending"}
class WebSearchTool(Tool):
def __init__(self):
super().__init__("web_search", "Searches web for solutions")
async def execute(self, query: str) -> Dict:
self.logger.info(f"Web search: {query}")
metrics.record_metric("tool_usage", (self.name, 1))
return {"query": query, "results": ["Placeholder result"]}
class ToolRegistry:
"""Central registry for all available tools"""
def __init__(self):
self.tools: Dict[str, Tool] = {}
self.register_default_tools()
def register_default_tools(self):
self.register(FileAnalyzerTool())
self.register(CodeExecutionTool())
self.register(WebSearchTool())
def register(self, tool: Tool):
self.tools[tool.name] = tool
logging.info(f"Tool registered: {tool.name}")
def get_tool(self, name: str) -> Optional[Tool]:
return self.tools.get(name)
async def execute_tool(self, name: str, *args, **kwargs) -> Any:
tool = self.get_tool(name)
if tool:
return await tool.execute(*args, **kwargs)
raise ValueError(f"Tool not found: {name}")
# AGENT BASE CLASS
@dataclass
class AgentTask:
task_id: str
agent_type: AgentType
input_data: Dict
created_at: float
status: AgentStatus = AgentStatus.IDLE
result: Optional[Dict] = None
error: Optional[str] = None
class BaseAgent:
"""Base class for all specialized agents"""
def __init__(self, agent_type: AgentType, tools: ToolRegistry):
self.agent_type = agent_type
self.agent_id = str(uuid.uuid4())
self.status = AgentStatus.IDLE
self.tools = tools
self.logger = logging.getLogger(f"Agent.{agent_type.value}")
self.context_manager = ContextManager()
async def execute(self, task: AgentTask, memory: MemoryBank) -> Dict:
"""Execute agent task with observability"""
start_time = time.time()
self.status = AgentStatus.RUNNING
task.status = AgentStatus.RUNNING
self.logger.info(f"Starting task: {task.task_id}")
metrics.record_metric("agent_calls", 1)
try:
context = memory.get_context_summary()
self.context_manager.add_context(context, priority=2)
result = await self._process(task)
task.status = AgentStatus.COMPLETED
task.result = result
self.status = AgentStatus.COMPLETED
elapsed = time.time() - start_time
metrics.record_metric("avg_response_time", elapsed)
metrics.record_metric("agent_performance", (self.agent_type.value, elapsed))
metrics.record_metric("successful_analyses", 1)
self.logger.info(f"Task completed: {task.task_id} in {elapsed:.2f}s")
memory.add_memory(
content=f"Agent {self.agent_type.value} completed task",
tags=[self.agent_type.value, "success"],
metadata={"task_id": task.task_id, "duration": elapsed}
)
return result
except Exception as e:
task.status = AgentStatus.FAILED
task.error = str(e)
self.status = AgentStatus.FAILED
metrics.record_metric("failed_analyses", 1)
self.logger.error(f"Task failed: {task.task_id} - {e}")
memory.add_memory(
content=f"Agent {self.agent_type.value} failed: {str(e)}",
tags=[self.agent_type.value, "failure"],
metadata={"task_id": task.task_id, "error": str(e)}
)
raise
async def _process(self, task: AgentTask) -> Dict:
"""Override in subclasses"""
raise NotImplementedError
# SPECIALIZED AGENTS
class CodeAnalyzerAgent(BaseAgent):
def __init__(self, tools: ToolRegistry):
super().__init__(AgentType.CODE_ANALYZER, tools)
async def _process(self, task: AgentTask) -> Dict:
filepath = task.input_data.get('filepath')
screenshot = task.input_data.get('screenshot')
if filepath:
file_data = await self.tools.execute_tool('file_analyzer', filepath)
analysis = f"Analyzed file: {filepath}\nLines: {file_data.get('lines', 0)}"
else:
analysis = "Screen-based analysis"
return {
"agent": self.agent_type.value,
"analysis": analysis,
"recommendations": ["Code structure looks good", "Consider adding error handling"]
}
class BugDetectorAgent(BaseAgent):
def __init__(self, tools: ToolRegistry):
super().__init__(AgentType.BUG_DETECTOR, tools)
async def _process(self, task: AgentTask) -> Dict:
code_content = task.input_data.get('code', '')
filepath = task.input_data.get('filepath', 'Unknown')
screenshot_path = task.input_data.get('screenshot_path')
bugs = []
try:
prompt = f"""Analyze this code and find ALL bugs. For EACH bug, provide:
1. Exact line number
2. The CURRENT buggy line
3. The CORRECTED line (exact replacement)
File: {filepath}
Code:
{code_content}
Respond in this EXACT JSON format:
{{
"bugs": [
{{
"line_number": <number>,
"buggy_line": "<exact current line>",
"fixed_line": "<exact corrected line>",
"issue": "<brief 1-sentence issue>"
}}
]
}}
Focus on: syntax errors, wrong keywords, wrong method names, logic errors.
BE PRECISE with line numbers and exact code."""
if screenshot_path and os.path.exists(screenshot_path):
img = Image.open(screenshot_path)
response = model.generate_content([prompt, img])
else:
response = model.generate_content(prompt)
result_text = response.text.strip()
json_match = re.search(r'\{.*\}', result_text, re.DOTALL)
if json_match:
result_json = json.loads(json_match.group())
bugs = result_json.get('bugs', [])
if not bugs:
bugs = self._detect_bugs_from_code(code_content, filepath)
self.logger.info(f"Bug detector found {len(bugs)} issues")
except Exception as e:
self.logger.error(f"Bug detection failed: {e}")
bugs = self._detect_bugs_from_code(code_content, filepath)
return {
"agent": self.agent_type.value,
"bugs_found": len(bugs),
"bugs": bugs
}
def _detect_bugs_from_code(self, code: str, filepath: str) -> List[Dict]:
"""Pattern-based bug detection with line-by-line fixes"""
bugs = []
lines = code.split('\n')
# Handle None filepath
if not filepath:
filepath = "unknown"
is_java = filepath.endswith('.java')
is_python = filepath.endswith('.py')
for i, line in enumerate(lines, 1):
original_line = line
fixed_line = None
issue = None
if is_java:
if 'public void main' in line and 'static' not in line:
fixed_line = line.replace('public void main', 'public static void main')
issue = "main method must be static"
elif '.length()' in line:
fixed_line = line.replace('.length()', '.length')
issue = "Arrays use .length property"
elif 'printLine' in line:
fixed_line = line.replace('printLine', 'println')
issue = "Wrong method name"
elif '<=' in line and '.length' in line and 'for' in line:
fixed_line = line.replace('<=', '<')
issue = "Loop bound should use < not <="
if is_python:
if 'def init' in line:
fixed_line = line.replace('def init', 'def __init__')
issue = "Incorrect constructor name"
if fixed_line and fixed_line != original_line:
bugs.append({
"line_number": i,
"buggy_line": original_line.strip(),
"fixed_line": fixed_line.strip(),
"issue": issue
})
return bugs
class FixGeneratorAgent(BaseAgent):
def __init__(self, tools: ToolRegistry):
super().__init__(AgentType.FIX_GENERATOR, tools)
async def _process(self, task: AgentTask) -> Dict:
bugs = task.input_data.get('bugs', [])
previous_result = task.input_data.get('previous_result', {})
if not bugs and previous_result:
bugs = previous_result.get('bugs', [])
if not bugs:
self.logger.warning("No bugs provided to fix generator")
return {
"agent": self.agent_type.value,
"fixes": [],
"message": "No bugs to fix"
}
fixes = []
for bug in bugs:
fixes.append({
"line_number": bug.get('line_number', bug.get('line', 'unknown')),
"buggy_line": bug.get('buggy_line', ''),
"fixed_line": bug.get('fixed_line', ''),
"issue": bug.get('issue', bug.get('message', 'Fix applied'))
})
self.logger.info(f"Prepared {len(fixes)} fixes for application")
return {
"agent": self.agent_type.value,
"fixes": fixes,
"fixes_count": len(fixes)
}
class SecurityAuditorAgent(BaseAgent):
def __init__(self, tools: ToolRegistry):
super().__init__(AgentType.SECURITY_AUDITOR, tools)
async def _process(self, task: AgentTask) -> Dict:
code = task.input_data.get('code', '')
vulnerabilities = []
if 'eval(' in code:
vulnerabilities.append("Dangerous eval() usage detected")
if 'exec(' in code:
vulnerabilities.append("Dangerous exec() usage detected")
return {
"agent": self.agent_type.value,
"vulnerabilities": vulnerabilities,
"risk_level": "medium" if vulnerabilities else "low"
}
# ORCHESTRATOR - Multi-Agent Coordination
class AgentOrchestrator:
"""Coordinates multiple agents in parallel and sequential workflows"""
def __init__(self, tools: ToolRegistry, memory: MemoryBank, session_service: InMemorySessionService):
self.tools = tools
self.memory = memory
self.session_service = session_service
self.agents: Dict[AgentType, BaseAgent] = {}
self.logger = logging.getLogger("Orchestrator")
self.task_queue = asyncio.Queue()
self.initialize_agents()
def initialize_agents(self):
"""Initialize all specialized agents"""
self.agents[AgentType.CODE_ANALYZER] = CodeAnalyzerAgent(self.tools)
self.agents[AgentType.BUG_DETECTOR] = BugDetectorAgent(self.tools)
self.agents[AgentType.FIX_GENERATOR] = FixGeneratorAgent(self.tools)
self.agents[AgentType.SECURITY_AUDITOR] = SecurityAuditorAgent(self.tools)
self.logger.info(f"Initialized {len(self.agents)} agents")
async def execute_parallel(self, tasks: List[AgentTask]) -> List[Dict]:
"""Execute multiple agents in parallel"""
self.logger.info(f"Executing {len(tasks)} tasks in parallel")
async def run_task(task):
agent = self.agents.get(task.agent_type)
if agent:
return await agent.execute(task, self.memory)
return {"error": "Agent not found"}
results = await asyncio.gather(*[run_task(task) for task in tasks], return_exceptions=True)
return [r if not isinstance(r, Exception) else {"error": str(r)} for r in results]
async def execute_sequential(self, tasks: List[AgentTask]) -> List[Dict]:
"""Execute agents in sequence, passing output to next"""
self.logger.info(f"Executing {len(tasks)} tasks sequentially")
results = []
previous_result = {}
for task in tasks:
task.input_data['previous_result'] = previous_result
agent = self.agents.get(task.agent_type)
if agent:
result = await agent.execute(task, self.memory)
results.append(result)
previous_result = result
else:
results.append({"error": "Agent not found"})
return results
async def execute_workflow(self, workflow_type: str, input_data: Dict) -> Dict:
"""Execute a predefined workflow"""
if workflow_type == "full_analysis":
return await self._full_analysis_workflow(input_data)
elif workflow_type == "security_audit":
return await self._security_audit_workflow(input_data)
else:
raise ValueError(f"Unknown workflow: {workflow_type}")
async def _full_analysis_workflow(self, input_data: Dict) -> Dict:
"""Complete code analysis workflow"""
parallel_tasks = [
AgentTask(
task_id=str(uuid.uuid4()),
agent_type=AgentType.CODE_ANALYZER,