Skip to content

The agent that grows with you

fix(bot-mode): qualify the peer-dm author id with the sender's hostname

Erosika091ac34ba935
diff --git a/agent/turn_author.py b/agent/turn_author.py
index d1e4c705d99..c837f9b2660 100644
--- a/agent/turn_author.py
+++ b/agent/turn_author.py
@@ -8,6 +8,7 @@ from __future__ import annotations
import json
import os
+import socket
import unicodedata
from typing import Any, Dict, Mapping, MutableMapping, Optional
@@ -38,15 +39,27 @@ def _bot_flag(value: Any) -> bool:
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."""
+ """``bot:<profile>`` for a bot on the recipient's own install, ``bot:<origin>/<profile>`` for one on another
+ install. The origin is the Desktop's connection id on a relayed dm and the sender's hostname on a peer dm."""
origin = (origin or "").strip()
return f"bot:{origin}/{profile}" if origin else f"bot:{profile}"
+def local_origin() -> str:
+ """This machine's hostname as an author-id origin, cleaned like any author field. Empty when unknown."""
+ try:
+ host = socket.gethostname()
+ except Exception:
+ return ""
+ # A slash would split the id into a different origin and profile at parse time.
+ return (_clean_text(host) or "").replace("/", "")
+
+
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,
- ``bot:<connection>/<profile>`` when the Desktop relayed it from another machine, the platform user id elsewhere.
+ The id is whatever the transport knows the sender by: ``bot:<profile>`` on a bot-mode delivery inside one
+ install, ``bot:<connection>/<profile>`` when the Desktop relayed it from another machine,
+ ``bot:<hostname>/<profile>`` on a peer dm, the platform user id elsewhere.
An ``origin`` field qualifies a bare ``bot:<profile>`` id the same way."""
try:
if isinstance(raw, (str, bytes)):
diff --git a/tests/agent/test_turn_author.py b/tests/agent/test_turn_author.py
index af1cbff6c37..966b3502062 100644
--- a/tests/agent/test_turn_author.py
+++ b/tests/agent/test_turn_author.py
@@ -7,6 +7,7 @@ import pytest
from agent.turn_author import (
TURN_AUTHOR_ENV,
a2a_key,
+ local_origin,
parse_turn_author,
take_turn_author_from_env,
turn_author_env,
@@ -83,3 +84,21 @@ class TestEnvCarrier:
])
def test_a2a_key_names_a_bot_authors_turns(author, expected):
assert a2a_key(author) == expected
+
+
[email protected]("host, expected", [
+ ("eri-mac.local", "eri-mac.local"),
+ (" eri/mac\x00.local\n", "erimac.local"),
+ ("", ""),
+], ids=["plain", "slash and control characters dropped", "empty"])
+def test_local_origin_is_the_cleaned_hostname(monkeypatch, host, expected):
+ monkeypatch.setattr("socket.gethostname", lambda: host)
+ assert local_origin() == expected
+
+
+def test_local_origin_is_empty_when_the_hostname_lookup_fails(monkeypatch):
+ def _no_host():
+ raise OSError("no hostname")
+
+ monkeypatch.setattr("socket.gethostname", _no_host)
+ assert local_origin() == ""
diff --git a/tests/tools/test_bot_mode_dm.py b/tests/tools/test_bot_mode_dm.py
index 5b2cd49a1da..45565e51cee 100644
--- a/tests/tools/test_bot_mode_dm.py
+++ b/tests/tools/test_bot_mode_dm.py
@@ -316,6 +316,7 @@ def test_peer_delivery_command_pins_registry_profile_for_secondary_bots(
def test_peer_delivery_command(tmp_path, monkeypatch):
calls = _capture_spawn(monkeypatch)
+ monkeypatch.setattr("socket.gethostname", lambda: "eri-mac.local")
home = _managed_home(tmp_path, peers=("spark",))
agent = _FakeAgent(home, title="Bot Chat")
@@ -328,7 +329,7 @@ def test_peer_delivery_command(tmp_path, monkeypatch):
assert mode == "stdin"
assert transport_argv == ["hermes", "-p", "default", "peer", "dm", "spark/researcher"]
# the peer child reads the author from its env and forwards it in the request body
- assert _runner_author(calls[0]["command"]) == {"id": "bot:default", "name": "hermes", "is_bot": True}
+ assert _runner_author(calls[0]["command"]) == {"id": "bot:eri-mac.local/default", "name": "hermes", "is_bot": True}
# bare peer name targets the peer's main agent
result2 = json.loads(
@@ -340,6 +341,35 @@ def test_peer_delivery_command(tmp_path, monkeypatch):
assert transport_argv == ["hermes", "-p", "default", "peer", "dm", "spark"]
+def test_peer_delivery_author_carries_the_sender_hostname_and_local_stays_bare(tmp_path, monkeypatch):
+ """A peer dm crosses installs, so its author id is ``bot:<hostname>/<profile>``: the peer's own ``coder`` and a
+ remote ``coder`` must not share one id. A teammate on this install still sees the bare ``bot:coder``."""
+ calls = _capture_spawn(monkeypatch)
+ monkeypatch.setattr("socket.gethostname", lambda: " eri/mac\x00.local ")
+ home = _managed_home(tmp_path, teammates=("researcher", "coder"), peers=("spark",))
+ agent = _FakeAgent(home / "profiles" / "coder", title="Bot Chat")
+
+ assert json.loads(bot_mode_dm.message_agent_tool(target="spark", message="ping", agent=agent))["status"] == "sent"
+ assert json.loads(bot_mode_dm.message_agent_tool(target="researcher", message="ping", agent=agent))["status"] == "sent"
+
+ assert _runner_author(calls[0]["command"]) == {"id": "bot:erimac.local/coder", "name": "coder", "is_bot": True}
+ assert _runner_author(calls[1]["command"]) == {"id": "bot:coder", "name": "coder", "is_bot": True}
+
+
+def test_peer_delivery_author_stays_bare_when_the_hostname_is_unknown(tmp_path, monkeypatch):
+ calls = _capture_spawn(monkeypatch)
+
+ def _no_host():
+ raise OSError("no hostname")
+
+ monkeypatch.setattr("socket.gethostname", _no_host)
+ home = _managed_home(tmp_path, peers=("spark",))
+ agent = _FakeAgent(home, title="Bot Chat")
+
+ assert json.loads(bot_mode_dm.message_agent_tool(target="spark", message="ping", agent=agent))["status"] == "sent"
+ assert _runner_author(calls[0]["command"]) == {"id": "bot:default", "name": "hermes", "is_bot": True}
+
+
def test_named_profile_sender_prefix(tmp_path, monkeypatch):
"""A named-profile bot signs with its own handle, not @hermes."""
calls = _capture_spawn(monkeypatch)
@@ -588,7 +618,7 @@ def test_delivery_main_rejects_invalid_cli(args, monkeypatch):
@pytest.mark.parametrize("mode, author", [
- ("stdin", {"id": "bot:coder", "name": "coder", "is_bot": True}),
+ ("stdin", {"id": "bot:eri-mac.local/coder", "name": "coder", "is_bot": True}),
("query-file", {"id": "bot:coder", "name": "coder", "is_bot": True}),
("query-file", None),
], ids=["stdin", "query-file", "no author"])
diff --git a/tools/bot_mode_dm.py b/tools/bot_mode_dm.py
index ee8c022bad1..8366a8a4fad 100644
--- a/tools/bot_mode_dm.py
+++ b/tools/bot_mode_dm.py
@@ -224,12 +224,15 @@ def message_agent_tool(target: str = "", message: str = "", task_id: Optional[st
if peer_name not in peers:
return _roster_err(f"No registered peer named '{peer_name}'.")
dm_target = f"{peer_name}/{peer_profile}" if peer_profile else peer_name
+ # A peer dm crosses installs: qualify the id with this host so the peer's own '<me>' stays distinct.
+ from agent.turn_author import bot_author_id, local_origin
+ peer_author = {**author, "id": bot_author_id(me, local_origin())}
# Pin the registry-owning profile: `hermes peer` resolves bot_peers via the profile-scoped
# load_config(), while the roster above reads the machine-root config — the CLI must run
# in that same profile or a secondary-profile bot sees an empty registry.
return _start_delivery(["hermes", "-p", _self_profile_name(root), "peer", "dm", dm_target], content,
f"@{peer_profile or peer_name} on peer '{peer_name}'", stdin_file=True,
- author=author, **delivery)
+ author=peer_author, **delivery)
# Local teammate.
is_local_shape = bool(_LOCAL_TARGET_RE.match(raw_target))