Skip to content

The agent that grows with you

feat(gateway): allow intentional silence per room

Nico Suarez33cf20374d75
diff --git a/cli-config.yaml.example b/cli-config.yaml.example
index 9386b5a0437..5bdff09394e 100644
--- a/cli-config.yaml.example
+++ b/cli-config.yaml.example
@@ -1505,6 +1505,13 @@ platform_toolsets:
# priority:
# - my_plugin_command
# - my-important-skill
+# matrix:
+# channel_overrides:
+# "!exampleTeamRoom:example.org":
+# # Successful explicit NO_REPLY/[SILENT] finals stay silent, even when addressed.
+# # Omitted/null/false keeps the current reply policy; failures remain visible.
+# # Restart the gateway after changing room overrides.
+# allow_silence: true
# slack:
# extra:
# # Render live tool calls as Slack-native plan/task cards. This explicit
diff --git a/gateway/config.py b/gateway/config.py
index 8f97b5bd260..3e9634d1f3b 100644
--- a/gateway/config.py
+++ b/gateway/config.py
@@ -377,10 +377,11 @@ def persist_home_channel(home: HomeChannel, *, enabled_if_new: bool = False) ->
@dataclass
class ChannelOverride:
- """Per-channel model/provider/system_prompt override (``platforms.<name>.channel_overrides[channel_id]``)."""
+ """Per-channel reply policy/model/provider/system_prompt override (``platforms.<name>.channel_overrides[channel_id]``)."""
model: Optional[str] = None
provider: Optional[str] = None
system_prompt: Optional[str] = None
+ allow_silence: Optional[bool] = None
def to_dict(self) -> dict[str, Any]:
return {k: v for k, v in asdict(self).items() if v is not None}
diff --git a/gateway/response_filters.py b/gateway/response_filters.py
index 27428148843..ff17a9c8cee 100644
--- a/gateway/response_filters.py
+++ b/gateway/response_filters.py
@@ -223,9 +223,20 @@ def is_machinery_display_kind(display_kind: Any) -> bool:
return display_kind in MACHINERY_DISPLAY_KINDS
-def silence_allowed(display_kind: Any, reply_expected: Optional[bool] = None) -> bool:
- """Whether a successful bare silence marker may remain silent for this turn."""
- return is_machinery_display_kind(display_kind) or reply_expected is False
+def silence_allowed(
+ display_kind: Any, reply_expected: Optional[bool] = None, *,
+ allow_silence: Optional[bool] = None, agent_result: Optional[dict] = None,
+) -> bool:
+ """Keep existing exemptions; room opt-in additionally requires a healthy completed result.
+
+ Marker recognition stays with the caller. Extra health restrictions apply only to the new
+ room permission, preserving the established internal/unaddressed semantics.
+ """
+ if is_machinery_display_kind(display_kind) or reply_expected is False:
+ return True
+ return (allow_silence is True and isinstance(agent_result, dict)
+ and not any(agent_result.get(k) for k in ("failed", "partial", "interrupted", "error"))
+ and agent_result.get("completed") is not False)
def reply_expected_metadata(reply_expected: Optional[bool]) -> dict:
diff --git a/gateway/run_config_loaders.py b/gateway/run_config_loaders.py
index 512216d8fe3..9a3995e7640 100644
--- a/gateway/run_config_loaders.py
+++ b/gateway/run_config_loaders.py
@@ -108,6 +108,28 @@ class GatewayConfigLoadersMixin:
return None
return _get_channel_override(config, platform, chat_id, thread_id=thread_id, parent_id=parent_id)
+ def _silence_allowed_for_source(self, source, display_kind, reply_expected, agent_result) -> bool:
+ """Evaluate existing exemptions before consulting the optional room permission."""
+ from gateway.response_filters import silence_allowed
+ return silence_allowed(display_kind, reply_expected) or silence_allowed(
+ display_kind, reply_expected, allow_silence=self._room_allow_silence(source),
+ agent_result=agent_result)
+
+ def _room_allow_silence(self, source: SessionSource) -> Optional[bool]:
+ """Resolve the room policy in the serving profile, never the launch snapshot for a route."""
+ from gateway.config import GatewayConfig
+ from gateway.run import _get_channel_override, _load_gateway_config
+ from gateway.session_identity import identity_of
+ config = getattr(self, "config", None)
+ if (identity_of(source) is not None or source.profile
+ or getattr(config, "multiplex_profiles", False) or config is None):
+ home = self._resolve_profile_home_for_source(source)
+ config = GatewayConfig.from_dict(_load_gateway_config(home / "config.yaml"))
+ override = _get_channel_override(
+ config, source.platform, source.chat_id,
+ thread_id=source.thread_id, parent_id=source.parent_chat_id)
+ return override.allow_silence if override is not None else None
+
def _resolve_model_for_channel(
self, platform: Platform, chat_id: str, *, user_config: Optional[dict] = None,
thread_id: Optional[str] = None, parent_id: Optional[str] = None,
diff --git a/gateway/run_startup.py b/gateway/run_startup.py
index f0969d610bf..90983102ed4 100644
--- a/gateway/run_startup.py
+++ b/gateway/run_startup.py
@@ -796,8 +796,9 @@ class GatewayStartupMixin:
started = started_at.timestamp() # aware UTC marker; a pre-upgrade naive one reads as local
if started < cutoff:
continue
+ decision = await self.async_session_store.get_session_metadata(key, "room_silence_decision", {})
text = self._crash_left_reply(await self.async_session_store.load_transcript(session_id),
- started, origin)
+ started, origin, silence_decision=decision, active_token=token)
if text is None or (text and not ledger_on):
continue # no final reply to deliver: the turn resumes
if text:
@@ -810,7 +811,9 @@ class GatewayStartupMixin:
ledgered += 1
return ledgered
- def _crash_left_reply(self, history: list, started: float, origin) -> Optional[str]:
+ def _crash_left_reply(
+ self, history: list, started: float, origin, *, silence_decision=None, active_token=None,
+ ) -> Optional[str]:
"""What a crash-left turn owes, judged as live delivery would have: ``None`` when it never
persisted a final reply after *started*; ``""`` when nothing would have been presented (a
silence marker on a machinery turn or on a turn the adapter reported as not addressed to the
@@ -841,8 +844,13 @@ class GatewayStartupMixin:
if diagnostic_turn_muted(prompt.get("display_metadata"), origin.platform):
return ""
if is_intentional_silence_response(last["content"]):
+ decision = silence_decision or {}
+ proven_silent = (active_token is not None and decision.get("token") == active_token
+ and decision.get("timestamp") == last.get("timestamp")
+ and decision.get("silent") is True)
silent_ok = silence_allowed(
- prompt.get("display_kind"), (prompt.get("display_metadata") or {}).get("reply_expected"))
+ prompt.get("display_kind"), (prompt.get("display_metadata") or {}).get("reply_expected"),
+ allow_silence=proven_silent, agent_result={})
return "" if silent_ok else _unexpected_silence_reply()
reply = strip_trailing_silence_marker(last["content"])
return _strip_media_directives(_sanitize_gateway_final_response(origin.platform, reply)).strip() or None
diff --git a/gateway/run_turn.py b/gateway/run_turn.py
index 82f10cbc1ed..21e69b4248a 100644
--- a/gateway/run_turn.py
+++ b/gateway/run_turn.py
@@ -27,7 +27,7 @@ from gateway.platforms.base import BasePlatformAdapter, ProcessingOutcome
from gateway.platforms.event import MessageEvent
from gateway.response_filters import (
display_kind_for_event, display_metadata_for_event, is_machinery_display_kind, persisted_user_metadata_for_event,
- reply_expected_metadata, silence_allowed,
+ reply_expected_metadata,
)
from gateway.warning_notifications import diagnostic_metadata, diagnostic_turn_muted, diagnostic_wake_muted
from gateway.session import (
@@ -188,17 +188,6 @@ class GatewayTurnMixin(GatewayTurnPrepareMixin, GatewayTurnHygieneMixin, Gateway
return adapter._post_delivery_callbacks.pop(key, None)
return None
- @staticmethod
- def _is_intentional_silence(agent_result, response) -> bool:
- try:
- from gateway.response_filters import is_intentional_silence_agent_result
- return is_intentional_silence_agent_result(agent_result, response)
- except Exception:
- return False
-
-
-
-
async def _hmwa_stop_typing_for_turn(self, event, source):
"""Stop the typing indicator (never raises). Slack AI status is scoped to a thread/
workspace, so preserve the routing metadata used by the response delivery path."""
@@ -330,6 +319,9 @@ class GatewayTurnMixin(GatewayTurnPrepareMixin, GatewayTurnHygieneMixin, Gateway
hidden_reasoning_incomplete=hidden_reasoning_incomplete,
is_context_overflow_failure=is_context_overflow_failure,
)
+ await self._record_room_silence_decision(
+ session_key, agent_result, _intentional_silence,
+ display_kind=prepared.persist_user_display_kind, reply_expected=event.reply_expected)
return await self._deliver_turn_response_then_limit_offer(
event, source, session_entry, session_key, run_generation,
agent_result, agent_messages, response, _footer_line, _intentional_silence,
@@ -1778,8 +1770,11 @@ class GatewayTurnMixin(GatewayTurnPrepareMixin, GatewayTurnHygieneMixin, Gateway
_sc, first_response, previewed=bool(_delivery_result.get("response_previewed")),
)
# Same silence predicate as the normal path, else this branch leaks the literal marker.
+ _silent = False
if self._is_intentional_silence(_delivery_result, first_response):
- if silence_allowed(turn_ctx.persist_user_display_kind, turn_ctx.reply_expected):
+ _silent = self._silence_allowed_for_source(
+ turn_ctx.source, turn_ctx.persist_user_display_kind, turn_ctx.reply_expected, _delivery_result)
+ if _silent:
logger.info(
"Queued follow-up for session %s: suppressing intentional silence marker before continuing.",
session_key or "?",
@@ -1792,6 +1787,9 @@ class GatewayTurnMixin(GatewayTurnPrepareMixin, GatewayTurnHygieneMixin, Gateway
)
first_response = _unexpected_silence_reply()
_already_streamed = False
+ await self._record_room_silence_decision(
+ session_key, _delivery_result, _silent,
+ display_kind=turn_ctx.persist_user_display_kind, reply_expected=turn_ctx.reply_expected)
# Failed turns deliver their text but never their attachments (completed-turn parity).
_deliver_media = not _delivery_result.get("failed")
if first_response:
@@ -1997,6 +1995,7 @@ class GatewayTurnMixin(GatewayTurnPrepareMixin, GatewayTurnHygieneMixin, Gateway
"queued_terminal_inbound_id": next_inbound_id,
"queued_terminal_display_kind": next_display_kind,
"queued_terminal_reply_expected": next_reply_expected,
+ "queued_terminal_source": next_source,
"queued_terminal_notification_category": (
(pending_event.metadata or {}).get("notification_category", "result")
if pending_event is not None and pending_event.internal else "result"),
diff --git a/gateway/run_turn_persistence.py b/gateway/run_turn_persistence.py
index 81dafa69034..2adc2d9e154 100644
--- a/gateway/run_turn_persistence.py
+++ b/gateway/run_turn_persistence.py
@@ -55,6 +55,44 @@ def _acp_launch(runner, source) -> bool:
class GatewayTurnPersistenceMixin:
+ @staticmethod
+ def _is_intentional_silence(agent_result, response) -> bool:
+ try:
+ from gateway.response_filters import is_intentional_silence_agent_result
+ return is_intentional_silence_agent_result(agent_result, response)
+ except Exception:
+ return False
+
+ async def _record_room_silence_decision(
+ self, session_key, agent_result, silent, *, display_kind=None, reply_expected=None,
+ ):
+ """Bind recovery permission to this exact persisted final and active-turn token.
+
+ A raw persisted marker is not proof that a partial/interrupted turn completed. A crash
+ before this receipt is durable keeps the human safeguard; transcript bytes stay intact.
+ """
+ from gateway.response_filters import is_intentional_silence_response, silence_allowed
+ kind = agent_result.get("queued_terminal_display_kind", display_kind)
+ expected = agent_result.get("queued_terminal_reply_expected", reply_expected)
+ if (not silent or not session_key or silence_allowed(kind, expected)
+ or not is_intentional_silence_response(agent_result.get("final_response"))):
+ return
+ store = self.async_session_store
+ entry = await store.lookup_by_session_key(session_key)
+ token = entry.active_turn_token if entry is not None else None
+ if not isinstance(token, str):
+ return
+ history = await store.load_transcript(entry.session_id)
+ # The agent may have saved its final before gateway session metadata was appended.
+ # Match recovery's visible tail rather than the literal last bookkeeping row.
+ last = next((m for m in reversed(history) if m.get("role") not in ("session_meta", "system")), {})
+ if (last.get("role") != "assistant" or last.get("timestamp") is None
+ or last.get("content") != agent_result.get("final_response")):
+ return
+ await store.set_session_metadata(session_key, "room_silence_decision", {
+ "token": token, "timestamp": last.get("timestamp"), "silent": bool(silent),
+ })
+
async def _hmwa_shape_agent_response(
self, agent_result, source, history, session_entry, session_key,
_quick_key, run_generation, _run_start_session_id, _platform_name, _msg_start_time,
@@ -78,13 +116,14 @@ class GatewayTurnPersistenceMixin:
# A queued (/queue) chain's TERMINAL turn owns the silence verdict, not the event that
# opened the chain: an internal follow-up, or a message not addressed to the bot, may go
# silent; any other human one must not.
- from gateway.response_filters import (
- is_machinery_display_kind, silence_allowed, strip_trailing_silence_marker,
- )
+ from gateway.response_filters import is_machinery_display_kind, strip_trailing_silence_marker
from gateway.run_turn import _unexpected_silence_reply
_silence_kind = agent_result.get("queued_terminal_display_kind", persist_user_display_kind)
_silence_reply_expected = agent_result.get("queued_terminal_reply_expected", reply_expected)
- if _intentional_silence and not silence_allowed(_silence_kind, _silence_reply_expected):
+ _silence_source = agent_result.get("queued_terminal_source", source)
+ if _intentional_silence and not self._silence_allowed_for_source(
+ _silence_source, _silence_kind, _silence_reply_expected, agent_result,
+ ):
logger.warning(
"silence marker rejected on a user turn: platform=%s chat=%s",
_platform_name, source.chat_id or "unknown",
@@ -93,7 +132,7 @@ class GatewayTurnPersistenceMixin:
response = _unexpected_silence_reply()
elif _intentional_silence and not is_machinery_display_kind(_silence_kind):
logger.debug(
- "silence marker suppressed on an unaddressed turn: platform=%s chat=%s",
+ "silence marker suppressed on an unaddressed or opted-in turn: platform=%s chat=%s",
_platform_name, source.chat_id or "unknown",
)
@@ -594,7 +633,7 @@ class GatewayTurnPersistenceMixin:
if response and adapter and not agent_result.get("media_already_delivered"):
await self._deliver_media_from_response(response, event, adapter)
# Streaming delivered the body, but the footer was held back (`not already_sent` gate).
- if _footer_line and adapter:
+ if _footer_line and adapter and not _intentional_silence:
try:
await adapter.send(source.chat_id, _footer_line, metadata=self._event_thread_metadata(event, source))
except Exception as _e:
diff --git a/tests/gateway/test_gateway_silence_tokens.py b/tests/gateway/test_gateway_silence_tokens.py
index 6238f2f5fcd..690e0ffec3d 100644
--- a/tests/gateway/test_gateway_silence_tokens.py
+++ b/tests/gateway/test_gateway_silence_tokens.py
@@ -240,6 +240,7 @@ async def test_queued_terminal_turn_owns_the_silence_verdict(monkeypatch, tmp_pa
assert followup["persist_user_display_metadata"]["reply_expected"] is True
assert merged["queued_terminal_display_kind"] == "internal_notification"
assert merged["queued_terminal_reply_expected"] is True
+ assert merged["queued_terminal_source"] is pending_event.source
def _result(terminal_kind, terminal_reply_expected=None):
return {
diff --git a/tests/gateway/test_room_allow_silence.py b/tests/gateway/test_room_allow_silence.py
new file mode 100644
index 00000000000..194aacb8692
--- /dev/null
+++ b/tests/gateway/test_room_allow_silence.py
@@ -0,0 +1,233 @@
+"""Room opt-in reaches live, queued and crash-left delivery without crossing profiles."""
+
+import json
+import time
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+import pytest
+
+from gateway.config import GatewayConfig
+from gateway.session_identity import RoutingIdentity
+from tests.gateway.test_gateway_silence_tokens import _event, _runner, _source
+from tests.gateway.test_active_turn_recovery import _close_store_db, _db_runner, _entry_for
+
+
+def _configure(runner, tmp_path, *, setting=True, other_profile=False):
+ home = tmp_path / "served"
+ home.mkdir()
+ room = {} if setting is None else {"allow_silence": None if setting == "null" else setting}
+ raw = {"platforms": {"telegram": {"channel_overrides": {
+ "-1001": room, "parent": {"allow_silence": True},
+ }}}}
+ if setting in ("thread", "parent"):
+ del raw["platforms"]["telegram"]["channel_overrides"]["-1001"]
+ raw["platforms"]["telegram"]["channel_overrides"][setting] = {"allow_silence": True}
+ (home / "config.yaml").write_text(json.dumps(raw), encoding="utf-8")
+ loaded = GatewayConfig.from_dict(raw)
+ roundtrip = loaded.to_dict()["platforms"]["telegram"]["channel_overrides"]
+ expected = {} if setting == "null" else room
+ if setting not in ("thread", "parent"):
+ assert roundtrip["-1001"] == expected
+ # The launch snapshot deliberately disagrees with the served profile.
+ runner.config = GatewayConfig.from_dict({"platforms": {"telegram": {
+ "channel_overrides": {"-1001": {"allow_silence": bool(other_profile) or not bool(setting)}}}}})
+ runner.config.multiplex_profiles = True
+ source = _source()
+ source.parent_chat_id = "parent"
+ source.thread_id = "thread"
+ if other_profile:
+ home = tmp_path / "other"
+ home.mkdir()
+ (home / "config.yaml").write_text("{}\n", encoding="utf-8")
+ source._identity = RoutingIdentity("default", "served", tmp_path, home)
+ return source
+
+
[email protected]("lane", ["normal", "queued", "recovery"])
[email protected]("setting,other_profile,reply_expected,internal,silent", [
+ (True, False, True, False, True),
+ (True, False, None, False, True),
+ (False, False, True, False, False),
+ (None, False, None, False, False),
+ ("null", False, True, False, False),
+ ("thread", False, True, False, True),
+ ("parent", False, True, False, True),
+ (True, True, True, False, False),
+ (False, False, False, False, True),
+ (False, False, True, True, True),
+])
+async def test_room_config_controls_delivery(monkeypatch, tmp_path, lane, setting,
+ other_profile, reply_expected, internal, silent):
+ runner = _runner(monkeypatch, tmp_path)
+ source = _configure(runner, tmp_path, setting=setting, other_profile=other_profile)
+ event = _event(internal=internal, reply_expected=reply_expected)
+ event.source = source
+ result = {"final_response": "NO_REPLY", "failed": False, "api_calls": 1,
+ "messages": [{"role": "user", "content": "question",
+ "display_kind": "internal_notification" if internal else None,
+ "display_metadata": {"reply_expected": reply_expected}},
+ {"role": "assistant", "content": "NO_REPLY"}]}
+ if lane == "normal":
+ adapter = SimpleNamespace(send=AsyncMock())
+ runner._delivery_adapter_for = lambda _: adapter
+ if setting is True and reply_expected is None:
+ result["already_sent"] = True
+ runner._run_agent = AsyncMock(return_value=result)
+ # Even a streaming result must not create a usage-only final.
+ runner._hmwa_runtime_footer_line = lambda *_: "usage footer"
+ response = await runner._handle_message_with_agent(event, source, "lane", 1)
+ assert bool(response) is not silent
+ assert all(call.args[1] != "usage footer" for call in adapter.send.await_args_list)
+ rows = [c.args[1] for c in runner.session_store.append_to_transcript.call_args_list]
+ assert any(r.get("content") == "NO_REPLY" for r in rows)
+ elif lane == "queued":
+ runner._deliver_queued_first_response = AsyncMock(return_value=True)
+ ctx = SimpleNamespace(session_key="lane", source=source, stream_consumer_holder=[None],
+ mute_notification_reply=False, persist_user_display_kind=(
+ "internal_notification" if internal else None),
+ reply_expected=reply_expected, _status_thread_metadata=None,
+ event_message_id=None, inbound_message_id="42", run_generation=1)
+ await runner._run_agent_deliver_first_response(ctx, None, result, result, None)
+ assert runner._deliver_queued_first_response.called is not silent
+ else:
+ from gateway.delivery_ledger import sweep_recoverable
+ _, store = _db_runner(tmp_path)
+ runner.session_store = store
+ result["agent_persisted"] = False
+ runner._run_agent = AsyncMock(return_value=result)
+ try:
+ # Finish the real normal turn, then crash before the adapter sends or clears its token.
+ await runner._handle_message_with_agent(event, source, store._generate_session_key(source), 1)
+ # Re-open the routing index and DB: the verdict must survive a process restart.
+ _close_store_db(store)
+ recovered, store = _db_runner(tmp_path)
+ assert await recovered._recover_unclean_sessions() == (0, 0 if silent else 1)
+ assert bool(sweep_recoverable(deliverable_platforms={"telegram"})) is not silent
+ assert _entry_for(store, source).active_turn_token is None
+ finally:
+ _close_store_db(store)
+
+
[email protected]("lane", ["normal", "queued", "recovery"])
[email protected]("changes", [
+ {"failed": True}, {"partial": True}, {"interrupted": True},
+ {"completed": False}, {"error": "provider error"}, {"final_response": ""},
+ {"final_response": "An ordinary reply."},
+])
+async def test_opt_in_does_not_hide_unhealthy_or_empty_results(monkeypatch, tmp_path, lane, changes):
+ runner = _runner(monkeypatch, tmp_path)
+ source = _configure(runner, tmp_path)
+ result = {"final_response": "NO_REPLY", "failed": False, "api_calls": 1, "messages": [], **changes}
+ if lane == "normal":
+ runner._run_agent = AsyncMock(return_value=result)
+ assert await runner._handle_message_with_agent(_event(reply_expected=True), source, "lane", 1)
+ elif lane == "queued":
+ from gateway.run import _normalize_empty_agent_response
+ result = {**result, "final_response": _normalize_empty_agent_response(result, result["final_response"])}
+ runner._deliver_queued_first_response = AsyncMock(return_value=True)
+ ctx = SimpleNamespace(session_key="lane", source=source, stream_consumer_holder=[None],
+ mute_notification_reply=False, persist_user_display_kind=None,
+ reply_expected=True, _status_thread_metadata=None,
+ event_message_id=None, inbound_message_id="42", run_generation=1)
+ await runner._run_agent_deliver_first_response(ctx, None, result, result, None)
+ runner._deliver_queued_first_response.assert_awaited_once()
+ else:
+ from gateway.delivery_ledger import sweep_recoverable
+ recovered, store = _db_runner(tmp_path)
+ recovered.config = runner.config
+ entry = store.get_or_create_session(source)
+ store.mark_turn_active(entry.session_key)
+ store.append_to_transcript(entry.session_id, {"role": "user", "content": "question"})
+ store.append_to_transcript(entry.session_id, {"role": "assistant", "content": result["final_response"]})
+ try:
+ _, intentional, _ = await recovered._hmwa_shape_agent_response(
+ result, source, [], entry, entry.session_key, entry.session_key, 1,
+ entry.session_id, "telegram", time.time(), reply_expected=True)
+ await recovered._record_room_silence_decision(entry.session_key, result, intentional)
+ resumed, ledgered = await recovered._recover_unclean_sessions()
+ assert resumed + ledgered == 1
+ if result["final_response"]:
+ assert sweep_recoverable(deliverable_platforms={"telegram"})
+ finally:
+ _close_store_db(store)
+
+
[email protected]("terminal_opted_in", [False, True])
+async def test_queued_terminal_source_owns_policy(monkeypatch, tmp_path, terminal_opted_in):
+ runner = _runner(monkeypatch, tmp_path)
+ opted = _configure(runner, tmp_path)
+ from gateway.session_identity import replace_source
+ guarded_home = tmp_path / "guarded"
+ guarded_home.mkdir()
+ (guarded_home / "config.yaml").write_text("{}\n", encoding="utf-8")
+ guarded = replace_source(opted, profile="guarded")
+ guarded._identity = RoutingIdentity("default", "guarded", tmp_path, guarded_home)
+ opener, terminal = (guarded, opted) if terminal_opted_in else (opted, guarded)
+ runner._run_agent = AsyncMock(return_value={
+ "final_response": "NO_REPLY", "api_calls": 1, "messages": [],
+ "queued_terminal_inbound_id": "43", "queued_terminal_source": terminal,
+ "queued_terminal_display_kind": None, "queued_terminal_reply_expected": True,
+ })
+ response = await runner._handle_message_with_agent(_event(), opener, "lane", 1)
+ assert bool(response) is not terminal_opted_in
+
+
+async def test_agent_persisted_final_survives_trailing_session_metadata(monkeypatch, tmp_path):
+ from gateway.delivery_ledger import sweep_recoverable
+ runner = _runner(monkeypatch, tmp_path)
+ source = _configure(runner, tmp_path)
+ _, store = _db_runner(tmp_path)
+ runner.session_store = store
+ event = _event(reply_expected=True)
+ event.source = source
+ messages = [{"role": "user", "content": "question", "display_metadata": {"reply_expected": True}},
+ {"role": "assistant", "content": "NO_REPLY"}]
+
+ async def persist_agent_result(*_args, **_kwargs):
+ entry = store.get_or_create_session(source)
+ for message in messages:
+ store.append_to_transcript(entry.session_id, message)
+ return {"final_response": "NO_REPLY", "failed": False, "api_calls": 1,
+ "agent_persisted": True, "messages": messages}
+
+ runner._run_agent = AsyncMock(side_effect=persist_agent_result)
+ try:
+ assert await runner._handle_message_with_agent(event, source, store._generate_session_key(source), 1) == ""
+ entry = _entry_for(store, source)
+ assert store.load_transcript(entry.session_id)[-1]["role"] == "session_meta"
+ _close_store_db(store)
+ recovered, store = _db_runner(tmp_path)
+ assert await recovered._recover_unclean_sessions() == (0, 0)
+ assert not sweep_recoverable(deliverable_platforms={"telegram"})
+ assert _entry_for(store, source).active_turn_token is None
+ finally:
+ _close_store_db(store)
+
+
[email protected]("mismatch", ["missing", "token", "timestamp"])
+async def test_recovery_keeps_guard_without_exact_completed_decision(tmp_path, mismatch):
+ from gateway.delivery_ledger import sweep_recoverable
+ runner, store = _db_runner(tmp_path)
+ source = _source()
+ entry = store.get_or_create_session(source)
+ token = store.mark_turn_active(entry.session_key)
+ store.append_to_transcript(entry.session_id, {"role": "user", "content": "question"})
+ store.append_to_transcript(entry.session_id, {"role": "assistant", "content": "NO_REPLY"})
+ try:
+ if mismatch != "missing":
+ history = store.load_transcript(entry.session_id)
+ store.set_session_metadata(entry.session_key, "room_silence_decision", {
+ "token": "old-token" if mismatch == "token" else token,
+ "timestamp": 0 if mismatch == "timestamp" else history[-1]["timestamp"],
+ "silent": True,
+ })
+ assert await runner._recover_unclean_sessions() == (0, 1)
+ assert sweep_recoverable(deliverable_platforms={"telegram"})
+ finally:
+ _close_store_db(store)
diff --git a/website/docs/user-guide/messaging/index.md b/website/docs/user-guide/messaging/index.md
index 3bef1150036..a7d10591918 100644
--- a/website/docs/user-guide/messaging/index.md
+++ b/website/docs/user-guide/messaging/index.md
@@ -342,11 +342,40 @@ platforms:
Details:
-- All three keys are optional — set only `model`, only `system_prompt`, or any combination. Unset fields fall back to the global defaults.
+- `model`, `provider`, and `system_prompt` are optional. Unset fields fall back to the global defaults. A room can also opt into intentional silence with `allow_silence` (below).
- Lookup order is exact channel/thread id first, then the **parent** channel/forum id — so Discord threads inherit their parent channel's override automatically.
- Resolution priority for the model is: session `/model` override → `channel_overrides` → global config. A user running `/model` in a chat still wins over the channel default.
- The `system_prompt` override replaces the global gateway prompt for that channel (it is ephemeral — injected per turn, not stored in history).
+## Per-Room Intentional Silence
+
+In multi-agent rooms, a model may choose to end its turn with an explicit silence marker such as
+`NO_REPLY` or `[SILENT]`. To let a successful marker-only turn stay silent even when Hermes was
+mentioned or directly addressed, enable `allow_silence` for that room in the serving profile's
+`config.yaml`:
+
+```yaml
+platforms:
+ matrix:
+ channel_overrides:
+ "!exampleTeamRoom:example.org":
+ allow_silence: true
+```
+
+The default is the existing reply policy: omitted, `null`, or `false` keeps the visible warning
+when a human message needs a reply (or the adapter cannot tell). Internal notifications,
+scheduled heartbeats, and messages known to be unaddressed keep their existing silence exemptions,
+even with `allow_silence: false`. This is a room override, not a profile-wide setting.
+It uses the same chat ID → thread ID → parent ID lookup as other channel overrides; the first
+matching entry wins, including an explicit `false`.
+
+Restart the gateway after editing configuration so all serving profiles use the updated settings.
+The override affects final delivery only: it does not undo tool actions, retract progress already
+sent, or instruct the model to choose silence. Empty, failed, partial, and interrupted results do
+not gain permission to disappear. Ordinary replies and conversation history stay unchanged.
+Crash recovery honors a suppression decision only after it was saved for that exact final reply;
+a crash before that point keeps the human-turn safeguard.
+
## Security
**By default, the gateway denies all users who are not in an allowlist or paired via DM.** This is the safe default for a bot with terminal access.