Skip to content

The agent that grows with you

refactor(child-env): one secret-suffix rule, one env-table walk, one bundled manifest read

kshitijk4poor1ede0b805b56
diff --git a/hermes_cli/config.py b/hermes_cli/config.py
index 5d64973aea6..56e0d88360b 100644
--- a/hermes_cli/config.py
+++ b/hermes_cli/config.py
@@ -3990,48 +3990,62 @@ def _inject_profile_env_vars() -> None:
_inject_profile_env_vars()
-def _platform_plugin_manifests(home: Optional[Path] = None, *, bundled: bool = True,
- user: bool = True, strict: bool = False):
- """Yield ``(dir_name, manifest_dict)`` for every platform plugin manifest: bundled
- ``plugins/platforms/*``, the user's ``<home>/plugins/platforms/*`` category dir, and flat
- user installs ``<home>/plugins/*`` that declare ``kind: platform`` (#46600). ``home``
- defaults to the bound Hermes home. ``strict`` raises when a manifest cannot be read
- instead of skipping it: the child-env scrub must not lose a declared secret to an I/O error.
- A manifest that does not parse declares nothing (its adapter cannot load either) and is skipped."""
- user_plugins = (home if home is not None else get_hermes_home()) / "plugins"
+def _platform_manifest_paths(home: Optional[Path] = None, source: str = "all"):
+ """Yield ``(dir_name, manifest_path, require_kind)`` for every platform plugin manifest file.
+ ``source`` is ``"bundled"`` (shipped ``plugins/platforms/*``), ``"user"`` (``<home>/plugins/
+ platforms/*`` plus flat ``<home>/plugins/*`` installs, which must declare ``kind: platform``,
+ #46600) or ``"all"``. ``home`` defaults to the bound Hermes home."""
roots = []
- if bundled:
+ if source in ("all", "bundled"):
roots.append((get_project_root() / "plugins" / "platforms", False))
- if user:
- roots += [(user_plugins / "platforms", False),
- (user_plugins, True)] # flat layout: only manifests that say they are platforms
+ if source in ("all", "user"):
+ user_plugins = (home if home is not None else get_hermes_home()) / "plugins"
+ roots += [(user_plugins / "platforms", False), (user_plugins, True)]
for root, require_kind in roots:
if not root.is_dir():
continue
for child in root.iterdir():
manifest_path = next(
(p for p in (child / "plugin.yaml", child / "plugin.yml") if child.is_dir() and p.exists()), None)
- if manifest_path is None:
- continue
- try:
- with open(manifest_path, "r", encoding="utf-8-sig") as f:
- manifest = fast_safe_load(f) or {}
- except OSError:
- if strict: # a file we cannot read may declare secrets; a malformed one declares none
- raise
- continue
- except Exception:
- continue
- if not isinstance(manifest, dict) or (require_kind and manifest.get("kind") != "platform"):
- continue
- yield child.name, manifest
+ if manifest_path is not None:
+ yield child.name, manifest_path, require_kind
+
+
+def platform_manifest_stamp(home: Optional[Path] = None, source: str = "user") -> tuple:
+ """``(path, mtime_ns)`` of every platform plugin manifest file: changes whenever one is added,
+ removed or edited in place, so a cache keyed on it never serves a stale declaration."""
+ return tuple((str(path), path.stat().st_mtime_ns) for _dir, path, _kind in _platform_manifest_paths(home, source))
+
+
+def _platform_plugin_manifests(home: Optional[Path] = None, source: str = "all", *, strict: bool = False):
+ """Yield ``(dir_name, manifest_dict)`` for every platform plugin manifest (see
+ :func:`_platform_manifest_paths`). ``strict`` raises when a manifest cannot be read instead of
+ skipping it: the child-env scrub must not lose a declared secret to an I/O error. A manifest
+ that does not parse declares nothing (its adapter cannot load either) and is skipped."""
+ for dir_name, manifest_path, require_kind in _platform_manifest_paths(home, source):
+ try:
+ with open(manifest_path, "r", encoding="utf-8-sig") as f:
+ manifest = fast_safe_load(f) or {}
+ except OSError:
+ if strict:
+ raise
+ continue
+ except Exception:
+ continue
+ if not isinstance(manifest, dict) or (require_kind and manifest.get("kind") != "platform"):
+ continue
+ yield dir_name, manifest
+
+
+# Env-name suffixes that make a platform variable a secret unless its declaration says otherwise.
+PLATFORM_SECRET_ENV_SUFFIXES = ("_TOKEN", "_SECRET", "_KEY", "_PASSWORD", "_JSON")
def _platform_manifest_env_entries(manifest: dict):
"""Yield ``(name, is_secret, meta)`` for a manifest's ``requires_env`` / ``optional_env``
entries (a bare name or a dict with ``name`` plus optional ``description``/``url``/
- ``password``/``prompt``/``category``). *TOKEN / *SECRET / *KEY / *PASSWORD / *JSON are
- password fields unless the entry says ``password: false``."""
+ ``password``/``prompt``/``category``). A name ending in PLATFORM_SECRET_ENV_SUFFIXES is a
+ password field unless the entry says ``password: false``."""
for entry in [*(manifest.get("requires_env") or []), *(manifest.get("optional_env") or [])]:
meta = {"name": entry} if isinstance(entry, str) else entry if isinstance(entry, dict) else {}
name = meta.get("name")
@@ -4039,50 +4053,64 @@ def _platform_manifest_env_entries(manifest: dict):
continue
is_secret = bool(meta.get("password") or meta.get("secret"))
if not is_secret and not meta.get("password") is False:
- is_secret = name.upper().endswith(("_TOKEN", "_SECRET", "_KEY", "_PASSWORD", "_JSON"))
+ is_secret = name.upper().endswith(PLATFORM_SECRET_ENV_SUFFIXES)
yield name, is_secret, meta
-# Names declared in core (OPTIONAL_ENV_VARS before any platform manifest is read). A manifest
-# never reclassifies one of these: the config form keeps the core entry, and the child-env scrub
-# keeps a plugin that lists OPENAI_API_KEY from turning a provider key into an adapter secret.
-_CORE_DECLARED_ENV_NAMES: frozenset[str] = frozenset()
+def _manifest_secret_envs(manifests) -> frozenset[str]:
+ """Upper-cased secret messaging env names the given manifests declare, minus core-declared
+ names: a manifest never reclassifies a core variable such as OPENAI_API_KEY."""
+ names = {name.upper() for _dir, manifest in manifests
+ for name, is_secret, meta in _platform_manifest_env_entries(manifest)
+ if is_secret and (meta.get("category") or "messaging") == "messaging"}
+ return frozenset(names - {n.upper() for n in CORE_DECLARED_ENV_NAMES})
-def platform_manifest_secret_envs(home: Optional[Path] = None, *, bundled: bool,
+def platform_manifest_secret_envs(home: Optional[Path] = None, source: str = "user", *,
strict: bool = False) -> frozenset[str]:
- """Upper-cased secret env names the platform plugin manifests declare, minus core-declared
- names. ``bundled=True`` reads only the shipped plugins (process-wide); ``bundled=False`` reads
- only ``home``'s user-installed platform plugins, which belong to that profile alone."""
- names: set[str] = set()
- for _dir, manifest in _platform_plugin_manifests(home, bundled=bundled, user=not bundled, strict=strict):
- names.update(name.upper() for name, is_secret, meta in _platform_manifest_env_entries(manifest)
- if is_secret and (meta.get("category") or "messaging") == "messaging")
- return frozenset(names - {n.upper() for n in _CORE_DECLARED_ENV_NAMES})
+ """Secret env names declared by one source's platform plugin manifests: ``"user"`` reads only
+ ``home``'s user-installed plugins, which belong to that profile alone; ``"bundled"`` returns
+ the set read once at import (re-read strictly if that read hit an I/O error)."""
+ if source == "bundled" and BUNDLED_PLATFORM_SECRET_ENVS is not None:
+ return BUNDLED_PLATFORM_SECRET_ENVS
+ return _manifest_secret_envs(_platform_plugin_manifests(home, source, strict=strict))
-def _inject_platform_plugin_env_vars() -> None:
+def _inject_platform_plugin_env_vars() -> "frozenset[str] | None":
"""Populate OPTIONAL_ENV_VARS from platform plugin manifests (bundled AND user-installed) so
Teams / IRC / Google Chat and third-party platforms are configurable in the ``hermes config`` /
Desktop Gateway form without the core knowing they exist. Failures are swallowed so a
- malformed plugin.yaml can't break CLI import.
+ malformed plugin.yaml can't break CLI import. Returns the bundled manifests' secret names, or
+ None when a bundled manifest could not be read (the policy then re-reads strictly).
"""
- global _CORE_DECLARED_ENV_NAMES
- _CORE_DECLARED_ENV_NAMES = frozenset(OPTIONAL_ENV_VARS)
+ bundled: "list | None" = []
try:
- for dir_name, manifest in _platform_plugin_manifests():
- label = manifest.get("label") or manifest.get("name") or dir_name
- for name, is_secret, meta in _platform_manifest_env_entries(manifest):
- if name in OPTIONAL_ENV_VARS:
- continue # hardcoded entry wins (back-compat)
- OPTIONAL_ENV_VARS[name] = {
- "description": meta.get("description") or f"{label} configuration",
- "prompt": meta.get("prompt") or name,
- "url": meta.get("url") or None,
- "password": is_secret,
- "category": meta.get("category") or "messaging"}
- except Exception:
- pass
-
-
-_inject_platform_plugin_env_vars()
+ bundled = list(_platform_plugin_manifests(source="bundled", strict=True))
+ except OSError:
+ bundled = None
+ manifests = list(bundled or [])
+ for source in ("bundled", "user") if bundled is None else ("user",):
+ try:
+ manifests += list(_platform_plugin_manifests(source=source))
+ except Exception:
+ pass
+ for dir_name, manifest in manifests:
+ label = manifest.get("label") or manifest.get("name") or dir_name
+ for name, is_secret, meta in _platform_manifest_env_entries(manifest):
+ if name in OPTIONAL_ENV_VARS:
+ continue # hardcoded entry wins (back-compat)
+ OPTIONAL_ENV_VARS[name] = {
+ "description": meta.get("description") or f"{label} configuration",
+ "prompt": meta.get("prompt") or name,
+ "url": meta.get("url") or None,
+ "password": is_secret,
+ "category": meta.get("category") or "messaging"}
+ return _manifest_secret_envs(bundled) if bundled is not None else None
+
+
+# Names declared in core, before any platform manifest is read. A manifest never reclassifies
+# one: the config form keeps the core entry, and the child-env scrub keeps a plugin that lists
+# OPENAI_API_KEY from turning a provider key into an adapter secret.
+CORE_DECLARED_ENV_NAMES: frozenset[str] = frozenset(OPTIONAL_ENV_VARS)
+BUNDLED_PLATFORM_SECRET_ENVS: "frozenset[str] | None" = None
+BUNDLED_PLATFORM_SECRET_ENVS = _inject_platform_plugin_env_vars()
diff --git a/hermes_cli/profile_channels.py b/hermes_cli/profile_channels.py
index e4fa15886e4..7eac42c82df 100644
--- a/hermes_cli/profile_channels.py
+++ b/hermes_cli/profile_channels.py
@@ -122,6 +122,20 @@ def _cred_row_envs(row) -> Set[str]:
return names
+def config_env_table_keys() -> Dict[str, str]:
+ """``{ENV_KEY: platform_id}`` for the names the gateway env-override table reads outright: the
+ enable-credential sets and every ``_Cred`` row. Registry-free, so it is cheap at import time;
+ raises if the table cannot be read (callers decide whether that is fatal)."""
+ from gateway import config_env
+ keys: Dict[str, str] = {}
+ for platform, names in config_env._ENV_ENABLE_CREDENTIALS.items():
+ keys.update(dict.fromkeys(names, platform.value))
+ for step in config_env._ENV_STEPS:
+ if isinstance(step, config_env._Cred):
+ keys.update(dict.fromkeys(_cred_row_envs(step), step.platform.value))
+ return keys
+
+
def declared_channel_env_keys(source_dir: Optional[Path] = None) -> Dict[str, str]:
"""``{ENV_KEY: platform_id}`` for every env name an adapter declares outright (registry entry
fields, the gateway env-override table) plus gateway-wide channel policy. Prefix matching covers
@@ -134,12 +148,9 @@ def declared_channel_env_keys(source_dir: Optional[Path] = None) -> Dict[str, st
keys[name] = entry.name
with contextlib.suppress(Exception):
from gateway import config_env
- for platform, names in config_env._ENV_ENABLE_CREDENTIALS.items():
- keys.update(dict.fromkeys(names, platform.value))
+ keys.update(config_env_table_keys())
for step in config_env._ENV_STEPS:
- if isinstance(step, config_env._Cred):
- keys.update(dict.fromkeys(_cred_row_envs(step), step.platform.value))
- elif isinstance(step, partial):
+ if isinstance(step, partial):
platform = step.keywords.get("platform")
for kw in ("env", "env_base"):
if step.keywords.get(kw) and platform is not None:
diff --git a/tests/tools/test_local_env_blocklist.py b/tests/tools/test_local_env_blocklist.py
index 4536023c209..ff3a6e9ad23 100644
--- a/tests/tools/test_local_env_blocklist.py
+++ b/tests/tools/test_local_env_blocklist.py
@@ -161,6 +161,16 @@ def test_user_platform_plugin_secrets_belong_to_their_own_profile(child_env, mon
finally:
reset_hermes_home_override(token)
assert seen == {"a": (False, False, False), "b": (True, True, True)}
+ # An in-place manifest edit (no directory mtime change) takes effect on the next spawn.
+ manifest = a / "plugins" / "platforms" / "chatx" / "plugin.yaml"
+ manifest.write_text(manifest.read_text(encoding="utf-8") + " - name: CHATX_WEBHOOK_KEY\n", encoding="utf-8")
+ os.utime(manifest, ns=(manifest.stat().st_atime_ns, manifest.stat().st_mtime_ns + 10**9))
+ monkeypatch.setenv("CHATX_WEBHOOK_KEY", "fake-value")
+ token = set_hermes_home_override(a)
+ try:
+ assert "CHATX_WEBHOOK_KEY" not in local.hermes_subprocess_env(inherit_credentials=True)
+ finally:
+ reset_hermes_home_override(token)
@pytest.mark.skipif(os.name == "nt" or os.geteuid() == 0, # windows-footgun: ok — short-circuits on nt
@@ -173,12 +183,12 @@ def test_unreadable_platform_manifest_fails_closed(tmp_path):
broken = tmp_path / "plugins" / "platforms" / "broken"
broken.mkdir()
(broken / "plugin.yaml").write_text("name: [unclosed\n", encoding="utf-8")
- assert platform_manifest_secret_envs(tmp_path, bundled=False, strict=True) == {"CHATX_SIGNING_SECRET"}
+ assert platform_manifest_secret_envs(tmp_path, strict=True) == {"CHATX_SIGNING_SECRET"}
manifest = tmp_path / "plugins" / "platforms" / "chatx" / "plugin.yaml"
manifest.chmod(0)
try:
with pytest.raises(PermissionError):
- platform_manifest_secret_envs(tmp_path, bundled=False, strict=True)
+ platform_manifest_secret_envs(tmp_path, strict=True)
finally:
manifest.chmod(0o644)
diff --git a/tools/environments/local.py b/tools/environments/local.py
index 93f681167f7..bdf81b32af0 100644
--- a/tools/environments/local.py
+++ b/tools/environments/local.py
@@ -21,7 +21,7 @@ from tools.environments.base import BaseEnvironment
from tools.environments.base_output import _pipe_stdin
from hermes_cli._subprocess_compat import windows_hide_flags
from tools.environments.local_env_policy import ( # noqa: F401 — _HERMES_PROVIDER_ENV_BLOCKLIST stays importable from here
- _ALWAYS_STRIP_KEYS, _HERMES_PROVIDER_ENV_BLOCKLIST, _HERMES_PROVIDER_ENV_FORCE_PREFIX,
+ _ALWAYS_STRIP_FOLDED, _ALWAYS_STRIP_KEYS, _HERMES_PROVIDER_ENV_BLOCKLIST, _HERMES_PROVIDER_ENV_FORCE_PREFIX,
_is_hermes_internal_secret, _is_provider_env_blocklisted, _is_terminal_first_party_env,
_home_adapter_secret_env, _matches_terminal_first_party_prefix, _plugin_terminal_env_strip_keys,
_registered_adapter_secret_env,
@@ -335,8 +335,7 @@ def _scrub_credentials(env: dict, *, inherit_credentials: bool) -> dict:
"""Tier 1 (always) and, unless ``inherit_credentials``, Tier 2 provider/tool credentials, in place."""
# Credential names fold to uppercase for membership: on Windows the env block
# itself is case-insensitive, so a lowercase-stored ``gh_token`` IS GH_TOKEN.
- strip_folded = frozenset(k.upper() for k in (
- _ALWAYS_STRIP_KEYS | _plugin_terminal_env_strip_keys() | _home_adapter_secret_env()))
+ strip_folded = _ALWAYS_STRIP_FOLDED | {k.upper() for k in _plugin_terminal_env_strip_keys()} | _home_adapter_secret_env()
registered = _registered_adapter_secret_env()
for key in list(env):
if (key.upper() in strip_folded
diff --git a/tools/environments/local_env_policy.py b/tools/environments/local_env_policy.py
index 3a09fd823c1..8b869ca4c89 100644
--- a/tools/environments/local_env_policy.py
+++ b/tools/environments/local_env_policy.py
@@ -90,36 +90,25 @@ def _build_provider_env_blocklist() -> frozenset:
return frozenset(blocked)
-_SECRET_ENV_SUFFIXES = ("_TOKEN", "_SECRET", "_PASSWORD", "_KEY")
-
-
def _build_adapter_secret_env() -> frozenset:
"""Secrets the messaging adapters declare, process-wide: core ``password`` messaging entries
of OPTIONAL_ENV_VARS, the bundled platform plugin manifests' secret entries, and the
secret-named keys the gateway env-override table reads (WEIXIN_TOKEN, FEISHU_ENCRYPT_KEY, ...).
Declared names only: a user's own ``SLACK_USER_TOKEN`` or ``LOCAL_LLM_API_KEY`` is not Hermes's.
A profile's user-installed platform plugins are per home: :func:`_home_adapter_secret_env`.
- The bundled manifests are read strictly: an unreadable one fails the import rather than
- dropping its secrets from the policy."""
+ Nothing here fails soft: an unreadable bundled manifest or env table fails the import rather
+ than dropping its secrets from the policy."""
+ from hermes_cli.config import (
+ CORE_DECLARED_ENV_NAMES, OPTIONAL_ENV_VARS, PLATFORM_SECRET_ENV_SUFFIXES, platform_manifest_secret_envs)
+ from hermes_cli.profile_channels import config_env_table_keys
# Read in code only, declared nowhere else: the Microsoft Graph app secret and webhook
# clientState, and the QQ bot's speech-to-text key.
names: set[str] = {"MSGRAPH_CLIENT_SECRET", "MSGRAPH_WEBHOOK_CLIENT_STATE", "QQ_STT_API_KEY"}
- from hermes_cli.config import (
- _CORE_DECLARED_ENV_NAMES, OPTIONAL_ENV_VARS, platform_manifest_secret_envs)
names.update(name.upper() for name, meta in OPTIONAL_ENV_VARS.items()
- if name in _CORE_DECLARED_ENV_NAMES
+ if name in CORE_DECLARED_ENV_NAMES
and meta.get("category") == "messaging" and meta.get("password"))
- names |= platform_manifest_secret_envs(bundled=True, strict=True)
- try:
- from gateway import config_env
- from hermes_cli.profile_channels import _cred_row_envs
- declared = {n for ns in config_env._ENV_ENABLE_CREDENTIALS.values() for n in ns}
- for step in config_env._ENV_STEPS:
- if isinstance(step, config_env._Cred):
- declared |= _cred_row_envs(step)
- names.update(n.upper() for n in declared if n.upper().endswith(_SECRET_ENV_SUFFIXES))
- except ImportError:
- pass
+ names |= platform_manifest_secret_envs(source="bundled", strict=True)
+ names.update(n.upper() for n in config_env_table_keys() if n.upper().endswith(PLATFORM_SECRET_ENV_SUFFIXES))
return frozenset(names)
@@ -129,22 +118,22 @@ _PROVIDER_ENV_BLOCKLIST = _build_provider_env_blocklist()
_ADAPTER_SECRET_ENV = _build_adapter_secret_env()
_HERMES_PROVIDER_ENV_BLOCKLIST = _PROVIDER_ENV_BLOCKLIST | _ADAPTER_SECRET_ENV
-_HOME_ADAPTER_SECRET_CACHE: dict = {}
+_HOME_ADAPTER_SECRET_CACHE: dict[str, tuple] = {}
def _home_adapter_secret_env() -> frozenset:
"""Secrets declared by the bound profile's own user-installed platform plugins. Per home, not
process-wide: under multiplex profile A's plugin must neither strip a same-named value from
- profile B's children nor be missing from A's. Cached per home until its plugin dirs change;
- an unreadable manifest raises instead of silently dropping the declaration."""
- from hermes_cli.config import platform_manifest_secret_envs
+ profile B's children nor be missing from A's. Cached per home, keyed on every manifest file's
+ mtime (an in-place edit invalidates it); an unreadable manifest raises instead of silently
+ dropping the declaration."""
+ from hermes_cli.config import platform_manifest_secret_envs, platform_manifest_stamp
from hermes_constants import get_hermes_home
home = get_hermes_home()
- plugins = home / "plugins"
- stamp = tuple(d.stat().st_mtime_ns if d.is_dir() else None for d in (plugins, plugins / "platforms"))
+ stamp = platform_manifest_stamp(home)
cached = _HOME_ADAPTER_SECRET_CACHE.get(str(home))
if cached is None or cached[0] != stamp:
- cached = (stamp, platform_manifest_secret_envs(home, bundled=False, strict=True) - _ADAPTER_SECRET_ENV)
+ cached = (stamp, platform_manifest_secret_envs(home, strict=True) - _ADAPTER_SECRET_ENV)
_HOME_ADAPTER_SECRET_CACHE[str(home)] = cached
return cached[1]
@@ -156,8 +145,9 @@ def _registered_adapter_secret_env() -> frozenset:
an unchecked setup list, so a plugin naming OPENAI_API_KEY must not strip it from credentialed
children. No blanket fallback: a registry error surfaces instead of an empty (fail-open) set."""
from gateway.platform_registry import platform_registry
+ from hermes_cli.config import PLATFORM_SECRET_ENV_SUFFIXES
registered = {n.upper() for n in platform_registry.required_env_names()
- if n.upper().endswith(_SECRET_ENV_SUFFIXES)}
+ if n.upper().endswith(PLATFORM_SECRET_ENV_SUFFIXES)}
return frozenset(registered) | _home_adapter_secret_env()
@@ -382,3 +372,4 @@ _ALWAYS_STRIP_KEYS: frozenset[str] = frozenset({
# Remote-compute / infrastructure secrets
"MODAL_TOKEN_ID", "MODAL_TOKEN_SECRET", "DAYTONA_API_KEY",
}) | _ADAPTER_SECRET_ENV # every declared adapter secret is Tier 1, like the bot tokens above
+_ALWAYS_STRIP_FOLDED: frozenset[str] = frozenset(k.upper() for k in _ALWAYS_STRIP_KEYS)