Skip to content

The agent that grows with you

refactor(agent): iron_proxy signal guard ctx manager + yaml loader helper; table/kwargs compaction across group

Tekniumaf0ddcb2ec6b
diff --git a/agent/monitoring/cron_health.py b/agent/monitoring/cron_health.py
index de4e9ea73d6..ecd9e739fd4 100644
--- a/agent/monitoring/cron_health.py
+++ b/agent/monitoring/cron_health.py
@@ -37,8 +37,8 @@ class CronHealthSnapshot:
_job_key = _safe_instance_id
_AUTH_RE = re.compile(
- r"\b(?:authentication|authenticated|authenticate|authorization|authorized|authorize"
- r"|unauthorized|forbidden|bearer|401|403)\b|\b(?:access|api|refresh) token\b"
+ r"\b(?:authentication|authenticated|authenticate|authorization|authorized|authorize|unauthorized|forbidden|bearer|401|403)\b"
+ r"|\b(?:access|api|refresh) token\b"
)
# Ordered (predicate, class) rules; first match wins. Auth uses word boundaries so
@@ -146,15 +146,11 @@ def _single_metric(name: str, reader: Callable[[], Any]) -> Callable[[list[Gatew
# Each group is independently fail-open so one unavailable source never hides the rest.
# Readers are wrapped in lambdas so monkeypatching this module's names still takes effect.
_METRIC_GROUPS: tuple[tuple[Callable[[list[GatewayMetric]], None], str], ...] = (
- (_freshness_metric("hermes.cron.scheduler.heartbeat_age_seconds", lambda: get_ticker_heartbeat_age()),
- "cron freshness metric unavailable"),
- (_freshness_metric("hermes.cron.scheduler.last_success_age_seconds", lambda: get_ticker_success_age()),
- "cron freshness metric unavailable"),
- (_single_metric("hermes.cron.scheduler.catch_up_occurrences", lambda: get_catch_up_occurrence_count()),
- "cron catch-up metric unavailable"),
+ (_freshness_metric("hermes.cron.scheduler.heartbeat_age_seconds", lambda: get_ticker_heartbeat_age()), "cron freshness metric unavailable"),
+ (_freshness_metric("hermes.cron.scheduler.last_success_age_seconds", lambda: get_ticker_success_age()), "cron freshness metric unavailable"),
+ (_single_metric("hermes.cron.scheduler.catch_up_occurrences", lambda: get_catch_up_occurrence_count()), "cron catch-up metric unavailable"),
(_job_metrics, "cron job metrics unavailable"),
- (_single_metric("hermes.cron.jobs.running", lambda: len(get_running_job_ids())),
- "cron running-job metric unavailable"),
+ (_single_metric("hermes.cron.jobs.running", lambda: len(get_running_job_ids())), "cron running-job metric unavailable"),
)
diff --git a/agent/monitoring/emitter.py b/agent/monitoring/emitter.py
index b54ac549185..d3cf44a27d2 100644
--- a/agent/monitoring/emitter.py
+++ b/agent/monitoring/emitter.py
@@ -123,12 +123,7 @@ class MonitoringEmitter:
finished.wait(timeout=timeout)
def stats(self) -> Dict[str, int]:
- return {
- "queued": self._q.qsize(),
- "dispatched": self._dispatched,
- "dropped": self._dropped,
- "subscribers": len(self._subscribers),
- }
+ return {"queued": self._q.qsize(), "dispatched": self._dispatched, "dropped": self._dropped, "subscribers": len(self._subscribers)}
def close(self) -> None:
self._stop.set()
diff --git a/agent/monitoring/gateway_health.py b/agent/monitoring/gateway_health.py
index c3051108962..21419a4f25e 100644
--- a/agent/monitoring/gateway_health.py
+++ b/agent/monitoring/gateway_health.py
@@ -60,10 +60,8 @@ _GATEWAY_ERROR_RULES: tuple[tuple[Callable[[str], bool], str], ...] = (
(_contains_any("auth", "token", "unauthorized", "forbidden", "401", "403"), "auth_failed"),
(lambda s: "rate" in s and "limit" in s, "rate_limited"),
(_contains_any("timeout", "timed out"), "timeout"),
- (_contains_any(
- "network", "connection", "dns", "socket", "connect call failed",
- "failed to connect", "cannot connect", "unreachable", "name resolution",
- ), "network_error"),
+ (_contains_any("network", "connection", "dns", "socket", "connect call failed", "failed to connect", "cannot connect",
+ "unreachable", "name resolution"), "network_error"),
(_contains_any("config", "missing", "invalid"), "invalid_config"),
(_contains_any("startup"), "startup_failed"),
(_contains_any("fatal"), "platform_fatal"),
@@ -126,13 +124,13 @@ def platform_for_subsystem(subsystem: str) -> Optional[str]:
return (subsystem.split(".", 1)[1] or None) if subsystem.startswith("platform.") else None
-def _gateway_status(name: str, fallback: Callable[..., Any], /, **kwargs: Any) -> Any:
+def _gateway_status(name: str, fallback: Callable[[], Any], /, **kwargs: Any) -> Any:
"""Prefer ``gateway.status.<name>`` (the runtime-status contract); fall back to the local approximation."""
try:
import gateway.status as status
return getattr(status, name)(**kwargs)
except Exception:
- return fallback(**kwargs)
+ return fallback()
def _int_or_zero(raw: Any) -> int:
@@ -143,25 +141,17 @@ def _int_or_zero(raw: Any) -> int:
def _parse_active_agents(raw: Any) -> int:
- return _gateway_status("parse_active_agents", _int_or_zero, raw=raw)
+ return _gateway_status("parse_active_agents", lambda: _int_or_zero(raw), raw=raw)
def _derive_busy(gateway_running: bool, gateway_state: Any, active_agents: Any) -> bool:
- return _gateway_status(
- "derive_gateway_busy",
- lambda gateway_running, gateway_state, active_agents: bool(
- gateway_running and gateway_state == "running" and _parse_active_agents(active_agents) > 0
- ),
- gateway_running=gateway_running, gateway_state=gateway_state, active_agents=active_agents,
- )
+ fallback = lambda: bool(gateway_running and gateway_state == "running" and _parse_active_agents(active_agents) > 0) # noqa: E731
+ return _gateway_status("derive_gateway_busy", fallback, gateway_running=gateway_running, gateway_state=gateway_state, active_agents=active_agents)
def _derive_drainable(gateway_running: bool, gateway_state: Any) -> bool:
- return _gateway_status(
- "derive_gateway_drainable",
- lambda gateway_running, gateway_state: bool(gateway_running and gateway_state == "running"),
- gateway_running=gateway_running, gateway_state=gateway_state,
- )
+ fallback = lambda: bool(gateway_running and gateway_state == "running") # noqa: E731
+ return _gateway_status("derive_gateway_drainable", fallback, gateway_running=gateway_running, gateway_state=gateway_state)
def _base_attrs(*, install_id: str, version: str, supervision_mode: str) -> Dict[str, str]:
diff --git a/agent/outbound_webhooks.py b/agent/outbound_webhooks.py
index 91d430060b7..d9a81af1c3e 100644
--- a/agent/outbound_webhooks.py
+++ b/agent/outbound_webhooks.py
@@ -180,11 +180,9 @@ def _parse_single_target(index: int, raw: Any) -> Optional[WebhookTarget]:
if not isinstance(events_raw, list) or not events_raw:
warn(" needs a non-empty 'events' list (valid: %s)", valid_list)
return None
- events: List[str] = []
+ events: List[str] = [ev for ev in events_raw if ev in VALID_HOOKS]
for ev in events_raw:
- if ev in VALID_HOOKS:
- events.append(ev)
- else:
+ if ev not in VALID_HOOKS:
warn(": unknown event %r ignored (valid: %s)", ev, valid_list)
if not events:
warn(" has no valid events — skipped")
@@ -204,12 +202,8 @@ def _parse_single_target(index: int, raw: Any) -> Optional[WebhookTarget]:
timeout = DEFAULT_TIMEOUT_SECONDS
name = raw.get("name")
return WebhookTarget(
- url=url,
- events=events,
- name=name.strip() if isinstance(name, str) else "",
- secret=_resolve_secret(index, raw),
- matcher=matcher,
- timeout=max(1, min(timeout, MAX_TIMEOUT_SECONDS)),
+ url=url, events=events, name=name.strip() if isinstance(name, str) else "", secret=_resolve_secret(index, raw),
+ matcher=matcher, timeout=max(1, min(timeout, MAX_TIMEOUT_SECONDS)),
)
@@ -260,21 +254,16 @@ def _serialize_payload(event: str, kwargs: Dict[str, Any], delivery_id: str) ->
# Profile resolved at fire time so a multiplexed gateway's receivers can tell which profile emitted.
from hermes_cli.profiles import get_active_profile_name
payload = {
- "hook_event_name": event,
- "profile": get_active_profile_name(),
- **_payload_fields(kwargs),
- "delivery_id": delivery_id,
- "timestamp": _utc_now_iso(),
+ "hook_event_name": event, "profile": get_active_profile_name(), **_payload_fields(kwargs),
+ "delivery_id": delivery_id, "timestamp": _utc_now_iso(),
}
return json.dumps(payload, ensure_ascii=False, default=str).encode("utf-8")
def _build_delivery(event: str, target: WebhookTarget, body: bytes, delivery_id: str) -> Dict[str, Any]:
headers = {
- "Content-Type": "application/json",
- "User-Agent": "Hermes-Agent-Outbound-Webhook",
- "X-Hermes-Event": event,
- "X-Hermes-Delivery": delivery_id,
+ "Content-Type": "application/json", "User-Agent": "Hermes-Agent-Outbound-Webhook",
+ "X-Hermes-Event": event, "X-Hermes-Delivery": delivery_id,
}
if target.secret:
digest = hmac.new(target.secret.encode("utf-8"), body, hashlib.sha256).hexdigest()
diff --git a/agent/proxy_sources/iron_proxy.py b/agent/proxy_sources/iron_proxy.py
index d5cd271165f..44b462eb691 100644
--- a/agent/proxy_sources/iron_proxy.py
+++ b/agent/proxy_sources/iron_proxy.py
@@ -24,7 +24,7 @@ import threading
import time
import urllib.error
import urllib.request
-from contextlib import suppress
+from contextlib import contextmanager, suppress
from dataclasses import dataclass, field, replace
from pathlib import Path
from typing import Dict, List, Optional, Tuple
@@ -61,14 +61,10 @@ _DEFAULT_ALLOWED_HOSTS: Tuple[str, ...] = (
# Provider env-var name -> upstream hosts on which the Authorization Bearer token is swapped.
_BEARER_PROVIDERS: Dict[str, Tuple[str, ...]] = {
- "OPENROUTER_API_KEY": ("openrouter.ai", "*.openrouter.ai"),
- "OPENAI_API_KEY": ("api.openai.com",),
- "GROQ_API_KEY": ("api.groq.com",),
- "TOGETHER_API_KEY": ("api.together.xyz",),
- "DEEPSEEK_API_KEY": ("api.deepseek.com",),
- "MISTRAL_API_KEY": ("api.mistral.ai",),
- "XAI_API_KEY": ("api.x.ai",),
- "NOUS_API_KEY": ("inference.nousresearch.com",),
+ "OPENROUTER_API_KEY": ("openrouter.ai", "*.openrouter.ai"), "OPENAI_API_KEY": ("api.openai.com",),
+ "GROQ_API_KEY": ("api.groq.com",), "TOGETHER_API_KEY": ("api.together.xyz",),
+ "DEEPSEEK_API_KEY": ("api.deepseek.com",), "MISTRAL_API_KEY": ("api.mistral.ai",),
+ "XAI_API_KEY": ("api.x.ai",), "NOUS_API_KEY": ("inference.nousresearch.com",),
}
# Non-Authorization-header providers (v0.39 ``match_headers`` is case-insensitive). ``aliases``
@@ -80,20 +76,13 @@ _HEADER_AUTH_PROVIDERS: Dict[str, Dict[str, Tuple[str, ...]]] = {
"ANTHROPIC_API_KEY": {"hosts": ("api.anthropic.com",), "match_headers": ("x-api-key", "Authorization"), "aliases": ()},
"AZURE_OPENAI_API_KEY": {
"hosts": ("*.openai.azure.com", "*.cognitiveservices.azure.com", "*.services.ai.azure.com"),
- "match_headers": ("api-key", "Authorization"),
- "aliases": (),
- },
- "GEMINI_API_KEY": {
- "hosts": ("generativelanguage.googleapis.com",),
- "match_headers": ("x-goog-api-key",),
- "aliases": ("GOOGLE_API_KEY",),
+ "match_headers": ("api-key", "Authorization"), "aliases": (),
},
+ "GEMINI_API_KEY": {"hosts": ("generativelanguage.googleapis.com",), "match_headers": ("x-goog-api-key",), "aliases": ("GOOGLE_API_KEY",)},
}
# Creds that static header replacement can't swap (SigV4, SDK-minted OAuth): warning only.
-_NON_BEARER_PROVIDERS: Tuple[str, ...] = (
- "AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "GOOGLE_APPLICATION_CREDENTIALS",
-)
+_NON_BEARER_PROVIDERS: Tuple[str, ...] = ("AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "GOOGLE_APPLICATION_CREDENTIALS")
# Default SSRF deny list (docs promise: cloud metadata IPs refused regardless of allowlist);
# callers pass [] to disable (hermetic tests only).
@@ -108,8 +97,7 @@ _DEFAULT_UPSTREAM_DENY_CIDRS: Tuple[str, ...] = (
# Minimal daemon env; everything else is stripped so /proc/<pid>/environ never exposes operator secrets.
_PROXY_SUBPROCESS_ENV_ALLOWLIST: Tuple[str, ...] = (
- "PATH", "HOME", "TMPDIR", "TZ", "LANG", "LC_ALL", "LC_CTYPE", "NO_COLOR",
- "SSL_CERT_DIR", "SSL_CERT_FILE",
+ "PATH", "HOME", "TMPDIR", "TZ", "LANG", "LC_ALL", "LC_CTYPE", "NO_COLOR", "SSL_CERT_DIR", "SSL_CERT_FILE",
"SYSTEMROOT", "USERPROFILE", # Windows
)
@@ -435,11 +423,19 @@ def ensure_management_token(*, force: bool = False) -> str:
return token
-def _load_proxy_yaml(cfg: Path):
- """Parsed proxy.yaml, or ``{}`` when missing/unreadable/PyYAML absent."""
+def _yaml():
+ """PyYAML module or None (it is a Hermes dep, but never a hard requirement here)."""
try:
import yaml
+ return yaml
except ImportError:
+ return None
+
+
+def _load_proxy_yaml(cfg: Path):
+ """Parsed proxy.yaml, or ``{}`` when missing/unreadable/PyYAML absent."""
+ yaml = _yaml()
+ if yaml is None:
return {}
try:
return yaml.safe_load(cfg.read_text(encoding="utf-8")) or {}
@@ -658,13 +654,11 @@ def _write_state_file_atomic(state: Path, name: str, dump) -> Path:
def write_proxy_config(config: Dict) -> Path:
"""Serialize the config dict to ``<hermes_home>/proxy/proxy.yaml`` (safe_dump, no Python tags)."""
- try:
- import yaml # PyYAML is already a Hermes dep
- except ImportError as exc:
- raise RuntimeError("PyYAML is required to write the iron-proxy config but is not installed.") from exc
+ yaml = _yaml()
+ if yaml is None:
+ raise RuntimeError("PyYAML is required to write the iron-proxy config but is not installed.")
return _write_state_file_atomic(
- _proxy_state_dir(), "proxy.yaml",
- lambda f: yaml.safe_dump(config, f, default_flow_style=False, sort_keys=False),
+ _proxy_state_dir(), "proxy.yaml", lambda f: yaml.safe_dump(config, f, default_flow_style=False, sort_keys=False),
)
@@ -876,17 +870,8 @@ def start_proxy(
# Probe the CONFIGURED bind host (on Linux the docker bridge, where loopback never connects).
probe_host, tunnel_port = _probe_target()
- install_handlers = platform.system() != "Windows" and threading.current_thread() is threading.main_thread()
- prev_sigint = prev_sigterm = None
- if install_handlers:
- prev_sigint = signal.signal(signal.SIGINT, _interrupt_handler)
- prev_sigterm = signal.signal(signal.SIGTERM, _interrupt_handler)
- try:
+ with _interrupt_guard(_interrupt_handler):
listening = _await_listening(proc, probe_host, tunnel_port, on_exit=_exited_error)
- finally:
- if install_handlers:
- signal.signal(signal.SIGINT, prev_sigint)
- signal.signal(signal.SIGTERM, prev_sigterm)
# Process may have died right at deadline.
if proc.poll() is not None:
raise _exited_error()
@@ -897,6 +882,20 @@ def start_proxy(
return get_status()
+@contextmanager
+def _interrupt_guard(handler):
+ """Route SIGINT/SIGTERM to ``handler`` for the block (POSIX main thread only), restoring the previous handlers after."""
+ if platform.system() == "Windows" or threading.current_thread() is not threading.main_thread():
+ yield
+ return
+ prev = [(sig, signal.signal(sig, handler)) for sig in (signal.SIGINT, signal.SIGTERM)]
+ try:
+ yield
+ finally:
+ for sig, old in prev:
+ signal.signal(sig, old)
+
+
def _spawn_daemon(bin_path: Path, cfg: Path, env: Dict[str, str], log_path: Path) -> "subprocess.Popen":
"""Popen with stdout/stderr appended to ``log_path`` (0o600 from the first byte, O_NOFOLLOW so a
planted symlink e.g. to authorized_keys can't receive output, owner-checked). Our log fd is
@@ -911,10 +910,10 @@ def _spawn_daemon(bin_path: Path, cfg: Path, env: Dict[str, str], log_path: Path
raise RuntimeError(f"iron-proxy log {log_path} has unexpected owner uid={st.st_uid}; refusing to write.")
try:
# start_new_session is POSIX-only (Windows isn't supported anyway — no upstream binary).
- popen_kwargs: Dict = dict(env=env, stdin=subprocess.DEVNULL, stdout=log_fd, stderr=subprocess.STDOUT)
- if platform.system() != "Windows":
- popen_kwargs["start_new_session"] = True
- return subprocess.Popen([str(bin_path), "-config", str(cfg)], **popen_kwargs) # noqa: S603
+ session_kw = {} if platform.system() == "Windows" else {"start_new_session": True}
+ return subprocess.Popen( # noqa: S603
+ [str(bin_path), "-config", str(cfg)], env=env, stdin=subprocess.DEVNULL, stdout=log_fd, stderr=subprocess.STDOUT, **session_kw,
+ )
except OSError as exc:
raise RuntimeError(f"failed to spawn iron-proxy: {exc}") from exc
finally: