The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat: share live clarification controls across attached viewers
Teknium9c474378a1f6
diff --git a/gateway/run_turn_runner.py b/gateway/run_turn_runner.pyindex 4446a976893..f2cb77a8333 100644--- a/gateway/run_turn_runner.py+++ b/gateway/run_turn_runner.py@@ -282,6 +282,13 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):logger.warning("%s boundary timed out or failed: %s", reason, err)return False+ async def _send_shared_clarify(self, entry, **kwargs):+ result = await self._ctx._status_adapter.send_clarify(**kwargs)+ if self._approval_owner is not None and result.success:+ authority, session_id, generation = self._approval_owner+ authority.register_clarify(session_id, generation, entry)+ return result+def _clarify_callback_sync(self, question: str, choices, multi_select: bool = False) -> str:"""Present a clarify prompt and block on a response (clarify_tool's synchronous contract):schedule send_clarify on the gateway loop, block on the primitive's threading.Event with a@@ -295,7 +302,7 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):session_key = ctx.session_key or ""clarify_id = uuid.uuid4().hex[:10]choices = list(choices) if choices else None- clarify_mod.register(+ entry = clarify_mod.register(clarify_id=clarify_id, session_key=session_key, question=question, choices=choices,multi_select=bool(multi_select),)@@ -316,7 +323,7 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):except Exception:logger.debug("Stream-consumer flush before clarify prompt failed", exc_info=True)fut = self._schedule(- ctx._status_adapter.send_clarify(+ self._send_shared_clarify(entry,chat_id=ctx._status_chat_id, question=question, choices=choices, clarify_id=clarify_id,session_key=session_key, metadata=ctx._status_thread_metadata,),@@ -326,6 +333,9 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):# have posted with a late ack. Only a definitive failure tears down the registration;# ambiguous falls through to the bounded wait so a late reply resolves.response = _clarify_send_then_wait(fut, clarify_id=clarify_id, session_key=session_key, clarify_mod=clarify_mod)+ if self._approval_owner is not None:+ authority, session_id, generation = self._approval_owner+ authority.sessions[session_id].controls.snapshot(session_id, generation)# Only re-arm typing when the user actually answered — the undeliverable sentinel and the# timeout/cancellation strings start with '[' and must pass through untouched.if not (isinstance(response, str) and response.startswith("[")):diff --git a/gateway/session_authority.py b/gateway/session_authority.pyindex 4c2f03bd3d3..78756b189fb 100644--- a/gateway/session_authority.py+++ b/gateway/session_authority.py@@ -14,7 +14,7 @@ from gateway.session_contract import (SubscriptionSnapshot,)from gateway.session_events import SessionEvents-from gateway.session_pending_controls import PendingApprovals+from gateway.session_pending_controls import PendingControlsfrom hermes_state_runtime import (RuntimeStoreError, admit_session_input, begin_runtime_epoch,cancel_session_input, claim_session_input, get_session_admission,@@ -29,10 +29,10 @@ class LiveSession:task: asyncio.Task | None = Nonesubscribers: dict = field(default_factory=dict)event_stream: SessionEvents = field(default_factory=SessionEvents)- controls: PendingApprovals = field(init=False)+ controls: PendingControls = field(init=False)def __post_init__(self):- self.controls = PendingApprovals(self.event_stream)+ self.controls = PendingControls(self.event_stream)class SessionAuthority:@@ -224,8 +224,17 @@ class SessionAuthority:self.check_approval_generation(session_id, generation)live.controls.register(session_id, route, generation, data)- async def respond(self, actor, ref, generation, prompt_id, response):- self.authorize(actor, ref, "session:approve")+ def register_clarify(self, session_id, generation, entry):+ live = self.sessions[session_id]+ with live.event_stream.lock:+ self.check_approval_generation(session_id, generation)+ live.controls.register_clarify(session_id, generation, entry)++ async def respond(self, actor, ref, generation, prompt_id, response, *, kind="approval"):+ capability = {"approval": "session:approve", "clarify": "session:control"}.get(kind)+ if capability is None:+ raise RuntimeStoreError("invalid_params")+ self.authorize(actor, ref, capability)live = self.sessions[ref.session_id]with live.event_stream.lock:if actor not in live.subscribers.values():@@ -235,7 +244,7 @@ class SessionAuthority:self.check_approval_generation(ref.session_id, generation)if not isinstance(prompt_id, str) or not prompt_id:raise RuntimeStoreError("invalid_params")- return live.controls.respond(ref.session_id, generation, prompt_id, response)+ return live.controls.respond(ref.session_id, generation, prompt_id, response, kind=kind)async def _drain(self, ref):from gateway.session_ingress import execute_admissiondiff --git a/gateway/session_controls.py b/gateway/session_controls.pyindex 7a57636c4a3..a31334612d5 100644--- a/gateway/session_controls.py+++ b/gateway/session_controls.py@@ -26,7 +26,7 @@ class AuthorityConnection:handlers = {'session.resume': self.resume, 'prompt.submit': self.submit,'prompt.receipt': self.receipt, 'prompt.cancel': self.cancel,'session.interrupt': self.interrupt, 'session.events.since': self.events_since,- 'approval.respond': self.respond}+ 'approval.respond': self.respond, 'clarify.respond': self.respond_clarify}try:if method not in handlers:raise RuntimeStoreError('invalid_params')@@ -88,6 +88,12 @@ class AuthorityConnection:return await self.authority.respond(self.actor, ref, params["execution_generation"],params["prompt_id"], {"choice": params["choice"]})+ async def respond_clarify(self, ref, params):+ if set(params) != {"session_id", "execution_generation", "prompt_id", "answer"}:+ raise RuntimeStoreError("invalid_params")+ return await self.authority.respond(self.actor, ref, params["execution_generation"],+ params["prompt_id"], {"answer": params["answer"]}, kind="clarify")+async def close(self):for subscription in self.subscriptions.values():await self.authority.detach(self.actor, subscription)diff --git a/gateway/session_pending_controls.py b/gateway/session_pending_controls.pyindex f82a7bf8577..0ce9a70699e 100644--- a/gateway/session_pending_controls.py+++ b/gateway/session_pending_controls.py@@ -1,7 +1,7 @@"""Generation-bound projection/control of the existing blocking approval queue.-Only ordinary approval choices cross this boundary. Clarify and secret/sudo-prompts remain on their native paths; no answer is published or journaled here.+Ordinary approvals and clarify prompts share the existing native waiters.+Secret/sudo prompts remain native; no response is published or journaled here."""from copy import deepcopy@@ -9,7 +9,7 @@ from hermes_state_runtime import RuntimeStoreErrorfrom tools.approval import list_gateway_approvals, resolve_gateway_approval-class PendingApprovals:+class PendingControls:def __init__(self, events):self.events = eventsself.pending = {}@@ -31,23 +31,45 @@ class PendingApprovals:self.pending[prompt_id] = (route, prompt)self.events.publish(session_id, prompt, event_type='approval.request')+ def register_clarify(self, session_id, generation, entry):+ from gateway.run import _redact_approval_command+ with self.events.lock:+ prompt = {"kind": "clarify", "prompt_id": entry.clarify_id,+ "execution_generation": generation,+ "question": _redact_approval_command(entry.question),+ "choices": [_redact_approval_command(c) for c in entry.choices or []],+ "multi_select": entry.multi_select}+ self.pending[entry.clarify_id] = (entry, prompt)+ self.events.publish(session_id, prompt, event_type="clarify.request")+def snapshot(self, session_id, generation):with self.events.lock:for prompt_id, (route, prompt) in list(self.pending.items()):- active = {p['request_id'] for p in list_gateway_approvals(route)}- if prompt['execution_generation'] != generation or prompt_id not in active:+ active = (not route.event.is_set() if prompt['kind'] == 'clarify' else+ any(p['request_id'] == prompt_id for p in list_gateway_approvals(route)))+ if prompt['execution_generation'] != generation or not active:del self.pending[prompt_id]self.events.publish(session_id, {'prompt_id': prompt_id,- 'execution_generation': prompt['execution_generation']}, event_type='approval.settled')+ 'execution_generation': prompt['execution_generation']}, event_type=prompt['kind'] + '.settled')return tuple(deepcopy(prompt) for _, prompt in self.pending.values())- def respond(self, session_id, generation, prompt_id, response):+ def respond(self, session_id, generation, prompt_id, response, *, kind="approval"):with self.events.lock:self.snapshot(session_id, generation)entry = self.pending.get(prompt_id)if entry is None:return {'status': 'already_resolved', 'prompt_id': prompt_id}route, prompt = entry+ if prompt['kind'] != kind:+ raise RuntimeStoreError('invalid_params')+ if kind == 'clarify':+ from tools.clarify_gateway import resolve_gateway_clarify+ if (not isinstance(response, dict) or set(response) != {'answer'}+ or not isinstance(response['answer'], str)):+ raise RuntimeStoreError('invalid_params')+ resolved = resolve_gateway_clarify(prompt_id, response['answer'])+ self.snapshot(session_id, generation)+ return {'status': 'resolved' if resolved else 'already_resolved', 'prompt_id': prompt_id}if not isinstance(response, dict) or set(response) != {'choice'} or response['choice'] not in prompt['choices']:raise RuntimeStoreError('invalid_params')# The tools lock arbitrates native taps versus attached responders;diff --git a/tests/gateway/fixtures/authority_clarify_peer.py b/tests/gateway/fixtures/authority_clarify_peer.pynew file mode 100644index 00000000000..71a796d9cac--- /dev/null+++ b/tests/gateway/fixtures/authority_clarify_peer.py@@ -0,0 +1,157 @@+"""Owned loopback model, real clarify tool, native card, two authenticated sockets."""+import asyncio+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+import json+import os+from pathlib import Path+import threading+import traceback+++class ModelPeer(BaseHTTPRequestHandler):+ def log_message(self, *args):+ pass++ def do_GET(self):+ self.send_response(200)+ self.end_headers()+ self.wfile.write(b'{"data": []}')++ def do_POST(self):+ body = json.loads(self.rfile.read(int(self.headers['Content-Length'])))+ messages = body.get('messages', [])+ self.server.requests.append(messages)+ asking = bool(messages) and not any(m['role'] == 'tool' for m in messages)+ message = {'role': 'assistant', 'content': 'CLARIFY_FINISHED'}+ if asking:+ message = {'role': 'assistant', 'content': None, 'tool_calls': [{+ 'index': 0, 'id': 'owned-clarify', 'type': 'function', 'function': {+ 'name': 'clarify', 'arguments': json.dumps({'questions': [+ {'question': 'Pick a color', 'choices': ['blue', 'green']}]})}}]}+ self.send_response(200)+ self.send_header('Content-Type', 'text/event-stream' if body.get('stream') else 'application/json')+ self.end_headers()+ if body.get('stream'):+ for delta, finish in [(message, None), ({}, 'tool_calls' if asking else 'stop')]:+ frame = {'id': 'local', 'object': 'chat.completion.chunk', 'created': 1,+ 'model': 'local', 'choices': [{'index': 0, 'delta': delta, 'finish_reason': finish}]}+ self.wfile.write(('data: ' + json.dumps(frame) + '\n\n').encode())+ self.wfile.write(b'data: [DONE]\n\n')+ else:+ self.wfile.write(json.dumps({'id': 'local', 'choices': [{'index': 0, 'message': message,+ 'finish_reason': 'tool_calls' if asking else 'stop'}]}).encode())+ self.wfile.flush()+++async def probe(peer):+ import websockets+ from gateway.config import Platform, PlatformConfig+ from gateway.platforms.base import BasePlatformAdapter, SendResult+ from gateway.run import GatewayRunner+ from gateway.run_api import start_gateway_api, stop_gateway_api+ from gateway.session import SessionSource+ from gateway.session_authority import initialize_session_authority+ from hermes_cli import web_server+ from tools import clarify_gateway++ class Adapter(BasePlatformAdapter):+ async def connect(self, **kwargs):+ return True+ async def disconnect(self):+ pass+ async def send(self, chat_id, content, **kwargs):+ return SendResult(success=True, message_id='owned')+ async def send_typing(self, *args, **kwargs):+ pass+ async def get_chat_info(self, chat_id):+ return {'id': chat_id}+ async def send_clarify(self, **kwargs):+ return SendResult(success=True, message_id='owned-card')++ runner = GatewayRunner()+ authority = await initialize_session_authority(runner, profile_id='fixture', instance_id='clarify')+ runner.adapters[Platform.TELEGRAM] = Adapter(PlatformConfig(enabled=True, token='fixture'), Platform.TELEGRAM)+ ref = authority.register(SessionSource(platform=Platform.TELEGRAM, chat_id='clarify-chat',+ chat_type='dm', user_id='fixture-user'))+ api = await start_gateway_api(runner)+ url = api.api_origin.replace('http:', 'ws:') + '/api/ws?token=' + web_server._SESSION_TOKEN++ async def rpc(ws, rid, method, **params):+ await ws.send(json.dumps({'jsonrpc': '2.0', 'id': rid, 'method': method,+ 'params': {'session_id': ref.session_id, **params}}))+ async with asyncio.timeout(10):+ while True:+ frame = json.loads(await ws.recv())+ if frame.get('id') == rid:+ return frame++ a = b = None+ try:+ a, b = await websockets.connect(url), await websockets.connect(url)+ await rpc(a, 1, 'session.resume')+ await rpc(b, 1, 'session.resume')+ assert 'result' in await rpc(a, 2, 'prompt.submit', input_id='clarify-first', text='Ask my color')+ try:+ async with asyncio.timeout(15):+ while True:+ snapshot = await rpc(b, 3, 'session.resume')+ prompts = snapshot['result']['prompts']+ if prompts:+ break+ await asyncio.sleep(.05)+ except TimeoutError:+ raise AssertionError('real clarify waiter missing from shared snapshot') from None+ prompt = prompts[0]+ assert prompt['kind'] == 'clarify', prompt+ assert clarify_gateway.has_pending(authority.sessions[ref.session_id].route)+ await a.close()+ a = None+ assert (await rpc(b, 4, 'session.resume'))['result']['prompts'][0]['prompt_id'] == prompt['prompt_id']+ identity = {'prompt_id': prompt['prompt_id'], 'execution_generation': prompt['execution_generation']}+ stale = await rpc(b, 5, 'clarify.respond', **{**identity, 'execution_generation': -1}, answer='green')+ assert stale['error']['data']['reason'] == 'stale_generation'+ response = await rpc(b, 6, 'clarify.respond', **identity, answer='green')+ assert response['result']['status'] == 'resolved', response+ duplicate = await rpc(b, 7, 'clarify.respond', **identity, answer='SHOULD_NOT_REPLACE')+ assert duplicate.get('result', {}).get('status') == 'already_resolved' or duplicate.get('error', {}).get('data', {}).get('reason') == 'stale_generation', duplicate+ await asyncio.wait_for(authority.sessions[ref.session_id].task, 15)+ tools = [m for messages in peer.requests for m in messages if m['role'] == 'tool']+ assert any('green' in json.dumps(m) for m in tools), tools+ assert not any('SHOULD_NOT_REPLACE' in json.dumps(m) for m in tools)+ assert (await rpc(b, 8, 'session.resume'))['result']['prompts'] == []+ Path(os.environ['HERMES_HOME'], 'clarify-passed').write_text('reply reached real model; stale reply rejected')+ finally:+ clarify_gateway.clear_session(authority.sessions[ref.session_id].route)+ task = authority.sessions[ref.session_id].task+ if task is not None:+ await asyncio.wait_for(task, 15)+ for ws in (a, b):+ if ws is not None:+ await ws.close()+ await stop_gateway_api(api)+++def main():+ peer = ThreadingHTTPServer(('127.0.0.1', 0), ModelPeer)+ peer.requests = []+ threading.Thread(target=peer.serve_forever, daemon=True).start()+ url = f'http://127.0.0.1:{peer.server_port}/v1'+ os.environ.update(OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=url, TELEGRAM_ALLOWED_USERS='fixture-user')+ Path(os.environ['HERMES_HOME'], 'config.yaml').write_text(+ f'model:\n default: local\n provider: custom\n base_url: {url}\n'+ 'agent:\n clarify_timeout: 25\nauxiliary:\n title_generation:\n enabled: false\n')+ try:+ asyncio.run(probe(peer))+ finally:+ peer.shutdown()+ peer.server_close()+++if __name__ == '__main__':+ status = 0+ try:+ main()+ except BaseException:+ traceback.print_exc()+ status = 1+ os._exit(status)diff --git a/tests/gateway/test_shared_clarify.py b/tests/gateway/test_shared_clarify.pynew file mode 100644index 00000000000..bb34e021676--- /dev/null+++ b/tests/gateway/test_shared_clarify.py@@ -0,0 +1,37 @@+"""Clarification response survives viewer detach through the real gateway worker."""+import os+from pathlib import Path+import subprocess+import sys+++def test_real_shared_clarify_survives_detach(tmp_path):+ home, state = tmp_path / 'home', tmp_path / 'state'+ home.mkdir()+ state.mkdir()+ repo = Path(__file__).resolve().parents[2]+ env = {key: os.environ[key] for key in ('PATH', 'LANG', 'TZ') if key in os.environ}+ env.update(HOME=str(home), USERPROFILE=str(home), HERMES_HOME=str(state), PYTHONPATH=str(repo))+ result = subprocess.run(+ [sys.executable, str(Path(__file__).parent / 'fixtures' / 'authority_clarify_peer.py')],+ cwd=repo, env=env, stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=60)+ assert result.returncode == 0, result.stdout + result.stderr+ assert (state / 'clarify-passed').read_text() == 'reply reached real model; stale reply rejected'+++def test_expired_clarify_disappears_before_turn_settlement():+ from gateway.session_events import SessionEvents+ from gateway.session_pending_controls import PendingControls+ from tools import clarify_gateway++ events = SessionEvents()+ controls = PendingControls(events)+ entry = clarify_gateway.register('owned-expiring-question', 'owned-expiring-route', 'Choose', ['a', 'b'])+ try:+ controls.register_clarify('owned-session', 1, entry)+ assert controls.snapshot('owned-session', 1)+ assert clarify_gateway.wait_for_response(entry.clarify_id, timeout=.01) is None+ assert controls.snapshot('owned-session', 1) == ()+ assert controls.respond('owned-session', 1, entry.clarify_id, {'answer': 'a'}, kind='clarify')['status'] == 'already_resolved'+ finally:+ clarify_gateway.clear_session(entry.session_key)diff --git a/tools/clarify_gateway.py b/tools/clarify_gateway.pyindex e33a5ff083b..8ace7542aa0 100644--- a/tools/clarify_gateway.py+++ b/tools/clarify_gateway.py@@ -79,6 +79,7 @@ def wait_for_response(clarify_id: str, timeout: float) -> Optional[str]:touch_activity_if_due(activity_state, "waiting for user clarify response")with _lock:_entries.pop(clarify_id, None) # regardless of outcome+ entry.event.set() # Timeout also retires shared projections of this waiter.ids = _session_index.get(entry.session_key) or []if clarify_id in ids:ids.remove(clarify_id)diff --git a/website/docs/developer-guide/gateway-internals.md b/website/docs/developer-guide/gateway-internals.mdindex 1b06a051f3d..8336190414b 100644--- a/website/docs/developer-guide/gateway-internals.md+++ b/website/docs/developer-guide/gateway-internals.md@@ -8,6 +8,27 @@ description: "How the messaging gateway boots, authorizes users, routes sessionsThe messaging gateway is the long-running process that connects Hermes to 20+ external messaging platforms through a unified architecture.+## Shared authority clarification protocol++When the HTTP/WebSocket surface is bound to a `SessionAuthority`, attached authorized+viewers receive `clarify.request` events and pending questions in the `session.resume`+`prompts` snapshot. This is an authority API contract; it does not imply that every+native frontend already renders the shared form or that ordinary bootstrap is complete.++A response uses `clarify.respond` with `session_id`, `execution_generation`, `prompt_id`,+and an `answer` string. The connected viewer must be subscribed and have+`session:control`. The authority checks the running generation and resolves the existing+native clarify waiter by exact prompt ID, without adding a user prompt to the admission+queue. The first response wins; detach does not cancel it. Native answers and timeouts+retire the same prompt and emit `clarify.settled`; response text is not placed in the+control replay stream, although the normal clarify tool result becomes part of the+conversation. Questions and choice labels use the existing display redactor.++Publication follows successful native card delivery. A failed native delivery does not+create an actionable shared form. Ordinary approvals use the separate `approval.respond`+permission path; sudo/secret prompts and durable control restoration after daemon restart+are not implemented by this clarification path.+## Key Files| File | Purpose |