Skip to content

The agent that grows with you

refactor(gateway): contextlib.suppress for swallow-only try blocks, field-driven SessionResetPolicy.from_dict

Teknium838220617afd
diff --git a/gateway/authz_mixin.py b/gateway/authz_mixin.py
index f46fd32bf3e..763e49ce1f7 100644
--- a/gateway/authz_mixin.py
+++ b/gateway/authz_mixin.py
@@ -7,6 +7,7 @@ that logs imports its ``logger`` lazily so records keep the ``"gateway.run"`` na
from __future__ import annotations
+import contextlib
import os
from typing import Optional
@@ -52,15 +53,13 @@ def _platform_gate_env(name: str, default: str = "") -> str:
"""
if not name:
return default
- try:
+ with contextlib.suppress(Exception):
from agent.secret_scope import current_secret_scope, is_multiplex_active
scope = current_secret_scope()
if scope is not None and is_multiplex_active():
val = scope.get(name)
return default if val is None else str(val).strip()
- except Exception:
- pass
return (os.getenv(name) or default).strip()
@@ -75,12 +74,11 @@ def _registry_entry(platform):
"""Platform-registry entry for a (plugin) platform, or None."""
if platform is None:
return None
- try:
+ with contextlib.suppress(Exception):
from gateway.platform_registry import platform_registry
return platform_registry.get(platform.value)
- except Exception:
- return None
+ return None
def _coerce_allow_set(raw) -> set[str]:
@@ -198,12 +196,8 @@ class GatewayAuthorizationMixin:
# Identity captured at construction, not the per-turn HERMES_HOME-derived name.
primary_profile = getattr(self, "_primary_profile_name", None)
if not primary_profile:
- active_profile_fn = getattr(self, "_active_profile_name", None)
- if callable(active_profile_fn):
- try:
- primary_profile = active_profile_fn()
- except Exception:
- primary_profile = None
+ with contextlib.suppress(Exception):
+ primary_profile = self._active_profile_name()
if profile_name == primary_profile:
return self._primary_adapters().get(platform)
# Fail closed: a secondary profile whose adapter failed to connect must NOT
@@ -442,12 +436,10 @@ class GatewayAuthorizationMixin:
return True
# config.yaml fallback (``extra.group_allowed_chats``): Telegram observe-
# unmentioned mode strips user_id, so the env-only check above misses it.
- try:
+ with contextlib.suppress(Exception):
adapter_group_allowed = self._adapter_extra_for_source(source).get("group_allowed_chats")
if adapter_group_allowed and _allows(_coerce_allow_set(adapter_group_allowed), source.chat_id):
return True
- except Exception:
- pass
# Bots admitted by {PLATFORM}_ALLOW_BOTS bypass the human allowlist. Also before
# the no-user-id guard: Slack Workflow Builder posts arrive with user=None.
@@ -463,11 +455,9 @@ class GatewayAuthorizationMixin:
platform_allow_all_var = _ALLOW_ALL_ENV.get(source.platform, "")
if source.platform not in _ALLOWED_USERS_ENV:
entry = _registry_entry(source.platform)
- try:
+ with contextlib.suppress(Exception):
platform_allow_env = getattr(entry, "allowed_users_env", "") or platform_allow_env
platform_allow_all_var = getattr(entry, "allow_all_env", "") or platform_allow_all_var
- except Exception:
- pass
if platform_allow_all_var and _env_truthy(platform_allow_all_var):
return True
@@ -542,16 +532,13 @@ class GatewayAuthorizationMixin:
# Guarded on ``platform_allowlist`` so group/global-only configs never consult
# adapter memory; type-checked so mock adapters cannot auto-truthy in.
if platform_allowlist:
- try:
+ adapter = resolved_ids = None
+ with contextlib.suppress(Exception):
adapter = self._adapter_for_source(source)
- except Exception:
- adapter = None
resolver = getattr(adapter, "resolved_allowlist_user_ids", None)
if callable(resolver):
- try:
+ with contextlib.suppress(Exception):
resolved_ids = resolver()
- except Exception:
- resolved_ids = None
if isinstance(resolved_ids, (set, frozenset, list, tuple)):
allowed_ids.update(
str(entry).strip() for entry in resolved_ids if isinstance(entry, (str, int)) and str(entry).strip()
diff --git a/gateway/channel_directory.py b/gateway/channel_directory.py
index 77beea20ad8..8d2fdd46e7e 100644
--- a/gateway/channel_directory.py
+++ b/gateway/channel_directory.py
@@ -172,12 +172,10 @@ async def build_channel_directory(adapters: Dict[Any, Any]) -> Dict[str, Any]:
for plat in Platform:
await _discover(plat.value)
# Plugin platforms are dynamic enum members missing from Platform.__members__.
- try:
+ with contextlib.suppress(Exception):
from gateway.platform_registry import platform_registry
for entry in platform_registry.plugin_entries():
await _discover(entry.name)
- except Exception:
- pass
_apply_channel_aliases(platforms)
@@ -217,11 +215,10 @@ def _build_discord(adapter) -> List[Dict[str, str]]:
def _slack_api_error_code(error: Exception) -> Optional[str]:
"""Slack Web API error code from SlackApiError-like exceptions."""
- try:
- value = getattr(error, "response").get("error")
- except Exception:
- return None
- return str(value) if value else None
+ with contextlib.suppress(Exception):
+ value = error.response.get("error")
+ return str(value) if value else None
+ return None
def _normalize_adapter_channels(raw_channels: Any) -> List[Dict[str, Any]]:
diff --git a/gateway/config.py b/gateway/config.py
index 70793496691..04eac75dc29 100644
--- a/gateway/config.py
+++ b/gateway/config.py
@@ -2,11 +2,12 @@
policies and delivery preferences, loaded from config.yaml / gateway.json / env.
"""
+import contextlib
import logging
import math
import os
from pathlib import Path
-from dataclasses import asdict, dataclass, field, is_dataclass
+from dataclasses import asdict, dataclass, field, fields, is_dataclass
from typing import Dict, List, Optional, Any, Callable
from enum import Enum
@@ -57,10 +58,7 @@ def _normalize_multiplex_profile_allowlist(value: Any) -> Optional[List[str]]:
normalized: List[str] = []
for entry in value:
if not isinstance(entry, str):
- logger.warning(
- "Skipping invalid gateway.multiplex_profile_allowlist entry %r (expected a profile name)",
- entry,
- )
+ logger.warning("Skipping invalid gateway.multiplex_profile_allowlist entry %r (expected a profile name)", entry)
continue
try:
name = normalize_profile_name(entry)
@@ -132,9 +130,7 @@ def _coerce_optional_positive_int(value: Any, key: str) -> Optional[int]:
raise ValueError(value)
parsed = int(value.strip(), 10) if isinstance(value, str) else int(value)
except (TypeError, ValueError):
- logger.warning(
- "Ignoring invalid %s=%r (expected a positive integer; 0/null disables)", key, value
- )
+ logger.warning("Ignoring invalid %s=%r (expected a positive integer; 0/null disables)", key, value)
return None
return parsed if parsed > 0 else None
@@ -252,12 +248,10 @@ class Platform(Enum):
_Platform__bundled_plugin_names = cls._scan_bundled_plugin_platforms()
if value in _Platform__bundled_plugin_names:
return cls._add_pseudo_member(value)
- try:
+ with contextlib.suppress(Exception):
from gateway.platform_registry import platform_registry
if platform_registry.is_registered(value):
return cls._add_pseudo_member(value)
- except Exception:
- pass
return None
@classmethod
@@ -368,20 +362,16 @@ class SessionResetPolicy:
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> "SessionResetPolicy":
data = _coerce_dict(data)
-
- def val(key: str, default: Any) -> Any:
- # Missing keys and explicit YAML nulls both take the default.
- value = data.get(key)
- return default if value is None else value
-
exclude = data.get("notify_exclude_platforms")
+ # Missing keys and explicit YAML nulls both take the field default.
+ plain = {
+ f.name: f.default if data.get(f.name) is None else data[f.name]
+ for f in fields(cls) if f.name not in ("notify", "notify_exclude_platforms")
+ }
return cls(
- mode=val("mode", "none"),
- at_hour=val("at_hour", 4),
- idle_minutes=val("idle_minutes", 1440),
notify=_coerce_bool(data.get("notify"), True),
notify_exclude_platforms=tuple(exclude) if exclude is not None else ("api_server", "webhook"),
- bg_process_max_age_hours=val("bg_process_max_age_hours", 24),
+ **plain,
)
@@ -659,11 +649,9 @@ class GatewayConfig:
# Plugin platforms; force (idempotent) discovery for directly-constructed configs.
try:
from gateway.platform_registry import platform_registry
- try:
+ with contextlib.suppress(Exception):
from hermes_cli.plugins import discover_plugins
discover_plugins()
- except Exception:
- pass
entry = platform_registry.get(platform.value)
if entry:
if entry.is_connected is not None:
diff --git a/gateway/pairing.py b/gateway/pairing.py
index c328bdcb7c5..a2e1110580c 100644
--- a/gateway/pairing.py
+++ b/gateway/pairing.py
@@ -90,14 +90,10 @@ def _allowlist_env_for_platform(platform: str) -> Optional[str]:
env_var = _PLATFORM_ALLOWLIST_ENV.get(platform)
if env_var:
return env_var
- try:
+ with contextlib.suppress(Exception):
from gateway.platform_registry import platform_registry
- entry = platform_registry.get(platform)
- if entry and entry.allowed_users_env:
- return entry.allowed_users_env
- except Exception:
- pass
+ return platform_registry.get(platform).allowed_users_env or None
return None
@@ -148,15 +144,13 @@ def _read_allowlist_env(env_var: str) -> str:
legacy ``os.getenv`` read. Writes go through ``save_env_value``/``remove_env_value``,
which target the active profile's ``.env`` / installed scope, not ``os.environ``.
"""
- try:
+ with contextlib.suppress(Exception):
from agent.secret_scope import UnscopedSecretError, get_secret
try:
return (get_secret(env_var) or "").strip()
except UnscopedSecretError:
pass
- except Exception:
- pass
return (os.getenv(env_var) or "").strip()
@@ -192,12 +186,11 @@ def _sync_allowlist_add(platform: str, user_id: str) -> None:
def _iter_live_gateway_adapters():
"""Yield adapters from the in-process GatewayRunner, if one is running."""
- try:
+ runner = None
+ with contextlib.suppress(Exception):
from gateway.run import _gateway_runner_ref
runner = _gateway_runner_ref()
- except Exception:
- runner = None
if runner is None:
return
mappings = [getattr(runner, "adapters", None) or {}]