From fad62f9ee3956b24e2a5ea242951e12952746180 Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Wed, 2 Sep 2026 21:53:17 -0700 Subject: [PATCH 01/13] =?UTF-8?q?refactor(gateway/platforms):=20base.py=20?= =?UTF-8?q?=E2=80=94=20contextlib.suppress=20for=20pass-only=20handlers,?= =?UTF-8?q?=20=5For=5Fdefault/=5Fresolve=5Fpath=20helpers,=20unify=20sessi?= =?UTF-8?q?on=20task=20tracking?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- gateway/platforms/base.py | 233 ++++++++++++++------------------------ 1 file changed, 87 insertions(+), 146 deletions(-) diff --git a/gateway/platforms/base.py b/gateway/platforms/base.py index befc5905a9..8251ae57d9 100644 --- a/gateway/platforms/base.py +++ b/gateway/platforms/base.py @@ -1,6 +1,7 @@ """Base platform adapter interface; every platform adapter inherits from BasePlatformAdapter.""" import asyncio +import contextlib import inspect import ipaddress import logging @@ -68,10 +69,8 @@ def transcode_to_ogg_opus(path: str, *, bitrate: str = "32k") -> "str | None": return ogg_path except Exception: logger.debug("voice transcode to Ogg/Opus failed for %s", path, exc_info=True) - try: + with contextlib.suppress(OSError): os.unlink(ogg_path) - except OSError: - pass return None _POST_DELIVERY_CALLBACK_TIMEOUT_SECONDS = 30.0 # Delivery-time history is best-effort dedup metadata: stay well below the Discord heartbeat @@ -89,12 +88,17 @@ def _platform_name(platform) -> str: return str(value or "").lower() +def _or_default(thunk, default, exc=(TypeError, ValueError)): + """``thunk()``, or ``default`` when it raises one of ``exc`` (numeric config/env coercion).""" + try: + return thunk() + except exc: + return default + + def _float_env(name: str, default: float) -> float: raw = os.environ.get(name, "").strip() - try: - return float(raw) if raw else default - except (TypeError, ValueError): - return default + return _or_default(lambda: float(raw) if raw else default, default) def _thread_metadata_for_source(source, reply_to_message_id: str | None = None) -> dict | None: @@ -216,13 +220,11 @@ def _prefix_within_utf16_limit(s: str, limit: int) -> str: def is_network_accessible(host: str) -> bool: """True if *host* would expose the server beyond loopback (incl. IPv4-mapped ::ffff:127.0.0.1); hostnames are resolved and DNS failure fails closed (True).""" - try: + with contextlib.suppress(ValueError): # ValueError: hostname — resolve below addr = ipaddress.ip_address(host) # ::ffff:127.0.0.1 reports is_loopback=False; check the mapped IPv4 explicitly. mapped = getattr(addr, "ipv4_mapped", None) return not (addr.is_loopback or (mapped and mapped.is_loopback)) - except ValueError: - pass # hostname — resolve below try: resolved = _socket.getaddrinfo(host, None, _socket.AF_UNSPEC, _socket.SOCK_STREAM) # Network-accessible if any resolved address is non-loopback. @@ -291,9 +293,7 @@ def _no_proxy_entry_matches(entry: str, host: str, port: int | None = None) -> b if token == "*": return True token_host, token_port = _split_host_port(token) - if token_port is not None and (port is None or token_port != port): - return False - if not token_host: + if not token_host or (token_port is not None and (port is None or token_port != port)): return False host_ip = _ip_or_none(host) network = _ip_or_none(token_host, lambda v: ipaddress.ip_network(v, strict=False)) @@ -431,8 +431,7 @@ from pathlib import Path from typing import TYPE_CHECKING, Dict, List, Optional, Any, Callable, Awaitable, Tuple, Union from enum import Enum -from pathlib import Path as _Path -sys.path.insert(0, str(_Path(__file__).resolve().parents[2])) +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) from gateway.config import Platform, PlatformConfig from gateway.platforms.helpers import fence_state_after @@ -505,9 +504,7 @@ def safe_url_for_log(url: str, max_len: int = 80) -> str: safe = f"{parsed.scheme}://{parsed.netloc.rsplit('@', 1)[-1]}{tail}" if len(safe) <= max_len: return safe - if max_len <= 3: - return "." * max_len - return f"{safe[:max_len - 3]}..." + return "." * max_len if max_len <= 3 else f"{safe[:max_len - 3]}..." async def _ssrf_redirect_guard(response): @@ -545,10 +542,9 @@ DEFAULT_INBOUND_MEDIA_MAX_BYTES = 128 * 1024 * 1024 def get_inbound_media_max_bytes() -> int: """Max inbound media bytes held in memory (``gateway.max_inbound_media_bytes``); ``0`` / negative / unparseable disables the cap; unreadable config → default.""" - try: - return int(_config_section("gateway")["max_inbound_media_bytes"]) - except (KeyError, TypeError, ValueError): - return DEFAULT_INBOUND_MEDIA_MAX_BYTES + return _or_default( + lambda: int(_config_section("gateway")["max_inbound_media_bytes"]), + DEFAULT_INBOUND_MEDIA_MAX_BYTES, (KeyError, TypeError, ValueError)) def validate_inbound_media_size( @@ -601,9 +597,7 @@ get_image_cache_dir, cleanup_image_cache = _cache_dir_accessors( def _looks_like_image(data: bytes) -> bool: """Return True if *data* starts with a known image magic-byte sequence.""" - if len(data) < 4: - return False - return ( + return len(data) >= 4 and ( data[:8] == b"\x89PNG\r\n\x1a\n" or data[:3] == b"\xff\xd8\xff" or data[:6] in {b"GIF87a", b"GIF89a"} @@ -674,11 +668,9 @@ def _cleanup_cache_dir(cache_dir: Path, max_age_hours: int) -> int: removed = 0 for f in cache_dir.iterdir(): if f.is_file() and f.stat().st_mtime < cutoff: - try: + with contextlib.suppress(OSError): f.unlink() removed += 1 - except OSError: - pass return removed @@ -826,10 +818,8 @@ def _media_delivery_recency_seconds() -> float: if raw in ("0", "false", "no", "off", ""): return 0.0 custom = os.environ.get(MEDIA_DELIVERY_TRUST_RECENT_SECONDS_ENV, "").strip() - try: - return max(0.0, float(custom)) if custom else float(_MEDIA_DELIVERY_TRUST_RECENT_DEFAULT_SECONDS) - except (TypeError, ValueError): - return float(_MEDIA_DELIVERY_TRUST_RECENT_DEFAULT_SECONDS) + default = float(_MEDIA_DELIVERY_TRUST_RECENT_DEFAULT_SECONDS) + return _or_default(lambda: max(0.0, float(custom)) if custom else default, default) def _media_delivery_denied_paths() -> List[Path]: @@ -842,19 +832,24 @@ def _media_delivery_denied_paths() -> List[Path]: return denied +def _resolve_path(path: Path, *, strict: bool = False, expand: bool = False) -> Optional[Path]: + """``path[.expanduser()].resolve(strict)`` or None when it fails (OSError / RuntimeError / + ValueError — embedded NUL, symlink loop, undeterminable home, missing file under ``strict``).""" + try: + return (path.expanduser() if expand else path).resolve(strict=strict) + except (OSError, RuntimeError, ValueError): + return None + + def _path_under_denied_prefix(resolved: Path) -> bool: """True if ``resolved`` lives under a deny-listed system path — except a denied prefix that IS the running user's own home: ``/root`` is listed so a non-root gateway can't deliver another user's home, but a root-run gateway's own deliverables live under ``$HOME=/root``. Credential sub-dirs (``~/.ssh``, ``~/.hermes/.env``) stay blocked (more-specific entries).""" - try: - home = Path(os.path.expanduser("~")).resolve(strict=False) - except (OSError, RuntimeError, ValueError): - home = None + home = _resolve_path(Path(os.path.expanduser("~"))) for denied in _media_delivery_denied_paths(): - try: - resolved_denied = denied.expanduser().resolve(strict=False) - except (OSError, RuntimeError, ValueError): + resolved_denied = _resolve_path(denied, expand=True) + if resolved_denied is None: continue hit = resolved == resolved_denied or _path_is_within(resolved, resolved_denied) if hit and resolved_denied != home: @@ -868,18 +863,16 @@ def _file_is_recently_produced(resolved: Path, window_seconds: float) -> bool: if window_seconds <= 0: return False try: - mtime = resolved.stat().st_mtime + return (time.time() - resolved.stat().st_mtime) <= window_seconds except OSError: return False - return (time.time() - mtime) <= window_seconds def _path_is_within(path: Path, root: Path) -> bool: - try: + with contextlib.suppress(ValueError): path.relative_to(root) return True - except ValueError: - return False + return False def _tenv(name: str, default: str = "") -> str: @@ -916,12 +909,8 @@ def _parse_docker_volume_mounts() -> List[Tuple[Path, Path]]: host_expanded = os.path.expanduser(spec[:sep]) if not (host_expanded.startswith("/") or (len(host_expanded) > 1 and host_expanded[1] == ":")): continue - try: - host_path = Path(host_expanded).resolve(strict=False) - container_path = Path(container_raw) - except (OSError, RuntimeError, ValueError): - continue - if container_path.is_absolute(): + host_path, container_path = _resolve_path(Path(host_expanded)), Path(container_raw) + if host_path is not None and container_path.is_absolute(): mounts.append((host_path, container_path)) return mounts @@ -1029,11 +1018,9 @@ def _translate_docker_container_media_path(candidate: Path, session_key: str = " return None # In-process gateways (Desktop, `hermes serve`) may not have bridged terminal.* # config into TERMINAL_* env; run the idempotent bridge so mount parsing sees it. - try: + with contextlib.suppress(Exception): from tools.terminal_tool import _ensure_terminal_env_bridged _ensure_terminal_env_bridged() - except Exception: - pass mounts = [*_parse_docker_volume_mounts(), *_cache_dir_container_mounts()] mounted = {c.as_posix() for _, c in mounts} # Synthetic /workspace mounts: profile-scoped layout first, then legacy per-session. @@ -1091,19 +1078,13 @@ def validate_media_delivery_path(path: str, session_key: str = "") -> Optional[s # Docker agents emit MEDIA:/workspace/... — map container paths to host paths first. resolved = _translate_docker_container_media_path(expanded, session_key=session_key) if resolved is None: - try: - resolved = expanded.resolve(strict=True) - except (OSError, RuntimeError, ValueError): - return None - if not resolved.is_file(): + resolved = _resolve_path(expanded, strict=True) + if resolved is None or not resolved.is_file(): return None # Cache / operator allowlist is trusted unconditionally, regardless of mode. for root in _media_delivery_allowed_roots(): - try: - resolved_root = root.expanduser().resolve(strict=False) - except (OSError, RuntimeError, ValueError): - continue - if _path_is_within(resolved, resolved_root): + resolved_root = _resolve_path(root, expand=True) + if resolved_root is not None and _path_is_within(resolved, resolved_root): return str(resolved) # Non-strict (default): accept anything not denylisted — /etc, /proc, ~/.ssh, ~/.aws and the # Hermes-root secret stores stay rejected (MEDIA:/etc/passwd, MEDIA:~/.hermes/google_token.json) @@ -1359,12 +1340,12 @@ class CachedMedia: return f"[{self.kind} '{self.display_name}' saved at: {self.path}]" -# MIME -> extension reverse lookup; first match across image, video, document tables wins. -_MIME_TO_EXT: Dict[str, str] = {} -for _table in (SUPPORTED_IMAGE_DOCUMENT_TYPES, SUPPORTED_VIDEO_TYPES, SUPPORTED_DOCUMENT_TYPES): - for _ext, _mime in _table.items(): - _MIME_TO_EXT.setdefault(_mime, _ext) -del _table, _ext, _mime +# MIME -> extension reverse lookup; FIRST match across image, video, document tables wins +# (built in reverse so the earliest extension is the one that survives). +_MIME_TO_EXT: Dict[str, str] = { + mime: ext + for table in (SUPPORTED_DOCUMENT_TYPES, SUPPORTED_VIDEO_TYPES, SUPPORTED_IMAGE_DOCUMENT_TYPES) + for ext, mime in reversed(table.items())} def _resolve_media_ext(filename: str, mime_type: str) -> str: @@ -1534,7 +1515,7 @@ def coerce_plaintext_gateway_command(event: "MessageEvent") -> None: """Rewrite a tiny set of DM plaintext admin phrases into slash commands, keeping ``restart gateway`` out of the LLM/tool path (a self-restart from inside the running agent leaves the gateway stuck in ``draining`` waiting on that agent). Narrow: DM text, exact phrases only.""" - try: + with contextlib.suppress(Exception): if event is None or event.message_type != MessageType.TEXT: return text = (event.text or "").strip() @@ -1544,8 +1525,6 @@ def coerce_plaintext_gateway_command(event: "MessageEvent") -> None: return if any(pattern.match(text) for pattern in _PLAINTEXT_GATEWAY_RESTART_PATTERNS): event.text = "/restart" - except Exception: - return @dataclass @@ -1888,10 +1867,7 @@ class BasePlatformAdapter(ABC): """Per-chat max length in ``message_len_fn_for_chat`` units. Default: the adapter scalar ``MAX_MESSAGE_LENGTH`` (4096 when absent); the relay adapter overrides because one adapter fronts N platforms with different caps.""" - try: - return int(getattr(self, "MAX_MESSAGE_LENGTH", 4096) or 4096) - except (TypeError, ValueError): - return 4096 + return _or_default(lambda: int(getattr(self, "MAX_MESSAGE_LENGTH", 4096) or 4096), 4096) def message_len_fn_for_chat(self, chat_id: str) -> Callable[[str], int]: """Per-chat length function (companion to max_message_length_for_chat); the relay @@ -1998,28 +1974,16 @@ class BasePlatformAdapter(ABC): the preview's metadata (e.g. a URL shortened for display).""" return preview.text - @property - def has_fatal_error(self) -> bool: - return self._fatal_error_message is not None - - @property - def fatal_error_message(self) -> Optional[str]: - return self._fatal_error_message - - @property - def fatal_error_code(self) -> Optional[str]: - return self._fatal_error_code - - @property - def fatal_error_retryable(self) -> bool: - return self._fatal_error_retryable + has_fatal_error = property(lambda self: self._fatal_error_message is not None) + fatal_error_message = property(lambda self: self._fatal_error_message) + fatal_error_code = property(lambda self: self._fatal_error_code) + fatal_error_retryable = property(lambda self: self._fatal_error_retryable) def _should_auto_tts_for_chat(self, chat_id: str) -> bool: """Whether auto-TTS fires for ``chat_id``: explicit ``/voice on|tts`` wins, then explicit ``/voice off``, then the global ``voice.auto_tts`` default.""" - if chat_id in self._auto_tts_enabled_chats: - return True - return chat_id not in self._auto_tts_disabled_chats and bool(self._auto_tts_default) + return chat_id in self._auto_tts_enabled_chats or ( + chat_id not in self._auto_tts_disabled_chats and bool(self._auto_tts_default)) def set_fatal_error_handler(self, handler: Callable[["BasePlatformAdapter"], Awaitable[None] | None]) -> None: self._fatal_error_handler = handler @@ -2094,8 +2058,7 @@ class BasePlatformAdapter(ABC): acquired, existing = acquire_scoped_lock(scope, identity, metadata=lock_meta) if acquired: return True - if (bool(getattr(self, "_platform_lock_takeover_allowed", False)) - and not bool(getattr(self, "_platform_lock_takeover_attempted", False)) + if (self._platform_lock_takeover_allowed and not self._platform_lock_takeover_attempted and isinstance(existing, dict)): # Consume the authority before any I/O: one adapter connect gets at most one # termination attempt, even if lock re-acquire or later initialization fails. @@ -2371,9 +2334,8 @@ class BasePlatformAdapter(ABC): except BaseException as exc: error = exc try: - loop.call_soon_threadsafe(_publish_result, result, error) - except RuntimeError: - pass # Event loop already closed during gateway shutdown. + with contextlib.suppress(RuntimeError): # loop already closed (gateway shutdown) + loop.call_soon_threadsafe(_publish_result, result, error) finally: admission.release() try: @@ -2437,10 +2399,7 @@ class BasePlatformAdapter(ABC): def _get_ephemeral_system_ttl_default(self) -> int: """Default :class:`EphemeralReply` TTL from ``display.ephemeral_system_ttl`` (``0`` = no auto-delete); non-fatal if config is unreadable.""" - try: - return int(_config_section("display").get("ephemeral_system_ttl", 0)) - except (TypeError, ValueError): - return 0 + return _or_default(lambda: int(_config_section("display").get("ephemeral_system_ttl", 0)), 0) def _schedule_ephemeral_delete(self, chat_id: str, message_id: str, ttl_seconds: int) -> None: """Spawn a detached task that deletes ``message_id`` after ``ttl_seconds``; best-effort @@ -2952,10 +2911,9 @@ class BasePlatformAdapter(ABC): try: if typing_task is not None and not typing_task.done(): typing_task.cancel() - try: + # Slow adapter cleanup must not block delivery/shutdown. + with contextlib.suppress(asyncio.CancelledError, asyncio.TimeoutError): await asyncio.wait_for(asyncio.shield(typing_task), timeout=timeout) - except (asyncio.CancelledError, asyncio.TimeoutError): - pass # Cancelled; slow adapter cleanup must not block delivery/shutdown. if not hasattr(self, "stop_typing"): return for attempt in range(max(1, stop_attempts)): @@ -2967,10 +2925,8 @@ class BasePlatformAdapter(ABC): async def _stop_typing_quietly(self, chat_id: str, metadata=None) -> None: """Best-effort platform stop_typing; adapter errors are swallowed.""" - try: + with contextlib.suppress(Exception): await self._stop_typing_with_metadata(chat_id, metadata) - except Exception: - pass def pause_typing_for_chat(self, chat_id: str) -> None: """Pause typing for a chat (approval waits); GIL-safe from the sync agent thread.""" @@ -3105,10 +3061,7 @@ class BasePlatformAdapter(ABC): return response, 0 ttl = response.ttl_seconds if ttl is None: - try: - ttl = int(self._get_ephemeral_system_ttl_default()) - except Exception: - ttl = 0 + ttl = _or_default(lambda: int(self._get_ephemeral_system_ttl_default()), 0, Exception) if ttl and ttl > 0 and type(self).delete_message is BasePlatformAdapter.delete_message: ttl = 0 return response.text, int(ttl or 0) @@ -3148,9 +3101,8 @@ class BasePlatformAdapter(ABC): except Exception: logger.debug("[%s] Failed to resolve live adapter for final delivery", self.name) return self - if isinstance(live_adapter, BasePlatformAdapter) and live_adapter.platform == self.platform: - return live_adapter - return self + is_peer = isinstance(live_adapter, BasePlatformAdapter) and live_adapter.platform == self.platform + return live_adapter if is_peer else self async def _send_with_retry( self, chat_id: str, content: str, reply_to: Optional[str] = None, metadata: Any = None, @@ -3374,13 +3326,20 @@ class BasePlatformAdapter(ABC): guard = interrupt_event or asyncio.Event() self._active_sessions[session_key] = guard task = asyncio.create_task(self._process_message_background(event, session_key)) + if not self._track_session_task(session_key, task): + self._session_tasks.pop(session_key, None) + self._release_session_guard(session_key, guard=guard) + return False + return True + + def _track_session_task(self, session_key: str, task: Any) -> bool: + """Record ``task`` as the session owner and track it for shutdown; False when + ``create_task`` was stubbed with an unhashable sentinel (tests) — the owner entry + is left for the caller to roll back.""" self._session_tasks[session_key] = task try: self._background_tasks.add(task) except TypeError: - # Tests stub create_task() with unhashable sentinels lacking lifecycle callbacks. - self._session_tasks.pop(session_key, None) - self._release_session_guard(session_key, guard=guard) return False if hasattr(task, "add_done_callback"): task.add_done_callback(self._background_tasks.discard) @@ -3552,11 +3511,8 @@ class BasePlatformAdapter(ABC): return 0.0 if mode == "natural": return random.uniform(800 / 1000.0, 2500 / 1000.0) - def _ms(name: str, default: int) -> int: - try: - return int(os.getenv(name, str(default))) - except (TypeError, ValueError): - return default # custom mode tolerates malformed env vars + def _ms(name: str, default: int) -> int: # custom mode tolerates malformed env vars + return _or_default(lambda: int(os.getenv(name, str(default))), default) return random.uniform( _ms("HERMES_HUMAN_DELAY_MIN_MS", 800) / 1000.0, _ms("HERMES_HUMAN_DELAY_MAX_MS", 2500) / 1000.0) @@ -3851,12 +3807,10 @@ class BasePlatformAdapter(ABC): _post_cb = self.pop_post_delivery_callback( session_key, generation=getattr(interrupt_event, "_hermes_run_generation", None)) if callable(_post_cb): - try: + with contextlib.suppress(asyncio.TimeoutError, Exception): _post_result = _post_cb() if inspect.isawaitable(_post_result): await asyncio.wait_for(_post_result, timeout=_POST_DELIVERY_CALLBACK_TIMEOUT_SECONDS) - except (asyncio.TimeoutError, Exception): - pass def _finish_session_task(self, session_key: str, interrupt_event: asyncio.Event) -> None: """End-of-task guard/ownership reconciliation. A late ``_pending_messages`` @@ -3925,15 +3879,11 @@ class BasePlatformAdapter(ABC): event, text_content, _tts_path, _tts_index == 0, _final_thread_metadata, _record_delivery) finally: - try: + with contextlib.suppress(OSError): os.remove(_tts_path) - except OSError: - pass if not _tts_paths and _tts_requested_path is not None: - try: + with contextlib.suppress(OSError): os.remove(_tts_requested_path) - except OSError: - pass if text_content and not _tts_caption_delivered: await self._send_final_text( event, session_key, text_content, _final_thread_metadata, @@ -3997,13 +3947,8 @@ class BasePlatformAdapter(ABC): _active = self._active_sessions.get(session_key) if _active is not None: _active.clear() - drain_task = asyncio.create_task(self._process_message_background(pending_event, session_key)) - self._session_tasks[session_key] = drain_task - try: - self._background_tasks.add(drain_task) - drain_task.add_done_callback(self._background_tasks.discard) - except TypeError: - pass # Tests stub create_task() with non-hashable sentinels; tolerate. + self._track_session_task( + session_key, asyncio.create_task(self._process_message_background(pending_event, session_key))) def _cleanup_finished_session_task( self, session_key: str, interrupt_event: Optional[asyncio.Event]) -> None: @@ -4039,12 +3984,9 @@ class BasePlatformAdapter(ABC): self._background_tasks.clear() self._expected_cancelled_tasks.clear() self._session_tasks.clear() - # Flush pending messages to disk before clearing. - try: + with contextlib.suppress(Exception): # flush pending messages to disk before clearing from gateway.shutdown_flush import flush_pending_to_file flush_pending_to_file(self._pending_messages, reason="adapter_shutdown") - except Exception: - pass self._pending_messages.clear() self._active_sessions.clear() for state in list(self._text_debounce_store().values()): @@ -4185,6 +4127,5 @@ class BasePlatformAdapter(ABC): carry_lang = None chunks.append(full_chunk) if len(chunks) > 1: - total = len(chunks) - chunks = [f"{chunk} ({i + 1}/{total})" for i, chunk in enumerate(chunks)] + chunks = [f"{chunk} ({i + 1}/{len(chunks)})" for i, chunk in enumerate(chunks)] return chunks From bc1d02079e56f6bde163beb7a297b26b6936760e Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Wed, 2 Sep 2026 22:21:55 -0700 Subject: [PATCH 02/13] =?UTF-8?q?refactor(gateway/platforms):=20base.py=20?= =?UTF-8?q?=E2=80=94=20AST-neutral=20rewrap=20of=2057=20multi-line=20state?= =?UTF-8?q?ments/headers=20to=20PEP8=20aligned=20continuation?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- gateway/platforms/base.py | 328 +++++++++++++++----------------------- 1 file changed, 132 insertions(+), 196 deletions(-) diff --git a/gateway/platforms/base.py b/gateway/platforms/base.py index 8251ae57d9..af92a22cfa 100644 --- a/gateway/platforms/base.py +++ b/gateway/platforms/base.py @@ -239,9 +239,8 @@ def _detect_macos_system_proxy() -> str | None: if sys.platform != "darwin": return None try: - out = subprocess.check_output( - ["scutil", "--proxy"], timeout=3, text=True, encoding='utf-8', errors='replace', stderr=subprocess.DEVNULL, - ) + out = subprocess.check_output(["scutil", "--proxy"], timeout=3, text=True, encoding='utf-8', + errors='replace', stderr=subprocess.DEVNULL) except Exception: return None props = { @@ -356,9 +355,8 @@ def _aiohttp_socks_connector(proxy_url: str): return ProxyConnector.from_url(proxy_url, rdns=True) except ImportError: if proxy_url.lower().startswith("socks"): - logger.warning( - "aiohttp_socks not installed — SOCKS proxy %s ignored. " - "Run: pip install aiohttp-socks", proxy_url) + logger.warning("aiohttp_socks not installed — SOCKS proxy %s ignored. " + "Run: pip install aiohttp-socks", proxy_url) return None @@ -473,9 +471,8 @@ def streaming_tts_turn_key(session_key: str | None, turn_marker: Any = None, *, return None if turn_marker is None else f"{session_key}:{turn_marker}" -def streaming_tts_should_skip_whole_file( - completed_turns: set[str], session_key: str | None, turn_marker: Any = None, *, - event: Any = None) -> bool: +def streaming_tts_should_skip_whole_file(completed_turns: set[str], session_key: str | None, + turn_marker: Any = None, *, event: Any = None) -> bool: """Pure, turn-scoped auto-TTS suppression decision (testable without the adapter stack).""" turn_key = streaming_tts_turn_key(session_key, turn_marker, event=event) return bool(turn_key and turn_key in completed_turns) @@ -542,9 +539,8 @@ DEFAULT_INBOUND_MEDIA_MAX_BYTES = 128 * 1024 * 1024 def get_inbound_media_max_bytes() -> int: """Max inbound media bytes held in memory (``gateway.max_inbound_media_bytes``); ``0`` / negative / unparseable disables the cap; unreadable config → default.""" - return _or_default( - lambda: int(_config_section("gateway")["max_inbound_media_bytes"]), - DEFAULT_INBOUND_MEDIA_MAX_BYTES, (KeyError, TypeError, ValueError)) + return _or_default(lambda: int(_config_section("gateway")["max_inbound_media_bytes"]), + DEFAULT_INBOUND_MEDIA_MAX_BYTES, (KeyError, TypeError, ValueError)) def validate_inbound_media_size( @@ -597,12 +593,9 @@ get_image_cache_dir, cleanup_image_cache = _cache_dir_accessors( def _looks_like_image(data: bytes) -> bool: """Return True if *data* starts with a known image magic-byte sequence.""" - return len(data) >= 4 and ( - data[:8] == b"\x89PNG\r\n\x1a\n" - or data[:3] == b"\xff\xd8\xff" - or data[:6] in {b"GIF87a", b"GIF89a"} - or data[:2] == b"BM" - or (data[:4] == b"RIFF" and len(data) >= 12 and data[8:12] == b"WEBP")) + return len(data) >= 4 and (data[:8] == b"\x89PNG\r\n\x1a\n" or data[:3] == b"\xff\xd8\xff" + or data[:6] in {b"GIF87a", b"GIF89a"} or data[:2] == b"BM" + or (data[:4] == b"RIFF" and len(data) >= 12 and data[8:12] == b"WEBP")) def _write_cache_file(cache_dir: Path, prefix: str, ext: str, data: bytes) -> str: @@ -622,9 +615,8 @@ def cache_image_from_bytes(data: bytes, ext: str = ".jpg") -> str: return _write_cache_file(get_image_cache_dir(), "img", ext, data) -async def _cache_media_from_url( - url: str, ext: str, retries: int, *, media_type: str, accept: str, cache_fn, log_label: str, -) -> str: +async def _cache_media_from_url(url: str, ext: str, retries: int, *, media_type: str, accept: str, + cache_fn, log_label: str) -> str: """Shared downloader behind ``cache_image_from_url`` / ``cache_audio_from_url``: SSRF-checked (pre-flight + per-redirect; raises ValueError), size-capped, and retried with linear backoff on timeouts / 429 / 5xx.""" @@ -647,9 +639,8 @@ async def _cache_media_from_url( raise if attempt < retries: wait = 1.5 * (attempt + 1) - logger.debug( - "%s cache retry %d/%d for %s (%.1fs): %s", - log_label, attempt + 1, retries, safe_url_for_log(url), wait, exc) + logger.debug("%s cache retry %d/%d for %s (%.1fs): %s", log_label, attempt + 1, + retries, safe_url_for_log(url), wait, exc) await asyncio.sleep(wait) continue raise @@ -790,11 +781,10 @@ def _kanban_attachment_roots() -> List[Path]: roots = [root / "kanban" / "attachments"] boards_root = root / "kanban" / "boards" try: - board_dirs = [ - path for path in boards_root.iterdir() - if path.is_dir() and not path.is_symlink() - and re.fullmatch(r"[a-z0-9][a-z0-9_-]{0,63}", path.name) - and (path / "kanban.db").is_file()] + board_dirs = [path for path in boards_root.iterdir() + if path.is_dir() and not path.is_symlink() + and re.fullmatch(r"[a-z0-9][a-z0-9_-]{0,63}", path.name) + and (path / "kanban.db").is_file()] except OSError: return roots roots.extend(path / "attachments" for path in board_dirs) @@ -963,9 +953,8 @@ def _docker_persistent_sandbox_roots(session_key: str, leaf: str) -> List[Path]: try: from tools.environments.base import get_sandbox_dir base = get_sandbox_dir() / "docker" - return [ - cand for name in _docker_sandbox_dir_candidates(session_key) - if (cand := (base / name / leaf).resolve(strict=False)).is_dir()] + return [cand for name in _docker_sandbox_dir_candidates(session_key) + if (cand := (base / name / leaf).resolve(strict=False)).is_dir()] except Exception: return [] @@ -1002,12 +991,10 @@ def _warn_unresolved_docker_media(candidate: Path, session_key: str, reason: str the generic "Skipping unsafe MEDIA directive path" line). Docker-only; host rejections quiet.""" if not _docker_env_active(): return - logger.warning( - "Docker MEDIA path %s did not resolve to a host sandbox file (%s%s); " - "the producing container's sandbox directory may not exist yet or " - "was pruned", - _log_safe_path(str(candidate)), reason, - f", session_key={session_key}" if session_key else "") + logger.warning("Docker MEDIA path %s did not resolve to a host sandbox file (%s%s); " + "the producing container's sandbox directory may not exist yet or " + "was pruned", _log_safe_path(str(candidate)), reason, + f", session_key={session_key}" if session_key else "") def _translate_docker_container_media_path(candidate: Path, session_key: str = "") -> Optional[Path]: @@ -1354,9 +1341,8 @@ def _resolve_media_ext(filename: str, mime_type: str) -> str: return ext or _MIME_TO_EXT.get((mime_type or "").lower(), "") -def cache_media_bytes( - data: bytes, *, filename: str = "", mime_type: str = "", default_kind: Optional[str] = None, -) -> Optional[CachedMedia]: +def cache_media_bytes(data: bytes, *, filename: str = "", mime_type: str = "", + default_kind: Optional[str] = None) -> Optional[CachedMedia]: """Classify and cache raw attachment bytes; return a CachedMedia or None. ``default_kind`` biases classification when extension/MIME are ambiguous (Telegram native photo, no name). Anything not image/video/audio is a document; only images failing validation return None.""" @@ -1626,9 +1612,8 @@ class EphemeralReply(str): return str.__str__(self) -def merge_pending_message_event( - pending_messages: Dict[str, MessageEvent], session_key: str, event: MessageEvent, *, - merge_text: bool = False) -> None: +def merge_pending_message_event(pending_messages: Dict[str, MessageEvent], session_key: str, + event: MessageEvent, *, merge_text: bool = False) -> None: """Store or merge a pending event for a session: photo bursts/albums (several near-simultaneous PHOTO events) merge into the queued event so the next turn sees the whole burst; with ``merge_text``, rapid follow-up TEXT events are appended instead of replacing the turn.""" @@ -1667,9 +1652,7 @@ def merge_pending_message_event( if hasattr(existing, attr): delattr(existing, attr) return - if ( - merge_text - and getattr(existing, "message_type", None) == MessageType.TEXT + if (merge_text and getattr(existing, "message_type", None) == MessageType.TEXT and event.message_type == MessageType.TEXT): if event.text: existing.text = _append_text(existing.text, event.text) @@ -1915,9 +1898,8 @@ class BasePlatformAdapter(ABC): (Telegram Rich Messages: 32,768 vs 4,096). ``None`` = use ``MAX_MESSAGE_LENGTH``.""" return None - async def send_draft( - self, chat_id: str, draft_id: int, content: str, metadata: Optional[Dict[str, Any]] = None, - ) -> SendResult: + async def send_draft(self, chat_id: str, draft_id: int, content: str, + metadata: Optional[Dict[str, Any]] = None) -> SendResult: """Send or update an animated streaming-draft preview. Reuse one non-zero ``draft_id`` across a single response so the platform animates; @@ -2111,9 +2093,8 @@ class BasePlatformAdapter(ABC): factory(native, self) logger.info("[%s] Wired native handlers from plugin '%s'", self.name, plugin_name) except Exception as exc: - logger.error( - "[%s] Plugin '%s' handler factory raised: %s", - self.name, plugin_name, exc, exc_info=True) + logger.error("[%s] Plugin '%s' handler factory raised: %s", self.name, plugin_name, + exc, exc_info=True) @property def name(self) -> str: @@ -2180,10 +2161,9 @@ class BasePlatformAdapter(ABC): senders as unverified background rather than authoritative input.""" self._authorization_check = callback - def _is_sender_authorized( - self, user_id: Optional[str], chat_type: Optional[str] = None, - chat_id: Optional[str] = None, *, is_bot: bool = False, thread_id: Optional[str] = None, - ) -> Optional[bool]: + def _is_sender_authorized(self, user_id: Optional[str], chat_type: Optional[str] = None, + chat_id: Optional[str] = None, *, is_bot: bool = False, + thread_id: Optional[str] = None) -> Optional[bool]: """True/False from the registered check, or ``None`` when no check exists ("trust unknown", legacy). ``is_bot``/``thread_id`` are forwarded as keywords only when set so legacy three-positional callbacks keep working. Only literal booleans propagate: @@ -2197,14 +2177,12 @@ class BasePlatformAdapter(ABC): result = self._authorization_check(user_id, chat_type, chat_id, **extra) if result is True or result is False: return result - logger.warning( - "[%s] Authorization check returned %s for user %s; treating as unknown", - self.name, type(result).__name__, user_id) + logger.warning("[%s] Authorization check returned %s for user %s; treating as unknown", + self.name, type(result).__name__, user_id) return None except Exception: - logger.warning( - "[%s] Authorization check raised for user %s; treating as unknown", - self.name, user_id, exc_info=True) + logger.warning("[%s] Authorization check raised for user %s; treating as unknown", + self.name, user_id, exc_info=True) return None def set_session_store(self, session_store: Any) -> None: @@ -2367,9 +2345,8 @@ class BasePlatformAdapter(ABC): """Disconnect from the platform.""" @abstractmethod - async def send( - self, chat_id: str, content: str, reply_to: Optional[str] = None, - metadata: Optional[Dict[str, Any]] = None) -> SendResult: + async def send(self, chat_id: str, content: str, reply_to: Optional[str] = None, + metadata: Optional[Dict[str, Any]] = None) -> SendResult: """Send ``content`` (may be markdown) to a chat; returns SendResult with message id.""" # True for surfaces that need an explicit finalize edit to close the message @@ -2443,10 +2420,9 @@ class BasePlatformAdapter(ABC): """Shared exec-approval prompt text: header + fenced (truncated) command + reason, plus the smart-deny line. Buttons/trailing instructions stay platform-local.""" cmd_preview = self._truncate_preview(str(command or ""), self._EA_CMD_BUDGET) - text = ( - f"{self._EA_HEADER}" - f"{self._EA_CODE_OPEN}{self._ea_escape(cmd_preview)}{self._EA_CODE_CLOSE}" - f"{self._EA_REASON_LABEL}{self._ea_escape(description)}") + text = (f"{self._EA_HEADER}" + f"{self._EA_CODE_OPEN}{self._ea_escape(cmd_preview)}{self._EA_CODE_CLOSE}" + f"{self._EA_REASON_LABEL}{self._ea_escape(description)}") return text + self._EA_SMART_DENY_LINE if smart_denied else text @staticmethod @@ -2459,9 +2435,8 @@ class BasePlatformAdapter(ABC): page = max(0, min(page, total_pages - 1)) start, end = page * per_page, min(page * per_page + per_page, total) page_info = f" ({start + 1}–{end} of {total})" if total_pages > 1 else "" - meta: Dict[str, Any] = { - "page": page, "total_pages": total_pages, "start": start, "end": end, - "total": total, "page_info": page_info} + meta: Dict[str, Any] = {"page": page, "total_pages": total_pages, "start": start, + "end": end, "total": total, "page_info": page_info} return options[start:end], meta async def send_slash_confirm( @@ -2545,9 +2520,8 @@ class BasePlatformAdapter(ABC): if human_delay > 0: await asyncio.sleep(human_delay) try: - logger.info( - "[%s] Sending image: %s (alt=%s)", - self.name, safe_url_for_log(image_url), alt_text[:30] if alt_text else "") + logger.info("[%s] Sending image: %s (alt=%s)", self.name, + safe_url_for_log(image_url), alt_text[:30] if alt_text else "") caption = alt_text if alt_text else None if image_url.startswith("file://"): sender, url_kw = self.send_image_file, {"image_path": _unquote(image_url[7:])} @@ -2684,10 +2658,9 @@ class BasePlatformAdapter(ABC): return await self._send_media_fallback_notice( "send_video", "video", video_path, chat_id, caption, reply_to, metadata) - async def send_document( - self, chat_id: str, file_path: str, caption: Optional[str] = None, - file_name: Optional[str] = None, reply_to: Optional[str] = None, - metadata: Optional[Dict[str, Any]] = None, **kwargs) -> SendResult: + async def send_document(self, chat_id: str, file_path: str, caption: Optional[str] = None, + file_name: Optional[str] = None, reply_to: Optional[str] = None, + metadata: Optional[Dict[str, Any]] = None, **kwargs) -> SendResult: """Send a document/file natively. Default: friendly failure notice.""" return await self._send_media_fallback_notice( "send_document", "file", file_path, chat_id, caption, reply_to, metadata, file_name=file_name) @@ -2856,9 +2829,8 @@ class BasePlatformAdapter(ABC): cleaned = cleaned.replace(raw, '') return list(unique), re.sub(r'\n{3,}', '\n\n', cleaned).strip() if unique else cleaned - async def _keep_typing( - self, chat_id: str, interval: float = 2.0, metadata=None, - stop_event: asyncio.Event | None = None) -> None: + async def _keep_typing(self, chat_id: str, interval: float = 2.0, metadata=None, + stop_event: asyncio.Event | None = None) -> None: """Refresh the typing indicator every ``interval`` seconds until cancelled. Platform typing state expires after ~5s. Chats in ``_typing_paused`` are skipped @@ -2873,9 +2845,8 @@ class BasePlatformAdapter(ABC): return if chat_id not in self._typing_paused: try: - await asyncio.wait_for( - self.send_typing(chat_id, metadata=metadata), - timeout=_send_typing_timeout) + await asyncio.wait_for(self.send_typing(chat_id, metadata=metadata), + timeout=_send_typing_timeout) except asyncio.TimeoutError: pass # Slow network — abandon this tick, stay on schedule. except Exception as typing_err: @@ -3075,9 +3046,8 @@ class BasePlatformAdapter(ABC): if not text: return if log_cmd is not None: - logger.info( - "[%s] Sending command '/%s' response (%d chars) to %s", - self.name, log_cmd, len(text), event.source.chat_id) + logger.info("[%s] Sending command '/%s' response (%d chars) to %s", self.name, log_cmd, + len(text), event.source.chat_id) result = await self._send_with_retry( chat_id=event.source.chat_id, content=text, reply_to=_reply_anchor_for_event(event), metadata=_mark_notify_metadata(thread_meta)) @@ -3128,9 +3098,8 @@ class BasePlatformAdapter(ABC): backoff = server_retry_after delay = backoff + random.uniform(0, 1) server_retry_after = None - logger.warning( - "[%s] Send failed (attempt %d/%d, retrying in %.1fs): %s", - self.name, attempt, max_retries, delay, error_str) + logger.warning("[%s] Send failed (attempt %d/%d, retrying in %.1fs): %s", self.name, + attempt, max_retries, delay, error_str) await asyncio.sleep(delay) result = await _send(content) if result.success: @@ -3176,14 +3145,11 @@ class BasePlatformAdapter(ABC): """Return True for normal text eligible for queue-mode debounce.""" result = ( getattr(self, "_busy_text_mode", "interrupt") == "queue" - and event.message_type == MessageType.TEXT - and not getattr(event, "internal", False) - and not event.is_command() - and bool((event.text or "").strip())) + and event.message_type == MessageType.TEXT and not getattr(event, "internal", False) + and not event.is_command() and bool((event.text or "").strip())) if result: - logger.debug( - "[%s] Queue-text debounce candidate accepted: session=%s text_len=%d", self.name, - getattr(event, "session_key", "?"), len(event.text or "")) + logger.debug("[%s] Queue-text debounce candidate accepted: session=%s text_len=%d", + self.name, getattr(event, "session_key", "?"), len(event.text or "")) return result def _can_merge_text_debounce_events(self, existing: MessageEvent, event: MessageEvent) -> bool: @@ -3208,9 +3174,8 @@ class BasePlatformAdapter(ABC): state = self._text_debounce_store().get(session_key) if state is None: return 0.0 - deadline = min( - state.last_ts + self._busy_text_debounce_seconds, - state.first_ts + self._busy_text_hard_cap_seconds) + deadline = min(state.last_ts + self._busy_text_debounce_seconds, + state.first_ts + self._busy_text_hard_cap_seconds) return max(0.0, deadline - time.monotonic()) async def _queue_text_debounce(self, session_key: str, event: MessageEvent) -> None: @@ -3267,8 +3232,7 @@ class BasePlatformAdapter(ABC): state.cancel_timer(unless=asyncio.current_task()) state.task = None existing_pending = self._pending_messages.get(session_key) - if ( - existing_pending is not None + if (existing_pending is not None and not self._can_merge_text_debounce_events(existing_pending, state.event)): return False store.pop(session_key, None) @@ -3308,18 +3272,16 @@ class BasePlatformAdapter(ABC): nothing processing) traps the chat in "Interrupting..." until restart.""" if session_key not in self._active_sessions or not self._session_task_is_stale(session_key): return False - logger.warning( - "[%s] Healing stale session lock for %s (owner task is done/absent)", - self.name, session_key) + logger.warning("[%s] Healing stale session lock for %s (owner task is done/absent)", + self.name, session_key) self._active_sessions.pop(session_key, None) self._pending_messages.pop(session_key, None) self._session_tasks.pop(session_key, None) self._discard_text_debounce(session_key) return True - def _start_session_processing( - self, event: MessageEvent, session_key: str, *, - interrupt_event: Optional[asyncio.Event] = None) -> bool: + def _start_session_processing(self, event: MessageEvent, session_key: str, *, + interrupt_event: Optional[asyncio.Event] = None) -> bool: """Spawn a background processing task under the session guard; True on success. If ``create_task`` is stubbed with a non-Task sentinel (tests), the guard is rolled back and False returned — no half-installed lock.""" @@ -3346,9 +3308,8 @@ class BasePlatformAdapter(ABC): task.add_done_callback(self._expected_cancelled_tasks.discard) return True - async def cancel_session_processing( - self, session_key: str, *, release_guard: bool = True, discard_pending: bool = True, - ) -> None: + async def cancel_session_processing(self, session_key: str, *, release_guard: bool = True, + discard_pending: bool = True) -> None: """Cancel in-flight processing for one session. ``release_guard=False`` keeps the guard so reset-like commands finish atomically before follow-ups start; the await is bounded (5s) so a wedged finally block can't stall dispatch.""" @@ -3362,14 +3323,12 @@ class BasePlatformAdapter(ABC): except asyncio.CancelledError: pass except asyncio.TimeoutError: - logger.warning( - "[%s] Cancelled task for %s did not exit within 5s; " - "unblocking dispatch and letting the task unwind in the background", - self.name, session_key) + logger.warning("[%s] Cancelled task for %s did not exit within 5s; " + "unblocking dispatch and letting the task unwind in the background", + self.name, session_key) except Exception: - logger.debug( - "[%s] Session cancellation raised while unwinding %s", self.name, session_key, - exc_info=True) + logger.debug("[%s] Session cancellation raised while unwinding %s", self.name, + session_key, exc_info=True) if discard_pending: self._pending_messages.pop(session_key, None) self._discard_text_debounce(session_key) @@ -3423,9 +3382,8 @@ class BasePlatformAdapter(ABC): session_key = self._event_session_key(event) expected_session_key = str((event.metadata or {}).get("gateway_session_key") or "").strip() if expected_session_key and session_key != expected_session_key: - logger.warning( - "Dropping internally routed event: expected session=%s derived=%s", - expected_session_key, session_key) + logger.warning("Dropping internally routed event: expected session=%s derived=%s", + expected_session_key, session_key) return # On-entry self-heal: clear a guard whose owner task already exited. if session_key in self._active_sessions: @@ -3452,9 +3410,8 @@ class BasePlatformAdapter(ABC): self._discard_text_debounce(session_key) await self._dispatch_active_session_command(event, session_key, cmd) else: - logger.debug( - "[%s] Command '/%s' bypassing active-session guard for %s", - self.name, cmd, session_key) + logger.debug("[%s] Command '/%s' bypassing active-session guard for %s", + self.name, cmd, session_key) await self._dispatch_inline_reply(event) except Exception as e: logger.error("[%s] Command '/%s' dispatch failed: %s", self.name, cmd, e, exc_info=True) @@ -3487,19 +3444,15 @@ class BasePlatformAdapter(ABC): merge_pending_message_event(self._pending_messages, session_key, event) return if self._is_queue_text_debounce_candidate(event): - logger.debug( - "[%s] New text message while session %s is active — " - "debouncing follow-up (busy_text_mode=queue, window=%.2fs)", - self.name, session_key, self._busy_text_debounce_seconds) + logger.debug("[%s] New text message while session %s is active — " + "debouncing follow-up (busy_text_mode=queue, window=%.2fs)", self.name, + session_key, self._busy_text_debounce_seconds) await self._queue_text_debounce(session_key, event) else: - logger.debug( - "[%s] New message while session %s is active — queuing follow-up " - "(no interrupt, will cascade after current turn)", - self.name, session_key) - merge_pending_message_event( - self._pending_messages, session_key, event, - merge_text=event.message_type == MessageType.TEXT) + logger.debug("[%s] New message while session %s is active — queuing follow-up " + "(no interrupt, will cascade after current turn)", self.name, session_key) + merge_pending_message_event(self._pending_messages, session_key, event, + merge_text=event.message_type == MessageType.TEXT) @staticmethod def _get_human_delay() -> float: @@ -3513,9 +3466,8 @@ class BasePlatformAdapter(ABC): return random.uniform(800 / 1000.0, 2500 / 1000.0) def _ms(name: str, default: int) -> int: # custom mode tolerates malformed env vars return _or_default(lambda: int(os.getenv(name, str(default))), default) - return random.uniform( - _ms("HERMES_HUMAN_DELAY_MIN_MS", 800) / 1000.0, - _ms("HERMES_HUMAN_DELAY_MAX_MS", 2500) / 1000.0) + return random.uniform(_ms("HERMES_HUMAN_DELAY_MIN_MS", 800) / 1000.0, + _ms("HERMES_HUMAN_DELAY_MAX_MS", 2500) / 1000.0) async def _synthesize_auto_tts(self, text_content: str) -> Tuple[List[str], Optional[str]]: """Synthesize auto-TTS audio -> ``(existing_paths, requested_path)``; empty/None @@ -3540,9 +3492,8 @@ class BasePlatformAdapter(ABC): logger.warning("[%s] Auto-TTS failed: %s", self.name, tts_err) return paths, requested_path - def _wants_auto_tts( - self, event: MessageEvent, session_key: str, interrupt_event: asyncio.Event, - text_content: str, media_files: list) -> bool: + def _wants_auto_tts(self, event: MessageEvent, session_key: str, interrupt_event: asyncio.Event, + text_content: str, media_files: list) -> bool: """Auto-TTS on voice input (voice-first), gated by /voice or voice.auto_tts; skipped when streaming TTS already delivered audio this turn.""" return bool( @@ -3609,9 +3560,8 @@ class BasePlatformAdapter(ABC): await asyncio.to_thread(mark_failed, obligation_id, _delivery_error) if _delivery_error == "send_path_degraded": _live_adapter = self._final_delivery_adapter(event.source) - _runtime_redeliver = getattr( - getattr(self, "gateway_runner", None), - "_redeliver_failed_obligations_for_platform", None) + _runtime_redeliver = getattr(getattr(self, "gateway_runner", None), + "_redeliver_failed_obligations_for_platform", None) if _live_adapter is not delivery_adapter and callable(_runtime_redeliver): await _runtime_redeliver( event.source.platform, @@ -3683,9 +3633,8 @@ class BasePlatformAdapter(ABC): """Send the final text on the CURRENT transport (a reconnect may have replaced this adapter), ledger-bracketed; the message-id owner owns the ephemeral delete.""" delivery_adapter = self._final_delivery_adapter(event.source) - logger.info( - "[%s] Sending response (%d chars) to %s", delivery_adapter.name, len(text_content), - event.source.chat_id) + logger.info("[%s] Sending response (%d chars) to %s", delivery_adapter.name, + len(text_content), event.source.chat_id) _obligation_id = await self._record_delivery_obligation( event, session_key, text_content, delivery_adapter, is_ephemeral_response) result = await delivery_adapter._send_with_retry( @@ -3708,18 +3657,15 @@ class BasePlatformAdapter(ABC): _thread_metadata = _thread_metadata_for_source(event.source, _reply_anchor_for_event(event)) await self.send( chat_id=event.source.chat_id, - content=( - f"Sorry, I encountered an error ({type(e).__name__}).\n{error_detail}\n" - "Try again or use /reset to start a fresh session."), - metadata=_thread_metadata) + content=(f"Sorry, I encountered an error ({type(e).__name__}).\n{error_detail}\n" + "Try again or use /reset to start a fresh session."), metadata=_thread_metadata) except Exception as notify_err: logger.error( "[%s] Failed to send error notification to user: %s", self.name, notify_err, exc_info=True) return _thread_metadata - async def _deliver_attachments( - self, event: MessageEvent, extracted: "_ExtractedResponse", metadata: Dict[str, Any], *, - anything_sent: bool) -> None: + async def _deliver_attachments(self, event: MessageEvent, extracted: "_ExtractedResponse", + metadata: Dict[str, Any], *, anything_sent: bool) -> None: """Send extracted image URLs, MEDIA files and bare local files (human-paced), then fail loudly if a non-empty response produced nothing deliverable.""" human_delay = self._get_human_delay() @@ -3732,15 +3678,13 @@ class BasePlatformAdapter(ABC): force_document_attachments=extracted.force_document_attachments, human_delay=human_delay, metadata=metadata) if not (anything_sent or images or local_files or media_files) and extracted.pre_extract.strip(): - logger.error( - "[%s] response_delivery_dropped: non-empty response " - "(%d chars) produced no delivered message or attachment " - "for %s (empty after extract, recovery yielded nothing).", - self.name, len(extracted.pre_extract), event.source.chat_id) + logger.error("[%s] response_delivery_dropped: non-empty response " + "(%d chars) produced no delivered message or attachment " + "for %s (empty after extract, recovery yielded nothing).", self.name, + len(extracted.pre_extract), event.source.chat_id) - def _start_typing_refresh( - self, event: MessageEvent, interrupt_event: asyncio.Event, metadata: Optional[dict], - ) -> Optional[asyncio.Task]: + def _start_typing_refresh(self, event: MessageEvent, interrupt_event: asyncio.Event, + metadata: Optional[dict]) -> Optional[asyncio.Task]: """Spawn the typing-refresh task, or None when ``typing_indicator=False``. ``stop_event`` is passed only when the (possibly overridden) ``_keep_typing`` accepts it.""" if not getattr(self.config, "typing_indicator", True): @@ -3754,9 +3698,8 @@ class BasePlatformAdapter(ABC): kwargs["stop_event"] = interrupt_event return asyncio.create_task(self._keep_typing(event.source.chat_id, **kwargs)) - async def _extract_response_content( - self, response: str, event: MessageEvent, session_key: str, *, is_ephemeral_response: bool, - ) -> "_ExtractedResponse": + async def _extract_response_content(self, response: str, event: MessageEvent, session_key: str, + *, is_ephemeral_response: bool) -> "_ExtractedResponse": """Split a handler response into deliverable text + attachments. Order matters: MEDIA tags → image URLs → residual directives → bare local paths (skipped for ephemeral notices so config paths stay text; unknown-extension MEDIA tags survive @@ -3790,11 +3733,10 @@ class BasePlatformAdapter(ABC): if not (text_content or images or local_files or media_files): _recovered = _strip_media_directives(response).strip() if _recovered: - logger.warning( - "[%s] response_delivery_recovered: extract pipeline " - "reduced a non-empty response (%d chars) to empty with " - "no attachment; delivering recovered original to %s", - self.name, len(pre_extract), event.source.chat_id) + logger.warning("[%s] response_delivery_recovered: extract pipeline " + "reduced a non-empty response (%d chars) to empty with " + "no attachment; delivering recovered original to %s", self.name, + len(pre_extract), event.source.chat_id) text_content = _recovered return _ExtractedResponse( text_content=text_content, images=images, media_files=media_files, @@ -3854,9 +3796,8 @@ class BasePlatformAdapter(ABC): # None/empty is normal (streamed/queued). Suppress a stale response when the # session was interrupted by a still-pending message. if (response and interrupt_event.is_set() and session_key in self._pending_messages): - logger.info( - "[%s] Suppressing stale response for interrupted session %s", - self.name, session_key) + logger.info("[%s] Suppressing stale response for interrupted session %s", self.name, + session_key) response = None if not response: logger.debug("[%s] Handler returned empty/None response for %s", self.name, event.source.chat_id) @@ -3976,10 +3917,9 @@ class BasePlatformAdapter(ABC): asyncio.gather(*(asyncio.shield(t) for t in tasks), return_exceptions=True), timeout=5.0) except asyncio.TimeoutError: - logger.warning( - "[%s] %d background task(s) did not exit within 5s; " - "releasing tracking and letting them unwind in the background", - self.name, len([t for t in tasks if not t.done()])) + logger.warning("[%s] %d background task(s) did not exit within 5s; " + "releasing tracking and letting them unwind in the background", + self.name, len([t for t in tasks if not t.done()])) break self._background_tasks.clear() self._expected_cancelled_tasks.clear() @@ -4014,13 +3954,12 @@ class BasePlatformAdapter(ABC): profile is stamped on ``source.profile`` for per-profile HERMES_HOME isolation.""" def _opt(value) -> Optional[str]: return str(value) if value else None - fields = dict( - platform=self.platform, chat_id=str(chat_id), chat_name=chat_name, chat_type=chat_type, - user_id=_opt(user_id), user_name=user_name, thread_id=_opt(thread_id), - chat_topic=(chat_topic or "").strip() or None, - user_id_alt=user_id_alt, chat_id_alt=chat_id_alt, is_bot=is_bot, - scope_id=_opt(scope_id), guild_id=_opt(guild_id), parent_chat_id=_opt(parent_chat_id), - message_id=_opt(message_id)) + fields = dict(platform=self.platform, chat_id=str(chat_id), chat_name=chat_name, + chat_type=chat_type, user_id=_opt(user_id), user_name=user_name, + thread_id=_opt(thread_id), chat_topic=(chat_topic or "").strip() or None, + user_id_alt=user_id_alt, chat_id_alt=chat_id_alt, is_bot=is_bot, + scope_id=_opt(scope_id), guild_id=_opt(guild_id), + parent_chat_id=_opt(parent_chat_id), message_id=_opt(message_id)) profile = None # from configured routes; None when no match / no routes profile_route_rejected = False runner = getattr(self, "gateway_runner", None) @@ -4031,13 +3970,11 @@ class BasePlatformAdapter(ABC): except ProfileRouteRejected: profile_route_rejected = True except Exception: - logger.warning( - "Profile resolution failed for %s/%s, defaulting to active profile", - self.platform, chat_id, exc_info=True) - source = SessionSource( - **fields, profile=profile, role_authorized=role_authorized, - auto_thread_created=auto_thread_created, - auto_thread_initial_name=auto_thread_initial_name) + logger.warning("Profile resolution failed for %s/%s, defaulting to active profile", + self.platform, chat_id, exc_info=True) + source = SessionSource(**fields, profile=profile, role_authorized=role_authorized, + auto_thread_created=auto_thread_created, + auto_thread_initial_name=auto_thread_initial_name) # Both transport-only, kept out of to_dict(): the live receiving adapter is # authoritative this turn even if profile_routes picks another runtime; the # fail-closed reject flag is consumed before auth so rejected routes never 500. @@ -4061,9 +3998,8 @@ class BasePlatformAdapter(ABC): return content @staticmethod - def truncate_message( - content: str, max_length: int = 4096, len_fn: Optional["Callable[[str], int]"] = None, - ) -> List[str]: + def truncate_message(content: str, max_length: int = 4096, + len_fn: Optional["Callable[[str], int]"] = None) -> List[str]: """Split a long message into chunks, preserving code-block boundaries: a split inside a fence closes it at the chunk end and reopens it (same language tag) in the next; multi-chunk output gets ``(1/3)`` indicators. ``len_fn`` overrides From 9a00333d71671c673bf1fd2ed87c3d60c0bc5edd Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Wed, 2 Sep 2026 22:44:09 -0700 Subject: [PATCH 03/13] =?UTF-8?q?refactor(gateway/platforms):=20base.py=20?= =?UTF-8?q?=E2=80=94=20fold=20cache-dir=20resolver,=20alias=20=5Fstrip=5Fm?= =?UTF-8?q?edia=5Fdirectives,=20=5Faccepts=5Fkwarg=20+=20=5Fthread=5Fmetad?= =?UTF-8?q?ata=5Ffor=5Fevent=20helpers?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- gateway/platforms/base.py | 147 ++++++++++++++++++-------------------- 1 file changed, 70 insertions(+), 77 deletions(-) diff --git a/gateway/platforms/base.py b/gateway/platforms/base.py index af92a22cfa..06f09eff59 100644 --- a/gateway/platforms/base.py +++ b/gateway/platforms/base.py @@ -130,6 +130,11 @@ def _thread_metadata_for_source(source, reply_to_message_id: str | None = None) return metadata +def _thread_metadata_for_event(event) -> dict | None: + """``_thread_metadata_for_source`` for an event, anchored on its reply id.""" + return _thread_metadata_for_source(event.source, _reply_anchor_for_event(event)) + + def _mark_notify_metadata(metadata: dict | None) -> dict: """Clone metadata and mark a user-visible reply as notify-worthy.""" notify_metadata = dict(metadata) if metadata else {} @@ -519,17 +524,6 @@ async def _ssrf_redirect_guard(response): IMAGE_CACHE_DIR = get_hermes_dir("cache/images", "image_cache") -def _resolve_cache_dir(constant_name: str, new_subpath: str, old_name: str) -> Path: - """Resolve fresh via get_hermes_dir (active profile) unless a test monkeypatched - the module constant away from its import-time default; create the directory.""" - d = get_hermes_dir(new_subpath, old_name) - current = globals().get(constant_name) - default = _CACHE_DIR_IMPORT_DEFAULTS.get(constant_name) - if current is not None and default is not None and current != default: - d = Path(current) - d.mkdir(parents=True, exist_ok=True) - return d - # Inbound media size cap: payloads are buffered fully in memory before hitting the cache, so # an uncapped upload (Discord Nitro: 500 MB) or huge remote URL can OOM-kill the gateway. # Enforced in ``cache_*_from_bytes`` and ``cache_*_from_url``; ``gateway.max_inbound_media_bytes``. @@ -575,10 +569,18 @@ async def _read_httpx_body_with_limit(response, *, media_type: str) -> bytes: def _cache_dir_accessors(kind: str, constant_name: str, new_subpath: str, old_name: str): - """``(get__cache_dir, cleanup__cache)`` pair: the getter resolves and creates - the directory; ``cleanup(max_age_hours=24)`` deletes older files and returns the count.""" + """``(get__cache_dir, cleanup__cache)`` pair. The getter resolves fresh via + get_hermes_dir (active profile) unless a test monkeypatched the module constant away from + its import-time default, and creates the directory; ``cleanup(max_age_hours=24)`` deletes + older files and returns the count.""" def get_dir() -> Path: - return _resolve_cache_dir(constant_name, new_subpath, old_name) + d = get_hermes_dir(new_subpath, old_name) + current = globals().get(constant_name) + default = _CACHE_DIR_IMPORT_DEFAULTS.get(constant_name) + if current is not None and default is not None and current != default: + d = Path(current) + d.mkdir(parents=True, exist_ok=True) + return d def cleanup(max_age_hours: int = 24) -> int: return _cleanup_cache_dir(get_dir(), max_age_hours) @@ -1288,10 +1290,11 @@ def _delete_spans(text: str, spans: list) -> str: def _strip_media_tag_directives(text: str) -> str: - """Remove MEDIA: tags and [[audio_as_voice]] / [[as_document]] markers. Protected spans - are mask-located only — tags inside them are neither stripped nor mangled, matching - ``extract_media`` so display and delivery agree.""" - if not _has_media_directives(text): + """Remove MEDIA: tags and [[audio_as_voice]] / [[as_document]] markers so they never render + as text (backstop after ``extract_media``). Protected spans are mask-located only — tags + inside them are neither stripped nor mangled, matching ``extract_media`` so display and + delivery agree. Empty/None text is returned as-is.""" + if not text or not _has_media_directives(text): return text cleaned = text.replace("[[audio_as_voice]]", "").replace("[[as_document]]", "") return _delete_spans(cleaned, _real_media_tag_spans(_mask_media_scan_text(cleaned))) @@ -1619,7 +1622,8 @@ def merge_pending_message_event(pending_messages: Dict[str, MessageEvent], sessi ``merge_text``, rapid follow-up TEXT events are appended instead of replacing the turn.""" existing = pending_messages.get(session_key) if existing: - existing_is_photo = getattr(existing, "message_type", None) == MessageType.PHOTO + existing_type = getattr(existing, "message_type", None) + existing_is_photo = existing_type == MessageType.PHOTO incoming_is_photo = event.message_type == MessageType.PHOTO both_photo = existing_is_photo and incoming_is_photo incoming_has_media = bool(event.media_urls) @@ -1642,9 +1646,7 @@ def merge_pending_message_event(pending_messages: Dict[str, MessageEvent], sessi existing.text = BasePlatformAdapter._merge_caption(existing.text, event.text) if existing_is_photo or incoming_is_photo: existing.message_type = MessageType.PHOTO - elif ( - getattr(existing, "message_type", None) == MessageType.TEXT - and event.message_type != MessageType.TEXT): + elif existing_type == MessageType.TEXT and event.message_type != MessageType.TEXT: existing.message_type = event.message_type # Drop the *derived* STT transcript cache now that the event changed; the echo # ledger (``_gateway_pending_stt_echoed``) must survive or notes echo twice. @@ -1652,8 +1654,8 @@ def merge_pending_message_event(pending_messages: Dict[str, MessageEvent], sessi if hasattr(existing, attr): delattr(existing, attr) return - if (merge_text and getattr(existing, "message_type", None) == MessageType.TEXT - and event.message_type == MessageType.TEXT): + both_text = existing_type == MessageType.TEXT and event.message_type == MessageType.TEXT + if merge_text and both_text: if event.text: existing.text = _append_text(existing.text, event.text) return @@ -1728,10 +1730,7 @@ def _lazy_attr(obj: Any, name: str, factory: Callable[[], Any]) -> Any: return value -def _strip_media_directives(text: str) -> str: - """Backstop strip of delivery directives ([[audio_as_voice]], [[as_document]], - MEDIA:) so they never render as text; run ``extract_media`` first.""" - return _strip_media_tag_directives(text) if text else text +_strip_media_directives = _strip_media_tag_directives class BasePlatformAdapter(ABC): @@ -2121,8 +2120,7 @@ class BasePlatformAdapter(ABC): """Install a thread_id-recovery hook (Telegram DM topic mode): called with ``event.source`` before session keying; a non-None return replaces ``source.thread_id``. ``None`` clears the hook.""" - # getattr-guard: tests build adapters via object.__new__ (no __init__). - self._topic_recovery_fn = fn # type: ignore[attr-defined] + self._topic_recovery_fn = fn def _apply_topic_recovery(self, event: MessageEvent) -> None: """Rewrite ``event.source.thread_id`` in place if the hook returns one.""" @@ -2151,8 +2149,7 @@ class BasePlatformAdapter(ABC): (``platform``, ``event_name`` "reaction:added"/"reaction:removed", ``reaction``, ``user_id``, ``item_user_id``, ``channel_id``, ``message_ts``, ``event_ts``, ``raw_event``) fanned out via ``HookRegistry.emit``.""" - # getattr-guard: tests build adapters via object.__new__ (no __init__). - self._reaction_handler = handler # type: ignore[attr-defined] + self._reaction_handler = handler def set_authorization_check( self, callback: Optional[Callable[[str, Optional[str], Optional[str]], bool]]) -> None: @@ -2385,8 +2382,6 @@ class BasePlatformAdapter(ABC): try: await asyncio.sleep(max(1, int(ttl_seconds))) await self.delete_message(chat_id=chat_id, message_id=message_id) - except asyncio.CancelledError: - raise except Exception as e: logger.debug("[%s] Ephemeral delete failed for %s/%s: %s", self.name, chat_id, message_id, e) coro = _run_delete() @@ -2493,20 +2488,25 @@ class BasePlatformAdapter(ABC): async def stop_typing(self, chat_id: str) -> None: """Stop a persistent typing indicator; override where typing runs as a loop.""" + @staticmethod + def _accepts_kwarg(fn: Callable, name: str, *, var_kw: bool, unknown: bool) -> bool: + """Whether ``fn``'s signature takes keyword ``name`` (``var_kw``: a ``**kwargs`` also + counts); ``unknown`` when the signature can't be introspected.""" + try: + params = inspect.signature(fn).parameters + except (TypeError, ValueError): + return unknown + return name in params or (var_kw and any( + p.kind is inspect.Parameter.VAR_KEYWORD for p in params.values())) + async def _stop_typing_with_metadata(self, chat_id: str, metadata=None) -> None: """Stop typing, forwarding ``metadata`` only if ``stop_typing`` accepts it (Slack AI status is per thread, so dropping metadata could clear a sibling thread; introspecting keeps legacy ``stop_typing(chat_id)`` adapters working).""" - if metadata: - try: - params = inspect.signature(self.stop_typing).parameters - accepts_metadata = "metadata" in params or any( - param.kind is inspect.Parameter.VAR_KEYWORD for param in params.values()) - except (TypeError, ValueError): - accepts_metadata = False - if accepts_metadata: - await self.stop_typing(chat_id, metadata=metadata) - return + if metadata and self._accepts_kwarg( + self.stop_typing, "metadata", var_kw=True, unknown=False): + await self.stop_typing(chat_id, metadata=metadata) + return await self.stop_typing(chat_id) async def send_multiple_images( @@ -2522,14 +2522,14 @@ class BasePlatformAdapter(ABC): try: logger.info("[%s] Sending image: %s (alt=%s)", self.name, safe_url_for_log(image_url), alt_text[:30] if alt_text else "") - caption = alt_text if alt_text else None if image_url.startswith("file://"): sender, url_kw = self.send_image_file, {"image_path": _unquote(image_url[7:])} elif self._is_animation_url(image_url): sender, url_kw = self.send_animation, {"animation_url": image_url} else: sender, url_kw = self.send_image, {"image_url": image_url} - img_result = await sender(chat_id=chat_id, **url_kw, caption=caption, metadata=metadata) + img_result = await sender( + chat_id=chat_id, **url_kw, caption=alt_text or None, metadata=metadata) if not img_result.success: logger.error("[%s] Failed to send image: %s", self.name, img_result.error) except Exception as img_err: @@ -2574,8 +2574,8 @@ class BasePlatformAdapter(ABC): def _remove_if_extracted(match): url = match.group(2) if match.lastindex >= 2 else match.group(1) return '' if url in extracted_urls else match.group(0) - cleaned = re.sub(md_pattern, _remove_if_extracted, cleaned) - cleaned = re.sub(html_pattern, _remove_if_extracted, cleaned) + for pattern in (md_pattern, html_pattern): + cleaned = re.sub(pattern, _remove_if_extracted, cleaned) cleaned = re.sub(r'\n{3,}', '\n\n', cleaned).strip() # leftover blank lines return images, cleaned @@ -2677,10 +2677,10 @@ class BasePlatformAdapter(ABC): else _media_failure_text("file", os.path.basename(media_path))) try: notice = await self.send(chat_id=chat_id, content=text, metadata=metadata) - failed, problem = not notice.success, notice.error + problem = None if notice.success else notice.error except Exception as notify_err: - failed, problem = True, notify_err - if failed: + problem = notify_err + if problem is not None: logger.debug("[%s] Could not send media-delivery-failure notice: %s", self.name, problem) async def send_image_file( @@ -3040,7 +3040,7 @@ class BasePlatformAdapter(ABC): async def _dispatch_inline_reply(self, event: MessageEvent, *, log_cmd: Optional[str] = None) -> None: """Call the handler and send its reply inline, with retry, threading and ephemeral deletion — no session lifecycle (active-session bypass paths).""" - thread_meta = _thread_metadata_for_source(event.source, _reply_anchor_for_event(event)) + thread_meta = _thread_metadata_for_event(event) response = await self._message_handler(event) text, eph_ttl = self._unwrap_ephemeral(response) if not text: @@ -3062,8 +3062,7 @@ class BasePlatformAdapter(ABC): unsent final response belongs on the replacement transport, but message IDs, edits and deletes stay owned by the old one (nothing is migrated). """ - runner = getattr(self, "gateway_runner", None) - resolve = getattr(runner, "_adapter_for_source", None) + resolve = getattr(self.gateway_runner, "_adapter_for_source", None) if not callable(resolve): return self try: @@ -3556,16 +3555,15 @@ class BasePlatformAdapter(ABC): if getattr(result, "success", False): await asyncio.to_thread(mark_delivered, obligation_id) return - _delivery_error = str(getattr(result, "error", "") or "") - await asyncio.to_thread(mark_failed, obligation_id, _delivery_error) - if _delivery_error == "send_path_degraded": - _live_adapter = self._final_delivery_adapter(event.source) - _runtime_redeliver = getattr(getattr(self, "gateway_runner", None), - "_redeliver_failed_obligations_for_platform", None) - if _live_adapter is not delivery_adapter and callable(_runtime_redeliver): - await _runtime_redeliver( - event.source.platform, - profile=getattr(delivery_adapter, "_owner_profile", None)) + error = str(getattr(result, "error", "") or "") + await asyncio.to_thread(mark_failed, obligation_id, error) + if error == "send_path_degraded": + redeliver = getattr( + self.gateway_runner, "_redeliver_failed_obligations_for_platform", None) + live = self._final_delivery_adapter(event.source) + if live is not delivery_adapter and callable(redeliver): + await redeliver(event.source.platform, + profile=getattr(delivery_adapter, "_owner_profile", None)) except Exception: logger.debug("delivery ledger update failed", exc_info=True) @@ -3654,7 +3652,7 @@ class BasePlatformAdapter(ABC): _thread_metadata = None try: error_detail = str(e)[:300] if str(e) else "no details available" - _thread_metadata = _thread_metadata_for_source(event.source, _reply_anchor_for_event(event)) + _thread_metadata = _thread_metadata_for_event(event) await self.send( chat_id=event.source.chat_id, content=(f"Sorry, I encountered an error ({type(e).__name__}).\n{error_detail}\n" @@ -3690,11 +3688,7 @@ class BasePlatformAdapter(ABC): if not getattr(self.config, "typing_indicator", True): return None kwargs: Dict[str, Any] = {"metadata": metadata} - try: - sig = inspect.signature(self._keep_typing) - except (TypeError, ValueError): - sig = None - if sig is None or "stop_event" in sig.parameters: + if self._accepts_kwarg(self._keep_typing, "stop_event", var_kw=False, unknown=True): kwargs["stop_event"] = interrupt_event return asyncio.create_task(self._keep_typing(event.source.chat_id, **kwargs)) @@ -3785,7 +3779,7 @@ class BasePlatformAdapter(ABC): # Reuse the interrupt event handle_message() installed; new Event only if removed externally. interrupt_event = self._active_sessions.get(session_key) or asyncio.Event() self._active_sessions[session_key] = interrupt_event - _thread_metadata = _thread_metadata_for_source(event.source, _reply_anchor_for_event(event)) + _thread_metadata = _thread_metadata_for_event(event) typing_task = self._start_typing_refresh(event, interrupt_event, _thread_metadata) try: await self._run_processing_hook("on_processing_start", event) @@ -3795,7 +3789,7 @@ class BasePlatformAdapter(ABC): response, _ephemeral_ttl = self._unwrap_ephemeral(response) # None/empty is normal (streamed/queued). Suppress a stale response when the # session was interrupted by a still-pending message. - if (response and interrupt_event.is_set() and session_key in self._pending_messages): + if response and interrupt_event.is_set() and session_key in self._pending_messages: logger.info("[%s] Suppressing stale response for interrupted session %s", self.name, session_key) response = None @@ -3834,10 +3828,9 @@ class BasePlatformAdapter(ABC): anything_sent=delivery_attempted or _tts_caption_delivered) processing_ok = delivery_succeeded if delivery_attempted else not bool(response) # Clean up the per-turn streaming-TTS flag. - self._streaming_tts_completed_turns.discard( - self._streaming_tts_turn_key( - session_key, getattr(interrupt_event, "_hermes_run_generation", None), - event=event) or "") + self._streaming_tts_completed_turns.discard(self._streaming_tts_turn_key( + session_key, getattr(interrupt_event, "_hermes_run_generation", None), + event=event) or "") await self._run_processing_hook( "on_processing_complete", event, ProcessingOutcome.SUCCESS if processing_ok else ProcessingOutcome.FAILURE) @@ -3962,7 +3955,7 @@ class BasePlatformAdapter(ABC): parent_chat_id=_opt(parent_chat_id), message_id=_opt(message_id)) profile = None # from configured routes; None when no match / no routes profile_route_rejected = False - runner = getattr(self, "gateway_runner", None) + runner = self.gateway_runner if runner is not None: from gateway.profile_routing import ProfileRouteRejected try: From e05277fe966c6c51e8944bacd3b5c0a3d2fe6066 Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Wed, 2 Sep 2026 22:59:01 -0700 Subject: [PATCH 04/13] =?UTF-8?q?refactor(gateway/platforms):=20base.py=20?= =?UTF-8?q?=E2=80=94=20compact=2068=20multi-line=20docstrings=20(keep=20ev?= =?UTF-8?q?ery=20invariant/WHY),=20reflow=20to=20100=20cols?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- gateway/platforms/base.py | 484 +++++++++++++++++--------------------- 1 file changed, 220 insertions(+), 264 deletions(-) diff --git a/gateway/platforms/base.py b/gateway/platforms/base.py index 06f09eff59..0060ec824c 100644 --- a/gateway/platforms/base.py +++ b/gateway/platforms/base.py @@ -25,9 +25,8 @@ logger = logging.getLogger(__name__) def _consume_detached_handler_exception(task: "asyncio.Task") -> None: - """Done-callback retrieving a detached fatal-error handler's exception, so handler - tasks left running after their carrier was cancelled (``_notify_fatal_error``) - never log "Task exception was never retrieved".""" + """Done-callback for a detached fatal-error handler task (carrier cancelled in + ``_notify_fatal_error``): retrieve its exception so asyncio never logs "never retrieved".""" if task.cancelled(): return exc = task.exception() @@ -50,9 +49,8 @@ _TELEGRAM_VOICE_EXTS = frozenset({'.ogg', '.opus'}) def transcode_to_ogg_opus(path: str, *, bitrate: str = "32k") -> "str | None": - """Best-effort ffmpeg transcode to Ogg/Opus (voip-tuned) for native voice bubbles: a NEW - temp ``.ogg`` path (caller owns cleanup), or ``None`` when ffmpeg is missing/fails so - callers keep their document fallback. Blocking — use ``asyncio.to_thread``.""" + """Best-effort ffmpeg transcode to Ogg/Opus (voip-tuned) for native voice bubbles: a NEW temp + ``.ogg`` path (caller cleans up), or None when ffmpeg is missing/fails. Blocking (to_thread).""" import shutil as _shutil ffmpeg = _shutil.which("ffmpeg") if not ffmpeg: @@ -314,11 +312,8 @@ def _no_proxy_entry_matches(entry: str, host: str, port: int | None = None) -> b def should_bypass_proxy(target_hosts: str | list[str] | tuple[str, ...] | set[str] | None) -> bool: - """Return True when NO_PROXY/no_proxy matches at least one target host. - - Supports exact hosts, domain suffixes, wildcard suffixes, IP literals, - CIDR ranges, optional host:port entries, and ``*``. - """ + """True when NO_PROXY/no_proxy matches at least one target host (exact hosts, domain / + wildcard suffixes, IP literals, CIDR ranges, optional host:port entries, ``*``).""" entries = _no_proxy_entries() if not entries or not target_hosts: return False @@ -351,10 +346,9 @@ def resolve_proxy_url( def _aiohttp_socks_connector(proxy_url: str): - """``aiohttp_socks.ProxyConnector`` for ``proxy_url``, or None when aiohttp_socks is - missing (SOCKS then logs a warning; HTTP callers fall back to ``proxy=``). - ``rdns=True`` forces remote DNS through the proxy — required by many SOCKS - implementations (Shadowrocket, Clash) and essential against GFW DNS pollution.""" + """``aiohttp_socks.ProxyConnector`` for ``proxy_url``, or None when aiohttp_socks is missing + (SOCKS logs a warning; HTTP callers fall back to ``proxy=``). ``rdns=True`` forces remote DNS + through the proxy — required by Shadowrocket/Clash-style SOCKS and against GFW DNS pollution.""" try: from aiohttp_socks import ProxyConnector return ProxyConnector.from_url(proxy_url, rdns=True) @@ -398,9 +392,9 @@ def gateway_trust_env() -> bool: def proxy_kwargs_for_aiohttp(proxy_url: str | None) -> tuple[dict, dict]: - """``(session_kwargs, request_kwargs)`` for a standalone ``aiohttp.ClientSession``. - With aiohttp-socks every scheme uses a connector (libraries like mautrix never forward - per-request ``proxy=``); without it HTTP falls back to ``({}, {"proxy": url})``, SOCKS is ignored.""" + """``(session_kwargs, request_kwargs)`` for a standalone ``aiohttp.ClientSession``. With + aiohttp-socks every scheme uses a connector (mautrix-style libs never forward per-request + ``proxy=``); without it HTTP falls back to ``({}, {"proxy": url})`` and SOCKS is ignored.""" if not proxy_url: return {}, {} connector = _aiohttp_socks_connector(proxy_url) @@ -510,9 +504,8 @@ def safe_url_for_log(url: str, max_len: int = 80) -> str: async def _ssrf_redirect_guard(response): - """Re-validate each redirect target: a public URL that 302-redirects to - http://169.254.169.254/ would otherwise bypass the pre-flight is_safe_url() check. - Async because httpx.AsyncClient awaits response event hooks.""" + """Re-validate each redirect target (a public URL 302-ing to http://169.254.169.254/ would + bypass the pre-flight is_safe_url()). Async because httpx awaits response event hooks.""" from tools.url_safety import is_safe_url, redirect_target_from_response redirect_url = redirect_target_from_response(response) if redirect_url and not is_safe_url(redirect_url): @@ -547,9 +540,8 @@ def validate_inbound_media_size( async def _read_httpx_body_with_limit(response, *, media_type: str) -> bytes: - """Read an httpx streaming body under the media cap: reject an oversized - ``Content-Length`` early, then re-check the running total per chunk so a - lying/absent header can't smuggle an unbounded body past the cap.""" + """Read an httpx streaming body under the media cap: reject an oversized ``Content-Length`` + early, then re-check the running total per chunk (a lying/absent header can't smuggle more).""" max_bytes = get_inbound_media_max_bytes() content_length = response.headers.get("content-length") if content_length: @@ -619,9 +611,8 @@ def cache_image_from_bytes(data: bytes, ext: str = ".jpg") -> str: async def _cache_media_from_url(url: str, ext: str, retries: int, *, media_type: str, accept: str, cache_fn, log_label: str) -> str: - """Shared downloader behind ``cache_image_from_url`` / ``cache_audio_from_url``: - SSRF-checked (pre-flight + per-redirect; raises ValueError), size-capped, and - retried with linear backoff on timeouts / 429 / 5xx.""" + """Shared downloader behind ``cache_*_from_url``: SSRF-checked (pre-flight + per-redirect; + raises ValueError), size-capped, linear-backoff retries on timeouts / 429 / 5xx.""" from tools.url_safety import create_ssrf_safe_async_client, is_safe_url import httpx if not is_safe_url(url): @@ -1000,9 +991,8 @@ def _warn_unresolved_docker_media(candidate: Path, session_key: str, reason: str def _translate_docker_container_media_path(candidate: Path, session_key: str = "") -> Optional[Path]: - """Translate a container-absolute path to its host path via longest-prefix match - over ``docker_volumes``, the auto-mounted cache dirs (``/root/.hermes/...``), the - persistent ``/workspace`` host root, and the persistent ``/root`` home mount.""" + """Container-absolute path -> host path via longest-prefix match over ``docker_volumes``, the + auto-mounted cache dirs (``/root/.hermes/...``), persistent ``/workspace`` and ``/root``.""" if not candidate.is_absolute(): return None # In-process gateways (Desktop, `hermes serve`) may not have bridged terminal.* @@ -1047,13 +1037,11 @@ def _translate_docker_container_media_path(candidate: Path, session_key: str = " def validate_media_delivery_path(path: str, session_key: str = "") -> Optional[str]: - """Return a safe absolute file path for native media delivery, else None. - - Default: any existing regular file outside the credential / system denylist (symmetric - with inbound). Strict (``HERMES_MEDIA_DELIVERY_STRICT=1``, for public bots where one - user's prompt injection must not exfiltrate host secrets): MUST be under a Hermes cache, - an operator root (``HERMES_MEDIA_ALLOW_DIRS``), or freshly produced within the recency - window. Symlinks are resolved before any check.""" + """Safe absolute file path for native media delivery, else None. Default: any existing + regular file outside the credential / system denylist (symmetric with inbound). Strict + (``HERMES_MEDIA_DELIVERY_STRICT=1``, public bots where prompt injection must not exfiltrate + host secrets): MUST be under a Hermes cache, an operator root (``HERMES_MEDIA_ALLOW_DIRS``), + or freshly produced within the recency window. Symlinks are resolved before any check.""" candidate = _normalize_media_tag_path(path) if not candidate: return None @@ -1190,9 +1178,9 @@ MEDIA_EXTENSIONLESS_TAG_RE = re.compile( def _match_extensionless_path(scan_text: str, match: "re.Match") -> Optional[Tuple[str, int]]: - """Resolve an extensionless MEDIA tag match to a validated on-disk path: the captured - path first, then extended forward across single spaces (max 8 tokens, never past a - newline or the next ``MEDIA:``). Returns ``(safe_path, end_offset)`` or ``None``.""" + """Extensionless MEDIA tag match -> validated on-disk ``(safe_path, end_offset)`` or None: the + captured path first, then extended across single spaces (max 8 tokens, never past a newline + or the next ``MEDIA:``).""" path = _normalize_media_tag_path(match.group("path")) if not path: return None @@ -1346,9 +1334,9 @@ def _resolve_media_ext(filename: str, mime_type: str) -> str: def cache_media_bytes(data: bytes, *, filename: str = "", mime_type: str = "", default_kind: Optional[str] = None) -> Optional[CachedMedia]: - """Classify and cache raw attachment bytes; return a CachedMedia or None. ``default_kind`` - biases classification when extension/MIME are ambiguous (Telegram native photo, no name). - Anything not image/video/audio is a document; only images failing validation return None.""" + """Classify and cache raw attachment bytes -> CachedMedia (None only for images failing + validation). ``default_kind`` biases ambiguous ext/MIME (Telegram native photo, no name); + anything not image/video/audio is a document.""" from tools.credential_files import to_agent_visible_cache_path ext = _resolve_media_ext(filename, mime_type) mime = (mime_type or "").lower() @@ -1501,9 +1489,9 @@ _PLAINTEXT_GATEWAY_RESTART_PATTERNS: tuple[re.Pattern[str], ...] = ( def coerce_plaintext_gateway_command(event: "MessageEvent") -> None: - """Rewrite a tiny set of DM plaintext admin phrases into slash commands, keeping ``restart - gateway`` out of the LLM/tool path (a self-restart from inside the running agent leaves the - gateway stuck in ``draining`` waiting on that agent). Narrow: DM text, exact phrases only.""" + """Rewrite a tiny set of DM plaintext admin phrases (exact matches only) into slash commands so + ``restart gateway`` never reaches the LLM/tool path (a self-restart from inside the running + agent leaves the gateway stuck in ``draining`` waiting on that agent).""" with contextlib.suppress(Exception): if event is None or event.message_type != MessageType.TEXT: return @@ -1581,17 +1569,16 @@ _SEND_ERROR_CLASSIFIERS: Tuple[Tuple[str, Callable[[str], bool]], ...] = ( def classify_send_error(exc: Optional[BaseException], error_text: str = "") -> str: - """Map a send exception / error string to a :data:`SEND_ERROR_KINDS` value. - Conservative substring matching: anything unrecognized is ``"unknown"`` so an - unclassified failure is never mistaken for a benign one.""" + """Map a send exception / error string to a :data:`SEND_ERROR_KINDS` value; anything + unrecognized is ``"unknown"`` so an unclassified failure is never mistaken for a benign one.""" blob = _error_blob(exc, error_text) return next((kind for kind, matches in _SEND_ERROR_CLASSIFIERS if matches(blob)), "unknown") def is_chat_level_not_found(exc: Optional[BaseException] = None, error_text: str = "") -> bool: - """Whether a ``not_found`` failure means the *whole chat* is gone — only that should mark - a delivery target dead; a deleted forum topic or edited-away message leaves the parent - chat reachable. When both markers are present the sub-chat reading wins.""" + """Whether a ``not_found`` failure means the *whole chat* is gone (only that marks a target + dead; a deleted topic / edited-away message leaves the parent chat reachable). When both + markers are present the sub-chat reading wins.""" blob = _error_blob(exc, error_text) return (not _any_in(blob, *_SUBCHAT_NOT_FOUND_SUBSTRINGS) and _any_in(blob, *_CHAT_LEVEL_NOT_FOUND_SUBSTRINGS)) @@ -1617,9 +1604,9 @@ class EphemeralReply(str): def merge_pending_message_event(pending_messages: Dict[str, MessageEvent], session_key: str, event: MessageEvent, *, merge_text: bool = False) -> None: - """Store or merge a pending event for a session: photo bursts/albums (several near-simultaneous - PHOTO events) merge into the queued event so the next turn sees the whole burst; with - ``merge_text``, rapid follow-up TEXT events are appended instead of replacing the turn.""" + """Store or merge a pending event: photo bursts/albums merge into the queued event so the next + turn sees the whole burst; with ``merge_text`` rapid TEXT follow-ups append instead of + replace.""" existing = pending_messages.get(session_key) if existing: existing_type = getattr(existing, "message_type", None) @@ -1676,9 +1663,8 @@ MessageHandler = Callable[[MessageEvent], Awaitable[Optional[Union[str, "Ephemer def resolve_channel_prompt(config_extra: dict, channel_id: str, parent_id: str | None = None) -> str | None: - """Resolve a per-channel ephemeral prompt from ``config.extra["channel_prompts"]``: - exact *channel_id* first, then *parent_id* (forum threads / child channels inherit - the parent prompt). Blank prompts count as absent.""" + """Per-channel ephemeral prompt from ``config.extra["channel_prompts"]``: exact *channel_id* + first, then *parent_id* (threads inherit the parent prompt). Blank prompts count as absent.""" prompts = config_extra.get("channel_prompts") or {} if not isinstance(prompts, dict): return None @@ -1691,11 +1677,9 @@ def resolve_channel_prompt(config_extra: dict, channel_id: str, parent_id: str | def resolve_channel_skills( config_extra: dict, channel_id: str, parent_id: str | None = None) -> list[str] | None: - """Resolve auto-loaded skill(s) for a channel/thread from ``channel_skill_bindings`` - (a list of ``{id: "", skills: [...]}`` entries; ``skill: ""`` - single string also accepted). Exact *channel_id* match first, then *parent_id* - (threads inherit the parent channel's binding). Returns a deduplicated, - order-preserving list or None.""" + """Auto-loaded skill(s) for a channel/thread from ``channel_skill_bindings`` (entries + ``{id: "", skills: [...]}``; ``skill: ""`` also accepted). Exact + *channel_id* first, then *parent_id* (threads inherit). Deduplicated ordered list or None.""" bindings = config_extra.get("channel_skill_bindings") or [] if not isinstance(bindings, list) or not bindings: return None @@ -1716,7 +1700,8 @@ def resolve_channel_skills( def _split_post_delivery_entry(entry: Any) -> Tuple[Optional[int], Any]: - """``(generation, callback)`` from a post-delivery slot; legacy bare callbacks have no generation.""" + """``(generation, callback)`` from a post-delivery slot; legacy bare callbacks have no + generation.""" return entry if isinstance(entry, tuple) and len(entry) == 2 else (None, entry) @@ -1745,11 +1730,9 @@ class BasePlatformAdapter(ABC): supports_status_text: bool = False def set_status_text(self, chat_id: str, text: Optional[str]) -> None: - """Set or clear (``None``) the live working-state phrase for a chat. - - In-memory only: the next typing refresh renders it; a no-op store on adapters - that never read ``_status_text``. - """ + """Set or clear (``None``) the live working-state phrase for a chat. In-memory only: the + next typing refresh renders it; a no-op store on adapters that never read + ``_status_text``.""" store = _lazy_attr(self, "_status_text", dict) if text: store[str(chat_id)] = text @@ -1846,9 +1829,9 @@ class BasePlatformAdapter(ABC): return len def max_message_length_for_chat(self, chat_id: str) -> int: - """Per-chat max length in ``message_len_fn_for_chat`` units. Default: the adapter - scalar ``MAX_MESSAGE_LENGTH`` (4096 when absent); the relay adapter overrides - because one adapter fronts N platforms with different caps.""" + """Per-chat max length in ``message_len_fn_for_chat`` units: the adapter's + ``MAX_MESSAGE_LENGTH`` (4096 when absent); the relay adapter overrides since it fronts N + platforms with different caps.""" return _or_default(lambda: int(getattr(self, "MAX_MESSAGE_LENGTH", 4096) or 4096), 4096) def message_len_fn_for_chat(self, chat_id: str) -> Callable[[str], int]: @@ -1859,23 +1842,19 @@ class BasePlatformAdapter(ABC): @property def enforces_own_access_policy(self) -> bool: """Whether this adapter enforces its own config-driven access policy at intake - (``dm_policy``/``group_policy``/``allow_from``: WeCom, Weixin, QQBot, WhatsApp…). - - The gateway env allowlist runs *after* the adapter; with no env allowlist it trusts - this flag ONLY when the effective policy is a real ``"allowlist"`` — never ``"open"`` - (the default), which would be a network-exposed fail-open (SECURITY.md §2.6). Open - access still requires ``{PLATFORM}_ALLOW_ALL_USERS`` / ``GATEWAY_ALLOW_ALL_USERS``. - """ + (``dm_policy``/``group_policy``/``allow_from``: WeCom, Weixin, QQBot, WhatsApp…). The + gateway env allowlist runs *after* the adapter; without one it trusts this flag ONLY when + the effective policy is a real ``"allowlist"`` — never ``"open"`` (the default), which would + be a network-exposed fail-open (SECURITY.md §2.6). Open access still requires + ``{PLATFORM}_ALLOW_ALL_USERS`` / ``GATEWAY_ALLOW_ALL_USERS``.""" return False @property def authorization_is_upstream(self) -> bool: - """Whether inbound was already authorized by a TRUSTED UPSTREAM (relay only). - - The Team Gateway connector authenticates the WebSocket and resolves owner-only author - binding BEFORE delivery, so the no-allowlist default-deny would be wrong. This is - authorization DELEGATED, not ABSENT — every network-exposed direct adapter leaves it False. - """ + """Whether inbound was already authorized by a TRUSTED UPSTREAM (relay only): the Team + Gateway connector authenticates the WebSocket and resolves owner-only author binding BEFORE + delivery, so the no-allowlist default-deny would be wrong. Authorization DELEGATED, not + ABSENT — every network-exposed direct adapter leaves it False.""" return False def supports_draft_streaming( @@ -1899,13 +1878,10 @@ class BasePlatformAdapter(ABC): async def send_draft(self, chat_id: str, draft_id: int, content: str, metadata: Optional[Dict[str, Any]] = None) -> SendResult: - """Send or update an animated streaming-draft preview. - - Reuse one non-zero ``draft_id`` across a single response so the platform animates; - different responses in the same chat need different ids. Drafts have no message_id - (no edit/reply/delete) — the final answer goes out as a regular ``send``. Must be - overridden by adapters returning True from :meth:`supports_draft_streaming`. - """ + """Send or update an animated streaming-draft preview. Reuse one non-zero ``draft_id`` + across a response so the platform animates (different responses need different ids). Drafts + have no message_id (no edit/reply/delete) — the final answer goes out as a regular ``send``. + Must be overridden by adapters returning True from :meth:`supports_draft_streaming`.""" raise NotImplementedError(f"{type(self).__name__} does not implement send_draft") # ── Structured stream-event rendering (gateway/stream_events.py): presentation-only, @@ -1925,9 +1901,9 @@ class BasePlatformAdapter(ABC): sink.on_commentary(event.text) def format_tool_event(self, event: Any, *, mode: str = "all", preview_max_len: int = 40) -> Optional[str]: - """Rendered chrome for a ToolCallChunk, or None to eat it (adapters without editing/ - rich text override to None). ``mode`` is the tool-progress mode ("all"/"new"/ - "verbose"); ``preview_max_len`` mirrors ``tool_preview_length`` (0 = no cap in verbose).""" + """Rendered chrome for a ToolCallChunk, or None to eat it (adapters without editing/rich + text override to None). ``mode``: tool-progress mode ("all"/"new"/"verbose"); + ``preview_max_len`` mirrors ``tool_preview_length`` (0 = no cap in verbose).""" from gateway.stream_events import ToolCallChunk if not isinstance(event, ToolCallChunk): return None @@ -2111,15 +2087,15 @@ class BasePlatformAdapter(ABC): def set_platform_event_handler( self, handler: Optional[Callable[[Dict[str, Any], Any], Awaitable[None]]]) -> None: - """Install the gateway-owned normalized platform-event boundary: adapters pass stable - dicts plus an internal ``SessionSource``; the runner owns authorization and plugin - dispatch, so no callback = fail closed.""" + """Install the gateway-owned normalized platform-event boundary (stable dicts + internal + ``SessionSource``); the runner owns authorization and plugin dispatch: no callback = fail + closed.""" self._platform_event_handler = handler def set_topic_recovery_fn(self, fn: Optional[Callable[[Any], Optional[str]]]) -> None: - """Install a thread_id-recovery hook (Telegram DM topic mode): called with - ``event.source`` before session keying; a non-None return replaces - ``source.thread_id``. ``None`` clears the hook.""" + """Install a thread_id-recovery hook (Telegram DM topic mode): called with ``event.source`` + before session keying; a non-None return replaces ``source.thread_id``. ``None`` clears + it.""" self._topic_recovery_fn = fn def _apply_topic_recovery(self, event: MessageEvent) -> None: @@ -2147,25 +2123,23 @@ class BasePlatformAdapter(ABC): def set_reaction_handler(self, handler: Optional[Callable[[Dict[str, Any]], Awaitable[None]]]) -> None: """Set the handler for platform-native emoji-reaction events: a normalised dict (``platform``, ``event_name`` "reaction:added"/"reaction:removed", ``reaction``, - ``user_id``, ``item_user_id``, ``channel_id``, ``message_ts``, ``event_ts``, - ``raw_event``) fanned out via ``HookRegistry.emit``.""" + ``user_id``, ``item_user_id``, ``channel_id``, ``message_ts``, ``event_ts``, ``raw_event``) + fanned out via ``HookRegistry.emit``.""" self._reaction_handler = handler def set_authorization_check( self, callback: Optional[Callable[[str, Optional[str], Optional[str]], bool]]) -> None: - """Register ``(user_id, chat_type, chat_id) -> bool``; adapters that pull - external context (Slack thread replies) use it to flag non-allowlisted - senders as unverified background rather than authoritative input.""" + """Register ``(user_id, chat_type, chat_id) -> bool``; adapters pulling external context + (Slack thread replies) use it to flag non-allowlisted senders as unverified background.""" self._authorization_check = callback def _is_sender_authorized(self, user_id: Optional[str], chat_type: Optional[str] = None, chat_id: Optional[str] = None, *, is_bot: bool = False, thread_id: Optional[str] = None) -> Optional[bool]: - """True/False from the registered check, or ``None`` when no check exists ("trust - unknown", legacy). ``is_bot``/``thread_id`` are forwarded as keywords only when set - so legacy three-positional callbacks keep working. Only literal booleans propagate: - a truthy non-boolean is "unknown", never coerced into an authorization that gates - a credentialed side effect.""" + """True/False from the registered check, or None when no check exists ("trust unknown", + legacy). ``is_bot``/``thread_id`` are forwarded as keywords only when set so legacy + three-positional callbacks keep working. Only literal booleans propagate: a truthy + non-boolean is "unknown", never an authorization that gates a credentialed side effect.""" if not user_id or self._authorization_check is None: return None extra: Dict[str, Any] = {**({"is_bot": True} if is_bot else {}), @@ -2193,11 +2167,11 @@ class BasePlatformAdapter(ABC): self._owner_profile = None if (name := (profile_name or "").strip() or None) == "default" else name def _session_key_profile(self, source: Optional[Any] = None) -> Optional[str]: - """Profile namespace for an adapter-derived session key. Ingress runs BEFORE the - runner stamps ``source.profile``, so without this every bot in a multiplexed gateway - shares one ``agent:main:`` lane. Order: ``source.profile`` → ``_owner_profile`` → - session-store resolver; getattr-guarded (object.__new__ in tests) and type-checked - so a MagicMock never lands in the key.""" + """Profile namespace for an adapter-derived session key. Ingress runs BEFORE the runner + stamps ``source.profile``, so without this every bot in a multiplexed gateway shares one + ``agent:main:`` lane. Order: ``source.profile`` → ``_owner_profile`` → session-store + resolver; getattr-guarded (object.__new__ in tests), type-checked (no MagicMock in the + key).""" for candidate in ( getattr(source, "profile", None) if source is not None else None, getattr(self, "_owner_profile", None)): @@ -2333,9 +2307,9 @@ class BasePlatformAdapter(ABC): @abstractmethod async def connect(self, *, is_reconnect: bool = False) -> bool: - """Connect and start receiving; True on success. ``is_reconnect`` is True when the - reconnect watcher re-establishes a dropped platform: adapters with a server-side - update queue (Telegram) must preserve it so outage-time messages aren't discarded.""" + """Connect and start receiving; True on success. ``is_reconnect``: the reconnect watcher is + re-establishing a dropped platform — adapters with a server-side update queue (Telegram) + must preserve it so outage-time messages aren't discarded.""" @abstractmethod async def disconnect(self) -> None: @@ -2351,23 +2325,23 @@ class BasePlatformAdapter(ABC): REQUIRES_EDIT_FINALIZE: bool = False async def create_handoff_thread(self, parent_chat_id: str, name: str) -> Optional[str]: - """Create a fresh thread under ``parent_chat_id`` for a CLI→platform session handoff; - return its id as a string, or ``None`` when threading is unsupported/failed (the - watcher then uses ``parent_chat_id`` directly). Thread-capable adapters override.""" + """Create a fresh thread under ``parent_chat_id`` for a CLI→platform session handoff; its id + as str, or None when unsupported/failed (the watcher then uses ``parent_chat_id`` + directly).""" return None async def edit_message( self, chat_id: str, message_id: str, content: str, *, finalize: bool = False) -> SendResult: - """Edit a sent message. Optional: return success=False and callers send anew. - ``finalize`` marks the last edit of a streamed response; surfaces with a distinct - "in progress" state (DingTalk AI Cards) use it to close the message and should also - set ``REQUIRES_EDIT_FINALIZE`` so the final edit is routed even when content is unchanged.""" + """Edit a sent message (optional: success=False makes callers send anew). ``finalize`` marks + the last edit of a streamed response; surfaces with a distinct "in progress" state (DingTalk + AI Cards) close the message on it and set ``REQUIRES_EDIT_FINALIZE`` so it's routed even + when content is unchanged.""" return SendResult(success=False, error="Not supported") async def delete_message(self, chat_id: str, message_id: str) -> bool: - """Delete a sent message; ``True`` on success. Optional: platforms without a - deletion API return ``False`` and callers leave the message in place. - Used by the stream consumer's fresh-final cleanup to remove stale previews.""" + """Delete a sent message; True on success (platforms without a deletion API return False and + callers leave it). Used by the stream consumer's fresh-final cleanup to remove stale + previews.""" return False def _get_ephemeral_system_ttl_default(self) -> int: @@ -2422,9 +2396,9 @@ class BasePlatformAdapter(ABC): @staticmethod def _format_choice_page(options: list, page: int, per_page: int) -> "tuple[list, Dict[str, Any]]": - """Shared picker pagination: clamp ``page``, slice ``options``, return - ``(page_options, meta)`` with ``page``/``total_pages``/``start``/``end``/ - ``total``/``page_info`` (the `` (N–M of T)`` suffix, empty for one page).""" + """Shared picker pagination: clamp ``page``, slice ``options`` -> ``(page_options, meta)`` + with ``page``/``total_pages``/``start``/``end``/``total``/``page_info`` (`` (N–M of T)``, + empty for one page).""" total = len(options) total_pages = max(1, (total + per_page - 1) // per_page) page = max(0, min(page, total_pages - 1)) @@ -2437,22 +2411,22 @@ class BasePlatformAdapter(ABC): async def send_slash_confirm( self, chat_id: str, title: str, message: str, session_key: str, confirm_id: str, metadata: Optional[Dict[str, Any]] = None) -> SendResult: - """Send a three-option slash-command confirmation (e.g. ``/reload-mcp``). Button - adapters override to render Approve Once / Always Approve / Cancel and MUST resolve - via ``GatewayRunner._resolve_slash_confirm(confirm_id, choice)`` with ``"once"``/ - ``"always"``/``"cancel"``. Default (not supported) falls through to the gateway text - fallback (``/approve``/``/always``/``/cancel``).""" + """Three-option slash-command confirmation (e.g. ``/reload-mcp``). Button adapters render + Approve Once / Always Approve / Cancel and MUST resolve via + ``GatewayRunner._resolve_slash_confirm(confirm_id, "once"|"always"|"cancel")``. Default (not + supported) falls through to the gateway text fallback + (``/approve``/``/always``/``/cancel``).""" return SendResult(success=False, error="Not supported") async def send_clarify( self, chat_id: str, question: str, choices: Optional[list], clarify_id: str, session_key: str, metadata: Optional[Dict[str, Any]] = None) -> SendResult: - """Send a clarify prompt; button-capable adapters SHOULD override. Multiple choice - (``choices`` non-empty): one button per choice plus "Other"; callbacks MUST resolve via - ``tools.clarify_gateway.resolve_gateway_clarify(clarify_id, response)`` and "Other" - calls ``mark_awaiting_text(clarify_id)``. Open-ended: send the question as text; the - gateway text-intercept resolves the next message. Default: numbered text list + - ``mark_awaiting_text`` so replies aren't lost.""" + """Clarify prompt; button-capable adapters SHOULD override. Multiple choice (``choices``): + one button per choice plus "Other"; callbacks MUST resolve via + ``tools.clarify_gateway.resolve_gateway_clarify(clarify_id, response)``, "Other" calls + ``mark_awaiting_text(clarify_id)``. Open-ended: send the question as text (the gateway + text-intercept resolves the next message). Default: numbered list + + ``mark_awaiting_text``.""" if choices: # Multi-select flag lives on the pending entry; look it up by id so the # signature stays adapter-compatible. @@ -2512,9 +2486,9 @@ class BasePlatformAdapter(ABC): async def send_multiple_images( self, chat_id: str, images: List[Tuple[str, str]], metadata: Optional[Dict[str, Any]] = None, human_delay: float = 0.0) -> None: - """Send a batch of ``(url, alt)`` images (``http(s)://`` or ``file://``) individually - (GIFs via ``send_animation``, local files via ``send_image_file``); override to - bundle into one native call (Signal).""" + """Send ``(url, alt)`` images (``http(s)://`` or ``file://``) one by one (GIFs via + ``send_animation``, local files via ``send_image_file``); override to bundle natively + (Signal).""" from urllib.parse import unquote as _unquote for image_url, alt_text in images: if human_delay > 0: @@ -2545,7 +2519,8 @@ class BasePlatformAdapter(ABC): async def send_animation( self, chat_id: str, animation_url: str, caption: Optional[str] = None, reply_to: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None) -> SendResult: - """Send a GIF as a native animation (auto-plays inline); default falls back to send_image.""" + """Send a GIF as a native animation (auto-plays inline); default falls back to + send_image.""" return await self.send_image( chat_id=chat_id, image_url=animation_url, caption=caption, reply_to=reply_to, metadata=metadata) @@ -2591,18 +2566,18 @@ class BasePlatformAdapter(ABC): self, method: str, kind: str, path: str, chat_id: str, caption: Optional[str], reply_to: Optional[str], metadata: Optional[Dict[str, Any]], *, file_name: Optional[str] = None, ) -> SendResult: - """Shared default for send_voice/send_video/send_document/send_image_file. The local - path is logged but NEVER echoed into chat (it would leak the host layout); only the - caller-supplied ``file_name`` is shown.""" + """Shared default for send_voice/send_video/send_document/send_image_file. The local path is + logged but NEVER echoed into chat (host layout leak); only the caller's ``file_name`` is + shown.""" logger.warning("[%s] %s fallback: native %s send unavailable for %s", self.name, method, kind, path) text = _media_failure_text(kind, file_name) text = f"{caption}\n{text}" if caption else text return await self.send(chat_id=chat_id, content=text, reply_to=reply_to, metadata=metadata) def prepare_tts_text(self, text: str) -> str: - """Turn chat Markdown into a transcript-like spoken script: reasoning blocks - removed, headings/bullets flattened, units expanded (``°C`` → degrees Celsius). - Chunking and delivery limits are the TTS tool's job.""" + """Chat Markdown -> transcript-like spoken script (reasoning blocks removed, + headings/bullets flattened, units expanded). Chunking and delivery limits are the TTS tool's + job.""" try: from tools.tts_text_normalize import prepare_spoken_text return prepare_spoken_text(text, max_chars=None) @@ -2710,9 +2685,9 @@ class BasePlatformAdapter(ABC): @staticmethod def _mask_protected_spans(content: str) -> str: - """Blank fenced code, inline code and blockquotes (length-preserving, so - regex offsets stay valid) to prevent MEDIA: false positives; backtick-quoted - paths inside MEDIA: tags are left scannable.""" + """Blank fenced code, inline code and blockquotes (length-preserving so regex offsets stay + valid) against MEDIA: false positives; backtick-quoted paths inside MEDIA: tags stay + scannable.""" spans: list = [m.span() for m in _FENCED_CODE_RE.finditer(content)] for m in _INLINE_CODE_RE.finditer(content): start = m.start() @@ -2732,11 +2707,11 @@ class BasePlatformAdapter(ABC): @staticmethod def _mask_json_string_media(content: str) -> str: - """Blank ``MEDIA:`` tags inside JSON string *values* (stored tool-result - text like ``{"result": "MEDIA:/x/stale.png"}``) so they are never re-delivered. Only - spans opened by a value-context quote (``:,{[`` before the ``"``) count, and only bare - paths (``/``, ``~/``, ``X:\\``) — ``MEDIA:"..."`` quoted tags and line-start/prose tags - are untouched. Offsets are preserved (blanked with spaces).""" + """Blank ``MEDIA:`` tags inside JSON string *values* (stored tool-result text + like ``{"result": "MEDIA:/x/stale.png"}``) so they are never re-delivered. Only + value-context strings (``:,{[`` before the ``"``) and bare paths (``/``, ``~/``, ``X:\``) + count; ``MEDIA:"..."`` quoted tags and line-start/prose tags are untouched. Offsets + preserved.""" if '"' not in content or "MEDIA:" not in content: return content # JSON value-context string: a quote preceded by : , { or [ (optional ws), @@ -2748,11 +2723,10 @@ class BasePlatformAdapter(ABC): @staticmethod def extract_media(content: str) -> Tuple[List[Tuple[str, bool]], str]: - """Extract ``MEDIA:`` tags and strip the ``[[audio_as_voice]]`` / - ``[[as_document]]`` directives; returns ``([(path, is_voice), ...], cleaned)``. - Both directives are message-global; ``[[as_document]]`` (unmodified sendDocument - delivery for large images) is detected by dispatch sites on the original response - and only stripped here.""" + """Extract ``MEDIA:`` tags and strip ``[[audio_as_voice]]`` / ``[[as_document]]`` -> + ``([(path, is_voice), ...], cleaned)``. Both directives are message-global; + ``[[as_document]]`` (unmodified sendDocument for large images) is detected by dispatch sites + on the ORIGINAL response and only stripped here.""" media = [] has_voice_tag = "[[audio_as_voice]]" in content cleaned = content.replace("[[audio_as_voice]]", "").replace("[[as_document]]", "") @@ -2801,11 +2775,10 @@ class BasePlatformAdapter(ABC): @staticmethod def extract_local_files(content: str) -> Tuple[List[str], str]: - """Detect bare local file paths (absolute, ``~/`` or drive-letter) with deliverable - extensions and return ``(expanded_paths, cleaned_text)``. Candidates must exist on - disk (``os.path.isfile``) so URLs and hallucinated paths are ignored; paths inside - fenced or inline code are skipped so code samples are never mutilated. Dispatch by - type lives in ``gateway/run.py``.""" + """Bare local file paths (absolute, ``~/`` or drive-letter) with deliverable extensions -> + ``(expanded_paths, cleaned_text)``. Candidates must exist on disk (URLs / hallucinated paths + ignored); paths inside fenced or inline code are skipped so code samples are never + mutilated. Dispatch by type lives in ``gateway/run.py``.""" ext_part = '|'.join(e.lstrip('.') for e in MEDIA_DELIVERY_EXTS) # Lookbehind rejects URL/relative-path matches (https://…/img.png, ./foo.png); # the alternation anchors Unix absolute, ``~/`` and Windows drive paths. @@ -2831,13 +2804,10 @@ class BasePlatformAdapter(ABC): async def _keep_typing(self, chat_id: str, interval: float = 2.0, metadata=None, stop_event: asyncio.Event | None = None) -> None: - """Refresh the typing indicator every ``interval`` seconds until cancelled. - - Platform typing state expires after ~5s. Chats in ``_typing_paused`` are skipped - (approval waits — Slack's setStatus disables the compose box). Each ``send_typing`` - is bounded by a sub-interval timeout (below ``interval``) so one slow round-trip - is abandoned before the next tick rather than letting the bubble lapse. - """ + """Refresh the typing indicator every ``interval`` seconds until cancelled (platform typing + state expires after ~5s). Chats in ``_typing_paused`` are skipped (approval waits — Slack's + setStatus disables the compose box). Each ``send_typing`` is bounded by a sub-interval + timeout so one slow round-trip is abandoned before the next tick, not the bubble lapsing.""" _send_typing_timeout = max(0.25, min(1.5, interval - 0.25)) try: while True: @@ -2916,12 +2886,10 @@ class BasePlatformAdapter(ABC): def register_post_delivery_callback( self, session_key: str, callback: Callable, *, generation: int | None = None) -> None: - """Register a deferred callback to fire after the main response. - - Same-key registrations are chained (both fire, in order, with per-callback - exception isolation) so independent features coexist. ``generation`` ties - the callback to a gateway run; stale generations never overwrite a fresher slot. - """ + """Register a deferred callback to fire after the main response. Same-key registrations are + chained (both fire in order, per-callback exception isolation) so independent features + coexist; ``generation`` ties it to a gateway run — stale generations never overwrite a + fresher slot.""" if not session_key or not callable(callback): return existing = self._post_delivery_callbacks.get(session_key) @@ -2973,13 +2941,10 @@ class BasePlatformAdapter(ABC): """Hook called when background processing begins.""" async def on_processing_complete(self, event: MessageEvent, outcome: ProcessingOutcome) -> None: - """Hook called when background processing completes. - - Default: opt-in reaction ack — with ``_OK_EMOJI``/``_FAIL_EMOJI`` set and - ``_add_reaction``/``_remove_reaction`` present, swap the in-progress reaction - for the outcome one. Remove-then-add is deterministic whether the platform - replaces or stacks a sender's reactions. CANCELLED leaves it unreacted. - """ + """Hook called when background processing completes. Default: opt-in reaction ack — with + ``_OK_EMOJI``/``_FAIL_EMOJI`` set and ``_add_reaction``/``_remove_reaction`` present, swap + the in-progress reaction for the outcome one. Remove-then-add is deterministic whether the + platform replaces or stacks a sender's reactions. CANCELLED leaves it unreacted.""" if self._OK_EMOJI is None and self._FAIL_EMOJI is None: return add: Any = getattr(self, "_add_reaction", None) @@ -3022,12 +2987,10 @@ class BasePlatformAdapter(ABC): return any(pat in lowered for pat in ("timed out", "readtimeout", "writetimeout")) def _unwrap_ephemeral(self, response: Any) -> Tuple[Optional[str], int]: - """Unwrap a str/None/:class:`EphemeralReply` response into ``(text, ttl)``. - - ``ttl > 0`` means the caller should schedule ``_schedule_ephemeral_delete`` - after a successful send; forced to 0 when the adapter doesn't override - ``delete_message`` so non-supporting platforms degrade to normal sends. - """ + """Unwrap a str/None/:class:`EphemeralReply` response into ``(text, ttl)``. ``ttl > 0`` + means schedule ``_schedule_ephemeral_delete`` after a successful send; forced to 0 when the + adapter doesn't override ``delete_message`` so non-supporting platforms degrade to normal + sends.""" if not isinstance(response, EphemeralReply): return response, 0 ttl = response.ttl_seconds @@ -3056,12 +3019,9 @@ class BasePlatformAdapter(ABC): chat_id=event.source.chat_id, message_id=result.message_id, ttl_seconds=eph_ttl) def _final_delivery_adapter(self, source: Optional[SessionSource]) -> "BasePlatformAdapter": - """Return the runner's current adapter for a new final-response send. - - A reconnect can swap the registry adapter while this task is in flight; an - unsent final response belongs on the replacement transport, but message IDs, - edits and deletes stay owned by the old one (nothing is migrated). - """ + """The runner's CURRENT adapter for a new final-response send: a reconnect can swap the + registry adapter mid-task; an unsent final response belongs on the replacement transport, + while message IDs, edits and deletes stay owned by the old one (nothing is migrated).""" resolve = getattr(self.gateway_runner, "_adapter_for_source", None) if not callable(resolve): return self @@ -3128,9 +3088,9 @@ class BasePlatformAdapter(ABC): @staticmethod def _merge_caption(existing_text: Optional[str], new_text: str) -> str: - """Merge a new caption into existing text unless an identical (whitespace- - normalised) caption already exists — exact match per caption, not - substring, so "Meeting" is not swallowed by "Meeting agenda".""" + """Merge a new caption into existing text unless an identical (stripped) caption already + exists — exact match per caption, not substring ("Meeting" isn't swallowed by "Meeting + agenda").""" if not existing_text: return new_text if new_text.strip() in [c.strip() for c in existing_text.split("\n\n")]: @@ -3250,25 +3210,22 @@ class BasePlatformAdapter(ABC): # and stale-lock self-heal on the next inbound message. def _release_session_guard(self, session_key: str, *, guard: Optional[asyncio.Event] = None) -> None: - """Release the session guard; with ``guard`` given, only if the entry is - still that exact Event (so an old task's unwind can't clear the temporary - guard a reset-like command swapped in).""" + """Release the session guard; with ``guard`` given, only if the entry is still that exact + Event (an old task's unwind must not clear the guard a reset-like command swapped in).""" current_guard = self._active_sessions.get(session_key) if current_guard is None or (guard is not None and current_guard is not guard): return del self._active_sessions[session_key] def _session_task_is_stale(self, session_key: str) -> bool: - """True if the recorded owner task for ``session_key`` has exited. No owner - task at all is NOT stale (guards installed outside handle_message, as tests - do, must not be healed); only owner-recorded-then-exited counts.""" + """True if the recorded owner task for ``session_key`` has exited. No owner task at all is + NOT stale (guards installed outside handle_message, as tests do, must not be healed).""" done = getattr(self._session_tasks.get(session_key), "done", None) return bool(done and done()) def _heal_stale_session_lock(self, session_key: str) -> bool: - """Clear a stale session lock; True if healed, False if no lock or the owner - is still alive. On-entry safety net: without it a split-brain (guard held, - nothing processing) traps the chat in "Interrupting..." until restart.""" + """Clear a stale session lock; True if healed. On-entry safety net: without it a split-brain + (guard held, nothing processing) traps the chat in "Interrupting..." until restart.""" if session_key not in self._active_sessions or not self._session_task_is_stale(session_key): return False logger.warning("[%s] Healing stale session lock for %s (owner task is done/absent)", @@ -3281,9 +3238,9 @@ class BasePlatformAdapter(ABC): def _start_session_processing(self, event: MessageEvent, session_key: str, *, interrupt_event: Optional[asyncio.Event] = None) -> bool: - """Spawn a background processing task under the session guard; True on - success. If ``create_task`` is stubbed with a non-Task sentinel (tests), - the guard is rolled back and False returned — no half-installed lock.""" + """Spawn a background processing task under the session guard; True on success. If + ``create_task`` is stubbed with a non-Task sentinel (tests), the guard is rolled back + (False).""" guard = interrupt_event or asyncio.Event() self._active_sessions[session_key] = guard task = asyncio.create_task(self._process_message_background(event, session_key)) @@ -3295,8 +3252,8 @@ class BasePlatformAdapter(ABC): def _track_session_task(self, session_key: str, task: Any) -> bool: """Record ``task`` as the session owner and track it for shutdown; False when - ``create_task`` was stubbed with an unhashable sentinel (tests) — the owner entry - is left for the caller to roll back.""" + ``create_task`` was stubbed with an unhashable sentinel (tests) — the owner entry is left + for the caller.""" self._session_tasks[session_key] = task try: self._background_tasks.add(task) @@ -3309,9 +3266,9 @@ class BasePlatformAdapter(ABC): async def cancel_session_processing(self, session_key: str, *, release_guard: bool = True, discard_pending: bool = True) -> None: - """Cancel in-flight processing for one session. ``release_guard=False`` keeps - the guard so reset-like commands finish atomically before follow-ups start; - the await is bounded (5s) so a wedged finally block can't stall dispatch.""" + """Cancel in-flight processing for one session. ``release_guard=False`` keeps the guard so + reset-like commands finish atomically; the await is bounded (5s) so a wedged finally can't + stall.""" task = self._session_tasks.pop(session_key, None) if task is not None and not task.done(): logger.debug("[%s] Cancelling active processing for session %s", self.name, session_key) @@ -3345,9 +3302,9 @@ class BasePlatformAdapter(ABC): self._start_session_processing(pending_event, session_key) async def _dispatch_active_session_command(self, event: MessageEvent, session_key: str, cmd: str) -> None: - """Dispatch a reset-like bypass command (/stop, /new, /reset): keep a guard - installed while the runner handles it (racing follow-ups stay queued), cancel - the old task AFTER the response is sent, then release and drain once.""" + """Dispatch a reset-like bypass command (/stop, /new, /reset): keep a guard installed while + the runner handles it (follow-ups stay queued), cancel the old task AFTER the response, + drain once.""" logger.debug("[%s] Command '/%s' bypassing active-session guard for %s", self.name, cmd, session_key) current_guard = self._active_sessions.get(session_key) command_guard = asyncio.Event() @@ -3455,9 +3412,9 @@ class BasePlatformAdapter(ABC): @staticmethod def _get_human_delay() -> float: - """Random human-like pacing delay in seconds, from HERMES_HUMAN_DELAY_MODE - ("off" default | "natural" 800-2500ms | "custom" via - HERMES_HUMAN_DELAY_MIN_MS / HERMES_HUMAN_DELAY_MAX_MS).""" + """Random human-like pacing delay (s) from HERMES_HUMAN_DELAY_MODE: "off" (default) | + "natural" 800-2500ms | "custom" via HERMES_HUMAN_DELAY_MIN_MS / + HERMES_HUMAN_DELAY_MAX_MS.""" mode = os.getenv("HERMES_HUMAN_DELAY_MODE", "off").lower() if mode == "off": return 0.0 @@ -3469,9 +3426,9 @@ class BasePlatformAdapter(ABC): _ms("HERMES_HUMAN_DELAY_MAX_MS", 2500) / 1000.0) async def _synthesize_auto_tts(self, text_content: str) -> Tuple[List[str], Optional[str]]: - """Synthesize auto-TTS audio -> ``(existing_paths, requested_path)``; empty/None - on failure (logged, never raised). The path is built platform-aware here - because HERMES_SESSION_PLATFORM is already cleared post-handler.""" + """Synthesize auto-TTS audio -> ``(existing_paths, requested_path)``; empty/None on failure + (logged, never raised). Path built platform-aware HERE: HERMES_SESSION_PLATFORM is cleared + post-handler.""" paths: List[str] = [] requested_path = None try: @@ -3519,9 +3476,9 @@ class BasePlatformAdapter(ABC): async def _record_delivery_obligation( self, event: MessageEvent, session_key: str, text_content: str, delivery_adapter: "BasePlatformAdapter", is_ephemeral_response: bool) -> Optional[str]: - """Record the final response in the ledger BEFORE the send so a crash before - platform ACK redelivers on next boot; best-effort, skips slash-command and - ephemeral replies. Returns the obligation id or None.""" + """Ledger the final response BEFORE the send so a crash before platform ACK redelivers on + next boot; best-effort, skips slash-command and ephemeral replies. Returns the obligation id + or None.""" if is_ephemeral_response or str(event.text or "").lstrip().startswith( ("/", self.typed_command_prefix or "!")): return None @@ -3547,9 +3504,9 @@ class BasePlatformAdapter(ABC): async def _finalize_delivery_obligation( self, obligation_id: str, result: Any, event: MessageEvent, delivery_adapter: "BasePlatformAdapter") -> None: - """Mark the ledger row delivered/failed (best-effort). On ``send_path_degraded`` - with a replacement adapter live, signal another redelivery sweep (the watcher's - may have run before this failure landed; atomic claiming keeps it idempotent).""" + """Mark the ledger row delivered/failed (best-effort). On ``send_path_degraded`` with a + replacement adapter live, trigger another redelivery sweep (the watcher's may have run + before this failure landed; atomic claiming keeps it idempotent).""" try: from gateway.delivery_ledger import mark_delivered, mark_failed if getattr(result, "success", False): @@ -3570,10 +3527,10 @@ class BasePlatformAdapter(ABC): async def _deliver_media_attachments( self, event: MessageEvent, media_files: list, local_files: list, *, force_document_attachments: bool, human_delay: float, metadata: Dict[str, Any]) -> None: - """Deliver MEDIA-tag files and auto-detected local files by type: images are - batched via ``send_multiple_images`` unless ``[[as_document]]`` forced document - delivery; other MEDIA files route audio → send_voice, video → send_video, else - send_document (local files never go to send_voice). Every failure is reported.""" + """Deliver MEDIA-tag files and detected local files by type: images batched via + ``send_multiple_images`` unless ``[[as_document]]``; otherwise audio → send_voice (MEDIA + tags only, never bare local files), video → send_video, else send_document. Every failure is + reported.""" from urllib.parse import quote as _quote def _as_image(path: str) -> bool: @@ -3586,7 +3543,8 @@ class BasePlatformAdapter(ABC): chat_id = event.source.chat_id async def _send_one(path: str, *, is_voice: bool, media_tag: bool) -> None: - """MEDIA-tag files (``media_tag``) may route to send_voice; bare local files never do.""" + """MEDIA-tag files (``media_tag``) may route to send_voice; bare local files never + do.""" ext = Path(path).suffix.lower() if media_tag and should_send_media_as_audio(self.platform, ext, is_voice=is_voice): result = await self.send_voice(chat_id=chat_id, audio_path=path, metadata=metadata, is_voice=is_voice) @@ -3694,11 +3652,10 @@ class BasePlatformAdapter(ABC): async def _extract_response_content(self, response: str, event: MessageEvent, session_key: str, *, is_ephemeral_response: bool) -> "_ExtractedResponse": - """Split a handler response into deliverable text + attachments. Order matters: - MEDIA tags → image URLs → residual directives → bare local paths (skipped for - ephemeral notices so config paths stay text; unknown-extension MEDIA tags survive - the strip for the bare-path detector). History dedup is bare-path only, off-loop, - fail-open. If extraction empties a non-empty response, the text is recovered.""" + """Split a handler response into deliverable text + attachments. Order matters: MEDIA tags → + image URLs → residual directives → bare local paths (skipped for ephemeral notices so config + paths stay text; unknown-extension MEDIA tags survive for the bare-path detector). History + dedup is bare-path only, off-loop, fail-open. An emptied non-empty response is recovered.""" # Captured before extract_media strips it: images then go via send_document (no recompression). force_document = "[[as_document]]" in response pre_extract = response @@ -3737,9 +3694,9 @@ class BasePlatformAdapter(ABC): local_files=local_files, force_document_attachments=force_document, pre_extract=pre_extract) async def _fire_post_delivery_callback(self, session_key: str, interrupt_event: asyncio.Event) -> None: - """Run the one-shot post-delivery callback (bounded, errors swallowed). The - generation is read HERE: it is stamped on the interrupt event DURING the handler - await, so an earlier snapshot would let stale runs fire a fresher run's callbacks.""" + """Run the one-shot post-delivery callback (bounded, errors swallowed). The generation is + read HERE — stamped on the interrupt event DURING the handler await; an earlier snapshot + would let stale runs fire a fresher run's callbacks.""" _post_cb = self.pop_post_delivery_callback( session_key, generation=getattr(interrupt_event, "_hermes_run_generation", None)) if callable(_post_cb): @@ -3749,10 +3706,10 @@ class BasePlatformAdapter(ABC): await asyncio.wait_for(_post_result, timeout=_POST_DELIVERY_CALLBACK_TIMEOUT_SECONDS) def _finish_session_task(self, session_key: str, interrupt_event: asyncio.Event) -> None: - """End-of-task guard/ownership reconciliation. A late ``_pending_messages`` - arrival must not drop: re-queue it if another task already owns the session - (drain handoff), else spawn the drain task and leave it the guard. With - nothing pending, release the guard only if we still own the session.""" + """End-of-task guard/ownership reconciliation. A late ``_pending_messages`` arrival must not + drop: re-queue it if another task already owns the session (drain handoff), else spawn the + drain task and leave it the guard. Nothing pending: release the guard only if we still own + it.""" late_pending = self._pending_messages.pop(session_key, None) current_task = asyncio.current_task() if late_pending is not None: @@ -3876,8 +3833,8 @@ class BasePlatformAdapter(ABC): def _spawn_drain_task(self, pending_event: MessageEvent, session_key: str) -> None: """Hand the session to a fresh task for a queued follow-up — never recurse (chained - follow-ups grew the C stack to SIGSEGV). Clearing, not deleting, the Event keeps - the guard live for concurrent inbound; ownership moves so stale-lock detection works.""" + follow-ups grew the C stack to SIGSEGV). Clearing (not deleting) the Event keeps the guard + live for concurrent inbound; ownership moves so stale-lock detection works.""" _active = self._active_sessions.get(session_key) if _active is not None: _active.clear() @@ -3886,9 +3843,9 @@ class BasePlatformAdapter(ABC): def _cleanup_finished_session_task( self, session_key: str, interrupt_event: Optional[asyncio.Event]) -> None: - """Release a finished owner task's guard, dropping its ``_session_tasks`` entry - ONLY if the guard was actually released: if a concurrent path swapped guards, - the done-task entry lets ``_session_task_is_stale`` heal the orphan.""" + """Release a finished owner task's guard, dropping its ``_session_tasks`` entry ONLY if the + guard was released: after a concurrent guard swap the done-task entry lets + ``_session_task_is_stale`` heal the orphan.""" self._release_session_guard(session_key, guard=interrupt_event) if session_key not in self._active_sessions: self._session_tasks.pop(session_key, None) @@ -3993,10 +3950,9 @@ class BasePlatformAdapter(ABC): @staticmethod def truncate_message(content: str, max_length: int = 4096, len_fn: Optional["Callable[[str], int]"] = None) -> List[str]: - """Split a long message into chunks, preserving code-block boundaries: a split - inside a fence closes it at the chunk end and reopens it (same language tag) in - the next; multi-chunk output gets ``(1/3)`` indicators. ``len_fn`` overrides - ``len`` (``utf16_len`` for Telegram, which counts UTF-16 code units).""" + """Split a long message into chunks preserving code blocks: a split inside a fence closes it + at the chunk end and reopens it (same language tag) in the next; multi-chunk output gets + ``(1/3)`` indicators. ``len_fn`` overrides ``len`` (``utf16_len`` for Telegram).""" _len = len_fn or len if _len(content) <= max_length: return [content] From d7fc269b9fc0ef62153ec2c8b1060da412d63830 Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Wed, 2 Sep 2026 23:12:17 -0700 Subject: [PATCH 05/13] =?UTF-8?q?refactor(gateway/platforms):=20base.py=20?= =?UTF-8?q?=E2=80=94=20collapse=20redundant=20guards=20(hasattr=20stop=5Ft?= =?UTF-8?q?yping,=20active-guard=20clear=20helper,=20retry=20backoff),=20s?= =?UTF-8?q?implify=20small=20bodies?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- gateway/platforms/base.py | 106 +++++++++++++++++--------------------- 1 file changed, 47 insertions(+), 59 deletions(-) diff --git a/gateway/platforms/base.py b/gateway/platforms/base.py index 0060ec824c..ea48296eea 100644 --- a/gateway/platforms/base.py +++ b/gateway/platforms/base.py @@ -2056,10 +2056,10 @@ class BasePlatformAdapter(ABC): """Invoke plugin-registered native handler factories (``ctx.register_platform_handler``) with ``(native, adapter)``; adapters call this from ``connect()`` once the native client exists. Each factory is isolated so a bad plugin can't block connecting.""" - platform_name = getattr(self.platform, "value", str(self.platform)) try: from hermes_cli.plugins import get_plugin_manager - factories = get_plugin_manager().get_platform_handler_factories(platform_name) + factories = get_plugin_manager().get_platform_handler_factories( + getattr(self.platform, "value", str(self.platform))) except Exception as e: # pragma: no cover - defensive logger.warning("[%s] Could not load plugin handler factories: %s", self.name, e) return @@ -2106,11 +2106,11 @@ class BasePlatformAdapter(ABC): return try: recovered = recover(source) + if recovered is None or str(recovered) == str(source.thread_id or ""): + return except Exception: logger.debug("topic recovery hook failed", exc_info=True) return - if recovered is None or str(recovered) == str(source.thread_id or ""): - return try: event.source = dataclasses.replace(source, thread_id=str(recovered)) except Exception: @@ -2179,24 +2179,23 @@ class BasePlatformAdapter(ABC): return candidate store = getattr(self, "_session_store", None) resolver = getattr(store, "_resolve_profile_for_key", None) if store else None - if callable(resolver): - try: - resolved = resolver(source) - except Exception: - return None - if isinstance(resolved, str) and resolved.strip(): - return resolved - return None + if not callable(resolver): + return None + try: + resolved = resolver(source) + except Exception: + return None + return resolved if isinstance(resolved, str) and resolved.strip() else None # ── Inbound text batching (adapters that merge split messages): subclasses supply # ``_pending_text_batches`` / ``_pending_text_batch_tasks`` dicts and ``_flush_text_batch(key)``. def _event_session_key(self, event: "MessageEvent") -> str: """Adapter-level session key for ``event``, profile-namespaced like the agent run.""" + extra = self.config.extra return build_session_key( - event.source, - group_sessions_per_user=self.config.extra.get("group_sessions_per_user", True), - thread_sessions_per_user=self.config.extra.get("thread_sessions_per_user", False), + event.source, group_sessions_per_user=extra.get("group_sessions_per_user", True), + thread_sessions_per_user=extra.get("thread_sessions_per_user", False), profile=self._session_key_profile(event.source)) def _text_batch_key(self, event: "MessageEvent") -> str: @@ -2207,17 +2206,15 @@ class BasePlatformAdapter(ABC): """Buffer a text event (merging into a pending one) and restart the flush timer.""" key = self._text_batch_key(event) existing = self._pending_text_batches.get(key) - chunk_len = len(event.text or "") if existing is None: - event._last_chunk_len = chunk_len # type: ignore[attr-defined] - self._pending_text_batches[key] = event + existing = self._pending_text_batches[key] = event else: if event.text: existing.text = _append_text(existing.text, event.text) - existing._last_chunk_len = chunk_len # type: ignore[attr-defined] if event.media_urls: existing.media_urls.extend(event.media_urls) existing.media_types.extend(event.media_types) + existing._last_chunk_len = len(event.text or "") # type: ignore[attr-defined] prior_task = self._pending_text_batch_tasks.get(key) if prior_task and not prior_task.done(): prior_task.cancel() @@ -2254,8 +2251,7 @@ class BasePlatformAdapter(ABC): history.remove(last_reply) if not history: return None - # Avoid circular import: gateway.run already imports this module. - from gateway.run import _collect_history_media_paths + from gateway.run import _collect_history_media_paths # lazy: gateway.run imports us return _collect_history_media_paths(history) async def _bounded_history_media_paths_for_session(self, session_key: str) -> Optional[set]: @@ -2433,8 +2429,7 @@ class BasePlatformAdapter(ABC): try: from tools import clarify_gateway as _cg with _cg._lock: - _entry = _cg._entries.get(clarify_id) - _is_multi = bool(_entry and getattr(_entry, "multi_select", False)) + _is_multi = bool(getattr(_cg._entries.get(clarify_id), "multi_select", False)) except Exception: _is_multi = False hint = ( @@ -2709,7 +2704,7 @@ class BasePlatformAdapter(ABC): def _mask_json_string_media(content: str) -> str: """Blank ``MEDIA:`` tags inside JSON string *values* (stored tool-result text like ``{"result": "MEDIA:/x/stale.png"}``) so they are never re-delivered. Only - value-context strings (``:,{[`` before the ``"``) and bare paths (``/``, ``~/``, ``X:\``) + value-context strings (``:,{[`` before the ``"``) and bare paths (``/``, ``~/``, ``X:\\``) count; ``MEDIA:"..."`` quoted tags and line-start/prose tags are untouched. Offsets preserved.""" if '"' not in content or "MEDIA:" not in content: @@ -2797,10 +2792,12 @@ class BasePlatformAdapter(ABC): else: # Most common reason a promised file never arrives — log the gap. logger.info("Skipping bare file path in reply (no file on disk): %s", _log_safe_path(raw)) + if not unique: + return [], content cleaned = content for raw in unique.values(): cleaned = cleaned.replace(raw, '') - return list(unique), re.sub(r'\n{3,}', '\n\n', cleaned).strip() if unique else cleaned + return list(unique), re.sub(r'\n{3,}', '\n\n', cleaned).strip() async def _keep_typing(self, chat_id: str, interval: float = 2.0, metadata=None, stop_event: asyncio.Event | None = None) -> None: @@ -2838,8 +2835,7 @@ class BasePlatformAdapter(ABC): finally: # A send_typing after an outer stop_typing() may have recreated the # platform typing loop; cancelling this task alone won't clean it up. - if hasattr(self, "stop_typing"): - await self._stop_typing_quietly(chat_id, metadata) + await self._stop_typing_quietly(chat_id, metadata) self._typing_paused.discard(chat_id) # getattr-guard: tests build adapters via object.__new__ without _status_text. getattr(self, "_status_text", {}).pop(str(chat_id), None) @@ -2855,8 +2851,6 @@ class BasePlatformAdapter(ABC): # Slow adapter cleanup must not block delivery/shutdown. with contextlib.suppress(asyncio.CancelledError, asyncio.TimeoutError): await asyncio.wait_for(asyncio.shield(typing_task), timeout=timeout) - if not hasattr(self, "stop_typing"): - return for attempt in range(max(1, stop_attempts)): if attempt: await asyncio.sleep(0) @@ -2879,9 +2873,8 @@ class BasePlatformAdapter(ABC): async def interrupt_session_activity(self, session_key: str, chat_id: str, metadata=None) -> None: """Signal the active session loop to stop and clear typing immediately.""" - interrupt_event = self._active_sessions.get(session_key) if session_key else None - if interrupt_event is not None: - interrupt_event.set() + if session_key and session_key in self._active_sessions: + self._active_sessions[session_key].set() await self._stop_typing_quietly(chat_id, metadata) def register_post_delivery_callback( @@ -3015,8 +3008,7 @@ class BasePlatformAdapter(ABC): chat_id=event.source.chat_id, content=text, reply_to=_reply_anchor_for_event(event), metadata=_mark_notify_metadata(thread_meta)) if eph_ttl > 0 and result.success and result.message_id: - self._schedule_ephemeral_delete( - chat_id=event.source.chat_id, message_id=result.message_id, ttl_seconds=eph_ttl) + self._schedule_ephemeral_delete(event.source.chat_id, result.message_id, eph_ttl) def _final_delivery_adapter(self, source: Optional[SessionSource]) -> "BasePlatformAdapter": """The runner's CURRENT adapter for a new final-response send: a reconnect can swap the @@ -3052,9 +3044,9 @@ class BasePlatformAdapter(ABC): # A server-requested retry_after (Telegram FloodWait) overrides backoff, once per send. server_retry_after = result.retry_after for attempt in range(1, max_retries + 1): - backoff = base_delay * (2 ** (attempt - 1)) - if server_retry_after is not None: - backoff = server_retry_after + backoff = server_retry_after + if backoff is None: + backoff = base_delay * (2 ** (attempt - 1)) delay = backoff + random.uniform(0, 1) server_retry_after = None logger.warning("[%s] Send failed (attempt %d/%d, retrying in %.1fs): %s", self.name, @@ -3065,8 +3057,7 @@ class BasePlatformAdapter(ABC): logger.info("[%s] Send succeeded on retry %d", self.name, attempt) return result error_str = result.error or "" - if result.retry_after is not None: - server_retry_after = result.retry_after + server_retry_after = result.retry_after # None unless the server asked again if not (result.retryable or self._is_retryable_error(error_str)): break # non-transient now — fall through to plain-text fallback else: # retries exhausted — notify user @@ -3418,12 +3409,11 @@ class BasePlatformAdapter(ABC): mode = os.getenv("HERMES_HUMAN_DELAY_MODE", "off").lower() if mode == "off": return 0.0 - if mode == "natural": - return random.uniform(800 / 1000.0, 2500 / 1000.0) - def _ms(name: str, default: int) -> int: # custom mode tolerates malformed env vars - return _or_default(lambda: int(os.getenv(name, str(default))), default) - return random.uniform(_ms("HERMES_HUMAN_DELAY_MIN_MS", 800) / 1000.0, - _ms("HERMES_HUMAN_DELAY_MAX_MS", 2500) / 1000.0) + lo, hi = 800, 2500 + if mode != "natural": # custom mode tolerates malformed env vars + lo = _or_default(lambda: int(os.getenv("HERMES_HUMAN_DELAY_MIN_MS", str(lo))), lo) + hi = _or_default(lambda: int(os.getenv("HERMES_HUMAN_DELAY_MAX_MS", str(hi))), hi) + return random.uniform(lo / 1000.0, hi / 1000.0) async def _synthesize_auto_tts(self, text_content: str) -> Tuple[List[str], Optional[str]]: """Synthesize auto-TTS audio -> ``(existing_paths, requested_path)``; empty/None on failure @@ -3601,8 +3591,7 @@ class BasePlatformAdapter(ABC): await self._finalize_delivery_obligation(_obligation_id, result, event, delivery_adapter) if ephemeral_ttl and ephemeral_ttl > 0 and result.success and result.message_id: delivery_adapter._schedule_ephemeral_delete( - chat_id=event.source.chat_id, message_id=result.message_id, - ttl_seconds=ephemeral_ttl) + event.source.chat_id, result.message_id, ephemeral_ttl) async def _notify_turn_error(self, event: MessageEvent, e: BaseException) -> Optional[dict]: """Tell the user a turn failed rather than leaving radio silence (last resort: @@ -3798,9 +3787,7 @@ class BasePlatformAdapter(ABC): if session_key in self._pending_messages: pending_event = self._pending_messages.pop(session_key) logger.debug("[%s] Processing queued follow-up message", self.name) - _active = self._active_sessions.get(session_key) - if _active is not None: - _active.clear() + self._clear_session_guard(session_key) await self._stop_typing_refresh(event.source.chat_id, typing_task, metadata=_thread_metadata) self._spawn_drain_task(pending_event, session_key) return # Drain task owns the session now. @@ -3835,11 +3822,15 @@ class BasePlatformAdapter(ABC): """Hand the session to a fresh task for a queued follow-up — never recurse (chained follow-ups grew the C stack to SIGSEGV). Clearing (not deleting) the Event keeps the guard live for concurrent inbound; ownership moves so stale-lock detection works.""" + self._clear_session_guard(session_key) + self._track_session_task( + session_key, asyncio.create_task(self._process_message_background(pending_event, session_key))) + + def _clear_session_guard(self, session_key: str) -> None: + """Clear (not delete) the session's interrupt Event so the guard stays live for inbound.""" _active = self._active_sessions.get(session_key) if _active is not None: _active.clear() - self._track_session_task( - session_key, asyncio.create_task(self._process_message_background(pending_event, session_key))) def _cleanup_finished_session_task( self, session_key: str, interrupt_event: Optional[asyncio.Event]) -> None: @@ -3871,17 +3862,14 @@ class BasePlatformAdapter(ABC): "releasing tracking and letting them unwind in the background", self.name, len([t for t in tasks if not t.done()])) break - self._background_tasks.clear() - self._expected_cancelled_tasks.clear() - self._session_tasks.clear() with contextlib.suppress(Exception): # flush pending messages to disk before clearing from gateway.shutdown_flush import flush_pending_to_file flush_pending_to_file(self._pending_messages, reason="adapter_shutdown") - self._pending_messages.clear() - self._active_sessions.clear() - for state in list(self._text_debounce_store().values()): + for state in self._text_debounce_store().values(): state.cancel_timer() - self._text_debounce_store().clear() + for bucket in (self._background_tasks, self._expected_cancelled_tasks, self._session_tasks, + self._pending_messages, self._active_sessions, self._text_debounce_store()): + bucket.clear() def has_pending_interrupt(self, session_key: str) -> bool: """Check if there's a pending interrupt for a session.""" From 421c95f3b2044bd67f769160728a21e8f64c0212 Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Wed, 2 Sep 2026 23:19:30 -0700 Subject: [PATCH 06/13] =?UTF-8?q?refactor(gateway/platforms):=20base.py=20?= =?UTF-8?q?=E2=80=94=20compact=2088=20comment=20blocks=20(keep=20every=20W?= =?UTF-8?q?HY/invariant),=20wrap=20to=20100=20cols?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- gateway/platforms/base.py | 422 ++++++++++++++++---------------------- 1 file changed, 176 insertions(+), 246 deletions(-) diff --git a/gateway/platforms/base.py b/gateway/platforms/base.py index ea48296eea..4b0289d95b 100644 --- a/gateway/platforms/base.py +++ b/gateway/platforms/base.py @@ -34,8 +34,8 @@ def _consume_detached_handler_exception(task: "asyncio.Task") -> None: logger.error("Detached fatal-error handler task failed: %s", exc, exc_info=exc) -# Audio extensions Hermes recognizes for native audio delivery. Telegram's narrower -# attachment/voice sets stay separate: MPEG-2 Layer II is audio to Hermes but not to sendAudio. +# Audio exts for native audio delivery; Telegram's narrower sets stay separate (.m2a is audio to +# Hermes but not to sendAudio). _AUDIO_MIME_TYPES = { ".ogg": "audio/ogg", ".opus": "audio/opus", ".mp3": "audio/mpeg", ".m2a": "audio/mpeg", ".wav": "audio/wav", ".m4a": "audio/m4a", ".flac": "audio/flac"} @@ -71,11 +71,10 @@ def transcode_to_ogg_opus(path: str, *, bitrate: str = "32k") -> "str | None": os.unlink(ogg_path) return None _POST_DELIVERY_CALLBACK_TIMEOUT_SECONDS = 30.0 -# Delivery-time history is best-effort dedup metadata: stay well below the Discord heartbeat -# watchdog window and fail open rather than withhold a legitimate attachment. +# History dedup is best-effort: stay well below the Discord heartbeat watchdog and fail open. _HISTORY_MEDIA_LOOKUP_TIMEOUT_SECONDS = 5.0 -# Timed-out reads can't be cancelled mid-SQLite; isolate and cap them so wedged dedup work -# can't consume the shared executor or spawn unbounded threads. +# Timed-out reads can't be cancelled mid-SQLite: cap the isolated threads so wedged lookups +# can't exhaust the shared executor. _HISTORY_MEDIA_LOOKUP_MAX_WORKERS = 2 _HISTORY_MEDIA_LOOKUP_ADMISSION = threading.BoundedSemaphore(_HISTORY_MEDIA_LOOKUP_MAX_WORKERS) @@ -106,8 +105,8 @@ def _thread_metadata_for_source(source, reply_to_message_id: str | None = None) thread_id = getattr(source, "thread_id", None) platform = _platform_name(getattr(source, "platform", None)) metadata = {"thread_id": thread_id} if thread_id is not None else {} - # Slack workspace identity is durable routing state: carry it on every outbound path - # so a multi-workspace Socket Mode gateway never falls back to its primary WebClient. + # Slack workspace identity is routing state: carry it so a multi-workspace Socket Mode + # gateway never falls back to its primary WebClient. scope_id = getattr(source, "scope_id", None) if platform == "slack" else None if scope_id: metadata["slack_team_id"] = str(scope_id) @@ -120,8 +119,8 @@ def _thread_metadata_for_source(source, reply_to_message_id: str | None = None) anchor = reply_to_message_id or getattr(source, "message_id", None) if anchor is not None: metadata["telegram_reply_to_message_id"] = str(anchor) - # Routed profile for shared state.db namespaces (multiplex / profile_routes); - # outbound prune paths must not assume the adapter's static profile stamp. + # Routed profile (multiplex / profile_routes): outbound prune paths must not assume the + # adapter's static profile stamp. profile = str(getattr(source, "profile", None) or "").strip() if profile: metadata["hermes_profile"] = profile @@ -148,13 +147,12 @@ def _reply_anchor_for_event(event) -> str | None: raw_message = getattr(event, "raw_message", None) if (platform == "slack" and isinstance(raw_message, dict) and raw_message.get("_hermes_no_thread_response")): - # Slack reaction handoffs create a new top-level message in the target channel; - # returning message_id would make _resolve_thread_ts() reply in a nonexistent thread. + # Slack reaction handoff = new top-level message; a message_id anchor would make + # _resolve_thread_ts() reply in a nonexistent thread. return None if platform == "telegram" and thread_id: - # Forum topics route by topic metadata (no reply); DM-topic lanes reply to the - # triggering user message — replying to Telegram's topic seed/anchor can render - # the bot response outside the active lane. + # Forum topics route by topic metadata (no reply); DM-topic lanes reply to the triggering + # message — replying to the topic seed/anchor can render outside the active lane. if getattr(source, "chat_type", None) != "dm": return None return getattr(event, "message_id", None) or getattr(event, "reply_to_message_id", None) @@ -512,14 +510,13 @@ async def _ssrf_redirect_guard(response): raise ValueError(f"Blocked redirect to private/internal address: {safe_url_for_log(redirect_url)}") -# Inbound images are cached locally so the vision tool can read them by path (platform URLs -# are ephemeral). Import-time default; tests monkeypatch it, getters re-resolve per call. +# Inbound images are cached locally for the vision tool (platform URLs are ephemeral). +# Import-time default; tests monkeypatch it, getters re-resolve per call. IMAGE_CACHE_DIR = get_hermes_dir("cache/images", "image_cache") -# Inbound media size cap: payloads are buffered fully in memory before hitting the cache, so -# an uncapped upload (Discord Nitro: 500 MB) or huge remote URL can OOM-kill the gateway. -# Enforced in ``cache_*_from_bytes`` and ``cache_*_from_url``; ``gateway.max_inbound_media_bytes``. +# Inbound media cap (``gateway.max_inbound_media_bytes``): payloads are buffered fully in memory, +# so an uncapped upload (Discord Nitro: 500 MB) could OOM-kill the gateway. DEFAULT_INBOUND_MEDIA_MAX_BYTES = 128 * 1024 * 1024 @@ -714,11 +711,10 @@ _HERMES_ROOT = get_default_hermes_root() MEDIA_DELIVERY_ALLOW_DIRS_ENV = "HERMES_MEDIA_ALLOW_DIRS" MEDIA_DELIVERY_TRUST_RECENT_ENV = "HERMES_MEDIA_TRUST_RECENT_FILES" MEDIA_DELIVERY_TRUST_RECENT_SECONDS_ENV = "HERMES_MEDIA_TRUST_RECENT_SECONDS" -# Strict mode = allowlist+recency validation. Off by default (symmetric with inbound; the -# denylist still blocks credential / system paths); set true on public-facing gateways. +# Strict mode = allowlist+recency validation; off by default (the denylist still blocks +# credential / system paths). Set true on public-facing gateways. MEDIA_DELIVERY_STRICT_ENV = "HERMES_MEDIA_DELIVERY_STRICT" -# Canonical cache subdirs holding deliverable artifacts; also used to enumerate -# per-profile cache roots at check time (_media_delivery_allowed_roots). +# Canonical cache subdirs of deliverable artifacts; also enumerates per-profile cache roots. _MEDIA_DELIVERY_CACHE_SUBDIRS = ("images", "audio", "videos", "documents", "screenshots") MEDIA_DELIVERY_SAFE_ROOTS = ( IMAGE_CACHE_DIR, AUDIO_CACHE_DIR, VIDEO_CACHE_DIR, DOCUMENT_CACHE_DIR, SCREENSHOT_CACHE_DIR, @@ -727,12 +723,12 @@ MEDIA_DELIVERY_SAFE_ROOTS = ( # Canonical cache layout, alongside the legacy *_cache dirs (installs may have both). *(_HERMES_HOME / "cache" / d for d in _MEDIA_DELIVERY_CACHE_SUBDIRS)) -# Recency window (seconds) for trusting freshly-produced files: build artifacts land seconds -# before delivery; pre-existing host files (/etc/passwd, ~/.ssh/id_rsa) are days/months old. +# Recency window (s) for trusting fresh files: artifacts land seconds before delivery, +# pre-existing host files (/etc/passwd, ~/.ssh/id_rsa) are days/months old. _MEDIA_DELIVERY_TRUST_RECENT_DEFAULT_SECONDS = 600 -# Hard denylist applied even to "recent" files: credentials, system state, process -# introspection. The cache-dir allowlist still beats it (an operator may allow a root here). +# Hard denylist even for "recent" files (credentials, system state, /proc); the cache-dir +# allowlist still beats it. _MEDIA_DELIVERY_DENIED_PREFIXES = ( "/etc", "/proc", "/sys", "/dev", "/root", "/boot", "/var/log", "/var/lib", "/var/run") @@ -741,11 +737,10 @@ _MEDIA_DELIVERY_DENIED_HOME_SUBPATHS = ( ".ssh", ".aws", ".gnupg", ".kube", ".docker", ".config", ".azure", ".gcloud", "Library/Keychains") -# Credential / secret stores at the HERMES_HOME root, denied per-file (not the whole tree, so -# skills/, logs/ and agent-written files under ~/.hermes stay deliverable; cache subdirs are -# allowlisted BEFORE this denylist). Mirrors the read guard in agent/file_safety.py so the exfil -# side never trails the write side. google_token.json's mtime bumps every turn (defeats the strict -# recency window); pairing/ and mcp-tokens/ (live MCP OAuth tokens) are denied as whole trees. +# Credential stores at the HERMES_HOME root, denied per-file so skills/, logs/ and agent-written +# files stay deliverable (cache subdirs are allowlisted BEFORE this). Mirrors agent/file_safety.py +# so exfil never trails the read guard. google_token.json's mtime bumps every turn (defeats the +# recency window); pairing/ and mcp-tokens/ (live OAuth tokens) are denied as whole trees. _ROOT_CREDENTIAL_PATHS = ( ".env", "auth.json", "auth.lock", "credentials", "config.yaml", ".anthropic_oauth.json", "google_token.json", "google_oauth_pending.json", os.path.join("auth", "google_oauth.json"), @@ -995,8 +990,8 @@ def _translate_docker_container_media_path(candidate: Path, session_key: str = " auto-mounted cache dirs (``/root/.hermes/...``), persistent ``/workspace`` and ``/root``.""" if not candidate.is_absolute(): return None - # In-process gateways (Desktop, `hermes serve`) may not have bridged terminal.* - # config into TERMINAL_* env; run the idempotent bridge so mount parsing sees it. + # In-process gateways (Desktop, `hermes serve`) may not have bridged terminal.* config into + # TERMINAL_* env yet; the bridge is idempotent. with contextlib.suppress(Exception): from tools.terminal_tool import _ensure_terminal_env_bridged _ensure_terminal_env_bridged() @@ -1005,9 +1000,9 @@ def _translate_docker_container_media_path(candidate: Path, session_key: str = " # Synthetic /workspace mounts: profile-scoped layout first, then legacy per-session. if "/workspace" not in mounted: mounts.extend((root, Path("/workspace")) for root in _default_docker_workspace_host_roots(session_key)) - # Synthetic /root home mounts only catch stray home writes like /root/out.png (cache mounts - # are longer prefixes). /root/.hermes/* that missed a cache mount is the container's credential - # surface (.env, auth.json, ...); translating via the home mount would dodge the host denylist. + # Synthetic /root mounts catch stray home writes (/root/out.png; cache mounts are longer + # prefixes). /root/.hermes/* that missed a cache mount is the container's credential surface — + # translating it via the home mount would dodge the host denylist. if "/root" not in mounted and not candidate.as_posix().startswith("/root/.hermes"): mounts.extend( (root, Path("/root")) for root in _docker_persistent_sandbox_roots(session_key, "home")) @@ -1063,12 +1058,10 @@ def validate_media_delivery_path(path: str, session_key: str = "") -> Optional[s resolved_root = _resolve_path(root, expand=True) if resolved_root is not None and _path_is_within(resolved, resolved_root): return str(resolved) - # Non-strict (default): accept anything not denylisted — /etc, /proc, ~/.ssh, ~/.aws and the - # Hermes-root secret stores stay rejected (MEDIA:/etc/passwd, MEDIA:~/.hermes/google_token.json) + # Non-strict (default): anything not denylisted (/etc, /proc, ~/.ssh, Hermes-root secrets). if os.environ.get(MEDIA_DELIVERY_STRICT_ENV, "0").strip().lower() not in _TRUTHY: return None if _path_under_denied_prefix(resolved) else str(resolved) - # Strict: fall back to recency trust for freshly-produced files (pandoc -o /tmp/x.pdf); - # system / credential paths stay blocked even when "recent". + # Strict: recency trust for fresh files (pandoc -o /tmp/x.pdf); denylist still applies. window = _media_delivery_recency_seconds() if (window > 0 and not _path_under_denied_prefix(resolved) and _file_is_recently_produced(resolved, window)): @@ -1076,8 +1069,8 @@ def validate_media_delivery_path(path: str, session_key: str = "") -> Optional[s return None -# Neutralise control chars and Unicode line separators (NEL, LS, PS) that splitlines() -# / log aggregators treat as breaks, so a model-emitted path can't forge a log line. +# Control chars + Unicode line separators (NEL, LS, PS) that log aggregators treat as breaks: a +# model-emitted path must not forge a log line. _LOG_UNSAFE_CHARS = re.compile(r"[\x00-\x1f\x7f\x85\u2028\u2029]") @@ -1107,8 +1100,8 @@ SUPPORTED_DOCUMENT_TYPES = { ".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation", ".ts": "text/plain", ".py": "text/plain", ".sh": "text/plain"} -# Files safe to inline into the prompt when small. Deliberately an extension gate, NOT a blind -# UTF-8 decode — PDF/zip/docx can start with decodable ASCII. Non-members are still cached by path. +# Files safe to inline into the prompt when small. An extension gate, NOT a blind UTF-8 decode +# (PDF/zip/docx can start with decodable ASCII). Non-members are still cached by path. _TEXT_INJECT_EXTENSIONS = { ".txt", ".md", ".markdown", ".csv", ".tsv", ".log", ".json", ".jsonl", ".ndjson", ".xml", ".yaml", ".yml", ".toml", ".ini", ".cfg", ".conf", ".env", ".properties", ".html", ".htm", @@ -1119,15 +1112,13 @@ _TEXT_INJECT_EXTENSIONS = { ".dockerfile", ".makefile", ".cmake", ".gradle", ".rst", ".tex", ".srt", ".vtt", ".diff", ".patch"} -# Image extensions platforms may deliver as "documents" (file-picker uploads, stickers/ -# screenshots wrapped as files); routed through the image cache / vision path instead of rejected. +# Image exts platforms may deliver as "documents" (file-picker uploads); routed to the image cache. SUPPORTED_IMAGE_DOCUMENT_TYPES = { ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".png": "image/png", ".webp": "image/webp", ".gif": "image/gif"} -# Media-delivery extension allowlist — SINGLE SOURCE OF TRUTH for both extractors (MEDIA: tags, -# bare paths) and the cleanup regexes, so a tag is only stripped when its extension is deliverable -# and an unknown-extension path survives in the body. Dispatch partition lives in gateway/run.py. +# Media-delivery ext allowlist — SINGLE SOURCE OF TRUTH for both extractors and the cleanup +# regexes: a tag is stripped only when deliverable, unknown-ext paths survive in the body. MEDIA_DELIVERY_EXTS: Tuple[str, ...] = ( ".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".tiff", ".svg", # images (embed inline) ".mp4", ".mov", ".avi", ".mkv", ".webm", ".3gp", # video (embed inline where supported) @@ -1142,17 +1133,13 @@ MEDIA_DELIVERY_EXTS: Tuple[str, ...] = ( # Bare extensions (no dot) longest-first so a shorter ext never matches as a prefix of a longer one. _MEDIA_EXT_ALTERNATION = "|".join(sorted((e.lstrip(".") for e in MEDIA_DELIVERY_EXTS), key=len, reverse=True)) -# Anchored ``MEDIA:`` cleanup pattern shared by the non-streaming dispatch path and the -# streaming consumer. Strips only a tag whose path ends in a known deliverable extension -# (optionally quoted/backticked); unknown-extension tags stay for the bare-path detector. Rules: -# * Path anchors: ``~/``, ``/``, ``X:\`` or ``X:/`` (Windows drive letter). -# * Up to 3 quote/emphasis markers each side (``**MEDIA:/x.pdf**``); code / inline-code / -# blockquote contexts are neutralised earlier by ``_mask_protected_spans``. -# * Non-greedy path forms with ``MEDIA:`` as a boundary, so glued tags -# (``MEDIA:/a.pngMEDIA:/b.png``) or trailing prose never merge into one invalid path. -# * Sentence-final ``.`` is a boundary only before whitespace/EOL (``\.(?=\s|$)``): ``data.csv.`` -# yields ``data.csv`` while ``archive.tar.gz`` extends past ``.tar``. -# * CJK full-width punctuation terminates paths too (``MEDIA:D:\path\早报.pdf(782.6 KB)``). +# Anchored ``MEDIA:`` cleanup pattern (dispatch path + streaming consumer). Strips only tags +# whose path ends in a deliverable extension (optionally quoted/backticked); unknown-ext tags stay +# for the bare-path detector. Rules: anchors ``~/``, ``/``, ``X:\`` / ``X:/``; up to 3 quote/ +# emphasis markers each side (code/blockquote contexts are masked earlier); non-greedy with +# ``MEDIA:`` as a boundary so glued tags (``MEDIA:/a.pngMEDIA:/b.png``) never merge; sentence-final +# ``.`` is a boundary only before whitespace/EOL (``data.csv.`` -> ``data.csv``, ``archive.tar.gz`` +# extends past ``.tar``); CJK full-width punctuation terminates paths (``早报.pdf(782.6 KB)``). _MEDIA_CJK_TERMINATORS = "()〈〉《》:,。;!?、\u201c\u201d\u2018\u2019【】" MEDIA_TAG_CLEANUP_RE = re.compile( @@ -1162,12 +1149,10 @@ MEDIA_TAG_CLEANUP_RE = re.compile( r'''(?=[\s`"'*_,;:)\]}\[''' + _MEDIA_CJK_TERMINATORS + r''']|MEDIA:|\.(?:\s|$)|$)[`"'*_]{0,3}\.?''', re.IGNORECASE) -# Extension-less (Caddyfile) or unknown-extension (.py, .log) paths are delivered via this -# pattern only after ``validate_media_delivery_path`` accepts them (on disk, not denylisted, -# strict-mode rules honored), so prompt-injection paths that don't validate stay visible. The -# bare path class is a whitespace-bounded tempered-greedy token: a tag glued to the next -# ``MEDIA:`` or to prose must not absorb it. Spaced paths (``MEDIA:/data/map data.kmz``) are -# recovered by ``_match_extensionless_path`` with on-disk validation as the oracle. +# Extension-less (Caddyfile) / unknown-ext (.py, .log) tags deliver only after +# ``validate_media_delivery_path`` accepts them, so injected paths that don't validate stay visible. +# The bare path class is whitespace-bounded (a tag glued to the next ``MEDIA:`` or prose must not +# absorb it); spaced paths are recovered by ``_match_extensionless_path`` with on-disk validation. MEDIA_EXTENSIONLESS_TAG_RE = re.compile( r'''[`"'*_]{0,3}MEDIA:\s*''' r'''(?P`[^`\n]+`|"[^"\n]+"|'[^'\n]+'|''' @@ -1357,10 +1342,8 @@ def cache_media_bytes(data: bytes, *, filename: str = "", mime_type: str = "", return None out_mime = mime if passthrough and mime.startswith(f"{kind}/") else table[kind_ext] return CachedMedia(to_agent_visible_cache_path(path), out_mime, kind, display) - # Any other file type is cached and surfaced as a local path: once a user is authorized - # to message the agent, the extension allowlist must not silently drop their uploads. - # Unknown types get application/octet-stream (or the caller's MIME) so the agent knows - # to reach for terminal tools. + # Any other type is cached and surfaced as a path — an authorized user's uploads must never be + # silently dropped. Unknown types get octet-stream so the agent reaches for terminal tools. fallback_name = filename or (f"document{ext}" if ext else "document.bin") path = cache_document_from_bytes(data, fallback_name) out_mime = SUPPORTED_DOCUMENT_TYPES.get(ext) or mime or "application/octet-stream" @@ -1398,8 +1381,8 @@ class MessageEvent: source: SessionSource = None raw_message: Any = None message_id: Optional[str] = None - # Platform update id (Telegram ``update_id``); ``/restart`` records it so the new gateway - # advances the offset past it and never re-processes it if PTB's shutdown ACK times out. + # Platform update id (Telegram ``update_id``): ``/restart`` records it so the new gateway + # advances past it even if PTB's shutdown ACK times out. platform_update_id: Optional[int] = None # Media attachments: local file paths (for vision tool access) media_urls: List[str] = field(default_factory=list) @@ -1411,24 +1394,23 @@ class MessageEvent: reply_to_author_id: Optional[str] = None reply_to_author_name: Optional[str] = None reply_to_is_own_message: bool = False # True when the user replied to this bot/assistant's message - # Structured interactive-prompt reply (relay): {prompt_id, option_id, label?, - # prompt_message_id?}. RelayAdapter routes it to the approval / slash-confirm / clarify - # resolvers BEFORE normal dispatch; native adapters never set it (buttons resolve in-process). + # Structured interactive-prompt reply (relay only): {prompt_id, option_id, label?, + # prompt_message_id?}; routed to the approval/slash-confirm/clarify resolvers BEFORE dispatch. prompt_response: Optional[Dict[str, Any]] = None # Auto-loaded skill(s) for topic/channel bindings; a single name or ordered list. auto_skill: Optional[str | list[str]] = None # Per-channel ephemeral system prompt; applied at API call time, never persisted to transcript. channel_prompt: Optional[str] = None - # Channel context recovered by history backfill (messages missed under require_mention); - # separate from ``text`` so run.py's sender-prefix logic sees only the trigger message. + # History-backfilled channel context (missed under require_mention); kept out of ``text`` so + # run.py's sender-prefix logic sees only the trigger message. channel_context: Optional[str] = None # Set for synthetic events (e.g. background-process notifications) that must bypass user authorization. internal: bool = False # Free-form per-event metadata (e.g. ``whatsapp_from_owner=True``); plugins must ``.get()``. metadata: Dict[str, Any] = field(default_factory=dict) timestamp: datetime = field(default_factory=datetime.now) - # May this event resolve gateway commands / pending control prompts? Kept last for positional - # compat. Proactive plugin events set False so untrusted payload text stays conversational. + # May this event resolve gateway commands / control prompts? Proactive plugin events set False + # so untrusted payload text stays conversational. Kept last for positional compat. allow_gateway_control: bool = True def is_command(self) -> bool: @@ -1510,30 +1492,28 @@ class SendResult: success: bool message_id: Optional[str] = None error: Optional[str] = None - # Adapter-specific metadata. Cross-layer contract: Telegram edit-overflow partials set - # raw_response["partial_overflow"] (delivered_chunks, total_chunks, last_message_id, - # delivered_prefix, continuation_message_ids) so the stream consumer sends the missing tail. + # Adapter-specific metadata. Contract: Telegram edit-overflow partials set + # raw_response["partial_overflow"] so the stream consumer sends the missing tail. raw_response: Any = None retryable: bool = False # transient connection error — base retries automatically retry_after: Optional[float] = None # server-requested delay (Telegram FloodWait) beats our backoff - # Extra ids (send order) when an oversized payload was split across platform messages; - # ``message_id`` is then the LAST visible id so later edits target the newest chunk. + # Extra ids (send order) when a payload was split; ``message_id`` is then the LAST id so + # later edits target the newest chunk. continuation_message_ids: tuple = () - # SEND_ERROR_KINDS member (only when ``success`` is False) so consumers branch without - # substring-matching ``error``; producers set it via :func:`classify_send_error`. + # SEND_ERROR_KINDS member (failures only) via :func:`classify_send_error`, so consumers + # branch without substring-matching ``error``. error_kind: Optional[str] = None -# Platform-neutral send-failure categories for ``SendResult.error_kind``, so the gateway -# decides once whether a failure is worth surfacing: too_long (size cap; adapter usually -# splits), bad_format (markup/entities rejected; plain-text retry fixes), forbidden (blocked/ -# kicked/no permission — the bot CANNOT reach the user), not_found (chat/thread/message gone), -# rate_limited (flood control), transient (connection-level, safe to retry), unknown. +# Platform-neutral send-failure kinds for ``SendResult.error_kind``: too_long (size cap), +# bad_format (markup rejected; plain-text retry fixes), forbidden (the bot CANNOT reach the user), +# not_found (chat/thread/message gone), rate_limited, transient (connection-level, retry-safe), +# unknown. SEND_ERROR_KINDS = frozenset( {"too_long", "bad_format", "forbidden", "not_found", "rate_limited", "transient", "unknown"}) -# ``not_found`` substrings split by blast radius: chat-level = whole target dead; thread/topic/ -# message-level leaves the parent chat reachable and must NOT mark it dead. +# ``not_found`` substrings by blast radius: chat-level = target dead; thread/topic/message-level +# leaves the parent chat reachable. _CHAT_LEVEL_NOT_FOUND_SUBSTRINGS = ("chat not found",) _SUBCHAT_NOT_FOUND_SUBSTRINGS = ( "message to edit not found", "message to reply not found", "thread not found", "topic_deleted", @@ -1622,8 +1602,8 @@ def merge_pending_message_event(pending_messages: Dict[str, MessageEvent], sessi if incoming_has_media: existing.media_text_inlined = _padded_inline_flags(existing) incoming_inline_flags = _padded_inline_flags(event) - # A photo burst always absorbs (even media-less PHOTO events); otherwise merge only - # when media is involved on either side. Captions merge in every absorbing case. + # A photo burst always absorbs; otherwise merge only when media is involved on either + # side. Captions merge in every absorbing case. if both_photo or existing.media_urls or incoming_has_media: if both_photo or incoming_has_media: existing.media_urls.extend(event.media_urls) @@ -1635,8 +1615,8 @@ def merge_pending_message_event(pending_messages: Dict[str, MessageEvent], sessi existing.message_type = MessageType.PHOTO elif existing_type == MessageType.TEXT and event.message_type != MessageType.TEXT: existing.message_type = event.message_type - # Drop the *derived* STT transcript cache now that the event changed; the echo - # ledger (``_gateway_pending_stt_echoed``) must survive or notes echo twice. + # Drop the *derived* STT cache (event changed); the echo ledger must survive or + # notes echo twice. for attr in ("_gateway_pending_stt_text", "_gateway_pending_stt_transcripts"): if hasattr(existing, attr): delattr(existing, attr) @@ -1649,16 +1629,13 @@ def merge_pending_message_event(pending_messages: Dict[str, MessageEvent], sessi pending_messages[session_key] = event -# Substrings marking a transient *connection* failure worth retrying. Plain "timeout" / -# "readtimeout" / "writetimeout" are excluded on purpose: a read/write timeout on a -# non-idempotent send may have reached the server, so a retry risks duplicate delivery; -# "connecttimeout" never connected. Platforms that know better set SendResult.retryable. +# Transient *connection* failures worth retrying. Plain/read/write "timeout" excluded on purpose: +# the send may have reached the server (retry = duplicate); "connecttimeout" never connected. _RETRYABLE_ERROR_PATTERNS = ( "connecterror", "connectionerror", "connectionreset", "connectionrefused", "connecttimeout", "network", "broken pipe", "remotedisconnected", "eoferror") -# Handlers return a plain string (normal reply), an ``EphemeralReply`` (auto-deletion), or -# ``None`` when the response was already delivered (e.g. via streaming). +# Handler result: str (reply), ``EphemeralReply`` (auto-delete) or None (already delivered). MessageHandler = Callable[[MessageEvent], Awaitable[Optional[Union[str, "EphemeralReply"]]]] @@ -1721,12 +1698,10 @@ _strip_media_directives = _strip_media_tag_directives class BasePlatformAdapter(ABC): """Base class for platform adapters: connect/auth, receive, send, handle media.""" - # ``format_message`` renders triple-backtick fences as real code blocks (tool-progress - # renders a terminal command as a bare fenced block; plain-text platforms get the preview). + # ``format_message`` renders ``` fences as real code blocks (tool-progress then sends a bare + # fenced terminal command; plain-text platforms get the preview). supports_code_blocks: bool = False - - # Typing indicator renders TEXT (status line by the bot name) rather than a textless - # bubble; when True the gateway feeds per-tool phrases via set_status_text(). + # Typing indicator renders TEXT (status line); the gateway then feeds set_status_text(). supports_status_text: bool = False def set_status_text(self, chat_id: str, text: Optional[str]) -> None: @@ -1739,40 +1714,31 @@ class BasePlatformAdapter(ABC): else: store.pop(str(chat_id), None) - # Can wake a fresh turn AFTER a turn ends (background/detached-subagent completions). - # False for stateless request/response adapters (API server); propagated to - # ``HERMES_SESSION_ASYNC_DELIVERY`` so tools never promise a delivery they can't keep. + # Can wake a fresh turn AFTER a turn ends (detached-subagent completions); False for stateless + # adapters (API server). Propagated to ``HERMES_SESSION_ASYNC_DELIVERY`` so tools never promise + # a delivery they can't keep. supports_async_delivery: bool = True - - # ``send()`` chunks long content natively via ``truncate_message()``; when True the - # delivery router skips gateway-level truncation. Set True only when verified. + # ``send()`` chunks natively via ``truncate_message()`` -> the router skips its truncation. splits_long_messages: bool = False - - # Prefix users can always TYPE to reach Hermes commands ("!" where the client - # intercepts a leading "/": Slack threads, Matrix) so instruction text names the working form. + # Prefix users can always TYPE for Hermes commands ("!" where the client eats a leading "/"). typed_command_prefix: str = "/" - - # ``in_channel`` continuable-cron surface: job delivered FLAT into a channel, plain replies - # continue it via the whole-channel bucket ``(platform, chat_id, None)``; needs a flat-reply - # outbound gate too (Slack ``reply_in_thread: false``). False fails SAFE -> ``thread``. + # ``in_channel`` continuable-cron surface: job delivered FLAT, plain replies continue it via + # the whole-channel bucket ``(platform, chat_id, None)``; needs a flat-reply outbound gate too + # (Slack ``reply_in_thread: false``). False fails SAFE -> ``thread``. supports_inchannel_continuable: bool = False - - # A human is present to answer "session restored — what next?"; non-interactive event - # platforms (webhook) set False so auto-resume finishes the work instead of asking nobody. + # A human can answer "session restored — what next?"; webhook-style platforms set False so + # auto-resume finishes the work instead of asking nobody. interactive_resume: bool = True - - # Back-reference to the running ``GatewayRunner`` (injected by gateway/run.py); on the base - # so ``build_source`` resolves the inbound profile via ``runner._profile_name_for_source``. - gateway_runner = None # type: ignore[assignment] # set by gateway/run.py + # Back-reference to the running ``GatewayRunner`` (set by gateway/run.py); ``build_source`` + # resolves the inbound profile via ``runner._profile_name_for_source``. + gateway_runner = None # type: ignore[assignment] def __init__(self, config: PlatformConfig, platform: Platform): self.config = config self.platform = platform self._message_handler: Optional[MessageHandler] = None - # Gateway fan-out for platform-native reaction events (set_reaction_handler). self._reaction_handler: Optional[Callable[[Dict[str, Any]], Awaitable[None]]] = None - # Runner-owned boundary for normalized events (+ internal SessionSource): - # authorization/profile state never lives in an SDK adapter. + # Runner-owned boundary for normalized events: auth/profile state never lives in an adapter. self._platform_event_handler: Optional[Callable[[Dict[str, Any], Any], Awaitable[None]]] = None # Rewrites ``event.source.thread_id`` before session keying (Telegram DM topics). self._topic_recovery_fn: Optional[Callable[[Any], Optional[str]]] = None @@ -1782,16 +1748,15 @@ class BasePlatformAdapter(ABC): self._fatal_error_handler: Optional[Callable[["BasePlatformAdapter"], Awaitable[None] | None]] = None # Strong refs to shielded fatal-error handler tasks (asyncio keeps only weak refs). self._detached_fatal_tasks: set = set() - # Cross-HERMES_HOME lock takeover, armed by GatewayRunner only for the initial - # connect of an explicit ``gateway run --replace``; reconnects fail safe. + # Lock takeover armed only for the initial connect of ``gateway run --replace``. self._platform_lock_takeover_allowed = self._platform_lock_takeover_attempted = False - # Per-session interrupt Event + owner Task so /stop, /new, /reset cancel the right - # task; without the owner map an old task's finally could drop a newer guard. + # Per-session interrupt Event + owner Task: without the owner map an old task's finally + # could drop a newer guard. self._active_sessions: Dict[str, asyncio.Event] = {} self._pending_messages: Dict[str, MessageEvent] = {} self._session_tasks: Dict[str, asyncio.Task] = {} - # Legacy env knob; the runner syncs the busy_input_mode-derived value after - # construction. Default "interrupt" so a pre-sync read never silently queues. + # Legacy env knob; the runner syncs the busy_input_mode value after construction. + # Default "interrupt" so a pre-sync read never silently queues. self._busy_text_mode: str = ( os.environ.get("HERMES_GATEWAY_BUSY_TEXT_MODE", "interrupt").strip().lower() or "interrupt") self._busy_text_debounce_seconds: float = _float_env("HERMES_GATEWAY_BUSY_TEXT_DEBOUNCE_SECONDS", 0.35) @@ -1799,27 +1764,23 @@ class BasePlatformAdapter(ABC): self._text_debounce: dict[str, TextDebounceState] = {} # handle_message() tasks; shutdown cancels them so a replaced gateway stops working. self._background_tasks: set[asyncio.Task] = set() - # Post-delivery one-shots keyed by session_key: bare callback (legacy) or - # ``(generation, callback)`` so a stale run can't clear a fresher run's callback. + # Post-delivery one-shots per session_key: bare callback (legacy) or ``(generation, + # callback)`` so a stale run can't clear a fresher run's callback. self._post_delivery_callbacks: Dict[str, Any] = {} self._expected_cancelled_tasks: set[asyncio.Task] = set() self._busy_session_handler: Optional[Callable[[MessageEvent, str], Awaitable[bool]]] = None - # Owning multiplex profile (None on primary/single-profile); ``source.profile`` is - # stamped only after adapter ingress — see _session_key_profile. + # Owning multiplex profile (None on primary); see _session_key_profile. self._owner_profile: Optional[str] = None - # Registered by GatewayRunner; adapters that fetch external context (Slack thread - # history) mark non-allowlisted senders unverified (prompt-injection mitigation). + # Registered by GatewayRunner (see set_authorization_check). self._authorization_check: Optional[Callable[[str, Optional[str], Optional[str]], bool]] = None - # Auto-TTS on voice input: global default (``voice.auto_tts``) plus per-chat - # opt-in (``/voice on|tts``, fires even if default False) / opt-out (``/voice off``). + # Auto-TTS on voice input: ``voice.auto_tts`` default plus per-chat /voice on|tts / off. self._auto_tts_default: bool = False self._auto_tts_enabled_chats, self._auto_tts_disabled_chats = set(), set() # Turn keys where streaming TTS already delivered audio; whole-file auto-TTS skips them. self._streaming_tts_completed_turns: set[str] = set() # Chats whose typing indicator is paused (approval waits); _keep_typing skips them. self._typing_paused: set = set() - # Per-chat working-state phrase read by text-rendering typing indicators (Slack); - # the regular _keep_typing refresh picks it up, so updates cost no extra API calls. + # Per-chat status phrase; the regular _keep_typing refresh renders it (no extra API calls). self._status_text: Dict[str, str] = {} @property @@ -1894,8 +1855,7 @@ class BasePlatformAdapter(ABC): if isinstance(event, MessageChunk) and event.text: sink.on_delta(event.text) elif isinstance(event, MessageStop) and not event.final: - # Intermediate stop (text → tool → text) = segment break; the terminal - # stop is signalled by the gateway via finish(), not here. + # Intermediate stop (text → tool → text) = segment break; the terminal stop is finish(). sink.on_segment_break() elif isinstance(event, Commentary) and event.text: sink.on_commentary(event.text) @@ -1968,8 +1928,8 @@ class BasePlatformAdapter(ABC): (failures — permissions, ENOSPC — must neither be silent nor spam reconnect loops).""" try: from gateway.status import write_runtime_status - # Multiplexed secondary adapters share the runtime status file; their - # runner stamps a ``:`` key so profiles don't clobber. + # Multiplexed adapters share the status file; the runner stamps + # ``:``. platform_key = getattr(self, "_runtime_status_platform_key", None) or self.platform.value write_runtime_status(platform=platform_key, **kwargs) except Exception as exc: @@ -1987,10 +1947,9 @@ class BasePlatformAdapter(ABC): return result = handler(self) if asyncio.iscoroutine(result): - # Detached + shielded: often awaited from an adapter-owned task that the - # handler's ``disconnect()`` cancels; unshielded, the handler died mid-flight - # (adapter popped but never queued for reconnect). Strong ref so the loop's - # weak-ref task table can't GC it. + # Detached + shielded: often awaited from an adapter-owned task that the handler's + # ``disconnect()`` cancels; unshielded, the handler died mid-flight (adapter popped + # but never queued for reconnect). Strong ref so the loop can't GC it. task = asyncio.ensure_future(result) _tasks = _lazy_attr(self, "_detached_fatal_tasks", set) _tasks.add(task) @@ -1998,8 +1957,7 @@ class BasePlatformAdapter(ABC): try: await asyncio.shield(task) except asyncio.CancelledError: - # Carrier cancelled (typically by our own teardown inside the handler): let it - # finish detached and consume its exception to avoid "never retrieved" noise. + # Carrier cancelled (our own teardown inside the handler): let it finish detached. if not task.done(): task.add_done_callback(_consume_detached_handler_exception) raise @@ -2017,8 +1975,7 @@ class BasePlatformAdapter(ABC): return True if (self._platform_lock_takeover_allowed and not self._platform_lock_takeover_attempted and isinstance(existing, dict)): - # Consume the authority before any I/O: one adapter connect gets at most one - # termination attempt, even if lock re-acquire or later initialization fails. + # Consume the authority before any I/O: at most one termination attempt per connect. self._platform_lock_takeover_allowed = False self._platform_lock_takeover_attempted = True owner_pid = take_over_scoped_lock_holder(existing) @@ -2031,8 +1988,8 @@ class BasePlatformAdapter(ABC): logger.info("[%s] Acquired %s after taking over PID %d", self.name, resource_desc, owner_pid) return True owner_pid = existing.get('pid') if isinstance(existing, dict) else None - # Scoped locks are machine-global: name the owning profile when known so the - # operator can tell WHICH gateway holds the credential. + # Scoped locks are machine-global: name the owning profile so the operator knows WHICH + # gateway. owner_profile = scoped_lock_owner_label(existing) pid_part = f" (PID {owner_pid})" if owner_pid else "" holder = f" by the '{owner_profile}' profile gateway{pid_part}" if owner_profile else pid_part @@ -2187,8 +2144,8 @@ class BasePlatformAdapter(ABC): return None return resolved if isinstance(resolved, str) and resolved.strip() else None - # ── Inbound text batching (adapters that merge split messages): subclasses supply - # ``_pending_text_batches`` / ``_pending_text_batch_tasks`` dicts and ``_flush_text_batch(key)``. + # ── Inbound text batching: subclasses supply ``_pending_text_batches`` / + # ``_pending_text_batch_tasks`` dicts and ``_flush_text_batch(key)``. def _event_session_key(self, event: "MessageEvent") -> str: """Adapter-level session key for ``event``, profile-namespaced like the agent run.""" @@ -2227,8 +2184,7 @@ class BasePlatformAdapter(ABC): if not store: return None try: - # Transcripts are keyed by session_id, not gateway session_key; map via - # the routing index, falling back to the raw key for stores that accept either. + # Transcripts are keyed by session_id; map via the routing index, else the raw key. peek = getattr(store, "peek_session_id", None) session_id = peek(session_key) if callable(peek) else None transcript = store.load_transcript(session_id or session_key) @@ -2236,9 +2192,8 @@ class BasePlatformAdapter(ABC): return None if not transcript: return None - # Exclude the CURRENT TURN entirely (from the last user message onward): rows are - # persisted as produced, so this turn's tool results are already there and a - # text_to_speech media_tag would dedup away its own attachment. + # Exclude the CURRENT TURN (from the last user message on): rows persist as produced, so a + # text_to_speech media_tag would otherwise dedup away its own attachment. history = list(transcript) last_user_idx = next( (i for i in range(len(history) - 1, -1, -1) if history[i].get("role") == "user"), None) @@ -2286,8 +2241,7 @@ class BasePlatformAdapter(ABC): try: threading.Thread(target=_worker, name="media-history-lookup", daemon=True).start() except Exception: - # start() failed (thread exhaustion): the worker never ran, so release the permit - # here or it leaks. Plain Exception on purpose — don't eat KeyboardInterrupt/SystemExit. + # start() failed (thread exhaustion): the worker never ran, so release the permit here. admission.release() _fail_open("Could not start media-delivery history lookup worker for", exc_info=True) return None @@ -2316,8 +2270,7 @@ class BasePlatformAdapter(ABC): metadata: Optional[Dict[str, Any]] = None) -> SendResult: """Send ``content`` (may be markdown) to a chat; returns SendResult with message id.""" - # True for surfaces that need an explicit finalize edit to close the message - # lifecycle (DingTalk AI Cards), so the stream consumer never skips it. + # Surfaces needing an explicit finalize edit (DingTalk AI Cards): the consumer never skips it. REQUIRES_EDIT_FINALIZE: bool = False async def create_handoff_thread(self, parent_chat_id: str, name: str) -> Optional[str]: @@ -2361,8 +2314,7 @@ class BasePlatformAdapter(ABC): # No running loop (unit tests): close the coroutine to avoid a never-awaited warning. coro.close() - # ── Shared interactive-prompt formatting cores: ``_format_exec_approval`` templates; - # adapters override them to keep their historical wording byte-identical. + # ── ``_format_exec_approval`` templates; adapters override to keep historical wording. _EA_HEADER: str = "⚠️ Command Approval Required\n\n" _EA_CODE_OPEN: str = "```\n" _EA_CODE_CLOSE: str = "\n```\n" @@ -2424,8 +2376,7 @@ class BasePlatformAdapter(ABC): text-intercept resolves the next message). Default: numbered list + ``mark_awaiting_text``.""" if choices: - # Multi-select flag lives on the pending entry; look it up by id so the - # signature stays adapter-compatible. + # Multi-select flag lives on the pending entry (signature stays adapter-compatible). try: from tools import clarify_gateway as _cg with _cg._lock: @@ -2585,8 +2536,8 @@ class BasePlatformAdapter(ABC): """Play auto-TTS audio; override for invisible playback (Web UI). Default: send_voice.""" return await self.send_voice(chat_id=chat_id, audio_path=audio_path, **kwargs) - # ── Streaming TTS adapter contract: voice-capable adapters (LiveKit, Discord voice) accept - # PCM chunks while the LLM generates. Defaults report "unsupported" (whole-file fallback). + # ── Streaming TTS contract: voice adapters accept PCM chunks while the LLM generates. + # Defaults report "unsupported" (whole-file fallback). def supports_streaming_tts(self, chat_id: str, audio_format: AudioFormat) -> bool: """Return True when this adapter can accept streaming PCM for *chat_id*.""" @@ -2688,9 +2639,8 @@ class BasePlatformAdapter(ABC): start = m.start() if re.search(r'MEDIA:\s*$', content[max(0, start - 20):start]): continue # This is a MEDIA path quote, not inline code - # A whole tag in inline code (`MEDIA:/path.csv`) is a real directive — models - # format paths as code — so deliver it IF the path validates; prose examples - # with non-existent paths stay masked, fenced blocks always. + # A whole tag in inline code (`MEDIA:/path.csv`) is a real directive (models format + # paths as code): deliver IF it validates; non-existent examples stay masked. inner = m.group(0)[1:-1].strip() if inner.upper().startswith("MEDIA:"): candidate = _normalize_media_tag_path(inner[6:]) @@ -2709,8 +2659,8 @@ class BasePlatformAdapter(ABC): preserved.""" if '"' not in content or "MEDIA:" not in content: return content - # JSON value-context string: a quote preceded by : , { or [ (optional ws), - # capturing the (escape-aware) string body up to the closing quote. + # Value-context string: quote preceded by : , { or [; escape-aware body to the closing + # quote. spans = [ m.span(1) for m in re.finditer(r'(?<=[:,{\[])\s*"((?:[^"\\\n]|\\.)*)"', content) if re.search(r'MEDIA:\s*(?:~/|/|[A-Za-z]:[/\\])', m.group(1))] @@ -2725,15 +2675,13 @@ class BasePlatformAdapter(ABC): media = [] has_voice_tag = "[[audio_as_voice]]" in content cleaned = content.replace("[[audio_as_voice]]", "").replace("[[as_document]]", "") - # Scan a masked copy so example/stored MEDIA paths (code blocks, quotes, JSON string - # values) are never delivered; dedupe on the expanded path so a file referenced - # twice is uploaded once. + # Scan a masked copy so example/stored MEDIA paths (code, quotes, JSON values) are never + # delivered; dedupe on the expanded path so a file referenced twice uploads once. scan_content = _mask_media_scan_text(content) seen_paths: set = set() def _add(path: str) -> None: - # is_voice only for audio files: flagging an image is_voice would - # push it out of the photo batch into send_document. + # is_voice only for audio: a voice-flagged image would leave the photo batch. if path not in seen_paths: seen_paths.add(path) media.append((path, has_voice_tag and os.path.splitext(path)[1].lower() in _AUDIO_EXTS)) @@ -2751,8 +2699,8 @@ class BasePlatformAdapter(ABC): resolved = _match_extensionless_path(scan_content, match) if resolved is not None: _add(resolved[0]) - # Locate real tag spans on a masked copy of ``cleaned``, then delete exactly - # those spans from the unmasked text so protected spans survive verbatim. + # Locate tag spans on a masked copy, delete them from the unmasked text (protected spans + # survive). if media: spans = _real_media_tag_spans(_mask_media_scan_text(cleaned)) if spans: @@ -2775,8 +2723,7 @@ class BasePlatformAdapter(ABC): ignored); paths inside fenced or inline code are skipped so code samples are never mutilated. Dispatch by type lives in ``gateway/run.py``.""" ext_part = '|'.join(e.lstrip('.') for e in MEDIA_DELIVERY_EXTS) - # Lookbehind rejects URL/relative-path matches (https://…/img.png, ./foo.png); - # the alternation anchors Unix absolute, ``~/`` and Windows drive paths. + # Lookbehind rejects URL/relative matches (https://…/img.png, ./foo.png). path_re = re.compile( r'(? None: - # Must be async: the invoker awaits awaitable callbacks, and a sync - # wrapper would silently drop coroutines returned by async hooks. + # Async so coroutines returned by async hooks are awaited, not dropped. for _cb in _chain: try: _result = _cb() @@ -2921,11 +2866,9 @@ class BasePlatformAdapter(ABC): self._post_delivery_callbacks.pop(session_key, None) return callback if callable(callback) else None - # ── Processing lifecycle hooks ────────────────────────────────────────── - # Subclasses override these to react to processing events (e.g. Discord - # 👀/✅/❌ reactions). Adapters exposing ``_add_reaction(chat_id, message_id, - # emoji)`` / ``_remove_reaction(chat_id, message_id)`` can instead set the - # emoji attributes below; left ``None`` the hook stays a no-op. + # ── Processing lifecycle hooks (Discord 👀/✅/❌ reactions). Adapters exposing + # ``_add_reaction(chat_id, message_id, emoji)`` / ``_remove_reaction(chat_id, message_id)`` + # can just set the emoji attributes; left ``None`` the hook is a no-op. _ACK_EMOJI: Optional[str] = None _OK_EMOJI: Optional[str] = None _FAIL_EMOJI: Optional[str] = None @@ -3133,8 +3076,8 @@ class BasePlatformAdapter(ABC): store = self._text_debounce_store() state = store.get(session_key) if state is not None and not self._can_merge_text_debounce_events(state.event, event): - # Preserve sender attribution in shared sessions: flush the current - # buffer as the next pending turn; the new sender starts a fresh burst. + # Preserve sender attribution: flush the buffer as the next turn, new sender starts + # fresh. await self._flush_text_debounce_now(session_key) state = store.get(session_key) if state is not None and not self._can_merge_text_debounce_events(state.event, event): @@ -3195,10 +3138,8 @@ class BasePlatformAdapter(ABC): if state is not None: state.cancel_timer() - # ── Session task + guard ownership helpers ────────────────────────────── - # Paired with the _session_tasks owner map so lifecycle reconciliation is - # deterministic across normal completion, /stop /new /reset bypass commands, - # and stale-lock self-heal on the next inbound message. + # ── Session task + guard ownership helpers: paired with the _session_tasks owner map so + # reconciliation is deterministic across completion, /stop /new /reset, and stale-lock heal. def _release_session_guard(self, session_key: str, *, guard: Optional[asyncio.Event] = None) -> None: """Release the session guard; with ``guard`` given, only if the entry is still that exact @@ -3301,8 +3242,8 @@ class BasePlatformAdapter(ABC): command_guard = asyncio.Event() self._active_sessions[session_key] = command_guard try: - # Send BEFORE cancelling the old task so cancellation side effects - # can't drop the "/new" confirmation; cancel AFTER for deterministic ordering. + # Send BEFORE cancelling so cancellation side effects can't drop the "/new" + # confirmation. await self._dispatch_inline_reply(event, log_cmd=cmd) await self.cancel_session_processing(session_key, release_guard=False, discard_pending=False) except Exception: @@ -3338,21 +3279,18 @@ class BasePlatformAdapter(ABC): if session_key in self._active_sessions: await self._handle_message_while_active(event, session_key) return - # Guard is installed synchronously BEFORE the task spawns (grammY sequentialize) - # so a second message can't race in; the owner task is recorded atomically. + # Guard installed synchronously BEFORE the task spawns so a second message can't race in. self._start_session_processing(event, session_key) async def _handle_message_while_active(self, event: MessageEvent, session_key: str) -> None: """Route a message that arrived while ``session_key`` is busy: bypass commands / clarify replies dispatch inline, everything else is queued.""" - # Bypass commands run inline: queued they would leak as user text (/stop, /new) - # or deadlock (/approve, /deny). + # Bypass commands run inline: queued they'd leak as user text (/new) or deadlock (/approve). cmd = event.get_command() from hermes_cli.commands import (is_interrupt_then_dispatch, should_bypass_active_session) if should_bypass_active_session(cmd): try: - # /stop, /new, /reset take the handoff path (cancel + response + drain); - # other bypass commands dispatch directly without cancelling the task. + # /stop, /new, /reset: cancel + response + drain; other bypasses don't cancel. if cmd and is_interrupt_then_dispatch(cmd): self._discard_text_debounce(session_key) await self._dispatch_active_session_command(event, session_key, cmd) @@ -3363,8 +3301,8 @@ class BasePlatformAdapter(ABC): except Exception as e: logger.error("[%s] Command '/%s' dispatch failed: %s", self.name, cmd, e, exc_info=True) return - # Clarify bypass: while blocked on clarify_tool, the next non-command message - # must reach the runner's text-intercept, not the queue. + # Clarify bypass: while blocked on clarify_tool the next message must reach the + # text-intercept. if not cmd and event.allow_gateway_control: try: from tools import clarify_gateway as _clarify_mod @@ -3733,8 +3671,7 @@ class BasePlatformAdapter(ABC): is_ephemeral_response = isinstance(response, EphemeralReply) # Unwrap EphemeralReply for downstream text processing; TTL applies after send. response, _ephemeral_ttl = self._unwrap_ephemeral(response) - # None/empty is normal (streamed/queued). Suppress a stale response when the - # session was interrupted by a still-pending message. + # None/empty is normal (streamed/queued). Suppress a stale response after an interrupt. if response and interrupt_event.is_set() and session_key in self._pending_messages: logger.info("[%s] Suppressing stale response for interrupted session %s", self.name, session_key) @@ -3745,8 +3682,7 @@ class BasePlatformAdapter(ABC): extracted = await self._extract_response_content( response, event, session_key, is_ephemeral_response=is_ephemeral_response) text_content, media_files = extracted.text_content, extracted.media_files - # Final user-visible content gets notify=True; typing/status - # metadata stays unmarked so progress bubbles remain thread-strict. + # Final content gets notify=True; typing metadata stays unmarked (thread-strict). _final_thread_metadata = _mark_notify_metadata(_thread_metadata) _tts_paths, _tts_requested_path = ( await self._synthesize_auto_tts(text_content) @@ -3780,9 +3716,8 @@ class BasePlatformAdapter(ABC): await self._run_processing_hook( "on_processing_complete", event, ProcessingOutcome.SUCCESS if processing_ok else ProcessingOutcome.FAILURE) - # The active drain owns debounce state: force-flush an unfired timer so this - # task hands off the follow-up to a fresh drain task. Clear the Event BEFORE - # the stop-typing await so a concurrent inbound still sees a live guard. + # Force-flush an unfired debounce timer so this task hands off to a fresh drain task. + # Clear the Event BEFORE the stop-typing await so concurrent inbound sees a live guard. await self._flush_text_debounce_now(session_key) if session_key in self._pending_messages: pending_event = self._pending_messages.pop(session_key) @@ -3801,17 +3736,15 @@ class BasePlatformAdapter(ABC): await self._run_processing_hook("on_processing_complete", event, ProcessingOutcome.FAILURE) logger.error("[%s] Error handling message: %s", self.name, e, exc_info=True) _thread_metadata = (await self._notify_turn_error(event, e)) or _thread_metadata - # SystemExit/KeyboardInterrupt must propagate; other BaseExceptions are - # contained so this task never logs "exception was never retrieved". + # SystemExit/KeyboardInterrupt propagate; other BaseExceptions are contained. if isinstance(e, (SystemExit, KeyboardInterrupt)): raise finally: - # Stop typing BEFORE the post-delivery callback: a stuck callback must not - # leave the refresh running indefinitely. + # Stop typing BEFORE the post-delivery callback: a stuck callback must not keep it + # alive. await self._stop_typing_refresh(event.source.chat_id, typing_task, metadata=_thread_metadata) await self._fire_post_delivery_callback(session_key, interrupt_event) - # Callback work or a late refresh may have recreated platform typing — one - # final bounded stop before releasing the guard. + # Callback work or a late refresh may have recreated typing — one final bounded stop. await self._stop_typing_refresh( event.source.chat_id, None, metadata=_thread_metadata, stop_attempts=1) # Flush any timer that missed the in-band drain, then reconcile ownership. @@ -3844,8 +3777,8 @@ class BasePlatformAdapter(ABC): async def cancel_background_tasks(self) -> None: """Cancel in-flight background tasks (shutdown/replacement); 5s bound each, stragglers are untracked and left to unwind.""" - # Re-drain (max 5 rounds) until the task set stabilizes: a message arriving mid-gather - # would spawn a task the final clear() would untrack. + # Re-drain (max 5 rounds): a message arriving mid-gather spawns a task clear() would + # untrack. for _ in range(5): tasks = [task for task in self._background_tasks if not task.done()] if not tasks: @@ -3913,9 +3846,8 @@ class BasePlatformAdapter(ABC): source = SessionSource(**fields, profile=profile, role_authorized=role_authorized, auto_thread_created=auto_thread_created, auto_thread_initial_name=auto_thread_initial_name) - # Both transport-only, kept out of to_dict(): the live receiving adapter is - # authoritative this turn even if profile_routes picks another runtime; the - # fail-closed reject flag is consumed before auth so rejected routes never 500. + # Transport-only, kept out of to_dict(): the receiving adapter is authoritative this turn + # even if profile_routes picks another runtime; the reject flag is consumed before auth. source._transport_adapter_ref = weakref.ref(self) source.profile_route_rejected = profile_route_rejected return source @@ -3951,8 +3883,7 @@ class BasePlatformAdapter(ABC): carry_lang: Optional[str] = None # language tag ("" ok) when previous chunk ended mid-fence while remaining: prefix = f"```{carry_lang}\n" if carry_lang is not None else "" - # Body budget after prefix, closing fence and indicator; floored so a tiny - # max_length (0/1 from a relay capability descriptor) can't stall the loop. + # Body budget after prefix/fence/indicator; floored so a tiny max_length can't stall. headroom = max_length - INDICATOR_RESERVE - _len(prefix) - _len(FENCE_CLOSE) if headroom < 1: headroom = max(1, max_length // 2) @@ -3963,8 +3894,7 @@ class BasePlatformAdapter(ABC): final_chunk += FENCE_CLOSE chunks.append(final_chunk) break - # Natural split (newline, then space). A custom _len measures headroom in its - # own units: map to the largest codepoint offset that fits the budget. + # Natural split (newline, then space); a custom _len budget maps to a codepoint offset. _cp_limit = ( _custom_unit_to_cp(remaining, headroom, _len) if _len is not len else headroom) region = remaining[:_cp_limit] @@ -3972,9 +3902,9 @@ class BasePlatformAdapter(ABC): if split_at < _cp_limit // 2: split_at = region.rfind(" ") if split_at < 1: - # Floor at one codepoint: a zero _cp_limit (max_length 0/1, or a surrogate - # pair wider than the utf16 budget) would never shrink ``remaining`` and - # spin forever; exceeding max_length by one codepoint beats a hang. + # Floor at one codepoint: a zero _cp_limit (max_length 0/1, or a surrogate pair + # wider than the utf16 budget) would never shrink ``remaining``; overshooting beats + # a hang. split_at = max(1, _cp_limit) # Don't split inside an inline code span: an unpaired backtick breaks MarkdownV2. candidate = remaining[:split_at] From 268edd80a6f72fc61f31947113dfb0f46f0c0ffa Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Wed, 2 Sep 2026 23:26:53 -0700 Subject: [PATCH 07/13] =?UTF-8?q?refactor(gateway/platforms):=20base.py=20?= =?UTF-8?q?=E2=80=94=20flatten=20format=5Ftool=5Fevent/=5Fis=5Fsender=5Fau?= =?UTF-8?q?thorized,=20=5Fchain=5Fcallbacks=20helper,=20drop=20redundant?= =?UTF-8?q?=20IP-literal=20branch,=20reaction=20emoji=20dispatch?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- gateway/platforms/base.py | 151 +++++++++++++++++--------------------- 1 file changed, 69 insertions(+), 82 deletions(-) diff --git a/gateway/platforms/base.py b/gateway/platforms/base.py index 4b0289d95b..5862c098b6 100644 --- a/gateway/platforms/base.py +++ b/gateway/platforms/base.py @@ -297,11 +297,8 @@ def _no_proxy_entry_matches(entry: str, host: str, port: int | None = None) -> b return False host_ip = _ip_or_none(host) network = _ip_or_none(token_host, lambda v: ipaddress.ip_network(v, strict=False)) - if network is not None: + if network is not None: # CIDR or bare IP literal (a /32 / /128 network) return host_ip is not None and host_ip in network - token_ip = _ip_or_none(token_host) - if token_ip is not None: - return host_ip == token_ip if token_host.startswith("*."): return host.endswith(token_host[1:]) if token_host.startswith("."): @@ -874,9 +871,7 @@ def _parse_docker_volume_mounts() -> List[Tuple[Path, Path]]: except Exception: return [] mounts: List[Tuple[Path, Path]] = [] - if not isinstance(parsed, list): - return mounts - for entry in parsed: + for entry in parsed if isinstance(parsed, list) else (): spec = entry.strip() if isinstance(entry, str) else "" # Prefer the first ':/' so absolute container paths are unambiguous. sep = spec.find(":/") @@ -1021,11 +1016,9 @@ def _translate_docker_container_media_path(candidate: Path, session_key: str = " return None matched.sort(key=lambda m: -m[2]) for host_root, container_root, _score in matched: - try: - translated = (host_root / candidate.relative_to(container_root)).resolve(strict=True) - except (OSError, RuntimeError, ValueError): - continue - if translated == host_root or _path_is_within(translated, host_root): + translated = _resolve_path(host_root / candidate.relative_to(container_root), strict=True) + if translated is not None and ( + translated == host_root or _path_is_within(translated, host_root)): return translated _warn_unresolved_docker_media(candidate, session_key, "host file missing from sandbox") return None @@ -1867,24 +1860,22 @@ class BasePlatformAdapter(ABC): from gateway.stream_events import ToolCallChunk if not isinstance(event, ToolCallChunk): return None - from agent.display import get_tool_emoji - emoji = get_tool_emoji(event.tool_name, default="⚙️") + from agent.display import get_tool_emoji, prepare_tool_preview + head = f"{get_tool_emoji(event.tool_name, default='⚙️')} {event.tool_name}" if mode == "verbose" and event.args: import json args_str = json.dumps(event.args, ensure_ascii=False, default=str) if preview_max_len > 0 and len(args_str) > preview_max_len: args_str = args_str[:preview_max_len - 3] + "..." - return f"{emoji} {event.tool_name}({list(event.args.keys())})\n{args_str}" - if event.preview: - if mode == "verbose": - return f"{emoji} {event.tool_name}: \"{event.preview}\"" - # "all" / "new": short capped preview (default 40; progress bubbles persist as messages). - from agent.display import prepare_tool_preview - cap = preview_max_len if preview_max_len > 0 else 40 - prepared = prepare_tool_preview( - event.tool_name, event.args, fallback=event.preview, max_len=cap) - return f"{emoji} {event.tool_name}: \"{self.format_tool_preview(prepared)}\"" - return f"{emoji} {event.tool_name}..." + return f"{head}({list(event.args.keys())})\n{args_str}" + if not event.preview: + return f"{head}..." + if mode == "verbose": + return f'{head}: "{event.preview}"' + # "all" / "new": short capped preview (default 40; progress bubbles persist as messages). + cap = preview_max_len if preview_max_len > 0 else 40 + prepared = prepare_tool_preview(event.tool_name, event.args, fallback=event.preview, max_len=cap) + return f'{head}: "{self.format_tool_preview(prepared)}"' def format_tool_preview(self, preview: "ToolPreview") -> str: """Platform-native formatting of a compact tool preview; rich-text adapters may use @@ -2099,19 +2090,22 @@ class BasePlatformAdapter(ABC): non-boolean is "unknown", never an authorization that gates a credentialed side effect.""" if not user_id or self._authorization_check is None: return None - extra: Dict[str, Any] = {**({"is_bot": True} if is_bot else {}), - **({"thread_id": thread_id} if thread_id is not None else {})} + extra: Dict[str, Any] = {} + if is_bot: + extra["is_bot"] = True + if thread_id is not None: + extra["thread_id"] = thread_id try: result = self._authorization_check(user_id, chat_type, chat_id, **extra) - if result is True or result is False: - return result - logger.warning("[%s] Authorization check returned %s for user %s; treating as unknown", - self.name, type(result).__name__, user_id) - return None except Exception: logger.warning("[%s] Authorization check raised for user %s; treating as unknown", self.name, user_id, exc_info=True) return None + if result is True or result is False: + return result + logger.warning("[%s] Authorization check returned %s for user %s; treating as unknown", + self.name, type(result).__name__, user_id) + return None def set_session_store(self, session_store: Any) -> None: """Set the session store (e.g. Slack checks for an active thread session @@ -2839,21 +2833,24 @@ class BasePlatformAdapter(ABC): # Same-or-newer generation: chain so both fire in registration order. if callable(existing_cb) and ( existing_gen is None or generation is None or int(existing_gen) == int(generation)): - _chain = (existing_cb, callback) - - async def _chained() -> None: - # Async so coroutines returned by async hooks are awaited, not dropped. - for _cb in _chain: - try: - _result = _cb() - if inspect.isawaitable(_result): - await _result - except Exception: - logger.debug("Post-delivery callback failed", exc_info=True) - callback = _chained + callback = self._chain_callbacks(existing_cb, callback) self._post_delivery_callbacks[session_key] = ( callback if generation is None else (int(generation), callback)) + @staticmethod + def _chain_callbacks(*callbacks: Callable) -> Callable[[], Awaitable[None]]: + """Async wrapper running ``callbacks`` in order with per-callback exception isolation; + async so coroutines returned by async hooks are awaited, not dropped.""" + async def _chained() -> None: + for _cb in callbacks: + try: + _result = _cb() + if inspect.isawaitable(_result): + await _result + except Exception: + logger.debug("Post-delivery callback failed", exc_info=True) + return _chained + def pop_post_delivery_callback( self, session_key: str, *, generation: int | None = None) -> Callable | None: """Pop a deferred callback, optionally requiring generation ownership.""" @@ -2886,16 +2883,14 @@ class BasePlatformAdapter(ABC): add: Any = getattr(self, "_add_reaction", None) remove: Any = getattr(self, "_remove_reaction", None) enabled = getattr(self, "_reactions_enabled", None) - if not callable(add) or not callable(remove) or (callable(enabled) and not enabled()): - return chat_id = getattr(event.source, "chat_id", None) message_id = getattr(event, "message_id", None) - if not chat_id or not message_id: + if (not callable(add) or not callable(remove) or (callable(enabled) and not enabled()) + or not chat_id or not message_id): return await remove(chat_id, message_id) - emoji = ( - self._OK_EMOJI if outcome == ProcessingOutcome.SUCCESS - else self._FAIL_EMOJI if outcome == ProcessingOutcome.FAILURE else None) + emoji = {ProcessingOutcome.SUCCESS: self._OK_EMOJI, + ProcessingOutcome.FAILURE: self._FAIL_EMOJI}.get(outcome) if emoji: await add(chat_id, message_id, emoji) @@ -3124,9 +3119,8 @@ class BasePlatformAdapter(ABC): return False state.cancel_timer(unless=asyncio.current_task()) state.task = None - existing_pending = self._pending_messages.get(session_key) - if (existing_pending is not None - and not self._can_merge_text_debounce_events(existing_pending, state.event)): + pending = self._pending_messages.get(session_key) + if pending is not None and not self._can_merge_text_debounce_events(pending, state.event): return False store.pop(session_key, None) merge_pending_message_event(self._pending_messages, session_key, state.event, merge_text=True) @@ -3483,13 +3477,12 @@ class BasePlatformAdapter(ABC): else: result = await self.send_document(chat_id=chat_id, file_path=path, metadata=metadata) if not result.success: - label = "media" if media_tag else "local file" - logger.warning("[%s] Failed to send %s (%s): %s", self.name, label, ext, result.error) + logger.warning("[%s] Failed to send %s (%s): %s", self.name, + "media" if media_tag else "local file", ext, result.error) await self._notify_media_delivery_failure(chat_id, path, is_voice=is_voice, metadata=metadata) - _non_image_media = [(p, v) for p, v in media_files if v or not _as_image(p)] - if _non_image_media: - logger.info("[%s] Delivering %d non-image MEDIA attachment(s)", self.name, len(_non_image_media)) - queue = [(p, v, True) for p, v in _non_image_media] + queue = [(p, v, True) for p, v in media_files if v or not _as_image(p)] + if queue: + logger.info("[%s] Delivering %d non-image MEDIA attachment(s)", self.name, len(queue)) queue += [(p, False, False) for p in local_files if not _as_image(p)] for path, is_voice, media_tag in queue: if human_delay > 0: @@ -3596,16 +3589,14 @@ class BasePlatformAdapter(ABC): if not is_ephemeral_response: local_files, text_content = self.extract_local_files(text_content) local_files = self.filter_local_delivery_paths(local_files, session_key=session_key) - _history_media_paths = ( - await self._bounded_history_media_paths_for_session(session_key) - if local_files else None) - if _history_media_paths: - _suppressed = [p for p in local_files if p in _history_media_paths] - if _suppressed: - logger.info( - "[%s] Suppressing %d bare local file path(s) already " - "delivered in this session: %s", self.name, len(_suppressed), _suppressed) - local_files = [p for p in local_files if p not in _history_media_paths] + history = (await self._bounded_history_media_paths_for_session(session_key) + if local_files else None) + if history: + suppressed = [p for p in local_files if p in history] + if suppressed: + logger.info("[%s] Suppressing %d bare local file path(s) already delivered in " + "this session: %s", self.name, len(suppressed), suppressed) + local_files = [p for p in local_files if p not in history] if local_files: logger.info("[%s] extract_local_files found %d file(s) in response", self.name, len(local_files)) if not (text_content or images or local_files or media_files): @@ -3684,10 +3675,10 @@ class BasePlatformAdapter(ABC): text_content, media_files = extracted.text_content, extracted.media_files # Final content gets notify=True; typing metadata stays unmarked (thread-strict). _final_thread_metadata = _mark_notify_metadata(_thread_metadata) - _tts_paths, _tts_requested_path = ( - await self._synthesize_auto_tts(text_content) - if self._wants_auto_tts(event, session_key, interrupt_event, text_content, media_files) - else ([], None)) + _tts_paths, _tts_requested_path = [], None + if self._wants_auto_tts( + event, session_key, interrupt_event, text_content, media_files): + _tts_paths, _tts_requested_path = await self._synthesize_auto_tts(text_content) # TTS plays before text; generated files are removed afterwards. _tts_caption_delivered = False for _tts_index, _tts_path in enumerate(_tts_paths): @@ -3833,11 +3824,10 @@ class BasePlatformAdapter(ABC): parent_chat_id=_opt(parent_chat_id), message_id=_opt(message_id)) profile = None # from configured routes; None when no match / no routes profile_route_rejected = False - runner = self.gateway_runner - if runner is not None: + if self.gateway_runner is not None: from gateway.profile_routing import ProfileRouteRejected try: - profile = runner._profile_name_for_source(SessionSource(**fields)) + profile = self.gateway_runner._profile_name_for_source(SessionSource(**fields)) except ProfileRouteRejected: profile_route_rejected = True except Exception: @@ -3923,12 +3913,9 @@ class BasePlatformAdapter(ABC): full_chunk = prefix + chunk_body # Walk only chunk_body (not the prepended prefix) for the fence state. in_code, lang = fence_state_after(chunk_body, carry_lang is not None, carry_lang or "") - if in_code: - full_chunk += FENCE_CLOSE # Close the orphaned fence so the chunk stands alone - carry_lang = lang - else: - carry_lang = None - chunks.append(full_chunk) + carry_lang = lang if in_code else None + # Close the orphaned fence so the chunk stands alone. + chunks.append(full_chunk + FENCE_CLOSE if in_code else full_chunk) if len(chunks) > 1: chunks = [f"{chunk} ({i + 1}/{len(chunks)})" for i, chunk in enumerate(chunks)] return chunks From a0e4d9a87d420c88af3e50168ec2464f025324bf Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Wed, 2 Sep 2026 23:27:24 -0700 Subject: [PATCH 08/13] =?UTF-8?q?refactor(gateway/platforms):=20base.py=20?= =?UTF-8?q?=E2=80=94=20wrap=20long=20line?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- gateway/platforms/base.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/gateway/platforms/base.py b/gateway/platforms/base.py index 5862c098b6..b7f3975c3e 100644 --- a/gateway/platforms/base.py +++ b/gateway/platforms/base.py @@ -1874,7 +1874,8 @@ class BasePlatformAdapter(ABC): return f'{head}: "{event.preview}"' # "all" / "new": short capped preview (default 40; progress bubbles persist as messages). cap = preview_max_len if preview_max_len > 0 else 40 - prepared = prepare_tool_preview(event.tool_name, event.args, fallback=event.preview, max_len=cap) + prepared = prepare_tool_preview( + event.tool_name, event.args, fallback=event.preview, max_len=cap) return f'{head}: "{self.format_tool_preview(prepared)}"' def format_tool_preview(self, preview: "ToolPreview") -> str: From f82f0751690c3324c71a463cb23d62bdf27b96e0 Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Wed, 2 Sep 2026 23:31:47 -0700 Subject: [PATCH 09/13] =?UTF-8?q?refactor(gateway/platforms):=20base.py=20?= =?UTF-8?q?=E2=80=94=20single-normalizer=20=5Fsplit=5Fhost=5Fport,=20next(?= =?UTF-8?q?)-based=20proxy=20env=20scan,=20comprehension=20denylist/kanban?= =?UTF-8?q?=20roots?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- gateway/platforms/base.py | 59 ++++++++++++++++----------------------- 1 file changed, 24 insertions(+), 35 deletions(-) diff --git a/gateway/platforms/base.py b/gateway/platforms/base.py index b7f3975c3e..93fe8ece1f 100644 --- a/gateway/platforms/base.py +++ b/gateway/platforms/base.py @@ -256,20 +256,22 @@ def _detect_macos_system_proxy() -> str | None: def _split_host_port(value: str) -> tuple[str, int | None]: + """``(host, port)`` from a URL, ``[v6]:port``, ``host:port`` or bare host; host lowercased.""" raw = str(value or "").strip() if not raw: return "", None if "://" in raw: parsed = urlsplit(raw) - return (parsed.hostname or "").lower().rstrip("."), parsed.port - if raw.startswith("[") and "]" in raw: + host, port = parsed.hostname or "", parsed.port + elif raw.startswith("[") and "]" in raw: host, _, rest = raw[1:].partition("]") port = int(rest[1:]) if rest.startswith(":") and rest[1:].isdigit() else None - return host.lower().rstrip("."), port - host, _, maybe_port = raw.rpartition(":") - if raw.count(":") == 1 and maybe_port.isdigit(): - return host.lower().rstrip("."), int(maybe_port) - return raw.lower().strip("[]").rstrip("."), None + elif raw.count(":") == 1 and raw.rpartition(":")[2].isdigit(): + host, _, port_s = raw.rpartition(":") + port = int(port_s) + else: + host, port = raw.strip("[]"), None + return host.lower().rstrip("."), port def _no_proxy_entries() -> list[str]: @@ -326,18 +328,12 @@ def resolve_proxy_url( ``gateway.trust_env`` is true. None when nothing is found or NO_PROXY matches a target.""" value = (os.environ.get(platform_env_var) or "").strip() if platform_env_var else "" if not value: - if not gateway_trust_env(): - # trust_env false: only the explicit per-platform var above is honored. + if not gateway_trust_env(): # only the explicit per-platform var is honored return None - for key in ("HTTPS_PROXY", "HTTP_PROXY", "ALL_PROXY", - "https_proxy", "http_proxy", "all_proxy"): - value = (os.environ.get(key) or "").strip() - if value: - break + keys = ("HTTPS_PROXY", "HTTP_PROXY", "ALL_PROXY", "https_proxy", "http_proxy", "all_proxy") + value = next((v for k in keys if (v := (os.environ.get(k) or "").strip())), "") proxy = normalize_proxy_url(value or _detect_macos_system_proxy()) - if proxy and should_bypass_proxy(target_hosts): - return None - return proxy + return None if proxy and should_bypass_proxy(target_hosts) else proxy def _aiohttp_socks_connector(proxy_url: str): @@ -764,15 +760,12 @@ def _kanban_attachment_roots() -> List[Path]: home_override = os.environ.get("HERMES_KANBAN_HOME", "").strip() root = Path(home_override).expanduser() if home_override else _HERMES_ROOT roots = [root / "kanban" / "attachments"] - boards_root = root / "kanban" / "boards" - try: - board_dirs = [path for path in boards_root.iterdir() + with contextlib.suppress(OSError): + board_dirs = [path for path in (root / "kanban" / "boards").iterdir() if path.is_dir() and not path.is_symlink() and re.fullmatch(r"[a-z0-9][a-z0-9_-]{0,63}", path.name) and (path / "kanban.db").is_file()] - except OSError: - return roots - roots.extend(path / "attachments" for path in board_dirs) + roots.extend(path / "attachments" for path in board_dirs) return roots @@ -799,12 +792,10 @@ def _media_delivery_recency_seconds() -> float: def _media_delivery_denied_paths() -> List[Path]: """Return absolute denylist paths under which delivery is never allowed.""" - denied = [Path(p) for p in _MEDIA_DELIVERY_DENIED_PREFIXES] home = Path(os.path.expanduser("~")) - denied.extend(home / sub for sub in _MEDIA_DELIVERY_DENIED_HOME_SUBPATHS) - for hermes_root in (_HERMES_HOME, _HERMES_ROOT): - denied.extend(hermes_root / rel for rel in _ROOT_CREDENTIAL_PATHS) - return denied + return [*map(Path, _MEDIA_DELIVERY_DENIED_PREFIXES), + *(home / sub for sub in _MEDIA_DELIVERY_DENIED_HOME_SUBPATHS), + *(r / rel for r in (_HERMES_HOME, _HERMES_ROOT) for rel in _ROOT_CREDENTIAL_PATHS)] def _resolve_path(path: Path, *, strict: bool = False, expand: bool = False) -> Optional[Path]: @@ -893,25 +884,23 @@ def _docker_sandbox_dir_candidates(session_key: str = "") -> List[str]: ``_resolve_container_task_id`` (tools/terminal_tool.py): containers are PROFILE-scoped (``default``, else ``profile:``); legacy ``session:`` sandboxes stay as a fallback. The key is passed explicitly because delivery runs after the turn's contextvars were cleared.""" - candidates: List[str] = [] try: from tools.environments.path_utils import sanitize_task_id_for_path except Exception: return ["default"] - # Explicit trusted-profiles opt-in: one shared container identity. - shared = _tenv("TERMINAL_DOCKER_SHARED_CONTAINER_KEY", "").strip() - if shared: - candidates.append(sanitize_task_id_for_path(f"shared:{shared}")) try: from hermes_cli.profiles import get_active_profile_name profile = get_active_profile_name() or "default" except Exception: profile = "default" + candidates: List[str] = [] + # Explicit trusted-profiles opt-in: one shared container identity. + if shared := _tenv("TERMINAL_DOCKER_SHARED_CONTAINER_KEY", "").strip(): + candidates.append(sanitize_task_id_for_path(f"shared:{shared}")) if profile != "default": candidates.append(sanitize_task_id_for_path(f"profile:{profile}")) candidates.append("default") - if session_key: - # Bug-window legacy layout: per-session sandboxes. + if session_key: # bug-window legacy layout: per-session sandboxes candidates.append(sanitize_task_id_for_path(f"session:{session_key}")) return candidates From 35d4e86b6c1e83582675008eaeecc6be0061f2ad Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Wed, 2 Sep 2026 23:36:22 -0700 Subject: [PATCH 10/13] =?UTF-8?q?refactor(gateway/platforms):=20base.py=20?= =?UTF-8?q?=E2=80=94=20unify=20extension-less=20MEDIA=20tag=20scan=20(=5Fe?= =?UTF-8?q?xtensionless=5Fmedia=5Fmatches)=20across=20extract=5Fmedia=20an?= =?UTF-8?q?d=20span=20stripping?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- gateway/platforms/base.py | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/gateway/platforms/base.py b/gateway/platforms/base.py index 93fe8ece1f..bc505cb893 100644 --- a/gateway/platforms/base.py +++ b/gateway/platforms/base.py @@ -1192,21 +1192,26 @@ def _has_media_directives(text: str) -> bool: def _mask_media_scan_text(text: str) -> str: """Offset-preserving mask of protected spans (code, quotes, JSON string values). BasePlatformAdapter is defined later in this module; resolved at call time.""" - return BasePlatformAdapter._mask_json_string_media( - BasePlatformAdapter._mask_protected_spans(text)) + A = BasePlatformAdapter + return A._mask_json_string_media(A._mask_protected_spans(text)) + + +def _extensionless_media_matches(masked: str): + """Yield ``(match, safe_path, end_offset)`` for every extension-less / unknown-extension + MEDIA tag in ``masked`` that ``validate_media_delivery_path`` accepts.""" + for match in MEDIA_EXTENSIONLESS_TAG_RE.finditer(masked): + path = _normalize_media_tag_path(match.group("path")) + if path and _path_lacks_deliverable_extension(path): + resolved = _match_extensionless_path(masked, match) + if resolved is not None: + yield match, resolved[0], resolved[1] def _real_media_tag_spans(masked: str) -> list: """(start, end) spans of deliverable MEDIA tags on a masked copy: known-extension tags unconditionally, extension-less / unknown ones only if validate_media_delivery_path accepts.""" spans: list = [m.span() for m in MEDIA_TAG_CLEANUP_RE.finditer(masked)] - for match in MEDIA_EXTENSIONLESS_TAG_RE.finditer(masked): - path = _normalize_media_tag_path(match.group("path")) - if not path or not _path_lacks_deliverable_extension(path): - continue - resolved = _match_extensionless_path(masked, match) - if resolved is not None: - spans.append((match.start(), resolved[1])) + spans.extend((match.start(), end) for match, _, end in _extensionless_media_matches(masked)) return spans @@ -1216,7 +1221,7 @@ _INLINE_CODE_RE = re.compile(r'`[^`\n]+`') def _code_spans(content: str) -> list: """(start, end) spans of fenced code blocks and inline code in ``content``.""" - return [m.span() for m in _FENCED_CODE_RE.finditer(content)] + [m.span() for m in _INLINE_CODE_RE.finditer(content)] + return [m.span() for rx in (_FENCED_CODE_RE, _INLINE_CODE_RE) for m in rx.finditer(content)] def _blank_spans(text: str, spans: list) -> str: @@ -2676,13 +2681,8 @@ class BasePlatformAdapter(ABC): _add(os.path.expanduser(path)) except (OSError, RuntimeError, ValueError): continue # crafted ~\x00 path: skip it, keep the rest - for match in MEDIA_EXTENSIONLESS_TAG_RE.finditer(scan_content): - path = _normalize_media_tag_path(match.group("path")) - if not path or not _path_lacks_deliverable_extension(path): - continue - resolved = _match_extensionless_path(scan_content, match) - if resolved is not None: - _add(resolved[0]) + for _, safe_path, _ in _extensionless_media_matches(scan_content): + _add(safe_path) # Locate tag spans on a masked copy, delete them from the unmasked text (protected spans # survive). if media: From 46ef48b06d40cf8504b2bfc322717ebe2d3b3c2f Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Wed, 2 Sep 2026 23:48:48 -0700 Subject: [PATCH 11/13] =?UTF-8?q?refactor(gateway/platforms):=20base.py=20?= =?UTF-8?q?=E2=80=94=20early-return=20extract=5Fimages,=20flatten=20media-?= =?UTF-8?q?failure=20text,=20tidy=20build=5Fsource/obligation/cancel=20bod?= =?UTF-8?q?ies?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- gateway/platforms/base.py | 119 +++++++++++++++++++------------------- 1 file changed, 59 insertions(+), 60 deletions(-) diff --git a/gateway/platforms/base.py b/gateway/platforms/base.py index bc505cb893..62052178ea 100644 --- a/gateway/platforms/base.py +++ b/gateway/platforms/base.py @@ -771,13 +771,12 @@ def _kanban_attachment_roots() -> List[Path]: def _media_delivery_allowed_roots() -> List[Path]: """Return roots from which model-emitted local media may be delivered.""" - roots = [*map(Path, MEDIA_DELIVERY_SAFE_ROOTS), *_profile_cache_roots(), - *_kanban_attachment_roots()] - roots.extend( + operator_roots = ( root for chunk in os.environ.get(MEDIA_DELIVERY_ALLOW_DIRS_ENV, "").split(os.pathsep) for raw_root in chunk.split(",") if (root := Path(os.path.expanduser(raw_root.strip()))).is_absolute()) - return roots + return [*map(Path, MEDIA_DELIVERY_SAFE_ROOTS), *_profile_cache_roots(), + *_kanban_attachment_roots(), *operator_roots] def _media_delivery_recency_seconds() -> float: @@ -995,16 +994,14 @@ def _translate_docker_container_media_path(candidate: Path, session_key: str = " return None # Longest container-prefix match; equal-length prefixes are tried in insertion order. candidate_posix = candidate.as_posix() - matched: List[Tuple[Path, Path, int]] = [ - (host_root, container_root, len(container_posix)) - for host_root, container_root in mounts - for container_posix in (container_root.as_posix().rstrip("/") or "/",) - if candidate_posix == container_posix or candidate_posix.startswith(container_posix + "/")] + matched = [ + (host_root, container_root, len(prefix)) for host_root, container_root in mounts + for prefix in (container_root.as_posix().rstrip("/") or "/",) + if candidate_posix == prefix or candidate_posix.startswith(prefix + "/")] if not matched: _warn_unresolved_docker_media(candidate, session_key, "no mounted prefix matches") return None - matched.sort(key=lambda m: -m[2]) - for host_root, container_root, _score in matched: + for host_root, container_root, _score in sorted(matched, key=lambda m: -m[2]): translated = _resolve_path(host_root / candidate.relative_to(container_root), strict=True) if translated is not None and ( translated == host_root or _path_is_within(translated, host_root)): @@ -1920,9 +1917,8 @@ class BasePlatformAdapter(ABC): write_runtime_status(platform=platform_key, **kwargs) except Exception as exc: logged = _lazy_attr(self, "_status_write_logged", set) # object.__new__ in tests - key = (self.platform.value, context) - first = key not in logged - logged.add(key) + first = (self.platform.value, context) not in logged + logged.add((self.platform.value, context)) (logger.warning if first else logger.debug)( "Failed to write runtime status (%s) for %s: %s" + (" (further failures at debug level)" if first else ""), context, self.platform.value, exc) @@ -2372,10 +2368,10 @@ class BasePlatformAdapter(ABC): _is_multi = bool(getattr(_cg._entries.get(clarify_id), "multi_select", False)) except Exception: _is_multi = False - hint = ( - "Multiple selections allowed — reply with the numbers separated by commas or " - "spaces (e.g. \"1, 3\"), the option text, or your own answer." - if _is_multi else "Reply with the number, the option text, or your own answer.") + hint = "Reply with the number, the option text, or your own answer." + if _is_multi: + hint = ("Multiple selections allowed — reply with the numbers separated by commas " + "or spaces (e.g. \"1, 3\"), the option text, or your own answer.") numbered = [f" {i}. {choice}" for i, choice in enumerate(choices, start=1)] text = "\n".join([f"❓ {question}", "", *numbered, "", hint]) # Text fallback: let the gateway intercept capture the typed reply. @@ -2468,26 +2464,28 @@ class BasePlatformAdapter(ABC): def extract_images(content: str) -> Tuple[List[Tuple[str, str]], str]: """Extract ``![alt](url)`` and ```` image URLs from a response; returns ``([(url, alt_text), ...], content with those tags removed)``.""" - cleaned = content md_pattern = r'!\[([^\]]*)\]\((https?://[^\s\)]+)\)' - # Only extract URLs that look like actual images - images = [ - (m.group(2), m.group(1)) for m in re.finditer(md_pattern, content) - if any(m.group(2).lower().endswith(ext) or ext in m.group(2).lower() for ext in - ['.png', '.jpg', '.jpeg', '.gif', '.webp', 'fal.media', 'fal-cdn', 'replicate.delivery'])] # / / html_pattern = r']+)["\']?\s*/?>\s*(?:)?' + # Only extract URLs that look like actual images. + markers = ('.png', '.jpg', '.jpeg', '.gif', '.webp', 'fal.media', 'fal-cdn', + 'replicate.delivery') + images = [(m.group(2), m.group(1)) for m in re.finditer(md_pattern, content) + if any(m.group(2).lower().endswith(ext) or ext in m.group(2).lower() + for ext in markers)] images.extend((match.group(1), "") for match in re.finditer(html_pattern, content)) + if not images: + return images, content # Remove only the tags we extracted, not every markdown image. - if images: - extracted_urls = {url for url, _ in images} - def _remove_if_extracted(match): - url = match.group(2) if match.lastindex >= 2 else match.group(1) - return '' if url in extracted_urls else match.group(0) - for pattern in (md_pattern, html_pattern): - cleaned = re.sub(pattern, _remove_if_extracted, cleaned) - cleaned = re.sub(r'\n{3,}', '\n\n', cleaned).strip() # leftover blank lines - return images, cleaned + extracted_urls = {url for url, _ in images} + + def _remove_if_extracted(match): + url = match.group(2) if match.lastindex >= 2 else match.group(1) + return '' if url in extracted_urls else match.group(0) + cleaned = content + for pattern in (md_pattern, html_pattern): + cleaned = re.sub(pattern, _remove_if_extracted, cleaned) + return images, re.sub(r'\n{3,}', '\n\n', cleaned).strip() # leftover blank lines async def send_voice( self, chat_id: str, audio_path: str, caption: Optional[str] = None, @@ -2581,10 +2579,12 @@ class BasePlatformAdapter(ABC): """User-visible notice when a MEDIA attachment upload failed: the tag was already stripped from the text, so silence would be a silent drop.""" ext = Path(media_path).suffix.lower() - text = (_media_failure_text("audio") - if is_voice or should_send_media_as_audio(self.platform, ext, is_voice=is_voice) - else _media_failure_text("video") if ext in _VIDEO_EXTS - else _media_failure_text("file", os.path.basename(media_path))) + if is_voice or should_send_media_as_audio(self.platform, ext, is_voice=is_voice): + text = _media_failure_text("audio") + elif ext in _VIDEO_EXTS: + text = _media_failure_text("video") + else: + text = _media_failure_text("file", os.path.basename(media_path)) try: notice = await self.send(chat_id=chat_id, content=text, metadata=metadata) problem = None if notice.success else notice.error @@ -3364,13 +3364,11 @@ class BasePlatformAdapter(ABC): text_content: str, media_files: list) -> bool: """Auto-TTS on voice input (voice-first), gated by /voice or voice.auto_tts; skipped when streaming TTS already delivered audio this turn.""" + generation = getattr(interrupt_event, "_hermes_run_generation", None) return bool( self._should_auto_tts_for_chat(event.source.chat_id) - and event.message_type == MessageType.VOICE - and text_content - and not media_files - and not self._streaming_tts_turn_completed( - session_key, getattr(interrupt_event, "_hermes_run_generation", None), event=event)) + and event.message_type == MessageType.VOICE and text_content and not media_files + and not self._streaming_tts_turn_completed(session_key, generation, event=event)) async def _play_tts_file( self, event: MessageEvent, text_content: str, tts_path: str, first: bool, @@ -3399,12 +3397,13 @@ class BasePlatformAdapter(ABC): compute_obligation_id, ledger_enabled, mark_attempting, record_obligation) if not await asyncio.to_thread(ledger_enabled): return None + source = event.source obligation_id = compute_obligation_id( session_key, str(getattr(event, "message_id", "") or ""), text_content) await asyncio.to_thread( record_obligation, obligation_id=obligation_id, session_key=session_key, - platform=str(getattr(event.source.platform, "value", event.source.platform)), - chat_id=event.source.chat_id, thread_id=getattr(event.source, "thread_id", None), + platform=str(getattr(source.platform, "value", source.platform)), + chat_id=source.chat_id, thread_id=getattr(source, "thread_id", None), content=text_content, adapter_profile=getattr(delivery_adapter, "_owner_profile", None)) await asyncio.to_thread(mark_attempting, obligation_id) @@ -3708,10 +3707,10 @@ class BasePlatformAdapter(ABC): self._spawn_drain_task(pending_event, session_key) return # Drain task owns the session now. except asyncio.CancelledError: - outcome = ( - ProcessingOutcome.CANCELLED if asyncio.current_task() in self._expected_cancelled_tasks - else ProcessingOutcome.FAILURE) - await self._run_processing_hook("on_processing_complete", event, outcome) + expected = asyncio.current_task() in self._expected_cancelled_tasks + await self._run_processing_hook( + "on_processing_complete", event, + ProcessingOutcome.CANCELLED if expected else ProcessingOutcome.FAILURE) raise except BaseException as e: await self._run_processing_hook("on_processing_complete", event, ProcessingOutcome.FAILURE) @@ -3774,7 +3773,7 @@ class BasePlatformAdapter(ABC): except asyncio.TimeoutError: logger.warning("[%s] %d background task(s) did not exit within 5s; " "releasing tracking and letting them unwind in the background", - self.name, len([t for t in tasks if not t.done()])) + self.name, sum(not t.done() for t in tasks)) break with contextlib.suppress(Exception): # flush pending messages to disk before clearing from gateway.shutdown_flush import flush_pending_to_file @@ -3806,14 +3805,13 @@ class BasePlatformAdapter(ABC): profile is stamped on ``source.profile`` for per-profile HERMES_HOME isolation.""" def _opt(value) -> Optional[str]: return str(value) if value else None - fields = dict(platform=self.platform, chat_id=str(chat_id), chat_name=chat_name, - chat_type=chat_type, user_id=_opt(user_id), user_name=user_name, - thread_id=_opt(thread_id), chat_topic=(chat_topic or "").strip() or None, - user_id_alt=user_id_alt, chat_id_alt=chat_id_alt, is_bot=is_bot, - scope_id=_opt(scope_id), guild_id=_opt(guild_id), - parent_chat_id=_opt(parent_chat_id), message_id=_opt(message_id)) - profile = None # from configured routes; None when no match / no routes - profile_route_rejected = False + fields = dict( + platform=self.platform, chat_id=str(chat_id), chat_name=chat_name, chat_type=chat_type, + user_id=_opt(user_id), user_name=user_name, thread_id=_opt(thread_id), + chat_topic=(chat_topic or "").strip() or None, user_id_alt=user_id_alt, + chat_id_alt=chat_id_alt, is_bot=is_bot, scope_id=_opt(scope_id), + guild_id=_opt(guild_id), parent_chat_id=_opt(parent_chat_id), message_id=_opt(message_id)) + profile, profile_route_rejected = None, False # profile from configured routes, if any if self.gateway_runner is not None: from gateway.profile_routing import ProfileRouteRejected try: @@ -3823,9 +3821,10 @@ class BasePlatformAdapter(ABC): except Exception: logger.warning("Profile resolution failed for %s/%s, defaulting to active profile", self.platform, chat_id, exc_info=True) - source = SessionSource(**fields, profile=profile, role_authorized=role_authorized, - auto_thread_created=auto_thread_created, - auto_thread_initial_name=auto_thread_initial_name) + source = SessionSource( + **fields, profile=profile, role_authorized=role_authorized, + auto_thread_created=auto_thread_created, + auto_thread_initial_name=auto_thread_initial_name) # Transport-only, kept out of to_dict(): the receiving adapter is authoritative this turn # even if profile_routes picks another runtime; the reject flag is consumed before auth. source._transport_adapter_ref = weakref.ref(self) From e7e4aa2eed8d84d8dfa452f07445d23cb1db9ad8 Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Wed, 2 Sep 2026 23:50:40 -0700 Subject: [PATCH 12/13] =?UTF-8?q?refactor(gateway/platforms):=20base.py=20?= =?UTF-8?q?=E2=80=94=20final=20rewrap=20of=20remaining=20multi-line=20stat?= =?UTF-8?q?ements?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- gateway/platforms/base.py | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/gateway/platforms/base.py b/gateway/platforms/base.py index 62052178ea..18ec6e5260 100644 --- a/gateway/platforms/base.py +++ b/gateway/platforms/base.py @@ -994,10 +994,9 @@ def _translate_docker_container_media_path(candidate: Path, session_key: str = " return None # Longest container-prefix match; equal-length prefixes are tried in insertion order. candidate_posix = candidate.as_posix() - matched = [ - (host_root, container_root, len(prefix)) for host_root, container_root in mounts - for prefix in (container_root.as_posix().rstrip("/") or "/",) - if candidate_posix == prefix or candidate_posix.startswith(prefix + "/")] + matched = [(host_root, container_root, len(prefix)) for host_root, container_root in mounts + for prefix in (container_root.as_posix().rstrip("/") or "/",) + if candidate_posix == prefix or candidate_posix.startswith(prefix + "/")] if not matched: _warn_unresolved_docker_media(candidate, session_key, "no mounted prefix matches") return None @@ -3809,8 +3808,8 @@ class BasePlatformAdapter(ABC): platform=self.platform, chat_id=str(chat_id), chat_name=chat_name, chat_type=chat_type, user_id=_opt(user_id), user_name=user_name, thread_id=_opt(thread_id), chat_topic=(chat_topic or "").strip() or None, user_id_alt=user_id_alt, - chat_id_alt=chat_id_alt, is_bot=is_bot, scope_id=_opt(scope_id), - guild_id=_opt(guild_id), parent_chat_id=_opt(parent_chat_id), message_id=_opt(message_id)) + chat_id_alt=chat_id_alt, is_bot=is_bot, scope_id=_opt(scope_id), guild_id=_opt(guild_id), + parent_chat_id=_opt(parent_chat_id), message_id=_opt(message_id)) profile, profile_route_rejected = None, False # profile from configured routes, if any if self.gateway_runner is not None: from gateway.profile_routing import ProfileRouteRejected @@ -3821,10 +3820,9 @@ class BasePlatformAdapter(ABC): except Exception: logger.warning("Profile resolution failed for %s/%s, defaulting to active profile", self.platform, chat_id, exc_info=True) - source = SessionSource( - **fields, profile=profile, role_authorized=role_authorized, - auto_thread_created=auto_thread_created, - auto_thread_initial_name=auto_thread_initial_name) + source = SessionSource(**fields, profile=profile, role_authorized=role_authorized, + auto_thread_created=auto_thread_created, + auto_thread_initial_name=auto_thread_initial_name) # Transport-only, kept out of to_dict(): the receiving adapter is authoritative this turn # even if profile_routes picks another runtime; the reject flag is consumed before auth. source._transport_adapter_ref = weakref.ref(self) From baa22741fc8006a407757f80a02cb8f874a2531e Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Wed, 2 Sep 2026 23:54:28 -0700 Subject: [PATCH 13/13] =?UTF-8?q?refactor(gateway/platforms):=20base.py=20?= =?UTF-8?q?=E2=80=94=20wrap=20remaining=20>100-col=20lines?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- gateway/platforms/base.py | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/gateway/platforms/base.py b/gateway/platforms/base.py index 18ec6e5260..eab21d3b78 100644 --- a/gateway/platforms/base.py +++ b/gateway/platforms/base.py @@ -2280,7 +2280,8 @@ class BasePlatformAdapter(ABC): def _get_ephemeral_system_ttl_default(self) -> int: """Default :class:`EphemeralReply` TTL from ``display.ephemeral_system_ttl`` (``0`` = no auto-delete); non-fatal if config is unreadable.""" - return _or_default(lambda: int(_config_section("display").get("ephemeral_system_ttl", 0)), 0) + return _or_default( + lambda: int(_config_section("display").get("ephemeral_system_ttl", 0)), 0) def _schedule_ephemeral_delete(self, chat_id: str, message_id: str, ttl_seconds: int) -> None: """Spawn a detached task that deletes ``message_id`` after ``ttl_seconds``; best-effort @@ -2949,8 +2950,9 @@ class BasePlatformAdapter(ABC): except Exception: logger.debug("[%s] Failed to resolve live adapter for final delivery", self.name) return self - is_peer = isinstance(live_adapter, BasePlatformAdapter) and live_adapter.platform == self.platform - return live_adapter if is_peer else self + if isinstance(live_adapter, BasePlatformAdapter) and live_adapter.platform == self.platform: + return live_adapter + return self async def _send_with_retry( self, chat_id: str, content: str, reply_to: Optional[str] = None, metadata: Any = None, @@ -3736,7 +3738,8 @@ class BasePlatformAdapter(ABC): live for concurrent inbound; ownership moves so stale-lock detection works.""" self._clear_session_guard(session_key) self._track_session_task( - session_key, asyncio.create_task(self._process_message_background(pending_event, session_key))) + session_key, + asyncio.create_task(self._process_message_background(pending_event, session_key))) def _clear_session_guard(self, session_key: str) -> None: """Clear (not delete) the session's interrupt Event so the guard stays live for inbound.""" @@ -3808,8 +3811,9 @@ class BasePlatformAdapter(ABC): platform=self.platform, chat_id=str(chat_id), chat_name=chat_name, chat_type=chat_type, user_id=_opt(user_id), user_name=user_name, thread_id=_opt(thread_id), chat_topic=(chat_topic or "").strip() or None, user_id_alt=user_id_alt, - chat_id_alt=chat_id_alt, is_bot=is_bot, scope_id=_opt(scope_id), guild_id=_opt(guild_id), - parent_chat_id=_opt(parent_chat_id), message_id=_opt(message_id)) + chat_id_alt=chat_id_alt, is_bot=is_bot, scope_id=_opt(scope_id), + guild_id=_opt(guild_id), parent_chat_id=_opt(parent_chat_id), + message_id=_opt(message_id)) profile, profile_route_rejected = None, False # profile from configured routes, if any if self.gateway_runner is not None: from gateway.profile_routing import ProfileRouteRejected