The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(hermes_cli/subcommands): peer.py — dispatch-table cmd_peer into per-action handlers, unify error/JSON emission
Teknium0b0064209691
diff --git a/hermes_cli/subcommands/peer.py b/hermes_cli/subcommands/peer.pyindex a4249230bcd..6670513b950 100644--- a/hermes_cli/subcommands/peer.py+++ b/hermes_cli/subcommands/peer.py@@ -1,33 +1,12 @@"""``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)- hermes peer run spark --idempotency-key ticket-123 < /tmp/long-task.txt- hermes peer status spark run_abc123--``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.--``run`` starts the same canonical-session turn through the asynchronous Runs-API and returns a ``run_id`` immediately. ``status`` polls that handle without-holding the original HTTP connection open. Use this pair for long turns.--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.+A *peer* is another Hermes gateway running the ``api_server`` platform; its stock+API is the transport (no new server surface). ``dm`` resolves the remote canonical+"Bot Chat" session (creating it when missing) and runs ONE synchronous turn — the+cross-machine twin of ``hermes -p <bot> chat --in ~ -c "Bot Chat"``. ``run``/``status``+/``stop`` do the same turn through the async Runs API. Peer labels/URLs live in+config.yaml (``bot_peers``); the key lives in ``~/.hermes/.env`` as+``HERMES_PEER_<NAME>_KEY``. ``<peer>/<profile>`` targets the ``/p/<profile>/`` mirror."""from __future__ import annotations@@ -223,181 +202,182 @@ def _peer_run_durability(base: str, key: str) -> bool | None:return bool(contract.get("durable"))-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).")+def _peer_failure(peer_name: str, exc: Exception) -> int:+ """Print a peer HTTP rejection or transport failure to stderr; always exit 1."""+ if isinstance(exc, urllib.error.HTTPError):+ detail = _http_error_detail(exc)+ print(f"Peer '{peer_name}' rejected the request (HTTP {exc.code}): {detail}",+ file=sys.stderr)+ else:+ print(f"Could not reach peer '{peer_name}': {exc}", file=sys.stderr)+ return 1+++def _emit(args, payload: dict, text_lines: list[str]) -> int:+ if getattr(args, "json", False):+ print(json.dumps(payload))+ else:+ for line in text_lines:+ print(line)+ return 0+++def _peer_add(args) -> int:+ 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+++def _peer_remove(args) -> int:+ 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+++def _peer_list(args) -> int:+ 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-- 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}")+ 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+++def _peer_run_ctl(args, action: str, peer_name: str, profile: str | None, base: str,+ key: str) -> int:+ """``status`` / ``stop`` on an asynchronous run."""+ run_id = (getattr(args, "run_id", None) or "").strip()+ if not run_id:+ print("Run ID required.", file=sys.stderr)+ return 2+ stop = action == "stop"+ try:+ result = _request(+ f"{base}/v1/runs/{urllib.parse.quote(run_id, safe='')}" + ("/stop" if stop else ""),+ key, method="POST" if stop else "GET", body={} if stop else None)+ except (urllib.error.URLError, TimeoutError, OSError, RuntimeError) as exc:+ return _peer_failure(peer_name, exc)+ if getattr(args, "json", False):+ print(json.dumps({"peer": peer_name, "profile": profile, **result}))return 0+ print(f"{run_id}: {result.get('status', 'unknown')}")+ if not stop and result.get("output"):+ print(result["output"])+ elif not stop and result.get("error"):+ print(result["error"], file=sys.stderr)+ return 0+++def _peer_run(args, message: str, peer_name: str, profile: str | None, base: str, key: str) -> int:+ idempotency_key = (getattr(args, "idempotency_key", None) or f"peer-{uuid.uuid4().hex}").strip()+ if (not idempotency_key or len(idempotency_key) > 255+ or re.search(r"[\r\n\x00]", idempotency_key)):+ print("Idempotency key must be 1-255 characters without control newlines.", file=sys.stderr)+ return 2+ try:+ if _peer_run_durability(base, key) is not True:+ print(+ "Warning: this peer does not advertise restart-durable "+ "run replay; keep the run ID and avoid blind retries "+ "after a gateway restart.", file=sys.stderr)+ session_id = _ensure_bot_chat(base, key)+ result = _request(+ f"{base}/v1/runs", key, method="POST",+ body={"input": message, "session_id": session_id},+ headers={"Idempotency-Key": idempotency_key})+ except (urllib.error.URLError, TimeoutError, OSError, RuntimeError) as exc:+ return _peer_failure(peer_name, exc)+ run_id = str(result.get("run_id") or "")+ if not run_id:+ print(f"Peer '{peer_name}' did not return a run ID.", file=sys.stderr)+ return 1+ payload = {+ "peer": peer_name, "profile": profile, "session_id": session_id, "run_id": run_id,+ "status": result.get("status") or "started", "idempotency_key": idempotency_key,+ "replayed": bool(result.get("replayed", False))}+ replay = " (replayed)" if payload["replayed"] else ""+ return _emit(args, payload, [+ f"{run_id}: {payload['status']}{replay}", f"session_id: {session_id}",+ f"idempotency_key: {idempotency_key}"])+++def _peer_dm(args, message: str, peer_name: str, profile: str | None, base: str, key: str) -> int:+ 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 RuntimeError as exc:+ print(f"Peer '{peer_name}': {exc}", file=sys.stderr)+ return 1+ except (urllib.error.URLError, TimeoutError, OSError) as exc:+ return _peer_failure(peer_name, exc)+ msg = result.get("message")+ reply = str(msg.get("content") or "") if isinstance(msg, dict) else ""+ payload = {"peer": peer_name, "profile": profile,+ "session_id": result.get("session_id") or session_id, "reply": reply}+ return _emit(args, payload, [reply or "(no reply)"])+++_REGISTRY_ACTIONS = {+ "add": _peer_add, "set": _peer_add, "remove": _peer_remove, "rm": _peer_remove,+ "list": _peer_list, "ls": _peer_list, None: _peer_list}- if action in {"dm", "run", "status", "stop"}:- try:- peer_name, profile, peer, key = _resolve_peer_target(args.target)- except ValueError as exc:- print(str(exc), file=sys.stderr)- return 2- except (LookupError, PermissionError) as exc:- print(str(exc), file=sys.stderr)- return 1-- base = _base_url(peer, profile)-- if action in {"status", "stop"}:- run_id = (getattr(args, "run_id", None) or "").strip()- if not run_id:- print("Run ID required.", file=sys.stderr)- return 2- try:- result = _request(- f"{base}/v1/runs/{urllib.parse.quote(run_id, safe='')}"- + ("/stop" if action == "stop" else ""),- key, method="POST" if action == "stop" else "GET",- body={} if action == "stop" else None)- 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-- payload = {"peer": peer_name, "profile": profile, **result}- if getattr(args, "json", False):- print(json.dumps(payload))- else:- print(f"{run_id}: {result.get('status', 'unknown')}")- if action == "status" and result.get("output"):- print(result["output"])- elif action == "status" and result.get("error"):- print(result["error"], file=sys.stderr)- return 0-- message = _message_from_args(args)- if not message:- print("Message required (argument or stdin).", file=sys.stderr)- return 2-- if action == "run":- idempotency_key = (- getattr(args, "idempotency_key", None) or f"peer-{uuid.uuid4().hex}").strip()- if (- not idempotency_key- or len(idempotency_key) > 255- or re.search(r"[\r\n\x00]", idempotency_key)):- print(- "Idempotency key must be 1-255 characters without control newlines.",- file=sys.stderr)- return 2- try:- durability = _peer_run_durability(base, key)- if durability is not True:- print(- "Warning: this peer does not advertise restart-durable "- "run replay; keep the run ID and avoid blind retries "- "after a gateway restart.", file=sys.stderr)- session_id = _ensure_bot_chat(base, key)- result = _request(- f"{base}/v1/runs", key, method="POST",- body={"input": message, "session_id": session_id},- headers={"Idempotency-Key": idempotency_key})- 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-- run_id = str(result.get("run_id") or "")- if not run_id:- print(f"Peer '{peer_name}' did not return a run ID.", file=sys.stderr)- return 1- payload = {- "peer": peer_name, "profile": profile, "session_id": session_id, "run_id": run_id,- "status": result.get("status") or "started", "idempotency_key": idempotency_key,- "replayed": bool(result.get("replayed", False))}- if getattr(args, "json", False):- print(json.dumps(payload))- else:- replay = " (replayed)" if payload["replayed"] else ""- print(f"{run_id}: {payload['status']}{replay}")- print(f"session_id: {session_id}")- print(f"idempotency_key: {idempotency_key}")- return 0-- 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 RuntimeError as exc:- print(f"Peer '{peer_name}': {exc}", file=sys.stderr)- return 1- except (urllib.error.URLError, TimeoutError, OSError) 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 cmd_peer(args) -> int:+ action = getattr(args, "peer_action", None)+ if action in _REGISTRY_ACTIONS:+ return _REGISTRY_ACTIONS[action](args)+ if action not in {"dm", "run", "status", "stop"}:+ print("Unknown peer action. See: hermes peer --help", file=sys.stderr)+ return 2+ try:+ peer_name, profile, peer, key = _resolve_peer_target(args.target)+ except ValueError as exc:+ print(str(exc), file=sys.stderr)+ return 2+ except (LookupError, PermissionError) as exc:+ print(str(exc), file=sys.stderr)+ return 1+ base = _base_url(peer, profile)+ if action in {"status", "stop"}:+ return _peer_run_ctl(args, action, peer_name, profile, base, key)+ message = _message_from_args(args)+ if not message:+ print("Message required (argument or stdin).", file=sys.stderr)+ return 2+ handler = _peer_run if action == "run" else _peer_dm+ return handler(args, message, peer_name, profile, base, key)def build_peer_parser(subparsers) -> None: