entry.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. """CLI entry point for the hermes-agent ACP adapter.
  2. Loads ``~/.hermes/.env``, routes logging to stderr (stdout is reserved for ACP
  3. JSON-RPC), and starts the ACP agent server.
  4. Usage::
  5. python -m acp_adapter.entry # or: hermes acp / hermes-acp
  6. """
  7. # IMPORTANT: hermes_bootstrap must be the very first import — UTF-8 stdio
  8. # on Windows. No-op on POSIX. See hermes_bootstrap.py for full rationale.
  9. try:
  10. import hermes_bootstrap
  11. except ModuleNotFoundError as exc:
  12. # Partial ``hermes update`` (git-reset landed, ``uv pip install -e .`` did not).
  13. if exc.name != "hermes_bootstrap":
  14. raise # the bootstrap exists but cannot load: skipping it would skip PM activation
  15. else:
  16. # Stop a ``utils/``/``proxy/``/``ui/`` package in the launch cwd from shadowing Hermes modules.
  17. hermes_bootstrap.harden_import_path()
  18. # `hermes-acp` runs without hermes_cli.main: repair a `hermes update` killed mid-pull here, before
  19. # importing anything else from the checkout (a no-op under `hermes acp`, which already did).
  20. from hermes_cli import _early_recovery
  21. if _early_recovery.restore_interrupted_pull():
  22. _early_recovery.relaunch_after_restore()
  23. import argparse
  24. import asyncio
  25. import logging
  26. import os
  27. import sys
  28. from pathlib import Path
  29. from hermes_constants import get_hermes_home
  30. # Liveness-probe methods outside the ACP schema. The router correctly answers JSON-RPC -32601
  31. # (clients treat that as "agent alive"), but the dispatching supervisor task also logs
  32. # ``"Background task failed"`` with a traceback every probe. Keep the response; silence the noise.
  33. _BENIGN_PROBE_METHODS = frozenset({"ping", "health", "healthcheck"})
  34. class _BenignProbeMethodFilter(logging.Filter):
  35. """Suppress acp 'Background task failed' tracebacks caused by unknown liveness-probe methods
  36. (e.g. ``ping``); every other background-task error, incl. method_not_found for non-probe
  37. methods, stays visible."""
  38. def filter(self, record: logging.LogRecord) -> bool:
  39. if record.getMessage() != "Background task failed" or not record.exc_info:
  40. return True
  41. # Lazy import keeps this module importable without ``agent-client-protocol``.
  42. try:
  43. from acp.exceptions import RequestError
  44. except ImportError:
  45. return True
  46. exc = record.exc_info[1]
  47. if not isinstance(exc, RequestError) or getattr(exc, "code", None) != -32601:
  48. return True
  49. data = getattr(exc, "data", None)
  50. return not (isinstance(data, dict) and data.get("method") in _BENIGN_PROBE_METHODS)
  51. def _setup_logging() -> None:
  52. """Route all logging to stderr so stdout stays clean for ACP stdio."""
  53. from agent.redact import RedactingFormatter
  54. handler = logging.StreamHandler(sys.stderr)
  55. handler.setFormatter(RedactingFormatter("%(asctime)s [%(levelname)s] %(name)s: %(message)s",
  56. datefmt="%Y-%m-%d %H:%M:%S"))
  57. handler.addFilter(_BenignProbeMethodFilter())
  58. root = logging.getLogger()
  59. root.handlers.clear()
  60. root.addHandler(handler)
  61. root.setLevel(logging.INFO)
  62. for noisy in ("httpx", "httpcore", "openai"):
  63. logging.getLogger(noisy).setLevel(logging.WARNING)
  64. def _load_env() -> None:
  65. """Load .env from HERMES_HOME (default ``~/.hermes``)."""
  66. from hermes_cli.env_loader import load_hermes_dotenv
  67. hermes_home = get_hermes_home()
  68. loaded = load_hermes_dotenv(hermes_home=hermes_home)
  69. log = logging.getLogger(__name__)
  70. for env_file in loaded or ():
  71. log.info("Loaded env from %s", env_file)
  72. if not loaded:
  73. log.info("No .env found at %s, using system env", hermes_home / ".env")
  74. def _parse_args(argv: list[str] | None = None) -> argparse.Namespace:
  75. parser = argparse.ArgumentParser(prog="hermes-acp", description="Run Hermes Agent as an ACP stdio server.")
  76. parser.add_argument("--version", action="store_true", help="Print Hermes version and exit")
  77. parser.add_argument("--check", action="store_true", help="Verify ACP dependencies and adapter imports, then exit")
  78. parser.add_argument("--setup", action="store_true",
  79. help="Run interactive Hermes provider/model setup for ACP terminal auth")
  80. parser.add_argument("--setup-browser", action="store_true",
  81. help="Prepare PM's pinned Chromium for browser_exec.")
  82. parser.add_argument("--yes", "-y", action="store_true", dest="assume_yes",
  83. help="Accept setup prompts.")
  84. return parser.parse_args(argv)
  85. def _print_version() -> None:
  86. from hermes_cli.version_info import get_version_info
  87. print(get_version_info().derived_version)
  88. def _run_check() -> None:
  89. import acp
  90. from acp_adapter.server import HermesACPAgent
  91. print("Hermes ACP check OK")
  92. def _run_setup() -> None:
  93. from hermes_cli.main import main as hermes_main
  94. old_argv = sys.argv[:]
  95. try:
  96. sys.argv = [old_argv[0] if old_argv else "hermes", "model"]
  97. hermes_main()
  98. finally:
  99. sys.argv = old_argv
  100. # Terminal auth is the first-run UX for registry installs, so offer the browser-tools
  101. # install here. Skip silently without a TTY.
  102. if not sys.stdin.isatty():
  103. return
  104. try:
  105. reply = input("\nInstall browser tools? Downloads the pinned "
  106. "Chromium through PM. [y/N] ").strip().lower()
  107. except (EOFError, KeyboardInterrupt):
  108. return
  109. if reply in {"y", "yes"}:
  110. _run_setup_browser(assume_yes=False)
  111. def _run_setup_browser(assume_yes: bool = False) -> int:
  112. """The setup command is an explicit request for PM's Chromium (browser_exec's local browser)."""
  113. import pm
  114. try:
  115. pm.ensure("chromium", explicit=True)
  116. except (pm.InstallError, OSError) as exc:
  117. print(f"Browser setup failed: {exc}", file=sys.stderr)
  118. return 1
  119. return 0
  120. def _warm_memory_provider_import(logger: logging.Logger) -> None:
  121. """Import ``memory.provider``'s module + numpy (no provider instance) before the ACP threads start."""
  122. from plugins.memory import import_memory_provider_module
  123. if not import_memory_provider_module():
  124. logger.debug("memory provider not warmed (none configured or import failed; agent init reports that)")
  125. def main(argv: list[str] | None = None) -> None:
  126. """Entry point: load env, configure logging, run the ACP agent."""
  127. args = _parse_args(argv)
  128. for flag, action in (("version", _print_version), ("check", _run_check), ("setup", _run_setup)):
  129. if getattr(args, flag):
  130. return action()
  131. if args.setup_browser:
  132. if rc := _run_setup_browser(assume_yes=args.assume_yes):
  133. sys.exit(rc)
  134. return
  135. _setup_logging()
  136. _load_env()
  137. logger = logging.getLogger(__name__)
  138. logger.info("Starting hermes-agent ACP adapter")
  139. # Ensure the project root is on sys.path so ``from run_agent import AIAgent`` works
  140. project_root = str(Path(__file__).resolve().parent.parent)
  141. if project_root not in sys.path:
  142. sys.path.insert(0, project_root)
  143. # One TLS authority: trust the OS store before any outbound call (bare
  144. # requests/urllib included) resolves a CA bundle — see agent/ssl_verify.py.
  145. # This console script bypasses hermes_cli.main, which does the same.
  146. from agent.ssl_verify import install_truststore
  147. install_truststore()
  148. import acp
  149. from .server import HermesACPAgent
  150. # Windows: import the configured memory provider (and numpy) on the main thread before
  151. # the ACP stdin-reader thread starts. A first-time native-extension import racing another
  152. # thread's import chain deadlocked in create_module and session/new never answered (#58083).
  153. if sys.platform == "win32":
  154. _warm_memory_provider_import(logger)
  155. # MCP discovery and execution belong to the gateway daemon; this process is a viewer.
  156. agent = HermesACPAgent()
  157. async def serve():
  158. # MCP and execution belong to the daemon. Close only this viewer, while
  159. # its event loop is still alive, including on protocol/transport errors.
  160. try:
  161. await acp.run_agent(agent, use_unstable_protocol=True)
  162. finally:
  163. await agent.aclose()
  164. try:
  165. asyncio.run(serve())
  166. except KeyboardInterrupt:
  167. logger.info("Shutting down (KeyboardInterrupt)")
  168. except Exception:
  169. logger.exception("ACP agent crashed")
  170. sys.exit(1)
  171. # No ended_at stamp here: sessions are daemon-owned and may have other viewers or queued work.
  172. # The owner ends an ACP session when its last viewer detaches with an idle FIFO, and at gateway
  173. # stop (gateway/session_acp_lifecycle.py, #118216).
  174. if __name__ == "__main__":
  175. main()