Skip to content

The agent that grows with you

fix(bot-mode): every transport into a live Bot Chat waits on the owner's receipt through one primitive

teknium14179dc9b090e
diff --git a/gateway/platforms/api_server.py b/gateway/platforms/api_server.py
index 6a5716906a1..4ea5a6eef73 100644
--- a/gateway/platforms/api_server.py
+++ b/gateway/platforms/api_server.py
@@ -3249,19 +3249,21 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):
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
+ """Wait on the owner's mailbox record through the shared ``await_delivery_async`` primitive 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 await_delivery_async
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:
+ while record["status"] in ("queued", "claimed"):
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ break
+ budget = remaining if keepalive is None else min(remaining, CHAT_COMPLETIONS_SSE_KEEPALIVE_SECONDS)
+ record = await await_delivery_async(home, delivery_id, budget) or record
+ if keepalive is not None and record["status"] in ("queued", "claimed"):
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"]:
diff --git a/gateway/platforms/api_server_runs.py b/gateway/platforms/api_server_runs.py
index 732a48c3dad..26646f26c4b 100644
--- a/gateway/platforms/api_server_runs.py
+++ b/gateway/platforms/api_server_runs.py
@@ -825,7 +825,7 @@ async def _execute_run_via_live_owner(self, run: _RunLaunch, home, record: Dict[
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
+ from tools.bot_live_delivery import await_delivery_async
run_id = run.run_id
delivery_id = record["delivery_id"]
@@ -837,12 +837,11 @@ async def _execute_run_via_live_owner(self, run: _RunLaunch, home, record: Dict[
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
+ record = await await_delivery_async(
+ home, delivery_id, None, should_stop=lambda: run_id in self._stopping_run_ids) or record
+ if record["status"] in ("queued", "claimed"):
+ _finish("cancelled", completed=False, partial=False, interrupted=True)
+ return
if record["status"] == "settled":
_finish("completed", completed=True, partial=False, interrupted=False,
output=record.get("reply") or "", usage={})
diff --git a/tools/bot_live_delivery.py b/tools/bot_live_delivery.py
index 6830dc6b0ca..7372b3cf6d1 100644
--- a/tools/bot_live_delivery.py
+++ b/tools/bot_live_delivery.py
@@ -17,7 +17,7 @@ from contextlib import contextmanager
from utils import atomic_json_write, atomic_write_text, fsync_directory
from pathlib import Path
-from typing import Any
+from typing import Any, Callable
from hermes_cli.active_sessions import _FileLock
@@ -295,3 +295,52 @@ def complete_delivery(
def read_delivery_result(profile_home: Path | str, delivery_id: str) -> dict[str, Any] | None:
"""Read admission/claim/terminal state without waiting or deleting its receipt."""
return _read(_root(profile_home) / f"{_delivery_id(delivery_id)}.json")
+
+
+_PENDING = ("queued", "claimed")
+_POLL_SECONDS = 0.5
+
+
+def await_delivery(
+ profile_home: Path | str, delivery_id: str, timeout: float | None,
+ *, should_stop: Callable[[], bool] | None = None,
+) -> dict[str, Any] | None:
+ """Poll a receipt until the owner settles it, ``timeout`` lapses, or ``should_stop`` says so.
+
+ Every transport that hands a turn to a live Bot Chat owner (local ``message_agent``, the
+ Desktop relay, ``hermes peer dm`` and ``hermes peer run``) waits on the same receipt; keeping
+ the loop here is what stops the lanes drifting (one lane returned a receipt sentence instead
+ of the reply, two never waited at all). Returns the last record read — still pending when the
+ budget lapsed, None when the receipt was never readable.
+ """
+ deadline = None if timeout is None else time.monotonic() + timeout
+ while True:
+ record = read_delivery_result(profile_home, delivery_id)
+ if record is None or record["status"] not in _PENDING:
+ return record
+ if should_stop is not None and should_stop():
+ return record
+ remaining = None if deadline is None else deadline - time.monotonic()
+ if remaining is not None and remaining <= 0:
+ return record
+ time.sleep(_POLL_SECONDS if remaining is None else min(_POLL_SECONDS, remaining))
+
+
+async def await_delivery_async(
+ profile_home: Path | str, delivery_id: str, timeout: float | None,
+ *, should_stop: Callable[[], bool] | None = None,
+) -> dict[str, Any] | None:
+ """``await_delivery`` for an event loop: never blocks a worker thread for the whole budget."""
+ import asyncio
+
+ deadline = None if timeout is None else time.monotonic() + timeout
+ while True:
+ record = await asyncio.to_thread(read_delivery_result, profile_home, delivery_id)
+ if record is None or record["status"] not in _PENDING:
+ return record
+ if should_stop is not None and should_stop():
+ return record
+ remaining = None if deadline is None else deadline - time.monotonic()
+ if remaining is not None and remaining <= 0:
+ return record
+ await asyncio.sleep(_POLL_SECONDS if remaining is None else min(_POLL_SECONDS, remaining))
diff --git a/tools/bot_mode_dm.py b/tools/bot_mode_dm.py
index 7ccf6acefab..c6aebeb9656 100644
--- a/tools/bot_mode_dm.py
+++ b/tools/bot_mode_dm.py
@@ -504,15 +504,10 @@ def _admit_live_dm(profile_home: Path | None, dm_file: str, author: Optional[dic
def _wait_live_dm(home: str, delivery_id: str, *, dm_file: "str | os.PathLike | None" = None) -> int:
- from tools.bot_live_delivery import read_delivery_result
-
- deadline = time.monotonic() + _LIVE_WAIT_SECONDS
- while True:
- record = read_delivery_result(home, delivery_id)
- status = record["status"] if record else "ambiguous"
- if status not in ("queued", "claimed") or time.monotonic() >= deadline:
- break
- time.sleep(min(0.5, max(0, deadline - time.monotonic())))
+ from tools.bot_live_delivery import await_delivery
+
+ record = await_delivery(home, delivery_id, _LIVE_WAIT_SECONDS)
+ status = record["status"] if record else "ambiguous"
payload = {key: record[key] for key in ("reply", "error", "reason") if record and record.get(key)}
payload.update(status=status, delivery_id=delivery_id)
if status in ("queued", "claimed", "ambiguous"):
diff --git a/tui_gateway/methods_bot_relay.py b/tui_gateway/methods_bot_relay.py
index e4e5d8a60f2..b679a87f045 100644
--- a/tui_gateway/methods_bot_relay.py
+++ b/tui_gateway/methods_bot_relay.py
@@ -142,17 +142,13 @@ def _(rid, params: dict, _root=_relay_root, _run=_run_delivery,
# the next idle boundary and settles a receipt carrying the reply. Local DMs wait on that
# receipt (_wait_live_dm); so does this relay, on the same budget, so the sender gets the
# target's answer rather than a receipt when its Bot Chat happens to be open.
- import time
- from tools.bot_live_delivery import deliver_to_live_owner, find_canonical_live_owner, read_delivery_result
+ from tools.bot_live_delivery import await_delivery, deliver_to_live_owner, find_canonical_live_owner
from tools.bot_mode_dm import _LIVE_WAIT_SECONDS
owner_home = live_home if live_home is not None else Path(_hermes_home)
owner = find_canonical_live_owner(owner_home)
if owner is not None:
record = deliver_to_live_owner(owner_home, owner, message, author=author)
- deadline = time.monotonic() + _LIVE_WAIT_SECONDS
- while record["status"] in ("queued", "claimed") and time.monotonic() < deadline:
- time.sleep(0.5)
- record = read_delivery_result(owner_home, record["delivery_id"]) or record
+ record = await_delivery(owner_home, record["delivery_id"], _LIVE_WAIT_SECONDS) or record
if record["status"] == "settled":
from tui_gateway.prompt_turn import _bot_mode_delivery_text
return _ok(rid, {"reply": _bot_mode_delivery_text((record.get("reply") or "").strip(), successful=True)})