The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(lsp): trust the workspace the session was opened in, not only the process cwd
kshitijk4poore929702021f6
diff --git a/agent/lsp/manager.py b/agent/lsp/manager.pyindex 638e7996541..0b1d08eb716 100644--- a/agent/lsp/manager.py+++ b/agent/lsp/manager.py@@ -25,7 +25,7 @@ from agent.lsp.client import DIAGNOSTICS_DOCUMENT_WAIT, LSPClient, _diagnostic_kfrom 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+from agent.lsp.workspace import clear_cache, is_trusted_workspace, operator_workspace_roots, resolve_workspace_for_filelogger = logging.getLogger("agent.lsp.manager")@@ -65,17 +65,18 @@ def parse_trusted_workspaces(value: Any) -> List[str]: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",+ "only the workspaces you launched Hermes or opened the session in are 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:+def _client_key(srv: ServerDef, root: str, trusted: bool) -> _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."""- return (srv.server_id, "" if srv.multi_root else root)+ ``server_id`` across trusted roots; everything else, untrusted roots included, is keyed per+ resolved project root (a shared process keeps the trust its first root spawned it with)."""+ return (srv.server_id, "" if srv.multi_root and trusted else root)class _BackgroundLoop:@@ -167,6 +168,7 @@ class LSPService:self._exclude_roots: Optional[List[str]] = _parse_exclude_roots(exclude_roots)self._trusted_workspaces: List[str] = parse_trusted_workspaces(trusted_workspaces)self._untrusted_skipped: set = set() # (server_id, root) pairs denied by workspace trust+ self._operator_roots: frozenset = frozenset() # see _trustedself._loop = _BackgroundLoop()if self._enabled:@@ -268,17 +270,25 @@ 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):+ if self._untrusted_denied(srv, key[1], file_path, self._trusted(key[1])):return Falseif self._is_broken(key):eventlog.log_skipped_broken(srv.server_id, key[1], file_path, retry_in=self._broken_retry_in(key))return Falsereturn True- def _untrusted_denied(self, srv: ServerDef, root: str, file_path: str) -> bool:+ def _trusted(self, root: str) -> bool:+ """Trust for ``root``; remembers each ``operator_workspace_roots`` answer, because a tool thread+ sees the session's cwd while the loop thread that spawns servers does not."""+ if not (roots := operator_workspace_roots()) <= self._operator_roots:+ with self._state_lock: # rebind, never mutate: other threads read the old set lock-free+ self._operator_roots = self._operator_roots | roots+ return is_trusted_workspace(root, self._trusted_workspaces, self._operator_roots)++ def _untrusted_denied(self, srv: ServerDef, root: str, file_path: str, trusted: bool) -> 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):+ if trusted or srv.server_id in UNTRUSTED_SAFE_SERVERS:return Falsewith self._state_lock:self._untrusted_skipped.add((srv.server_id, root))@@ -319,7 +329,7 @@ class LSPService:if key is None:return self._wait_timeoutwith self._state_lock:- client = self._clients.get(_client_key(srv, key[1]))+ client = self._clients.get(_client_key(srv, key[1], self._trusted(key[1])))return self._wait_timeout if client is not None and client.is_running else self._warmup_timeoutdef snapshot_baseline(self, file_path: str) -> None:@@ -420,7 +430,7 @@ class LSPService:returnalready_broken = self._is_broken(key)self._mark_broken(key)- ckey = _client_key(srv, key[1])+ ckey = _client_key(srv, key[1], self._trusted(key[1]))with self._state_lock:client = self._clients.pop(ckey, None)self._last_used.pop(ckey, None)@@ -511,7 +521,7 @@ class LSPService:if root is None:return []with self._state_lock:- client = self._clients.get(_client_key(srv, root))+ client = self._clients.get(_client_key(srv, root, self._trusted(root)))return list(client.diagnostics_for(file_path, fresh_only=True)) if client else []async def _get_or_spawn(self, file_path: str) -> Optional[LSPClient]:@@ -529,11 +539,12 @@ 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):+ trusted = self._trusted(root)+ if self._untrusted_denied(srv, root, file_path, trusted):return Noneif self._is_broken((srv.server_id, root)):return None- key = _client_key(srv, root)+ key = _client_key(srv, root, trusted)with self._state_lock:client = self._clients.get(key)if client is not None and client.is_running:@@ -554,7 +565,7 @@ class LSPService:return Nonereturn await self._attach_root(srv, client, root) if client is not None else Nonetry:- client = await self._spawn_client(srv, root)+ client = await self._spawn_client(srv, root, trusted)if client is None:self._mark_broken((srv.server_id, root))else:@@ -575,12 +586,12 @@ class LSPService:await client.add_workspace_folder(root)return client- async def _spawn_client(self, srv: ServerDef, root: str) -> Optional[LSPClient]:+ async def _spawn_client(self, srv: ServerDef, root: str, trusted: bool) -> Optional[LSPClient]:"""Resolve the binary and start a client; ``None`` (after logging) when either fails."""ctx = ServerContext(workspace_root=root, install_strategy=self._install_strategy, binary_overrides=self._binary_overrides,env_overrides=self._env_overrides, init_overrides=self._init_overrides,- trusted=is_trusted_workspace(root, self._trusted_workspaces),+ trusted=trusted,)spec = srv.build_spawn(root, ctx)if spec is None:diff --git a/agent/lsp/workspace.py b/agent/lsp/workspace.pyindex c3cf2e0c952..a4147bac753 100644--- a/agent/lsp/workspace.py+++ b/agent/lsp/workspace.py@@ -12,7 +12,7 @@ from __future__ import annotationsimport loggingimport osfrom pathlib import Path-from typing import Iterable, Iterator, Optional, Tuple+from typing import Iterable, Iterator, Optional, Set, Tuplelogger = logging.getLogger("agent.lsp.workspace")@@ -154,20 +154,32 @@ 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:+def operator_workspace_roots() -> Set[str]:+ """Git worktrees the operator pointed Hermes at: the launch dir and the surface-set workspace+ (``resolve_agent_cwd``: the Desktop/TUI session cwd, ``hermes -w``'s worktree, a gateway's+ ``terminal.cwd``, a cron job's workdir). The agent moves neither (its ``cd`` only moves the+ terminal's cwd). ``$HOME`` never counts: a dotfiles repo there would trust every directory below it."""+ from agent.runtime_cwd import resolve_agent_cwd+ from tools.terminal_scope import TerminalPolicyUnavailable+ roots: Set[str] = set()+ for anchor in (os.getcwd, resolve_agent_cwd):+ try:+ root = find_git_worktree(str(anchor()))+ except (OSError, TerminalPolicyUnavailable): # a deleted cwd; a profile whose terminal policy failed+ continue+ if root is not None and root != normalize_path("~"):+ roots.add(root)+ return roots+++def is_trusted_workspace(root: str, trusted_roots: Iterable[str], operator_roots: Iterable[str]) -> 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."""+ TypeScript SDK, config files, build scripts): ``root`` is inside an ``lsp.trusted_workspaces``+ entry, or belongs to one of the ``operator_workspace_roots`` worktrees. A nested clone inside+ such a 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+ return find_git_worktree(root) in set(operator_roots)def clear_cache() -> None:@@ -177,5 +189,5 @@ def clear_cache() -> None:__all__ = ["find_git_worktree", "is_inside_workspace", "is_trusted_workspace", "nearest_root", "normalize_path",- "resolve_workspace_for_file", "clear_cache",+ "operator_workspace_roots", "resolve_workspace_for_file", "clear_cache",]diff --git a/cli-config.yaml.example b/cli-config.yaml.exampleindex fdb8d80d4e8..8fefa9aa667 100644--- a/cli-config.yaml.example+++ b/cli-config.yaml.example@@ -584,11 +584,11 @@ terminal:# enabled: true# # Language servers only load code a project ships (its .venv interpreter,# # 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. 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.+# # in the git worktree of the directory you launched Hermes in or opened+# # the session in (hermes -w, a Desktop project, terminal.cwd), or under a+# # directory listed 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.# trusted_workspaces:# - ~/code/my-appdiff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.pyindex 57e58fcd814..db159a52e8d 100644--- a/hermes_cli/config_defaults.py+++ b/hermes_cli/config_defaults.py@@ -2402,10 +2402,11 @@ 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, 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.+ # TypeScript SDK, svelte.config.js, build files (cargo, Gradle, mix, ...). The worktree of+ # the launch dir or the session's workspace (hermes -w, a Desktop project, terminal.cwd) is+ # always trusted; in any other checkout (a clone the agent made) 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_manager_locking.py b/tests/agent/lsp/test_manager_locking.pyindex 622a6506a69..3d987b1b0d9 100644--- a/tests/agent/lsp/test_manager_locking.py+++ b/tests/agent/lsp/test_manager_locking.py@@ -43,6 +43,7 @@ def test_reused_multiroot_client_attaches_outside_state_lock(monkeypatch):)client = StubClient()+ monkeypatch.setattr(service, "_trusted", lambda _root: True) # trusted roots share the processservice._clients[(server.server_id, "")] = client # multi-root client keyservice._last_used[(server.server_id, "")] = 0.0diff --git a/tests/agent/lsp/test_root_policy.py b/tests/agent/lsp/test_root_policy.pyindex 5e420dd5db1..e1d0873b1df 100644--- a/tests/agent/lsp/test_root_policy.py+++ b/tests/agent/lsp/test_root_policy.py@@ -112,7 +112,7 @@ def test_warmup_timeout_applies_to_cold_root_only(tmp_path, monkeypatch):try:with patch.object(svc, "_get_or_spawn", spawn):svc.snapshot_baseline(str(src)) # cold: no client registered for the root yet- key = _client_key(find_server_for_file(str(src)), str(repo))+ key = _client_key(find_server_for_file(str(src)), str(repo), svc._trusted(str(repo)))with svc._state_lock:svc._clients[key] = fakeassert svc.get_diagnostics_sync(str(src)) == [] # warmdiff --git a/tests/agent/lsp/test_workspace_trust.py b/tests/agent/lsp/test_workspace_trust.pyindex e25db00d480..6f9b3717da2 100644--- a/tests/agent/lsp/test_workspace_trust.py+++ b/tests/agent/lsp/test_workspace_trust.py@@ -126,7 +126,7 @@ def test_untrusted_checkout_starts_only_allowlisted_servers_pinned_to_hermes_codassert 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):+def test_only_operator_workspaces_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"@@ -146,7 +146,9 @@ def test_only_the_launch_worktree_and_listed_directories_are_trusted(tmp_path, mmonkeypatch.setattr(fops, "_lsp_will_handle", lambda _path: False)def shell_linted(root):+ """``npx tsc`` / rustup resolve the toolchain from the linter's cwd: the agent has ``cd``'d into ``root``."""ran.clear()+ fops.env.cwd = str(root)for name in ("a.ts", "a.rs"):fops._check_lint(str(root / name))return len(ran)@@ -159,3 +161,11 @@ def test_only_the_launch_worktree_and_listed_directories_are_trusted(tmp_path, massert not is_inside_workspace(handed[("pyright", str(root))].get("python", {}).get("pythonPath", ""), str(root)), rootassert ("rust-analyzer", str(root)) not in handedassert shell_linted(root) == 0, root++ # The workspace a surface points the session at is the operator's too (hermes -w, a Desktop project)...+ monkeypatch.setenv("TERMINAL_CWD", str(sibling))+ assert shell_linted(sibling) == 2+ # ...but never $HOME: a dotfiles repo there would trust every directory below it.+ monkeypatch.setenv("HOME", str(sibling))+ monkeypatch.setenv("USERPROFILE", str(sibling))+ assert shell_linted(sibling) == 0diff --git a/tools/file_operations_lint.py b/tools/file_operations_lint.pyindex 70b06084a04..daf3ad9309c 100644--- a/tools/file_operations_lint.py+++ b/tools/file_operations_lint.py@@ -168,7 +168,7 @@ 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):+ if ext in _SHELL_LINTER_RUNS_PROJECT_TOOLCHAIN and self._local_workspace_untrusted():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():@@ -251,21 +251,18 @@ class LintMixin:return Falsereturn 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."""+ def _local_workspace_untrusted(self) -> bool:+ """True iff on a local backend the linter's cwd lies outside every trusted workspace+ (``workspace.is_trusted_workspace``): ``npx`` and rustup resolve the toolchain from there, not+ from the linted file's directory. 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+ from agent.lsp.manager import parse_trusted_workspaces+ from agent.lsp.workspace import is_trusted_workspace, operator_workspace_roots+ 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)+ return not is_trusted_workspace(self.env.cwd or self.cwd, trusted, operator_workspace_roots())def _lsp_service(self):"""The active LSPService, or None on a non-local backend / any failure.diff --git a/website/docs/user-guide/features/lsp.md b/website/docs/user-guide/features/lsp.mdindex 3b13c1df6b6..f4663ba3ecb 100644--- a/website/docs/user-guide/features/lsp.md+++ b/website/docs/user-guide/features/lsp.md@@ -71,15 +71,18 @@ not for a repository the agent has just cloned.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+- the git worktree of a directory you pointed Hermes at: where you+ launched it (`cd my-app && hermes`), the worktree `hermes -w`+ created, the project a Desktop or TUI session is opened in, a+ gateway's `terminal.cwd`, or a cron job's workdir, or- a directory listed under `lsp.trusted_workspaces` (or anydirectory 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.+The agent cannot widen this: a `cd` in its terminal does not move the+session's workspace. A checkout nested inside a trusted worktree has+its own `.git`, so it is not trusted, and neither is a git repository+at your home directory itself (a dotfiles repo there would otherwise+trust everything below it).In an untrusted workspace Hermes **denies by default**: only theservers below start, each with settings that keep it on Hermes-side@@ -101,7 +104,8 @@ lsp.trusted_workspaces`, and `hermes lsp status` marks those servers| 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+checkout's own toolchain are skipped the same way whenever the terminal's+current directory is untrusted: `npx tsc` (it runsthe repository's `node_modules/.bin/tsc`, or installs from theregistry its `.npmrc` names) and `rustfmt --check` (rustup honours therepository's `rust-toolchain.toml`). Sandboxed backends (Docker, SSH,@@ -275,8 +279,8 @@ lsp:# 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.+ # entry counts. The worktree of the directory you launched Hermes in,+ # or opened the session in, is always trusted.trusted_workspaces: []# trusted_workspaces: ["~/code/my-app"]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.mdindex 5da7a9d6221..7cbdc554713 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@@ -59,11 +59,14 @@ haskell-language-server 等服务器在启动时就会求值项目的构建文因此,除以下情况外,Hermes 将所有工作区视为不受信任:-- 启动 Hermes 时所在的 git 工作树(即进程工作目录,例如 `cd my-app && hermes`),或+- 你让 Hermes 指向的目录所在的 git 工作树:启动 Hermes 的目录(`cd my-app && hermes`)、+ `hermes -w` 创建的工作树、桌面端或 TUI 会话打开的项目、网关的 `terminal.cwd`,+ 或定时任务的工作目录,或- `lsp.trusted_workspaces` 中列出的目录(及其下任意子目录)。-嵌套在启动工作树内部的检出拥有自己的 `.git`,因此不受信任。网关和桌面端-后端通常在任何仓库之外启动,所以在你列出项目之前,那里没有受信任的工作区。+agent 无法扩大信任范围:它在终端里执行 `cd` 不会改变会话的工作区。嵌套在受信任+工作树内部的检出拥有自己的 `.git`,因此不受信任;位于主目录本身的 git 仓库也不受+信任(否则主目录下的 dotfiles 仓库会让其下的所有目录都受信任)。在不受信任的工作区中,Hermes **默认拒绝**:只有下表中的服务器会启动,并且各自使用让它停留在 Hermes 一侧工具上的设置。其他所有服务器都会被跳过,包括@@ -82,7 +85,7 @@ prisma、astro,以及你在 `lsp.servers` 下声明的任何服务器。诊断| bash-language-server、yaml-language-server、dockerfile-ls、intelephense | 不变:它们只解析文件 || clangd | 不变:Hermes 从不传入 `--query-driver`,因此不会运行项目的编译器 |-在本地后端上,会使用检出自带工具链的写入后 shell 检查器也会以同样方式跳过:+在本地后端上,当终端的当前目录不受信任时,会使用检出自带工具链的写入后 shell 检查器也会以同样方式跳过:`npx tsc`(它会运行仓库的 `node_modules/.bin/tsc`,或从仓库 `.npmrc` 指定的registry 安装)和 `rustfmt --check`(rustup 会遵循仓库的 `rust-toolchain.toml`)。沙箱后端(Docker、SSH、Modal 等)不受影响。@@ -168,8 +171,8 @@ lsp:install_strategy: auto# 允许语言服务器加载项目自带代码的目录(见上文“工作区信任”)。- # 支持 ~ 展开,条目下的所有子目录均算在内。启动 Hermes 时所在的- # git 工作树始终受信任。+ # 支持 ~ 展开,条目下的所有子目录均算在内。启动 Hermes 或打开会话时+ # 所在目录的 git 工作树始终受信任。trusted_workspaces: []# trusted_workspaces: ["~/code/my-app"]