Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
Mirrored from https://github.com/Camo67/composio.git
Synced Nov 23, 04:15 UTC
Add trigger subscription with pusher
haxzie committed
Apr 17, 2025 at 16:12 UTC
cfb5ad72328bb64309a30ccd7f2d6f5adccf9c8f
8 files changed
+277
-13
README.md
+3
@@ -51,5 +51,8 @@ What's not included from @composio/client
51
- [ ] CLI
52
- [ ] MCP
53
- [ ] Team Members
54
+- [ ] File uploads/user files
55
+- [ ] Trigger Subscriptions
56
+- [ ] Tests
57
58
These models can be still be accessed via the SDK explicitly by using the `@composio/client`.
\ No newline at end of file
packages/core/package.json
+1
-1
@@ -18,7 +18,7 @@
18
"typescript": "^5.8.3"
19
},
20
"dependencies": {
21
- "@composio/client": "0.1.0-alpha.1",
21
+ "@composio/client": "0.1.0-alpha.7",
22
"zod": "^3.24.2"
23
}
24
}
packages/core/src/composio.ts
+3
-2
@@ -18,7 +18,7 @@ import { checkForLatestVersionFromNPM } from "./utils/version";
18
19
export type ComposioConfig<TToolCollection, TTool, TToolset extends BaseComposioToolset<TToolCollection, TTool>> = {
20
apiKey?: string;
21
- baseUrl?: string;
21
+ baseURL?: string;
22
allowTracking?: boolean;
23
allowTracing?: boolean;
24
toolset?: TToolset;
@@ -79,7 +79,7 @@ export class Composio<TToolCollection, TTool, TToolset extends BaseComposioTools
79
constructor(config: ComposioConfig<TToolCollection, TTool, TToolset>) {
80
81
const { baseURL: baseURLParsed, apiKey: apiKeyParsed } = getSDKConfig(
82
- config?.baseUrl,
82
+ config?.baseURL,
83
config?.apiKey
84
);
85
@@ -97,6 +97,7 @@ export class Composio<TToolCollection, TTool, TToolset extends BaseComposioTools
97
baseURL: baseURLParsed,
98
});
99
100
+ this.client
101
/**
102
* Keep a reference to the config object.
103
* This is useful for creating a builder pattern, debugging and logging.
packages/core/src/models/Session.ts
new
+21
@@ -0,0 +1,21 @@
1
+import { SessionGetInfoResponse } from "@composio/client/resources/auth/session";
2
+import { InstrumentedInstance } from "../types/telemetry.types";
3
+import ComposioSDK from "@composio/client";
4
+
5
+
6
+export class Session implements InstrumentedInstance {
7
+ readonly FILE_NAME: string = "core/models/Session.ts";
8
+ private client: ComposioSDK;
9
+
10
+ constructor(client: ComposioSDK) {
11
+ this.client = client;
12
+ }
13
+
14
+ /**
15
+ * Get the active session info
16
+ * @returns {Promise<SessionGetInfoResponse>} Session info
17
+ */
18
+ async getInfo(): Promise<SessionGetInfoResponse> {
19
+ return this.client.auth.session.getInfo();
20
+ }
21
+}
\ No newline at end of file
packages/core/src/models/Triggers.ts
+66
-1
@@ -11,8 +11,11 @@ import {
11
TriggersTypeRetrieveEnumResponse,
12
TriggersTypeRetrieveResponse,
13
} from "@composio/client/resources/index";
14
-import { TriggerStatusEnum } from "../types/triggers.types";
14
+import { TriggerStatusEnum, TriggerSubscribeParams } from "../types/triggers.types";
15
import { InstrumentedInstance } from "../types/telemetry.types";
16
+import { PusherUtils, TriggerData } from "../utils/pusher";
17
+import logger from "../utils/logger";
18
+import { Session } from "./Session";
19
20
21
@@ -162,4 +165,66 @@ export class Triggers implements InstrumentedInstance {
165
async listEnum(options?: RequestOptions): Promise<TriggersTypeRetrieveEnumResponse> {
166
return this.client.triggersTypes.retrieveEnum(options);
167
}
168
+
169
+ async subscribe(
170
+ fn: (data: TriggerData) => void,
171
+ filters: TriggerSubscribeParams = {}
172
+ ) {
173
+
174
+ if (!fn) throw new Error("Function is required for trigger subscription");
175
+
176
+ // @TODO: Get the client id from the backend
177
+ const session = new Session(this.client);
178
+ const sessionInfo = await session.getInfo();
179
+ const clientId = sessionInfo.project?.id;
180
+
181
+ if (!clientId) throw new Error("Client ID not found");
182
+
183
+ await PusherUtils.getPusherClient(
184
+ this.client.baseURL,
185
+ this.client.apiKey
186
+ );
187
+
188
+ const shouldSendTrigger = (data: TriggerData) => {
189
+ if (Object.keys(filters).length === 0) return true;
190
+ else {
191
+ return (
192
+ (!filters.appName ||
193
+ data.appName.toLowerCase() === filters.appName.toLowerCase()) &&
194
+ (!filters.triggerId ||
195
+ data.metadata.id.toLowerCase() ===
196
+ filters.triggerId.toLowerCase()) &&
197
+ (!filters.connectionId ||
198
+ data.metadata.connectionId.toLowerCase() ===
199
+ filters.connectionId.toLowerCase()) &&
200
+ (!filters.triggerName ||
201
+ data.metadata.triggerName.toLowerCase() ===
202
+ filters.triggerName.toLowerCase()) &&
203
+ (!filters.entityId ||
204
+ data.metadata.connection.clientUniqueUserId.toLowerCase() ===
205
+ filters.entityId.toLowerCase()) &&
206
+ (!filters.integrationId ||
207
+ data.metadata.connection.integrationId.toLowerCase() ===
208
+ filters.integrationId.toLowerCase())
209
+ );
210
+ }
211
+ };
212
+
213
+ logger.debug("Subscribing to triggers", filters);
214
+ PusherUtils.triggerSubscribe(clientId, (data: TriggerData) => {
215
+ if (shouldSendTrigger(data)) {
216
+ fn(data);
217
+ }
218
+ });
219
+ }
220
+
221
+ async unsubscribe() {
222
+ const session = new Session(this.client);
223
+ const sessionInfo = await session.getInfo();
224
+ const clientId = sessionInfo.project?.id;
225
+
226
+ if (!clientId) throw new Error("Client ID not found");
227
+
228
+ PusherUtils.triggerUnsubscribe(clientId);
229
+ }
230
}
packages/core/src/types/triggers.types.ts
+14
-1
@@ -1 +1,14 @@
1
-export type TriggerStatusEnum = "enable" | "disable";
\ No newline at end of file
1
+import { z } from "zod";
2
+
3
+export type TriggerStatusEnum = "enable" | "disable";
4
+
5
+export const ZTriggerSubscribeParam = z.object({
6
+ appName: z.string().optional(),
7
+ triggerId: z.string().optional(),
8
+ connectionId: z.string().optional(),
9
+ integrationId: z.string().optional(),
10
+ triggerName: z.string().optional(),
11
+ triggerData: z.string().optional(),
12
+ entityId: z.string().optional(),
13
+});
14
+export type TriggerSubscribeParams = z.infer<typeof ZTriggerSubscribeParam>;
\ No newline at end of file
packages/core/src/utils/pusher.ts
new
+164
@@ -0,0 +1,164 @@
1
+import logger from "./logger";
2
+
3
+const PUSHER_KEY = process.env.CLIENT_PUSHER_KEY || "ff9f18c208855d77a152";
4
+const PUSHER_CLUSTER = "mt1";
5
+
6
+type Channel = {
7
+ subscribe: (channelName: string) => unknown;
8
+ unsubscribe: (channelName: string) => unknown;
9
+ bind: (
10
+ event: string,
11
+ callback: (data: Record<string, unknown>) => void
12
+ ) => unknown;
13
+};
14
+
15
+type PusherClient = {
16
+ subscribe: (channelName: string) => Channel;
17
+ unsubscribe: (channelName: string) => unknown;
18
+ bind: (
19
+ event: string,
20
+ callback: (data: Record<string, unknown>) => void
21
+ ) => unknown;
22
+};
23
+
24
+type TChunkedTriggerData = {
25
+ id: string;
26
+ index: number;
27
+ chunk: string;
28
+ final: boolean;
29
+};
30
+
31
+export type TriggerData = {
32
+ appName: string;
33
+ clientId: number;
34
+ payload: Record<string, unknown>;
35
+ originalPayload: Record<string, unknown>;
36
+ metadata: {
37
+ id: string;
38
+ connectionId: string;
39
+ triggerName: string;
40
+ triggerData: string;
41
+ triggerConfig: Record<string, unknown>;
42
+ connection: {
43
+ id: string;
44
+ integrationId: string;
45
+ clientUniqueUserId: string;
46
+ status: string;
47
+ };
48
+ };
49
+};
50
+
51
+export class PusherUtils {
52
+ static pusherClient: PusherClient;
53
+
54
+ static getPusherClient(baseURL: string, apiKey: string): PusherClient {
55
+ if (!PusherUtils.pusherClient) {
56
+ // Dynamic import not available, using require for now
57
+ // TODO: Update to use dynamic import when available
58
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
59
+ const PusherClient = require("pusher-js");
60
+ PusherUtils.pusherClient = new PusherClient(PUSHER_KEY, {
61
+ cluster: PUSHER_CLUSTER,
62
+ channelAuthorization: {
63
+ endpoint: `${baseURL}/api/v1/client/auth/pusher_auth`,
64
+ headers: {
65
+ "x-api-key": apiKey,
66
+ },
67
+ transport: "ajax",
68
+ },
69
+ });
70
+ }
71
+ return PusherUtils.pusherClient;
72
+ }
73
+ /**
74
+ * Subscribes to a Pusher channel and binds an event to a callback function.
75
+ * @param {string} channelName - The name of the channel to subscribe to.
76
+ * @param {string} event - The event to bind to the channel.
77
+ * @param {(data: Record<string, unknown>) => void} fn - The callback function to execute when the event is triggered.
78
+ * @returns {PusherClient} The Pusher client instance.
79
+ */
80
+ static async subscribe(
81
+ channelName: string,
82
+ event: string,
83
+ fn: (data: Record<string, unknown>) => void
84
+ ): Promise<void> {
85
+ try {
86
+ await PusherUtils.pusherClient.subscribe(channelName).bind(event, fn);
87
+ } catch (error) {
88
+ logger.error(
89
+ `Error subscribing to ${channelName} with event ${event}: ${error}`
90
+ );
91
+ }
92
+ }
93
+
94
+ /**
95
+ * Unsubscribes from a Pusher channel.
96
+ * @param {string} channelName - The name of the channel to unsubscribe from.
97
+ * @returns {void}
98
+ */
99
+ static async unsubscribe(channelName: string): Promise<void> {
100
+ PusherUtils.pusherClient.unsubscribe(channelName);
101
+ }
102
+
103
+ /**
104
+ * Binds an event to a channel with support for chunked messages.
105
+ * @param {PusherClient} channel - The Pusher channel to bind the event to.
106
+ * @param {string} event - The event to bind to the channel.
107
+ * @param {(data: unknown) => void} callback - The callback function to execute when the event is triggered.
108
+ */
109
+ private static bindWithChunking(
110
+ channel: PusherClient,
111
+ event: string,
112
+ callback: (data: Record<string, unknown>) => void
113
+ ): void {
114
+ channel.bind(event, callback); // Allow normal unchunked events.
115
+
116
+ // Now the chunked variation. Allows arbitrarily long messages.
117
+ const events: {
118
+ [key: string]: { chunks: string[]; receivedFinal: boolean };
119
+ } = {};
120
+ channel.bind("chunked-" + event, (data) => {
121
+ const typedData = data as TChunkedTriggerData;
122
+ if (!events.hasOwnProperty(typedData.id)) {
123
+ events[typedData.id] = { chunks: [], receivedFinal: false };
124
+ }
125
+ const ev = events[typedData.id];
126
+ ev.chunks[typedData.index] = typedData.chunk;
127
+ if (typedData.final) ev.receivedFinal = true;
128
+ if (
129
+ ev.receivedFinal &&
130
+ ev.chunks.length === Object.keys(ev.chunks).length
131
+ ) {
132
+ callback(JSON.parse(ev.chunks.join("")));
133
+ delete events[typedData.id];
134
+ }
135
+ });
136
+ }
137
+
138
+ /**
139
+ * Subscribes to a trigger channel for a client and handles chunked data.
140
+ * @param {string} clientId - The unique identifier for the client subscribing to the events.
141
+ * @param {(data: TriggerData) => void} fn - The callback function to execute when trigger data is received.
142
+ */
143
+ static triggerSubscribe(
144
+ clientId: string,
145
+ fn: (data: TriggerData) => void
146
+ ): void {
147
+ const channel = PusherUtils.pusherClient.subscribe(
148
+ `private-${clientId}_triggers`
149
+ );
150
+ PusherUtils.bindWithChunking(
151
+ channel as PusherClient,
152
+ "trigger_to_client",
153
+ fn as (data: unknown) => void
154
+ );
155
+
156
+ logger.info(
157
+ `Subscribed to triggers. You should start receiving events now.`
158
+ );
159
+ }
160
+
161
+ static triggerUnsubscribe(clientId: string): void {
162
+ PusherUtils.pusherClient.unsubscribe(`${clientId}_triggers`);
163
+ }
164
+}
pnpm-lock.yaml
+5
-8
@@ -34,11 +34,8 @@ importers:
34
packages/core:
35
dependencies:
36
'@composio/client':
37
- specifier: 0.1.0-alpha.1
38
- version: 0.1.0-alpha.1
39
- '@composio/openai-toolset':
40
- specifier: workspace:^
41
- version: link:../toolsets/openai
37
+ specifier: 0.1.0-alpha.7
38
+ version: 0.1.0-alpha.7
39
zod:
40
specifier: ^3.24.2
41
version: 3.24.2
@@ -154,8 +151,8 @@ packages:
151
'@cloudflare/workers-types@4.20250416.0':
152
resolution: {integrity: sha512-i37TX0Clp+MrPdXMBdvKZM7JghCrWD9GtG7E+8ANOAPmtZjUkZfEy9qq46IG3XlNpagPaWDkY3SgJ3s01gPxCw==}
153
157
- '@composio/client@0.1.0-alpha.1':
158
- resolution: {integrity: sha512-cWN3Kffl1zkJ9LVHXtIAZplyUP1fktNIXgPhKL9RMRrUlQyuwpA8k2so4nlxg4f1C77NZSM+9/gbNOLNRWx21g==}
154
+ '@composio/client@0.1.0-alpha.7':
155
+ resolution: {integrity: sha512-2KYo7mloXf6vplX+6cMjnuaS/Hia74HwPZd7/3RCehVptqTzaqgQFBEAGfnQ3zMBtTkLt+S7JQsZc9RE0SIMoA==}
156
157
'@emnapi/core@1.4.0':
158
resolution: {integrity: sha512-H+N/FqT07NmLmt6OFFtDfwe8PNygprzBikrEMyQfgqSmT0vzE515Pz7R8izwB9q/zsH/MA64AKoul3sA6/CzVg==}
@@ -1252,7 +1249,7 @@ snapshots:
1249
1250
'@cloudflare/workers-types@4.20250416.0': {}
1251
1255
- '@composio/client@0.1.0-alpha.1': {}
1252
+ '@composio/client@0.1.0-alpha.7': {}
1253
1254
'@emnapi/core@1.4.0':
1255
dependencies: