shared_session_attach.py 4.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. """Discover a cooperative local runtime without taking its session lease.
  2. The owner's handshake supplies the existing authenticated WebSocket URL. A
  3. registry entry is discovery information, not authority to mint a credential.
  4. """
  5. from __future__ import annotations
  6. import ipaddress
  7. import json
  8. from pathlib import Path
  9. from urllib.parse import urlencode, urlsplit
  10. import httpx
  11. from hermes_constants import get_hermes_home
  12. from hermes_cli.active_sessions import active_session_registry_snapshot, session_owner_details
  13. def _local_origin(url: str, scheme: str) -> tuple[str, int]:
  14. parts = urlsplit(url)
  15. host = parts.hostname or ""
  16. try:
  17. local = ipaddress.ip_address(host).is_loopback
  18. except ValueError:
  19. local = False
  20. if (parts.scheme != scheme or not local or parts.username is not None
  21. or parts.password is not None or parts.fragment or not parts.port):
  22. raise ValueError("Shared runtime endpoint must be an explicit loopback address and port.")
  23. return host, parts.port
  24. def discover_attach_url(session_id: str, *, registry_home: str | Path | None = None) -> str | None:
  25. """Return a fenced authenticated URL, None for no owner, or refuse safely.
  26. This deliberately does not scan ports or read another profile. The runtime
  27. must advertise ``metadata.shared_runtime_url`` and implement the local
  28. ``/api/session-attach`` handshake. Unsupported owners keep their lease.
  29. """
  30. home = Path(registry_home if registry_home is not None else get_hermes_home()).resolve()
  31. owners = [entry for entry in active_session_registry_snapshot(home, strict=True)
  32. if entry.get("session_id") == session_id]
  33. if not owners:
  34. return None
  35. if len(owners) != 1:
  36. raise ValueError("Session owner identity is ambiguous; no attachment was attempted.")
  37. owner = owners[0]
  38. endpoint = (owner.get("metadata") or {}).get("shared_runtime_url")
  39. if not isinstance(endpoint, str) or not endpoint:
  40. raise ValueError("This chat is open in another Hermes window/terminal, and attaching "
  41. "this terminal to it is not available in this build. Close the chat "
  42. "there and run hermes --resume " + session_id + " here to take it over.\n"
  43. + session_owner_details(session_id, owner))
  44. origin = _local_origin(endpoint, "http")
  45. parts = urlsplit(endpoint)
  46. if parts.path not in ("", "/") or parts.query:
  47. raise ValueError("Shared runtime endpoint must be an origin without a path or query.")
  48. query = urlencode({"session_id": session_id, "lease_id": owner["lease_id"],
  49. "profile_home": str(home)})
  50. try:
  51. # Ignore proxy env and redirects: local discovery must stay on the
  52. # advertised endpoint, including on machines with corporate proxies.
  53. with httpx.Client(trust_env=False, follow_redirects=False, timeout=3.0) as client:
  54. with client.stream("GET", endpoint.rstrip("/") + "/api/session-attach?" + query) as response:
  55. response.raise_for_status()
  56. body = bytearray()
  57. for chunk in response.iter_bytes():
  58. body.extend(chunk)
  59. if len(body) > 65536:
  60. raise ValueError("Shared runtime handshake response is too large.")
  61. reply = json.loads(body)
  62. except (httpx.HTTPError, json.JSONDecodeError) as exc:
  63. # Never include a remote body or authenticated URL in diagnostics.
  64. raise ValueError("This chat is open in another Hermes window/terminal, and attaching "
  65. "this terminal to it just failed. Use the chat where it is open, or "
  66. "close it there and run hermes --resume " + session_id + " here.\n"
  67. + session_owner_details(session_id, owner)) from exc
  68. if not isinstance(reply, dict) or any(reply.get(key) != value for key, value in {
  69. "session_id": session_id, "lease_id": owner["lease_id"], "profile_home": str(home),
  70. }.items()):
  71. raise ValueError("Shared runtime handshake identity does not match the requested owner.")
  72. websocket_url = reply.get("websocket_url")
  73. if (not isinstance(websocket_url, str) or _local_origin(websocket_url, "ws") != origin
  74. or urlsplit(websocket_url).path != "/api/ws"):
  75. raise ValueError("Shared runtime handshake returned a different endpoint.")
  76. return websocket_url
  77. def configure_tui_attachment(env: dict[str, str], session_id: str | None, *,
  78. registry_home: str | Path | None = None) -> None:
  79. """Retain an explicit transport, otherwise attach a resumed owner's runtime."""
  80. if not session_id or env.get("HERMES_TUI_GATEWAY_URL", "").strip():
  81. return
  82. url = discover_attach_url(session_id, registry_home=registry_home)
  83. if url is not None:
  84. env["HERMES_TUI_GATEWAY_URL"] = url