diff --git a/integrations/hermes/plugin/ctx_discord_policy/README.md b/integrations/hermes/plugin/ctx_discord_policy/README.md index d4dddfc53..e6b98181c 100644 --- a/integrations/hermes/plugin/ctx_discord_policy/README.md +++ b/integrations/hermes/plugin/ctx_discord_policy/README.md @@ -24,9 +24,9 @@ hermes ctx-discord-policy routing set on the host: run a configuration on the host. Nothing in Discord can extend it: no role, no server admin, no guidance text. - **Members can talk to the bot.** They mention it, reply to it, call it by one of its names ("Nova, …", "hey Nova"), or react to a message with the server's wake emoji; in a conversation channel the bot reads along - and joins in when it has something to add. Their turns run without tools, except the member tools you allow - for that server: the current channel's recent messages, linked messages, skills you name, entries of your - knowledge sources you name. + and joins in when it has something to add, and posts nothing when it has not. Their turns run without tools, + except the member tools you allow for that server: the current channel's recent messages, linked messages, + skills you name, entries of your knowledge sources you name. - **Links and channels in a message.** When a message links Discord messages or mentions channels, the bot sees that content as quoted data, read with the rights of the person who wrote the message. In members' turns only what everyone who sees the answer may read. diff --git a/integrations/hermes/plugin/ctx_discord_policy/__init__.py b/integrations/hermes/plugin/ctx_discord_policy/__init__.py index 4d580edc3..ec7b89d33 100644 --- a/integrations/hermes/plugin/ctx_discord_policy/__init__.py +++ b/integrations/hermes/plugin/ctx_discord_policy/__init__.py @@ -21,7 +21,7 @@ from pathlib import Path from typing import Any, Optional -PLUGIN_VERSION = "3.0.1" +PLUGIN_VERSION = "3.0.2" RUNTIME_API = 1 ANCHOR_NAME = "ctx_discord_policy" diff --git a/integrations/hermes/plugin/ctx_discord_policy/dsp/__init__.py b/integrations/hermes/plugin/ctx_discord_policy/dsp/__init__.py index c158d2166..d95049664 100644 --- a/integrations/hermes/plugin/ctx_discord_policy/dsp/__init__.py +++ b/integrations/hermes/plugin/ctx_discord_policy/dsp/__init__.py @@ -1,4 +1,4 @@ """Policy runtime of the ``ctx_discord_policy`` Hermes plugin.""" -__version__ = "3.0.1" +__version__ = "3.0.2" RUNTIME_API = 1 diff --git a/integrations/hermes/plugin/ctx_discord_policy/dsp/adapt/interventions.py b/integrations/hermes/plugin/ctx_discord_policy/dsp/adapt/interventions.py index b460db475..eb332bfe3 100644 --- a/integrations/hermes/plugin/ctx_discord_policy/dsp/adapt/interventions.py +++ b/integrations/hermes/plugin/ctx_discord_policy/dsp/adapt/interventions.py @@ -173,6 +173,25 @@ def _in_guild(event: Any) -> bool: return bool(getattr(getattr(event, "source", None), "guild_id", None)) +def _expect_no_reply_when_ambient(adapter: Any, event: Any) -> None: + """Tell Hermes that a turn in ambient mode expects no reply (``MessageEvent.reply_expected = False``). + + In ambient mode the bot reads along and the prompt lets the model answer ``NO_REPLY`` + (``prompts.assemble.SILENCE_RULE``). Hermes keeps such an answer silent only for an event that says no + reply is expected; its Discord adapter leaves the field unset, and Hermes then posts its notice ("The + model returned only a silence marker for a message that needed a reply") into the channel instead. Only + an unset field is written, only on a Hermes whose event has the field, and only for a route in ambient + mode: an addressed message that ends in a bare marker keeps Hermes' notice.""" + if getattr(event, "reply_expected", True) is not None: + return # no such field on this Hermes, or already decided + binding = RUNTIME.bots.for_adapter(adapter) + if binding is None: + return + candidate = authority.candidate_for_event(event, bot_id=binding.bot_id) + if candidate is not None and candidate.mode == AMBIENT: + event.reply_expected = False + + def _make_event_gate(original: Any) -> Any: async def policy_event(self: Any, event: Any, *args: Any, **kwargs: Any) -> Any: try: @@ -186,6 +205,11 @@ async def policy_event(self: Any, event: Any, *args: Any, **kwargs: Any) -> Any: "it: %s", getattr(source, "message_id", None) or getattr(event, "message_id", None), getattr(source, "chat_id", None), refusal) return None + try: + _expect_no_reply_when_ambient(self, event) + except Exception: + # Comfort only: without the mark Hermes answers a bare NO_REPLY with its notice, as before. + logger.exception("ctx_discord_policy: could not mark an ambient turn as expecting no reply") return await original(self, event, *args, **kwargs) return policy_event diff --git a/integrations/hermes/plugin/ctx_discord_policy/dsp/web/members.py b/integrations/hermes/plugin/ctx_discord_policy/dsp/web/members.py index 09439612e..b33e601f8 100644 --- a/integrations/hermes/plugin/ctx_discord_policy/dsp/web/members.py +++ b/integrations/hermes/plugin/ctx_discord_policy/dsp/web/members.py @@ -70,7 +70,7 @@ def _store(key: tuple, value: Any) -> None: def _rest(path: str, token: str) -> Any: request = urllib.request.Request(API + path, headers={"Authorization": f"Bot {token}", - "User-Agent": "DiscordBot (hermes-plugin, 3.0.1)"}) + "User-Agent": "DiscordBot (hermes-plugin, 3.0.2)"}) with urllib.request.urlopen(request, timeout=REST_TIMEOUT) as response: # noqa: S310 - fixed https host return json.loads(response.read().decode("utf-8")) diff --git a/integrations/hermes/plugin/ctx_discord_policy/plugin.yaml b/integrations/hermes/plugin/ctx_discord_policy/plugin.yaml index efd93258c..7719d8612 100644 --- a/integrations/hermes/plugin/ctx_discord_policy/plugin.yaml +++ b/integrations/hermes/plugin/ctx_discord_policy/plugin.yaml @@ -1,6 +1,6 @@ manifest_version: 2 name: ctx_discord_policy -version: 3.0.1 +version: 3.0.2 description: "Let your Hermes bot talk in your Discord servers while its tools stay yours: members can call the bot by name, mention it, reply to it or wake it with a reaction, and chat with it in channels you open for that, but only the operators you list in the Hermes configuration get tool calls, and no role, server admin or text in Discord can change that. Each server is set up from inside Discord with /policy: the channels where the bot joins in or keeps quiet, its name and reply language, a guidance text for the server, the Hermes profile and models it runs on, the progress display, and a thread where your own tool work goes. The form of every place where the plugin hooks into Hermes is checked when Hermes loads it and when the Discord bot connects; while it runs, protection fails closed (members get no access) and comfort features fall back to Hermes' own behaviour, shown in /policy and in hermes ctx-discord-policy status. Needs the Discord platform and plugins running in the gateway process (not plugins.isolation: host). Works without ctx." author: Jan-Stefan Janetzky license: MPL-2.0 diff --git a/integrations/hermes/plugin/ctx_discord_policy/tests/contract/test_ambient_silence.py b/integrations/hermes/plugin/ctx_discord_policy/tests/contract/test_ambient_silence.py new file mode 100644 index 000000000..6dc2553a0 --- /dev/null +++ b/integrations/hermes/plugin/ctx_discord_policy/tests/contract/test_ambient_silence.py @@ -0,0 +1,66 @@ +"""A turn in ambient mode may end in silence: the event Hermes gets says that no reply is expected. + +Real: Hermes' Discord admission and handler (A5/A6) and the event Hermes builds from the message; the plugin's +event gate on the adapter's ``handle_message`` (A10) marks it. Where Hermes has the rule, its own +``gateway.response_filters.silence_allowed`` judges the marked event. Not covered here: a model's turn and the +delivery of its answer. +""" + +from __future__ import annotations + +import dataclasses + +import pytest +from contract.policy_world import BOT, CHANNEL, GUILD, MEMBER, OPERATOR, World + + +@pytest.fixture +def gated(hermes, tmp_path, monkeypatch): + """Events reach a recorder standing for Hermes' pipeline beneath the plugin's ``handle_message`` gate.""" + w = World(hermes, tmp_path, monkeypatch, capture=False) + try: + yield w + finally: + w.close() + + +def _has_field(event) -> bool: + return "reply_expected" in {f.name for f in dataclasses.fields(event)} + + +def _ambient(w) -> None: + w.mod("store.ops").update_fields(w.binding().store, BOT, GUILD, + {"conversation.ambient_channels": [CHANNEL]}, by="test") + + +async def test_an_ambient_turn_expects_no_reply(gated): + _ambient(gated) + for author, mid in ((MEMBER, 8901), (OPERATOR, 8902)): + out = await gated.deliver(gated.message(author, mid, "anyone seen the new build?", mention=None)) + event = out["event"] + assert event is not None and event.raw_message._dsp_route.mode == "ambient" + if not _has_field(event): + pytest.skip("this Hermes has no MessageEvent.reply_expected") + assert event.reply_expected is False, author + + +async def test_an_addressed_message_keeps_hermes_rule(gated): + _ambient(gated) # addressed in an ambient channel: direct, not ambient + out = await gated.deliver(gated.message(MEMBER, 8903, "are you there?")) + event = out["event"] + assert event is not None and event.raw_message._dsp_route.mode == "direct" + assert getattr(event, "reply_expected", None) is None + + +async def test_hermes_keeps_a_bare_marker_of_an_ambient_turn_silent(gated): + filters = pytest.importorskip("gateway.response_filters") + silence_allowed = getattr(filters, "silence_allowed", None) + if silence_allowed is None: + pytest.skip("this Hermes has no silence_allowed") + _ambient(gated) + ambient = (await gated.deliver(gated.message(MEMBER, 8904, "lunch?", mention=None)))["event"] + direct = (await gated.deliver(gated.message(MEMBER, 8905, "lunch?")))["event"] + if not _has_field(ambient): + pytest.skip("this Hermes has no MessageEvent.reply_expected") + assert silence_allowed(None, ambient.reply_expected) is True + assert silence_allowed(None, direct.reply_expected) is False diff --git a/integrations/hermes/plugin/ctx_discord_policy/tests/contract/test_dashboard_api.py b/integrations/hermes/plugin/ctx_discord_policy/tests/contract/test_dashboard_api.py index b30439c97..edfb6365e 100644 --- a/integrations/hermes/plugin/ctx_discord_policy/tests/contract/test_dashboard_api.py +++ b/integrations/hermes/plugin/ctx_discord_policy/tests/contract/test_dashboard_api.py @@ -133,7 +133,7 @@ def test_every_route_needs_a_hermes_sign_in(dash, method, path): def test_meta_answers_behind_the_gate_and_names_the_process(dash, bound): body = dash.client.get(f"{BASE}/meta").json() - assert body["plugin_version"] == "3.0.1" and body["process"] == "dashboard" + assert body["plugin_version"] == "3.0.2" and body["process"] == "dashboard" dash.app.state.gateway_runner = object() try: assert dash.client.get(f"{BASE}/meta").json()["process"] == "gateway" diff --git a/integrations/hermes/plugin/ctx_discord_policy/tests/contract/test_two_homes.py b/integrations/hermes/plugin/ctx_discord_policy/tests/contract/test_two_homes.py index 1cd7b1161..fbfc61616 100644 --- a/integrations/hermes/plugin/ctx_discord_policy/tests/contract/test_two_homes.py +++ b/integrations/hermes/plugin/ctx_discord_policy/tests/contract/test_two_homes.py @@ -99,7 +99,7 @@ def test_second_plugin_version_in_process_registers_nothing(homes, tmp_path, cap assert not runtime.armed.is_armed(hermes_home_key(stale)) # ... but nothing registered assert "restart" in caplog.text.lower() assert runtime.status.snapshot()["refused"][-1]["version"] == "3.9.9" - assert sys.modules[ANCHOR].__version__ == "3.0.1" + assert sys.modules[ANCHOR].__version__ == "3.0.2" def test_armed_means_the_hook_is_in_the_live_registry(homes): diff --git a/integrations/hermes/plugin/ctx_discord_policy/tests/unit/test_anchor.py b/integrations/hermes/plugin/ctx_discord_policy/tests/unit/test_anchor.py index fce335ab9..b07404bf0 100644 --- a/integrations/hermes/plugin/ctx_discord_policy/tests/unit/test_anchor.py +++ b/integrations/hermes/plugin/ctx_discord_policy/tests/unit/test_anchor.py @@ -98,7 +98,7 @@ def test_status_file_is_private_and_reports_changes(anchor, monkeypatch, caplog) assert not path.exists() # register() never writes it (CLI processes load plugins too) anchor.bootstrap.write_status(home) data = json.loads(path.read_text(encoding="utf-8")) - assert data["plugin_version"] == "3.0.1" + assert data["plugin_version"] == "3.0.2" assert data["interventions"]["A8[default]"]["outcome"] == "armed" if os.name == "posix": assert stat.S_IMODE(path.stat().st_mode) == 0o600 diff --git a/integrations/hermes/plugin/ctx_discord_policy/tests/unit/test_dashboard_routes.py b/integrations/hermes/plugin/ctx_discord_policy/tests/unit/test_dashboard_routes.py index 3c1cac916..c6c060079 100644 --- a/integrations/hermes/plugin/ctx_discord_policy/tests/unit/test_dashboard_routes.py +++ b/integrations/hermes/plugin/ctx_discord_policy/tests/unit/test_dashboard_routes.py @@ -127,7 +127,7 @@ def test_host_actor_comes_from_the_guard(web, anchor): def test_meta_names_process_and_version(web): body = web.call("GET", "/meta", process="gateway").body - assert body["plugin_version"] == "3.0.1" and body["api"] == 1 and body["process"] == "gateway" + assert body["plugin_version"] == "3.0.2" and body["api"] == 1 and body["process"] == "gateway" assert body["features"]["guidance_ops"] is callable(getattr(web.ops, "set_guidance", None))