errors.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. """Gateway HTTP errors and envelope parsing.
  2. Per-tool execute failures are result entries, not exceptions; connection links are intentionally unredacted for the model to relay.
  3. """
  4. from __future__ import annotations
  5. from typing import Any, Mapping, Optional
  6. from tools.connectors.turn import CARD, LINK, SIDE
  7. __all__ = [
  8. "SIDE_AGENT_HINT",
  9. "GatewayAuthError",
  10. "GatewayUnavailable",
  11. "IdempotencyConflict",
  12. "ToolGatewayError",
  13. "parse_gateway_error",
  14. "render_connection_required",
  15. ]
  16. class ToolGatewayError(RuntimeError):
  17. """HTTP-level gateway failure; ``retryable`` is decided by the envelope parser."""
  18. def __init__(
  19. self,
  20. message: str,
  21. *,
  22. code: str = "GATEWAY_ERROR",
  23. status: Optional[int] = None,
  24. request_id: Optional[str] = None,
  25. retryable: bool = False,
  26. ) -> None:
  27. super().__init__(message)
  28. self.code = code
  29. self.status = status
  30. self.request_id = request_id
  31. self.retryable = retryable
  32. class GatewayAuthError(ToolGatewayError):
  33. """Authentication or entitlement failure."""
  34. class GatewayUnavailable(ToolGatewayError):
  35. """404 signals callers to degrade silently to local-only behavior."""
  36. class IdempotencyConflict(ToolGatewayError):
  37. """Never retry a reused idempotency key with a different body."""
  38. class RateLimited(ToolGatewayError):
  39. """429 with the gateway's retry hint in seconds; the caller decides whether to wait."""
  40. def __init__(self, message: str, *, retry_after: float, **kwargs: Any) -> None:
  41. super().__init__(message, **kwargs)
  42. self.retry_after = retry_after
  43. def parse_gateway_error(status: int, body: Any, headers: Optional[Mapping[str, Any]] = None) -> ToolGatewayError:
  44. """Parse every gateway error envelope without raising on a malformed body.
  45. Three envelope shapes exist: ``{error: {code, message}}`` on most routes, ``{error: "<code>"}``
  46. on the account routes, and a flat ``{code, message, requestId, retryAfterMs}`` on a 429."""
  47. code = f"HTTP_{status}"
  48. message = ""
  49. request_id = None
  50. retry_after_ms: Optional[float] = None
  51. if isinstance(body, Mapping):
  52. envelope = body.get("error")
  53. if isinstance(envelope, Mapping):
  54. code = str(envelope.get("code") or code)
  55. message = str(envelope.get("message") or "")
  56. elif isinstance(envelope, str) and envelope:
  57. code = envelope
  58. elif body.get("code"):
  59. code = str(body["code"])
  60. message = str(body.get("message") or "")
  61. raw_request_id = body.get("requestId")
  62. if raw_request_id is not None:
  63. request_id = str(raw_request_id)
  64. if isinstance(body.get("retryAfterMs"), (int, float)):
  65. retry_after_ms = float(body["retryAfterMs"])
  66. elif body:
  67. message = str(body)[:500]
  68. if not message:
  69. message = f"tool gateway request failed with status {status}"
  70. kwargs = {
  71. "code": code,
  72. "status": status,
  73. "request_id": request_id,
  74. }
  75. if status in (401, 403):
  76. return GatewayAuthError(message, **kwargs)
  77. if status == 404:
  78. return GatewayUnavailable(message, **kwargs)
  79. if status == 409:
  80. return IdempotencyConflict(message, **kwargs)
  81. if status == 429:
  82. header = (headers or {}).get("Retry-After") if headers else None
  83. retry_after = float(header) if header not in (None, "") else (retry_after_ms or 1000.0) / 1000.0
  84. return RateLimited(message, retry_after=retry_after, **kwargs)
  85. return ToolGatewayError(message, retryable=status >= 500, **kwargs)
  86. SIDE_AGENT_HINT = (
  87. "This app is not connected. Only the main agent can connect it, so report that back "
  88. "instead of trying to connect it here."
  89. )
  90. CARD_HINT = (
  91. "This app is not connected. Call manage_connections to open a connection card for it; "
  92. "there is no link to show the user."
  93. )
  94. # CONNECTION_EXPIRED: the account exists but the vendor no longer accepts it.
  95. EXPIRED_SIDE_AGENT_HINT = (
  96. "This app's connection expired. Only the main agent can reconnect it, so report that back "
  97. "instead of trying to reconnect it here."
  98. )
  99. EXPIRED_CARD_HINT = (
  100. "This app's connection expired. Call manage_connections with action 'reconnect' to open a "
  101. "connection card for it; there is no link to show the user."
  102. )
  103. EXPIRED_LINK_HINT = "The connection expired. Show the user the connect_url to reconnect, then retry the call."
  104. _HINTS = {
  105. "CONNECTION_REQUIRED": {SIDE: SIDE_AGENT_HINT, CARD: CARD_HINT},
  106. "CONNECTION_EXPIRED": {SIDE: EXPIRED_SIDE_AGENT_HINT, CARD: EXPIRED_CARD_HINT, LINK: EXPIRED_LINK_HINT},
  107. }
  108. def render_connection_required(
  109. *,
  110. connector: Optional[str] = None,
  111. message: Optional[str] = None,
  112. connect_url: Optional[str] = None,
  113. hint: Optional[str] = None,
  114. surface: str = LINK,
  115. code: str = "CONNECTION_REQUIRED",
  116. ) -> dict[str, Any]:
  117. """The model-facing shape for an app the call cannot use until the user connects it.
  118. ``code`` is CONNECTION_REQUIRED or CONNECTION_EXPIRED; both keep the card and link behaviour,
  119. the expired one with reconnect wording."""
  120. hints = _HINTS.get(code, _HINTS["CONNECTION_REQUIRED"])
  121. payload: dict[str, Any] = {
  122. "code": code,
  123. "message": message or _default_message(code, connector),
  124. }
  125. if connector:
  126. payload["connector"] = connector
  127. if surface == SIDE:
  128. payload["hint"] = hints[SIDE]
  129. return payload
  130. if surface == CARD:
  131. payload["connect_card_available"] = True
  132. payload["hint"] = hints[CARD]
  133. return payload
  134. if connect_url:
  135. payload["connect_url"] = connect_url
  136. hint = hint or hints.get(LINK)
  137. if hint:
  138. payload["hint"] = hint
  139. return payload
  140. def _default_message(code: str, connector: Optional[str]) -> str:
  141. app = f"The {connector} connector" if connector else "This connector"
  142. if code == "CONNECTION_EXPIRED":
  143. return f"{app} connection for this account has expired and must be reconnected."
  144. return f"{app} is not connected for this account."