Skip to content

The agent that grows with you

refactor(agent/lsp): compact client/manager/servers/install/cli; dict-dispatch installers; shared warn-once + await-push helpers

Teknium09b84b96b203
diff --git a/agent/lsp/__init__.py b/agent/lsp/__init__.py
index 21d072b8ecc..33cf08d5c52 100644
--- a/agent/lsp/__init__.py
+++ b/agent/lsp/__init__.py
@@ -2,16 +2,12 @@
Hermes runs real language servers (pyright, gopls, rust-analyzer, ...) as
subprocesses and pipes their ``textDocument/publishDiagnostics`` output into
-the post-write lint delta filter used by ``write_file`` and ``patch``.
-
-LSP is **gated on git workspace detection**: outside a git repository the
+the post-write lint delta filter used by ``write_file`` and ``patch``. LSP is
+**gated on git workspace detection**: outside a git repository the
file_operations layer falls back to its in-process syntax checks, so users
on user-home cwd's (e.g. Telegram gateway chats) never spawn daemons.
-
-Public API: ``get_service()`` returns the singleton :class:`LSPService` (or
-``None`` when disabled); the wiring lives in
-:func:`tools.file_operations.FileOperations._check_lint_delta`. Architecture
-docs: ``website/docs/user-guide/features/lsp.md``.
+``get_service()`` returns the singleton :class:`LSPService` (or ``None`` when
+disabled); wiring: :func:`tools.file_operations.FileOperations._check_lint_delta`.
"""
from __future__ import annotations
@@ -43,15 +39,13 @@ def get_service() -> Optional[LSPService]:
kernel reaps the stateless servers with their parent.)
"""
global _service, _atexit_registered
- if _service is not None:
- return _active(_service)
- with _service_lock:
- if _service is not None:
- return _active(_service)
- _service = LSPService.create_from_config()
- if not _atexit_registered:
- atexit.register(_atexit_shutdown)
- _atexit_registered = True
+ if _service is None:
+ with _service_lock:
+ if _service is None:
+ _service = LSPService.create_from_config()
+ if not _atexit_registered:
+ atexit.register(_atexit_shutdown)
+ _atexit_registered = True
return _active(_service)
@@ -59,8 +53,7 @@ def shutdown_service() -> None:
"""Tear down the LSP service if one was started. Idempotent."""
global _service
with _service_lock:
- svc = _service
- _service = None
+ svc, _service = _service, None
if svc is not None:
try:
svc.shutdown()
diff --git a/agent/lsp/cli.py b/agent/lsp/cli.py
index 70e9b13a15f..f2faa43e4bd 100644
--- a/agent/lsp/cli.py
+++ b/agent/lsp/cli.py
@@ -7,6 +7,8 @@ from __future__ import annotations
import argparse
import sys
+_STATUS_MARKERS = {"installed": "✓", "missing": "·", "manual-only": "?"}
+
def register_subparser(subparsers: argparse._SubParsersAction) -> None:
"""Wire the ``hermes lsp`` subcommand tree into the main argparse."""
@@ -20,38 +22,30 @@ def register_subparser(subparsers: argparse._SubParsersAction) -> None:
)
sub = parser.add_subparsers(dest="lsp_command")
- sub_status = sub.add_parser("status", help="Show LSP service status")
- sub_status.add_argument(
+ sub.add_parser("status", help="Show LSP service status").add_argument(
"--json", action="store_true", help="Emit machine-readable JSON"
)
-
- sub_list = sub.add_parser("list", help="List supported language servers")
- sub_list.add_argument(
+ sub.add_parser("list", help="List supported language servers").add_argument(
"--installed-only",
action="store_true",
help="Only show servers whose binary is currently available",
)
-
- sub_install = sub.add_parser("install", help="Install a server binary")
- sub_install.add_argument("server", help="Server id (e.g. pyright, gopls)")
-
- sub_install_all = sub.add_parser(
+ sub.add_parser("install", help="Install a server binary").add_argument(
+ "server", help="Server id (e.g. pyright, gopls)"
+ )
+ sub.add_parser(
"install-all",
help="Install every server with a known auto-install recipe",
- )
- sub_install_all.add_argument(
+ ).add_argument(
"--include-manual",
action="store_true",
help="Even attempt servers marked manual-install (best effort)",
)
-
sub.add_parser(
"restart",
help="Tear down running LSP clients (next edit re-spawns)",
)
-
- sub_which = sub.add_parser("which", help="Print binary path for a server")
- sub_which.add_argument("server", help="Server id")
+ sub.add_parser("which", help="Print binary path for a server").add_argument("server", help="Server id")
parser.set_defaults(func=run_lsp_command)
@@ -85,7 +79,6 @@ def _cmd_status(emit_json: bool) -> int:
from agent.lsp.install import detect_status
svc = get_service()
- service_active = svc is not None
info = svc.get_status() if svc is not None else {"enabled": False}
if emit_json:
@@ -105,28 +98,23 @@ def _cmd_status(emit_json: bool) -> int:
sys.stdout.write(json.dumps(payload, indent=2) + "\n")
return 0
- out = []
- out.append("LSP Service")
- out.append("===========")
- out.append(f" enabled: {info.get('enabled', False)}")
- if service_active:
+ out = ["LSP Service", "===========", f" enabled: {info.get('enabled', False)}"]
+ if svc is not None:
out.append(f" wait_mode: {info.get('wait_mode')}")
out.append(f" wait_timeout: {info.get('wait_timeout')}s")
out.append(f" install_strategy:{info.get('install_strategy')}")
clients = info.get("clients") or []
if clients:
out.append(f" active clients: {len(clients)}")
- for c in clients:
- out.append(
- f" - {c['server_id']:20s} state={c['state']:10s} root={c['workspace_root']}"
- )
+ out.extend(
+ f" - {c['server_id']:20s} state={c['state']:10s} root={c['workspace_root']}" for c in clients
+ )
else:
out.append(" active clients: none")
broken = info.get("broken") or []
if broken:
out.append(f" broken pairs: {len(broken)}")
- for b in broken:
- out.append(f" - {b}")
+ out.extend(f" - {b}" for b in broken)
disabled = info.get("disabled_servers") or []
if disabled:
out.append(f" disabled in cfg: {', '.join(disabled)}")
@@ -134,28 +122,15 @@ def _cmd_status(emit_json: bool) -> int:
# Sidecar gaps the registry table can't show (bash-language-server -> shellcheck).
backend_warnings = _backend_warnings()
if backend_warnings:
- out.append("")
- out.append("Backend warnings")
- out.append("================")
- for line in backend_warnings:
- out.append(f" ! {line}")
- out.append("")
- out.append("Registered Servers")
- out.append("==================")
+ out.extend(["", "Backend warnings", "================"])
+ out.extend(f" ! {line}" for line in backend_warnings)
+ out.extend(["", "Registered Servers", "=================="])
for s in SERVERS:
- pkg = _recipe_pkg_for(s.server_id)
- status = detect_status(pkg)
- marker = {
- "installed": "✓",
- "missing": "·",
- "manual-only": "?",
- }.get(status, " ")
+ status = detect_status(_recipe_pkg_for(s.server_id))
ext_summary = ", ".join(list(s.extensions)[:5])
if len(s.extensions) > 5:
ext_summary += f", … (+{len(s.extensions) - 5})"
- out.append(
- f" {marker} {s.server_id:24s} [{status:11s}] {ext_summary}"
- )
+ out.append(f" {_STATUS_MARKERS.get(status, ' ')} {s.server_id:24s} [{status:11s}] {ext_summary}")
if s.description:
out.append(f" {s.description}")
sys.stdout.write("\n".join(out) + "\n")
@@ -167,33 +142,24 @@ def _cmd_list(installed_only: bool) -> int:
from agent.lsp.install import detect_status
for s in SERVERS:
- pkg = _recipe_pkg_for(s.server_id)
- status = detect_status(pkg)
- if installed_only and status != "installed":
- continue
- sys.stdout.write(
- f"{s.server_id:24s} [{status:11s}] {','.join(s.extensions)}\n"
- )
+ status = detect_status(_recipe_pkg_for(s.server_id))
+ if not (installed_only and status != "installed"):
+ sys.stdout.write(f"{s.server_id:24s} [{status:11s}] {','.join(s.extensions)}\n")
return 0
def _cmd_install(server_id: str) -> int:
from agent.lsp.install import try_install, INSTALL_RECIPES, detect_status
pkg = _recipe_pkg_for(server_id)
- pre_status = detect_status(pkg)
- if pre_status == "installed":
+ if detect_status(pkg) == "installed":
sys.stdout.write(f"{server_id} already installed\n")
return 0
sys.stdout.write(f"installing {server_id} (pkg={pkg}) ...\n")
sys.stdout.flush()
bin_path = try_install(pkg, "auto")
if bin_path is None:
- recipe = INSTALL_RECIPES.get(pkg)
- if recipe and recipe.get("strategy") == "manual":
- sys.stderr.write(
- f"{server_id}: this server requires a manual install. "
- f"See documentation.\n"
- )
+ if (INSTALL_RECIPES.get(pkg) or {}).get("strategy") == "manual":
+ sys.stderr.write(f"{server_id}: this server requires a manual install. See documentation.\n")
else:
sys.stderr.write(f"{server_id}: install failed (see logs).\n")
return 1
@@ -209,9 +175,7 @@ def _cmd_install_all(include_manual: bool) -> int:
for s in SERVERS:
pkg = _recipe_pkg_for(s.server_id)
recipe = INSTALL_RECIPES.get(pkg)
- if recipe is None:
- continue
- if recipe.get("strategy") == "manual" and not include_manual:
+ if recipe is None or (recipe.get("strategy") == "manual" and not include_manual):
continue
if detect_status(pkg) == "installed":
sys.stdout.write(f" {s.server_id:24s} already installed\n")
@@ -238,9 +202,7 @@ def _cmd_restart() -> int:
def _cmd_which(server_id: str) -> int:
from agent.lsp.install import INSTALL_RECIPES, _existing_binary
- recipe = INSTALL_RECIPES.get(server_id)
- bin_name = (recipe or {}).get("bin", server_id)
- resolved = _existing_binary(bin_name)
+ resolved = _existing_binary((INSTALL_RECIPES.get(server_id) or {}).get("bin", server_id))
if resolved:
sys.stdout.write(resolved + "\n")
return 0
@@ -264,14 +226,12 @@ def _recipe_pkg_for(server_id: str) -> str:
def _backend_warnings() -> list:
"""Notes about missing sidecar tools that make a server spawn fine but emit nothing (e.g. shellcheck)."""
- import shutil as _shutil
+ import shutil
from agent.lsp.install import _existing_binary
- notes: list = []
- bash_installed = _existing_binary("bash-language-server") is not None
- if bash_installed and _shutil.which("shellcheck") is None:
- notes.append(
+ if _existing_binary("bash-language-server") is not None and shutil.which("shellcheck") is None:
+ return [
"bash-language-server is installed but shellcheck is missing — "
"diagnostics will be empty (apt: shellcheck, brew: shellcheck, "
"scoop: shellcheck)."
- )
- return notes
+ ]
+ return []
diff --git a/agent/lsp/client.py b/agent/lsp/client.py
index 4740652a7cd..ad498c9a39d 100644
--- a/agent/lsp/client.py
+++ b/agent/lsp/client.py
@@ -1,25 +1,14 @@
-"""Async LSP client over stdin/stdout.
-
-One :class:`LSPClient` per ``(language_server, workspace_root)`` pair. It owns
-the child process, drives JSON-RPC, and exposes :meth:`open_file`,
-:meth:`wait_for_diagnostics`, :meth:`diagnostics_for` and :meth:`shutdown`.
-:class:`agent.lsp.manager.LSPService` runs the event loop in a background
-thread so the synchronous file_operations layer can call in.
-
-Implementation notes:
-
-- Freshness is tracked with **document versions**, not timestamps: every
- didChange bumps ``version`` and each stored push/pull result is tagged with
- the version it describes. A result is fresh iff its tag >= the version
- being waited on, so a didChange implicitly invalidates everything older.
- This is what prevents "ghost diagnostics" — a slow server's leftovers from
- the previous edit can never masquerade as a verdict on the current content.
-- Whole-document sync: even when the server advertises incremental sync we
- send one ``contentChanges`` entry replacing the whole document. Every
- major server tolerates this and it saves range bookkeeping.
-- Every ``open_file`` also fires ``workspace/didChangeWatchedFiles`` (CREATED
- first, CHANGED after) — some servers (clangd, eslint) only re-scan on it.
-- ``ContentModified`` (-32801) errors are retried with exponential backoff.
+"""Async LSP client over stdin/stdout — one per ``(server, workspace_root)``.
+
+Owns the child process, drives JSON-RPC, and exposes ``open_file`` /
+``wait_for_diagnostics`` / ``diagnostics_for`` / ``shutdown``. Freshness is
+tracked with **document versions**, not timestamps: every didChange bumps
+``version`` and each stored push/pull result is tagged with the version it
+describes, so a slow server's leftovers can never masquerade as a verdict on
+the current content ("ghost diagnostics"). Whole-document sync is always
+sent (every major server tolerates it), every ``open_file`` also fires
+``workspace/didChangeWatchedFiles`` (clangd, eslint only re-scan on it), and
+``ContentModified`` (-32801) errors are retried with exponential backoff.
"""
from __future__ import annotations
@@ -63,6 +52,33 @@ MAX_CONTENT_MODIFIED_RETRIES = 3
RETRY_BASE_DELAY = 0.5
_WRITE_ERRORS = (BrokenPipeError, ConnectionResetError, OSError)
+_LIVE_STATES = {"starting", "running"}
+
+_CLIENT_CAPABILITIES: Dict[str, Any] = {
+ "window": {"workDoneProgress": True},
+ "workspace": {
+ "configuration": True,
+ "workspaceFolders": True,
+ "didChangeWatchedFiles": {"dynamicRegistration": True},
+ "diagnostics": {"refreshSupport": False},
+ },
+ "textDocument": {
+ "synchronization": {
+ "dynamicRegistration": False, "didOpen": True, "didChange": True,
+ "didSave": True, "willSave": False, "willSaveWaitUntil": False,
+ },
+ "diagnostic": {"dynamicRegistration": True, "relatedDocumentSupport": True},
+ "publishDiagnostics": {
+ "relatedInformation": True, "tagSupport": {"valueSet": [1, 2]},
+ "versionSupport": True, "codeDescriptionSupport": True, "dataSupport": False,
+ },
+ "hover": {"contentFormat": ["markdown", "plaintext"]},
+ "definition": {"linkSupport": True},
+ "references": {},
+ "documentSymbol": {"hierarchicalDocumentSymbolSupport": True},
+ },
+ "general": {"positionEncodings": ["utf-16"]},
+}
def file_uri(path: str) -> str:
@@ -91,8 +107,7 @@ def _end_position(text: str) -> Dict[str, int]:
if not text:
return {"line": 0, "character": 0}
lines = text.splitlines(keepends=False)
- # A trailing newline isn't represented by splitlines: the end is then
- # the start of the next (empty) line.
+ # splitlines drops a trailing newline: the end is then the start of the next (empty) line.
if text.endswith(("\n", "\r")):
return {"line": len(lines), "character": 0}
return {"line": len(lines) - 1, "character": len(lines[-1])}
@@ -104,8 +119,8 @@ class _DocState:
``version`` is the LSP document version last sent (didOpen=0, +1 per
didChange) and doubles as the freshness token: ``push_version`` /
- ``pull_version`` tag stored results, which are fresh iff tag >= version.
- Tags start at -1 ("no data yet"). Servers that echo a version in
+ ``pull_version`` tag stored results, fresh iff tag >= version. Tags
+ start at -1 ("no data yet"). Servers that echo a version in
publishDiagnostics get exact tagging; others are credited with the
current version at receipt time.
"""
@@ -161,12 +176,12 @@ class LSPClient:
# Server → client requests; anything else gets method-not-found.
self._request_handlers: Dict[str, Callable[[Any], Awaitable[Any]]] = {
- "window/workDoneProgress/create": self._handle_work_done_create,
+ "window/workDoneProgress/create": self._handle_null, # ack progress tokens
"workspace/configuration": self._handle_workspace_configuration,
"client/registerCapability": self._handle_register_capability,
"client/unregisterCapability": self._handle_unregister_capability,
"workspace/workspaceFolders": self._handle_workspace_folders,
- "workspace/diagnostic/refresh": self._handle_diagnostic_refresh,
+ "workspace/diagnostic/refresh": self._handle_null, # we re-pull on every touch anyway
}
# Server → client notifications; others (showMessage, $/progress) are dropped.
self._notification_handlers: Dict[str, Callable[[Any], None]] = {
@@ -193,10 +208,9 @@ class LSPClient:
return self._state == "running" and self._connection_is_open()
def _connection_is_open(self) -> bool:
- proc = self._proc
- reader = self._reader_task
+ proc, reader = self._proc, self._reader_task
return (
- self._state in {"starting", "running"}
+ self._state in _LIVE_STATES
and proc is not None
and proc.returncode is None
and proc.stdin is not None
@@ -214,7 +228,7 @@ class LSPClient:
On failure the process is killed and state is ``"error"``; re-call to retry.
"""
- if self._state in {"running", "starting"}:
+ if self._state in _LIVE_STATES:
return
self._state = "starting"
try:
@@ -239,14 +253,10 @@ class LSPClient:
env = dict(os.environ)
if self._env:
env.update(self._env)
-
- cmd = self._command
- if sys.platform == "win32":
- cmd = self._win_wrap_cmd(cmd)
-
+ cmd = self._win_wrap_cmd(self._command) if sys.platform == "win32" else self._command
try:
- # start_new_session=True gives the server its own process group.
- # Otherwise it inherits the gateway's pgid and mcp_tool's orphan
+ # start_new_session=True gives the server its own process group;
+ # otherwise it inherits the gateway's pgid and mcp_tool's orphan
# sweeper can killpg() the TUI parent along with it.
# windows_hide_flags() suppresses the console window a .cmd shim
# would flash from a console-less host (CREATE_NO_WINDOW; 0 on POSIX).
@@ -262,9 +272,7 @@ class LSPClient:
creationflags=windows_hide_flags(),
)
except FileNotFoundError as e:
- raise LSPProtocolError(
- f"LSP server binary not found: {cmd[0]} ({e})"
- ) from e
+ raise LSPProtocolError(f"LSP server binary not found: {cmd[0]} ({e})") from e
# stderr must be drained or the pipe buffer fills and the server hangs.
self._stderr_task = asyncio.create_task(self._drain_stderr())
@@ -307,7 +315,7 @@ class LSPClient:
except (asyncio.CancelledError, OSError):
pass
finally:
- unexpected_close = not self._stopping and self._state in {"starting", "running"}
+ unexpected_close = not self._stopping and self._state in _LIVE_STATES
if unexpected_close:
self._state = "error"
# Fail pending requests fast.
@@ -319,76 +327,30 @@ class LSPClient:
await self._cleanup_process()
async def _initialize(self) -> None:
+ root_uri = file_uri(self.workspace_root)
params = {
- "rootUri": file_uri(self.workspace_root),
+ "rootUri": root_uri,
"rootPath": self.workspace_root,
"processId": os.getpid(),
- "workspaceFolders": [
- {"name": "workspace", "uri": file_uri(self.workspace_root)}
- ],
+ "workspaceFolders": [{"name": "workspace", "uri": root_uri}],
"initializationOptions": self._init_options,
- "capabilities": {
- "window": {"workDoneProgress": True},
- "workspace": {
- "configuration": True,
- "workspaceFolders": True,
- "didChangeWatchedFiles": {"dynamicRegistration": True},
- "diagnostics": {"refreshSupport": False},
- },
- "textDocument": {
- "synchronization": {
- "dynamicRegistration": False,
- "didOpen": True,
- "didChange": True,
- "didSave": True,
- "willSave": False,
- "willSaveWaitUntil": False,
- },
- "diagnostic": {
- "dynamicRegistration": True,
- "relatedDocumentSupport": True,
- },
- "publishDiagnostics": {
- "relatedInformation": True,
- "tagSupport": {"valueSet": [1, 2]},
- "versionSupport": True,
- "codeDescriptionSupport": True,
- "dataSupport": False,
- },
- "hover": {"contentFormat": ["markdown", "plaintext"]},
- "definition": {"linkSupport": True},
- "references": {},
- "documentSymbol": {"hierarchicalDocumentSymbolSupport": True},
- },
- "general": {"positionEncodings": ["utf-16"]},
- },
+ "capabilities": _CLIENT_CAPABILITIES,
}
-
- result = await asyncio.wait_for(
- self._send_request("initialize", params),
- timeout=INITIALIZE_TIMEOUT,
- )
+ result = await asyncio.wait_for(self._send_request("initialize", params), timeout=INITIALIZE_TIMEOUT)
self._sync_kind = self._extract_sync_kind(result.get("capabilities") or {})
await self._send_notification("initialized", {})
if self._init_options:
# Some servers (vtsls, eslint) only pick config up via
# didChangeConfiguration even when it was in initializationOptions.
- await self._send_notification(
- "workspace/didChangeConfiguration",
- {"settings": self._init_options},
- )
+ await self._send_notification("workspace/didChangeConfiguration", {"settings": self._init_options})
@staticmethod
def _extract_sync_kind(capabilities: dict) -> int:
sync = capabilities.get("textDocumentSync")
- if isinstance(sync, int):
- return sync
if isinstance(sync, dict):
- change = sync.get("change")
- if isinstance(change, int):
- return change
- return 1 # default to Full
+ sync = sync.get("change")
+ return sync if isinstance(sync, int) else 1 # default to Full
async def shutdown(self) -> None:
"""Best-effort graceful shutdown: ``shutdown`` + ``exit``, then SIGTERM/SIGKILL. Idempotent."""
@@ -420,15 +382,12 @@ class LSPClient:
async def _cleanup_process(self) -> None:
async with self._cleanup_lock:
- reader_task = self._reader_task
- self._reader_task = None
+ reader_task, self._reader_task = self._reader_task, None
if reader_task is not asyncio.current_task():
await self._cancel_task(reader_task)
- stderr_task = self._stderr_task
- self._stderr_task = None
+ stderr_task, self._stderr_task = self._stderr_task, None
await self._cancel_task(stderr_task)
- proc = self._proc
- self._proc = None
+ proc, self._proc = self._proc, None
if proc is None or proc.returncode is not None:
return
try:
@@ -436,11 +395,8 @@ class LSPClient:
try:
await asyncio.wait_for(proc.wait(), timeout=SHUTDOWN_GRACE)
except asyncio.TimeoutError:
- try:
- proc.kill()
- await proc.wait()
- except ProcessLookupError:
- pass
+ proc.kill()
+ await proc.wait()
except ProcessLookupError:
pass
@@ -453,13 +409,14 @@ class LSPClient:
self._proc.stdin.write(encode_message(msg))
await self._proc.stdin.drain()
- async def _send_request(self, method: str, params: Any) -> Any:
+ def _require_open(self, method: str) -> None:
if not self._connection_is_open():
raise LSPProtocolError(f"cannot send {method!r}: server connection closed")
- loop = asyncio.get_running_loop()
- req_id = self._next_id
- self._next_id += 1
- fut: asyncio.Future = loop.create_future()
+
+ async def _send_request(self, method: str, params: Any) -> Any:
+ self._require_open(method)
+ req_id, self._next_id = self._next_id, self._next_id + 1
+ fut: asyncio.Future = asyncio.get_running_loop().create_future()
self._pending[req_id] = fut
try:
await self._write(make_request(req_id, method, params))
@@ -483,8 +440,7 @@ class LSPClient:
raise
async def _send_notification(self, method: str, params: Any) -> None:
- if not self._connection_is_open():
- raise LSPProtocolError(f"cannot send {method!r}: server connection closed")
+ self._require_open(method)
try:
await self._write(make_notification(method, params))
except _WRITE_ERRORS as e:
@@ -505,25 +461,22 @@ class LSPClient:
return
if "error" in msg:
err = msg["error"] or {}
- fut.set_exception(
- LSPRequestError(
- code=int(err.get("code", -32000)),
- message=str(err.get("message", "unknown")),
- data=err.get("data"),
- )
- )
+ fut.set_exception(LSPRequestError(
+ code=int(err.get("code", -32000)),
+ message=str(err.get("message", "unknown")),
+ data=err.get("data"),
+ ))
else:
fut.set_result(msg.get("result"))
async def _dispatch_request(self, req_id: Any, msg: dict) -> None:
method = msg.get("method", "")
- params = msg.get("params")
handler = self._request_handlers.get(method)
if handler is None:
await self._send_reply(make_error_response(req_id, ERROR_METHOD_NOT_FOUND, f"method not found: {method}"))
return
try:
- result = await handler(params)
+ result = await handler(msg.get("params"))
except Exception as e: # noqa: BLE001 — protocol must not blow up
logger.warning("[%s] request handler %s failed: %s", self.server_id, method, e)
await self._send_reply(make_error_response(req_id, -32000, f"handler failed: {e}"))
@@ -543,8 +496,7 @@ class LSPClient:
# built-in server-→-client request handlers
# ------------------------------------------------------------------
- async def _handle_work_done_create(self, params: Any) -> Any:
- # Acknowledge progress tokens — required by some servers.
+ async def _handle_null(self, params: Any) -> Any:
return None
async def _handle_workspace_configuration(self, params: Any) -> Any:
@@ -562,59 +514,41 @@ class LSPClient:
continue
cur: Any = self._init_options
for part in str(section).split("."):
- if isinstance(cur, dict) and part in cur:
- cur = cur[part]
- else:
+ if not (isinstance(cur, dict) and part in cur):
cur = None
break
+ cur = cur[part]
out.append(cur)
return out
async def _handle_register_capability(self, params: Any) -> Any:
- if not isinstance(params, dict):
- return None
- for reg in params.get("registrations") or []:
- if not isinstance(reg, dict):
- continue
- reg_id = reg.get("id")
- if reg.get("method") == "textDocument/diagnostic" and reg_id:
- self._diagnostic_registrations[str(reg_id)] = reg
- self._registration_event.set()
+ if isinstance(params, dict):
+ for reg in params.get("registrations") or []:
+ if isinstance(reg, dict) and reg.get("method") == "textDocument/diagnostic" and reg.get("id"):
+ self._diagnostic_registrations[str(reg["id"])] = reg
+ self._registration_event.set()
return None
async def _handle_unregister_capability(self, params: Any) -> Any:
- if not isinstance(params, dict):
- return None
- for unreg in params.get("unregisterations") or []:
- if not isinstance(unreg, dict):
- continue
- reg_id = unreg.get("id")
- if reg_id:
- self._diagnostic_registrations.pop(str(reg_id), None)
+ if isinstance(params, dict):
+ for unreg in params.get("unregisterations") or []:
+ if isinstance(unreg, dict) and unreg.get("id"):
+ self._diagnostic_registrations.pop(str(unreg["id"]), None)
return None
async def _handle_workspace_folders(self, params: Any) -> Any:
return [{"name": "workspace", "uri": file_uri(self.workspace_root)}]
- async def _handle_diagnostic_refresh(self, params: Any) -> Any:
- # We don't honour refresh — we re-pull on every touchFile.
- return None
-
def _handle_publish_diagnostics(self, params: Any) -> None:
- if not isinstance(params, dict):
- return
- uri = params.get("uri")
- if not isinstance(uri, str):
+ if not isinstance(params, dict) or not isinstance(params.get("uri"), str):
return
diagnostics = params.get("diagnostics") or []
- if not isinstance(diagnostics, list):
- diagnostics = []
version = params.get("version")
- doc = self._docs.setdefault(uri_to_path(uri), _DocState(version=-1))
+ doc = self._docs.setdefault(uri_to_path(params["uri"]), _DocState(version=-1))
is_seed = self._seed_first_push and not doc.seed_seen
doc.seed_seen = True
- doc.push = diagnostics
+ doc.push = diagnostics if isinstance(diagnostics, list) else []
if is_seed:
# First push is baseline data only: it predates any didChange we
# sent, so it's stored WITHOUT a freshness tag and never satisfies a waiter.
@@ -646,66 +580,46 @@ class LSPClient:
uri = file_uri(abs_path)
doc = self._docs.get(abs_path)
+ if doc is not None and doc.version < 0:
+ doc = None # never opened (relatedDocuments spillover): treat as new
+ # FileChangeType: 1 = CREATED, 2 = CHANGED.
+ await self._send_notification(
+ "workspace/didChangeWatchedFiles", {"changes": [{"uri": uri, "type": 1 if doc is None else 2}]}
+ )
- if doc is not None and doc.version >= 0:
- await self._send_notification(
- "workspace/didChangeWatchedFiles",
- {"changes": [{"uri": uri, "type": 2}]}, # 2 = CHANGED
- )
+ if doc is not None:
new_version = doc.version + 1
- content_changes: List[Dict[str, Any]]
if self._sync_kind == 2:
- content_changes = [
- {
- "range": {
- "start": {"line": 0, "character": 0},
- "end": _end_position(doc.text),
- },
- "text": text,
- }
- ]
+ content_changes = [{
+ "range": {"start": {"line": 0, "character": 0}, "end": _end_position(doc.text)},
+ "text": text,
+ }]
else:
content_changes = [{"text": text}]
await self._send_notification(
"textDocument/didChange",
- {
- "textDocument": {"uri": uri, "version": new_version},
- "contentChanges": content_changes,
- },
+ {"textDocument": {"uri": uri, "version": new_version}, "contentChanges": content_changes},
)
# Bumping the version is the whole invalidation story (see _DocState).
doc.version = new_version
doc.text = text
return new_version
- await self._send_notification(
- "workspace/didChangeWatchedFiles",
- {"changes": [{"uri": uri, "type": 1}]}, # 1 = CREATED
- )
# Fresh state: anything a pre-open push stashed under this path
# (relatedDocuments spillover) is discarded.
self._docs[abs_path] = _DocState(version=0, text=text)
await self._send_notification(
"textDocument/didOpen",
- {
- "textDocument": {
- "uri": uri,
- "languageId": language_id,
- "version": 0,
- "text": text,
- }
- },
+ {"textDocument": {"uri": uri, "languageId": language_id, "version": 0, "text": text}},
)
return 0
async def save_file(self, path: str) -> None:
"""Send didSave for ``path``. Some linters re-scan only on save."""
- if not self.is_running:
- return
- await self._send_notification(
- "textDocument/didSave",
- {"textDocument": {"uri": file_uri(os.path.abspath(path))}},
- )
+ if self.is_running:
+ await self._send_notification(
+ "textDocument/didSave", {"textDocument": {"uri": file_uri(os.path.abspath(path))}}
+ )
# ------------------------------------------------------------------
# diagnostics: pull + wait
@@ -740,9 +654,7 @@ class LSPClient:
related = result.get("relatedDocuments")
if isinstance(related, dict):
for uri, sub in related.items():
- if not isinstance(sub, dict):
- continue
- sub_items = sub.get("items")
+ sub_items = sub.get("items") if isinstance(sub, dict) else None
if isinstance(sub_items, list):
rel = self._docs.setdefault(uri_to_path(uri), _DocState(version=-1))
rel.pull = sub_items
@@ -775,9 +687,7 @@ class LSPClient:
while True:
if not self._connection_is_open():
- raise LSPProtocolError(
- "server connection closed while waiting for diagnostics"
- )
+ raise LSPProtocolError("server connection closed while waiting for diagnostics")
remaining = deadline - asyncio.get_event_loop().time()
if remaining <= 0:
return False
@@ -785,10 +695,8 @@ class LSPClient:
# Concurrent: document pull + push wait.
pull_task = asyncio.create_task(self._pull_document_diagnostics(abs_path))
push_task = asyncio.create_task(self._wait_for_fresh_push(abs_path, version, remaining))
- done, pending = await asyncio.wait(
- {pull_task, push_task},
- timeout=remaining,
- return_when=asyncio.FIRST_COMPLETED,
+ _done, pending = await asyncio.wait(
+ {pull_task, push_task}, timeout=remaining, return_when=asyncio.FIRST_COMPLETED
)
for t in pending:
t.cancel()
@@ -802,9 +710,19 @@ class LSPClient:
if doc and (doc.fresh_push(version) or doc.fresh_pull(version)):
return True
+ async def _await_push(self, timeout: float) -> bool:
+ """Block until the next publishDiagnostics or ``timeout``; True iff a push woke us."""
+ self._push_event.clear()
+ try:
+ await asyncio.wait_for(self._push_event.wait(), timeout=timeout)
+ return True
+ except asyncio.TimeoutError:
+ return False
+
async def _wait_for_fresh_push(self, path: str, version: int, timeout: float) -> None:
"""Wait until a fresh publishDiagnostics arrives for ``path`` at ``version``+."""
- deadline = asyncio.get_event_loop().time() + timeout
+ now = asyncio.get_event_loop().time
+ deadline = now() + timeout
baseline = self._push_counter
while True:
doc = self._docs.get(path)
@@ -812,29 +730,20 @@ class LSPClient:
# Debounce: TS often emits in pairs. Snapshot the counter so
# we wake on a *new* push, not the one that just satisfied us.
debounce_baseline = self._push_counter
- debounce_deadline = asyncio.get_event_loop().time() + PUSH_DEBOUNCE
+ debounce_deadline = now() + PUSH_DEBOUNCE
while self._push_counter == debounce_baseline:
- remaining = debounce_deadline - asyncio.get_event_loop().time()
- if remaining <= 0:
- break
- self._push_event.clear()
- try:
- await asyncio.wait_for(self._push_event.wait(), timeout=remaining)
- except asyncio.TimeoutError:
+ remaining = debounce_deadline - now()
+ if remaining <= 0 or not await self._await_push(remaining):
break
return
- remaining = deadline - asyncio.get_event_loop().time()
+ remaining = deadline - now()
if remaining <= 0:
return
if self._push_counter > baseline:
# New push but predicate still false — re-check without waiting.
baseline = self._push_counter
continue
- self._push_event.clear()
- try:
- await asyncio.wait_for(self._push_event.wait(), timeout=min(remaining, 0.5))
- except asyncio.TimeoutError:
- continue
+ await self._await_push(min(remaining, 0.5))
def diagnostics_for(self, path: str, *, fresh_only: bool = False) -> List[Dict[str, Any]]:
"""Merged + deduped push/pull diagnostics for one file.
@@ -847,10 +756,7 @@ class LSPClient:
if doc is None:
return []
if fresh_only:
- return _dedupe(
- doc.push if doc.fresh_push() else [],
- doc.pull if doc.fresh_pull() else [],
- )
+ return _dedupe(doc.push if doc.fresh_push() else [], doc.pull if doc.fresh_pull() else [])
return _dedupe(doc.push, doc.pull)
@@ -859,13 +765,9 @@ def _dedupe(*lists: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
out: List[Dict[str, Any]] = []
for lst in lists:
for d in lst:
- if not isinstance(d, dict):
- continue
- key = _diagnostic_key(d)
- if key in seen:
- continue
- seen.add(key)
- out.append(d)
+ if isinstance(d, dict) and (key := _diagnostic_key(d)) not in seen:
+ seen.add(key)
+ out.append(d)
return out
@@ -881,17 +783,13 @@ def _diagnostic_key(d: Dict[str, Any]) -> str:
start = rng.get("start") or {}
end = rng.get("end") or {}
code = d.get("code")
- if code is not None and not isinstance(code, str):
- code = str(code)
- return "\x00".join(
- [
- str(d.get("severity") or 1),
- str(code or ""),
- str(d.get("source") or ""),
- str(d.get("message") or "").strip(),
- f"{start.get('line', 0)}:{start.get('character', 0)}-{end.get('line', 0)}:{end.get('character', 0)}",
- ]
- )
+ return "\x00".join([
+ str(d.get("severity") or 1),
+ "" if code is None else str(code),
+ str(d.get("source") or ""),
+ str(d.get("message") or "").strip(),
+ f"{start.get('line', 0)}:{start.get('character', 0)}-{end.get('line', 0)}:{end.get('character', 0)}",
+ ])
__all__ = [
diff --git a/agent/lsp/eventlog.py b/agent/lsp/eventlog.py
index 60d452fb3e8..ecfae14e5c3 100644
--- a/agent/lsp/eventlog.py
+++ b/agent/lsp/eventlog.py
@@ -1,20 +1,15 @@
"""Structured logging with steady-state silence for the LSP layer.
LSP fires on every write_file/patch, so the level model keeps ``agent.log``
-greppable (``rg 'lsp\\['``) without noise:
-
-- ``DEBUG`` for steady-state events with no novel signal (clean, skipped,
- repeat "no project root", repeat "server unavailable").
-- ``INFO`` for once-per-session transitions (``active for <root>`` the first
- time a client starts, first ``no project root`` per file) and for every
- diagnostic event (rare and exactly what users grep for).
-- ``WARNING`` for action-required failures: first ``server unavailable`` per
- (server_id, binary), ``no server configured`` once per language, and every
- timeout / unexpected error.
-
-Dedup uses module-level sets bounded by the distinct pairs touched in one
-process. A bounded LRU was rejected: evicting an entry would re-fire the
-line we explicitly want suppressed.
+greppable (``rg 'lsp\\['``) without noise: DEBUG for steady-state events with
+no novel signal (clean, skipped, repeat "no project root" / "server
+unavailable"); INFO for once-per-session transitions (first ``active for
+<root>``, first ``no project root`` per file) and every diagnostic event;
+WARNING for action-required failures (first ``server unavailable`` per
+(server_id, binary), every timeout / unexpected error). Dedup uses
+module-level sets bounded by the distinct pairs touched in one process — a
+bounded LRU was rejected because evicting an entry would re-fire the line
+we explicitly want suppressed.
"""
from __future__ import annotations
@@ -51,18 +46,12 @@ def _emit(server_id: str, level: int, message: str) -> None:
event_log.log(level, "lsp[%s] %s", server_id, message)
-def _announce_once(bucket: set, key: Tuple) -> bool:
- """Atomically mark *key* announced; True only for the first caller."""
- with _announce_lock:
- if key in bucket:
- return False
- bucket.add(key)
- return True
-
-
def _emit_once(bucket: set, key: Tuple, server_id: str, level: int, first: str, repeat: str) -> None:
"""Log *first* at *level* the first time *key* is seen, *repeat* at DEBUG thereafter."""
- if _announce_once(bucket, key):
+ with _announce_lock:
+ is_first = key not in bucket
+ bucket.add(key)
+ if is_first:
_emit(server_id, level, first)
else:
_emit(server_id, logging.DEBUG, repeat)
@@ -119,20 +108,12 @@ def log_timeout(server_id: str, file_path: str, kind: str = "diagnostics") -> No
def log_server_error(server_id: str, file_path: str, exc: BaseException) -> None:
"""An unexpected exception bubbled out of the LSP layer. WARNING."""
- _emit(
- server_id,
- logging.WARNING,
- f"unexpected error for {_short_path(file_path)}: {type(exc).__name__}: {exc}",
- )
+ _emit(server_id, logging.WARNING, f"unexpected error for {_short_path(file_path)}: {type(exc).__name__}: {exc}")
def log_spawn_failed(server_id: str, workspace_root: str, exc: BaseException) -> None:
"""The LSP server failed to spawn or initialize. WARNING."""
- _emit(
- server_id,
- logging.WARNING,
- f"spawn/initialize failed for {workspace_root}: {type(exc).__name__}: {exc}",
- )
+ _emit(server_id, logging.WARNING, f"spawn/initialize failed for {workspace_root}: {type(exc).__name__}: {exc}")
def log_reaped(keys: List[Tuple[str, str]], idle_timeout: float) -> None:
@@ -145,11 +126,7 @@ def log_reaped(keys: List[Tuple[str, str]], idle_timeout: float) -> None:
for key in keys:
_announced_active.discard(key)
summary = ", ".join(f"{sid} ({root})" for sid, root in keys)
- _emit(
- "reaper",
- logging.INFO,
- f"reaped {len(keys)} idle client(s) after {idle_timeout:.0f}s: {summary}",
- )
+ _emit("reaper", logging.INFO, f"reaped {len(keys)} idle client(s) after {idle_timeout:.0f}s: {summary}")
def reset_announce_caches() -> None:
diff --git a/agent/lsp/install.py b/agent/lsp/install.py
index 01040b9ff7f..5e098b59e14 100644
--- a/agent/lsp/install.py
+++ b/agent/lsp/install.py
@@ -4,11 +4,9 @@ Installs go to a Hermes-owned staging dir, ``<HERMES_HOME>/lsp/bin/``, so the
user's global toolchain stays untouched. Strategies: ``auto`` (install with
the best available package manager), ``manual`` / ``off`` (probe only; a
missing binary skips the server and ``hermes lsp status`` reports it).
-
-Installs run synchronously the first time a server is needed; concurrent
-:func:`try_install` calls for the same package are serialized per-package.
-Every failure path returns ``None`` so the tool layer falls back to its
-in-process syntax checker.
+Installs run synchronously the first time a server is needed, serialized
+per-package; every failure path returns ``None`` so the tool layer falls
+back to its in-process syntax checker.
"""
from __future__ import annotations
@@ -18,7 +16,7 @@ import shutil
import subprocess
import threading
from pathlib import Path
-from typing import Any, Dict, Optional
+from typing import Any, Callable, Dict, Optional
from hermes_cli._subprocess_compat import windows_hide_flags
from hermes_constants import find_node_executable
@@ -30,30 +28,38 @@ def _recipe(strategy: str, pkg: str, bin_name: str, **extra: Any) -> Dict[str, A
return {"strategy": strategy, "pkg": pkg, "bin": bin_name, **extra}
+def _npm(pkg: str, bin_name: str, **extra: Any) -> Dict[str, Any]:
+ return _recipe("npm", pkg, bin_name, **extra)
+
+
+def _manual(bin_name: str) -> Dict[str, Any]:
+ return _recipe("manual", "", bin_name)
+
+
# Recipe key → {strategy, pkg, bin[, extra_pkgs]}. After install we look for
# ``bin`` in ``<HERMES_HOME>/lsp/bin/`` first, then on PATH. ``extra_pkgs``
# are sibling npm packages a server needs in the same node_modules tree.
INSTALL_RECIPES: Dict[str, Dict[str, Any]] = {
- "pyright": _recipe("npm", "pyright", "pyright-langserver"),
+ "pyright": _npm("pyright", "pyright-langserver"),
# tsserver must be importable from the same node_modules tree or
# initialize() fails with "Could not find a valid TypeScript installation".
- "typescript-language-server": _recipe("npm", "typescript-language-server", "typescript-language-server", extra_pkgs=["typescript"]),
- "@vue/language-server": _recipe("npm", "@vue/language-server", "vue-language-server"),
- "svelte-language-server": _recipe("npm", "svelte-language-server", "svelteserver"),
- "@astrojs/language-server": _recipe("npm", "@astrojs/language-server", "astro-ls"),
- "yaml-language-server": _recipe("npm", "yaml-language-server", "yaml-language-server"),
- "bash-language-server": _recipe("npm", "bash-language-server", "bash-language-server"),
- "intelephense": _recipe("npm", "intelephense", "intelephense"),
- "dockerfile-language-server-nodejs": _recipe("npm", "dockerfile-language-server-nodejs", "docker-langserver"),
+ "typescript-language-server": _npm("typescript-language-server", "typescript-language-server", extra_pkgs=["typescript"]),
+ "@vue/language-server": _npm("@vue/language-server", "vue-language-server"),
+ "svelte-language-server": _npm("svelte-language-server", "svelteserver"),
+ "@astrojs/language-server": _npm("@astrojs/language-server", "astro-ls"),
+ "yaml-language-server": _npm("yaml-language-server", "yaml-language-server"),
+ "bash-language-server": _npm("bash-language-server", "bash-language-server"),
+ "intelephense": _npm("intelephense", "intelephense"),
+ "dockerfile-language-server-nodejs": _npm("dockerfile-language-server-nodejs", "docker-langserver"),
"gopls": _recipe("go", "golang.org/x/tools/gopls@latest", "gopls"),
# Manual: rust-analyzer (via rustup) and clangd (ships with LLVM) are far too
# heavy to bootstrap; LuaLS is platform-specific GitHub release binaries.
- "rust-analyzer": _recipe("manual", "", "rust-analyzer"),
- "clangd": _recipe("manual", "", "clangd"),
- "lua-language-server": _recipe("manual", "", "lua-language-server"),
+ "rust-analyzer": _manual("rust-analyzer"),
+ "clangd": _manual("clangd"),
+ "lua-language-server": _manual("lua-language-server"),
# PowerShellEditorServices is a release-zip bundle driven by pwsh; we probe
# the host so `hermes lsp status` reports its presence.
- "powershell": _recipe("manual", "", "pwsh"),
+ "powershell": _manual("pwsh"),
}
@@ -90,29 +96,27 @@ def _native_binary_candidates(base: Path) -> list[Path]:
return candidates
+def _first_existing(*bases: Path) -> Optional[Path]:
+ """First platform-native candidate of any ``base`` that exists on disk."""
+ for base in bases:
+ for c in _native_binary_candidates(base):
+ if c.exists():
+ return c
+ return None
+
+
def _existing_binary(name: str) -> Optional[str]:
"""Probe the staging dir + PATH for a binary named ``name``."""
for staged in _native_binary_candidates(hermes_lsp_bin_dir() / name):
if staged.exists() and os.access(staged, os.X_OK):
return str(staged)
- on_path = shutil.which(name)
- if on_path:
- return on_path
- if _is_windows():
- for suffix in _WINDOWS_WRAPPER_SUFFIXES:
- on_path = shutil.which(f"{name}{suffix}")
- if on_path:
- return on_path
- return None
+ suffixes = ("", *_WINDOWS_WRAPPER_SUFFIXES) if _is_windows() else ("",)
+ return next((p for s in suffixes if (p := shutil.which(f"{name}{s}"))), None)
def _get_lock(pkg: str) -> threading.Lock:
with _install_lock_meta:
- lock = _install_locks.get(pkg)
- if lock is None:
- lock = threading.Lock()
- _install_locks[pkg] = lock
- return lock
+ return _install_locks.setdefault(pkg, threading.Lock())
def try_install(pkg: str, strategy: str = "auto") -> Optional[str]:
@@ -122,9 +126,8 @@ def try_install(pkg: str, strategy: str = "auto") -> Optional[str]:
existing binary. Results are cached per package and concurrent calls
are serialized.
"""
- if strategy not in {"auto",}:
- recipe = INSTALL_RECIPES.get(pkg, {})
- return _existing_binary(recipe.get("bin", pkg))
+ if strategy != "auto":
+ return _existing_binary(INSTALL_RECIPES.get(pkg, {}).get("bin", pkg))
if pkg in _install_results:
return _install_results[pkg]
@@ -154,19 +157,11 @@ def _do_install(pkg: str) -> Optional[str]:
logger.debug("[install] %s requires manual install (recipe=%s)", pkg, recipe)
return None
- if strategy == "npm":
- return _install_npm(
- recipe.get("pkg", pkg),
- bin_name,
- extra_pkgs=recipe.get("extra_pkgs") or [],
- )
- if strategy == "go":
- return _install_go(recipe.get("pkg", pkg), bin_name)
- if strategy == "pip":
- return _install_pip(recipe.get("pkg", pkg), bin_name)
-
- logger.warning("[install] unknown strategy %r for %s", strategy, pkg)
- return None
+ installer = _INSTALLERS.get(strategy)
+ if installer is None:
+ logger.warning("[install] unknown strategy %r for %s", strategy, pkg)
+ return None
+ return installer(recipe, bin_name)
def _run_installer(tool: str, pkg: str, cmd: list, *, timeout: int, env: Optional[dict] = None) -> bool:
@@ -183,9 +178,7 @@ def _run_installer(tool: str, pkg: str, cmd: list, *, timeout: int, env: Optiona
creationflags=windows_hide_flags(),
)
if proc.returncode != 0:
- logger.warning(
- "[install] %s install failed for %s: %s", tool, pkg, proc.stderr.strip()[:500]
- )
+ logger.warning("[install] %s install failed for %s: %s", tool, pkg, proc.stderr.strip()[:500])
return False
except (subprocess.TimeoutExpired, OSError) as e:
logger.warning("[install] %s install errored for %s: %s", tool, pkg, e)
@@ -208,11 +201,7 @@ def _link_into_bin(target: Path) -> str:
return str(link if link.exists() else target)
-def _install_npm(
- pkg: str,
- bin_name: str,
- extra_pkgs: Optional[list] = None,
-) -> Optional[str]:
+def _install_npm(pkg: str, bin_name: str, extra_pkgs: Optional[list] = None) -> Optional[str]:
"""``npm install --prefix <staging>`` then link ``node_modules/.bin/<bin_name>`` into ``lsp/bin/``."""
# Managed npm first: $HERMES_HOME/node isn't on an arbitrary process's
# PATH, so a bare which() would miss the Node that Hermes installed.
@@ -222,11 +211,7 @@ def _install_npm(
return None
staging = hermes_lsp_bin_dir().parent # <HERMES_HOME>/lsp/
install_targets = [pkg] + list(extra_pkgs or [])
- logger.info(
- "[install] npm install --prefix %s %s",
- staging,
- " ".join(install_targets),
- )
+ logger.info("[install] npm install --prefix %s %s", staging, " ".join(install_targets))
if not _run_installer(
"npm", pkg,
[npm, "install", "--prefix", str(staging), "--silent", "--no-fund", "--no-audit", *install_targets],
@@ -234,10 +219,9 @@ def _install_npm(
):
return None
- nm_bin = staging / "node_modules" / ".bin" / bin_name
- for c in _native_binary_candidates(nm_bin):
- if c.exists():
- return _link_into_bin(c)
+ found = _first_existing(staging / "node_modules" / ".bin" / bin_name)
+ if found is not None:
+ return _link_into_bin(found)
logger.warning("[install] npm install for %s succeeded but bin %s not found", pkg, bin_name)
return None
@@ -249,8 +233,7 @@ def _install_go(pkg: str, bin_name: str) -> Optional[str]:
logger.info("[install] cannot install %s: go not on PATH", pkg)
return None
staging = hermes_lsp_bin_dir()
- env = dict(os.environ)
- env["GOBIN"] = str(staging)
+ env = {**os.environ, "GOBIN": str(staging)}
logger.info("[install] go install %s (GOBIN=%s)", pkg, staging)
if not _run_installer("go", pkg, [go, "install", pkg], timeout=600, env=env):
return None
@@ -271,34 +254,31 @@ def _install_pip(pkg: str, bin_name: str) -> Optional[str]:
logger.info("[install] pip install --target %s %s", pip_target, pkg)
from hermes_cli.tools_config import _pip_install
- proc = _pip_install(
- ["--target", str(pip_target), "--quiet", pkg],
- timeout=300,
- )
+ proc = _pip_install(["--target", str(pip_target), "--quiet", pkg], timeout=300)
if proc.returncode != 0:
- logger.warning(
- "[install] pip install failed for %s: %s", pkg, (proc.stderr or "").strip()[:500]
- )
+ logger.warning("[install] pip install failed for %s: %s", pkg, (proc.stderr or "").strip()[:500])
return None
except (subprocess.TimeoutExpired, OSError) as e:
logger.warning("[install] pip install errored for %s: %s", pkg, e)
return None
# POSIX wheels write console scripts to bin/, native Windows to Scripts/.
- script_dirs = [pip_target / "bin"]
- if _is_windows():
- script_dirs.append(pip_target / "Scripts")
- for script_dir in script_dirs:
- for bin_path in _native_binary_candidates(script_dir / bin_name):
- if bin_path.exists():
- return _link_into_bin(bin_path)
- return None
+ script_dirs = [pip_target / "bin"] + ([pip_target / "Scripts"] if _is_windows() else [])
+ found = _first_existing(*(d / bin_name for d in script_dirs))
+ return _link_into_bin(found) if found is not None else None
+
+
+# strategy → installer(recipe, bin_name). ``manual`` is handled before dispatch.
+_INSTALLERS: Dict[str, Callable[[Dict[str, Any], str], Optional[str]]] = {
+ "npm": lambda r, b: _install_npm(r["pkg"], b, extra_pkgs=r.get("extra_pkgs") or []),
+ "go": lambda r, b: _install_go(r["pkg"], b),
+ "pip": lambda r, b: _install_pip(r["pkg"], b),
+}
def detect_status(pkg: str) -> str:
"""Return ``installed``, ``missing``, or ``manual-only`` (for ``hermes lsp status``; spawns nothing)."""
recipe = INSTALL_RECIPES.get(pkg)
- bin_name = recipe.get("bin", pkg) if recipe else pkg
- if _existing_binary(bin_name):
+ if _existing_binary(recipe.get("bin", pkg) if recipe else pkg):
return "installed"
if recipe and recipe.get("strategy") == "manual":
return "manual-only"
diff --git a/agent/lsp/manager.py b/agent/lsp/manager.py
index 275d8721add..76eca701a2a 100644
--- a/agent/lsp/manager.py
+++ b/agent/lsp/manager.py
@@ -1,19 +1,14 @@
"""Service-level orchestration for LSP clients.
:class:`LSPService` bridges the synchronous file_operations layer and the
-async :class:`agent.lsp.client.LSPClient`:
-
-- One asyncio loop in a background thread; :meth:`get_diagnostics_sync`
- opens + waits + drains in one blocking call.
-- One lazily spawned client per ``(server_id, workspace_root)``.
-- A **broken-set** of pairs that failed to spawn/initialize — never retried
- for the life of the service.
-- A **delta baseline** per file: ``snapshot_baseline()`` runs BEFORE a write,
- and the next ``get_diagnostics_sync()`` returns only diagnostics not in it.
-
-The service is off unless config enables it; :meth:`is_active` says whether
-it does anything, and file_operations falls back to the in-process syntax
-check otherwise.
+async :class:`agent.lsp.client.LSPClient`: one asyncio loop in a background
+thread (``get_diagnostics_sync`` opens + waits + drains in one blocking
+call), one lazily spawned client per ``(server_id, workspace_root)``, a
+**broken-set** of pairs that failed to spawn/initialize (never retried for
+the life of the service), and a **delta baseline** per file
+(``snapshot_baseline()`` runs BEFORE a write; the next
+``get_diagnostics_sync()`` returns only diagnostics not in it). Off unless
+config enables it — file_operations falls back to in-process syntax checks.
"""
from __future__ import annotations
@@ -30,22 +25,16 @@ from agent.lsp.client import (
LSPClient,
_diagnostic_key as _diag_key,
)
-from agent.lsp.servers import (
- ServerContext,
- ServerDef,
- find_server_for_file,
- language_id_for,
-)
-from agent.lsp.workspace import (
- clear_cache,
- resolve_workspace_for_file,
-)
+from agent.lsp.servers import ServerContext, ServerDef, find_server_for_file, language_id_for
+from agent.lsp.workspace import clear_cache, resolve_workspace_for_file
logger = logging.getLogger("agent.lsp.manager")
DEFAULT_IDLE_TIMEOUT = 600 # seconds; servers idle for >10min get reaped
MIN_IDLE_TIMEOUT = 30 # floor for config values; must exceed any per-op wait budget
+_Key = Tuple[str, str]
+
class _BackgroundLoop:
"""A daemon thread owning one asyncio loop; :meth:`run` blocks on a coroutine."""
@@ -58,11 +47,7 @@ class _BackgroundLoop:
def start(self) -> None:
if self._thread is not None:
return
- self._thread = threading.Thread(
- target=self._run_forever,
- name="hermes-lsp-loop",
- daemon=True,
- )
+ self._thread = threading.Thread(target=self._run_forever, name="hermes-lsp-loop", daemon=True)
self._thread.start()
self._ready.wait(timeout=5.0)
@@ -140,10 +125,10 @@ class LSPService:
self._loop.start()
# Per-(server_id, workspace_root) state
- self._clients: Dict[Tuple[str, str], LSPClient] = {}
+ self._clients: Dict[_Key, LSPClient] = {}
self._broken: set = set()
- self._spawning: Dict[Tuple[str, str], asyncio.Future] = {}
- self._last_used: Dict[Tuple[str, str], float] = {}
+ self._spawning: Dict[_Key, asyncio.Future] = {}
+ self._last_used: Dict[_Key, float] = {}
self._state_lock = threading.Lock()
self._idle_reaper_task: Optional[asyncio.Task] = None
@@ -167,10 +152,6 @@ class LSPService:
if not isinstance(lsp_cfg, dict):
lsp_cfg = {}
- enabled = bool(lsp_cfg.get("enabled", True))
- wait_mode = lsp_cfg.get("wait_mode", "document")
- wait_timeout = float(lsp_cfg.get("wait_timeout", DIAGNOSTICS_DOCUMENT_WAIT))
- install_strategy = lsp_cfg.get("install_strategy", "auto")
try:
idle_timeout = float(lsp_cfg.get("idle_timeout", DEFAULT_IDLE_TIMEOUT))
except (TypeError, ValueError):
@@ -202,10 +183,10 @@ class LSPService:
init_overrides[name] = init
return cls(
- enabled=enabled,
- wait_mode=wait_mode,
- wait_timeout=wait_timeout,
- install_strategy=install_strategy,
+ enabled=bool(lsp_cfg.get("enabled", True)),
+ wait_mode=lsp_cfg.get("wait_mode", "document"),
+ wait_timeout=float(lsp_cfg.get("wait_timeout", DIAGNOSTICS_DOCUMENT_WAIT)),
+ install_strategy=lsp_cfg.get("install_strategy", "auto"),
binary_overrides=binary_overrides,
env_overrides=env_overrides,
init_overrides=init_overrides,
@@ -221,7 +202,7 @@ class LSPService:
"""Return True iff this service should be consulted at all."""
return self._enabled
- def _broken_key(self, srv: ServerDef, file_path: str) -> Optional[Tuple[str, str]]:
+ def _broken_key(self, srv: ServerDef, file_path: str) -> Optional[_Key]:
"""``(server_id, per-server root)`` broken-set key, or ``None`` when the file isn't gated in.
Falls back to the workspace root when the per-server resolver fails —
@@ -265,11 +246,11 @@ class LSPService:
# server gets falsely marked broken.
t = max(8.0, self._wait_timeout + 3.0)
diags = self._loop.run(self._snapshot_async(file_path), timeout=t)
- self._delta_baseline[os.path.abspath(file_path)] = diags or []
except Exception as e: # noqa: BLE001
logger.debug("baseline snapshot failed for %s: %s", file_path, e)
self._mark_broken_for_file(file_path, e)
- self._delta_baseline[os.path.abspath(file_path)] = []
+ diags = []
+ self._delta_baseline[os.path.abspath(file_path)] = diags or []
def get_diagnostics_sync(
self,
@@ -300,14 +281,13 @@ class LSPService:
try:
t = timeout if timeout is not None else self._wait_timeout + 2.0
diags = self._loop.run(self._open_and_wait_async(file_path), timeout=t)
- except asyncio.TimeoutError as e:
- eventlog.log_timeout(server_id, file_path)
- logger.debug("LSP diagnostics timeout for %s: %s", file_path, e)
- self._mark_broken_for_file(file_path, e)
- return []
except Exception as e: # noqa: BLE001
- eventlog.log_server_error(server_id, file_path, e)
- logger.debug("LSP diagnostics fetch failed for %s: %s", file_path, e)
+ if isinstance(e, asyncio.TimeoutError):
+ eventlog.log_timeout(server_id, file_path)
+ logger.debug("LSP diagnostics timeout for %s: %s", file_path, e)
+ else:
+ eventlog.log_server_error(server_id, file_path, e)
+ logger.debug("LSP diagnostics fetch failed for %s: %s", file_path, e)
self._mark_broken_for_file(file_path, e)
return []
@@ -353,9 +333,7 @@ class LSPService:
``exc`` is used only for logging.
"""
srv = find_server_for_file(file_path)
- if srv is None:
- return
- key = self._broken_key(srv, file_path)
+ key = self._broken_key(srv, file_path) if srv is not None else None
if key is None:
return
already_broken = key in self._broken
@@ -372,7 +350,7 @@ class LSPService:
pass
if not already_broken:
- eventlog.log_spawn_failed(srv.server_id, key[1], exc)
+ eventlog.log_spawn_failed(key[0], key[1], exc)
def shutdown(self) -> None:
"""Tear down all clients and stop the background loop."""
@@ -449,9 +427,7 @@ class LSPService:
return None
per_server_root = srv.resolve_root(file_path, ws_root)
if per_server_root is None:
- eventlog.log_disabled(
- srv.server_id, file_path, "exclude marker hit (server gated off)"
- )
+ eventlog.log_disabled(srv.server_id, file_path, "exclude marker hit (server gated off)")
return None
key = (srv.server_id, per_server_root)
@@ -470,52 +446,55 @@ class LSPService:
except Exception: # noqa: BLE001
return None
- loop = asyncio.get_running_loop()
- spawn_future: asyncio.Future = loop.create_future()
+ spawn_future: asyncio.Future = asyncio.get_running_loop().create_future()
with self._state_lock:
self._spawning[key] = spawn_future
try:
- ctx = ServerContext(
- workspace_root=per_server_root,
- install_strategy=self._install_strategy,
- binary_overrides=self._binary_overrides,
- env_overrides=self._env_overrides,
- init_overrides=self._init_overrides,
- )
- spec = srv.build_spawn(per_server_root, ctx)
- if spec is None:
- # Binary not locatable (auto-install off, manual-only, or
- # install failed) — surface once via the structured logger.
- eventlog.log_server_unavailable(srv.server_id, srv.server_id)
- self._broken.add(key)
- spawn_future.set_result(None)
- return None
- client = LSPClient(
- server_id=srv.server_id,
- workspace_root=spec.workspace_root,
- command=spec.command,
- env=spec.env,
- cwd=spec.cwd,
- initialization_options=spec.initialization_options,
- seed_diagnostics_on_first_push=spec.seed_diagnostics_on_first_push or srv.seed_first_push,
- )
- try:
- await client.start()
- except Exception as e: # noqa: BLE001
- eventlog.log_spawn_failed(srv.server_id, per_server_root, e)
+ client = await self._spawn_client(srv, per_server_root)
+ if client is not None:
+ with self._state_lock:
+ self._clients[key] = client
+ self._last_used[key] = time.time()
+ eventlog.log_active(srv.server_id, per_server_root)
+ else:
self._broken.add(key)
- spawn_future.set_result(None)
- return None
- with self._state_lock:
- self._clients[key] = client
- self._last_used[key] = time.time()
- eventlog.log_active(srv.server_id, per_server_root)
spawn_future.set_result(client)
return client
finally:
with self._state_lock:
self._spawning.pop(key, None)
+ async def _spawn_client(self, srv: ServerDef, root: str) -> Optional[LSPClient]:
+ """Resolve the binary and start a client; ``None`` (after logging) when either fails."""
+ ctx = ServerContext(
+ workspace_root=root,
+ install_strategy=self._install_strategy,
+ binary_overrides=self._binary_overrides,
+ env_overrides=self._env_overrides,
+ init_overrides=self._init_overrides,
+ )
+ spec = srv.build_spawn(root, ctx)
+ if spec is None:
+ # Binary not locatable (auto-install off, manual-only, or
+ # install failed) — surface once via the structured logger.
+ eventlog.log_server_unavailable(srv.server_id, srv.server_id)
+ return None
+ client = LSPClient(
+ server_id=srv.server_id,
+ workspace_root=spec.workspace_root,
+ command=spec.command,
+ env=spec.env,
+ cwd=spec.cwd,
+ initialization_options=spec.initialization_options,
+ seed_diagnostics_on_first_push=spec.seed_diagnostics_on_first_push or srv.seed_first_push,
+ )
+ try:
+ await client.start()
+ except Exception as e: # noqa: BLE001
+ eventlog.log_spawn_failed(srv.server_id, root, e)
+ return None
+ return client
+
async def _start_idle_reaper(self) -> None:
self._idle_reaper_task = asyncio.create_task(self._idle_reaper_loop())
@@ -542,27 +521,16 @@ class LSPService:
async def _reap_idle_once(self) -> None:
cutoff = time.time() - self._idle_timeout
with self._state_lock:
- idle_keys = [
- key
- for key in self._clients
- if self._last_used.get(key, 0) < cutoff
- ]
+ idle_keys = [key for key in self._clients if self._last_used.get(key, 0) < cutoff]
clients = [self._clients.pop(key) for key in idle_keys]
for key in idle_keys:
self._last_used.pop(key, None)
if clients:
- eventlog.log_reaped(
- [(c.server_id, c.workspace_root) for c in clients],
- self._idle_timeout,
- )
- await asyncio.gather(
- *(client.shutdown() for client in clients),
- return_exceptions=True,
- )
+ eventlog.log_reaped([(c.server_id, c.workspace_root) for c in clients], self._idle_timeout)
+ await asyncio.gather(*(client.shutdown() for client in clients), return_exceptions=True)
async def _shutdown_async(self) -> None:
- reaper = self._idle_reaper_task
- self._idle_reaper_task = None
+ reaper, self._idle_reaper_task = self._idle_reaper_task, None
if reaper is not None:
reaper.cancel()
await asyncio.gather(reaper, return_exceptions=True)
@@ -571,21 +539,13 @@ class LSPService:
self._clients.clear()
self._broken.clear()
self._last_used.clear()
- await asyncio.gather(
- *(c.shutdown() for c in clients),
- return_exceptions=True,
- )
+ await asyncio.gather(*(c.shutdown() for c in clients), return_exceptions=True)
def get_status(self) -> Dict[str, Any]:
"""Return a snapshot of the service for ``hermes lsp status``."""
with self._state_lock:
clients = [
- {
- "server_id": k[0],
- "workspace_root": k[1],
- "state": c.state,
- "running": c.is_running,
- }
+ {"server_id": k[0], "workspace_root": k[1], "state": c.state, "running": c.is_running}
for k, c in self._clients.items()
]
broken = list(self._broken)
diff --git a/agent/lsp/protocol.py b/agent/lsp/protocol.py
index 51616eeec04..9f800093a4b 100644
--- a/agent/lsp/protocol.py
+++ b/agent/lsp/protocol.py
@@ -16,7 +16,6 @@ logger = logging.getLogger("agent.lsp.protocol")
# LSP error codes we care about (spec 3.17 #errorCodes).
ERROR_CONTENT_MODIFIED = -32801
-ERROR_REQUEST_CANCELLED = -32800
ERROR_METHOD_NOT_FOUND = -32601
_MAX_HEADER_BYTES = 8192 # a well-behaved server fits in well under 200 bytes
@@ -40,16 +39,11 @@ class LSPRequestError(Exception):
def encode_message(obj: dict) -> bytes:
"""Encode an envelope as compact UTF-8 JSON with an exact Content-Length header."""
body = json.dumps(obj, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
- header = f"Content-Length: {len(body)}\r\n\r\n".encode("ascii")
- return header + body
+ return f"Content-Length: {len(body)}\r\n\r\n".encode("ascii") + body
-async def read_message(reader: asyncio.StreamReader) -> Optional[dict]:
- """Read one framed message.
-
- Returns ``None`` on clean EOF between messages (typical shutdown);
- raises :class:`LSPProtocolError` on malformed framing.
- """
+async def _read_headers(reader: asyncio.StreamReader) -> Optional[dict]:
+ """Read the header block; ``None`` on clean EOF before any header started."""
headers: dict = {}
header_bytes = 0
while True:
@@ -59,18 +53,14 @@ async def read_message(reader: asyncio.StreamReader) -> Optional[dict]:
# EOF before any header started is a clean close; mid-block is bad framing.
if not e.partial and not headers:
return None
- raise LSPProtocolError(
- f"unexpected EOF while reading LSP headers (partial={e.partial!r})"
- ) from e
+ raise LSPProtocolError(f"unexpected EOF while reading LSP headers (partial={e.partial!r})") from e
# Cap against a server streaming headers without ever emitting CRLF-CRLF.
header_bytes += len(line)
if header_bytes > _MAX_HEADER_BYTES:
- raise LSPProtocolError(
- "LSP header block exceeded 8 KiB without terminator"
- )
+ raise LSPProtocolError("LSP header block exceeded 8 KiB without terminator")
line = line[:-2] # strip CRLF
if not line:
- break # blank line ends header block
+ return headers # blank line ends header block
try:
key, _, value = line.decode("ascii").partition(":")
except UnicodeDecodeError as e:
@@ -79,6 +69,17 @@ async def read_message(reader: asyncio.StreamReader) -> Optional[dict]:
raise LSPProtocolError(f"malformed LSP header line: {line!r}")
headers[key.strip().lower()] = value.strip()
+
+async def read_message(reader: asyncio.StreamReader) -> Optional[dict]:
+ """Read one framed message.
+
+ Returns ``None`` on clean EOF between messages (typical shutdown);
+ raises :class:`LSPProtocolError` on malformed framing.
+ """
+ headers = await _read_headers(reader)
+ if headers is None:
+ return None
+
cl = headers.get("content-length")
if cl is None:
raise LSPProtocolError(f"LSP message missing Content-Length: {headers!r}")
@@ -92,9 +93,7 @@ async def read_message(reader: asyncio.StreamReader) -> Optional[dict]:
try:
body = await reader.readexactly(n)
except asyncio.IncompleteReadError as e:
- raise LSPProtocolError(
- f"truncated LSP body: expected {n} bytes, got {len(e.partial)}"
- ) from e
+ raise LSPProtocolError(f"truncated LSP body: expected {n} bytes, got {len(e.partial)}") from e
try:
return json.loads(body.decode("utf-8"))
@@ -146,14 +145,13 @@ def classify_message(msg: dict) -> Tuple[str, Any]:
return "request", msg["id"]
if has_id and ("result" in msg or "error" in msg):
return "response", msg["id"]
- if has_method and not has_id:
+ if has_method:
return "notification", msg["method"]
return "invalid", None
__all__ = [
"ERROR_CONTENT_MODIFIED",
- "ERROR_REQUEST_CANCELLED",
"ERROR_METHOD_NOT_FOUND",
"LSPProtocolError",
"LSPRequestError",
diff --git a/agent/lsp/range_shift.py b/agent/lsp/range_shift.py
index fa3aa85e89a..377aa0bbb2c 100644
--- a/agent/lsp/range_shift.py
+++ b/agent/lsp/range_shift.py
@@ -5,18 +5,18 @@ moves. The delta filter keys on ``(severity, code, source, message, range)``,
so without adjustment the shifted-but-identical diagnostics look brand-new.
We build a pre→post line map from ``difflib.SequenceMatcher.get_opcodes()``
and apply it to the baseline before the set-difference; diagnostics in a
-deleted region map to ``None`` and drop out (they genuinely no longer apply).
-
-Keeping range in the key (rather than content-only dedup) preserves the
-"new instance of an identical error at a different line" signal.
+deleted region map to ``None`` and drop out. Keeping range in the key
+preserves the "new instance of an identical error at a different line" signal.
"""
from __future__ import annotations
import difflib
from typing import Any, Callable, Dict, List, Optional
+_Shift = Callable[[int], Optional[int]]
+
-def build_line_shift(pre_text: str, post_text: str) -> Callable[[int], Optional[int]]:
+def build_line_shift(pre_text: str, post_text: str) -> _Shift:
"""Return ``shift(pre_line) -> post_line | None`` over 0-indexed lines (LSP convention).
``None`` means the line was deleted. One ``get_opcodes()`` call up front;
@@ -32,7 +32,7 @@ def build_line_shift(pre_text: str, post_text: str) -> Callable[[int], Optional[
opcodes = difflib.SequenceMatcher(a=pre_lines, b=post_lines, autojunk=False).get_opcodes()
def shift(line: int) -> Optional[int]:
- for tag, i1, i2, j1, j2 in opcodes:
+ for tag, i1, i2, j1, _j2 in opcodes:
if i1 <= line < i2:
# 'equal' maps by offset; 'delete'/'replace' lines have no
# post counterpart. 'insert' has i1 == i2 and can't match.
@@ -45,8 +45,7 @@ def build_line_shift(pre_text: str, post_text: str) -> Callable[[int], Optional[
return shift
-def shift_diagnostic_range(diag: Dict[str, Any],
- shift: Callable[[int], Optional[int]]) -> Optional[Dict[str, Any]]:
+def shift_diagnostic_range(diag: Dict[str, Any], shift: _Shift) -> Optional[Dict[str, Any]]:
"""Copy of ``diag`` with its line range remapped; ``None`` if the start line was deleted.
A multi-line diagnostic whose end straddles the deletion collapses to a
@@ -64,25 +63,19 @@ def shift_diagnostic_range(diag: Dict[str, Any],
if new_end_line is None:
new_end_line = new_start_line
- shifted = dict(diag)
- shifted["range"] = {
- "start": {"line": new_start_line, "character": int(start.get("character", 0))},
- "end": {"line": new_end_line, "character": int(end.get("character", 0))},
+ return {
+ **diag,
+ "range": {
+ "start": {"line": new_start_line, "character": int(start.get("character", 0))},
+ "end": {"line": new_end_line, "character": int(end.get("character", 0))},
+ },
}
- return shifted
-def shift_baseline(baseline: List[Dict[str, Any]],
- shift: Callable[[int], Optional[int]]) -> List[Dict[str, Any]]:
+def shift_baseline(baseline: List[Dict[str, Any]], shift: _Shift) -> List[Dict[str, Any]]:
"""Apply ``shift`` to every diagnostic in ``baseline``, dropping deleted entries."""
- out: List[Dict[str, Any]] = []
- for d in baseline:
- if not isinstance(d, dict):
- continue
- shifted = shift_diagnostic_range(d, shift)
- if shifted is not None:
- out.append(shifted)
- return out
+ shifted = (shift_diagnostic_range(d, shift) for d in baseline if isinstance(d, dict))
+ return [s for s in shifted if s is not None]
__all__ = ["build_line_shift", "shift_diagnostic_range", "shift_baseline"]
diff --git a/agent/lsp/reporter.py b/agent/lsp/reporter.py
index 468ae579c80..269f82832ef 100644
--- a/agent/lsp/reporter.py
+++ b/agent/lsp/reporter.py
@@ -36,23 +36,19 @@ def _sanitize_field(value: Any, *, limit: int) -> str:
return ""
raw = str(value).replace("\r", " ").replace("\n", " ")
raw = "".join(ch for ch in raw if ch == " " or ch.isprintable())
- raw = raw.strip()[:limit]
- return html.escape(raw, quote=False)
+ return html.escape(raw.strip()[:limit], quote=False)
def format_diagnostic(d: Dict[str, Any]) -> str:
"""One-line representation of a single diagnostic (fields sanitized)."""
sev = SEVERITY_NAMES.get(d.get("severity") or 1, "ERROR")
- rng = d.get("range") or {}
- start = rng.get("start") or {}
+ start = (d.get("range") or {}).get("start") or {}
line = int(start.get("line", 0)) + 1
col = int(start.get("character", 0)) + 1
msg = _sanitize_field(d.get("message"), limit=MAX_MESSAGE_CHARS)
code = _sanitize_field(d.get("code"), limit=MAX_CODE_CHARS)
- code_part = f" [{code}]" if code else ""
source = _sanitize_field(d.get("source"), limit=MAX_SOURCE_CHARS)
- source_part = f" ({source})" if source else ""
- return f"{sev} [{line}:{col}] {msg}{code_part}{source_part}"
+ return f"{sev} [{line}:{col}] {msg}{f' [{code}]' if code else ''}{f' ({source})' if source else ''}"
def report_for_file(
@@ -63,14 +59,11 @@ def report_for_file(
max_per_file: int = MAX_PER_FILE,
) -> str:
"""Build a ``<diagnostics file=...>`` block; ``""`` when nothing passes the severity filter."""
- if not diagnostics:
- return ""
- filtered = [d for d in diagnostics if (d.get("severity") or 1) in severities]
+ filtered = [d for d in diagnostics or [] if (d.get("severity") or 1) in severities]
if not filtered:
return ""
- limited = filtered[:max_per_file]
- extra = len(filtered) - len(limited)
- body = "\n".join(format_diagnostic(d) for d in limited)
+ body = "\n".join(format_diagnostic(d) for d in filtered[:max_per_file])
+ extra = len(filtered) - max_per_file
if extra > 0:
body += f"\n... and {extra} more"
# quote=True also escapes ``"`` so a crafted file name can't break out of
diff --git a/agent/lsp/servers.py b/agent/lsp/servers.py
index 97341b09369..51f90d36c41 100644
--- a/agent/lsp/servers.py
+++ b/agent/lsp/servers.py
@@ -18,82 +18,37 @@ from agent.lsp.workspace import nearest_root
logger = logging.getLogger("agent.lsp.servers")
-# LSP languageId for ``textDocument/didOpen``. A few servers
-# (typescript-language-server, vue-language-server) refuse wrong IDs.
-LANGUAGE_BY_EXT: Dict[str, str] = {
- ".py": "python",
- ".pyi": "python",
- ".ts": "typescript",
- ".tsx": "typescriptreact",
- ".js": "javascript",
- ".jsx": "javascriptreact",
- ".mjs": "javascript",
- ".cjs": "javascript",
- ".mts": "typescript",
- ".cts": "typescript",
- ".vue": "vue",
- ".svelte": "svelte",
- ".astro": "astro",
- ".go": "go",
- ".rs": "rust",
- ".rb": "ruby",
- ".rake": "ruby",
- ".gemspec": "ruby",
- ".ru": "ruby",
- ".c": "c",
- ".h": "c",
- ".cc": "cpp",
- ".cpp": "cpp",
- ".cxx": "cpp",
- ".hh": "cpp",
- ".hpp": "cpp",
- ".hxx": "cpp",
- ".cs": "csharp",
- ".csx": "csharp",
- ".fs": "fsharp",
- ".fsi": "fsharp",
- ".fsx": "fsharp",
- ".swift": "swift",
- ".java": "java",
- ".kt": "kotlin",
- ".kts": "kotlin",
- ".yaml": "yaml",
- ".yml": "yaml",
- ".json": "json",
- ".jsonc": "jsonc",
- ".lua": "lua",
- ".php": "php",
- ".prisma": "prisma",
- ".dart": "dart",
- ".ml": "ocaml",
- ".mli": "ocaml",
- ".sh": "shellscript",
- ".bash": "shellscript",
- ".zsh": "shellscript",
- ".tf": "terraform",
- ".tfvars": "terraform",
- ".tex": "latex",
- ".bib": "bibtex",
- ".gleam": "gleam",
- ".clj": "clojure",
- ".cljs": "clojurescript",
- ".cljc": "clojure",
- ".edn": "clojure",
- ".nix": "nix",
- ".typ": "typst",
- ".typc": "typst",
- ".hs": "haskell",
- ".lhs": "haskell",
- ".jl": "julia",
- ".ex": "elixir",
- ".exs": "elixir",
- ".zig": "zig",
- ".zon": "zig",
- ".dockerfile": "dockerfile",
- ".ps1": "powershell",
- ".psm1": "powershell",
- ".psd1": "powershell",
+# LSP languageId for ``textDocument/didOpen``, as language → extensions. A few
+# servers (typescript-language-server, vue-language-server) refuse wrong IDs.
+_EXTS_BY_LANGUAGE: Dict[str, Sequence[str]] = {
+ "python": (".py", ".pyi"),
+ "typescript": (".ts", ".mts", ".cts"),
+ "typescriptreact": (".tsx",),
+ "javascript": (".js", ".mjs", ".cjs"),
+ "javascriptreact": (".jsx",),
+ "vue": (".vue",), "svelte": (".svelte",), "astro": (".astro",),
+ "go": (".go",), "rust": (".rs",),
+ "ruby": (".rb", ".rake", ".gemspec", ".ru"),
+ "c": (".c", ".h"),
+ "cpp": (".cc", ".cpp", ".cxx", ".hh", ".hpp", ".hxx"),
+ "csharp": (".cs", ".csx"), "fsharp": (".fs", ".fsi", ".fsx"),
+ "swift": (".swift",), "java": (".java",), "kotlin": (".kt", ".kts"),
+ "yaml": (".yaml", ".yml"), "json": (".json",), "jsonc": (".jsonc",),
+ "lua": (".lua",), "php": (".php",), "prisma": (".prisma",), "dart": (".dart",),
+ "ocaml": (".ml", ".mli"),
+ "shellscript": (".sh", ".bash", ".zsh"),
+ "terraform": (".tf", ".tfvars"),
+ "latex": (".tex",), "bibtex": (".bib",), "gleam": (".gleam",),
+ "clojure": (".clj", ".cljc", ".edn"), "clojurescript": (".cljs",),
+ "nix": (".nix",), "typst": (".typ", ".typc"), "haskell": (".hs", ".lhs"),
+ "julia": (".jl",), "elixir": (".ex", ".exs"), "zig": (".zig", ".zon"),
+ "dockerfile": (".dockerfile",),
+ "powershell": (".ps1", ".psm1", ".psd1"),
}
+LANGUAGE_BY_EXT: Dict[str, str] = {ext: lang for lang, exts in _EXTS_BY_LANGUAGE.items() for ext in exts}
+
+_SpawnFn = Callable[[str, "ServerContext"], Optional["SpawnSpec"]]
+_RootFn = Callable[[str, str], Optional[str]]
@dataclass
@@ -119,8 +74,8 @@ class ServerDef:
server_id: str
extensions: Tuple[str, ...]
- resolve_root: Callable[[str, str], Optional[str]]
- build_spawn: Callable[[str, "ServerContext"], Optional[SpawnSpec]]
+ resolve_root: _RootFn
+ build_spawn: _SpawnFn
seed_first_push: bool = False
description: str = ""
@@ -148,43 +103,30 @@ class ServerContext:
def _file_ext_or_basename(path: str) -> str:
"""Lower-cased extension, or the full basename for extensionless files (``Dockerfile``)."""
base = os.path.basename(path)
- _root, ext = os.path.splitext(base)
+ ext = os.path.splitext(base)[1]
return ext.lower() if ext else base
def _which(*names: str) -> Optional[str]:
"""Return the full path of the first command found on PATH."""
- for n in names:
- path = shutil.which(n)
- if path:
- return path
- return None
+ return next((p for n in names if (p := shutil.which(n))), None)
def _root_or_workspace(file_path: str, workspace: str, markers: Sequence[str], excludes: Sequence[str] = ()) -> Optional[str]:
"""``nearest_root`` with workspace fallback; ``None`` iff an exclude marker hit."""
ceiling = os.path.dirname(workspace) if workspace else None
found = nearest_root(file_path, markers, excludes=excludes, ceiling=ceiling)
- if found is None and excludes:
- # None is ambiguous with excludes configured: re-check without them —
- # a hit now means the exclude fired (gated off), else fall back.
- if nearest_root(file_path, markers, ceiling=ceiling) is not None:
- return None
- return workspace
+ if found is None and excludes and nearest_root(file_path, markers, ceiling=ceiling) is not None:
+ # None is ambiguous with excludes configured: a hit without them means
+ # the exclude fired (gated off); otherwise fall back to the workspace.
+ return None
return found or workspace
-def _resolve_override(ctx: ServerContext, server_id: str) -> Optional[str]:
- """User can pin a binary path in config."""
- override = ctx.binary_overrides.get(server_id)
- if override and override[0] and os.path.exists(override[0]):
- return override[0]
- return None
-
-
def _find_binary(ctx: ServerContext, server_id: str, which: Sequence[str], install_pkg: Optional[str]) -> Optional[str]:
- """Override → PATH → (optional) auto-install; ``None`` when nothing resolves."""
- bin_path = _resolve_override(ctx, server_id) or _which(*which)
+ """Config override → PATH → (optional) auto-install; ``None`` when nothing resolves."""
+ override = ctx.binary_overrides.get(server_id)
+ bin_path = override[0] if override and override[0] and os.path.exists(override[0]) else _which(*which)
if bin_path is None and install_pkg is not None:
from agent.lsp.install import try_install
bin_path = try_install(install_pkg, ctx.install_strategy)
@@ -193,11 +135,7 @@ def _find_binary(ctx: ServerContext, server_id: str, which: Sequence[str], insta
def _make_spec(root: str, ctx: ServerContext, server_id: str, command: List[str],
base_init: Optional[Dict[str, Any]] = None, seed: bool = False) -> SpawnSpec:
- if base_init is None:
- init = ctx.init_overrides.get(server_id, {})
- else:
- init = dict(base_init)
- init.update(ctx.init_overrides.get(server_id, {}))
+ init = ctx.init_overrides.get(server_id, {}) if base_init is None else {**base_init, **ctx.init_overrides.get(server_id, {})}
return SpawnSpec(
command=command,
workspace_root=root,
@@ -210,7 +148,7 @@ def _make_spec(root: str, ctx: ServerContext, server_id: str, command: List[str]
def _simple_spawn(server_id: str, which: Sequence[str], args: Sequence[str] = (),
install_pkg: Optional[str] = None, base_init: Optional[Dict[str, Any]] = None,
- seed: bool = False) -> Callable[[str, ServerContext], Optional[SpawnSpec]]:
+ seed: bool = False) -> _SpawnFn:
"""Build a spawn function for the common single-binary server shape."""
def build(root: str, ctx: ServerContext) -> Optional[SpawnSpec]:
bin_path = _find_binary(ctx, server_id, which, install_pkg)
@@ -220,7 +158,7 @@ def _simple_spawn(server_id: str, which: Sequence[str], args: Sequence[str] = ()
return build
-def _markers_root(markers: Optional[Sequence[str]], excludes: Sequence[str] = ()) -> Callable[[str, str], Optional[str]]:
+def _markers_root(markers: Optional[Sequence[str]], excludes: Sequence[str] = ()) -> _RootFn:
"""Root resolver over marker files; ``None`` markers means "always the workspace root"."""
if markers is None:
return lambda fp, ws: ws
@@ -241,18 +179,14 @@ def _spawn_pyright(root: str, ctx: ServerContext) -> Optional[SpawnSpec]:
sibling = os.path.join(os.path.dirname(bin_path), "pyright-langserver")
if os.path.exists(sibling):
bin_path = sibling
- init: Dict[str, Any] = {}
# Point pyright at the project venv; its default "python on PATH" rarely is.
py = _detect_python(root)
- if py:
- init["python"] = {"pythonPath": py}
+ init: Dict[str, Any] = {"python": {"pythonPath": py}} if py else {}
return _make_spec(root, ctx, "pyright", [bin_path, "--stdio"], init)
def _detect_python(root: str) -> Optional[str]:
- candidates = []
- if os.environ.get("VIRTUAL_ENV"):
- candidates.append(os.environ["VIRTUAL_ENV"])
+ candidates = [v for v in (os.environ.get("VIRTUAL_ENV"),) if v]
candidates.extend([os.path.join(root, ".venv"), os.path.join(root, "venv")])
for v in candidates:
for sub in ("bin/python", "bin/python3", "Scripts/python.exe"):
@@ -262,7 +196,13 @@ def _detect_python(root: str) -> Optional[str]:
return None
-_BASH_SHELLCHECK_WARNED = False
+_warned_once: set = set()
+
+
+def _warn_once(key: str, message: str) -> None:
+ if key not in _warned_once:
+ _warned_once.add(key)
+ logger.warning(message)
def _spawn_bash_ls(root: str, ctx: ServerContext) -> Optional[SpawnSpec]:
@@ -271,20 +211,16 @@ def _spawn_bash_ls(root: str, ctx: ServerContext) -> Optional[SpawnSpec]:
return None
# bash-language-server delegates diagnostics to shellcheck; without it the
# server runs but never reports anything. Warn once so the gap is visible.
- global _BASH_SHELLCHECK_WARNED
- if not _BASH_SHELLCHECK_WARNED and _which("shellcheck") is None:
- _BASH_SHELLCHECK_WARNED = True
- logger.warning(
+ if _which("shellcheck") is None:
+ _warn_once(
+ "shellcheck",
"bash-language-server: shellcheck not found on PATH — "
"diagnostics will be empty until shellcheck is installed "
- "(apt: shellcheck, brew: shellcheck, scoop: shellcheck)."
+ "(apt: shellcheck, brew: shellcheck, scoop: shellcheck).",
)
return _make_spec(root, ctx, "bash-language-server", [bin_path, "start"])
-_PSES_BUNDLE_WARNED = False
-
-
def _find_pses_bundle(ctx: ServerContext) -> Optional[str]:
"""Locate the PowerShellEditorServices bundle dir (release zip, manual install).
@@ -292,23 +228,17 @@ def _find_pses_bundle(ctx: ServerContext) -> Optional[str]:
``init_overrides["powershell"]["bundlePath"]``, ``PSES_BUNDLE_PATH`` env,
then ``<HERMES_HOME>/lsp/PowerShellEditorServices``.
"""
- candidates: List[str] = []
- override = ctx.binary_overrides.get("powershell")
- if override and override[0]:
- candidates.append(override[0])
- init = ctx.init_overrides.get("powershell", {})
- if isinstance(init, dict) and init.get("bundlePath"):
- candidates.append(str(init["bundlePath"]))
- env_path = os.environ.get("PSES_BUNDLE_PATH")
- if env_path:
- candidates.append(env_path)
from hermes_constants import get_hermes_home
- candidates.append(os.path.join(str(get_hermes_home()), "lsp", "PowerShellEditorServices"))
-
- for cand in candidates:
- if not cand:
- continue
+ override = ctx.binary_overrides.get("powershell")
+ init = ctx.init_overrides.get("powershell", {})
+ candidates = [
+ override[0] if override else None,
+ str(init["bundlePath"]) if isinstance(init, dict) and init.get("bundlePath") else None,
+ os.environ.get("PSES_BUNDLE_PATH"),
+ os.path.join(str(get_hermes_home()), "lsp", "PowerShellEditorServices"),
+ ]
+ for cand in filter(None, candidates):
# Accept either the bundle root or the inner module dir.
if os.path.isfile(os.path.join(cand, "PowerShellEditorServices", "Start-EditorServices.ps1")):
return cand
@@ -324,27 +254,24 @@ def _spawn_powershell_es(root: str, ctx: ServerContext) -> Optional[SpawnSpec]:
return None
bundle = _find_pses_bundle(ctx)
if bundle is None:
- global _PSES_BUNDLE_WARNED
- if not _PSES_BUNDLE_WARNED:
- _PSES_BUNDLE_WARNED = True
- logger.warning(
- "powershell: pwsh found but the PowerShellEditorServices "
- "bundle is missing. Download the release zip from "
- "https://github.com/PowerShell/PowerShellEditorServices/releases, "
- "extract it, and either set lsp.servers.powershell.command "
- "to the bundle path or unzip it to "
- "<HERMES_HOME>/lsp/PowerShellEditorServices."
- )
+ _warn_once(
+ "pses-bundle",
+ "powershell: pwsh found but the PowerShellEditorServices "
+ "bundle is missing. Download the release zip from "
+ "https://github.com/PowerShell/PowerShellEditorServices/releases, "
+ "extract it, and either set lsp.servers.powershell.command "
+ "to the bundle path or unzip it to "
+ "<HERMES_HOME>/lsp/PowerShellEditorServices.",
+ )
return None
start_script = os.path.join(bundle, "PowerShellEditorServices", "Start-EditorServices.ps1")
# PSES writes connection info to the session details file on startup.
- session_path = os.path.join(hermes_lsp_session_dir(), f"pses-session-{os.getpid()}.json")
- log_path = os.path.join(hermes_lsp_session_dir(), "pses.log")
+ session_dir = hermes_lsp_session_dir()
inner = (
f"& '{start_script}' "
f"-BundledModulesPath '{bundle}' "
- f"-LogPath '{log_path}' "
- f"-SessionDetailsPath '{session_path}' "
+ f"-LogPath '{os.path.join(session_dir, 'pses.log')}' "
+ f"-SessionDetailsPath '{os.path.join(session_dir, f'pses-session-{os.getpid()}.json')}' "
f"-FeatureFlags @() -AdditionalModules @() "
f"-HostName Hermes -HostProfileId hermes -HostVersion 1.0.0 "
f"-Stdio -LogLevel Normal"
@@ -354,11 +281,7 @@ def _spawn_powershell_es(root: str, ctx: ServerContext) -> Optional[SpawnSpec]:
workspace_root=root,
cwd=root,
env=ctx.env_overrides.get("powershell", {}),
- initialization_options={
- k: v
- for k, v in ctx.init_overrides.get("powershell", {}).items()
- if k != "bundlePath"
- },
+ initialization_options={k: v for k, v in ctx.init_overrides.get("powershell", {}).items() if k != "bundlePath"},
)
@@ -382,8 +305,7 @@ _root_typescript = _markers_root(_JS_MARKERS, _DENO_EXCLUDES)
def _server(server_id: str, extensions: Tuple[str, ...], description: str, *,
markers: Optional[Sequence[str]] = None, excludes: Sequence[str] = (),
- resolve_root: Optional[Callable[[str, str], Optional[str]]] = None,
- build_spawn: Optional[Callable[[str, ServerContext], Optional[SpawnSpec]]] = None,
+ resolve_root: Optional[_RootFn] = None, build_spawn: Optional[_SpawnFn] = None,
which: Sequence[str] = (), args: Sequence[str] = (), install_pkg: Optional[str] = None,
base_init: Optional[Dict[str, Any]] = None, seed: bool = False) -> ServerDef:
return ServerDef(
@@ -458,10 +380,7 @@ SERVERS: List[ServerDef] = [
def find_server_for_file(file_path: str) -> Optional[ServerDef]:
"""Return the registry entry that handles ``file_path``, or None."""
- for srv in SERVERS:
- if srv.matches(file_path):
- return srv
- return None
+ return next((srv for srv in SERVERS if srv.matches(file_path)), None)
def language_id_for(path: str) -> str: