Skip to content

The agent that grows with you

feat(connectors): name the caller on every gateway request

Siddharth Balyane375e86a6c72
diff --git a/tools/connectors/gateway/client.py b/tools/connectors/gateway/client.py
index 608ad865266..3f99a19e1c2 100644
--- a/tools/connectors/gateway/client.py
+++ b/tools/connectors/gateway/client.py
@@ -23,6 +23,7 @@ from tools.connectors.gateway.errors import (
)
from tools.connectors.gateway.merge import PlannedCall
+from tools.managed_gateway_identity import CallRef, connector_headers, log_connector_outcome, response_request_id
logger = logging.getLogger(__name__)
@@ -77,10 +78,15 @@ class ConnectorClient:
transport: Optional[Transport] = None,
endpoint_resolver: Optional[Callable[[], Optional[str]]] = None,
header_provider: Optional[Callable[[str], dict]] = None,
+ call: Optional[CallRef] = None,
+ initiator: Optional[str] = None,
) -> None:
self._transport = transport or _default_transport()
self._endpoint_resolver = endpoint_resolver or _default_endpoint_resolver
self._header_provider = header_provider or _default_header_provider
+ # The model call this client serves, and who asked for a connect; both go on the wire.
+ self._call = call
+ self._initiator = initiator
def search(self, queries: Sequence[dict[str, Any]]) -> dict[str, Any]:
body = wire.ConnectorSearchRequest(
@@ -111,7 +117,7 @@ class ConnectorClient:
existing account to repair, named or not."""
body = wire.ConnectorConnectionsRequest(
connectors=list(connectors), reinitiate=reinitiate, alias=alias, connection_id=connection_id,
- return_to=return_to, op=op,
+ return_to=return_to, op=op, initiator=self._initiator,
).model_dump(by_alias=True, exclude_none=True)
payload = self._post(wire.CONNECTOR_CONNECTIONS_PATH, body, retries=0)
return wire.ConnectorConnectionsResponse.model_validate(payload).model_dump()
@@ -213,17 +219,10 @@ class ConnectorClient:
)
url = f"{origin.rstrip('/')}/{path}"
+ route = _route_key(path)
last_error: Optional[ToolGatewayError] = None
for attempt in range(1 + retries):
- headers = dict(self._header_provider(url))
- if not headers:
- raise GatewayAuthError(
- "no portal access token available", code="NO_TOKEN", status=401
- )
- headers["Content-Type"] = "application/json"
- if idempotency_key:
- headers["x-idempotency-key"] = idempotency_key
-
+ headers = self._attempt_headers(url, idempotency_key)
try:
response = self._transport.request(
method, url, headers=headers, json=body, timeout=timeout
@@ -232,16 +231,18 @@ class ConnectorClient:
last_error = ToolGatewayError(
f"transport failure: {exc}", code="TRANSPORT_ERROR", retryable=True
)
- logger.debug(
- "Connector %s attempt %d transport failure: %s", path, attempt + 1, exc
- )
+ log_connector_outcome(route, None, code="TRANSPORT_ERROR", call=self._call)
continue
status = int(getattr(response, "status_code", 0))
+ request_id = response_request_id(response)
if 200 <= status < 300:
+ log_connector_outcome(route, status, request_id=request_id, call=self._call)
return response.json()
error = parse_gateway_error(status, _safe_json(response), getattr(response, "headers", None))
+ error.request_id = error.request_id or request_id
+ log_connector_outcome(route, status, code=error.code, request_id=error.request_id, call=self._call)
if error.retryable and attempt < retries:
last_error = error
logger.debug(
@@ -256,6 +257,19 @@ class ConnectorClient:
assert last_error is not None
raise last_error
+ def _attempt_headers(self, url: str, idempotency_key: Optional[str]) -> dict[str, str]:
+ """Every header of one HTTP attempt: auth, caller identity, and the idempotency key."""
+ headers = dict(self._header_provider(url))
+ if not headers:
+ raise GatewayAuthError(
+ "no portal access token available", code="NO_TOKEN", status=401
+ )
+ headers.update(connector_headers(self._call))
+ headers["Content-Type"] = "application/json"
+ if idempotency_key:
+ headers["x-idempotency-key"] = idempotency_key
+ return headers
+
def return_to_args(*, op: Optional[str] = None) -> dict[str, Any]:
"""The ``returnTo`` / ``op`` arguments a connect or execute call carries so the vendor's done page
@@ -270,6 +284,14 @@ def return_to_args(*, op: Optional[str] = None) -> dict[str, Any]:
return {"return_to": target, "op": op} if op else {"return_to": target}
+def _route_key(path: str) -> str:
+ """``v1/connectors/accounts/<id>?x`` -> ``connectors.accounts``: the route without ids or query."""
+ parts = path.split("?", 1)[0].strip("/").split("/")[1:]
+ if len(parts) > 2:
+ parts = parts[:2]
+ return ".".join(parts) or path
+
+
def _result_dict(result: wire.ConnectorExecuteResult) -> dict[str, Any]:
error = None
if result.error is not None:
diff --git a/tools/connectors/gateway/wire.py b/tools/connectors/gateway/wire.py
index 231f7326575..e4729d84611 100644
--- a/tools/connectors/gateway/wire.py
+++ b/tools/connectors/gateway/wire.py
@@ -22,6 +22,9 @@ CONNECTOR_ACCOUNTS_PATH = f"{CONNECTORS_PATH}/accounts"
ConnectionStatus = Literal["pending", "active", "failed", "expired", "revoked", "inactive"]
# Where the vendor's done page sends the browser after consent; the dev desktop registers hermes-dev://.
ConnectorReturnTarget = Literal["hermes-desktop", "hermes-desktop-dev", "portal"]
+# Who asked for a connect, so the gateway can attribute each minted link. The gateway sets
+# ``execute_link`` and ``portal`` itself; an older gateway ignores the field.
+ConnectorInitiator = Literal["agent_tool", "desktop_page", "card_retry"]
# Hermes dispatch caps batches lower, so client-side chunking is deliberately absent.
WIRE_BATCH_MAX = 25
@@ -145,6 +148,7 @@ class ConnectorConnectionsRequest(_Wire):
return_to: Optional[ConnectorReturnTarget] = Field(default=None, alias="returnTo")
# The caller's operation id, echoed on the hermes://connections/done link.
op: Optional[str] = Field(default=None, min_length=1, max_length=128)
+ initiator: Optional[ConnectorInitiator] = None
class ConnectorConnectionResult(_Wire):
diff --git a/tools/connectors/portal/client.py b/tools/connectors/portal/client.py
index 090e52c745b..00eba8d68a0 100644
--- a/tools/connectors/portal/client.py
+++ b/tools/connectors/portal/client.py
@@ -24,6 +24,7 @@ from tools.connectors.portal.wire import (
ConnectorToolsListing,
)
from tools.managed_gateway_auth import read_nous_access_token
+from tools.managed_gateway_identity import connector_headers, log_connector_outcome, response_request_id
DEFAULT_TIMEOUT_SECONDS = 30.0
@@ -92,7 +93,7 @@ class PortalConnectorClient:
return token.strip() if scheme.lower() == "bearer" and token.strip() else None
def _authorized_headers(self, url: str, extra: dict[str, str] | None = None) -> dict[str, str]:
- headers = {"Accept": "application/json", **(extra or {}), **self._header_provider(url)}
+ headers = {"Accept": "application/json", **(extra or {}), **connector_headers(), **self._header_provider(url)}
if not isinstance(headers.get("Authorization"), str) or not headers["Authorization"].strip():
raise GatewayAuthError("portal authorization required", code="NO_TOKEN", status=401)
return headers
@@ -161,11 +162,16 @@ class PortalConnectorClient:
try:
response = self._transport.request(method, url, headers=headers, json=body, timeout=DEFAULT_TIMEOUT_SECONDS)
except Exception as exc:
+ log_connector_outcome(_route_key(path), None, code="TRANSPORT_ERROR")
raise PortalConnectorUnavailable("portal connector metadata unavailable", code="TRANSPORT_ERROR", retryable=True) from exc
status = int(getattr(response, "status_code", 0))
+ request_id = response_request_id(response)
if not 200 <= status < 300 and status != 304:
error = parse_gateway_error(status, _safe_json(response), getattr(response, "headers", None))
+ error.request_id = error.request_id or request_id
+ log_connector_outcome(_route_key(path), status, code=error.code, request_id=error.request_id)
raise error
+ log_connector_outcome(_route_key(path), status, request_id=request_id)
return response, status
@staticmethod
@@ -179,6 +185,16 @@ class PortalConnectorClient:
raise error_type(message, code="INVALID_RESPONSE", status=status) from exc
+def _route_key(path: str) -> str:
+ """``/api/v1/connectors/gmail/tools`` -> ``portal.connectors.tools``: no slugs or ids."""
+ parts = path.strip("/").split("/")[2:]
+ named = [part for part in parts if part in _PORTAL_ROUTE_WORDS]
+ return ".".join(["portal", *named]) or "portal"
+
+
+_PORTAL_ROUTE_WORDS = frozenset({"connectors", "tools", "catalog", "accounts", "policy"})
+
+
def _safe_json(response: Any) -> Any:
try:
return response.json()
diff --git a/tools/managed_gateway_auth.py b/tools/managed_gateway_auth.py
index df503fc65bb..f3e769a9aa9 100644
--- a/tools/managed_gateway_auth.py
+++ b/tools/managed_gateway_auth.py
@@ -75,4 +75,6 @@ def managed_gateway_auth_headers(
if not isinstance(token, str) or not token.strip():
return {}
- return {"Authorization": f"Bearer {token.strip()}"}
+ from tools.managed_gateway_identity import user_agent
+
+ return {"Authorization": f"Bearer {token.strip()}", "User-Agent": user_agent()}
diff --git a/tools/managed_gateway_identity.py b/tools/managed_gateway_identity.py
new file mode 100644
index 00000000000..72f30702dfe
--- /dev/null
+++ b/tools/managed_gateway_identity.py
@@ -0,0 +1,133 @@
+"""Caller identity for requests to the first-party gateways: who is calling, and which turn asked.
+
+``user_agent()`` goes on every request. The correlation headers name the conversation, turn and tool
+call, so they go only to connector routes and only when the profile has opted in to sending
+telemetry. The gateway strips every ``x-nous-`` header before it calls a vendor.
+"""
+
+from __future__ import annotations
+
+import logging
+import uuid
+from dataclasses import dataclass
+from typing import Mapping, Optional
+
+logger = logging.getLogger(__name__)
+
+__all__ = [
+ "CallRef",
+ "connector_headers",
+ "correlation_headers",
+ "log_connector_outcome",
+ "request_surface",
+ "response_request_id",
+ "user_agent",
+]
+
+SESSION_HEADER = "x-nous-hermes-session"
+TURN_HEADER = "x-nous-hermes-turn"
+TOOL_CALL_HEADER = "x-nous-hermes-tool-call"
+REQUEST_ID_HEADER = "x-request-id"
+
+# sys.platform -> the shared-metrics OS family.
+_OS_FAMILY = {"darwin": "macos", "linux": "linux", "win32": "windows"}
+
+# The account route answers 404 with this code until the vendor has created the account.
+_EXPECTED_MISSES = frozenset({"connection_not_found"})
+
+
+@dataclass(frozen=True)
+class CallRef:
+ """The model's ids for the call a request serves. Absent fields are not sent."""
+
+ turn_id: Optional[str] = None
+ tool_call_id: Optional[str] = None
+
+
+def _platform_name() -> str:
+ """The session's platform: the running turn's agent platform, else the bound session vars.
+
+ Off a turn (a desktop page action, an account operation thread) only the session vars exist.
+ The classic CLI and one-shot runs bind neither, so they read as ``cli``."""
+ from agent.relay_runtime import current_turn
+ from gateway.session_context import get_session_env
+ from tools.connectors.gateway.config import session_platform
+ from utils import is_truthy_value
+
+ turn = current_turn()
+ if turn is not None and turn.lease.platform:
+ return turn.lease.platform
+ if platform := session_platform():
+ return platform
+ return "cron" if is_truthy_value(get_session_env("HERMES_CRON_SESSION", "")) else "cli"
+
+
+def request_surface() -> str:
+ from hermes_cli.observability.shared_metrics_contract import execution_surface
+
+ surface = execution_surface({"execution_surface": _platform_name()})
+ return "other" if surface == "unknown" else surface
+
+
+def user_agent() -> str:
+ from hermes_cli.version_info import get_version_info
+ from hermes_platform.host.facts import os_family
+
+ os_name = _OS_FAMILY.get(os_family(), "unknown")
+ return f"hermes-agent/{get_version_info().base_version} ({request_surface()}; {os_name})"
+
+
+def _send_consented() -> bool:
+ from hermes_cli.config import read_raw_config_readonly
+ from hermes_cli.observability.shared_metrics_send_config import resolve_send_config
+
+ return resolve_send_config(read_raw_config_readonly() or {}).send is True
+
+
+def _conversation_id() -> Optional[str]:
+ from agent.portal_tags import get_conversation_context
+ from gateway.session_context import get_session_env
+
+ return get_conversation_context() or get_session_env("HERMES_SESSION_ID", "") or None
+
+
+def correlation_headers(call: Optional[CallRef] = None) -> dict[str, str]:
+ """``x-request-id`` (fresh per HTTP attempt) and the conversation, turn and tool call ids, or
+ ``{}`` when the profile has not opted in to sending telemetry."""
+ if not _send_consented():
+ return {}
+ headers = {REQUEST_ID_HEADER: str(uuid.uuid4())}
+ ids = {
+ SESSION_HEADER: _conversation_id(),
+ TURN_HEADER: call.turn_id if call else None,
+ TOOL_CALL_HEADER: call.tool_call_id if call else None,
+ }
+ headers.update({name: str(value) for name, value in ids.items() if value})
+ return headers
+
+
+def connector_headers(call: Optional[CallRef] = None) -> dict[str, str]:
+ """Every identity header for one connector HTTP attempt. Call it once per attempt."""
+ return {"User-Agent": user_agent(), **correlation_headers(call)}
+
+
+def response_request_id(response: object) -> Optional[str]:
+ headers = getattr(response, "headers", None)
+ if not isinstance(headers, Mapping):
+ return None
+ value = headers.get(REQUEST_ID_HEADER) or headers.get("X-Request-Id")
+ return str(value) if value else None
+
+
+def log_connector_outcome(
+ route: str, status: Optional[int], *, code: Optional[str] = None, request_id: Optional[str] = None,
+ call: Optional[CallRef] = None,
+) -> None:
+ """One line per connector HTTP outcome: failures at WARNING, success and expected misses at DEBUG."""
+ failed = status is None or not 200 <= status < 300
+ level = logging.WARNING if failed and code not in _EXPECTED_MISSES else logging.DEBUG
+ logger.log(
+ level, "connector %s %s %s request_id=%s dispatch=%s",
+ route, status if status is not None else "transport", code or "-", request_id or "-",
+ (call.tool_call_id if call else None) or "-",
+ )