The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): peer turns into the Bot Chat compose with session authority through the deliver door
teknium1f327908b4a70
diff --git a/gateway/platforms/api_server.py b/gateway/platforms/api_server.pyindex 7be9410855c..7658b8e5291 100644--- a/gateway/platforms/api_server.py+++ b/gateway/platforms/api_server.py@@ -3225,10 +3225,16 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):"""if not isinstance(message, str):return None- # Under session authority the canonical FIFO is the single writer for every session,- # so a peer turn is admitted there (``run_api_turn``) rather than handed to a lease holder.+ # Under session authority the Bot Chat is a LOCAL session whose only writer is the+ # authority FIFO (a Desktop showing it is a viewer, not a lease holder): the turn enters+ # through the same door as ``bot_relay.deliver`` and the receipt is its admission's.if getattr(self.gateway_runner, "session_authority", None) is not None:- return None+ from gateway.platforms.api_server_bot_chat import admit_peer_turn+ from gateway.session_authorities import active_authority+ authority = active_authority(self.gateway_runner)+ if authority is None:+ return None+ return await admit_peer_turn(authority, session_id, message, author)db = await self._ensure_session_db_async()if db is None:return None@@ -3279,19 +3285,19 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):code=record.get("reason") or record["status"], headers=headers)async def _await_live_bot_chat_receipt(self, home: Path, record: Dict[str, Any], *, keepalive=None) -> Dict[str, Any]:- """Wait on the owner's mailbox record through the shared ``await_delivery_async`` primitive until it- settles or the local DM budget runs out; ``keepalive`` (async) is called every SSE keepalive interval- so a streaming caller's proxy keeps the socket."""- from tools.bot_live_delivery import await_delivery_async+ """Wait on the live Bot Chat's receipt (the authority admission's waiter, or the legacy owner+ mailbox through ``await_delivery_async``) until it settles or the local DM budget runs out;+ ``keepalive`` (async) is called every SSE keepalive interval so a streaming caller's proxy+ keeps the socket."""+ from gateway.platforms.api_server_bot_chat import await_live_deliveryfrom tools.bot_mode_dm import _LIVE_WAIT_SECONDS- delivery_id = record["delivery_id"]deadline = time.monotonic() + _LIVE_WAIT_SECONDSwhile record["status"] in ("queued", "claimed"):remaining = deadline - time.monotonic()if remaining <= 0:breakbudget = remaining if keepalive is None else min(remaining, CHAT_COMPLETIONS_SSE_KEEPALIVE_SECONDS)- record = await await_delivery_async(home, delivery_id, budget) or record+ record = await await_live_delivery(self, home, record, budget)if keepalive is not None and record["status"] in ("queued", "claimed"):await keepalive()return recorddiff --git a/gateway/platforms/api_server_bot_chat.py b/gateway/platforms/api_server_bot_chat.pynew file mode 100644index 00000000000..2199aa5859d--- /dev/null+++ b/gateway/platforms/api_server_bot_chat.py@@ -0,0 +1,105 @@+"""Peer turns into the canonical Bot Chat under session authority.++``hermes peer dm`` (``/api/sessions/{id}/chat[/stream]``) and ``hermes peer run`` (``/v1/runs``)+aim at the profile's Bot Chat. Under session authority that chat is a LOCAL session whose only+writer is the authority FIFO — a Desktop showing it is a viewer, never a lease-holding executor —+so the API edge admits the turn through the same door as ``bot_relay.deliver``+(``gateway/session_bot.py``) and reads the reply from that admission's receipt. Binding the+session as an API conversation (``run_api_turn``) would be a second writer and is refused+(``permission_denied``) by design. Without an authority the legacy live-owner mailbox applies.+"""+import asyncio+from pathlib import Path+from types import SimpleNamespace+import uuid++from gateway.session_contract import Principal+from hermes_state_runtime import RuntimeStoreError++_PENDING = ('queued', 'claimed')+++def bot_chat_tip(authority, session_id):+ """The canonical Bot Chat's tip row when *session_id* is in its lineage, else None."""+ db = authority.db+ row = db.get_session_by_title('Bot Chat')+ if row is None:+ return None+ tip = db.get_compression_tip(row['id'])+ if not tip or db.get_compression_tip(session_id) != tip:+ return None+ return db.get_session(tip)+++async def admit_peer_turn(authority, session_id, message, author):+ """``(profile home, receipt)`` when *session_id* is the Bot Chat and the turn was admitted to its+ FIFO; None when the target is any other session (the caller runs it as an API turn)."""+ from gateway.session_authorities import served_profile_name+ from gateway.session_bot import deliver+ tip = bot_chat_tip(authority, session_id)+ if tip is None:+ return None+ home = Path(authority.db.db_path).parent.resolve()+ # The API key already authenticated the peer; the turn enters the chat as its owner's own+ # input, the way owner recovery re-admits queued deliveries (``recover_bot_deliveries``).+ actor = Principal(tip['user_id'], authority.profile_id,+ frozenset({'session:submit', 'session:read'}), 'api-peer-dm')+ key = uuid.uuid4().hex+ params = dict(id=key, profile=served_profile_name(home), message=message)+ if author is not None:+ params['author'] = dict(author)+ try:+ record = await deliver(SimpleNamespace(authority=authority, actor=actor), params)+ except RuntimeStoreError as exc:+ record = {'status': 'failed', 'delivery_id': key, 'reason': exc.reason,+ 'error': f'Bot Chat admission refused: {exc.reason}'}+ return home, record+++async def await_live_delivery(adapter, home, record, timeout, *, should_stop=None):+ """Wait for a live Bot Chat receipt through whichever door admitted it: the authority FIFO+ (in-process waiter) or the legacy owner mailbox (``await_delivery_async``)."""+ from gateway.session_authorities import active_authority+ authority = active_authority(adapter.gateway_runner) if getattr(+ adapter.gateway_runner, 'session_authority', None) is not None else None+ if authority is not None and record.get('admission_id'):+ return await await_peer_receipt(authority, record, timeout, should_stop=should_stop)+ from tools.bot_live_delivery import await_delivery_async+ return await await_delivery_async(home, record['delivery_id'], timeout, should_stop=should_stop) or record+++async def await_peer_receipt(authority, record, timeout, *, should_stop=None):+ """The admission's current receipt after it settles, *timeout* lapses, or *should_stop* says so."""+ from gateway.session_bot import _result+ admission_id = record['admission_id']+ if record['status'] not in _PENDING:+ return record+ loop = asyncio.get_running_loop()+ # Register the waiter BEFORE re-reading: a settle between the two either shows in the read+ # or resolves this future; a settle before both would otherwise leave a future nobody pops.+ waiter = authority.waiters.setdefault(admission_id, loop.create_future())+ current = _receipt(authority, record)+ deadline = None if timeout is None else loop.time() + timeout+ while current['status'] in _PENDING and not waiter.done():+ if should_stop is not None and should_stop():+ break+ remaining = None if deadline is None else deadline - loop.time()+ if remaining is not None and remaining <= 0:+ break+ tick = 0.5 if should_stop is not None else remaining+ await asyncio.wait([waiter], timeout=tick if remaining is None else min(tick, remaining))+ current = _receipt(authority, record)+ return current+++def _receipt(authority, record):+ from gateway.session_bot import _result+ from gateway.session_results import admission_result+ current = {**record, **_result(authority, record)}+ if current['status'] == 'failed' and not current.get('error'):+ saved = admission_result(authority.db, record['admission_id'])+ error = (saved or {}).get('result', {}).get('error')+ if error:+ from tools.bot_failure_reasons import classify_agent_error+ current.update(error=error, reason=classify_agent_error(error))+ return currentdiff --git a/gateway/platforms/api_server_runs.py b/gateway/platforms/api_server_runs.pyindex 9257bb9442f..a21e33c79b9 100644--- a/gateway/platforms/api_server_runs.py+++ b/gateway/platforms/api_server_runs.py@@ -726,7 +726,13 @@ async def _handle_runs(self, request: "web.Request", *, _api_server) -> "web.Resbrowser_control_principal=_api_server._api_request_browser_control_principal.get(),browser_control_transport_family=_api_server._api_request_browser_control_transport_family.get(),turn_author=turn_author)- if getattr(self.gateway_runner, 'session_authority', None) is not None:+ # A canonical Bot Chat that a Desktop holds live is that Desktop's to run: executing here would+ # be a second writer beside its lease (#114959). The owner's mailbox takes the turn and its+ # receipt drives this run's status, so `peer run` keeps its run_id and `peer status` still works.+ # Under session authority the same call admits the turn to the Bot Chat's own FIFO, which is+ # why it is decided BEFORE ``admit_api_turn`` would bind the chat as an API conversation.+ admitted = await self._admit_to_live_bot_chat(session_id, user_message, turn_author) if selected_session_id else None+ if admitted is None and getattr(self.gateway_runner, 'session_authority', None) is not None:from gateway.session_api_turn import admit_api_turnfrom hermes_state_runtime import RuntimeStoreErrortry:@@ -749,10 +755,6 @@ async def _handle_runs(self, request: "web.Request", *, _api_server) -> "web.Resself._run_idempotency_store.forget(idempotency_scope, idempotency_key)return _json_error(_openai_error, exc.reason, code=exc.reason, status=409)self._activate_admitted_request()- # A canonical Bot Chat that a Desktop holds live is that Desktop's to run: executing here would- # be a second writer beside its lease (#114959). The owner's mailbox takes the turn and its- # receipt drives this run's status, so `peer run` keeps its run_id and `peer status` still works.- admitted = await self._admit_to_live_bot_chat(session_id, user_message, turn_author) if selected_session_id else Noneif admitted is not None:task = self._active_run_tasks[run_id] = asyncio.create_task(_execute_run_via_live_owner(self, launch, *admitted, _api_server=_api_server))@@ -888,7 +890,7 @@ async def _execute_run_via_live_owner(self, run: _RunLaunch, home, record: Dict[as ``cancelled`` while the chat finishes on its own; the stop handler already reports that arun without an in-process agent is not interruptible here."""- from tools.bot_live_delivery import await_delivery_async+ from gateway.platforms.api_server_bot_chat import await_live_deliveryrun_id = run.run_iddelivery_id = record["delivery_id"]@@ -904,8 +906,8 @@ async def _execute_run_via_live_owner(self, run: _RunLaunch, home, record: Dict[try:self._set_run_status(run_id, "running", delivery_id=delivery_id)- record = await await_delivery_async(- home, delivery_id, None, should_stop=lambda: run_id in self._stopping_run_ids) or record+ record = await await_live_delivery(+ self, home, record, None, should_stop=lambda: run_id in self._stopping_run_ids)if record["status"] in ("queued", "claimed"):_finish("cancelled", completed=False, partial=False, interrupted=True)return@@ -1295,7 +1297,10 @@ async def _handle_stop_run(self, request: "web.Request", *, _api_server) -> "webself, request, _api_server=_api_server, permission="stop", active_fallback=True)if err is not None:return err- if getattr(self.gateway_runner, 'session_authority', None) is not None:+ # A run whose turn a live Bot Chat owns (``_execute_run_via_live_owner``) is not an API+ # admission: its stop is the legacy in-process task cancel below, never ``stop_run``.+ if (getattr(self.gateway_runner, 'session_authority', None) is not None+ and not (task is not None and status.get("delivery_id"))):from gateway.platforms.api_server_authority_runs import stop_runfrom hermes_state_runtime import RuntimeStoreErrortry:diff --git a/tests/gateway/test_peer_dm_bot_chat_authority.py b/tests/gateway/test_peer_dm_bot_chat_authority.pynew file mode 100644index 00000000000..4c03d64676f--- /dev/null+++ b/tests/gateway/test_peer_dm_bot_chat_authority.py@@ -0,0 +1,112 @@+"""A peer turn into the canonical Bot Chat under session authority is that chat's own admission.++``hermes peer dm`` / ``peer run`` reach the API edge; under the unified runtime the Bot Chat is+a LOCAL session whose only writer is the authority FIFO, so the turn goes through the+``bot_relay.deliver`` door (``gateway/session_bot.py``) and the reply is its admission's+receipt. Binding the chat as an API conversation would be a second writer (``permission_denied``).+"""+import asyncio+import json+from types import SimpleNamespace++import pytest+import pytest_asyncio+from aiohttp import web+from aiohttp.test_utils import TestClient, TestServer++from gateway.config import PlatformConfig+from gateway.platforms.api_server import APIServerAdapter+from gateway.session_contract import Principal++AUTHOR = {"id": "bot:cto", "name": "cto", "is_bot": True}+++@pytest_asyncio.fixture+async def peer(tmp_path, monkeypatch):+ from gateway import run+ from gateway.config import GatewayConfig+ from gateway.session import SessionStore+ from gateway.session_authority import initialize_session_authority+ from gateway.session_local import create_local_session+ from gateway.session_local_title import title_new_session++ monkeypatch.setenv('HERMES_HOME', str(tmp_path))+ monkeypatch.setattr(run, '_load_gateway_config', lambda: {'platform_toolsets': {'cli': []}})+ monkeypatch.setattr('tools.bot_mode_dm._LIVE_WAIT_SECONDS', 2.0)+ from hermes_state import SessionDB+ store = SessionStore(tmp_path / 'sessions', GatewayConfig())+ store._db = SessionDB(db_path=tmp_path / 'state.db')+ runner = SimpleNamespace(session_store=store, _session_db=store._db, adapters={}, _draining=False,+ _evict_cached_agent=lambda route: None)+ authority = await initialize_session_authority(runner, profile_id='default', instance_id='fixture')+ owner = Principal('uid:1000', 'default', frozenset({'session:create', 'session:read', 'session:submit'}), 'native')+ chat = create_local_session(authority, owner, {'request_id': 'bot', 'source': 'gui', 'cwd': str(tmp_path),+ 'model': 'fixture', 'toolsets': []})+ title_new_session(authority, chat, 'Bot Chat')+ authority.db.create_session('scratch', 'api_server')+ adapter = APIServerAdapter(PlatformConfig(enabled=True))+ adapter.gateway_runner = runner+ adapter._session_db = authority.db+ from gateway.config import Platform+ runner.adapters[Platform.API_SERVER] = adapter+ runner._adapter_for_source = lambda source: runner.adapters.get(source.platform)+ executed = []++ async def execute(authority, ref, row):+ text = row['payload']['text']+ executed.append((ref.session_id, row['principal_id'], text, row['payload'].get('local_automation_v1', {}).get('turn_author')))+ if text == 'fail':+ raise RuntimeError('provider said 429')+ return 'pong'++ monkeypatch.setattr('gateway.session_finite.execute_finite_admission', execute)+ app = web.Application()+ app.router.add_post("/api/sessions/{session_id}/chat", adapter._handle_session_chat)+ app.router.add_post("/api/sessions/{session_id}/chat/stream", adapter._handle_session_chat_stream)+ app.router.add_post("/v1/runs", adapter._handle_runs)+ app.router.add_get("/v1/runs/{run_id}", adapter._handle_get_run)+ try:+ async with TestClient(TestServer(app)) as cli:+ yield SimpleNamespace(cli=cli, authority=authority, chat=chat.session_id, executed=executed,+ adapter=adapter, home=tmp_path)+ finally:+ adapter._response_store.close()+ adapter._run_idempotency_store.close()+ store._db.close()+++async def test_peer_dm_into_the_bot_chat_is_the_chats_own_admission(peer):+ resp = await peer.cli.post(f"/api/sessions/{peer.chat}/chat", json={"message": "ping", "author": AUTHOR})+ body = await resp.json()+ assert resp.status == 200, body+ assert body['message']['content'] == 'pong' and body['delivery_id']+ assert peer.executed == [(peer.chat, 'automation:' + peer.authority.sessions[peer.chat].route, 'ping', AUTHOR)]+ # The receipt is durable and exact: the same delivery reads back settled, no re-execution.+ record = json.loads((peer.home / 'runtime' / 'bot_live_delivery' / f"{body['delivery_id']}.json").read_text())+ assert record['status'] == 'settled' and record['session_id'] == peer.chat+ rows = peer.authority.db._read_all("SELECT principal_id FROM session_admissions WHERE principal_id='api'")+ assert rows == [], 'the Bot Chat was never bound as an API conversation'+++async def test_streamed_peer_dm_and_peer_run_ride_the_same_door(peer):+ resp = await peer.cli.post(f"/api/sessions/{peer.chat}/chat/stream", json={"message": "ping", "author": AUTHOR})+ assert resp.status == 200, await resp.text()+ assert resp.content_type == "text/event-stream"+ names = [line[7:] for line in (await resp.text()).splitlines() if line.startswith('event: ')]+ assert names[0] == 'run.started' and 'assistant.completed' in names and names[-1] == 'done'++ resp = await peer.cli.post("/v1/runs", json={"input": "fail", "session_id": peer.chat, "author": AUTHOR})+ run_id = (await resp.json())['run_id']+ for _ in range(100):+ status = await (await peer.cli.get(f"/v1/runs/{run_id}")).json()+ if status['status'] in ('completed', 'failed', 'cancelled'):+ break+ await asyncio.sleep(0.05)+ assert status['status'] == 'failed' and status['delivery_id'], status+ assert [text for _, _, text, _ in peer.executed] == ['ping', 'fail']+ # A turn into any other session still runs as an ordinary API admission.+ resp = await peer.cli.post("/api/sessions/scratch/chat", json={"message": "elsewhere"})+ assert resp.status == 200 and [text for _, _, text, _ in peer.executed][-1] == 'elsewhere'+ assert peer.authority.db._read_all("SELECT 1 FROM session_admissions WHERE principal_id='api'")diff --git a/tests/gateway/test_peer_dm_into_open_bot_chat.py b/tests/gateway/test_peer_dm_into_open_bot_chat.pyindex fcedd9e9867..dd902d246be 100644--- a/tests/gateway/test_peer_dm_into_open_bot_chat.py+++ b/tests/gateway/test_peer_dm_into_open_bot_chat.py@@ -1,9 +1,11 @@-"""A peer DM into a Bot Chat that a Desktop holds open is answered BY that open chat.--``hermes peer dm`` posts to ``/api/sessions/{id}/chat`` on the peer. When the peer's canonical Bot-Chat is open in its Desktop, the Desktop session holds the chat's single-writer lease; running the-turn in the API server beside it made a second writer the open chat never saw. The message now goes-through the owner's mailbox, like local and relayed DMs, and the owner's receipt carries the reply.+"""A peer DM into a Bot Chat is answered by that chat, never by a second writer.++``hermes peer dm`` posts to ``/api/sessions/{id}/chat`` on the peer. Under session authority the+Bot Chat's single writer is the authority FIFO and the turn enters through the ``bot_relay.deliver``+door (``tests/gateway/test_peer_dm_bot_chat_authority.py``). This file keeps the no-authority lane:+a Desktop lease is a viewer, not an executor (the lease-advertised mailbox consumer was retired), so+without an authority to hand the chat to, this process runs the turn itself and no mailbox record+is admitted."""from __future__ import annotations@@ -54,19 +56,17 @@ def _owner_answers(home, reply):@pytest.mark.parametrize(("target", "open_in_desktop", "owner_replies", "status", "content", "turn_ran_here"),[- ("bot-chat", True, True, 200, "pong", False),- ("bot-chat", True, False, 202, None, False),("scratch", True, True, 200, "ran here", True),+ ("bot-chat", True, False, 200, "ran here", True),("bot-chat", False, False, 200, "ran here", True),],- ids=["open-bot-chat-answers", "open-bot-chat-still-running", "other-session", "bot-chat-not-open"],+ ids=["other-session", "bot-chat-open-in-a-viewer", "bot-chat-not-open"],)async def test_a_peer_turn_into_an_open_bot_chat_is_answered_by_its_live_owner(tmp_path, monkeypatch, target, open_in_desktop, owner_replies, status, content, turn_ran_here):- """Only the canonical Bot Chat's live owner takes the turn; every other session, and a Bot Chat- nobody holds, still runs here. A turn the owner has not finished inside the wait is reported as- queued in that chat, never as a failure the sender would resend."""+ """Without a profile authority nothing else may execute the Bot Chat's turn: a Desktop viewer+ lease is not an owner, so the turn runs here and no mailbox delivery is admitted."""home = tmp_path.resolve()monkeypatch.setenv("HERMES_HOME", str(home))monkeypatch.setattr("tools.bot_mode_dm._LIVE_WAIT_SECONDS", 1.0)@@ -120,54 +120,6 @@ def _sse_events(raw: str) -> list[tuple[str, dict]]:return events[email protected](("owner_replies", "terminal"), [(True, "assistant.completed"), (False, "run.queued")],- ids=["open-bot-chat-answers", "open-bot-chat-still-running"])-async def test_a_streamed_peer_turn_into_an_open_bot_chat_is_answered_by_its_live_owner(- tmp_path, monkeypatch, owner_replies, terminal-):- """The SSE sibling of the chat route takes the same door: the owner's receipt arrives as the run's- single assistant.completed event (or run.queued at the budget) and no turn runs here."""- home = tmp_path.resolve()- monkeypatch.setenv("HERMES_HOME", str(home))- monkeypatch.setattr("tools.bot_mode_dm._LIVE_WAIT_SECONDS", 1.0)- db = SessionDB(home / "state.db")- db.create_session("bot-chat", "desktop")- db.set_session_title("bot-chat", "Bot Chat")- from hermes_cli.active_sessions import try_acquire_active_session- lease, refusal = try_acquire_active_session(- session_id="bot-chat", surface="desktop", config={}, registry_home=home, track_liveness=True,- metadata={"live_session_id": "live-1", "bot_live_delivery_consumer": True})- assert lease is not None and refusal is None- owner = _owner_answers(home, "pong") if owner_replies else None- adapter = APIServerAdapter(PlatformConfig(enabled=True))- adapter._session_db = db- app = web.Application()- app.router.add_post("/api/sessions/{session_id}/chat/stream", adapter._handle_session_chat_stream)- try:- with patch.object(adapter, "_run_agent", AsyncMock(return_value=({"final_response": "ran here"}, {}))) as run:- async with TestClient(TestServer(app)) as cli:- resp = await cli.post("/api/sessions/bot-chat/chat/stream", json={"message": "ping", "author": AUTHOR})- assert resp.status == 200 and resp.content_type == "text/event-stream"- events = _sse_events(await resp.text())- if owner is not None:- owner.join(5)- assert not run.called- [record] = [json.loads(p.read_text()) for p in (home / "runtime" / "bot_live_delivery").glob("*.json")]- assert (record["message"], record["author"]) == ("ping", AUTHOR)- names = [name for name, _ in events]- assert names[0] == "run.started" and names[-1] == "done" and terminal in names- payload = dict(events)[terminal]- assert payload["delivery_id"] == record["delivery_id"]- if owner_replies:- assert payload["content"] == "pong" and "run.completed" in names- else:- assert payload["status"] == "queued"- finally:- lease.release()- db.close()--def _runs_app(adapter):app = web.Application()app.router.add_post("/v1/runs", adapter._handle_runs)@@ -208,19 +160,16 @@ async def _poll_terminal(cli, run_id, *, until=("completed", "failed", "cancelle@pytest.mark.parametrize(("target", "receipt", "stop", "expected", "turn_ran_here"),[- ("bot-chat", ("settled", "pong", "", ""), False, ("completed", "pong"), False),- ("bot-chat", ("failed", "", "provider said 429", "provider_rate_limit"), False, ("failed", "provider_rate_limit"), False),- ("bot-chat", None, True, ("cancelled", None), False),("scratch", None, False, ("completed", "ran here"), True),+ ("bot-chat", None, False, ("completed", "ran here"), True),],- ids=["owner-settles", "owner-fails-with-reason", "stopped-while-queued", "other-session-runs-here"],+ ids=["other-session-runs-here", "bot-chat-runs-here-without-an-authority"],)async def test_a_peer_run_into_an_open_bot_chat_is_driven_by_its_owners_receipt(tmp_path, monkeypatch, target, receipt, stop, expected, turn_ran_here):- """`peer run` keeps its run_id and `peer status` keeps working, but the turn is the open- chat's: the owner's receipt is the run's status — reply, classified failure, or a stop that- ends the run without pretending it reached a turn this process never ran."""+ """`peer run` into the Bot Chat with no authority to hand it to runs here like any other+ session; the run keeps its run_id and `peer status` keeps working."""home = tmp_path.resolve()monkeypatch.setenv("HERMES_HOME", str(home))db = SessionDB(home / "state.db")