Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
remove triggers
haxzie committed
May 28, 2025 at 17:08 UTC
bca2754947eae2481720e2aaee47c93a930b7159
5 files changed
+53
-307
examples/triggers/src/index.ts
+1
-1
@@ -17,7 +17,7 @@ import 'dotenv/config';
17
*/
18
const composio = new Composio({
19
apiKey: process.env.COMPOSIO_API_KEY,
20
- baseURL: 'http://localhost:9900',
20
+ baseURL: 'https://staging-backend.composio.dev',
21
});
22
23
/**
packages/core/src/models/Triggers.ts
+1
-1
@@ -24,8 +24,8 @@ import {
24
TriggerSubscribeParamSchema,
25
IncomingTriggerPayloadSchema,
26
IncomingTriggerPayload,
27
+ TriggerData,
28
} from '../types/triggers.types';
28
-import { TriggerData } from '../utils/pusher';
29
import logger from '../utils/logger';
30
import { telemetry } from '../telemetry/Telemetry';
31
import { ValidationError } from '../errors';
packages/core/src/types/triggers.types.ts
+28
@@ -117,3 +117,31 @@ export const IncomingTriggerPayloadSchema = z.object({
117
});
118
119
export type IncomingTriggerPayload = z.infer<typeof IncomingTriggerPayloadSchema>;
120
+
121
+type TChunkedTriggerData = {
122
+ id: string;
123
+ index: number;
124
+ chunk: string;
125
+ final: boolean;
126
+};
127
+
128
+export type TriggerData = {
129
+ appName: string;
130
+ clientId: number;
131
+ payload: Record<string, unknown>;
132
+ originalPayload: Record<string, unknown>;
133
+ metadata: {
134
+ id: string;
135
+ triggerName: string;
136
+ triggerData: string;
137
+ triggerConfig: Record<string, unknown>;
138
+ connection: {
139
+ id: string;
140
+ connectedAccountNanoId: string;
141
+ integrationId: string;
142
+ authConfigNanoId: string;
143
+ clientUniqueUserId: string;
144
+ status: string;
145
+ };
146
+ };
147
+};
packages/core/src/utils/pusher.ts
deleted
-289
@@ -1,289 +0,0 @@
1
-import { PusherSubscriptionError } from '../errors/PusherErrors';
2
-import logger from './logger';
3
-
4
-const PUSHER_KEY = process.env.CLIENT_PUSHER_KEY || 'ff9f18c208855d77a152';
5
-const PUSHER_CLUSTER = 'mt1';
6
-
7
-type Channel = {
8
- subscribe: (channelName: string) => unknown;
9
- unsubscribe: (channelName: string) => unknown;
10
- bind: (event: string, callback: (data: Record<string, unknown>) => void) => unknown;
11
-};
12
-
13
-type PusherClient = {
14
- subscribe: (channelName: string) => Channel;
15
- unsubscribe: (channelName: string) => unknown;
16
- bind: (event: string, callback: (data: Record<string, unknown>) => void) => unknown;
17
- connection: {
18
- bind: (event: string, callback: (error: Error) => void) => void;
19
- socket_id?: string;
20
- };
21
-};
22
-
23
-type AuthOptions = {
24
- endpoint: string;
25
- headers: Record<string, string>;
26
- params?: Record<string, string>;
27
-};
28
-
29
-type TChunkedTriggerData = {
30
- id: string;
31
- index: number;
32
- chunk: string;
33
- final: boolean;
34
-};
35
-
36
-export type TriggerData = {
37
- appName: string;
38
- clientId: number;
39
- payload: Record<string, unknown>;
40
- originalPayload: Record<string, unknown>;
41
- metadata: {
42
- id: string;
43
- triggerName: string;
44
- triggerData: string;
45
- triggerConfig: Record<string, unknown>;
46
- connection: {
47
- id: string;
48
- connectedAccountNanoId: string;
49
- integrationId: string;
50
- authConfigNanoId: string;
51
- clientUniqueUserId: string;
52
- status: string;
53
- };
54
- };
55
-};
56
-
57
-export class PusherUtils {
58
- static pusherClient: PusherClient;
59
-
60
- static async getPusherClient(baseURL: string, apiKey: string): Promise<PusherClient> {
61
- try {
62
- if (!PusherUtils.pusherClient) {
63
- // Dynamic import not available, using require for now
64
- // TODO: Update to use dynamic import when available
65
- // eslint-disable-next-line @typescript-eslint/no-require-imports
66
- const PusherClient = require('pusher-js');
67
- PusherUtils.pusherClient = new PusherClient(PUSHER_KEY, {
68
- cluster: PUSHER_CLUSTER,
69
- channelAuthorization: {
70
- endpoint: `${baseURL}/api/v1/client/auth/pusher_auth`,
71
- headers: {
72
- 'x-api-key': apiKey,
73
- },
74
- transport: 'ajax',
75
- customHandler: async (authOptions: AuthOptions) => {
76
- try {
77
- const response = await fetch(authOptions.endpoint, {
78
- method: 'POST',
79
- headers: {
80
- ...authOptions.headers,
81
- 'Content-Type': 'application/json',
82
- },
83
- body: JSON.stringify(authOptions.params),
84
- });
85
- const data = await response.text();
86
- logger.debug('Pusher auth response:', data);
87
- try {
88
- return JSON.parse(data);
89
- } catch (e) {
90
- logger.error('Failed to parse auth response:', data);
91
- throw new Error('Invalid auth response format');
92
- }
93
- } catch (error) {
94
- logger.error('Pusher auth request failed:', error);
95
- throw error;
96
- }
97
- },
98
- },
99
- });
100
-
101
- // Add connection error handling
102
- PusherUtils.pusherClient.connection.bind('error', (err: Error) => {
103
- logger.error('Pusher connection error:', err);
104
- throw new Error(`Pusher connection error: ${err.message}`);
105
- });
106
- }
107
- return PusherUtils.pusherClient;
108
- } catch (error: unknown) {
109
- const errorMessage = error instanceof Error ? error.message : String(error);
110
- logger.error('Failed to initialize Pusher client:', error);
111
- throw new Error(`Failed to initialize Pusher client: ${errorMessage}`);
112
- }
113
- }
114
-
115
- /**
116
- * Subscribes to a Pusher channel and binds an event to a callback function.
117
- * @param {string} channelName - The name of the channel to subscribe to.
118
- * @param {string} event - The event to bind to the channel.
119
- * @param {(data: Record<string, unknown>) => void} fn - The callback function to execute when the event is triggered.
120
- * @returns {PusherClient} The Pusher client instance.
121
- */
122
- static async subscribe(
123
- channelName: string,
124
- event: string,
125
- fn: (data: Record<string, unknown>) => void
126
- ): Promise<void> {
127
- try {
128
- await PusherUtils.pusherClient.subscribe(channelName).bind(event, fn);
129
- } catch (error) {
130
- logger.error(`Error subscribing to ${channelName} with event ${event}: ${error}`);
131
- }
132
- }
133
-
134
- /**
135
- * Unsubscribes from a Pusher channel.
136
- * @param {string} channelName - The name of the channel to unsubscribe from.
137
- * @returns {void}
138
- */
139
- static async unsubscribe(channelName: string): Promise<void> {
140
- PusherUtils.pusherClient.unsubscribe(channelName);
141
- }
142
-
143
- /**
144
- * Binds an event to a channel with support for chunked messages.
145
- * @param {PusherClient} channel - The Pusher channel to bind the event to.
146
- * @param {string} event - The event to bind to the channel.
147
- * @param {(data: unknown) => void} callback - The callback function to execute when the event is triggered.
148
- */
149
- private static bindWithChunking(
150
- channel: PusherClient,
151
- event: string,
152
- callback: (data: Record<string, unknown>) => void
153
- ): void {
154
- try {
155
- // Wrap the callback to handle errors
156
- const safeCallback = (data: Record<string, unknown>) => {
157
- try {
158
- callback(data);
159
- } catch (error: unknown) {
160
- const errorMessage = error instanceof Error ? error.message : String(error);
161
- logger.error('Error in chunked event callback:', errorMessage);
162
- // Don't throw here to prevent breaking the subscription
163
- }
164
- };
165
-
166
- channel.bind(event, safeCallback);
167
-
168
- // Now the chunked variation. Allows arbitrarily long messages.
169
- const events: {
170
- [key: string]: { chunks: string[]; receivedFinal: boolean };
171
- } = {};
172
-
173
- channel.bind('chunked-' + event, data => {
174
- try {
175
- const typedData = data as TChunkedTriggerData;
176
-
177
- // Validate chunked data
178
- if (
179
- !typedData ||
180
- typeof typedData.id !== 'string' ||
181
- typeof typedData.index !== 'number'
182
- ) {
183
- throw new Error('Invalid chunked trigger data format');
184
- }
185
-
186
- if (!events.hasOwnProperty(typedData.id)) {
187
- events[typedData.id] = { chunks: [], receivedFinal: false };
188
- }
189
-
190
- const ev = events[typedData.id];
191
- ev.chunks[typedData.index] = typedData.chunk;
192
-
193
- if (typedData.final) ev.receivedFinal = true;
194
-
195
- if (ev.receivedFinal && ev.chunks.length === Object.keys(ev.chunks).length) {
196
- try {
197
- const parsedData = JSON.parse(ev.chunks.join(''));
198
- safeCallback(parsedData);
199
- } catch (parseError: unknown) {
200
- const errorMessage =
201
- parseError instanceof Error ? parseError.message : String(parseError);
202
- logger.error('Failed to parse chunked data:', errorMessage);
203
- } finally {
204
- delete events[typedData.id];
205
- }
206
- }
207
- } catch (error: unknown) {
208
- const errorMessage = error instanceof Error ? error.message : String(error);
209
- logger.error('Error processing chunked trigger data:', errorMessage);
210
- // Clean up the event data to prevent memory leaks
211
- if (data && typeof data === 'object' && 'id' in data) {
212
- delete events[data.id as string];
213
- }
214
- }
215
- });
216
- } catch (error: unknown) {
217
- const errorMessage = error instanceof Error ? error.message : String(error);
218
- logger.error('Failed to bind chunked events:', error);
219
- throw new Error(`Failed to bind chunked events: ${errorMessage}`);
220
- }
221
- }
222
-
223
- /**
224
- * Subscribes to a trigger channel for a client and handles chunked data.
225
- * @param {string} clientId - The unique identifier for the client subscribing to the events.
226
- * @param {(data: TriggerData) => void} fn - The callback function to execute when trigger data is received.
227
- *
228
- * @example
229
- * ```ts
230
- * composio.trigger.subscribe((data) => {
231
- * console.log(data);
232
- * });
233
- * ```
234
- */
235
- static triggerSubscribe(clientId: string, fn: (data: TriggerData) => void): void {
236
- try {
237
- if (!PusherUtils.pusherClient) {
238
- throw new Error('Pusher client not initialized');
239
- }
240
-
241
- const channel = PusherUtils.pusherClient.subscribe(`private-${clientId}_triggers`);
242
-
243
- // Add subscription error handling
244
- channel.bind('pusher:subscription_error', (data: Record<string, unknown>) => {
245
- const error = data.error ? String(data.error) : 'Unknown subscription error';
246
- throw new PusherSubscriptionError(`Trigger subscription error`, {
247
- cause: error,
248
- });
249
- });
250
-
251
- // Wrap the callback to handle errors
252
- const safeCallback = (data: TriggerData) => {
253
- try {
254
- fn(data);
255
- } catch (error: unknown) {
256
- const errorMessage = error instanceof Error ? error.message : String(error);
257
- logger.error('Error in trigger callback:', errorMessage);
258
- // Don't throw here to prevent breaking the subscription
259
- }
260
- };
261
-
262
- PusherUtils.bindWithChunking(
263
- channel as PusherClient,
264
- 'trigger_to_client',
265
- safeCallback as (data: unknown) => void
266
- );
267
-
268
- logger.info(`Subscribed to triggers. You should start receiving events now.`);
269
- } catch (error: unknown) {
270
- const errorMessage = error instanceof Error ? error.message : String(error);
271
- logger.error('Failed to subscribe to triggers:', error);
272
- throw new Error(`Failed to subscribe to triggers: ${errorMessage}`);
273
- }
274
- }
275
-
276
- static triggerUnsubscribe(clientId: string): void {
277
- try {
278
- if (!PusherUtils.pusherClient) {
279
- throw new Error('Pusher client not initialized');
280
- }
281
- PusherUtils.pusherClient.unsubscribe(`private-${clientId}_triggers`);
282
- logger.info('Successfully unsubscribed from triggers');
283
- } catch (error: unknown) {
284
- const errorMessage = error instanceof Error ? error.message : String(error);
285
- logger.error('Failed to unsubscribe from triggers:', error);
286
- throw new Error(`Failed to unsubscribe from triggers: ${errorMessage}`);
287
- }
288
- }
289
-}
packages/core/test/models/triggers.test.ts
+23
-16
@@ -1,9 +1,12 @@
1
import { describe, it, expect, vi, beforeEach, afterEach, Mock } from 'vitest';
2
import { Triggers } from '../../src/models/triggers';
3
import ComposioClient from '@composio/client';
4
-import { TriggerData } from '../../src/utils/pusher';
4
import logger from '../../src/utils/logger';
6
-import { TriggerSubscribeParams } from '../../src/types/triggers.types';
5
+import {
6
+ TriggerSubscribeParams,
7
+ TriggerData,
8
+ IncomingTriggerPayload,
9
+} from '../../src/types/triggers.types';
10
import { telemetry } from '../../src/telemetry/Telemetry';
11
import { ValidationError } from '../../src/errors';
12
import { PusherService } from '../../src/services/pusher/Pusher';
@@ -127,38 +130,40 @@ const mockTriggerData: TriggerData = {
130
originalPayload: { action: 'push', repository: 'test-repo' },
131
metadata: {
132
id: 'trigger-123',
130
- connectionId: 'conn-123',
133
triggerName: 'github_webhook',
134
triggerData: '{"action":"push"}',
135
triggerConfig: { webhook_url: 'https://example.com/webhook' },
136
connection: {
137
id: 'conn-123',
138
+ connectedAccountNanoId: 'conn-123',
139
integrationId: 'github',
140
+ authConfigNanoId: 'auth-123',
141
clientUniqueUserId: 'user-456',
142
status: 'enable',
143
},
144
},
145
};
146
143
-const mockIncomingTriggerPayload = {
147
+const mockIncomingTriggerPayload: IncomingTriggerPayload = {
148
id: 'trigger-123',
145
- clientId: '123',
149
triggerSlug: 'github_webhook',
150
toolkitSlug: 'github',
151
+ userId: 'user-456',
152
payload: { action: 'push', repository: 'test-repo' },
153
originalPayload: { action: 'push', repository: 'test-repo' },
154
metadata: {
155
id: 'trigger-123',
152
- connectedAccountId: 'conn-123',
156
+ toolkitSlug: 'github',
157
triggerSlug: 'github_webhook',
154
- triggerName: 'github_webhook',
158
triggerData: '{"action":"push"}',
159
triggerConfig: { webhook_url: 'https://example.com/webhook' },
157
- connection: {
160
+ connectedAccount: {
161
id: 'conn-123',
159
- integrationId: 'github',
160
- clientUniqueUserId: 'user-456',
161
- status: 'enable',
162
+ uuid: 'conn-123',
163
+ authConfigId: 'auth-123',
164
+ authConfigUUID: 'github',
165
+ userId: 'user-456',
166
+ status: 'ACTIVE',
167
},
168
},
169
};
@@ -409,7 +414,7 @@ describe('Triggers', () => {
414
toolkits: ['github'],
415
triggerId: 'trigger-123',
416
connectedAccountId: 'conn-123',
412
- triggerName: 'github_webhook',
417
+ triggerSlug: ['github_webhook'],
418
triggerData: '{"action":"push"}',
419
userId: 'user-456',
420
};
@@ -484,8 +489,8 @@ describe('Triggers', () => {
489
);
490
});
491
487
- it('should log debug message when triggerName filter does not match', async () => {
488
- const filters: TriggerSubscribeParams = { triggerName: 'slack_message' };
492
+ it('should log debug message when triggerSlug filter does not match', async () => {
493
+ const filters: TriggerSubscribeParams = { triggerSlug: ['slack_message'] };
494
await triggers.subscribe(mockCallback, filters);
495
496
const subscribeCall = vi.mocked(mockPusherService.subscribe).mock.calls[0];
@@ -495,7 +500,7 @@ describe('Triggers', () => {
500
501
expect(mockCallback).not.toHaveBeenCalled();
502
expect(logger.debug).toHaveBeenCalledWith(
498
- 'Trigger does not match triggerName filter',
503
+ 'Trigger does not match triggerSlug filter',
504
expect.any(String)
505
);
506
});
@@ -537,9 +542,10 @@ describe('Triggers', () => {
542
toolkits: ['github'],
543
triggerId: 'trigger-123',
544
connectedAccountId: 'conn-123',
540
- triggerName: 'github_webhook',
545
+ triggerSlug: ['github_webhook'],
546
triggerData: '{"action":"push"}',
547
userId: 'user-456',
548
+ authConfigId: 'auth-123',
549
};
550
await triggers.subscribe(mockCallback, filters);
551
@@ -557,6 +563,7 @@ describe('Triggers', () => {
563
const filters: TriggerSubscribeParams = {
564
toolkits: ['slack'],
565
triggerId: 'trigger-456',
566
+ triggerSlug: ['slack_message'],
567
};
568
await triggers.subscribe(mockCallback, filters);
569