The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(cli): hermes peer — bot-to-bot DMs across machines and gateways
Teknium6229683b62bc
diff --git a/hermes_cli/main.py b/hermes_cli/main.pyindex 3d1051e71d1..280747d2f37 100644--- a/hermes_cli/main.py+++ b/hermes_cli/main.py@@ -10008,6 +10008,7 @@ def _coalesce_session_name_args(argv: list) -> list:"security","acp","webhook",+ "peer","memory","dump","debug",@@ -11413,7 +11414,7 @@ _BUILTIN_SUBCOMMANDS = frozenset("dump", "egress", "fallback", "gateway", "hooks", "import", "import-agent", "insights","gui", "desktop", "kanban", "login", "logout", "logs", "lsp", "mcp", "memory", "migrate", "moa","journey", "memory-graph", "learning",- "model", "monitoring", "pairing", "pause", "pets", "plugins", "portal", "profile",+ "model", "monitoring", "pairing", "pause", "peer", "pets", "plugins", "portal", "profile","project", "proxy","prompt-size","resume",@@ -12495,6 +12496,13 @@ def main():# =========================================================================build_webhook_parser(subparsers, cmd_webhook=cmd_webhook)+ # =========================================================================+ # peer command — bot-to-bot DMs across machines (peer Hermes gateways)+ # =========================================================================+ from hermes_cli.subcommands.peer import build_peer_parser++ build_peer_parser(subparsers)+# =========================================================================# portal command — Nous Portal status + Tool Gateway routing# =========================================================================diff --git a/hermes_cli/subcommands/peer.py b/hermes_cli/subcommands/peer.pynew file mode 100644index 00000000000..22a675405f0--- /dev/null+++ b/hermes_cli/subcommands/peer.py@@ -0,0 +1,313 @@+"""``hermes peer`` — bot-to-bot DMs across machines/gateways.++A *peer* is another Hermes gateway (any machine: homelab, Spark, Hermes+Cloud) running the ``api_server`` platform. Registering it here gives every+bot on THIS machine a transport to message bots on THAT machine:++ hermes peer add spark --url http://spark.lan:8377 --key <API_SERVER_KEY>+ hermes peer dm spark "Message from 🤖 dixie (@dixie): disk status?"+ hermes peer dm spark/researcher "..." # named profile (multiplexed peer)++``dm`` resolves the remote agent's canonical "Bot Chat" session (by title,+creating it when missing), runs ONE synchronous agent turn over the peer's+existing ``POST /api/sessions/{id}/chat`` endpoint, and prints the reply on+stdout — the exact cross-machine twin of the local+``hermes -p <bot> chat --in ~ -c "Bot Chat" ...`` bot-messaging command, so+the Bot Mode protocol composes over it unchanged.++Design notes:+- No new server surface: the peer's stock api_server is the transport.+- Peer labels/URLs live in config.yaml (``bot_peers``); the peer's+ API_SERVER_KEY is a credential and lives in ``~/.hermes/.env`` as+ ``HERMES_PEER_<NAME>_KEY``.+- Named-profile targets use the peer's ``/p/<profile>/`` multiplex mirror;+ the bare target is the peer gateway's own (launch) profile.+"""++from __future__ import annotations++import argparse+import json+import re+import sys+import urllib.error+import urllib.parse+import urllib.request++BOT_CHAT_TITLE = "Bot Chat"+_PEER_NAME_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{0,63}$")+_PROFILE_RE = re.compile(r"^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$")++# One synchronous agent turn can legitimately take minutes.+DM_TIMEOUT_S = 600+LIST_TIMEOUT_S = 30+++def _peer_key_env(name: str) -> str:+ return f"HERMES_PEER_{name.upper().replace('-', '_')}_KEY"+++def _load_peers() -> dict:+ from hermes_cli.config import load_config++ cfg = load_config() or {}+ peers = cfg.get("bot_peers")+ return peers if isinstance(peers, dict) else {}+++def _save_peers(peers: dict) -> None:+ from hermes_cli.config import load_config, save_config++ cfg = load_config() or {}+ cfg["bot_peers"] = peers+ save_config(cfg)+++def _peer_secret(name: str) -> str:+ """The peer's API key: profile-scoped secret store first, raw env fallback."""+ env_name = _peer_key_env(name)+ try:+ from agent.secret_scope import get_secret++ return (get_secret(env_name, "") or "").strip()+ except Exception:+ import os++ return (os.environ.get(env_name) or "").strip()+++def _request(url: str, key: str, *, method: str = "GET", body: dict | None = None, timeout: int = LIST_TIMEOUT_S) -> dict:+ data = json.dumps(body).encode("utf-8") if body is not None else None+ req = urllib.request.Request(+ url,+ data=data,+ method=method,+ headers={+ "Authorization": f"Bearer {key}",+ "Content-Type": "application/json",+ "User-Agent": "hermes-peer-dm",+ },+ )+ with urllib.request.urlopen(req, timeout=timeout) as resp: # noqa: S310 — user-registered peer URL+ payload = resp.read().decode("utf-8", "replace")+ try:+ parsed = json.loads(payload)+ except ValueError as exc:+ raise RuntimeError(f"Peer returned non-JSON response: {payload[:200]}") from exc+ if not isinstance(parsed, dict):+ raise RuntimeError("Peer returned a non-object JSON response")+ return parsed+++def _base_url(peer: dict, profile: str | None) -> str:+ url = str(peer.get("url") or "").rstrip("/")+ if profile:+ # Multiplex mirror: same handlers, scoped to the named profile.+ return f"{url}/p/{urllib.parse.quote(profile, safe='')}"+ return url+++def _find_bot_chat(base: str, key: str) -> str | None:+ """The remote canonical Bot Chat's session id, or None."""+ listing = _request(f"{base}/api/sessions?limit=200", key)+ for session in listing.get("data") or []:+ if isinstance(session, dict) and (session.get("title") or "").strip() == BOT_CHAT_TITLE:+ return str(session.get("id") or "") or None+ return None+++def _ensure_bot_chat(base: str, key: str) -> str:+ existing = _find_bot_chat(base, key)+ if existing:+ return existing+ created = _request(+ f"{base}/api/sessions",+ key,+ method="POST",+ body={"title": BOT_CHAT_TITLE, "source": "bot_peer_dm"},+ )+ session_id = str(created.get("id") or created.get("session_id") or "")+ if not session_id:+ raise RuntimeError("Peer did not return a session id for the new Bot Chat")+ return session_id+++def _parse_target(target: str) -> tuple[str, str | None]:+ """``<peer>`` or ``<peer>/<profile>`` → (peer, profile|None)."""+ raw = (target or "").strip()+ peer, _, profile = raw.partition("/")+ peer = peer.strip()+ profile = profile.strip() or None+ if not peer:+ raise ValueError("Peer name required (hermes peer dm <peer>[/<agent>] ...)")+ if profile and not _PROFILE_RE.match(profile):+ raise ValueError(f"Invalid agent/profile name: {profile!r}")+ return peer, profile+++def _http_error_detail(exc: urllib.error.HTTPError) -> str:+ try:+ body = exc.read().decode("utf-8", "replace")+ parsed = json.loads(body)+ message = parsed.get("error", {}).get("message") if isinstance(parsed, dict) else None+ return message or body[:200]+ except Exception:+ return str(exc)+++def cmd_peer(args) -> int:+ action = getattr(args, "peer_action", None)++ if action in ("add", "set"):+ name = (args.name or "").strip().lower()+ if not _PEER_NAME_RE.match(name):+ print(f"Invalid peer name: {name!r} (lowercase, digits, -, _; max 64)", file=sys.stderr)+ return 2+ url = (args.url or "").strip()+ if not url.lower().startswith(("http://", "https://")):+ print("Peer --url must be an http(s) gateway base URL, e.g. http://spark.lan:8377", file=sys.stderr)+ return 2+ peers = _load_peers()+ peers[name] = {"url": url.rstrip("/"), **({"note": args.note.strip()} if getattr(args, "note", "") else {})}+ _save_peers(peers)+ key = (getattr(args, "key", "") or "").strip()+ if key:+ from hermes_cli.config import save_env_value++ save_env_value(_peer_key_env(name), key)+ print(f"Peer '{name}' saved ({url}) — key stored as {_peer_key_env(name)} in ~/.hermes/.env")+ else:+ print(+ f"Peer '{name}' saved ({url}). No key given — set the peer's API_SERVER_KEY with:\n"+ f" hermes peer add {name} --url {url} --key <key>\n"+ f" (or add {_peer_key_env(name)}=<key> to ~/.hermes/.env)"+ )+ return 0++ if action in ("remove", "rm"):+ name = (args.name or "").strip().lower()+ peers = _load_peers()+ if name not in peers:+ print(f"No peer named '{name}'.", file=sys.stderr)+ return 1+ peers.pop(name)+ _save_peers(peers)+ print(f"Peer '{name}' removed (its {_peer_key_env(name)} entry in .env is kept; delete it manually if unused).")+ return 0++ if action in ("list", "ls", None):+ peers = _load_peers()+ if not peers:+ print("No peers registered. Add one: hermes peer add <name> --url http://host:port --key <API_SERVER_KEY>")+ return 0+ for name in sorted(peers):+ entry = peers[name] if isinstance(peers[name], dict) else {}+ has_key = "key set" if _peer_secret(name) else f"NO KEY ({_peer_key_env(name)} unset)"+ note = f" — {entry.get('note')}" if entry.get("note") else ""+ print(f"{name}\t{entry.get('url', '?')}\t[{has_key}]{note}")+ return 0++ if action == "dm":+ try:+ peer_name, profile = _parse_target(args.target)+ except ValueError as exc:+ print(str(exc), file=sys.stderr)+ return 2+ peers = _load_peers()+ peer = peers.get(peer_name)+ if not isinstance(peer, dict) or not peer.get("url"):+ print(f"No peer named '{peer_name}'. Run: hermes peer list", file=sys.stderr)+ return 1+ key = _peer_secret(peer_name)+ if not key:+ print(+ f"No API key for peer '{peer_name}'. Set it: hermes peer add {peer_name} "+ f"--url <url> --key <key> (or add {_peer_key_env(peer_name)}=<key> to ~/.hermes/.env)",+ file=sys.stderr,+ )+ return 1+ message = (args.message or "").strip()+ if not message and not sys.stdin.isatty():+ message = sys.stdin.read().strip()+ if not message:+ print("Message required (argument or stdin).", file=sys.stderr)+ return 2++ base = _base_url(peer, profile)+ try:+ session_id = _ensure_bot_chat(base, key)+ result = _request(+ f"{base}/api/sessions/{urllib.parse.quote(session_id, safe='')}/chat",+ key,+ method="POST",+ body={"message": message},+ timeout=DM_TIMEOUT_S,+ )+ except urllib.error.HTTPError as exc:+ print(f"Peer '{peer_name}' rejected the request (HTTP {exc.code}): {_http_error_detail(exc)}", file=sys.stderr)+ return 1+ except (urllib.error.URLError, TimeoutError, OSError, RuntimeError) as exc:+ print(f"Could not reach peer '{peer_name}': {exc}", file=sys.stderr)+ return 1++ reply = ""+ msg = result.get("message")+ if isinstance(msg, dict):+ reply = str(msg.get("content") or "")+ if getattr(args, "json", False):+ print(json.dumps({"peer": peer_name, "profile": profile, "session_id": result.get("session_id") or session_id, "reply": reply}))+ else:+ print(reply or "(no reply)")+ return 0++ print("Unknown peer action. See: hermes peer --help", file=sys.stderr)+ return 2+++def build_peer_parser(subparsers) -> None:+ """Attach the ``peer`` subcommand to ``subparsers``."""+ parser = subparsers.add_parser(+ "peer",+ help="Bot-to-bot DMs across machines (peer Hermes gateways)",+ description=(+ "Register other Hermes gateways as peers and message their agents. "+ "'hermes peer dm <peer>[/<agent>] \"...\"' delivers into the remote "+ "agent's canonical Bot Chat over the peer's API server and prints "+ "the reply — the cross-machine twin of 'hermes -p <bot> chat'. "+ "The peer must run the api_server platform; its API_SERVER_KEY is "+ "stored locally as a credential in ~/.hermes/.env."+ ),+ epilog=(+ "Examples:\n"+ " hermes peer add spark --url http://spark.lan:8377 --key <API_SERVER_KEY>\n"+ " hermes peer list\n"+ ' hermes peer dm spark "Message from 🤖 dixie (@dixie): disk status?"\n'+ ' hermes peer dm spark/researcher "..." # named profile on a multiplexed peer\n'+ " hermes peer remove spark\n"+ "\n"+ "Exit codes: 0 ok, 1 delivery/peer error, 2 usage error."+ ),+ formatter_class=argparse.RawDescriptionHelpFormatter,+ )+ peer_sub = parser.add_subparsers(dest="peer_action")++ add_p = peer_sub.add_parser("add", aliases=["set"], help="Register (or update) a peer gateway")+ add_p.add_argument("name", help="Peer name (lowercase slug, e.g. spark, homelab)")+ add_p.add_argument("--url", required=True, help="Peer gateway base URL, e.g. http://spark.lan:8377")+ add_p.add_argument("--key", default="", help="The peer's API_SERVER_KEY (stored in ~/.hermes/.env)")+ add_p.add_argument("--note", default="", help="Optional description")++ peer_sub.add_parser("list", aliases=["ls"], help="List registered peers")++ rm_p = peer_sub.add_parser("remove", aliases=["rm"], help="Remove a peer")+ rm_p.add_argument("name", help="Peer name")++ dm_p = peer_sub.add_parser(+ "dm",+ help="Message an agent on a peer gateway and print its reply",+ )+ dm_p.add_argument("target", help="<peer> or <peer>/<agent> (named profile on a multiplexed peer)")+ dm_p.add_argument("message", nargs="?", default=None, help="Message text (or stdin)")+ dm_p.add_argument("--json", action="store_true", default=False, help="Emit a JSON result")++ parser.set_defaults(func=cmd_peer)diff --git a/tests/hermes_cli/test_peer_cmd.py b/tests/hermes_cli/test_peer_cmd.pynew file mode 100644index 00000000000..60e53f1302b--- /dev/null+++ b/tests/hermes_cli/test_peer_cmd.py@@ -0,0 +1,186 @@+"""Tests for ``hermes peer`` — cross-machine bot-to-bot DMs."""++import json+import threading+from http.server import BaseHTTPRequestHandler, HTTPServer+from types import SimpleNamespace++import pytest++from hermes_cli.subcommands import peer as peer_cmd+++# ── target parsing ───────────────────────────────────────────────────────────+++def test_parse_target_bare_peer():+ assert peer_cmd._parse_target("spark") == ("spark", None)+++def test_parse_target_peer_and_profile():+ assert peer_cmd._parse_target("spark/researcher") == ("spark", "researcher")+++def test_parse_target_rejects_empty():+ with pytest.raises(ValueError):+ peer_cmd._parse_target("")+++def test_parse_target_rejects_bad_profile():+ with pytest.raises(ValueError):+ peer_cmd._parse_target("spark/../etc")+++# ── url scoping ──────────────────────────────────────────────────────────────+++def test_base_url_bare_and_profile():+ peer = {"url": "http://spark.lan:8377/"}+ assert peer_cmd._base_url(peer, None) == "http://spark.lan:8377"+ assert peer_cmd._base_url(peer, "researcher") == "http://spark.lan:8377/p/researcher"+++# ── registry round-trip (isolated config) ────────────────────────────────────+++def test_add_list_remove_roundtrip(monkeypatch, capsys):+ store = {}++ monkeypatch.setattr(peer_cmd, "_load_peers", lambda: dict(store))++ def fake_save(peers):+ store.clear()+ store.update(peers)++ monkeypatch.setattr(peer_cmd, "_save_peers", fake_save)+ monkeypatch.setattr(peer_cmd, "_peer_secret", lambda name: "k" * 20)++ rc = peer_cmd.cmd_peer(+ SimpleNamespace(peer_action="add", name="spark", url="http://spark.lan:8377", key="", note="")+ )+ assert rc == 0+ assert store["spark"]["url"] == "http://spark.lan:8377"++ rc = peer_cmd.cmd_peer(SimpleNamespace(peer_action="list"))+ assert rc == 0+ assert "spark" in capsys.readouterr().out++ rc = peer_cmd.cmd_peer(SimpleNamespace(peer_action="remove", name="spark"))+ assert rc == 0+ assert "spark" not in store+++def test_add_rejects_bad_name_and_url(monkeypatch):+ monkeypatch.setattr(peer_cmd, "_load_peers", lambda: {})+ monkeypatch.setattr(peer_cmd, "_save_peers", lambda peers: None)++ assert peer_cmd.cmd_peer(SimpleNamespace(peer_action="add", name="Bad Name!", url="http://x", key="", note="")) == 2+ assert peer_cmd.cmd_peer(SimpleNamespace(peer_action="add", name="ok", url="ftp://x", key="", note="")) == 2+++def test_dm_unknown_peer_and_missing_key(monkeypatch):+ monkeypatch.setattr(peer_cmd, "_load_peers", lambda: {"spark": {"url": "http://x"}})+ monkeypatch.setattr(peer_cmd, "_peer_secret", lambda name: "")++ assert peer_cmd.cmd_peer(SimpleNamespace(peer_action="dm", target="nope", message="hi", json=False)) == 1+ assert peer_cmd.cmd_peer(SimpleNamespace(peer_action="dm", target="spark", message="hi", json=False)) == 1+++# ── live HTTP dm flow (real loopback server, fake peer gateway) ──────────────+++class _FakePeer(BaseHTTPRequestHandler):+ sessions: list = []+ chats: list = []+ auth_seen: list = []++ def _json(self, payload, status=200):+ body = json.dumps(payload).encode()+ self.send_response(status)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(body)))+ self.end_headers()+ self.wfile.write(body)++ def do_GET(self):+ type(self).auth_seen.append(self.headers.get("Authorization", ""))+ if self.path.startswith("/api/sessions"):+ data = [{"id": s, "title": "Bot Chat"} for s in type(self).sessions]+ return self._json({"object": "list", "data": data})+ return self._json({"error": {"message": "not found"}}, 404)++ def do_POST(self):+ type(self).auth_seen.append(self.headers.get("Authorization", ""))+ length = int(self.headers.get("Content-Length", 0))+ body = json.loads(self.rfile.read(length) or b"{}")++ if self.path == "/api/sessions":+ type(self).sessions.append("bc_1")+ return self._json({"id": "bc_1", "title": body.get("title")}, 201)++ if self.path.startswith("/api/sessions/") and self.path.endswith("/chat"):+ type(self).chats.append(body.get("message"))+ return self._json(+ {+ "object": "hermes.session.chat.completion",+ "session_id": "bc_1",+ "message": {"role": "assistant", "content": "reply from the other machine"},+ }+ )++ return self._json({"error": {"message": "not found"}}, 404)++ def log_message(self, *args): # noqa: D102 — silence test server logging+ pass+++def fake_peer_server():+ _FakePeer.sessions = []+ _FakePeer.chats = []+ _FakePeer.auth_seen = []+ server = HTTPServer(("127.0.0.1", 0), _FakePeer)+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()+ try:+ yield f"http://127.0.0.1:{server.server_port}"+ finally:+ server.shutdown()+ thread.join(timeout=5)+++def test_dm_creates_bot_chat_then_chats(monkeypatch, capsys, fake_peer_server):+ monkeypatch.setattr(peer_cmd, "_load_peers", lambda: {"spark": {"url": fake_peer_server}})+ monkeypatch.setattr(peer_cmd, "_peer_secret", lambda name: "secret-key-123456")++ rc = peer_cmd.cmd_peer(+ SimpleNamespace(+ peer_action="dm",+ target="spark",+ message="Message from 🤖 dixie (@dixie): disk status?",+ json=False,+ )+ )++ assert rc == 0+ out = capsys.readouterr().out+ assert "reply from the other machine" in out+ # One Bot Chat was created (none existed), then the chat turn ran on it.+ assert _FakePeer.sessions == ["bc_1"]+ assert _FakePeer.chats == ["Message from 🤖 dixie (@dixie): disk status?"]+ # Every request carried the peer key.+ assert all(a == "Bearer secret-key-123456" for a in _FakePeer.auth_seen)+++def test_dm_reuses_existing_bot_chat(monkeypatch, capsys, fake_peer_server):+ _FakePeer.sessions = ["bc_existing"]+ monkeypatch.setattr(peer_cmd, "_load_peers", lambda: {"spark": {"url": fake_peer_server}})+ monkeypatch.setattr(peer_cmd, "_peer_secret", lambda name: "secret-key-123456")++ rc = peer_cmd.cmd_peer(SimpleNamespace(peer_action="dm", target="spark", message="ping", json=True))++ assert rc == 0+ payload = json.loads(capsys.readouterr().out)+ assert payload["reply"] == "reply from the other machine"+ # No new session was created — the existing canonical chat was reused.+ assert _FakePeer.sessions == ["bc_existing"]diff --git a/tests/tools/test_bot_mode_probe.py b/tests/tools/test_bot_mode_probe.pyindex a1e9177328d..b74b85c5223 100644--- a/tests/tools/test_bot_mode_probe.py+++ b/tests/tools/test_bot_mode_probe.py@@ -200,3 +200,53 @@ def test_legacy_bot_chat_upgrade(tmp_path):home2 = tmp_path / ".hermes2"home2.mkdir()assert not bot_mode_probe.stored_bot_chat_prompt_needs_upgrade(legacy, home2)+++# ── peer gateways (cross-machine DMs) ────────────────────────────────────────+++def test_peer_paragraph_absent_without_peers(tmp_path):+ home = tmp_path / ".hermes"+ home.mkdir()+ _make_bot_profile(home, "researcher", managed=True)++ section = bot_mode_probe.get_bot_mode_protocol_section(home)+ assert "hermes peer dm" not in section+ assert "OTHER machines" not in section+++def test_peer_paragraph_lists_registered_peers(tmp_path):+ home = tmp_path / ".hermes"+ home.mkdir()+ _make_bot_profile(home, "researcher", managed=True)+ (home / "config.yaml").write_text(+ textwrap.dedent(+ """\+ bot_peers:+ spark:+ url: http://spark.lan:8377+ homelab:+ url: http://homelab.lan:8377+ """+ ),+ encoding="utf-8",+ )++ section = bot_mode_probe.get_bot_mode_protocol_section(home)+ assert "hermes peer dm" in section+ assert "`homelab`" in section and "`spark`" in section+ assert "hermes peer list" in section+++def test_fingerprint_changes_when_a_peer_is_registered(tmp_path):+ home = tmp_path / ".hermes"+ home.mkdir()+ _make_bot_profile(home, "researcher", managed=True)++ before = bot_mode_probe.capability_fingerprint(home)+ (home / "config.yaml").write_text(+ "bot_peers:\n spark:\n url: http://spark.lan:8377\n",+ encoding="utf-8",+ )+ after = bot_mode_probe.capability_fingerprint(home)+ assert before != afterdiff --git a/tools/bot_mode_probe.py b/tools/bot_mode_probe.pyindex c1bcfce5716..0ae74c5ff15 100644--- a/tools/bot_mode_probe.py+++ b/tools/bot_mode_probe.py@@ -105,6 +105,49 @@ def _handle(name: str) -> str:return "hermes" if name == "default" else name+def _peers(root: Path) -> list[str]:+ """Registered peer gateway names (``hermes peer``), for the protocol text.++ Reads config.yaml directly (cheap, no config-loader import) — the section+ is optional and absent on most installs. Never raises.+ """+ try:+ cfg_path = root / "config.yaml"+ if not cfg_path.is_file():+ return []+ raw = cfg_path.read_text(encoding="utf-8", errors="replace")+ if "bot_peers" not in raw:+ return []+ import yaml++ data = yaml.safe_load(raw)+ peers = data.get("bot_peers") if isinstance(data, dict) else None+ if not isinstance(peers, dict):+ return []+ return sorted(str(name) for name in peers if str(name).strip())+ except Exception:+ return []+++def _peer_paragraph(root: Path) -> str:+ """Protocol addendum for cross-machine DMs — only when peers exist."""+ peers = _peers(root)+ if not peers:+ return ""+ listed = ", ".join(f"`{p}`" for p in peers)+ return (+ "\n\nTeammates on OTHER machines: this install also has peer gateways "+ f"registered ({listed}). Message an agent on a peer the same way, via "+ "`hermes peer dm` (same terminal-tool pattern: background=true, "+ "notify_on_complete=true; the reply prints on stdout when it completes):\n"+ "```\n"+ 'hermes peer dm <peer>/<agent-name> "Message from 🤖 <you> (@<you>): your message"\n'+ "```\n"+ "Use `<peer>` alone for the peer's main agent. Run `hermes peer list` "+ "for the live peer list."+ )++def _build_section(home: Path) -> str:root = _hermes_root(home)me = _profile_name(home)@@ -138,6 +181,7 @@ def _build_section(home: Path) -> str:"handoff: message that agent, wait for the reply, and report back, saying ""which agent it came from. Run `hermes profile list` for the LIVE teammate "f"list before a handoff. Teammates at session start: {teammates}."+ + _peer_paragraph(root))@@ -230,6 +274,13 @@ def capability_fingerprint(home: str | os.PathLike | None = None) -> str:surface["roster"] = sorted(n for n, d in _roster(root) if _is_bot_managed(d))except Exception:surface["roster"] = []+ try:+ # Peer gateways are part of the messaging surface: registering one+ # must refresh eternal Bot Chat prompts so the cross-machine DM+ # paragraph appears on the next message.+ surface["peers"] = _peers(_hermes_root(resolved))+ except Exception:+ surface["peers"] = []try:blob = json.dumps(surface, sort_keys=True).encode("utf-8")return hashlib.sha256(blob).hexdigest()[:12]diff --git a/website/docs/reference/cli-commands.md b/website/docs/reference/cli-commands.mdindex e853c1fccab..2b873479611 100644--- a/website/docs/reference/cli-commands.md+++ b/website/docs/reference/cli-commands.md@@ -53,6 +53,7 @@ hermes [global-options] <command> [subcommand/options]| `hermes auth` | Manage credentials — add, list, remove, reset, status, logout. Handles OAuth flows for Codex/Nous/Anthropic. || `hermes login` / `logout` | **Deprecated** — use `hermes auth` instead. || `hermes send` | Send a one-shot message to a configured messaging platform (Telegram, Discord, Slack, Signal, SMS, …). Useful from shell scripts, cron jobs, CI hooks, and monitoring daemons — no agent loop, no LLM. |+| `hermes peer` | Register peer Hermes gateways on other machines and DM their agents' canonical Bot Chats (`hermes peer dm <peer>[/<agent>] "…"`). The transport behind cross-machine bot-to-bot messaging. || `hermes secrets` | Manage external secret sources (currently Bitwarden Secrets Manager) for pulling API keys at process startup instead of from `~/.hermes/.env`. || `hermes migrate` | Diagnose and (optionally) rewrite `config.yaml` to replace references to retired models or deprecated settings (e.g. `migrate xai`). || `hermes status` | Show agent, auth, and platform status. |@@ -438,6 +439,42 @@ hermes send --list telegram # filter by platform```++## `hermes peer`++```bash+hermes peer add <name> --url http://host:port --key <API_SERVER_KEY>+hermes peer list+hermes peer dm <peer>[/<agent>] "message"+hermes peer remove <name>+```++Bot-to-bot DMs across machines. Register another Hermes gateway (any machine+running the `api_server` platform) as a *peer*, then message its agents:+`hermes peer dm` resolves the remote agent's canonical **Bot Chat** session+over the peer's API server, runs one agent turn there, and prints the reply+on stdout — the cross-machine twin of the local+`hermes -p <bot> chat --in ~ -c "Bot Chat" …` bot-messaging command.++`<peer>` alone targets the peer gateway's main agent;+`<peer>/<agent>` targets a named profile on a multiplexed peer (routed via+its `/p/<profile>/` mirror).++| Subcommand | Description |+|--------|-------------|+| `add <name> --url <URL> [--key <KEY>] [--note TEXT]` | Register or update a peer. The URL goes to `config.yaml` (`bot_peers`); the key is stored as `HERMES_PEER_<NAME>_KEY` in `~/.hermes/.env`. |+| `list` | List peers and whether each has a key configured. |+| `dm <peer>[/<agent>] [message]` | Message the peer agent's canonical Bot Chat and print the reply (`--json` for machine-readable output; message falls back to stdin). |+| `remove <name>` | Remove a peer from the registry (the `.env` key entry is left in place). |++When at least one peer is registered, the Bot Mode messaging protocol+(`agent.bot_mode_protocol`) taught to every canonical Bot Chat automatically+includes the peer roster and the `hermes peer dm` pattern, so agents discover+cross-machine teammates without SOUL edits. See+[Bot Mode](../user-guide/bot-mode.md).++Exit codes: `0` on success, `1` on delivery/peer failure, `2` on usage errors.+## `hermes secrets````bashdiff --git a/website/docs/user-guide/bot-mode.md b/website/docs/user-guide/bot-mode.mdindex 4c81f86d2a1..40382b5b981 100644--- a/website/docs/user-guide/bot-mode.md+++ b/website/docs/user-guide/bot-mode.md@@ -104,6 +104,23 @@ agent:Bot-to-bot delivery is per-invocation: the receiving Bot picks the message up when it next runs. Live interrupt of a Bot mid-conversation is future work.:::+### Bot-initiated DMs across machines (`hermes peer`)++Bots on one machine can message Bots on **another machine's gateway** without any desktop in the loop. Register the other gateway as a *peer* (its API server URL + `API_SERVER_KEY`):++```bash+hermes peer add spark --url http://spark.lan:8377 --key <API_SERVER_KEY>+hermes peer list+hermes peer dm spark "Message from 🤖 dixie (@dixie): disk status?"+hermes peer dm spark/researcher "..." # named profile on a multiplexed peer+```++`hermes peer dm` delivers into the remote agent's canonical Bot Chat over the peer's existing API server, runs one agent turn there, and prints the reply on stdout — the exact cross-machine twin of the local `hermes -p <bot> chat` command.++Once a peer is registered, the messaging protocol taught to every Bot Chat (`agent.bot_mode_protocol`) automatically includes the peer roster and the `hermes peer dm` pattern — so **your bots learn on their own** that teammates exist on other machines and how to reach them. Registering or removing a peer refreshes each Bot Chat's protocol on its next message (capability epoch).++Requirements: the peer machine runs the `api_server` gateway platform with a strong `API_SERVER_KEY`; reachability is your network's business (LAN, Tailscale, VPN). The key is a credential and lives in `~/.hermes/.env` as `HERMES_PEER_<NAME>_KEY`; peer names/URLs live in `config.yaml` under `bot_peers`.+## Bots across machinesWhen you register several backends in **Settings → Connections** — the local runtime, remote gateways, SSH hosts, Hermes Cloud instances — the roster shows the Bots from **every** connected source, persistently: SSH sources are inventoried without spawning anything on the remote box, and machines that are momentarily unreachable keep their last-known rows instead of vanishing. When the same profile name exists on several sources, handles disambiguate as `@name-device` (for example `@research-homelab`). A Bot's chats, sessions, memory, and routines live on the machine that owns the profile.