Skip to content

The agent that grows with you

refactor(gateway): fingerprint candidate table, listener-claim guard collapse, import-blank trim

Teknium6a2fe1ffdb9a
diff --git a/gateway/run_adapters.py b/gateway/run_adapters.py
index 6dee535343b..c7a44477367 100644
--- a/gateway/run_adapters.py
+++ b/gateway/run_adapters.py
@@ -900,7 +900,6 @@ class GatewayAdapterLifecycleMixin:
with _profile_runtime_scope(profile_home, hydrate_secrets=False):
profile_runtime_cfg = _load_gateway_runtime_config()
from hermes_cli.plugins import discover_plugins
-
discover_plugins()
# Register this profile's shell hooks / outbound webhooks: start() registers before any
@@ -996,7 +995,6 @@ class GatewayAdapterLifecycleMixin:
) -> int:
"""Create+connect one profile's adapters under its runtime scope."""
from gateway.run import _platform_has_bot_credential, _profile_runtime_scope
-
profile_cfg = await self._load_secondary_profile_config(profile_name, profile_home)
multiplex = getattr(self.config, "multiplex_profiles", False)
profile_map = self._profile_adapters.setdefault(profile_name, {})
@@ -1140,7 +1138,6 @@ class GatewayAdapterLifecycleMixin:
from hermes_cli.profiles import get_profile_dir
from hermes_cli.env_loader import hydrate_profile_secret_sources
from gateway.config import load_gateway_config
-
profile_home = get_profile_dir(profile_name)
# Hydrate external secret sources off-loop so they cannot starve heartbeats.
await asyncio.to_thread(hydrate_profile_secret_sources, profile_home)
@@ -1417,12 +1414,8 @@ class GatewayAdapterLifecycleMixin:
"""Authorize and publish one normalized adapter event to plugin hooks."""
try:
from hermes_cli.lifecycle import has_hook, invoke_hook
-
- if not has_hook("gateway_platform_event"):
- return
- if not self._is_user_authorized_for_source(source):
- return
- invoke_hook("gateway_platform_event", **event)
+ if has_hook("gateway_platform_event") and self._is_user_authorized_for_source(source):
+ invoke_hook("gateway_platform_event", **event)
except Exception:
# Observer failures must never break the adapter's update loop.
logger.debug("gateway_platform_event hook dispatch failed", exc_info=True)
@@ -1465,22 +1458,17 @@ class GatewayAdapterLifecycleMixin:
"""Return the exclusive credential resource claimed by an adapter."""
from gateway.run import GatewayRunner
fingerprint = GatewayRunner._adapter_credential_fingerprint(adapter)
- if fingerprint is None:
- return None
- return (platform, fingerprint)
+ return None if fingerprint is None else (platform, fingerprint)
@staticmethod
def _adapter_listener_claim(platform: Platform, adapter: Any) -> Optional[tuple]:
"""Exclusive listener claim (Photon sidecar bind+port): distinct credentials still cannot
share a port, so the later adapter is rejected before connect() disturbs the first."""
- if getattr(platform, "value", None) != "photon":
- return None
bind = getattr(adapter, "_sidecar_bind", None)
- port = getattr(adapter, "_sidecar_port", None)
- if not isinstance(bind, str) or not bind.strip():
+ if getattr(platform, "value", None) != "photon" or not isinstance(bind, str) or not bind.strip():
return None
try:
- port = int(port)
+ port = int(getattr(adapter, "_sidecar_port", None))
except (TypeError, ValueError):
return None
return ("listener", "photon", bind.strip().lower(), port)
@@ -1489,30 +1477,22 @@ class GatewayAdapterLifecycleMixin:
def _adapter_credential_fingerprint(adapter: Any) -> Optional[str]:
"""Salted, log-safe hash of an adapter's credential; None when none is discoverable
(conflict detection is then skipped)."""
- token = None
- for attr in (
- "token", "bot_token", "_token", "api_token", "_bot_token",
- "_project_secret", # Photon/Spectrum: project credentials, not a bot token
- "_app_id", # Feishu/Lark app_id — stable, log-safe, already the _app_lock_identity
- "_client_id", "_bot_id", # Teams / WeCom app-style id pairs
- ):
- val = getattr(adapter, attr, None)
+ # Many adapters (e.g. Discord) keep the token on `config`; without that fallback the
+ # same-token check is silently skipped and every profile polls the same bot.
+ candidates = [
+ (adapter, attr) for attr in (
+ "token", "bot_token", "_token", "api_token", "_bot_token",
+ "_project_secret", # Photon/Spectrum: project credentials, not a bot token
+ "_app_id", # Feishu/Lark app_id — stable, log-safe, already the _app_lock_identity
+ "_client_id", "_bot_id", # Teams / WeCom app-style id pairs
+ )
+ ] + [(getattr(adapter, "config", None), attr) for attr in ("token", "bot_token")]
+ for obj, attr in candidates:
+ val = getattr(obj, attr, None)
if isinstance(val, str) and val.strip():
- token = val.strip()
- break
- # Many adapters (e.g. Discord) keep the token on `config`; without this the same-token check
- # is silently skipped and every profile polls the same bot — a race over which one answers.
- if not token:
- cfg = getattr(adapter, "config", None)
- for attr in ("token", "bot_token"):
- val = getattr(cfg, attr, None)
- if isinstance(val, str) and val.strip():
- token = val.strip()
- break
- if not token:
- return None
- import hashlib
- return hashlib.sha256(("hermes-mux:" + token).encode("utf-8")).hexdigest()[:16]
+ import hashlib
+ return hashlib.sha256(("hermes-mux:" + val.strip()).encode("utf-8")).hexdigest()[:16]
+ return None
def _create_adapter(self, platform: Platform, config: Any) -> Optional[BasePlatformAdapter]:
"""Create an adapter bound to this runner (every lifecycle path goes through here so
diff --git a/gateway/run_busy.py b/gateway/run_busy.py
index 65d24f7aa09..191c35f543f 100644
--- a/gateway/run_busy.py
+++ b/gateway/run_busy.py
@@ -149,7 +149,6 @@ class GatewayBusySessionMixin:
"""Return the configured active chat session cap, if enabled."""
try:
from hermes_cli.active_sessions import resolve_max_concurrent_sessions
-
return resolve_max_concurrent_sessions(getattr(self, "config", None))
except Exception:
return None
@@ -163,7 +162,6 @@ class GatewayBusySessionMixin:
if active_count < max_sessions:
return None
from hermes_cli.active_sessions import active_session_limit_message
-
return active_session_limit_message(active_count, max_sessions)
def _claim_active_session_slot(
@@ -177,7 +175,6 @@ class GatewayBusySessionMixin:
return None, limit_message
try:
from hermes_cli.active_sessions import try_acquire_active_session
-
platform = source.platform.value if source and source.platform else "gateway"
return try_acquire_active_session(
session_id=session_key,
@@ -772,7 +769,6 @@ class GatewayBusySessionMixin:
"""`/pause [reason]` engages the global emergency stop; `/pause off` lifts it (the estop gate
lets slash commands through while paused so messaging-only operators are never locked out)."""
from agent import estop
-
args = (event.get_command_args() or "").strip()
if args.lower() in {"off", "resume", "stop", "disengage"}:
if estop.disengage():
@@ -796,7 +792,6 @@ class GatewayBusySessionMixin:
async def _busy_egress_command(self, event: MessageEvent, quick_key: str, source):
from hermes_cli.proxy_cli import format_status_text
-
return format_status_text()
async def _busy_stop_command(self, event: MessageEvent, quick_key: str, source):
@@ -904,7 +899,6 @@ class GatewayBusySessionMixin:
"""Denial message if ``source`` cannot run ``canonical_cmd``, else None (both dispatch paths
use it so an in-flight agent can't bypass admin gating; no ``allow_admin_from`` → None)."""
from gateway.slash_access import policy_for_source as _policy_for_source
-
if not canonical_cmd:
return None
policy = _policy_for_source(self.config, source)
@@ -1005,7 +999,6 @@ class GatewayBusySessionMixin:
from gateway.run import _command_origin_for_source
try:
from hermes_cli.suggestions_cmd import handle_suggestions_command
-
return handle_suggestions_command(
(event.get_command_args() or "").strip(),
origin=_command_origin_for_source(event.source), surface="gateway",
@@ -1019,7 +1012,6 @@ class GatewayBusySessionMixin:
from gateway.run import _command_origin_for_source
try:
from hermes_cli.blueprint_cmd import handle_blueprint_command
-
return handle_blueprint_command(
(event.get_command_args() or "").strip(),
origin=_command_origin_for_source(event.source), surface="gateway",
@@ -1027,7 +1019,6 @@ class GatewayBusySessionMixin:
except Exception as e:
logger.debug("blueprint command failed: %s", e)
from hermes_cli.blueprint_cmd import BlueprintCommandResult
-
return BlueprintCommandResult(f"Cron blueprint command failed: {e}")
async def _maybe_confirm_destructive_slash(
@@ -1122,7 +1113,6 @@ class GatewayBusySessionMixin:
"cancel" and its return is sent as a message. Returns None if buttons rendered, else the
text-fallback message (which IS the ack)."""
from tools import slash_confirm as _slash_confirm_mod
-
source = event.source
session_key = self._session_key_for_source(source)
# object.__new__ test runners lack the counter; fall back to a local one.