Skip to content

The agent that grows with you

fix(lsp): no automatic trust for scheduled work; lock-free trust lookups

kshitijk4poorda2b64304bae
diff --git a/agent/lsp/manager.py b/agent/lsp/manager.py
index e32ebf7a5fd..56f83e3cc54 100644
--- a/agent/lsp/manager.py
+++ b/agent/lsp/manager.py
@@ -44,27 +44,32 @@ def _float_or(value: Any, default: float) -> float:
return default
-def _parse_path_list(value: Any, key: str, expected: str, consequence: str, invalid: Optional[List[str]]):
- """Normalise a ``~``-expanded list of paths; ``invalid`` (with a WARNING) for a non-list value."""
+def _path_list(value: Any) -> Optional[List[str]]:
+ """A config list of paths, ``~``-expanded; ``None`` when the value is not a list of strings."""
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.%s must be %s (got %s); %s until the key is fixed",
- key, expected, type(value).__name__, consequence)
- return invalid
+ return None
return [os.path.expanduser(p) for p in value if p]
def _parse_exclude_roots(value: Any) -> Optional[List[str]]:
"""``lsp.exclude_roots``; ``None`` (fail closed: every root excluded) for a malformed value."""
- return _parse_path_list(value, "exclude_roots", "a list of glob patterns, e.g. ['~/big-monorepo', '/srv/*/vendor']",
- "LSP is skipped for every workspace", None)
+ if (roots := _path_list(value)) is None:
+ eventlog.event_log.warning(
+ "lsp.exclude_roots must be a list of glob patterns, e.g. ['~/big-monorepo', '/srv/*/vendor'] "
+ "(got %s); LSP is skipped for every workspace until the key is fixed", type(value).__name__)
+ return roots
def parse_trusted_workspaces(value: Any) -> List[str]:
"""``lsp.trusted_workspaces``; a malformed value trusts nothing extra."""
- return _parse_path_list(value, "trusted_workspaces", "a list of directories, e.g. ['~/code/my-app']",
- "only the workspaces you launched Hermes or opened the session in are trusted", [])
+ if (roots := _path_list(value)) is None:
+ eventlog.event_log.warning(
+ "lsp.trusted_workspaces must be a list of directories, e.g. ['~/code/my-app'] (got %s); only the "
+ "workspaces you launched Hermes or opened a session in are trusted until the key is fixed",
+ type(value).__name__)
+ return roots or []
def _client_key(srv: ServerDef, root: str, trusted: bool) -> _Key:
@@ -163,7 +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 _trusted
+ self._operator_roots = frozenset(operator_workspace_roots()) # see _note_operator_roots
self._loop = _BackgroundLoop()
if self._enabled:
@@ -265,6 +270,7 @@ 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
+ self._note_operator_roots()
if self._untrusted_denied(srv, key[1], file_path, self._trusted(key[1])):
return False
if self._is_broken(key):
@@ -272,14 +278,24 @@ class LSPService:
return False
return True
- 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."""
+ def _note_operator_roots(self) -> None:
+ """Remember this thread's ``operator_workspace_roots``. Called where a tool thread enters (it sees
+ the session's cwd; the loop thread that spawns servers does not), so trust is per process: a
+ workspace any session was opened in stays trusted until shutdown."""
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
+
+ def _trusted(self, root: str) -> bool:
return is_trusted_workspace(root, self._trusted_workspaces, self._operator_roots)
+ def _live_key(self, srv: ServerDef, root: str) -> _Key:
+ """The client key for ``root`` (under ``_state_lock``): a multi-root server started while
+ ``root`` was untrusted keeps its own client after ``root`` becomes trusted, so it is found and
+ released rather than orphaned."""
+ own = (srv.server_id, root)
+ return own if own in self._clients or own in self._spawning else _client_key(srv, root, self._trusted(root))
+
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)."""
@@ -324,7 +340,7 @@ class LSPService:
if key is None:
return self._wait_timeout
with self._state_lock:
- client = self._clients.get(_client_key(srv, key[1], self._trusted(key[1])))
+ client = self._clients.get(self._live_key(srv, key[1]))
return self._wait_timeout if client is not None and client.is_running else self._warmup_timeout
def snapshot_baseline(self, file_path: str) -> None:
@@ -425,8 +441,8 @@ class LSPService:
return
already_broken = self._is_broken(key)
self._mark_broken(key)
- ckey = _client_key(srv, key[1], self._trusted(key[1]))
with self._state_lock:
+ ckey = self._live_key(srv, key[1])
client = self._clients.pop(ckey, None)
self._last_used.pop(ckey, None)
if client is not None:
@@ -458,7 +474,7 @@ 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)
+ untrusted = sorted(pair for pair in self._untrusted_skipped if not self._trusted(pair[1]))
return {
"enabled": self._enabled, "wait_mode": self._wait_mode, "wait_timeout": self._wait_timeout,
"install_strategy": self._install_strategy, "clients": clients, "broken": broken,
@@ -516,7 +532,7 @@ class LSPService:
if root is None:
return []
with self._state_lock:
- client = self._clients.get(_client_key(srv, root, self._trusted(root)))
+ client = self._clients.get(self._live_key(srv, 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]:
@@ -534,13 +550,15 @@ class LSPService:
if root is None:
eventlog.log_disabled(srv.server_id, file_path, "exclude marker hit (server gated off)")
return None
- trusted = self._trusted(root)
- if self._untrusted_denied(srv, root, file_path, trusted):
+ if self._untrusted_denied(srv, root, file_path, self._trusted(root)):
return None
if self._is_broken((srv.server_id, root)):
return None
- key = _client_key(srv, root, trusted)
with self._state_lock:
+ key = self._live_key(srv, root)
+ # Derived with the key: trust only grows, so one read before the lock could store an
+ # untrusted spawn under the shared multi-root key every trusted root then attaches to.
+ trusted = key[1] == "" or self._trusted(root)
client = self._clients.get(key)
if client is not None and client.is_running:
self._last_used[key] = time.time()
diff --git a/agent/lsp/servers.py b/agent/lsp/servers.py
index 60b153267e0..3a584b8c8b3 100644
--- a/agent/lsp/servers.py
+++ b/agent/lsp/servers.py
@@ -236,9 +236,9 @@ _VUE_TSDK_MSG = (
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
- (``root`` is None for an untrusted workspace, whose own JavaScript must not load)."""
+ """``node_modules`` trees that may hold a server and its TypeScript SDK: the launcher's own tree
+ (symlinks resolved), Hermes staging, then the project's (``root`` None: Hermes's trees only, for
+ TypeScript's SDK pin in 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")] if root else [])
real = os.path.realpath(bin_path)
diff --git a/agent/lsp/workspace.py b/agent/lsp/workspace.py
index a4147bac753..fa5560bfe25 100644
--- a/agent/lsp/workspace.py
+++ b/agent/lsp/workspace.py
@@ -12,7 +12,7 @@ from __future__ import annotations
import logging
import os
from pathlib import Path
-from typing import Iterable, Iterator, Optional, Set, Tuple
+from typing import AbstractSet, Iterable, Iterator, Optional, Set, Tuple
logger = logging.getLogger("agent.lsp.workspace")
@@ -157,29 +157,40 @@ def resolve_workspace_for_file(file_path: str, *, cwd: Optional[str] = None) ->
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."""
+ ``terminal.cwd``). The agent's ``cd`` moves neither (it only moves the terminal's cwd). A repo at
+ or above ``$HOME`` never counts: a dotfiles repo would trust every directory below it."""
from agent.runtime_cwd import resolve_agent_cwd
+ from gateway.session_context import get_session_env
from tools.terminal_scope import TerminalPolicyUnavailable
+ from utils import is_truthy_value
+ # Work the model can schedule has no operator anchor: a kanban worker is launched in (with
+ # TERMINAL_CWD =) the task's workspace and a cron run's session cwd is the job's workdir, and the
+ # kanban_create / cronjob tools let the model pick both.
+ if os.environ.get("HERMES_KANBAN_TASK"):
+ return set()
+ anchors = [os.getcwd]
+ if not is_truthy_value(get_session_env("HERMES_CRON_SESSION", "")):
+ anchors.append(resolve_agent_cwd)
+ home = normalize_path("~")
roots: Set[str] = set()
- for anchor in (os.getcwd, resolve_agent_cwd):
+ for anchor in anchors:
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("~"):
+ if root is not None and not is_inside_workspace(home, root):
roots.add(root)
return roots
-def is_trusted_workspace(root: str, trusted_roots: Iterable[str], operator_roots: Iterable[str]) -> bool:
+def is_trusted_workspace(root: str, trusted_roots: Iterable[str], operator_roots: AbstractSet[str]) -> bool:
"""True iff a language server may load code the project at ``root`` ships (its own interpreter,
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
- return find_git_worktree(root) in set(operator_roots)
+ return find_git_worktree(root) in operator_roots
def clear_cache() -> None:
diff --git a/tests/agent/lsp/test_workspace_trust.py b/tests/agent/lsp/test_workspace_trust.py
index fa6acf21487..93a57b331fb 100644
--- a/tests/agent/lsp/test_workspace_trust.py
+++ b/tests/agent/lsp/test_workspace_trust.py
@@ -161,7 +161,17 @@ def test_only_operator_workspaces_and_listed_directories_are_trusted(tmp_path, m
# 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.
+ # ...but not one the model scheduled: a cron job's workdir or a kanban task's workspace...
+ from gateway.session_context import clear_session_vars, set_session_vars
+ tokens = set_session_vars(cron_session="1")
+ try:
+ assert shell_linted(sibling) == 0
+ finally:
+ clear_session_vars(tokens)
+ monkeypatch.setenv("HERMES_KANBAN_TASK", "t_1")
+ assert shell_linted(sibling) == 0
+ monkeypatch.delenv("HERMES_KANBAN_TASK")
+ # ...and 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) == 0
diff --git a/tools/file_operations_lint.py b/tools/file_operations_lint.py
index daf3ad9309c..ff3273c0ead 100644
--- a/tools/file_operations_lint.py
+++ b/tools/file_operations_lint.py
@@ -262,7 +262,7 @@ class LintMixin:
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())
+ return not is_trusted_workspace(getattr(self.env, "cwd", None) 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.md
index 8ec1219928b..a5e188c437d 100644
--- a/website/docs/user-guide/features/lsp.md
+++ b/website/docs/user-guide/features/lsp.md
@@ -73,16 +73,20 @@ Hermes therefore treats every workspace as untrusted unless it is:
- 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
+ created, the project a Desktop or TUI session is opened in, or a
+ gateway's `terminal.cwd`, or
- a directory listed under `lsp.trusted_workspaces` (or any
directory below one).
-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).
+A `cd` in the agent's terminal does not move the session's workspace.
+Cron jobs and Kanban workers get no automatic trust, because the agent
+can choose their workdir or workspace; list the directories they should
+trust under `lsp.trusted_workspaces`. A checkout nested inside a trusted
+worktree has its own `.git`, so it is not trusted, and neither is a git
+repository at or above your home directory (a dotfiles repo there would
+otherwise trust everything below it). Trust covers the whole directory
+you pointed Hermes at, including anything later cloned into it, and
+lasts until Hermes exits.
In an untrusted workspace Hermes **denies by default**: only the
servers below start, each with settings that keep it on Hermes-side
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 72a31095edd..3bc9c0941b6 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
@@ -60,13 +60,15 @@ haskell-language-server 等服务器在启动时就会求值项目的构建文
因此,除以下情况外,Hermes 将所有工作区视为不受信任:
- 你让 Hermes 指向的目录所在的 git 工作树:启动 Hermes 的目录(`cd my-app && hermes`)、
- `hermes -w` 创建的工作树、桌面端或 TUI 会话打开的项目、网关的 `terminal.cwd`,
- 或定时任务的工作目录,或
+ `hermes -w` 创建的工作树、桌面端或 TUI 会话打开的项目,或网关的 `terminal.cwd`,或
- `lsp.trusted_workspaces` 中列出的目录(及其下任意子目录)。
-agent 无法扩大信任范围:它在终端里执行 `cd` 不会改变会话的工作区。嵌套在受信任
-工作树内部的检出拥有自己的 `.git`,因此不受信任;位于主目录本身的 git 仓库也不受
-信任(否则主目录下的 dotfiles 仓库会让其下的所有目录都受信任)。
+agent 在终端里执行 `cd` 不会改变会话的工作区。定时任务和 Kanban worker 不会自动获得
+信任,因为 agent 可以选择它们的工作目录或工作区;请在 `lsp.trusted_workspaces` 中列出
+它们应信任的目录。嵌套在受信任工作树内部的检出拥有自己的 `.git`,因此不受信任;位于
+主目录或其上级目录的 git 仓库也不受信任(否则主目录下的 dotfiles 仓库会让其下的所有目录
+都受信任)。信任覆盖你让 Hermes 指向的整个目录(包括之后克隆到其中的内容),并持续到
+Hermes 退出。
在不受信任的工作区中,Hermes **默认拒绝**:只有下表中的服务器会启动,并且各自
使用让它停留在 Hermes 一侧工具上的设置。其他所有服务器都会被跳过,包括