The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): move an API-held Bot Chat title aside and mint the local chat
Teknium3606e74a21fe
diff --git a/gateway/platforms/api_server_bot_chat.py b/gateway/platforms/api_server_bot_chat.pyindex 47f216c787e..c775b93dd14 100644--- a/gateway/platforms/api_server_bot_chat.py+++ b/gateway/platforms/api_server_bot_chat.py@@ -77,7 +77,8 @@ def _refusal(authority, tip, exc):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"+ reason, hint = 'bot_chat_not_local', ("it is a conversation the gateway cannot own; it is moved aside "+ "as 'Bot Chat (API <id>)' on the next delivery")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})"@@ -108,10 +109,17 @@ async def admit_peer_turn(runner, session_id, message, author):if tip is None:return Nonehome = 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')+ from gateway.session_bot import displaceable_bot_chat+ if displaceable_bot_chat(authority, authority.db.get_session_by_title('Bot Chat') or tip) is not None:+ # The title is held by an API conversation no FIFO can own (#140769, MSG-21): the owner+ # moves it aside and mints the local Bot Chat for the peer, as ``create_peer_bot_chat`` does.+ actor = Principal(_PEER_SUBJECT, authority.profile_id,+ frozenset({'session:create', 'session:read', 'session:submit'}), 'api-peer-dm')+ else:+ # 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().hexparams = dict(id=key, profile=served_profile_name(home), message=message)if author is not None:diff --git a/gateway/session_bot.py b/gateway/session_bot.pyindex 60a107290be..5645cb02fc2 100644--- a/gateway/session_bot.py+++ b/gateway/session_bot.py@@ -17,6 +17,7 @@ from gateway.platforms.event import MessageEventfrom hermes_state_runtime import RuntimeStoreError, get_session_admissionfrom tools.bot_failure_reasons import HELD_NOT_SENTfrom tools.bot_live_delivery import _TERMINAL, _delivery_id, _read+logger = logging.getLogger(__name__)from gateway.session_bot_mailbox import (mailbox_lock, read_receipt, write_receipt,scan_receipts, remember_receipt, track_receipt_task, withdraw_pin, refuse_pin, requeue_pin)@@ -180,8 +181,11 @@ def _home(authority, actor, profile):async def _target(authority, actor):ref = None- if authority.db.get_session_by_title('Bot Chat') is None:- ref = await _create_bot_chat(authority, actor) # None: a concurrent delivery created it first+ row = authority.db.get_session_by_title('Bot Chat')+ if row is None or (displaced := displaceable_bot_chat(authority, row)) is not None:+ # None: a concurrent delivery created it first. A title held by an API conversation no FIFO+ # can own is moved aside first, under the same lock (MSG-21, #140769).+ ref = await _create_bot_chat(authority, actor, displace=None if row is None else displaced)if ref is None:row = authority.db.get_session_by_title('Bot Chat')tip = authority.db.get_compression_tip(row['id'])@@ -198,8 +202,45 @@ async def _target(authority, actor):return ref, live, entry-async def _create_bot_chat(authority, actor):- """No Bot Chat yet: mint it the way ``hermes chat --in ~ -c "Bot Chat" --create-if-missing``+def displaceable_bot_chat(authority, row):+ """The id holding the canonical title when the Bot Chat is a conversation no FIFO can own (an+ ``api_`` row an older gateway or a plain ``POST /api/sessions`` minted, a messaging row), else+ None. Such a row can never be adopted (``validate_legacy_row``), renamed (the canonical title+ is its identity) or renamed over the API, so it would refuse every delivery for good. A bound+ local chat and old local history (CLI, TUI, Desktop rows a native open adopts) are never moved."""+ from hermes_state_local import POLICY_PREFIX+ from hermes_state_local_migration import LEGACY_LOCAL_SOURCES, LEGACY_PREFIX+ db = authority.db+ tip = db.get_session(db.get_compression_tip(row['id']) or row['id'])+ for candidate in (row, tip):+ if candidate is None:+ return None+ chat_id = str(candidate.get('chat_id') or '')+ if chat_id.startswith('local-') or candidate.get('source') in LEGACY_LOCAL_SOURCES:+ return None+ with db._read_ctx() as conn:+ if conn.execute('SELECT 1 FROM state_meta WHERE key IN (?,?)',+ (POLICY_PREFIX + (chat_id or candidate['id']),+ LEGACY_PREFIX + (chat_id or candidate['id']))).fetchone():+ return None+ return row['id']+++def _displace_bot_chat(db, sid):+ """Free the canonical title from *sid*: it keeps its id and history under a visible name the+ user can find, rename or delete (``Bot Chat (API <id>)``). False when the title moved meanwhile."""+ name = f'Bot Chat (API {sid})'+ if len(name) > db.MAX_TITLE_LENGTH:+ name = name[:db.MAX_TITLE_LENGTH - 2] + '…)'++ def write(conn):+ return conn.execute("UPDATE sessions SET title=?, title_source=?, hidden=0 WHERE id=? AND title='Bot Chat'",+ (name, db.TITLE_SOURCE_USER, sid)).rowcount+ return bool(db._execute_write(write))+++async def _create_bot_chat(authority, actor, *, displace=None):+ """No Bot Chat yet (or *displace*, an API conversation holding its title, is moved aside first): mint it the way ``hermes chat --in ~ -c "Bot Chat" --create-if-missing``did on the CLI lane this door replaced, so a fresh profile's first delivery has somewhereto land instead of being recorded as failed. Same owner step as ``session.create`` with atitle: lookup, creation and title run under the authority's titled-create lock, with the@@ -216,8 +257,13 @@ async def _create_bot_chat(authority, actor):if lock is None:lock = authority._titled_create_lock = asyncio.Lock()async with lock:- if authority.db.get_session_by_title('Bot Chat') is not None:- return None+ held = authority.db.get_session_by_title('Bot Chat')+ if held is not None:+ if displace is None or held['id'] != displace or displaceable_bot_chat(authority, held) != displace:+ return None+ logger.warning("Bot Chat title held by %s, a conversation no FIFO can own: moving it aside", displace)+ if not await tracked_write(authority, partial(_displace_bot_chat, authority.db, displace)):+ return None# The Bot Chat follows its profile whoever mints it (a Bot or cron delivery, a peer DM),# the same contract Desktop's create asks for. A later profile change reaches it.request_id = _bot_chat_creation_id(authority, actor)diff --git a/tests/gateway/test_peer_dm_bot_chat_headless.py b/tests/gateway/test_peer_dm_bot_chat_headless.pyindex 0f5bb62302b..3597267927f 100644--- a/tests/gateway/test_peer_dm_bot_chat_headless.py+++ b/tests/gateway/test_peer_dm_bot_chat_headless.py@@ -125,18 +125,114 @@ async def test_concurrent_peer_creates_mint_one_local_bot_chat(headless):assert headless.authority.db.get_session_by_title('Bot Chat')['id'] == rows[0][0]+def _api_bot_chat(db, sid='api_1_stale', source='api_server', hidden=True):+ """A canonical Bot Chat an older gateway minted through the plain API create (#140769): an+ ``api_`` row, no ``chat_id``, that no native client can ever adopt."""+ db.create_session(sid, source)+ db.set_session_title(sid, 'Bot Chat')+ db.append_message(sid, 'user', 'old history')+ if hidden:+ db._execute_write(lambda conn: conn.execute('UPDATE sessions SET hidden=1 WHERE id=?', (sid,)))+ return sid+++def _assert_displaced(db, old, new):+ """The API row keeps its id and history under a visible name; the title is the local chat's."""+ row = db.get_session(old)+ assert row['title'] == f'Bot Chat (API {old})' and not row['hidden'], row+ assert [m['content'] for m in db.get_messages(old)] == ['old history']+ titled = db._read_all("SELECT id FROM sessions WHERE title = 'Bot Chat'")+ assert [r[0] for r in titled] == [new] and str(db.get_session(new)['chat_id']).startswith('local-')++[email protected]('source', ['api_server', 'bot_peer_dm'])@pytest.mark.asyncio-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.+async def test_peer_dm_into_an_api_created_bot_chat_lands_in_a_local_bot_chat(headless, source):+ # #140769 / MSG-21: main refused every DM with ``bot_chat_not_local`` ("rename or delete it+ # there"), and neither is possible: the canonical title cannot be renamed and the API has no+ # rename route. The owner now moves the API row aside and mints the local Bot Chat.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})+ old = _api_bot_chat(db, source=source)+ resp = await headless.cli.post(f"/api/sessions/{old}/chat", json={"message": 'one', "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) == []+ assert resp.status == 200, body+ assert body['message']['content'] == 'pong'+ new = db.get_session_by_title('Bot Chat')['id']+ assert new != old and db.get_session(new)['user_id'] == 'api-peer'+ _assert_displaced(db, old, new)+ # ``hermes peer dm`` resolves the Bot Chat by title on every call: the next DM names the new id.+ resp = await headless.cli.post(f"/api/sessions/{new}/chat", json={"message": 'two', "author": AUTHOR})+ assert resp.status == 200 and (await resp.json())['message']['content'] == 'pong'+ assert [(sid, text) for sid, _, text in headless.executed] == [(new, 'one'), (new, 'two')]+ assert _api_admissions(headless.authority) == [], 'the API row was never bound as an API conversation'+ # Each retry reuses the one local chat: no second Bot Chat, no new api_ row.+ assert len(_sessions(headless.authority)) == 2+++async def test_peer_create_if_missing_after_the_api_row_moved_finds_the_local_chat(headless):+ db = headless.authority.db+ old = _api_bot_chat(db)+ resp = await headless.cli.post(f"/api/sessions/{old}/chat", json={"message": "one", "author": AUTHOR})+ assert resp.status == 200, await resp.text()+ # ``hermes peer dm``'s next create-if-missing collides on the local chat's title, as for any+ # existing Bot Chat; it never mints another row.+ 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'+ assert len(_sessions(headless.authority)) == 2+++async def test_local_bot_relay_delivery_moves_an_api_bot_chat_aside(headless):+ # MSG-21 on the local door: ``bot_relay.deliver`` / a cron delivery found the API row by title+ # and failed adoption with ``not_found``, permanently.+ from pathlib import Path+ from gateway.session_authorities import served_profile_name+ from gateway.session_bot import deliver+ from tests.waiting import async_wait_until+ db = headless.authority.db+ old = _api_bot_chat(db)+ profile = served_profile_name(Path(db.db_path).parent.resolve())+ record = await deliver(_local_owner(headless.authority),+ dict(id='e' * 32, profile=profile, message='relayed', author=AUTHOR))+ new = record['session_id']+ _assert_displaced(db, old, new)+ await async_wait_until(lambda: headless.executed, timeout=10, interval=.05)+ assert [(sid, text) for sid, _, text in headless.executed] == [(new, 'relayed')]+++async def test_a_submit_only_delivery_never_moves_the_api_bot_chat(headless):+ # Owner recovery and other submit-only principals cannot create the replacement, so the title+ # stays where it is (still ``not_found``): moving it would leave the profile with no Bot Chat.+ from pathlib import Path+ from gateway.session_authorities import served_profile_name+ from gateway.session_bot import deliver+ from gateway.session_contract import Principal+ from hermes_state_runtime import RuntimeStoreError+ db = headless.authority.db+ old = _api_bot_chat(db)+ actor = Principal('uid:1000', headless.authority.profile_id,+ frozenset({'session:submit', 'session:read'}), 'bot-owner-recovery')+ profile = served_profile_name(Path(db.db_path).parent.resolve())+ with pytest.raises(RuntimeStoreError) as exc:+ await deliver(SimpleNamespace(authority=headless.authority, actor=actor),+ dict(id='f' * 32, profile=profile, message='relayed'))+ assert exc.value.reason == 'not_found'+ assert db.get_session_by_title('Bot Chat')['id'] == old and len(_sessions(headless.authority)) == 1+++async def test_an_adoptable_legacy_bot_chat_is_not_moved_aside(headless):+ # A pre-upgrade CLI Bot Chat is real local history its owner adopts on first open; the peer is+ # told so by name, and its title and history stay where they are.+ db = headless.authority.db+ db.create_session('legacy_cli', 'cli')+ db.set_session_title('legacy_cli', 'Bot Chat')+ resp = await headless.cli.post("/api/sessions/legacy_cli/chat", json={"message": "ping", "author": AUTHOR})+ body = await resp.json()+ assert resp.status == 502 and body['error']['code'] == 'bot_chat_unbound', body+ assert db.get_session_by_title('Bot Chat')['id'] == 'legacy_cli' and len(_sessions(headless.authority)) == 1async def _peer_minted(headless):