Skip to content

The agent that grows with you

fix(api-server): a peer run into a Bot Chat open in Desktop is that chat's turn, and its receipt drives the run

John Paul Soliva07405b65ed39
diff --git a/gateway/platforms/api_server.py b/gateway/platforms/api_server.py
index 9885a9c5aab..38e147ebe68 100644
--- a/gateway/platforms/api_server.py
+++ b/gateway/platforms/api_server.py
@@ -25,7 +25,7 @@ import threading
import time
import uuid
from pathlib import Path
-from typing import Any, Dict, List, Optional
+from typing import Any, Dict, List, Optional, Tuple
# _resolve_request_profile result for a /p/<profile>/ prefix this gateway does not serve (-> 404);
# distinct from None (no prefix / multiplexing off -> default profile).
@@ -3187,37 +3187,51 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):
return ""
return "confirmed" if runtime else "accepted"
- async def _answer_through_live_bot_chat(self, ctx: Dict[str, Any]) -> Optional["web.Response"]:
- """Hand a turn aimed at a canonical Bot Chat that a Desktop holds live to that owner.
+ async def _admit_to_live_bot_chat(
+ self, session_id: str, message: Any, author: Optional[Dict[str, Any]],
+ ) -> Optional[Tuple[Path, Dict[str, Any]]]:
+ """Admit a turn aimed at the canonical Bot Chat to the Desktop session that holds it live.
- This is the ``hermes peer dm`` transport. Running the turn here would make this process a
- second writer beside the lease holder: the open chat never shows the message or the reply,
- its live context never learns of them, and the two transcripts interleave in state.db.
- Local and relayed DMs already hand such a message to the owner's mailbox
- (``tools/bot_mode_dm.py``, ``tui_gateway/methods_bot_relay.py``). This waits for the owner's
- receipt on the same budget as the local path, so the peer still gets the reply on this call.
+ ``(profile home, mailbox record)`` when a live owner took it; None when this process should
+ run the turn itself — the session is not the canonical Bot Chat's own lineage, or nobody
+ holds that chat. Both peer transports (``/api/sessions/{id}/chat`` for ``peer dm``,
+ ``/v1/runs`` for ``peer run``) go through here, so the two lanes cannot drift.
"""
- message = ctx["user_message"]
if not isinstance(message, str):
return None
db = await self._ensure_session_db_async()
if db is None:
return None
home = Path(db.db_path).parent
- session_id = ctx["session_id"]
- from tools.bot_live_delivery import deliver_to_live_owner, find_canonical_live_owner, read_delivery_result
- from tools.bot_mode_dm import _LIVE_WAIT_SECONDS
+ from tools.bot_live_delivery import deliver_to_live_owner, find_canonical_live_owner
def _admit() -> Optional[Dict[str, Any]]:
owner = find_canonical_live_owner(home)
# Only the canonical Bot Chat's own lineage: a peer turn into any other session runs here.
if owner is None or db.get_compression_tip(session_id) != owner["session_id"]:
return None
- return deliver_to_live_owner(home, owner, message, author=ctx["run_kwargs"]["turn_author"])
+ return deliver_to_live_owner(home, owner, message, author=author)
record = await asyncio.to_thread(_admit)
- if record is None:
+ return None if record is None else (home, record)
+
+ async def _answer_through_live_bot_chat(self, ctx: Dict[str, Any]) -> Optional["web.Response"]:
+ """Hand a turn aimed at a canonical Bot Chat that a Desktop holds live to that owner.
+
+ This is the ``hermes peer dm`` transport. Running the turn here would make this process a
+ second writer beside the lease holder: the open chat never shows the message or the reply,
+ its live context never learns of them, and the two transcripts interleave in state.db.
+ Local and relayed DMs already hand such a message to the owner's mailbox
+ (``tools/bot_mode_dm.py``, ``tui_gateway/methods_bot_relay.py``). This waits for the owner's
+ receipt 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"]["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
delivery_id = record["delivery_id"]
deadline = time.monotonic() + _LIVE_WAIT_SECONDS
while record["status"] in ("queued", "claimed") and time.monotonic() < deadline:
diff --git a/gateway/platforms/api_server_runs.py b/gateway/platforms/api_server_runs.py
index 1bf96361132..eaad177cac0 100644
--- a/gateway/platforms/api_server_runs.py
+++ b/gateway/platforms/api_server_runs.py
@@ -619,7 +619,15 @@ async def _handle_runs(self, request: "web.Request", *, _api_server) -> "web.Res
browser_control_transport_family=_api_server._api_request_browser_control_transport_family.get(),
turn_author=turn_author)
self._activate_admitted_request()
- task = self._active_run_tasks[run_id] = asyncio.create_task(_execute_run(self, launch, _api_server=_api_server))
+ # 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 None
+ if 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))
+ else:
+ task = self._active_run_tasks[run_id] = asyncio.create_task(_execute_run(self, launch, _api_server=_api_server))
with suppress(TypeError):
self._background_tasks.add(task) # tracked for shutdown drain
if hasattr(task, "add_done_callback"):
@@ -741,6 +749,54 @@ def _make_approval_notify(self, run: _RunLaunch, *, _api_server) -> Callable[[Di
return _approval_notify
+async def _execute_run_via_live_owner(self, run: _RunLaunch, home, record: Dict[str, Any], *, _api_server) -> None:
+ """Drive a run whose turn a live Bot Chat owner is executing, from that owner's mailbox receipt.
+
+ The receipt is the only truth about the turn: ``settled`` completes the run with the owner's
+ reply, a failed receipt fails it with the owner's classified reason. ``/stop`` cannot reach the
+ owner's turn — the mailbox has no recall once a record is claimed — so a stop ends this run
+ as ``cancelled`` while the chat finishes on its own; the stop handler already reports that a
+ run without an in-process agent is not interruptible here.
+ """
+ from tools.bot_live_delivery import read_delivery_result
+
+ run_id = run.run_id
+ delivery_id = record["delivery_id"]
+
+ def _finish(status: str, **fields: Any) -> None:
+ self._set_run_status(run_id, status, **fields, last_event=f"run.{status}")
+ with suppress(Exception):
+ run.put_event(_run_event(run_id, f"run.{status}", **fields))
+
+ try:
+ self._set_run_status(run_id, "running", delivery_id=delivery_id)
+ while record["status"] in ("queued", "claimed"):
+ if run_id in self._stopping_run_ids:
+ _finish("cancelled", completed=False, partial=False, interrupted=True)
+ return
+ await asyncio.sleep(0.5)
+ record = await asyncio.to_thread(read_delivery_result, home, delivery_id) or record
+ if record["status"] == "settled":
+ _finish("completed", completed=True, partial=False, interrupted=False,
+ output=record.get("reply") or "", usage={})
+ elif record["status"] == "cancelled":
+ _finish("cancelled", completed=False, partial=False, interrupted=True)
+ else:
+ _finish("failed", completed=False, partial=False, interrupted=False,
+ error=record.get("error") or f"Bot Chat delivery {record['status']}",
+ **({"reason": record["reason"]} if record.get("reason") else {}))
+ except asyncio.CancelledError:
+ _finish("cancelled", completed=False, partial=False, interrupted=True)
+ raise
+ except Exception as exc:
+ logger.exception("[api_server] run %s (live Bot Chat) failed", run_id)
+ _finish("failed", completed=False, partial=False, interrupted=False, error=str(exc))
+ finally:
+ with suppress(Exception):
+ run.put_event(None) # sentinel: close the SSE stream
+ _retire_live_run(self, run_id)
+
+
async def _execute_run(self, run: _RunLaunch, *, _api_server) -> None:
"""Drive one admitted run, publish its terminal event/status, release live state."""
_redact_api_error_text = _api_server._redact_api_error_text
diff --git a/tests/gateway/test_peer_dm_into_open_bot_chat.py b/tests/gateway/test_peer_dm_into_open_bot_chat.py
index 4197432bc3f..018f9fdc7a8 100644
--- a/tests/gateway/test_peer_dm_into_open_bot_chat.py
+++ b/tests/gateway/test_peer_dm_into_open_bot_chat.py
@@ -8,6 +8,7 @@ through the owner's mailbox, like local and relayed DMs, and the owner's receipt
from __future__ import annotations
+import asyncio
import json
import threading
import time
@@ -110,6 +111,116 @@ async def test_a_peer_turn_into_an_open_bot_chat_is_answered_by_its_live_owner(
db.close()
+def _runs_app(adapter):
+ app = web.Application()
+ app.router.add_post("/v1/runs", adapter._handle_runs)
+ app.router.add_get("/v1/runs/{run_id}", adapter._handle_get_run)
+ app.router.add_post("/v1/runs/{run_id}/stop", adapter._handle_stop_run)
+ return app
+
+
+def _owner_settles(home, *, status, reply="", error="", reason="", after=0.05):
+ """The Desktop's live session: claim the delivery, run it, write the receipt."""
+ def _run():
+ owner = mailbox.find_canonical_live_owner(home)
+ for _ in range(200):
+ claimed = mailbox.claim_pending_delivery(home, owner)
+ if claimed is not None:
+ time.sleep(after)
+ mailbox.complete_delivery(home, claimed["delivery_id"], status=status, reply=reply,
+ error=error, reason=reason)
+ return
+ time.sleep(0.02)
+
+ thread = threading.Thread(target=_run, daemon=True)
+ thread.start()
+ return thread
+
+
+async def _poll_terminal(cli, run_id, *, until=("completed", "failed", "cancelled"), tries=100):
+ status = {}
+ for _ in range(tries):
+ status = await (await cli.get(f"/v1/runs/{run_id}")).json()
+ if status.get("status") in until:
+ break
+ await asyncio.sleep(0.05)
+ return status
+
+
+ ("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),
+ ],
+ ids=["owner-settles", "owner-fails-with-reason", "stopped-while-queued", "other-session-runs-here"],
+)
+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."""
+ home = tmp_path.resolve()
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ db = SessionDB(home / "state.db")
+ db.create_session("bot-chat", "desktop")
+ db.set_session_title("bot-chat", "Bot Chat")
+ db.create_session("scratch", "api_server")
+ 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_settles(home, status=receipt[0], reply=receipt[1], error=receipt[2], reason=receipt[3]) if receipt else None
+ adapter = APIServerAdapter(PlatformConfig(enabled=True))
+ adapter._session_db = db
+ ran_here = []
+
+ def _create_agent(**kwargs):
+ agent = type("Agent", (), {})()
+ agent.run_conversation = lambda *a, **k: (ran_here.append(k.get("task_id")), {"final_response": "ran here"})[1]
+ agent.session_prompt_tokens = agent.session_completion_tokens = agent.session_total_tokens = 0
+ return agent
+
+ try:
+ with patch.object(adapter, "_create_agent", side_effect=_create_agent):
+ async with TestClient(TestServer(_runs_app(adapter))) as cli:
+ resp = await cli.post("/v1/runs", json={"input": "ping", "session_id": target, "author": AUTHOR})
+ body = await resp.json()
+ assert resp.status == 202, body
+ run_id = body["run_id"]
+ if stop:
+ status = await _poll_terminal(cli, run_id, until=("running",))
+ assert status["status"] == "running"
+ assert (await cli.post(f"/v1/runs/{run_id}/stop")).status == 200
+ status = await _poll_terminal(cli, run_id)
+ if owner is not None:
+ owner.join(5)
+ assert status["status"] == expected[0], status
+ assert bool(ran_here) is turn_ran_here
+ admitted = sorted((home / "runtime" / "bot_live_delivery").glob("*.json"))
+ if turn_ran_here:
+ assert status["output"] == expected[1] and not admitted
+ return
+ [record] = [json.loads(path.read_text()) for path in admitted]
+ assert (record["message"], record["author"], record["owner"]["live_session_id"]) == ("ping", AUTHOR, "live-1")
+ assert status["delivery_id"] == record["delivery_id"]
+ if expected[0] == "completed":
+ assert status["output"] == expected[1] and status["completed"] is True
+ elif expected[0] == "failed":
+ assert status["reason"] == expected[1] and "429" in status["error"]
+ else:
+ assert status["interrupted"] is True and status["completed"] is False
+ assert run_id not in adapter._active_run_tasks, "the run retired like an executor-backed one"
+ finally:
+ lease.release()
+ db.close()
+
+
@pytest.mark.parametrize("as_json", [False, True], ids=["text", "json"])
def test_peer_dm_reports_a_turn_queued_in_the_open_bot_chat_as_delivered(monkeypatch, capsys, as_json):
"""The queued answer means the message IS in the peer's open Bot Chat: say so, succeed, and tell
diff --git a/website/docs/user-guide/bot-mode.md b/website/docs/user-guide/bot-mode.md
index 9d2e90900a9..488a3b1f872 100644
--- a/website/docs/user-guide/bot-mode.md
+++ b/website/docs/user-guide/bot-mode.md
@@ -252,7 +252,7 @@ open in its Desktop, the message is handed to that open chat and runs there as i
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
turn, `peer run` returns a
-`run_id` immediately; poll it with `peer status`. The run inherits the
+`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 the
canonical Bot Chat transcript, and a stable `--idempotency-key` makes a retry
return the original run instead of starting duplicate work. Use `peer stop`
with that exact run ID to interrupt it without targeting another turn.