managed_gateway_identity.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. """Caller identity for requests to the first-party gateways: who is calling, and which turn asked.
  2. ``user_agent()`` goes on every request. The correlation headers name the conversation, turn and tool
  3. call, so they go only to connector routes and only when the profile has opted in to sending
  4. telemetry. The gateway strips every ``x-nous-`` header before it calls a vendor.
  5. """
  6. from __future__ import annotations
  7. import logging
  8. import uuid
  9. from dataclasses import dataclass
  10. from typing import Mapping, Optional
  11. logger = logging.getLogger(__name__)
  12. __all__ = [
  13. "CallRef",
  14. "connector_headers",
  15. "correlation_headers",
  16. "log_connector_outcome",
  17. "request_surface",
  18. "response_request_id",
  19. "user_agent",
  20. ]
  21. SESSION_HEADER = "x-nous-hermes-session"
  22. TURN_HEADER = "x-nous-hermes-turn"
  23. TOOL_CALL_HEADER = "x-nous-hermes-tool-call"
  24. REQUEST_ID_HEADER = "x-request-id"
  25. # sys.platform -> the shared-metrics OS family.
  26. _OS_FAMILY = {"darwin": "macos", "linux": "linux", "win32": "windows"}
  27. # The account route answers 404 with this code until the vendor has created the account.
  28. _EXPECTED_MISSES = frozenset({"connection_not_found"})
  29. @dataclass(frozen=True)
  30. class CallRef:
  31. """The model's ids for the call a request serves. Absent fields are not sent."""
  32. turn_id: Optional[str] = None
  33. tool_call_id: Optional[str] = None
  34. def _platform_name() -> str:
  35. """The session's platform: the running turn's agent platform, else the bound session vars.
  36. Off a turn (a desktop page action, an account operation thread) only the session vars exist.
  37. The classic CLI and one-shot runs bind neither, so they read as ``cli``."""
  38. from agent.relay_runtime import current_turn
  39. from gateway.session_context import get_session_env
  40. from tools.connectors.gateway.config import session_platform
  41. from utils import is_truthy_value
  42. turn = current_turn()
  43. if turn is not None and turn.lease.platform:
  44. return turn.lease.platform
  45. if platform := session_platform():
  46. return platform
  47. return "cron" if is_truthy_value(get_session_env("HERMES_CRON_SESSION", "")) else "cli"
  48. def request_surface() -> str:
  49. from hermes_cli.observability.shared_metrics_contract import execution_surface
  50. surface = execution_surface({"execution_surface": _platform_name()})
  51. return "other" if surface == "unknown" else surface
  52. def user_agent() -> str:
  53. from hermes_cli.version_info import get_version_info
  54. from hermes_platform.host.facts import os_family
  55. os_name = _OS_FAMILY.get(os_family(), "unknown")
  56. return f"hermes-agent/{get_version_info().base_version} ({request_surface()}; {os_name})"
  57. def _send_consented() -> bool:
  58. from hermes_cli.config import read_raw_config_readonly
  59. from hermes_cli.observability.shared_metrics_send_config import resolve_send_config
  60. return resolve_send_config(read_raw_config_readonly() or {}).send is True
  61. def _conversation_id() -> Optional[str]:
  62. from agent.portal_tags import get_conversation_context
  63. from gateway.session_context import get_session_env
  64. return get_conversation_context() or get_session_env("HERMES_SESSION_ID", "") or None
  65. def correlation_headers(call: Optional[CallRef] = None) -> dict[str, str]:
  66. """``x-request-id`` (fresh per HTTP attempt) and the conversation, turn and tool call ids, or
  67. ``{}`` when the profile has not opted in to sending telemetry."""
  68. if not _send_consented():
  69. return {}
  70. headers = {REQUEST_ID_HEADER: str(uuid.uuid4())}
  71. ids = {
  72. SESSION_HEADER: _conversation_id(),
  73. TURN_HEADER: call.turn_id if call else None,
  74. TOOL_CALL_HEADER: call.tool_call_id if call else None,
  75. }
  76. headers.update({name: str(value) for name, value in ids.items() if value})
  77. return headers
  78. def connector_headers(call: Optional[CallRef] = None) -> dict[str, str]:
  79. """Every identity header for one connector HTTP attempt. Call it once per attempt."""
  80. return {"User-Agent": user_agent(), **correlation_headers(call)}
  81. def response_request_id(response: object) -> Optional[str]:
  82. headers = getattr(response, "headers", None)
  83. if not isinstance(headers, Mapping):
  84. return None
  85. value = headers.get(REQUEST_ID_HEADER) or headers.get("X-Request-Id")
  86. return str(value) if value else None
  87. def log_connector_outcome(
  88. route: str, status: Optional[int], *, code: Optional[str] = None, request_id: Optional[str] = None,
  89. call: Optional[CallRef] = None,
  90. ) -> None:
  91. """One line per connector HTTP outcome: failures at WARNING, success and expected misses at DEBUG.
  92. The ``code`` makes a line a failure, not the status: a 200 whose body failed carries one, and a
  93. 304 that refreshed a cached list does not."""
  94. level = logging.WARNING if code is not None and code not in _EXPECTED_MISSES else logging.DEBUG
  95. logger.log(
  96. level, "connector %s %s %s request_id=%s dispatch=%s",
  97. route, status if status is not None else "transport", code or "-", request_id or "-",
  98. (call.tool_call_id if call else None) or "-",
  99. )