The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(gateway): fold delivery send-result/dead-target micro-helpers, dedupe ledger claim rows, compact control socket
Tekniumf22fbb264ca3
diff --git a/gateway/control_socket.py b/gateway/control_socket.pyindex 668ac226089..c135febe37a 100644--- a/gateway/control_socket.py+++ b/gateway/control_socket.py@@ -1,18 +1,10 @@-"""Gateway control socket — the gateway-owned local coordination surface.--Instead of process-table scans or ``gateway_state.json`` (which can outlive-its writer), the gateway serves a local-only socket answering versioned JSON-verbs (``identify``, ``status``). A connectable socket with a well-formed-``identify`` answer IS liveness — no PID-reuse heuristics.--Transport — never a TCP port; filesystem/pipe ACLs are the auth boundary.-POSIX: ``$HERMES_HOME/gateway.sock``, or a temp-dir socket plus a-``gateway.sock.path`` pointer file when the home path exceeds ``sun_path``.-Windows: named pipe ``\\\\.\\pipe\\hermes-gateway-<home-hash>``.--Wire contract: ONE request per connection — one JSON line in, one out, then-the server closes (no keep-alive/pipelining). Consumers PREFER the socket and-fall back to the state-file/scan layer when it doesn't answer.+"""Gateway control socket — the gateway-owned local coordination surface: a local-only socket answering+versioned JSON verbs (``identify``, ``status``). A connectable socket with a well-formed ``identify``+answer IS liveness — no PID-reuse heuristics. Never a TCP port: filesystem/pipe ACLs are the auth+boundary. POSIX: ``$HERMES_HOME/gateway.sock`` (or a temp-dir socket + ``gateway.sock.path`` pointer+file when the home path exceeds ``sun_path``); Windows: named pipe ``\\\\.\\pipe\\hermes-gateway-<hash>``.+Wire contract: ONE request per connection — one JSON line in, one out, then the server closes.+Consumers PREFER the socket and fall back to the state-file/scan layer when it doesn't answer."""from __future__ import annotations@@ -33,28 +25,18 @@ from typing import Any, Callable, Optionallogger = logging.getLogger(__name__)CONTROL_PROTOCOL_VERSION = 1-_SOCKET_FILENAME = "gateway.sock"_POINTER_FILENAME = "gateway.sock.path"_IS_WINDOWS = sys.platform == "win32"--# sun_path limit is 104 on macOS/BSD, 108 on Linux; leave margin for the NUL.-_MAX_UNIX_PATH = 100-+_MAX_UNIX_PATH = 100 # sun_path limit is 104 on macOS/BSD, 108 on Linux; margin for the NUL# Single-line JSON in/out; bounded so a misbehaving peer can't balloon memory._MAX_REQUEST_BYTES = 64 * 1024_MAX_RESPONSE_BYTES = 512 * 1024-_DEFAULT_CLIENT_TIMEOUT = 2.0-# ----------------------------------------------------------------------------# Path resolution (shared by server and client)-# ----------------------------------------------------------------------------def _home_hash(home: Path) -> str:- canonical = os.path.normcase(str(Path(home).expanduser().resolve(strict=False)))- return hashlib.sha256(canonical.encode("utf-8")).hexdigest()[:16]+ return hashlib.sha256(os.path.normcase(str(Path(home).expanduser().resolve(strict=False))).encode("utf-8")).hexdigest()[:16]def windows_pipe_name(home: Path) -> str:@@ -67,29 +49,20 @@ def _fits_sun_path(path: Path) -> bool:def _fallback_socket_path(home: Path) -> Path:- """Short temp-dir path for homes whose direct socket path exceeds sun_path.-- Tries ``tempfile.gettempdir()`` then ``/tmp`` (POSIX). If nothing fits the- tempdir candidate is returned anyway — bind fails non-fatally and- consumers use the scan layer.- """+ """Short temp-dir path for homes whose direct socket path exceeds sun_path: ``tempfile.gettempdir()``+ then ``/tmp`` (POSIX); if nothing fits the tempdir candidate is returned anyway — bind fails+ non-fatally and consumers use the scan layer."""name = f"hermes-gw-{_home_hash(home)}.sock"candidates = [Path(tempfile.gettempdir()) / name]if not _IS_WINDOWS:candidates.append(Path("/tmp") / name)- for candidate in candidates:- if _fits_sun_path(candidate):- return candidate- return candidates[0]+ return next((c for c in candidates if _fits_sun_path(c)), candidates[0])def resolve_server_socket_path(home: Path) -> tuple[Path, Optional[Path]]:- """Return ``(bind_path, pointer_file)``; pointer_file is non-None only- when the temp-dir fallback is in use and the server must record it."""+ """Return ``(bind_path, pointer_file)``; pointer_file is set only for the temp-dir fallback."""direct = Path(home) / _SOCKET_FILENAME- if _fits_sun_path(direct):- return direct, None- return _fallback_socket_path(home), Path(home) / _POINTER_FILENAME+ return (direct, None) if _fits_sun_path(direct) else (_fallback_socket_path(home), Path(home) / _POINTER_FILENAME)def resolve_client_socket_path(home: Path) -> Optional[Path]:@@ -98,30 +71,21 @@ def resolve_client_socket_path(home: Path) -> Optional[Path]:if direct.exists():return directpointer = Path(home) / _POINTER_FILENAME- try:+ with contextlib.suppress(OSError):if pointer.is_file():target = pointer.read_text(encoding="utf-8").strip()if target and Path(target).exists():return Path(target)- except OSError:- passreturn None-# ----------------------------------------------------------------------------# Default payload builders (import-light; overridable at wiring time)-# ----------------------------------------------------------------------------def _detect_supervisor() -> str:- """Supervisor kind for THIS process, declared from its own launch env- (not inferred outside-in like ``_detect_supervisor_for_pid``)."""+ """Supervisor kind for THIS process from its own launch env (not inferred outside-in)."""env = os.environif env.get("INVOCATION_ID"):return "systemd"- if sys.platform == "darwin" and (- env.get("XPC_SERVICE_NAME", "").startswith("ai.hermes")- or env.get("LAUNCHD_SOCKET")- ):+ if sys.platform == "darwin" and (env.get("XPC_SERVICE_NAME", "").startswith("ai.hermes")+ or env.get("LAUNCHD_SOCKET")):return "launchd"if env.get("HERMES_DESKTOP_MANAGED"):return "desktop"@@ -132,13 +96,7 @@ def _detect_supervisor() -> str:def build_identify_payload() -> dict[str, Any]:"""Default ``identify`` answer, built from gateway.status primitives."""- from gateway.status import (- _build_pid_record,- _get_code_identity_fields,- _profile_label_for_home,- read_runtime_status,- )-+ from gateway.status import _build_pid_record, _get_code_identity_fields, _profile_label_for_home, read_runtime_statusrecord = _build_pid_record()payload: dict[str, Any] = {"protocol": CONTROL_PROTOCOL_VERSION,@@ -147,82 +105,56 @@ def build_identify_payload() -> dict[str, Any]:"supervisor": _detect_supervisor(),}payload.update(_get_code_identity_fields())- # served_profiles (multiplex mode) is stamped into runtime status by the runner.- try:+ with contextlib.suppress(Exception):+ # served_profiles (multiplex mode) is stamped into runtime status by the runner.served = (read_runtime_status() or {}).get("served_profiles")if isinstance(served, list) and served:payload["served_profiles"] = served- except Exception:- passreturn payloaddef build_status_payload() -> dict[str, Any]:"""Default ``status`` answer — current runtime status, answered live."""from gateway.status import read_runtime_status+ return {**(read_runtime_status() or {}), "protocol": CONTROL_PROTOCOL_VERSION,+ "answered_at": time.time(), "answering_pid": os.getpid()}- payload = dict(read_runtime_status() or {})- payload["protocol"] = CONTROL_PROTOCOL_VERSION- payload["answered_at"] = time.time()- payload["answering_pid"] = os.getpid()- return payload---# ----------------------------------------------------------------------------# Server-# ---------------------------------------------------------------------------class GatewayControlServer:- """Gateway-owned control socket server (identify/status, v1).-- ``start()`` after the PID-file claim, ``stop()`` on shutdown. All failures- are non-fatal — the gateway never refuses to serve messaging because its- control socket couldn't bind; consumers fall back to the scan layer.- """-- def __init__(- self,- home: Optional[Path] = None,- *,- verb_handlers: Optional[dict[str, Callable[[], dict[str, Any]]]] = None,- ) -> None:+ """Gateway-owned control socket server (identify/status, v1): ``start()`` after the PID-file claim,+ ``stop()`` on shutdown. All failures are non-fatal — the gateway never refuses to serve messaging+ because its control socket couldn't bind; consumers fall back to the scan layer."""++ def __init__(self, home: Optional[Path] = None, *,+ verb_handlers: Optional[dict[str, Callable[[], dict[str, Any]]]] = None) -> None:if home is None:from gateway.status import _get_process_hermes_home-home = _get_process_hermes_home()self._home = Path(home)self._server: Optional[asyncio.AbstractServer] = Noneself._pipe_server: Any = None # Windows proactor pipe serverself._bind_path: Optional[Path] = Noneself._pointer_file: Optional[Path] = None- self._handlers: dict[str, Callable[[], dict[str, Any]]] = {- "identify": build_identify_payload,- "status": build_status_payload,- }- if verb_handlers:- self._handlers.update(verb_handlers)-- # -- lifecycle ---------------------------------------------------------+ self._handlers: dict[str, Callable[[], dict[str, Any]]] = {"identify": build_identify_payload,+ "status": build_status_payload}+ self._handlers.update(verb_handlers or {})async def start(self) -> bool:"""Bind and start serving. Returns True on success, False otherwise."""try:- if _IS_WINDOWS:- return await self._start_windows()- return await self._start_posix()+ return await (self._start_windows() if _IS_WINDOWS else self._start_posix())except Exception as exc:logger.warning("Gateway control socket failed to start (non-fatal): %s", exc)return Falseasync def _start_posix(self) -> bool:bind_path, pointer_file = resolve_server_socket_path(self._home)- # We only get here after winning the PID-file O_EXCL race, so any- # existing file is stale or a collision — never a live sibling.+ # We only get here after winning the PID-file O_EXCL race, so any existing+ # file is stale or a collision — never a live sibling.with contextlib.suppress(OSError):if bind_path.exists():bind_path.unlink()- # Restrictive umask so the socket is never world-connectable, even- # for the instant before chmod.+ # Restrictive umask so the socket is never world-connectable, even for the instant before chmod.old_umask = os.umask(0o177)try:self._server = await asyncio.start_unix_server(self._handle_connection, path=str(bind_path))@@ -241,10 +173,8 @@ class GatewayControlServer:loop = asyncio.get_running_loop()start_serving_pipe = getattr(loop, "start_serving_pipe", None)if start_serving_pipe is None:- logger.debug(- "Event loop %s has no start_serving_pipe — control socket "- "disabled (selector loop on Windows).", type(loop).__name__,- )+ logger.debug("Event loop %s has no start_serving_pipe — control socket "+ "disabled (selector loop on Windows).", type(loop).__name__)return Falsepipe_name = windows_pipe_name(self._home)servers = await start_serving_pipe(lambda: _PipeControlProtocol(self), pipe_name)@@ -258,11 +188,10 @@ class GatewayControlServer:self._server.close()with contextlib.suppress(Exception):await self._server.wait_closed()- self._server = Noneif self._pipe_server is not None:with contextlib.suppress(Exception):self._pipe_server.close()- self._pipe_server = None+ self._server = self._pipe_server = Noneself.cleanup_files()def cleanup_files(self) -> None:@@ -272,34 +201,22 @@ class GatewayControlServer:with contextlib.suppress(OSError):path.unlink(missing_ok=True)- # -- request handling -----------------------------------------------------def handle_request_line(self, raw: bytes) -> bytes:- """One JSON request line -> one JSON response line. Never raises.-- Shared by the POSIX stream handler and the Windows pipe protocol.- """+ """One JSON request line -> one JSON response line. Never raises (shared by POSIX + pipe)."""request_id: Any = Nonetry:request = json.loads(raw.decode("utf-8"))if not isinstance(request, dict):raise ValueError("request must be a JSON object")- request_id = request.get("id")- verb = request.get("verb")+ request_id, verb = request.get("id"), request.get("verb")handler = self._handlers.get(verb) if isinstance(verb, str) else Noneif handler is None:- response: dict[str, Any] = {- "ok": False, "error": f"unknown verb: {verb!r}",- "protocol": CONTROL_PROTOCOL_VERSION,- "supported_verbs": sorted(self._handlers),- }+ response: dict[str, Any] = {"ok": False, "error": f"unknown verb: {verb!r}",+ "protocol": CONTROL_PROTOCOL_VERSION, "supported_verbs": sorted(self._handlers)}else:response = {"ok": True, "protocol": CONTROL_PROTOCOL_VERSION, "result": handler()}except Exception as exc:- response = {- "ok": False, "error": f"{type(exc).__name__}: {exc}",- "protocol": CONTROL_PROTOCOL_VERSION,- }+ response = {"ok": False, "error": f"{type(exc).__name__}: {exc}", "protocol": CONTROL_PROTOCOL_VERSION}if request_id is not None:response["id"] = request_idtry:@@ -315,10 +232,10 @@ class GatewayControlServer:raw = await asyncio.wait_for(reader.readline(), timeout=_DEFAULT_CLIENT_TIMEOUT)if not raw or len(raw) > _MAX_REQUEST_BYTES:return- # Handlers read disk; keep that off the loop that drives every- # platform adapter so a fast-polling consumer can't stall heartbeats.- loop = asyncio.get_running_loop()- response = await loop.run_in_executor(None, self.handle_request_line, raw.rstrip(b"\n"))+ # Handlers read disk; keep that off the loop that drives every platform+ # adapter so a fast-polling consumer can't stall heartbeats.+ response = await asyncio.get_running_loop().run_in_executor(+ None, self.handle_request_line, raw.rstrip(b"\n"))writer.write(response)await writer.drain()except (asyncio.TimeoutError, ConnectionError, OSError):@@ -332,7 +249,6 @@ class GatewayControlServer:class _PipeControlProtocol(asyncio.Protocol):"""One-shot request/response protocol for the Windows named pipe."""-def __init__(self, server: GatewayControlServer) -> None:self._server = serverself._transport: Any = None@@ -354,29 +270,18 @@ class _PipeControlProtocol(asyncio.Protocol):self._transport.close()-# ----------------------------------------------------------------------------# Client (synchronous — used by CLI/updater consumers)-# -----------------------------------------------------------------------------def query_gateway_control(- home: Path, verb: str, *, timeout: float = _DEFAULT_CLIENT_TIMEOUT-) -> Optional[dict[str, Any]]:- """Ask the gateway serving ``home`` a control verb; None when unanswered.-- Returns the verb's ``result`` payload. Any failure (no/stale socket,- timeout, malformed answer, ``ok: false``) returns None so callers fall- back to the scan layer. Never raises.- """+def query_gateway_control(home: Path, verb: str, *, timeout: float = _DEFAULT_CLIENT_TIMEOUT) -> Optional[dict[str, Any]]:+ """Ask the gateway serving ``home`` a control verb; returns its ``result`` payload. Any failure (no/stale+ socket, timeout, malformed answer, ``ok: false``) returns None so callers fall back to the scan layer.+ Never raises."""request = json.dumps({"verb": verb, "id": 1, "protocol": CONTROL_PROTOCOL_VERSION}).encode("utf-8") + b"\n"query = _query_windows_pipe if _IS_WINDOWS else _query_unix_sockettry:raw = query(Path(home), request, timeout)except Exception:return None- if not raw:- return Nonetry:- response = json.loads(raw.decode("utf-8"))+ response = json.loads(raw.decode("utf-8")) if raw else Noneexcept (ValueError, UnicodeDecodeError):return Noneif not isinstance(response, dict) or response.get("ok") is not True:@@ -409,13 +314,12 @@ def _query_unix_socket(home: Path, request: bytes, timeout: float) -> Optional[bsock.settimeout(timeout)try:sock.connect(str(path))- except (ConnectionRefusedError, FileNotFoundError, OSError):+ except OSError: # incl. ConnectionRefusedError / FileNotFoundErrorreturn Nonesock.sendall(request)- try:+ with contextlib.suppress(socket.timeout):return _read_response_line(lambda: sock.recv(65536), time.monotonic() + timeout)- except socket.timeout:- return None+ return Nonedef _query_windows_pipe(home: Path, request: bytes, timeout: float) -> Optional[bytes]: # pragma: no cover - wine2e lane@@ -446,10 +350,7 @@ def identify_gateway(home: Path, *, timeout: float = _DEFAULT_CLIENT_TIMEOUT) ->def pause_gateway_for_update(home: Path, *, timeout: float = _DEFAULT_CLIENT_TIMEOUT) -> Optional[dict[str, Any]]:- """Ask the gateway serving ``home`` to drain and exit for an update.-- Returns the ACK ``{"pausing", "already_stopping", "pid", "drain_timeout"}``- or None when no gateway answers (old gateway without the verb, no/dead- socket) — the caller then uses the legacy signal/tree-kill pause path.- """+ """Ask the gateway serving ``home`` to drain and exit for an update. Returns the ACK ``{"pausing",+ "already_stopping", "pid", "drain_timeout"}`` or None when no gateway answers (old gateway without+ the verb, no/dead socket) — the caller then uses the legacy signal/tree-kill pause path."""return query_gateway_control(home, "pause-for-update", timeout=timeout)diff --git a/gateway/dead_targets.py b/gateway/dead_targets.pyindex b0ffa3cdd64..93805a149c8 100644--- a/gateway/dead_targets.py+++ b/gateway/dead_targets.py@@ -1,18 +1,9 @@-"""Persistent registry of delivery targets that are confirmed unreachable.--When a platform reports a target chat is permanently gone (deleted group,-bot kicked/blocked, deactivated user), re-sending on every cron tick wastes a-send against flood control and spams logs. The delivery layer short-circuits-targets proven dead; any later successful send clears the flag (self-healing).--Scope is deliberately narrow: only *whole-chat* deaths (``forbidden`` and-chat-level ``not_found``) are recorded. Thread/topic-level ``not_found`` is-NOT — adapters self-heal that by retrying without ``reply_to``, and a deleted-topic does not mean the parent chat is dead.--Storage is a JSON file under the active profile's HERMES_HOME (each profile-keeps its own dead set). Reads/writes are best-effort: a corrupt or unwritable-file degrades to in-memory-only rather than raising on the delivery path.+"""Persistent registry of delivery targets confirmed unreachable. Re-sending to a permanently gone chat+(deleted group, bot kicked/blocked, deactivated user) every cron tick wastes flood-control budget; delivery+short-circuits targets proven dead and any later successful send clears the flag. Only *whole-chat* deaths+(``forbidden``, chat-level ``not_found``) are recorded: adapters self-heal thread/topic-level ``not_found``+by retrying without ``reply_to``. Storage is a per-profile JSON file; reads/writes are best-effort (a+corrupt or unwritable file degrades to in-memory-only rather than raising on the delivery path)."""from __future__ import annotations@@ -28,8 +19,7 @@ from hermes_cli.config import get_hermes_homelogger = logging.getLogger(__name__)-# Error kinds (gateway.platforms.base.classify_send_error) meaning the whole-# chat is unreachable, not a transient or thread-level problem.+# classify_send_error kinds meaning the whole chat is unreachable (not transient / thread-level)._DEAD_ERROR_KINDS = frozenset({"forbidden", "not_found"})@@ -38,28 +28,38 @@ def _normalize(platform: str, chat_id: str) -> str:return f"{str(platform).strip().lower()}:{str(chat_id).strip()}"-class DeadTargetRegistry:- """Thread-safe, persistent set of confirmed-dead targets keyed ``platform:chat_id``.+def classify_dead_error(error_text: Optional[str]) -> Optional[str]:+ """Best-effort dead-target error_kind from a raised error's text, else None. ``_deliver_to_platform``+ raises on hard failure (no SendResult), so ``deliver()`` only has the exception string. ``not_found``+ collapses chat-level and thread/topic/message-level failures: only a whole-chat not_found means the+ target is dead — a deleted forum topic or edited-away message must not mark the entire chat dead."""+ if not error_text:+ return None+ try:+ from .platforms.base import classify_send_error, is_chat_level_not_found+ except Exception: # pragma: no cover - import guard+ return None+ kind = classify_send_error(None, error_text=error_text)+ if kind not in _DEAD_ERROR_KINDS or (kind == "not_found" and not is_chat_level_not_found(error_text=error_text)):+ return None+ return kind+- Each entry stores reason + timestamp for observability; :meth:`clear`- (called on a successful send) removes the flag.- """+class DeadTargetRegistry:+ """Thread-safe, persistent set of confirmed-dead targets keyed ``platform:chat_id``. Each entry stores+ reason + timestamp for observability; :meth:`clear` (called on a successful send) removes the flag."""def __init__(self, path: Optional[Path] = None) -> None:self._lock = threading.RLock()self._dead: Dict[str, Dict[str, object]] = {}self._path = path if path is not None else get_hermes_home() / "gateway" / "dead_targets.json"- self._load()-- def _load(self) -> None:try:if self._path.exists():raw = json.loads(self._path.read_text(encoding="utf-8"))if isinstance(raw, dict):self._dead = {k: v for k, v in raw.items() if isinstance(v, dict)}except (OSError, ValueError) as exc:- logger.debug("dead_targets: could not load %s (%s) — starting empty",- self._path, exc)+ logger.debug("dead_targets: could not load %s (%s) — starting empty", self._path, exc)self._dead = {}def _flush_locked(self) -> None:@@ -68,42 +68,26 @@ class DeadTargetRegistry:tmp = self._path.with_suffix(self._path.suffix + ".tmp")tmp.write_text(json.dumps(self._dead, indent=2), encoding="utf-8")tmp.replace(self._path)- except OSError as exc:- # Best-effort: keep in-memory state, never break delivery.+ except OSError as exc: # best-effort: keep in-memory state, never break deliverylogger.debug("dead_targets: could not persist %s (%s)", self._path, exc)- @staticmethod- def is_dead_error_kind(error_kind: Optional[str]) -> bool:- """True when ``error_kind`` denotes a permanent whole-chat death."""- return bool(error_kind) and error_kind in _DEAD_ERROR_KINDS-def is_dead(self, platform: str, chat_id: Optional[str]) -> bool:- if not chat_id:- return Falsewith self._lock:- return _normalize(platform, chat_id) in self._dead+ return bool(chat_id) and _normalize(platform, chat_id) in self._dead- def mark_dead(self, platform: str, chat_id: Optional[str],- reason: str = "") -> bool:+ def mark_dead(self, platform: str, chat_id: Optional[str], reason: str = "") -> bool:"""Record a target as confirmed-dead. Returns True if newly added."""if not chat_id:return Falsekey = _normalize(platform, chat_id)with self._lock:existed = key in self._dead- self._dead[key] = {- "platform": str(platform).strip().lower(),- "chat_id": str(chat_id),- "reason": str(reason)[:200],- "marked_at": time.time(),- }+ self._dead[key] = {"platform": str(platform).strip().lower(), "chat_id": str(chat_id),+ "reason": str(reason)[:200], "marked_at": time.time()}self._flush_locked()if not existed:- logger.info(- "dead_targets: marked %s as unreachable (%s) — future deliveries "- "to this target will be skipped until a send succeeds",- key, reason or "no reason given",- )+ logger.info("dead_targets: marked %s as unreachable (%s) — future deliveries "+ "to this target will be skipped until a send succeeds", key, reason or "no reason given")return not existeddef clear(self, platform: str, chat_id: Optional[str]) -> bool:diff --git a/gateway/delivery.py b/gateway/delivery.pyindex e5ded9c5f82..7ecc8561542 100644--- a/gateway/delivery.py+++ b/gateway/delivery.py@@ -1,10 +1,5 @@-"""-Delivery routing for cron job outputs and agent responses.--Routes messages by target: explicit ("telegram:123456789"), platform home-channel ("telegram"), origin (back to where the job was created), or local-(saved to files).-"""+"""Delivery routing for cron job outputs and agent responses, by target: explicit ("telegram:123456789"),+platform home channel ("telegram"), origin (back to where the job was created), or local (files)."""import loggingimport os@@ -16,43 +11,35 @@ from typing import Dict, List, Optional, Anyfrom hermes_cli.config import get_hermes_home+from .config import Platform, GatewayConfig, PlatformConfig+from .session import SessionSource+from .dead_targets import DeadTargetRegistry, classify_dead_error+logger = logging.getLogger(__name__)-# Cap before gateway-level truncation of cron output for non-chunking platform-# delivery. Telegram's hard API limit is 4096; the headroom covers the "full-# output saved to …" footer. Adapters that split long messages natively-# (BasePlatformAdapter.splits_long_messages) bypass this entirely.+# Cap before gateway-level truncation of cron output for non-chunking platform delivery. Telegram's hard+# API limit is 4096; the headroom covers the "full output saved to …" footer. Adapters that split long+# messages natively (splits_long_messages) bypass this entirely.MAX_PLATFORM_OUTPUT = 4000--# Matches strings that are *only* a "silence" narration with optional markdown-# wrappers: *(silent)*, _silent_, `silent`, (silent), silent, 🔇, a bare ".",-# "…", and marker-padded variants. Anchored so substantive messages that merely-# *contain* the word "silent" never match.+# Matches strings that are *only* a "silence" narration with optional markdown wrappers (*(silent)*,+# _silent_, 🔇, a bare ".", "…"). Anchored so messages that merely *contain* "silent" never match._SILENCE_NARRATION = re.compile(r'^[\s*_~`]*\(?\s*(silent|silence|no\s+response|no\s+reply)\s*\.?\)?[\s*_~`]*$'r'|^[\s*_~`]*[\U0001F507\.\u2026]+[\s*_~`]*$',re.IGNORECASE,)+_THREAD_ROUTING_KEYS = ("thread_id", "message_thread_id", "direct_messages_topic_id", "telegram_direct_messages_topic_id")def _is_silence_narration(content: Optional[str]) -> bool:"""True when ``content`` is *only* a silence-narration token (length-guarded)."""- if not content:- return False- stripped = content.strip()- if not stripped or len(stripped) > 64:- return False- return bool(_SILENCE_NARRATION.match(stripped))--from .config import Platform, GatewayConfig, PlatformConfig-from .session import SessionSource-from .dead_targets import DeadTargetRegistry+ stripped = content.strip() if content else ""+ return bool(stripped) and len(stripped) <= 64 and bool(_SILENCE_NARRATION.match(stripped))@dataclass(frozen=True)class DeliveryTransport:"""Resolved live transport for one logical delivery platform."""-adapter: Anyconfig: Optional[PlatformConfig]transport_platform: Platform@@ -61,33 +48,20 @@ class DeliveryTransport:def is_relay(self) -> bool:return self.transport_platform == Platform.RELAY- async def send(- self,- logical_platform: Platform,- chat_id: str,- content: str,- metadata: Optional[Dict[str, Any]],- ) -> Any:+ async def send(self, logical_platform: Platform, chat_id: str, content: str,+ metadata: Optional[Dict[str, Any]]) -> Any:"""Send through this transport while preserving the logical platform."""if self.is_relay:- return await self.adapter.send_for_platform(- logical_platform, chat_id, content, metadata=metadata,- )+ return await self.adapter.send_for_platform(logical_platform, chat_id, content, metadata=metadata)return await self.adapter.send(chat_id, content, metadata=metadata)-def resolve_delivery_transport(- platform: Platform,- config: GatewayConfig,- adapters: Optional[Dict[Platform, Any]],-) -> Optional[DeliveryTransport]:- """Resolve a logical platform to its live delivery transport.-- A concrete native adapter always wins. Relay is eligible only when its- authenticated transport explicitly advertises that it fronts the logical- platform, so restart-time delivery is independent of per-chat caches without- letting Relay hijack unrelated platform targets.- """+def resolve_delivery_transport(platform: Platform, config: GatewayConfig,+ adapters: Optional[Dict[Platform, Any]]) -> Optional[DeliveryTransport]:+ """Resolve a logical platform to its live delivery transport. A concrete native adapter always wins;+ Relay is eligible only when its authenticated transport explicitly advertises that it fronts the+ logical platform, so restart-time delivery is independent of per-chat caches without letting Relay+ hijack unrelated platform targets."""live_adapters = adapters or {}native = live_adapters.get(platform)native_config = config.platforms.get(platform)@@ -99,90 +73,40 @@ def resolve_delivery_transport(relay = live_adapters.get(Platform.RELAY)relay_config = config.platforms.get(Platform.RELAY)fronts_platform = getattr(relay, "fronts_platform", None)- if (- relay is not None- and (relay_config is None or relay_config.enabled)- and callable(fronts_platform)- and fronts_platform(platform)- ):+ if (relay is not None and (relay_config is None or relay_config.enabled)+ and callable(fronts_platform) and fronts_platform(platform)):return DeliveryTransport(relay, relay_config, Platform.RELAY)return None-def _as_int(value: Any) -> Optional[int]:+def looks_like_telegram_private_chat_id(chat_id: Optional[str]) -> bool:+ """True when ``chat_id`` is a positive int — Telegram's private-chat shape (groups/channels are negative).+ Single source of truth, reused by the handoff seed path in ``gateway/run.py`` so handoff-created DM+ topics key the same way as inbound DM-topic messages."""try:- return int(value)+ return int(chat_id) > 0except (TypeError, ValueError):- return None---def looks_like_telegram_private_chat_id(chat_id: Optional[str]) -> bool:- """True when ``chat_id`` is a positive int — Telegram's private-chat shape.-- Groups/channels/supergroups use negative IDs. Single source of truth for the- heuristic, reused by the handoff seed path in ``gateway/run.py`` so- handoff-created DM topics key the same way as inbound DM-topic messages.- """- if chat_id is None:return False- parsed = _as_int(chat_id)- return parsed is not None and parsed > 0def _looks_like_int(value: Optional[str]) -> bool:- return value is not None and _as_int(value) is not None---def _result_field(result: Any, name: str, default: Any = None) -> Any:- """Read ``name`` from a SendResult object or a plain result dict."""- if isinstance(result, dict):- return result.get(name, default)- return getattr(result, name, default)---def _send_result_failed(result: Any) -> bool:- return _result_field(result, "success", True) is False+ try:+ return int(value) is not None+ except (TypeError, ValueError):+ return Falsedef _send_result_error(result: Any) -> Optional[str]:- error = _result_field(result, "error")- return str(error) if error else None---def _is_thread_not_found_delivery_error(result: Any) -> bool:- error = _send_result_error(result)- return bool(error and "thread not found" in error.lower())---def _classify_dead_from_error_text(error_text: Optional[str]) -> Optional[str]:- """Best-effort dead-target classification from a raised error's text.-- ``_deliver_to_platform`` raises on hard failure (no SendResult), so the- ``deliver()`` loop only has the exception string; reuse the platform-neutral- classifier to recover the error_kind from it.- """- if not error_text:- return None- try:- from .platforms.base import classify_send_error, is_chat_level_not_found- except Exception: # pragma: no cover - import guard+ """Error string of a failed SendResult object / plain result dict ("" if none), or None on success."""+ get = result.get if isinstance(result, dict) else (lambda name, default=None: getattr(result, name, default))+ if get("success", True) is not False:return None- kind = classify_send_error(None, error_text=error_text)- if not DeadTargetRegistry.is_dead_error_kind(kind):- return None- # ``not_found`` collapses chat-level and thread/topic/message-level failures.- # Only a whole-chat not_found means the target is dead — a deleted forum- # topic or an edited-away message must not mark the entire chat (and all its- # future deliveries) dead (see gateway.dead_targets).- if kind == "not_found" and not is_chat_level_not_found(error_text=error_text):- return None- return kind+ return str(get("error") or "")@dataclassclass DeliveryTarget:- """A single delivery target: "origin", "local", "telegram" (home channel),- or "telegram:123456[:thread]" (specific chat)."""+ """One target: "origin", "local", "telegram" (home channel) or "telegram:123456[:thread]"."""platform: Platformchat_id: Optional[str] = None # None means use home channelthread_id: Optional[str] = None@@ -192,38 +116,23 @@ class DeliveryTarget:@classmethoddef parse(cls, target: str, origin: Optional[SessionSource] = None) -> "DeliveryTarget":"""Parse "origin" | "local" | "<platform>" | "<platform>:<chat_id>[:<thread_id>]"."""- target_stripped = target.strip()- target_lower = target_stripped.lower()-+ target_stripped, target_lower = target.strip(), target.strip().lower()+ if target_lower == "origin" and origin:+ return cls(platform=origin.platform, chat_id=origin.chat_id, thread_id=origin.thread_id, is_origin=True)if target_lower == "origin":- if origin:- return cls(- platform=origin.platform,- chat_id=origin.chat_id,- thread_id=origin.thread_id,- is_origin=True,- )return cls(platform=Platform.LOCAL, is_origin=True)-if target_lower == "local":return cls(platform=Platform.LOCAL)-- # Platform names are case-insensitive; chat/thread ids keep original case.- # Unknown platforms are treated as local.- if ":" in target_stripped:- parts = target_stripped.split(":", 2)- chat_id = parts[1] if len(parts) > 1 else None- thread_id = parts[2] if len(parts) > 2 else None- try:- platform = Platform(parts[0].lower())- except ValueError:- return cls(platform=Platform.LOCAL)- return cls(platform=platform, chat_id=chat_id, thread_id=thread_id, is_explicit=True)-+ # Platform names are case-insensitive; chat/thread ids keep case. Unknown platforms -> local.+ parts = target_stripped.split(":", 2)try:- return cls(platform=Platform(target_lower))+ platform = Platform(parts[0].lower())except ValueError:return cls(platform=Platform.LOCAL)+ if len(parts) == 1:+ return cls(platform=platform)+ return cls(platform=platform, chat_id=parts[1],+ thread_id=parts[2] if len(parts) > 2 else None, is_explicit=True)def to_string(self) -> str:"""Convert back to string format."""@@ -231,23 +140,16 @@ class DeliveryTarget:return "origin"if self.platform == Platform.LOCAL:return "local"- if self.chat_id and self.thread_id:- return f"{self.platform.value}:{self.chat_id}:{self.thread_id}"- if self.chat_id:- return f"{self.platform.value}:{self.chat_id}"- return self.platform.value+ parts = [self.platform.value, self.chat_id, self.thread_id if self.chat_id else None]+ return ":".join(p for p in parts if p)async def _ensure_named_dm_topic(adapter: Any, chat_id: str, name: str, *, refresh: bool) -> str:"""Create (or force-recreate) a named Telegram private DM topic; return its thread id."""- verb = "refresh" if refresh else "create"- ensure_dm_topic = getattr(adapter, "ensure_dm_topic", None)+ verb, ensure_dm_topic = "refresh" if refresh else "create", getattr(adapter, "ensure_dm_topic", None)if ensure_dm_topic is None:raise RuntimeError(f"Telegram adapter cannot {verb} named private DM topics")- if refresh:- thread_id = await ensure_dm_topic(chat_id, name, force_create=True)- else:- thread_id = await ensure_dm_topic(chat_id, name)+ thread_id = await ensure_dm_topic(chat_id, name, **({"force_create": True} if refresh else {}))if not thread_id:raise RuntimeError(f"Failed to {verb} Telegram private DM topic '{name}'")return str(thread_id)@@ -257,251 +159,158 @@ class DeliveryRouter:"""Resolves delivery targets and dispatches messages to platform adapters."""def __init__(self, config: GatewayConfig, adapters: Dict[Platform, Any] = None,- dead_targets: Optional[DeadTargetRegistry] = None):- """``dead_targets``: shared registry of confirmed-unreachable targets;- a profile-local registry is created when omitted."""+ dead_targets: Optional[DeadTargetRegistry] = None): # profile-local registry when omittedself.config = configself.adapters = adapters or {}self.output_dir = get_hermes_home() / "cron" / "output"self.dead_targets = dead_targets or DeadTargetRegistry()- async def deliver(- self,- content: str,- targets: List[DeliveryTarget],- job_id: Optional[str] = None,- job_name: Optional[str] = None,- metadata: Optional[Dict[str, Any]] = None- ) -> Dict[str, Any]:+ async def deliver(self, content: str, targets: List[DeliveryTarget], job_id: Optional[str] = None,+ job_name: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:"""Deliver content to all targets; returns per-target results keyed by target string."""results = {}-for target in targets:- # Skip targets proven permanently unreachable (deleted group, blocked- # bot, deactivated user) — re-sending each tick wastes flood-control- # budget. Self-healing: a later successful send clears the flag.- # LOCAL/origin-without-chat targets are never dead-tracked.+ # Skip targets proven permanently unreachable (deleted group, blocked bot, deactivated user) —+ # re-sending each tick wastes flood-control budget. Self-healing: a later successful send+ # clears the flag. LOCAL/origin-without-chat targets are never dead-tracked.tracked = target.platform != Platform.LOCAL and target.chat_idif tracked and self.dead_targets.is_dead(target.platform.value, target.chat_id):- logger.info(- "Skipping delivery to known-dead target %s:%s "- "(send to it again to clear)",- target.platform.value, target.chat_id,- )- results[target.to_string()] = {- "success": False,- "skipped": "dead_target",- "error": "target previously confirmed unreachable",- }+ logger.info("Skipping delivery to known-dead target %s:%s (send to it again to clear)",+ target.platform.value, target.chat_id)+ results[target.to_string()] = {"success": False, "skipped": "dead_target",+ "error": "target previously confirmed unreachable"}continuetry:if target.platform == Platform.LOCAL:result = self._deliver_local(content, job_id, job_name, metadata)else:result = await self._deliver_to_platform(target, content, metadata)- if target.chat_id and not _send_result_failed(result):+ if target.chat_id and _send_result_error(result) is None:self.dead_targets.clear(target.platform.value, target.chat_id)results[target.to_string()] = {"success": True, "result": result}except Exception as e:- # Hard failures raise. Record a whole-chat death so future- # deliveries short-circuit.- if tracked:- dead_kind = _classify_dead_from_error_text(str(e))- if dead_kind:- self.dead_targets.mark_dead(- target.platform.value, target.chat_id,- reason=f"{dead_kind}: {str(e)[:120]}",- )+ # Hard failures raise. Record a whole-chat death so future deliveries short-circuit.+ dead_kind = classify_dead_error(str(e)) if tracked else None+ if dead_kind:+ self.dead_targets.mark_dead(target.platform.value, target.chat_id,+ reason=f"{dead_kind}: {str(e)[:120]}")results[target.to_string()] = {"success": False, "error": str(e)}-return results- def _deliver_local(- self,- content: str,- job_id: Optional[str],- job_name: Optional[str],- metadata: Optional[Dict[str, Any]]- ) -> Dict[str, Any]:+ def _deliver_local(self, content: str, job_id: Optional[str], job_name: Optional[str],+ metadata: Optional[Dict[str, Any]]) -> Dict[str, Any]:"""Save content to local files."""timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")output_path = self.output_dir / (job_id or "misc") / f"{timestamp}.md"output_path.parent.mkdir(parents=True, exist_ok=True)-- lines = [- f"# {job_name}" if job_name else "# Delivery Output",- "",- f"**Timestamp:** {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}",- ]- if job_id:- lines.append(f"**Job ID:** {job_id}")- for key, value in (metadata or {}).items():- lines.append(f"**{key}:** {value}")- lines += ["", "---", "", content]-+ lines = [f"# {job_name}" if job_name else "# Delivery Output", "",+ f"**Timestamp:** {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"]+ lines += [f"**Job ID:** {job_id}"] if job_id else []+ lines += [f"**{key}:** {value}" for key, value in (metadata or {}).items()] + ["", "---", "", content]output_path.write_text("\n".join(lines), encoding="utf-8")return {"path": str(output_path), "timestamp": timestamp}def _save_full_output(self, content: str, job_id: str) -> Path:"""Save full cron output to disk and return the file path."""timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")- out_dir = get_hermes_home() / "cron" / "output"- out_dir.mkdir(parents=True, exist_ok=True)- path = out_dir / f"{job_id}_{timestamp}.txt"+ path = get_hermes_home() / "cron" / "output" / f"{job_id}_{timestamp}.txt"+ path.parent.mkdir(parents=True, exist_ok=True)path.write_text(content, encoding="utf-8")return pathdef _filter_silence_narration_enabled(self) -> bool:- """``HERMES_FILTER_SILENCE_NARRATION`` env overrides the- ``gateway.filter_silence_narration`` config flag (default True)."""+ """``HERMES_FILTER_SILENCE_NARRATION`` env overrides the ``gateway.filter_silence_narration`` flag."""env = os.getenv("HERMES_FILTER_SILENCE_NARRATION")- if env is not None:- return env.strip().lower() in ("1", "true", "yes", "on")- return bool(getattr(self.config, "filter_silence_narration", True))+ if env is None:+ return bool(getattr(self.config, "filter_silence_narration", True))+ return env.strip().lower() in ("1", "true", "yes", "on")def _cap_oversized_output(self, adapter: Any, content: str, job_id: str) -> str:- """Audit-save oversized cron output; truncate it for non-chunking adapters.-- Two independent decisions: (1) above MAX_PLATFORM_OUTPUT the full output- is always written to disk as an audit trail, best-effort — a failed save- (full disk, permissions) never blocks delivery; (2) non-chunking adapters- get the content truncated with a footer pointing to the saved file, while- ``splits_long_messages`` adapters receive the full payload.- """+ """Audit-save oversized cron output; truncate it for non-chunking adapters. Above MAX_PLATFORM_OUTPUT+ the full output is always written to disk as an audit trail, best-effort — a failed save (full disk,+ permissions) never blocks delivery. Non-chunking adapters then get the content truncated with a+ footer pointing to the saved file; ``splits_long_messages`` adapters receive the full payload."""if len(content) <= MAX_PLATFORM_OUTPUT:return contentsaved_path: Optional[Path] = Nonetry:saved_path = self._save_full_output(content, job_id)except OSError as exc:- logger.warning(- "Audit save failed for cron output (%d chars, job=%s): %s — "- "delivery proceeds without audit copy",- len(content), job_id, exc,- )-+ logger.warning("Audit save failed for cron output (%d chars, job=%s): %s — "+ "delivery proceeds without audit copy", len(content), job_id, exc)if getattr(adapter, "splits_long_messages", False):if saved_path:- logger.info(- "Cron output preserved for chunking adapter (%d chars) — "- "full output saved to %s",- len(content), saved_path,- )+ logger.info("Cron output preserved for chunking adapter (%d chars) — "+ "full output saved to %s", len(content), saved_path)return content-# The footer needs a valid path: if the best-effort save failed, retry# (a failure now is a real delivery problem and propagates).if saved_path is None:saved_path = self._save_full_output(content, job_id)footer = f"\n\n... [truncated, full output saved to {saved_path}]"- visible = max(0, MAX_PLATFORM_OUTPUT - len(footer))- logger.info(- "Cron output truncated (%d chars) — full output: %s",- len(content), saved_path,- )- return content[:visible] + footer-- async def _deliver_to_platform(- self,- target: DeliveryTarget,- content: str,- metadata: Optional[Dict[str, Any]]- ) -> Dict[str, Any]:+ logger.info("Cron output truncated (%d chars) — full output: %s", len(content), saved_path)+ return content[:max(0, MAX_PLATFORM_OUTPUT - len(footer))] + footer++ async def _deliver_to_platform(self, target: DeliveryTarget, content: str,+ metadata: Optional[Dict[str, Any]]) -> Dict[str, Any]:"""Deliver content to a messaging platform."""transport = resolve_delivery_transport(target.platform, self.config, self.adapters)if transport is None:raise ValueError(f"No adapter configured for {target.platform.value}")- adapter = transport.adapter-if not target.chat_id:raise ValueError(f"No chat ID for {target.platform.value} delivery")-- content = self._cap_oversized_output(- adapter, content, (metadata or {}).get("job_id", "unknown")- )-- # Substrate-level anti-loop guard: drop hallucinated "silence narration"- # (*(silent)*, 🔇, a bare ".") before it reaches any adapter — in- # bot-to-bot channels these mirror back and forth until a model crashes- # with "no content after all retries"; prompt rules drift across- # providers, so this single chokepoint covers every platform. Local/file- # delivery is never filtered (saved silence has no loop risk).- # Cron output is an ARTIFACT, not model chatter: a legitimately terse job- # ("...", a single 🔇) has no mirror loop, and dropping it while returning- # success is how a cron gets logged as delivered with nothing on the- # wire. Cron sends carry job_id in metadata; everything else is filtered.+ adapter = transport.adapter+ content = self._cap_oversized_output(adapter, content, (metadata or {}).get("job_id", "unknown"))++ # Substrate-level anti-loop guard: drop hallucinated "silence narration" (*(silent)*, 🔇, a bare ".")+ # before it reaches any adapter — in bot-to-bot channels these mirror back and forth until a model+ # crashes with "no content after all retries"; prompt rules drift across providers, so this single+ # chokepoint covers every platform. Local/file delivery is never filtered (saved silence has no loop+ # risk). Cron output is an ARTIFACT, not model chatter: a legitimately terse job ("...", a single 🔇)+ # has no mirror loop, and dropping it while returning success is how a cron gets logged as delivered+ # with nothing on the wire. Cron sends carry job_id in metadata; everything else is filtered.is_cron_artifact = "job_id" in (metadata or {})- if (- self._filter_silence_narration_enabled()- and not is_cron_artifact- and _is_silence_narration(content)- ):- logger.warning(- "Dropped silence-narration outbound to %s (chat=%s): %r",- target.platform.value,- target.chat_id,- content[:40],- )- return {- "success": True,- "filtered": "silence_narration",- "delivered": False,- }+ if self._filter_silence_narration_enabled() and not is_cron_artifact and _is_silence_narration(content):+ logger.warning("Dropped silence-narration outbound to %s (chat=%s): %r",+ target.platform.value, target.chat_id, content[:40])+ return {"success": True, "filtered": "silence_narration", "delivered": False}send_metadata = dict(metadata or {})if transport.is_relay:home = self.config.get_home_channel(target.platform)if home is not None and home.chat_id == target.chat_id:- if home.user_id:- send_metadata["user_id"] = home.user_id- if home.scope_id:- send_metadata["scope_id"] = home.scope_id+ send_metadata.update({k: v for k, v in (("user_id", home.user_id), ("scope_id", home.scope_id)) if v})# Caller-supplied thread routing always wins over target.thread_id.named_telegram_private_topic_name: Optional[str] = Nonethread_id = target.thread_id- thread_unrouted = thread_id and not any(- key in send_metadata- for key in ("thread_id", "message_thread_id",- "direct_messages_topic_id", "telegram_direct_messages_topic_id")- )- if thread_unrouted:- is_telegram_private = (- target.platform == Platform.TELEGRAM- and looks_like_telegram_private_chat_id(target.chat_id)- )+ if thread_id and not any(key in send_metadata for key in _THREAD_ROUTING_KEYS):+ is_telegram_private = target.platform == Platform.TELEGRAM and looks_like_telegram_private_chat_id(target.chat_id)+ send_metadata["thread_id"] = thread_idif is_telegram_private and not _looks_like_int(thread_id):# Named topic: create via createForumTopic, use message_thread_id directly.named_telegram_private_topic_name = thread_id- send_metadata["thread_id"] = await _ensure_named_dm_topic(- adapter, target.chat_id, thread_id, refresh=False- )+ send_metadata["thread_id"] = await _ensure_named_dm_topic(adapter, target.chat_id, thread_id, refresh=False)send_metadata["telegram_dm_topic_created_for_send"] = Trueelif is_telegram_private:- # Legacy numeric private topic ids not created by this send path- # need a reply anchor to stay visible in the requested lane.+ # Legacy numeric private topic ids not created by this send path need a reply+ # anchor to stay visible in the requested lane.if send_metadata.get("telegram_reply_to_message_id") is None:raise RuntimeError("Telegram private DM topic delivery requires telegram_reply_to_message_id; ""send to the bare chat or provide a reply anchor")- send_metadata["thread_id"] = thread_idsend_metadata["telegram_dm_topic_reply_fallback"] = True- else:- send_metadata["thread_id"] = thread_id-- result = await transport.send(- target.platform, target.chat_id, content, metadata=send_metadata or None,- )- if _send_result_failed(result):- if named_telegram_private_topic_name and _is_thread_not_found_delivery_error(result):- send_metadata["thread_id"] = await _ensure_named_dm_topic(- adapter, target.chat_id, named_telegram_private_topic_name, refresh=True- )- send_metadata["telegram_dm_topic_created_for_send"] = True- result = await transport.send(- target.platform, target.chat_id, content, metadata=send_metadata or None,- )- if _send_result_failed(result):- raise RuntimeError(_send_result_error(result) or f"{target.platform.value} delivery failed")++ result = await transport.send(target.platform, target.chat_id, content, metadata=send_metadata or None)+ error = _send_result_error(result)+ if error is not None and named_telegram_private_topic_name and "thread not found" in error.lower():+ send_metadata["thread_id"] = await _ensure_named_dm_topic(+ adapter, target.chat_id, named_telegram_private_topic_name, refresh=True+ )+ send_metadata["telegram_dm_topic_created_for_send"] = True+ result = await transport.send(target.platform, target.chat_id, content, metadata=send_metadata or None)+ error = _send_result_error(result)+ if error is not None:+ raise RuntimeError(error or f"{target.platform.value} delivery failed")return resultdiff --git a/gateway/delivery_ledger.py b/gateway/delivery_ledger.pyindex 7d5fa26d646..db65b5bfe17 100644--- a/gateway/delivery_ledger.py+++ b/gateway/delivery_ledger.py@@ -1,37 +1,13 @@-"""Durable delivery-obligation ledger for gateway final responses.--A final agent response generated but not yet confirmed-delivered is the one-artifact the gateway can lose without a trace: the turn already burned its-tokens, the text exists only in a Python local, and a crash / restart between-finalize and platform ACK drops it silently.--Each outbound final response gets a small durable row in the shared ``state.db``-(same conventions as ``tools.async_delegation`` — WAL, owner pid + process-start-liveness, bounded retention). The gateway writes three checkpoints:-- record_obligation() state='pending' before any send attempt- mark_attempting() state='attempting' immediately before the await- mark_delivered() / state='delivered' only on SendResult.success- mark_failed() state='failed' on a definitive rejection--On startup ``sweep_recoverable()`` claims rows whose owner is dead and hands-them back for redelivery. After an adapter reconnects without a restart,-``sweep_failed_for_runtime()`` may claim only the same live process's-allowlisted transient failures. Crash semantics are explicit about ambiguity-(never silently resend an ambiguous send):--- ``pending`` — send never started: redeliver plainly, no dup risk.-- ``attempting`` — crashed mid-await: the platform MAY already have it.- Redelivered WITH a visible recovered-reply marker (honest at-least-once).-- ``failed`` — definitively rejected once; restart is a natural retry- boundary. Also carries the marker.-- ``delivered`` — nothing to do; retention prunes.--Poison rows cannot spin: attempts are capped and stale rows expire, both-transitioning to ``abandoned`` (kept briefly, then pruned).--Everything here is best-effort: ledger failures must never block or delay an-actual send. Callers wrap every call in try/except.+"""Durable delivery-obligation ledger for gateway final responses (rows in the shared ``state.db``;+WAL, owner pid + process-start liveness, bounded retention) so a crash between finalize and+platform ACK cannot lose a response silently. Checkpoints: record_obligation() 'pending' before+any send | mark_attempting() 'attempting' right before the await | mark_delivered() 'delivered'+only on SendResult.success | mark_failed() 'failed' on a definitive rejection. Crash semantics+(never silently resend an ambiguous send): pending = never started, redeliver plainly; attempting+= crashed mid-await, platform MAY have it, redeliver WITH a visible recovered marker; failed =+rejected once, restart is a retry boundary, also marked; delivered = prune. Attempts are capped+and stale rows expire, both -> 'abandoned' (kept briefly, then pruned). Everything is+best-effort: ledger failures must never block a send; callers wrap every call in try/except."""from __future__ import annotations@@ -48,7 +24,6 @@ from typing import Any, Dict, Iterator, List, Optionalfrom hermes_constants import get_hermes_homelogger = logging.getLogger(__name__)-_DB_LOCK = threading.Lock()# Redelivery policy knobs (deliberately not config — the ledger is gated by@@ -58,23 +33,15 @@ STALE_AFTER_SECONDS = 24 * 60 * 60_RETENTION_SECONDS = 7 * 24 * 60 * 60_MAX_ROWS = 500-# Visible prefix for redeliveries that might duplicate an already-received-# message (crash mid-send / post-rejection retry). Honest at-least-once.-RECOVERED_MARKER = (- "♻️ Recovered reply — the gateway restarted during delivery, "- "so this may be a duplicate:\n\n"-)--# Runtime recovery uses a distinct marker: no restart occurred, but a network-# rejection's acknowledgement can still have been lost independently.-RECONNECTED_MARKER = (- "♻️ Recovered reply — the messaging platform reconnected after the original "- "delivery failed, so this may be a duplicate:\n\n"-)--# Runtime replay is fail-closed: only errors whose send contract proves they are-# transient reconnect failures. Permanent rejects (blocked bot, bad auth, missing-# chat) must not be retried merely because an adapter reconnected.+# Visible prefixes for redeliveries that might duplicate an already-received message (crash mid-send /+# post-rejection retry) — honest at-least-once. Runtime recovery uses a distinct marker: no restart+# occurred, but a network rejection's acknowledgement can still have been lost independently.+RECOVERED_MARKER = "♻️ Recovered reply — the gateway restarted during delivery, so this may be a duplicate:\n\n"+RECONNECTED_MARKER = ("♻️ Recovered reply — the messaging platform reconnected after the original "+ "delivery failed, so this may be a duplicate:\n\n")++# Runtime replay is fail-closed: only errors whose send contract proves they are transient reconnect+# failures. Permanent rejects (blocked bot, bad auth, missing chat) must not be retried on reconnect._RUNTIME_RETRYABLE_ERRORS = frozenset({"send_path_degraded"})@@ -89,15 +56,13 @@ def _connect() -> sqlite3.Connection:try:_initialize_schema(conn)except Exception:- # A PRAGMA/DDL failure after connect() must not leak the connection.- conn.close()+ conn.close() # a PRAGMA/DDL failure after connect() must not leak the connectionraisereturn conndef _initialize_schema(conn: sqlite3.Connection) -> None:from hermes_state import apply_wal_with_fallback-apply_wal_with_fallback(conn, db_label="state.db (delivery_ledger)")conn.execute("""CREATE TABLE IF NOT EXISTS delivery_obligations (@@ -129,13 +94,9 @@ def _initialize_schema(conn: sqlite3.Connection) -> None:@contextmanagerdef _transaction() -> Iterator[sqlite3.Connection]:- """Open a connection, commit/rollback on exit, and ALWAYS close it.-- ``sqlite3.Connection`` as a context manager only commits/rolls back; it does- not close. ``with _connect()`` alone would leak a connection (and its WAL/SHM- fds) per call until GC — ``record_obligation`` runs on every outbound final- response, so this ledger would exhaust ``RLIMIT_NOFILE`` on a long-running gateway.- """+ """Open a connection, commit/rollback on exit, and ALWAYS close it: ``sqlite3.Connection`` as a+ context manager only commits/rolls back, so ``with _connect()`` alone leaks a connection (and its+ WAL/SHM fds) per call — ``record_obligation`` runs on every final response; exhausts RLIMIT_NOFILE."""conn = _connect()try:with conn:@@ -148,7 +109,6 @@ def _owner_stamp() -> tuple[int, Optional[int]]:pid = os.getpid()try:from gateway.status import get_process_start_time-return pid, get_process_start_time(pid)except Exception:return pid, None@@ -164,16 +124,14 @@ def _owner_alive(pid: Any, started_at: Any) -> bool:return Falsetry:from gateway.status import get_process_start_time-current_start = get_process_start_time(pid)except Exception:current_start = Noneif current_start is None:- # Start time unreadable: alive iff the pid exists. Route through the- # cross-platform probe — ``os.kill(pid, 0)`` on Windows is NOT a no-op- # (bpo-14484: it maps to ``GenerateConsoleCtrlEvent(0, pid)`` and could- # Ctrl+C the gateway's own console group). ``_pid_exists`` keeps the- # EPERM-means-alive semantics (pid exists but is owned by another user).+ # Start time unreadable: alive iff the pid exists. Route through the cross-platform probe —+ # ``os.kill(pid, 0)`` on Windows is NOT a no-op (bpo-14484: it maps to+ # ``GenerateConsoleCtrlEvent(0, pid)`` and could Ctrl+C the gateway's own console group).+ # ``_pid_exists`` keeps EPERM-means-alive semantics (pid exists, owned by another user).try:from gateway.status import _pid_existsexcept Exception:@@ -181,46 +139,31 @@ def _owner_alive(pid: Any, started_at: Any) -> bool:return False # never fall back to a raw sig-0 probe on Windowstry:os.kill(pid, 0) # windows-footgun: ok — POSIX-only fallback branch- except ProcessLookupError:- return Falseexcept PermissionError:return True- except OSError:+ except OSError: # incl. ProcessLookupErrorreturn Falsereturn Truetry:return bool(_pid_exists(pid))except Exception:return False- if started_at is None:- return Truetry:- return int(current_start) == int(started_at)+ return started_at is None or int(current_start) == int(started_at)except (TypeError, ValueError):return Truedef compute_obligation_id(session_key: str, message_ref: str, content: str) -> str:- """Stable id: same turn + same content re-records idempotently, while distinct- threads/topics on one chat never collide (session_key carries platform, chat and- thread; ``message_ref`` is the triggering inbound message id)."""- payload = f"{session_key}|{message_ref}|{content}"- return hashlib.sha256(payload.encode("utf-8", "replace")).hexdigest()[:24]---def record_obligation(- *,- obligation_id: str,- session_key: str,- platform: str,- chat_id: str,- thread_id: Optional[str],- content: str,- adapter_profile: Optional[str] = None,-) -> None:+ """Stable id: same turn + same content re-records idempotently, while distinct threads/topics on one+ chat never collide (session_key carries platform/chat/thread; ``message_ref`` = inbound message id)."""+ return hashlib.sha256(f"{session_key}|{message_ref}|{content}".encode("utf-8", "replace")).hexdigest()[:24]+++def record_obligation(*, obligation_id: str, session_key: str, platform: str, chat_id: str,+ thread_id: Optional[str], content: str, adapter_profile: Optional[str] = None) -> None:"""Record a final response as owed to the platform (state='pending')."""now = time.time()- stored_profile = str(adapter_profile).strip() if adapter_profile else "default"pid, started = _owner_stamp()with _DB_LOCK, _transaction() as conn:conn.execute(@@ -229,9 +172,8 @@ def record_obligation(content, state, attempts, created_at, updated_at,owner_pid, owner_started_at, adapter_profile)VALUES (?, ?, ?, ?, ?, ?, 'pending', 0, ?, ?, ?, ?, ?)""",- (obligation_id, session_key, platform, str(chat_id),- str(thread_id) if thread_id else None, content, now, now,- pid, started, stored_profile),+ (obligation_id, session_key, platform, str(chat_id), str(thread_id) if thread_id else None,+ content, now, now, pid, started, str(adapter_profile).strip() if adapter_profile else "default"),)_prune()@@ -251,11 +193,9 @@ def mark_failed(obligation_id: str, error: str = "") -> None:def release_runtime_claim(obligation_id: str, error: str = "") -> bool:"""Return an unsent runtime claim to ``failed`` without spending an attempt.- Runtime recovery claims before clearing ``resume_pending`` so two reconnect- paths cannot send the same row. If the session flag cannot be cleared, no- send was attempted and the claim must not consume the redelivery budget.- Fail-closed to the exact current process instance and ``attempting`` state.- """+ Runtime recovery claims before clearing ``resume_pending`` so two reconnect paths cannot send the+ same row; if the flag cannot be cleared no send was attempted and the claim must not consume the+ redelivery budget. Fail-closed to the exact current process instance and ``attempting`` state."""pid, started = _owner_stamp()if started is None:return False@@ -267,8 +207,7 @@ def release_runtime_claim(obligation_id: str, error: str = "") -> bool:updated_at=?, last_error=?WHERE obligation_id=? AND state='attempting'AND owner_pid IS ? AND owner_started_at IS ?""",- (time.time(), error[:500] if error else None,- obligation_id, pid, started),+ (time.time(), error[:500] if error else None, obligation_id, pid, started),)return bool(cursor.rowcount)@@ -287,29 +226,33 @@ def _exhausted(attempts: int, created_at: float, now: float) -> bool:return attempts >= MAX_ATTEMPTS or (now - created_at) > STALE_AFTER_SECONDS-def sweep_recoverable(- now: Optional[float] = None,- *,- deliverable_platforms: Optional[set] = None,- deliverable_targets: Optional[set] = None,-) -> List[Dict[str, Any]]:+def _claimed_row(oid, session_key, platform, chat_id, thread_id, content, attempts, profile, *,+ needs_marker: bool, runtime: bool = False) -> Dict[str, Any]:+ """Claimed-row dict handed back for redelivery; ``runtime`` adds the reconnect-marker fields."""+ row: Dict[str, Any] = {"obligation_id": oid, "session_key": session_key, "platform": platform,+ "chat_id": chat_id, "thread_id": thread_id, "content": content,+ "needs_marker": needs_marker}+ if runtime:+ row["marker"] = RECONNECTED_MARKER+ row["profile"] = profile+ if runtime:+ row["runtime_recovery"] = True+ row["attempts"] = attempts + 1+ return row+++def sweep_recoverable(now: Optional[float] = None, *, deliverable_platforms: Optional[set] = None,+ deliverable_targets: Optional[set] = None) -> List[Dict[str, Any]]:"""Claim undelivered rows owned by dead processes; return them for redelivery.- Claiming atomically re-stamps the owner to THIS process and increments- ``attempts`` (the UPDATE is guarded on the previous owner stamp, so a second- gateway racing the same sweep cannot double-claim). Rows over the attempts- cap or stale cutoff transition to 'abandoned' instead of being returned.-- ``deliverable_platforms`` restricts claiming to platforms the caller can- actually send on this boot: ``attempts`` is the redelivery budget and must- only be spent on a real send, else a platform that failed to connect burns- one attempt per boot and hits the cap having never been sent once. Rows for- absent platforms are left untouched (the stale cutoff still bounds them).-- ``deliverable_targets`` further scopes multiplexed gateways by exact- ``(platform, adapter_profile)`` so one connected bot cannot spend another- disconnected bot's retry budget.- """+ Claiming atomically re-stamps the owner to THIS process and increments ``attempts`` (the UPDATE is+ guarded on the previous owner stamp, so a second gateway racing the same sweep cannot double-claim).+ Rows over the attempts cap or stale cutoff become 'abandoned'. ``deliverable_platforms`` restricts+ claiming to platforms the caller can send on this boot: ``attempts`` is the redelivery budget and+ must only be spent on a real send, else a platform that failed to connect burns one attempt per boot+ and hits the cap having never been sent once (the stale cutoff still bounds untouched rows).+ ``deliverable_targets`` further scopes multiplexed gateways by exact ``(platform, adapter_profile)``+ so one connected bot cannot spend another disconnected bot's retry budget."""now = now if now is not None else time.time()pid, started = _owner_stamp()claimed: List[Dict[str, Any]] = []@@ -321,9 +264,8 @@ def sweep_recoverable(FROM delivery_obligationsWHERE state IN ('pending', 'attempting', 'failed')""").fetchall()- for (oid, session_key, platform, chat_id, thread_id, content, state,- attempts, created_at, owner_pid, owner_started_at,- adapter_profile) in rows:+ for (oid, session_key, platform, chat_id, thread_id, content, state, attempts, created_at,+ owner_pid, owner_started_at, adapter_profile) in rows:if _owner_alive(owner_pid, owner_started_at):continue # a live gateway still owns this rowif _exhausted(attempts, created_at, now):@@ -344,50 +286,28 @@ def sweep_recoverable(WHERE obligation_id=? AND (owner_pid IS ? OR owner_pid=?)""",(pid, started, now, oid, owner_pid, owner_pid),)- if cursor.rowcount:- claimed.append({- "obligation_id": oid,- "session_key": session_key,- "platform": platform,- "chat_id": chat_id,- "thread_id": thread_id,- "content": content,- # pending = never started, redeliver plainly; else carry marker.- "needs_marker": state != "pending",- "profile": adapter_profile,- "attempts": attempts + 1,- })+ if cursor.rowcount: # pending = never started, redeliver plainly; else carry marker+ claimed.append(_claimed_row(oid, session_key, platform, chat_id, thread_id, content, attempts,+ adapter_profile, needs_marker=state != "pending"))return claimed-def sweep_failed_for_runtime(- platform: str,- now: Optional[float] = None,- *,- profile: Optional[str] = None,-) -> List[Dict[str, Any]]:+def sweep_failed_for_runtime(platform: str, now: Optional[float] = None, *,+ profile: Optional[str] = None) -> List[Dict[str, Any]]:"""Claim this process's reconnect-retryable failed rows for one adapter.- ``profile`` scopes multiplexed gateways to the bot identity that owned the- failed send; ``None`` means the primary/default adapter. The persisted- adapter owner is independent of the routed session namespace. Unowned rows- and rows owned by another process are left for the startup/dead-owner sweep.-- Startup recovery ignores rows owned by a live gateway, so a final response- rejected with ``send_path_degraded`` would stay stranded when only the- adapter reconnects. This sweep closes that gap without weakening ownership:- only rows stamped to this exact process instance, only allowlisted transient- errors, same attempts/staleness bounds, every update guarded by the prior- owner stamp and ``failed`` state. Claimed rows always carry the reconnect- marker because the failed send's acknowledgement is not safe to infer.- """+ ``profile`` scopes multiplexed gateways to the bot identity that owned the failed send (``None`` =+ primary/default adapter); unowned rows and rows owned by another process are left for the+ startup/dead-owner sweep. Startup recovery ignores rows owned by a live gateway, so a response+ rejected with ``send_path_degraded`` would stay stranded when only the adapter reconnects; this closes+ that gap without weakening ownership: only rows stamped to this exact process instance, only+ allowlisted transient errors, same attempts/staleness bounds, every update guarded by the prior owner+ stamp and ``failed`` state. Claimed rows always carry the reconnect marker (the failed send's ack is+ not safe to infer)."""now = now if now is not None else time.time()pid, started = _owner_stamp()- if started is None:- # PID alone cannot distinguish this process from a stale row left after- # PID reuse. Runtime replay is optional, so fail closed; startup- # recovery remains the durable fallback.- return []+ if started is None: # PID alone cannot distinguish this process from a stale row left after PID+ return [] # reuse; runtime replay is optional, so fail closed (startup recovery remains).expected_profile = "default" if not profile or profile == "default" else str(profile)claimed: List[Dict[str, Any]] = []with _DB_LOCK, _transaction() as conn:@@ -399,15 +319,11 @@ def sweep_failed_for_runtime(WHERE state='failed' AND platform=?""",(platform,),).fetchall()- for (oid, session_key, row_platform, chat_id, thread_id, content,- attempts, created_at, owner_pid, owner_started_at, last_error,- adapter_profile) in rows:- if adapter_profile != expected_profile:- continue+ for (oid, session_key, row_platform, chat_id, thread_id, content, attempts, created_at,+ owner_pid, owner_started_at, last_error, adapter_profile) in rows:# Exact process-start matching prevents PID reuse from stealing work.- if owner_pid != pid or owner_started_at != started:- continue- if str(last_error or "").strip().lower() not in _RUNTIME_RETRYABLE_ERRORS:+ if (adapter_profile != expected_profile or owner_pid != pid or owner_started_at != started+ or str(last_error or "").strip().lower() not in _RUNTIME_RETRYABLE_ERRORS):continueowner_guard = (oid, owner_pid, owner_started_at)if _exhausted(attempts, created_at, now):@@ -427,31 +343,19 @@ def sweep_failed_for_runtime((now, *owner_guard),)if cursor.rowcount:- claimed.append({- "obligation_id": oid,- "session_key": session_key,- "platform": row_platform,- "chat_id": chat_id,- "thread_id": thread_id,- "content": content,- "needs_marker": True,- "marker": RECONNECTED_MARKER,- "profile": adapter_profile,- "runtime_recovery": True,- "attempts": attempts + 1,- })+ claimed.append(_claimed_row(oid, session_key, row_platform, chat_id, thread_id, content,+ attempts, adapter_profile, needs_marker=True, runtime=True))return claimeddef _prune(now: Optional[float] = None) -> None:now = now if now is not None else time.time()- cutoff = now - _RETENTION_SECONDStry:with _transaction() as conn:conn.execute("""DELETE FROM delivery_obligationsWHERE state IN ('delivered', 'abandoned') AND updated_at < ?""",- (cutoff,),+ (now - _RETENTION_SECONDS,),)total = conn.execute("SELECT COUNT(*) FROM delivery_obligations").fetchone()[0]excess = max(0, total - _MAX_ROWS)@@ -476,10 +380,8 @@ def ledger_enabled(config: Optional[Dict[str, Any]] = None) -> bool:try:if config is None:from hermes_cli.config import load_config-config = load_config()- gw = config.get("gateway") or {}- value = gw.get("delivery_ledger", True)+ value = (config.get("gateway") or {}).get("delivery_ledger", True)if isinstance(value, str):return value.strip().lower() not in {"false", "0", "no", "off"}return bool(value)diff --git a/gateway/rich_sent_store.py b/gateway/rich_sent_store.pyindex ebd6a1a71af..74cdb981a4f 100644--- a/gateway/rich_sent_store.py+++ b/gateway/rich_sent_store.py@@ -1,13 +1,8 @@-"""Local index of text we've sent via ``sendRichMessage`` (Bot API 10.1).--Telegram does NOT echo a rich message's content back in ``reply_to_message``-(``.text``/``.caption`` empty, ``.api_kwargs`` None), so replies to rich sends-arrive with no quotable text. We remember ``message_id -> text`` at send time-and look it up by ``reply_to_id`` on inbound. This module is the single source-of truth for that index.--Best-effort and dependency-free: every operation swallows errors and degrades-to a no-op / ``None`` so it can never break a send or an inbound message.+"""Local index of text we've sent via ``sendRichMessage`` (Bot API 10.1). Telegram does NOT echo a rich+message's content back in ``reply_to_message`` (``.text``/``.caption`` empty, ``.api_kwargs`` None), so+replies to rich sends arrive with no quotable text; we remember ``message_id -> text`` at send time and+look it up by ``reply_to_id`` on inbound. Best-effort and dependency-free: every operation swallows+errors and degrades to a no-op / ``None`` so it can never break a send or an inbound message."""from __future__ import annotations@@ -22,16 +17,10 @@ _MAX_TEXT_CHARS = 2000def _store_path() -> str:- # get_hermes_home() honors the active profile override.- from hermes_constants import get_hermes_home-+ from hermes_constants import get_hermes_home # honors the active profile overridereturn os.path.join(str(get_hermes_home()), "state", "rich_sent_index.json")-def _key(chat_id, message_id) -> str:- return f"{chat_id}:{message_id}"--def _load(path: str) -> dict:try:with open(path, "r", encoding="utf-8") as fh:@@ -49,7 +38,7 @@ def record(chat_id, message_id, text: Optional[str]) -> None:try:os.makedirs(os.path.dirname(path), exist_ok=True)data = _load(path)- data[_key(chat_id, message_id)] = {"t": text[:_MAX_TEXT_CHARS], "ts": int(time.time())}+ data[f"{chat_id}:{message_id}"] = {"t": text[:_MAX_TEXT_CHARS], "ts": int(time.time())}if len(data) > _MAX_ENTRIES: # trim oldest by timestampby_age = sorted(data.items(), key=lambda kv: kv[1].get("ts", 0))for k, _ in by_age[: len(data) - _MAX_ENTRIES]:@@ -66,5 +55,5 @@ def lookup(chat_id, message_id) -> Optional[str]:"""Return stored text for ``(chat_id, message_id)`` or ``None``."""if message_id is None or chat_id is None:return None- entry = _load(_store_path()).get(_key(chat_id, message_id))+ entry = _load(_store_path()).get(f"{chat_id}:{message_id}")return (entry.get("t") or None) if isinstance(entry, dict) else None