Skip to content

The agent that grows with you

fix(bot-mode): qualify relayed authors with the sender's connection id

Erosikad3c8bacbe3cd
diff --git a/agent/turn_author.py b/agent/turn_author.py
index 36066fe565f..d1e4c705d99 100644
--- a/agent/turn_author.py
+++ b/agent/turn_author.py
@@ -37,9 +37,17 @@ def _bot_flag(value: Any) -> bool:
return isinstance(value, (bool, int)) and bool(value)
+def bot_author_id(profile: str, origin: Optional[str] = None) -> str:
+ """``bot:<profile>`` for a bot on this machine, ``bot:<origin>/<profile>`` for one reached through a Desktop connection."""
+ origin = (origin or "").strip()
+ return f"bot:{origin}/{profile}" if origin else f"bot:{profile}"
+
+
def parse_turn_author(raw: Any) -> Optional[Dict[str, Any]]:
"""Normalize a dict or JSON string into ``{"id", "name", "is_bot"}``; None for anything else or without id and name.
- The id is whatever the transport knows the sender by: ``bot:<profile>`` on bot-mode deliveries, the platform user id elsewhere."""
+ The id is whatever the transport knows the sender by: ``bot:<profile>`` on bot-mode deliveries,
+ ``bot:<connection>/<profile>`` when the Desktop relayed it from another machine, the platform user id elsewhere.
+ An ``origin`` field qualifies a bare ``bot:<profile>`` id the same way."""
try:
if isinstance(raw, (str, bytes)):
raw = json.loads(raw)
@@ -52,6 +60,9 @@ def parse_turn_author(raw: Any) -> Optional[Dict[str, Any]]:
}
if author["id"] is None and author["name"] is None:
return None
+ origin = _clean_text(raw.get("origin"))
+ if origin and author["id"] and author["id"].startswith("bot:") and "/" not in author["id"]:
+ author["id"] = _clean_text(bot_author_id(author["id"][len("bot:"):], origin))
return author
except Exception:
return None
diff --git a/apps/desktop/src/plugins/hermes-bots/relay.test.ts b/apps/desktop/src/plugins/hermes-bots/relay.test.ts
index 55ba196b35d..84cd45a7a6f 100644
--- a/apps/desktop/src/plugins/hermes-bots/relay.test.ts
+++ b/apps/desktop/src/plugins/hermes-bots/relay.test.ts
@@ -511,6 +511,31 @@ describe('the drain loop wires drain → deliver → reply', () => {
stopBotRelay()
})
+ it('tells the target which connection the sender is on, so its author id names the machine', async () => {
+ const calls = respondWith(call => {
+ if (call.method === 'bot_relay.outbox.drain') {
+ return {
+ envelopes: call.connectionId === 'a' ? [{ ...envelope, from_handle: 'scout', from_profile: 'scout' }] : []
+ }
+ }
+
+ return { reply: 'ok' }
+ })
+
+ const { startBotRelay, stopBotRelay } = await loadRelay()
+
+ startBotRelay()
+ await pushAndSettle()
+
+ expect(calls.find(call => call.method === 'bot_relay.deliver')?.params).toMatchObject({
+ from_connection: 'a',
+ from_handle: 'scout',
+ from_profile: 'scout'
+ })
+
+ stopBotRelay()
+ })
+
it('still posts a reply when the target connection is gone — the waiter must never dangle', async () => {
const calls = respondWith(call =>
call.method === 'bot_relay.outbox.drain'
diff --git a/apps/desktop/src/plugins/hermes-bots/relay.ts b/apps/desktop/src/plugins/hermes-bots/relay.ts
index 50772744adc..4f60d85fc7e 100644
--- a/apps/desktop/src/plugins/hermes-bots/relay.ts
+++ b/apps/desktop/src/plugins/hermes-bots/relay.ts
@@ -402,9 +402,11 @@ async function drainRelayOutboxes() {
{
profile: String(envelope?.target_profile || ''),
message: String(envelope?.message || ''),
- // The target gateway sets HERMES_TURN_AUTHOR on the delivery turn from these two.
+ // The target gateway sets HERMES_TURN_AUTHOR on the delivery turn from these; the
+ // sender's connection id qualifies a bot on another machine.
from_profile: String(envelope?.from_profile || ''),
- from_handle: String(envelope?.from_handle || '')
+ from_handle: String(envelope?.from_handle || ''),
+ from_connection: String(sender.id)
},
RELAY_DELIVER_TIMEOUT_MS
)
diff --git a/tests/agent/test_turn_author.py b/tests/agent/test_turn_author.py
index 166c6db8dff..af1cbff6c37 100644
--- a/tests/agent/test_turn_author.py
+++ b/tests/agent/test_turn_author.py
@@ -26,8 +26,13 @@ class TestParseTurnAuthor:
({"id": "bot:\x00al\x1bpha\n", "name": "Al\tpha\r"}, {"id": "bot:alpha", "name": "Alpha", "is_bot": False}),
({"id": "bot:alpha", "name": f"{FAMILY} Al\u00a0pha\u00a0"}, {"id": "bot:alpha", "name": f"{FAMILY} Al\u00a0pha", "is_bot": False}),
({"id": "x" * 500, "name": "y" * 201}, {"id": "x" * 200, "name": "y" * 200, "is_bot": False}),
+ ({"id": "bot:cloud-1/alpha", "name": "Alpha", "is_bot": True}, {"id": "bot:cloud-1/alpha", "name": "Alpha", "is_bot": True}),
+ ({"id": "bot:alpha", "name": "Alpha", "is_bot": True, "origin": " cloud-1 "}, {"id": "bot:cloud-1/alpha", "name": "Alpha", "is_bot": True}),
+ ({"id": "bot:cloud-1/alpha", "name": "Alpha", "is_bot": True, "origin": "cloud-2"}, {"id": "bot:cloud-1/alpha", "name": "Alpha", "is_bot": True}),
+ ({"id": "5551234", "name": "Alpha", "is_bot": True, "origin": "cloud-1"}, {"id": "5551234", "name": "Alpha", "is_bot": True}),
], ids=["dict", "json string", "missing id", "non-string id", "empty id", "control characters stripped",
- "format characters and nbsp survive", "oversize fields capped"])
+ "format characters and nbsp survive", "oversize fields capped", "connection-qualified id survives",
+ "origin qualifies a bare bot id", "origin never requalifies", "origin leaves a platform id alone"])
def test_fields_are_normalized(self, raw, expected):
assert parse_turn_author(raw) == expected
@@ -70,6 +75,7 @@ class TestEnvCarrier:
@pytest.mark.parametrize("author, expected", [
({"id": "bot:coder", "name": "coder", "is_bot": True}, "a2a:bot:coder"),
+ ({"id": "bot:cloud-1/coder", "name": "coder", "is_bot": True}, "a2a:bot:cloud-1/coder"),
({"id": "5551234", "name": "SomeBot", "is_bot": True}, "a2a:5551234"),
({"id": "111222", "name": "Alice", "is_bot": False}, None),
({"id": None, "name": "mystery", "is_bot": True}, None),
diff --git a/tests/gateway/test_api_server_runs.py b/tests/gateway/test_api_server_runs.py
index 63da3ac15dc..273ef8c91de 100644
--- a/tests/gateway/test_api_server_runs.py
+++ b/tests/gateway/test_api_server_runs.py
@@ -269,8 +269,10 @@ class TestStartRun:
@pytest.mark.parametrize("body, expected", [
({"input": "hello", "author": {"id": "bot:dixie", "name": " dixie ", "is_bot": True, "role": "admin"}},
{"id": "bot:dixie", "name": "dixie", "is_bot": True}),
+ ({"input": "hello", "author": {"id": "bot:dixie", "name": "dixie", "is_bot": True, "origin": "cloud-1"}},
+ {"id": "bot:cloud-1/dixie", "name": "dixie", "is_bot": True}),
({"input": "hello"}, "absent"),
- ], ids=["author", "no author"])
+ ], ids=["author", "author with origin", "no author"])
async def test_start_passes_normalized_author_to_run_conversation(self, adapter, body, expected):
"""A body ``author`` reaches ``run_conversation`` normalized; it labels memory only. Without one the
call keeps today's shape."""
diff --git a/tests/tools/test_bot_relay.py b/tests/tools/test_bot_relay.py
index 4ac617b2091..c880c8c301d 100644
--- a/tests/tools/test_bot_relay.py
+++ b/tests/tools/test_bot_relay.py
@@ -598,6 +598,15 @@ def test_delivery_turn_author_from_envelope_sender_fields():
assert bot_relay.delivery_turn_author(None, None) is None
+def test_delivery_turn_author_qualifies_a_remote_sender_by_its_connection():
+ """Two machines can both run ``ops``; the Desktop's connection id keeps them apart, and its own gateway
+ (``local``) keeps the bare id."""
+ remote = bot_relay.delivery_turn_author("ops", "ops-bot", "cloud-1")
+ assert remote == {"id": "bot:cloud-1/ops", "name": "ops-bot", "is_bot": True}
+ assert bot_relay.delivery_turn_author("ops", "ops-bot", "local") == {"id": "bot:ops", "name": "ops-bot", "is_bot": True}
+ assert bot_relay.delivery_turn_author("ops", "ops-bot", "") == {"id": "bot:ops", "name": "ops-bot", "is_bot": True}
+
+
def test_delivery_env_carries_only_the_given_author(monkeypatch):
"""The dispatcher's own HERMES_TURN_AUTHOR never reaches the child: dropped without an author, replaced with one."""
from agent.turn_author import TURN_AUTHOR_ENV
diff --git a/tests/tui_gateway/test_bot_relay_methods.py b/tests/tui_gateway/test_bot_relay_methods.py
index a0fcd073ed9..04f9deb9227 100644
--- a/tests/tui_gateway/test_bot_relay_methods.py
+++ b/tests/tui_gateway/test_bot_relay_methods.py
@@ -215,8 +215,10 @@ def fake_runs(monkeypatch):
@pytest.mark.parametrize("sender, expected", [
({"from_profile": "scout", "from_handle": "scout"}, {"id": "bot:scout", "name": "scout", "is_bot": True}),
+ ({"from_profile": "scout", "from_handle": "scout", "from_connection": "cloud-1"},
+ {"id": "bot:cloud-1/scout", "name": "scout", "is_bot": True}),
({}, None),
-], ids=["sender fields", "no sender fields"])
+], ids=["sender fields", "sender on another connection", "no sender fields"])
def test_deliver_child_env_carries_the_envelope_sender_on_every_attempt(home, monkeypatch, fake_runs, sender, expected):
"""HERMES_TURN_AUTHOR on the child comes from the envelope's sender fields alone: the retry gets the same
author, and without sender fields a stale author on the gateway's own environment never reaches the child."""
diff --git a/tools/bot_relay.py b/tools/bot_relay.py
index 5245e3ed4c6..ec0abc685a8 100644
--- a/tools/bot_relay.py
+++ b/tools/bot_relay.py
@@ -400,13 +400,19 @@ class DeliveryAuthor:
return f"DeliveryAuthor({self.author!r})"
-def delivery_turn_author(from_profile: Any, from_handle: Any) -> Optional[dict]:
- """The author of a relayed DM's recipient turn, built from the envelope's sender fields.
+def delivery_turn_author(from_profile: Any, from_handle: Any, from_connection: Any = None) -> Optional[dict]:
+ """The author of a relayed DM's recipient turn, built from the envelope's sender fields. A sender on another
+ machine is qualified by the Desktop's id for its connection, so two machines' ``scout`` profiles stay distinct.
None when the envelope names no sender, so an unattributed delivery stays unattributed."""
+ from agent.turn_author import bot_author_id
+
profile = str(from_profile or "").strip()
if not profile:
return None
- return {"id": f"bot:{profile}", "name": str(from_handle or "").strip() or profile, "is_bot": True}
+ connection = str(from_connection or "").strip()
+ # The Desktop names its own gateway "local"; that sender keeps the bare id local deliveries always had.
+ origin = connection if connection != "local" else ""
+ return {"id": bot_author_id(profile, origin), "name": str(from_handle or "").strip() or profile, "is_bot": True}
def delivery_env(author: Optional[dict]) -> dict[str, str]:
diff --git a/tui_gateway/methods_bot_relay.py b/tui_gateway/methods_bot_relay.py
index 5df99273ff9..41830b2af41 100644
--- a/tui_gateway/methods_bot_relay.py
+++ b/tui_gateway/methods_bot_relay.py
@@ -92,7 +92,7 @@ def _(rid, params: dict, _root=_relay_root, _run=_run_delivery) -> dict:
record, _session_lookup_key(record, fallback=live_sid)) == BOT_CHAT_TITLE), "")
# The Desktop forwards the envelope's sender. The author labels memory only and grants nothing.
from tools.bot_relay import DeliveryAuthor, delivery_env, delivery_turn_author
- author = delivery_turn_author(params.get("from_profile"), params.get("from_handle"))
+ author = delivery_turn_author(params.get("from_profile"), params.get("from_handle"), params.get("from_connection"))
if live_sid:
# queued=True: a teammate's DM runs as the NEXT turn and never interrupts or steers a
# turn in flight (the default busy mode does); arrivals queue in order.