The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(gateway): narrow or log blind excepts; time out eval subprocesses
Tekniumb6bf0183bafb
diff --git a/agent/managed_worker.py b/agent/managed_worker.pyindex 06126ef2aed..bb3eb0ae58d 100644--- a/agent/managed_worker.py+++ b/agent/managed_worker.py@@ -13,12 +13,15 @@ except ModuleNotFoundError as exc:raiseimport json+import loggingimport osimport refrom pathlib import Pathimport sysimport threading+logger = logging.getLogger(__name__)+MAX_FRAME = 4 * 1024 * 1024BOOTSTRAP_FIELDS = {'version', 'home', 'scope', 'policy', 'api_key', 'text', 'route', 'user_id', 'chat_id','turn_author', 'safe_mode', 'ignore_user_config'}@@ -322,12 +325,18 @@ def hello():def main():channel = WorkerChannel(os.fdopen(os.dup(sys.stdout.fileno()), 'wb', buffering=0)) # windows-footgun: ok — binary framesos.dup2(sys.stderr.fileno(), sys.stdout.fileno())+ # This process's own stderr only (the owner discards it): never the channel, and never the+ # profile's log files, which the module contract keeps free of assignment secrets.+ if not logger.handlers:+ logger.addHandler(logging.StreamHandler(sys.stderr))+ logger.propagate = Falsetry:channel.send('hello', **hello())frame = validate_bootstrap(read_frame(sys.stdin.buffer))execute(frame, channel)except Exception:# Runtime exceptions can contain credentials; the owner gets no raw traceback.+ logger.exception('managed worker failed')channel.send('error', reason='managed_worker_failed')return 1finally:diff --git a/evals/desktop_gateway_ticket_native/run.py b/evals/desktop_gateway_ticket_native/run.pyindex 35cac2bc04d..b457322bf79 100644--- a/evals/desktop_gateway_ticket_native/run.py+++ b/evals/desktop_gateway_ticket_native/run.py@@ -3,6 +3,7 @@ from __future__ import annotationsimport argparseimport json+import loggingimport osfrom pathlib import Pathimport shutil@@ -17,6 +18,8 @@ REPO = Path(__file__).resolve().parents[2]sys.path.insert(0, str(REPO))from hermes_cli.gateway_runtime_discovery import query_identify # noqa: E402+logger = logging.getLogger(__name__)+def stop_owned(process):if process.poll() is not None:@@ -129,6 +132,7 @@ def main():if status or not receipt.get('passed'):raise RuntimeError(f'Electron probe failed: exit={status}')except Exception as error:+ logger.exception('harness error')receipt['passed'] = Falsereceipt['harnessError'] = str(error)finally:diff --git a/evals/desktop_gateway_ticket_native/run_multiplex.py b/evals/desktop_gateway_ticket_native/run_multiplex.pyindex 837dec59efe..4d4179bab13 100644--- a/evals/desktop_gateway_ticket_native/run_multiplex.py+++ b/evals/desktop_gateway_ticket_native/run_multiplex.py@@ -6,6 +6,7 @@ from __future__ import annotationsimport argparseimport json+import loggingimport osfrom pathlib import Pathimport subprocess@@ -18,6 +19,8 @@ sys.path.insert(0, str(REPO))from evals.desktop_gateway_ticket_native.run import stop_owned # noqa: E402from hermes_cli.gateway_runtime_discovery import query_identify # noqa: E402+logger = logging.getLogger(__name__)+def ready(process, home, wanted):deadline = time.monotonic() + 90@@ -99,6 +102,7 @@ def main():if status or not receipt.get('passed'):raise RuntimeError(f'Electron probe failed: exit={status}')except Exception as error:+ logger.exception('harness error')receipt['passed'] = Falsereceipt['harnessError'] = str(error)finally:diff --git a/evals/shared_gateway/normal_boot.py b/evals/shared_gateway/normal_boot.pyindex f0b342df24c..58c21a34f0d 100644--- a/evals/shared_gateway/normal_boot.py+++ b/evals/shared_gateway/normal_boot.py@@ -48,7 +48,7 @@ def main():repo = args.repo.resolve()args.output.parent.mkdir(parents=True, exist_ok=True)receipt = {'head': subprocess.check_output(- ['git', 'rev-parse', 'HEAD'], cwd=repo, stdin=subprocess.DEVNULL, text=True).strip(),+ ['git', 'rev-parse', 'HEAD'], cwd=repo, stdin=subprocess.DEVNULL, text=True, timeout=30).strip(),'surface': 'gateway.run control descriptor', 'passed': False, 'observations': []}with tempfile.TemporaryDirectory(prefix='ugw-boot-') as directory:root = Path(directory)diff --git a/evals/shared_gateway/search_readonly_ab.py b/evals/shared_gateway/search_readonly_ab.pyindex 1a350534a68..a9bf06f34bf 100644--- a/evals/shared_gateway/search_readonly_ab.py+++ b/evals/shared_gateway/search_readonly_ab.py@@ -60,8 +60,9 @@ def main():returnreceipts = []for label, repo in [('baseline', args.baseline), ('fixed', args.fixed)]:- sha = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=repo, text=True).strip()- diff = subprocess.check_output(['git', 'diff', 'HEAD', '--', 'tools/session_search_tool.py'], cwd=repo, text=True)+ sha = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=repo, text=True, timeout=30).strip()+ diff = subprocess.check_output(['git', 'diff', 'HEAD', '--', 'tools/session_search_tool.py'], cwd=repo, text=True,+ timeout=30)import hashlibsource_hash = hashlib.sha256((repo / 'tools/session_search_tool.py').read_bytes()).hexdigest()for case in ['empty', 'foreign', 'existing']:diff --git a/evals/shared_gateway/session_readers_cli_ab.py b/evals/shared_gateway/session_readers_cli_ab.pyindex 28841f047a9..9fb61904917 100644--- a/evals/shared_gateway/session_readers_cli_ab.py+++ b/evals/shared_gateway/session_readers_cli_ab.py@@ -31,7 +31,8 @@ EXPECTED = {}results = []for (label, tree), (name, command), populated in itertools.product(TREES.items(), COMMANDS.items(), (False, True)):- sha = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=tree, text=True, stdin=subprocess.DEVNULL).strip()+ sha = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=tree, text=True, stdin=subprocess.DEVNULL,+ timeout=30).strip()with tempfile.TemporaryDirectory(prefix='hermes-readers-cli-ab-') as tmp:home = Path(tmp) / 'profile'home.mkdir()diff --git a/gateway/hosted_room_attachments.py b/gateway/hosted_room_attachments.pyindex 86f704fba91..9f77e51df2e 100644--- a/gateway/hosted_room_attachments.py+++ b/gateway/hosted_room_attachments.py@@ -969,7 +969,8 @@ class HostedRoomAttachmentStore:for item in payload.get("attachments", [])if isinstance(item, Mapping)}- except Exception:+ # Malformed row: bad/over-nested JSON, a non-object payload, or non-iterable attachments.+ except (ValueError, TypeError, AttributeError, RecursionError):continueif str(row["attachment_id"]) not in ids:continuediff --git a/gateway/run_profile_reconcile.py b/gateway/run_profile_reconcile.pyindex e600b7cd975..b53c0ec67a8 100644--- a/gateway/run_profile_reconcile.py+++ b/gateway/run_profile_reconcile.py@@ -279,7 +279,7 @@ class GatewayProfileReconcileMixin:await serve_profile_runtime(self, name, home)except Exception as exc:logger.error("[MULTIPLEX] Profile '%s' not served: its session store is unusable (%s): %s",- name, home, exc)+ name, home, exc, exc_info=True)release_profile_home(self, home)return f"session store unusable: {exc}"return Nonediff --git a/gateway/run_runtime_init.py b/gateway/run_runtime_init.pyindex b253aca4661..16591b2f4c5 100644--- a/gateway/run_runtime_init.py+++ b/gateway/run_runtime_init.py@@ -1,6 +1,10 @@"""Writable runner initialization, separate from process ownership."""from __future__ import annotations+import logging++logger = logging.getLogger("gateway.run") # log-record parity with gateway/run.py+class GatewayRuntimeInitMixin:def _init_runtime_settings(self) -> None:"""Load ephemeral per-call config (prefill, reasoning, busy modes, timeouts, routing)."""@@ -158,7 +162,7 @@ class GatewayRuntimeInitMixin:def _init_session_db(self) -> None:"""Open the session DB for the active scope and run opportunistic state.db / checkpoint maintenance."""- from gateway.run import (Any, Dict, Path, _SESSION_DB_UNPINNED, _housekeeping_chore, _housekeeping_state_db_maintenance, _launch_sessions_dir, logger, threading)+ from gateway.run import (Any, Dict, Path, _SESSION_DB_UNPINNED, _housekeeping_chore, _housekeeping_state_db_maintenance, _launch_sessions_dir, threading)# Session DB is a property caching one AsyncSessionDB per path (a handle bound here would pin the# root home under multiplex); priming here keeps startup diagnostics at init.# Initialize session database for session_search tool support. Same frozen-handle class of bug as@@ -175,7 +179,7 @@ class GatewayRuntimeInitMixin:self._open_session_db_for_active_scope(raise_on_error=True)except Exception as e:# WARNING (not DEBUG) so it lands in errors.log; else an NFS HERMES_HOME silently loses /resume etc.- logger.warning("SQLite session store not available: %s", e)+ logger.warning("SQLite session store not available: %s", e, exc_info=True)self._session_db_init_error = str(e) # surfaced on the home channel(s) once connected# Opportunistic state.db maintenance (prune + optional VACUUM), at most once per min_interval_hours.diff --git a/gateway/runtime_bootstrap_windows.py b/gateway/runtime_bootstrap_windows.pyindex 425eb4d8858..723a3b856ab 100644--- a/gateway/runtime_bootstrap_windows.py+++ b/gateway/runtime_bootstrap_windows.py@@ -7,11 +7,14 @@ from __future__ import annotationsimport ctypesfrom ctypes import wintypes+import loggingimport osfrom pathlib import Pathimport threadingimport time+logger = logging.getLogger(__name__)+def _native():if os.name != 'nt':@@ -264,6 +267,8 @@ class NativeControlServer:if exc.winerror != 233: # ERROR_PIPE_NOT_CONNECTED: the client already leftraiseexcept BaseException as exc:+ # Hand-off to the owning thread: start() re-raises the stored error.+ logger.debug('runtime control pipe stopped', exc_info=True)self._error = excself._ready.set()finally:diff --git a/gateway/session_readiness.py b/gateway/session_readiness.pyindex 8fd40c3291f..19d48e93714 100644--- a/gateway/session_readiness.py+++ b/gateway/session_readiness.py@@ -1,9 +1,12 @@"""Profile-bound setup checks without legacy session execution dispatch."""import asyncio+import loggingfrom pathlib import Pathfrom hermes_state_runtime import RuntimeStoreError+logger = logging.getLogger(__name__)+async def readiness(authority, actor, params, *, runtime):if 'session:create' not in actor.capabilities or actor.profile_id != authority.profile_id:@@ -31,7 +34,8 @@ async def readiness(authority, actor, params, *, runtime):if runtime:return check_runtime_readiness(params.get('provider') or None, strict_profile_scope=True)return {'provider_configured': bool(_has_any_provider_configured(strict_profile_scope=True))}- except Exception as exc:+ except Exception as exc: # a readiness probe reports, never raises+ logger.debug('readiness probe failed', exc_info=True)return {'ok': False, 'error': str(exc)}return await asyncio.to_thread(probe)diff --git a/hermes_state_gateway.py b/hermes_state_gateway.pyindex 125d365311b..80c02ae5a56 100644--- a/hermes_state_gateway.py+++ b/hermes_state_gateway.py@@ -374,7 +374,7 @@ class SessionGatewayMixin:for row in self._read_all("SELECT entry_json FROM gateway_routing"):try:entry = json.loads(row["entry_json"] or "{}")- except Exception:+ except (ValueError, TypeError, RecursionError): # malformed / non-text / over-nested entrycontinueif isinstance(entry, dict) and entry.get("session_id") == session_id:return entry@@ -389,7 +389,7 @@ class SessionGatewayMixin:for row in self._read_all("SELECT scope, session_key, entry_json FROM gateway_routing"):try:entry = json.loads(row["entry_json"] or "{}")- except Exception:+ except (ValueError, TypeError, RecursionError): # malformed / non-text / over-nested entrycontinueif isinstance(entry, dict) and entry.get("session_id") in session_ids:found.append((row["scope"], row["session_key"], entry["session_id"]))diff --git a/plugins/platforms/a2a/adapter.py b/plugins/platforms/a2a/adapter.pyindex 4803959e7e8..34ad567dff4 100644--- a/plugins/platforms/a2a/adapter.py+++ b/plugins/platforms/a2a/adapter.py@@ -591,6 +591,8 @@ class A2AAdapter(BasePlatformAdapter):except TimeoutError:return "[profile reply unverified; accepted work was not cancelled]", protocol.STATE_FAILEDexcept Exception as exc:+ # Boundary for a network peer: the full error stays in the local log, the reply is redacted.+ logger.warning("A2A: dispatch to profile %r unverified", profile, exc_info=True)return security.redact_outbound(f"Profile dispatch unverified: {exc}"), protocol.STATE_FAILEDresult = receipt.get('result') or {}completed = receipt.get('outcome') == 'completed' and not result.get('failed')diff --git a/tools/approval_context.py b/tools/approval_context.pyindex e11711bf434..cd58dfb64ed 100644--- a/tools/approval_context.py+++ b/tools/approval_context.py@@ -156,10 +156,11 @@ def _is_single_query_approval_context() -> bool:over the daemon): the viewer detaches on the first prompt, so nobody answers there either."""try:from gateway.session_finite import finite_turn_required+ except ImportError: # install without the gateway package: no admitted turn to carry the flag+ pass+ else:if finite_turn_required() is True:return True- except Exception:- passreturn is_truthy_value(_session_env("HERMES_SINGLE_QUERY_SESSION"))diff --git a/tools/session_search_tool.py b/tools/session_search_tool.pyindex 0b3c67a0a2f..aa4c709b9a9 100644--- a/tools/session_search_tool.py+++ b/tools/session_search_tool.py@@ -621,6 +621,7 @@ def session_search(query: str = "", role_filter: str = None, limit: int = 3, db=try:profile_db = _resolve_profile_db(profile)except Exception as e:+ logging.debug("session_search: cannot open profile %r", profile, exc_info=True)return tool_error(f"profile '{profile}': {e}", success=False)if profile_db is not None:db, current_session_id = profile_db, None