cli.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. """``hermes lsp`` CLI subcommand: status / list / install / install-all / restart / which.
  2. Handlers live here (not in ``hermes_cli/main.py``) so the LSP module ships self-contained.
  3. """
  4. from __future__ import annotations
  5. import argparse
  6. import sys
  7. _STATUS_MARKERS = {"installed": "✓", "missing": "·", "manual-only": "?"}
  8. # (name, help, optional (flag, add_argument kwargs), handler(args)) — order defines the help listing.
  9. _SUBCOMMANDS = [
  10. ("status", "Show LSP service status",
  11. ("--json", {"action": "store_true", "help": "Emit machine-readable JSON"}),
  12. lambda a: _cmd_status(getattr(a, "json", False))),
  13. ("list", "List supported language servers",
  14. ("--installed-only", {"action": "store_true", "help": "Only show servers whose binary is currently available"}),
  15. lambda a: _cmd_list(getattr(a, "installed_only", False))),
  16. ("install", "Install a server binary", ("server", {"help": "Server id (e.g. pyright, gopls)"}),
  17. lambda a: _cmd_install(a.server)),
  18. ("install-all", "Install every server with a known auto-install recipe",
  19. ("--include-manual", {"action": "store_true", "help": "Even attempt servers marked manual-install (best effort)"}),
  20. lambda a: _cmd_install_all(getattr(a, "include_manual", False))),
  21. ("restart", "Tear down running LSP clients (next edit re-spawns)", None, lambda a: _cmd_restart()),
  22. ("which", "Print binary path for a server", ("server", {"help": "Server id"}), lambda a: _cmd_which(a.server)),
  23. ]
  24. _COMMANDS = {name: handler for name, _, _, handler in _SUBCOMMANDS}
  25. def register_subparser(subparsers: argparse._SubParsersAction) -> None:
  26. """Wire the ``hermes lsp`` subcommand tree into the main argparse."""
  27. parser = subparsers.add_parser(
  28. "lsp",
  29. help="Language Server Protocol management",
  30. description="Manage the LSP layer that powers post-write semantic diagnostics in write_file/patch.",
  31. )
  32. sub = parser.add_subparsers(dest="lsp_command")
  33. for name, help_text, arg, _handler in _SUBCOMMANDS:
  34. p = sub.add_parser(name, help=help_text)
  35. if arg is not None:
  36. p.add_argument(arg[0], **arg[1])
  37. parser.set_defaults(func=run_lsp_command)
  38. def run_lsp_command(args: argparse.Namespace) -> int:
  39. """Top-level dispatcher for ``hermes lsp <subcommand>``."""
  40. sub = getattr(args, "lsp_command", None) or "status"
  41. try:
  42. handler = _COMMANDS.get(sub)
  43. if handler is None:
  44. sys.stderr.write(f"unknown lsp subcommand: {sub}\n")
  45. return 2
  46. return handler(args)
  47. except KeyboardInterrupt:
  48. return 130
  49. def _all_servers() -> list:
  50. """Config-declared servers (``lsp.servers.<id>.extensions``) ahead of the built-in registry."""
  51. from agent.lsp.servers import SERVERS, custom_servers
  52. from hermes_cli.config import load_config_readonly
  53. try:
  54. lsp_cfg = load_config_readonly().get("lsp") or {}
  55. except Exception:
  56. lsp_cfg = {}
  57. return [*custom_servers(lsp_cfg.get("servers") if isinstance(lsp_cfg, dict) else None), *SERVERS]
  58. def _status_for(server_id: str) -> str:
  59. import os
  60. from agent.lsp.install import detect_status
  61. from agent.lsp.servers import SERVERS, ServerContext
  62. custom = next((s for s in _all_servers() if s.server_id == server_id and s not in SERVERS), None)
  63. if custom is not None: # no install recipe: installed iff the configured command resolves
  64. cwd = os.getcwd()
  65. return "installed" if custom.build_spawn(cwd, ServerContext(cwd, install_strategy="manual")) else "manual-only"
  66. return detect_status(_recipe_pkg_for(server_id))
  67. def _cmd_status(emit_json: bool) -> int:
  68. from agent.lsp import get_service
  69. from agent.lsp.servers import UNTRUSTED_SAFE_SERVERS
  70. servers = _all_servers()
  71. svc = get_service()
  72. info = svc.get_status() if svc is not None else {"enabled": False}
  73. if emit_json:
  74. import json
  75. registry = [{"server_id": s.server_id, "extensions": list(s.extensions), "description": s.description,
  76. "binary_status": _status_for(s.server_id)} for s in servers]
  77. sys.stdout.write(json.dumps({"service": info, "registry": registry}, indent=2) + "\n")
  78. return 0
  79. out = ["LSP Service", "===========", f" enabled: {info.get('enabled', False)}"]
  80. if svc is not None:
  81. out += [f" wait_mode: {info.get('wait_mode')}",
  82. f" wait_timeout: {info.get('wait_timeout')}s",
  83. f" install_strategy:{info.get('install_strategy')}"]
  84. clients = info.get("clients") or []
  85. out.append(f" active clients: {len(clients)}" if clients else " active clients: none")
  86. out += [f" - {c['server_id']:20s} state={c['state']:10s} root={c['workspace_root']}" for c in clients]
  87. broken = info.get("broken") or []
  88. if broken:
  89. out.append(f" broken pairs: {len(broken)}")
  90. out += [f" - {b}" for b in broken]
  91. if disabled := info.get("disabled_servers"):
  92. out.append(f" disabled in cfg: {', '.join(disabled)}")
  93. if untrusted := info.get("untrusted_skipped"):
  94. out.append(f" untrusted skips: {len(untrusted)} (add the workspace to lsp.trusted_workspaces)")
  95. out += [f" - {sid:20s} root={root}" for sid, root in untrusted]
  96. # Sidecar gaps the registry table can't show (bash-language-server -> shellcheck).
  97. if backend_warnings := _backend_warnings():
  98. out += ["", "Backend warnings", "================"] + [f" ! {line}" for line in backend_warnings]
  99. out += ["", "Registered Servers", "=================="]
  100. for s in servers:
  101. status = _status_for(s.server_id)
  102. ext_summary = ", ".join(list(s.extensions)[:5])
  103. if len(s.extensions) > 5:
  104. ext_summary += f", … (+{len(s.extensions) - 5})"
  105. out.append(f" {_STATUS_MARKERS.get(status, ' ')} {s.server_id:24s} [{status:11s}] {ext_summary}")
  106. if s.description:
  107. gate = "" if s.server_id in UNTRUSTED_SAFE_SERVERS else " [trusted workspaces only]"
  108. out.append(f" {s.description}{gate}")
  109. sys.stdout.write("\n".join(out) + "\n")
  110. return 0
  111. def _cmd_list(installed_only: bool) -> int:
  112. for s in _all_servers():
  113. status = _status_for(s.server_id)
  114. if not (installed_only and status != "installed"):
  115. sys.stdout.write(f"{s.server_id:24s} [{status:11s}] {','.join(s.extensions)}\n")
  116. return 0
  117. def _cmd_install(server_id: str) -> int:
  118. from agent.lsp.install import try_install, INSTALL_RECIPES
  119. pkg = _recipe_pkg_for(server_id)
  120. if _status_for(server_id) == "installed":
  121. sys.stdout.write(f"{server_id} already installed\n")
  122. return 0
  123. sys.stdout.write(f"installing {server_id} (pkg={pkg}) ...\n")
  124. sys.stdout.flush()
  125. bin_path = try_install(pkg, "auto")
  126. if bin_path is not None:
  127. sys.stdout.write(f"installed: {bin_path}\n")
  128. return 0
  129. manual = (INSTALL_RECIPES.get(pkg) or {}).get("strategy") == "manual"
  130. sys.stderr.write(f"{server_id}: this server requires a manual install. See documentation.\n" if manual
  131. else f"{server_id}: install failed (see logs).\n")
  132. return 1
  133. def _cmd_install_all(include_manual: bool) -> int:
  134. from agent.lsp.servers import SERVERS
  135. from agent.lsp.install import try_install, INSTALL_RECIPES
  136. rc = 0
  137. for s in SERVERS:
  138. pkg = _recipe_pkg_for(s.server_id)
  139. recipe = INSTALL_RECIPES.get(pkg)
  140. if recipe is None or (recipe.get("strategy") == "manual" and not include_manual):
  141. continue
  142. if _status_for(s.server_id) == "installed":
  143. sys.stdout.write(f" {s.server_id:24s} already installed\n")
  144. continue
  145. sys.stdout.write(f" installing {s.server_id} (pkg={pkg}) ... ")
  146. sys.stdout.flush()
  147. path = try_install(pkg, "auto")
  148. sys.stdout.write(f"ok ({path})\n" if path else "FAILED\n")
  149. rc = rc if path else 1
  150. return rc
  151. def _cmd_restart() -> int:
  152. from agent.lsp import shutdown_service
  153. shutdown_service()
  154. sys.stdout.write("LSP service shut down. Next edit will respawn clients.\n")
  155. return 0
  156. def _cmd_which(server_id: str) -> int:
  157. from agent.lsp.install import INSTALL_RECIPES, _existing_binary
  158. resolved = _existing_binary((INSTALL_RECIPES.get(server_id) or {}).get("bin", server_id))
  159. if resolved:
  160. sys.stdout.write(resolved + "\n")
  161. return 0
  162. sys.stderr.write(f"{server_id}: not installed\n")
  163. return 1
  164. # server_id → install-recipe key, where the two differ.
  165. _RECIPE_ALIASES = {
  166. "vue-language-server": "@vue/language-server",
  167. "astro-language-server": "@astrojs/language-server",
  168. "dockerfile-ls": "dockerfile-language-server-nodejs",
  169. "typescript": "typescript-language-server",
  170. }
  171. def _recipe_pkg_for(server_id: str) -> str:
  172. """Map a registry ``server_id`` to its install-recipe package key."""
  173. return _RECIPE_ALIASES.get(server_id, server_id)
  174. def _backend_warnings() -> list:
  175. """Notes about missing sidecar tools that make a server spawn fine but emit nothing (e.g. shellcheck)."""
  176. import shutil
  177. from agent.lsp.install import _existing_binary
  178. if _existing_binary("bash-language-server") is not None and shutil.which("shellcheck") is None:
  179. return ["bash-language-server is installed but shellcheck is missing — "
  180. "diagnostics will be empty (apt: shellcheck, brew: shellcheck, scoop: shellcheck)."]
  181. return []