Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

next
py 191 lines 5.74 KB
Raw
1 """
2 Webhook event types for typed event handling.
3
4 This module provides TypedDict definitions for specific webhook event types,
5 enabling type-safe handling of events like connection expiration.
6 """
7
8 from __future__ import annotations
9
10 import typing as t
11 from enum import Enum
12
13 import typing_extensions as te
14
15
16 class WebhookEventType(str, Enum):
17 """Known webhook event types."""
18
19 CONNECTION_EXPIRED = "composio.connected_account.expired"
20 TRIGGER_MESSAGE = "composio.trigger.message"
21
22
23 class ConnectionStatusEnum(str, Enum):
24 """Connection status values."""
25
26 INITIALIZING = "INITIALIZING"
27 INITIATED = "INITIATED"
28 ACTIVE = "ACTIVE"
29 FAILED = "FAILED"
30 EXPIRED = "EXPIRED"
31 INACTIVE = "INACTIVE"
32 REVOKED = "REVOKED"
33
34
35 # =============================================================================
36 # CONNECTED ACCOUNT DATA (matches GET /api/v3/connected_accounts/{id})
37 # =============================================================================
38
39
40 class ConnectedAccountToolkit(te.TypedDict):
41 """Toolkit information in connected account response."""
42
43 slug: str
44
45
46 class ConnectedAccountAuthConfigDeprecated(te.TypedDict, total=False):
47 """Deprecated auth config fields."""
48
49 uuid: str
50
51
52 class ConnectedAccountAuthConfig(te.TypedDict, total=False):
53 """Auth config details in connected account response."""
54
55 id: te.Required[str]
56 auth_scheme: te.Required[str]
57 is_composio_managed: te.Required[bool]
58 is_disabled: te.Required[bool]
59 deprecated: ConnectedAccountAuthConfigDeprecated
60
61
62 class ConnectionStateVal(te.TypedDict, total=False):
63 """Connection state value - varies by auth scheme."""
64
65 status: str
66 # OAuth2 fields
67 access_token: str
68 refresh_token: t.Optional[str]
69 token_type: str
70 expires_in: t.Union[int, str, None]
71 scope: t.Union[str, t.List[str], None]
72 id_token: str
73 code_verifier: str
74 callback_url: str
75 # OAuth1 fields
76 oauth_token: str
77 oauth_token_secret: str
78 # API Key fields
79 api_key: str
80 generic_api_key: str
81 # Bearer Token fields
82 token: str
83 # Basic auth fields
84 username: str
85 password: str
86
87
88 class ConnectionState(te.TypedDict):
89 """Connection state data discriminated by auth scheme."""
90
91 authScheme: str
92 val: ConnectionStateVal
93
94
95 class ConnectedAccountDeprecated(te.TypedDict, total=False):
96 """Deprecated connected account fields."""
97
98 labels: t.List[str]
99 uuid: str
100
101
102 class SingleConnectedAccountDetailedResponse(te.TypedDict, total=False):
103 """
104 Connected account data matching GET /api/v3/connected_accounts/{id} response.
105
106 This is used in webhook payloads for connection lifecycle events.
107 It intentionally does NOT reuse composio_client's ConnectedAccountRetrieveResponse
108 because webhook payloads arrive in raw snake_case format, while the SDK client
109 transforms responses to a different shape. This TypedDict validates the raw
110 webhook payload directly without any transformation layer.
111
112 See Also:
113 composio_client.types.connected_account_retrieve_response for the SDK version.
114 """
115
116 toolkit: te.Required[ConnectedAccountToolkit]
117 auth_config: te.Required[ConnectedAccountAuthConfig]
118 id: te.Required[str]
119 user_id: te.Required[str]
120 status: te.Required[str] # ConnectionStatusEnum value
121 created_at: te.Required[str]
122 updated_at: te.Required[str]
123 state: te.Required[ConnectionState]
124 data: te.Required[t.Dict[str, t.Any]]
125 params: te.Required[t.Dict[str, t.Any]]
126 status_reason: te.Required[t.Optional[str]]
127 is_disabled: te.Required[bool]
128 test_request_endpoint: str
129 deprecated: ConnectedAccountDeprecated
130
131
132 # =============================================================================
133 # CONNECTION EXPIRED WEBHOOK EVENT
134 # =============================================================================
135
136
137 class WebhookConnectionMetadata(te.TypedDict):
138 """Webhook metadata for connection events."""
139
140 project_id: str
141 org_id: str
142
143
144 class ConnectionExpiredEvent(te.TypedDict):
145 """
146 Connection expired webhook event payload.
147
148 Emitted when a connected account expires due to authentication refresh failure.
149
150 Example:
151 >>> from composio.core.models.webhook_events import is_connection_expired_event
152 >>>
153 >>> def handle_webhook(payload: dict) -> None:
154 ... if is_connection_expired_event(payload):
155 ... print(f"Connection {payload['data']['id']} expired")
156 ... print(f"Toolkit: {payload['data']['toolkit']['slug']}")
157 ... print(f"User: {payload['data']['user_id']}")
158 """
159
160 id: str # Unique message ID (e.g., "msg_847cdfcd-d219-4f18-a6dd-91acd42ca94a")
161 timestamp: str # ISO-8601 timestamp
162 type: t.Literal["composio.connected_account.expired"]
163 data: SingleConnectedAccountDetailedResponse
164 metadata: WebhookConnectionMetadata
165
166
167 # Type alias for non-trigger webhook events with specific typed schemas.
168 # Trigger events (composio.trigger.message) are handled through the
169 # TriggerEvent type in triggers.py via the trigger subscription system.
170 WebhookEvent = t.Union[ConnectionExpiredEvent]
171
172
173 def is_connection_expired_event(
174 payload: t.Dict[str, t.Any],
175 ) -> t.TypeGuard[ConnectionExpiredEvent]:
176 """
177 Check if a webhook payload is a connection expired event.
178
179 :param payload: The webhook payload to check
180 :return: True if this is a connection expired event
181
182 Example:
183 >>> from composio.core.models.webhook_events import is_connection_expired_event
184 >>>
185 >>> if is_connection_expired_event(payload):
186 ... handle_connection_expired(payload) # payload is narrowed to ConnectionExpiredEvent
187 """
188 return (
189 isinstance(payload, dict)
190 and payload.get("type") == WebhookEventType.CONNECTION_EXPIRED.value
191 )