Skip to content

The agent that grows with you

feat: hermes chat --safe-mode runs as a frozen policy in an isolated worker

Tekniumee6b11605014
diff --git a/gateway/run.py b/gateway/run.py
index 2d2e9e67702..cbb0d59de23 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -2007,7 +2007,12 @@ def _bridge_config_to_env(_cfg: dict) -> None:
def _load_bridge_config(config_path: Path) -> dict:
"""Raw config read for the presence-sensitive env bridge, with the managed overlay applied. Raw (not
defaults-merged) so only keys the user wrote are bridged, else all of DEFAULT_CONFIG would be
- exported; the overlay applies BEFORE bridging so pinned values win in env too."""
+ exported; the overlay applies BEFORE bridging so pinned values win in env too. A bypass worker
+ bridges its frozen explicit snapshot instead: the profile file is exactly what it must not read."""
+ from agent.safe_worker_policy import worker_config_snapshot
+ snapshot = worker_config_snapshot()
+ if snapshot is not None:
+ return snapshot
from hermes_cli.config import _expand_env_vars, read_user_config_raw
cfg = _expand_env_vars(read_user_config_raw(config_path))
if not isinstance(cfg, dict):
diff --git a/hermes_cli/_parser.py b/hermes_cli/_parser.py
index 35a48e2a3ca..9a6db0ac6ed 100644
--- a/hermes_cli/_parser.py
+++ b/hermes_cli/_parser.py
@@ -221,6 +221,12 @@ def _build_chat_parser(subparsers) -> argparse.ArgumentParser:
# too; runtime resolution (resolve_runtime_provider) validates, same as the top-level flag.
inherited(chat_parser, "--provider", default=SUPPRESS,
help="Inference provider (default: auto). Built-in or a user-defined name from `providers:` in config.yaml.")
+ # Explicit endpoint launches (custom provider, --safe-mode isolation) are frozen into the
+ # session policy by the gateway; the key lives only in the authority's memory, never on disk.
+ add("--base-url", dest="base_url", default=SUPPRESS, metavar="URL",
+ help="OpenAI-compatible endpoint for --provider custom (e.g. http://127.0.0.1:8000/v1).")
+ add("--api-key", dest="api_key", default=SUPPRESS, metavar="KEY",
+ help="API key for this launch only; not persisted.")
add("-v", "--verbose", action="store_true", default=SUPPRESS, help="Verbose output")
add("-Q", "--quiet", action="store_true",
help="Quiet mode for programmatic use: suppress banner, spinner, and tool previews. Only output the final response and session info.")
diff --git a/hermes_cli/gateway_chat.py b/hermes_cli/gateway_chat.py
index e7f84e9ad95..0a9d746f143 100644
--- a/hermes_cli/gateway_chat.py
+++ b/hermes_cli/gateway_chat.py
@@ -14,12 +14,18 @@ from hermes_cli.gateway_client import GatewayClientError, connect_gateway
# the authority. Reject them, rather than mutate process-wide gateway settings.
_UNSUPPORTED = (
"image", "skills", "worktree", "w", "checkpoints", "pass_session_id",
- "ignore_user_config", "safe_mode", "yolo", "accept_hooks",
+ "yolo", "accept_hooks",
"continue_last", "create_if_missing", "no_restore_cwd", "usage_file",
"run_budget", "verbose", "compact",
"list_tools", "list_toolsets",
)
-_POLICY = ("model", "provider", "reasoning", "toolsets", "max_turns", "base_url", "ignore_rules", "api_key")
+_POLICY = ("model", "provider", "reasoning", "toolsets", "max_turns", "base_url", "ignore_rules", "api_key",
+ "safe_mode", "ignore_user_config")
+
+
+def bypass_launch(args) -> bool:
+ """--safe-mode / --ignore-user-config: the owner freezes code defaults, the client reads no profile."""
+ return bool(getattr(args, "safe_mode", False) or getattr(args, "ignore_user_config", False))
def validate_options(args):
@@ -32,6 +38,8 @@ def validate_options(args):
if getattr(args, "resume", None) and (getattr(args, "in_dir", None) or getattr(args, "source", None) or
any(getattr(args, name, None) not in (None, False) for name in _POLICY)):
raise GatewayClientError("Resume retains gateway session policy; creation overrides are unsupported on resume.")
+ if bypass_launch(args) and not getattr(args, "model", None):
+ raise GatewayClientError("--safe-mode / --ignore-user-config read no profile default: pass --model explicitly.")
async def run_gateway_chat(args):
@@ -46,7 +54,7 @@ async def run_gateway_chat(args):
if source not in contract.get("sources", []):
raise GatewayClientError(f"Gateway does not support source {source!r}")
parameters = contract.get("parameters", [])
- policy = {key: getattr(args, key) for key in _POLICY if getattr(args, key, None) is not None}
+ policy = {key: getattr(args, key) for key in _POLICY if getattr(args, key, None) not in (None, False)}
if isinstance(policy.get("toolsets"), str):
policy["toolsets"] = [name.strip() for name in policy["toolsets"].split(",") if name.strip()]
cwd = str(Path(getattr(args, "in_dir", None) or os.getcwd()).expanduser().resolve())
diff --git a/hermes_cli/gateway_chat_startup.py b/hermes_cli/gateway_chat_startup.py
index 7df48c810b5..bfbb71d8635 100644
--- a/hermes_cli/gateway_chat_startup.py
+++ b/hermes_cli/gateway_chat_startup.py
@@ -5,6 +5,11 @@ import os
def ensure_launch_provider(args) -> bool:
+ from hermes_cli.gateway_chat import bypass_launch
+ if bypass_launch(args):
+ # The owner freezes code defaults for this launch; the profile is the thing under
+ # investigation, so the client must not probe or repair it either.
+ return True
from hermes_cli.main import _first_run_setup_guard, _has_any_provider_configured
# A resumed/remote session owns its provider policy. Explicit endpoint/key
@@ -24,10 +29,12 @@ def ensure_launch_provider(args) -> bool:
def launch_gateway_chat(args) -> int:
try:
from hermes_cli.main import _confirm_startup_expensive_model_override
- from hermes_cli.gateway_chat import launch_from_args
+ from hermes_cli.gateway_chat import launch_from_args, bypass_launch
- # Consent belongs before discovery/admission, even with --yolo.
- _confirm_startup_expensive_model_override(args)
+ # Consent belongs before discovery/admission, even with --yolo. A bypass launch has
+ # no profile-derived model/provider to guard and must not read config.yaml here.
+ if not bypass_launch(args):
+ _confirm_startup_expensive_model_override(args)
return launch_from_args(args)
except ImportError as exc:
from hermes_constants import emit_partial_update_hint
diff --git a/hermes_cli/main.py b/hermes_cli/main.py
index 9a8f30fa99d..1916f781043 100644
--- a/hermes_cli/main.py
+++ b/hermes_cli/main.py
@@ -1654,7 +1654,7 @@ _CHAT_PASSTHROUGH = (
def cmd_chat(args):
"""Run interactive chat CLI."""
- if not _resolve_use_tui(args):
+ if _bypass_chat_launch(args) or not _resolve_use_tui(args):
from hermes_cli.gateway_chat_startup import launch_gateway_chat
sys.exit(launch_gateway_chat(args))
_apply_safe_mode(args)
@@ -2689,6 +2689,8 @@ _AGENT_SUBCOMMANDS = {
def _is_tui_chat_launch(args) -> bool:
+ if _bypass_chat_launch(args):
+ return False
if getattr(args, "tui", False) or os.environ.get("HERMES_TUI") == "1":
return True
# The chat path decides TUI-vs-classic via _resolve_use_tui (--cli/--tui
@@ -2704,6 +2706,14 @@ def _is_tui_chat_launch(args) -> bool:
return _resolve_use_tui(args)
+def _bypass_chat_launch(args) -> bool:
+ """--safe-mode / --ignore-user-config chat: the gateway owner freezes code defaults and runs
+ the turn out of process, so the profile's display.interface must not pick a surface and the
+ client performs no discovery. Explicit --tui is refused later by the TUI's own option gate."""
+ return bool(getattr(args, "safe_mode", False) or getattr(args, "ignore_user_config", False)) \
+ and not getattr(args, "tui", False)
+
+
def _agent_subcommand_selected(args) -> bool:
"""True for ``cron run/tick``, ``gateway run``, ``mcp serve`` (see _AGENT_SUBCOMMANDS)."""
_sub_attr, _sub_set = _AGENT_SUBCOMMANDS.get(args.command, (None, None))
@@ -2730,6 +2740,11 @@ def _prepare_agent_startup(args) -> None:
# See #7994.
if getattr(args, "yolo", False):
os.environ["HERMES_YOLO_MODE"] = "1"
+ if args.command in {None, "chat"} and _bypass_chat_launch(args):
+ # Bypass launches are frozen by the gateway owner and executed out of process. This
+ # client is a transport: no env mutation (it would ride into an authority spawn),
+ # no plugin/MCP/hook discovery, and no profile read of the config under suspicion.
+ return
_apply_safe_mode(args)
_apply_user_config_bypass(args)
_guard_noninteractive_user_config(args)
diff --git a/tests/hermes_cli/test_gateway_chat.py b/tests/hermes_cli/test_gateway_chat.py
index 8fb8258b61e..7d55a8bdbde 100644
--- a/tests/hermes_cli/test_gateway_chat.py
+++ b/tests/hermes_cli/test_gateway_chat.py
@@ -8,12 +8,15 @@ def test_unsupported_launch_options_fail_before_connection(monkeypatch, capsys):
from hermes_cli import gateway_chat
calls = []
monkeypatch.setattr(gateway_chat, "connect_gateway", lambda: calls.append(True))
- for option in ("yolo", "safe_mode", "worktree", "continue_last", "usage_file"):
+ for option in ("yolo", "worktree", "continue_last", "usage_file"):
args = argparse.Namespace(**{option: True})
assert gateway_chat.launch_from_args(args) == 2
assert option.replace("_", "-") in capsys.readouterr().err
assert calls == []
assert gateway_chat.launch_from_args(argparse.Namespace(resume="stored", source="tui", query="x")) == 2
+ # Bypass launches read no profile default model, so one must be explicit.
+ assert gateway_chat.launch_from_args(argparse.Namespace(safe_mode=True, query="x")) == 1
+ assert "--model" in capsys.readouterr().err
assert calls == []
diff --git a/tests/hermes_cli/test_gateway_startup_validation.py b/tests/hermes_cli/test_gateway_startup_validation.py
index 58122924482..6f40f118285 100644
--- a/tests/hermes_cli/test_gateway_startup_validation.py
+++ b/tests/hermes_cli/test_gateway_startup_validation.py
@@ -9,5 +9,14 @@ def test_invalid_options_are_reported_before_reading_profile(monkeypatch, capsys
raise AssertionError("Unsupported launch read profile configuration")
monkeypatch.setattr("hermes_cli.main._has_any_provider_configured", unexpected)
- assert launch_gateway_chat(Namespace(safe_mode=True)) == 2
- assert "--safe-mode" in capsys.readouterr().err
+ assert launch_gateway_chat(Namespace(yolo=True)) == 2
+ assert "--yolo" in capsys.readouterr().err
+ # A bypass launch skips provider probing and the profile cost guard entirely.
+ monkeypatch.setattr("hermes_cli.main._confirm_startup_expensive_model_override", lambda args: unexpected())
+ from hermes_cli.gateway_client import GatewayClientError
+
+ def refused():
+ raise GatewayClientError("transport reached")
+ monkeypatch.setattr("hermes_cli.gateway_chat.connect_gateway", refused)
+ assert launch_gateway_chat(Namespace(safe_mode=True, model="explicit", provider="custom", query="x")) == 1
+ assert "transport reached" in capsys.readouterr().err
diff --git a/tests/hermes_cli/test_safe_mode.py b/tests/hermes_cli/test_safe_mode.py
index 07affbd43cf..67ffd785f34 100644
--- a/tests/hermes_cli/test_safe_mode.py
+++ b/tests/hermes_cli/test_safe_mode.py
@@ -1,80 +1,256 @@
-"""Tests for `hermes chat --safe-mode` isolation."""
-
-from __future__ import annotations
-
+"""`hermes chat --safe-mode` is an owner-frozen policy executed out of process, not client env.
+
+Contract recipe D-F: sentinels seeded in a disposable profile fire on an ordinary turn
+(positive control); the canonical safe launch through the real CLI gets a loopback reply from
+a managed worker that opened no plugin, profile YAML, rules or skill file and fired no sentinel;
+a malformed profile does not block it; config-only keeps plugin discovery.
+"""
+import asyncio
+from contextlib import closing
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+import json
import os
+from pathlib import Path
+import pty
+import re
+import select
+import sqlite3
+import subprocess
import sys
-import types
+import threading
+import time
import pytest
-
-_VARS = ("HERMES_SAFE_MODE", "HERMES_IGNORE_USER_CONFIG", "HERMES_IGNORE_RULES")
-
-
[email protected](autouse=True)
-def _clean_env(monkeypatch):
- for var in _VARS:
- monkeypatch.delenv(var, raising=False)
- yield
- for var in _VARS:
- os.environ.pop(var, None)
-
-
-def test_cmd_chat_safe_mode_sets_env_before_startup(monkeypatch):
- import hermes_cli.main as main_mod
- from hermes_cli._parser import build_top_level_parser
-
- parser, _subparsers, chat_parser = build_top_level_parser()
- chat_parser.set_defaults(func=main_mod.cmd_chat)
- args = parser.parse_args(["chat", "--safe-mode"])
- captured: dict[str, object] = {}
- fake_cli = types.ModuleType("cli")
-
- def fake_has_provider() -> bool:
- assert os.environ["HERMES_SAFE_MODE"] == "1"
- assert os.environ["HERMES_IGNORE_USER_CONFIG"] == "1"
- assert os.environ["HERMES_IGNORE_RULES"] == "1"
- return True
-
- def fake_main(**kwargs):
- captured.update(kwargs)
-
- monkeypatch.setattr(main_mod, "_has_any_provider_configured", fake_has_provider)
- monkeypatch.setattr(main_mod, "_pin_kanban_board_env", lambda: None)
- monkeypatch.setattr(main_mod, "_sync_bundled_skills_for_startup", lambda: None)
- monkeypatch.setattr(main_mod, "_termux_should_prefetch_update_check", lambda: False)
- setattr(fake_cli, "main", fake_main)
- monkeypatch.setitem(sys.modules, "cli", fake_cli)
-
- main_mod.cmd_chat(args)
-
- assert captured["ignore_user_config"] is True
- assert captured["ignore_rules"] is True
-
-
-
-
-def test_plugin_discovery_skipped(monkeypatch):
- monkeypatch.setenv("HERMES_SAFE_MODE", "1")
- from hermes_cli.plugins import PluginManager
-
- mgr = PluginManager()
- called = []
- monkeypatch.setattr(mgr, "_discover_and_load_inner", lambda: called.append(True))
-
- mgr.discover_and_load()
-
- assert called == []
- assert mgr._discovered is True
- assert mgr._plugins == {}
-
-
-
-
-
-
-
-
-
-
+from tests.gateway.fixtures.local_recovery_probe import daemon, rpc, websocket
+
+
+class Model(BaseHTTPRequestHandler):
+ def log_message(self, *args):
+ pass
+
+ def do_POST(self):
+ body = json.loads(self.rfile.read(int(self.headers['Content-Length'])))
+ if body.get('messages'):
+ self.server.requests.append({'auth': self.headers.get('Authorization'), 'path': self.path, 'body': body})
+ message = {'role': 'assistant', 'content': 'SAFE_REPLY_OK'}
+ choice = {'index': 0, 'message': message, 'finish_reason': 'stop'}
+ frame = {'id': 'local', 'model': body.get('model'), 'choices': [choice],
+ 'usage': {'prompt_tokens': 10, 'completion_tokens': 5, 'total_tokens': 15}}
+ kind = 'application/json'
+ if body.get('stream'):
+ choice['delta'] = choice.pop('message')
+ payload = ('data: ' + json.dumps(frame) + '\n\ndata: [DONE]\n\n').encode()
+ kind = 'text/event-stream'
+ else:
+ payload = json.dumps(frame).encode()
+ try:
+ self.send_response(200)
+ self.send_header('Content-Type', kind)
+ self.send_header('Content-Length', str(len(payload)))
+ self.end_headers()
+ self.wfile.write(payload)
+ except (BrokenPipeError, ConnectionResetError):
+ pass
+
+
+def _pty_cli(argv, cwd, env, timeout=90):
+ """Real PTY launch: stdin/stdout/stderr are a terminal, like a user's shell."""
+ master, slave = pty.openpty()
+ proc = subprocess.Popen(argv, cwd=cwd, env=env, stdin=slave, stdout=slave, stderr=slave, close_fds=True)
+ os.close(slave)
+ output, deadline = bytearray(), time.monotonic() + timeout
+ with closing(os.fdopen(master, 'rb', buffering=0)) as reader:
+ while time.monotonic() < deadline:
+ ready, _, _ = select.select([reader], [], [], .2)
+ if ready:
+ try:
+ chunk = reader.read(65536)
+ except OSError:
+ break
+ if not chunk:
+ break
+ output.extend(chunk)
+ elif proc.poll() is not None:
+ break
+ code = proc.wait(timeout=10)
+ return code, output.decode('utf-8', 'replace')
+
+
+def test_canonical_safe_launch_is_frozen_policy_executed_in_isolated_worker(tmp_path):
+ root = Path(__file__).resolve().parents[2]
+ home, user, work = tmp_path / 'state', tmp_path / 'user', tmp_path / 'work'
+ home.mkdir(mode=0o700)
+ user.mkdir()
+ work.mkdir()
+ events = home / 'events'
+ events.mkdir()
+ peer = ThreadingHTTPServer(('127.0.0.1', 0), Model)
+ peer.requests = []
+ thread = threading.Thread(target=peer.serve_forever, daemon=True)
+ thread.start()
+ url = f'http://127.0.0.1:{peer.server_port}/v1'
+ # Sentinels: general plugin (import + pre_llm_call hook), shell hook, SOUL, project rules, skill.
+ plugin = home / 'plugins' / 'sentinel'
+ plugin.mkdir(parents=True)
+ (plugin / 'plugin.yaml').write_text('name: sentinel\nversion: 1.0.0\nkind: standalone\n', encoding='utf-8')
+ (plugin / '__init__.py').write_text(
+ 'import os\nfrom pathlib import Path\n'
+ f'EVENTS = Path({str(events)!r})\n'
+ '(EVENTS / f"plugin-import-{os.getpid()}").touch()\n'
+ 'def register(ctx):\n'
+ ' ctx.register_hook("pre_llm_call", lambda **kw: (EVENTS / f"plugin-hook-{os.getpid()}").touch())\n',
+ encoding='utf-8')
+ shell_witness = tmp_path / 'shell_witness.py'
+ shell_witness.write_text(f'import os; from pathlib import Path\nPath({str(events)!r}, "shell-" + str(os.getppid())).touch()\n', encoding='utf-8')
+ (home / 'SOUL.md').write_text('SOUL_SENTINEL identity text', encoding='utf-8')
+ (work / 'AGENTS.md').write_text('RULES_SENTINEL project rules', encoding='utf-8')
+ skill = home / 'skills' / 'probe'
+ skill.mkdir(parents=True)
+ (skill / 'SKILL.md').write_text('---\nname: probe\ndescription: SKILL_SENTINEL probe skill\n---\nSKILL_SENTINEL body\n', encoding='utf-8')
+ config = {'gateway': {'multiplex_profiles': False},
+ 'model': {'provider': 'custom', 'default': 'owner-model', 'base_url': url},
+ 'auxiliary': {'title_generation': {'enabled': False}},
+ 'plugins': {'enabled': ['sentinel']}, 'hooks_auto_accept': True,
+ 'hooks': {'pre_llm_call': [{'command': f'{sys.executable} {shell_witness}'}]},
+ 'memory': {'memory_enabled': False, 'user_profile_enabled': False},
+ 'platform_toolsets': {'cli': ['terminal']}}
+ (home / 'config.yaml').write_text(json.dumps(config), encoding='utf-8')
+ audit = tmp_path / 'opens.jsonl'
+ site = tmp_path / 'audit-site'
+ site.mkdir()
+ (site / 'sitecustomize.py').write_text(
+ "import json, os, sys\n"
+ f"AUDIT = {str(audit)!r}\n"
+ "def record(kind, **fields):\n"
+ " with open(AUDIT, 'a', encoding='utf-8') as f:\n"
+ " f.write(json.dumps({'kind': kind, 'pid': os.getpid(), **fields}) + '\\n')\n"
+ "# sys.argv is not populated yet at site time; the kernel cmdline is.\n"
+ "with open('/proc/self/cmdline', 'rb') as f:\n"
+ " cmdline = f.read().split(b'\\0')\n"
+ "record('start', ppid=os.getppid(), argv=[a.decode('utf-8', 'replace') for a in cmdline if a])\n"
+ "import threading\n"
+ "_busy = threading.local()\n"
+ "def witness(event, args):\n"
+ " if event != 'open' or AUDIT in str(args[0]) or getattr(_busy, 'on', False):\n"
+ " return\n"
+ " _busy.on = True\n"
+ " try:\n"
+ " path = str(args[0])\n"
+ " fields = {}\n"
+ " if '/plugins/' in path or path.endswith(('config.yaml', '.env', 'SOUL.md', 'AGENTS.md', 'SKILL.md')):\n"
+ " frame, stack = sys._getframe(1), []\n"
+ " while frame is not None and len(stack) < 14:\n"
+ " stack.append(f'{frame.f_code.co_filename}:{frame.f_lineno}:{frame.f_code.co_name}')\n"
+ " frame = frame.f_back\n"
+ " fields['stack'] = stack\n"
+ " record('open', path=path, mode=str(args[1]), **fields)\n"
+ " finally:\n"
+ " _busy.on = False\n"
+ "sys.addaudithook(witness)\n", encoding='utf-8')
+ env = {k: os.environ[k] for k in ('PATH', 'LANG', 'TZ') if k in os.environ}
+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home), TERM='xterm',
+ PYTHONPATH=os.pathsep.join([str(site), str(root)]), OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=url)
+
+ def query(sql, args=()):
+ with closing(sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True)) as db:
+ return db.execute(sql, args).fetchall()
+
+ def records():
+ return [json.loads(line) for line in audit.read_text(encoding='utf-8').splitlines()]
+
+ def worker_pids(owner_pid):
+ return sorted({r['pid'] for r in records() if r['kind'] == 'start' and r['ppid'] == owner_pid
+ and r['argv'][-2:] == ['-m', 'agent.managed_worker']})
+
+ def system_text(request):
+ return json.dumps([m for m in request['body']['messages'] if m['role'] in {'system', 'developer'}])
+
+ async def ordinary_turn(desc):
+ async with websocket(home, desc) as ws:
+ created = await rpc(ws, 'session.create', request_id='ordinary', source='cli', cwd=str(work),
+ model='owner-model', provider='custom', base_url=url, api_key='loopback-only')
+ assert 'result' in created, created
+ sid = created['result']['session_id']
+ submitted = await rpc(ws, 'prompt.submit', session_id=sid, input_id='ordinary-input', text='ORDINARY_PROBE')
+ assert 'result' in submitted, submitted
+ async with asyncio.timeout(60):
+ while query('SELECT status FROM session_admissions WHERE request_id=?', ('ordinary-input',)) != [('terminal',)]:
+ await asyncio.sleep(.05)
+ return sid
+
+ def safe_cli(request_tag, *flags):
+ code, output = _pty_cli([sys.executable, '-m', 'hermes_cli.main', 'chat', *flags, '--provider', 'custom',
+ '--base-url', url, '--model', 'safe-fixture', '--api-key', 'fixture',
+ '-Q', '-q', 'SAFE_PROBE_' + request_tag], cwd=work, env=env)
+ assert code == 0, output
+ assert 'SAFE_REPLY_OK' in output, output
+ sid = re.search(r'Session: (\S+)', output).group(1)
+ return sid, output
+
+ try:
+ with daemon(root, home, env, barrier=False) as (owner, desc):
+ # Positive control: the ordinary in-process turn fires every sentinel in the owner.
+ asyncio.run(ordinary_turn(desc))
+ ordinary = [r for r in peer.requests if r['body']['model'] == 'owner-model']
+ assert len(ordinary) == 1, [r['body']['model'] for r in peer.requests]
+ assert 'SOUL_SENTINEL' in system_text(ordinary[0]) and 'RULES_SENTINEL' in system_text(ordinary[0])
+ skill_in_ordinary = 'SKILL_SENTINEL' in system_text(ordinary[0])
+ fired = sorted(p.name for p in events.iterdir())
+ assert f'plugin-import-{owner.pid}' in fired and f'plugin-hook-{owner.pid}' in fired, fired
+ assert f'shell-{owner.pid}' in fired, fired
+ owner_opens = [r['path'] for r in records() if r['kind'] == 'open' and r['pid'] == owner.pid]
+ assert any('/plugins/' in p for p in owner_opens) and any(p.endswith('config.yaml') for p in owner_opens)
+
+ # Canonical safe launch through the real CLI on a real PTY.
+ safe_sid, output = safe_cli('one', '--safe-mode')
+ assert query('SELECT status FROM session_admissions WHERE target_session_id=?', (safe_sid,)) == [('terminal',)]
+ assert query('SELECT status FROM worker_executions WHERE session_id=?', (safe_sid,)) == [('terminal',)]
+ policy = json.loads(query('SELECT value FROM state_meta WHERE key=?', ('gateway.local_policy.v1:' + safe_sid,))[0][0])['policy']
+ assert policy['safe_mode'] is True and policy['ignore_user_config'] is True
+ workers = worker_pids(owner.pid)
+ assert len(workers) == 1 and workers[0] != owner.pid, workers
+ worker = workers[0]
+ worker_records = [r for r in records() if r['kind'] == 'open' and r['pid'] == worker]
+ assert worker_records, 'audit hook not live in the worker'
+ leaked = [(r['path'], r.get('stack')) for r in worker_records
+ if '/plugins/' in r['path'] or r['path'].endswith(('config.yaml', '.env', 'SOUL.md', 'AGENTS.md', 'SKILL.md'))]
+ assert leaked == [], json.dumps(leaked, indent=1)
+ assert not [name for name in os.listdir(events) if name.endswith(f'-{worker}')], sorted(os.listdir(events))
+ def inferences(tag):
+ # Title generation is a code default and also targets the explicit endpoint; the
+ # probe turn itself must be inferred exactly once.
+ return [r for r in peer.requests if r['body']['model'] == 'safe-fixture'
+ and r['body']['messages'][-1].get('content') == 'SAFE_PROBE_' + tag
+ and not str(r['body']['messages'][0].get('content', '')).startswith('You name chat sessions')]
+ safe = inferences('one')
+ assert len(safe) == 1 and safe[0]['auth'] == 'Bearer fixture' and safe[0]['path'] == '/v1/chat/completions', \
+ [(r['path'], [str(m.get('content'))[:80] for m in r['body']['messages']]) for r in peer.requests]
+ assert not any(s in system_text(safe[0]) for s in ('SOUL_SENTINEL', 'RULES_SENTINEL', 'SKILL_SENTINEL'))
+ assert 'HERMES_SAFE_MODE' not in Path(f'/proc/{owner.pid}/environ').read_bytes().decode('utf-8', 'replace')
+
+ # Malformed profile YAML: bypass launch still works and neither repairs nor rewrites it.
+ (home / 'config.yaml').write_text('model: [unterminated\n', encoding='utf-8')
+ before = (home / 'config.yaml').read_bytes()
+ second_sid, _ = safe_cli('two', '--safe-mode')
+ assert second_sid != safe_sid
+ assert (home / 'config.yaml').read_bytes() == before
+ second = inferences('two')
+ assert len(second) == 1 and second[0]['body'].get('tools') == safe[0]['body'].get('tools')
+
+ # Config-only keeps plugin discovery (the gate is safe_mode), yet reads no profile YAML.
+ (home / 'config.yaml').write_text(json.dumps(config), encoding='utf-8')
+ config_sid, _ = safe_cli('three', '--ignore-user-config')
+ config_worker = [p for p in worker_pids(owner.pid) if p not in workers][-1]
+ config_opens = [r['path'] for r in records() if r['kind'] == 'open' and r['pid'] == config_worker]
+ assert any('/plugins/' in p for p in config_opens), 'config-only must still discover plugins'
+ assert not [p for p in config_opens if p.endswith(('config.yaml', '.env'))]
+ print(json.dumps({'owner_pid': owner.pid, 'safe_worker_pid': worker, 'config_only_worker_pid': config_worker,
+ 'safe_session': safe_sid, 'skill_in_ordinary_prompt': skill_in_ordinary,
+ 'sentinels_fired': fired, 'safe_worker_leaked_opens': leaked,
+ 'model_requests': [r['body']['model'] for r in peer.requests]}))
+ finally:
+ peer.shutdown()
+ peer.server_close()
+ thread.join(timeout=5)
diff --git a/website/docs/reference/cli-commands.md b/website/docs/reference/cli-commands.md
index 019a447f49f..da8923af66d 100644
--- a/website/docs/reference/cli-commands.md
+++ b/website/docs/reference/cli-commands.md
@@ -128,7 +128,8 @@ Common options:
| `--pass-session-id` | Pass the session ID into the system prompt. |
| `--ignore-user-config` | Ignore `~/.hermes/config.yaml` and use built-in defaults. Credentials in `.env` are still loaded. Useful for isolated CI runs, reproducible bug reports, and third-party integrations. |
| `--ignore-rules` | Skip auto-injection of `AGENTS.md`, `SOUL.md`, `.cursorrules`, persistent memory, and preloaded skills. Combine with `--ignore-user-config` for a fully isolated run. |
-| `--safe-mode` | Troubleshooting mode: disable ALL customizations — user config, rules/memory injection, plugins, shell hooks, and MCP servers (implies `--ignore-user-config` and `--ignore-rules`). Use to isolate whether a problem comes from your setup or from Hermes itself. |
+| `--safe-mode` | Troubleshooting mode: disable ALL customizations — user config, rules/memory injection, plugins, shell hooks, and MCP servers (implies `--ignore-user-config` and `--ignore-rules`). The gateway freezes code defaults plus your explicit options into the session and runs the turn in an isolated worker process that never reads the profile, so a broken `config.yaml` cannot block it. Requires an explicit `--model` (there is no profile default to inherit); pair with `--provider custom --base-url <url> --api-key <key>` for a fully explicit endpoint. |
+| `--base-url <url>` / `--api-key <key>` | Explicit OpenAI-compatible endpoint and launch-only key for `--provider custom`. The key is held in the running gateway's memory for this session and never written to disk. |
| `--source <tag>` | Session source tag for filtering (default: `cli`). Use `tool` for third-party integrations that should not appear in user session lists. |
| `--max-turns <N>` | Maximum tool-calling iterations per conversation turn (default: 500, or `agent.max_turns` in config). |
@@ -143,7 +144,8 @@ hermes chat --toolsets web,terminal,skills
hermes chat --quiet -q "Return only JSON"
hermes chat --worktree -q "Review this repo and open a PR"
hermes chat --ignore-user-config --ignore-rules -q "Repro without my personal setup"
-hermes chat --safe-mode -q "Is this bug mine or Hermes'?"
+hermes chat --safe-mode --model gpt-4.1 -q "Is this bug mine or Hermes'?"
+hermes chat --safe-mode --provider custom --base-url http://127.0.0.1:8000/v1 --model local -q "Isolate against a local server"
```
### `hermes -z <prompt>` — scripted one-shot
diff --git a/website/docs/reference/environment-variables.md b/website/docs/reference/environment-variables.md
index 0849306b17a..67505d6fe9b 100644
--- a/website/docs/reference/environment-variables.md
+++ b/website/docs/reference/environment-variables.md
@@ -810,7 +810,7 @@ Advanced per-platform knobs for throttling the outbound message batcher. Most us
| `HERMES_ACCEPT_HOOKS` | Auto-approve any unseen shell hooks declared in `config.yaml` without a TTY prompt. Equivalent to `--accept-hooks` or `hooks_auto_accept: true`. |
| `HERMES_IGNORE_USER_CONFIG` | Skip `~/.hermes/config.yaml` and use built-in defaults (credentials in `.env` still load). Equivalent to `--ignore-user-config`. |
| `HERMES_IGNORE_RULES` | Skip auto-injection of `AGENTS.md`, `SOUL.md`, `.cursorrules`, memory, and preloaded skills. Equivalent to `--ignore-rules`. |
-| `HERMES_SAFE_MODE` | Troubleshooting mode: disable ALL customizations — skips plugin discovery, MCP server loading, and shell-hook registration. Set automatically by `--safe-mode` (which also sets the two flags above). |
+| `HERMES_SAFE_MODE` | Legacy in-process troubleshooting switch: skips plugin discovery, MCP server loading, and shell-hook registration for that process. `hermes chat --safe-mode` no longer sets it — the gateway freezes the safe policy into the session and executes it in an isolated worker instead, so the running daemon's environment is never mutated. |
| `HERMES_TOOL_PROGRESS` | Unsupported since the config-v12 support floor — the variable is ignored. Use `display.tool_progress` in `config.yaml`. |
| `HERMES_TOOL_PROGRESS_MODE` | Deprecated compatibility variable for tool progress mode (still read by the gateway as a fallback). Prefer `display.tool_progress` in `config.yaml`. |
| `HERMES_HUMAN_DELAY_MODE` | Response pacing: `off`/`natural`/`custom` |