Skip to content

The agent that grows with you

fix(bot-mode): a remote default is addressable by its title slug and signs relayed DMs reply-safely

teknium127e30a28d599
diff --git a/tests/tools/test_bot_relay.py b/tests/tools/test_bot_relay.py
index 2119ba45691..79192cb5d60 100644
--- a/tests/tools/test_bot_relay.py
+++ b/tests/tools/test_bot_relay.py
@@ -406,6 +406,39 @@ def test_relay_route_ambiguous_target_errors_with_forms(tmp_path, monkeypatch):
assert out2.get("status") == "queued"
+def test_remote_default_is_addressable_by_its_title_slug(tmp_path, monkeypatch):
+ """A remote ``default`` is ``@hermes`` like every gateway's own, so its Bot Mode title is the only
+ bare form that singles it out: ``message_agent`` accepts the slug, the prompt roster offers it
+ (never bare ``@hermes``, which is the LOCAL default), and the form does not depend on roster order."""
+ from tools import bot_mode_probe
+
+ home = _managed_home(tmp_path)
+ rows = [
+ {"profile": "default", "handle": "hermes", "connection_id": "vps-1", "title": "CoS Bot"},
+ {"profile": "default", "handle": "hermes", "connection_id": "cloud-1", "title": "Ops Bot"},
+ {"profile": "cos-bot", "handle": "cos-bot", "connection_id": "cloud-1", "title": "Other"},
+ ]
+ monkeypatch.setattr("tools.bot_mode_dm._spawn_delivery", lambda *a, **k: json.dumps({"status": "queued"}))
+ agent = _FakeAgent(home)
+ for order in (rows, rows[::-1]):
+ bot_relay.write_remote_roster(home, order)
+ roster = bot_relay.read_remote_roster(home)
+ forms = dict(zip((r["connection_id"] + "/" + r["profile"] for r in roster),
+ bot_relay.remote_target_forms(roster, bot_mode_probe.local_taken_forms(home))))
+ # an exact handle beats a colliding title slug; the collided title falls back to the qualified form
+ assert forms == {"cloud-1/cos-bot": "cos-bot", "vps-1/default": "hermes@vps-1", "cloud-1/default": "ops-bot"}
+ assert bot_relay.resolve_remote_target("cos-bot", roster)["profile"] == "cos-bot"
+ out = json.loads(message_agent_tool(target="@ops-bot", message="ping", agent=agent))
+ assert out.get("status") == "queued"
+ [env] = bot_relay.claim_pending_envelopes(home)
+ assert (env["target_connection"], env["target_profile"]) == ("cloud-1", "default")
+ # a bare @hermes from the local default is the two remote defaults — offered under their reply-safe forms
+ err = json.loads(message_agent_tool(target="hermes", message="ping", agent=agent))["error"]
+ assert "hermes@vps-1" in err and "ops-bot" in err
+ section = bot_mode_probe.get_bot_mode_protocol_section(home)
+ assert "`@ops-bot`" in section and "`@hermes@vps-1`" in section and "- `@hermes` —" not in section
+
+
def test_unknown_target_error_mentions_connected_machines(tmp_path):
home = _managed_home(tmp_path)
agent = _FakeAgent(home)
@@ -423,7 +456,8 @@ def test_protocol_section_lists_remote_teammates(tmp_path):
])
section = bot_mode_probe.get_bot_mode_protocol_section(home, force_refresh=True)
assert "OTHER connected machines" in section
- assert "`@hermes` — on Hermes Cloud — Moxie" in section
+ # Offered under its title slug: bare `@hermes` is THIS gateway's own default (#103731).
+ assert "`@moxie` — on Hermes Cloud — Moxie" in section
def test_capability_fingerprint_changes_with_relay_roster(tmp_path):
diff --git a/tests/tui_gateway/test_bot_relay_methods.py b/tests/tui_gateway/test_bot_relay_methods.py
index fdc99135ce8..76512f46220 100644
--- a/tests/tui_gateway/test_bot_relay_methods.py
+++ b/tests/tui_gateway/test_bot_relay_methods.py
@@ -111,6 +111,34 @@ def test_deliver_requires_params(home):
assert "error" in err
+def test_deliver_restamps_relayed_sender_with_a_reply_safe_handle(home, monkeypatch):
+ """#103731: the sender signs with its bare @handle, which for another machine's ``default`` is
+ ``@hermes`` — the recipient's OWN default. The delivered text names the sender by the form this
+ gateway resolves back to it: its title slug when the local relay roster carries it, else
+ ``handle@connection``. A stamp that is not the relay's is left alone."""
+ seen = []
+
+ class _Proc:
+ returncode, stderr, stdout = 0, "", "ok"
+
+ def _fake_run(argv, **_kwargs):
+ seen.append(Path(argv[argv.index("--query-file") + 1]).read_text(encoding="utf-8"))
+ return _Proc()
+
+ monkeypatch.setattr("subprocess.run", _fake_run)
+ bot_relay.write_remote_roster(home, [
+ {"profile": "default", "handle": "hermes", "connection_id": "vps-1", "title": "CoS Bot"},
+ ])
+ stamp = "Message from 🤖 CoS Bot (@hermes): are we done?"
+ sender = {"from_profile": "default", "from_handle": "hermes", "from_connection": "vps-1"}
+ _result(srv._methods["bot_relay.deliver"](1, {"profile": "ops", "message": stamp, **sender}))
+ _result(srv._methods["bot_relay.deliver"](2, {"profile": "ops", "message": stamp, **sender, "from_connection": "lan-2"}))
+ _result(srv._methods["bot_relay.deliver"](3, {"profile": "ops", "message": "plain text (@hermes): x", **sender}))
+ assert seen == ["Message from 🤖 CoS Bot (@cos-bot): are we done?",
+ "Message from 🤖 CoS Bot (@hermes@lan-2): are we done?",
+ "plain text (@hermes): x"]
+
+
def test_deliver_relays_empty_reply_for_a_bare_silence_marker(home, monkeypatch):
"""#110782: the subprocess transport applies the gateway's silence rule — a bare marker
relays as "", prose that merely mentions one is relayed verbatim."""
diff --git a/tools/bot_mode_dm.py b/tools/bot_mode_dm.py
index 2c753fcba0a..7ccf6acefab 100644
--- a/tools/bot_mode_dm.py
+++ b/tools/bot_mode_dm.py
@@ -290,9 +290,10 @@ def _try_relay_delivery(root: Path, raw_target: str, content: str, me: str, *,
to drain; a background waiter is spawned immediately so the relayed reply wakes
the sender through the standard completion-notification path."""
try:
- from tools.bot_mode_probe import _handle
+ from tools.bot_mode_probe import _handle, local_taken_forms
from tools.bot_relay import (
- EnvelopeRefusedError, enqueue_envelope, read_remote_roster, resolve_remote_target, waiter_command,
+ EnvelopeRefusedError, _target_aliases, enqueue_envelope, read_remote_roster, remote_target_forms,
+ resolve_remote_target, waiter_command,
)
roster = read_remote_roster(root)
@@ -300,8 +301,9 @@ def _try_relay_delivery(root: Path, raw_target: str, content: str, me: str, *,
if match is None:
return None
if match == "ambiguous":
- want = raw_target.strip().lstrip("@").lower()
- forms = ", ".join(f"{r['handle']}@{r['connection_id']}" for r in roster if r["handle"].lower() == want)
+ want = raw_target.strip().lstrip("@").partition("@")[0].lower()
+ forms = ", ".join(form for r, form in zip(roster, remote_target_forms(roster, local_taken_forms(root)))
+ if want in _target_aliases(r))
return _err(f"'{raw_target}' exists on several connected machines — disambiguate with one of: {forms}.")
try:
envelope = enqueue_envelope(root, target=match, message=content, sender_profile=me, sender_handle=_handle(me))
diff --git a/tools/bot_mode_probe.py b/tools/bot_mode_probe.py
index 2dca99377e4..ea0c3f33c11 100644
--- a/tools/bot_mode_probe.py
+++ b/tools/bot_mode_probe.py
@@ -224,6 +224,12 @@ def _remote_roster(root: Path) -> list[dict]:
return _swallow(_read, [])
+def local_taken_forms(root: Path) -> set[str]:
+ """Bare forms this gateway's own profiles answer to (handles + friendly-name slugs); a remote
+ row must not be offered under any of them, since local resolution wins (``_resolve_local_name``)."""
+ return {_handle(name) for name, _d in _roster(root)} | set(local_alias_map(root))
+
+
def _remote_paragraph(root: Path) -> str:
"""Addendum for agents on OTHER connected machines; only when the relay roster is non-empty."""
roster = _remote_roster(root)
@@ -233,7 +239,7 @@ def _remote_paragraph(root: Path) -> str:
lines = [
_bullet(f"@{form}", f"on {row['connection_label'] or row['connection_id']}", row["title"], row["description"])
- for row, form in zip(roster, remote_target_forms(roster))
+ for row, form in zip(roster, remote_target_forms(roster, local_taken_forms(root)))
]
return (
"\n\nTeammates on OTHER connected machines (reachable through the "
diff --git a/tools/bot_relay.py b/tools/bot_relay.py
index 9944652262e..6794f4beeb9 100644
--- a/tools/bot_relay.py
+++ b/tools/bot_relay.py
@@ -26,7 +26,7 @@ import uuid
from pathlib import Path
from typing import Any, Iterator, Mapping, Optional
-from tools.bot_mode_probe import _default_home, _hermes_root
+from tools.bot_mode_probe import _default_home, _hermes_root, alias_forms
from utils import atomic_json_write
logger = logging.getLogger(__name__)
@@ -166,25 +166,84 @@ def read_remote_roster(root: Path | str) -> list[dict]:
return []
+def _target_ids(row: dict) -> set[str]:
+ """Lower-cased routing ids of a roster row: its @handle and profile folder id."""
+ return {row["handle"].lower(), row["profile"].lower()}
+
+
+def _target_aliases(row: dict) -> set[str]:
+ """Every lower-cased bare form that addresses ``row``: routing ids plus the Bot Mode title's
+ mention slugs (``"CoS Bot"`` → ``cos-bot``/``cosbot``, what the Desktop picker inserts). A remote
+ ``default`` is ``@hermes`` on every gateway, so its title is the only bare form that can single it out."""
+ return _target_ids(row) | alias_forms(row.get("title") or "")
+
+
def resolve_remote_target(raw_target: str, roster: list[dict]) -> Any:
- """Matched row for a bare handle/profile (unique across connections) or
- ``<handle|profile>@<connection-id>``; ``"ambiguous"`` for a bare form on several connections; None otherwise."""
+ """Matched row for a bare handle/profile/title slug (unique across connections) or
+ ``<handle|profile|title-slug>@<connection-id>``; ``"ambiguous"`` for a bare form on several
+ connections; None otherwise. An exact handle/profile match beats a title slug, so a title
+ colliding with another row's handle never steals it."""
want, at, conn = (p.strip() for p in str(raw_target or "").strip().lstrip("@").partition("@"))
if not want or (at and not conn):
return None
- matches = [row for row in roster if want.lower() in (row["handle"].lower(), row["profile"].lower())
- and (not conn or row["connection_id"].lower() == conn.lower())]
+ want = want.lower()
+ rows = [row for row in roster if not conn or row["connection_id"].lower() == conn.lower()]
+ matches = [row for row in rows if want in _target_ids(row)] or [row for row in rows if want in _target_aliases(row)]
if not matches:
return None
return matches[0] if len(matches) == 1 else "ambiguous"
-def remote_target_forms(roster: list[dict]) -> list[str]:
- """Target strings: bare handle when unique across connections, else
- ``handle@connection`` (mirrors ``resolve_remote_target``)."""
- handles = [row["handle"].lower() for row in roster]
- return [f"{row['handle']}@{row['connection_id']}" if handles.count(h) > 1 else row["handle"]
- for row, h in zip(roster, handles)]
+def _title_slug(row: dict) -> str:
+ """The Bot Mode title's slug form (``"CoS Bot"`` → ``cos-bot``, what the picker inserts); "" when the
+ title is empty, reserved (a bot titled "Hermes") or not a valid handle."""
+ title = str(row.get("title") or "")
+ slug = re.sub(r"[^a-z0-9_-]+", "-", title.strip().lower()).strip("-")
+ return slug if slug in alias_forms(title) else ""
+
+
+def remote_target_forms(roster: list[dict], local_taken: "set[str] | frozenset[str]" = frozenset()) -> list[str]:
+ """One unambiguous target string per row, shortest first: the bare handle when no other remote
+ row and no LOCAL profile (``local_taken``: this gateway's handles and friendly-name slugs) answers
+ to it; else the title slug under the same test (a remote ``default`` titled "CoS Bot" is
+ ``@cos-bot``, since bare ``@hermes`` is always this gateway's own default); else
+ ``handle@connection``. Mirrors ``resolve_remote_target``."""
+ taken = {form.lower() for form in local_taken}
+ id_claims: dict[str, int] = {}
+ alias_claims: dict[str, int] = {}
+ for row in roster:
+ for form in _target_ids(row):
+ id_claims[form] = id_claims.get(form, 0) + 1
+ for form in _target_aliases(row):
+ alias_claims[form] = alias_claims.get(form, 0) + 1
+
+ def _form(row: dict) -> str:
+ # The handle needs only be unique among routing ids (resolution gives it precedence over a
+ # colliding title); a title slug must be unique among every alias.
+ for candidate, claims in ((row["handle"], id_claims), (_title_slug(row), alias_claims)):
+ if candidate and candidate.lower() not in taken and claims.get(candidate.lower(), 0) == 1:
+ return candidate
+ return f"{row['handle']}@{row['connection_id']}"
+
+ return [_form(row) for row in roster]
+
+
+_SENDER_STAMP_RE = re.compile(r"^(Message from 🤖 .+? \(@)([A-Za-z0-9_-]+)(\): )", re.DOTALL)
+
+
+def qualify_sender_stamp(message: str, from_handle: Any, from_connection: Any, roster: list[dict],
+ local_taken: "set[str] | frozenset[str]" = frozenset()) -> str:
+ """Rewrite a relayed DM's ``Message from 🤖 <name> (@<handle>):`` stamp so the handle is the
+ form THIS gateway can reply to: the sender's row in the local relay roster as
+ ``remote_target_forms`` renders it, else ``handle@connection``. A relayed ``@hermes`` is another
+ machine's default — left bare, a reply lands on the recipient's own default (#103731)."""
+ handle, conn = str(from_handle or "").strip().lstrip("@"), str(from_connection or "").strip()
+ match = _SENDER_STAMP_RE.match(str(message or ""))
+ if not match or not conn or not _HANDLE_RE.match(handle) or not _HANDLE_RE.match(conn):
+ return message
+ forms = dict(zip(((r["connection_id"].lower(), r["handle"].lower()) for r in roster), remote_target_forms(roster, local_taken)))
+ form = forms.get((conn.lower(), handle.lower())) or f"{handle}@{conn}"
+ return f"{match.group(1)}{form}{match.group(3)}{message[match.end():]}"
def _envelope_ttl_seconds() -> int:
diff --git a/tui_gateway/methods_bot_relay.py b/tui_gateway/methods_bot_relay.py
index c638e057b9c..4ffb0ed27ff 100644
--- a/tui_gateway/methods_bot_relay.py
+++ b/tui_gateway/methods_bot_relay.py
@@ -79,6 +79,12 @@ def _(rid, params: dict, _root=_relay_root, _run=_run_delivery,
resolved = "default" if profile.lower() == "hermes" else profile
if resolved not in known:
return _err(rid, 4092, f"no profile '{profile}' on this gateway")
+ # The sender stamped itself with its bare @handle; a relayed "@hermes" is ANOTHER machine's
+ # default, so re-stamp it with the form this gateway can reply to (#103731).
+ from tools.bot_mode_probe import local_taken_forms
+ from tools.bot_relay import qualify_sender_stamp, read_remote_roster
+ message = qualify_sender_stamp(message, params.get("from_handle"), params.get("from_connection"),
+ read_remote_roster(root), local_taken_forms(root))
# When THIS gateway already hosts the target's Bot Chat live, the subprocess transport is
# fenced out by the single-owner lease and the payload dropped. Land the DM in the live
diff --git a/website/docs/user-guide/bot-mode.md b/website/docs/user-guide/bot-mode.md
index 1aa5db88761..ef6c1d240e0 100644
--- a/website/docs/user-guide/bot-mode.md
+++ b/website/docs/user-guide/bot-mode.md
@@ -218,6 +218,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. 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`)