@composio/core 0.24.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 (48) hide show
  1. package/dist/{CustomTool-CnJxXr07.mjs → CustomTool-BYHB7sPs.mjs} +1 -1
  2. package/dist/{CustomTool-CNJysHMK.d.mts → CustomTool-DZY1yLHN.d.mts} +1 -1
  3. package/dist/{cancellation-BQibgpRG.mjs → cancellation-D-tMPk48.mjs} +1 -1
  4. package/dist/{composio-BFTtZj82.d.mts → composio-B8AENilE.d.mts} +22 -10
  5. package/dist/{customTool.types-D57QrTns.d.mts → customTool.types-Bi6-keZC.d.mts} +326 -3
  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 +11 -8
  30. package/dist/index.mjs +301 -143
  31. package/dist/{types-q8TwAngA.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 +4 -4
  38. package/src/composio.ts +19 -16
  39. package/src/errors/ToolRouterErrors.ts +5 -5
  40. package/src/lib/toolRouterParams.ts +28 -16
  41. package/src/models/ToolRouter.ts +5 -0
  42. package/src/models/ToolRouterSession.ts +17 -0
  43. package/src/models/Triggers.ts +8 -6
  44. package/src/services/pusher/Pusher.ts +159 -88
  45. package/src/types/pusher.types.ts +2 -0
  46. package/src/types/toolRouter.types.ts +103 -17
  47. package/src/utils/session.ts +25 -47
  48. 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 = {
@@ -9,6 +9,7 @@ import type {
9
9
  SessionConfigHistoryResponse,
10
10
  SessionCreateResponse,
11
11
  SessionExecuteMetaParams,
12
+ SessionExecuteParams,
12
13
  } from '@composio/client/resources/tool-router/session/session.mjs';
13
14
  import type {
14
15
  CustomTool,
@@ -109,6 +110,39 @@ export const ToolRouterToolkitsEnabledConfigSchema = z
109
110
  })
110
111
  .strict();
111
112
 
113
+ /**
114
+ * Toolkits whose tools need the user's approval before they run. A call that
115
+ * needs approval doesn't run: `session.execute()` throws
116
+ * `ComposioToolInputRequiredError` with the question to show the user.
117
+ * @experimental
118
+ */
119
+ const ToolRouterToolkitsRequireApprovalSchema = ToolRouterToolkitsParamSchema.describe(
120
+ 'Experimental. Toolkits whose tools need the user approval before they run'
121
+ );
122
+
123
+ /** Session toolkit policy: a list to enable, an enable/disable object, or only an approval list. */
124
+ const ToolRouterSessionToolkitsSchema = z.union([
125
+ ToolRouterToolkitsParamSchema,
126
+ ToolRouterToolkitsDisabledConfigSchema.extend({
127
+ requireApproval: ToolRouterToolkitsRequireApprovalSchema.optional(),
128
+ }).strict(),
129
+ ToolRouterToolkitsEnabledConfigSchema.extend({
130
+ requireApproval: ToolRouterToolkitsRequireApprovalSchema.optional(),
131
+ }).strict(),
132
+ z.object({ requireApproval: ToolRouterToolkitsRequireApprovalSchema }).strict(),
133
+ ]);
134
+
135
+ /**
136
+ * What happens to a call that needs the user's approval when the session's MCP
137
+ * client can't ask the user.
138
+ * @experimental
139
+ */
140
+ const ToolRouterNoElicitationSupportFallbackSchema = z
141
+ .enum(['deny', 'allow'])
142
+ .describe(
143
+ 'Experimental. What happens to a call that needs approval when the MCP client cannot ask the user'
144
+ );
145
+
112
146
  /** Experimental Instant usage policy for a Session. */
113
147
  export const ToolRouterInstantSchema = z.union([
114
148
  z.literal(false),
@@ -175,6 +209,13 @@ export const ToolRouterTagsEnableDisableSchema = z
175
209
  disable: ToolRouterTagsParamSchema.optional().describe(
176
210
  'The tags to disable in the tool router session'
177
211
  ),
212
+ /**
213
+ * Tools with any of these tags need the user's approval before they run.
214
+ * @experimental
215
+ */
216
+ requireApproval: ToolRouterTagsParamSchema.optional().describe(
217
+ 'Experimental. Tools with any of these tags need the user approval before they run'
218
+ ),
178
219
  })
179
220
  .strict();
180
221
  export const ToolRouterConfigTagsSchema = z
@@ -209,6 +250,14 @@ export const ToolRouterToolsParamSchema = z
209
250
  .describe('The tools to use in the tool router session');
210
251
  export type ToolRouterToolsParam = z.infer<typeof ToolRouterToolsParamSchema>;
211
252
 
253
+ /**
254
+ * Tools of the toolkit that need the user's approval before they run.
255
+ * @experimental
256
+ */
257
+ const ToolRouterToolsRequireApprovalSchema = ToolRouterToolsParamSchema.describe(
258
+ 'Experimental. Tools of this toolkit that need the user approval before they run'
259
+ );
260
+
212
261
  export const ToolRouterConfigToolsSchema = z
213
262
  .union([
214
263
  ToolRouterToolsParamSchema,
@@ -217,6 +266,7 @@ export const ToolRouterConfigToolsSchema = z
217
266
  enable: ToolRouterToolsParamSchema.describe(
218
267
  'The tools to enable in the tool router session'
219
268
  ),
269
+ requireApproval: ToolRouterToolsRequireApprovalSchema.optional(),
220
270
  })
221
271
  .strict(),
222
272
  z
@@ -224,6 +274,7 @@ export const ToolRouterConfigToolsSchema = z
224
274
  disable: ToolRouterToolsParamSchema.describe(
225
275
  'The tools to disable in the tool router session'
226
276
  ),
277
+ requireApproval: ToolRouterToolsRequireApprovalSchema.optional(),
227
278
  })
228
279
  .strict(),
229
280
  z
@@ -231,13 +282,15 @@ export const ToolRouterConfigToolsSchema = z
231
282
  tags: ToolRouterConfigTagsSchema.describe(
232
283
  'The tags to filter the tools by, this will override the global tags'
233
284
  ),
285
+ requireApproval: ToolRouterToolsRequireApprovalSchema.optional(),
234
286
  })
235
287
  .strict(),
288
+ z.object({ requireApproval: ToolRouterToolsRequireApprovalSchema }).strict(),
236
289
  ])
237
290
  .superRefine((val, ctx) => {
238
- // If it's an object (not an array), ensure only one property is present
291
+ // If it's an object (not an array), allow at most one of enable, disable and tags
239
292
  if (typeof val === 'object' && !Array.isArray(val)) {
240
- const keys = Object.keys(val);
293
+ const keys = Object.keys(val).filter(key => key !== 'requireApproval');
241
294
  if (keys.length > 1) {
242
295
  ctx.addIssue({
243
296
  code: z.ZodIssueCode.custom,
@@ -299,14 +352,9 @@ const ToolRouterCreateSessionConfigBaseSchema = z
299
352
 
300
353
  tags: ToolRouterConfigTagsSchema.optional().describe('Global tags to filter the tools by'),
301
354
 
302
- toolkits: z
303
- .union([
304
- ToolRouterToolkitsParamSchema,
305
- ToolRouterToolkitsDisabledConfigSchema,
306
- ToolRouterToolkitsEnabledConfigSchema,
307
- ])
308
- .optional()
309
- .describe('The toolkits to use in the tool router session'),
355
+ toolkits: ToolRouterSessionToolkitsSchema.optional().describe(
356
+ 'The toolkits to use in the tool router session'
357
+ ),
310
358
 
311
359
  instant: ToolRouterInstantSchema.optional().describe(
312
360
  'Experimental Instant usage policy. Omission permits eligible tools when the project allows Instant usage; false disables it for this Session.'
@@ -411,6 +459,13 @@ const ToolRouterCreateSessionConfigBaseSchema = z
411
459
  .describe(
412
460
  'ID of a saved Session config (`sc_…`) to apply when the session is created. Cannot be combined with toolkits, tools, tags, customTools or customToolkits.'
413
461
  ),
462
+ /**
463
+ * What happens to a call that needs the user's approval when the
464
+ * session's MCP client can't ask the user: `deny` (the default) or
465
+ * `allow`.
466
+ * @experimental
467
+ */
468
+ noElicitationSupportFallback: ToolRouterNoElicitationSupportFallbackSchema.optional(),
414
469
  })
415
470
  .optional()
416
471
  .describe('Experimental features configuration - not stable, may be modified or removed'),
@@ -773,17 +828,48 @@ export interface ToolRouterSessionExecuteOptions {
773
828
  * COMPOSIO_MULTI_EXECUTE_TOOL.tools[].account.
774
829
  */
775
830
  account?: string;
831
+ /**
832
+ * The user's answers to the questions of a `ComposioToolInputRequiredError`,
833
+ * keyed by the IDs in its `inputRequests`. Send them by repeating the same
834
+ * call (same tool and arguments). An approved call runs; a denied or
835
+ * declined one returns `resultType: 'failed'`.
836
+ * @experimental
837
+ */
838
+ inputResponses?: Record<string, ToolRouterInputResponse>;
839
+ /**
840
+ * The `requestState` of the `ComposioToolInputRequiredError`, sent back
841
+ * unchanged with `inputResponses`.
842
+ * @experimental
843
+ */
844
+ requestState?: string;
776
845
  }
777
846
 
847
+ /**
848
+ * The user's answer to one question, in the shape of an MCP elicitation
849
+ * result: `accept` with the form's fields in `content`, `decline` when they
850
+ * said no, or `cancel` when they dismissed it. For an approval, `content` is
851
+ * `{ decision: 'approve' }`, `{ decision: 'always_approve' }` or
852
+ * `{ decision: 'deny' }`.
853
+ * @experimental
854
+ */
855
+ export type ToolRouterInputResponse = NonNullable<SessionExecuteParams['input_responses']>[string];
856
+
778
857
  /**
779
858
  * Slug of a Composio meta tool (`COMPOSIO_*`) that `session.executeMeta()` can
780
859
  * run, for example `COMPOSIO_SEARCH_TOOLS`.
781
860
  */
782
861
  export type ToolRouterSessionMetaToolSlug = SessionExecuteMetaParams['slug'];
783
862
 
863
+ /** Options for `session.executeMeta()`: the user's answers to an earlier `input_required` call. */
864
+ export type ToolRouterSessionExecuteMetaOptions = Pick<
865
+ ToolRouterSessionExecuteOptions,
866
+ 'inputResponses' | 'requestState'
867
+ >;
868
+
784
869
  export type ToolRouterSessionExecuteMetaFn = (
785
870
  slug: ToolRouterSessionMetaToolSlug,
786
871
  arguments_?: Record<string, unknown>,
872
+ options?: ToolRouterSessionExecuteMetaOptions,
787
873
  requestOptions?: ComposioRequestOptions
788
874
  ) => Promise<ToolRouterSessionExecuteResponse>;
789
875
 
@@ -925,6 +1011,12 @@ export const ToolRouterUpdateExperimentalSchema = z
925
1011
  .describe(
926
1012
  'Exposes the COMPOSIO_SUBMIT_FEEDBACK helper tool. `null` removes the stored block'
927
1013
  ),
1014
+ /**
1015
+ * What happens to a call that needs the user's approval when the session's
1016
+ * MCP client can't ask the user: `deny` or `allow`.
1017
+ * @experimental
1018
+ */
1019
+ noElicitationSupportFallback: ToolRouterNoElicitationSupportFallbackSchema.optional(),
928
1020
  sessionConfigId: z
929
1021
  .string()
930
1022
  .min(1)
@@ -947,13 +1039,7 @@ export const ToolRouterUpdateSessionConfigSchema = z
947
1039
  instant: ToolRouterInstantSchema.optional().describe(
948
1040
  'Experimental Instant usage policy. False disables it. Any supplied object, even one that only sets returnInstantCharge, re-enables it. Omitted subfields keep their stored values.'
949
1041
  ),
950
- toolkits: z
951
- .union([
952
- ToolRouterToolkitsParamSchema,
953
- ToolRouterToolkitsDisabledConfigSchema,
954
- ToolRouterToolkitsEnabledConfigSchema,
955
- ])
956
- .nullable()
1042
+ toolkits: ToolRouterSessionToolkitsSchema.nullable()
957
1043
  .optional()
958
1044
  .describe(
959
1045
  'Toolkit policy. An empty allowlist (`[]` or `{ enable: [] }`) is sent as-is and denies every app toolkit; `null` removes the stored policy and restores the unrestricted default'
@@ -1,9 +1,7 @@
1
1
  import type { BaseComposioProvider } from '../provider/BaseProvider';
2
2
  // Resolve against the installed package, including slim's copy of the core build.
3
- import identity from '#client_identity' with { type: 'json' };
4
- import { z } from 'zod';
5
- import { VERSION as clientLibraryVersion } from '@composio/client';
6
- import type { ComposioRequestHeaders } from '../types/composio.types';
3
+ import manifest from '#client_identity' with { type: 'json' };
4
+ import type { ClientIdentity } from '@composio/client';
7
5
 
8
6
  /**
9
7
  * Extended globalThis interface for runtime detection
@@ -93,51 +91,31 @@ function detectRuntime(): string {
93
91
 
94
92
  // Detect once at module initialization
95
93
  const RUNTIME_ENV = detectRuntime();
96
- const RuntimeVersionsSchema = z.object({
97
- Bun: z.object({ version: z.string() }).optional(),
98
- Deno: z.object({ version: z.object({ deno: z.string() }) }).optional(),
99
- });
100
- const runtimeVersions = RuntimeVersionsSchema.safeParse(globalThis);
101
- const detectRuntimeVersion = (): string | undefined => {
102
- switch (RUNTIME_ENV) {
103
- case 'BUN':
104
- return runtimeVersions.success ? runtimeVersions.data.Bun?.version : undefined;
105
- case 'DENO':
106
- return runtimeVersions.success ? runtimeVersions.data.Deno?.version.deno : undefined;
107
- case 'NODEJS':
108
- return process.versions.node;
109
- default:
110
- return undefined;
111
- }
112
- };
113
- const RUNTIME_VERSION = detectRuntimeVersion();
114
94
 
115
- export function getSessionHeaders(
116
- provider: BaseComposioProvider<unknown, unknown, unknown> | undefined
117
- ) {
118
- return {
119
- 'x-framework': provider?.name || 'unknown',
120
- 'x-source': 'TYPESCRIPT_SDK',
121
- 'x-runtime': RUNTIME_ENV,
122
- 'x-client-runtime':
123
- RUNTIME_ENV === 'CLOUDFLARE_WORKERS' ? 'cloudflare' : RUNTIME_ENV.toLowerCase(),
124
- 'x-sdk-version': identity.version,
125
- 'x-client-provenance': identity.name,
126
- 'x-client-version': identity.version,
127
- 'x-client-language': 'typescript',
128
- 'x-client-library': '@composio/client',
129
- 'x-client-library-version': clientLibraryVersion,
130
- ...(RUNTIME_VERSION ? { 'x-runtime-version': RUNTIME_VERSION } : {}),
131
- };
132
- }
95
+ /**
96
+ * An identity value is sent as a header, so the client accepts only non-empty
97
+ * printable ASCII with no leading or trailing whitespace.
98
+ */
99
+ const HEADER_SAFE = /^[\x21-\x7e](?:[\x20-\x7e]*[\x21-\x7e])?$/;
133
100
 
134
- export const getDefaultHeaders = (
135
- headers: ComposioRequestHeaders | undefined,
101
+ /**
102
+ * The identity the API client reports for this SDK: its product headers
103
+ * (`x-client-provenance`, `x-client-version`, `x-sdk-version`) and the legacy
104
+ * `x-source`, `x-framework` and `x-runtime` labels. The client adds the
105
+ * library headers and detects the runtime and its version itself.
106
+ *
107
+ * A custom provider whose name cannot be sent as a header value is reported
108
+ * as `unknown` rather than making the SDK fail to construct.
109
+ */
110
+ export function getClientIdentity(
136
111
  provider: BaseComposioProvider<unknown, unknown, unknown> | undefined
137
- ) => {
138
- const sessionHeaders = getSessionHeaders(provider);
112
+ ): ClientIdentity {
113
+ const framework = provider?.name;
139
114
  return {
140
- ...(headers || {}),
141
- ...sessionHeaders,
115
+ product: manifest.name,
116
+ version: manifest.version,
117
+ source: 'TYPESCRIPT_SDK',
118
+ framework: framework && HEADER_SAFE.test(framework) ? framework : 'unknown',
119
+ runtime: RUNTIME_ENV,
142
120
  };
143
- };
121
+ }