Skip to content

The agent that grows with you

fix(gateway): do not let a launching profile own the host gateway

brooklyn!1ac24fa20983
diff --git a/gateway/run.py b/gateway/run.py
index e60de6e07d1..248e6438f50 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -1809,12 +1809,18 @@ async def _async_profile_runtime_scope(profile_home: "Path"):
def load_gateway_config_for_runner() -> "GatewayConfig":
"""Load gateway config for the process-level GatewayRunner. An UNSET ``multiplex_profiles`` is
settled first by ``resolve_multiplex_mode`` (the default is on; the boot guard keeps a fleet that
- still runs per-profile gateways standalone). Multiplexed: reload under the default profile's
- ``_profile_runtime_scope`` so platform tokens in its ``.env`` resolve via the secret scope;
- unscoped ``_getenv`` falls to ``os.environ``, which often lacks a token living only under
- ``profiles/<name>/.env``. Off -> identical to ``load_gateway_config()``.
+ still runs per-profile gateways standalone). Multiplexed: set multiplex-active, then reload
+ under the default root's ``_profile_runtime_scope`` — not ``get_hermes_home()``, which is the
+ named launcher when a profile-scoped process started the host. A scope miss must not fall
+ through to that process's ``os.environ``. Off -> identical to ``load_gateway_config()``.
See #64674.
+
+ The probe load above only decides whether this process is a multiplexer. The primary
+ config is the scoped reload: multiplex must already be active (a scope miss must not
+ fall through to the launching profile's ``os.environ``) and the home must be the
+ default root, not ``get_hermes_home()`` — a named launcher's home is not the owner
+ of the primary adapter map.
"""
from hermes_cli.gateway_multiplex_mode import log_multiplex_decision, resolve_multiplex_mode
cfg = load_gateway_config()
@@ -1822,7 +1828,13 @@ def load_gateway_config_for_runner() -> "GatewayConfig":
if not cfg.multiplex_profiles:
return cfg
try:
- home = get_hermes_home()
+ from agent.secret_scope import set_multiplex_active
+ set_multiplex_active(True)
+ except Exception:
+ logger.debug("could not set multiplex-active before primary config load", exc_info=True)
+ try:
+ from hermes_constants import get_default_hermes_root
+ home = get_default_hermes_root()
except Exception:
return cfg
try:
@@ -3611,8 +3623,14 @@ class GatewayRunner(
self._agent_cache: "OrderedDict[str, tuple]" = OrderedDict()
self._agent_cache_lock = threading.Lock()
# Launch-time identity of the profile that owns ``self.adapters``; ``_authorization_adapter``
- # compares against this rather than the per-turn ``_active_profile_name()``.
- self._primary_profile_name = self._kanban_notifier_profile = self._active_profile_name()
+ # compares against this rather than the per-turn ``_active_profile_name()``. A multiplex
+ # host's primary map is always the default profile, even when a named profile launched
+ # the process (that launcher is a secondary adapter owner).
+ launch = self._active_profile_name()
+ self._kanban_notifier_profile = launch
+ self._primary_profile_name = (
+ "default" if getattr(self.config, "multiplex_profiles", False) else launch
+ )
# Teams meeting pipeline runtime (bound later when msgraph_webhook adapter exists).
self._teams_pipeline_runtime = None
self._teams_pipeline_runtime_error: Optional[str] = None
diff --git a/gateway/run_adapters.py b/gateway/run_adapters.py
index 36033a374c0..af0ece0a1b1 100644
--- a/gateway/run_adapters.py
+++ b/gateway/run_adapters.py
@@ -879,7 +879,12 @@ class GatewayAdapterLifecycleMixin:
from hermes_cli.profiles import get_active_profile_name, profiles_to_serve, profile_is_parked
except Exception:
return 0
- active = get_active_profile_name() or "default" # launch profile, pre-identity (adapter boot)
+ if self._multiplex_on():
+ # Primary adapters belong to default. A named launcher is not skipped here —
+ # it still needs its own secondary adapter and credential ownership entry.
+ active = getattr(self, "_primary_profile_name", None) or "default"
+ else:
+ active = get_active_profile_name() or "default" # launch profile, pre-identity (adapter boot)
for name, home in profiles_to_serve(True, include_parked=True):
if name != "default" and profile_is_parked(home):
logger.info("profile '%s' is parked (gateway.parked); not served by this gateway", name)
@@ -988,8 +993,71 @@ class GatewayAdapterLifecycleMixin:
)
return profile_cfg
+ @staticmethod
+ def _credential_claim_origin(profile_name: str, profile_home, platform: Platform, token: str) -> Optional[str]:
+ """Where *token* was configured for *profile_name*: that profile's ``.env``, or ambient env.
+
+ ``None`` when the value is not in either place (yaml-only, or unknown). An env label
+ is only returned when the profile's own ``.env`` does not contain the value — a shell
+ export that merely echoes the file is the file.
+ """
+ from gateway.config import PLATFORM_TOKEN_ENV_NAMES
+ env_name = PLATFORM_TOKEN_ENV_NAMES.get(platform)
+ if not env_name or not isinstance(token, str) or not token.strip():
+ return None
+ token = token.strip()
+ in_dotenv = False
+ if profile_home:
+ try:
+ from agent.secret_scope import load_env_file
+ in_dotenv = (load_env_file(Path(profile_home) / ".env").get(env_name) or "").strip() == token
+ except Exception:
+ in_dotenv = False
+ if in_dotenv:
+ if profile_name and profile_name != "default":
+ return f"profiles/{profile_name}/.env"
+ return ".env"
+ if (os.environ.get(env_name) or "").strip() == token:
+ return f"env {env_name}"
+ return None
+
+ def _duplicate_credential_origins(
+ self, owner: str, profile_name: str, profile_home, platform: Platform, adapter: Any,
+ ) -> tuple:
+ """``(owner_origin, incoming_origin)`` for a same-credential refusal; either may be None."""
+ token = None
+ for obj, attr in (
+ (adapter, "token"), (adapter, "bot_token"),
+ (getattr(adapter, "config", None), "token"),
+ ):
+ val = getattr(obj, attr, None) if obj is not None else None
+ if isinstance(val, str) and val.strip():
+ token = val.strip()
+ break
+ if not token:
+ return None, None
+ incoming = self._credential_claim_origin(profile_name, profile_home, platform, token)
+ owner_home = None
+ if owner == "default":
+ try:
+ from hermes_constants import get_default_hermes_root
+ owner_home = get_default_hermes_root()
+ except Exception:
+ owner_home = None
+ else:
+ try:
+ from hermes_cli.profiles import get_profile_dir
+ owner_home = get_profile_dir(owner)
+ except Exception:
+ owner_home = None
+ owner_origin = (
+ self._credential_claim_origin(owner, owner_home, platform, token) if owner_home else None
+ )
+ return owner_origin, incoming
+
def _refuse_duplicate_claim(
- self, claim, claimed: Dict[tuple, str], profile_name: str, platform: Platform, kind: str
+ self, claim, claimed: Dict[tuple, str], profile_name: str, platform: Platform, kind: str,
+ *, owner_origin: Optional[str] = None, incoming_origin: Optional[str] = None,
) -> bool:
"""Log + park a secondary adapter whose credential/listener another profile owns (True when
refused). NOT disconnected: it never connected, and for a same-credential Photon adapter
@@ -998,13 +1066,19 @@ class GatewayAdapterLifecycleMixin:
if owner is None:
return False
pv = platform.value
- head = f"Profile '{owner}' and '{profile_name}' both configure {pv} "
+ env_derived = any(
+ isinstance(origin, str) and origin.startswith("env ")
+ for origin in (owner_origin, incoming_origin)
+ )
+ def _who(name: str, origin: Optional[str]) -> str:
+ return f"{name} ({origin})" if env_derived and origin else name
+ head = f"Profile '{_who(owner, owner_origin)}' and '{_who(profile_name, incoming_origin)}' both configure {pv} "
if kind == "credential":
message = head + f"with the same credential. Give each profile its own {pv} credential."
logger.error(
"Profile '%s' and '%s' both configure %s with the same credential — refusing to start the "
"duplicate (one credential cannot be consumed twice). Give each profile its own %s credential.",
- owner, profile_name, pv, pv,
+ _who(owner, owner_origin), _who(profile_name, incoming_origin), pv, pv,
)
else:
bind, port = claim[-2:]
@@ -1119,8 +1193,15 @@ class GatewayAdapterLifecycleMixin:
# Same-token / same-listener conflict detection — refuse a duplicate poll or bind.
credential_claim = self._adapter_credential_claim(platform, adapter)
listener_claim = self._adapter_listener_claim(platform, adapter)
+ owner_name = claimed.get(credential_claim) if credential_claim is not None else None
+ owner_origin, incoming_origin = (None, None)
+ if owner_name:
+ owner_origin, incoming_origin = self._duplicate_credential_origins(
+ owner_name, profile_name, profile_home, platform, adapter,
+ )
if self._refuse_duplicate_claim(
- credential_claim, claimed, profile_name, platform, "credential"
+ credential_claim, claimed, profile_name, platform, "credential",
+ owner_origin=owner_origin, incoming_origin=incoming_origin,
) or self._refuse_duplicate_claim(listener_claim, claimed, profile_name, platform, "listener"):
continue
self._configure_profile_adapter(adapter, profile_name, platform)
diff --git a/gateway/run_shutdown.py b/gateway/run_shutdown.py
index 55df73c66db..7d12cea0134 100644
--- a/gateway/run_shutdown.py
+++ b/gateway/run_shutdown.py
@@ -1380,10 +1380,36 @@ class GatewayShutdownMixin:
# Restart orchestration
@staticmethod
def _restart_watcher_env() -> dict:
- """Watcher env minus ``_HERMES_GATEWAY`` (else the CLI's self-restart guard refuses; gateway stays down)."""
+ """Watcher env minus ``_HERMES_GATEWAY`` (else the CLI's self-restart guard refuses; gateway stays down).
+
+ The host multiplexer is respawned with ``host_gateway_child_env`` (default-root
+ secrets via ``served_profile_child_env``, not ``os.environ.copy()``). A standalone
+ named-profile gateway keeps that profile's home — only a multiplexer, or a process
+ already on the default root, is the host.
+ """
from gateway.config_loader import drop_bridged_env
- from tools.environments.local import build_subprocess_env
- watcher_env = drop_bridged_env(build_subprocess_env(scrub_secrets=False, inherit_profile_home=True))
+ from hermes_constants import get_default_hermes_root, get_hermes_home
+ from tools.environments.local import host_gateway_child_env, served_profile_child_env
+
+ home = get_hermes_home()
+ try:
+ on_default = home.resolve() == get_default_hermes_root().resolve()
+ except Exception:
+ on_default = False
+ multiplex = False
+ if not on_default:
+ try:
+ from gateway.config import load_gateway_config
+ multiplex = bool(load_gateway_config().multiplex_profiles)
+ except Exception:
+ multiplex = False
+ if on_default or multiplex:
+ watcher_env = host_gateway_child_env()
+ else:
+ watcher_env = served_profile_child_env(
+ target_home=home, inherit_credentials=True,
+ )
+ watcher_env = drop_bridged_env(watcher_env)
watcher_env.pop("_HERMES_GATEWAY", None)
return watcher_env
diff --git a/hermes_cli/gateway.py b/hermes_cli/gateway.py
index 6410d392e07..0ac2d5615e6 100644
--- a/hermes_cli/gateway.py
+++ b/hermes_cli/gateway.py
@@ -970,10 +970,47 @@ def launch_detached_gateway_restart_by_cmdline(old_pid: int, run_argv: list[str]
def launch_detached_profile_gateway_restart(profile: str, old_pid: int) -> bool:
"""Relaunch a manually-run profile gateway after its current PID exits."""
- return old_pid > 0 and _spawn_gateway_restart_watcher(old_pid, _gateway_run_args_for_profile(profile))
+ return old_pid > 0 and _spawn_gateway_restart_watcher(
+ old_pid,
+ _gateway_run_args_for_profile(profile),
+ host=profile == "default",
+ )
+
+
+def _restart_argv_is_host_gateway(argv: list[str]) -> bool:
+ """True when *argv* relaunches the host multiplexer, not a named profile's own gateway.
+
+ ``--profile <name>`` (other than default) is that profile. No selector is the host
+ only when this process is already the default root — a worker ``gateway run`` has
+ no selector and must not be retargeted.
+ """
+ if not argv or "gateway" not in argv:
+ return False
+ for flag in ("--profile", "-p"):
+ if flag in argv:
+ idx = argv.index(flag)
+ name = argv[idx + 1] if idx + 1 < len(argv) else ""
+ return name == "default"
+ if any(part == "--profile=default" for part in argv):
+ return True
+ if any(part.startswith("--profile=") and not part.endswith("=default") for part in argv):
+ return False
+ try:
+ from hermes_constants import get_default_hermes_root, get_hermes_home
+ return get_hermes_home().resolve() == get_default_hermes_root().resolve()
+ except Exception:
+ return False
+
+
+def _host_gateway_watcher_env() -> dict[str, str]:
+ """Scrubbed default-profile env for a detached host-gateway respawn watcher."""
+ from tools.environments.local import host_gateway_child_env
+ env = host_gateway_child_env()
+ env.pop("_HERMES_GATEWAY", None)
+ return env
-def _spawn_gateway_restart_watcher(old_pid: int, run_argv: list[str]) -> bool:
+def _spawn_gateway_restart_watcher(old_pid: int, run_argv: list[str], *, host: bool | None = None) -> bool:
"""Spawn the detached watcher that respawns ``run_argv`` once ``old_pid`` exits. Watcher and respawn
both need platform-appropriate detach: POSIX setsid; on Windows ``start_new_session`` does NOT detach
(the watcher would die with the CLI console), so ``windows_detach_popen_kwargs()`` supplies flags."""
@@ -1077,9 +1114,15 @@ def _spawn_gateway_restart_watcher(old_pid: int, run_argv: list[str]) -> bool:
watcher_argv = [sys.executable, "-c", watcher, str(old_pid), *run_argv]
devnull = {"stdout": subprocess.DEVNULL, "stderr": subprocess.DEVNULL}
+ # Host respawn must not inherit a named launcher's dotenv. The watcher copies os.environ
+ # into the gateway child, so the scrub has to be the watcher's own environ.
+ watcher_env = _host_gateway_watcher_env() if (
+ _restart_argv_is_host_gateway(run_argv) if host is None else host
+ ) else None
+ popen_env = {"env": watcher_env} if watcher_env is not None else {}
# Same detach for the watcher itself, so closing the terminal doesn't kill it.
try:
- subprocess.Popen(watcher_argv, **devnull, **windows_detach_popen_kwargs())
+ subprocess.Popen(watcher_argv, **devnull, **popen_env, **windows_detach_popen_kwargs())
except OSError:
# Parent job object rejected CREATE_BREAKAWAY_FROM_JOB; retry without it (Windows only —
# ``start_new_session=True`` cannot raise OSError on POSIX).
@@ -1088,7 +1131,7 @@ def _spawn_gateway_restart_watcher(old_pid: int, run_argv: list[str]) -> bool:
else {"start_new_session": True}
)
try:
- subprocess.Popen(watcher_argv, **devnull, **fallback_kwargs)
+ subprocess.Popen(watcher_argv, **devnull, **popen_env, **fallback_kwargs)
except OSError:
return False
return True
diff --git a/hermes_cli/gateway_launchd.py b/hermes_cli/gateway_launchd.py
index ae24089f4f9..94c920bca32 100644
--- a/hermes_cli/gateway_launchd.py
+++ b/hermes_cli/gateway_launchd.py
@@ -276,13 +276,20 @@ def _spawn_detached_gateway() -> bool:
file that `run_gateway` writes, so stop/status/restart keep working.
"""
from hermes_cli._subprocess_compat import windows_detach_popen_kwargs
+ from hermes_constants import get_hermes_home
+ from tools.environments.local import served_profile_child_env
log_dir = _gw().get_hermes_home() / "logs"
log_dir.mkdir(parents=True, exist_ok=True)
+ child_env = served_profile_child_env(
+ target_home=get_hermes_home(), inherit_credentials=True,
+ )
+ child_env.pop("_HERMES_GATEWAY", None)
try:
with open(log_dir / "gateway.log", "ab") as out:
subprocess.Popen(
_timestamped_stderr_gateway_command(log_dir / "gateway.error.log"),
stdin=subprocess.DEVNULL, stdout=out, stderr=subprocess.DEVNULL,
+ env=child_env,
**windows_detach_popen_kwargs(),
)
except OSError:
diff --git a/hermes_cli/gateway_windows.py b/hermes_cli/gateway_windows.py
index f4cf3d5a082..83f607a3762 100644
--- a/hermes_cli/gateway_windows.py
+++ b/hermes_cli/gateway_windows.py
@@ -717,7 +717,11 @@ def _spawn_detached(script_path: Path | None = None, home: Path | None = None) -
"""
_assert_windows()
argv, working_dir, env_overlay = _build_gateway_argv(home)
- env = {**os.environ, **env_overlay}
+ from tools.environments.local import served_profile_child_env
+ # home=None is this process's own gateway, not a forced jump to the default root.
+ # served_profile_child_env overlays that home's secrets instead of os.environ.copy().
+ target = home if home is not None else _hermes_home()
+ env = {**served_profile_child_env(target_home=target, inherit_credentials=True), **env_overlay}
# Stray print()/native stderr goes to a sidecar log; real gateway logs still land in gateway.log
# via the logging FileHandler.
diff --git a/hermes_cli/update_restart_recovery.py b/hermes_cli/update_restart_recovery.py
index 5b4ec296654..6fd9c3d7d89 100644
--- a/hermes_cli/update_restart_recovery.py
+++ b/hermes_cli/update_restart_recovery.py
@@ -109,14 +109,24 @@ def _child_environment(profile: str | None = None) -> dict[str, str]:
this process's authorization gates (``DISCORD_ALLOWED_CHANNELS``, ``GATEWAY_ALLOW_ALL_USERS`` ...)
and enforce them as its own — its ``.env`` only overwrites the keys it defines (#113270). Gates are
dropped when *profile* is not the launch profile; a same-profile child keeps an operator export.
+
+ Restarting the host multiplexer from a named profile does not copy this process's environ: the
+ child is ``host_gateway_child_env`` (``served_profile_child_env`` for the default root) so the
+ launching profile's platform credentials never become the primary adapter's.
"""
- env = os.environ.copy()
+ launch = _launch_profile()
+ target = profile if profile is not None else launch
+ if target == "default" and launch != "default":
+ from tools.environments.local import host_gateway_child_env
+ env = host_gateway_child_env()
+ else:
+ env = os.environ.copy()
+ if profile is not None and profile != launch:
+ from tools.environments.local_env_policy import strip_profile_gate_env
+ strip_profile_gate_env(env)
for marker in _GATEWAY_MARKERS:
env.pop(marker, None)
env[_RECOVERY_ENV] = "1"
- if profile is not None and profile != _launch_profile():
- from tools.environments.local_env_policy import strip_profile_gate_env
- strip_profile_gate_env(env)
return env
diff --git a/hermes_cli/web_server_gateway.py b/hermes_cli/web_server_gateway.py
index 1e5c292ad96..48c6d2e905f 100644
--- a/hermes_cli/web_server_gateway.py
+++ b/hermes_cli/web_server_gateway.py
@@ -319,6 +319,24 @@ def _named_profile_from_action(subcommand: List[str]) -> Optional[str]:
return None
+def _is_host_gateway_spawn(subcommand: List[str]) -> bool:
+ """True when *subcommand* starts the host multiplexer, not a named profile's own gateway.
+
+ ``hermes gateway restart`` and ``hermes -p default gateway restart`` are the host.
+ ``hermes -p coder gateway stop`` is not.
+ """
+ profile = _named_profile_from_action(subcommand)
+ if profile not in (None, "default"):
+ return False
+ args = list(subcommand)
+ if profile is not None:
+ if args and args[0] in {"-p", "--profile"}:
+ args = args[2:]
+ elif args and str(args[0]).startswith("--profile="):
+ args = args[1:]
+ return bool(args) and args[0] == "gateway"
+
+
def _profile_action_environment(
subcommand: List[str], env_overrides: Optional[Dict[str, str]] = None,
) -> Dict[str, str]:
@@ -333,11 +351,16 @@ def _profile_action_environment(
Named-profile actions therefore start from Hermes' standard scrubbed subprocess env, then drop
the profile-managed keys plus every key declared by the dashboard/default profile dotenv files
and their hydrated secret sources, and pin ``HERMES_HOME`` to the target profile. The child's
- normal startup then loads that profile's own ``.env``. Actions without a profile selector keep
+ normal startup then loads that profile's own ``.env``. A host-gateway verb (bare ``gateway``
+ or ``-p default gateway``) starts from ``host_gateway_child_env`` so a named-profile dashboard
+ cannot donate its dotenv to the multiplexer. Other actions without a profile selector keep
the historical environment exactly.
"""
profile = _named_profile_from_action(subcommand)
- if profile is None:
+ if _is_host_gateway_spawn(subcommand):
+ from tools.environments.local import host_gateway_child_env
+ action_env = host_gateway_child_env()
+ elif profile is None:
action_env = dict(os.environ)
else:
from hermes_cli.env_loader import (
diff --git a/tests/gateway/test_host_gateway_profile_env.py b/tests/gateway/test_host_gateway_profile_env.py
new file mode 100644
index 00000000000..b1e250b6be3
--- /dev/null
+++ b/tests/gateway/test_host_gateway_profile_env.py
@@ -0,0 +1,174 @@
+"""A host gateway spawned from a profile-scoped process must not adopt that profile.
+
+Two disposable homes: the default root (the multiplexer) and a named profile whose
+``.env`` holds the only Telegram token. The process environment is that profile's
+— the shape a desktop / update spawn inherits. The host's primary adapter claim
+must stay the default profile's, the named launcher must start as a secondary,
+and a duplicate refusal must say which claim came from the environment.
+"""
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from gateway.config import GatewayConfig, Platform, PlatformConfig
+
+_WORKER_TOKEN = "worker-profile-token-456"
+
+
[email protected](autouse=True)
+def _reset_multiplex_flag():
+ from agent import secret_scope as ss
+
+ ss.set_multiplex_active(False)
+ yield
+ ss.set_multiplex_active(False)
+
+
+def _two_homes(tmp_path: Path) -> tuple[Path, Path]:
+ """Default root plus ``profiles/worker``, each a real Hermes home."""
+ default_home = tmp_path / "default"
+ worker_home = default_home / "profiles" / "worker"
+ worker_home.mkdir(parents=True)
+ (default_home / "config.yaml").write_text(
+ "gateway:\n multiplex_profiles: true\n", encoding="utf-8",
+ )
+ (default_home / ".env").write_text("", encoding="utf-8")
+ (worker_home / "config.yaml").write_text(
+ "gateway:\n multiplex_profiles: true\n", encoding="utf-8",
+ )
+ (worker_home / ".env").write_text(
+ f"TELEGRAM_BOT_TOKEN={_WORKER_TOKEN}\n", encoding="utf-8",
+ )
+ return default_home, worker_home
+
+
+def _inherit_worker_env(monkeypatch, worker_home: Path) -> None:
+ """Model a process spawned from the worker profile: its home and its dotenv."""
+ monkeypatch.setenv("HERMES_HOME", str(worker_home))
+ monkeypatch.setenv("TELEGRAM_BOT_TOKEN", _WORKER_TOKEN)
+
+
+class TestProfileEnvIsNotThePrimaryClaim:
+ def test_worker_env_does_not_become_the_host_primary_token(self, tmp_path, monkeypatch):
+ """Profile env inherited by the host process must not seed the primary adapter."""
+ from gateway import run as run_mod
+
+ default_home, worker_home = _two_homes(tmp_path)
+ _inherit_worker_env(monkeypatch, worker_home)
+
+ cfg = run_mod.load_gateway_config_for_runner()
+
+ assert cfg.multiplex_profiles is True
+ telegram = cfg.platforms.get(Platform.TELEGRAM)
+ token = "" if telegram is None else (telegram.token or "")
+ assert token != _WORKER_TOKEN, (
+ "host primary claimed the launching profile's TELEGRAM_BOT_TOKEN"
+ )
+ # The reload that produced the primary config ran under the default root,
+ # not the named launcher's home.
+ assert Path(default_home).resolve() != Path(worker_home).resolve()
+
+ @pytest.mark.asyncio
+ async def test_named_launcher_starts_as_secondary(self, tmp_path, monkeypatch):
+ from gateway.run import GatewayRunner
+
+ default_home, worker_home = _two_homes(tmp_path)
+ _inherit_worker_env(monkeypatch, worker_home)
+ runner = GatewayRunner.__new__(GatewayRunner)
+ runner.config = GatewayConfig(multiplex_profiles=True)
+ runner.adapters = {}
+ runner._profile_adapters = {}
+ runner._profile_configs = {}
+ runner._profile_failed_platforms = {}
+ runner._served_profile_signatures = {}
+ runner.session_store = None
+ runner._busy_text_mode = "queue"
+ runner.pairing_stores = {}
+ runner.pairing_store = object()
+ runner._record_served_profiles = lambda *_args: None
+ runner._restore_secondary_completion_ledgers = lambda *_args: None
+ started = []
+
+ monkeypatch.setattr(
+ "hermes_cli.profiles.profiles_to_serve",
+ lambda multiplex, **_kw: [("default", default_home), ("worker", worker_home)],
+ )
+ monkeypatch.setattr("hermes_cli.profiles.get_active_profile_name", lambda: "worker")
+
+ async def fake_start(profile_name, profile_home, claimed):
+ started.append(profile_name)
+ return 1
+
+ monkeypatch.setattr(runner, "_start_one_profile_adapters", fake_start)
+ monkeypatch.setattr(
+ "gateway.run_profile_reconcile.profile_serve_signature", lambda _home: "signature",
+ )
+
+ assert await runner._start_secondary_profile_adapters() == 1
+ assert started == ["worker"]
+
+
+class TestHostGatewaySpawnEnv:
+ def test_restart_watcher_does_not_inherit_profile_token(self, tmp_path, monkeypatch):
+ """The detached restart child is built with served_profile_child_env, not os.environ.copy()."""
+ from gateway.run_shutdown import GatewayShutdownMixin
+
+ default_home, worker_home = _two_homes(tmp_path)
+ _inherit_worker_env(monkeypatch, worker_home)
+
+ env = GatewayShutdownMixin._restart_watcher_env()
+
+ assert env.get("HERMES_HOME") == str(default_home)
+ assert env.get("TELEGRAM_BOT_TOKEN") != _WORKER_TOKEN
+
+
+class TestDuplicateRefusalNamesEnvClaim:
+ @pytest.mark.asyncio
+ async def test_refusal_says_which_claim_is_env_derived(self, tmp_path, monkeypatch):
+ """Default inherited the token from the process env; worker configured it in .env."""
+ from gateway.run import GatewayRunner
+
+ default_home, worker_home = _two_homes(tmp_path)
+ _inherit_worker_env(monkeypatch, worker_home)
+ runner = GatewayRunner.__new__(GatewayRunner)
+ runner.config = GatewayConfig(multiplex_profiles=True)
+ runner.adapters = {}
+ runner._profile_adapters = {}
+ runner._profile_failed_platforms = {}
+ writes = []
+
+ class _Adapter:
+ def __init__(self):
+ self.token = _WORKER_TOKEN
+ self.config = PlatformConfig(enabled=True, token=_WORKER_TOKEN)
+
+ adapter = _Adapter()
+ config = GatewayConfig(
+ multiplex_profiles=True,
+ platforms={Platform.TELEGRAM: PlatformConfig(enabled=True, token=_WORKER_TOKEN)},
+ )
+ monkeypatch.setattr("gateway.config.load_gateway_config", lambda: config)
+ monkeypatch.setattr(runner, "_create_adapter", lambda _p, _c: adapter)
+ monkeypatch.setattr(
+ runner, "_update_platform_runtime_status",
+ lambda platform, **kwargs: writes.append((platform, kwargs)),
+ )
+ monkeypatch.setattr(runner, "_subscribe_plugin_rewire", lambda *_a, **_k: None)
+ monkeypatch.setattr(runner, "_register_config_hooks", lambda *_a, **_k: None)
+ monkeypatch.setattr(runner, "_snapshot_profile_busy_modes", lambda *_a, **_k: None)
+ claim = runner._adapter_credential_claim(Platform.TELEGRAM, adapter)
+ assert claim is not None
+
+ connected = await runner._start_one_profile_adapters(
+ "worker", worker_home, {claim: "default"},
+ )
+
+ assert connected == 0
+ assert writes, "duplicate was not refused"
+ message = writes[0][1]["error_message"]
+ assert "env TELEGRAM_BOT_TOKEN" in message
+ assert "default" in message
+ assert "worker" in message
+ assert "profiles/worker/.env" in message
diff --git a/tools/environments/local.py b/tools/environments/local.py
index df94391845e..346d22da2ea 100644
--- a/tools/environments/local.py
+++ b/tools/environments/local.py
@@ -411,6 +411,21 @@ def served_profile_child_env(
return env
+def host_gateway_child_env(
+ base: "Mapping[str, str] | None" = None,
+) -> dict[str, str]:
+ """Child env for the host gateway: the default profile's secrets, never the launcher's.
+
+ ``served_profile_child_env`` — not ``os.environ.copy()``. A profile-scoped parent
+ (desktop, fleet restart, detached watcher) must not donate its dotenv to the
+ multiplexer that owns the primary adapter map.
+ """
+ from hermes_constants import get_default_hermes_root
+ return served_profile_child_env(
+ base=base, target_home=get_default_hermes_root(), inherit_credentials=True,
+ )
+
+
def _is_routed_home(target_home: "str | Path") -> bool:
"""True when ``target_home`` is not the process's own (launch) home.