Skip to content

The agent that grows with you

fix(gateway): mint a headless peer DM's Bot Chat through its owner

unsupportedpastels6c2c8570b463
diff --git a/gateway/platforms/api_server.py b/gateway/platforms/api_server.py
index 7ff23f7cd4c..87ea195e823 100644
--- a/gateway/platforms/api_server.py
+++ b/gateway/platforms/api_server.py
@@ -3071,6 +3071,9 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):
body, err = await self._read_json_body(request)
if err:
return err
+ from gateway.platforms.api_server_bot_chat import create_peer_bot_chat
+ if (bot_chat := await create_peer_bot_chat(self, body)) is not None:
+ return bot_chat # the owner minted the canonical Bot Chat (#139370)
db = await self._ensure_session_db_async()
if db is None:
return self._session_db_unavailable()
@@ -3421,11 +3424,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):
# 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:
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)
+ return await admit_peer_turn(self.gateway_runner, session_id, message, author)
db = await self._ensure_session_db_async()
if db is None:
return None
diff --git a/gateway/platforms/api_server_bot_chat.py b/gateway/platforms/api_server_bot_chat.py
index 7ca853cdd5e..c4508e53505 100644
--- a/gateway/platforms/api_server_bot_chat.py
+++ b/gateway/platforms/api_server_bot_chat.py
@@ -9,6 +9,7 @@ session as an API conversation (``run_api_turn``) would be a second writer and i
(``permission_denied``) by design. Without an authority the legacy live-owner mailbox applies.
"""
import asyncio
+import logging
from pathlib import Path
from types import SimpleNamespace
import uuid
@@ -16,7 +17,62 @@ import uuid
from gateway.session_contract import Principal
from hermes_state_runtime import RuntimeStoreError
+logger = logging.getLogger(__name__)
+
_PENDING = ('queued', 'claimed')
+# Owner of a Bot Chat the gateway mints for a peer's create-if-missing (no native client asked).
+_PEER_SUBJECT = 'api-peer'
+
+
+def _authority(runner):
+ from gateway.session_authorities import active_authority
+ return active_authority(runner) if getattr(runner, 'session_authority', None) is not None else None
+
+
+async def create_peer_bot_chat(adapter, body):
+ """``POST /api/sessions`` titled "Bot Chat" (``hermes peer dm``'s create-if-missing) under session
+ authority: the owner mints the chat through the step a first ``bot_relay.deliver`` takes
+ (``session_bot._create_bot_chat``), so a headless gateway's Bot Chat is a LOCAL session its FIFO
+ owns, not an API row no remote sender can ever bind (#139370). None when the ordinary handler
+ answers: no authority, another title, an explicit id, or the chat exists (its title conflict)."""
+ from tools.bot_mode_probe import BOT_CHAT_TITLE
+ authority = _authority(adapter.gateway_runner)
+ if (authority is None or str(body.get('title') or '').strip() != BOT_CHAT_TITLE
+ or body.get('id') or body.get('session_id')):
+ return None
+ from aiohttp import web
+ from gateway.platforms.api_server import _error_response
+ from gateway.session_bot import _create_bot_chat
+ from gateway.session_runtime_workers import track_mutation
+ actor = Principal(_PEER_SUBJECT, authority.profile_id,
+ frozenset({'session:create', 'session:read', 'session:submit'}), 'api-peer-dm')
+ try:
+ authority._require_admission_open()
+ ref = await asyncio.shield(track_mutation(authority, _create_bot_chat(authority, actor)))
+ except RuntimeStoreError as exc:
+ return _error_response(f'Bot Chat creation refused: {exc.reason}', 503, code=exc.reason)
+ if ref is None:
+ return None
+ row = await asyncio.to_thread(authority.db.get_session, ref.session_id)
+ return web.json_response({'object': 'hermes.session', 'session': adapter._session_response(row)}, status=201)
+
+
+def _refusal(authority, tip, exc):
+ """``(reason, error)`` for a refused peer turn. A ``not_found`` on a Bot Chat that is no local
+ chat is named: a remote sender never binds unowned history, so a bare code would leave the
+ peer nothing to act on. The full clause stays in gateway.log."""
+ reason = exc.reason
+ if reason == 'not_found' and not str(tip.get('chat_id') or '').startswith('local-'):
+ from hermes_state_local_migration import validate_legacy_row
+ try:
+ validate_legacy_row(authority.db, tip)
+ reason, hint = 'bot_chat_unbound', 'open it once with `hermes chat -c "Bot Chat"` on that host'
+ except RuntimeStoreError:
+ reason, hint = 'bot_chat_not_local', "it is an API conversation; rename or delete it there"
+ logger.warning('Peer DM into Bot Chat %s refused: %s (not_found: field=%s detail=%s)',
+ tip['id'], reason, exc.field, exc.detail)
+ return reason, f"Bot Chat admission refused: {reason} (this profile's 'Bot Chat' is not a local chat; {hint})"
+ return reason, f'Bot Chat admission refused: {reason}'
def bot_chat_tip(authority, session_id):
@@ -31,11 +87,14 @@ def bot_chat_tip(authority, session_id):
return db.get_session(tip)
-async def admit_peer_turn(authority, session_id, message, author):
+async def admit_peer_turn(runner, 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
+ authority = _authority(runner)
+ if authority is None:
+ return None
tip = bot_chat_tip(authority, session_id)
if tip is None:
return None
@@ -51,17 +110,15 @@ async def admit_peer_turn(authority, session_id, message, 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}'}
+ reason, error = _refusal(authority, tip, exc)
+ record = {'status': 'failed', 'delivery_id': key, 'reason': reason, 'error': error}
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
+ authority = _authority(adapter.gateway_runner)
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
diff --git a/tests/gateway/test_peer_dm_bot_chat_headless.py b/tests/gateway/test_peer_dm_bot_chat_headless.py
new file mode 100644
index 00000000000..a38dff5e60d
--- /dev/null
+++ b/tests/gateway/test_peer_dm_bot_chat_headless.py
@@ -0,0 +1,101 @@
+"""A headless gateway's first peer DM lands in a Bot Chat its own authority FIFO owns.
+
+``hermes peer dm`` creates the remote canonical chat through ``POST /api/sessions`` when it is
+missing. With no Desktop/CLI in the loop that create used to mint an API row nothing can ever bind
+(the peer is a remote sender, never a native ticket), so every DM answered 502 "admission refused:
+not_found" (#139370). The titled create now goes through the owner's own Bot Chat creation step;
+a peer-created API row left over from before is refused by a named reason, never a bare not_found.
+"""
+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
+
+AUTHOR = {"id": "bot:cto", "name": "cto", "is_bot": True}
+
+
+@pytest_asyncio.fixture
+async def headless(tmp_path, monkeypatch):
+ from gateway import run
+ from gateway.config import GatewayConfig, Platform
+ from gateway.session import SessionStore
+ from gateway.session_authority import initialize_session_authority
+
+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))
+ monkeypatch.setattr(run, '_load_gateway_config',
+ lambda: {'platform_toolsets': {'cli': []}, 'model': {'default': 'fixture'}})
+ 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)
+ # The gateway owns its home's session authority; no Desktop/CLI ever made a "Bot Chat".
+ authority = await initialize_session_authority(runner, profile_id='default', instance_id='fixture')
+ adapter = APIServerAdapter(PlatformConfig(enabled=True))
+ adapter.gateway_runner = runner
+ adapter._session_db = authority.db
+ runner.adapters[Platform.API_SERVER] = adapter
+ runner._adapter_for_source = lambda source: runner.adapters.get(source.platform)
+ executed = []
+
+ async def execute(authority, ref, row):
+ executed.append((ref.session_id, row['principal_id'], row['payload']['text']))
+ return 'pong'
+
+ monkeypatch.setattr('gateway.session_finite.execute_finite_admission', execute)
+ app = web.Application()
+ app.router.add_post("/api/sessions", adapter._handle_create_session)
+ app.router.add_post("/api/sessions/{session_id}/chat", adapter._handle_session_chat)
+ try:
+ async with TestClient(TestServer(app)) as cli:
+ yield SimpleNamespace(cli=cli, authority=authority, executed=executed)
+ finally:
+ adapter._response_store.close()
+ adapter._run_idempotency_store.close()
+ store._db.close()
+
+
+def _api_admissions(authority):
+ return authority.db._read_all("SELECT 1 FROM session_admissions WHERE principal_id='api'")
+
+
+async def test_headless_peer_dm_creates_the_bot_chat_through_its_owner(headless):
+ # The peer client's own creation path (hermes_cli/subcommands/peer.py::_ensure_bot_chat).
+ created = await headless.cli.post("/api/sessions", json={"title": "Bot Chat", "source": "bot_peer_dm"})
+ assert created.status == 201, await created.text()
+ session_id = (await created.json())["session"]["id"]
+ row = headless.authority.db.get_session_by_title('Bot Chat')
+ assert row['id'] == session_id and str(row['chat_id']).startswith('local-'), row
+
+ for text in ('one', 'two'):
+ resp = await headless.cli.post(f"/api/sessions/{session_id}/chat", json={"message": text, "author": AUTHOR})
+ body = await resp.json()
+ assert resp.status == 200, body
+ assert body['message']['content'] == 'pong' and body['delivery_id']
+ route = headless.authority.sessions[session_id].route
+ assert headless.executed == [(session_id, 'automation:' + route, 'one'),
+ (session_id, 'automation:' + route, 'two')]
+ assert _api_admissions(headless.authority) == [], 'the Bot Chat was never bound as an API conversation'
+ # Once it exists the titled create keeps today's answer: the title is taken.
+ again = await headless.cli.post("/api/sessions", json={"title": "Bot Chat", "source": "bot_peer_dm"})
+ assert again.status == 400 and (await again.json())['error']['code'] == 'invalid_title'
+
+
+async def test_peer_created_api_bot_chat_is_refused_by_name(headless):
+ # A row an older gateway minted through the plain API create: no FIFO can own it.
+ db = headless.authority.db
+ db.create_session('api_1_stale', 'bot_peer_dm')
+ db.set_session_title('api_1_stale', 'Bot Chat')
+ resp = await headless.cli.post("/api/sessions/api_1_stale/chat", json={"message": "ping", "author": AUTHOR})
+ body = await resp.json()
+ assert resp.status == 502, body
+ assert body['error']['code'] == 'bot_chat_not_local', body
+ assert 'not_found' not in body['error']['message']
+ assert headless.executed == [] and _api_admissions(headless.authority) == []