peer.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. """``hermes peer`` — bot-to-bot DMs across machines/gateways.
  2. A *peer* is another Hermes gateway running the ``api_server`` platform; its stock
  3. API is the transport (no new server surface). ``dm`` resolves the remote canonical
  4. "Bot Chat" session (creating it when missing) and runs ONE synchronous turn — the
  5. cross-machine twin of ``hermes -p <bot> chat --in ~ -c "Bot Chat"``. ``run``/``status``
  6. /``stop`` do the same turn through the async Runs API. Peer labels/URLs live in
  7. config.yaml (``bot_peers``); the key lives in ``~/.hermes/.env`` as
  8. ``HERMES_PEER_<NAME>_KEY``. ``<peer>/<profile>`` targets the ``/p/<profile>/`` mirror.
  9. """
  10. from __future__ import annotations
  11. import argparse
  12. import json
  13. import re
  14. import sys
  15. import urllib.error
  16. import urllib.parse
  17. import urllib.request
  18. import uuid
  19. BOT_CHAT_TITLE = "Bot Chat"
  20. _PEER_NAME_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{0,63}$")
  21. _PROFILE_RE = re.compile(r"^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$")
  22. # The @handle Bot Mode shows for a host's default profile, and the body of the 404 a peer returns for
  23. # a /p/<profile>/ prefix naming no profile it has (UNKNOWN_PROFILE_ERROR in
  24. # gateway/platforms/api_server_profile_prefix.py; a 'hermes' profile it has but does not serve differs).
  25. DEFAULT_PROFILE_HANDLE = "hermes"
  26. _UNKNOWN_PROFILE_ERROR = "Unknown or unconfigured profile"
  27. # One synchronous agent turn can legitimately take minutes.
  28. DM_TIMEOUT_S = 600
  29. LIST_TIMEOUT_S = 30
  30. def _peer_key_env(name: str) -> str:
  31. return f"HERMES_PEER_{name.upper().replace('-', '_')}_KEY"
  32. def _load_peers() -> dict:
  33. from hermes_cli.config import load_config
  34. cfg = load_config() or {}
  35. peers = cfg.get("bot_peers")
  36. return peers if isinstance(peers, dict) else {}
  37. def _save_peers(peers: dict) -> None:
  38. from hermes_cli.config import load_config, save_config
  39. cfg = load_config() or {}
  40. cfg["bot_peers"] = peers
  41. save_config(cfg)
  42. def _peer_secret(name: str) -> str:
  43. """The peer's API key: profile-scoped secret store first, raw env fallback."""
  44. env_name = _peer_key_env(name)
  45. try:
  46. from agent.secret_scope import get_secret
  47. return (get_secret(env_name, "") or "").strip()
  48. except Exception:
  49. import os
  50. return (os.environ.get(env_name) or "").strip()
  51. def _request(
  52. url: str, key: str, *, method: str = "GET", body: dict | None = None,
  53. timeout: int = LIST_TIMEOUT_S, headers: dict[str, str] | None = None) -> dict:
  54. from hermes_cli.urllib_security import open_credentialed_url
  55. data = json.dumps(body).encode("utf-8") if body is not None else None
  56. request_headers = {
  57. "Authorization": f"Bearer {key}", "Content-Type": "application/json",
  58. "User-Agent": "hermes-peer-dm"}
  59. if headers:
  60. request_headers.update(headers)
  61. req = urllib.request.Request(url, data=data, method=method, headers=request_headers)
  62. # The peer URL is user-registered (``hermes peer add``); a redirect to a
  63. # different origin must not carry the Authorization: Bearer key with it —
  64. # a compromised/MITM'd peer could otherwise harvest it. open_credentialed_url
  65. # strips non-safelisted headers across a cross-origin redirect.
  66. with open_credentialed_url(req, timeout=timeout) as resp:
  67. payload = resp.read().decode("utf-8", "replace")
  68. try:
  69. parsed = json.loads(payload)
  70. except ValueError as exc:
  71. raise RuntimeError(f"Peer returned non-JSON response: {payload[:200]}") from exc
  72. if not isinstance(parsed, dict):
  73. raise RuntimeError("Peer returned a non-object JSON response")
  74. return parsed
  75. def _base_url(peer: dict, profile: str | None) -> str:
  76. url = str(peer.get("url") or "").rstrip("/")
  77. if profile:
  78. # Multiplex mirror: same handlers, scoped to the named profile.
  79. return f"{url}/p/{urllib.parse.quote(profile, safe='')}"
  80. return url
  81. def _peer_lacks_profile(exc: Exception) -> bool:
  82. """True only for the peer's own "no such profile" verdict: the 404 its /p/<profile>/ prefix
  83. middleware returns before any handler runs. A handler's 404 (unknown run or session) carries
  84. ``{"error": {"message": ...}}`` and a transport failure is no verdict at all."""
  85. if not isinstance(exc, urllib.error.HTTPError) or exc.code != 404:
  86. return False
  87. try:
  88. body = json.loads(exc.read().decode("utf-8", "replace"))
  89. except (OSError, ValueError):
  90. return False
  91. return isinstance(body, dict) and body.get("error") == _UNKNOWN_PROFILE_ERROR
  92. def _resolve_base(peer: dict, profile: str | None, key: str, peer_name: str = "") -> str:
  93. """The mirror a target addresses. Bot Mode shows a peer's default profile as @hermes
  94. (#118076); an upgraded peer aliases ``/p/hermes`` to its default itself, unless it has a real
  95. pre-reservation profile named ``hermes``, which keeps the handle. The client never reroutes on
  96. its own: an older peer answers the same generic 404 for "no such profile" and for a real
  97. ``hermes`` profile it does not serve (parked, standalone), so guessing ``/p/default`` there
  98. delivers into the wrong agent. That ambiguous answer becomes an error naming the explicit
  99. ``<peer>/default`` address instead."""
  100. base = _base_url(peer, profile)
  101. if profile != DEFAULT_PROFILE_HANDLE:
  102. return base
  103. try:
  104. _request(f"{base}/health", key)
  105. except (urllib.error.URLError, TimeoutError, OSError, RuntimeError) as exc:
  106. if _peer_lacks_profile(exc):
  107. name = peer_name or "<peer>"
  108. raise LookupError(
  109. f"Peer '{name}' answered that it serves no '{DEFAULT_PROFILE_HANDLE}' profile. That answer "
  110. f"is ambiguous: an up-to-date gateway gives it when it does not serve its default profile, "
  111. f"and an older one also when it has a '{DEFAULT_PROFILE_HANDLE}' profile it does not serve. "
  112. f"If the peer serves its default profile, address that bot as {name}/default.") from exc
  113. return base
  114. def _find_bot_chat(base: str, key: str) -> str | None:
  115. """The remote canonical Bot Chat's session id, or None.
  116. Bot Mode always HIDES canonical chats, so the plain listing (which
  117. excludes hidden sessions) misses an existing Bot Chat and the caller
  118. would try to create a duplicate that the peer's UNIQUE(title) guard
  119. rejects (issue #91583). Newer peers support an exact-title lookup with
  120. ``include_hidden=1``; older peers ignore the unknown query params and
  121. return the ordinary visible listing, so this single request degrades
  122. to exactly the previous behavior against them.
  123. """
  124. query = urllib.parse.urlencode({"limit": 200, "title": BOT_CHAT_TITLE, "include_hidden": 1})
  125. listing = _request(f"{base}/api/sessions?{query}", key)
  126. for session in listing.get("data") or []:
  127. if isinstance(session, dict) and (session.get("title") or "").strip() == BOT_CHAT_TITLE:
  128. return str(session.get("id") or "") or None
  129. return None
  130. def _ensure_bot_chat(base: str, key: str) -> str:
  131. existing = _find_bot_chat(base, key)
  132. if existing:
  133. return existing
  134. try:
  135. created = _request(
  136. f"{base}/api/sessions", key, method="POST",
  137. body={"title": BOT_CHAT_TITLE, "source": "bot_peer_dm"})
  138. except urllib.error.HTTPError as exc:
  139. detail = _http_error_detail(exc)
  140. if exc.code == 400 and "title" in detail.lower():
  141. # Older peer (no title/include_hidden lookup support): its
  142. # canonical Bot Chat exists but is hidden, so we couldn't see it
  143. # and the create collided with the UNIQUE(title) guard.
  144. raise RuntimeError(
  145. f"Peer already has a '{BOT_CHAT_TITLE}' session but it is hidden and the "
  146. f"peer's gateway is too old to expose hidden sessions to this lookup "
  147. f"(HTTP 400: {detail}). Update the peer's hermes-agent, or unhide the "
  148. f"session there: PATCH /api/sessions/<id> {{\"hidden\": false}}.") from exc
  149. raise
  150. # Real api_server wraps the row: {"object": "hermes.session", "session": {...}}.
  151. session = created.get("session") if isinstance(created.get("session"), dict) else created
  152. session_id = str(session.get("id") or session.get("session_id") or "")
  153. if not session_id:
  154. raise RuntimeError("Peer did not return a session id for the new Bot Chat")
  155. return session_id
  156. def _parse_target(target: str) -> tuple[str, str | None]:
  157. """``<peer>`` or ``<peer>/<profile>`` → (peer, profile|None)."""
  158. raw = (target or "").strip()
  159. peer, _, profile = raw.partition("/")
  160. peer = peer.strip()
  161. profile = profile.strip() or None
  162. if not peer:
  163. raise ValueError("Peer name required (hermes peer dm <peer>[/<agent>] ...)")
  164. if profile and not _PROFILE_RE.match(profile):
  165. raise ValueError(f"Invalid agent/profile name: {profile!r}")
  166. if profile:
  167. # Profile ids are lowercase (normalize_profile_name); 'box/Hermes' must address the
  168. # peer's real 'hermes' profile on every peer, including those that compare prefixes exactly.
  169. from hermes_cli.profiles import normalize_profile_name
  170. profile = normalize_profile_name(profile)
  171. return peer, profile
  172. def _http_error_detail(exc: urllib.error.HTTPError) -> str:
  173. try:
  174. body = exc.read().decode("utf-8", "replace")
  175. parsed = json.loads(body)
  176. message = parsed.get("error", {}).get("message") if isinstance(parsed, dict) else None
  177. return message or body[:200]
  178. except Exception:
  179. return str(exc)
  180. def _resolve_peer_target(target: str) -> tuple[str, str | None, dict, str]:
  181. """Resolve a registered target to ``(name, profile, config, key)``."""
  182. peer_name, profile = _parse_target(target)
  183. peer = _load_peers().get(peer_name)
  184. if not isinstance(peer, dict) or not peer.get("url"):
  185. raise LookupError(f"No peer named '{peer_name}'. Run: hermes peer list")
  186. key = _peer_secret(peer_name)
  187. if not key:
  188. raise PermissionError(
  189. f"No API key for peer '{peer_name}'. Set it: hermes peer add {peer_name} "
  190. f"--url <url> --key <key> (or add {_peer_key_env(peer_name)}=<key> to ~/.hermes/.env)")
  191. return peer_name, profile, peer, key
  192. def _message_from_args(args) -> str:
  193. message = (getattr(args, "message", None) or "").strip()
  194. if not message and not sys.stdin.isatty():
  195. message = sys.stdin.read().strip()
  196. return message
  197. def _peer_run_durability(base: str, key: str) -> bool | None:
  198. """Return durable support, or None when an older peer cannot advertise it."""
  199. try:
  200. capabilities = _request(f"{base}/v1/capabilities", key)
  201. except Exception:
  202. return None
  203. features = capabilities.get("features")
  204. if not isinstance(features, dict):
  205. return None
  206. contract = features.get("runs_idempotency")
  207. if not isinstance(contract, dict) or not contract.get("supported"):
  208. return None
  209. return bool(contract.get("durable"))
  210. def _peer_failure(peer_name: str, exc: Exception) -> int:
  211. """Print a peer HTTP rejection or transport failure to stderr; always exit 1."""
  212. if isinstance(exc, urllib.error.HTTPError):
  213. detail = _http_error_detail(exc)
  214. print(f"Peer '{peer_name}' rejected the request (HTTP {exc.code}): {detail}",
  215. file=sys.stderr)
  216. else:
  217. print(f"Could not reach peer '{peer_name}': {exc}", file=sys.stderr)
  218. return 1
  219. def _emit(args, payload: dict, text_lines: list[str]) -> int:
  220. if getattr(args, "json", False):
  221. print(json.dumps(payload))
  222. else:
  223. for line in text_lines:
  224. print(line)
  225. return 0
  226. def _peer_add(args) -> int:
  227. name = (args.name or "").strip().lower()
  228. if not _PEER_NAME_RE.match(name):
  229. print(f"Invalid peer name: {name!r} (lowercase, digits, -, _; max 64)", file=sys.stderr)
  230. return 2
  231. url = (args.url or "").strip()
  232. if not url.lower().startswith(("http://", "https://")):
  233. print("Peer --url must be an http(s) gateway base URL, e.g. http://spark.lan:8377", file=sys.stderr)
  234. return 2
  235. peers = _load_peers()
  236. peers[name] = {"url": url.rstrip("/"), **({"note": args.note.strip()} if getattr(args, "note", "") else {})}
  237. _save_peers(peers)
  238. key = (getattr(args, "key", "") or "").strip()
  239. if key:
  240. from hermes_cli.config import save_env_value
  241. save_env_value(_peer_key_env(name), key)
  242. print(f"Peer '{name}' saved ({url}) — key stored as {_peer_key_env(name)} in ~/.hermes/.env")
  243. else:
  244. print(
  245. f"Peer '{name}' saved ({url}). No key given — set the peer's API_SERVER_KEY with:\n"
  246. f" hermes peer add {name} --url {url} --key <key>\n"
  247. f" (or add {_peer_key_env(name)}=<key> to ~/.hermes/.env)")
  248. return 0
  249. def _peer_remove(args) -> int:
  250. name = (args.name or "").strip().lower()
  251. peers = _load_peers()
  252. if name not in peers:
  253. print(f"No peer named '{name}'.", file=sys.stderr)
  254. return 1
  255. peers.pop(name)
  256. _save_peers(peers)
  257. print(f"Peer '{name}' removed (its {_peer_key_env(name)} entry in .env is kept; delete it manually if unused).")
  258. return 0
  259. def _peer_list(args) -> int:
  260. peers = _load_peers()
  261. if not peers:
  262. print("No peers registered. Add one: hermes peer add <name> --url http://host:port --key <API_SERVER_KEY>")
  263. return 0
  264. for name in sorted(peers):
  265. entry = peers[name] if isinstance(peers[name], dict) else {}
  266. has_key = "key set" if _peer_secret(name) else f"NO KEY ({_peer_key_env(name)} unset)"
  267. note = f" — {entry.get('note')}" if entry.get("note") else ""
  268. print(f"{name}\t{entry.get('url', '?')}\t[{has_key}]{note}")
  269. return 0
  270. def _peer_run_ctl(args, action: str, peer_name: str, profile: str | None, base: str,
  271. key: str) -> int:
  272. """``status`` / ``stop`` on an asynchronous run."""
  273. run_id = (getattr(args, "run_id", None) or "").strip()
  274. if not run_id:
  275. print("Run ID required.", file=sys.stderr)
  276. return 2
  277. stop = action == "stop"
  278. try:
  279. result = _request(
  280. f"{base}/v1/runs/{urllib.parse.quote(run_id, safe='')}" + ("/stop" if stop else ""),
  281. key, method="POST" if stop else "GET", body={} if stop else None)
  282. except (urllib.error.URLError, TimeoutError, OSError, RuntimeError) as exc:
  283. return _peer_failure(peer_name, exc)
  284. if getattr(args, "json", False):
  285. print(json.dumps({"peer": peer_name, "profile": profile, **result}))
  286. return 0
  287. print(f"{run_id}: {result.get('status', 'unknown')}")
  288. if not stop and result.get("output"):
  289. print(result["output"])
  290. elif not stop and result.get("error"):
  291. print(result["error"], file=sys.stderr)
  292. return 0
  293. def _turn_body(message: str, *, message_key: str, **extra) -> dict:
  294. """Request body for one turn. ``author`` is added only when a dispatcher set HERMES_TURN_AUTHOR."""
  295. from agent.turn_author import turn_author_from_env
  296. body = {message_key: message, **extra}
  297. author = turn_author_from_env()
  298. if author is not None:
  299. body["author"] = author
  300. return body
  301. def _peer_run(args, message: str, peer_name: str, profile: str | None, base: str, key: str) -> int:
  302. idempotency_key = (getattr(args, "idempotency_key", None) or f"peer-{uuid.uuid4().hex}").strip()
  303. if (not idempotency_key or len(idempotency_key) > 255
  304. or re.search(r"[\r\n\x00]", idempotency_key)):
  305. print("Idempotency key must be 1-255 characters without control newlines.", file=sys.stderr)
  306. return 2
  307. try:
  308. if _peer_run_durability(base, key) is not True:
  309. print(
  310. "Warning: this peer does not advertise restart-durable "
  311. "run replay; keep the run ID and avoid blind retries "
  312. "after a gateway restart.", file=sys.stderr)
  313. session_id = _ensure_bot_chat(base, key)
  314. result = _request(
  315. f"{base}/v1/runs", key, method="POST",
  316. body=_turn_body(message, message_key="input", session_id=session_id),
  317. headers={"Idempotency-Key": idempotency_key})
  318. except (urllib.error.URLError, TimeoutError, OSError, RuntimeError) as exc:
  319. return _peer_failure(peer_name, exc)
  320. run_id = str(result.get("run_id") or "")
  321. if not run_id:
  322. print(f"Peer '{peer_name}' did not return a run ID.", file=sys.stderr)
  323. return 1
  324. payload = {
  325. "peer": peer_name, "profile": profile, "session_id": session_id, "run_id": run_id,
  326. "status": result.get("status") or "started", "idempotency_key": idempotency_key,
  327. "replayed": bool(result.get("replayed", False))}
  328. replay = " (replayed)" if payload["replayed"] else ""
  329. return _emit(args, payload, [
  330. f"{run_id}: {payload['status']}{replay}", f"session_id: {session_id}",
  331. f"idempotency_key: {idempotency_key}"])
  332. def _peer_dm(args, message: str, peer_name: str, profile: str | None, base: str, key: str) -> int:
  333. session_id = ""
  334. try:
  335. session_id = _ensure_bot_chat(base, key)
  336. result = _request(
  337. f"{base}/api/sessions/{urllib.parse.quote(session_id, safe='')}/chat", key,
  338. method="POST", body=_turn_body(message, message_key="message"), timeout=DM_TIMEOUT_S)
  339. except RuntimeError as exc:
  340. print(f"Peer '{peer_name}': {exc}", file=sys.stderr)
  341. return 1
  342. except (urllib.error.URLError, TimeoutError, OSError) as exc:
  343. # A timeout while awaiting the response, once the Bot Chat is known, means the peer took
  344. # this turn: the message is already in its Bot Chat and the gateway runs the turn to
  345. # completion regardless of this client, so reporting it unreachable makes the sender resend
  346. # and deliver it twice. urllib raises that timeout bare; one it wraps in URLError hit while
  347. # connecting or sending, so the request never arrived and "could not reach" is the truth.
  348. if session_id and isinstance(exc, TimeoutError):
  349. print(f"Peer '{peer_name}' accepted the message but its turn is still running after "
  350. f"{DM_TIMEOUT_S}s: the message is already in its Bot Chat (session {session_id}) "
  351. "and will be answered there. The reply cannot come back on this call. Do NOT resend.",
  352. file=sys.stderr)
  353. return 1
  354. return _peer_failure(peer_name, exc)
  355. if result.get("object") == "hermes.session.chat.queued":
  356. # The peer's Bot Chat is open in its Desktop and that turn outlasted the peer's wait: the
  357. # message is in the open chat and is answered there, so a resend would run it twice.
  358. queued_in = result.get("session_id") or session_id
  359. return _emit(args, {"peer": peer_name, "profile": profile, "session_id": queued_in,
  360. "status": result.get("status") or "queued", "delivery_id": result.get("delivery_id")},
  361. [f"Peer '{peer_name}' has its Bot Chat open, so the message went into that chat (session "
  362. f"{queued_in}) and is answered there. The reply cannot come back on this call. Do NOT resend."])
  363. msg = result.get("message")
  364. reply = str(msg.get("content") or "") if isinstance(msg, dict) else ""
  365. # A successful bare silence marker is a delivery decision, not a message:
  366. # the turn stays in the peer's own transcript, the sending agent never
  367. # sees NO_REPLY/[SILENT] as a real reply. Same rule as the gateway's live
  368. # Bot Chat completion, the Desktop bot_relay.deliver RPC and the one-shot
  369. # local `hermes chat -Q` transport (tools/bot_mode_dm.py) — this is the
  370. # 4th Bot Mode delivery door and was missing the same check.
  371. from gateway.response_filters import is_intentional_silence_response, strip_trailing_silence_marker
  372. reply = "" if is_intentional_silence_response(reply) else strip_trailing_silence_marker(reply)
  373. payload = {"peer": peer_name, "profile": profile,
  374. "session_id": result.get("session_id") or session_id, "reply": reply}
  375. return _emit(args, payload, [reply or "(no reply)"])
  376. _REGISTRY_ACTIONS = {
  377. "add": _peer_add, "set": _peer_add, "remove": _peer_remove, "rm": _peer_remove,
  378. "list": _peer_list, "ls": _peer_list, None: _peer_list}
  379. def cmd_peer(args) -> int:
  380. action = getattr(args, "peer_action", None)
  381. if action in _REGISTRY_ACTIONS:
  382. return _REGISTRY_ACTIONS[action](args)
  383. if action not in {"dm", "run", "status", "stop"}:
  384. print("Unknown peer action. See: hermes peer --help", file=sys.stderr)
  385. return 2
  386. try:
  387. peer_name, profile, peer, key = _resolve_peer_target(args.target)
  388. except ValueError as exc:
  389. print(str(exc), file=sys.stderr)
  390. return 2
  391. except (LookupError, PermissionError) as exc:
  392. print(str(exc), file=sys.stderr)
  393. return 1
  394. try:
  395. base = _resolve_base(peer, profile, key, peer_name)
  396. except LookupError as exc:
  397. print(str(exc), file=sys.stderr)
  398. return 1
  399. if action in {"status", "stop"}:
  400. return _peer_run_ctl(args, action, peer_name, profile, base, key)
  401. message = _message_from_args(args)
  402. if not message:
  403. print("Message required (argument or stdin).", file=sys.stderr)
  404. return 2
  405. handler = _peer_run if action == "run" else _peer_dm
  406. return handler(args, message, peer_name, profile, base, key)
  407. def build_peer_parser(subparsers) -> None:
  408. """Attach the ``peer`` subcommand to ``subparsers``."""
  409. parser = subparsers.add_parser(
  410. "peer", help="Bot-to-bot DMs across machines (peer Hermes gateways)",
  411. description="Register other Hermes gateways as peers and message their agents. "
  412. "'hermes peer dm <peer>[/<agent>] \"...\"' delivers into the remote "
  413. "agent's canonical Bot Chat over the peer's API server and prints "
  414. "the reply — the cross-machine twin of 'hermes -p <bot> chat'. "
  415. "The peer must run the api_server platform; its API_SERVER_KEY is "
  416. "stored locally as a credential in ~/.hermes/.env.",
  417. epilog=(
  418. "Examples:\n"
  419. " hermes peer add spark --url http://spark.lan:8377 --key <API_SERVER_KEY>\n"
  420. " hermes peer list\n"
  421. ' hermes peer dm spark "Message from 🤖 dixie (@dixie): disk status?"\n'
  422. ' hermes peer dm spark/researcher "..." # named profile on a multiplexed peer\n'
  423. " hermes peer run spark --idempotency-key ticket-123 < long-task.txt\n"
  424. " hermes peer status spark run_abc123\n"
  425. " hermes peer stop spark run_abc123\n"
  426. " hermes peer remove spark\n"
  427. "\n"
  428. "Exit codes: 0 ok, 1 delivery/peer error, 2 usage error."),
  429. formatter_class=argparse.RawDescriptionHelpFormatter)
  430. peer_sub = parser.add_subparsers(dest="peer_action")
  431. add_p = peer_sub.add_parser("add", aliases=["set"], help="Register (or update) a peer gateway")
  432. add_p.add_argument("name", help="Peer name (lowercase slug, e.g. spark, homelab)")
  433. add_p.add_argument("--url", required=True, help="Peer gateway base URL, e.g. http://spark.lan:8377")
  434. add_p.add_argument("--key", default="", help="The peer's API_SERVER_KEY (stored in ~/.hermes/.env)")
  435. add_p.add_argument("--note", default="", help="Optional description")
  436. peer_sub.add_parser("list", aliases=["ls"], help="List registered peers")
  437. rm_p = peer_sub.add_parser("remove", aliases=["rm"], help="Remove a peer")
  438. rm_p.add_argument("name", help="Peer name")
  439. def _remote(name: str, help: str, *, run_id: bool):
  440. sp = peer_sub.add_parser(name, help=help)
  441. sp.add_argument("target", help="<peer> or <peer>/<agent> (named profile on a multiplexed peer)")
  442. if run_id:
  443. sp.add_argument("run_id", help="Run ID returned by 'hermes peer run'")
  444. else:
  445. sp.add_argument("message", nargs="?", default=None, help="Message text (or stdin)")
  446. if name == "run":
  447. sp.add_argument(
  448. "--idempotency-key", default=None, help="Stable retry key (generated when omitted)")
  449. sp.add_argument("--json", action="store_true", default=False, help="Emit a JSON result")
  450. _remote("dm", "Message an agent on a peer gateway and print its reply", run_id=False)
  451. _remote("run", "Start a long peer turn asynchronously and return its run ID", run_id=False)
  452. _remote("status", "Read the status and final output of an asynchronous peer run", run_id=True)
  453. _remote("stop", "Stop one asynchronous peer run without affecting another turn", run_id=True)
  454. parser.set_defaults(func=cmd_peer)