diff --git a/docs/NOTIFICATIONS.md b/docs/NOTIFICATIONS.md index bd0e2d0..837cbec 100644 --- a/docs/NOTIFICATIONS.md +++ b/docs/NOTIFICATIONS.md @@ -43,6 +43,21 @@ copy, including the phone's content key. Each alert shows the agent's name, picture and the start of its message (up to 1,600 characters). Event IDs are stable (`:`), so a retry never produces a second alert. +### Silent replies + +Agents can answer with a silence marker such as `[SILENT]` or `NO_REPLY` when there's nothing to say. A reply +alert follows Hermes' own delivery rules (`gateway/response_filters.py` on the host), so the phone never shows a +marker Hermes itself wouldn't send: + +- **Scheduled tasks and webhooks** use Hermes' loose rule. A reply that is a marker, starts with `[SILENT]`, or has + a marker on its own first or last line sends no alert. +- **Other chats** use Hermes' exact rule: only a reply that is just a marker counts. It stays silent when no + person is waiting for an answer, for example an off-screen note like a widget tap, a Hermes internal notification, + or a group message that wasn't addressed to the agent. When a person's message got only a marker, the alert + carries Hermes' notice instead ("The model returned only a silence marker…"). Hermes versions before that notice + keep every bare marker silent. +- Failed runs always alert. + ## End-to-end encryption With a registered content key, the host seals each alert's title, text and avatar for that phone diff --git a/loopdy_plugin/link_contracts.py b/loopdy_plugin/link_contracts.py index 27c0630..5a38591 100644 --- a/loopdy_plugin/link_contracts.py +++ b/loopdy_plugin/link_contracts.py @@ -112,7 +112,7 @@ def parse_direct_enrollment(payload: dict[str, Any]) -> dict[str, Any]: "body_fat_percentage", "workout", ) -PLUGIN_VERSION = "2.18.0" +PLUGIN_VERSION = "2.18.1" AVAILABLE_WIKI_OPERATIONS = available_wiki_operations() GROUPS_OPERATIONS = frozenset( { diff --git a/loopdy_plugin/managed_notifications.py b/loopdy_plugin/managed_notifications.py index b7e6a75..1ec1fc4 100644 --- a/loopdy_plugin/managed_notifications.py +++ b/loopdy_plugin/managed_notifications.py @@ -12,6 +12,7 @@ fcntl = None import hashlib import base64 +import importlib import json import logging import os @@ -77,6 +78,57 @@ def _identifier(value: Any, pattern: re.Pattern = _ID) -> str: return value +# A reply alert carries only what Hermes itself would deliver (gateway/response_filters.py). +# Scheduled and webhook runs use the loose rule the cron scheduler and webhook adapter use. Any +# other turn stays silent only on an exact marker, and only when no person is waiting for the +# answer; a person who got a bare marker sees the notice Hermes' gateway sends instead. +_AUTONOMOUS_PLATFORMS = frozenset({"cron", "webhook"}) +# The one kind prompt.submit lets a client author: an off-screen send nobody sees (a widget tap, +# or an older bighelp reaction note). Hermes history drops these rows, so for silence they are +# machinery too. +_OFF_SCREEN_DISPLAY_KIND = "hidden" +# gateway/run_turn.py's _UNEXPECTED_SILENCE_REPLY, word for word. +_UNEXPECTED_SILENCE_REPLY = ("⚠️ The model returned only a silence marker for a message that needed " + "a reply. Try again or rephrase.") +_LEGACY_SILENCE_MARKERS = frozenset({"[SILENT]", "SILENT", "NO_REPLY", "NO REPLY"}) + + +def _turn_prompt(history: Any) -> tuple[Any, Any]: + """The current turn's user-row display kind and ``reply_expected`` flag. Hermes appends the + turn's user row, typed at turn start, before the model runs.""" + for message in reversed(history if isinstance(history, list) else ()): + if isinstance(message, dict) and message.get("role") == "user": + metadata = message.get("display_metadata") + return (message.get("display_kind"), + metadata.get("reply_expected") if isinstance(metadata, dict) else None) + return None, None + + +def _delivered_reply(response: Any, *, autonomous: bool, history: Any) -> Any: + """``response`` as Hermes would deliver it: ``""`` when the turn stays silent, Hermes' notice + when a person got a bare marker, else unchanged. Never raises; unsure means unchanged.""" + try: + rules = importlib.import_module("gateway.response_filters") + except ImportError: # Every supported Hermes has it; a bare marker still stays quiet. + text = response.strip().upper() if isinstance(response, str) else "" + return "" if text in _LEGACY_SILENCE_MARKERS or (autonomous and text.startswith("[SILENT]")) else response + try: + if autonomous: + return "" if rules.is_autonomous_silence_response(response) else response + if not rules.is_intentional_silence_response(response): + return response + silence_allowed = getattr(rules, "silence_allowed", None) + if silence_allowed is None: # Before the human-turn notice, Hermes kept every bare marker quiet. + return "" + kind, reply_expected = _turn_prompt(history) + if kind == _OFF_SCREEN_DISPLAY_KIND or silence_allowed(kind, reply_expected): + return "" + return _UNEXPECTED_SILENCE_REPLY + except Exception: + logger.warning("Notification silence check unavailable; the reply alerts unchanged") + return response + + def session_reference(profile: str, session_id: str) -> str: return b64url_encode(hashlib.sha256(f"{profile}\0{session_id}".encode()).digest()) @@ -740,8 +792,15 @@ def _observe(self, hook: str, *, profile: str, **payload: Any): turn = payload.get("turn_id") if hook == "post_llm_call" and isinstance(turn, str) and _ID.fullmatch(turn): coordinate = (profile, session_id, turn) + scheduled = payload.get("platform") == "cron" or _CRON_SESSION.fullmatch(session_id) is not None try: - response_text = self._rich_text(payload.get("assistant_response")) + # A turn Hermes keeps silent keeps no reply here either, so neither this alert + # nor the on_session_end fallback pushes a marker. Failures still alert. The + # check reads the raw reply: _rich_text collapses the lines the loose rule reads. + reply = _delivered_reply( + payload.get("assistant_response"), history=payload.get("conversation_history"), + autonomous=scheduled or payload.get("platform") in _AUTONOMOUS_PLATFORMS) + response_text = self._rich_text(reply) if reply else "" except ManagedNotificationError: response_text = "" if response_text: @@ -754,7 +813,6 @@ def _observe(self, hook: str, *, profile: str, **payload: Any): # reply is saved. on_session_end comes only after post-turn work (external memory # sync, reviews) that can take several seconds, so the reply alert goes out now. if response_text and not child_hook: - scheduled = payload.get("platform") == "cron" or _CRON_SESSION.fullmatch(session_id) is not None try: self._queue_event(profile, session_id, turn, "scheduled.completed" if scheduled else "session.completed", diff --git a/plugin.yaml b/plugin.yaml index 75f21dd..4b71585 100644 --- a/plugin.yaml +++ b/plugin.yaml @@ -2,7 +2,7 @@ manifest_version: 1 name: loopdy label: Loopdy kind: platform -version: "2.18.0" +version: "2.18.1" license: Apache-2.0 description: > Native authenticated Hermes workspace controls, media voice, approvals, and diff --git a/tests/test_managed_notifications.py b/tests/test_managed_notifications.py index 2bc4290..e166f06 100644 --- a/tests/test_managed_notifications.py +++ b/tests/test_managed_notifications.py @@ -7,6 +7,9 @@ import unittest import uuid import hashlib +import importlib +import sys +import types from unittest.mock import patch from cryptography.hazmat.primitives.asymmetric import ec from loopdy_plugin.managed_notifications import ManagedNotifications, ManagedNotificationError, host_request_transcript @@ -234,6 +237,90 @@ def test_scheduled_run_alerts_without_a_session_subscription(self): self.service.drain_pending() self.assertIn("scheduled.completed",[e["eventType"] for e in self.events_sent()]) + def test_silent_scheduled_run_sends_no_alert(self): + # Regression: a cron run answering "[SILENT]" skipped Telegram delivery but + # still reached the phone as a push reading "[SILENT]". + self.grant["eventTypes"]=["scheduled.completed","scheduled.failed","session.completed","session.failed"] + grant_id=str(uuid.uuid4()); self.grant["grantId"]=grant_id; self.grant_id=grant_id + self.service.enroll(grant_id,str(uuid.uuid4())); self.calls.clear() + cron="cron_143638f07ae3_20260927_185802" + for turn,reply in (("turn-s","[SILENT]"),("turn-t","[SILENT] No qualifying restock.")): + self.service.observe("post_llm_call",profile="default",session_id=cron,turn_id=turn,assistant_response=reply,platform="cron") + self.service.observe("on_session_end",profile="default",session_id=cron,turn_id=turn,completed=True,platform="cron") + self.service.drain_pending() + self.assertEqual(self.events_sent(),[]) + self.service.observe("post_llm_call",profile="default",session_id=cron,turn_id="turn-r",assistant_response="Restock: ETB in stock at MSRP.",platform="cron") + self.service.observe("on_session_end",profile="default",session_id=cron,turn_id="turn-r",completed=True,platform="cron") + self.service.observe("on_session_end",profile="default",session_id=cron,turn_id="turn-f",failed=True,error="provider unreachable",platform="cron") + self.service.drain_pending() + self.assertEqual([e["eventType"] for e in self.events_sent()],["scheduled.completed","scheduled.failed"]) + + def hermes_rules(self, *, human_turn_notice=True, broken=False): + # Hermes' own predicates; silence_allowed arrived with the human-turn notice, so + # supply it (or leave it out) to cover every supported Hermes the same way. + real=importlib.import_module("gateway.response_filters") + rules=types.ModuleType("gateway.response_filters") + rules.is_intentional_silence_response=real.is_intentional_silence_response + rules.is_autonomous_silence_response=real.is_autonomous_silence_response + if human_turn_notice: + rules.silence_allowed=lambda kind,reply_expected=None: kind=="internal_notification" or reply_expected is False + if broken: + def fail(_response): raise RuntimeError("synthetic") + rules.is_intentional_silence_response=fail + return patch.dict(sys.modules,{"gateway.response_filters":rules}) + + def chat_turn(self, turn, reply, *, prompt=None, platform="desktop"): + history=[{"role":"user","content":"earlier","display_kind":"internal_notification"},{"role":"assistant","content":"ok"}, + dict({"role":"user","content":"now"},**(prompt or {})),{"role":"assistant","content":reply}] + self.service.observe("post_llm_call",profile="default",session_id="desktop-chat",turn_id=turn,assistant_response=reply,conversation_history=history,platform=platform) + self.service.observe("on_session_end",profile="default",session_id="desktop-chat",turn_id=turn,completed=True,platform=platform) + + def alerts(self): + self.service.drain_pending() + sent=[(e["eventType"],e["content"]["text"]) for e in self.events_sent()] + self.calls.clear() + return sent + + def test_bare_marker_answering_a_person_alerts_hermes_notice(self): + # Hermes' gateway never lets a person's message vanish: a bare marker becomes its notice. + # An earlier machinery row must not make this human turn silent. + with self.hermes_rules(): + self.chat_turn("turn-a","[SILENT]") + self.chat_turn("turn-b","no_reply.",prompt={"display_metadata":{"reply_expected":True}}) + notice="⚠️ The model returned only a silence marker for a message that needed a reply. Try again or rephrase." + self.assertEqual(self.alerts(),[("session.completed",notice)]*2) + + def test_turns_nobody_typed_stay_silent(self): + # Off-screen notes (a widget tap), Hermes' internal notifications and + # messages not addressed to the agent may end on a bare marker, stray punctuation and all. + with self.hermes_rules(): + self.chat_turn("turn-a","[SILENT]",prompt={"display_kind":"hidden"}) + self.chat_turn("turn-b","NO_REPLY",prompt={"display_kind":"internal_notification"}) + self.chat_turn("turn-c","*SILENT*",prompt={"display_metadata":{"reply_expected":False}}) + self.assertEqual(self.alerts(),[]) + + def test_prose_mentioning_a_marker_alerts_unchanged(self): + with self.hermes_rules(): + self.chat_turn("turn-a","Reply with [SILENT] when there's nothing new.",prompt={"display_kind":"hidden"}) + self.assertEqual(self.alerts(),[("session.completed","Reply with [SILENT] when there's nothing new.")]) + + def test_webhook_run_uses_the_loose_rule(self): + with self.hermes_rules(): + self.chat_turn("turn-a","[SILENT]\n\nNothing new this tick.",platform="webhook") + self.chat_turn("turn-b","Deploy finished.",platform="webhook") + self.assertEqual(self.alerts(),[("session.completed","Deploy finished.")]) + + def test_older_hermes_keeps_every_bare_marker_quiet(self): + # Before the human-turn notice, Hermes delivered nothing for any bare marker. + with self.hermes_rules(human_turn_notice=False): + self.chat_turn("turn-a","[SILENT]") + self.assertEqual(self.alerts(),[]) + + def test_a_failing_silence_check_alerts_the_reply_unchanged(self): + with self.hermes_rules(broken=True): + self.chat_turn("turn-a","[SILENT]") + self.assertEqual(self.alerts(),[("session.completed","[SILENT]")]) + def test_subagent_completion_alerts_for_an_unopened_parent_session(self): self.grant["eventTypes"]=["session.completed","session.failed","subagent.completed","subagent.failed"] grant_id=str(uuid.uuid4()); self.grant["grantId"]=grant_id; self.grant_id=grant_id