config.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. """Configuration and availability gate for connector tools.
  2. Availability fails closed; the gateway remains authoritative for entitlement and route availability.
  3. """
  4. from __future__ import annotations
  5. import logging
  6. from dataclasses import dataclass
  7. from typing import Any, Callable, Optional
  8. logger = logging.getLogger(__name__)
  9. __all__ = [
  10. "MAX_CALLS_PER_DISPATCH",
  11. "ConnectorConfig",
  12. "connectors_available",
  13. "ensure_guest_identity",
  14. "guest_identity_pending",
  15. "load_config",
  16. ]
  17. # Context cap, not a wire limit; the gateway batch cap is deliberately unreachable.
  18. MAX_CALLS_PER_DISPATCH = 10
  19. _FALSE_STRINGS = frozenset({"false", "0", "no", "off", ""})
  20. @dataclass(frozen=True)
  21. class ConnectorConfig:
  22. enabled: bool = True
  23. @classmethod
  24. def from_raw(cls, raw: Any) -> ConnectorConfig:
  25. """Malformed configuration falls back to the enabled default."""
  26. if isinstance(raw, bool):
  27. return cls(enabled=raw)
  28. if isinstance(raw, dict):
  29. return cls(enabled=_coerce_bool(raw.get("enabled"), True))
  30. return cls()
  31. def _coerce_bool(value: Any, fallback: bool) -> bool:
  32. if isinstance(value, bool):
  33. return value
  34. if value is None:
  35. return fallback
  36. if isinstance(value, (int, float)):
  37. return bool(value)
  38. if isinstance(value, str):
  39. return value.strip().lower() not in _FALSE_STRINGS
  40. return fallback
  41. def load_config() -> ConnectorConfig:
  42. try:
  43. from hermes_cli.config import load_config_readonly as _load
  44. cfg = _load() or {}
  45. tools_cfg = cfg.get("tools") if isinstance(cfg.get("tools"), dict) else {}
  46. if not isinstance(tools_cfg, dict):
  47. tools_cfg = {}
  48. return ConnectorConfig.from_raw(tools_cfg.get("connectors"))
  49. except Exception as e:
  50. logger.debug("Failed to load connector config: %s", e)
  51. return ConnectorConfig.from_raw(None)
  52. def managed_tools_rolled_out() -> bool:
  53. """The portal has enabled connectors for this account.
  54. The gateway answers 404 to every ``/v1/connectors`` route for an account the portal has not
  55. enabled, and 404 is indistinguishable from "dark" by design. Paid access or a free tool pool
  56. says nothing about that, so entitlement is the wrong predicate here: the portal mints its
  57. answer onto the token as ``managed_tools`` and this reads only that. A token minted before
  58. the claim existed carries none and reads as not enabled."""
  59. from hermes_cli.nous_account import get_nous_portal_account_info
  60. account_info = get_nous_portal_account_info()
  61. return bool(account_info.logged_in) and account_info.managed_tools_rolled_out
  62. def connectors_available(
  63. config_loader: Optional[Callable[[], ConnectorConfig]] = None,
  64. entitlement_check: Optional[Callable[[], bool]] = None,
  65. ) -> bool:
  66. """Fail closed so availability failures do not become model-visible errors.
  67. The one gate for the connectors surface, and the tool's ``check_fn``: outside it the tool is
  68. not in the schema at all, so the model never narrates a gateway 404 to a user the portal has
  69. not enabled. Free-tier identities are always in, and so is a user with no identity who may get
  70. one; accounts are in only when the portal says so via the token claim."""
  71. try:
  72. resolved_loader = config_loader or load_config
  73. if not resolved_loader().enabled:
  74. return False
  75. if entitlement_check is None:
  76. from hermes_cli.anon_auth import is_guest_state
  77. from tools.managed_tool_gateway import _read_nous_provider_state
  78. # Availability must not mint or refresh an identity.
  79. if is_guest_state(_read_nous_provider_state()) or guest_identity_pending():
  80. return True
  81. entitlement_check = managed_tools_rolled_out
  82. return bool(entitlement_check())
  83. except Exception as e:
  84. logger.debug("Connector availability check failed: %s", e)
  85. return False
  86. def guest_identity_pending() -> bool:
  87. """No Nous identity or bearer yet, and a guest one may be created (``nous.guest`` is not false
  88. and no earlier mint was refused for good). No network: this feeds the ``check_fn``."""
  89. from hermes_cli.anon_auth import guest_allowed, last_mint_failure
  90. from tools.managed_tool_gateway import _read_nous_provider_state, peek_nous_access_token
  91. if not guest_allowed() or _read_nous_provider_state() is not None or peek_nous_access_token():
  92. return False
  93. failure = last_mint_failure()
  94. return not failure or bool(failure["retryable"])
  95. _SETUP_FAILED = "Hosted connectors could not be set up. "
  96. def guest_setup_failure() -> Optional[str]:
  97. """The last failed guest creation for this profile, worded with the wait still left, or None."""
  98. from hermes_cli.anon_auth import anon_failure_copy, last_mint_failure
  99. if not (failure := last_mint_failure()):
  100. return None
  101. return _SETUP_FAILED + anon_failure_copy(failure["error_code"], retry_after=failure["retry_after"])
  102. def ensure_guest_identity() -> Optional[str]:
  103. """Create the guest identity on the first hosted connector action, synchronously.
  104. Returns None when an identity exists or was just created, else the failure copy for the model:
  105. a refusal, a rate limit or an unreachable portal, with the wait when there is one."""
  106. if not guest_identity_pending():
  107. return None
  108. from hermes_cli.anon_auth import ensure_portal_identity
  109. from hermes_cli.auth_constants import AuthError
  110. try:
  111. if ensure_portal_identity(explicit=True) is not None:
  112. return None
  113. except AuthError as exc:
  114. return _SETUP_FAILED + str(exc)
  115. return guest_setup_failure() or _SETUP_FAILED + "Try again shortly."
  116. def operation_session_key(session_id: Optional[str]) -> str:
  117. """The key an operation is registered under: the gateway session key the RPCs look up by
  118. (``HERMES_SESSION_KEY``), falling back to the agent's session id where no gateway bound one.
  119. The agent id alone is wrong on the desktop: compaction rotates it mid-turn while the gateway
  120. key stays, and a card keyed by the old id can no longer be driven."""
  121. from gateway.session_context import get_session_env
  122. return get_session_env("HERMES_SESSION_KEY", "") or str(session_id or "")
  123. def session_platform() -> str:
  124. from gateway.session_context import get_session_env
  125. platform = get_session_env("HERMES_SESSION_PLATFORM", "") or get_session_env("HERMES_SESSION_SOURCE", "")
  126. return str(platform or "").strip().lower()