Files
hermes-agent/tools/message_agent_tool.py
alt-glitch 2115d74421 refactor(bots): Bot Mode and Bot Desktop move from tools/ to bots/
tools/ holds model tools. These 19 files register none: they resolve the
Bot Mode roster, deliver message_agent's DMs and run their by-path runner,
hold the cross-connection relay and its receipts, and run the Bot Desktop
screen. They move to a new root package, bots/ (flat plus bots/desktop/,
with the launcher and wallpaper beside the runtime that reads them).
tools/message_agent_tool.py stays; only its imports change.

Function bodies are unchanged and every import stays where it was. Tests
whose subject is a moved file go to tests/bots/, whose conftest imports
the tests/tools/ autouse fixtures they ran under. Loggers follow their
modules; bots joins the tools log component, so `hermes logs --component
tools` shows the same lines, and every hand-written root-package list.

Old names keep working. Each moved top-level module has a MOVES key.
Processes started on v0.21.6 to v0.23.5 that outlive an update import
these modules inside functions and start tools/bot_mode_dm.py by path as
the DM runner, so those names get generated old-path files. Pinned catalog
plugins import tools.bot_desktop and tools.bot_live_delivery; the plugin
guide lists both.
2026-12-01 17:49:22 +05:30

232 lines
12 KiB
Python

"""The ``message_agent`` model tool: Bot Mode agent-to-agent DMs.
Lets a Bot Mode agent message a teammate (a profile on this install, an agent on
a registered peer gateway, or one on another Desktop-connected machine): the
target is validated against the live roster, the attribution prefix is applied
server-side, and the reply arrives later via the background-process completion
notification (fire-and-forget). Containment: the schema is injected ONLY into a
bot's canonical "Bot Chat" session on a Bot-Mode-managed install (same gate as
``bots/roster_probe.py``; never in the registry or any toolset), and dispatch
re-checks that gate so a forged call returns a structured error. Delivery
(target resolution, transports, DM files, the background runner) is
``bots/dm_delivery.py``.
"""
from __future__ import annotations
import contextlib
import logging
from pathlib import Path
from typing import Any, Optional
from bots.dm_delivery import MESSAGE_MAX_CHARS, Sender, _default_home, _err
logger = logging.getLogger(__name__)
MESSAGE_AGENT_TOOL_NAME = "message_agent"
# Fan-out bound: one combined runner holds one sub-runner per target.
FAN_OUT_MAX = 8
def message_agent_tool_schema() -> dict:
"""OpenAI-format schema for ``message_agent`` (injected, not registered)."""
return {
"type": "function",
"function": {
"name": MESSAGE_AGENT_TOOL_NAME,
"description": (
"Send a message to ANOTHER agent (teammate) on this install, a registered peer gateway, or "
"another connected machine. FIRE-AND-FORGET: it validates the target against the live roster, "
"delivers into that agent's Bot Chat with your attribution prefixed, and returns a dispatch "
"ack at once (status queued + delivery_id: a hand-off, not a receipt). It never returns the "
"reply: finish your turn; the completion notification wakes you with the outcome (its "
"`outcome` line says who answered or why not) — unless the ack says reply_delivery=\"poll\": "
"then follow its process(action=\"wait\") instruction first. COMPOSE the message yourself "
"(lead with the point and the concrete ask); never paste the user's words verbatim or share "
"private 1:1 content. Targets: a roster name ('researcher'), '<peer>/<agent>' or '<peer>' for "
"a peer gateway, '<handle>@<connection>' when a handle exists on several machines."
),
"parameters": {
"type": "object",
"properties": {
"target": {
"type": "string",
"description": (f"Who to message ('hermes' is the default agent). Up to {FAN_OUT_MAX} "
"comma-separated names fan out: one combined reply."),
},
"message": {
"type": "string",
"description": (
"The message YOU composed for that agent (max "
f"{MESSAGE_MAX_CHARS} chars). Do not include the "
"'Message from …' prefix — it is added automatically."
),
},
"constraints": {
"type": "string",
"description": "Limits their answer must respect (scope, length, format).",
},
"expecting": {
"type": "string",
"description": "What you need back from them; shown to them as the reply they owe you.",
},
"expects_reply": {
"type": "boolean",
"description": "false: notify only — no reply comes back and nothing wakes you.",
},
"cancel": {
"type": "string",
"description": "A delivery_id from your own ack: withdraw that queued request or stop the turn it started.",
},
},
"required": ["target"],
},
},
}
def message_agent_authorized(agent: Any) -> bool:
"""The ``message_agent`` gate: a protocol-enabled agent whose session is a managed
Bot-Mode canonical Bot Chat. Session-stable, so it is prompt-cache safe to re-evaluate
on every tool-snapshot rebuild. Never raises."""
try:
if not getattr(agent, "_bot_mode_protocol", True):
return False
from bots.roster_probe import BOT_CHAT_TITLE, is_bot_mode_managed
# Managed-install check, NOT section non-emptiness: a SOUL.md carrying the
# legacy protocol text gets an empty section but must still get the tool.
return _session_title(agent) == BOT_CHAT_TITLE and is_bot_mode_managed(_agent_home(agent))
except Exception: # pragma: no cover — must never break a turn
logger.debug("message_agent_authorized failed", exc_info=True)
return False
def ensure_message_agent_tool(agent: Any) -> bool:
"""Inject the ``message_agent`` schema into a Bot Chat agent's tool list (once per turn).
Idempotent and deterministic for the session's life (the gate is stable from the
first turn), so the tool list is byte-identical across turns — prompt-cache safe. Never raises."""
try:
if not getattr(agent, "_bot_mode_protocol", True):
return False
tools = getattr(agent, "tools", None)
present = bool(tools) and any(
isinstance(t, dict) and t.get("function", {}).get("name") == MESSAGE_AGENT_TOOL_NAME
for t in tools
)
if not present:
if not message_agent_authorized(agent):
return False
if agent.tools is None:
agent.tools = []
agent.tools.append(message_agent_tool_schema())
# Success means BOTH halves hold: a tool-surface rebuild (compaction, MCP refresh)
# can keep the schema while valid_tool_names is republished without it, and an
# advertised-but-nondispatchable tool sends the model hunting for shellouts (#96105).
valid = getattr(agent, "valid_tool_names", None)
if isinstance(valid, set):
valid.add(MESSAGE_AGENT_TOOL_NAME)
return True
except Exception: # pragma: no cover — must never break a turn
logger.debug("ensure_message_agent_tool failed", exc_info=True)
return False
def _envelope(message: Any, constraints: Any, expecting: Any) -> str:
"""The request as the teammate reads it: the message, then its typed constraints and the reply
the sender needs back, each on its own labelled line."""
typed = [f"{label}: {str(value).strip()}" for label, value in (("Constraints", constraints),
("Reply needed", expecting)) if str(value or "").strip()]
return "\n\n".join([str(message or "").strip(), *(["\n".join(typed)] if typed else [])])
def _wants_reply(value: Any) -> bool:
"""``expects_reply`` as models send it: a bool, or its string spelling."""
return str(value).strip().lower() not in ("false", "0", "no")
def message_agent_tool(target: str = "", message: str = "", task_id: Optional[str] = None, agent: Any = None,
expects_reply: Any = True, cancel: str = "", constraints: str = "", expecting: str = "") -> str:
"""Deliver ``message`` to ``target``'s Bot Chat (several comma-separated targets fan out),
or withdraw the caller's own request ``cancel``. Returns a JSON ack/error.
``agent`` is the calling AIAgent — used for the Bot Chat gate and sender identity."""
home = _agent_home(agent)
try:
from bots.roster_probe import (
BOT_CHAT_TITLE, NO_REPLY_MARKER, _display_name, _handle, _hermes_root, _peers,
_profile_name as _self_profile_name, _roster, is_bot_mode_managed,
)
if _session_title(agent) != BOT_CHAT_TITLE:
return _err("message_agent is only available in a Bot Mode 'Bot Chat' session. "
"This session is not one; do not retry.")
if not is_bot_mode_managed(home):
return _err("This install is not Bot-Mode-managed (no bot roster); "
"message_agent is unavailable. Do not retry.")
except Exception as exc: # pragma: no cover — defensive
return _err(f"Bot Mode gate check failed: {exc}")
from hermes_cli.observability.shared_metrics_signals import record_feature_used
record_feature_used("bot_mode", hermes_home=home)
root, me = _hermes_root(Path(home)), _self_profile_name(Path(home))
roster_homes = dict(_roster(root))
peers = _peers(root)
sender = Sender(home=home, root=root, me=me, roster_homes=roster_homes, peers=peers,
teammates=[_handle(n, list(roster_homes)) for n in roster_homes if n != me], task_id=task_id, agent=agent)
if str(cancel or "").strip():
from bots.dm_coordination import cancel_own_delivery
return cancel_own_delivery(str(cancel).strip(), str(target or ""), sender)
if not str(message or "").strip():
return _err("message is required — compose what you want to say to that agent.")
body = _envelope(message, constraints, expecting)
if len(body) > MESSAGE_MAX_CHARS:
return _err(f"message too long ({len(body)} chars > {MESSAGE_MAX_CHARS}). "
"Send the essentials; share large content as a file path instead.")
from bots.dm_coordination import split_targets
targets = split_targets(target, sender)
if not targets:
return sender.roster_err("target is required.")
if len(targets) > FAN_OUT_MAX:
return _err(f"Too many targets ({len(targets)} > {FAN_OUT_MAX}); message the ones the task needs.")
reply = _wants_reply(expects_reply)
# Sender signature: the friendly name when the bot has one (#89720); the @handle stays the routing alias.
signature = f"Message from 🤖 {_display_name(me, roster_homes.get(me, Path(home)), list(roster_homes))} (@{_handle(me, list(roster_homes))}): "
from bots.dm_chain import send_gated
# The runtime's chain rules run before any transport (hop cap, repeated ask, reply to a bot: #137027).
return send_gated(targets, reply, body, lambda wants: signature + ("" if wants else f"{NO_REPLY_MARKER} ") + body,
sender)
# agent-context helpers (mirror system_prompt.py's resolution)
def _agent_home(agent: Any) -> str:
"""The calling agent's OWN home (its store's profile), not ambient env."""
with contextlib.suppress(Exception):
persistence = getattr(agent, "persistence", None)
if persistence is not None:
return str(persistence.scope.profile_dir)
return _default_home()
def _session_title(agent: Any) -> str:
title = str(getattr(agent, "_session_title_hint", "") or "").strip()
if title:
return title
with contextlib.suppress(Exception):
from agent.runtime_session_store import RuntimeSessionStore
persistence, sid = getattr(agent, "persistence", None), getattr(agent, "session_id", None)
worker_store = getattr(agent, "_session_db", None)
if persistence is not None and sid:
return str(persistence.sessions.get_title(sid) or "").strip()
if isinstance(worker_store, RuntimeSessionStore) and sid: # a managed worker reads its owner's row
return str(worker_store.get_session_title(sid) or "").strip()
return ""