Skip to content

The agent that grows with you

fix(bot-mode): message_agent resolves friendly names and Desktop @-slugs to folder ids

teknium1002df670f81c
diff --git a/tests/tools/test_bot_mode_dm.py b/tests/tools/test_bot_mode_dm.py
index 1de28f47ad8..04504852148 100644
--- a/tests/tools/test_bot_mode_dm.py
+++ b/tests/tools/test_bot_mode_dm.py
@@ -312,6 +312,54 @@ def test_local_delivery_command_and_ack(tmp_path, monkeypatch):
assert '$(and this is not shell)' in content
+def _rename(home: Path, folder: str, *, display_name: str = "", title: str = "") -> None:
+ lines = ["description: teammate for tests", "ui_meta:", " hermes-bots:", " shape: cloud"]
+ if title:
+ lines.append(f" title: {title}")
+ if display_name:
+ lines.append(f"display_name: {display_name}")
+ (home / "profiles" / folder / "profile.yaml").write_text("\n".join(lines) + "\n", encoding="utf-8")
+
+
[email protected]("target", ["Scribe", "@scribe", "Dr. Foo", "dr-foo", "drfoo", "Builder"])
+def test_friendly_names_and_desktop_slugs_resolve_to_folder_ids(tmp_path, monkeypatch, target):
+ """A display name, Bot Mode title or the Desktop's @-slug of either lands on the
+ folder id message_agent keys on — the same aliases the composer autocompletes (#100671)."""
+ calls = _capture_spawn(monkeypatch)
+ monkeypatch.setattr(bot_relay, "_hermes_cli", lambda: "hermes")
+ home = _managed_home(tmp_path, teammates=("writer", "foo", "builder"))
+ _rename(home, "writer", display_name="Scribe")
+ _rename(home, "foo", title="Dr. Foo")
+ _rename(home, "builder", display_name="Builder")
+ expected = {"Scribe": "writer", "@scribe": "writer", "Dr. Foo": "foo", "dr-foo": "foo", "drfoo": "foo",
+ "Builder": "builder"}[target]
+
+ result = json.loads(bot_mode_dm.message_agent_tool(target=target, message="ping", agent=_FakeAgent(home)))
+
+ assert result["status"] == "sent", result
+ assert result["to"] == f"@{expected}"
+ _mode, _dm_file, argv = _runner_parts(calls[0]["command"])
+ assert argv[1:3] == ["-p", expected]
+
+
+def test_ambiguous_friendly_name_fails_closed(tmp_path, monkeypatch):
+ """Two bots titled the same must not let a DM land on whichever sorts first; the
+ reserved @hermes alias can never be hijacked by a rename."""
+ calls = _capture_spawn(monkeypatch)
+ home = _managed_home(tmp_path, teammates=("aaa", "bbb", "ops"))
+ _rename(home, "aaa", display_name="Scribe")
+ _rename(home, "bbb", display_name="Scribe")
+ _rename(home, "ops", display_name="Hermes")
+
+ ambiguous = json.loads(bot_mode_dm.message_agent_tool(target="Scribe", message="ping", agent=_FakeAgent(home)))
+ hijack = json.loads(bot_mode_dm.message_agent_tool(target="hermes", message="ping",
+ agent=_FakeAgent(home / "profiles" / "aaa")))
+
+ assert "error" in ambiguous and "No teammate named 'Scribe'" in ambiguous["error"]
+ assert hijack.get("to") == "@hermes"
+ assert [_runner_parts(c["command"])[2][1:3] for c in calls] == [["-p", "default"]]
+
+
def test_peer_delivery_command_pins_registry_profile_for_secondary_bots(
tmp_path, monkeypatch
):
diff --git a/tools/bot_mode_dm.py b/tools/bot_mode_dm.py
index f98f85ea85d..7a9dedb9042 100644
--- a/tools/bot_mode_dm.py
+++ b/tools/bot_mode_dm.py
@@ -158,12 +158,24 @@ def ensure_message_agent_tool(agent: Any) -> bool:
return False
-def _resolve_local_name(target: str, roster: list[str]) -> Optional[str]:
- """Map a target handle to a profile name ('hermes' → 'default')."""
+def _resolve_local_name(target: str, roster: list[str], root: Path | None = None) -> Optional[str]:
+ """Map a target to a local profile FOLDER id: 'hermes' → 'default'; an exact folder id
+ (case-insensitive); else — when ``root`` is given — a friendly name or its Desktop @-slug
+ (profile.yaml ``display_name`` / Bot Mode title: 'Scribe', '@scribe', 'Dr. Foo' → 'foo').
+ Ambiguous friendly names resolve to None so a DM never lands on the wrong bot (#100671)."""
want = target.strip().lower()
+ if not want:
+ return None
if want == "hermes":
return "default" if "default" in roster else None
- return next((name for name in roster if name.lower() == want), None) if want else None
+ exact = next((name for name in roster if name.lower() == want), None)
+ if exact is not None or root is None:
+ return exact
+ from tools.bot_mode_probe import alias_forms, local_alias_map
+
+ aliases = local_alias_map(root)
+ hits = set().union(*(aliases.get(form, set()) for form in alias_forms(want) | {want}))
+ return next(iter(hits)) if len(hits) == 1 else None
def _err(message: str, *, roster: list[str] | None = None, peers: list[str] | None = None) -> str:
@@ -243,11 +255,11 @@ def message_agent_tool(target: str = "", message: str = "", task_id: Optional[st
f"@{peer_profile or peer_name} on peer '{peer_name}'", stdin_file=True,
author=peer_author, **delivery)
- # Local teammate.
+ # Local teammate — folder id, or a friendly name / Desktop @-slug ('Scribe', 'Dr. Foo').
+ resolved = _resolve_local_name(raw_target, roster, root)
is_local_shape = bool(_LOCAL_TARGET_RE.match(raw_target))
- if not is_local_shape and "@" not in raw_target:
+ if resolved is None and not is_local_shape and "@" not in raw_target:
return _roster_err(f"Invalid target: {raw_target!r}.")
- resolved = _resolve_local_name(raw_target, roster) if is_local_shape else None
if resolved is None or resolved == me:
# Unknown locally, or same-name target on ANOTHER connection (this gateway's 'default'
# messaging the cloud 'default'): every Desktop-connected gateway is reachable via the
diff --git a/tools/bot_mode_probe.py b/tools/bot_mode_probe.py
index 7439ff563ea..07bdfd58c7e 100644
--- a/tools/bot_mode_probe.py
+++ b/tools/bot_mode_probe.py
@@ -139,16 +139,54 @@ def _bullet(handle: str, *parts: str) -> str:
def _profile_role(profile_dir: Path) -> str:
"""Teammate role line: Bot Mode title — profile description; tells a teammate
- WHO to message for a job. Single-line, ≤160 chars, "" when neither. Never raises."""
+ WHO to message for a job. A friendly ``display_name`` (``hermes profile rename``) that
+ differs from both the folder id and the title leads the line, so an untagged
+ "talk to Scribe" maps to the folder handle without a disk search (#100671).
+ Single-line, ≤160 chars, "" when nothing. Never raises."""
def _role() -> str:
data = _read_yaml_dict(profile_dir / "profile.yaml") or {}
- line = _role_line(str((_bots_meta(data) or {}).get("title") or "").strip(),
- str(data.get("description") or "").strip())
+ title = str((_bots_meta(data) or {}).get("title") or "").strip()
+ display = str(data.get("display_name") or "").strip()
+ if display.lower() in (profile_dir.name.lower(), title.lower()):
+ display = ""
+ line = _role_line(display, title, str(data.get("description") or "").strip())
return " ".join(line.split())[:160]
return _swallow(_role, "")
+# Tokens the Desktop mention parser reserves; a bot titled "Hermes" never hijacks @hermes.
+_RESERVED_ALIASES = frozenset({"all", "everyone", "user", "default", "hermes"})
+
+
+def alias_forms(value: str) -> set[str]:
+ """Lower-cased mention forms of a friendly name, mirroring the Desktop's
+ ``mentionNameForms``: slugified (``"Dr. Foo"`` → ``dr-foo``, what autocomplete inserts)
+ and collapsed (``drfoo``). Reserved tokens and empty forms are dropped."""
+ name = str(value or "").strip().lower()
+ slug = re.sub(r"[^a-z0-9_-]+", "-", name).strip("-")
+ collapsed = re.sub(r"[^a-z0-9_-]+", "", name)
+ return {f for f in (slug, collapsed)
+ if f and re.fullmatch(r"[a-z0-9][a-z0-9_-]*", f) and f not in _RESERVED_ALIASES}
+
+
+def local_alias_map(root: Path) -> dict[str, set[str]]:
+ """``alias form → {folder ids}`` for every local profile's friendly names (profile.yaml
+ ``display_name`` and the Bot Mode title). Folder ids themselves are not aliases — the
+ caller matches those first — so a friendly name equal to ANOTHER folder id is visibly
+ ambiguous instead of silently winning. Never raises."""
+ def _build() -> dict[str, set[str]]:
+ aliases: dict[str, set[str]] = {}
+ for name, profile_dir in _roster(root):
+ data = _read_yaml_dict(profile_dir / "profile.yaml") or {}
+ friendly = (str(data.get("display_name") or ""), str((_bots_meta(data) or {}).get("title") or ""))
+ for form in set().union(*(alias_forms(f) for f in friendly)):
+ aliases.setdefault(form, set()).add(name)
+ return aliases
+
+ return _swallow(_build, {})
+
+
def _peers(root: Path) -> list[str]:
"""Registered peer gateway names (``hermes peer``) from config.yaml, read
directly (no config-loader import; the section is absent on most installs). Never raises."""