The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): name the local Bot Chat a moved-aside API turn landed in
Teknium676d468ace19
diff --git a/gateway/platforms/api_server.py b/gateway/platforms/api_server.pyindex 9e8096c3233..a9b7a0b6917 100644--- a/gateway/platforms/api_server.py+++ b/gateway/platforms/api_server.py@@ -1096,6 +1096,13 @@ def _run_route_delegate(name: str):return _handler++def _delivered_session_id(admitted: tuple[Path, dict[str, Any]], requested: str) -> str:+ """The session a live Bot Chat delivery actually landed in: the requested id, unless the owner moved+ an API-held \"Bot Chat\" title aside and minted the local chat (MSG-21), whose id every answer names."""+ return str(admitted[1].get("session_id") or requested)++class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):"""aiohttp server routing OpenAI-format requests through hermes-agent's AIAgent."""@@ -3455,10 +3462,10 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):(``tools/bot_mode_dm.py``, ``tui_gateway/methods_bot_relay.py``). This waits for the owner'sreceipt on the same budget as the local path, so the peer still gets the reply on this call."""- session_id = ctx["session_id"]- admitted = await self._admit_to_live_bot_chat(session_id, ctx["user_message"], ctx["run_kwargs"].get("turn_author"))+ admitted = await self._admit_to_live_bot_chat(ctx["session_id"], ctx["user_message"], ctx["run_kwargs"].get("turn_author"))if admitted is None:return None+ session_id = _delivered_session_id(admitted, ctx["session_id"])record = await self._await_live_bot_chat_receipt(*admitted)delivery_id = record["delivery_id"]headers = self._session_headers(session_id, ctx["gateway_session_key"])@@ -3496,10 +3503,10 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):"""``_answer_through_live_bot_chat`` for the SSE sibling route: the owner's settled receipt isthe run's single ``assistant.completed`` event; a receipt still open at the budget is a``run.queued`` event (the 202 shape), a failed one an ``error`` event carrying the reason."""- session_id = ctx["session_id"]- admitted = await self._admit_to_live_bot_chat(session_id, ctx["user_message"], ctx["run_kwargs"].get("turn_author"))+ admitted = await self._admit_to_live_bot_chat(ctx["session_id"], ctx["user_message"], ctx["run_kwargs"].get("turn_author"))if admitted is None:return None+ session_id = _delivered_session_id(admitted, ctx["session_id"])events = _SessionEventQueue(session_id, f"run_{uuid.uuid4().hex}")response = await self._prepare_sse_response(request, session_id, ctx["gateway_session_key"])diff --git a/gateway/platforms/api_server_runs.py b/gateway/platforms/api_server_runs.pyindex 39c7e15dae2..6d44c938c6b 100644--- a/gateway/platforms/api_server_runs.py+++ b/gateway/platforms/api_server_runs.py@@ -835,6 +835,11 @@ async def _handle_runs(self, request: web.Request, *, _api_server) -> web.Respon# 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 not None and (delivered := admitted[1].get("session_id")) and delivered != session_id:+ # The owner moved an API-held "Bot Chat" title aside and the turn landed in the local chat it+ # minted (MSG-21): the run record (and its idempotency replay) names that chat, not the old row.+ session_id = launch.session_id = delivered+ self._set_run_status(run_id, "queued", session_id=session_id)if admitted is None and getattr(self.gateway_runner, 'session_authority', None) is not None:refused = await _admit_run_to_authority(self, launch, run_id, session_history_delivery, _declared_selected,diff --git a/tests/gateway/test_peer_dm_bot_chat_headless.py b/tests/gateway/test_peer_dm_bot_chat_headless.pyindex 3597267927f..7871696abfe 100644--- a/tests/gateway/test_peer_dm_bot_chat_headless.py+++ b/tests/gateway/test_peer_dm_bot_chat_headless.py@@ -52,6 +52,9 @@ async def headless(tmp_path, monkeypatch):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)+ 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, executed=executed)@@ -388,3 +391,37 @@ async def test_peer_minted_bot_chat_is_the_local_rosters_canonical_session(headlhome = Path(headless.authority.db.db_path).parentroster = _profiles(headless.authority, _local_owner(headless.authority).actor, home, {})assert (roster['profiles'][0]['canonical_session'] or {}).get('id') == session_id, roster['profiles'][0]++[email protected]('door', ['chat', 'stream', 'run'])+async def test_a_turn_after_the_move_aside_names_the_local_bot_chat(headless, door):+ # The turn runs in the newly minted local Bot Chat, so every answer names that chat: a client+ # that keeps the id it was given must not continue in the displaced API row.+ import asyncio+ import json+ db = headless.authority.db+ old = _api_bot_chat(db)+ if door == 'chat':+ resp = await headless.cli.post(f"/api/sessions/{old}/chat", json={"message": 'one', "author": AUTHOR})+ body = await resp.json()+ assert resp.status == 200, body+ named = {body['session_id'], resp.headers['X-Hermes-Session-Id']}+ elif door == 'stream':+ resp = await headless.cli.post(f"/api/sessions/{old}/chat/stream", json={"message": 'one', "author": AUTHOR})+ assert resp.status == 200, await resp.text()+ frames = [json.loads(line[6:]) for line in (await resp.text()).splitlines() if line.startswith('data: ')]+ named = {resp.headers['X-Hermes-Session-Id']} | {f['session_id'] for f in frames if 'session_id' in f}+ else:+ resp = await headless.cli.post("/v1/runs", json={"input": 'one', "session_id": old, "author": AUTHOR})+ run_id = (await resp.json())['run_id']+ for _ in range(100):+ status = await (await headless.cli.get(f"/v1/runs/{run_id}")).json()+ if status['status'] in ('completed', 'failed', 'cancelled'):+ break+ await asyncio.sleep(0.05)+ assert status['status'] == 'completed', status+ named = {status['session_id']}+ new = db.get_session_by_title('Bot Chat')['id']+ assert new != old and named == {new}, (named, old, new)+ assert [sid for sid, _, _ in headless.executed] == [new]