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
 
 
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
#!/usr/bin/env python3
"""
Multi-Agent Orchestration System for E-FIRE-1
Autonomous agent coordination, communication, and task delegation
"""

import asyncio
import json
import time
import hashlib
from datetime import datetime
from typing import Dict, List, Any, Optional
from dataclasses import dataclass, asdict
import websockets
import threading
import sqlite3
import os
try:
    import psycopg2
except Exception:
    psycopg2 = None  # type: ignore
import logging
import uuid


@dataclass
class AgentMessage:
    """Message structure for inter-agent communication"""
    id: str
    sender: str
    recipient: str
    type: str  # 'task', 'response', 'broadcast', 'coordination'
    content: Any
    timestamp: datetime
    priority: int = 1
    ttl: int = 300  # Time to live in seconds


@dataclass
class Task:
    """Task structure for agent delegation"""
    id: str
    type: str
    data: Dict[str, Any]
    priority: int
    assigned_agent: Optional[str] = None
    status: str = 'pending'  # pending, assigned, in_progress, completed, failed
    created_at: datetime = None
    completed_at: Optional[datetime] = None
    result: Optional[Dict[str, Any]] = None
    attempts: int = 0
    max_attempts: int = 3


class AgentOrchestrator:
    """Central orchestrator for multi-agent system"""
    
    def __init__(self, port=8765):
        self.port = port
        self.agents: Dict[str, Dict[str, Any]] = {}
        self.message_queue: List[AgentMessage] = []
        self.tasks: Dict[str, Task] = {}
        self.running = False
        self.websocket_server = None
        self.logger = logging.getLogger('AgentOrchestrator')
        self.setup_database()
    
    def setup_database(self):
        """Setup message and task storage"""
        self.db = sqlite3.connect('agent_communications.db', check_same_thread=False)
        cursor = self.db.cursor()
        
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS messages (
                id TEXT PRIMARY KEY,
                sender TEXT,
                recipient TEXT,
                type TEXT,
                content TEXT,
                timestamp TEXT,
                priority INTEGER,
                processed BOOLEAN DEFAULT FALSE
            )
        ''')
        
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS tasks (
                id TEXT PRIMARY KEY,
                type TEXT,
                data TEXT,
                priority INTEGER,
                assigned_agent TEXT,
                status TEXT,
                created_at TEXT,
                completed_at TEXT,
                result TEXT,
                attempts INTEGER DEFAULT 0
            )
        ''')
        
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS agent_performance (
                agent_id TEXT,
                timestamp TEXT,
                tasks_completed INTEGER,
                earnings REAL,
                uptime REAL
            )
        ''')
        
        self.db.commit()
        # Optional Postgres durable store
        self.pg = None
        dsn = os.getenv('POSTGRES_DSN')
        if dsn and psycopg2 is not None:
            try:
                self.pg = psycopg2.connect(dsn)
                with self.pg.cursor() as cur:
                    ddl = open('/data/adaptai/projects/elizabeth/sql/orchestrator_store.sql').read()
                    cur.execute(ddl)
                self.pg.commit()
            except Exception:
                self.pg = None
    
    def register_agent(self, agent_id: str, capabilities: List[str], endpoint: str = None):
        """Register a new agent with capabilities"""
        self.agents[agent_id] = {
            'id': agent_id,
            'capabilities': capabilities,
            'endpoint': endpoint,
            'status': 'active',
            'last_heartbeat': datetime.now(),
            'tasks_completed': 0,
            'earnings': 0.0
        }
    
    def send_message(self, sender: str, recipient: str, msg_type: str, content: Any, priority: int = 1) -> str:
        """Send message to specific agent or broadcast"""
        message_id = str(uuid.uuid4())
        message = AgentMessage(
            id=message_id,
            sender=sender,
            recipient=recipient,
            type=msg_type,
            content=content,
            timestamp=datetime.now(),
            priority=priority
        )
        
        self.message_queue.append(message)
        
        # Store in database
        cursor = self.db.cursor()
        cursor.execute('''
            INSERT INTO messages (id, sender, recipient, type, content, timestamp, priority)
            VALUES (?, ?, ?, ?, ?, ?, ?)
        ''', (
            message_id, sender, recipient, msg_type,
            json.dumps(content), datetime.now().isoformat(), priority
        ))
        self.db.commit()
        # Dual-write to Postgres if available
        if getattr(self, 'pg', None):
            try:
                with self.pg, self.pg.cursor() as cur:
                    cur.execute(
                        "INSERT INTO eliz_orch_messages (id, sender, recipient, type, content, timestamp, priority) VALUES (%s,%s,%s,%s,%s,%s,%s)",
                        (message_id, sender, recipient, msg_type, json.dumps(content), datetime.now(), priority)
                    )
            except Exception:
                pass
        
        return message_id
    
    def create_task(self, task_type: str, data: Dict[str, Any], priority: int = 1) -> str:
        """Create a new task for agent delegation"""
        task_id = str(uuid.uuid4())
        task = Task(
            id=task_id,
            type=task_type,
            data=data,
            priority=priority,
            created_at=datetime.now()
        )
        
        self.tasks[task_id] = task
        
        # Store in database
        cursor = self.db.cursor()
        cursor.execute('''
            INSERT INTO tasks (id, type, data, priority, status, created_at)
            VALUES (?, ?, ?, ?, ?, ?)
        ''', (
            task_id, task_type, json.dumps(data), priority, 'pending',
            datetime.now().isoformat()
        ))
        self.db.commit()
        # Dual-write to Postgres if available
        if getattr(self, 'pg', None):
            try:
                with self.pg, self.pg.cursor() as cur:
                    cur.execute(
                        "INSERT INTO eliz_orch_tasks (id, type, data, priority, status, created_at) VALUES (%s,%s,%s,%s,%s,%s)",
                        (task_id, task_type, json.dumps(data), priority, 'pending', datetime.now())
                    )
            except Exception:
                pass
        
        return task_id
    
    def delegate_task(self, task_id: str) -> Optional[str]:
        """Intelligently delegate task to most suitable agent"""
        task = self.tasks.get(task_id)
        if not task:
            return None
        
        # Find agents with required capabilities
        suitable_agents = []
        for agent_id, agent in self.agents.items():
            if agent['status'] == 'active' and task['type'] in agent['capabilities']:
                # Calculate suitability score
                score = (
                    1.0 / (agent.get('load', 1) + 1) +
                    0.5 * (datetime.now() - agent['last_heartbeat']).total_seconds() < 300
                )
                suitable_agents.append((agent_id, score))
        
        if suitable_agents:
            # Select best agent
            best_agent = max(suitable_agents, key=lambda x: x[1])[0]
            task.assigned_agent = best_agent
            task.status = 'assigned'
            
            # Update database
            cursor = self.db.cursor()
            cursor.execute('''
                UPDATE tasks SET assigned_agent = ?, status = ? WHERE id = ?
            ''', (best_agent, 'assigned', task_id))
            self.db.commit()
            # Postgres mirror
            if getattr(self, 'pg', None):
                try:
                    with self.pg, self.pg.cursor() as cur:
                        cur.execute("UPDATE eliz_orch_tasks SET assigned_agent=%s, status=%s WHERE id=%s", (best_agent, 'assigned', task_id))
                except Exception:
                    pass
            
            # Send task to agent
            self.send_message(
                'orchestrator',
                best_agent,
                'task',
                {
                    'task_id': task_id,
                    'type': task.type,
                    'data': task.data,
                    'priority': task.priority
                },
                priority=task.priority
            )
            
            return best_agent
        
        return None
    
    async def handle_websocket_connection(self, websocket, path):
        """Handle WebSocket connections from agents"""
        agent_id = None
        
        try:
            async for message in websocket:
                data = json.loads(message)
                
                if data['type'] == 'register':
                    agent_id = data['agent_id']
                    capabilities = data['capabilities']
                    self.register_agent(agent_id, capabilities, websocket.remote_address)
                    
                    await websocket.send(json.dumps({
                        'type': 'registered',
                        'agent_id': agent_id,
                        'timestamp': datetime.now().isoformat()
                    }))
                
                elif data['type'] == 'heartbeat':
                    if agent_id in self.agents:
                        self.agents[agent_id]['last_heartbeat'] = datetime.now()
                        self.agents[agent_id]['status'] = 'active'
                
                elif data['type'] == 'task_result':
                    task_id = data['task_id']
                    if task_id in self.tasks:
                        task = self.tasks[task_id]
                        task.result = data['result']
                        task.status = 'completed'
                        task.completed_at = datetime.now()
                        
                        # Update agent performance
                        if task.assigned_agent in self.agents:
                            self.agents[task.assigned_agent]['tasks_completed'] += 1
                            if 'earnings' in data['result']:
                                self.agents[task.assigned_agent]['earnings'] += data['result']['earnings']
                        
                        # Update database
                        cursor = self.db.cursor()
                        cursor.execute('''
                            UPDATE tasks SET status = ?, completed_at = ?, result = ?
                            WHERE id = ?
                        ''', (
                            'completed',
                            datetime.now().isoformat(),
                            json.dumps(data['result']),
                            task_id
                        ))
                        self.db.commit()
                        if getattr(self, 'pg', None):
                            try:
                                with self.pg, self.pg.cursor() as cur:
                                    cur.execute("UPDATE eliz_orch_tasks SET status=%s, completed_at=%s, result=%s WHERE id=%s",
                                                ('completed', datetime.now(), json.dumps(data['result']), task_id))
                            except Exception:
                                pass
                
                elif data['type'] == 'task_failed':
                    task_id = data['task_id']
                    if task_id in self.tasks:
                        task = self.tasks[task_id]
                        task.attempts += 1
                        
                        if task.attempts >= task.max_attempts:
                            task.status = 'failed'
                            cursor = self.db.cursor()
                            cursor.execute('''
                                UPDATE tasks SET status = ?, attempts = ? WHERE id = ?
                            ''', ('failed', task.attempts, task_id))
                            self.db.commit()
                            if getattr(self, 'pg', None):
                                try:
                                    with self.pg, self.pg.cursor() as cur:
                                        cur.execute("UPDATE eliz_orch_tasks SET status=%s, attempts=%s WHERE id=%s", ('failed', task.attempts, task_id))
                                except Exception:
                                    pass
                        else:
                            task.status = 'pending'
                            task.assigned_agent = None
                            # Re-delegate task
                            self.delegate_task(task_id)
                
        except websockets.exceptions.ConnectionClosed:
            if agent_id in self.agents:
                self.agents[agent_id]['status'] = 'offline'
        
        except Exception as e:
            self.logger.error(f"WebSocket error: {e}")
    
    def process_message_queue(self):
        """Process message queue with priority handling"""
        while self.running:
            if self.message_queue:
                # Sort by priority and timestamp
                self.message_queue.sort(key=lambda x: (-x.priority, x.timestamp))
                message = self.message_queue.pop(0)
                
                if message.recipient == 'broadcast':
                    # Broadcast to all active agents
                    for agent_id, agent in self.agents.items():
                        if agent['status'] == 'active':
                            self._send_to_agent(agent_id, message)
                else:
                    # Send to specific agent
                    self._send_to_agent(message.recipient, message)
            
            time.sleep(0.1)
    
    def _send_to_agent(self, agent_id: str, message: AgentMessage):
        """Send message to specific agent"""
        # This would use WebSocket connections in real implementation
        # For now, just log the message
        self.logger.info(f"Sending message to {agent_id}: {message.content}")
    
    def get_system_metrics(self) -> Dict[str, Any]:
        """Get comprehensive system metrics"""
        return {
            'active_agents': len([a for a in self.agents.values() if a['status'] == 'active']),
            'total_agents': len(self.agents),
            'pending_tasks': len([t for t in self.tasks.values() if t.status == 'pending']),
            'completed_tasks': len([t for t in self.tasks.values() if t.status == 'completed']),
            'failed_tasks': len([t for t in self.tasks.values() if t.status == 'failed']),
            'message_queue_size': len(self.message_queue),
            'uptime': str(datetime.now() - datetime.now())  # Placeholder
        }
    
    async def start_server(self):
        """Start the WebSocket server for agent communication"""
        self.running = True
        
        # Start message processing thread
        message_thread = threading.Thread(target=self.process_message_queue, daemon=True)
        message_thread.start()
        
        # Start WebSocket server
        self.websocket_server = await websockets.serve(
            self.handle_websocket_connection,
            "localhost",
            self.port
        )
        
        self.logger.info(f"Agent orchestrator started on port {self.port}")
        
        # Keep server running
        await self.websocket_server.wait_closed()
    
    def stop_server(self):
        """Stop the orchestrator"""
        self.running = False
        if self.websocket_server:
            self.websocket_server.close()


# Specialized agent implementations
class CryptoTradingAgent:
    """Specialized cryptocurrency trading agent"""
    
    def __init__(self, orchestrator: AgentOrchestrator):
        self.orchestrator = orchestrator
        self.capabilities = ['crypto_analysis', 'arbitrage_detection', 'trade_execution']
        self.performance = {'trades': 0, 'profit': 0.0, 'accuracy': 0.0}
    
    async def start(self, endpoint: str = "ws://localhost:8765"):
        """Connect to orchestrator and start processing tasks"""
        async with websockets.connect(endpoint) as websocket:
            # Register with orchestrator
            await websocket.send(json.dumps({
                'type': 'register',
                'agent_id': 'crypto_trader',
                'capabilities': self.capabilities
            }))
            
            # Process tasks
            async for message in websocket:
                data = json.loads(message)
                if data['type'] == 'task':
                    result = await self.execute_task(data['data'])
                    await websocket.send(json.dumps({
                        'type': 'task_result',
                        'task_id': data['task_id'],
                        'result': result
                    }))
    
    async def execute_task(self, task_data: Dict[str, Any]) -> Dict[str, Any]:
        """Execute cryptocurrency trading task"""
        # Implement actual trading logic here
        return {
            'success': True,
            'earnings': 5.23,
            'currency': 'USD',
            'details': {'trade_type': 'arbitrage', 'pairs': ['BTC/USDT', 'ETH/USDT']}
        }


class DeFiYieldAgent:
    """DeFi yield farming agent"""
    
    def __init__(self, orchestrator: AgentOrchestrator):
        self.orchestrator = orchestrator
        self.capabilities = ['yield_farming', 'liquidity_provision', 'protocol_analysis']
        self.active_positions = []
    
    async def start(self, endpoint: str = "ws://localhost:8765"):
        """Connect to orchestrator and start processing tasks"""
        async with websockets.connect(endpoint) as websocket:
            await websocket.send(json.dumps({
                'type': 'register',
                'agent_id': 'defi_farmer',
                'capabilities': self.capabilities
            }))
            
            async for message in websocket:
                data = json.loads(message)
                if data['type'] == 'task':
                    result = await self.execute_task(data['data'])
                    await websocket.send(json.dumps({
                        'type': 'task_result',
                        'task_id': data['task_id'],
                        'result': result
                    }))
    
    async def execute_task(self, task_data: Dict[str, Any]) -> Dict[str, Any]:
        """Execute DeFi yield farming task"""
        # Implement actual DeFi operations
        return {
            'success': True,
            'earnings': 2.15,
            'currency': 'USD',
            'details': {'protocol': 'Aave', 'apy': 8.5}
        }


if __name__ == "__main__":
    # Start the orchestrator
    orchestrator = AgentOrchestrator()
    
    async def main():
        await orchestrator.start_server()
    
    asyncio.run(main())