|
| 1 | +""" |
| 2 | +MASTERMIND Cognitive Framework v3.1 |
| 3 | +Production-Grade Autonomous Agent Orchestration System |
| 4 | +""" |
| 5 | + |
| 6 | +import os |
| 7 | +import sys |
| 8 | +import asyncio |
| 9 | +import signal |
| 10 | +import json |
| 11 | +import logging |
| 12 | +import psutil |
| 13 | +import aiohttp |
| 14 | +from dataclasses import dataclass, field |
| 15 | +from typing import Dict, List, Set, Any, Optional, AsyncGenerator |
| 16 | +from contextlib import asynccontextmanager |
| 17 | + |
| 18 | +# Configure production logging |
| 19 | +logging.basicConfig( |
| 20 | + level=logging.INFO, |
| 21 | + format='%(asctime)s|%(name)s|%(levelname)s|%(message)s', |
| 22 | + handlers=[ |
| 23 | + logging.FileHandler('mastermind.log'), |
| 24 | + logging.StreamHandler() |
| 25 | + ] |
| 26 | +) |
| 27 | +logger = logging.getLogger('MASTERMIND') |
| 28 | + |
| 29 | +# -------------------------- |
| 30 | +# Core Cognitive Architecture |
| 31 | +# -------------------------- |
| 32 | + |
| 33 | +@dataclass |
| 34 | +class Belief: |
| 35 | + content: str |
| 36 | + certainty: float = 1.0 |
| 37 | + source: str = "perception" |
| 38 | + dependencies: Set[str] = field(default_factory=set) |
| 39 | + |
| 40 | +@dataclass |
| 41 | +class Desire: |
| 42 | + goal: str |
| 43 | + priority: int = 1 |
| 44 | + preconditions: Set[str] = field(default_factory=set) |
| 45 | + postconditions: Set[str] = field(default_factory=set) |
| 46 | + |
| 47 | +@dataclass |
| 48 | +class Intention: |
| 49 | + plan: List[str] |
| 50 | + current_step: int = 0 |
| 51 | + status: str = "pending" |
| 52 | + |
| 53 | +class GoalSystem: |
| 54 | + def __init__(self): |
| 55 | + self.active_goals: List[Desire] = [] |
| 56 | + self.completed_goals: List[Desire] = [] |
| 57 | + self.failed_goals: List[Desire] = [] |
| 58 | + |
| 59 | + async def add_goal(self, goal: Desire): |
| 60 | + """Thread-safe goal addition""" |
| 61 | + if not any(g.goal == goal.goal for g in self.active_goals): |
| 62 | + self.active_goals.append(goal) |
| 63 | + self.active_goals.sort(key=lambda x: x.priority, reverse=True) |
| 64 | + |
| 65 | +# -------------------------- |
| 66 | +# Asynchronous Agent Base |
| 67 | +# -------------------------- |
| 68 | + |
| 69 | +class AsyncCognitiveAgent: |
| 70 | + def __init__(self, name: str): |
| 71 | + self.name = name |
| 72 | + self._shutdown_event = asyncio.Event() |
| 73 | + self._task_queue = asyncio.Queue(maxsize=1000) |
| 74 | + self._current_tasks = set() |
| 75 | + self.beliefs: List[Belief] = [] |
| 76 | + self.desires: List[Desire] = [] |
| 77 | + self.intentions: List[Intention] = [] |
| 78 | + |
| 79 | + async def start(self): |
| 80 | + """Start agent's main loop""" |
| 81 | + logger.info(f"Agent {self.name} starting") |
| 82 | + asyncio.create_task(self._run_loop()) |
| 83 | + |
| 84 | + async def stop(self): |
| 85 | + """Graceful shutdown""" |
| 86 | + logger.info(f"Agent {self.name} stopping") |
| 87 | + self._shutdown_event.set() |
| 88 | + await self._task_queue.join() |
| 89 | + |
| 90 | + async def _run_loop(self): |
| 91 | + while not self._shutdown_event.is_set(): |
| 92 | + task = await self._task_queue.get() |
| 93 | + task_obj = asyncio.create_task(self._execute_task(task)) |
| 94 | + self._current_tasks.add(task_obj) |
| 95 | + task_obj.add_done_callback(lambda t: self._current_tasks.discard(t)) |
| 96 | + |
| 97 | + async def _execute_task(self, task: Any): |
| 98 | + """Template method for task execution""" |
| 99 | + try: |
| 100 | + await self.perceive(task) |
| 101 | + await self.deliberate() |
| 102 | + return await self.act() |
| 103 | + except Exception as e: |
| 104 | + logger.error(f"Task failed: {str(e)}") |
| 105 | + raise |
| 106 | + |
| 107 | + async def perceive(self, data: Any): |
| 108 | + """Override in subclasses""" |
| 109 | + raise NotImplementedError |
| 110 | + |
| 111 | + async def deliberate(self): |
| 112 | + """BDI decision cycle""" |
| 113 | + raise NotImplementedError |
| 114 | + |
| 115 | + async def act(self) -> Any: |
| 116 | + """Action implementation""" |
| 117 | + raise NotImplementedError |
| 118 | + |
| 119 | + async def get_metrics(self) -> Dict[str, Any]: |
| 120 | + """Agent performance metrics""" |
| 121 | + proc = psutil.Process() |
| 122 | + return { |
| 123 | + "cpu": proc.cpu_percent(), |
| 124 | + "memory": proc.memory_info().rss, |
| 125 | + "queue_size": self._task_queue.qsize(), |
| 126 | + "active_tasks": len(self._current_tasks) |
| 127 | + } |
| 128 | + |
| 129 | +# -------------------------- |
| 130 | +# Control Plane |
| 131 | +# -------------------------- |
| 132 | + |
| 133 | +class MastermindController: |
| 134 | + def __init__(self): |
| 135 | + self.agents: Dict[str, AsyncCognitiveAgent] = {} |
| 136 | + self._shutdown_event = asyncio.Event() |
| 137 | + self._monitor_task: Optional[asyncio.Task] = None |
| 138 | + |
| 139 | + def _setup_signals(self): |
| 140 | + loop = asyncio.get_running_loop() |
| 141 | + for sig in (signal.SIGTERM, signal.SIGINT): |
| 142 | + loop.add_signal_handler(sig, self.graceful_shutdown) |
| 143 | + |
| 144 | + async def add_agent(self, agent: AsyncCognitiveAgent): |
| 145 | + """Register and start agent""" |
| 146 | + self.agents[agent.name] = agent |
| 147 | + await agent.start() |
| 148 | + logger.info(f"Agent {agent.name} registered") |
| 149 | + |
| 150 | + async def monitor_system(self): |
| 151 | + """Resource monitoring coroutine""" |
| 152 | + while not self._shutdown_event.is_set(): |
| 153 | + try: |
| 154 | + metrics = {} |
| 155 | + for name, agent in self.agents.items(): |
| 156 | + metrics[name] = await agent.get_metrics() |
| 157 | + |
| 158 | + sys_metrics = { |
| 159 | + "cpu": psutil.cpu_percent(), |
| 160 | + "memory": psutil.virtual_memory().percent, |
| 161 | + "agents": len(self.agents) |
| 162 | + } |
| 163 | + |
| 164 | + logger.info("System Metrics: %s", json.dumps(sys_metrics)) |
| 165 | + logger.debug("Agent Metrics: %s", json.dumps(metrics)) |
| 166 | + |
| 167 | + await asyncio.sleep(5) |
| 168 | + except Exception as e: |
| 169 | + logger.error(f"Monitoring error: {str(e)}") |
| 170 | + |
| 171 | + @asynccontextmanager |
| 172 | + async def lifecycle(self) -> AsyncGenerator[None, None]: |
| 173 | + """Managed execution context""" |
| 174 | + self._setup_signals() |
| 175 | + self._monitor_task = asyncio.create_task(self.monitor_system()) |
| 176 | + try: |
| 177 | + yield |
| 178 | + finally: |
| 179 | + await self.graceful_shutdown() |
| 180 | + |
| 181 | + async def graceful_shutdown(self): |
| 182 | + """Orderly shutdown procedure""" |
| 183 | + logger.info("Initiating shutdown sequence") |
| 184 | + self._shutdown_event.set() |
| 185 | + |
| 186 | + if self._monitor_task: |
| 187 | + self._monitor_task.cancel() |
| 188 | + |
| 189 | + shutdown_tasks = [agent.stop() for agent in self.agents.values()] |
| 190 | + await asyncio.gather(*shutdown_tasks, return_exceptions=True) |
| 191 | + logger.info("Shutdown complete") |
| 192 | + |
| 193 | +# -------------------------- |
| 194 | +# Example Agent Implementation |
| 195 | +# -------------------------- |
| 196 | + |
| 197 | +class SimpleCoder(AsyncCognitiveAgent): |
| 198 | + def __init__(self): |
| 199 | + super().__init__("SimpleCoder") |
| 200 | + self.skills = { |
| 201 | + "python": self._handle_python, |
| 202 | + "javascript": self._handle_js |
| 203 | + } |
| 204 | + |
| 205 | + async def perceive(self, task: Dict): |
| 206 | + """Process incoming task""" |
| 207 | + logger.info(f"Received task: {task['id']}") |
| 208 | + |
| 209 | + async def deliberate(self): |
| 210 | + """Decision making""" |
| 211 | + if len(self.intentions) == 0: |
| 212 | + self.intentions.append(Intention( |
| 213 | + plan=["analyze", "generate", "test"] |
| 214 | + )) |
| 215 | + |
| 216 | + async def act(self) -> Dict: |
| 217 | + """Execute coding task""" |
| 218 | + current_step = self.intentions[0].current_step |
| 219 | + step_name = self.intentions[0].plan[current_step] |
| 220 | + |
| 221 | + async with aiohttp.ClientSession() as session: |
| 222 | + response = await session.post( |
| 223 | + "https://api.codegen.com/tasks", |
| 224 | + json={"step": step_name} |
| 225 | + ) |
| 226 | + result = await response.json() |
| 227 | + |
| 228 | + self.intentions[0].current_step += 1 |
| 229 | + return result |
| 230 | + |
| 231 | + async def _handle_python(self, task: Dict): |
| 232 | + """Python-specific handling""" |
| 233 | + pass |
| 234 | + |
| 235 | + async def _handle_js(self, task: Dict): |
| 236 | + """JavaScript handling""" |
| 237 | + pass |
| 238 | + |
| 239 | +# -------------------------- |
| 240 | +# Main Execution |
| 241 | +# -------------------------- |
| 242 | + |
| 243 | +async def main(): |
| 244 | + controller = MastermindController() |
| 245 | + |
| 246 | + async with controller.lifecycle(): |
| 247 | + # Register agents |
| 248 | + coder = SimpleCoder() |
| 249 | + await controller.add_agent(coder) |
| 250 | + |
| 251 | + # Keep alive |
| 252 | + while True: |
| 253 | + await asyncio.sleep(3600) |
| 254 | + |
| 255 | +if __name__ == "__main__": |
| 256 | + try: |
| 257 | + asyncio.run(main()) |
| 258 | + except KeyboardInterrupt: |
| 259 | + logger.info("System terminated by user") |
| 260 | + except Exception as e: |
| 261 | + logger.critical(f"Fatal error: {str(e)}") |
| 262 | + sys.exit(1) |
0 commit comments