Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions agent/conversation_loop.py
Original file line number Diff line number Diff line change
Expand Up @@ -1390,7 +1390,7 @@ def _stop_spinner():
agent._persist_session(messages, conversation_history)
agent.clear_interrupt()
return {
"final_response": f"Operation interrupted during retry ({_failure_hint}, attempt {retry_count}/{max_retries}).",
"final_response": None if agent._suppress_platform_notifications() else f"Operation interrupted during retry ({_failure_hint}, attempt {retry_count}/{max_retries}).",
"messages": messages,
"api_calls": api_call_count,
"completed": False,
Expand Down Expand Up @@ -1810,7 +1810,7 @@ def _stop_spinner():
agent._vprint(f"{agent.log_prefix}⚡ Interrupted during API call.", force=True)
agent._persist_session(messages, conversation_history)
interrupted = True
final_response = f"Operation interrupted: waiting for model response ({api_elapsed:.1f}s elapsed)."
final_response = "" if agent._suppress_platform_notifications() else f"Operation interrupted: waiting for model response ({api_elapsed:.1f}s elapsed)."
break

except Exception as api_error:
Expand Down Expand Up @@ -2404,7 +2404,7 @@ def _stop_spinner():
agent._persist_session(messages, conversation_history)
agent.clear_interrupt()
return {
"final_response": f"Operation interrupted: handling API error ({error_type}: {agent._clean_error_message(str(api_error))}).",
"final_response": None if agent._suppress_platform_notifications() else f"Operation interrupted: handling API error ({error_type}: {agent._clean_error_message(str(api_error))}).",
"messages": messages,
"api_calls": api_call_count,
"completed": False,
Expand Down Expand Up @@ -3057,7 +3057,7 @@ def _stop_spinner():
agent._persist_session(messages, conversation_history)
agent.clear_interrupt()
return {
"final_response": f"Operation interrupted: retrying API call after error (retry {retry_count}/{max_retries}).",
"final_response": None if agent._suppress_platform_notifications() else f"Operation interrupted: retrying API call after error (retry {retry_count}/{max_retries}).",
"messages": messages,
"api_calls": api_call_count,
"completed": False,
Expand Down
13 changes: 13 additions & 0 deletions gateway/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -298,6 +298,15 @@ class PlatformConfig:
# noise; keep True for back-channels where the operator wants them.
gateway_restart_notification: bool = True

# When True, the gateway delivers ONLY genuine agent replies on this
# platform and drops every gateway-originated "notice" (status, lifecycle,
# cron headers, STT/home-channel/footer prompts, "still working", shutdown,
# session-reset, etc.). Intended for platforms shared with human contacts
# (e.g. WhatsApp) where internal bubbles are reputationally bad. Enforced
# at the adapter send() chokepoint via the _delivering_agent_reply marker
# set by BasePlatformAdapter._send_with_retry. Default False = unchanged.
suppress_notifications: bool = False

# Platform-specific settings
extra: Dict[str, Any] = field(default_factory=dict)

Expand All @@ -307,6 +316,7 @@ def to_dict(self) -> Dict[str, Any]:
"extra": self.extra,
"reply_to_mode": self.reply_to_mode,
"gateway_restart_notification": self.gateway_restart_notification,
"suppress_notifications": self.suppress_notifications,
}
if self.token:
result["token"] = self.token
Expand Down Expand Up @@ -337,6 +347,9 @@ def from_dict(cls, data: Dict[str, Any]) -> "PlatformConfig":
home_channel=home_channel,
reply_to_mode=data.get("reply_to_mode", "first"),
gateway_restart_notification=_coerce_bool(_grn, True),
suppress_notifications=_coerce_bool(
data.get("suppress_notifications"), False
),
extra=data.get("extra", {}),
)

Expand Down
40 changes: 40 additions & 0 deletions gateway/platforms/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"""

import asyncio
import contextvars
import inspect
import ipaddress
import logging
Expand All @@ -24,6 +25,17 @@

logger = logging.getLogger(__name__)

# Task-local marker: True only while delivering a genuine agent reply through
# ``_send_with_retry`` (the single funnel both the background and synchronous
# message paths use for the model's text response, including slash-command
# replies the user explicitly requested). Adapters can consult this to drop
# gateway-internal "bubble" sends (status/lifecycle/cron/notice messages that
# call ``send()`` directly) on platforms where the user disabled them — see
# WhatsAppAdapter.send(). Task-local so concurrent sessions never cross-talk.
_delivering_agent_reply: contextvars.ContextVar[bool] = contextvars.ContextVar(
"hermes_delivering_agent_reply", default=False
)

# Audio file extensions Hermes recognizes for native audio delivery.
# Kept in sync with tools/send_message_tool.py and cron/scheduler.py via
# should_send_media_as_audio() below.
Expand Down Expand Up @@ -2780,6 +2792,34 @@ async def _send_with_retry(
metadata: Any = None,
max_retries: int = 2,
base_delay: float = 2.0,
) -> "SendResult":
"""Deliver a genuine agent reply, marking it for adapters.

Sets ``_delivering_agent_reply`` for the duration so platform adapters
can distinguish the model's actual reply from gateway-internal bubble
sends. The real retry/fallback logic lives in ``_send_with_retry_impl``.
"""
_reply_token = _delivering_agent_reply.set(True)
try:
return await self._send_with_retry_impl(
chat_id=chat_id,
content=content,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_send_with_retry is not reply-only: current main calls it for the draining status (gateway/run.py:5301-5316) and busy/queue acknowledgement (gateway/run.py:5600-5652). Setting this marker for every invocation lets those gateway notices bypass the proposed suppression guard.

reply_to=reply_to,
metadata=metadata,
max_retries=max_retries,
base_delay=base_delay,
)
finally:
_delivering_agent_reply.reset(_reply_token)

async def _send_with_retry_impl(
self,
chat_id: str,
content: str,
reply_to: Optional[str] = None,
metadata: Any = None,
max_retries: int = 2,
base_delay: float = 2.0,
) -> "SendResult":
"""
Send a message with automatic retry for transient network errors.
Expand Down
39 changes: 39 additions & 0 deletions gateway/platforms/whatsapp.py
Original file line number Diff line number Diff line change
Expand Up @@ -886,6 +886,45 @@ async def send(
if not content or not content.strip():
return SendResult(success=True, message_id=None)

# Notification suppression (single outbound chokepoint). Genuine agent
# replies are delivered through base._send_with_retry, which sets
# _delivering_agent_reply for the call. Every gateway-originated notice
# (status, lifecycle, cron, STT/home-channel/footer prompts, "still
# working", shutdown, session-reset, etc.) calls send() directly WITHOUT
# that marker. When whatsapp.suppress_notifications is true, drop any
# send that is not a genuine reply. This catches new notice types
# automatically without per-call-site patching.
try:
from gateway.platforms.base import _delivering_agent_reply
if not _delivering_agent_reply.get():
from hermes_cli.config import read_raw_config
_raw = read_raw_config()
# Dedicated first-class flag: whatsapp.suppress_notifications.
# Read from the raw config dict (always reflects config.yaml);
# fall back to the typed PlatformConfig field if present.
_wa = _raw.get("whatsapp") or {}
_suppress = bool(_wa.get(
"suppress_notifications",
getattr(self.config, "suppress_notifications", False),
))
if not _suppress:
# Legacy fallback: display.platforms.whatsapp.interim_assistant_messages: false
from gateway.display_config import resolve_display_setting
from gateway.config import is_truthy_value
_interim = resolve_display_setting(
_raw, "whatsapp", "interim_assistant_messages"
)
_suppress = not is_truthy_value(_interim, default=True)
if _suppress:
logger.debug(
"[Whatsapp] Suppressed non-reply notice "
"(whatsapp.suppress_notifications): %.80s",
content.replace("\n", " "),
)
return SendResult(success=True, message_id=None)
except Exception:
pass

try:
import aiohttp

Expand Down
36 changes: 36 additions & 0 deletions run_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -1937,13 +1937,49 @@ def _file_mutation_verifier_enabled(self) -> bool:
_cfg = _load_config() or {}
except Exception:
_cfg = {}
# Per-platform suppression: this footer is appended to the assistant
# reply (not a separate send), so it bypasses the adapter notice
# chokepoint. On platforms that drop gateway notices
# (<platform>.suppress_notifications, e.g. WhatsApp shared with human
# contacts) skip the developer-facing verifier footer too. CLI/TUI
# and other platforms keep it.
try:
_plat = (getattr(self, "platform", None) or "").lower().strip()
_plat_cfg = _cfg.get(_plat) if (_plat and isinstance(_cfg, dict)) else None
if isinstance(_plat_cfg, dict) and _plat_cfg.get("suppress_notifications"):
return False
except Exception:
pass
_display = _cfg.get("display") if isinstance(_cfg, dict) else None
if isinstance(_display, dict) and "file_mutation_verifier" in _display:
return bool(_display.get("file_mutation_verifier"))
except Exception:
pass
return True # safe default: verifier on

def _suppress_platform_notifications(self) -> bool:
"""True when the active platform drops gateway notices.

Reads ``<platform>.suppress_notifications`` from config.yaml (e.g.
WhatsApp shared with a human contact). Interrupt / API-error status
strings are assigned to ``final_response`` and so ride the genuine
agent-reply path — they bypass the adapter notice chokepoint, which
only catches separate ``send()`` notices. Gate them on this so they
stay silent on suppressed platforms; CLI/TUI and every other platform
are unaffected. Fail-open (return False) on any error so a config
glitch can never swallow a normal reply.
"""
try:
from hermes_cli.config import load_config as _load_config
_cfg = _load_config() or {}
_plat = (getattr(self, "platform", None) or "").lower().strip()
_plat_cfg = _cfg.get(_plat) if (_plat and isinstance(_cfg, dict)) else None
if isinstance(_plat_cfg, dict) and _plat_cfg.get("suppress_notifications"):
return True
except Exception:
pass
return False

@staticmethod
def _format_file_mutation_failure_footer(failed: Dict[str, Dict[str, Any]]) -> str:
"""Render the per-turn failed-mutation dict as a user-facing footer.
Expand Down