Skip to content

The agent that grows with you

fix(lsp): never run a cloned repository's own interpreter or TypeScript SDK in an untrusted workspace

John Paul Solivaf5c754d4365e
diff --git a/agent/lsp/manager.py b/agent/lsp/manager.py
index fb4a7180d23..f0bc93bca24 100644
--- a/agent/lsp/manager.py
+++ b/agent/lsp/manager.py
@@ -23,7 +23,7 @@ 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.workspace import clear_cache, resolve_workspace_for_file
+from agent.lsp.workspace import clear_cache, is_trusted_workspace, resolve_workspace_for_file
logger = logging.getLogger("agent.lsp.manager")
@@ -56,6 +56,20 @@ 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]:
+ """Normalise ``lsp.trusted_workspaces``; a malformed value trusts nothing extra (WARNING)."""
+ if value is None:
+ return []
+ if not isinstance(value, list) or not all(isinstance(p, str) for p in value):
+ eventlog.event_log.warning(
+ "lsp.trusted_workspaces must be a list of directories, e.g. ['~/code/my-app'] (got %s); "
+ "only the launch directory's git worktree is trusted until the key is fixed",
+ type(value).__name__,
+ )
+ return []
+ return [os.path.expanduser(p) for p in value if p]
+
+
def _client_key(srv: ServerDef, root: str) -> _Key:
"""Cache key for the client serving ``root``: multi-root servers share one process per
``server_id``; everything else is keyed per resolved project root."""
@@ -131,6 +145,7 @@ class LSPService:
broken_retry_seconds: float = 0.0,
warmup_timeout: float = 0.0,
exclude_roots: Any = None,
+ trusted_workspaces: Any = None,
) -> None:
self._enabled = enabled
self._wait_mode = wait_mode if wait_mode in {"document", "full"} else "document"
@@ -148,6 +163,7 @@ 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._loop = _BackgroundLoop()
if self._enabled:
@@ -205,6 +221,7 @@ class LSPService:
broken_retry_seconds=_float_or(lsp_cfg.get("broken_retry_seconds"), 0.0),
warmup_timeout=_float_or(lsp_cfg.get("warmup_timeout"), 0.0),
exclude_roots=lsp_cfg.get("exclude_roots"),
+ trusted_workspaces=lsp_cfg.get("trusted_workspaces"),
)
def _server_for(self, file_path: str) -> Optional[ServerDef]:
@@ -544,6 +561,7 @@ class LSPService:
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,
+ trusted=is_trusted_workspace(root, self._trusted_workspaces),
)
spec = srv.build_spawn(root, ctx)
if spec is None:
diff --git a/agent/lsp/servers.py b/agent/lsp/servers.py
index 41742406999..be8192c43b5 100644
--- a/agent/lsp/servers.py
+++ b/agent/lsp/servers.py
@@ -90,6 +90,9 @@ class ServerContext:
binary_overrides: Dict[str, List[str]] = field(default_factory=dict)
env_overrides: Dict[str, Dict[str, str]] = field(default_factory=dict)
init_overrides: Dict[str, Dict[str, Any]] = field(default_factory=dict)
+ # Whether the server may load code the project ships (see workspace.is_trusted_workspace).
+ # Defaults closed: a context built without a trust decision must never run the repo's code.
+ trusted: bool = False
# ---- helpers ----
@@ -173,14 +176,17 @@ def _spawn_pyright(root: str, ctx: ServerContext) -> Optional[SpawnSpec]:
sibling = os.path.join(os.path.dirname(bin_path), f"pyright-langserver{suffix}")
if os.path.exists(sibling):
bin_path = sibling
- # Point pyright at the project venv; its default "python on PATH" rarely is.
- py = _detect_python(root)
+ # Point pyright at the project venv; its default "python on PATH" rarely is. Pyright executes
+ # this interpreter, so a checkout's own venv is only used when the workspace is trusted.
+ py = _detect_python(root if ctx.trusted else None)
return _make_spec(root, ctx, "pyright", [bin_path, "--stdio"], {"python": {"pythonPath": py}} if py else {})
-def _detect_python(root: str) -> Optional[str]:
- # Pyright needs the project's dependencies, not Hermes's runtime packages.
- venvs = [v for v in (os.environ.get("VIRTUAL_ENV"), os.path.join(root, ".venv"), os.path.join(root, "venv")) if v]
+def _detect_python(root: Optional[str]) -> Optional[str]:
+ # Pyright needs the project's dependencies, not Hermes's runtime packages. ``VIRTUAL_ENV`` is the
+ # operator's own environment; ``root`` (the project's .venv/venv) is None for an untrusted workspace.
+ project = (os.path.join(root, ".venv"), os.path.join(root, "venv")) if root else ()
+ venvs = [v for v in (os.environ.get("VIRTUAL_ENV"), *project) if v]
paths = (os.path.join(v, sub) for v in venvs for sub in ("bin/python", "bin/python3", "Scripts/python.exe"))
project_python = next((p for p in paths if os.path.exists(p)), None)
if project_python is not None:
@@ -227,11 +233,12 @@ _VUE_TSDK_MSG = (
)
-def _node_modules_trees(bin_path: str, root: str) -> List[str]:
+def _node_modules_trees(bin_path: str, root: Optional[str]) -> List[str]:
"""``node_modules`` trees that may hold the Vue server and its TypeScript SDK:
- the launcher's own tree (symlinks resolved), Hermes staging, then the project's."""
+ the launcher's own tree (symlinks resolved), Hermes staging, then the project's
+ (``root`` is None for an untrusted workspace, whose own JavaScript must not load)."""
from agent.lsp.install import hermes_lsp_bin_dir
- trees = [str(hermes_lsp_bin_dir().parent / "node_modules"), os.path.join(root, "node_modules")]
+ trees = [str(hermes_lsp_bin_dir().parent / "node_modules")] + ([os.path.join(root, "node_modules")] if root else [])
real = os.path.realpath(bin_path)
marker = f"{os.sep}node_modules{os.sep}"
if (idx := real.rfind(marker)) >= 0:
@@ -262,7 +269,7 @@ def _spawn_vue(root: str, ctx: ServerContext) -> Optional[SpawnSpec]:
bin_path = _find_binary(ctx, "vue-language-server", ("vue-language-server",), "@vue/language-server")
if bin_path is None:
return None
- trees = _node_modules_trees(bin_path, root)
+ trees = _node_modules_trees(bin_path, root if ctx.trusted else None)
if _vue_server_major(trees) >= 3:
_warn_once("vue-tunnel", _VUE_TUNNEL_MSG)
return None
@@ -274,6 +281,39 @@ def _spawn_vue(root: str, ctx: ServerContext) -> Optional[SpawnSpec]:
{"typescript": {"tsdk": tsdk}, "vue": {"hybridMode": False}})
+_TS_UNTRUSTED_MSG = (
+ "typescript-language-server: no TypeScript SDK next to the server, and this workspace is untrusted so its "
+ "own node_modules/typescript is not loaded — diagnostics are skipped. Reinstall: hermes lsp install "
+ "typescript-language-server, or list the workspace under lsp.trusted_workspaces."
+)
+
+
+def _spawn_typescript(root: str, ctx: ServerContext) -> Optional[SpawnSpec]:
+ """typescript-language-server loads the workspace's own ``node_modules/typescript`` unless
+ ``tsserver.path`` names another, so an untrusted workspace is pinned to Hermes's copy."""
+ bin_path = _find_binary(ctx, "typescript", ("typescript-language-server",), "typescript-language-server")
+ if bin_path is None:
+ return None
+ base: Dict[str, Any] = {}
+ if not ctx.trusted:
+ sdk = _typescript_sdk_dir(_node_modules_trees(bin_path, None))
+ if sdk is None:
+ _warn_once("ts-untrusted", _TS_UNTRUSTED_MSG)
+ return None
+ base = {"tsserver": {"path": sdk}}
+ return _make_spec(root, ctx, "typescript", [bin_path, "--stdio"], base, seed=True)
+
+
+def _untrusted_init(server_id: str, init: Dict[str, Any], which: Sequence[str], args: Sequence[str],
+ install_pkg: str) -> _SpawnFn:
+ """A single-binary server whose own option switches off project-code loading when untrusted."""
+ def build(root: str, ctx: ServerContext) -> Optional[SpawnSpec]:
+ bin_path = _find_binary(ctx, server_id, which, install_pkg)
+ return None if bin_path is None else _make_spec(root, ctx, server_id, [bin_path, *args],
+ None if ctx.trusted else init)
+ return build
+
+
def _find_pses_bundle(ctx: ServerContext) -> Optional[str]:
"""Locate the PowerShellEditorServices bundle dir (release zip, manual install). Resolution order:
``lsp.servers.powershell.command[0]`` when a directory, ``init_overrides["powershell"]["bundlePath"]``,
@@ -365,15 +405,21 @@ SERVERS: List[ServerDef] = [
build_spawn=_spawn_pyright, multi_root=True),
_server("typescript", (".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts"),
"JavaScript/TypeScript — typescript-language-server", resolve_root=_root_typescript,
- which=("typescript-language-server",), args=("--stdio",), install_pkg="typescript-language-server", seed=True),
+ build_spawn=_spawn_typescript, seed=True),
_server("vue-language-server", (".vue",), "Vue.js — @vue/language-server", resolve_root=_root_typescript,
build_spawn=_spawn_vue),
+ # Untrusted: no svelte.config.js and no project svelte/prettier (the server's own isTrusted switch).
_server("svelte-language-server", (".svelte",), "Svelte — svelte-language-server", resolve_root=_root_typescript,
- which=("svelteserver", "svelte-language-server"), args=("--stdio",), install_pkg="svelte-language-server"),
+ build_spawn=_untrusted_init("svelte-language-server", {"isTrusted": False},
+ ("svelteserver", "svelte-language-server"), ("--stdio",), "svelte-language-server")),
_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"),
- _server("rust-analyzer", (".rs",), "Rust — rust-analyzer", markers=["Cargo.toml", "Cargo.lock"], install_pkg="rust-analyzer"),
+ # 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("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"),
diff --git a/agent/lsp/workspace.py b/agent/lsp/workspace.py
index b1115d5ec94..c3cf2e0c952 100644
--- a/agent/lsp/workspace.py
+++ b/agent/lsp/workspace.py
@@ -2,7 +2,8 @@
1. **Workspace gate** — LSP only runs when the cwd (or the edited file) sits inside a git
worktree, so gateway users on user-home cwd's never spawn daemons.
-2. **nearest_root** — the per-server project-root walk: up from a start path looking for marker
+2. **Workspace trust** — whether a server may load code the project itself ships.
+3. **nearest_root** — the per-server project-root walk: up from a start path looking for marker
files (``pyproject.toml``, ``Cargo.toml``, ...), optionally bailing if an exclude marker
shows up first.
"""
@@ -153,12 +154,28 @@ def resolve_workspace_for_file(file_path: str, *, cwd: Optional[str] = None) ->
return None, False
+def is_trusted_workspace(root: str, trusted_roots: Iterable[str] = (), *, cwd: Optional[str] = None) -> bool:
+ """True iff a language server may load code the project at ``root`` ships (its own interpreter,
+ TypeScript SDK, config files, build scripts). Trusted: ``root`` is inside an operator-listed
+ ``lsp.trusted_workspaces`` entry, or it belongs to the same git worktree as the process cwd
+ (where the operator launched Hermes). A nested clone inside that worktree has its own ``.git``
+ and is not trusted: the agent may have fetched it."""
+ if any(is_inside_workspace(root, t) for t in trusted_roots):
+ return True
+ try:
+ anchor = cwd or os.getcwd()
+ except OSError:
+ return False
+ launch_root = find_git_worktree(anchor)
+ return launch_root is not None and find_git_worktree(root) == launch_root
+
+
def clear_cache() -> None:
"""Clear the workspace-resolution cache (on service shutdown, so re-init doesn't see stale results)."""
_workspace_cache.clear()
__all__ = [
- "find_git_worktree", "is_inside_workspace", "nearest_root", "normalize_path", "resolve_workspace_for_file",
- "clear_cache",
+ "find_git_worktree", "is_inside_workspace", "is_trusted_workspace", "nearest_root", "normalize_path",
+ "resolve_workspace_for_file", "clear_cache",
]
diff --git a/cli-config.yaml.example b/cli-config.yaml.example
index ccb5201d809..fb87be7d7a5 100644
--- a/cli-config.yaml.example
+++ b/cli-config.yaml.example
@@ -577,6 +577,19 @@ terminal:
# protected_instruction_files: true
# protected_instruction_extra_patterns: []
+# =============================================================================
+# LSP Diagnostics (post-write lint for write_file / patch)
+# =============================================================================
+# 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)
+# # 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.
+# trusted_workspaces:
+# - ~/code/my-app
+
# =============================================================================
# Browser Tool Configuration
# =============================================================================
diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.py
index 3054e81d19c..3dabf84a3f4 100644
--- a/hermes_cli/config_defaults.py
+++ b/hermes_cli/config_defaults.py
@@ -2400,6 +2400,12 @@ DEFAULT_CONFIG = {
# finish in budget, while every other workspace keeps its diagnostics. Must be a list —
# any other shape logs a warning and skips LSP for every workspace until fixed.
"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.
+ "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.
"install_strategy": "auto",
diff --git a/tests/agent/lsp/test_python_discovery.py b/tests/agent/lsp/test_python_discovery.py
index 0c95c1d2d99..327606129d0 100644
--- a/tests/agent/lsp/test_python_discovery.py
+++ b/tests/agent/lsp/test_python_discovery.py
@@ -46,7 +46,7 @@ def test_pyright_uses_the_project_interpreter_before_hermes(tmp_path, monkeypatc
pm_python = _seed_pm_python(tmp_path, monkeypatch)
context = servers.ServerContext(
workspace_root=str(project), install_strategy="off",
- binary_overrides={"pyright": [sys.executable]},
+ binary_overrides={"pyright": [sys.executable]}, trusted=True,
)
server = servers.find_server_for_file(str(project / "app.py"))
assert server is not None
diff --git a/tests/agent/lsp/test_workspace_trust.py b/tests/agent/lsp/test_workspace_trust.py
new file mode 100644
index 00000000000..af8e422de84
--- /dev/null
+++ b/tests/agent/lsp/test_workspace_trust.py
@@ -0,0 +1,128 @@
+"""Language servers must not load code a checkout ships 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.
+"""
+from __future__ import annotations
+
+import dataclasses
+import json
+import os
+import shutil
+
+from agent.lsp import manager
+from agent.lsp.servers import 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"}
+
+
+def _write(path, text: str = ""):
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(text, encoding="utf-8")
+ return path
+
+
+def _hermes_side_tree(tmp_path, monkeypatch) -> str:
+ """``<HERMES_HOME>/lsp/node_modules`` with a JS TypeScript SDK and Vue 2.x; returns a launcher inside it."""
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))
+ monkeypatch.delenv("VIRTUAL_ENV", raising=False)
+ staging = tmp_path / "home" / "lsp" / "node_modules"
+ _write(staging / "typescript" / "lib" / "typescript.js")
+ _write(staging / "typescript" / "lib" / "tsserver.js")
+ _write(staging / "@vue" / "language-server" / "package.json", json.dumps({"version": "2.2.12"}))
+ return str(_write(staging / "server-launcher"))
+
+
+def _checkout_shipping_its_own_toolchain(root) -> None:
+ """Marker files only: an interpreter path and a TypeScript SDK 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")
+
+
+def _strings(value):
+ if isinstance(value, str):
+ yield value
+ elif isinstance(value, dict):
+ for v in value.values():
+ yield from _strings(v)
+ elif isinstance(value, (list, tuple)):
+ for v in 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)
+ _write(tmp_path / "home" / "config.yaml", json.dumps({"lsp": {
+ "trusted_workspaces": [str(tmp_path / "listed")],
+ "servers": {"pyright": {"command": [launcher]}},
+ }}))
+ (launch / "src").mkdir()
+ monkeypatch.chdir(launch / "src")
+ clear_cache()
+
+ handed = {}
+
+ class _RecordingClient:
+ def __init__(self, *, workspace_root, initialization_options, **_):
+ handed[workspace_root] = initialization_options
+
+ async def start(self):
+ raise RuntimeError("recorded, not started")
+
+ 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)
+ finally:
+ svc.shutdown()
+
+ 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
diff --git a/website/docs/user-guide/features/lsp.md b/website/docs/user-guide/features/lsp.md
index 03fe7cc036b..4dd330c4435 100644
--- a/website/docs/user-guide/features/lsp.md
+++ b/website/docs/user-guide/features/lsp.md
@@ -56,6 +56,50 @@ real language server. Two channels, independent signals — the
agent sees a syntax-clean file with semantic problems as
``lint: ok`` plus a populated ``lsp_diagnostics``.
+### Workspace trust
+
+Some 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.
+
+Hermes therefore lets a server load project code only in a
+**trusted** workspace:
+
+- the git worktree Hermes was launched in (the process working
+ directory, so `cd my-app && hermes`), or
+- a directory listed under `lsp.trusted_workspaces` (or any
+ directory below one).
+
+A checkout nested inside the launch worktree has its own `.git`, so
+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:
+
+| Server | Untrusted workspace |
+|---|---|
+| pyright | `VIRTUAL_ENV` or the Hermes-managed Python, never the project's `.venv`/`venv` |
+| 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 |
+
+Diagnostics that need the project's dependencies (for example
+unresolved-import warnings) may be less precise until you trust the
+workspace.
+
+```yaml
+lsp:
+ trusted_workspaces:
+ - ~/code/my-app
+```
+
## Supported languages
| Language | Server | Auto-install |
@@ -212,6 +256,13 @@ lsp:
exclude_roots: []
# exclude_roots: ["~/work/huge-monorepo", "/srv/checkouts/*/vendor"]
+ # Directories whose projects a language server may load code from
+ # (see "Workspace trust" above). ~ expanded; everything under an
+ # entry counts. The git worktree Hermes was launched in is always
+ # trusted.
+ trusted_workspaces: []
+ # trusted_workspaces: ["~/code/my-app"]
+
# How to handle missing server binaries.
# auto — install via npm/pip/go install into <HERMES_HOME>/lsp/bin
# manual — only use binaries already on PATH
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 c2c04249ecb..51093f87370 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
@@ -46,6 +46,40 @@ agent 看到的输出如下:
`lsp_diagnostics` 字段承载来自真实语言服务器的语义诊断。两个通道,独立信号——
agent 对于语法正确但存在语义问题的文件,会看到 ``lint: ok`` 加上已填充的 ``lsp_diagnostics``。
+### 工作区信任
+
+部分语言服务器会运行项目自带的代码:pyright 会执行所配置的 Python
+解释器,typescript-language-server 会加载项目的
+`node_modules/typescript`,svelte-language-server 会加载
+`svelte.config.js`,rust-analyzer 会运行构建脚本和过程宏。对你自己的项目
+这没有问题,但对 agent 刚克隆下来的仓库则不应如此。
+
+因此,Hermes 只在**受信任**的工作区中允许服务器加载项目代码:
+
+- 启动 Hermes 时所在的 git 工作树(即进程工作目录,例如 `cd my-app && hermes`),或
+- `lsp.trusted_workspaces` 中列出的目录(及其下任意子目录)。
+
+嵌套在启动工作树内部的检出拥有自己的 `.git`,因此不受信任。网关和桌面端
+后端通常在任何仓库之外启动,所以在你列出项目之前,那里没有受信任的工作区。
+
+在不受信任的工作区中,服务器仍会运行,但使用 Hermes 一侧的工具:
+
+| 服务器 | 不受信任的工作区 |
+|---|---|
+| pyright | 使用 `VIRTUAL_ENV` 或 Hermes 管理的 Python,绝不使用项目的 `.venv`/`venv` |
+| 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 和工具链文件 |
+
+依赖项目依赖项的诊断(例如无法解析的导入)在信任该工作区之前可能不够精确。
+
+```yaml
+lsp:
+ trusted_workspaces:
+ - ~/code/my-app
+```
+
## 支持的语言
| 语言 | 服务器 | 自动安装 |
@@ -118,6 +152,12 @@ lsp:
# manual — 仅使用已在 PATH 上的二进制文件
install_strategy: auto
+ # 允许语言服务器加载项目自带代码的目录(见上文“工作区信任”)。
+ # 支持 ~ 展开,条目下的所有子目录均算在内。启动 Hermes 时所在的
+ # git 工作树始终受信任。
+ trusted_workspaces: []
+ # trusted_workspaces: ["~/code/my-app"]
+
# 各服务器覆盖配置(均为可选)。
servers:
pyright: