__init__.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. """Language Server Protocol (LSP) integration for Hermes Agent.
  2. Real language servers (pyright, gopls, ...) run as subprocesses and their
  3. ``publishDiagnostics`` feed the post-write lint delta filter of ``write_file`` /
  4. ``patch`` (wiring: ``FileOperations._check_lint_delta``). LSP is **gated on git
  5. workspace detection** so user-home cwd's (e.g. Telegram gateway chats) never
  6. spawn daemons; ``get_service()`` returns the singleton or ``None`` when disabled.
  7. """
  8. from __future__ import annotations
  9. import atexit
  10. import logging
  11. import threading
  12. from typing import Optional
  13. from agent.lsp.manager import LSPService
  14. logger = logging.getLogger("agent.lsp")
  15. _service: Optional[LSPService] = None
  16. # Routed multiplex profiles (HERMES_HOME override) each get their own service: ``lsp.*`` config
  17. # (enabled, servers, idle timeout) is per profile, so one process-wide singleton would let the first
  18. # profile's settings decide whether every other profile gets diagnostics.
  19. _services_by_home: dict = {}
  20. _atexit_registered = False
  21. _service_lock = threading.Lock()
  22. def _active(svc: Optional[LSPService]) -> Optional[LSPService]:
  23. return svc if (svc is not None and svc.is_active()) else None
  24. def _register_atexit_once() -> None:
  25. global _atexit_registered
  26. if not _atexit_registered:
  27. atexit.register(_atexit_shutdown)
  28. _atexit_registered = True
  29. def get_service() -> Optional[LSPService]:
  30. """Return the lazily created LSP service for the active profile (process-wide singleton when no
  31. profile override is bound), or None when disabled.
  32. Also registers an :mod:`atexit` hook so a clean exit tears down spawned servers through
  33. the LSP ``shutdown``/``exit`` handshake: without it every ``hermes chat`` exit leaks
  34. pyright processes for a few seconds while their stdout buffers drain. SIGKILL/os._exit
  35. skip atexit; the owner-death supervisor (``LSPClient._spawn`` hands it each server's
  36. process group) kills whatever is left then.
  37. """
  38. global _service
  39. from hermes_constants import get_hermes_home_override, hermes_home_key
  40. if get_hermes_home_override() is not None:
  41. home_key = hermes_home_key()
  42. with _service_lock:
  43. if home_key not in _services_by_home:
  44. _services_by_home[home_key] = LSPService.create_from_config()
  45. _register_atexit_once()
  46. return _active(_services_by_home[home_key])
  47. if _service is None:
  48. with _service_lock:
  49. if _service is None:
  50. _service = LSPService.create_from_config()
  51. _register_atexit_once()
  52. return _active(_service)
  53. def release_workspace(path: str) -> int:
  54. """Shut down the LSP clients serving ``path`` (a worktree about to be removed) in every started
  55. service, without shutting down unrelated workspaces. Never creates a service. Returns the count."""
  56. with _service_lock:
  57. services = [svc for svc in (_service, *_services_by_home.values()) if svc is not None]
  58. released = 0
  59. for svc in services:
  60. try:
  61. released += svc.release_workspace(path)
  62. except Exception as e:
  63. logger.debug("LSP workspace release failed for %s: %s", path, e)
  64. return released
  65. def shutdown_service() -> None:
  66. """Tear down every LSP service that was started. Idempotent."""
  67. global _service
  68. with _service_lock:
  69. services = [_service, *_services_by_home.values()]
  70. _service = None
  71. _services_by_home.clear()
  72. for svc in services:
  73. if svc is not None:
  74. try:
  75. svc.shutdown()
  76. except Exception as e:
  77. logger.debug("LSP shutdown error: %s", e)
  78. def _atexit_shutdown() -> None:
  79. """atexit wrapper; logs at debug since the user has already seen the final output."""
  80. try:
  81. shutdown_service()
  82. except Exception as e:
  83. logger.debug("atexit LSP shutdown failed: %s", e)
  84. __all__ = ["LSPService", "get_service", "release_workspace", "shutdown_service"]