display.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. """``manage_connections`` action ``display``: the desktop's browsable connector card.
  2. The card is an operation with no targets, so only Continue, words typed in the composer, the deadline or /stop settle it. Connecting from the card runs the Connectors page's own account operation, never this one."""
  3. from __future__ import annotations
  4. import json
  5. from dataclasses import dataclass, field
  6. from typing import Any, Optional
  7. from tools.connectors.contract import SettleReason
  8. from tools.connectors.operation import ConnectionOperation
  9. from tools.connectors.run import Callback, Kind, open_and_drive
  10. OFF_DESKTOP_NOTE = (
  11. "The connector card shows only in the Hermes desktop app. Tell the user to connect apps from the "
  12. "desktop app or the portal."
  13. )
  14. @dataclass
  15. class DisplayOperation(ConnectionOperation):
  16. suggested: list[str] = field(default_factory=list)
  17. said: str | None = None
  18. def request_payload(self) -> dict[str, Any]:
  19. return {**super().request_payload(), "display": {"suggested": list(self.suggested)}}
  20. def apply_answer(operation: DisplayOperation, raw: str) -> None:
  21. answer = json.loads(raw)
  22. said = str(answer.get("said") or "").strip()
  23. if said:
  24. operation.said = said
  25. if said or answer.get("settled_by") == SettleReason.continue_.value:
  26. operation.settle(SettleReason.continue_)
  27. def connected_slugs(client: Any) -> set[str]:
  28. return {str(i.get("connector", "")).lower() for i in client.list_connectors()
  29. if isinstance(i, dict) and i.get("connected")}
  30. def _result(client: Any, before: set[str], operation: DisplayOperation) -> dict[str, Any]:
  31. after = connected_slugs(client)
  32. result = {"connected": sorted(after), "newly_connected": sorted(after - before), "suggested": operation.suggested}
  33. if operation.said:
  34. result["said"] = operation.said
  35. # A user who connected an app and walked away still gets it reported.
  36. return {**result, "timed_out": True} if operation.settled_by == SettleReason.deadline else result
  37. def _unchanged(_operation: Any) -> None:
  38. return None
  39. def run_display(client: Any, suggested: list[str], *, session_key: str, tool_call_id: Optional[str],
  40. connection_callback: Callback, call: Optional[Any] = None) -> str:
  41. """Draw the card and hold the tool thread until it settles."""
  42. before = connected_slugs(client)
  43. operation = DisplayOperation([], session_key=session_key, tool_call_id=tool_call_id, call=call,
  44. suggested=suggested)
  45. kind = Kind(prepare=_unchanged, observe=_unchanged, note="",
  46. result=lambda _settled: _result(client, before, operation))
  47. return open_and_drive(operation, kind, connection_callback=connection_callback, with_urls_in_result=False)