|
| 1 | +# Copyright (c) Microsoft. All rights reserved. |
| 2 | +"""Global agent registry for tracking and managing agent lifecycles across the application.""" |
| 3 | + |
| 4 | +import asyncio |
| 5 | +import logging |
| 6 | +import threading |
| 7 | +from typing import List, Dict, Any, Optional |
| 8 | +from weakref import WeakSet |
| 9 | + |
| 10 | + |
| 11 | +class AgentRegistry: |
| 12 | + """Global registry for tracking and managing all agent instances across the application.""" |
| 13 | + |
| 14 | + def __init__(self): |
| 15 | + self.logger = logging.getLogger(__name__) |
| 16 | + self._lock = threading.Lock() |
| 17 | + self._all_agents: WeakSet = WeakSet() |
| 18 | + self._agent_metadata: Dict[int, Dict[str, Any]] = {} |
| 19 | + |
| 20 | + def register_agent(self, agent: Any, user_id: Optional[str] = None) -> None: |
| 21 | + """Register an agent instance for tracking and lifecycle management.""" |
| 22 | + with self._lock: |
| 23 | + try: |
| 24 | + self._all_agents.add(agent) |
| 25 | + agent_id = id(agent) |
| 26 | + self._agent_metadata[agent_id] = { |
| 27 | + 'type': type(agent).__name__, |
| 28 | + 'user_id': user_id, |
| 29 | + 'name': getattr(agent, 'agent_name', getattr(agent, 'name', 'Unknown')) |
| 30 | + } |
| 31 | + self.logger.info(f"Registered agent: {type(agent).__name__} (ID: {agent_id}, User: {user_id})") |
| 32 | + except Exception as e: |
| 33 | + self.logger.error(f"Failed to register agent: {e}") |
| 34 | + |
| 35 | + def unregister_agent(self, agent: Any) -> None: |
| 36 | + """Unregister an agent instance.""" |
| 37 | + with self._lock: |
| 38 | + try: |
| 39 | + agent_id = id(agent) |
| 40 | + self._all_agents.discard(agent) |
| 41 | + if agent_id in self._agent_metadata: |
| 42 | + metadata = self._agent_metadata.pop(agent_id) |
| 43 | + self.logger.info(f"Unregistered agent: {metadata.get('type', 'Unknown')} (ID: {agent_id})") |
| 44 | + except Exception as e: |
| 45 | + self.logger.error(f"Failed to unregister agent: {e}") |
| 46 | + |
| 47 | + def get_all_agents(self) -> List[Any]: |
| 48 | + """Get all currently registered agents.""" |
| 49 | + with self._lock: |
| 50 | + return list(self._all_agents) |
| 51 | + |
| 52 | + def get_agent_count(self) -> int: |
| 53 | + """Get the total number of registered agents.""" |
| 54 | + with self._lock: |
| 55 | + return len(self._all_agents) |
| 56 | + |
| 57 | + async def cleanup_all_agents(self) -> None: |
| 58 | + """Clean up all registered agents across all users.""" |
| 59 | + all_agents = self.get_all_agents() |
| 60 | + |
| 61 | + if not all_agents: |
| 62 | + self.logger.info("No agents to clean up") |
| 63 | + return |
| 64 | + |
| 65 | + self.logger.info(f"🧹 Starting cleanup of {len(all_agents)} total agents") |
| 66 | + |
| 67 | + # Log agent details for debugging |
| 68 | + for i, agent in enumerate(all_agents): |
| 69 | + agent_name = getattr(agent, 'agent_name', getattr(agent, 'name', type(agent).__name__)) |
| 70 | + agent_type = type(agent).__name__ |
| 71 | + has_close = hasattr(agent, 'close') |
| 72 | + self.logger.info(f"Agent {i + 1}: {agent_name} (Type: {agent_type}, Has close(): {has_close})") |
| 73 | + |
| 74 | + # Clean up agents concurrently |
| 75 | + cleanup_tasks = [] |
| 76 | + for agent in all_agents: |
| 77 | + if hasattr(agent, 'close'): |
| 78 | + cleanup_tasks.append(self._safe_close_agent(agent)) |
| 79 | + else: |
| 80 | + agent_name = getattr(agent, 'agent_name', getattr(agent, 'name', type(agent).__name__)) |
| 81 | + self.logger.warning(f"⚠️ Agent {agent_name} has no close() method - just unregistering from registry") |
| 82 | + self.unregister_agent(agent) |
| 83 | + |
| 84 | + if cleanup_tasks: |
| 85 | + self.logger.info(f"🔄 Executing {len(cleanup_tasks)} cleanup tasks...") |
| 86 | + results = await asyncio.gather(*cleanup_tasks, return_exceptions=True) |
| 87 | + |
| 88 | + # Log any exceptions that occurred during cleanup |
| 89 | + success_count = 0 |
| 90 | + for i, result in enumerate(results): |
| 91 | + if isinstance(result, Exception): |
| 92 | + self.logger.error(f"❌ Error cleaning up agent {i}: {result}") |
| 93 | + else: |
| 94 | + success_count += 1 |
| 95 | + |
| 96 | + self.logger.info(f"✅ Successfully cleaned up {success_count}/{len(cleanup_tasks)} agents") |
| 97 | + |
| 98 | + # Clear all tracking |
| 99 | + with self._lock: |
| 100 | + self._all_agents.clear() |
| 101 | + self._agent_metadata.clear() |
| 102 | + |
| 103 | + self.logger.info("🎉 Completed cleanup of all agents") |
| 104 | + |
| 105 | + async def _safe_close_agent(self, agent: Any) -> None: |
| 106 | + """Safely close an agent with error handling.""" |
| 107 | + try: |
| 108 | + agent_name = getattr(agent, 'agent_name', getattr(agent, 'name', type(agent).__name__)) |
| 109 | + self.logger.info(f"Closing agent: {agent_name}") |
| 110 | + |
| 111 | + # Call the agent's close method - it should handle Azure deletion and registry cleanup |
| 112 | + if asyncio.iscoroutinefunction(agent.close): |
| 113 | + await agent.close() |
| 114 | + else: |
| 115 | + agent.close() |
| 116 | + |
| 117 | + self.logger.info(f"Successfully closed agent: {agent_name}") |
| 118 | + |
| 119 | + except Exception as e: |
| 120 | + agent_name = getattr(agent, 'agent_name', getattr(agent, 'name', type(agent).__name__)) |
| 121 | + self.logger.error(f"Failed to close agent {agent_name}: {e}") |
| 122 | + |
| 123 | + def get_registry_status(self) -> Dict[str, Any]: |
| 124 | + """Get current status of the agent registry for debugging and monitoring.""" |
| 125 | + with self._lock: |
| 126 | + status = { |
| 127 | + 'total_agents': len(self._all_agents), |
| 128 | + 'agent_types': {} |
| 129 | + } |
| 130 | + |
| 131 | + # Count agents by type |
| 132 | + for agent in self._all_agents: |
| 133 | + agent_type = type(agent).__name__ |
| 134 | + status['agent_types'][agent_type] = status['agent_types'].get(agent_type, 0) + 1 |
| 135 | + |
| 136 | + return status |
| 137 | + |
| 138 | + |
| 139 | +# Global registry instance |
| 140 | +agent_registry = AgentRegistry() |
0 commit comments