Skip to content

The agent that grows with you

fix(gateway): apply a client's HERMES_* behaviour values to its own session only

unsupportedpastelsaa86cf68155b
diff --git a/agent/session_client_env.py b/agent/session_client_env.py
new file mode 100644
index 00000000000..e3bc45dbd0e
--- /dev/null
+++ b/agent/session_client_env.py
@@ -0,0 +1,104 @@
+"""A local session's client environment: the allowlisted values a shell-launched client (classic CLI,
+Ink TUI) sends as ``session.create``'s ``client_env``. Main's ``hermes`` process read them from its own
+shell; the one gateway now runs every session, so they are frozen with the session's policy and bound
+for its turns only, never written to the gateway's ``os.environ``. Desktop sends none: its sessions
+keep the gateway's environment, and so does a session created before ``client_env`` existed.
+
+Plain names and string values only. Behaviour names are read through :func:`session_env`; the
+toolchain names (``PATH``, an activated venv, nvm/pyenv/conda) reach that session's tool subprocesses
+through :func:`tool_env`. Values are never logged.
+"""
+from __future__ import annotations
+
+import json
+import os
+import re
+from contextlib import contextmanager
+from contextvars import ContextVar
+
+# 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')
+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'
+# A name that looks like a credential never travels or lands in the session's stored policy, even when
+# listed (``NODE_AUTH_TOKEN`` matches ``NODE_``); secrets reach tools through ``terminal.env_passthrough``.
+_SECRETISH = re.compile(r'TOKEN|SECRET|PASS|KEY|AUTH|CREDENTIAL|COOKIE', re.IGNORECASE)
+_MAX_NAMES = 256
+_MAX_BYTES = 256 * 1024
+
+_BOUND: ContextVar = ContextVar('session_client_env', default=None)
+
+
+def configured_names(config) -> frozenset:
+ """The profile's extra tool names (``terminal.client_env_passthrough``)."""
+ terminal = config.get('terminal') if isinstance(config, dict) else None
+ raw = terminal.get(CONFIG_KEY) if isinstance(terminal, dict) else None
+ return frozenset(name.strip() for name in raw if isinstance(name, str) and name.strip()) if isinstance(raw, list) else frozenset()
+
+
+def allowed(name: str, extra: frozenset = frozenset()) -> bool:
+ if name in BEHAVIOUR_ENV:
+ return True
+ if _SECRETISH.search(name):
+ return False
+ return name in TOOL_ENV or name.startswith(TOOL_ENV_PREFIXES) or name in extra
+
+
+def collect_client_env(environ=None, config=None) -> dict[str, str]:
+ """Client side: this shell's allowlisted values (the profile's extra names included)."""
+ environ = os.environ if environ is None else environ
+ extra = configured_names(config)
+ 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.
+ Raises ``ValueError`` for anything but a bounded flat string-to-string map."""
+ if (not isinstance(value, dict) or len(value) > _MAX_NAMES
+ or 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)}
+
+
+def retry_matches(committed_json, params) -> bool:
+ """Whether a retried ``session.create`` carries the client environment its committed session froze.
+ The committed (normalised) map decides, never the current allowlist: every stored name must come back
+ with its value; names the gateway filtered out at creation do not count, whatever the rules are now."""
+ if committed_json is None:
+ return 'client_env' not in params
+ value = params.get('client_env')
+ return isinstance(value, dict) and all(value.get(k) == v for k, v in json.loads(committed_json).items())
+
+
+@contextmanager
+def client_env_scope(env):
+ """Bind one session's client environment (``None``: the gateway's own) for this context."""
+ token = _BOUND.set(env)
+ try:
+ yield
+ finally:
+ _BOUND.reset(token)
+
+
+def bound_client_env():
+ return _BOUND.get()
+
+
+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:
+ return os.getenv(name, default)
+ return env.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}
diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.ts
index 3781859a945..82a0822e2d2 100644
--- a/apps/shared/src/gateway-contract.generated.ts
+++ b/apps/shared/src/gateway-contract.generated.ts
@@ -4881,6 +4881,7 @@ export interface CanonicalCreateParams {
cwd_explicit?: boolean | null
run_budget?: number | null
verbose?: boolean
+ client_env?: Record<string, string> | null
}
export interface CanonicalSnapshot {
session_id: string
diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.json
index 145e3ce295b..cf24441d675 100644
--- a/apps/shared/src/gateway-contract.openrpc.json
+++ b/apps/shared/src/gateway-contract.openrpc.json
@@ -8839,6 +8839,21 @@
"default": false,
"title": "Verbose",
"type": "boolean"
+ },
+ "client_env": {
+ "anyOf": [
+ {
+ "additionalProperties": {
+ "type": "string"
+ },
+ "type": "object"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Client Env"
}
},
"title": "CanonicalCreateParams",
diff --git a/gateway/run_config_loaders.py b/gateway/run_config_loaders.py
index fe8796bb207..5230924b184 100644
--- a/gateway/run_config_loaders.py
+++ b/gateway/run_config_loaders.py
@@ -91,9 +91,11 @@ class GatewayConfigLoadersMixin:
@staticmethod
def _load_ephemeral_system_prompt() -> str:
- """HERMES_EPHEMERAL_SYSTEM_PROMPT env first, then ``display.personality`` / ``agent.system_prompt``."""
+ """HERMES_EPHEMERAL_SYSTEM_PROMPT env first (a local session's: its client's), then
+ ``display.personality`` / ``agent.system_prompt``."""
+ from agent.session_client_env import session_env
from gateway.run import _load_gateway_config
- prompt = os.getenv("HERMES_EPHEMERAL_SYSTEM_PROMPT", "")
+ prompt = session_env("HERMES_EPHEMERAL_SYSTEM_PROMPT")
if prompt:
return prompt
return resolve_ephemeral_system_prompt_from_config(_load_gateway_config())
diff --git a/gateway/session_local.py b/gateway/session_local.py
index 5e57cdcd099..ef8b4080aaf 100644
--- a/gateway/session_local.py
+++ b/gateway/session_local.py
@@ -238,7 +238,9 @@ def stage_local_session(authority, actor, params, *, trusted_policy=None, truste
saved = local_receipt(authority.db, sid)
original = restore_policy(saved['policy'])
from hermes_state_local import same_create_request
- if not same_create_request(original.request_json, policy.request_json):
+ from agent.session_client_env import retry_matches
+ if (not same_create_request(original.request_json, policy.request_json)
+ or not retry_matches(original.client_env_json, params)):
raise RuntimeStoreError('invalid_params', field='request_id',
detail='a resumed request_id must carry the same frozen request')
import hmac
diff --git a/gateway/session_policy.py b/gateway/session_policy.py
index 87230e43659..2c1197e2d94 100644
--- a/gateway/session_policy.py
+++ b/gateway/session_policy.py
@@ -15,7 +15,7 @@ CREATE_FIELDS = frozenset({'request_id', 'source', 'cwd', 'model', 'toolsets',
'provider', 'base_url', 'reasoning', 'max_turns', 'ignore_rules', 'api_key', 'editor',
'yolo', 'safe_mode', 'ignore_user_config',
'skills', 'checkpoints', 'accept_hooks', 'pass_session_id', 'follow_profile_config',
- 'service_tier', 'cwd_explicit', 'run_budget', 'verbose', 'row_cwd'})
+ 'service_tier', 'cwd_explicit', 'run_budget', 'verbose', 'row_cwd', 'client_env'})
# Sections a ``follow_profile_config`` session re-reads from the owning profile's CURRENT config each
# turn (main's Bot Chat row), credentials included: a frozen key never crosses a profile route change.
FOLLOW_SECTIONS = ('model', 'providers', 'custom_providers', 'fallback_providers', 'fallback_model', 'model_aliases',
@@ -75,6 +75,12 @@ class LocalSessionPolicy:
# workspace). A following session replays this decision rather than re-probing its folder each turn: it
# drops the posture when its profile leaves ``focus``, and one created outside it never gains it later.
coding_posture: bool = False
+ # 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
+
+ def client_env(self):
+ return None if self.client_env_json is None else json.loads(self.client_env_json)
def config(self, authority=None, *, secrets=True):
return self.effective(authority, secrets=secrets)[0]
@@ -341,7 +347,15 @@ def build_policy(params, config, *, private_secrets=None, profile_terminal=True,
# configured cwd unless the user picked this folder for the session.
if params.get('cwd_explicit') is True or terminal_uses_host_cwd(terminal):
terminal['TERMINAL_CWD'] = cwd
- request = {k: v for k, v in params.items() if k not in {'request_id', 'api_key'}}
+ client_env = None
+ if 'client_env' in params:
+ from agent.session_client_env import accept_client_env
+ try:
+ client_env = json.dumps(accept_client_env(params['client_env'], config), 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.
+ request = {k: v for k, v in params.items() if k not in {'request_id', 'api_key', 'client_env'}}
request.setdefault('source', 'cli')
from gateway.session_local_mcp import private_editor_request
private_editor_request(request, private_secrets)
@@ -350,7 +364,7 @@ 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)
+ coding_posture=coding_posture, client_env_json=client_env)
def terminal_uses_host_cwd(terminal):
@@ -793,6 +807,7 @@ def restore_policy(data):
or type(policy.safe_mode) is not bool or type(policy.ignore_user_config) is not bool
or 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 (policy.safe_mode and not policy.ignore_user_config)):
raise ValueError('invalid policy')
from dataclasses import replace
@@ -807,6 +822,13 @@ def restore_policy(data):
raise RuntimeStoreError('storage_unavailable') from exc
+def _valid_client_env(value):
+ if value is None:
+ return True
+ env = json.loads(value) if isinstance(value, str) else None
+ return isinstance(env, dict) and all(isinstance(k, str) and isinstance(v, str) for k, v in env.items())
+
+
def policy_for_source(runner, source):
from gateway.session_local import LocalSessionAdapter
from gateway.config import Platform
@@ -849,6 +871,7 @@ 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_scope
from gateway.session_local_editor import editor_scope
try:
from agent.auxiliary_task_config import session_auxiliary_scope
@@ -856,7 +879,8 @@ def policy_scope(policy, *, authority=None):
# Auxiliary tasks read the session's frozen section, never live config.yaml (a rotated key there).
auxiliary = policy.config(authority).get('auxiliary') if authority is not None else None
aux_scope = session_auxiliary_scope(auxiliary) if authority is not None else contextlib.nullcontext()
- with editor_scope(policy), editor_mcp_scope(authority, policy), aux_scope:
+ with (editor_scope(policy), editor_mcp_scope(authority, policy), aux_scope,
+ client_env_scope(policy.client_env())):
yield
finally:
_ACTIVE_POLICY.reset(policy_token)
diff --git a/gateway/session_policy_credentials.py b/gateway/session_policy_credentials.py
index 3e391e93457..0e653055097 100644
--- a/gateway/session_policy_credentials.py
+++ b/gateway/session_policy_credentials.py
@@ -66,6 +66,8 @@ def policy_identity(policy):
data.pop('editor_mcp_json', None)
if not data.get('coding_posture'):
data.pop('coding_posture', None)
+ if data.get('client_env_json') is None:
+ data.pop('client_env_json', 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.py
index 3e863a2a00c..0e7838f3be8 100644
--- a/gateway/session_worker_construct.py
+++ b/gateway/session_worker_construct.py
@@ -41,8 +41,10 @@ def _ephemeral_prompt(authority, policy, chat_id):
configured = None
resolve = 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_scope
from gateway.config import Platform
- configured = resolve(Platform.LOCAL, chat_id or '')
+ with client_env_scope(policy.client_env()):
+ configured = resolve(Platform.LOCAL, chat_id or '')
return '\n\n'.join(p for p in (configured, policy.skills_prompt) if p) or None
@@ -117,12 +119,14 @@ def _held_prefill(authority):
def _read_prefill(authority, policy):
+ from agent.session_client_env import client_env_scope
from hermes_cli.cli_config_load import _load_prefill_messages, _resolve_prefill_messages_file
home = Path(str(authority.profile_id))
if not home.is_absolute():
from hermes_constants import get_hermes_home
home = get_hermes_home()
- path = _resolve_prefill_messages_file(policy.config(authority, secrets=False))
+ with client_env_scope(policy.client_env()): # HERMES_PREFILL_MESSAGES_FILE: the session's client's
+ path = _resolve_prefill_messages_file(policy.config(authority, secrets=False))
return _load_prefill_messages(path, home) or None
diff --git a/hermes_cli/cli_config_load.py b/hermes_cli/cli_config_load.py
index 688d58249b9..c382cc3d002 100644
--- a/hermes_cli/cli_config_load.py
+++ b/hermes_cli/cli_config_load.py
@@ -51,9 +51,10 @@ def _load_prefill_messages(file_path: str, base_dir: Path | None = None) -> list
def _resolve_prefill_messages_file(config: dict[str, Any]) -> str:
"""Prefill file path: env, then top-level ``prefill_messages_file``, then legacy ``agent.*``."""
+ from agent.session_client_env import session_env
agent_cfg = config.get("agent", {})
return (
- os.getenv("HERMES_PREFILL_MESSAGES_FILE", "").strip()
+ session_env("HERMES_PREFILL_MESSAGES_FILE").strip()
or str(config.get("prefill_messages_file", "") or "").strip()
or (str(agent_cfg.get("prefill_messages_file", "") or "").strip() if isinstance(agent_cfg, dict) else "")
)
diff --git a/hermes_cli/gateway_chat.py b/hermes_cli/gateway_chat.py
index 1c8c724db6c..944adb2a3b5 100644
--- a/hermes_cli/gateway_chat.py
+++ b/hermes_cli/gateway_chat.py
@@ -47,6 +47,24 @@ def env_launch_flags() -> dict:
return {field: True for field, name in _ENV_LAUNCH_FLAGS if is_truthy_value(os.environ.get(name))}
+def shell_client_env() -> dict:
+ """This shell's allowlisted environment (``agent.session_client_env``) with the extra names of the
+ profile's effective config (managed layer included), as the gateway reads them. A bypass launch's
+ owner freezes code defaults, so it reads no profile."""
+ from agent.session_client_env import collect_client_env
+ if {'safe_mode', 'ignore_user_config'} & set(env_launch_flags()):
+ return collect_client_env()
+ from hermes_cli.config import get_config_path
+ from hermes_cli.config_effective import load_user_config_effective
+ return collect_client_env(config=load_user_config_effective(get_config_path()))
+
+
+def client_env_policy(parameters) -> dict:
+ """``client_env`` for a new session (main's process read these from its shell; the shared gateway
+ applies them to this session only), or nothing for a gateway that predates the field."""
+ return {"client_env": shell_client_env()} if "client_env" in parameters else {}
+
+
def bypass_launch(args) -> bool:
"""--safe-mode / --ignore-user-config (or their env opt-ins): the owner freezes code defaults,
the client reads no profile."""
@@ -190,6 +208,7 @@ async def run_gateway_chat(args, emitter=None):
if create_if_missing:
policy["title"] = title
policy.update(env_launch_flags())
+ policy.update(client_env_policy(parameters))
cwd = await asyncio.to_thread(_caller_cwd, args)
if "cwd" in parameters:
policy["cwd"] = cwd
diff --git a/hermes_cli/gateway_chat_commands.py b/hermes_cli/gateway_chat_commands.py
index 142c0fe3b74..75907a021e9 100644
--- a/hermes_cli/gateway_chat_commands.py
+++ b/hermes_cli/gateway_chat_commands.py
@@ -133,6 +133,8 @@ async def _new(view, rest):
# The frozen request never holds the launch key; the one this terminal supplied rides along.
if getattr(view, "launch_api_key", None) and "api_key" in accepted:
request["api_key"] = view.launch_api_key
+ from hermes_cli.gateway_chat import client_env_policy
+ request.update(client_env_policy(accepted)) # never in launch_request: this shell's, sent afresh
snapshot = await view.client.rpc("session.create", request_id=uuid.uuid4().hex, **request)
await view.adopt(snapshot)
print(t("cli.session.new_session"))
diff --git a/hermes_cli/gateway_runtime_start.py b/hermes_cli/gateway_runtime_start.py
index 620260fa101..96ed336b41e 100644
--- a/hermes_cli/gateway_runtime_start.py
+++ b/hermes_cli/gateway_runtime_start.py
@@ -12,7 +12,9 @@ from hermes_cli.gateway_runtime_service import RuntimeStartError, remaining
# One launch's policy and pins, never the shared daemon's: hook consent would become daemon-lifetime
# auto-approval for messaging/cron, and a Kanban worker's or terminal's pins would retarget every later
-# session's board, cwd and source. HERMES_INFERENCE_* fallbacks stay (the daemon's own defaults).
+# session's board, cwd and source. The behaviour values main's CLI read per process (ephemeral prompt,
+# prefill file, provider request, project plugins) ride each session's ``client_env`` instead
+# (agent.session_client_env); an operator-started gateway keeps its own environment.
DAEMON_STRIPPED_ENV = (
"HERMES_PROFILE", "HERMES_YOLO_MODE", "HERMES_IGNORE_RULES", "HERMES_SAFE_MODE",
"HERMES_IGNORE_USER_CONFIG", "HERMES_ACCEPT_HOOKS", "HERMES_SESSION_SOURCE", "TERMINAL_CWD",
@@ -22,6 +24,8 @@ DAEMON_STRIPPED_ENV = (
"HERMES_KANBAN_BOARD", "HERMES_TENANT", "HERMES_SESSION_SOURCE_EXPLICIT", "HERMES_TURN_AUTHOR",
# Human-presence/one-shot markers: inherited, every messaging/cron turn would read as attended or -q.
"HERMES_INTERACTIVE", "HERMES_GATEWAY_SESSION", "HERMES_SINGLE_QUERY_SESSION",
+ "HERMES_EPHEMERAL_SYSTEM_PROMPT", "HERMES_PREFILL_MESSAGES_FILE", "HERMES_INFERENCE_PROVIDER",
+ "HERMES_ENABLE_PROJECT_PLUGINS", "HERMES_TUI_CLIENT_ENV",
)
diff --git a/hermes_cli/gateway_session_store.py b/hermes_cli/gateway_session_store.py
index d8f05dc3764..90ffba134e2 100644
--- a/hermes_cli/gateway_session_store.py
+++ b/hermes_cli/gateway_session_store.py
@@ -65,6 +65,7 @@ class GatewaySessionStore:
self.snapshots: dict[str, dict] = {}
self.current: dict | None = None
self._reader = None
+ self._create_parameters = None
def __bool__(self):
return not self.connection.final
@@ -156,9 +157,19 @@ class GatewaySessionStore:
params["row_cwd"] = os.getcwd() if record_cwd and local and params["source"] in CLI_FAMILY_SOURCES else ""
if title:
params["title"] = title
+ params.update(self.client_env())
snapshot = self.call("session.create", request_id=uuid.uuid4().hex, **params)
return self._adopt(snapshot)
+ def client_env(self):
+ """This shell's ``client_env`` when the gateway takes it (one ``runtime.describe`` per store)."""
+ from hermes_cli.gateway_chat import client_env_policy
+ if self._create_parameters is None:
+ described = self.call("runtime.describe")
+ contract = described.get("session_create") if isinstance(described, dict) else None
+ self._create_parameters = list((contract or {}).get("parameters") or [])
+ return client_env_policy(self._create_parameters)
+
def branch(self, session_id, title=None):
"""``session.mutate branch``: the gateway forks the whole active transcript into a child it
attaches this viewer to; returns the child id (main's /branch then switches to it)."""
@@ -459,7 +470,9 @@ def create_titled_session(title):
params["source"] = "cli" # main's titled row is `cli` (hermes_cli.main._create_titled_session)
params["row_cwd"] = ""
try:
- snapshot = session_store().call("session.create", request_id=uuid.uuid4().hex, title=title, **params)
+ store = session_store()
+ params.update(store.client_env())
+ snapshot = store.call("session.create", request_id=uuid.uuid4().hex, title=title, **params)
except GatewayClientError as exc:
logger.warning("Failed to create titled session %r on the gateway: %s", title, exc)
return None
diff --git a/hermes_cli/main_tui_launch.py b/hermes_cli/main_tui_launch.py
index 1e26f3730ad..02f5ccbff26 100644
--- a/hermes_cli/main_tui_launch.py
+++ b/hermes_cli/main_tui_launch.py
@@ -490,6 +490,11 @@ def _launch_tui(
env.pop("HERMES_TUI_CWD", None)
_apply_tui_python_env(env)
+ # This shell's allowlisted environment, sent as each session's ``client_env`` (LC-8, T3): taken from
+ # the shell before the launcher's own edits (NODE_OPTIONS heap, TUI pins) so the session gets the
+ # PATH / venv / HERMES_* values the user exported.
+ from hermes_cli.gateway_chat import shell_client_env
+ env["HERMES_TUI_CLIENT_ENV"] = json.dumps(shell_client_env())
skills_value = ""
if skills:
diff --git a/hermes_cli/runtime_provider.py b/hermes_cli/runtime_provider.py
index 8593a3a4342..6ca7ec061c9 100644
--- a/hermes_cli/runtime_provider.py
+++ b/hermes_cli/runtime_provider.py
@@ -535,7 +535,10 @@ def resolve_requested_provider(requested: Optional[str] = None) -> str:
cfg_provider = _get_model_config().get("provider")
if isinstance(cfg_provider, str) and cfg_provider.strip():
return cfg_provider.strip().lower()
- return get_secret_str("HERMES_INFERENCE_PROVIDER", "").strip().lower() or "auto"
+ from agent.session_client_env import bound_client_env
+ client = bound_client_env() # a local session's turn: its client's export, never the daemon's
+ requested = client.get("HERMES_INFERENCE_PROVIDER", "") if client is not None else get_secret_str("HERMES_INFERENCE_PROVIDER", "")
+ return requested.strip().lower() or "auto"
# ── extracted collaborators (re-exported; see module docstring) ────────────────────────────
diff --git a/hermes_state_local.py b/hermes_state_local.py
index dbfc6b07126..f4757b3accc 100644
--- a/hermes_state_local.py
+++ b/hermes_state_local.py
@@ -28,7 +28,8 @@ def commit_local_session(db, *, epoch, receipt):
saved = json.loads(old[0])
same = all(saved[k] == receipt[k] for k in (
'profile_id', 'principal_id', 'request_id', 'session_id', 'route'))
- same = same and same_create_request(saved['policy']['request_json'], receipt['policy']['request_json'])
+ same = (same and same_create_request(saved['policy']['request_json'], receipt['policy']['request_json'])
+ and saved['policy'].get('client_env_json') == receipt['policy'].get('client_env_json'))
except (ValueError, TypeError, KeyError) as exc:
raise RuntimeStoreError('storage_unavailable') from exc
if not same:
diff --git a/tests/acp_adapter/test_policy_identity_compat.py b/tests/acp_adapter/test_policy_identity_compat.py
index 566b4fc8f08..ac2bb808fde 100644
--- a/tests/acp_adapter/test_policy_identity_compat.py
+++ b/tests/acp_adapter/test_policy_identity_compat.py
@@ -13,5 +13,6 @@ def test_policy_identity_preserves_pre_editor_credential_binding(tmp_path):
legacy.pop('config_secret_ref')
legacy.pop('editor_mcp_json')
legacy.pop('coding_posture')
+ legacy.pop('client_env_json')
expected = hashlib.sha256(json.dumps(legacy, sort_keys=True).encode()).hexdigest()
assert policy_identity(policy) == expected
diff --git a/tests/gateway/test_session_client_env.py b/tests/gateway/test_session_client_env.py
new file mode 100644
index 00000000000..3acb5135f4d
--- /dev/null
+++ b/tests/gateway/test_session_client_env.py
@@ -0,0 +1,242 @@
+"""LC-8: a shell-launched client's allowlisted ``HERMES_*`` behaviour values ride ``session.create``
+(``client_env``) and apply to that session only; an auto-started gateway stops inheriting them from
+whichever client started it."""
+import json
+import sqlite3
+import time
+from types import SimpleNamespace
+
+import pytest
+
+_CONFIG = 'platform_toolsets: {cli: []}\nmodel: {provider: custom, default: m, base_url: http://x.invalid/v1}\n'
+
+
+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')
+ return owner, AuthorityConnection(owner, object(), {'user_id': 'owner'})
+
+
+def _home(tmp_path, config=_CONFIG):
+ home = tmp_path / 'home'
+ home.mkdir()
+ (home / 'config.yaml').write_text(config)
+ return home
+
+
+def _create(owner, actor, home, request_id, **extra):
+ from gateway.session_local import create_local_session
+ from gateway.session_policy import restore_policy
+ from hermes_state_local import local_receipt
+ ref = create_local_session(owner, actor, {'request_id': request_id, 'source': 'cli', 'cwd': str(home),
+ 'toolsets': [], **extra})
+ return ref, restore_policy(local_receipt(owner.db, ref.session_id)['policy'])
+
+
+def _turn_prompt(owner, policy):
+ """The gateway ephemeral prompt an in-process turn of *policy* resolves (inside its policy scope)."""
+ from gateway.run_config_loaders import GatewayConfigLoadersMixin
+ from gateway.session_policy import policy_scope
+ with policy_scope(policy, authority=owner):
+ return GatewayConfigLoadersMixin._load_ephemeral_system_prompt()
+
+
+async def test_each_session_runs_its_own_clients_ephemeral_prompt(tmp_path, monkeypatch):
+ home = _home(tmp_path)
+ # The first client started the daemon, so its export is the daemon's environment.
+ monkeypatch.setenv('HERMES_EPHEMERAL_SYSTEM_PROMPT', 'FIRST')
+ owner, connection = await _owner(home, monkeypatch)
+ try:
+ _, first = _create(owner, connection.actor, home, 'a', client_env={'HERMES_EPHEMERAL_SYSTEM_PROMPT': 'FIRST'})
+ _, second = _create(owner, connection.actor, home, 'b', client_env={'HERMES_EPHEMERAL_SYSTEM_PROMPT': 'SECOND'})
+ _, bare = _create(owner, connection.actor, home, 'c', client_env={}) # a shell that exported nothing
+ assert _turn_prompt(owner, first) == 'FIRST'
+ assert _turn_prompt(owner, second) == 'SECOND'
+ assert _turn_prompt(owner, bare) == ''
+ # The managed worker's owner-side inputs read the same per-session value.
+ from gateway.run_config_loaders import GatewayConfigLoadersMixin
+ from gateway.session_worker_construct import _ephemeral_prompt
+ owner.runner._get_system_prompt_for_channel = (
+ lambda platform, chat_id: GatewayConfigLoadersMixin._load_ephemeral_system_prompt())
+ assert _ephemeral_prompt(owner, second, 'chat') == 'SECOND'
+ assert _ephemeral_prompt(owner, bare, 'chat') is None
+ # Messaging/cron (no local policy) and a session whose client sent nothing (Desktop, or one
+ # created before this change) keep the gateway's own environment.
+ assert GatewayConfigLoadersMixin._load_ephemeral_system_prompt() == 'FIRST'
+ _, desktop = _create(owner, connection.actor, home, 'd')
+ assert _turn_prompt(owner, desktop) == 'FIRST'
+ finally:
+ await connection.close()
+ owner.db.close()
+
+
+async def test_each_session_reads_its_own_clients_prefill_file(tmp_path, monkeypatch):
+ from gateway.session_worker_construct import session_prefill
+ home = _home(tmp_path)
+ (home / 'one.json').write_text(json.dumps([{'role': 'user', 'content': 'ONE'}]))
+ (home / 'two.json').write_text(json.dumps([{'role': 'user', 'content': 'TWO'}]))
+ monkeypatch.setenv('HERMES_PREFILL_MESSAGES_FILE', str(home / 'one.json'))
+ owner, connection = await _owner(home, monkeypatch)
+ try:
+ ref, policy = _create(owner, connection.actor, home, 'p2',
+ client_env={'HERMES_PREFILL_MESSAGES_FILE': str(home / 'two.json')})
+ assert session_prefill(owner, policy, ref.session_id) == [{'role': 'user', 'content': 'TWO'}]
+ ref, policy = _create(owner, connection.actor, home, 'p0', client_env={})
+ assert session_prefill(owner, policy, ref.session_id) is None
+ finally:
+ await connection.close()
+ owner.db.close()
+
+
+async def test_each_session_resolves_its_own_clients_provider_request(tmp_path, monkeypatch):
+ from gateway.session_policy import policy_scope
+ from hermes_cli.runtime_provider import resolve_requested_provider
+ home = _home(tmp_path, 'platform_toolsets: {cli: []}\nmodel: {default: m}\n')
+ monkeypatch.setenv('HERMES_INFERENCE_PROVIDER', 'nous')
+ owner, connection = await _owner(home, monkeypatch)
+ try:
+ _, mine = _create(owner, connection.actor, home, 'r1', client_env={'HERMES_INFERENCE_PROVIDER': 'openrouter'})
+ _, bare = _create(owner, connection.actor, home, 'r2', client_env={})
+ with policy_scope(mine, authority=owner):
+ assert resolve_requested_provider() == 'openrouter'
+ with policy_scope(bare, authority=owner):
+ assert resolve_requested_provider() == 'auto'
+ assert resolve_requested_provider() == 'nous' # the gateway's own (messaging/cron)
+ finally:
+ await connection.close()
+ owner.db.close()
+
+
+async def test_client_env_is_filtered_validated_and_never_echoed(tmp_path, monkeypatch):
+ from hermes_state_runtime import RuntimeStoreError
+ home = _home(tmp_path)
+ owner, connection = await _owner(home, monkeypatch)
+ try:
+ _, policy = _create(owner, connection.actor, home, 'f1', client_env={
+ 'HERMES_EPHEMERAL_SYSTEM_PROMPT': 'P', 'OPENAI_API_KEY': 'sk-leak', 'HERMES_YOLO_MODE': '1'})
+ assert policy.client_env() == {'HERMES_EPHEMERAL_SYSTEM_PROMPT': 'P'}
+ assert 'client_env' not in json.loads(policy.request_json) # launch_request stays value-free
+ for bad in ('PATH=/x', {'PATH': 1}, {1: 'x'}):
+ with pytest.raises(RuntimeStoreError) as exc:
+ _create(owner, connection.actor, home, f'bad-{bad!r}', client_env=bad)
+ assert exc.value.reason == 'invalid_params'
+ finally:
+ await connection.close()
+ owner.db.close()
+
+
+def _strip_new_policy_fields(db_path, session_id):
+ """Rewrite a receipt into the exact shape a gateway before this change committed."""
+ from hermes_state_local import POLICY_PREFIX
+ conn = sqlite3.connect(db_path)
+ try:
+ key = POLICY_PREFIX + session_id
+ receipt = json.loads(conn.execute('SELECT value FROM state_meta WHERE key=?', (key,)).fetchone()[0])
+ assert receipt['policy'].pop('client_env_json') is None
+ conn.execute('UPDATE state_meta SET value=? WHERE key=?', (json.dumps(receipt), key))
+ conn.commit()
+ finally:
+ conn.close()
+
+
+async def test_exact_retry_of_a_session_created_before_client_env(tmp_path, monkeypatch):
+ from gateway.session_local import create_local_session
+ from hermes_state_local import local_receipt
+ from hermes_state_runtime import RuntimeStoreError
+ home = _home(tmp_path)
+ owner, connection = await _owner(home, monkeypatch)
+ params = {'request_id': 'old', 'source': 'cli', 'cwd': str(home), 'toolsets': []}
+ try:
+ ref = create_local_session(owner, connection.actor, dict(params))
+ _strip_new_policy_fields(owner.db.db_path, ref.session_id)
+ saved = local_receipt(owner.db, ref.session_id)['policy']
+ assert create_local_session(owner, connection.actor, dict(params)) == ref
+ assert local_receipt(owner.db, ref.session_id)['policy'] == saved
+ # A retry is the same request: a client environment it never carried is a different one.
+ with pytest.raises(RuntimeStoreError):
+ create_local_session(owner, connection.actor, {**params, 'client_env': {}})
+ new = {**params, 'request_id': 'new', 'client_env': {'HERMES_EPHEMERAL_SYSTEM_PROMPT': 'A'}}
+ ref = create_local_session(owner, connection.actor, dict(new))
+ assert create_local_session(owner, connection.actor, dict(new)) == ref
+ with pytest.raises(RuntimeStoreError):
+ create_local_session(owner, connection.actor, {**new, 'client_env': {'HERMES_EPHEMERAL_SYSTEM_PROMPT': 'B'}})
+ finally:
+ await connection.close()
+ owner.db.close()
+
+
+async def test_exact_retry_is_judged_by_the_committed_map_not_the_current_allowlist(tmp_path, monkeypatch):
+ from gateway.session_local import create_local_session
+ from hermes_state_local import local_receipt
+ from hermes_state_runtime import RuntimeStoreError
+ home = _home(tmp_path, _CONFIG + 'terminal: {client_env_passthrough: [GEM_HOME]}\n')
+ owner, connection = await _owner(home, monkeypatch)
+ env = {'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))
+ 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
+ # change leave the exact retry resolving to its committed session, unchanged.
+ (home / 'config.yaml').write_text(_CONFIG + 'terminal: {client_env_passthrough: [BUNDLE_PATH]}\n')
+ assert create_local_session(owner, connection.actor, dict(params)) == ref
+ assert local_receipt(owner.db, ref.session_id)['policy'] == saved
+ # A committed value changed or missing is a different request.
+ for changed in ({**env, 'GEM_HOME': '/other'}, {'PATH': '/client/bin'}):
+ with pytest.raises(RuntimeStoreError):
+ create_local_session(owner, connection.actor, {**params, 'client_env': changed})
+ # A fresh create takes the current rules.
+ _, fresh = _create(owner, connection.actor, home, 'g2', client_env=env)
+ assert fresh.client_env() == {'BUNDLE_PATH': '/bundle', 'PATH': '/client/bin'}
+ finally:
+ await connection.close()
+ owner.db.close()
+
+
+async def test_runtime_describe_lists_client_env(tmp_path, monkeypatch):
+ home = _home(tmp_path)
+ owner, connection = await _owner(home, monkeypatch)
+ try:
+ described = await connection.describe(None, {})
+ assert 'client_env' in described['session_create']['parameters']
+ finally:
+ await connection.close()
+ owner.db.close()
+
+
+def test_auto_started_gateway_does_not_inherit_client_behaviour_env(tmp_path, monkeypatch):
+ from hermes_cli import gateway_runtime_start
+ home = tmp_path / 'home'
+ home.mkdir()
+ captured = {}
+
+ def popen(command, **kwargs):
+ captured.update(kwargs['env'])
+ return SimpleNamespace(pid=1)
+ monkeypatch.setattr(gateway_runtime_start.subprocess, 'Popen', popen)
+ for name in ('HERMES_EPHEMERAL_SYSTEM_PROMPT', 'HERMES_PREFILL_MESSAGES_FILE', 'HERMES_INFERENCE_PROVIDER',
+ 'HERMES_ENABLE_PROJECT_PLUGINS', 'HERMES_TUI_CLIENT_ENV'):
+ monkeypatch.setenv(name, 'from-the-first-client')
+ monkeypatch.setenv('PATH', '/client/bin:/usr/bin')
+ gateway_runtime_start.spawn_unmanaged_gateway(home, deadline=time.monotonic() + 30)
+ leaked = sorted(name for name, value in captured.items() if value == 'from-the-first-client')
+ assert leaked == []
+ assert captured['PATH'] # the daemon still needs a PATH of its own
diff --git a/tests/hermes_cli/test_gateway_client_env.py b/tests/hermes_cli/test_gateway_client_env.py
new file mode 100644
index 00000000000..4472485f85d
--- /dev/null
+++ b/tests/hermes_cli/test_gateway_client_env.py
@@ -0,0 +1,132 @@
+"""LC-8 / T3 client side: the classic CLI and the Ink TUI launcher send this shell's allowlisted
+environment as ``session.create``'s ``client_env``, and only to a gateway that lists the field."""
+import asyncio
+import json
+import sys
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+
+def _shell(monkeypatch):
+ monkeypatch.setenv('PATH', '/client/venv/bin:/usr/bin')
+ monkeypatch.setenv('VIRTUAL_ENV', '/client/venv')
+ monkeypatch.setenv('HERMES_EPHEMERAL_SYSTEM_PROMPT', 'mine')
+ monkeypatch.setenv('NODE_AUTH_TOKEN', 'npm-secret')
+ monkeypatch.setenv('OPENAI_API_KEY', 'sk-secret')
+
+
+def _expected(env):
+ assert env['PATH'] == '/client/venv/bin:/usr/bin'
+ assert env['VIRTUAL_ENV'] == '/client/venv'
+ assert env['HERMES_EPHEMERAL_SYSTEM_PROMPT'] == 'mine'
+ assert 'NODE_AUTH_TOKEN' not in env and 'OPENAI_API_KEY' not in env
+
+
+class _Connection:
+ def __init__(self, parameters):
+ self.parameters, self.calls, self.final = parameters, [], False
+
+ def call(self, method, **params):
+ self.calls.append((method, params))
+ if method == 'runtime.describe':
+ return {'session_create': {'sources': ['cli'], 'parameters': self.parameters}}
+ return {'stored_session_id': 'sid'}
+
+ def state(self, sid):
+ return SimpleNamespace(adopt_snapshot=lambda snapshot: None)
+
+
[email protected]('takes', [True, False])
+def test_classic_cli_create_sends_client_env_when_the_gateway_takes_it(monkeypatch, takes):
+ from hermes_cli.gateway_session_store import GatewaySessionStore
+ _shell(monkeypatch)
+ connection = _Connection(['cwd', 'source', 'row_cwd', 'client_env'] if takes else ['cwd', 'source', 'row_cwd'])
+ GatewaySessionStore(connection).create({})
+ created = [params for method, params in connection.calls if method == 'session.create']
+ assert len(created) == 1
+ if takes:
+ _expected(created[0]['client_env'])
+ else:
+ assert 'client_env' not in created[0]
+
+
+def test_classic_cli_new_sends_this_shells_client_env(monkeypatch):
+ from hermes_cli import gateway_chat_commands
+ _shell(monkeypatch)
+ sent = {}
+
+ async def rpc(method, **params):
+ if method == 'session.info':
+ return {'launch_request': {'source': 'cli'}, 'cwd': '/tmp'}
+ if method == 'runtime.describe':
+ return {'session_create': {'parameters': ['source', 'cwd', 'client_env']}}
+ sent.update(params)
+ return {'stored_session_id': 'new'}
+
+ async def adopt(snapshot):
+ return None
+ view = SimpleNamespace(client=SimpleNamespace(rpc=rpc), session_id='old', adopt=adopt, launch_api_key=None)
+ asyncio.run(gateway_chat_commands._new(view, ''))
+ _expected(sent['client_env'])
+
+
+def test_client_env_policy_reads_the_profiles_extra_names(monkeypatch, tmp_path):
+ from hermes_cli.gateway_chat import client_env_policy
+ _shell(monkeypatch)
+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))
+ (tmp_path / 'config.yaml').write_text('terminal: {client_env_passthrough: [MY_TOOLCHAIN_HOME]}\n')
+ monkeypatch.setenv('MY_TOOLCHAIN_HOME', '/opt/tc')
+ assert client_env_policy(['source']) == {}
+ env = client_env_policy(['client_env'])['client_env']
+ _expected(env)
+ assert env['MY_TOOLCHAIN_HOME'] == '/opt/tc'
+
+
+def test_client_env_policy_reads_the_effective_config_and_bypass_reads_none(monkeypatch, tmp_path):
+ """The gateway takes extra names from the effective config (managed layer included); a bypass launch's
+ owner freezes code defaults, so the client then reads no profile either."""
+ from hermes_cli.gateway_chat import client_env_policy
+ _shell(monkeypatch)
+ home, managed = tmp_path / 'home', tmp_path / 'managed'
+ home.mkdir()
+ managed.mkdir()
+ monkeypatch.setenv('HERMES_HOME', str(home))
+ monkeypatch.setenv('HERMES_MANAGED_DIR', str(managed))
+ (managed / 'config.yaml').write_text('terminal: {client_env_passthrough: [GEM_HOME]}\n')
+ monkeypatch.setenv('GEM_HOME', '/gems')
+ for name in ('HERMES_SAFE_MODE', 'HERMES_IGNORE_USER_CONFIG'):
+ monkeypatch.delenv(name, raising=False)
+ env = client_env_policy(['client_env'])['client_env']
+ _expected(env)
+ assert env['GEM_HOME'] == '/gems'
+ (home / 'config.yaml').write_text('terminal: {client_env_passthrough: [MY_TOOLCHAIN_HOME]}\n')
+ monkeypatch.setenv('MY_TOOLCHAIN_HOME', '/opt/tc')
+ monkeypatch.setenv('HERMES_IGNORE_USER_CONFIG', '1')
+ bypass = client_env_policy(['client_env'])['client_env']
+ _expected(bypass)
+ assert 'GEM_HOME' not in bypass and 'MY_TOOLCHAIN_HOME' not in bypass
+
+
+def test_tui_launcher_hands_the_shell_env_to_ink(monkeypatch):
+ from hermes_cli import main as main_mod, main_tui_launch
+ _shell(monkeypatch)
+ monkeypatch.setenv('HERMES_PYTHON', sys.executable)
+ monkeypatch.setattr(main_mod, '_has_any_provider_configured', lambda: True)
+ monkeypatch.setattr(main_mod, '_oneshot_cleanup_done', False)
+ captured = {}
+ monkeypatch.setattr(main_tui_launch, '_make_tui_argv', lambda tui_dir, tui_dev: (['node', 'dist/entry.js'], Path('.')))
+
+ def fake_call(argv, cwd=None, env=None):
+ captured.update(env)
+ return 1
+ monkeypatch.setattr(main_mod.subprocess, 'call', fake_call)
+ with pytest.raises(SystemExit):
+ main_mod._launch_tui()
+ _expected(json.loads(captured['HERMES_TUI_CLIENT_ENV']))
+
+
+def test_tui_bootstrap_keeps_the_client_env_out_of_a_daemon_it_starts():
+ text = (Path(__file__).resolve().parents[2] / 'ui-tui' / 'scripts' / 'gateway_bootstrap.py').read_text()
+ assert 'HERMES_TUI_CLIENT_ENV' in text
diff --git a/tests/hermes_cli/test_gateway_session_store.py b/tests/hermes_cli/test_gateway_session_store.py
index 415868cd949..f9c6d7b3661 100644
--- a/tests/hermes_cli/test_gateway_session_store.py
+++ b/tests/hermes_cli/test_gateway_session_store.py
@@ -60,7 +60,8 @@ def test_new_session_is_created_on_the_gateway_and_its_id_adopted(store, monkeyp
db, client = store
sid = db.open_session(cli(), {"model": "m1", "toolsets": ["file", "web"], "provider": None})
assert sid == "local-new"
- method, params = client.calls[0]
+ # The store asks the owner's create contract first (does it take ``client_env``?).
+ method, params = next(call for call in client.calls if call[0] != "runtime.describe")
assert method == "session.create"
assert params["model"] == "m1" and params["toolsets"] == ["file", "web"] and params["source"] == "cli"
assert "provider" not in params and params["cwd"]
diff --git a/tui_gateway/contracts/canonical_sessions.py b/tui_gateway/contracts/canonical_sessions.py
index 49e8b244f88..225ad99c473 100644
--- a/tui_gateway/contracts/canonical_sessions.py
+++ b/tui_gateway/contracts/canonical_sessions.py
@@ -46,6 +46,9 @@ class CanonicalCreateParams(ProfileParams):
run_budget: float | None = None
# The classic CLI's `-v`: the session agent's status lines are not quieted.
verbose: bool = False
+ # A shell-launched client's allowlisted environment (HERMES_* behaviour values, toolchain PATH/venv),
+ # applied to this session only; never echoed in ``launch_request``.
+ client_env: dict[str, str] | None = None
class CanonicalResumeParams(ProfileParams):
diff --git a/ui-tui/scripts/gateway_bootstrap.py b/ui-tui/scripts/gateway_bootstrap.py
index e8bf030dd8f..1bcc3e728e7 100644
--- a/ui-tui/scripts/gateway_bootstrap.py
+++ b/ui-tui/scripts/gateway_bootstrap.py
@@ -66,7 +66,8 @@ def bootstrap(start: bool, recover: bool = False) -> dict:
for key in ("HERMES_MODEL", "HERMES_INFERENCE_MODEL", "HERMES_TUI_PROVIDER",
"HERMES_INFERENCE_PROVIDER", "HERMES_TUI_TOOLSETS", "HERMES_TUI_SKILLS",
"HERMES_CWD", "TERMINAL_CWD", "HERMES_YOLO", "HERMES_ACCEPT_HOOKS",
- "HERMES_TUI_CHECKPOINTS", "HERMES_TUI_PASS_SESSION_ID", "HERMES_KANBAN_BOARD"):
+ "HERMES_TUI_CHECKPOINTS", "HERMES_TUI_PASS_SESSION_ID", "HERMES_KANBAN_BOARD",
+ "HERMES_TUI_CLIENT_ENV"):
os.environ.pop(key, None)
receipt = (ensure_gateway_runtime(home, timeout=30, idle_exit=True) if start
else discover_gateway_endpoint(home, timeout=5))
diff --git a/ui-tui/src/__tests__/canonicalGateway.test.ts b/ui-tui/src/__tests__/canonicalGateway.test.ts
index d68c8dd95d7..4d96332802f 100644
--- a/ui-tui/src/__tests__/canonicalGateway.test.ts
+++ b/ui-tui/src/__tests__/canonicalGateway.test.ts
@@ -52,3 +52,17 @@ it('carries `hermes --tui --ignore-rules` (HERMES_IGNORE_RULES) onto session.cre
expect(localCreationOptions({ HERMES_IGNORE_RULES: '0' } as NodeJS.ProcessEnv)).not.toHaveProperty('ignore_rules')
expect(localCreationOptions({} as NodeJS.ProcessEnv)).not.toHaveProperty('ignore_rules')
})
+
+it('sends the launcher\'s client environment (LC-8, T3) only to a gateway that takes it', () => {
+ const options = localCreationOptions({ HERMES_TUI_CLIENT_ENV: JSON.stringify({ PATH: '/client/bin' }) } as NodeJS.ProcessEnv)
+ expect(options.client_env).toEqual({ PATH: '/client/bin' })
+ const takes = { sources: ['tui'], parameters: ['request_id', 'source', 'client_env'] }
+ expect(canonicalRequest('session.create', { request_id: 'r', ...options }, takes).params.client_env).toEqual({ PATH: '/client/bin' })
+ // An older gateway has no such field: the launch goes ahead without it rather than failing.
+ const older = { sources: ['tui'], parameters: ['request_id', 'source'] }
+ expect(canonicalRequest('session.create', { request_id: 'r', ...options }, older).params).not.toHaveProperty('client_env')
+
+ for (const raw of ['not json', '[]', '{"PATH": 1}']) {
+ expect(localCreationOptions({ HERMES_TUI_CLIENT_ENV: raw } as NodeJS.ProcessEnv)).not.toHaveProperty('client_env')
+ }
+})
diff --git a/ui-tui/src/canonicalGateway.ts b/ui-tui/src/canonicalGateway.ts
index 271b67429bb..100eceb31ed 100644
--- a/ui-tui/src/canonicalGateway.ts
+++ b/ui-tui/src/canonicalGateway.ts
@@ -16,6 +16,10 @@ export function canonicalRequest(method: string, original: Record<string, unknow
params.request_id ??= randomUUID()
if (!contract?.sources.includes('tui')) { throw new Error(t('canonical.launch.noTuiPolicy')) }
+
+ // The shell's environment is context, not a launch option: a gateway predating it runs the session
+ // with its own environment, as before.
+ if (!contract.parameters.includes('client_env')) { delete params.client_env }
const unsupported = Object.keys(params).filter(key => !contract.parameters.includes(key))
if (unsupported.length) { throw new Error(t('canonical.launch.unsupportedOptions', unsupported.join(', '))) }
@@ -111,6 +115,12 @@ export function localCreationOptions(env = process.env): Record<string, unknown>
if (skills.length) { options.skills = skills }
+ // The launcher's shell environment (allowlisted by `hermes --tui`): this session's HERMES_* behaviour
+ // values and tool PATH/venv on the shared gateway, as main's own process had them.
+ const clientEnv = parseClientEnv(env.HERMES_TUI_CLIENT_ENV)
+
+ if (clientEnv) { options.client_env = clientEnv }
+
// The launcher exports `--max-turns 5` as the string "5": numbers ride as
// ints (0 / -1 = unlimited), and a word ("none", "unlimited") stays text
// for the policy to read — `Number` would turn it into NaN, sent as null.
@@ -138,6 +148,23 @@ export function localCreationOptions(env = process.env): Record<string, unknown>
return options
}
+function parseClientEnv(raw?: string): Record<string, string> | undefined {
+ if (!raw) { return undefined }
+
+ try {
+ const value: unknown = JSON.parse(raw)
+
+ if (value && typeof value === 'object' && !Array.isArray(value)
+ && Object.values(value).every(item => typeof item === 'string')) {
+ return value as Record<string, string>
+ }
+ } catch {
+ // An unreadable hand-off sends nothing: the session keeps the gateway's environment.
+ }
+
+ return undefined
+}
+
const TOOL_PROGRESS_MODES = new Set(['off', 'new', 'all', 'verbose'])
/** `hermes --tui -v` / `-Q` export HERMES_TUI_TOOL_PROGRESS (verbose / off). The owner carries it as the