@composio/core 0.23.0 → 0.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/dist/{CustomTool-CnJxXr07.mjs → CustomTool-BYHB7sPs.mjs} +1 -1
  2. package/dist/{CustomTool-CnHdegDK.d.mts → CustomTool-DZY1yLHN.d.mts} +1 -1
  3. package/dist/{cancellation-BQibgpRG.mjs → cancellation-D-tMPk48.mjs} +1 -1
  4. package/dist/{composio-Dq708dZS.d.mts → composio-B8AENilE.d.mts} +74 -62
  5. package/dist/{customTool.types-B8lVpHOP.d.mts → customTool.types-Bi6-keZC.d.mts} +612 -141
  6. package/dist/docs/reference/sdk-reference/typescript/auth-configs.mdx +10 -10
  7. package/dist/docs/reference/sdk-reference/typescript/composio.mdx +2 -2
  8. package/dist/docs/reference/sdk-reference/typescript/connected-accounts.mdx +22 -22
  9. package/dist/docs/reference/sdk-reference/typescript/custom-toolkits.mdx +8 -8
  10. package/dist/docs/reference/sdk-reference/typescript/experimental.mdx +2 -2
  11. package/dist/docs/reference/sdk-reference/typescript/index.mdx +1 -1
  12. package/dist/docs/reference/sdk-reference/typescript/keyring.mdx +2 -2
  13. package/dist/docs/reference/sdk-reference/typescript/logs.mdx +5 -5
  14. package/dist/docs/reference/sdk-reference/typescript/mcp.mdx +15 -15
  15. package/dist/docs/reference/sdk-reference/typescript/meta.json +1 -1
  16. package/dist/docs/reference/sdk-reference/typescript/session-configs.mdx +5 -5
  17. package/dist/docs/reference/sdk-reference/typescript/session-files.mdx +10 -10
  18. package/dist/docs/reference/sdk-reference/typescript/session.mdx +56 -21
  19. package/dist/docs/reference/sdk-reference/typescript/sessions.mdx +6 -6
  20. package/dist/docs/reference/sdk-reference/typescript/toolkits.mdx +22 -22
  21. package/dist/docs/reference/sdk-reference/typescript/tools.mdx +18 -18
  22. package/dist/docs/reference/sdk-reference/typescript/triggers.mdx +25 -25
  23. package/dist/docs/reference/sdk-reference/typescript/usage.mdx +6 -6
  24. package/dist/docs/reference/sdk-reference/typescript/webhook-endpoints.mdx +14 -14
  25. package/dist/docs/reference/sdk-reference/typescript/webhook-subscriptions.mdx +13 -13
  26. package/dist/{errors-BN15NcCW.mjs → errors-Cly0vXFh.mjs} +5 -5
  27. package/dist/experimental/index.d.mts +2 -2
  28. package/dist/experimental/index.mjs +1 -1
  29. package/dist/index.d.mts +31 -7
  30. package/dist/index.mjs +382 -147
  31. package/dist/{types-eTw8Yw7Y.d.mts → types-BGDMkEUl.d.mts} +2 -2
  32. package/dist/utils/config-defaults/ConfigDefaults.node.d.mts +1 -1
  33. package/dist/utils/config-defaults/ConfigDefaults.workerd.d.mts +1 -1
  34. package/dist/utils/modifiers/FileToolModifier.node.d.mts +1 -1
  35. package/dist/utils/modifiers/FileToolModifier.node.mjs +2 -2
  36. package/dist/utils/modifiers/FileToolModifier.workerd.d.mts +1 -1
  37. package/package.json +8 -8
  38. package/src/composio.ts +19 -16
  39. package/src/errors/ToolRouterErrors.ts +5 -5
  40. package/src/lib/toolRouterParams.ts +44 -16
  41. package/src/models/MCP.ts +20 -1
  42. package/src/models/ToolRouter.ts +9 -0
  43. package/src/models/ToolRouterSession.ts +68 -0
  44. package/src/models/Triggers.ts +8 -6
  45. package/src/services/pusher/Pusher.ts +159 -88
  46. package/src/types/pusher.types.ts +2 -0
  47. package/src/types/toolRouter.types.ts +190 -19
  48. package/src/utils/session.ts +25 -47
  49. package/src/utils/transformers/toolRouterResponseTransform.ts +8 -2
  50. package/src/utils/userCallback.ts +41 -0
@@ -1,5 +1,5 @@
1
1
  import ComposioClient from '@composio/client';
2
- import { PusherClient, TChunkedTriggerData } from '../../types/pusher.types';
2
+ import { PusherChannel, PusherClient, TChunkedTriggerData } from '../../types/pusher.types';
3
3
  import { InternalService } from '../internal/InternalService';
4
4
  import { SDKRealtimeCredentialsResponse } from '../internal/InternalService.types';
5
5
  import {
@@ -8,6 +8,7 @@ import {
8
8
  ComposioFailedToSubscribeToPusherChannelError,
9
9
  } from '../../errors/TriggerErrors';
10
10
  import logger from '../../utils/logger';
11
+ import { invokeUserCallback } from '../../utils/userCallback';
11
12
  import { telemetry } from '../../telemetry/Telemetry';
12
13
  import { resolveCredentialHeaders } from '../../utils/sdk';
13
14
  import type { ComposioRequestHeaders } from '../../types/composio.types';
@@ -17,17 +18,41 @@ export type PusherServiceOptions = {
17
18
  defaultHeaders?: ComposioRequestHeaders;
18
19
  };
19
20
 
21
+ /** A pusher-js client and the triggers channel it subscribed to. */
22
+ type TriggerConnection = {
23
+ client: PusherClient;
24
+ channel: PusherChannel;
25
+ channelName: string;
26
+ };
27
+
28
+ /**
29
+ * Setup of the connection for one subscription period, which runs from the first `subscribe()`
30
+ * to the next `unsubscribe()`. Concurrent `subscribe()` calls share `ready`; `unsubscribe()`
31
+ * aborts `controller` so that setup still in flight neither connects nor installs handlers.
32
+ */
33
+ type ConnectionAttempt = {
34
+ controller: AbortController;
35
+ ready: Promise<TriggerConnection>;
36
+ };
37
+
38
+ /**
39
+ * Owns the realtime connection that delivers trigger events.
40
+ *
41
+ * Each subscription period gets its own pusher-js client, which `unsubscribe()` disconnects.
42
+ * Reusing one client across periods is unsafe: pusher-js keeps a channel, its bound handlers and
43
+ * its cancellation flag through `disconnect()` and resubscribes every kept channel on the next
44
+ * `connect()`, and a channel-auth reply requested on the old socket can arrive after a reconnect
45
+ * and be sent on the new one.
46
+ */
20
47
  export class PusherService {
21
- // these values are set via the Apollo API `/internal/sdk/realtime/credentials` endpoint
22
- private clientId!: string;
23
- private pusherKey!: string;
24
- private pusherCluster!: string;
25
- private pusherChannel!: string;
26
48
  // these details are set via the client SDK
27
49
  private pusherBaseURL!: string;
28
50
  private authHeaders!: Record<string, string>;
29
- private pusherClient!: PusherClient;
30
51
  private composioClient!: ComposioClient;
52
+ private attempt?: ConnectionAttempt;
53
+ // Set as soon as the current attempt creates its client, so that `unsubscribe()` can close it
54
+ // before the `subscribe()` calls waiting on `attempt.ready` resume.
55
+ private connection?: TriggerConnection;
31
56
 
32
57
  constructor(client: ComposioClient, options: PusherServiceOptions = {}) {
33
58
  this.composioClient = client;
@@ -43,54 +68,86 @@ export class PusherService {
43
68
  }
44
69
 
45
70
  /**
46
- * Creates a Pusher client
47
- *
48
- * This method is called when the Pusher client is first used.
49
- * It will fetch the SDK realtime credentials from the Apollo API and create a Pusher client.
71
+ * Returns the connection attempt of the current subscription period, starting one if needed.
72
+ * A failed attempt is forgotten, so the next `subscribe()` retries.
50
73
  */
51
- private async getPusherClient() {
52
- if (!this.pusherClient) {
53
- const internalService = new InternalService(this.composioClient);
54
- let sdkRealtimeCredentials: SDKRealtimeCredentialsResponse;
55
- try {
56
- sdkRealtimeCredentials = await internalService.getSDKRealtimeCredentials();
57
- } catch (error) {
58
- throw new ComposioFailedToGetSDKRealtimeCredentialsError(
59
- 'Failed to get SDK realtime credentials',
60
- {
61
- cause: error,
62
- }
63
- );
64
- }
74
+ private connect(): ConnectionAttempt {
75
+ if (this.attempt) return this.attempt;
65
76
 
66
- this.clientId = sdkRealtimeCredentials.projectId;
67
- this.pusherKey = sdkRealtimeCredentials.pusherKey;
68
- this.pusherCluster = sdkRealtimeCredentials.pusherCluster;
69
- this.pusherChannel = `private-${this.clientId}_triggers`;
77
+ const controller = new AbortController();
78
+ const ready = this.openConnection(controller.signal);
79
+ const attempt = { controller, ready };
80
+ this.attempt = attempt;
81
+ ready.catch(() => {
82
+ if (this.attempt === attempt) this.attempt = undefined;
83
+ });
84
+ return attempt;
85
+ }
70
86
 
71
- logger.debug(
72
- `[PusherService] Creating Pusher client for client ID: ${this.clientId} in cluster ${this.pusherCluster}`
87
+ /**
88
+ * Fetches the SDK realtime credentials from the Apollo API, creates a Pusher client and
89
+ * subscribes it to the triggers channel.
90
+ */
91
+ private async openConnection(signal: AbortSignal): Promise<TriggerConnection> {
92
+ const internalService = new InternalService(this.composioClient);
93
+ let sdkRealtimeCredentials: SDKRealtimeCredentialsResponse;
94
+ try {
95
+ sdkRealtimeCredentials = await internalService.getSDKRealtimeCredentials();
96
+ } catch (error) {
97
+ throw new ComposioFailedToGetSDKRealtimeCredentialsError(
98
+ 'Failed to get SDK realtime credentials',
99
+ {
100
+ cause: error,
101
+ }
73
102
  );
103
+ }
74
104
 
75
- // create the Pusher client
76
- try {
77
- const { default: Pusher } = await import('pusher-js');
78
- this.pusherClient = new Pusher(this.pusherKey, {
79
- cluster: this.pusherCluster,
80
- channelAuthorization: {
81
- endpoint: `${this.pusherBaseURL}/api/v3/internal/sdk/realtime/auth`,
82
- headers: { ...this.authHeaders },
83
- transport: 'ajax',
84
- },
85
- });
86
- } catch (error) {
87
- throw new ComposioFailedToCreatePusherClientError('Failed to create Pusher client', {
88
- cause: error,
89
- });
90
- }
105
+ const { projectId, pusherKey, pusherCluster } = sdkRealtimeCredentials;
106
+ const channelName = `private-${projectId}_triggers`;
107
+
108
+ let Pusher: (typeof import('pusher-js'))['default'];
109
+ try {
110
+ ({ default: Pusher } = await import('pusher-js'));
111
+ } catch (error) {
112
+ throw new ComposioFailedToCreatePusherClientError('Failed to create Pusher client', {
113
+ cause: error,
114
+ });
115
+ }
116
+
117
+ // unsubscribe() ran while the credentials or pusher-js were loading. Everything below is
118
+ // synchronous, so this is the last point at which it can cancel the attempt.
119
+ if (signal.aborted) {
120
+ throw new Error('Connection attempt cancelled by unsubscribe()');
91
121
  }
92
122
 
93
- return this.pusherClient;
123
+ logger.debug(
124
+ `[PusherService] Creating Pusher client for client ID: ${projectId} in cluster ${pusherCluster}`
125
+ );
126
+
127
+ let client: PusherClient;
128
+ try {
129
+ client = new Pusher(pusherKey, {
130
+ cluster: pusherCluster,
131
+ channelAuthorization: {
132
+ endpoint: `${this.pusherBaseURL}/api/v3/internal/sdk/realtime/auth`,
133
+ headers: { ...this.authHeaders },
134
+ transport: 'ajax',
135
+ },
136
+ });
137
+ } catch (error) {
138
+ throw new ComposioFailedToCreatePusherClientError('Failed to create Pusher client', {
139
+ cause: error,
140
+ });
141
+ }
142
+
143
+ logger.debug(`[PusherService] Subscribing to channel: ${channelName}`);
144
+ try {
145
+ this.connection = { client, channel: client.subscribe(channelName), channelName };
146
+ } catch (error) {
147
+ client.disconnect();
148
+ throw error;
149
+ }
150
+ return this.connection;
94
151
  }
95
152
 
96
153
  /**
@@ -102,7 +159,7 @@ export class PusherService {
102
159
  * @param callback - The function to call when the event is received
103
160
  */
104
161
  private bindWithChunking(
105
- channel: PusherClient,
162
+ channel: PusherChannel,
106
163
  event: string,
107
164
  callback: (data: Record<string, unknown>) => void
108
165
  ): void {
@@ -167,11 +224,10 @@ export class PusherService {
167
224
  /**
168
225
  * Subscribes to pusher to receive events from the server
169
226
  *
170
- * This method is used to subscribe to a Pusher channel.
171
- * It will create a Pusher client if it doesn't exist.
227
+ * The first call of a subscription period creates the Pusher client; concurrent calls share
228
+ * it. A call still waiting for the client when `unsubscribe()` runs resolves without
229
+ * subscribing.
172
230
  *
173
- * @param channelName - The name of the Pusher channel to subscribe to
174
- * @param event - The event to subscribe to
175
231
  * @param fn - The function to call when the event is received
176
232
  * @param onSubscriptionError - Optional callback invoked with the raw payload when the
177
233
  * Pusher subscription fails (for example on auth or permission rejection). Errors thrown
@@ -181,30 +237,38 @@ export class PusherService {
181
237
  fn: (data: Record<string, unknown>) => void,
182
238
  onSubscriptionError?: (data: Record<string, unknown>) => void
183
239
  ) {
240
+ const attempt = this.connect();
241
+ let connection: TriggerConnection;
184
242
  try {
185
- logger.debug(`[PusherService] Subscribing to channel: ${this.pusherChannel}`);
186
- const pusherClient = await this.getPusherClient();
187
- const channel = await pusherClient.subscribe(this.pusherChannel);
243
+ connection = await attempt.ready;
244
+ } catch (error) {
245
+ if (attempt.controller.signal.aborted) {
246
+ logger.debug('[PusherService] Subscribe cancelled by unsubscribe() before it connected');
247
+ return;
248
+ }
249
+ throw new ComposioFailedToSubscribeToPusherChannelError(
250
+ 'Failed to subscribe to Pusher channel',
251
+ {
252
+ cause: error,
253
+ }
254
+ );
255
+ }
256
+ // unsubscribe() ran after the client was created but before this call resumed.
257
+ if (attempt.controller.signal.aborted) {
258
+ logger.debug('[PusherService] Subscribe cancelled by unsubscribe() before it connected');
259
+ return;
260
+ }
188
261
 
189
- // add subscription error handling
190
- const logCallbackFailure = (callbackError: unknown) => {
191
- const errorMessage =
192
- callbackError instanceof Error ? callbackError.message : String(callbackError);
193
- logger.error('❌ Error in subscription error callback:', errorMessage);
194
- };
262
+ try {
263
+ const { channel } = connection;
195
264
  channel.bind('pusher:subscription_error', (data: Record<string, unknown>) => {
196
265
  logger.error('Trigger subscription error:', data);
197
266
 
198
267
  // surface the failure to the caller without letting a faulty
199
268
  // handler crash the host (same containment as the trigger callback).
200
- // A handler may be async: contain rejected promises too, or the
201
- // rejection escapes as an unhandled rejection after subscribe()
202
- // already resolved.
203
- try {
204
- Promise.resolve(onSubscriptionError?.(data)).catch(logCallbackFailure);
205
- } catch (callbackError: unknown) {
206
- logCallbackFailure(callbackError);
207
- }
269
+ invokeUserCallback('❌ Error in subscription error callback:', () =>
270
+ onSubscriptionError?.(data)
271
+ );
208
272
  });
209
273
 
210
274
  // log success only when Pusher itself confirms the subscription
@@ -212,18 +276,12 @@ export class PusherService {
212
276
  logger.info(`✅ Subscribed to triggers. You should start receiving events now.`);
213
277
  });
214
278
 
215
- // wrap the callback to handle errors
279
+ // don't let a failing callback break the subscription
216
280
  const safeCallback = (data: Record<string, unknown>) => {
217
- try {
218
- fn(data);
219
- } catch (error: unknown) {
220
- const errorMessage = error instanceof Error ? error.message : String(error);
221
- logger.error('❌ Error in trigger callback:', errorMessage);
222
- // don't throw here to prevent breaking the subscription
223
- }
281
+ invokeUserCallback('❌ Error in trigger callback:', () => fn(data));
224
282
  };
225
283
 
226
- this.bindWithChunking(channel as PusherClient, 'trigger_to_client', safeCallback);
284
+ this.bindWithChunking(channel, 'trigger_to_client', safeCallback);
227
285
  } catch (error) {
228
286
  throw new ComposioFailedToSubscribeToPusherChannelError(
229
287
  'Failed to subscribe to Pusher channel',
@@ -235,19 +293,29 @@ export class PusherService {
235
293
  }
236
294
 
237
295
  /**
238
- * Unsubscribes from a Pusher channel
239
- *
240
- * This method is used to unsubscribe from a Pusher channel.
241
- * It will create a Pusher client if it doesn't exist.
296
+ * Unsubscribes from the triggers channel and closes the connection
242
297
  *
243
- * @param channelName - The name of the Pusher channel to unsubscribe from
298
+ * This ends the subscription period: setup still in flight is cancelled, the handlers bound by
299
+ * every `subscribe()` call are removed, and the Pusher client is disconnected. Without a prior
300
+ * `subscribe()` this does nothing; it never creates a client or fetches credentials.
244
301
  */
245
302
  async unsubscribe() {
303
+ const { attempt, connection } = this;
304
+ this.attempt = undefined;
305
+ this.connection = undefined;
306
+ attempt?.controller.abort();
307
+
308
+ if (!connection) {
309
+ logger.debug('[PusherService] No open connection to unsubscribe from');
310
+ return;
311
+ }
312
+
313
+ logger.debug(`[PusherService] Unsubscribing from channel: ${connection.channelName}`);
246
314
  try {
247
- logger.debug(`[PusherService] Unsubscribing from channel: ${this.pusherChannel}`);
248
- const pusherClient = await this.getPusherClient();
249
- await pusherClient.unsubscribe(this.pusherChannel);
250
- logger.info(`✅ Unsubscribed from triggers.`);
315
+ // pusher-js keeps a reference to every client it creates, so release the handlers this
316
+ // service bound and the user callbacks they hold.
317
+ connection.channel.unbind_all();
318
+ connection.client.unsubscribe(connection.channelName);
251
319
  } catch (error) {
252
320
  throw new ComposioFailedToSubscribeToPusherChannelError(
253
321
  'Failed to unsubscribe from Pusher channel',
@@ -255,6 +323,9 @@ export class PusherService {
255
323
  cause: error,
256
324
  }
257
325
  );
326
+ } finally {
327
+ connection.client.disconnect();
258
328
  }
329
+ logger.info(`✅ Unsubscribed from triggers.`);
259
330
  }
260
331
  }
@@ -2,12 +2,14 @@ export interface PusherClient {
2
2
  subscribe: (channelName: string) => PusherChannel;
3
3
  unsubscribe: (channelName: string) => void;
4
4
  bind: (event: string, callback: (data: Record<string, unknown>) => void) => void;
5
+ disconnect: () => void;
5
6
  }
6
7
 
7
8
  export interface PusherChannel {
8
9
  subscribe: (channelName: string) => unknown;
9
10
  unsubscribe: (channelName: string) => void;
10
11
  bind: (event: string, callback: (data: Record<string, unknown>) => void) => void;
12
+ unbind_all: () => void;
11
13
  }
12
14
 
13
15
  export type TChunkedTriggerData = {