The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(agent/lsp): inline win-shim/sync-kind helpers, unify reply path in _dispatch_request, compact manager signatures
Teknium03f00ec3cf82
diff --git a/agent/lsp/client.py b/agent/lsp/client.pyindex c15c18b2c28..29d1cc030d1 100644--- a/agent/lsp/client.py+++ b/agent/lsp/client.py@@ -1,12 +1,11 @@"""Async LSP client over stdin/stdout — one per ``(server, workspace_root)``.-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.+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@@ -44,7 +43,6 @@ DIAGNOSTICS_FULL_WAIT = 10.0DIAGNOSTICS_REQUEST_TIMEOUT = 3.0PUSH_DEBOUNCE = 0.15SHUTDOWN_GRACE = 1.0 # seconds between SIGTERM and SIGKILL-# Retry policy for transient ContentModified errors: 0.5, 1.0, 2.0s.MAX_CONTENT_MODIFIED_RETRIES = 3RETRY_BASE_DELAY = 0.5@@ -107,13 +105,12 @@ def _end_position(text: str) -> Dict[str, int]:class _DocState:"""Per-document state.- ``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; -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`` 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; -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 = 0text: str = ""push: List[Dict[str, Any]] = field(default_factory=list)@@ -128,6 +125,9 @@ class _DocState:def fresh_pull(self, version: Optional[int] = None) -> bool:return self.pull_version >= (self.version if version is None else version)+ def fresh(self, version: Optional[int] = None) -> bool:+ return self.fresh_push(version) or self.fresh_pull(version)+class LSPClient:"""Async LSP client tied to one server process and one workspace root.@@ -136,17 +136,10 @@ class LSPClient:``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,- initialization_options: Optional[Dict[str, Any]] = None,- seed_diagnostics_on_first_push: bool = False,- ) -> None:+ def __init__(self, *, server_id: str, workspace_root: str, command: List[str],+ env: Optional[Dict[str, str]] = None, cwd: Optional[str] = None,+ initialization_options: Optional[Dict[str, Any]] = None,+ seed_diagnostics_on_first_push: bool = False) -> None:self.server_id = server_idself.workspace_root = workspace_rootself._command = list(command)@@ -204,11 +197,10 @@ class LSPClient:and reader is not None and not reader.done())- async def start(self) -> None:- """Spawn the server and complete the initialize handshake.+ # ---- lifecycle ----- On failure the process is killed and state is ``"error"``; re-call to retry.- """+ async def start(self) -> None:+ """Spawn + initialize handshake. On failure the process is killed and state is ``"error"``; re-call to retry."""if self._state in _LIVE_STATES:returnself._state = "starting"@@ -223,18 +215,10 @@ class LSPClient:await self._cleanup_process()raise- @staticmethod- def _win_wrap_cmd(cmd: List[str]) -> List[str]:- """On Windows, wrap .cmd/.bat shims so CreateProcess can run them."""- if cmd[0].lower().endswith((".cmd", ".bat")):- return ["cmd.exe", "/c", *cmd]- return cmd-async def _spawn(self) -> None:- env = dict(os.environ)- if self._env:- env.update(self._env)- cmd = self._win_wrap_cmd(self._command) if sys.platform == "win32" else self._command+ cmd = self._command+ if sys.platform == "win32" and cmd[0].lower().endswith((".cmd", ".bat")):+ cmd = ["cmd.exe", "/c", *cmd] # CreateProcess can't run .cmd/.bat shims directlytry:# start_new_session=True gives the server its own process group;# otherwise it inherits the gateway's pgid and mcp_tool's orphan@@ -242,19 +226,13 @@ class LSPClient:# windows_hide_flags() suppresses the console window a .cmd shim# would flash from a console-less host (CREATE_NO_WINDOW; 0 on POSIX).self._proc = await asyncio.create_subprocess_exec(- cmd[0],- *cmd[1:],- stdin=asyncio.subprocess.PIPE,- stdout=asyncio.subprocess.PIPE,- stderr=asyncio.subprocess.PIPE,- env=env,- cwd=self._cwd,- start_new_session=True,- creationflags=windows_hide_flags(),+ cmd[0], *cmd[1:],+ stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE,+ env={**os.environ, **(self._env or {})}, cwd=self._cwd,+ start_new_session=True, creationflags=windows_hide_flags(),)except FileNotFoundError as 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())self._reader_task = asyncio.create_task(self._reader_loop())@@ -300,32 +278,26 @@ class LSPClient:if unexpected_close:await self._cleanup_process()+ def _workspace_folders(self) -> List[Dict[str, str]]:+ return [{"name": "workspace", "uri": file_uri(self.workspace_root)}]+async def _initialize(self) -> None:- root_uri = file_uri(self.workspace_root)params = {- "rootUri": root_uri,- "rootPath": self.workspace_root,- "processId": os.getpid(),- "workspaceFolders": [{"name": "workspace", "uri": root_uri}],- "initializationOptions": self._init_options,- "capabilities": _CLIENT_CAPABILITIES,+ "rootUri": file_uri(self.workspace_root), "rootPath": self.workspace_root, "processId": os.getpid(),+ "workspaceFolders": self._workspace_folders(),+ "initializationOptions": self._init_options, "capabilities": _CLIENT_CAPABILITIES,}result = await asyncio.wait_for(self._send_request("initialize", params), timeout=INITIALIZE_TIMEOUT)- self._sync_kind = self._extract_sync_kind(result.get("capabilities") or {})-+ sync = (result.get("capabilities") or {}).get("textDocumentSync")+ if isinstance(sync, dict):+ sync = sync.get("change")+ self._sync_kind = sync if isinstance(sync, int) else 1 # default to Fullawait 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})- @staticmethod- def _extract_sync_kind(capabilities: dict) -> int:- sync = capabilities.get("textDocumentSync")- if isinstance(sync, dict):- 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."""if self._stopping:@@ -339,7 +311,7 @@ class LSPClient:passtry:await self._send_notification("exit", None)- except Exception:+ except Exception: # noqa: BLE001passfinally:self._state = "stopped"@@ -349,10 +321,7 @@ class LSPClient:async def _cancel_task(task: Optional[asyncio.Task]) -> None:if task is not None and not task.done():task.cancel()- try:- await task- except (asyncio.CancelledError, Exception): # noqa: BLE001- pass+ await asyncio.gather(task, return_exceptions=True)async def _cleanup_process(self) -> None:async with self._cleanup_lock:@@ -406,10 +375,9 @@ class LSPClient:try:return await asyncio.wait_for(self._send_request(method, params), timeout=timeout)except LSPRequestError as e:- if e.code == ERROR_CONTENT_MODIFIED and attempt < MAX_CONTENT_MODIFIED_RETRIES:- await asyncio.sleep(RETRY_BASE_DELAY * (2 ** attempt))- continue- raise+ if e.code != ERROR_CONTENT_MODIFIED or attempt >= MAX_CONTENT_MODIFIED_RETRIES:+ raise+ await asyncio.sleep(RETRY_BASE_DELAY * (2 ** attempt))async def _send_notification(self, method: str, params: Any) -> None:self._require_open(method)@@ -440,15 +408,14 @@ class LSPClient:method = msg.get("method", "")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(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}"))- return- await self._send_reply(make_response(req_id, result))+ reply = make_error_response(req_id, ERROR_METHOD_NOT_FOUND, f"method not found: {method}")+ else:+ try:+ reply = make_response(req_id, 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)+ reply = make_error_response(req_id, -32000, f"handler failed: {e}")+ await self._send_reply(reply)def _dispatch_notification(self, method: str, msg: dict) -> None:handler = self._notification_handlers.get(method)@@ -464,28 +431,27 @@ class LSPClient:async def _handle_null(self, params: Any) -> Any:return None+ async def _handle_workspace_folders(self, params: Any) -> Any:+ return self._workspace_folders()+async def _handle_workspace_configuration(self, params: Any) -> Any:"""Walk dotted ``section`` paths through initializationOptions; null when missing."""if not isinstance(params, dict):return [None]-- def lookup(item: Any) -> Any:- if not isinstance(item, dict):+ return [self._config_section(item) for item in params.get("items") or []]++ def _config_section(self, item: Any) -> Any:+ if not isinstance(item, dict):+ return None+ section = item.get("section")+ if not section or not self._init_options:+ 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):return None- section = item.get("section")- if not section or not self._init_options:- 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):- return None- cur = cur[part]- return cur-- 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)}]+ cur = cur[part]+ return curdef _handle_publish_diagnostics(self, params: Any) -> None:if not isinstance(params, dict) or not isinstance(params.get("uri"), str):@@ -497,13 +463,12 @@ class LSPClient:doc.seed_seen = Truedoc.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.+ # 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.return- # Tag with the echoed version when provided; otherwise credit the- # current version (a push observed after our change describes it or- # newer). doc.version is -1 for never-opened paths (relatedDocuments- # spillover), keeping them unfresh.+ # Tag with the echoed version when provided; otherwise credit the current+ # version (a push observed after our change describes it or newer). doc.version+ # is -1 for never-opened paths (relatedDocuments spillover), keeping them unfresh.doc.push_version = version if isinstance(version, int) else doc.version# Keep the Event sticky-set so in-progress waits resolve; waiters# compare ``_push_counter`` to detect a genuinely new push.@@ -529,28 +494,26 @@ class LSPClient:await self._send_notification("workspace/didChangeWatchedFiles", {"changes": [{"uri": uri, "type": 1 if doc is None else 2}]})-- if doc is not None:- change: Dict[str, Any] = {"text": text}- if self._sync_kind == 2:- change["range"] = {"start": {"line": 0, "character": 0}, "end": _end_position(doc.text)}- new_version = doc.version + 1+ if doc is None:+ # 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/didChange",- {"textDocument": {"uri": uri, "version": new_version}, "contentChanges": [change]},+ "textDocument/didOpen",+ {"textDocument": {"uri": uri, "languageId": language_id, "version": 0, "text": text}},)- # Bumping the version is the whole invalidation story (see _DocState).- doc.version, doc.text = new_version, text- return new_version-- # Fresh state: anything a pre-open push stashed under this path- # (relatedDocuments spillover) is discarded.- self._docs[abs_path] = _DocState(version=0, text=text)+ return 0+ change: Dict[str, Any] = {"text": text}+ if self._sync_kind == 2:+ change["range"] = {"start": {"line": 0, "character": 0}, "end": _end_position(doc.text)}+ new_version = doc.version + 1await self._send_notification(- "textDocument/didOpen",- {"textDocument": {"uri": uri, "languageId": language_id, "version": 0, "text": text}},+ "textDocument/didChange",+ {"textDocument": {"uri": uri, "version": new_version}, "contentChanges": [change]},)- return 0+ # Bumping the version is the whole invalidation story (see _DocState).+ doc.version, doc.text = new_version, text+ return new_versionasync def save_file(self, path: str) -> None:"""Send didSave for ``path``. Some linters re-scan only on save."""@@ -564,9 +527,8 @@ class LSPClient:async def _pull_document_diagnostics(self, path: str) -> None:"""Send ``textDocument/diagnostic`` for one file into the pull store.- Results are tagged with the version captured at send time, so a- didChange racing past the request makes them stale automatically.- Silently no-ops on errors (server may not support pull).+ Results are tagged with the version captured at send time, so a didChange racing+ past the request makes them stale automatically. Silently no-ops on errors."""abs_path = os.path.abspath(path)doc = self._docs.get(abs_path)@@ -593,21 +555,13 @@ class LSPClient:d.pull = itemsd.pull_version = d.version if tag is None else tag- async def wait_for_diagnostics(- self,- path: str,- version: int,- *,- mode: str = "document",- timeout: Optional[float] = None,- ) -> bool:- """Wait for fresh diagnostics for ``path`` at ``version``.-- ``mode`` is ``"document"`` (5s) or ``"full"`` (10s); ``timeout`` overrides- the budget (this is how ``lsp.wait_timeout`` reaches the loop). Returns- True when fresh data arrived (push at/after our didChange, or a pull- answered after it), False on timeout. Callers must treat False as- "no data", NOT "no errors" — the stores may still hold stale entries.+ async def wait_for_diagnostics(self, path: str, version: int, *, mode: str = "document",+ timeout: Optional[float] = None) -> bool:+ """Wait for fresh diagnostics for ``path`` at ``version``; True iff fresh data arrived in budget.++ ``mode`` is ``"document"`` (5s) or ``"full"`` (10s); ``timeout`` overrides the+ budget (how ``lsp.wait_timeout`` reaches the loop). Callers must treat False+ as "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 not (timeout is not None and timeout > 0):@@ -615,7 +569,6 @@ class LSPClient:now = asyncio.get_event_loop().timedeadline = now() + timeoutabs_path = os.path.abspath(path)-while True:if not self._connection_is_open():raise LSPProtocolError("server connection closed while waiting for diagnostics")@@ -632,7 +585,7 @@ class LSPClient:t.cancel()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)):+ if doc and doc.fresh(version):return Trueasync def _await_push(self, timeout: float) -> bool:@@ -673,9 +626,8 @@ class LSPClient:def diagnostics_for(self, path: str, *, fresh_only: bool = False) -> List[Dict[str, Any]]:"""Merged + deduped push/pull diagnostics for one file.- With ``fresh_only=True`` a store only contributes when its version tag- has caught up to the document's version — report paths must use this- so "stale errors" and "no errors" aren't conflated.+ With ``fresh_only=True`` a store only contributes once its version tag has caught+ up to the document's — report paths must use this so "stale" and "clean" aren't conflated."""doc = self._docs.get(os.path.abspath(path))if doc is None:@@ -698,19 +650,16 @@ def _dedupe(*lists: List[Dict[str, Any]]) -> List[Dict[str, Any]]:def _diagnostic_key(d: Dict[str, Any]) -> str:"""Content-equality key: severity + code + source + message + range.- Shared with the manager's cross-edit delta filter (as ``_diag_key``) so- both layers agree on diagnostic identity. The range is included so an- identical error introduced at a second site still surfaces as new; the- manager line-shifts its baseline into post-edit coordinates before keying.+ Shared with the manager's cross-edit delta filter (as ``_diag_key``) so both layers+ agree on identity. Range is included so an identical error at a second site still+ surfaces as new; the manager line-shifts its baseline into post-edit coordinates first."""rng = d.get("range") or {}start = rng.get("start") or {}end = rng.get("end") or {}code = d.get("code")return "\x00".join([- str(d.get("severity") or 1),- "" if code is None else str(code),- str(d.get("source") or ""),+ 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)}",])diff --git a/agent/lsp/eventlog.py b/agent/lsp/eventlog.pyindex ecfae14e5c3..4ab8363d891 100644--- a/agent/lsp/eventlog.py+++ b/agent/lsp/eventlog.py@@ -57,9 +57,7 @@ def _emit_once(bucket: set, key: Tuple, server_id: str, level: int, first: str,_emit(server_id, logging.DEBUG, repeat)-# ----------------------------------------------------------------------------# Public event helpers — call these from the LSP layer.-# ---------------------------------------------------------------------------+# ---- Public event helpers — call these from the LSP layer ----def log_clean(server_id: str, file_path: str) -> None:@@ -137,16 +135,7 @@ def reset_announce_caches() -> None:__all__ = [- "event_log",- "log_clean",- "log_disabled",- "log_active",- "log_diagnostics",- "log_no_project_root",- "log_server_unavailable",- "log_timeout",- "log_server_error",- "log_spawn_failed",- "log_reaped",+ "event_log", "log_clean", "log_disabled", "log_active", "log_diagnostics", "log_no_project_root",+ "log_server_unavailable", "log_timeout", "log_server_error", "log_spawn_failed", "log_reaped","reset_announce_caches",]diff --git a/agent/lsp/manager.py b/agent/lsp/manager.pyindex a93efcea9ef..ed23b2beeeb 100644--- a/agent/lsp/manager.py+++ b/agent/lsp/manager.py@@ -1,14 +1,13 @@"""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 (``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.+:class:`LSPService` bridges the synchronous file_operations layer and the 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@@ -20,11 +19,7 @@ import timefrom typing import Any, Callable, Dict, List, Optional, Tuplefrom agent.lsp import eventlog-from agent.lsp.client import (- DIAGNOSTICS_DOCUMENT_WAIT,- LSPClient,- _diagnostic_key as _diag_key,-)+from agent.lsp.client import DIAGNOSTICS_DOCUMENT_WAIT, LSPClient, _diagnostic_key as _diag_keyfrom agent.lsp.servers import ServerContext, ServerDef, find_server_for_file, language_id_forfrom agent.lsp.workspace import clear_cache, resolve_workspace_for_file@@ -34,6 +29,7 @@ DEFAULT_IDLE_TIMEOUT = 600 # seconds; servers idle for >10min get reapedMIN_IDLE_TIMEOUT = 30 # floor for config values; must exceed any per-op wait budget_Key = Tuple[str, str]+_Diags = List[Dict[str, Any]]class _BackgroundLoop:@@ -52,8 +48,7 @@ class _BackgroundLoop:self._ready.wait(timeout=5.0)def _run_forever(self) -> None:- loop = asyncio.new_event_loop()- self._loop = loop+ loop = self._loop = asyncio.new_event_loop()asyncio.set_event_loop(loop)self._ready.set()try:@@ -81,7 +76,7 @@ class _BackgroundLoop:raisedef stop(self) -> None:- loop = self._loop+ loop, self._loop = self._loop, Noneif loop is None:returntry:@@ -90,7 +85,6 @@ class _BackgroundLoop:passif self._thread is not None:self._thread.join(timeout=2.0)- self._loop = Noneself._thread = None@@ -98,12 +92,7 @@ class LSPService:"""The process-wide LSP service; use :func:`agent.lsp.get_service` rather than constructing directly."""def __init__(- self,- *,- enabled: bool,- wait_mode: str,- wait_timeout: float,- install_strategy: str,+ self, *, enabled: bool, wait_mode: str, wait_timeout: float, install_strategy: str,binary_overrides: Optional[Dict[str, List[str]]] = None,env_overrides: Optional[Dict[str, Dict[str, str]]] = None,init_overrides: Optional[Dict[str, Dict[str, Any]]] = None,@@ -132,7 +121,7 @@ class LSPService:self._state_lock = threading.Lock()self._idle_reaper_task: Optional[asyncio.Task] = None# abs file path → diagnostics snapshot taken immediately before a write.- self._delta_baseline: Dict[str, List[Dict[str, Any]]] = {}+ self._delta_baseline: Dict[str, _Diags] = {}if self._enabled and self._idle_timeout > 0:self._loop.run(self._start_idle_reaper(), timeout=2.0)@@ -146,19 +135,17 @@ class LSPService:except Exception as e: # noqa: BLE001logger.debug("LSP config load failed: %s", e)return None-lsp_cfg = (cfg.get("lsp") or {}) if isinstance(cfg, dict) else {}if not isinstance(lsp_cfg, dict):lsp_cfg = {}-try:idle_timeout = float(lsp_cfg.get("idle_timeout", DEFAULT_IDLE_TIMEOUT))except (TypeError, ValueError):idle_timeout = DEFAULT_IDLE_TIMEOUTif 0 < idle_timeout < MIN_IDLE_TIMEOUT:- # Below the per-op wait budget the reaper could kill a client- # mid-flight and the outer timeout would then mark the pair broken- # for the process lifetime. Clamp (0 still disables).+ # Below the per-op wait budget the reaper could kill a client mid-flight and+ # the outer timeout would then mark the pair broken for the process lifetime.+ # Clamp (0 still disables).idle_timeout = MIN_IDLE_TIMEOUTservers_cfg = lsp_cfg.get("servers") or {}servers = {n: c for n, c in servers_cfg.items() if isinstance(c, dict)} if isinstance(servers_cfg, dict) else {}@@ -177,9 +164,7 @@ class LSPService:idle_timeout=idle_timeout,)- # ------------------------------------------------------------------- # public API- # ------------------------------------------------------------------+ # ---- public API ----def is_active(self) -> bool:"""Return True iff this service should be consulted at all."""@@ -200,13 +185,8 @@ class LSPService:return (srv.server_id, ws_root)def enabled_for(self, file_path: str) -> bool:- """Return True iff LSP should run for this file.-- Gates on a registered, non-disabled server for the extension, on- git-workspace detection, and on the pair not being in the broken-set- (so a failed server costs no spawn attempts or timeouts until- ``hermes lsp restart`` or process exit).- """+ """True iff LSP should run for this file: registered non-disabled server, git workspace,+ and pair not broken (a failed server costs nothing until ``hermes lsp restart`` / exit)."""srv = find_server_for_file(file_path) if self._enabled else Noneif srv is None or srv.server_id in self._disabled_servers:return False@@ -222,8 +202,7 @@ class LSPService:if not self.enabled_for(file_path):returntry:- # Outer budget must exceed the inner wait or a slow-but-alive- # server gets falsely marked broken.+ # Outer budget must exceed the inner wait or a slow-but-alive 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)except Exception as e: # noqa: BLE001@@ -233,23 +212,16 @@ class LSPService:self._delta_baseline[os.path.abspath(file_path)] = diags or []def get_diagnostics_sync(- self,- file_path: str,- *,- delta: bool = True,- timeout: Optional[float] = None,+ self, file_path: str, *, delta: bool = True, timeout: Optional[float] = None,line_shift: Optional[Callable[[int], Optional[int]]] = None,- ) -> List[Dict[str, Any]]:- """Synchronously open ``file_path``, wait for diagnostics, return them.-- With ``delta`` (default) the result excludes anything in the baseline- from :meth:`snapshot_baseline`. ``line_shift`` (built by- :func:`agent.lsp.range_shift.build_line_shift`) remaps the baseline- into post-edit coordinates first, so pre-existing diagnostics that- merely moved don't look introduced by this edit.-- Returns ``[]`` when LSP is disabled, no workspace/server matches, or- the server can't be spawned. Never raises.+ ) -> _Diags:+ """Synchronously open ``file_path``, wait for diagnostics, return them. Never raises.++ With ``delta`` (default) the result excludes the :meth:`snapshot_baseline`;+ ``line_shift`` (from :func:`agent.lsp.range_shift.build_line_shift`) remaps+ that baseline into post-edit coordinates first, so pre-existing diagnostics+ that merely moved don't look introduced by this edit. ``[]`` when LSP is+ disabled, nothing matches, or the server can't be spawned."""if not self.enabled_for(file_path):return []@@ -266,15 +238,12 @@ class LSPService:logger.debug("LSP diagnostics fetch failed for %s: %s", file_path, e)self._mark_broken_for_file(file_path, e)return []-if diags is None:- # Server alive but no verdict on the post-edit content in budget- # (common for tsserver on big projects). Report "no data" rather- # than stale stores — that would be the ghost-diagnostics bug.- # Not marked broken: slow is not dead.+ # Server alive but no verdict on the post-edit content in budget (common for+ # tsserver on big projects). Report "no data" rather than stale stores — that+ # would be the ghost-diagnostics bug. Not marked broken: slow is not dead.eventlog.log_timeout(server_id, file_path, kind="fresh diagnostics")return []-if delta:diags = self._apply_delta(file_path, diags, line_shift)if diags:@@ -283,8 +252,7 @@ class LSPService: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]]:+ def _apply_delta(self, file_path: str, diags: _Diags, line_shift: Optional[Callable[[int], Optional[int]]]) -> _Diags:"""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 []@@ -307,11 +275,9 @@ class LSPService: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.- The outer ``_loop.run`` timeout cancels the in-flight spawn before- ``_get_or_spawn`` could record the failure, so without this every- later write would re-pay the full timeout. Also kills any- half-initialized client left in ``_clients`` and logs the failure once.- ``exc`` is used only for logging.+ The outer ``_loop.run`` timeout cancels the in-flight spawn before ``_get_or_spawn``+ could record the failure; without this every later write would re-pay the full+ timeout. Also kills any half-initialized client and logs the failure once."""srv = find_server_for_file(file_path)key = self._broken_key(srv, file_path) if srv is not None else None@@ -342,23 +308,32 @@ class LSPService:self._loop.stop()clear_cache()- # ------------------------------------------------------------------- # async internals- # ------------------------------------------------------------------+ 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}+ for k, c in self._clients.items()+ ]+ broken = list(self._broken)+ return {+ "enabled": self._enabled, "wait_mode": self._wait_mode, "wait_timeout": self._wait_timeout,+ "install_strategy": self._install_strategy, "clients": clients, "broken": broken,+ "disabled_servers": sorted(self._disabled_servers),+ }++ # ---- async internals ----- async def _snapshot_async(self, file_path: str) -> List[Dict[str, Any]]:- # No fresh data for the pre-edit content → empty baseline. Safe: the- # delta filter then removes less, never more. Never seed from stale stores.+ async def _snapshot_async(self, file_path: str) -> _Diags:+ # No fresh data for the pre-edit content → empty baseline. Safe: the delta+ # filter then removes less, never more. Never seed from stale stores.return await self._open_and_wait_async(file_path, snapshot=True) or []- async def _open_and_wait_async(self, file_path: str, *, snapshot: bool = False) -> Optional[List[Dict[str, Any]]]:- """Open + wait for FRESH diagnostics.+ async def _open_and_wait_async(self, file_path: str, *, snapshot: bool = False) -> Optional[_Diags]:+ """Open + wait for FRESH diagnostics: ``[]`` = checked clean, ``None`` = no verdict in budget.- Returns the fresh list, or ``None`` when the server produced no- post-change data in budget. ``[]`` means "checked, clean"; ``None``- means "no verdict" — callers must not substitute stale data for either.- ``snapshot`` mode (pre-write baseline) skips didSave and uses the- default wait budget.+ Callers must not substitute stale data for either. ``snapshot`` mode+ (pre-write baseline) skips didSave and uses the default wait budget."""client = await self._get_or_spawn(file_path)if client is None:@@ -368,8 +343,7 @@ class LSPService:if not snapshot:await client.save_file(file_path)fresh = await client.wait_for_diagnostics(- file_path, version, mode=self._wait_mode,- timeout=None if snapshot else self._wait_timeout,+ file_path, version, mode=self._wait_mode, timeout=None if snapshot else self._wait_timeout,)except Exception as e: # noqa: BLE001if snapshot:@@ -380,7 +354,7 @@ class LSPService:self._touch(client)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]]:+ async def _current_diags_async(self, file_path: str) -> _Diags:ws, gated = resolve_workspace_for_file(file_path)srv = find_server_for_file(file_path)if not (ws and gated and srv):@@ -400,12 +374,11 @@ class LSPService:if not (ws_root and gated):eventlog.log_no_project_root(srv.server_id, file_path)return None- per_server_root = srv.resolve_root(file_path, ws_root)- if per_server_root is None:+ root = srv.resolve_root(file_path, ws_root)+ if root is None:eventlog.log_disabled(srv.server_id, file_path, "exclude marker hit (server gated off)")return None-- key = (srv.server_id, per_server_root)+ key = (srv.server_id, root)if key in self._broken:return Nonewith self._state_lock:@@ -415,25 +388,23 @@ class LSPService:eventlog.log_active(*key)return clientspawning = self._spawning.get(key)- if spawning is None:+ owner = spawning is None+ if owner:spawning = self._spawning[key] = asyncio.get_running_loop().create_future()- owner = True- else:- owner = Falseif not owner:try:return await spawningexcept Exception: # noqa: BLE001return Nonetry:- client = await self._spawn_client(srv, per_server_root)- if client is not None:+ client = await self._spawn_client(srv, root)+ if client is None:+ self._broken.add(key)+ else:with self._state_lock:self._clients[key] = clientself._last_used[key] = time.time()eventlog.log_active(*key)- else:- self._broken.add(key)spawning.set_result(client)return clientfinally:@@ -443,25 +414,17 @@ class LSPService: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,+ 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.+ # Binary not locatable (auto-install off, manual-only, or install failed) — surface once.eventlog.log_server_unavailable(srv.server_id, srv.server_id)return Noneclient = 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,+ 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:@@ -471,9 +434,6 @@ class LSPService:return Nonereturn client- async def _start_idle_reaper(self) -> None:- self._idle_reaper_task = asyncio.create_task(self._idle_reaper_loop())-def _touch(self, client: LSPClient) -> None:"""Refresh last-used; guarded on membership so a client reaped mid-operation can't resurrect its entry."""key = (client.server_id, client.workspace_root)@@ -481,6 +441,9 @@ class LSPService:if key in self._clients:self._last_used[key] = time.time()+ async def _start_idle_reaper(self) -> None:+ self._idle_reaper_task = asyncio.create_task(self._idle_reaper_loop())+async def _idle_reaper_loop(self) -> None:interval = min(60.0, self._idle_timeout)while True:@@ -517,23 +480,5 @@ class LSPService:self._last_used.clear()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}- for k, c in self._clients.items()- ]- broken = list(self._broken)- return {- "enabled": self._enabled,- "wait_mode": self._wait_mode,- "wait_timeout": self._wait_timeout,- "install_strategy": self._install_strategy,- "clients": clients,- "broken": broken,- "disabled_servers": sorted(self._disabled_servers),- }-__all__ = ["LSPService"]diff --git a/agent/lsp/protocol.py b/agent/lsp/protocol.pyindex 9f800093a4b..ab98aecabde 100644--- a/agent/lsp/protocol.py+++ b/agent/lsp/protocol.py@@ -89,12 +89,10 @@ async def read_message(reader: asyncio.StreamReader) -> Optional[dict]:raise LSPProtocolError(f"non-integer Content-Length: {cl!r}") from eif n < 0 or n > _MAX_BODY_BYTES:raise LSPProtocolError(f"unreasonable Content-Length: {n}")-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-try:return json.loads(body.decode("utf-8"))except json.JSONDecodeError as e:@@ -105,18 +103,12 @@ async def read_message(reader: asyncio.StreamReader) -> Optional[dict]:def make_notification(method: str, params: Any) -> dict:"""Build a JSON-RPC 2.0 notification envelope (no ``id``)."""- msg: dict = {"jsonrpc": "2.0", "method": method}- if params is not None:- msg["params"] = params- return msg+ return {"jsonrpc": "2.0", "method": method, **({} if params is None else {"params": params})}def make_request(req_id: int, method: str, params: Any) -> dict:"""Build a JSON-RPC 2.0 request envelope."""- msg: dict = {"jsonrpc": "2.0", "id": req_id, "method": method}- if params is not None:- msg["params"] = params- return msg+ return {"jsonrpc": "2.0", "id": req_id, "method": method, **({} if params is None else {"params": params})}def make_response(req_id: Any, result: Any) -> dict:@@ -126,9 +118,7 @@ def make_response(req_id: Any, result: Any) -> dict:def make_error_response(req_id: Any, code: int, message: str, data: Any = None) -> dict:"""Build a JSON-RPC 2.0 error response envelope."""- err: dict = {"code": code, "message": message}- if data is not None:- err["data"] = data+ err = {"code": code, "message": message, **({} if data is None else {"data": data})}return {"jsonrpc": "2.0", "id": req_id, "error": err}@@ -151,15 +141,7 @@ def classify_message(msg: dict) -> Tuple[str, Any]:__all__ = [- "ERROR_CONTENT_MODIFIED",- "ERROR_METHOD_NOT_FOUND",- "LSPProtocolError",- "LSPRequestError",- "encode_message",- "read_message",- "make_request",- "make_notification",- "make_response",- "make_error_response",- "classify_message",+ "ERROR_CONTENT_MODIFIED", "ERROR_METHOD_NOT_FOUND", "LSPProtocolError", "LSPRequestError",+ "encode_message", "read_message", "make_request", "make_notification", "make_response",+ "make_error_response", "classify_message",]diff --git a/agent/lsp/reporter.py b/agent/lsp/reporter.pyindex 269f82832ef..85f160fcc38 100644--- a/agent/lsp/reporter.py+++ b/agent/lsp/reporter.py@@ -80,11 +80,4 @@ def truncate(s: str, *, limit: int = MAX_TOTAL_CHARS) -> str:return s[: limit - len(marker)] + marker-__all__ = [- "SEVERITY_NAMES",- "DEFAULT_SEVERITIES",- "MAX_PER_FILE",- "format_diagnostic",- "report_for_file",- "truncate",-]+__all__ = ["SEVERITY_NAMES", "DEFAULT_SEVERITIES", "MAX_PER_FILE", "format_diagnostic", "report_for_file", "truncate"]