Skip to content

The agent that grows with you

refactor(agent/lsp): extract _apply_delta/_spawn_client, table-drive config overrides, compact client plumbing

Teknium1a27739c3a6b
diff --git a/agent/lsp/cli.py b/agent/lsp/cli.py
index f2faa43e4bd..8c7bfb24c4e 100644
--- a/agent/lsp/cli.py
+++ b/agent/lsp/cli.py
@@ -83,26 +83,19 @@ def _cmd_status(emit_json: bool) -> int:
if emit_json:
import json
- payload = {
- "service": info,
- "registry": [
- {
- "server_id": s.server_id,
- "extensions": list(s.extensions),
- "description": s.description,
- "binary_status": detect_status(_recipe_pkg_for(s.server_id)),
- }
- for s in SERVERS
- ],
- }
- sys.stdout.write(json.dumps(payload, indent=2) + "\n")
+ registry = [
+ {"server_id": s.server_id, "extensions": list(s.extensions), "description": s.description,
+ "binary_status": detect_status(_recipe_pkg_for(s.server_id))}
+ for s in SERVERS
+ ]
+ sys.stdout.write(json.dumps({"service": info, "registry": registry}, indent=2) + "\n")
return 0
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')}")
+ out += [f" wait_mode: {info.get('wait_mode')}",
+ 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)}")
diff --git a/agent/lsp/client.py b/agent/lsp/client.py
index ad498c9a39d..c15c18b2c28 100644
--- a/agent/lsp/client.py
+++ b/agent/lsp/client.py
@@ -1,13 +1,11 @@
"""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
+Owns the child process and drives JSON-RPC. 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 never masquerade as a verdict on the current content
+("ghost diagnostics"). Whole-document sync is always sent, every ``open_file``
+also fires ``didChangeWatchedFiles`` (clangd/eslint only re-scan on it), and
``ContentModified`` (-32801) errors are retried with exponential backoff.
"""
from __future__ import annotations
@@ -56,22 +54,14 @@ _LIVE_STATES = {"starting", "running"}
_CLIENT_CAPABILITIES: Dict[str, Any] = {
"window": {"workDoneProgress": True},
- "workspace": {
- "configuration": True,
- "workspaceFolders": True,
- "didChangeWatchedFiles": {"dynamicRegistration": True},
- "diagnostics": {"refreshSupport": False},
- },
+ "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,
- },
+ "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,
- },
+ "publishDiagnostics": {"relatedInformation": True, "tagSupport": {"valueSet": [1, 2]},
+ "versionSupport": True, "codeDescriptionSupport": True, "dataSupport": False},
"hover": {"contentFormat": ["markdown", "plaintext"]},
"definition": {"linkSupport": True},
"references": {},
@@ -119,10 +109,9 @@ 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, 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.
+ ``pull_version`` tag stored results, fresh iff tag >= version; -1 means
+ "no data yet". Servers that echo a version in publishDiagnostics get
+ exact tagging; others are credited with the current version at receipt.
"""
version: int = 0
@@ -170,38 +159,37 @@ class LSPClient:
self._stderr_task: Optional[asyncio.Task] = None
self._reader_task: Optional[asyncio.Task] = None
self._cleanup_lock = asyncio.Lock()
-
self._next_id: int = 0
self._pending: Dict[int, asyncio.Future] = {}
- # Server → client requests; anything else gets method-not-found.
+ # Server → client requests; anything else gets method-not-found. Capability
+ # (un)registration and diagnostic refresh are acknowledged but not acted on:
+ # we re-pull on every touch anyway.
self._request_handlers: Dict[str, Callable[[Any], Awaitable[Any]]] = {
- "window/workDoneProgress/create": self._handle_null, # ack progress tokens
+ "window/workDoneProgress/create": self._handle_null,
"workspace/configuration": self._handle_workspace_configuration,
- "client/registerCapability": self._handle_register_capability,
- "client/unregisterCapability": self._handle_unregister_capability,
+ "client/registerCapability": self._handle_null,
+ "client/unregisterCapability": self._handle_null,
"workspace/workspaceFolders": self._handle_workspace_folders,
- "workspace/diagnostic/refresh": self._handle_null, # we re-pull on every touch anyway
+ "workspace/diagnostic/refresh": self._handle_null,
}
# Server → client notifications; others (showMessage, $/progress) are dropped.
self._notification_handlers: Dict[str, Callable[[Any], None]] = {
"textDocument/publishDiagnostics": self._handle_publish_diagnostics,
}
- # Per-document state keyed by absolute path (NOT URI).
- self._docs: Dict[str, _DocState] = {}
- # Only diagnostic capability registrations are tracked.
- self._diagnostic_registrations: Dict[str, Dict[str, Any]] = {}
-
+ self._docs: Dict[str, _DocState] = {} # keyed by absolute path (NOT URI)
self._state: str = "stopped"
self._sync_kind: int = 1 # 1=Full, 2=Incremental
self._stopping: bool = False
-
# Waiters snapshot ``_push_counter`` and treat any increase as "recheck
# the predicate" — avoids the asyncio.Event sticky-state trap.
self._push_event = asyncio.Event()
self._push_counter = 0
- self._registration_event = asyncio.Event()
+
+ @property
+ def state(self) -> str:
+ return self._state
@property
def is_running(self) -> bool:
@@ -211,18 +199,11 @@ class LSPClient:
proc, reader = self._proc, self._reader_task
return (
self._state in _LIVE_STATES
- and proc is not None
- and proc.returncode is None
- and proc.stdin is not None
- and not proc.stdin.is_closing()
- and reader is not None
- and not reader.done()
+ and proc is not None and proc.returncode is None
+ and proc.stdin is not None and not proc.stdin.is_closing()
+ and reader is not None and not reader.done()
)
- @property
- def state(self) -> str:
- return self._state
-
async def start(self) -> None:
"""Spawn the server and complete the initialize handshake.
@@ -282,12 +263,8 @@ class LSPClient:
if self._proc is None or self._proc.stderr is None:
return
try:
- while True:
- line = await self._proc.stderr.readline()
- if not line:
- break
- text = line.decode("utf-8", errors="replace").rstrip()
- if text:
+ while line := await self._proc.stderr.readline():
+ if text := line.decode("utf-8", errors="replace").rstrip():
logger.debug("[%s] stderr: %s", self.server_id, text[:1000])
except (asyncio.CancelledError, OSError):
pass
@@ -296,11 +273,7 @@ class LSPClient:
if self._proc is None or self._proc.stdout is None:
return
try:
- while True:
- msg = await read_message(self._proc.stdout)
- if msg is None:
- logger.debug("[%s] server closed stdout cleanly", self.server_id)
- break
+ while (msg := await read_message(self._proc.stdout)) is not None:
kind, key = classify_message(msg)
if kind == "response":
self._dispatch_response(key, msg)
@@ -310,6 +283,7 @@ class LSPClient:
self._dispatch_notification(key, msg)
else:
logger.warning("[%s] dropping invalid message: %r", self.server_id, msg)
+ logger.debug("[%s] server closed stdout cleanly", self.server_id)
except LSPProtocolError as e:
logger.warning("[%s] protocol error in reader loop: %s", self.server_id, e)
except (asyncio.CancelledError, OSError):
@@ -383,11 +357,11 @@ class LSPClient:
async def _cleanup_process(self) -> None:
async with self._cleanup_lock:
reader_task, self._reader_task = self._reader_task, None
+ stderr_task, self._stderr_task = self._stderr_task, None
+ proc, self._proc = self._proc, None
if reader_task is not asyncio.current_task():
await self._cancel_task(reader_task)
- stderr_task, self._stderr_task = self._stderr_task, None
await self._cancel_task(stderr_task)
- proc, self._proc = self._proc, None
if proc is None or proc.returncode is not None:
return
try:
@@ -400,9 +374,7 @@ class LSPClient:
except ProcessLookupError:
pass
- # ------------------------------------------------------------------
- # request / notification plumbing
- # ------------------------------------------------------------------
+ # ---- request / notification plumbing ----
async def _write(self, msg: dict) -> None:
assert self._proc is not None and self._proc.stdin is not None
@@ -448,12 +420,11 @@ class LSPClient:
async def _send_reply(self, msg: dict) -> None:
"""Send a response to a server→client request; silently no-ops when the pipe is gone."""
- if self._proc is None or self._proc.stdin is None or self._proc.stdin.is_closing():
- return
- try:
- await self._write(msg)
- except _WRITE_ERRORS:
- pass
+ if self._proc is not None and self._proc.stdin is not None and not self._proc.stdin.is_closing():
+ try:
+ await self._write(msg)
+ except _WRITE_ERRORS:
+ pass
def _dispatch_response(self, req_id: int, msg: dict) -> None:
fut = self._pending.get(req_id)
@@ -461,11 +432,7 @@ 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(int(err.get("code", -32000)), str(err.get("message", "unknown")), err.get("data")))
else:
fut.set_result(msg.get("result"))
@@ -492,49 +459,30 @@ class LSPClient:
except Exception as e: # noqa: BLE001
logger.debug("[%s] notification handler %s failed: %s", self.server_id, method, e)
- # ------------------------------------------------------------------
- # built-in server-→-client request handlers
- # ------------------------------------------------------------------
+ # ---- built-in server-→-client request handlers ----
async def _handle_null(self, params: Any) -> Any:
return None
async def _handle_workspace_configuration(self, params: Any) -> Any:
- # Walk dotted sections through initializationOptions; null when missing.
+ """Walk dotted ``section`` paths through initializationOptions; null when missing."""
if not isinstance(params, dict):
return [None]
- out: List[Any] = []
- for item in params.get("items") or []:
+
+ def lookup(item: Any) -> Any:
if not isinstance(item, dict):
- out.append(None)
- continue
+ return None
section = item.get("section")
if not section or not self._init_options:
- out.append(self._init_options or None)
- continue
+ return self._init_options or None
cur: Any = self._init_options
for part in str(section).split("."):
if not (isinstance(cur, dict) and part in cur):
- cur = None
- break
+ return None
cur = cur[part]
- out.append(cur)
- return out
-
- async def _handle_register_capability(self, params: Any) -> Any:
- 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
+ return cur
- async def _handle_unregister_capability(self, params: Any) -> Any:
- 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
+ return [lookup(item) for item in params.get("items") or []]
async def _handle_workspace_folders(self, params: Any) -> Any:
return [{"name": "workspace", "uri": file_uri(self.workspace_root)}]
@@ -544,7 +492,6 @@ class LSPClient:
return
diagnostics = params.get("diagnostics") or []
version = params.get("version")
-
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
@@ -563,21 +510,17 @@ class LSPClient:
self._push_counter += 1
self._push_event.set()
- # ------------------------------------------------------------------
- # public file-sync API
- # ------------------------------------------------------------------
+ # ---- public file-sync API ----
async def open_file(self, path: str, *, language_id: str = "plaintext") -> int:
"""Send didOpen (first time) or didChange (subsequent); return the new document version."""
if not self.is_running:
raise LSPProtocolError("client not running")
-
abs_path = os.path.abspath(path)
try:
text = Path(abs_path).read_text(encoding="utf-8", errors="replace")
except OSError as e:
raise LSPProtocolError(f"cannot read {abs_path}: {e}") from e
-
uri = file_uri(abs_path)
doc = self._docs.get(abs_path)
if doc is not None and doc.version < 0:
@@ -588,21 +531,16 @@ class LSPClient:
)
if doc is not None:
- new_version = doc.version + 1
+ change: Dict[str, Any] = {"text": text}
if self._sync_kind == 2:
- content_changes = [{
- "range": {"start": {"line": 0, "character": 0}, "end": _end_position(doc.text)},
- "text": text,
- }]
- else:
- content_changes = [{"text": text}]
+ change["range"] = {"start": {"line": 0, "character": 0}, "end": _end_position(doc.text)}
+ new_version = doc.version + 1
await self._send_notification(
"textDocument/didChange",
- {"textDocument": {"uri": uri, "version": new_version}, "contentChanges": content_changes},
+ {"textDocument": {"uri": uri, "version": new_version}, "contentChanges": [change]},
)
# Bumping the version is the whole invalidation story (see _DocState).
- doc.version = new_version
- doc.text = text
+ doc.version, doc.text = new_version, text
return new_version
# Fresh state: anything a pre-open push stashed under this path
@@ -621,9 +559,7 @@ class LSPClient:
"textDocument/didSave", {"textDocument": {"uri": file_uri(os.path.abspath(path))}}
)
- # ------------------------------------------------------------------
- # diagnostics: pull + wait
- # ------------------------------------------------------------------
+ # ---- diagnostics: pull + wait ----
async def _pull_document_diagnostics(self, path: str) -> None:
"""Send ``textDocument/diagnostic`` for one file into the pull store.
@@ -637,8 +573,7 @@ class LSPClient:
sent_version = doc.version if doc else -1
try:
result = await self._send_request_with_retry(
- "textDocument/diagnostic",
- {"textDocument": {"uri": file_uri(abs_path)}},
+ "textDocument/diagnostic", {"textDocument": {"uri": file_uri(abs_path)}},
timeout=DIAGNOSTICS_REQUEST_TIMEOUT,
)
except (LSPRequestError, LSPProtocolError, asyncio.TimeoutError) as e:
@@ -646,20 +581,17 @@ class LSPClient:
return
if not isinstance(result, dict):
return
- items = result.get("items")
- if isinstance(items, list):
- doc = self._docs.setdefault(abs_path, _DocState(version=-1))
- doc.pull = items
- doc.pull_version = sent_version
related = result.get("relatedDocuments")
+ reports = [(abs_path, result, sent_version)]
if isinstance(related, dict):
- for uri, sub in related.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
- # Same send-anchored tagging: fresh only if that doc hasn't changed since.
- rel.pull_version = rel.version
+ # Related docs get the same send-anchored tagging: fresh only if unchanged since.
+ reports += [(uri_to_path(uri), sub, None) for uri, sub in related.items()]
+ for doc_path, report, tag in reports:
+ items = report.get("items") if isinstance(report, dict) else None
+ if isinstance(items, list):
+ d = self._docs.setdefault(doc_path, _DocState(version=-1))
+ d.pull = items
+ d.pull_version = d.version if tag is None else tag
async def wait_for_diagnostics(
self,
@@ -678,34 +610,27 @@ class LSPClient:
"no data", NOT "no errors" — the stores may still hold stale entries.
Never throws for servers lacking pull support; the push side still works.
"""
- if timeout is not None and timeout > 0:
- budget = timeout
- else:
- budget = DIAGNOSTICS_FULL_WAIT if mode == "full" else DIAGNOSTICS_DOCUMENT_WAIT
- deadline = asyncio.get_event_loop().time() + budget
+ if not (timeout is not None and timeout > 0):
+ timeout = DIAGNOSTICS_FULL_WAIT if mode == "full" else DIAGNOSTICS_DOCUMENT_WAIT
+ now = asyncio.get_event_loop().time
+ deadline = now() + timeout
abs_path = os.path.abspath(path)
while True:
if not self._connection_is_open():
raise LSPProtocolError("server connection closed while waiting for diagnostics")
- remaining = deadline - asyncio.get_event_loop().time()
+ remaining = deadline - now()
if remaining <= 0:
return False
-
# 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
- )
+ tasks = {
+ asyncio.create_task(self._pull_document_diagnostics(abs_path)),
+ asyncio.create_task(self._wait_for_fresh_push(abs_path, version, remaining)),
+ }
+ _done, pending = await asyncio.wait(tasks, timeout=remaining, return_when=asyncio.FIRST_COMPLETED)
for t in pending:
t.cancel()
- for t in pending:
- try:
- await t
- except (asyncio.CancelledError, Exception): # noqa: BLE001
- pass
-
+ await asyncio.gather(*pending, return_exceptions=True)
doc = self._docs.get(abs_path)
if doc and (doc.fresh_push(version) or doc.fresh_pull(version)):
return True
@@ -755,19 +680,18 @@ class LSPClient:
doc = self._docs.get(os.path.abspath(path))
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, doc.pull)
+ push = doc.push if not fresh_only or doc.fresh_push() else []
+ pull = doc.pull if not fresh_only or doc.fresh_pull() else []
+ return _dedupe(push, pull)
def _dedupe(*lists: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
seen: Set[str] = set()
out: List[Dict[str, Any]] = []
- for lst in lists:
- for d in lst:
- if isinstance(d, dict) and (key := _diagnostic_key(d)) not in seen:
- seen.add(key)
- out.append(d)
+ for d in (d for lst in lists for d in lst if isinstance(d, dict)):
+ if (key := _diagnostic_key(d)) not in seen:
+ seen.add(key)
+ out.append(d)
return out
@@ -792,11 +716,4 @@ def _diagnostic_key(d: Dict[str, Any]) -> str:
])
-__all__ = [
- "LSPClient",
- "file_uri",
- "uri_to_path",
- "INITIALIZE_TIMEOUT",
- "DIAGNOSTICS_DOCUMENT_WAIT",
- "DIAGNOSTICS_FULL_WAIT",
-]
+__all__ = ["LSPClient", "file_uri", "uri_to_path", "INITIALIZE_TIMEOUT", "DIAGNOSTICS_DOCUMENT_WAIT", "DIAGNOSTICS_FULL_WAIT"]
diff --git a/agent/lsp/install.py b/agent/lsp/install.py
index 5e098b59e14..af6c04f4d72 100644
--- a/agent/lsp/install.py
+++ b/agent/lsp/install.py
@@ -131,13 +131,10 @@ def try_install(pkg: str, strategy: str = "auto") -> Optional[str]:
if pkg in _install_results:
return _install_results[pkg]
-
with _get_lock(pkg):
- if pkg in _install_results:
- return _install_results[pkg]
- result = _do_install(pkg)
- _install_results[pkg] = result
- return result
+ if pkg not in _install_results:
+ _install_results[pkg] = _do_install(pkg)
+ return _install_results[pkg]
def _do_install(pkg: str) -> Optional[str]:
@@ -148,11 +145,9 @@ def _do_install(pkg: str) -> Optional[str]:
strategy = recipe.get("strategy", "manual")
bin_name = recipe.get("bin", pkg)
-
existing = _existing_binary(bin_name)
if existing:
return existing
-
if strategy == "manual":
logger.debug("[install] %s requires manual install (recipe=%s)", pkg, recipe)
return None
@@ -168,14 +163,8 @@ def _run_installer(tool: str, pkg: str, cmd: list, *, timeout: int, env: Optiona
"""Run one install subprocess; log and return False on non-zero exit or error."""
try:
proc = subprocess.run(
- cmd,
- check=False,
- capture_output=True,
- text=True, encoding="utf-8", errors="replace",
- timeout=timeout,
- env=env,
- stdin=subprocess.DEVNULL,
- creationflags=windows_hide_flags(),
+ cmd, check=False, capture_output=True, text=True, encoding="utf-8", errors="replace",
+ timeout=timeout, env=env, stdin=subprocess.DEVNULL, creationflags=windows_hide_flags(),
)
if proc.returncode != 0:
logger.warning("[install] %s install failed for %s: %s", tool, pkg, proc.stderr.strip()[:500])
@@ -212,13 +201,9 @@ def _install_npm(pkg: str, bin_name: str, extra_pkgs: Optional[list] = 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))
- if not _run_installer(
- "npm", pkg,
- [npm, "install", "--prefix", str(staging), "--silent", "--no-fund", "--no-audit", *install_targets],
- timeout=300,
- ):
+ cmd = [npm, "install", "--prefix", str(staging), "--silent", "--no-fund", "--no-audit", *install_targets]
+ if not _run_installer("npm", pkg, cmd, timeout=300):
return None
-
found = _first_existing(staging / "node_modules" / ".bin" / bin_name)
if found is not None:
return _link_into_bin(found)
@@ -237,9 +222,7 @@ def _install_go(pkg: str, bin_name: str) -> Optional[str]:
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
- bin_path = staging / bin_name
- if _is_windows():
- bin_path = bin_path.with_suffix(".exe")
+ bin_path = (staging / bin_name).with_suffix(".exe") if _is_windows() else staging / bin_name
if bin_path.exists():
return str(bin_path)
logger.warning("[install] go install for %s succeeded but bin %s not found", pkg, bin_name)
@@ -285,9 +268,4 @@ def detect_status(pkg: str) -> str:
return "missing"
-__all__ = [
- "INSTALL_RECIPES",
- "try_install",
- "detect_status",
- "hermes_lsp_bin_dir",
-]
+__all__ = ["INSTALL_RECIPES", "try_install", "detect_status", "hermes_lsp_bin_dir"]
diff --git a/agent/lsp/manager.py b/agent/lsp/manager.py
index 76eca701a2a..a93efcea9ef 100644
--- a/agent/lsp/manager.py
+++ b/agent/lsp/manager.py
@@ -131,8 +131,7 @@ class LSPService:
self._last_used: Dict[_Key, float] = {}
self._state_lock = threading.Lock()
self._idle_reaper_task: Optional[asyncio.Task] = None
-
- # file path → diagnostics snapshot taken immediately before a write.
+ # abs file path → diagnostics snapshot taken immediately before a write.
self._delta_baseline: Dict[str, List[Dict[str, Any]]] = {}
if self._enabled and self._idle_timeout > 0:
@@ -162,35 +161,19 @@ class LSPService:
# for the process lifetime. Clamp (0 still disables).
idle_timeout = MIN_IDLE_TIMEOUT
servers_cfg = lsp_cfg.get("servers") or {}
- disabled = []
- binary_overrides: Dict[str, List[str]] = {}
- env_overrides: Dict[str, Dict[str, str]] = {}
- init_overrides: Dict[str, Dict[str, Any]] = {}
- if isinstance(servers_cfg, dict):
- for name, sub in servers_cfg.items():
- if not isinstance(sub, dict):
- continue
- if sub.get("disabled"):
- disabled.append(name)
- cmd = sub.get("command")
- if isinstance(cmd, list) and cmd:
- binary_overrides[name] = cmd
- env = sub.get("env")
- if isinstance(env, dict):
- env_overrides[name] = {k: str(v) for k, v in env.items()}
- init = sub.get("initialization_options")
- if isinstance(init, dict):
- init_overrides[name] = init
-
+ servers = {n: c for n, c in servers_cfg.items() if isinstance(c, dict)} if isinstance(servers_cfg, dict) else {}
return cls(
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,
- disabled_servers=disabled,
+ binary_overrides={n: c["command"] for n, c in servers.items()
+ if isinstance(c.get("command"), list) and c["command"]},
+ env_overrides={n: {k: str(v) for k, v in c["env"].items()} for n, c in servers.items()
+ if isinstance(c.get("env"), dict)},
+ init_overrides={n: c["initialization_options"] for n, c in servers.items()
+ if isinstance(c.get("initialization_options"), dict)},
+ disabled_servers=[n for n, c in servers.items() if c.get("disabled")],
idle_timeout=idle_timeout,
)
@@ -212,10 +195,9 @@ class LSPService:
if not (ws_root and gated):
return None
try:
- per_server_root = srv.resolve_root(file_path, ws_root) or ws_root
+ return (srv.server_id, srv.resolve_root(file_path, ws_root) or ws_root)
except Exception: # noqa: BLE001
- per_server_root = ws_root
- return (srv.server_id, per_server_root)
+ return (srv.server_id, ws_root)
def enabled_for(self, file_path: str) -> bool:
"""Return True iff LSP should run for this file.
@@ -225,9 +207,7 @@ class LSPService:
(so a failed server costs no spawn attempts or timeouts until
``hermes lsp restart`` or process exit).
"""
- if not self._enabled:
- return False
- srv = find_server_for_file(file_path)
+ srv = find_server_for_file(file_path) if self._enabled else None
if srv is None or srv.server_id in self._disabled_servers:
return False
key = self._broken_key(srv, file_path)
@@ -273,11 +253,7 @@ class LSPService:
"""
if not self.enabled_for(file_path):
return []
-
- # Resolve server_id eagerly for structured logs on the error paths.
- srv = find_server_for_file(file_path)
- server_id = srv.server_id if srv else "?"
-
+ server_id = find_server_for_file(file_path).server_id # enabled_for guarantees a match
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)
@@ -299,30 +275,35 @@ class LSPService:
eventlog.log_timeout(server_id, file_path, kind="fresh diagnostics")
return []
- abs_path = os.path.abspath(file_path)
if delta:
- baseline = self._delta_baseline.get(abs_path) or []
- if baseline:
- if line_shift is not None:
- # Entries that map into a deleted region drop out — they no longer apply.
- from agent.lsp.range_shift import shift_baseline
- baseline = shift_baseline(baseline, line_shift)
- seen = {_diag_key(d) for d in baseline}
- diags = [d for d in diags if _diag_key(d) not in seen]
- # Roll the baseline forward so the next call is a delta against this state.
- try:
- fresh = self._loop.run(self._current_diags_async(file_path), timeout=2.0) or []
- except Exception: # noqa: BLE001
- fresh = []
- if fresh:
- self._delta_baseline[abs_path] = fresh
-
+ diags = self._apply_delta(file_path, diags, line_shift)
if diags:
eventlog.log_diagnostics(server_id, file_path, len(diags))
else:
eventlog.log_clean(server_id, file_path)
return diags
+ def _apply_delta(self, file_path: str, diags: List[Dict[str, Any]],
+ line_shift: Optional[Callable[[int], Optional[int]]]) -> List[Dict[str, Any]]:
+ """Drop diagnostics present in the pre-write baseline, then roll the baseline forward."""
+ abs_path = os.path.abspath(file_path)
+ baseline = self._delta_baseline.get(abs_path) or []
+ if baseline:
+ if line_shift is not None:
+ # Entries that map into a deleted region drop out — they no longer apply.
+ from agent.lsp.range_shift import shift_baseline
+ baseline = shift_baseline(baseline, line_shift)
+ seen = {_diag_key(d) for d in baseline}
+ diags = [d for d in diags if _diag_key(d) not in seen]
+ # Roll the baseline forward so the next call is a delta against this state.
+ try:
+ fresh = self._loop.run(self._current_diags_async(file_path), timeout=2.0) or []
+ except Exception: # noqa: BLE001
+ fresh = []
+ if fresh:
+ self._delta_baseline[abs_path] = fresh
+ return diags
+
def _mark_broken_for_file(self, file_path: str, exc: BaseException) -> None:
"""Mark the file's ``(server_id, root)`` pair broken after an outer timeout/error.
@@ -338,7 +319,6 @@ class LSPService:
return
already_broken = key in self._broken
self._broken.add(key)
-
with self._state_lock:
client = self._clients.pop(key, None)
self._last_used.pop(key, None)
@@ -348,7 +328,6 @@ class LSPService:
self._loop.run(client.shutdown(), timeout=1.0)
except Exception: # noqa: BLE001
pass
-
if not already_broken:
eventlog.log_spawn_failed(key[0], key[1], exc)
@@ -399,9 +378,7 @@ class LSPService:
logger.debug("open/wait failed for %s: %s", file_path, e)
return None
self._touch(client)
- if not fresh:
- return None
- return list(client.diagnostics_for(file_path, fresh_only=True))
+ return list(client.diagnostics_for(file_path, fresh_only=True)) if fresh else None
async def _current_diags_async(self, file_path: str) -> List[Dict[str, Any]]:
ws, gated = resolve_workspace_for_file(file_path)
@@ -410,9 +387,7 @@ class LSPService:
return []
with self._state_lock:
client = self._clients.get((srv.server_id, ws))
- if client is None:
- return []
- return list(client.diagnostics_for(file_path, fresh_only=True))
+ return list(client.diagnostics_for(file_path, fresh_only=True)) if client else []
async def _get_or_spawn(self, file_path: str) -> Optional[LSPClient]:
srv = find_server_for_file(file_path)
@@ -437,28 +412,29 @@ class LSPService:
client = self._clients.get(key)
if client is not None and client.is_running:
self._last_used[key] = time.time()
- eventlog.log_active(srv.server_id, per_server_root)
+ eventlog.log_active(*key)
return client
spawning = self._spawning.get(key)
- if spawning is not None:
+ if spawning is None:
+ spawning = self._spawning[key] = asyncio.get_running_loop().create_future()
+ owner = True
+ else:
+ owner = False
+ if not owner:
try:
return await spawning
except Exception: # noqa: BLE001
return None
-
- spawn_future: asyncio.Future = asyncio.get_running_loop().create_future()
- with self._state_lock:
- self._spawning[key] = spawn_future
try:
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)
+ eventlog.log_active(*key)
else:
self._broken.add(key)
- spawn_future.set_result(client)
+ spawning.set_result(client)
return client
finally:
with self._state_lock:
diff --git a/agent/lsp/servers.py b/agent/lsp/servers.py
index 51f90d36c41..11bb20bb169 100644
--- a/agent/lsp/servers.py
+++ b/agent/lsp/servers.py
@@ -54,7 +54,6 @@ _RootFn = Callable[[str, str], Optional[str]]
@dataclass
class SpawnSpec:
"""Result of resolving a server for a file (``None`` means skip)."""
-
command: List[str]
workspace_root: str
cwd: str
@@ -65,13 +64,8 @@ class SpawnSpec:
@dataclass
class ServerDef:
- """Definition of one language server.
-
- ``resolve_root(file_path, workspace_root)`` returns the per-server
- project root or ``None`` to skip; ``build_spawn(root, ctx)`` returns
- a :class:`SpawnSpec` or ``None`` when the binary can't be found.
- """
-
+ """One language server: ``resolve_root(file, ws)`` → per-server root or ``None`` to skip;
+ ``build_spawn(root, ctx)`` → :class:`SpawnSpec` or ``None`` when the binary can't be found."""
server_id: str
extensions: Tuple[str, ...]
resolve_root: _RootFn
@@ -80,14 +74,12 @@ class ServerDef:
description: str = ""
def matches(self, file_path: str) -> bool:
- """Return True iff this server handles ``file_path``."""
return _file_ext_or_basename(file_path) in self.extensions
@dataclass
class ServerContext:
"""User policy passed into :meth:`ServerDef.build_spawn` (install strategy, overrides)."""
-
workspace_root: str
install_strategy: str = "auto" # "auto" | "manual" | "off"
binary_overrides: Dict[str, List[str]] = field(default_factory=dict)
@@ -95,9 +87,7 @@ class ServerContext:
init_overrides: Dict[str, Dict[str, Any]] = field(default_factory=dict)
-# ---------------------------------------------------------------------------
-# helpers
-# ---------------------------------------------------------------------------
+# ---- helpers ----
def _file_ext_or_basename(path: str) -> str:
@@ -136,14 +126,8 @@ 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:
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,
- cwd=root,
- env=ctx.env_overrides.get(server_id, {}),
- initialization_options=init,
- seed_diagnostics_on_first_push=seed,
- )
+ return SpawnSpec(command, root, root, env=ctx.env_overrides.get(server_id, {}),
+ initialization_options=init, seed_diagnostics_on_first_push=seed)
def _simple_spawn(server_id: str, which: Sequence[str], args: Sequence[str] = (),
@@ -152,9 +136,7 @@ def _simple_spawn(server_id: str, which: Sequence[str], args: Sequence[str] = ()
"""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)
- if bin_path is None:
- return None
- return _make_spec(root, ctx, server_id, [bin_path, *args], base_init, seed)
+ return None if bin_path is None else _make_spec(root, ctx, server_id, [bin_path, *args], base_init, seed)
return build
@@ -165,9 +147,7 @@ def _markers_root(markers: Optional[Sequence[str]], excludes: Sequence[str] = ()
return lambda fp, ws: _root_or_workspace(fp, ws, markers, excludes=excludes)
-# ---------------------------------------------------------------------------
-# bespoke spawn builders
-# ---------------------------------------------------------------------------
+# ---- bespoke spawn builders ----
def _spawn_pyright(root: str, ctx: ServerContext) -> Optional[SpawnSpec]:
@@ -268,19 +248,15 @@ def _spawn_powershell_es(root: str, ctx: ServerContext) -> Optional[SpawnSpec]:
# PSES writes connection info to the session details file on startup.
session_dir = hermes_lsp_session_dir()
inner = (
- f"& '{start_script}' "
- f"-BundledModulesPath '{bundle}' "
+ f"& '{start_script}' -BundledModulesPath '{bundle}' "
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"
+ f"-HostName Hermes -HostProfileId hermes -HostVersion 1.0.0 -Stdio -LogLevel Normal"
)
return SpawnSpec(
- command=[pwsh, "-NoLogo", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", inner],
- workspace_root=root,
- cwd=root,
- env=ctx.env_overrides.get("powershell", {}),
+ [pwsh, "-NoLogo", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", inner],
+ root, root, env=ctx.env_overrides.get("powershell", {}),
initialization_options={k: v for k, v in ctx.init_overrides.get("powershell", {}).items() if k != "bundlePath"},
)
@@ -294,9 +270,7 @@ def hermes_lsp_session_dir() -> str:
return d
-# ---------------------------------------------------------------------------
-# the registry
-# ---------------------------------------------------------------------------
+# ---- the registry ----
_JS_MARKERS = ["package-lock.json", "bun.lockb", "bun.lock", "pnpm-lock.yaml", "yarn.lock", "package.json", "tsconfig.json"]
_DENO_EXCLUDES = ["deno.json", "deno.jsonc"]
@@ -308,13 +282,12 @@ def _server(server_id: str, extensions: Tuple[str, ...], description: str, *,
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:
+ """Registry entry factory: defaults to marker-based root + single-binary spawn."""
return ServerDef(
- server_id=server_id,
- extensions=extensions,
- resolve_root=resolve_root or _markers_root(markers, excludes),
- build_spawn=build_spawn or _simple_spawn(server_id, which or (server_id,), args, install_pkg, base_init, seed),
- seed_first_push=seed,
- description=description,
+ server_id, extensions,
+ resolve_root or _markers_root(markers, excludes),
+ build_spawn or _simple_spawn(server_id, which or (server_id,), args, install_pkg, base_init, seed),
+ seed_first_push=seed, description=description,
)
@@ -388,12 +361,4 @@ def language_id_for(path: str) -> str:
return LANGUAGE_BY_EXT.get(_file_ext_or_basename(path), "plaintext")
-__all__ = [
- "ServerDef",
- "ServerContext",
- "SpawnSpec",
- "SERVERS",
- "find_server_for_file",
- "language_id_for",
- "LANGUAGE_BY_EXT",
-]
+__all__ = ["ServerDef", "ServerContext", "SpawnSpec", "SERVERS", "find_server_for_file", "language_id_for", "LANGUAGE_BY_EXT"]