connectors_cmd.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. """``hermes connectors``: list, connect, rename and remove hosted connector accounts."""
  2. from __future__ import annotations
  3. import re
  4. import sys
  5. import time
  6. from typing import Any, Callable, NoReturn
  7. _POLL_SECONDS = 2.0
  8. _DONE_STATES = frozenset({"connected", "skipped", "failed", "expired", "not_connected"})
  9. _SIGN_IN = "Run `hermes auth upgrade` to sign in."
  10. class _CommandError(Exception):
  11. """A user-facing failure: the message is printed and the command exits 1."""
  12. def _fail(message: str) -> NoReturn:
  13. raise _CommandError(message)
  14. def _valid_alias(alias: str) -> str:
  15. from tools.connectors.targets import ALIAS_PATTERN
  16. if not re.match(ALIAS_PATTERN, alias):
  17. _fail(f"Invalid name {alias!r}. Use 1 to 32 lowercase letters, digits or hyphens, "
  18. "starting with a letter or digit.")
  19. return alias
  20. def _account_name(row: dict[str, Any]) -> str:
  21. return str(row.get("alias") or row.get("label") or row.get("connectionId") or "")
  22. def _display_name(row: dict[str, Any]) -> str:
  23. return row["alias"] if row.get("alias") else f"{row.get('label') or row.get('connectionId')} (unnamed)"
  24. def _app_accounts(app: str) -> list[dict[str, Any]]:
  25. from tools.connectors.portal.client import PortalConnectorClient
  26. return [r for r in PortalConnectorClient().list_accounts() if str(r.get("connector", "")).lower() == app]
  27. def _names_hint(app: str, rows: list[dict[str, Any]]) -> str:
  28. names = sorted({_account_name(r) for r in rows})
  29. return f"Its accounts are: {', '.join(names)}." if names else f"You have no {app} account."
  30. def _match_named(app: str, rows: list[dict[str, Any]], name: str) -> dict[str, Any]:
  31. matches = [r for r in rows if r.get("alias") == name] or [
  32. r for r in rows if not r.get("alias") and r.get("label") == name]
  33. if len(matches) != 1:
  34. what = "No" if not matches else "More than one"
  35. _fail(f"{what} {app} account is called {name!r}. {_names_hint(app, rows)}")
  36. return matches[0]
  37. def _list(args) -> int:
  38. from tools.connectors.managed import managed_client
  39. rows = managed_client(creates_guest=True).list_connectors()
  40. if not rows:
  41. print("No connectors are available.")
  42. return 0
  43. width = max(len(str(r.get("connector", ""))) for r in rows)
  44. for row in sorted(rows, key=lambda r: str(r.get("connector", ""))):
  45. state = "connected" if row.get("connected") else "not connected"
  46. print(f"{str(row.get('connector', '')).ljust(width)} {state}")
  47. return 0
  48. def _accounts(args) -> int:
  49. from tools.connectors.portal.client import PortalConnectorClient
  50. app = (args.app or "").strip().lower()
  51. rows = [r for r in PortalConnectorClient().list_accounts()
  52. if not app or str(r.get("connector", "")).lower() == app]
  53. retired = [r for r in rows if r.get("disabled")]
  54. shown = rows if args.all else [r for r in rows if not r.get("disabled")]
  55. if not shown and not retired:
  56. print(f"You have no {app} account." if app else "You have no connected accounts.")
  57. return 0
  58. table = [(str(r.get("connector", "")), _display_name(r), str(r.get("status", "")) + (" (retired)" if r.get("disabled") else ""))
  59. for r in sorted(shown, key=lambda r: (str(r.get("connector", "")), _account_name(r)))]
  60. if table:
  61. app_width = max(len(row[0]) for row in table)
  62. name_width = max(len(row[1]) for row in table)
  63. for connector, name, status in table:
  64. print(f"{connector.ljust(app_width)} {name.ljust(name_width)} {status}")
  65. if retired and not args.all:
  66. print(f"{len(retired)} retired (use --all to list)")
  67. return 0
  68. def _wait_for_link(start, app: str) -> dict[str, Any]:
  69. """Poll the operation until its one target settles; returns the last target snapshot."""
  70. printed_url = False
  71. while True:
  72. snapshot = start.operation.snapshot()
  73. target = snapshot["targets"][0]
  74. url = target.get("connect_url")
  75. if url and not printed_url:
  76. print(url, flush=True)
  77. print("Open this link in your browser to finish.", flush=True)
  78. printed_url = True
  79. if target.get("state") in _DONE_STATES or snapshot.get("settled_at") is not None:
  80. return target
  81. if time.time() >= start.operation.deadline_at:
  82. return target
  83. time.sleep(_POLL_SECONDS)
  84. def _report_connect(app: str, alias: str | None, target: dict[str, Any]) -> int:
  85. from tools.tool_labels import app_title
  86. state = target.get("state")
  87. if state == "connected":
  88. if alias:
  89. print(f"{app_title(app)} account {alias} is connected. "
  90. f"Rename it anytime: hermes connectors rename {app} {alias} --to <new-name>")
  91. else:
  92. print(f"{app_title(app)} is connected.")
  93. return 0
  94. if state == "skipped":
  95. print(f"Skipped connecting {app_title(app)}.")
  96. return 0
  97. detail = target.get("detail") or f"{app_title(app)} did not finish connecting."
  98. print(detail, file=sys.stderr)
  99. return 1
  100. def _connect(args) -> int:
  101. from tools.connectors import account, live
  102. from tools.connectors.contract import SettleReason
  103. app = args.app.strip().lower()
  104. if args.reconnect:
  105. # A repair is addressed by the account's id, which also reaches an unnamed account.
  106. row = _pick_account(app, args.alias)
  107. alias, name = None, _account_name(row)
  108. if row.get("status") == "active" and not args.force:
  109. # A repair of a working account would only replace its sign-in.
  110. print(f"{app} account {name} is connected. Nothing to repair; pass --force to sign in again.")
  111. return 0
  112. start = account.find_or_start_operation([app], action="reconnect", profile_home=None,
  113. repair_id=row["connectionId"])
  114. else:
  115. alias = _valid_alias(args.alias) if args.alias else None
  116. name = alias
  117. start = account.find_or_start_operation([app], action="connect", profile_home=None, alias=alias)
  118. try:
  119. account.wait_for_prepare(start)
  120. if start.failed:
  121. _fail(f"Could not start connecting {app}. Try again in a moment.")
  122. target = _wait_for_link(start, app)
  123. except KeyboardInterrupt:
  124. # The operation would otherwise stay open and block the next connect of this app.
  125. start.operation.settle(SettleReason.continue_)
  126. live.close(start.operation)
  127. print("\nStopped waiting.")
  128. return 130
  129. return _report_connect(app, name, target)
  130. def _rename(args) -> int:
  131. from tools.connectors.gateway.errors import GatewayUnavailable, IdempotencyConflict, ToolGatewayError
  132. from tools.connectors.portal.client import PortalConnectorClient
  133. app = args.app.strip().lower()
  134. new = _valid_alias(args.to)
  135. row = _match_named(app, _app_accounts(app), args.name)
  136. try:
  137. PortalConnectorClient().rename_account(row["connectionId"], new)
  138. except IdempotencyConflict:
  139. _fail(f"The name {new} is already used by another {app} account.")
  140. except GatewayUnavailable as exc:
  141. if exc.code == "connection_not_found":
  142. _fail("That account no longer exists.")
  143. _fail("This Nous Portal cannot rename connector accounts yet.")
  144. except ToolGatewayError as exc:
  145. if exc.status == 405:
  146. _fail("This Nous Portal cannot rename connector accounts yet.")
  147. raise
  148. print(f"Renamed {app} account {args.name} to {new}.")
  149. return 0
  150. def _pick_account(app: str, alias: str | None, *, retired: bool = False) -> dict[str, Any]:
  151. """``retired``: a retired account may be picked by name (removal); a repair never targets one."""
  152. rows = _app_accounts(app)
  153. if alias:
  154. return _match_named(app, [r for r in rows if retired or not r.get("disabled")], alias)
  155. live_rows = [r for r in rows if not r.get("disabled")]
  156. if len(live_rows) == 1:
  157. return live_rows[0]
  158. if not live_rows:
  159. _fail(f"You have no {app} account.")
  160. _fail(f"You have more than one {app} account. Pass --alias to pick one. {_names_hint(app, live_rows)}")
  161. def _disconnect(args) -> int:
  162. from tools.connectors.portal.client import PortalConnectorClient
  163. app = args.app.strip().lower()
  164. row = _pick_account(app, args.alias, retired=True)
  165. name = _account_name(row)
  166. if not args.yes:
  167. if not sys.stdin.isatty():
  168. _fail("Refusing to remove an account without confirmation. Pass --yes to confirm.")
  169. answer = input(f"Remove {app} account {name}? This signs Hermes out of it. [y/N] ").strip().lower()
  170. if answer not in ("y", "yes"):
  171. print("Nothing removed.")
  172. return 0
  173. PortalConnectorClient().delete_account(row["connectionId"])
  174. print(f"Removed {app} account {name}.")
  175. return 0
  176. _ACTIONS: dict[str, Callable[[Any], int]] = {
  177. "list": _list,
  178. "ls": _list,
  179. "accounts": _accounts,
  180. "connect": _connect,
  181. "rename": _rename,
  182. "disconnect": _disconnect,
  183. }
  184. def cmd_connectors(args) -> int:
  185. from tools.connectors import connectors_available
  186. from tools.connectors.gateway.errors import GatewayAuthError, ToolGatewayError
  187. handler = _ACTIONS.get(getattr(args, "connectors_action", None) or "list")
  188. if handler is None:
  189. print(f"Unknown connectors action: {args.connectors_action}", file=sys.stderr)
  190. return 2
  191. if not connectors_available():
  192. print(f"Connectors are not available. {_SIGN_IN}", file=sys.stderr)
  193. return 1
  194. try:
  195. return handler(args)
  196. except _CommandError as exc:
  197. print(str(exc), file=sys.stderr)
  198. except GatewayAuthError:
  199. print(_SIGN_IN, file=sys.stderr)
  200. except ToolGatewayError as exc:
  201. print(str(exc), file=sys.stderr)
  202. return 1