Skip to content

The agent that grows with you

fix(gateway): decline a local clarify nobody can answer, keyed on viewers

Teknium0feef55c120a
diff --git a/gateway/session_local.py b/gateway/session_local.py
index ec28a959b84..f41d3aadf75 100644
--- a/gateway/session_local.py
+++ b/gateway/session_local.py
@@ -67,19 +67,47 @@ class LocalSessionAdapter(BasePlatformAdapter):
return SendResult(success=True, message_id=uuid.uuid4().hex)
async def send_clarify(self, chat_id, question, choices, clarify_id, session_key, metadata=None):
- policy = self.policies.get(chat_id)
- if policy is not None and policy.source == 'bot_room':
- # Hosted controls expose approvals only; acknowledging this question would park the
- # member on an answer nobody can submit. A structured decline releases the wait at
- # once and skips the plain-text re-ask (an ordinary failure would fall back to a
- # send() that ACKs, and the member would wait the whole clarify timeout).
+ error = self._unanswerable_clarify(chat_id)
+ if error is not None:
+ # Acknowledging this question would park the turn on an answer nobody can submit.
+ # A structured decline releases the wait at once and skips the plain-text re-ask
+ # (an ordinary failure would fall back to a send() that ACKs, and the turn would
+ # wait the whole clarify timeout).
from gateway.relay.egress import EGRESS_DECLINE_CODE
- error = 'Clarification is unavailable in hosted rooms'
return SendResult(success=False, error=error, error_kind='forbidden',
raw_response={'success': False, 'code': EGRESS_DECLINE_CODE, 'error': error})
# Local sessions keep the base prompt: a choice question also captures typed text.
return await super().send_clarify(chat_id, question, choices, clarify_id, session_key, metadata)
+ def _unanswerable_clarify(self, chat_id):
+ """Why no one can answer a question asked in this chat now, or None to ask it.
+
+ Hosted rooms (controls expose approvals only) and forwarded A2A conversations (the
+ author is a remote peer with no prompt surface) never have an answering viewer. Any
+ other chat can be answered by an attached viewer holding ``session:respond``; with none
+ attached, a producer turn (Bot Chat DM, plugin/heartbeat injection) declines, while a
+ viewer's own turn keeps waiting so its author can re-attach and answer."""
+ policy = self.policies.get(chat_id)
+ if policy is None:
+ return None
+ from gateway.session_a2a import is_forward_policy
+ if policy.source == 'bot_room':
+ return 'Clarification is unavailable in hosted rooms'
+ if is_forward_policy(policy):
+ return 'Clarification is unavailable to a forwarded peer'
+ live = self.authority.sessions.get(chat_id)
+ if live is None:
+ return None
+ with live.event_stream.lock:
+ if any('session:respond' in member.capabilities for member in live.subscribers.values()):
+ return None
+ from hermes_state_runtime import list_session_admissions
+ started = next((row for row in list_session_admissions(self.authority.db, session_id=chat_id)
+ if row['status'] == 'started'), None)
+ if started is not None and 'local_automation_v1' in started['payload']:
+ return 'Clarification is unavailable: no viewer can answer this chat'
+ return None
+
def authorize_local_source(runner, source):
"""None for legacy/nonlocal routes; registered local adapters fail closed."""
diff --git a/tests/gateway/test_hosted_clarification_refusal.py b/tests/gateway/test_hosted_clarification_refusal.py
index 8b7174239ce..f0533d9c79d 100644
--- a/tests/gateway/test_hosted_clarification_refusal.py
+++ b/tests/gateway/test_hosted_clarification_refusal.py
@@ -1,5 +1,6 @@
"""Persisted hosted policies decline a question without a reply channel; local ones still ask."""
import asyncio
+import json
import threading
import time
from dataclasses import replace
@@ -22,10 +23,12 @@ def ask(owner, tmp_path, monkeypatch):
monkeypatch.setattr(clarify_mod, 'get_clarify_timeout', lambda: 10)
schedule = lambda coro: asyncio.run_coroutine_threadsafe(coro, loop)
- def run(source, on_sent=None):
+ def run(source, on_sent=None, request=None):
adapter = LocalSessionAdapter(owner)
policy = build_policy({'source': 'cli', 'cwd': str(tmp_path), 'model': 'm'}, {})
adapter.policies['chat'] = policy if source == 'cli' else replace(policy, source=source, platform=source)
+ if request is not None:
+ adapter.policies['chat'] = replace(adapter.policies['chat'], request_json=json.dumps(request))
kwargs = dict(chat_id='chat', question='Which?', choices=['one', 'two'], clarify_id='q-' + source,
session_key='route-' + source)
clarify_mod.register(clarify_id=kwargs['clarify_id'], session_key=kwargs['session_key'],
@@ -33,8 +36,9 @@ def ask(owner, tmp_path, monkeypatch):
sent = schedule(adapter.send_clarify(**kwargs))
if on_sent is not None:
sent.add_done_callback(lambda _: on_sent(kwargs['session_key']))
- fallback = lambda: (lambda coro: None if coro is None else schedule(coro))(
- text_fallback_coro(adapter, **kwargs))
+ def fallback():
+ coro = text_fallback_coro(adapter, **kwargs)
+ return None if coro is None else schedule(coro)
started = time.monotonic()
result = _clarify_send_then_wait(sent, clarify_id=kwargs['clarify_id'], session_key=kwargs['session_key'],
clarify_mod=clarify_mod, fallback=fallback)
@@ -58,3 +62,29 @@ def test_local_choice_prompt_still_accepts_a_typed_answer(ask):
clarify_mod.attempt_text_response_for_session(key, 'something else entirely')))
assert outcomes == [clarify_mod.TEXT_RESOLVED]
assert (response, answered) == ('something else entirely', True)
+
+
+def test_clarify_without_an_answering_viewer_is_declined(ask, owner):
+ """N8: the decline keys on who can answer, not on one source string. A forwarded A2A peer
+ never can; a producer turn (Bot Chat DM) can only while a viewer holding session:respond is
+ attached. A viewer's own turn keeps waiting for its author (the local test above)."""
+ from gateway.run_turn_runner_clarify_delivery import UNDELIVERED_DECLINED
+ from gateway.session_authority import LiveSession
+ from gateway.session_contract import Principal
+ from hermes_state_runtime import admit_session_input, claim_session_input
+ forwarded = {'source': 'a2a', 'a2a_identity': ['dev', '', 'peer', 'ctx']}
+ (response, answered), elapsed = ask('a2a', request=forwarded)
+ assert (response, answered) == (UNDELIVERED_DECLINED, False) and elapsed < 5
+ owner.db.create_session('chat', 'local')
+ owner.sessions['chat'] = live = LiveSession(object(), 'route-chat')
+ admit_session_input(owner.db, epoch=owner.epoch, principal_id='automation:route-chat', session_id='chat',
+ request_id='bot:dm', payload={'text': 'hi', 'local_automation_v1': {'identity': 'bot:dm'}})
+ assert claim_session_input(owner.db, epoch=owner.epoch, session_id='chat')['status'] == 'started'
+ (response, answered), elapsed = ask('cli')
+ assert (response, answered) == (UNDELIVERED_DECLINED, False), 'a Bot DM waited for an unseen question'
+ assert elapsed < 5
+ live.subscribers['viewer'] = Principal('uid', 'default', frozenset({'session:read', 'session:respond'}), 't')
+ outcomes = []
+ (response, answered), _ = ask('cli', on_sent=lambda key: outcomes.append(
+ clarify_mod.attempt_text_response_for_session(key, 'blue')))
+ assert (response, answered) == ('blue', True)