The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(bot-mode): envelope TTL + offline fast-fail for bot relay (#93091 item 2)
kshitijk4poorb96369212c22
diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.pyindex 64af9f5401e..a84cb5a93b0 100644--- a/hermes_cli/config_defaults.py+++ b/hermes_cli/config_defaults.py@@ -2706,6 +2706,19 @@ DEFAULT_CONFIG = {"done_sub_retention_days": 30,},+ # Bot Mode cross-connection relay (tools/bot_relay.py). Envelopes queued+ # by message_agent for agents on other connections wait in an on-disk+ # outbox until the Desktop drains them.+ "bot_mode": {+ # Drain-time TTL (seconds): an envelope older than this is NOT+ # delivered when the Desktop finally drains the outbox — the sender+ # gets an error reply (reason 'queued_expired') instead, so a DM+ # written while the Desktop was away can't land hours late as a+ # confusing zombie message. 0 disables drain-time expiry (the 6h+ # stale-artifact sweep still applies).+ "envelope_ttl_seconds": 900,+ },+# execute_code settings — controls the tool used for programmatic tool calls."code_execution": {# Execution mode:diff --git a/tests/tools/test_bot_relay.py b/tests/tools/test_bot_relay.pyindex 28b334e48ba..f2166d3f7b0 100644--- a/tests/tools/test_bot_relay.py+++ b/tests/tools/test_bot_relay.py@@ -340,3 +340,151 @@ def test_cleanup_bot_relay_artifacts_sweeps_stale_plaintext(tmp_path, monkeypatcdef test_cleanup_bot_relay_artifacts_missing_dir_is_zero(tmp_path, monkeypatch):monkeypatch.setenv("HERMES_HOME", str(tmp_path / "nope"))assert bot_relay.cleanup_bot_relay_artifacts() == 0+++# ── #93091 item 2: offline fail-fast + drain-time TTL ────────────────────────++import os as _os2+import time as _time2+++def _target(conn="cloud-1", profile="scout", handle="scout"):+ return {"profile": profile, "handle": handle, "connection_id": conn,+ "connection_label": "", "title": "", "description": ""}+++def test_enqueue_fails_fast_when_row_explicitly_offline(root):+ bot_relay.write_remote_roster(root, [+ {"profile": "scout", "handle": "scout", "connection_id": "cloud-1",+ "online": False},+ ])+ roster = bot_relay.read_remote_roster(root)+ assert roster[0]["online"] is False # additive field survives normalize+ with pytest.raises(bot_relay.EnvelopeRefusedError) as ei:+ bot_relay.enqueue_envelope(+ root, target=roster[0], message="hi",+ sender_profile="default", sender_handle="hermes",+ )+ assert ei.value.reason == "runtime_offline"+ assert "offline" in str(ei.value)+ # nothing was written to the outbox+ outdir = bot_relay.relay_root(root) / bot_relay.OUTBOX_DIR+ assert not outdir.exists() or list(outdir.glob("*.json")) == []+++def test_enqueue_fails_fast_when_target_absent_from_fresh_roster(root):+ bot_relay.write_remote_roster(root, _rows()) # fresh, no 'scout' row+ with pytest.raises(bot_relay.EnvelopeRefusedError) as ei:+ bot_relay.enqueue_envelope(+ root, target=_target(), message="hi",+ sender_profile="default", sender_handle="hermes",+ )+ assert ei.value.reason == "runtime_offline"+++def test_enqueue_fails_open_when_liveness_unknown(root):+ # 1. no roster ever synced → unknown → enqueue+ env = bot_relay.enqueue_envelope(+ root, target=_target(), message="hi",+ sender_profile="default", sender_handle="hermes",+ )+ assert (bot_relay.relay_root(root) / bot_relay.OUTBOX_DIR / f"{env['id']}.json").exists()+ # 2. stale roster missing the target → unknown → enqueue+ bot_relay.write_remote_roster(root, _rows())+ roster_path = bot_relay.relay_root(root) / bot_relay.ROSTER_FILE+ old = _time2.time() - bot_relay.ROSTER_FRESH_SECONDS - 5+ _os2.utime(roster_path, (old, old))+ env2 = bot_relay.enqueue_envelope(+ root, target=_target(), message="hi again",+ sender_profile="default", sender_handle="hermes",+ )+ assert (bot_relay.relay_root(root) / bot_relay.OUTBOX_DIR / f"{env2['id']}.json").exists()+ # 3. fresh roster listing the target without an online flag → enqueue+ bot_relay.write_remote_roster(root, _rows())+ target = bot_relay.read_remote_roster(root)[1] # researcher@ssh-vps+ env3 = bot_relay.enqueue_envelope(+ root, target=target, message="hello",+ sender_profile="default", sender_handle="hermes",+ )+ assert (bot_relay.relay_root(root) / bot_relay.OUTBOX_DIR / f"{env3['id']}.json").exists()+++def test_drain_expires_old_envelope_with_queued_expired_reply(root):+ env = bot_relay.enqueue_envelope(+ root, target=_target(), message="too late",+ sender_profile="default", sender_handle="hermes",+ )+ base = bot_relay.relay_root(root)+ out_path = base / bot_relay.OUTBOX_DIR / f"{env['id']}.json"+ # backdate the envelope beyond the TTL+ env["created_at"] = int(_time2.time()) - bot_relay.DEFAULT_ENVELOPE_TTL_SECONDS - 10+ out_path.write_text(json.dumps(env), encoding="utf-8")++ claimed = bot_relay.claim_pending_envelopes(root)++ assert claimed == [] # not delivered+ assert not out_path.exists() # expired outbox file removed+ reply = json.loads(+ (base / bot_relay.REPLIES_DIR / f"{env['id']}.json").read_text(encoding="utf-8")+ )+ assert reply["reason"] == "queued_expired"+ assert "expired" in reply["error"] and "NOT delivered" in reply["error"]+ assert not reply["reply"]+++def test_drain_delivers_fresh_envelope_under_ttl(root):+ env = bot_relay.enqueue_envelope(+ root, target=_target(), message="on time",+ sender_profile="default", sender_handle="hermes",+ )+ claimed = bot_relay.claim_pending_envelopes(root)+ assert [e["id"] for e in claimed] == [env["id"]]+ # no spurious expiry reply for a delivered envelope+ base = bot_relay.relay_root(root)+ assert not (base / bot_relay.REPLIES_DIR / f"{env['id']}.json").exists()+++def test_drain_ttl_zero_disables_expiry(root, monkeypatch):+ monkeypatch.setattr(bot_relay, "_envelope_ttl_seconds", lambda: 0)+ env = bot_relay.enqueue_envelope(+ root, target=_target(), message="never expires",+ sender_profile="default", sender_handle="hermes",+ )+ base = bot_relay.relay_root(root)+ out_path = base / bot_relay.OUTBOX_DIR / f"{env['id']}.json"+ env["created_at"] = int(_time2.time()) - 10 * 3600+ out_path.write_text(json.dumps(env), encoding="utf-8")+ claimed = bot_relay.claim_pending_envelopes(root)+ assert [e["id"] for e in claimed] == [env["id"]]+++def test_ttl_config_read_is_lazy_and_defensive(monkeypatch):+ import builtins++ real_import = builtins.__import__++ def _boom(name, *a, **k):+ if name.startswith("hermes_cli"):+ raise ImportError("config unavailable")+ return real_import(name, *a, **k)++ monkeypatch.setattr(builtins, "__import__", _boom)+ assert bot_relay._envelope_ttl_seconds() == bot_relay.DEFAULT_ENVELOPE_TTL_SECONDS+++def test_message_agent_surfaces_runtime_offline_refusal(tmp_path, monkeypatch):+ home = _managed_home(tmp_path)+ bot_relay.write_remote_roster(home, [+ {"profile": "default", "handle": "hermes", "connection_id": "cloud-1",+ "connection_label": "Hermes Cloud", "online": False},+ ])+ monkeypatch.setattr(+ "tools.bot_mode_dm._spawn_delivery",+ lambda *a, **k: json.dumps({"status": "sent"}),+ )+ agent = _FakeAgent(home)+ out = json.loads(message_agent_tool(target="hermes", message="ping", agent=agent))+ assert out.get("reason") == "runtime_offline"+ assert "offline" in out.get("error", "")+ # fail-fast means no envelope was queued+ assert bot_relay.claim_pending_envelopes(home) == []diff --git a/tools/bot_mode_dm.py b/tools/bot_mode_dm.pyindex 03819dcc494..72191dd92ab 100644--- a/tools/bot_mode_dm.py+++ b/tools/bot_mode_dm.py@@ -384,6 +384,7 @@ def _try_relay_delivery("""try:from tools.bot_relay import (+ EnvelopeRefusedError,enqueue_envelope,read_remote_roster,resolve_remote_target,@@ -406,13 +407,19 @@ def _try_relay_delivery(f"'{raw_target}' exists on several connected machines — "f"disambiguate with one of: {forms}.")- envelope = enqueue_envelope(- root,- target=match,- message=f"Message from 🤖 {sender_handle} (@{sender_handle}): {body}",- sender_profile=me,- sender_handle=sender_handle,- )+ try:+ envelope = enqueue_envelope(+ root,+ target=match,+ message=f"Message from 🤖 {sender_handle} (@{sender_handle}): {body}",+ sender_profile=me,+ sender_handle=sender_handle,+ )+ except EnvelopeRefusedError as exc:+ # Fail fast: target definitively offline — nothing was queued.+ # Structured refusal so the agent can distinguish it from a+ # resolution error ('runtime_offline' per the #93091 reason enum).+ return json.dumps({"error": str(exc), "reason": exc.reason})label = f"@{match['handle']} on {match['connection_label'] or match['connection_id']}"return _spawn_delivery(waiter_command(root, envelope), label, task_id=task_id, agent=agentdiff --git a/tools/bot_relay.py b/tools/bot_relay.pyindex 444df02186c..38250bd6739 100644--- a/tools/bot_relay.py+++ b/tools/bot_relay.py@@ -24,8 +24,10 @@ How the relay works (three files under ``<root>/bot_relay/``):The gateway never holds another connection's credentials; the Desktop ownsevery socket and does all cross-connection I/O. Everything here is plain-file plumbing on the gateway's own HERMES root — no network, never raises-out of the public helpers.+file plumbing on the gateway's own HERMES root — no network. The public+helpers never raise, with one deliberate exception: ``enqueue_envelope``+raises ``EnvelopeRefusedError`` when the target is definitively offline, so+the sender fails fast instead of queueing a DM nobody will drain (#93091)."""from __future__ import annotations@@ -58,6 +60,30 @@ REPLY_WAIT_SECONDS = 900# closed, connection died) and are swept opportunistically.STALE_AFTER_SECONDS = 6 * 3600+# Fallback envelope TTL when config is unreachable — mirrors the+# ``bot_mode.envelope_ttl_seconds`` default in hermes_cli/config_defaults.py.+# Envelopes older than the TTL are refused at drain time with a+# 'queued_expired' error reply instead of being delivered late.+DEFAULT_ENVELOPE_TTL_SECONDS = 900++# A roster older than this proves nothing about who is offline: the Desktop+# pushes roster.sync on connection-state changes, so only a recently-written+# roster is treated as an authoritative view for the fail-fast check.+ROSTER_FRESH_SECONDS = 600+++class EnvelopeRefusedError(RuntimeError):+ """``enqueue_envelope`` refused to queue — nothing was written to disk.++ ``reason`` is a stable machine code; ``str(exc)`` is the human text.+ 'runtime_offline' matches the #93091 item-1 failure-reason enum (plain+ literal here so the branches merge cleanly).+ """++ def __init__(self, reason: str, message: str):+ super().__init__(message)+ self.reason = reason+_HANDLE_RE = re.compile(r"^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$")@@ -102,6 +128,11 @@ def _normalize_roster_row(row: Any) -> Optional[dict]:"title": str(row.get("title") or "").strip()[:120],"description": " ".join(str(row.get("description") or "").split())[:160],}+ # Optional explicit liveness flag (additive — the Desktop may push it).+ # Preserved only when it is a real bool so absent stays distinguishable+ # from false: absent == liveness unknown == fail-open on enqueue.+ if isinstance(row.get("online"), bool):+ out["online"] = row["online"]return out@@ -203,6 +234,66 @@ def remote_target_forms(roster: list[dict]) -> list[str]:# ── outbox / replies ─────────────────────────────────────────────────────────+def _envelope_ttl_seconds() -> int:+ """Configured drain TTL (``bot_mode.envelope_ttl_seconds``), lazily read.++ tools/ must not pull heavy CLI config at import time, so the read happens+ per-drain and falls back to ``DEFAULT_ENVELOPE_TTL_SECONDS`` when config+ is unavailable (tests, stripped installs). ``0`` (or negative) disables+ drain-time expiry.+ """+ try:+ from hermes_cli.config import load_config_readonly++ cfg = load_config_readonly() or {}+ val = (cfg.get("bot_mode") or {}).get("envelope_ttl_seconds")+ if val is not None:+ return int(val)+ except Exception:+ logger.debug("bot_relay TTL config read failed", exc_info=True)+ return DEFAULT_ENVELOPE_TTL_SECONDS+++def _target_liveness(root: Path | str, target: dict) -> Optional[bool]:+ """Tri-state liveness for ``target``: True / False / None (unknown).++ Roster rows carry no heartbeat today, so 'definitively offline' is keyed+ off the two signals roster.json actually gives us:++ - an explicit ``online: false`` on the target's row (additive field,+ honored when the Desktop starts pushing it);+ - the target's (connection_id, profile) being ABSENT from a *fresh*+ roster — the Desktop re-pushes the whole roster on connection-state+ changes, so a recently-synced roster that dropped the target means its+ connection is gone.++ A missing, unreadable, or stale (older than ``ROSTER_FRESH_SECONDS``)+ roster proves nothing → None, and callers fail open. Never raises.+ """+ try:+ roster_path = relay_root(root) / ROSTER_FILE+ try:+ age = time.time() - roster_path.stat().st_mtime+ except OSError:+ return None # no roster ever synced — unknown+ if age > ROSTER_FRESH_SECONDS:+ return None # stale view — unknown+ roster = read_remote_roster(root)+ if not roster:+ return None # empty/corrupt roster — treat as unknown, fail open+ key = (str(target.get("connection_id") or ""), str(target.get("profile") or ""))+ for row in roster:+ if (row["connection_id"], row["profile"]) == key:+ online = row.get("online")+ if online is False:+ return False+ return True if online is True else None+ return False # fresh roster no longer lists the target — offline+ except Exception:+ logger.debug("bot_relay liveness check failed", exc_info=True)+ return None++def enqueue_envelope(root: Path | str,*,@@ -211,7 +302,23 @@ def enqueue_envelope(sender_profile: str,sender_handle: str,) -> dict:- """Queue a cross-connection DM for the Desktop relay. Returns envelope."""+ """Queue a cross-connection DM for the Desktop relay. Returns envelope.++ Raises ``EnvelopeRefusedError`` (reason ``'runtime_offline'``) instead of+ writing the outbox file when the target is definitively offline per+ ``_target_liveness``. Unknown liveness enqueues as before (fail-open).+ """+ if _target_liveness(root, target) is False:+ label = (+ f"@{target.get('handle') or target.get('profile') or '?'} on "+ f"{target.get('connection_label') or target.get('connection_id') or '?'}"+ )+ # 'runtime_offline' matches the #93091 item-1 reason enum.+ raise EnvelopeRefusedError(+ "runtime_offline",+ f"{label} is offline right now — the message was NOT queued. "+ "Try again once that machine reconnects to the Desktop.",+ )base = _ensure_dirs(root)envelope = {"id": uuid.uuid4().hex,@@ -233,12 +340,50 @@ def enqueue_envelope(def claim_pending_envelopes(root: Path | str) -> list[dict]:"""Drain the outbox (rename → claimed/, so a second drain can't double-- deliver). Sweeps stale claimed/reply artifacts opportunistically."""+ deliver). Sweeps stale claimed/reply artifacts opportunistically.++ Envelopes older than ``bot_mode.envelope_ttl_seconds`` are NOT delivered:+ each gets an error reply (reason ``'queued_expired'``) so the sender's+ waiter resolves, and its outbox file is removed (#93091 item 2).+ """base = _ensure_dirs(root)_sweep_stale(base)+ ttl = _envelope_ttl_seconds()+ now = time.time()out: list[dict] = []outbox = base / OUTBOX_DIRfor path in sorted(outbox.glob("*.json")):+ if ttl > 0:+ expired = False+ try:+ env = json.loads(path.read_text(encoding="utf-8"))+ created = float(env.get("created_at") or path.stat().st_mtime)+ if now - created > ttl:+ expired = True+ handle = str(env.get("target_handle") or "?")+ conn = str(env.get("target_connection") or "?")+ # 'queued_expired' matches the #93091 item-1 reason enum.+ write_reply(+ root,+ str(env.get("id") or ""),+ error=(+ f"queued message to @{handle} on {conn} expired after "+ f"{ttl}s waiting for the Desktop to drain it — it was "+ "NOT delivered. Resend once the Desktop reconnects."+ ),+ reason="queued_expired",+ )+ except (OSError, ValueError):+ # Unreadable envelope or invalid id: if it already counted as+ # expired, still remove it below; otherwise let the normal+ # claim attempt below deal with it.+ pass+ if expired:+ try:+ path.unlink()+ except OSError:+ pass+ continueclaimed = base / CLAIMED_DIR / path.nametry:os.replace(path, claimed) # atomic claim@@ -253,9 +398,10 @@ def write_reply() -> Path:"""Persist the relayed reply (or delivery error) for the waiter.- ``reason`` is an optional typed failure code (see- ``tools.bot_failure_reasons``); when omitted and ``error`` is non-empty- it is classified from the error text.+``reason`` is an optional typed failure code (see+ ``tools.bot_failure_reasons``, e.g. 'queued_expired'); when omitted and+ ``error`` is non-empty it is classified from the error text. The waiter+ only surfaces the human ``error``."""base = _ensure_dirs(root)safe = str(envelope_id or "").strip()