servers.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  1. """Server registry — per-language LSP server definitions.
  2. Each :class:`ServerDef` matches files (by extension or basename for
  3. extensionless files like ``Dockerfile``), resolves a project root, and
  4. assembles the spawn command. Auto-installation lives in
  5. :mod:`agent.lsp.install`; nothing here probes binaries until a file in
  6. that language is actually edited.
  7. """
  8. from __future__ import annotations
  9. import logging
  10. import os
  11. import shutil
  12. from dataclasses import dataclass, field
  13. from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple
  14. from agent.lsp.workspace import nearest_root
  15. logger = logging.getLogger("agent.lsp.servers")
  16. # LSP languageId for ``textDocument/didOpen``, as language → extensions. A few
  17. # servers (typescript-language-server, vue-language-server) refuse wrong IDs.
  18. _EXTS_BY_LANGUAGE: dict[str, Sequence[str]] = {
  19. "python": (".py", ".pyi"),
  20. "typescript": (".ts", ".mts", ".cts"),
  21. "typescriptreact": (".tsx",),
  22. "javascript": (".js", ".mjs", ".cjs"),
  23. "javascriptreact": (".jsx",),
  24. "vue": (".vue",), "svelte": (".svelte",), "astro": (".astro",),
  25. "go": (".go",), "rust": (".rs",),
  26. "ruby": (".rb", ".rake", ".gemspec", ".ru"),
  27. "c": (".c", ".h"),
  28. "cpp": (".cc", ".cpp", ".cxx", ".hh", ".hpp", ".hxx"),
  29. "csharp": (".cs", ".csx"), "fsharp": (".fs", ".fsi", ".fsx"),
  30. "swift": (".swift",), "java": (".java",), "kotlin": (".kt", ".kts"),
  31. "yaml": (".yaml", ".yml"), "json": (".json",), "jsonc": (".jsonc",),
  32. "lua": (".lua",), "php": (".php",), "blade": (".blade.php",), "prisma": (".prisma",), "dart": (".dart",),
  33. "ocaml": (".ml", ".mli"),
  34. "shellscript": (".sh", ".bash", ".zsh"),
  35. "terraform": (".tf", ".tfvars"),
  36. "latex": (".tex",), "bibtex": (".bib",), "gleam": (".gleam",),
  37. "clojure": (".clj", ".cljc", ".edn"), "clojurescript": (".cljs",),
  38. "nix": (".nix",), "typst": (".typ", ".typc"), "haskell": (".hs", ".lhs"),
  39. "julia": (".jl",), "elixir": (".ex", ".exs"), "zig": (".zig", ".zon"),
  40. "dockerfile": (".dockerfile",),
  41. "powershell": (".ps1", ".psm1", ".psd1"),
  42. }
  43. LANGUAGE_BY_EXT: dict[str, str] = {ext: lang for lang, exts in _EXTS_BY_LANGUAGE.items() for ext in exts}
  44. _SpawnFn = Callable[[str, "ServerContext"], Optional["SpawnSpec"]]
  45. _RootFn = Callable[[str, str], Optional[str]]
  46. @dataclass
  47. class SpawnSpec:
  48. """Result of resolving a server for a file (``None`` means skip)."""
  49. command: list[str]
  50. workspace_root: str
  51. cwd: str
  52. env: dict[str, str] = field(default_factory=dict)
  53. initialization_options: dict[str, Any] = field(default_factory=dict)
  54. seed_diagnostics_on_first_push: bool = False
  55. @dataclass
  56. class ServerDef:
  57. """One language server: ``resolve_root(file, ws)`` → per-server root or ``None`` to skip;
  58. ``build_spawn(root, ctx)`` → :class:`SpawnSpec` or ``None`` when the binary can't be found."""
  59. server_id: str
  60. extensions: tuple[str, ...]
  61. resolve_root: _RootFn
  62. build_spawn: _SpawnFn
  63. seed_first_push: bool = False
  64. description: str = ""
  65. # Server handles ``workspace/didChangeWorkspaceFolders``: one process serves every project root
  66. # (git worktrees included) as extra workspaceFolders instead of one process per root.
  67. multi_root: bool = False
  68. # didOpen languageId; "" = derive from LANGUAGE_BY_EXT (custom servers name theirs in config).
  69. language_id: str = ""
  70. def matches(self, file_path: str) -> bool:
  71. return _file_ext_or_basename(file_path) in self.extensions
  72. @dataclass
  73. class ServerContext:
  74. """User policy passed into :meth:`ServerDef.build_spawn` (install strategy, overrides)."""
  75. workspace_root: str
  76. install_strategy: str = "auto" # "auto" | "manual" | "off"
  77. binary_overrides: dict[str, list[str]] = field(default_factory=dict)
  78. env_overrides: dict[str, dict[str, str]] = field(default_factory=dict)
  79. init_overrides: dict[str, dict[str, Any]] = field(default_factory=dict)
  80. # Whether the server may load code the project ships (see workspace.is_trusted_workspace).
  81. # Defaults closed: a context built without a trust decision must never run the repo's code.
  82. trusted: bool = False
  83. # ---- helpers ----
  84. # Multi-part extensions that name a different language than their last segment: ``os.path.splitext``
  85. # would reduce ``home.blade.php`` to ``.php`` and hand Blade templates to the plain-PHP server.
  86. _COMPOUND_EXTS = (".blade.php",)
  87. def _file_ext_or_basename(path: str) -> str:
  88. """Lower-cased extension (compound ones first), or the full basename for extensionless files (``Dockerfile``)."""
  89. base = os.path.basename(path)
  90. lower = base.lower()
  91. return next((c for c in _COMPOUND_EXTS if lower.endswith(c)), None) or os.path.splitext(base)[1].lower() or base
  92. def _which(*names: str) -> Optional[str]:
  93. """Return the full path of the first command found on PATH."""
  94. return next((p for n in names if (p := shutil.which(n))), None)
  95. def _root_or_workspace(file_path: str, workspace: str, markers: Sequence[str], excludes: Sequence[str] = ()) -> Optional[str]:
  96. """``nearest_root`` with workspace fallback; ``None`` iff an exclude marker hit."""
  97. ceiling = os.path.dirname(workspace) if workspace else None
  98. found = nearest_root(file_path, markers, excludes=excludes, ceiling=ceiling)
  99. if found is None and excludes and nearest_root(file_path, markers, ceiling=ceiling) is not None:
  100. # None is ambiguous with excludes configured: a hit without them means
  101. # the exclude fired (gated off); otherwise fall back to the workspace.
  102. return None
  103. return found or workspace
  104. def _markers_root(markers: Optional[Sequence[str]], excludes: Sequence[str] = ()) -> _RootFn:
  105. """Root resolver over marker files; ``None`` markers means "always the workspace root"."""
  106. if markers is None:
  107. return lambda fp, ws: ws
  108. return lambda fp, ws: _root_or_workspace(fp, ws, markers, excludes=excludes)
  109. def _find_binary(ctx: ServerContext, server_id: str, which: Sequence[str], install_pkg: Optional[str]) -> Optional[str]:
  110. """Config override → PATH → (optional) auto-install; ``None`` when nothing resolves."""
  111. override = ctx.binary_overrides.get(server_id)
  112. bin_path = override[0] if override and override[0] and os.path.exists(override[0]) else _which(*which)
  113. if bin_path is None and install_pkg is not None:
  114. from agent.lsp.install import try_install
  115. bin_path = try_install(install_pkg, ctx.install_strategy)
  116. return bin_path
  117. def _make_spec(root: str, ctx: ServerContext, server_id: str, command: list[str],
  118. base_init: Optional[dict[str, Any]] = None, seed: bool = False) -> SpawnSpec:
  119. from pm import env_for
  120. init = ctx.init_overrides.get(server_id, {}) if base_init is None else {**base_init, **ctx.init_overrides.get(server_id, {})}
  121. env = env_for("node")
  122. env.update(ctx.env_overrides.get(server_id, {}))
  123. return SpawnSpec(command, root, root, env=env,
  124. initialization_options=init, seed_diagnostics_on_first_push=seed)
  125. def _simple_spawn(server_id: str, which: Sequence[str], args: Sequence[str] = (),
  126. install_pkg: Optional[str] = None, base_init: Optional[dict[str, Any]] = None,
  127. seed: bool = False, untrusted_init: Optional[dict[str, Any]] = None) -> _SpawnFn:
  128. """Build a spawn function for the common single-binary server shape; ``untrusted_init`` replaces
  129. ``base_init`` in an untrusted workspace (the server's own switch for not loading project code)."""
  130. def build(root: str, ctx: ServerContext) -> Optional[SpawnSpec]:
  131. bin_path = _find_binary(ctx, server_id, which, install_pkg)
  132. init = base_init if ctx.trusted or untrusted_init is None else untrusted_init
  133. return None if bin_path is None else _make_spec(root, ctx, server_id, [bin_path, *args], init, seed)
  134. return build
  135. # ---- bespoke spawn builders ----
  136. def _spawn_pyright(root: str, ctx: ServerContext) -> Optional[SpawnSpec]:
  137. bin_path = _find_binary(ctx, "pyright", ("pyright-langserver", "pyright"), "pyright")
  138. if bin_path is None:
  139. return None
  140. # If we got the cli ``pyright``, the langserver is its sibling — same suffix, since on Windows
  141. # the bare sibling is npm's unrunnable POSIX shim.
  142. stem, suffix = os.path.splitext(os.path.basename(bin_path))
  143. if stem == "pyright":
  144. sibling = os.path.join(os.path.dirname(bin_path), f"pyright-langserver{suffix}")
  145. if os.path.exists(sibling):
  146. bin_path = sibling
  147. # Point pyright at the project venv; its default "python on PATH" rarely is. Pyright executes
  148. # this interpreter, so a checkout's own venv is only used when the workspace is trusted.
  149. py = _detect_python(root if ctx.trusted else None)
  150. return _make_spec(root, ctx, "pyright", [bin_path, "--stdio"], {"python": {"pythonPath": py}} if py else {})
  151. def _detect_python(root: Optional[str]) -> Optional[str]:
  152. # Pyright needs the project's dependencies, not Hermes's runtime packages. ``VIRTUAL_ENV`` is the
  153. # operator's own environment; ``root`` (the project's .venv/venv) is None for an untrusted workspace.
  154. project = (os.path.join(root, ".venv"), os.path.join(root, "venv")) if root else ()
  155. venvs = [v for v in (os.environ.get("VIRTUAL_ENV"), *project) if v]
  156. paths = (os.path.join(v, sub) for v in venvs for sub in ("bin/python", "bin/python3", "Scripts/python.exe"))
  157. project_python = next((p for p in paths if os.path.exists(p)), None)
  158. if project_python is not None:
  159. return project_python
  160. from pm import installed_package
  161. installed = installed_package("python")
  162. return str(installed.binary) if installed is not None and installed.binary is not None else None
  163. _warned_once: set = set()
  164. def _warn_once(key: str, message: str) -> None:
  165. """Log ``message`` at WARNING the first time ``key`` is seen in this process."""
  166. if key not in _warned_once:
  167. _warned_once.add(key)
  168. logger.warning(message)
  169. def _spawn_bash_ls(root: str, ctx: ServerContext) -> Optional[SpawnSpec]:
  170. bin_path = _find_binary(ctx, "bash-language-server", ("bash-language-server",), "bash-language-server")
  171. if bin_path is None:
  172. return None
  173. # bash-language-server delegates diagnostics to shellcheck; without it the
  174. # server runs but never reports anything. Warn once so the gap is visible.
  175. if _which("shellcheck") is None:
  176. _warn_once("shellcheck", "bash-language-server: shellcheck not found on PATH — diagnostics will be empty "
  177. "until shellcheck is installed (apt: shellcheck, brew: shellcheck, scoop: shellcheck).")
  178. return _make_spec(root, ctx, "bash-language-server", [bin_path, "start"])
  179. _VUE_REINSTALL = (
  180. "delete <HERMES_HOME>/lsp/node_modules/@vue and <HERMES_HOME>/lsp/bin/vue-language-server*, "
  181. "then run: hermes lsp install vue-language-server"
  182. )
  183. _VUE_TUNNEL_MSG = (
  184. "vue-language-server: the installed @vue/language-server is 3.x, which only works behind a client-hosted "
  185. f"tsserver tunnel Hermes does not run — no diagnostics will arrive. Reinstall the self-hosting 2.x line: {_VUE_REINSTALL}"
  186. )
  187. _VUE_TSDK_MSG = (
  188. "vue-language-server: no JavaScript TypeScript SDK (typescript/lib/typescript.js) next to the server or under "
  189. f"the project's node_modules — diagnostics are skipped. Reinstall (the recipe co-installs one): {_VUE_REINSTALL}"
  190. )
  191. def _node_modules_trees(bin_path: str, root: Optional[str]) -> list[str]:
  192. """``node_modules`` trees that may hold a server and its TypeScript SDK: the launcher's own tree
  193. (symlinks resolved), Hermes staging, then the project's (``root`` None: Hermes's trees only, for
  194. TypeScript's SDK pin in an untrusted workspace, whose own JavaScript must not load)."""
  195. from agent.lsp.install import hermes_lsp_bin_dir
  196. trees = [str(hermes_lsp_bin_dir().parent / "node_modules")] + ([os.path.join(root, "node_modules")] if root else [])
  197. real = os.path.realpath(bin_path)
  198. marker = f"{os.sep}node_modules{os.sep}"
  199. if (idx := real.rfind(marker)) >= 0:
  200. trees.insert(0, real[: idx + len(marker) - 1])
  201. return trees
  202. def _vue_server_major(trees: Sequence[str]) -> int:
  203. """Major version of the first ``@vue/language-server`` found in ``trees``; 0 when unreadable."""
  204. import json
  205. for tree in trees:
  206. try:
  207. with open(os.path.join(tree, "@vue", "language-server", "package.json"), encoding="utf-8-sig") as fh:
  208. return int(str(json.load(fh).get("version", "")).split(".")[0])
  209. except (OSError, ValueError):
  210. continue
  211. return 0
  212. def _typescript_sdk_dir(trees: Sequence[str]) -> Optional[str]:
  213. """First ``typescript/lib`` in ``trees`` holding a JS ``typescript.js`` (TypeScript 7+ ships none)."""
  214. cands = (os.path.join(tree, "typescript", "lib") for tree in trees)
  215. return next((c for c in cands if os.path.isfile(os.path.join(c, "typescript.js"))), None)
  216. def _spawn_vue(root: str, ctx: ServerContext) -> Optional[SpawnSpec]:
  217. """Spawn @vue/language-server 2.x self-hosting TypeScript (``hybridMode`` off, explicit ``tsdk``)."""
  218. bin_path = _find_binary(ctx, "vue-language-server", ("vue-language-server",), "@vue/language-server")
  219. if bin_path is None:
  220. return None
  221. trees = _node_modules_trees(bin_path, root)
  222. if _vue_server_major(trees) >= 3:
  223. _warn_once("vue-tunnel", _VUE_TUNNEL_MSG)
  224. return None
  225. tsdk = _typescript_sdk_dir(trees)
  226. if tsdk is None:
  227. _warn_once("vue-tsdk", _VUE_TSDK_MSG)
  228. return None
  229. return _make_spec(root, ctx, "vue-language-server", [bin_path, "--stdio"],
  230. {"typescript": {"tsdk": tsdk}, "vue": {"hybridMode": False}})
  231. _TS_UNTRUSTED_MSG = (
  232. "typescript-language-server: no TypeScript SDK next to the server, and this workspace is untrusted so its "
  233. "own node_modules/typescript is not loaded — diagnostics are skipped. Reinstall: hermes lsp install "
  234. "typescript-language-server, or list the workspace under lsp.trusted_workspaces."
  235. )
  236. def _spawn_typescript(root: str, ctx: ServerContext) -> Optional[SpawnSpec]:
  237. """typescript-language-server loads the workspace's own ``node_modules/typescript`` unless
  238. ``tsserver.path`` names another, so an untrusted workspace is pinned to Hermes's copy."""
  239. bin_path = _find_binary(ctx, "typescript", ("typescript-language-server",), "typescript-language-server")
  240. if bin_path is None:
  241. return None
  242. base: dict[str, Any] = {}
  243. if not ctx.trusted:
  244. sdk = _typescript_sdk_dir(_node_modules_trees(bin_path, None))
  245. if sdk is None:
  246. _warn_once("ts-untrusted", _TS_UNTRUSTED_MSG)
  247. return None
  248. base = {"tsserver": {"path": sdk}}
  249. return _make_spec(root, ctx, "typescript", [bin_path, "--stdio"], base, seed=True)
  250. def _find_pses_bundle(ctx: ServerContext) -> Optional[str]:
  251. """Locate the PowerShellEditorServices bundle dir (release zip, manual install). Resolution order:
  252. ``lsp.servers.powershell.command[0]`` when a directory, ``init_overrides["powershell"]["bundlePath"]``,
  253. ``PSES_BUNDLE_PATH`` env, then ``<HERMES_HOME>/lsp/PowerShellEditorServices``."""
  254. from hermes_constants import get_hermes_home
  255. override = ctx.binary_overrides.get("powershell")
  256. init = ctx.init_overrides.get("powershell", {})
  257. candidates = [
  258. override[0] if override else None,
  259. str(init["bundlePath"]) if isinstance(init, dict) and init.get("bundlePath") else None,
  260. os.environ.get("PSES_BUNDLE_PATH"),
  261. os.path.join(str(get_hermes_home()), "lsp", "PowerShellEditorServices"),
  262. ]
  263. for cand in filter(None, candidates):
  264. # Accept either the bundle root or the inner module dir.
  265. if os.path.isfile(os.path.join(cand, "PowerShellEditorServices", "Start-EditorServices.ps1")):
  266. return cand
  267. if os.path.isfile(os.path.join(cand, "Start-EditorServices.ps1")):
  268. return os.path.dirname(cand)
  269. return None
  270. _PSES_MISSING_MSG = (
  271. "powershell: pwsh found but the PowerShellEditorServices bundle is missing. Download the release zip from "
  272. "https://github.com/PowerShell/PowerShellEditorServices/releases, extract it, and either set "
  273. "lsp.servers.powershell.command to the bundle path or unzip it to <HERMES_HOME>/lsp/PowerShellEditorServices."
  274. )
  275. def _spawn_powershell_es(root: str, ctx: ServerContext) -> Optional[SpawnSpec]:
  276. """Spawn PowerShellEditorServices: needs a ``pwsh``/``powershell`` host plus the module bundle."""
  277. pwsh = _which("pwsh", "powershell")
  278. if pwsh is None:
  279. return None
  280. bundle = _find_pses_bundle(ctx)
  281. if bundle is None:
  282. _warn_once("pses-bundle", _PSES_MISSING_MSG)
  283. return None
  284. start_script = os.path.join(bundle, "PowerShellEditorServices", "Start-EditorServices.ps1")
  285. # PSES writes connection info to the session details file on startup.
  286. session_dir = hermes_lsp_session_dir()
  287. inner = (
  288. f"& '{start_script}' -BundledModulesPath '{bundle}' "
  289. f"-LogPath '{os.path.join(session_dir, 'pses.log')}' "
  290. f"-SessionDetailsPath '{os.path.join(session_dir, f'pses-session-{os.getpid()}.json')}' "
  291. f"-FeatureFlags @() -AdditionalModules @() "
  292. f"-HostName Hermes -HostProfileId hermes -HostVersion 1.0.0 -Stdio -LogLevel Normal"
  293. )
  294. return SpawnSpec(
  295. [pwsh, "-NoLogo", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", inner],
  296. root, root, env=ctx.env_overrides.get("powershell", {}),
  297. initialization_options={k: v for k, v in ctx.init_overrides.get("powershell", {}).items() if k != "bundlePath"},
  298. )
  299. def hermes_lsp_session_dir() -> str:
  300. """Return (and create) the dir for PSES session/log scratch files."""
  301. from hermes_constants import get_hermes_home
  302. d = os.path.join(str(get_hermes_home()), "lsp", "pses")
  303. os.makedirs(d, exist_ok=True)
  304. return d
  305. # ---- workspace trust ----
  306. # The only servers that start in an untrusted workspace (``workspace.is_trusted_workspace``): with the
  307. # settings Hermes passes they run nothing the checkout ships. Everything else waits for trust, because
  308. # it evaluates project build files on start or on save (cargo check / build.rs / proc-macros, Gradle,
  309. # mix.exs, build.zig, stack/cabal, Lua ``runtime.plugin``, terraform providers, prisma.config.ts, Vue's
  310. # tsconfig ``vueCompilerOptions.plugins``, which @vue/language-core require()s from the project, ...),
  311. # and so do user-declared ``lsp.servers`` entries, whose behaviour Hermes cannot vouch for.
  312. UNTRUSTED_SAFE_SERVERS = frozenset({
  313. "pyright", # interpreter pinned to the operator's own (_spawn_pyright)
  314. "typescript", # tsserver pinned to Hermes's SDK; plugins then resolve beside it (_spawn_typescript)
  315. "svelte-language-server", # isTrusted: false — no svelte.config.js, no project svelte/prettier
  316. "bash-language-server", # parses scripts; diagnostics from shellcheck on PATH
  317. "yaml-language-server", # validates against JSON schemas (may fetch them); no project code
  318. "dockerfile-ls", # parses the Dockerfile; never builds it
  319. "intelephense", # static PHP indexer; never runs php or composer
  320. "clangd", # no --query-driver, so it never runs a project compiler
  321. })
  322. # ---- the registry ----
  323. _JS_MARKERS = ["package-lock.json", "bun.lockb", "bun.lock", "pnpm-lock.yaml", "yarn.lock", "package.json", "tsconfig.json"]
  324. _DENO_EXCLUDES = ["deno.json", "deno.jsonc"]
  325. _root_typescript = _markers_root(_JS_MARKERS, _DENO_EXCLUDES)
  326. def _server(server_id: str, extensions: tuple[str, ...], description: str, *,
  327. markers: Optional[Sequence[str]] = None, excludes: Sequence[str] = (),
  328. resolve_root: Optional[_RootFn] = None, build_spawn: Optional[_SpawnFn] = None,
  329. which: Sequence[str] = (), args: Sequence[str] = (), install_pkg: Optional[str] = None,
  330. base_init: Optional[dict[str, Any]] = None, seed: bool = False,
  331. untrusted_init: Optional[dict[str, Any]] = None, multi_root: bool = False) -> ServerDef:
  332. """Registry entry factory: defaults to marker-based root + single-binary spawn."""
  333. return ServerDef(
  334. server_id, extensions,
  335. resolve_root or _markers_root(markers, excludes),
  336. build_spawn or _simple_spawn(server_id, which or (server_id,), args, install_pkg, base_init, seed, untrusted_init),
  337. seed_first_push=seed, description=description, multi_root=multi_root,
  338. )
  339. SERVERS: list[ServerDef] = [
  340. _server("pyright", (".py", ".pyi"), "Python — Microsoft pyright",
  341. markers=["pyproject.toml", "setup.py", "setup.cfg", "requirements.txt", "Pipfile", "pyrightconfig.json"],
  342. build_spawn=_spawn_pyright, multi_root=True),
  343. _server("typescript", (".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts"),
  344. "JavaScript/TypeScript — typescript-language-server", resolve_root=_root_typescript,
  345. build_spawn=_spawn_typescript, seed=True),
  346. _server("vue-language-server", (".vue",), "Vue.js — @vue/language-server", resolve_root=_root_typescript,
  347. build_spawn=_spawn_vue),
  348. _server("svelte-language-server", (".svelte",), "Svelte — svelte-language-server", resolve_root=_root_typescript,
  349. which=("svelteserver", "svelte-language-server"), args=("--stdio",), install_pkg="svelte-language-server",
  350. untrusted_init={"isTrusted": False}),
  351. _server("astro-language-server", (".astro",), "Astro — @astrojs/language-server", resolve_root=_root_typescript,
  352. which=("astro-ls", "astro-language-server"), args=("--stdio",), install_pkg="@astrojs/language-server"),
  353. _server("gopls", (".go",), "Go — gopls", markers=["go.work", "go.mod", "go.sum"], install_pkg="gopls"),
  354. _server("rust-analyzer", (".rs",), "Rust — rust-analyzer", markers=["Cargo.toml", "Cargo.lock"], install_pkg="rust-analyzer"),
  355. _server("clangd", (".c", ".cpp", ".cc", ".cxx", ".h", ".hh", ".hpp", ".hxx"), "C/C++ — clangd",
  356. markers=["compile_commands.json", "compile_flags.txt", ".clangd"],
  357. args=("--background-index", "--clang-tidy"), install_pkg="clangd"),
  358. _server("bash-language-server", (".sh", ".bash", ".zsh", ".ksh"), "Bash — bash-language-server", build_spawn=_spawn_bash_ls),
  359. _server("yaml-language-server", (".yaml", ".yml"), "YAML — yaml-language-server",
  360. args=("--stdio",), install_pkg="yaml-language-server"),
  361. _server("lua-language-server", (".lua",), "Lua — lua-language-server",
  362. markers=[".luarc.json", ".luarc.jsonc", ".luacheckrc", ".stylua.toml", "stylua.toml", "selene.toml", "selene.yml"],
  363. install_pkg="lua-language-server"),
  364. # Before intelephense: Blade templates are Laravel's, plain .php stays with intelephense.
  365. _server("laravel-lsp", (".blade.php",), "Laravel Blade — laravel-lsp (manual: composer global require laravel/lsp)",
  366. markers=["artisan", "composer.json", "composer.lock"], args=("lsp",)),
  367. _server("intelephense", (".php",), "PHP — intelephense", markers=["composer.json", "composer.lock", ".php-version"],
  368. args=("--stdio",), install_pkg="intelephense", base_init={"telemetry": {"enabled": False}}),
  369. _server("ocaml-lsp", (".ml", ".mli"), "OCaml — ocaml-lsp", markers=["dune-project", "dune-workspace", ".merlin", "opam"],
  370. which=("ocamllsp",)),
  371. _server("dockerfile-ls", (".dockerfile", "Dockerfile"), "Dockerfile — dockerfile-language-server-nodejs",
  372. which=("docker-langserver",), args=("--stdio",), install_pkg="dockerfile-language-server-nodejs"),
  373. # terraform-ls is heavy to auto-install; require the user to provide it.
  374. _server("terraform-ls", (".tf", ".tfvars"), "Terraform — terraform-ls", markers=[".terraform.lock.hcl", "terraform.tfstate"],
  375. args=("serve",), base_init={"experimentalFeatures": {"prefillRequiredFields": True, "validateOnSave": True}}),
  376. _server("dart", (".dart",), "Dart — built-in language server", markers=["pubspec.yaml", "analysis_options.yaml"],
  377. args=("language-server", "--lsp")),
  378. _server("haskell-language-server", (".hs", ".lhs"), "Haskell — haskell-language-server",
  379. markers=["stack.yaml", "cabal.project", "hie.yaml"],
  380. which=("haskell-language-server-wrapper", "haskell-language-server"), args=("--lsp",)),
  381. _server("julia", (".jl",), "Julia — LanguageServer.jl", markers=["Project.toml", "Manifest.toml"],
  382. args=("--startup-file=no", "--history-file=no", "-e", "using LanguageServer; runserver()")),
  383. _server("clojure-lsp", (".clj", ".cljs", ".cljc", ".edn"), "Clojure — clojure-lsp",
  384. markers=["deps.edn", "project.clj", "shadow-cljs.edn", "bb.edn", "build.boot"], args=("listen",)),
  385. _server("nixd", (".nix",), "Nix — nixd", resolve_root=lambda fp, ws: nearest_root(fp, ["flake.nix"]) or ws),
  386. _server("zls", (".zig", ".zon"), "Zig — zls", markers=["build.zig"]),
  387. _server("gleam", (".gleam",), "Gleam — built-in language server", markers=["gleam.toml"], args=("lsp",)),
  388. _server("elixir-ls", (".ex", ".exs"), "Elixir — elixir-ls", markers=["mix.exs", "mix.lock"],
  389. which=("elixir-ls", "language_server.sh")),
  390. _server("prisma", (".prisma",), "Prisma — built-in language server", markers=["schema.prisma", "prisma/schema.prisma"],
  391. args=("language-server",)),
  392. _server("kotlin-language-server", (".kt", ".kts"), "Kotlin — kotlin-language-server",
  393. markers=["settings.gradle", "settings.gradle.kts", "build.gradle", "build.gradle.kts", "pom.xml"]),
  394. # jdtls has a complex install flow; we look for the wrapper script a manual install produces.
  395. _server("jdtls", (".java",), "Java — Eclipse JDT Language Server",
  396. markers=["pom.xml", "build.gradle", "build.gradle.kts", ".project", ".classpath", "settings.gradle"]),
  397. # No universal PowerShell root marker; nearest_root is exact-name only (no globs).
  398. _server("powershell", (".ps1", ".psm1", ".psd1"), "PowerShell — PowerShellEditorServices (manual bundle)",
  399. markers=["PSScriptAnalyzerSettings.psd1"], build_spawn=_spawn_powershell_es),
  400. ]
  401. def find_server_for_file(file_path: str, servers: Optional[Sequence[ServerDef]] = None) -> Optional[ServerDef]:
  402. """Return the first entry of ``servers`` (default: the built-in registry) that handles ``file_path``."""
  403. return next((srv for srv in (SERVERS if servers is None else servers) if srv.matches(file_path)), None)
  404. def language_id_for(path: str, srv: Optional[ServerDef] = None) -> str:
  405. """Return the LSP languageId to send in didOpen for ``path`` (a custom server's own id wins)."""
  406. if srv is not None and srv.language_id:
  407. return srv.language_id
  408. return LANGUAGE_BY_EXT.get(_file_ext_or_basename(path), "plaintext")
  409. def _custom_spawn(server_id: str, command: Sequence[str]) -> _SpawnFn:
  410. """Spawn builder for a config-declared server: ``command[0]`` is a path or a PATH lookup, no auto-install."""
  411. def build(root: str, ctx: ServerContext) -> Optional[SpawnSpec]:
  412. bin_path = _which(os.path.expanduser(command[0]))
  413. if bin_path is None:
  414. _warn_once(f"custom:{server_id}", f"lsp.servers.{server_id}: command {command[0]!r} not found on PATH — server skipped")
  415. return None
  416. return _make_spec(root, ctx, server_id, [bin_path, *command[1:]])
  417. return build
  418. def custom_servers(servers_cfg: Any) -> list[ServerDef]:
  419. """``lsp.servers`` entries that declare ``extensions`` and name no built-in server are user-declared
  420. servers (issue #100257). They go AHEAD of the built-ins so a custom entry can claim an extension;
  421. malformed entries are logged and skipped so one typo never disables the rest of the subsystem."""
  422. if not isinstance(servers_cfg, dict):
  423. return []
  424. builtin = {s.server_id for s in SERVERS}
  425. out: list[ServerDef] = []
  426. for server_id, cfg in servers_cfg.items():
  427. if server_id in builtin or not isinstance(cfg, dict) or "extensions" not in cfg:
  428. continue
  429. command, exts, markers = cfg.get("command"), cfg.get("extensions"), cfg.get("root_markers")
  430. if not (isinstance(command, list) and command and all(isinstance(c, str) and c for c in command)
  431. and isinstance(exts, list) and exts and all(isinstance(e, str) and e for e in exts)):
  432. logger.warning("lsp.servers.%s: custom server needs command: [bin, ...args] and extensions: [.ext, ...] — ignored", server_id)
  433. continue
  434. out.append(ServerDef(
  435. str(server_id), tuple(e.lower() if e.startswith(".") else e for e in exts),
  436. _markers_root([str(m) for m in markers] if isinstance(markers, list) and markers else None),
  437. _custom_spawn(str(server_id), command),
  438. description=str(cfg.get("description") or f"{server_id} — custom (lsp.servers)"),
  439. language_id=str(cfg.get("language_id") or ""),
  440. ))
  441. return out
  442. __all__ = [
  443. "LANGUAGE_BY_EXT",
  444. "SERVERS",
  445. "UNTRUSTED_SAFE_SERVERS",
  446. "ServerContext",
  447. "ServerDef",
  448. "SpawnSpec",
  449. "custom_servers",
  450. "find_server_for_file",
  451. "language_id_for",
  452. ]