Skip to content

The agent that grows with you

fix(lsp): deny by default in an untrusted workspace and skip the toolchain lint fallbacks there

John Paul Soliva59ec28114094
diff --git a/agent/lsp/cli.py b/agent/lsp/cli.py
index 6fcb2bd91ed..1ce05a47a6f 100644
--- a/agent/lsp/cli.py
+++ b/agent/lsp/cli.py
@@ -80,6 +80,7 @@ def _status_for(server_id: str) -> str:
def _cmd_status(emit_json: bool) -> int:
from agent.lsp import get_service
+ from agent.lsp.servers import UNTRUSTED_SAFE_SERVERS
servers = _all_servers()
svc = get_service()
info = svc.get_status() if svc is not None else {"enabled": False}
@@ -104,6 +105,9 @@ def _cmd_status(emit_json: bool) -> int:
out += [f" - {b}" for b in broken]
if disabled := info.get("disabled_servers"):
out.append(f" disabled in cfg: {', '.join(disabled)}")
+ if untrusted := info.get("untrusted_skipped"):
+ out.append(f" untrusted skips: {len(untrusted)} (add the workspace to lsp.trusted_workspaces)")
+ out += [f" - {sid:20s} root={root}" for sid, root in untrusted]
# Sidecar gaps the registry table can't show (bash-language-server -> shellcheck).
if backend_warnings := _backend_warnings():
out += ["", "Backend warnings", "================"] + [f" ! {line}" for line in backend_warnings]
@@ -115,7 +119,8 @@ def _cmd_status(emit_json: bool) -> int:
ext_summary += f", … (+{len(s.extensions) - 5})"
out.append(f" {_STATUS_MARKERS.get(status, ' ')} {s.server_id:24s} [{status:11s}] {ext_summary}")
if s.description:
- out.append(f" {s.description}")
+ gate = "" if s.server_id in UNTRUSTED_SAFE_SERVERS else " [trusted workspaces only]"
+ out.append(f" {s.description}{gate}")
sys.stdout.write("\n".join(out) + "\n")
return 0
diff --git a/agent/lsp/eventlog.py b/agent/lsp/eventlog.py
index 84f48bd64b8..5aea278a4d3 100644
--- a/agent/lsp/eventlog.py
+++ b/agent/lsp/eventlog.py
@@ -28,7 +28,9 @@ _announced_unavailable: set = set() # keys: (server_id, binary_path_or_name)
_announced_no_root: set = set() # keys: (server_id, file_path)
_announced_skipped: set = set() # keys: (server_id, workspace_root)
_announced_excluded: set = set() # keys: (server_id, workspace_root)
-_ALL_BUCKETS = (_announced_active, _announced_unavailable, _announced_no_root, _announced_skipped, _announced_excluded)
+_announced_untrusted: set = set() # keys: (server_id, workspace_root)
+_ALL_BUCKETS = (_announced_active, _announced_unavailable, _announced_no_root, _announced_skipped, _announced_excluded,
+ _announced_untrusted)
def _short_path(file_path: str) -> str:
@@ -133,6 +135,15 @@ def log_root_excluded(server_id: str, workspace_root: str, file_path: str, *, in
f"skipping {_short_path(file_path)}: {workspace_root} excluded")
+def log_untrusted_skipped(server_id: str, workspace_root: str, file_path: str) -> None:
+ """``server_id`` is not safe in an untrusted workspace and ``workspace_root`` is not trusted.
+ INFO once per root (a deliberate gate must not look like a clean file), DEBUG thereafter."""
+ _emit_once(_announced_untrusted, (server_id, workspace_root), server_id, logging.INFO,
+ f"skipped: untrusted workspace {workspace_root} ({_short_path(file_path)}); "
+ "add it to lsp.trusted_workspaces to run this server there",
+ f"skipped: untrusted workspace {workspace_root}")
+
+
def log_reaped(keys: List[Tuple[str, str]], idle_timeout: float) -> None:
"""Idle clients were reaped. INFO, one line per sweep.
@@ -163,6 +174,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_skipped_broken", "log_root_excluded", "log_reaped",
+ "log_server_unavailable", "log_timeout", "log_server_error", "log_spawn_failed", "log_skipped_broken", "log_root_excluded",
+ "log_untrusted_skipped", "log_reaped",
"reset_announce_caches",
]
diff --git a/agent/lsp/manager.py b/agent/lsp/manager.py
index f0bc93bca24..638e7996541 100644
--- a/agent/lsp/manager.py
+++ b/agent/lsp/manager.py
@@ -22,7 +22,9 @@ from typing import Any, Callable, Dict, List, Optional, Tuple
from agent.lsp import eventlog
from agent.lsp.client import DIAGNOSTICS_DOCUMENT_WAIT, LSPClient, _diagnostic_key as _diag_key
-from agent.lsp.servers import SERVERS, ServerContext, ServerDef, custom_servers, find_server_for_file, language_id_for
+from agent.lsp.servers import (
+ SERVERS, UNTRUSTED_SAFE_SERVERS, ServerContext, ServerDef, custom_servers, find_server_for_file, language_id_for,
+)
from agent.lsp.workspace import clear_cache, is_trusted_workspace, resolve_workspace_for_file
logger = logging.getLogger("agent.lsp.manager")
@@ -56,7 +58,7 @@ def _parse_exclude_roots(value: Any) -> Optional[List[str]]:
return [os.path.expanduser(p) for p in value if p]
-def _parse_trusted_workspaces(value: Any) -> List[str]:
+def parse_trusted_workspaces(value: Any) -> List[str]:
"""Normalise ``lsp.trusted_workspaces``; a malformed value trusts nothing extra (WARNING)."""
if value is None:
return []
@@ -163,7 +165,8 @@ class LSPService:
# bare string here means "exclude that workspace", and excluding nothing would re-pay the stall it
# was meant to avoid.
self._exclude_roots: Optional[List[str]] = _parse_exclude_roots(exclude_roots)
- self._trusted_workspaces: List[str] = _parse_trusted_workspaces(trusted_workspaces)
+ self._trusted_workspaces: List[str] = parse_trusted_workspaces(trusted_workspaces)
+ self._untrusted_skipped: set = set() # (server_id, root) pairs denied by workspace trust
self._loop = _BackgroundLoop()
if self._enabled:
@@ -265,11 +268,23 @@ class LSPService:
if self._root_excluded(key[1]):
eventlog.log_root_excluded(srv.server_id, key[1], file_path, invalid=self._exclude_roots is None)
return False
+ if self._untrusted_denied(srv, key[1], file_path):
+ return False
if self._is_broken(key):
eventlog.log_skipped_broken(srv.server_id, key[1], file_path, retry_in=self._broken_retry_in(key))
return False
return True
+ def _untrusted_denied(self, srv: ServerDef, root: str, file_path: str) -> bool:
+ """True iff ``srv`` may run project code and ``root`` is not a trusted workspace (deny by default:
+ only ``UNTRUSTED_SAFE_SERVERS`` start in a checkout the operator has not trusted)."""
+ if srv.server_id in UNTRUSTED_SAFE_SERVERS or is_trusted_workspace(root, self._trusted_workspaces):
+ return False
+ with self._state_lock:
+ self._untrusted_skipped.add((srv.server_id, root))
+ eventlog.log_untrusted_skipped(srv.server_id, root, file_path)
+ return True
+
def _root_excluded(self, root: str) -> bool:
"""True iff ``root`` matches an ``lsp.exclude_roots`` glob (or the key is misconfigured)."""
if self._exclude_roots is None:
@@ -438,12 +453,14 @@ class LSPService:
for c in self._clients.values()
]
broken = [key for key, deadline in self._broken.items() if time.monotonic() < deadline]
+ untrusted = sorted(self._untrusted_skipped)
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),
"broken_retry_seconds": self._broken_retry, "warmup_timeout": self._warmup_timeout,
"exclude_roots": list(self._exclude_roots) if self._exclude_roots is not None else "INVALID",
+ "trusted_workspaces": list(self._trusted_workspaces), "untrusted_skipped": untrusted,
}
# ---- async internals ----
@@ -512,6 +529,8 @@ class LSPService:
if root is None:
eventlog.log_disabled(srv.server_id, file_path, "exclude marker hit (server gated off)")
return None
+ if self._untrusted_denied(srv, root, file_path):
+ return None
if self._is_broken((srv.server_id, root)):
return None
key = _client_key(srv, root)
diff --git a/agent/lsp/servers.py b/agent/lsp/servers.py
index be8192c43b5..df94c4a4c83 100644
--- a/agent/lsp/servers.py
+++ b/agent/lsp/servers.py
@@ -377,6 +377,26 @@ def hermes_lsp_session_dir() -> str:
return d
+# ---- workspace trust ----
+
+# The only servers that start in an untrusted workspace (``workspace.is_trusted_workspace``): with the
+# settings Hermes passes they run nothing the checkout ships. Everything else waits for trust, because
+# it evaluates project build files on start or on save (cargo check / build.rs / proc-macros, Gradle,
+# mix.exs, build.zig, stack/cabal, Lua ``runtime.plugin``, terraform providers, prisma.config.ts, ...),
+# and so do user-declared ``lsp.servers`` entries, whose behaviour Hermes cannot vouch for.
+UNTRUSTED_SAFE_SERVERS = frozenset({
+ "pyright", # interpreter pinned to the operator's own (_spawn_pyright)
+ "typescript", # tsserver pinned to Hermes's SDK; plugins then resolve beside it (_spawn_typescript)
+ "vue-language-server", # Hermes's TypeScript SDK only (_spawn_vue)
+ "svelte-language-server", # isTrusted: false — no svelte.config.js, no project svelte/prettier
+ "bash-language-server", # parses scripts; diagnostics from shellcheck on PATH
+ "yaml-language-server", # parses YAML against JSON schemas; no project code
+ "dockerfile-ls", # parses the Dockerfile; never builds it
+ "intelephense", # static PHP indexer; never runs php or composer
+ "clangd", # no --query-driver, so it never runs a project compiler
+})
+
+
# ---- the registry ----
_JS_MARKERS = ["package-lock.json", "bun.lockb", "bun.lock", "pnpm-lock.yaml", "yarn.lock", "package.json", "tsconfig.json"]
@@ -415,11 +435,7 @@ SERVERS: List[ServerDef] = [
_server("astro-language-server", (".astro",), "Astro — @astrojs/language-server", resolve_root=_root_typescript,
which=("astro-ls", "astro-language-server"), args=("--stdio",), install_pkg="@astrojs/language-server"),
_server("gopls", (".go",), "Go — gopls", markers=["go.work", "go.mod", "go.sum"], install_pkg="gopls"),
- # Untrusted: no build scripts or proc-macros (rust-analyzer runs both by default).
- _server("rust-analyzer", (".rs",), "Rust — rust-analyzer", markers=["Cargo.toml", "Cargo.lock"],
- build_spawn=_untrusted_init("rust-analyzer", {"cargo": {"buildScripts": {"enable": False}},
- "procMacro": {"enable": False}},
- ("rust-analyzer",), (), "rust-analyzer")),
+ _server("rust-analyzer", (".rs",), "Rust — rust-analyzer", markers=["Cargo.toml", "Cargo.lock"], install_pkg="rust-analyzer"),
_server("clangd", (".c", ".cpp", ".cc", ".cxx", ".h", ".hh", ".hpp", ".hxx"), "C/C++ — clangd",
markers=["compile_commands.json", "compile_flags.txt", ".clangd"],
args=("--background-index", "--clang-tidy"), install_pkg="clangd"),
@@ -517,5 +533,5 @@ def custom_servers(servers_cfg: Any) -> List[ServerDef]:
return out
-__all__ = ["ServerDef", "ServerContext", "SpawnSpec", "SERVERS", "custom_servers", "find_server_for_file",
- "language_id_for", "LANGUAGE_BY_EXT"]
+__all__ = ["ServerDef", "ServerContext", "SpawnSpec", "SERVERS", "UNTRUSTED_SAFE_SERVERS", "custom_servers",
+ "find_server_for_file", "language_id_for", "LANGUAGE_BY_EXT"]
diff --git a/cli-config.yaml.example b/cli-config.yaml.example
index fb87be7d7a5..fdb8d80d4e8 100644
--- a/cli-config.yaml.example
+++ b/cli-config.yaml.example
@@ -583,10 +583,12 @@ terminal:
# lsp:
# enabled: true
# # Language servers only load code a project ships (its .venv interpreter,
-# # node_modules TypeScript, svelte.config.js, Rust build scripts/proc-macros)
+# # node_modules TypeScript, svelte.config.js, cargo/Gradle/mix build files)
# # in the git worktree Hermes was launched in, or under a directory listed
-# # here. Other checkouts, such as a repository the agent cloned, get
-# # Hermes-side tools instead. Gateway and desktop sessions usually need this.
+# # here. In other checkouts, such as a repository the agent cloned, only
+# # servers that run no project code start (pinned to Hermes-side tools) and
+# # the npx tsc / rustfmt lint fallbacks are skipped. Gateway and desktop
+# # sessions usually need this.
# trusted_workspaces:
# - ~/code/my-app
diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.py
index 3dabf84a3f4..57e58fcd814 100644
--- a/hermes_cli/config_defaults.py
+++ b/hermes_cli/config_defaults.py
@@ -2402,9 +2402,10 @@ DEFAULT_CONFIG = {
"exclude_roots": [],
# Directories (~ expanded; everything under an entry counts) whose projects a language
# server may load code from: the project's own .venv/venv interpreter, node_modules
- # TypeScript SDK, svelte.config.js, Rust build scripts and proc-macros. The git worktree
- # Hermes was launched in is always trusted; any other checkout (a clone the agent made,
- # a gateway/desktop session's repo) gets Hermes-side tools instead until listed here.
+ # TypeScript SDK, svelte.config.js, build files (cargo, Gradle, mix, ...). The git worktree
+ # Hermes was launched in is always trusted; in any other checkout (a clone the agent made,
+ # a gateway/desktop session's repo) only servers that run no project code start, pinned
+ # to Hermes-side tools, and the npx tsc / rustfmt lint fallbacks are skipped.
"trusted_workspaces": [],
# Missing server binaries: auto = install via npm/go/pip into <HERMES_HOME>/lsp/bin/ on
# first use; manual = only binaries on PATH; off = alias for manual.
diff --git a/tests/agent/lsp/test_custom_servers.py b/tests/agent/lsp/test_custom_servers.py
index 895ceb89049..4f5c694f2fd 100644
--- a/tests/agent/lsp/test_custom_servers.py
+++ b/tests/agent/lsp/test_custom_servers.py
@@ -42,6 +42,7 @@ def test_service_gets_diagnostics_from_config_declared_server(tmp_path, monkeypa
home.mkdir()
(home / "config.yaml").write_text(json.dumps({"lsp": {
"install_strategy": "manual", "wait_timeout": 5.0, "idle_timeout": 0,
+ "trusted_workspaces": [str(tmp_path / "ws")],
"servers": {"panache": {"command": [sys.executable, _MOCK], "extensions": [".pnch"],
"env": {"MOCK_LSP_SCRIPT": "errors"}}},
}}), encoding="utf-8")
diff --git a/tests/agent/lsp/test_install_and_lint_fixes.py b/tests/agent/lsp/test_install_and_lint_fixes.py
index 55d1fb84a92..d214757c45b 100644
--- a/tests/agent/lsp/test_install_and_lint_fixes.py
+++ b/tests/agent/lsp/test_install_and_lint_fixes.py
@@ -76,7 +76,8 @@ def test_check_lint_returns_error_for_real_ts_type_errors(tmp_path, monkeypatch)
return result
# Local .ts lint runs PM's npx directly, not through the terminal shell's _exec.
- with patch.object(fops, "_run_managed_node_linter", side_effect=lambda ext, path: fake_exec(path)):
+ with patch.object(fops, "_run_managed_node_linter", side_effect=lambda ext, path: fake_exec(path)), \
+ patch.object(fops, "_local_workspace_untrusted", return_value=False):
lint = fops._check_lint(str(ts_file))
assert lint.skipped is False
diff --git a/tests/agent/lsp/test_shell_linter_lsp_skip.py b/tests/agent/lsp/test_shell_linter_lsp_skip.py
index aba63821e69..ab75f3a21e5 100644
--- a/tests/agent/lsp/test_shell_linter_lsp_skip.py
+++ b/tests/agent/lsp/test_shell_linter_lsp_skip.py
@@ -128,6 +128,7 @@ def test_ts_shell_linter_runs_when_no_ancestor_tsconfig(tmp_path):
with patch.object(fops, "_lsp_local_only", return_value=True), \
patch.object(fops, "_lsp_will_handle", return_value=False), \
+ patch.object(fops, "_local_workspace_untrusted", return_value=False), \
patch.object(fops, "_run_managed_node_linter", return_value=exec_result) as exec_mock:
fops._check_lint(str(src))
diff --git a/tests/agent/lsp/test_workspace_trust.py b/tests/agent/lsp/test_workspace_trust.py
index af8e422de84..e25db00d480 100644
--- a/tests/agent/lsp/test_workspace_trust.py
+++ b/tests/agent/lsp/test_workspace_trust.py
@@ -1,23 +1,26 @@
-"""Language servers must not load code a checkout ships unless the operator trusts that workspace.
+"""Nothing a checkout ships runs unless the operator trusts that workspace.
A cloned repository can ship its own ``.venv/bin/python`` (pyright executes the configured
interpreter), ``node_modules/typescript`` (typescript-language-server and Vue load it),
-``svelte.config.js`` and Rust build scripts. Nothing here executes those files: the tests read
-the configuration Hermes hands each server.
+``svelte.config.js``, Rust build scripts and Gradle builds (rust-analyzer, jdtls and
+kotlin-language-server evaluate them), and a ``node_modules/.bin/tsc`` or ``rust-toolchain.toml``
+the post-write shell linters would pick up. Nothing here executes those files: the tests record
+which servers Hermes would start, the configuration it hands them, and the shell commands it runs.
"""
from __future__ import annotations
-import dataclasses
import json
import os
import shutil
+from types import SimpleNamespace
from agent.lsp import manager
-from agent.lsp.servers import ServerContext, find_server_for_file
+from agent.lsp.servers import UNTRUSTED_SAFE_SERVERS, ServerContext, find_server_for_file
from agent.lsp.workspace import clear_cache, is_inside_workspace
_SERVERS = {"pyright": "a.py", "typescript": "a.ts", "vue-language-server": "a.vue",
- "svelte-language-server": "a.svelte", "rust-analyzer": "a.rs"}
+ "svelte-language-server": "a.svelte", "rust-analyzer": "a.rs", "jdtls": "A.java",
+ "kotlin-language-server": "a.kt"}
def _write(path, text: str = ""):
@@ -38,13 +41,18 @@ def _hermes_side_tree(tmp_path, monkeypatch) -> str:
def _checkout_shipping_its_own_toolchain(root) -> None:
- """Marker files only: an interpreter path and a TypeScript SDK the project brings itself."""
+ """Marker files only: an interpreter, a TypeScript SDK and build files the project brings itself."""
(root / ".git").mkdir(parents=True)
_write(root / "pyproject.toml")
_write(root / ".venv" / "bin" / "python")
_write(root / ".venv" / "Scripts" / "python.exe")
_write(root / "node_modules" / "typescript" / "lib" / "typescript.js")
_write(root / "node_modules" / "typescript" / "lib" / "tsserver.js")
+ _write(root / "node_modules" / ".bin" / "tsc")
+ _write(root / "Cargo.toml")
+ _write(root / "build.rs")
+ _write(root / "rust-toolchain.toml")
+ _write(root / "build.gradle.kts")
def _strings(value):
@@ -58,55 +66,21 @@ def _strings(value):
yield from _strings(v)
-def test_untrusted_workspace_config_never_points_a_server_at_the_checkouts_own_code(tmp_path, monkeypatch):
- launcher = _hermes_side_tree(tmp_path, monkeypatch)
- root = tmp_path / "cloned"
- _checkout_shipping_its_own_toolchain(root)
- ctx = ServerContext(workspace_root=str(root), install_strategy="manual",
- binary_overrides={sid: [launcher] for sid in _SERVERS})
-
- untrusted = {sid: find_server_for_file(f).build_spawn(str(root), ctx) for sid, f in _SERVERS.items()}
- for sid, spec in untrusted.items():
- assert spec is not None, sid
- leaked = [s for s in _strings(spec.initialization_options) if os.path.isabs(s) and is_inside_workspace(s, str(root))]
- assert not leaked, (sid, leaked)
- # Servers that fall back to project code by themselves are told not to.
- assert os.path.isfile(os.path.join(untrusted["typescript"].initialization_options["tsserver"]["path"], "tsserver.js"))
- assert untrusted["svelte-language-server"].initialization_options["isTrusted"] is False
- rust = untrusted["rust-analyzer"].initialization_options
- assert rust["cargo"]["buildScripts"]["enable"] is False and rust["procMacro"]["enable"] is False
- # With no Hermes-side SDK, Vue is skipped rather than handed the checkout's TypeScript.
- shutil.rmtree(os.path.join(os.path.dirname(launcher), "typescript"))
- assert find_server_for_file("a.vue").build_spawn(str(root), ctx) is None
-
- # The same checkout, trusted, gets its own interpreter back and no restriction.
- trusted_ctx = dataclasses.replace(ctx, trusted=True)
- trusted = {sid: find_server_for_file(f).build_spawn(str(root), trusted_ctx) for sid, f in _SERVERS.items()}
- assert is_inside_workspace(trusted["pyright"].initialization_options["python"]["pythonPath"], str(root / ".venv"))
- assert all(spec.initialization_options == {} for sid, spec in trusted.items()
- if sid in {"typescript", "svelte-language-server", "rust-analyzer"})
-
-
-def test_only_the_launch_worktree_and_listed_directories_are_trusted(tmp_path, monkeypatch):
- """Config → service → spawn: which checkout's interpreter pyright is handed."""
- launcher = _hermes_side_tree(tmp_path, monkeypatch)
- launch, listed = tmp_path / "launch", tmp_path / "listed" / "proj"
- nested, sibling = launch / "vendor" / "clone", tmp_path / "elsewhere" / "clone"
- for root in (launch, nested, sibling, listed):
- _checkout_shipping_its_own_toolchain(root)
+def _record_spawns(tmp_path, monkeypatch, launcher, roots, *, trusted_workspaces=()):
+ """Config → service → spawn for every ``_SERVERS`` file in every root, cwd inside ``tmp/launch``.
+ Returns ``{(server_id, root): initialization_options}`` for the servers Hermes would start, and the status."""
_write(tmp_path / "home" / "config.yaml", json.dumps({"lsp": {
- "trusted_workspaces": [str(tmp_path / "listed")],
- "servers": {"pyright": {"command": [launcher]}},
+ "trusted_workspaces": [str(p) for p in trusted_workspaces],
+ "servers": {sid: {"command": [launcher]} for sid in _SERVERS},
}}))
- (launch / "src").mkdir()
- monkeypatch.chdir(launch / "src")
+ (tmp_path / "launch" / "src").mkdir(parents=True, exist_ok=True)
+ monkeypatch.chdir(tmp_path / "launch" / "src")
clear_cache()
-
handed = {}
class _RecordingClient:
- def __init__(self, *, workspace_root, initialization_options, **_):
- handed[workspace_root] = initialization_options
+ def __init__(self, *, server_id, workspace_root, initialization_options, **_):
+ handed[(server_id, workspace_root)] = initialization_options
async def start(self):
raise RuntimeError("recorded, not started")
@@ -114,15 +88,74 @@ def test_only_the_launch_worktree_and_listed_directories_are_trusted(tmp_path, m
monkeypatch.setattr(manager, "LSPClient", _RecordingClient)
svc = manager.LSPService.create_from_config()
try:
- for root in (launch, nested, sibling, listed):
- svc._loop.run(svc._get_or_spawn(str(_write(root / "mod.py"))), timeout=10)
+ for root in roots:
+ for name in _SERVERS.values():
+ svc._loop.run(svc._get_or_spawn(str(_write(root / name))), timeout=10)
+ status = svc.get_status()
finally:
svc.shutdown()
+ return handed, status
- def interpreter(root):
- return handed[str(root)].get("python", {}).get("pythonPath", "")
- assert is_inside_workspace(interpreter(launch), str(launch / ".venv"))
- assert is_inside_workspace(interpreter(listed), str(listed / ".venv"))
- for untrusted in (nested, sibling):
- assert not is_inside_workspace(interpreter(untrusted), str(untrusted)), untrusted
+def test_untrusted_checkout_starts_only_allowlisted_servers_pinned_to_hermes_code(tmp_path, monkeypatch):
+ launcher = _hermes_side_tree(tmp_path, monkeypatch)
+ launch, clone = tmp_path / "launch", tmp_path / "elsewhere" / "clone"
+ for root in (launch, clone):
+ _checkout_shipping_its_own_toolchain(root)
+ handed, status = _record_spawns(tmp_path, monkeypatch, launcher, (launch, clone))
+
+ untrusted = {sid: init for (sid, root), init in handed.items() if root == str(clone)}
+ # Deny by default: servers that evaluate build files (cargo, Gradle) never start in the clone.
+ assert set(untrusted) == set(_SERVERS) & UNTRUSTED_SAFE_SERVERS
+ assert {("rust-analyzer", str(clone)), ("jdtls", str(clone))} <= set(status["untrusted_skipped"])
+ for sid, init in untrusted.items():
+ leaked = [s for s in _strings(init) if os.path.isabs(s) and is_inside_workspace(s, str(clone))]
+ assert not leaked, (sid, leaked)
+ # Allowlisted servers that would fall back to project code by themselves are told not to.
+ assert os.path.isfile(os.path.join(untrusted["typescript"]["tsserver"]["path"], "tsserver.js"))
+ assert untrusted["svelte-language-server"]["isTrusted"] is False
+ # With no Hermes-side SDK, Vue is skipped rather than handed the checkout's TypeScript.
+ shutil.rmtree(os.path.join(os.path.dirname(launcher), "typescript"))
+ ctx = ServerContext(workspace_root=str(clone), install_strategy="manual", binary_overrides={"vue-language-server": [launcher]})
+ assert find_server_for_file("a.vue").build_spawn(str(clone), ctx) is None
+
+ # The launch worktree is trusted: every server starts, pyright gets the project interpreter back.
+ trusted = {sid: init for (sid, root), init in handed.items() if root == str(launch)}
+ assert set(trusted) == set(_SERVERS)
+ assert is_inside_workspace(trusted["pyright"]["python"]["pythonPath"], str(launch / ".venv"))
+ assert all(trusted[sid] == {} for sid in ("typescript", "svelte-language-server", "rust-analyzer"))
+
+
+def test_only_the_launch_worktree_and_listed_directories_are_trusted(tmp_path, monkeypatch):
+ """The same trust decision gates the servers and the post-write shell linters that use the repo's toolchain."""
+ launcher = _hermes_side_tree(tmp_path, monkeypatch)
+ launch, listed = tmp_path / "launch", tmp_path / "listed" / "proj"
+ nested, sibling = launch / "vendor" / "clone", tmp_path / "elsewhere" / "clone"
+ roots = (launch, nested, sibling, listed)
+ for root in roots:
+ _checkout_shipping_its_own_toolchain(root)
+ handed, _ = _record_spawns(tmp_path, monkeypatch, launcher, roots, trusted_workspaces=[tmp_path / "listed"])
+
+ from tools.environments.local import LocalEnvironment
+ from tools.file_operations import ShellFileOperations
+ fops = ShellFileOperations(LocalEnvironment(cwd=str(launch / "src")))
+ ran = []
+ monkeypatch.setattr(fops, "_exec", lambda cmd, **_: ran.append(cmd) or SimpleNamespace(exit_code=0, stdout=""))
+ monkeypatch.setattr(fops, "_run_managed_node_linter", lambda ext, path: ran.append(path) or SimpleNamespace(exit_code=0, stdout=""))
+ monkeypatch.setattr(fops, "_has_command", lambda _cmd: True)
+ monkeypatch.setattr(fops, "_lsp_will_handle", lambda _path: False)
+
+ def shell_linted(root):
+ ran.clear()
+ for name in ("a.ts", "a.rs"):
+ fops._check_lint(str(root / name))
+ return len(ran)
+
+ for root in (launch, listed):
+ assert is_inside_workspace(handed[("pyright", str(root))]["python"]["pythonPath"], str(root / ".venv"))
+ assert ("rust-analyzer", str(root)) in handed
+ assert shell_linted(root) == 2, root
+ for root in (nested, sibling):
+ assert not is_inside_workspace(handed[("pyright", str(root))].get("python", {}).get("pythonPath", ""), str(root)), root
+ assert ("rust-analyzer", str(root)) not in handed
+ assert shell_linted(root) == 0, root
diff --git a/tools/file_operations_lint.py b/tools/file_operations_lint.py
index a183b29a344..70b06084a04 100644
--- a/tools/file_operations_lint.py
+++ b/tools/file_operations_lint.py
@@ -33,6 +33,11 @@ _MANAGED_NODE_LINTERS = {'.js': ('node', '--check'), '.ts': ('npx', 'tsc', '--no
# node --check are file-local and correct so always run.
_SHELL_LINTER_LSP_REDUNDANT = frozenset({'.ts', '.go', '.rs'})
+# Shell linters that resolve the toolchain from the checkout they run in: ``npx tsc`` runs the
+# repo's ``node_modules/.bin/tsc`` (or installs from the registry its ``.npmrc`` names) and
+# rustup honours its ``rust-toolchain.toml``. Skipped on a local backend in an untrusted workspace.
+_SHELL_LINTER_RUNS_PROJECT_TOOLCHAIN = frozenset({'.ts', '.rs'})
+
# Output substrings (case-insensitive) meaning the linter binary exists but could
# not run → ``skipped`` so the write isn't flagged and the LSP tier still runs.
_LINTER_UNUSABLE_PATTERNS = {
@@ -163,6 +168,9 @@ class LintMixin:
))
if ext in _SHELL_LINTER_LSP_REDUNDANT and self._lsp_will_handle(path):
return LintResult(skipped=True, message=f"LSP server handles {ext} — shell linter skipped")
+ if ext in _SHELL_LINTER_RUNS_PROJECT_TOOLCHAIN and self._local_workspace_untrusted(path):
+ return LintResult(skipped=True, message=(
+ f"{LINTERS[ext].split()[0]} skipped: untrusted workspace (add it to lsp.trusted_workspaces to lint {ext} here)"))
if ext in _MANAGED_NODE_LINTERS and self._lsp_local_only():
base_cmd = _MANAGED_NODE_LINTERS[ext][0]
result = self._run_managed_node_linter(ext, path)
@@ -243,6 +251,22 @@ class LintMixin:
return False
return isinstance(env, LocalEnvironment)
+ def _local_workspace_untrusted(self, path: str) -> bool:
+ """True iff on a local backend ``path`` or the command cwd lies outside every trusted workspace
+ (``workspace.is_trusted_workspace``). Sandboxed backends answer False: their toolchain is not the host's."""
+ if not self._lsp_local_only():
+ return False
+ try:
+ from agent.lsp.manager import parse_trusted_workspaces
+ from agent.lsp.workspace import is_trusted_workspace
+ from hermes_cli.config import load_config_readonly
+ lsp_cfg = load_config_readonly().get("lsp")
+ trusted = parse_trusted_workspaces(lsp_cfg.get("trusted_workspaces") if isinstance(lsp_cfg, dict) else None)
+ dirs = {os.path.dirname(os.path.abspath(path)), getattr(self.env, "cwd", None) or os.getcwd()}
+ return not all(is_trusted_workspace(d, trusted) for d in dirs)
+ except Exception: # noqa: BLE001
+ return True # no trust decision: skipping a lint never breaks a write
+
def _lsp_service(self):
"""The active LSPService, or None on a non-local backend / any failure.
LSP is an enrichment layer and must never break a write."""
diff --git a/website/docs/user-guide/features/lsp.md b/website/docs/user-guide/features/lsp.md
index 4dd330c4435..3b13c1df6b6 100644
--- a/website/docs/user-guide/features/lsp.md
+++ b/website/docs/user-guide/features/lsp.md
@@ -58,16 +58,18 @@ agent sees a syntax-clean file with semantic problems as
### Workspace trust
-Some language servers run code that the project itself ships:
+Many language servers run code that the project itself ships:
pyright executes the configured Python interpreter,
typescript-language-server loads the project's
`node_modules/typescript`, svelte-language-server loads
-`svelte.config.js`, and rust-analyzer runs build scripts and
-proc-macros. That is fine for your own project, but not for a
-repository the agent has just cloned.
+`svelte.config.js`, rust-analyzer runs `cargo check` (build scripts,
+proc-macros) on every save, and servers such as jdtls,
+kotlin-language-server, elixir-ls, zls or haskell-language-server
+evaluate the project's build files (Gradle, `mix.exs`, `build.zig`,
+Cabal/Stack) when they start. That is fine for your own project, but
+not for a repository the agent has just cloned.
-Hermes therefore lets a server load project code only in a
-**trusted** workspace:
+Hermes therefore treats every workspace as untrusted unless it is:
- the git worktree Hermes was launched in (the process working
directory, so `cd my-app && hermes`), or
@@ -79,8 +81,15 @@ it is not trusted. Gateway and desktop backends are usually started
outside any repository, which means nothing is trusted there until
you list your projects.
-In an untrusted workspace, servers still run, but on Hermes-side
-tools:
+In an untrusted workspace Hermes **denies by default**: only the
+servers below start, each with settings that keep it on Hermes-side
+tools. Every other server is skipped, including rust-analyzer, gopls,
+jdtls, kotlin-language-server, elixir-ls, zls, clojure-lsp,
+haskell-language-server, lua-language-server, terraform-ls, prisma,
+astro and any server you declare under `lsp.servers`. The diagnostics
+log records `skipped: untrusted workspace …; add it to
+lsp.trusted_workspaces`, and `hermes lsp status` marks those servers
+`[trusted workspaces only]`.
| Server | Untrusted workspace |
|---|---|
@@ -88,7 +97,15 @@ tools:
| typescript-language-server | `tsserver.path` pinned to the TypeScript next to the server; skipped if there is none |
| vue-language-server | `tsdk` from Hermes's staging tree only |
| svelte-language-server | `isTrusted: false` (no `svelte.config.js`, no project `svelte`/`prettier`) |
-| rust-analyzer | build scripts and proc-macros disabled; cargo still reads the project's own cargo and toolchain files |
+| bash-language-server, yaml-language-server, dockerfile-ls, intelephense | unchanged: they only parse files |
+| clangd | unchanged: Hermes never passes `--query-driver`, so no project compiler runs |
+
+On a local backend, the post-write shell linters that would use the
+checkout's own toolchain are skipped the same way: `npx tsc` (it runs
+the repository's `node_modules/.bin/tsc`, or installs from the
+registry its `.npmrc` names) and `rustfmt --check` (rustup honours the
+repository's `rust-toolchain.toml`). Sandboxed backends (Docker, SSH,
+Modal, …) are unchanged.
Diagnostics that need the project's dependencies (for example
unresolved-import warnings) may be less precise until you trust the
diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/features/lsp.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/features/lsp.md
index 51093f87370..5da7a9d6221 100644
--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/features/lsp.md
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/features/lsp.md
@@ -48,13 +48,16 @@ agent 对于语法正确但存在语义问题的文件,会看到 ``lint: ok``
### 工作区信任
-部分语言服务器会运行项目自带的代码:pyright 会执行所配置的 Python
+许多语言服务器会运行项目自带的代码:pyright 会执行所配置的 Python
解释器,typescript-language-server 会加载项目的
`node_modules/typescript`,svelte-language-server 会加载
-`svelte.config.js`,rust-analyzer 会运行构建脚本和过程宏。对你自己的项目
-这没有问题,但对 agent 刚克隆下来的仓库则不应如此。
+`svelte.config.js`,rust-analyzer 每次保存都会运行 `cargo check`(构建脚本、
+过程宏),而 jdtls、kotlin-language-server、elixir-ls、zls、
+haskell-language-server 等服务器在启动时就会求值项目的构建文件(Gradle、
+`mix.exs`、`build.zig`、Cabal/Stack)。对你自己的项目这没有问题,但对 agent
+刚克隆下来的仓库则不应如此。
-因此,Hermes 只在**受信任**的工作区中允许服务器加载项目代码:
+因此,除以下情况外,Hermes 将所有工作区视为不受信任:
- 启动 Hermes 时所在的 git 工作树(即进程工作目录,例如 `cd my-app && hermes`),或
- `lsp.trusted_workspaces` 中列出的目录(及其下任意子目录)。
@@ -62,7 +65,13 @@ agent 对于语法正确但存在语义问题的文件,会看到 ``lint: ok``
嵌套在启动工作树内部的检出拥有自己的 `.git`,因此不受信任。网关和桌面端
后端通常在任何仓库之外启动,所以在你列出项目之前,那里没有受信任的工作区。
-在不受信任的工作区中,服务器仍会运行,但使用 Hermes 一侧的工具:
+在不受信任的工作区中,Hermes **默认拒绝**:只有下表中的服务器会启动,并且各自
+使用让它停留在 Hermes 一侧工具上的设置。其他所有服务器都会被跳过,包括
+rust-analyzer、gopls、jdtls、kotlin-language-server、elixir-ls、zls、
+clojure-lsp、haskell-language-server、lua-language-server、terraform-ls、
+prisma、astro,以及你在 `lsp.servers` 下声明的任何服务器。诊断日志会记录
+`skipped: untrusted workspace …; add it to lsp.trusted_workspaces`,
+`hermes lsp status` 会把这些服务器标记为 `[trusted workspaces only]`。
| 服务器 | 不受信任的工作区 |
|---|---|
@@ -70,7 +79,13 @@ agent 对于语法正确但存在语义问题的文件,会看到 ``lint: ok``
| typescript-language-server | `tsserver.path` 固定为服务器旁边的 TypeScript;若没有则跳过 |
| vue-language-server | `tsdk` 仅取自 Hermes 的暂存目录 |
| svelte-language-server | `isTrusted: false`(不加载 `svelte.config.js`,不加载项目的 `svelte`/`prettier`) |
-| rust-analyzer | 禁用构建脚本和过程宏;cargo 仍会读取项目自己的 cargo 和工具链文件 |
+| bash-language-server、yaml-language-server、dockerfile-ls、intelephense | 不变:它们只解析文件 |
+| clangd | 不变:Hermes 从不传入 `--query-driver`,因此不会运行项目的编译器 |
+
+在本地后端上,会使用检出自带工具链的写入后 shell 检查器也会以同样方式跳过:
+`npx tsc`(它会运行仓库的 `node_modules/.bin/tsc`,或从仓库 `.npmrc` 指定的
+registry 安装)和 `rustfmt --check`(rustup 会遵循仓库的 `rust-toolchain.toml`)。
+沙箱后端(Docker、SSH、Modal 等)不受影响。
依赖项目依赖项的诊断(例如无法解析的导入)在信任该工作区之前可能不够精确。