The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(bot-relay): re-offer only past the Desktop's deliver deadline, once per envelope, with a typed timeout after the waiter's budget
teknium1664c7e7d4f5a
diff --git a/tests/tools/test_bot_relay.py b/tests/tools/test_bot_relay.pyindex 3e8fdaf4892..46c5c147c5e 100644--- a/tests/tools/test_bot_relay.py+++ b/tests/tools/test_bot_relay.py@@ -199,14 +199,17 @@ def test_waiter_is_a_runner_entrypoint_the_approval_gate_lets_through(root):def test_waiter_outlives_the_desktop_deliver_deadline():"""The Desktop posts its timeout reply when RELAY_DELIVER_TIMEOUT_MS passes. A waiter that gaveup first left that reply, and any turn finishing after minute 15, in a file nobody read (#93911).- relay-deliver-budget.test.ts pins the TS constants against these Python ones."""- desktop_budget_s = (- bot_relay.TURN_WAIT_SECONDS_FALLBACK- + bot_relay.TURN_ATTEMPT_TIMEOUT_SECONDS * bot_relay.TURN_MAX_ATTEMPTS- + bot_relay.DESKTOP_DELIVER_SETTLEMENT_MARGIN_SECONDS- )+ relay-deliver-budget.test.ts pins the TS constants against these Python ones.++ The re-offer window (#111021) sits between the two: only past the Desktop's deadline — and the+ gateway's own worst-case deliver hold, which ends before it — is a claimed envelope's silence+ provably a dead Desktop rather than a slow turn, and the waiter must still be listening when the+ ONE re-offered delivery hits its own Desktop deadline."""+ live_hold_s = bot_relay.TURN_WAIT_SECONDS_FALLBACK + bot_relay.TURN_ATTEMPT_TIMEOUT_SECONDS * bot_relay.TURN_MAX_ATTEMPTS+ desktop_budget_s = live_hold_s + bot_relay.DESKTOP_DELIVER_SETTLEMENT_MARGIN_SECONDSassert bot_relay.DESKTOP_DELIVER_TIMEOUT_SECONDS == desktop_budget_s- assert bot_relay.REPLY_WAIT_SECONDS > desktop_budget_s+ assert bot_relay.REOFFER_AFTER_SECONDS > desktop_budget_s > live_hold_s+ assert bot_relay.REPLY_WAIT_SECONDS > bot_relay.REOFFER_AFTER_SECONDS + desktop_budget_s@pytest.mark.parametrize(diff --git a/tests/tui_gateway/test_bot_relay_methods.py b/tests/tui_gateway/test_bot_relay_methods.pyindex fb3c5c56a1a..86aa01fcd06 100644--- a/tests/tui_gateway/test_bot_relay_methods.py+++ b/tests/tui_gateway/test_bot_relay_methods.py@@ -67,8 +67,9 @@ def test_outbox_drain_reoffers_a_claimed_envelope_the_desktop_never_delivered(ho"""A Desktop that disconnects between ``outbox.drain`` and ``bot_relay.deliver`` leaves theenvelope in ``claimed/`` with no reply: silent until the waiter's deadline, then swept, whileevery later drain saw an empty outbox (#111021, redo of #111207). Once it has sat unanswered- for ``REOFFER_AFTER_SECONDS`` the next drain hands it out again — exactly once per window — and- an envelope whose reply already landed is never re-offered."""+ for ``REOFFER_AFTER_SECONDS`` the next drain hands it out again — exactly once, ever — an+ envelope whose reply already landed is never re-offered, and one still unanswered when the+ waiter's ``REPLY_WAIT_SECONDS`` run out gets a ``delivery_timeout`` reply instead of a turn loop."""import osimport time@@ -82,14 +83,23 @@ def test_outbox_drain_reoffers_a_claimed_envelope_the_desktop_never_delivered(ho# Fresh claims are the Desktop's for a whole window: nothing to re-offer yet.assert _result(drain(2, {}))["envelopes"] == []claimed_dir = bot_relay.relay_root(home) / bot_relay.CLAIMED_DIR+ lost_path = claimed_dir / f"{lost['id']}.json"old = time.time() - bot_relay.REOFFER_AFTER_SECONDS - 1for path in claimed_dir.glob("*.json"):os.utime(path, (old, old))reoffered = _result(drain(3, {}))["envelopes"]assert [(e["id"], e["message"]) for e in reoffered] == [(lost["id"], "lost")]- # The re-offer opened a new window (mtime bumped): the same drain does not hand it out twice.+ # One re-offer per envelope: a second silent loss is not handed out again, however old it gets.+ os.utime(lost_path, (old, old))assert _result(drain(4, {}))["envelopes"] == []- assert (claimed_dir / f"{lost['id']}.json").stat().st_mtime > old + 1+ assert json.loads(lost_path.read_text(encoding="utf-8"))["reoffered_at"] >= int(old)+ # Past the waiter's deadline the drain settles it with a typed timeout so the sender learns.+ stale = json.loads(lost_path.read_text(encoding="utf-8"))+ stale["created_at"] = int(time.time()) - bot_relay.REPLY_WAIT_SECONDS - 1+ lost_path.write_text(json.dumps(stale), encoding="utf-8")+ assert _result(drain(5, {}))["envelopes"] == []+ reply = json.loads((bot_relay.relay_root(home) / bot_relay.REPLIES_DIR / f"{lost['id']}.json").read_text(encoding="utf-8"))+ assert reply["reason"] == "delivery_timeout" and reply["error"]def test_deliver_validates_profile_and_runs_transport(home, monkeypatch):diff --git a/tools/bot_relay.py b/tools/bot_relay.pyindex ed695579bcd..689effed530 100644--- a/tools/bot_relay.py+++ b/tools/bot_relay.py@@ -49,15 +49,18 @@ DESKTOP_DELIVER_SETTLEMENT_MARGIN_SECONDS = 180DESKTOP_DELIVER_TIMEOUT_SECONDS = (TURN_WAIT_SECONDS_FALLBACK + TURN_ATTEMPT_TIMEOUT_SECONDS * TURN_MAX_ATTEMPTS + DESKTOP_DELIVER_SETTLEMENT_MARGIN_SECONDS)-# The Desktop posts its own timeout reply at that deadline, so the waiter must still be watching then.-REPLY_WAIT_SECONDS = DESKTOP_DELIVER_TIMEOUT_SECONDS + 60+# A claimed envelope still unanswered this long after its claim was taken by a Desktop that died+# before ``bot_relay.deliver``; the next drain re-offers it, once. The longest a LIVE delivery can+# be in flight without a reply on disk is the Desktop's own deliver deadline (it posts a+# ``delivery_timeout`` reply when that passes, and the gateway-side hold — lock wait + the turn+# attempts — ends before it by construction), so past that point plus posting headroom the silence+# is provably the Desktop's death, not a slow turn. tests/tools/test_bot_relay.py pins the order.+REOFFER_AFTER_SECONDS = DESKTOP_DELIVER_TIMEOUT_SECONDS + 60+# The waiter must outlive the Desktop's timeout reply for the first delivery AND for the one+# re-offered delivery: re-offer window + a whole deliver budget + posting headroom.+REPLY_WAIT_SECONDS = REOFFER_AFTER_SECONDS + DESKTOP_DELIVER_TIMEOUT_SECONDS + 60# Envelopes/replies older than this are stale artifacts (Desktop closed) and are swept.STALE_AFTER_SECONDS = 6 * 3600-# A claimed envelope still unanswered this long after its claim was taken by a Desktop that died-# before ``bot_relay.deliver``; the next drain re-offers it (once per window), while the waiter-# (``REPLY_WAIT_SECONDS``) is still listening. Two full turn attempts: a live delivery is never in-# flight that long without the Desktop having posted its own timeout reply.-REOFFER_AFTER_SECONDS = 2 * TURN_ATTEMPT_TIMEOUT_SECONDS# Only a recent roster is authoritative for the fail-fast offline check: the# Desktop re-pushes roster.sync on connection-state changes.ROSTER_FRESH_SECONDS = 600@@ -348,7 +351,7 @@ def claim_pending_envelopes(root: Path | str) -> list[dict]:ttl = _envelope_ttl_seconds()now = time.time()# Re-offers first: they are the oldest mail this drain hands out.- out: list[dict] = _reoffer_unanswered(base, now)+ out: list[dict] = _reoffer_unanswered(root, base, ttl, now)# Oldest first: the Desktop delivers each target's claimed envelopes in the order this list# gives them, so a sender's two DMs to one agent arrive in the order they were sent. Sorting# by filename ordered them by ``uuid4().hex`` — at random.@@ -368,30 +371,63 @@ def claim_pending_envelopes(root: Path | str) -> list[dict]:return out-def _reoffer_unanswered(base: Path, now: float) -> list[dict]:- """``claimed/`` envelopes older than ``REOFFER_AFTER_SECONDS`` with no ``replies/<id>.json``.+def _reoffer_unanswered(root: Path | str, base: Path, ttl: float, now: float) -> list[dict]:+ """``claimed/`` envelopes unanswered ``REOFFER_AFTER_SECONDS`` after their claim, at most once each.The claim is the Desktop's: one that disconnects between ``outbox.drain`` and ``bot_relay.deliver``leaves the envelope here with no reply, silent until the waiter's deadline and then swept, while- the reconnected Desktop's drains see an empty outbox (#111021, #111207). Re-offering it hands the- message to the next drain; the mtime bump makes that once per window."""+ the reconnected Desktop's drains see an empty outbox (#111021, #111207). Bounds, in check order:++ * ``created_at + REPLY_WAIT_SECONDS`` passed with no reply — the waiter is gone (or about to be);+ a ``delivery_timeout`` reply is written so it learns, and the envelope is never handed out again.+ * already re-offered (``reoffered_at`` stamped on the envelope) — one extra delivery per message,+ never a turn loop against a target nobody is listening for.+ * ``bot_mode.envelope_ttl_seconds`` applies to the re-offer leg exactly as to the outbox: the+ message is back in the queue from ``claim + REOFFER_AFTER_SECONDS``; a drain that comes ``ttl``+ later than that refuses it with ``queued_expired``.+ """out: list[dict] = []for path in sorted((base / CLAIMED_DIR).glob("*.json"), key=_queued_at):if (base / REPLIES_DIR / path.name).exists():continuewith contextlib.suppress(OSError, ValueError):- if now - path.stat().st_mtime < REOFFER_AFTER_SECONDS:- continue- os.utime(path, (now, now))+ claimed_at = path.stat().st_mtimeenvelope = json.loads(path.read_text(encoding="utf-8"))- if isinstance(envelope, dict):- out.append(envelope)+ if not isinstance(envelope, dict):+ raise ValueError(f"expected a JSON object, got {type(envelope).__name__}")+ env_id = str(envelope.get("id") or "")+ label = f"@{envelope.get('target_handle') or '?'} on {envelope.get('target_connection') or '?'}"+ created = float(envelope.get("created_at") or claimed_at)+ if now - created > REPLY_WAIT_SECONDS:+ write_reply(root, env_id, reason="delivery_timeout", error=(+ f"no reply from {label} within {REPLY_WAIT_SECONDS}s of sending — the Desktop picked "+ "the message up but never reported a delivery. It will not be retried; resend if it matters."))+ continue+ if envelope.get("reoffered_at"):+ continue+ queued_for = now - claimed_at - REOFFER_AFTER_SECONDS+ if queued_for < 0:+ continue+ if ttl > 0 and queued_for > ttl:+ write_reply(root, env_id, reason="queued_expired", error=(+ f"re-queued message to {label} expired after {ttl}s waiting for the Desktop to drain it "+ "again — it was NOT delivered. Resend once the Desktop reconnects."))+ continue+ envelope["reoffered_at"] = int(now)+ _atomic_write_json(path, envelope)+ out.append(envelope)return outdef write_reply(root: Path | str, envelope_id: str, *, reply: str = "", error: str = "", reason: str = "") -> Path:"""Persist the relayed reply (or delivery error) for the waiter. ``reason`` (typed- code, ``tools.bot_failure_reasons``) is classified from ``error`` when omitted."""+ code, ``tools.bot_failure_reasons``) is classified from ``error`` when omitted.++ Idempotent by envelope id — the first settled reply stands, error or not. That is safe because+ two deliveries of one envelope never overlap: ``_reoffer_unanswered`` waits past the Desktop's own+ deliver deadline (``REOFFER_AFTER_SECONDS``), so by the time a second delivery can start, the first+ has either replied (and the waiter may already have read it) or provably died without one. A+ later write is therefore a duplicate or a bookkeeping timeout, never a truer answer."""base = _ensure_dirs(root)safe = str(envelope_id or "").strip()if not re.match(r"^[0-9a-f]{32}$", safe):diff --git a/website/docs/user-guide/bot-mode.md b/website/docs/user-guide/bot-mode.mdindex f6de5a55fce..3c91927d931 100644--- a/website/docs/user-guide/bot-mode.md+++ b/website/docs/user-guide/bot-mode.md@@ -224,7 +224,7 @@ Every gateway you register in **Settings → Connections** — local, remote URL- **Rosters propagate on their own.** While the Desktop runs, it periodically tells each connected gateway which agents live on the *other* connections. Every Bot Chat's teammate roster then lists them ("Teammates on OTHER connected machines"), with names, roles, and which machine they're on — and the roster refreshes when agents appear, disappear, or get renamed (capability epoch).- **`message_agent` reaches them directly.** A Bot on your laptop messages the cloud agent with `message_agent(target="moxie", …)` exactly like a local teammate. If the same handle exists on several machines, disambiguate with `target="moxie@<connection>"` (the tool's error tells the Bot the exact forms). Delivery rides the Desktop: the sending gateway queues the message, the Desktop relays it to the target connection's own gateway, the target Bot runs a turn in its canonical Bot Chat, and the reply comes back to the sender as the same background completion notification local DMs use (the process that waits for it is a Hermes entrypoint, so it starts under `approvals.single_query_mode: deny` — the default for a Bot's one-shot reply turn — too). Messages to different Bots are delivered side by side, so one Bot's long turn never delays another Bot's mail (or ages it past `bot_mode.envelope_ttl_seconds`); messages to the *same* Bot are delivered in order, one turn at a time.-- **The Desktop is the courier.** Cross-connection delivery works while a Desktop that knows both connections is running (it holds the sockets and the credentials — gateways never see each other's auth). If the Desktop is closed mid-delivery, the sender's Bot is told the reply didn't arrive rather than left hanging; a message the Desktop picked up but never handed to the target (it disconnected in between) is offered to the next drain again after two turn budgets — while the sender is still waiting — and the first reply recorded for a message is the one that stands. For always-on machine-to-machine messaging with no Desktop in the loop, register a peer (`hermes peer`, below) — the two routes coexist.+- **The Desktop is the courier.** Cross-connection delivery works while a Desktop that knows both connections is running (it holds the sockets and the credentials — gateways never see each other's auth). If the Desktop is closed mid-delivery, the sender's Bot is told the reply didn't arrive rather than left hanging; a message the Desktop picked up but never handed to the target (it disconnected in between) is offered to the next drain again — once, and only after the Desktop's own delivery deadline (~26 minutes) has passed with no reply, so a slow-but-live turn is never delivered twice. The sender keeps waiting long enough for that second delivery to finish (~52 minutes in all); if it still gets no reply, the sender is told so with reason `delivery_timeout`. While a re-offered message waits for a drain, `bot_mode.envelope_ttl_seconds` applies to it exactly as to a freshly queued one, and the first reply recorded for a message is the one that stands. For always-on machine-to-machine messaging with no Desktop in the loop, register a peer (`hermes peer`, below) — the two routes coexist.- **A remote `default` goes by its title.** Every machine's `default` is `@hermes`, so a remote one is offered — and reachable — under its Bot Mode title instead (a remote `default` titled *CoS Bot* is `@cos-bot`; with no title, `hermes@<connection>`), and a DM it sends arrives signed with that same reply-safe form rather than a bare `@hermes` that would point back at your own default.### Bot-initiated DMs across machines (`hermes peer`)