@devries-cameron20 / composio-1 / commits / 47a7eea34
Fork 0

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

fix: trigger event parsing and revert old client compatibility code

angrybayblade committed Jun 19, 2025 at 12:41 UTC 47a7eea34045e3d5add8d4e36b09af35da6d1a07
1 file changed +345 -37
python/composio/core/models/triggers.py
+345 -37
@@ -24,6 +24,56 @@ from composio.utils.logging import WithLogger
24
25 PUSHER_AUTH_URL = "{base_url}/api/v3/internal/sdk/realtime/auth?source=python"
26
27 +"""
28 +export type _TriggerData = {
29 + appName: string;
30 + clientId: number;
31 + payload: Record<string, unknown>;
32 + originalPayload: Record<string, unknown>;
33 + metadata: {
34 + id: string;
35 + nanoId: string;
36 + triggerName: string;
37 + triggerData: string;
38 + triggerConfig: Record<string, unknown>;
39 + connection: {
40 + id: string;
41 + connectedAccountNanoId: string;
42 + integrationId: string;
43 + authConfigNanoId: string;
44 + clientUniqueUserId: string;
45 + status: string;
46 + };
47 + };
48 +};
49 +"""
50 +
51 +
52 +class _ConnectionData(te.TypedDict):
53 + id: str
54 + status: t.Literal["ACTIVE", "INACTIVE"]
55 + integrationId: str
56 + authConfigNanoId: str
57 + clientUniqueUserId: str
58 + connectedAccountNanoId: str
59 +
60 +
61 +class _TriggerMetadata(te.TypedDict):
62 + id: str
63 + nanoId: str
64 + triggerName: str
65 + triggerData: str
66 + triggerConfig: t.Dict
67 + connection: _ConnectionData
68 +
69 +
70 +class _TriggerData(te.TypedDict):
71 + clientId: str
72 + appName: str
73 + payload: t.Dict
74 + metadata: _TriggerMetadata
75 + originalPayload: t.Dict
76 +
77
78 class TriggerConnectedAccountSchema(t.TypedDict):
79 id: str
@@ -43,20 +93,242 @@ class TriggerMetadataSchema(t.TypedDict):
93 connected_account: TriggerConnectedAccountSchema
94
95
46 -class TriggerEventData(t.TypedDict):
96 +class TriggerEvent(t.TypedDict):
97 id: str # The ID of the trigger
98 + uuid: str # UUID of the trigger
99 + user_id: str # The ID of the user that triggered the event
100
101 trigger_slug: str # The slug of the trigger that triggered the event
50 - user_id: str # The ID of the user that triggered the event
102 toolkit_slug: str # The slug of the toolkit that triggered the event
103
53 - metadata: TriggerMetadataSchema
104 payload: t.Optional[t.Dict[str, t.Any]] # The payload of the trigger
105 + metadata: TriggerMetadataSchema
106 original_payload: t.Optional[
107 t.Dict[str, t.Any]
108 ] # The original payload of the trigger
109
110
111 +_ = {
112 + "appName": "github",
113 + "payload": {
114 + "author": "angrybayblade",
115 + "id": "a2334682759c4324e911d8f52f8fb6bdf1338d94",
116 + "message": "temp",
117 + "timestamp": "2025-06-19T11:28:01+05:30",
118 + "url": "https://github.com/angrybayblade/ph7/commit/a2334682759c4324e911d8f52f8fb6bdf1338d94",
119 + },
120 + "originalPayload": {
121 + "ref": "refs/heads/temp",
122 + "before": "e5eb72bc9f973b6cc82e0de9708660c5341befe5",
123 + "after": "a2334682759c4324e911d8f52f8fb6bdf1338d94",
124 + "repository": {
125 + "id": 752122629,
126 + "node_id": "R_kgDOLNR7BQ",
127 + "name": "ph7",
128 + "full_name": "angrybayblade/ph7",
129 + "private": False,
130 + "owner": {
131 + "name": "angrybayblade",
132 + "email": "35092918+angrybayblade@users.noreply.github.com",
133 + "login": "angrybayblade",
134 + "id": 35092918,
135 + "node_id": "MDQ6VXNlcjM1MDkyOTE4",
136 + "avatar_url": "https://avatars.githubusercontent.com/u/35092918?v=4",
137 + "gravatar_id": "",
138 + "url": "https://api.github.com/users/angrybayblade",
139 + "html_url": "https://github.com/angrybayblade",
140 + "followers_url": "https://api.github.com/users/angrybayblade/followers",
141 + "following_url": "https://api.github.com/users/angrybayblade/following{/other_user}",
142 + "gists_url": "https://api.github.com/users/angrybayblade/gists{/gist_id}",
143 + "starred_url": "https://api.github.com/users/angrybayblade/starred{/owner}{/repo}",
144 + "subscriptions_url": "https://api.github.com/users/angrybayblade/subscriptions",
145 + "organizations_url": "https://api.github.com/users/angrybayblade/orgs",
146 + "repos_url": "https://api.github.com/users/angrybayblade/repos",
147 + "events_url": "https://api.github.com/users/angrybayblade/events{/privacy}",
148 + "received_events_url": "https://api.github.com/users/angrybayblade/received_events",
149 + "type": "User",
150 + "user_view_type": "public",
151 + "site_admin": False,
152 + },
153 + "html_url": "https://github.com/angrybayblade/ph7",
154 + "description": "💧 Python native HTML rendering",
155 + "fork": False,
156 + "url": "https://api.github.com/repos/angrybayblade/ph7",
157 + "forks_url": "https://api.github.com/repos/angrybayblade/ph7/forks",
158 + "keys_url": "https://api.github.com/repos/angrybayblade/ph7/keys{/key_id}",
159 + "collaborators_url": "https://api.github.com/repos/angrybayblade/ph7/collaborators{/collaborator}",
160 + "teams_url": "https://api.github.com/repos/angrybayblade/ph7/teams",
161 + "hooks_url": "https://api.github.com/repos/angrybayblade/ph7/hooks",
162 + "issue_events_url": "https://api.github.com/repos/angrybayblade/ph7/issues/events{/number}",
163 + "events_url": "https://api.github.com/repos/angrybayblade/ph7/events",
164 + "assignees_url": "https://api.github.com/repos/angrybayblade/ph7/assignees{/user}",
165 + "branches_url": "https://api.github.com/repos/angrybayblade/ph7/branches{/branch}",
166 + "tags_url": "https://api.github.com/repos/angrybayblade/ph7/tags",
167 + "blobs_url": "https://api.github.com/repos/angrybayblade/ph7/git/blobs{/sha}",
168 + "git_tags_url": "https://api.github.com/repos/angrybayblade/ph7/git/tags{/sha}",
169 + "git_refs_url": "https://api.github.com/repos/angrybayblade/ph7/git/refs{/sha}",
170 + "trees_url": "https://api.github.com/repos/angrybayblade/ph7/git/trees{/sha}",
171 + "statuses_url": "https://api.github.com/repos/angrybayblade/ph7/statuses/{sha}",
172 + "languages_url": "https://api.github.com/repos/angrybayblade/ph7/languages",
173 + "stargazers_url": "https://api.github.com/repos/angrybayblade/ph7/stargazers",
174 + "contributors_url": "https://api.github.com/repos/angrybayblade/ph7/contributors",
175 + "subscribers_url": "https://api.github.com/repos/angrybayblade/ph7/subscribers",
176 + "subscription_url": "https://api.github.com/repos/angrybayblade/ph7/subscription",
177 + "commits_url": "https://api.github.com/repos/angrybayblade/ph7/commits{/sha}",
178 + "git_commits_url": "https://api.github.com/repos/angrybayblade/ph7/git/commits{/sha}",
179 + "comments_url": "https://api.github.com/repos/angrybayblade/ph7/comments{/number}",
180 + "issue_comment_url": "https://api.github.com/repos/angrybayblade/ph7/issues/comments{/number}",
181 + "contents_url": "https://api.github.com/repos/angrybayblade/ph7/contents/{+path}",
182 + "compare_url": "https://api.github.com/repos/angrybayblade/ph7/compare/{base}...{head}",
183 + "merges_url": "https://api.github.com/repos/angrybayblade/ph7/merges",
184 + "archive_url": "https://api.github.com/repos/angrybayblade/ph7/{archive_format}{/ref}",
185 + "downloads_url": "https://api.github.com/repos/angrybayblade/ph7/downloads",
186 + "issues_url": "https://api.github.com/repos/angrybayblade/ph7/issues{/number}",
187 + "pulls_url": "https://api.github.com/repos/angrybayblade/ph7/pulls{/number}",
188 + "milestones_url": "https://api.github.com/repos/angrybayblade/ph7/milestones{/number}",
189 + "notifications_url": "https://api.github.com/repos/angrybayblade/ph7/notifications{?since,all,participating}",
190 + "labels_url": "https://api.github.com/repos/angrybayblade/ph7/labels{/name}",
191 + "releases_url": "https://api.github.com/repos/angrybayblade/ph7/releases{/id}",
192 + "deployments_url": "https://api.github.com/repos/angrybayblade/ph7/deployments",
193 + "created_at": 1706936166,
194 + "updated_at": "2025-03-22T17:26:27Z",
195 + "pushed_at": 1750312684,
196 + "git_url": "git://github.com/angrybayblade/ph7.git",
197 + "ssh_url": "git@github.com:angrybayblade/ph7.git",
198 + "clone_url": "https://github.com/angrybayblade/ph7.git",
199 + "svn_url": "https://github.com/angrybayblade/ph7",
200 + "homepage": "https://angrybayblade.github.io/ph7/",
201 + "size": 3031,
202 + "stargazers_count": 7,
203 + "watchers_count": 7,
204 + "language": "Python",
205 + "has_issues": True,
206 + "has_projects": True,
207 + "has_downloads": True,
208 + "has_wiki": True,
209 + "has_pages": True,
210 + "has_discussions": False,
211 + "forks_count": 1,
212 + "mirror_url": None,
213 + "archived": False,
214 + "disabled": False,
215 + "open_issues_count": 0,
216 + "license": None,
217 + "allow_forking": True,
218 + "is_template": False,
219 + "web_commit_signoff_required": False,
220 + "topics": [
221 + "css",
222 + "django",
223 + "flask",
224 + "html",
225 + "js",
226 + "template-engine",
227 + "web",
228 + ],
229 + "visibility": "public",
230 + "forks": 1,
231 + "open_issues": 0,
232 + "watchers": 7,
233 + "default_branch": "main",
234 + "stargazers": 7,
235 + "master_branch": "main",
236 + },
237 + "pusher": {
238 + "name": "angrybayblade",
239 + "email": "35092918+angrybayblade@users.noreply.github.com",
240 + },
241 + "sender": {
242 + "login": "angrybayblade",
243 + "id": 35092918,
244 + "node_id": "MDQ6VXNlcjM1MDkyOTE4",
245 + "avatar_url": "https://avatars.githubusercontent.com/u/35092918?v=4",
246 + "gravatar_id": "",
247 + "url": "https://api.github.com/users/angrybayblade",
248 + "html_url": "https://github.com/angrybayblade",
249 + "followers_url": "https://api.github.com/users/angrybayblade/followers",
250 + "following_url": "https://api.github.com/users/angrybayblade/following{/other_user}",
251 + "gists_url": "https://api.github.com/users/angrybayblade/gists{/gist_id}",
252 + "starred_url": "https://api.github.com/users/angrybayblade/starred{/owner}{/repo}",
253 + "subscriptions_url": "https://api.github.com/users/angrybayblade/subscriptions",
254 + "organizations_url": "https://api.github.com/users/angrybayblade/orgs",
255 + "repos_url": "https://api.github.com/users/angrybayblade/repos",
256 + "events_url": "https://api.github.com/users/angrybayblade/events{/privacy}",
257 + "received_events_url": "https://api.github.com/users/angrybayblade/received_events",
258 + "type": "User",
259 + "user_view_type": "public",
260 + "site_admin": False,
261 + },
262 + "created": False,
263 + "deleted": False,
264 + "forced": False,
265 + "base_ref": None,
266 + "compare": "https://github.com/angrybayblade/ph7/compare/e5eb72bc9f97...a2334682759c",
267 + "commits": [
268 + {
269 + "id": "a2334682759c4324e911d8f52f8fb6bdf1338d94",
270 + "tree_id": "ed0ae8c902cb2a0e12d3c64aea8aab66f7b06054",
271 + "distinct": True,
272 + "message": "temp",
273 + "timestamp": "2025-06-19T11:28:01+05:30",
274 + "url": "https://github.com/angrybayblade/ph7/commit/a2334682759c4324e911d8f52f8fb6bdf1338d94",
275 + "author": {
276 + "name": "angrybayblade",
277 + "email": "vptl185@gmail.com",
278 + "username": "angrybayblade",
279 + },
280 + "committer": {
281 + "name": "angrybayblade",
282 + "email": "vptl185@gmail.com",
283 + "username": "angrybayblade",
284 + },
285 + "added": [],
286 + "removed": [],
287 + "modified": ["mkdocs.yml"],
288 + }
289 + ],
290 + "head_commit": {
291 + "id": "a2334682759c4324e911d8f52f8fb6bdf1338d94",
292 + "tree_id": "ed0ae8c902cb2a0e12d3c64aea8aab66f7b06054",
293 + "distinct": True,
294 + "message": "temp",
295 + "timestamp": "2025-06-19T11:28:01+05:30",
296 + "url": "https://github.com/angrybayblade/ph7/commit/a2334682759c4324e911d8f52f8fb6bdf1338d94",
297 + "author": {
298 + "name": "angrybayblade",
299 + "email": "vptl185@gmail.com",
300 + "username": "angrybayblade",
301 + },
302 + "committer": {
303 + "name": "angrybayblade",
304 + "email": "vptl185@gmail.com",
305 + "username": "angrybayblade",
306 + },
307 + "added": [],
308 + "removed": [],
309 + "modified": ["mkdocs.yml"],
310 + },
311 + },
312 + "metadata": {
313 + "id": "2507236e-4be2-4606-b338-fb24c76ce38d",
314 + "nanoId": "ti_VZEWUqF5fQ6P",
315 + "connectionId": "75271255-fe95-4d34-bee3-459a02645e38",
316 + "connectionNanoId": "ca_5KdA-e2C4ZMd",
317 + "triggerName": "GITHUB_COMMIT_EVENT",
318 + "triggerData": '{"event_type": "push", "github_hook_id": "552965247"}',
319 + "triggerConfig": {"repo": "ph7", "owner": "angrybayblade"},
320 + "connection": {
321 + "id": "75271255-fe95-4d34-bee3-459a02645e38",
322 + "connectedAccountNanoId": "ca_5KdA-e2C4ZMd",
323 + "integrationId": "500748ea-8547-4abb-9f9e-10dbcfdb81c2",
324 + "authConfigNanoId": "ac_ZxnpxqOo1nAP",
325 + "clientUniqueUserId": "default",
326 + "status": "ACTIVE",
327 + },
328 + },
329 +}
330 +
331 +
332 class _ChunkedTriggerEventData(te.TypedDict):
333 """Cunked trigger event data model."""
334
@@ -77,7 +349,7 @@ class TriggerEventFilters(te.TypedDict):
349 connected_account_id: te.NotRequired[str]
350
351
80 -TriggerCallback = t.Callable[[TriggerEventData], None]
352 +TriggerCallback = t.Callable[[TriggerEvent], None]
353
354
355 class TriggerSubscription(Resource):
@@ -108,14 +380,47 @@ class TriggerSubscription(Resource):
380
381 return _wrap
382
111 - def _parse_payload(self, event: str) -> t.Optional[TriggerEventData]:
383 + def _parse_payload(self, event: str) -> t.Optional[TriggerEvent]:
384 """Parse event payload."""
385 try:
114 - return TriggerEventData(**json.loads(event)) # type: ignore
386 + data = t.cast(_TriggerData, json.loads(event))
387 except Exception as e:
388 self.logger.warning(f"Error decoding payload: {e}")
389 return None
390
391 + return t.cast(
392 + TriggerEvent,
393 + {
394 + "id": data["metadata"]["nanoId"],
395 + "uuid": data["metadata"]["id"],
396 + "user_id": data["metadata"]["connection"]["clientUniqueUserId"],
397 + "toolkit_slug": data["appName"],
398 + "trigger_slug": data["metadata"]["triggerName"],
399 + "metadata": {
400 + "id": data["metadata"]["nanoId"],
401 + "uuid": data["metadata"]["id"],
402 + "toolkit_slug": data["appName"],
403 + "trigger_slug": data["metadata"]["triggerName"],
404 + "trigger_data": data["metadata"]["triggerData"],
405 + "trigger_config": data["metadata"]["triggerConfig"],
406 + "connected_account": {
407 + "id": data["metadata"]["connection"]["connectedAccountNanoId"],
408 + "uuid": data["metadata"]["connection"]["id"],
409 + "auth_config_id": data["metadata"]["connection"][
410 + "authConfigNanoId"
411 + ],
412 + "auth_config_uuid": data["metadata"]["connection"][
413 + "integrationId"
414 + ],
415 + "user_id": data["metadata"]["connection"]["clientUniqueUserId"],
416 + "status": data["metadata"]["connection"]["status"],
417 + },
418 + },
419 + "payload": data["payload"],
420 + "original_payload": data["originalPayload"],
421 + },
422 + )
423 +
424 def _handle_chunked_events(self, event: str) -> None:
425 """Handle chunked events."""
426 data = _ChunkedTriggerEventData(**json.loads(event)) # type: ignore
@@ -129,7 +434,7 @@ class TriggerSubscription(Resource):
434
435 def _filters_match(
436 self,
132 - data: TriggerEventData,
437 + data: TriggerEvent,
438 filters: TriggerEventFilters,
439 callback: str,
440 ) -> bool:
@@ -157,7 +462,7 @@ class TriggerSubscription(Resource):
462 def _handle_callback(
463 self,
464 callback: TriggerCallback,
160 - data: TriggerEventData,
465 + data: TriggerEvent,
466 filters: TriggerEventFilters,
467 ) -> t.Any:
468 """Handle callback."""
@@ -317,6 +622,12 @@ class _SubcriptionBuilder(WithLogger):
622 class Triggers(Resource):
623 """Triggers (instance) class"""
624
625 + enable: t.Callable
626 + """Enables a trigger given its id"""
627 +
628 + disable: t.Callable
629 + """Disables a trigger given its id"""
630 +
631 def __init__(self, client: HttpClient):
632 """
633 Initialize the triggers resource.
@@ -325,25 +636,16 @@ class Triggers(Resource):
636 """
637 self._client = client
638 self.list_enum = self._client.triggers_types.retrieve_enum
328 - self.list = self._client.triggers_types.list
639 self.get_type = self._client.triggers_types.retrieve
330 -
331 - def delete(self, trigger_id: str):
332 - """Delete a trigger instance by ID"""
333 - return self._client.trigger_instances.remove_upsert(slug=trigger_id)
334 -
335 - def enable(self, trigger_id: str):
336 - """Enable a trigger instance by ID"""
337 - return self._client.trigger_instances.update_status(
640 + self.list = self._client.triggers_types.list
641 + self.delete = self._client.trigger_instances.manage.delete
642 + self.enable = functools.partial(
643 + self._client.trigger_instances.manage.update,
644 status="enable",
339 - slug=trigger_id,
645 )
341 -
342 - def disable(self, trigger_id: str):
343 - """Disable a trigger instance by ID"""
344 - return self._client.trigger_instances.update_status(
646 + self.disable = functools.partial(
647 + self._client.trigger_instances.manage.update,
648 status="disable",
346 - slug=trigger_id,
649 )
650
651 def list_active(
@@ -413,21 +715,10 @@ class Triggers(Resource):
715 :return: The trigger instance
716 """
717 if user_id is not None:
416 - connected_account_id = self.get_type(slug=slug).toolkit.name
417 - connected_accounts = self._client.connected_accounts.list(
418 - toolkit_slugs=[connected_account_id]
718 + connected_account_id = self._get_connected_account_for_user(
719 + trigger=slug,
720 + user_id=user_id,
721 )
420 - if len(connected_accounts.items) == 0:
421 - raise exceptions.NoItemsFound(
422 - f"No connected accounts found for {slug}"
423 - )
424 -
425 - account, *_ = sorted(
426 - connected_accounts.items,
427 - key=lambda x: x.created_at,
428 - reverse=True,
429 - )
430 - connected_account_id = account.id
722
723 if connected_account_id is None:
724 raise exceptions.InvalidParams(
@@ -440,6 +731,23 @@ class Triggers(Resource):
731 body_trigger_config_1=trigger_config or self._client.not_given,
732 )
733
734 + def _get_connected_account_for_user(self, trigger: str, user_id: str) -> str:
735 + toolkit = self.get_type(slug=trigger).toolkit.name
736 + connected_accounts = self._client.connected_accounts.list(
737 + toolkit_slugs=[toolkit]
738 + )
739 + if len(connected_accounts.items) == 0:
740 + raise exceptions.NoItemsFound(
741 + f"No connected accounts found for {trigger} and {user_id}"
742 + )
743 +
744 + account, *_ = sorted(
745 + connected_accounts.items,
746 + key=lambda x: x.created_at,
747 + reverse=True,
748 + )
749 + return account.id
750 +
751 def subscribe(self, timeout: float = 15.0) -> TriggerSubscription:
752 """
753 Subscribe to a trigger and receive trigger events.