Skip to content

The agent that grows with you

refactor(agent/lsp): table-driven lsp argparse tree, compact install/eventlog/protocol helpers

Teknium52271332db8a
diff --git a/agent/lsp/__init__.py b/agent/lsp/__init__.py
index 33cf08d5c52..5eb01ac707c 100644
--- a/agent/lsp/__init__.py
+++ b/agent/lsp/__init__.py
@@ -1,13 +1,10 @@
"""Language Server Protocol (LSP) integration for Hermes Agent.
-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
-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.
-``get_service()`` returns the singleton :class:`LSPService` (or ``None`` when
-disabled); wiring: :func:`tools.file_operations.FileOperations._check_lint_delta`.
+Real language servers (pyright, gopls, ...) run as subprocesses and their
+``publishDiagnostics`` feed the post-write lint delta filter of ``write_file`` /
+``patch`` (wiring: ``FileOperations._check_lint_delta``). LSP is **gated on git
+workspace detection** so user-home cwd's (e.g. Telegram gateway chats) never
+spawn daemons; ``get_service()`` returns the singleton or ``None`` when disabled.
"""
from __future__ import annotations
@@ -30,12 +27,11 @@ def _active(svc: Optional[LSPService]) -> Optional[LSPService]:
def get_service() -> Optional[LSPService]:
- """Return the process-wide LSP service singleton, or None when disabled.
+ """Return the lazily created process-wide LSP service singleton, or None when disabled.
- Created lazily on first call. Also registers an :mod:`atexit` hook so a
- clean exit tears down spawned language servers: without it every
- ``hermes chat`` exit leaks pyright processes for a few seconds while
- their stdout buffers drain. (SIGKILL/os._exit skip atexit — fine, the
+ Also registers an :mod:`atexit` hook so a clean exit tears down spawned servers:
+ without it every ``hermes chat`` exit leaks pyright processes for a few seconds
+ while their stdout buffers drain. (SIGKILL/os._exit skip atexit — fine, the
kernel reaps the stateless servers with their parent.)
"""
global _service, _atexit_registered
diff --git a/agent/lsp/cli.py b/agent/lsp/cli.py
index 8c7bfb24c4e..28484ff2a71 100644
--- a/agent/lsp/cli.py
+++ b/agent/lsp/cli.py
@@ -9,44 +9,32 @@ import sys
_STATUS_MARKERS = {"installed": "✓", "missing": "·", "manual-only": "?"}
+# (name, parser kwargs, optional (flag, add_argument kwargs)) — order defines the help listing.
+_SUBCOMMANDS = [
+ ("status", {"help": "Show LSP service status"},
+ ("--json", {"action": "store_true", "help": "Emit machine-readable JSON"})),
+ ("list", {"help": "List supported language servers"},
+ ("--installed-only", {"action": "store_true", "help": "Only show servers whose binary is currently available"})),
+ ("install", {"help": "Install a server binary"}, ("server", {"help": "Server id (e.g. pyright, gopls)"})),
+ ("install-all", {"help": "Install every server with a known auto-install recipe"},
+ ("--include-manual", {"action": "store_true", "help": "Even attempt servers marked manual-install (best effort)"})),
+ ("restart", {"help": "Tear down running LSP clients (next edit re-spawns)"}, None),
+ ("which", {"help": "Print binary path for a server"}, ("server", {"help": "Server id"})),
+]
+
def register_subparser(subparsers: argparse._SubParsersAction) -> None:
"""Wire the ``hermes lsp`` subcommand tree into the main argparse."""
parser = subparsers.add_parser(
"lsp",
help="Language Server Protocol management",
- description=(
- "Manage the LSP layer that powers post-write semantic "
- "diagnostics in write_file/patch."
- ),
+ description="Manage the LSP layer that powers post-write semantic diagnostics in write_file/patch.",
)
sub = parser.add_subparsers(dest="lsp_command")
-
- sub.add_parser("status", help="Show LSP service status").add_argument(
- "--json", action="store_true", help="Emit machine-readable JSON"
- )
- 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.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",
- ).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.add_parser("which", help="Print binary path for a server").add_argument("server", help="Server id")
-
+ for name, kwargs, arg in _SUBCOMMANDS:
+ p = sub.add_parser(name, **kwargs)
+ if arg is not None:
+ p.add_argument(arg[0], **arg[1])
parser.set_defaults(func=run_lsp_command)
@@ -97,17 +85,12 @@ def _cmd_status(emit_json: bool) -> int:
f" wait_timeout: {info.get('wait_timeout')}s",
f" install_strategy:{info.get('install_strategy')}"]
clients = info.get("clients") or []
- if clients:
- out.append(f" active clients: {len(clients)}")
- 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")
+ out.append(f" active clients: {len(clients)}" if clients else " active clients: none")
+ out += [f" - {c['server_id']:20s} state={c['state']:10s} root={c['workspace_root']}" for c in clients]
broken = info.get("broken") or []
if broken:
out.append(f" broken pairs: {len(broken)}")
- out.extend(f" - {b}" for b in broken)
+ out += [f" - {b}" for b in broken]
disabled = info.get("disabled_servers") or []
if disabled:
out.append(f" disabled in cfg: {', '.join(disabled)}")
@@ -115,9 +98,8 @@ 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.extend(["", "Backend warnings", "================"])
- out.extend(f" ! {line}" for line in backend_warnings)
- out.extend(["", "Registered Servers", "=================="])
+ out += ["", "Backend warnings", "================"] + [f" ! {line}" for line in backend_warnings]
+ out += ["", "Registered Servers", "=================="]
for s in SERVERS:
status = detect_status(_recipe_pkg_for(s.server_id))
ext_summary = ", ".join(list(s.extensions)[:5])
@@ -176,11 +158,8 @@ def _cmd_install_all(include_manual: bool) -> int:
sys.stdout.write(f" installing {s.server_id} (pkg={pkg}) ... ")
sys.stdout.flush()
path = try_install(pkg, "auto")
- if path:
- sys.stdout.write(f"ok ({path})\n")
- else:
- sys.stdout.write("FAILED\n")
- rc = 1
+ sys.stdout.write(f"ok ({path})\n" if path else "FAILED\n")
+ rc = rc if path else 1
return rc
@@ -222,9 +201,6 @@ def _backend_warnings() -> list:
import shutil
from agent.lsp.install import _existing_binary
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 ["bash-language-server is installed but shellcheck is missing — "
+ "diagnostics will be empty (apt: shellcheck, brew: shellcheck, scoop: shellcheck)."]
return []
diff --git a/agent/lsp/client.py b/agent/lsp/client.py
index 29d1cc030d1..86c62315692 100644
--- a/agent/lsp/client.py
+++ b/agent/lsp/client.py
@@ -75,8 +75,7 @@ def file_uri(path: str) -> str:
if os.name == "nt":
# ``C:\foo`` → ``file:///C:/foo``: the drive letter must be a path component.
abs_path = abs_path.replace("\\", "/")
- if not abs_path.startswith("/"):
- abs_path = "/" + abs_path
+ abs_path = abs_path if abs_path.startswith("/") else "/" + abs_path
return "file://" + quote(abs_path, safe="/:")
@@ -130,11 +129,8 @@ class _DocState:
class LSPClient:
- """Async LSP client tied to one server process and one workspace root.
-
- Lifecycle: ``start()`` → ``open_file()`` → ``wait_for_diagnostics()`` →
- ``diagnostics_for()`` → ``shutdown()``.
- """
+ """One server process + one workspace root. ``start()`` → ``open_file()`` → ``wait_for_diagnostics()`` →
+ ``diagnostics_for()`` → ``shutdown()``."""
def __init__(self, *, server_id: str, workspace_root: str, command: List[str],
env: Optional[Dict[str, str]] = None, cwd: Optional[str] = None,
@@ -270,8 +266,7 @@ class LSPClient:
unexpected_close = not self._stopping and self._state in _LIVE_STATES
if unexpected_close:
self._state = "error"
- # Fail pending requests fast.
- for fut in list(self._pending.values()):
+ for fut in list(self._pending.values()): # fail pending requests fast
if not fut.done():
fut.set_exception(LSPProtocolError("server connection closed"))
self._pending.clear()
@@ -398,11 +393,11 @@ class LSPClient:
fut = self._pending.get(req_id)
if fut is None or fut.done():
return
- if "error" in msg:
- err = msg["error"] or {}
- fut.set_exception(LSPRequestError(int(err.get("code", -32000)), str(err.get("message", "unknown")), err.get("data")))
- else:
+ if "error" not in msg:
fut.set_result(msg.get("result"))
+ return
+ err = msg["error"] or {}
+ fut.set_exception(LSPRequestError(int(err.get("code", -32000)), str(err.get("message", "unknown")), err.get("data")))
async def _dispatch_request(self, req_id: Any, msg: dict) -> None:
method = msg.get("method", "")
diff --git a/agent/lsp/eventlog.py b/agent/lsp/eventlog.py
index 4ab8363d891..b105bec9aaa 100644
--- a/agent/lsp/eventlog.py
+++ b/agent/lsp/eventlog.py
@@ -37,9 +37,7 @@ def _short_path(file_path: str) -> str:
rel = os.path.relpath(file_path)
except ValueError:
return file_path
- if rel.startswith(".." + os.sep) or rel == "..":
- return file_path
- return rel
+ return file_path if rel.startswith(".." + os.sep) or rel == ".." else rel
def _emit(server_id: str, level: int, message: str) -> None:
@@ -51,10 +49,7 @@ def _emit_once(bucket: set, key: Tuple, server_id: str, level: int, first: str,
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)
+ _emit(server_id, level if is_first else logging.DEBUG, first if is_first else repeat)
# ---- Public event helpers — call these from the LSP layer ----
@@ -72,10 +67,8 @@ def log_disabled(server_id: str, file_path: str, reason: str) -> None:
def log_active(server_id: str, workspace_root: str) -> None:
"""A client started for (server_id, workspace_root). INFO once per pair, DEBUG thereafter."""
- _emit_once(
- _announced_active, (server_id, workspace_root), server_id, logging.INFO,
- f"active for {workspace_root}", f"reused client for {workspace_root}",
- )
+ _emit_once(_announced_active, (server_id, workspace_root), server_id, logging.INFO,
+ f"active for {workspace_root}", f"reused client for {workspace_root}")
def log_diagnostics(server_id: str, file_path: str, count: int) -> None:
@@ -121,8 +114,7 @@ def log_reaped(keys: List[Tuple[str, str]], idle_timeout: float) -> None:
re-announces at INFO instead of a misleading DEBUG "reused client".
"""
with _announce_lock:
- for key in keys:
- _announced_active.discard(key)
+ _announced_active.difference_update(keys)
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}")
diff --git a/agent/lsp/install.py b/agent/lsp/install.py
index af6c04f4d72..e83df3ace17 100644
--- a/agent/lsp/install.py
+++ b/agent/lsp/install.py
@@ -62,7 +62,6 @@ INSTALL_RECIPES: Dict[str, Dict[str, Any]] = {
"powershell": _manual("pwsh"),
}
-
_install_locks: Dict[str, threading.Lock] = {}
_install_results: Dict[str, Optional[str]] = {}
_install_lock_meta = threading.Lock()
@@ -83,26 +82,21 @@ def hermes_lsp_bin_dir() -> Path:
def _native_binary_candidates(base: Path) -> list[Path]:
- """Return platform-native executable candidates for a staged binary."""
+ """Return platform-native executable candidates for a staged binary (``base`` plus Windows wrappers)."""
candidates = [base]
if _is_windows():
- existing = {str(base).lower()}
+ seen = {str(base).lower()}
for suffix in _WINDOWS_WRAPPER_SUFFIXES:
candidate = Path(str(base) + suffix)
- key = str(candidate).lower()
- if key not in existing:
+ if str(candidate).lower() not in seen:
candidates.append(candidate)
- existing.add(key)
+ seen.add(str(candidate).lower())
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
+ return next((c for base in bases for c in _native_binary_candidates(base) if c.exists()), None)
def _existing_binary(name: str) -> Optional[str]:
@@ -114,24 +108,19 @@ def _existing_binary(name: str) -> Optional[str]:
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:
- return _install_locks.setdefault(pkg, threading.Lock())
-
-
def try_install(pkg: str, strategy: str = "auto") -> Optional[str]:
"""Try to install ``pkg``; return the binary path or ``None``.
- Only ``"auto"`` installs; ``"manual"``/``"off"`` just probe for an
- existing binary. Results are cached per package and concurrent calls
- are serialized.
+ Only ``"auto"`` installs; ``"manual"``/``"off"`` just probe for an existing
+ binary. Results are cached per package and concurrent calls are serialized.
"""
if strategy != "auto":
return _existing_binary(INSTALL_RECIPES.get(pkg, {}).get("bin", pkg))
-
if pkg in _install_results:
return _install_results[pkg]
- with _get_lock(pkg):
+ with _install_lock_meta:
+ lock = _install_locks.setdefault(pkg, threading.Lock())
+ with lock:
if pkg not in _install_results:
_install_results[pkg] = _do_install(pkg)
return _install_results[pkg]
@@ -140,9 +129,7 @@ def try_install(pkg: str, strategy: str = "auto") -> Optional[str]:
def _do_install(pkg: str) -> Optional[str]:
recipe = INSTALL_RECIPES.get(pkg)
if recipe is None:
- # Not in our registry — best-effort: just probe PATH.
- return shutil.which(pkg)
-
+ return shutil.which(pkg) # not in our registry — best-effort: just probe PATH
strategy = recipe.get("strategy", "manual")
bin_name = recipe.get("bin", pkg)
existing = _existing_binary(bin_name)
@@ -151,7 +138,6 @@ def _do_install(pkg: str) -> Optional[str]:
if strategy == "manual":
logger.debug("[install] %s requires manual install (recipe=%s)", pkg, recipe)
return None
-
installer = _INSTALLERS.get(strategy)
if installer is None:
logger.warning("[install] unknown strategy %r for %s", strategy, pkg)
@@ -218,9 +204,8 @@ 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 = {**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):
+ if not _run_installer("go", pkg, [go, "install", pkg], timeout=600, env={**os.environ, "GOBIN": str(staging)}):
return None
bin_path = (staging / bin_name).with_suffix(".exe") if _is_windows() else staging / bin_name
if bin_path.exists():
@@ -263,9 +248,7 @@ def detect_status(pkg: str) -> str:
recipe = INSTALL_RECIPES.get(pkg)
if _existing_binary(recipe.get("bin", pkg) if recipe else pkg):
return "installed"
- if recipe and recipe.get("strategy") == "manual":
- return "manual-only"
- return "missing"
+ return "manual-only" if recipe and recipe.get("strategy") == "manual" else "missing"
__all__ = ["INSTALL_RECIPES", "try_install", "detect_status", "hermes_lsp_bin_dir"]
diff --git a/agent/lsp/protocol.py b/agent/lsp/protocol.py
index ab98aecabde..faaca6b194d 100644
--- a/agent/lsp/protocol.py
+++ b/agent/lsp/protocol.py
@@ -31,9 +31,7 @@ class LSPRequestError(Exception):
def __init__(self, code: int, message: str, data: Any = None) -> None:
super().__init__(f"LSP error {code}: {message}")
- self.code = code
- self.message = message
- self.data = data
+ self.code, self.message, self.data = code, message, data
def encode_message(obj: dict) -> bytes:
@@ -129,15 +127,11 @@ def classify_message(msg: dict) -> Tuple[str, Any]:
"""
if not isinstance(msg, dict) or msg.get("jsonrpc") != "2.0":
return "invalid", None
- has_id = "id" in msg
- has_method = "method" in msg
- if has_id and has_method:
- return "request", msg["id"]
- if has_id and ("result" in msg or "error" in msg):
- return "response", msg["id"]
- if has_method:
- return "notification", msg["method"]
- return "invalid", None
+ if "id" in msg:
+ if "method" in msg:
+ return "request", msg["id"]
+ return ("response", msg["id"]) if ("result" in msg or "error" in msg) else ("invalid", None)
+ return ("notification", msg["method"]) if "method" in msg else ("invalid", None)
__all__ = [
diff --git a/agent/lsp/range_shift.py b/agent/lsp/range_shift.py
index 377aa0bbb2c..cdcd5ccc514 100644
--- a/agent/lsp/range_shift.py
+++ b/agent/lsp/range_shift.py
@@ -1,12 +1,11 @@
"""Diff-aware line-shift map for cross-edit LSP delta filtering.
-When an edit inserts or deletes lines, every diagnostic below the edit point
-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. Keeping range in the key
-preserves the "new instance of an identical error at a different line" signal.
+An edit that inserts/deletes lines moves every diagnostic below it, and the delta
+filter keys on ``(severity, code, source, message, range)`` — so shifted-but-identical
+diagnostics would 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.
+Keeping range in the key preserves the "same error at a new line" signal.
"""
from __future__ import annotations
@@ -24,10 +23,8 @@ def build_line_shift(pre_text: str, post_text: str) -> _Shift:
"""
pre_lines = pre_text.splitlines() if pre_text else []
post_lines = post_text.splitlines() if post_text else []
-
if pre_lines == post_lines:
return lambda line: line
-
# Opcodes are (tag, i1, i2, j1, j2): i-range in pre, j-range in post.
opcodes = difflib.SequenceMatcher(a=pre_lines, b=post_lines, autojunk=False).get_opcodes()
@@ -54,7 +51,6 @@ def shift_diagnostic_range(diag: Dict[str, Any], shift: _Shift) -> Optional[Dict
rng = diag.get("range") or {}
start = rng.get("start") or {}
end = rng.get("end") or {}
-
pre_start_line = int(start.get("line", 0))
new_start_line = shift(pre_start_line)
if new_start_line is None:
@@ -62,7 +58,6 @@ def shift_diagnostic_range(diag: Dict[str, Any], shift: _Shift) -> Optional[Dict
new_end_line = shift(int(end.get("line", pre_start_line)))
if new_end_line is None:
new_end_line = new_start_line
-
return {
**diag,
"range": {
diff --git a/agent/lsp/reporter.py b/agent/lsp/reporter.py
index 85f160fcc38..73f365990cf 100644
--- a/agent/lsp/reporter.py
+++ b/agent/lsp/reporter.py
@@ -63,9 +63,8 @@ def report_for_file(
if not filtered:
return ""
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"
+ if len(filtered) > max_per_file:
+ body += f"\n... and {len(filtered) - max_per_file} more"
# quote=True also escapes ``"`` so a crafted file name can't break out of
# the ``file="..."`` attribute and synthesize new tags.
safe_path = html.escape(file_path, quote=True)
diff --git a/agent/lsp/servers.py b/agent/lsp/servers.py
index 11bb20bb169..232a8d845aa 100644
--- a/agent/lsp/servers.py
+++ b/agent/lsp/servers.py
@@ -93,8 +93,7 @@ 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)
- ext = os.path.splitext(base)[1]
- return ext.lower() if ext else base
+ return os.path.splitext(base)[1].lower() or base
def _which(*names: str) -> Optional[str]:
@@ -113,6 +112,13 @@ def _root_or_workspace(file_path: str, workspace: str, markers: Sequence[str], e
return found or workspace
+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
+ return lambda fp, ws: _root_or_workspace(fp, ws, markers, excludes=excludes)
+
+
def _find_binary(ctx: ServerContext, server_id: str, which: Sequence[str], install_pkg: Optional[str]) -> Optional[str]:
"""Config override → PATH → (optional) auto-install; ``None`` when nothing resolves."""
override = ctx.binary_overrides.get(server_id)
@@ -140,13 +146,6 @@ def _simple_spawn(server_id: str, which: Sequence[str], args: Sequence[str] = ()
return build
-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
- return lambda fp, ws: _root_or_workspace(fp, ws, markers, excludes=excludes)
-
-
# ---- bespoke spawn builders ----
@@ -161,19 +160,13 @@ def _spawn_pyright(root: str, ctx: ServerContext) -> Optional[SpawnSpec]:
bin_path = sibling
# Point pyright at the project venv; its default "python on PATH" rarely is.
py = _detect_python(root)
- init: Dict[str, Any] = {"python": {"pythonPath": py}} if py else {}
- return _make_spec(root, ctx, "pyright", [bin_path, "--stdio"], init)
+ return _make_spec(root, ctx, "pyright", [bin_path, "--stdio"], {"python": {"pythonPath": py}} if py else {})
def _detect_python(root: str) -> Optional[str]:
- 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"):
- p = os.path.join(v, sub)
- if os.path.exists(p):
- return p
- return None
+ venvs = [v for v in (os.environ.get("VIRTUAL_ENV"), os.path.join(root, ".venv"), os.path.join(root, "venv")) if v]
+ paths = (os.path.join(v, sub) for v in venvs for sub in ("bin/python", "bin/python3", "Scripts/python.exe"))
+ return next((p for p in paths if os.path.exists(p)), None)
_warned_once: set = set()
@@ -192,12 +185,8 @@ def _spawn_bash_ls(root: str, ctx: ServerContext) -> Optional[SpawnSpec]:
# bash-language-server delegates diagnostics to shellcheck; without it the
# server runs but never reports anything. Warn once so the gap is visible.
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).",
- )
+ _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).")
return _make_spec(root, ctx, "bash-language-server", [bin_path, "start"])
@@ -209,7 +198,6 @@ def _find_pses_bundle(ctx: ServerContext) -> Optional[str]:
then ``<HERMES_HOME>/lsp/PowerShellEditorServices``.
"""
from hermes_constants import get_hermes_home
-
override = ctx.binary_overrides.get("powershell")
init = ctx.init_overrides.get("powershell", {})
candidates = [
@@ -227,6 +215,13 @@ def _find_pses_bundle(ctx: ServerContext) -> Optional[str]:
return None
+_PSES_MISSING_MSG = (
+ "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."
+)
+
+
def _spawn_powershell_es(root: str, ctx: ServerContext) -> Optional[SpawnSpec]:
"""Spawn PowerShellEditorServices: needs a ``pwsh``/``powershell`` host plus the module bundle."""
pwsh = _which("pwsh", "powershell")
@@ -234,15 +229,7 @@ def _spawn_powershell_es(root: str, ctx: ServerContext) -> Optional[SpawnSpec]:
return None
bundle = _find_pses_bundle(ctx)
if bundle is None:
- _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.",
- )
+ _warn_once("pses-bundle", _PSES_MISSING_MSG)
return None
start_script = os.path.join(bundle, "PowerShellEditorServices", "Start-EditorServices.ps1")
# PSES writes connection info to the session details file on startup.
@@ -264,7 +251,6 @@ def _spawn_powershell_es(root: str, ctx: ServerContext) -> Optional[SpawnSpec]:
def hermes_lsp_session_dir() -> str:
"""Return (and create) the dir for PSES session/log scratch files."""
from hermes_constants import get_hermes_home
-
d = os.path.join(str(get_hermes_home()), "lsp", "pses")
os.makedirs(d, exist_ok=True)
return d