The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(api-server): a streamed peer turn into a Bot Chat open in Desktop is answered by that chat too
teknium1af8e47a699d2
diff --git a/gateway/platforms/api_server.py b/gateway/platforms/api_server.pyindex 38e147ebe68..893c7d07c5e 100644--- a/gateway/platforms/api_server.py+++ b/gateway/platforms/api_server.py@@ -3229,14 +3229,8 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):admitted = await self._admit_to_live_bot_chat(session_id, ctx["user_message"], ctx["run_kwargs"]["turn_author"])if admitted is None:return None- home, record = admitted- from tools.bot_live_delivery import read_delivery_result- from tools.bot_mode_dm import _LIVE_WAIT_SECONDS+ record = await self._await_live_bot_chat_receipt(*admitted)delivery_id = record["delivery_id"]- deadline = time.monotonic() + _LIVE_WAIT_SECONDS- while record["status"] in ("queued", "claimed") and time.monotonic() < deadline:- await asyncio.sleep(0.5)- record = await asyncio.to_thread(read_delivery_result, home, delivery_id) or recordheaders = self._session_headers(session_id, ctx["gateway_session_key"])if record["status"] == "settled":return web.json_response(@@ -3250,6 +3244,63 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):return _error_response(record.get("error") or f"Bot Chat delivery {record['status']}", 502,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]:+ """Poll the owner's mailbox record 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 read_delivery_result+ from tools.bot_mode_dm import _LIVE_WAIT_SECONDS+ delivery_id = record["delivery_id"]+ deadline = time.monotonic() + _LIVE_WAIT_SECONDS+ next_keepalive = time.monotonic() + CHAT_COMPLETIONS_SSE_KEEPALIVE_SECONDS+ while record["status"] in ("queued", "claimed") and time.monotonic() < deadline:+ await asyncio.sleep(0.5)+ record = await asyncio.to_thread(read_delivery_result, home, delivery_id) or record+ if keepalive is not None and time.monotonic() >= next_keepalive:+ await keepalive()+ next_keepalive = time.monotonic() + CHAT_COMPLETIONS_SSE_KEEPALIVE_SECONDS+ return record++ async def _stream_through_live_bot_chat(self, request: "web.Request", ctx: Dict[str, Any]) -> Optional["web.StreamResponse"]:+ """``_answer_through_live_bot_chat`` for the SSE sibling route: the owner's settled receipt is+ the 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"]["turn_author"])+ if admitted is None:+ return None+ events = _SessionEventQueue(session_id, f"run_{uuid.uuid4().hex}")+ response = web.StreamResponse(status=200, headers={+ "Content-Type": "text/event-stream", "Cache-Control": "no-cache", "X-Accel-Buffering": "no",+ **self._session_headers(session_id, ctx["gateway_session_key"])})+ await response.prepare(request)++ async def _write(name: str, payload: Dict[str, Any]) -> None:+ name, payload = events.payload(name, payload)+ await response.write(_sse_frame(payload, event=name, ensure_ascii=False))++ async def _keepalive() -> None:+ await response.write(b": keepalive\n\n")++ try:+ await _write("run.started", {"user_message": {"role": "user", "content": ctx["user_message"]}, "runtime": {}})+ record = await self._await_live_bot_chat_receipt(*admitted, keepalive=_keepalive)+ delivery_id = record["delivery_id"]+ if record["status"] == "settled":+ message_id = f"msg_{uuid.uuid4().hex}"+ await _write("message.started", {"message": {"id": message_id, "role": "assistant"}})+ await _write("assistant.completed", {+ "message_id": message_id, "content": record.get("reply") or "", "delivery_id": delivery_id, "runtime": {}})+ await _write("run.completed", {"message_id": message_id, "delivery_id": delivery_id, "usage": {}, "runtime": {}})+ elif record["status"] in ("queued", "claimed"):+ await _write("run.queued", {"status": record["status"], "delivery_id": delivery_id})+ else:+ await _write("error", {"message": record.get("error") or f"Bot Chat delivery {record['status']}",+ "code": record.get("reason") or record["status"], "delivery_id": delivery_id})+ await _write("done", {})+ except (ConnectionResetError, ConnectionAbortedError, BrokenPipeError, OSError):+ logger.info("Session SSE client disconnected while a live Bot Chat held the turn")+ return response+@_admit_api_agent_requestasync def _handle_session_chat(self, request: "web.Request") -> "web.Response":"""POST /api/sessions/{session_id}/chat — one synchronous agent turn (plus the delivery lanes'@@ -3304,6 +3355,9 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):ctx, err = await self._prepare_session_chat(request)if err is not None:return err+ handed_off = await self._stream_through_live_bot_chat(request, ctx)+ if handed_off is not None:+ return handed_offgateway_session_key, session_id = ctx["gateway_session_key"], ctx["session_id"]user_message, runtime_request = ctx["user_message"], ctx["runtime_request"]runtime_meta = self._sanitize_runtime_metadata(diff --git a/tests/gateway/test_peer_dm_into_open_bot_chat.py b/tests/gateway/test_peer_dm_into_open_bot_chat.pyindex 018f9fdc7a8..794fc382bf1 100644--- a/tests/gateway/test_peer_dm_into_open_bot_chat.py+++ b/tests/gateway/test_peer_dm_into_open_bot_chat.py@@ -111,6 +111,63 @@ async def test_a_peer_turn_into_an_open_bot_chat_is_answered_by_its_live_owner(db.close()+def _sse_events(raw: str) -> list[tuple[str, dict]]:+ events = []+ for frame in raw.split("\n\n"):+ lines = [line for line in frame.splitlines() if line and not line.startswith(":")]+ if lines and lines[0].startswith("event: "):+ events.append((lines[0][7:], json.loads(lines[1][6:])))+ 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)diff --git a/website/docs/user-guide/bot-mode.md b/website/docs/user-guide/bot-mode.mdindex 488a3b1f872..69fe0ff0c35 100644--- a/website/docs/user-guide/bot-mode.md+++ b/website/docs/user-guide/bot-mode.md@@ -249,8 +249,9 @@ connection, the message is already in the peer's Bot Chat and the turn keeps runcommand says exactly that instead of reporting the peer unreachable — resending would run the turntwice. A timeout while connecting still reports the peer unreachable. When the peer's Bot Chat isopen in its Desktop, the message is handed to that open chat and runs there as its next turn —-whoever is watching sees it, and the reply still comes back on the call; if that turn is still going-after five minutes, `peer dm` reports the message as queued in that chat rather than lost. For a long+whoever is watching sees it, and the reply still comes back on the call (the streaming route answers+the same way, as that turn's single completion event); if that turn is still going after five+minutes, `peer dm` reports the message as queued in that chat rather than lost. For a longturn, `peer run` returns a`run_id` immediately; poll it with `peer status`. If the peer's Bot Chat is open in its Desktop, the run is that chat's next turn and its status follows the chat's own receipt. The run inherits thecanonical Bot Chat transcript, and a stable `--idempotency-key` makes a retry