The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(plugins): say plainly that the gateway does not load project plugins
unsupportedpastels027e62ed17ff
diff --git a/agent/session_client_env.py b/agent/session_client_env.pyindex 083218b7f97..31bb652c309 100644--- a/agent/session_client_env.py+++ b/agent/session_client_env.py@@ -6,7 +6,9 @@ keep the gateway's environment, and so does a session created before ``client_enPlain names and string values only. Behaviour names are read through :func:`session_env`; thetoolchain names (``PATH``, an activated venv, nvm/pyenv/conda) reach that session's tool subprocesses-through :func:`tool_env`. Values are never logged.+through :func:`toolchain_environ`. Values naming this host (toolchain paths, the prefill file, the+project-plugins check of the client's folder) apply only when the gateway proved the client is on its+host (``local``); otherwise the session keeps the gateway's and is told so. Values are never logged."""from __future__ import annotations@@ -20,13 +22,19 @@ from tools.code_execution_env import is_secret_env_name# What main's CLI read per process and the gateway otherwise reads daemon-wide.BEHAVIOUR_ENV = ('HERMES_EPHEMERAL_SYSTEM_PROMPT', 'HERMES_PREFILL_MESSAGES_FILE', 'HERMES_INFERENCE_PROVIDER','HERMES_ENABLE_PROJECT_PLUGINS')+# Behaviour values that name the client's host: a path, or the opt-in that inspects the client's folder.+HOST_BEHAVIOUR = ('HERMES_PREFILL_MESSAGES_FILE', 'HERMES_ENABLE_PROJECT_PLUGINS')TOOL_ENV = ('PATH', 'VIRTUAL_ENV', 'GOPATH', 'GOROOT', 'CARGO_HOME', 'RUSTUP_HOME', 'JAVA_HOME')TOOL_ENV_PREFIXES = ('CONDA_', 'NODE_', 'NVM_', 'PYENV_')# ``terminal.client_env_passthrough`` names more non-secret toolchain variables for a profile.CONFIG_KEY = 'client_env_passthrough'+# The session-start notice of a session whose client the gateway could not place on its own host.+NOT_LOCAL_WARNING = ("this session uses the gateway's own PATH, toolchain and prefill file: the client's environment "+ 'was not applied because the client is not attached to this gateway locally.')_MAX_NAMES = 256_MAX_BYTES = 256 * 1024+# (env, local) for the session executing here; None outside a shell client's session._BOUND: ContextVar = ContextVar('session_client_env', default=None)@@ -57,15 +65,17 @@ def collect_client_env(environ=None, config=None) -> dict[str, str]:return {name: value for name, value in environ.items() if isinstance(value, str) and allowed(name, extra)}-def accept_client_env(value, config) -> dict[str, str]:- """Gateway side: the validated map, filtered again against the session profile's own allowlist.+def accept_client_env(value, config, *, local=True) -> dict[str, str]:+ """Gateway side: the validated map, filtered again against the session profile's own allowlist; for a+ client not proven ``local`` only the values that name nothing on this host (prompt, provider request).Raises ``ValueError`` for anything but a bounded flat string-to-string map."""if (not isinstance(value, dict) or len(value) > _MAX_NAMESor any(not isinstance(k, str) or not isinstance(v, str) for k, v in value.items())or sum(len(k) + len(v) for k, v in value.items()) > _MAX_BYTES):raise ValueError('client_env must be a map of variable names to string values')extra = configured_names(config)- return {name: value[name] for name in sorted(value) if allowed(name, extra)}+ return {name: value[name] for name in sorted(value) if allowed(name, extra)+ and (local or (name in BEHAVIOUR_ENV and name not in HOST_BEHAVIOUR))}def retry_matches(committed_json, params) -> bool:@@ -79,9 +89,10 @@ def retry_matches(committed_json, params) -> bool:@contextmanager-def client_env_scope(env):- """Bind one session's client environment (``None``: the gateway's own) for this context."""- token = _BOUND.set(env)+def client_env_scope(env, *, local=True):+ """Bind one session's client environment (``None``: the gateway's own) for this context; ``local``+ is the gateway's own proof, frozen in the session's policy, that the client runs on this host."""+ token = _BOUND.set(None if env is None else (env, bool(local)))try:yieldfinally:@@ -89,31 +100,37 @@ def client_env_scope(env):def bound_client_env():- return _BOUND.get()+ bound = _BOUND.get()+ return None if bound is None else bound[0]def session_env(name: str, default: str = '') -> str:"""A behaviour value for the session executing here: its client's (an unexported name is unset,- as it was for main's process), else the gateway's own environment."""- env = _BOUND.get()- if env is None:+ as it was for main's process), else the gateway's own environment, which a client not attached+ locally also keeps for the values that name this host."""+ bound = _BOUND.get()+ if bound is None or (name in HOST_BEHAVIOUR and not bound[1]):return os.getenv(name, default)- return env.get(name, default)+ return bound[0].get(name, default)def tool_env() -> dict[str, str]:- """The toolchain values this session's tool subprocesses start with (empty when unbound)."""- env = _BOUND.get() or {}- return {name: value for name, value in env.items() if name not in BEHAVIOUR_ENV and _travels(name)}+ """The toolchain values this session's tool subprocesses start with (empty when unbound or remote)."""+ bound = _BOUND.get()+ if bound is None or not bound[1]:+ return {}+ return {name: value for name, value in bound[0].items() if name not in BEHAVIOUR_ENV and _travels(name)}def toolchain_environ(base=None) -> dict[str, str]:"""The environment this session's tool subprocesses start from (``base``: the gateway's). Unbound- (messaging, cron, Desktop): unchanged. A shell client's session: its toolchain replaces the gateway's,- and a built-in toolchain name it did not export is unset, as in main's process: one client's venv- never reaches another's session through the daemon it started."""+ (messaging, cron, Desktop) or a client not attached locally: unchanged. A local shell client's+ session: its toolchain replaces the gateway's, and a built-in toolchain name it did not export is+ unset, as in main's process: one client's venv never reaches another's session through the daemon+ it started."""env = dict(os.environ if base is None else base)- if _BOUND.get() is None:+ bound = _BOUND.get()+ if bound is None or not bound[1]:return envkept = {k: v for k, v in env.items() if k == 'PATH' or not (k in TOOL_ENV or k.startswith(TOOL_ENV_PREFIXES))}return kept | tool_env()diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.tsindex 82a0822e2d2..edfcf0f8317 100644--- a/apps/shared/src/gateway-contract.generated.ts+++ b/apps/shared/src/gateway-contract.generated.ts@@ -4594,6 +4594,7 @@ export interface CanonicalSessionInfo {api_mode?: string | nulltool_count?: number | nullcredential_hint?: string | null+ config_warning?: string | null[key: string]: unknown}export interface SessionStatsParams {diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.jsonindex cf24441d675..8e4ed54657a 100644--- a/apps/shared/src/gateway-contract.openrpc.json+++ b/apps/shared/src/gateway-contract.openrpc.json@@ -10204,6 +10204,18 @@],"default": null,"title": "Credential Hint"+ },+ "config_warning": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Config Warning"}},"required": [diff --git a/cli-config.yaml.example b/cli-config.yaml.exampleindex 4687dc01eb9..036c5a7b060 100644--- a/cli-config.yaml.example+++ b/cli-config.yaml.example@@ -433,9 +433,11 @@ terminal:lifetime_seconds: 300# A `hermes` / `hermes --tui` session's local tools (terminal, background processes, execute_code)# start with the launching shell's toolchain: PATH, VIRTUAL_ENV and CONDA_* / NODE_* / NVM_* /- # PYENV_* (plus GOPATH, GOROOT, CARGO_HOME, RUSTUP_HOME, JAVA_HOME), for that session only.- # List more non-secret names here; names that look like credentials (…TOKEN, …KEY, …SECRET,- # …PASSWORD, …AUTH) are never sent: pass secrets with `env_passthrough` instead.+ # PYENV_* (plus GOPATH, GOROOT, CARGO_HOME, RUSTUP_HOME, JAVA_HOME), for that session only, when+ # the client runs on the gateway's host (a remote client's session keeps the gateway's toolchain).+ # List more non-secret names here; names execute_code treats as credentials (…TOKEN, …KEY,+ # …SECRET, …PASSWORD, …AUTH, …DSN, …WEBHOOK, …CREDS, …BEARER, …COOKIE) and HERMES_* names are+ # never sent: pass secrets with `env_passthrough` instead.# client_env_passthrough: ["GEM_HOME", "POETRY_HOME"]# sudo_password: "hunter2" # Optional: pipe a sudo password via sudo -S. SECURITY WARNING: plaintext.# sudo_password: "" # Explicit empty password: try empty and never open the interactive sudo prompt.diff --git a/gateway/session_controls.py b/gateway/session_controls.pyindex 98af790bea3..a0c446d8ad9 100644--- a/gateway/session_controls.py+++ b/gateway/session_controls.py@@ -376,7 +376,9 @@ class AuthorityConnection:sid = local_identity(self.authority.profile_id, self.actor.subject, params['request_id'])if self.authority.db.get_session(sid) is None:skills_prompt = await asyncio.to_thread(render_launch_skills, params, sid)- ref = stage_local_session(self.authority, self.actor, params, skills_prompt=skills_prompt)+ # Host-bound client values apply only over the gateway's own ticketed attach (run_api).+ ref = stage_local_session(self.authority, self.actor, params, skills_prompt=skills_prompt,+ client_local=self.native_owner)if isinstance(ref, dict):# The creation commit runs off the owner loop: a held writer must not freeze# every session behind one new chat (N50).diff --git a/gateway/session_local.py b/gateway/session_local.pyindex ef8b4080aaf..ed4f09e3815 100644--- a/gateway/session_local.py+++ b/gateway/session_local.py@@ -4,6 +4,7 @@ Source and supported launch settings are frozen per route, never process env."""from __future__ import annotations+import loggingimport uuidfrom contextlib import contextmanager@@ -13,6 +14,8 @@ from gateway.session import SessionSourcefrom gateway.session_contract import CANONICAL_GATEWAY_PROTOCOLfrom hermes_state_runtime import RuntimeStoreError+logger = logging.getLogger(__name__)+class LocalSessionAdapter(BasePlatformAdapter):"""Delivery stays in the canonical event stream; no second local transport."""@@ -130,7 +133,7 @@ def authorize_local_source(runner, source):return adapter.authorize_source(source)-def _bypass_policy(params, *, private_secrets):+def _bypass_policy(params, *, private_secrets, client_local=False):"""Frozen snapshot for --safe-mode / --ignore-user-config: code defaults plus the explicitlaunch options. The profile's config.yaml/.env are never read, so a malformed profile cannotblock or shape the session; there is no default model to inherit, so one must be explicit."""@@ -143,7 +146,8 @@ def _bypass_policy(params, *, private_secrets):defaults = copy.deepcopy(DEFAULT_CONFIG)if not isinstance(defaults.get('model'), dict): # code default is the empty stringdefaults['model'] = {}- return build_policy(params, defaults, private_secrets=private_secrets, profile_terminal=False)+ return build_policy(params, defaults, private_secrets=private_secrets, profile_terminal=False,+ client_local=client_local)def load_profile_config(home=None):@@ -175,21 +179,45 @@ def profile_env_scope(home=None):reset_secret_scope(token)-def create_local_session(authority, actor, params, *, trusted_policy=None, trusted_secrets=None, skills_prompt=None):+def project_plugins_warning(policy):+ """The plain notice for a session whose client opted into project plugins (its forwarded+ ``HERMES_ENABLE_PROJECT_PLUGINS``) in a folder that has some: the gateway never loads them."""+ from pathlib import Path+ from utils import is_truthy_value+ # The client's folder is a path on this host only for a client the gateway proved local.+ env = policy.client_env() if policy is not None and not policy.client_env_remote else None+ folder = Path(policy.cwd) / '.hermes' / 'plugins' if env else None+ if not env or not is_truthy_value(env.get('HERMES_ENABLE_PROJECT_PLUGINS')) or not folder.is_dir():+ return None+ try:+ if not any(folder.iterdir()):+ return None+ except OSError: # an unlistable folder skips the optional notice, never the session+ return None+ return (f'project plugins in {folder} are not loaded: the gateway that runs Hermes sessions does not '+ 'load ./.hermes/plugins, so HERMES_ENABLE_PROJECT_PLUGINS has no effect here.')+++def create_local_session(authority, actor, params, *, trusted_policy=None, trusted_secrets=None, skills_prompt=None,+ client_local=False):"""Stage, commit and publish a local session inline (synchronous callers)."""from gateway.session_local_recovery import restore_local_sessionfrom hermes_state_local import commit_local_sessionstaged = stage_local_session(authority, actor, params, trusted_policy=trusted_policy,- trusted_secrets=trusted_secrets, skills_prompt=skills_prompt)+ trusted_secrets=trusted_secrets, skills_prompt=skills_prompt,+ client_local=client_local)if isinstance(staged, dict):commit_local_session(authority.db, epoch=authority.epoch, receipt=staged)staged = restore_local_session(authority, staged['session_id'])return staged-def stage_local_session(authority, actor, params, *, trusted_policy=None, trusted_secrets=None, skills_prompt=None):+def stage_local_session(authority, actor, params, *, trusted_policy=None, trusted_secrets=None, skills_prompt=None,+ client_local=False):"""Everything before the creation commit: the existing session's ref on an exact retry, else the- receipt ``commit_local_session`` writes (the async RPC commits it off the owner loop)."""+ receipt ``commit_local_session`` writes (the async RPC commits it off the owner loop).+ ``client_local``: the gateway's own proof that the client is on this host (its connection redeemed a+ ticket minted over the private control socket), never a value the client sends."""if actor.profile_id != authority.profile_id:raise RuntimeStoreError('profile_mismatch')if 'session:create' not in actor.capabilities:@@ -202,7 +230,7 @@ def stage_local_session(authority, actor, params, *, trusted_policy=None, trusteif trusted_policy is not None:policy = trusted_policyelif any(params.get(name) is True for name in BYPASS_FIELDS):- policy = _bypass_policy(params, private_secrets=private_secrets)+ policy = _bypass_policy(params, private_secrets=private_secrets, client_local=client_local)else:from gateway.session_local_route import resolve_launch_routeraw_model, sent = params.get('model'), params@@ -210,7 +238,8 @@ def stage_local_session(authority, actor, params, *, trusted_policy=None, trusteconfig = load_profile_config()params = resolve_launch_route(params, config)# A client's session.create is the one caller whose named folder may select the coding posture.- policy = build_policy(params, config, private_secrets=private_secrets, workspace_posture=True)+ policy = build_policy(params, config, private_secrets=private_secrets, workspace_posture=True,+ client_local=client_local)if params is not sent: # resolved, even to a model of the alias's own name# Owner-stamped provenance (not create fields): a remote client cannot re-resolve the typed# `-m` alias against its own home, so resume and an exact retry compare a repeat against the@@ -262,6 +291,8 @@ def stage_local_session(authority, actor, params, *, trusted_policy=None, trusteraise RuntimeStoreError('invalid_params', field='skills',detail='the caller must render -s skills before minting the session')policy = replace(policy, skills_prompt=skills_prompt)+ if warning := project_plugins_warning(policy):+ logger.warning('session %s: %s', sid, warning)policy = bind_launch_key(authority, sid, policy, params.get("api_key"), config_secrets=private_secrets,owner_key=client_key is None) # an overlapping exact retry takes the held onefrom gateway.session_local_recovery import local_source@@ -361,6 +392,11 @@ def local_session_info(authority, ref):# resuming client can tell "same flags again" from a real override attempt.import jsoninfo['launch_request'] = json.loads(policy.request_json)+ from agent.session_client_env import NOT_LOCAL_WARNING+ # Session-start notices main's TUI already renders as ``config_warning``.+ notices = (project_plugins_warning(policy), NOT_LOCAL_WARNING if policy.client_env_remote else None)+ if warning := ' '.join(filter(None, notices)):+ info['config_warning'] = warninginfo.update(_classic_cli_fields(authority, ref, live, agent, policy))return infodiff --git a/gateway/session_policy.py b/gateway/session_policy.pyindex 2c1197e2d94..6f099577fb7 100644--- a/gateway/session_policy.py+++ b/gateway/session_policy.py@@ -78,10 +78,17 @@ class LocalSessionPolicy:# The shell-launched client's allowlisted environment (``agent.session_client_env``), bound for this# session's turns only; None when the client sent none (Desktop, a session from before the field).client_env_json: str | None = None+ # The client sent one over an attach the gateway could not prove is on its host (no gateway-minted+ # ticket): only host-free values were kept, and its tools run with the gateway's own toolchain.+ client_env_remote: bool = Falsedef client_env(self):return None if self.client_env_json is None else json.loads(self.client_env_json)+ def client_env_scope(self):+ from agent.session_client_env import client_env_scope+ return client_env_scope(self.client_env(), local=not self.client_env_remote)+def config(self, authority=None, *, secrets=True):return self.effective(authority, secrets=secrets)[0]@@ -296,7 +303,8 @@ def present_sections(config):return config-def build_policy(params, config, *, private_secrets=None, profile_terminal=True, workspace_posture=False):+def build_policy(params, config, *, private_secrets=None, profile_terminal=True, workspace_posture=False,+ client_local=False):from agent.runtime_cwd import resolve_agent_cwdfrom tools.terminal_scope import build_profile_terminal_scope, default_terminal_scopefrom hermes_constants import get_hermes_home@@ -351,7 +359,8 @@ def build_policy(params, config, *, private_secrets=None, profile_terminal=True,if 'client_env' in params:from agent.session_client_env import accept_client_envtry:- client_env = json.dumps(accept_client_env(params['client_env'], config), sort_keys=True)+ client_env = json.dumps(accept_client_env(params['client_env'], config, local=client_local),+ sort_keys=True)except ValueError as exc:_refuse('client_env', str(exc))# Values stay out of the request: ``launch_request`` is echoed to every viewer of the session.@@ -364,7 +373,8 @@ def build_policy(params, config, *, private_secrets=None, profile_terminal=True,return LocalSessionPolicy(source, SURFACES[source], cwd, model, tuple(sorted(enabled)),json.dumps(config), json.dumps(request, sort_keys=True), json.dumps(terminal),safe_mode=safe_mode, ignore_user_config=ignore_user_config,- coding_posture=coding_posture, client_env_json=client_env)+ coding_posture=coding_posture, client_env_json=client_env,+ client_env_remote=client_env is not None and not client_local)def terminal_uses_host_cwd(terminal):@@ -807,7 +817,7 @@ def restore_policy(data):or type(policy.safe_mode) is not bool or type(policy.ignore_user_config) is not boolor not isinstance(policy.skills_prompt, (str, type(None)))or type(policy.coding_posture) is not bool- or not _valid_client_env(policy.client_env_json)+ or not _valid_client_env(policy.client_env_json) or type(policy.client_env_remote) is not boolor (policy.safe_mode and not policy.ignore_user_config)):raise ValueError('invalid policy')from dataclasses import replace@@ -871,7 +881,6 @@ def policy_scope(policy, *, authority=None):cwd_token = set_session_cwd(policy.cwd)terminal_token = set_terminal_scope(terminal)policy_token = _ACTIVE_POLICY.set(active)- from agent.session_client_env import client_env_scopefrom gateway.session_local_editor import editor_scopetry:from agent.auxiliary_task_config import session_auxiliary_scope@@ -880,7 +889,7 @@ def policy_scope(policy, *, authority=None):auxiliary = policy.config(authority).get('auxiliary') if authority is not None else Noneaux_scope = session_auxiliary_scope(auxiliary) if authority is not None else contextlib.nullcontext()with (editor_scope(policy), editor_mcp_scope(authority, policy), aux_scope,- client_env_scope(policy.client_env())):+ policy.client_env_scope()):yieldfinally:_ACTIVE_POLICY.reset(policy_token)diff --git a/gateway/session_policy_credentials.py b/gateway/session_policy_credentials.pyindex 0e653055097..1d68264a2ac 100644--- a/gateway/session_policy_credentials.py+++ b/gateway/session_policy_credentials.py@@ -68,6 +68,8 @@ def policy_identity(policy):data.pop('coding_posture', None)if data.get('client_env_json') is None:data.pop('client_env_json', None)+ if not data.get('client_env_remote'):+ data.pop('client_env_remote', None)return hashlib.sha256(json.dumps(data, sort_keys=True).encode()).hexdigest()diff --git a/gateway/session_worker_construct.py b/gateway/session_worker_construct.pyindex 0e7838f3be8..2796c7b2eb2 100644--- a/gateway/session_worker_construct.py+++ b/gateway/session_worker_construct.py@@ -41,9 +41,8 @@ def _ephemeral_prompt(authority, policy, chat_id):configured = Noneresolve = getattr(authority.runner, '_get_system_prompt_for_channel', None)if not policy.ignore_user_config and resolve is not None:- from agent.session_client_env import client_env_scopefrom gateway.config import Platform- with client_env_scope(policy.client_env()):+ with policy.client_env_scope():configured = resolve(Platform.LOCAL, chat_id or '')return '\n\n'.join(p for p in (configured, policy.skills_prompt) if p) or None@@ -119,13 +118,12 @@ def _held_prefill(authority):def _read_prefill(authority, policy):- from agent.session_client_env import client_env_scopefrom hermes_cli.cli_config_load import _load_prefill_messages, _resolve_prefill_messages_filehome = Path(str(authority.profile_id))if not home.is_absolute():from hermes_constants import get_hermes_homehome = get_hermes_home()- with client_env_scope(policy.client_env()): # HERMES_PREFILL_MESSAGES_FILE: the session's client's+ with policy.client_env_scope(): # HERMES_PREFILL_MESSAGES_FILE: a local session's client'spath = _resolve_prefill_messages_file(policy.config(authority, secrets=False))return _load_prefill_messages(path, home) or Nonediff --git a/hermes_cli/gateway_chat.py b/hermes_cli/gateway_chat.pyindex 944adb2a3b5..7b42222168d 100644--- a/hermes_cli/gateway_chat.py+++ b/hermes_cli/gateway_chat.py@@ -220,6 +220,8 @@ async def run_gateway_chat(args, emitter=None):if missing:raise GatewayClientError("Gateway does not support creation options: " + ", ".join(missing))snapshot = await client.rpc("session.create", request_id=uuid.uuid4().hex, source=source, **policy)+ if (warning := (snapshot.get("info") or {}).get("config_warning")) and not isinstance(oneshot_prompt, str):+ print(f"Warning: {warning}", file=sys.stderr)if not isinstance(oneshot_prompt, str): # main's -z writes nothing to stderr on successprint("Session: " + snapshot["stored_session_id"], file=sys.stderr, flush=True)if not oneshot:diff --git a/hermes_cli/gateway_session_store.py b/hermes_cli/gateway_session_store.pyindex 90ffba134e2..c09b78ffb28 100644--- a/hermes_cli/gateway_session_store.py+++ b/hermes_cli/gateway_session_store.py@@ -19,6 +19,7 @@ import argparseimport loggingimport osimport re+import sysimport uuidfrom hermes_cli.gateway_client import GatewayClientError@@ -159,6 +160,9 @@ class GatewaySessionStore:params["title"] = titleparams.update(self.client_env())snapshot = self.call("session.create", request_id=uuid.uuid4().hex, **params)+ warning = (snapshot.get("info") or {}).get("config_warning")+ if warning:+ print(f"Warning: {warning}", file=sys.stderr)return self._adopt(snapshot)def client_env(self):diff --git a/tests/acp_adapter/test_policy_identity_compat.py b/tests/acp_adapter/test_policy_identity_compat.pyindex ac2bb808fde..289118037af 100644--- a/tests/acp_adapter/test_policy_identity_compat.py+++ b/tests/acp_adapter/test_policy_identity_compat.py@@ -14,5 +14,6 @@ def test_policy_identity_preserves_pre_editor_credential_binding(tmp_path):legacy.pop('editor_mcp_json')legacy.pop('coding_posture')legacy.pop('client_env_json')+ legacy.pop('client_env_remote')expected = hashlib.sha256(json.dumps(legacy, sort_keys=True).encode()).hexdigest()assert policy_identity(policy) == expecteddiff --git a/tests/gateway/test_project_plugins_warning.py b/tests/gateway/test_project_plugins_warning.pynew file mode 100644index 00000000000..0d92f6f2c15--- /dev/null+++ b/tests/gateway/test_project_plugins_warning.py@@ -0,0 +1,111 @@+"""LC-4: the gateway runs every local session and never loads ``./.hermes/plugins``. A session whose+client opted in (``HERMES_ENABLE_PROJECT_PLUGINS``, forwarded in ``client_env``) from a folder that has+project plugins gets a gateway.log line and a client-visible ``config_warning`` saying so."""+import logging+from types import SimpleNamespace++import pytest+++async def _owner(home, monkeypatch):+ from gateway import run+ from gateway.config import GatewayConfig+ from gateway.session import SessionStore+ from gateway.session_authority import initialize_session_authority+ from gateway.session_controls import AuthorityConnection+ monkeypatch.setattr(run, '_hermes_home', home)+ monkeypatch.setenv('HERMES_HOME', str(home))+ store = SessionStore(home / 'sessions', GatewayConfig())+ runner = SimpleNamespace(session_store=store, _session_db=store._db, adapters={}, _draining=False,+ _cached_agent_for=lambda route: None, _adapter_for_source=lambda source: None,+ _evict_cached_agent=lambda route: None)+ owner = await initialize_session_authority(runner, profile_id=str(home), instance_id='fixture')+ # This fixture's runner has no adapter table: hand session.info the session's frozen policy.+ from gateway import session_policy+ from hermes_state_local import local_receipt+ monkeypatch.setattr(session_policy, 'policy_for_source', lambda runner, source: session_policy.restore_policy(+ local_receipt(owner.db, source.chat_id)['policy']))+ return owner, AuthorityConnection(owner, object(), {'user_id': 'owner'})+++async def test_an_opted_in_session_is_told_project_plugins_do_not_load(tmp_path, monkeypatch, caplog):+ from gateway.session_local import create_local_session, local_session_info+ home = tmp_path / 'home'+ home.mkdir()+ (home / 'config.yaml').write_text(+ 'platform_toolsets: {cli: []}\nmodel: {provider: custom, default: m, base_url: http://x.invalid/v1}\n')+ repo, plain = tmp_path / 'repo', tmp_path / 'plain'+ (repo / '.hermes' / 'plugins' / 'mine').mkdir(parents=True)+ (plain / '.hermes' / 'plugins').mkdir(parents=True) # opted in, but no plugin in it+ monkeypatch.delenv('HERMES_ENABLE_PROJECT_PLUGINS', raising=False)+ owner, connection = await _owner(home, monkeypatch)++ def create(request_id, cwd, **extra):+ ref = create_local_session(owner, connection.actor, {'request_id': request_id, 'source': 'cli',+ 'cwd': str(cwd), 'toolsets': [], **extra},+ client_local=True) # the client's folder is on this host+ return local_session_info(owner, ref).get('config_warning')+ try:+ with caplog.at_level(logging.WARNING):+ warning = create('opted', repo, client_env={'HERMES_ENABLE_PROJECT_PLUGINS': 'true'})+ assert warning and 'not loaded' in warning and str(repo / '.hermes' / 'plugins') in warning+ assert any('project plugins' in record.getMessage() and str(repo) in record.getMessage()+ for record in caplog.records)+ assert create('off', repo, client_env={'HERMES_ENABLE_PROJECT_PLUGINS': '0'}) is None+ assert create('unset', repo, client_env={}) is None+ assert create('empty', plain, client_env={'HERMES_ENABLE_PROJECT_PLUGINS': '1'}) is None+ assert create('desktop', repo) is None # a client that sends no environment+ finally:+ await connection.close()+ owner.db.close()+++async def test_an_unlistable_plugins_folder_never_blocks_the_session(tmp_path, monkeypatch):+ """``is_dir`` can pass while listing fails (no read permission): the optional notice is skipped and+ the session is still created and described."""+ import pathlib+ from gateway.session_local import create_local_session, local_session_info+ home, folder = tmp_path / 'home', tmp_path / 'repo' / '.hermes' / 'plugins'+ home.mkdir()+ (home / 'config.yaml').write_text(+ 'platform_toolsets: {cli: []}\nmodel: {provider: custom, default: m, base_url: http://x.invalid/v1}\n')+ (folder / 'mine').mkdir(parents=True)+ owner, connection = await _owner(home, monkeypatch)+ real = pathlib.Path.iterdir++ def iterdir(path):+ if path == folder:+ raise PermissionError(13, 'Permission denied', str(path))+ return real(path)+ monkeypatch.setattr(pathlib.Path, 'iterdir', iterdir)+ try:+ try:+ ref = create_local_session(owner, connection.actor, {+ 'request_id': 'locked', 'source': 'cli', 'cwd': str(tmp_path / 'repo'), 'toolsets': [],+ 'client_env': {'HERMES_ENABLE_PROJECT_PLUGINS': '1'}}, client_local=True)+ info = local_session_info(owner, ref)+ except OSError as exc:+ info = {'error': repr(exc)}+ assert 'error' not in info and info.get('config_warning') is None, info+ finally:+ await connection.close()+ owner.db.close()+++def test_classic_cli_prints_the_sessions_config_warning(capsys):+ from hermes_cli.gateway_session_store import GatewaySessionStore++ class Connection:+ final = False++ def call(self, method, **params):+ if method == 'runtime.describe':+ return {'session_create': {'parameters': []}}+ return {'stored_session_id': 'sid', 'info': {'config_warning': 'project plugins in /r are not loaded'}}++ def state(self, sid):+ return SimpleNamespace(adopt_snapshot=lambda snapshot: None)+ GatewaySessionStore(Connection()).create({})+ assert 'Warning: project plugins in /r are not loaded' in capsys.readouterr().errdiff --git a/tests/gateway/test_session_client_env.py b/tests/gateway/test_session_client_env.pyindex eb9fc69f049..fa087bfe69c 100644--- a/tests/gateway/test_session_client_env.py+++ b/tests/gateway/test_session_client_env.py@@ -38,8 +38,9 @@ def _create(owner, actor, home, request_id, **extra):from gateway.session_local import create_local_sessionfrom gateway.session_policy import restore_policyfrom hermes_state_local import local_receipt+ # A shell client attached through the gateway's own ticket (the gateway's proof it is on this host).ref = create_local_session(owner, actor, {'request_id': request_id, 'source': 'cli', 'cwd': str(home),- 'toolsets': [], **extra})+ 'toolsets': [], **extra}, client_local=True)return ref, restore_policy(local_receipt(owner.db, ref.session_id)['policy'])@@ -191,7 +192,7 @@ async def test_exact_retry_is_judged_by_the_committed_map_not_the_current_allowlenv = {'GEM_HOME': '/gems', 'BUNDLE_PATH': '/bundle', 'PATH': '/client/bin'}params = {'request_id': 'g', 'source': 'cli', 'cwd': str(home), 'toolsets': [], 'client_env': env}try:- ref = create_local_session(owner, connection.actor, dict(params))+ ref = create_local_session(owner, connection.actor, dict(params), client_local=True)saved = local_receipt(owner.db, ref.session_id)['policy']assert json.loads(saved['client_env_json']) == {'GEM_HOME': '/gems', 'PATH': '/client/bin'}# The profile stops listing GEM_HOME and starts listing BUNDLE_PATH: both directions of the@@ -211,6 +212,69 @@ async def test_exact_retry_is_judged_by_the_committed_map_not_the_current_allowlowner.db.close()+async def test_host_values_apply_only_over_a_gateway_proven_local_attach(tmp_path, monkeypatch):+ """Toolchain and path-valued values are the client's only when the gateway itself proves the attach is+ on its host: the connection redeemed a ticket minted over the gateway's private control socket+ (``run_api``: ``native_bootstrap``). Any other attach keeps the gateway's values and is told so;+ non-path behaviour values apply for any authenticated client. A client-sent flag never counts."""+ from gateway import session_policy+ from gateway.session_controls import AuthorityConnection+ from gateway.session_local import local_session_info+ from gateway.session_local_recovery import restore_local_session+ from gateway.session_policy import policy_scope, restore_policy+ from gateway.session_worker_construct import session_prefill+ from hermes_cli.runtime_provider import resolve_requested_provider+ from hermes_state_local import local_receipt+ from hermes_state_runtime import RuntimeStoreError+ from tools.environments.local import _make_run_env+ home = _home(tmp_path, 'platform_toolsets: {cli: []}\nmodel: {default: m}\n') # no configured provider+ repo = tmp_path / 'repo'+ (repo / '.hermes' / 'plugins' / 'mine').mkdir(parents=True)+ for name in ('gateway', 'client'):+ (home / f'{name}.json').write_text(json.dumps([{'role': 'user', 'content': name}]))+ monkeypatch.setenv('HERMES_PREFILL_MESSAGES_FILE', str(home / 'gateway.json'))+ monkeypatch.setenv('PATH', '/daemon/bin:/usr/bin:/bin')+ monkeypatch.delenv('NVM_DIR', raising=False)+ owner, remote = await _owner(home, monkeypatch) # an attach without the gateway's own ticket+ local = AuthorityConnection(owner, object(), {'user_id': 'owner', 'native_bootstrap': True})+ monkeypatch.setattr(session_policy, 'policy_for_source', lambda runner, source: restore_policy(+ local_receipt(owner.db, source.chat_id)['policy']))+ sent = {'PATH': '/client/bin:/usr/bin', 'NVM_DIR': '/client/nvm', 'HERMES_ENABLE_PROJECT_PLUGINS': '1',+ 'HERMES_PREFILL_MESSAGES_FILE': str(home / 'client.json'),+ 'HERMES_EPHEMERAL_SYSTEM_PROMPT': 'P', 'HERMES_INFERENCE_PROVIDER': 'openrouter'}++ async def create(connection, request_id):+ snapshot = await connection.create(None, {'request_id': request_id, 'source': 'cli', 'cwd': str(repo),+ 'toolsets': [], 'client_env': dict(sent)})+ ref = restore_local_session(owner, snapshot['session_id'])+ policy = restore_policy(local_receipt(owner.db, ref.session_id)['policy'])+ with policy_scope(policy, authority=owner):+ run = _make_run_env({})+ seen = (run['PATH'].split(':')[0], run.get('NVM_DIR'), _turn_prompt(owner, policy),+ resolve_requested_provider())+ return policy, seen, session_prefill(owner, policy, ref.session_id), local_session_info(owner, ref)+ try:+ policy, seen, prefill, info = await create(local, 'here')+ assert policy.client_env() == sent+ assert seen == ('/client/bin', '/client/nvm', 'P', 'openrouter')+ assert prefill == [{'role': 'user', 'content': 'client'}]+ assert 'project plugins' in info['config_warning']+ policy, seen, prefill, info = await create(remote, 'there')+ assert policy.client_env() == {'HERMES_EPHEMERAL_SYSTEM_PROMPT': 'P', 'HERMES_INFERENCE_PROVIDER': 'openrouter'}+ assert seen == ('/daemon/bin', None, 'P', 'openrouter')+ assert prefill == [{'role': 'user', 'content': 'gateway'}]+ assert 'not attached to this gateway locally' in info['config_warning']+ assert 'project plugins' not in info['config_warning']+ with pytest.raises(RuntimeStoreError): # a client cannot claim locality for itself+ await remote.create(None, {'request_id': 'claim', 'source': 'cli', 'cwd': str(repo), 'toolsets': [],+ 'client_env': dict(sent), 'client_local': True})+ finally:+ await local.close()+ await remote.close()+ owner.db.close()++@pytest.mark.asyncioasync def test_runtime_describe_lists_client_env(tmp_path, monkeypatch):home = _home(tmp_path)diff --git a/tests/tools/test_session_tool_env.py b/tests/tools/test_session_tool_env.pyindex b1da8470995..0ad7c469616 100644--- a/tests/tools/test_session_tool_env.py+++ b/tests/tools/test_session_tool_env.py@@ -152,7 +152,8 @@ async def test_a_sessions_terminal_runs_with_its_clients_path(tmp_path, monkeyparef = create_local_session(owner, connection.actor, {'request_id': name, 'source': 'cli', 'cwd': str(home), 'toolsets': [],'client_env': {'PATH': f'{path}{os.pathsep}/usr/bin{os.pathsep}/bin', 'NVM_DIR': str(path.parent),- 'MY_TOOLCHAIN_HOME': f'/opt/{name}', 'MY_API_TOKEN': 'secret', 'UNLISTED': 'x'}})+ 'MY_TOOLCHAIN_HOME': f'/opt/{name}', 'MY_API_TOKEN': 'secret', 'UNLISTED': 'x'}},+ client_local=True) # attached through the gateway's own ticketpolicies[name] = restore_policy(local_receipt(owner.db, ref.session_id)['policy'])# Listed toolchain names travel; a credential-looking name never lands in the stored policy.assert set(policies['alpha'].client_env()) == {'PATH', 'NVM_DIR', 'MY_TOOLCHAIN_HOME'}diff --git a/tui_gateway/contracts/canonical.py b/tui_gateway/contracts/canonical.pyindex d4b4ba6a007..9448f707f8e 100644--- a/tui_gateway/contracts/canonical.py+++ b/tui_gateway/contracts/canonical.py@@ -177,6 +177,8 @@ class CanonicalSessionInfo(SessionInventoryFields, OpenModel):api_mode: str | None = Nonetool_count: int | None = Nonecredential_hint: str | None = None+ # A session-start notice (the project plugins this gateway does not load).+ config_warning: str | None = Nonecanonical_method("session.info", params=CanonicalSessionInfoParams, result=CanonicalSessionInfo,diff --git a/website/docs/user-guide/features/plugins.md b/website/docs/user-guide/features/plugins.mdindex 0434973a0bb..001dae848af 100644--- a/website/docs/user-guide/features/plugins.md+++ b/website/docs/user-guide/features/plugins.md@@ -90,7 +90,11 @@ Drop both files into `~/.hermes/plugins/hello-world/`, restart Hermes, and the mThe model-facing tool description belongs in `schema["description"]`. The optional `ctx.register_tool(description=...)` value is separate `ToolEntry` registry metadata: when omitted, it defaults to the schema description, but Hermes does not copy it back into a schema that lacks `description`. Prefer defining the text once in the schema. If you provide both values, keep them synchronized; the model sees the schema value.-Project-local plugins under `./.hermes/plugins/` are disabled by default. Enable them only for trusted repositories by setting `HERMES_ENABLE_PROJECT_PLUGINS=true` before starting Hermes.+### Project-local plugins (`./.hermes/plugins/`) {#project-local-plugins}++The gateway does not load project-local plugins. Every Hermes session (`hermes`, `hermes --tui`, the Desktop app, messaging and cron) runs in the one gateway, which discovers plugins once for the whole process and never from the folder you started a session in. Setting `HERMES_ENABLE_PROJECT_PLUGINS=true` therefore has no effect on sessions: when a CLI or TUI session on the gateway's machine starts with it set in a folder whose `./.hermes/plugins/` has plugins, Hermes shows a warning at the start of that session and writes the same line to `gateway.log`.++To use a plugin, install it as a user plugin (`~/.hermes/plugins/` or `hermes plugins install`) and enable it with `hermes plugins enable <name>`.## What plugins can do@@ -126,7 +130,7 @@ Every `ctx.*` API below is available inside a plugin's `register(ctx)` function.|--------|------|----------|| Bundled | `<repo>/plugins/` | Ships with Hermes — see [Built-in Plugins](./built-in-plugins.md) || User | `~/.hermes/plugins/` | Personal plugins |-| Project | `.hermes/plugins/` | Project-specific plugins (requires `HERMES_ENABLE_PROJECT_PLUGINS=true`) |+| Project | `.hermes/plugins/` | Not loaded by the gateway that runs sessions; see [Project-local plugins](#project-local-plugins) || pip | `hermes_agent.plugins` entry_points | Distributed packages || Nix | `services.hermes-agent.extraPlugins` / `extraPythonPackages` | NixOS declarative installs — see [Nix Setup](../../getting-started/nix-setup.md#plugins) |