wire.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. """Wire models for the gateway connector routes.
  2. Tolerate added gateway fields; callers receive plain dictionaries. Correlate results by position, never wire ``index``.
  3. """
  4. from __future__ import annotations
  5. from typing import Any, Literal, Optional
  6. from pydantic import BaseModel, ConfigDict, Field
  7. CONNECTORS_PATH = "v1/connectors"
  8. CONNECTOR_SEARCH_PATH = f"{CONNECTORS_PATH}/search"
  9. CONNECTOR_SCHEMAS_PATH = f"{CONNECTORS_PATH}/schemas"
  10. CONNECTOR_EXECUTE_PATH = f"{CONNECTORS_PATH}/execute"
  11. CONNECTOR_CONNECTIONS_PATH = f"{CONNECTORS_PATH}/connections"
  12. CONNECTOR_ACCOUNTS_PATH = f"{CONNECTORS_PATH}/accounts"
  13. CONNECTOR_FILE_UPLOAD_PATH = f"{CONNECTORS_PATH}/files/upload"
  14. # The gateway's cap on a staged file's declared size.
  15. CONNECTOR_FILE_MAX_BYTES = 20 * 1024 * 1024
  16. # The gateway's six-state account status (contract `CONNECTOR_CONNECTION_STATUSES`; the vendor's
  17. # INITIALIZING and INITIATED both arrive as `pending`). Present only once the session binds an
  18. # account; a value outside this set is a contract break and fails validation.
  19. ConnectionStatus = Literal["pending", "active", "failed", "expired", "revoked", "inactive"]
  20. # Where the vendor's done page sends the browser after consent; the dev desktop registers hermes-dev://.
  21. ConnectorReturnTarget = Literal["hermes-desktop", "hermes-desktop-dev", "portal"]
  22. # Who asked for a connect, so the gateway can attribute each minted link. The gateway sets
  23. # ``execute_link`` and ``portal`` itself; an older gateway ignores the field.
  24. ConnectorInitiator = Literal["agent_tool", "desktop_page", "card_retry"]
  25. # Hermes dispatch caps batches lower, so client-side chunking is deliberately absent.
  26. WIRE_BATCH_MAX = 25
  27. # Any string: a gateway newer than this client may add codes, and an unknown code still renders.
  28. ConnectorErrorCode = str
  29. # `product`: the request or the user's setup is the cause. `backend`: the gateway or the vendor failed.
  30. ErrorFamily = Literal["product", "backend"]
  31. # Single-call execute failures: code -> (family, HTTP status). The legacy array envelope carries only
  32. # TOOL_NOT_ALLOWED, CONNECTION_REQUIRED, TOOL_NOT_FOUND and PROVIDER_ERROR, always under a 200.
  33. EXECUTE_ERROR_CODES: dict[str, tuple[ErrorFamily, int]] = {
  34. "TOOL_NOT_ALLOWED": ("product", 403),
  35. "CONNECTION_REQUIRED": ("product", 409),
  36. "CONNECTION_EXPIRED": ("product", 409),
  37. "ALIAS_REQUIRED": ("product", 422),
  38. "ALIAS_UNKNOWN": ("product", 422),
  39. "INVALID_ARGUMENTS": ("product", 422),
  40. "TOOL_NOT_FOUND": ("product", 404),
  41. "PROVIDER_ERROR": ("backend", 502),
  42. "PROVIDER_RATE_LIMITED": ("backend", 429),
  43. "PROVIDER_TIMEOUT": ("backend", 504),
  44. "POLICY_UNAVAILABLE": ("backend", 503),
  45. "GATEWAY_ERROR": ("backend", 500),
  46. }
  47. # Failures the agent reports itself while staging a file input, before the call reaches execute.
  48. FILE_ERROR_FAMILIES: dict[str, ErrorFamily] = {
  49. "FILE_NOT_ALLOWED": "product",
  50. "FILE_NOT_FOUND": "product",
  51. "FILE_TOO_LARGE": "product",
  52. "FILE_UPLOAD_FAILED": "backend",
  53. }
  54. def execute_error_family(code: str, family: Optional[str] = None) -> Optional[str]:
  55. """The gateway's family when it sent one, else the table's; ``None`` for an unknown code."""
  56. if family in ("product", "backend"):
  57. return family
  58. known = EXECUTE_ERROR_CODES.get(code)
  59. return known[0] if known else FILE_ERROR_FAMILIES.get(code)
  60. class _Wire(BaseModel):
  61. model_config = ConfigDict(extra="ignore", populate_by_name=True)
  62. class ConnectorSearchQuery(_Wire):
  63. use_case: str = Field(alias="useCase")
  64. known_fields: Optional[str] = Field(default=None, alias="knownFields")
  65. class ConnectorSearchRequest(_Wire):
  66. queries: list[ConnectorSearchQuery]
  67. class ConnectorToolSchema(_Wire):
  68. connector: str
  69. tool: str
  70. description: str = ""
  71. input_schema: dict[str, Any] = Field(default_factory=dict, alias="inputSchema")
  72. class ConnectorSearchResult(_Wire):
  73. # Vendor passthrough; result correlation uses array position.
  74. index: int
  75. use_case: str = Field(default="", alias="useCase")
  76. tools: list[str] = Field(default_factory=list)
  77. related_tools: list[str] = Field(default_factory=list, alias="relatedTools")
  78. connectors: list[str] = Field(default_factory=list)
  79. guidance: Optional[str] = None
  80. plan_steps: Optional[list[str]] = Field(default=None, alias="planSteps")
  81. pitfalls: Optional[list[str]] = None
  82. error: Optional[str] = None
  83. class ConnectorConnectionStatus(_Wire):
  84. connector: str
  85. connected: bool = False
  86. description: str = ""
  87. class ConnectorSearchResponse(_Wire):
  88. results: list[ConnectorSearchResult] = Field(default_factory=list)
  89. schemas: dict[str, ConnectorToolSchema] = Field(default_factory=dict)
  90. connections: list[ConnectorConnectionStatus] = Field(default_factory=list)
  91. next_steps: list[str] = Field(default_factory=list, alias="nextSteps")
  92. class ConnectorSchemasRequest(_Wire):
  93. tools: list[str]
  94. class ConnectorSchemasResponse(_Wire):
  95. schemas: dict[str, ConnectorToolSchema] = Field(default_factory=dict)
  96. not_found: list[str] = Field(default_factory=list, alias="notFound")
  97. suggestions: dict[str, list[str]] = Field(default_factory=dict)
  98. class ConnectorFileUploadRequest(_Wire):
  99. toolkit: str
  100. tool: str
  101. filename: str
  102. mimetype: str
  103. size: int
  104. class ConnectorFileDescriptor(_Wire):
  105. """The value a ``file_uploadable`` tool input takes on the wire."""
  106. name: str
  107. mimetype: str
  108. s3key: str
  109. class ConnectorFileUploadResponse(_Wire):
  110. upload_url: str = Field(alias="uploadUrl")
  111. headers: dict[str, str] = Field(default_factory=dict)
  112. descriptor: ConnectorFileDescriptor
  113. expires_at: str = Field(alias="expiresAt")
  114. class ConnectorToolError(_Wire):
  115. code: ConnectorErrorCode
  116. message: str
  117. connector: Optional[str] = None
  118. connect_url: Optional[str] = Field(default=None, alias="connectUrl")
  119. # The account the link was minted for; absent when the link mint failed. Absent means nothing to watch.
  120. connection_id: Optional[str] = Field(default=None, alias="connectionId")
  121. hint: Optional[str] = None
  122. family: Optional[str] = None
  123. class ConnectorExecuteFailure(ConnectorToolError):
  124. """The body of a non-2xx single-call execute answer."""
  125. request_id: Optional[str] = Field(default=None, alias="requestId")
  126. class ConnectorExecuteCall(_Wire):
  127. connector: str
  128. tool: str
  129. arguments: dict[str, Any] = Field(default_factory=dict)
  130. # Never sent by hermes: the model picks an account with the ``connector_alias`` argument, which
  131. # the gateway strips and resolves itself.
  132. account: Optional[str] = None
  133. class ConnectorExecuteRequest(_Wire):
  134. tools: list[ConnectorExecuteCall]
  135. # Ride any CONNECTION_REQUIRED link the call mints back to the surface that asked.
  136. return_to: Optional[ConnectorReturnTarget] = Field(default=None, alias="returnTo")
  137. op: Optional[str] = Field(default=None, min_length=1, max_length=128)
  138. class ConnectorExecuteSingleRequest(_Wire):
  139. call: ConnectorExecuteCall
  140. return_to: Optional[ConnectorReturnTarget] = Field(default=None, alias="returnTo")
  141. op: Optional[str] = Field(default=None, min_length=1, max_length=128)
  142. # What a model receiving this result must guarantee; absent when the connector asks nothing.
  143. DataUseRequirement = Literal["no_training", "zero_retention"]
  144. class ConnectorDataUse(_Wire):
  145. requires: list[DataUseRequirement]
  146. class ConnectorExecuteSingleResult(_Wire):
  147. connector: str = ""
  148. tool: str = ""
  149. data: Any = None
  150. account: Optional[str] = None
  151. data_use: Optional[ConnectorDataUse] = Field(default=None, alias="dataUse")
  152. class ConnectorExecuteSingleResponse(_Wire):
  153. result: ConnectorExecuteSingleResult
  154. class ConnectorExecuteResult(_Wire):
  155. # Never correlate results by wire index.
  156. index: int = 0
  157. connector: str = ""
  158. tool: str = ""
  159. data: Any = None
  160. error: Optional[ConnectorToolError] = None
  161. # The alias of the account the call ran under; null when that account has no alias.
  162. account: Optional[str] = None
  163. data_use: Optional[ConnectorDataUse] = Field(default=None, alias="dataUse")
  164. class ConnectorExecuteResponse(_Wire):
  165. results: list[ConnectorExecuteResult] = Field(default_factory=list)
  166. success_count: int = Field(default=0, alias="successCount")
  167. error_count: int = Field(default=0, alias="errorCount")
  168. total_count: int = Field(default=0, alias="totalCount")
  169. class ConnectorConnectionsRequest(_Wire):
  170. connectors: list[str]
  171. reinitiate: bool = False
  172. alias: Optional[str] = None
  173. # The existing account a reinitiate repairs; sent instead of ``alias`` when known.
  174. connection_id: Optional[str] = Field(default=None, alias="connectionId")
  175. return_to: Optional[ConnectorReturnTarget] = Field(default=None, alias="returnTo")
  176. # The caller's operation id, echoed on the hermes://connections/done link.
  177. op: Optional[str] = Field(default=None, min_length=1, max_length=128)
  178. initiator: Optional[ConnectorInitiator] = None
  179. class ConnectorConnectionResult(_Wire):
  180. connector: str
  181. status: Literal["active", "initiated", "failed"]
  182. connect_url: Optional[str] = Field(default=None, alias="connectUrl")
  183. # The vendor account the mint created or observed. Optional by vendor semantics (a no-auth toolkit
  184. # answers active with none); a target without one has nothing to watch.
  185. connection_id: Optional[str] = Field(default=None, alias="connectionId")
  186. alias: Optional[str] = None
  187. instruction: Optional[str] = None
  188. # Vendor error_message on ``failed``; the list route never carries it.
  189. status_reason: Optional[str] = Field(default=None, alias="statusReason")
  190. reinitiated: bool = False
  191. class ConnectorListItem(_Wire):
  192. connector: str
  193. enabled: bool = True
  194. connected: bool = False
  195. connection_status: Optional[ConnectionStatus] = Field(default=None, alias="connectionStatus")
  196. status_reason: Optional[str] = Field(default=None, alias="statusReason")
  197. gateway_disabled_tools: list[str] = Field(default_factory=list, alias="disabledTools")
  198. class ConnectorListResponse(_Wire):
  199. items: list[ConnectorListItem]
  200. next_cursor: Optional[str] = Field(default=None, alias="nextCursor")
  201. class ConnectorAccount(_Wire):
  202. connection_id: str = Field(alias="connectionId")
  203. connector: str
  204. status: ConnectionStatus
  205. status_reason: Optional[str] = Field(default=None, alias="statusReason")
  206. label: str = Field(min_length=1)
  207. alias: Optional[str] = None
  208. # The newest active account for this connector: the one the vendor executes with.
  209. active: bool
  210. # Retired by a reconnect that replaced it; kept, never selectable.
  211. disabled: bool = False
  212. created_at: str = Field(alias="createdAt")
  213. updated_at: str = Field(alias="updatedAt")
  214. class ConnectorAccountsResponse(_Wire):
  215. accounts: list[ConnectorAccount]
  216. class RemovedConnectorAccount(_Wire):
  217. connection_id: str = Field(alias="connectionId")
  218. connector: str
  219. status: Literal["removed"]
  220. class ConnectorConnectionsSummary(_Wire):
  221. total: int = 0
  222. active: int = 0
  223. initiated: int = 0
  224. failed: int = 0
  225. class ConnectorConnectionsResponse(_Wire):
  226. results: list[ConnectorConnectionResult] = Field(default_factory=list)
  227. summary: ConnectorConnectionsSummary = Field(
  228. default_factory=ConnectorConnectionsSummary
  229. )