manager.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import asyncio, atexit
  2. from opendevin.core.logger import opendevin_logger as logger
  3. from opendevin.server.session import session_manager
  4. from .agent import AgentUnit
  5. class AgentManager:
  6. sid_to_agent: dict[str, 'AgentUnit'] = {}
  7. def __init__(self):
  8. atexit.register(self.close)
  9. def register_agent(self, sid: str):
  10. """Registers a new agent.
  11. Args:
  12. sid: The session ID of the agent.
  13. """
  14. if sid not in self.sid_to_agent:
  15. self.sid_to_agent[sid] = AgentUnit(sid)
  16. return
  17. # TODO: confirm whether the agent is alive
  18. async def dispatch(self, sid: str, action: str | None, data: dict):
  19. """Dispatches actions to the agent from the client."""
  20. if sid not in self.sid_to_agent:
  21. # self.register_agent(sid) # auto-register agent, may be opened later
  22. logger.error(f'Agent not registered: {sid}')
  23. await session_manager.send_error(sid, 'Agent not registered')
  24. return
  25. await self.sid_to_agent[sid].dispatch(action, data)
  26. def close(self):
  27. try:
  28. loop = asyncio.get_event_loop()
  29. except RuntimeError:
  30. loop = asyncio.new_event_loop()
  31. asyncio.set_event_loop(loop)
  32. loop.run_until_complete(self._close())
  33. async def _close(self):
  34. logger.info(f'Closing {len(self.sid_to_agent)} agent(s)...')
  35. for sid, agent in self.sid_to_agent.items():
  36. await agent.close()