@composio/core 0.1.0-rc.1

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.
package/dist/index.js ADDED
@@ -0,0 +1,1419 @@
1
+ var __getOwnPropNames = Object.getOwnPropertyNames;
2
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
3
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
4
+ }) : x)(function(x) {
5
+ if (typeof require !== "undefined") return require.apply(this, arguments);
6
+ throw Error('Dynamic require of "' + x + '" is not supported');
7
+ });
8
+ var __commonJS = (cb, mod) => function __require2() {
9
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
10
+ };
11
+
12
+ // package.json
13
+ var require_package = __commonJS({
14
+ "package.json"(exports, module) {
15
+ module.exports = {
16
+ name: "@composio/core",
17
+ version: "0.1.0-rc.1",
18
+ description: "",
19
+ main: "src/index.ts",
20
+ type: "module",
21
+ publishConfig: {
22
+ access: "public",
23
+ main: "dist/index.js",
24
+ types: "dist/index.d.ts"
25
+ },
26
+ exports: {
27
+ ".": {
28
+ import: "./dist/index.js",
29
+ types: "./dist/index.d.ts",
30
+ require: "./dist/index.cjs"
31
+ }
32
+ },
33
+ files: ["README.md", "dist"],
34
+ scripts: {
35
+ build: "tsup",
36
+ test: 'echo "Error: no test specified" && exit 1'
37
+ },
38
+ keywords: [],
39
+ author: "",
40
+ license: "ISC",
41
+ packageManager: "pnpm@10.8.0",
42
+ devDependencies: {
43
+ tsup: "^8.4.0",
44
+ tsx: "^4.19.3",
45
+ typescript: "^5.8.3"
46
+ },
47
+ dependencies: {
48
+ "@composio/client": "0.1.0-alpha.7",
49
+ openai: "^4.94.0",
50
+ "pusher-js": "^8.4.0",
51
+ zod: "^3.24.2"
52
+ }
53
+ };
54
+ }
55
+ });
56
+
57
+ // src/composio.ts
58
+ import ComposioClient from "@composio/client";
59
+
60
+ // src/models/Tools.ts
61
+ var Tools = class {
62
+ FILE_NAME = "core/models/Tools.ts";
63
+ client;
64
+ constructor(client) {
65
+ this.client = client;
66
+ }
67
+ /**
68
+ * Lists all tools available in the Composio SDK.
69
+ * This method fetches the tools from the Composio API and wraps them using the toolset.
70
+ * @returns {Tools[]>} List of tools
71
+ */
72
+ async list(query = {}) {
73
+ const tools = await this.client.tools.list(query);
74
+ if (!tools) {
75
+ return {
76
+ items: [],
77
+ next_cursor: null,
78
+ total_pages: 0
79
+ };
80
+ }
81
+ return tools;
82
+ }
83
+ /**
84
+ * Retrieves a tool by its Slug.
85
+ * @param slug The ID of the tool to be retrieved
86
+ * @returns {Promise<Tool>} The tool
87
+ */
88
+ async get(slug) {
89
+ return this.client.tools.retrieve(slug);
90
+ }
91
+ /**
92
+ * Exectes a given tool with the provided parameters.
93
+ *
94
+ * This method calls the Composio API to execute the tool and returns the response.
95
+ *
96
+ * @param {string} slug - The ID of the tool to be executed
97
+ * @param {ToolExecuteParams} body - The parameters to be passed to the tool
98
+ * @returns {Promise<ToolExecuteResponse>} - The response from the tool execution
99
+ */
100
+ async execute(slug, body) {
101
+ return this.client.tools.execute(slug, body);
102
+ }
103
+ /**
104
+ * Fetches the list of all available tools in the Composio SDK.
105
+ *
106
+ * This method is mostly used by the CLI to get the list of tools.
107
+ * No filtering is done on the tools, the list is cached in the backend, no further optimization is required.
108
+ * @returns {string} - The list of all available tools as a string
109
+ */
110
+ async getToolsEnum() {
111
+ return this.client.tools.retrieveEnum();
112
+ }
113
+ /**
114
+ * Fetches the input parameters for a given tool.
115
+ *
116
+ * This method is used to get the input parameters for a tool before executing it.
117
+ *
118
+ * @param {string} slug - The ID of the tool to find input for
119
+ * @param {ToolGetInputParams} body - The parameters to be passed to the tool
120
+ * @returns
121
+ */
122
+ async getInput(slug, body) {
123
+ return this.client.tools.getInput(slug, body);
124
+ }
125
+ };
126
+
127
+ // src/models/Toolkits.ts
128
+ var Toolkits = class {
129
+ FILE_NAME = "core/models/Toolkits.ts";
130
+ client;
131
+ constructor(client) {
132
+ this.client = client;
133
+ }
134
+ /**
135
+ * List all toolkits available in the Composio SDK.
136
+ * This method fetches the toolkits from the Composio API.
137
+ * @returns {Promise<Toolkit[]>} List of toolkits
138
+ */
139
+ async list(query, options) {
140
+ return this.client.toolkits.list(query, options);
141
+ }
142
+ /**
143
+ * Fetches a toolkit by its Slug.
144
+ * This method retrieves the toolkit from the Composio API.
145
+ * @param slug - The ID of the toolkit to be retrieved
146
+ * @param options - Request options
147
+ * @returns {Promise<ToolkitRetrieveResponse>} The toolkit object
148
+ */
149
+ async get(slug, options) {
150
+ return this.client.toolkits.retrieve(slug, options);
151
+ }
152
+ /**
153
+ * Fetches all categories available in the Composio SDK
154
+ *
155
+ * @returns {Promise<ToolkitRetrieveCategoriesResponse>} List of categories
156
+ */
157
+ async listCategories(options) {
158
+ return this.client.toolkits.retrieveCategories(options);
159
+ }
160
+ };
161
+
162
+ // src/utils/env.ts
163
+ var getEnvVariable = (name, defaultValue = void 0) => {
164
+ try {
165
+ return process.env[name] || defaultValue;
166
+ } catch (_e) {
167
+ return defaultValue;
168
+ }
169
+ };
170
+
171
+ // src/utils/logger.ts
172
+ var LOG_LEVELS = {
173
+ silent: -1,
174
+ // No logs
175
+ error: 0,
176
+ // Highest priority - critical errors
177
+ warn: 1,
178
+ // Warning messages
179
+ info: 2,
180
+ // General information
181
+ debug: 3
182
+ // Debug information
183
+ };
184
+ var getLogLevel = () => {
185
+ const envLevel = getEnvVariable(
186
+ "COMPOSIO_LOGGING_LEVEL",
187
+ "info"
188
+ )?.toLowerCase();
189
+ return envLevel && envLevel in LOG_LEVELS ? envLevel : "info";
190
+ };
191
+ var Logger = class {
192
+ level;
193
+ includeTimestamp;
194
+ console;
195
+ constructor(options = {}) {
196
+ this.level = options.level ?? getLogLevel();
197
+ this.includeTimestamp = options.includeTimestamp ?? true;
198
+ this.console = console;
199
+ }
200
+ formatMessage(args) {
201
+ const formattedArgs = args.map((arg) => typeof arg === "object" ? JSON.stringify(arg) : String(arg)).join(" ");
202
+ if (!this.includeTimestamp) {
203
+ return formattedArgs;
204
+ }
205
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
206
+ return `${timestamp} - ${formattedArgs}`;
207
+ }
208
+ shouldLog(level) {
209
+ return LOG_LEVELS[level] <= LOG_LEVELS[this.level];
210
+ }
211
+ error(...args) {
212
+ if (this.shouldLog("error")) {
213
+ this.console.error(this.formatMessage(args));
214
+ }
215
+ }
216
+ warn(...args) {
217
+ if (this.shouldLog("warn")) {
218
+ this.console.warn(this.formatMessage(args));
219
+ }
220
+ }
221
+ info(...args) {
222
+ if (this.shouldLog("info")) {
223
+ this.console.info(this.formatMessage(args));
224
+ }
225
+ }
226
+ debug(...args) {
227
+ if (this.shouldLog("debug")) {
228
+ this.console.debug(this.formatMessage(args));
229
+ }
230
+ }
231
+ };
232
+ var logger = new Logger();
233
+ var logger_default = logger;
234
+
235
+ // src/utils/pusher.ts
236
+ var PUSHER_KEY = process.env.CLIENT_PUSHER_KEY || "ff9f18c208855d77a152";
237
+ var PUSHER_CLUSTER = "mt1";
238
+ var PusherUtils = class _PusherUtils {
239
+ static pusherClient;
240
+ static getPusherClient(baseURL, apiKey) {
241
+ if (!_PusherUtils.pusherClient) {
242
+ const PusherClient = __require("pusher-js");
243
+ _PusherUtils.pusherClient = new PusherClient(PUSHER_KEY, {
244
+ cluster: PUSHER_CLUSTER,
245
+ channelAuthorization: {
246
+ endpoint: `${baseURL}/api/v1/client/auth/pusher_auth`,
247
+ headers: {
248
+ "x-api-key": apiKey
249
+ },
250
+ transport: "ajax"
251
+ }
252
+ });
253
+ }
254
+ return _PusherUtils.pusherClient;
255
+ }
256
+ /**
257
+ * Subscribes to a Pusher channel and binds an event to a callback function.
258
+ * @param {string} channelName - The name of the channel to subscribe to.
259
+ * @param {string} event - The event to bind to the channel.
260
+ * @param {(data: Record<string, unknown>) => void} fn - The callback function to execute when the event is triggered.
261
+ * @returns {PusherClient} The Pusher client instance.
262
+ */
263
+ static async subscribe(channelName, event, fn) {
264
+ try {
265
+ await _PusherUtils.pusherClient.subscribe(channelName).bind(event, fn);
266
+ } catch (error) {
267
+ logger_default.error(
268
+ `Error subscribing to ${channelName} with event ${event}: ${error}`
269
+ );
270
+ }
271
+ }
272
+ /**
273
+ * Unsubscribes from a Pusher channel.
274
+ * @param {string} channelName - The name of the channel to unsubscribe from.
275
+ * @returns {void}
276
+ */
277
+ static async unsubscribe(channelName) {
278
+ _PusherUtils.pusherClient.unsubscribe(channelName);
279
+ }
280
+ /**
281
+ * Binds an event to a channel with support for chunked messages.
282
+ * @param {PusherClient} channel - The Pusher channel to bind the event to.
283
+ * @param {string} event - The event to bind to the channel.
284
+ * @param {(data: unknown) => void} callback - The callback function to execute when the event is triggered.
285
+ */
286
+ static bindWithChunking(channel, event, callback) {
287
+ channel.bind(event, callback);
288
+ const events = {};
289
+ channel.bind("chunked-" + event, (data) => {
290
+ const typedData = data;
291
+ if (!events.hasOwnProperty(typedData.id)) {
292
+ events[typedData.id] = { chunks: [], receivedFinal: false };
293
+ }
294
+ const ev = events[typedData.id];
295
+ ev.chunks[typedData.index] = typedData.chunk;
296
+ if (typedData.final) ev.receivedFinal = true;
297
+ if (ev.receivedFinal && ev.chunks.length === Object.keys(ev.chunks).length) {
298
+ callback(JSON.parse(ev.chunks.join("")));
299
+ delete events[typedData.id];
300
+ }
301
+ });
302
+ }
303
+ /**
304
+ * Subscribes to a trigger channel for a client and handles chunked data.
305
+ * @param {string} clientId - The unique identifier for the client subscribing to the events.
306
+ * @param {(data: TriggerData) => void} fn - The callback function to execute when trigger data is received.
307
+ */
308
+ static triggerSubscribe(clientId, fn) {
309
+ const channel = _PusherUtils.pusherClient.subscribe(
310
+ `private-${clientId}_triggers`
311
+ );
312
+ _PusherUtils.bindWithChunking(
313
+ channel,
314
+ "trigger_to_client",
315
+ fn
316
+ );
317
+ logger_default.info(
318
+ `Subscribed to triggers. You should start receiving events now.`
319
+ );
320
+ }
321
+ static triggerUnsubscribe(clientId) {
322
+ _PusherUtils.pusherClient.unsubscribe(`${clientId}_triggers`);
323
+ }
324
+ };
325
+
326
+ // src/models/Session.ts
327
+ var Session = class {
328
+ FILE_NAME = "core/models/Session.ts";
329
+ client;
330
+ constructor(client) {
331
+ this.client = client;
332
+ }
333
+ /**
334
+ * Get the active session info
335
+ * @returns {Promise<SessionGetInfoResponse>} Session info
336
+ */
337
+ async getInfo() {
338
+ return this.client.auth.session.getInfo();
339
+ }
340
+ };
341
+
342
+ // src/models/Triggers.ts
343
+ var Triggers = class {
344
+ FILE_NAME = "core/models/Triggers.ts";
345
+ client;
346
+ constructor(client) {
347
+ this.client = client;
348
+ }
349
+ /**
350
+ * Fetch list of all the active triggers
351
+ * @returns {Promise<TriggerInstance[]>} List of trigger instances
352
+ */
353
+ async list(query, options) {
354
+ return this.client.triggerInstances.listActive(query, options);
355
+ }
356
+ /**
357
+ * Create a new trigger instance
358
+ *
359
+ * @param {string} slug - The slug of the trigger instance
360
+ * @param {TriggerInstanceUpsertParams} body - The parameters to create the trigger instance
361
+ * @returns {Promise<TriggerInstanceUpsertResponse>} The created trigger instance
362
+ */
363
+ async create(slug, body, options) {
364
+ return this.client.triggerInstances.upsert(slug, body, options);
365
+ }
366
+ /**
367
+ * Update an existing trigger instance
368
+ *
369
+ * @param {string} slug - The slug of the trigger instance
370
+ * @param {TriggerInstanceUpsertParams} body - The parameters to create the trigger instance
371
+ * @returns {Promise<TriggerInstanceUpsertResponse>} The updated trigger instance
372
+ */
373
+ async update(slug, body, options) {
374
+ return this.client.triggerInstances.upsert(slug, body, options);
375
+ }
376
+ /**
377
+ * Delete a trigger instance
378
+ *
379
+ * @param {string} slug - The slug of the trigger instance
380
+ * @returns
381
+ */
382
+ async delete(slug) {
383
+ return this.client.triggerInstances.removeUpsert(slug);
384
+ }
385
+ /**
386
+ * Update the status of a trigger
387
+ *
388
+ * @param {TriggerStatusEnum} status - The new status of the trigger
389
+ * @param {TriggerInstanceUpdateStatusParams} params - The parameters to update the trigger instance
390
+ * @param {RequestOptions} options - Request options
391
+ * @returns {Promise<TriggerInstanceUpsertResponse>} The updated trigger instance
392
+ */
393
+ async updateStatus(status, params, options) {
394
+ return this.client.triggerInstances.updateStatus(status, params, options);
395
+ }
396
+ /**
397
+ * Disable a trigger instance
398
+ *
399
+ * @param {string} slug - The slug of the trigger instance
400
+ * @param {RequestOptions options - Request options
401
+ * @returns {Promise<TriggerInstanceUpsertResponse>} The updated trigger instance
402
+ */
403
+ async disable(slug, options) {
404
+ return this.client.triggerInstances.updateStatus(
405
+ "disable",
406
+ { slug },
407
+ options
408
+ );
409
+ }
410
+ /**
411
+ * Enable a trigger instance
412
+ *
413
+ * @param {string} slug - The slug of the trigger instance
414
+ * @param {RequestOptions options - Request options
415
+ * @returns {Promise<TriggerInstanceUpsertResponse>} The updated trigger instance
416
+ */
417
+ async enable(slug, options) {
418
+ return this.client.triggerInstances.updateStatus(
419
+ "enable",
420
+ { slug },
421
+ options
422
+ );
423
+ }
424
+ /**
425
+ * @TODO Learn about trigger types
426
+ */
427
+ /**
428
+ * List all the trigger types
429
+ *
430
+ * @param {TriggersTypeListParams} query - The query parameters to filter the trigger types
431
+ * @param {RequestOptions} options - Request options
432
+ * @returns {Promise<TriggersTypeListResponse>} The list of trigger types
433
+ */
434
+ async listTypes(query, options) {
435
+ return this.client.triggersTypes.list(query, options);
436
+ }
437
+ /**
438
+ * Retrieve a trigger type by its slug
439
+ *
440
+ * @param {string} slug - The slug of the trigger type
441
+ * @param {RequestOptions} options - request options
442
+ * @returns {Promise<TriggersTypeRetrieveResponse>} The trigger type object
443
+ */
444
+ async getType(slug, options) {
445
+ return this.client.triggersTypes.retrieve(slug, options);
446
+ }
447
+ /**
448
+ * Fetches the list of all the available trigger enums
449
+ *
450
+ * This method is used by the CLI where filters are not required.
451
+ * @param options
452
+ * @returns
453
+ */
454
+ async listEnum(options) {
455
+ return this.client.triggersTypes.retrieveEnum(options);
456
+ }
457
+ async subscribe(fn, filters = {}) {
458
+ if (!fn) throw new Error("Function is required for trigger subscription");
459
+ const session = new Session(this.client);
460
+ const sessionInfo = await session.getInfo();
461
+ const clientId = sessionInfo.project?.id;
462
+ if (!clientId) throw new Error("Client ID not found");
463
+ await PusherUtils.getPusherClient(
464
+ this.client.baseURL,
465
+ this.client.apiKey
466
+ );
467
+ const shouldSendTrigger = (data) => {
468
+ if (Object.keys(filters).length === 0) return true;
469
+ else {
470
+ return (!filters.appName || data.appName.toLowerCase() === filters.appName.toLowerCase()) && (!filters.triggerId || data.metadata.id.toLowerCase() === filters.triggerId.toLowerCase()) && (!filters.connectionId || data.metadata.connectionId.toLowerCase() === filters.connectionId.toLowerCase()) && (!filters.triggerName || data.metadata.triggerName.toLowerCase() === filters.triggerName.toLowerCase()) && (!filters.entityId || data.metadata.connection.clientUniqueUserId.toLowerCase() === filters.entityId.toLowerCase()) && (!filters.integrationId || data.metadata.connection.integrationId.toLowerCase() === filters.integrationId.toLowerCase());
471
+ }
472
+ };
473
+ logger_default.debug("Subscribing to triggers", filters);
474
+ PusherUtils.triggerSubscribe(clientId, (data) => {
475
+ if (shouldSendTrigger(data)) {
476
+ fn(data);
477
+ }
478
+ });
479
+ }
480
+ async unsubscribe() {
481
+ const session = new Session(this.client);
482
+ const sessionInfo = await session.getInfo();
483
+ const clientId = sessionInfo.project?.id;
484
+ if (!clientId) throw new Error("Client ID not found");
485
+ PusherUtils.triggerUnsubscribe(clientId);
486
+ }
487
+ };
488
+
489
+ // src/toolset/BaseToolset.ts
490
+ var BaseComposioToolset = class {
491
+ client;
492
+ DEFAULT_ENTITY_ID = "default";
493
+ /**
494
+ * Set the client for the toolset. This is automatically done by the Composio class.
495
+ * @param client - The Composio client.
496
+ */
497
+ setClient(client) {
498
+ this.client = client;
499
+ }
500
+ /**
501
+ * Get a tool from the client.
502
+ * @param slug - The slug of the tool.
503
+ * @returns The tool.
504
+ */
505
+ async getTool(slug) {
506
+ const tool = await this.client?.tools.get(slug);
507
+ return this._wrapTool(tool);
508
+ }
509
+ /**
510
+ * Ensure the client is initialized.
511
+ * This is automatically done by the Composio class.
512
+ */
513
+ ensureClient() {
514
+ if (!this.client) {
515
+ throw new Error("Client not initialized. Make sure the toolset is properly initialized with Composio.");
516
+ }
517
+ }
518
+ };
519
+
520
+ // src/toolset/ComposioToolset.ts
521
+ var ComposioToolset = class extends BaseComposioToolset {
522
+ FILE_NAME = "core/toolset/ComposioToolset.ts";
523
+ _wrapTool = (tool) => {
524
+ return tool;
525
+ };
526
+ async getTools(params) {
527
+ const tools = await this.client?.tools.list(params);
528
+ return tools?.items.map((tool) => this._wrapTool(tool)) ?? [];
529
+ }
530
+ async test() {
531
+ }
532
+ };
533
+
534
+ // src/models/AuthConfigs.ts
535
+ var AuthConfigs = class {
536
+ FILE_NAME = "core/models/AuthConfigs.ts";
537
+ client;
538
+ constructor(client) {
539
+ this.client = client;
540
+ }
541
+ /**
542
+ * List all auth configs
543
+ * @param {AuthConfigListParams} query - Query parameters for filtering auth configs
544
+ * @param {RequestOptions} options - Request options
545
+ * @returns {Promise<AuthConfigListResponse>} List of auth configs
546
+ */
547
+ async list(query, options) {
548
+ return this.client.authConfigs.list(query, options);
549
+ }
550
+ /**
551
+ * Create a new auth config
552
+ * @param {AuthConfigCreateParams} data - Data for creating a new auth config
553
+ * @param {RequestOptions} options - Request options
554
+ * @returns {Promise<AuthConfigCreateResponse>} Created auth config
555
+ */
556
+ async create(data, options) {
557
+ return this.client.authConfigs.create(data, options);
558
+ }
559
+ /**
560
+ * Get an auth config by nanoid
561
+ * @param {string} nanoid - Unique identifier of the auth config
562
+ * @param {RequestOptions} options - Request options
563
+ * @returns {Promise<AuthConfigRetrieveResponse>} Auth config details
564
+ */
565
+ async get(nanoid, options) {
566
+ return this.client.authConfigs.retrieve(nanoid, options);
567
+ }
568
+ /**
569
+ * Update an auth config
570
+ * @param {string} nanoid - Unique identifier of the auth config to update
571
+ * @param {AuthConfigUpdateParams} data - Data to update
572
+ * @param {RequestOptions} options - Request options
573
+ * @returns {Promise<AuthConfigUpdateResponse>} Updated auth config
574
+ */
575
+ async update(nanoid, data, options) {
576
+ return this.client.authConfigs.update(nanoid, data, options);
577
+ }
578
+ /**
579
+ * Delete an auth config
580
+ * @param {string} nanoid - Unique identifier of the auth config to delete
581
+ * @param {RequestOptions} options - Request options
582
+ * @returns {Promise<AuthConfigDeleteResponse>} Response from deletion
583
+ */
584
+ async delete(nanoid, options) {
585
+ return this.client.authConfigs.delete(nanoid, options);
586
+ }
587
+ /**
588
+ * Update the status of an auth config
589
+ * @param {string} status - The status to update the auth config to
590
+ * @param {string} nanoid - Unique identifier of the auth config
591
+ * @param {RequestOptions} options - Request options
592
+ * @returns {Promise<AuthConfigUpdateStatusResponse>} Updated auth config details
593
+ */
594
+ async updateStatus(status, nanoid, options) {
595
+ return this.client.authConfigs.updateStatus(status, { nanoid }, options);
596
+ }
597
+ /**
598
+ * Enable an auth config
599
+ * @param {string} nanoid - Unique identifier of the auth config
600
+ * @param {RequestOptions} options - Request options
601
+ * @returns {Promise<AuthConfigUpdateStatusResponse>} Updated auth config details
602
+ */
603
+ async enable(nanoid, options) {
604
+ return this.client.authConfigs.updateStatus("ENABLED", { nanoid }, options);
605
+ }
606
+ /**
607
+ * Disable an auth config
608
+ * @param {string} nanoid - Unique identifier of the auth config
609
+ * @param {RequestOptions} options - Request options
610
+ * @returns {Promise<AuthConfigUpdateStatusResponse>} Updated auth config details
611
+ */
612
+ async disable(nanoid, options) {
613
+ return this.client.authConfigs.updateStatus("DISABLED", { nanoid }, options);
614
+ }
615
+ };
616
+
617
+ // src/models/ConnectedAccounts.ts
618
+ var ConnectedAccounts = class {
619
+ FILE_NAME = "core/models/ConnectedAccounts.ts";
620
+ client;
621
+ constructor(client) {
622
+ this.client = client;
623
+ }
624
+ /**
625
+ * List all connected accounts
626
+ * @param {ConnectedAccountListParams} query - Query parameters for filtering connected accounts
627
+ * @param {RequestOptions} options - Request options
628
+ * @returns {Promise<ConnectedAccountListResponse>} List of connected accounts
629
+ */
630
+ async list(query, options) {
631
+ return this.client.connectedAccounts.list(query, options);
632
+ }
633
+ /**
634
+ * Create a new connected account
635
+ * @param {ConnectedAccountCreateParams} data - Data for creating a new connected account
636
+ * @param {RequestOptions} options - Request options
637
+ * @returns {Promise<ConnectedAccountCreateResponse>} Created connected account
638
+ */
639
+ async create(data, options) {
640
+ return this.client.connectedAccounts.create(data, options);
641
+ }
642
+ /**
643
+ * Get a connected account by nanoid
644
+ * @param {string} nanoid - Unique identifier of the connected account
645
+ * @param {RequestOptions} options - Request options
646
+ * @returns {Promise<ConnectedAccountRetrieveResponse>} Connected account details
647
+ */
648
+ async get(nanoid, options) {
649
+ return this.client.connectedAccounts.retrieve(nanoid, options);
650
+ }
651
+ /**
652
+ * Delete a connected account
653
+ * @param {string} nanoid - Unique identifier of the connected account to delete
654
+ * @param {RequestOptions} options - Request options
655
+ * @returns {Promise<ConnectedAccountDeleteResponse>} Response from deletion
656
+ */
657
+ async delete(nanoid, options) {
658
+ return this.client.connectedAccounts.delete(nanoid, options);
659
+ }
660
+ /**
661
+ * Refresh a connected account's credentials
662
+ * @param {string} nanoid - Unique identifier of the connected account to refresh
663
+ * @param {RequestOptions} options - Request options
664
+ * @returns {Promise<ConnectedAccountRefreshResponse>} Refreshed connected account details
665
+ */
666
+ async refresh(nanoid, options) {
667
+ return this.client.connectedAccounts.refresh(nanoid, options);
668
+ }
669
+ /**
670
+ * Update the status of a connected account
671
+ * @param {string} nanoid - Unique identifier of the connected account
672
+ * @param {ConnectedAccountUpdateStatusParams} params - Parameters for updating the status
673
+ * @param {RequestOptions} options - Request options
674
+ * @returns {Promise<ConnectedAccountUpdateStatusResponse>} Updated connected account details
675
+ */
676
+ async updateStatus(nanoid, params, options) {
677
+ return this.client.connectedAccounts.updateStatus(nanoid, params, options);
678
+ }
679
+ /**
680
+ * Enable a connected account
681
+ * @param {string} nanoid - Unique identifier of the connected account
682
+ * @param {RequestOptions} options - Request options
683
+ * @returns {Promise<ConnectedAccountUpdateStatusResponse>} Updated connected account details
684
+ */
685
+ async enable(nanoid, options) {
686
+ return this.client.connectedAccounts.updateStatus(nanoid, { enabled: true }, options);
687
+ }
688
+ /**
689
+ * Disable a connected account
690
+ * @param {string} nanoid - Unique identifier of the connected account
691
+ * @param {RequestOptions} options - Request options
692
+ * @returns {Promise<ConnectedAccountUpdateStatusResponse>} Updated connected account details
693
+ */
694
+ async disable(nanoid, options) {
695
+ return this.client.connectedAccounts.updateStatus(nanoid, { enabled: false }, options);
696
+ }
697
+ };
698
+
699
+ // src/types/telemetry.types.ts
700
+ var TELEMETRY_EVENTS = {
701
+ SDK_INITIALIZED: "SDK_INITIALIZED",
702
+ SDK_METHOD_INVOKED: "SDK_METHOD_INVOKED",
703
+ SDK_METHOD_ERROR: "SDK_METHOD_ERROR",
704
+ CLI_INVOKED: "CLI_INVOKED"
705
+ };
706
+
707
+ // src/utils/constants.ts
708
+ var COMPOSIO_DIR = ".composio";
709
+ var USER_DATA_FILE_NAME = "user_data.json";
710
+ var DEFAULT_BASE_URL = "https://backend.composio.dev";
711
+ var TELEMETRY_URL = "https://app.composio.dev";
712
+ var IS_DEVELOPMENT_OR_CI = process.env.DEVELOPMENT || process.env.CI || false;
713
+
714
+ // src/telemetry/BatchProcessor.ts
715
+ var BatchProcessor = class {
716
+ batch = [];
717
+ time;
718
+ batchSize;
719
+ processBatchCallback;
720
+ timer = null;
721
+ constructor(time = 2e3, batchSize = 100, processBatchCallback) {
722
+ this.batch = [];
723
+ this.time = time;
724
+ this.batchSize = batchSize;
725
+ this.processBatchCallback = processBatchCallback;
726
+ }
727
+ pushItem(item) {
728
+ this.batch.push(item);
729
+ if (this.batch.length >= this.batchSize) {
730
+ this.processBatch();
731
+ } else if (!this.timer) {
732
+ this.timer = setTimeout(() => this.processBatch(), this.time);
733
+ }
734
+ }
735
+ processBatch() {
736
+ if (this.batch.length > 0) {
737
+ this.processBatchCallback(this.batch);
738
+ this.batch = [];
739
+ }
740
+ if (this.timer) {
741
+ clearTimeout(this.timer);
742
+ this.timer = null;
743
+ }
744
+ }
745
+ };
746
+
747
+ // src/telemetry/transports/BrowserTransport.ts
748
+ var BrowserTelemetryTransport = class {
749
+ send(payload) {
750
+ if (typeof window === "undefined") {
751
+ return Promise.reject(new Error("BrowserTelemetryTransport can only be used in browser environments"));
752
+ }
753
+ return new Promise((resolve) => {
754
+ try {
755
+ const xhr = new XMLHttpRequest();
756
+ xhr.open(payload.method, payload.url, true);
757
+ xhr.setRequestHeader("Content-Type", "application/json");
758
+ Object.entries(payload.headers || {}).forEach(([key, value]) => {
759
+ xhr.setRequestHeader(key, value);
760
+ });
761
+ xhr.onload = function() {
762
+ resolve();
763
+ };
764
+ xhr.send(JSON.stringify(payload.data));
765
+ } catch (error) {
766
+ resolve();
767
+ }
768
+ });
769
+ }
770
+ };
771
+
772
+ // src/telemetry/transports/ProcessTransport.ts
773
+ var ProcessTelemetryTransport = class {
774
+ send(payload) {
775
+ if (typeof window !== "undefined") {
776
+ return Promise.reject(new Error("ProcessTelemetryTransport can only be used in Node.js environments"));
777
+ }
778
+ return new Promise((resolve) => {
779
+ try {
780
+ const url = new URL(payload.url);
781
+ const protocol = url.protocol === "https:" ? "https" : "http";
782
+ const port = url.port || (url.protocol === "https:" ? 443 : 80);
783
+ const args = [
784
+ "-e",
785
+ `
786
+ const http = require('${protocol}');
787
+ const options = {
788
+ hostname: '${url.hostname}',
789
+ path: '${url.pathname}${url.search}',
790
+ port: ${port},
791
+ method: '${payload.method}',
792
+ headers: ${JSON.stringify(payload.headers)}
793
+ };
794
+
795
+ const req = http.request(options, (res) => {
796
+ res.on('data', () => {});
797
+ res.on('end', () => {
798
+ process.exit(0);
799
+ });
800
+ });
801
+
802
+ req.on('error', () => {
803
+ process.exit(0);
804
+ });
805
+
806
+ req.write(JSON.stringify(${JSON.stringify(payload.data)}));
807
+ req.end();
808
+ `
809
+ ];
810
+ const { spawn } = __require("child_process");
811
+ spawn("node", args, {
812
+ stdio: "ignore",
813
+ detached: true,
814
+ shell: false
815
+ }).unref();
816
+ resolve();
817
+ } catch (error) {
818
+ resolve();
819
+ }
820
+ });
821
+ }
822
+ };
823
+
824
+ // src/telemetry/Telemetry.ts
825
+ var Telemetry = class {
826
+ telemetryMetadata;
827
+ transport;
828
+ batchProcessor = new BatchProcessor(100, 10, async (data) => {
829
+ await this.sendTelemetry(data);
830
+ });
831
+ constructor(metadata, transport) {
832
+ this.telemetryMetadata = metadata;
833
+ const isBrowser = typeof window !== "undefined";
834
+ if (transport) {
835
+ this.transport = transport;
836
+ } else if (isBrowser) {
837
+ this.transport = new BrowserTelemetryTransport();
838
+ } else {
839
+ this.transport = new ProcessTelemetryTransport();
840
+ }
841
+ this.sendTelemetry([{
842
+ eventName: TELEMETRY_EVENTS.SDK_INITIALIZED,
843
+ data: {},
844
+ sdk_meta: this.telemetryMetadata
845
+ }]);
846
+ }
847
+ /**
848
+ * Instrument the telemetry for the given instance.
849
+ *
850
+ * You can pass the instance and the file name of the instance to instrument the telemetry.
851
+ * This will instrument all the methods of the instance and log the telemetry for each method call.
852
+ * @param instance - any instance that extends InstrumentedInstance
853
+ * @param fileName - the file name of the instance
854
+ * @returns
855
+ */
856
+ instrumentTelemetry(instance, fileName) {
857
+ const proto = Object.getPrototypeOf(instance);
858
+ const methodNames = Object.getOwnPropertyNames(proto).filter((key) => {
859
+ const descriptor = Object.getOwnPropertyDescriptor(proto, key);
860
+ return key !== "constructor" && descriptor && typeof descriptor.value === "function" && descriptor.value.constructor.name === "AsyncFunction";
861
+ });
862
+ for (const name of methodNames) {
863
+ const originalMethod = instance[name];
864
+ instance[name] = async (...args) => {
865
+ const telemetryPayload = {
866
+ eventName: TELEMETRY_EVENTS.SDK_METHOD_INVOKED,
867
+ data: {
868
+ fileName: instance.FILE_NAME ?? fileName ?? "unknown",
869
+ method: name,
870
+ params: args
871
+ },
872
+ sdk_meta: this.telemetryMetadata
873
+ };
874
+ this.batchProcessor.pushItem(telemetryPayload);
875
+ try {
876
+ return await originalMethod.apply(instance, args);
877
+ } catch (error) {
878
+ const telemetryPayload2 = {
879
+ eventName: TELEMETRY_EVENTS.SDK_METHOD_ERROR,
880
+ data: {
881
+ fileName: instance.FILE_NAME ?? fileName ?? "unknown",
882
+ method: name,
883
+ params: args,
884
+ error
885
+ },
886
+ sdk_meta: this.telemetryMetadata
887
+ };
888
+ this.batchProcessor.pushItem(telemetryPayload2);
889
+ throw error;
890
+ }
891
+ };
892
+ }
893
+ return instance;
894
+ }
895
+ /**
896
+ * Send the telemetry payload to the server.
897
+ * @param payload - the telemetry payload to send
898
+ * @returns
899
+ */
900
+ async sendTelemetry(payload) {
901
+ const isTelemetryDisabled = getEnvVariable("TELEMETRY_DISABLED", "false") === "true";
902
+ if (isTelemetryDisabled) {
903
+ return;
904
+ }
905
+ const url = `${TELEMETRY_URL}/api/sdk_metrics/telemetry`;
906
+ const reqPayload = {
907
+ data: payload,
908
+ url,
909
+ method: "POST",
910
+ headers: { "Content-Type": "application/json" }
911
+ };
912
+ this.transport.send(reqPayload);
913
+ }
914
+ };
915
+
916
+ // src/utils/sdk.ts
917
+ var userDataPath = () => {
918
+ try {
919
+ const path = __require("path");
920
+ const os = __require("os");
921
+ return path.join(os.homedir(), COMPOSIO_DIR, USER_DATA_FILE_NAME);
922
+ } catch (_error) {
923
+ return null;
924
+ }
925
+ };
926
+ var getUserDataJson = () => {
927
+ try {
928
+ const fs = __require("fs");
929
+ const data = fs.readFileSync(userDataPath(), "utf8");
930
+ return JSON.parse(data);
931
+ } catch (_error) {
932
+ return {};
933
+ }
934
+ };
935
+ function getSDKConfig(baseUrl, apiKey) {
936
+ const userData = getUserDataJson();
937
+ const { api_key: apiKeyFromUserConfig, base_url: baseURLFromUserConfig } = userData;
938
+ const baseURLParsed = baseUrl || getEnvVariable("COMPOSIO_BASE_URL") || baseURLFromUserConfig || DEFAULT_BASE_URL;
939
+ const apiKeyParsed = apiKey || getEnvVariable("COMPOSIO_API_KEY") || apiKeyFromUserConfig || "";
940
+ return { baseURL: baseURLParsed, apiKey: apiKeyParsed };
941
+ }
942
+
943
+ // src/utils/version.ts
944
+ function isNewerVersion(version1, version2) {
945
+ const v1 = version1.split(".").map(Number);
946
+ const v2 = version2.split(".").map(Number);
947
+ for (let i = 0; i < 3; i++) {
948
+ if (v1[i] > v2[i]) return true;
949
+ if (v1[i] < v2[i]) return false;
950
+ }
951
+ return false;
952
+ }
953
+ async function checkForLatestVersionFromNPM() {
954
+ try {
955
+ const packageName = "composio-core";
956
+ const currentVersionFromPackageJson = require_package().version;
957
+ const response = await fetch(
958
+ `https://registry.npmjs.org/${packageName}/latest`
959
+ );
960
+ const data = await response.json();
961
+ const latestVersion = data.version;
962
+ if (isNewerVersion(latestVersion, currentVersionFromPackageJson) && !IS_DEVELOPMENT_OR_CI) {
963
+ logger_default.info(
964
+ `\u{1F680} Upgrade available! Your composio-core version (${currentVersionFromPackageJson}) is behind. Latest version: ${latestVersion}.`
965
+ );
966
+ }
967
+ } catch (_error) {
968
+ }
969
+ }
970
+
971
+ // src/composio.ts
972
+ var Composio = class {
973
+ DEFAULT_USER_ID = "default";
974
+ FILE_NAME = "core/composio.ts";
975
+ /**
976
+ * The Composio API client.
977
+ * @type {ComposioClient}
978
+ */
979
+ client;
980
+ /**
981
+ * The configuration for the Composio SDK.
982
+ * @type {ComposioConfig<TTool, TToolset>}
983
+ */
984
+ config;
985
+ telemetry;
986
+ /**
987
+ * Context variables for the Composio SDK.
988
+ */
989
+ userId;
990
+ connectedAccountIds;
991
+ /**
992
+ * Core models for Composio.
993
+ */
994
+ tools;
995
+ toolkits;
996
+ triggers;
997
+ toolset;
998
+ authConfigs;
999
+ connectedAccounts;
1000
+ /**
1001
+ * @param {Object} config Configuration for the Composio SDK.
1002
+ * @param {string} config.apiKey The API key for the Composio SDK.
1003
+ * @param {string} config.baseURL The base URL for the Composio SDK.
1004
+ * @param {string} config.runtime The runtime for the Composio SDK.
1005
+ * @param {boolean} config.allowTracking Whether to allow analytics / tracking. Defaults to true.
1006
+ * @param {boolean} config.allowTracing Whether to allow tracing. Defaults to true.
1007
+ * @param {TS} config.toolset The toolset to use for this Composio instance.
1008
+ */
1009
+ constructor(config) {
1010
+ const { baseURL: baseURLParsed, apiKey: apiKeyParsed } = getSDKConfig(
1011
+ config?.baseURL,
1012
+ config?.apiKey
1013
+ );
1014
+ if (IS_DEVELOPMENT_OR_CI) {
1015
+ logger_default.info(
1016
+ `Initializing Composio w API Key: [REDACTED] and baseURL: ${baseURLParsed}`
1017
+ );
1018
+ }
1019
+ if (config.userId && config.connectedAccountIds) {
1020
+ logger_default.warn(
1021
+ "When both userId and connectedAccountIds are provided, preference will be given to connectedAccountIds"
1022
+ );
1023
+ }
1024
+ this.client = new ComposioClient({
1025
+ apiKey: apiKeyParsed,
1026
+ baseURL: baseURLParsed
1027
+ });
1028
+ this.client;
1029
+ this.config = {
1030
+ ...config,
1031
+ allowTracking: config.allowTracking ?? true
1032
+ };
1033
+ this.userId = config.userId ?? this.DEFAULT_USER_ID;
1034
+ this.connectedAccountIds = config.connectedAccountIds ?? {};
1035
+ this.toolset = config.toolset ?? new ComposioToolset();
1036
+ this.toolset.setClient(this);
1037
+ this.tools = new Tools(this.client);
1038
+ this.toolkits = new Toolkits(this.client);
1039
+ this.triggers = new Triggers(this.client);
1040
+ this.authConfigs = new AuthConfigs(this.client);
1041
+ this.connectedAccounts = new ConnectedAccounts(this.client);
1042
+ if (this.config.allowTracking ?? true) {
1043
+ this.initializeTelemetry({
1044
+ apiKey: apiKeyParsed ?? "",
1045
+ baseUrl: baseURLParsed ?? "",
1046
+ frameworkRuntime: "node",
1047
+ source: "node",
1048
+ // @TODO: get the source
1049
+ sessionId: this.userId,
1050
+ composioVersion: require_package().version,
1051
+ isBrowser: typeof window !== "undefined"
1052
+ }, config.telemetryTransport);
1053
+ }
1054
+ checkForLatestVersionFromNPM();
1055
+ }
1056
+ /**
1057
+ * Initialize the instrumentations and telemetry for the Composio SDK.
1058
+ * @param {TelemetryMetadata} config - The configuration for the telemetry.
1059
+ * @param {BaseTelemetryTransport} transport - The transport for the telemetry.
1060
+ */
1061
+ initializeTelemetry(config, transport) {
1062
+ this.telemetry = new Telemetry(config, transport);
1063
+ this.telemetry.instrumentTelemetry(this);
1064
+ this.telemetry.instrumentTelemetry(this.tools);
1065
+ this.telemetry.instrumentTelemetry(this.toolkits);
1066
+ this.telemetry.instrumentTelemetry(this.triggers);
1067
+ this.telemetry.instrumentTelemetry(this.authConfigs);
1068
+ this.telemetry.instrumentTelemetry(this.connectedAccounts);
1069
+ this.telemetry.instrumentTelemetry(this.toolset);
1070
+ }
1071
+ /**
1072
+ * Get the connected account id for the given app name.
1073
+ * @param appName - The name of the app.
1074
+ * @returns {string | undefined} The connected account id for the given app name.
1075
+ */
1076
+ getConnectedAccountId(appName) {
1077
+ return this.connectedAccountIds?.[appName];
1078
+ }
1079
+ /**
1080
+ * Get the Composio SDK client.
1081
+ * @returns {ComposioClient} The Composio API client.
1082
+ */
1083
+ getClient() {
1084
+ if (!this.client) {
1085
+ throw new Error(
1086
+ "Composio client is not initialized. Please initialize it first."
1087
+ );
1088
+ }
1089
+ return this.client;
1090
+ }
1091
+ /**
1092
+ * Generic function to get all the tools
1093
+ * @returns {Promise<ReturnType<TToolset["getTool"]>>} Promise with list of tools
1094
+ */
1095
+ async getTool(slug) {
1096
+ return this.toolset.getTool(slug);
1097
+ }
1098
+ /**
1099
+ * Generic function to get all the tools
1100
+ * @param query - Query parameters for the tools
1101
+ * @returns {Promise<ReturnType<TToolset["getTools">} Promise with list/records of tools
1102
+ */
1103
+ async getTools(query) {
1104
+ return this.toolset.getTools(query);
1105
+ }
1106
+ };
1107
+
1108
+ // src/utils/jsonSchema.ts
1109
+ import z from "zod";
1110
+ function jsonSchemaPropertiesToTSTypes(value) {
1111
+ if (!value.type) {
1112
+ return z.object({});
1113
+ }
1114
+ let zodType;
1115
+ switch (value.type) {
1116
+ case "string":
1117
+ zodType = z.string().describe(
1118
+ (value.description || "") + (value.examples ? `
1119
+ Examples: ${value.examples.join(", ")}` : "")
1120
+ );
1121
+ break;
1122
+ case "number":
1123
+ zodType = z.number().describe(
1124
+ (value.description || "") + (value.examples ? `
1125
+ Examples: ${value.examples.join(", ")}` : "")
1126
+ );
1127
+ break;
1128
+ case "integer":
1129
+ zodType = z.number().int().describe(
1130
+ (value.description || "") + (value.examples ? `
1131
+ Examples: ${value.examples.join(", ")}` : "")
1132
+ );
1133
+ break;
1134
+ case "boolean":
1135
+ zodType = z.boolean().describe(
1136
+ (value.description || "") + (value.examples ? `
1137
+ Examples: ${value.examples.join(", ")}` : "")
1138
+ );
1139
+ break;
1140
+ case "array":
1141
+ zodType = z.array(
1142
+ jsonSchemaPropertiesToTSTypes(
1143
+ value.items
1144
+ )
1145
+ ).describe(
1146
+ (value.description || "") + (value.examples ? `
1147
+ Examples: ${value.examples.join(", ")}` : "")
1148
+ );
1149
+ break;
1150
+ case "object":
1151
+ zodType = jsonSchemaToModel(value).describe(
1152
+ (value.description || "") + (value.examples ? `
1153
+ Examples: ${value.examples.join(", ")}` : "")
1154
+ );
1155
+ break;
1156
+ case "null":
1157
+ zodType = z.null().describe(value.description || "");
1158
+ break;
1159
+ default:
1160
+ throw new Error(`Unsupported JSON schema type: ${value.type}`);
1161
+ }
1162
+ return zodType;
1163
+ }
1164
+ function jsonSchemaToModel(jsonSchema) {
1165
+ const properties = jsonSchema.properties;
1166
+ const requiredFields = jsonSchema.required || [];
1167
+ if (!properties) {
1168
+ return z.object({});
1169
+ }
1170
+ const zodSchema = {};
1171
+ for (const [key, _] of Object.entries(properties)) {
1172
+ const value = _;
1173
+ let zodType;
1174
+ if (value.anyOf) {
1175
+ const anyOfTypes = value.anyOf.map(
1176
+ (schema) => jsonSchemaPropertiesToTSTypes(
1177
+ schema
1178
+ )
1179
+ );
1180
+ zodType = z.union(anyOfTypes).describe(
1181
+ (value.description || "") + (value.examples ? `
1182
+ Examples: ${value.examples.join(", ")}` : "")
1183
+ );
1184
+ } else if (value.allOf) {
1185
+ const allOfTypes = value.allOf.map(
1186
+ (schema) => jsonSchemaPropertiesToTSTypes(
1187
+ schema
1188
+ )
1189
+ );
1190
+ zodType = z.intersection(
1191
+ allOfTypes[0],
1192
+ allOfTypes.slice(1).reduce(
1193
+ (acc, schema) => acc.and(schema),
1194
+ allOfTypes[0]
1195
+ )
1196
+ ).describe(
1197
+ (value.description || "") + (value.examples ? `
1198
+ Examples: ${value.examples.join(", ")}` : "")
1199
+ );
1200
+ } else {
1201
+ if (!value.type) {
1202
+ value.type = "string";
1203
+ }
1204
+ zodType = jsonSchemaPropertiesToTSTypes(
1205
+ value
1206
+ );
1207
+ }
1208
+ if (value.description) {
1209
+ zodType = zodType.describe(value.description);
1210
+ }
1211
+ if (requiredFields.includes(key)) {
1212
+ zodSchema[key] = zodType;
1213
+ } else {
1214
+ zodSchema[key] = zodType.optional();
1215
+ }
1216
+ }
1217
+ return z.object(zodSchema);
1218
+ }
1219
+
1220
+ // src/telemetry/TelemetryTransport.ts
1221
+ var BaseTelemetryTransport = class {
1222
+ };
1223
+
1224
+ // src/toolset/OpenAIToolset.ts
1225
+ var OpenAIToolset = class extends BaseComposioToolset {
1226
+ static FRAMEWORK_NAME = "openai";
1227
+ FILE_NAME = "toolsets/openai/src/index.ts";
1228
+ /**
1229
+ * Absract method to wrap a tool in the toolset.
1230
+ * This method is implemented by the toolset.
1231
+ * @param tool - The tool to wrap.
1232
+ * @returns The wrapped tool.
1233
+ */
1234
+ _wrapTool = (tool) => {
1235
+ const formattedSchema = {
1236
+ name: tool.slug,
1237
+ description: tool.description,
1238
+ parameters: tool.input_parameters
1239
+ };
1240
+ return {
1241
+ type: "function",
1242
+ function: formattedSchema
1243
+ };
1244
+ };
1245
+ /**
1246
+ * Get all the tools from the Composio in OpenAI format.
1247
+ * @param params - The parameters for the tool list.
1248
+ * @returns The tools.
1249
+ */
1250
+ async getTools(params) {
1251
+ const tools = await this.client?.tools.list(params);
1252
+ return tools?.items.map((tool) => this._wrapTool(tool)) ?? [];
1253
+ }
1254
+ /**
1255
+ * Execute a tool call.
1256
+ * @param {OpenAI.ChatCompletionMessageToolCall} tool - The tool to execute.
1257
+ * @param {string} userId - The user id.
1258
+ * @returns {Promise<string>} The result of the tool call.
1259
+ */
1260
+ async executeToolCall(tool, userId) {
1261
+ if (!this.client) {
1262
+ throw new Error("Client not set");
1263
+ }
1264
+ const toolSchema = await this.client.tools.get(tool.function.name);
1265
+ const appName = toolSchema?.toolkit?.name.toLowerCase();
1266
+ const connectedAccountId = this.client.getConnectedAccountId(appName);
1267
+ const payload = {
1268
+ entity_id: userId ?? this.client.userId,
1269
+ connected_account_id: connectedAccountId,
1270
+ arguments: JSON.parse(tool.function.arguments)
1271
+ };
1272
+ const results = await this.client.tools.execute(toolSchema.slug, payload);
1273
+ return JSON.stringify(results);
1274
+ }
1275
+ /**
1276
+ * Handle the tool call from the assistant.
1277
+ *
1278
+ * @param {OpenAI.ChatCompletion} chatCompletion - The chat completion object.
1279
+ * @param {string} userId - The user id.
1280
+ * @returns {Promise<string[]>} The results of the tool call.
1281
+ */
1282
+ async handleToolCall(chatCompletion, userId) {
1283
+ const outputs = [];
1284
+ for (const message of chatCompletion.choices) {
1285
+ if (message.message.tool_calls) {
1286
+ outputs.push(
1287
+ await this.executeToolCall(message.message.tool_calls[0], userId)
1288
+ );
1289
+ }
1290
+ }
1291
+ return outputs;
1292
+ }
1293
+ /**
1294
+ * Handles all the tool calls from the assistant.
1295
+ *
1296
+ * @param {OpenAI.Beta.Threads.Run} run - The run object.
1297
+ * @param {string} userId - The user id.
1298
+ * @returns {Promise<OpenAI.Beta.Threads.Runs.RunSubmitToolOutputsParams.ToolOutput[]>} The tool outputs.
1299
+ */
1300
+ async handleAssistantMessage(run, userId) {
1301
+ const tool_calls = run.required_action?.submit_tool_outputs?.tool_calls || [];
1302
+ const tool_outputs = await Promise.all(
1303
+ tool_calls.map(async (tool_call) => {
1304
+ logger_default.debug(`Executing tool call: ${tool_call.id}`);
1305
+ const tool_response = await this.executeToolCall(
1306
+ tool_call,
1307
+ userId
1308
+ );
1309
+ logger_default.debug(`Tool call ${tool_call.id} executed with response: ${tool_response}`);
1310
+ return {
1311
+ tool_call_id: tool_call.id,
1312
+ output: JSON.stringify(tool_response)
1313
+ };
1314
+ })
1315
+ );
1316
+ return tool_outputs;
1317
+ }
1318
+ /**
1319
+ * Waits for the assistant stream and handles the tool calls.
1320
+ *
1321
+ * @param {OpenAI} client - The OpenAI client.
1322
+ * @param {Stream<OpenAI.Beta.Assistants.AssistantStreamEvent>} runStream - The run stream.
1323
+ * @param {OpenAI.Beta.Threads.Thread} thread - The thread object.
1324
+ * @param {string} userId - The user id.
1325
+ * @returns {AsyncGenerator<OpenAI.Beta.Assistants.AssistantStreamEvent, void, unknown>} The run stream.
1326
+ */
1327
+ async *waitAndHandleAssistantStreamToolCalls(client, runStream, thread, userId) {
1328
+ const defaultUserId = this.client?.userId;
1329
+ let runId = null;
1330
+ for await (const event of runStream) {
1331
+ yield event;
1332
+ if (event.event === "thread.run.created") {
1333
+ const { id } = event.data;
1334
+ runId = id;
1335
+ }
1336
+ if (!runId) {
1337
+ continue;
1338
+ }
1339
+ if (event.event === "thread.run.requires_action") {
1340
+ const toolOutputs = await this.handleAssistantMessage(
1341
+ event.data,
1342
+ userId ?? defaultUserId
1343
+ );
1344
+ await client.beta.threads.runs.submitToolOutputs(thread.id, runId, {
1345
+ tool_outputs: toolOutputs
1346
+ });
1347
+ }
1348
+ if ([
1349
+ "thread.run.completed",
1350
+ "thread.run.failed",
1351
+ "thread.run.cancelled",
1352
+ "thread.run.expired"
1353
+ ].includes(event.event)) {
1354
+ break;
1355
+ }
1356
+ }
1357
+ if (!runId) {
1358
+ throw new Error("No run ID found");
1359
+ }
1360
+ let finalRun = await client.beta.threads.runs.retrieve(thread.id, runId);
1361
+ while (["queued", "in_progress", "requires_action"].includes(finalRun.status)) {
1362
+ if (finalRun.status === "requires_action") {
1363
+ const toolOutputs = await this.handleAssistantMessage(
1364
+ finalRun,
1365
+ userId ?? defaultUserId
1366
+ );
1367
+ finalRun = await client.beta.threads.runs.submitToolOutputs(
1368
+ thread.id,
1369
+ runId,
1370
+ {
1371
+ tool_outputs: toolOutputs
1372
+ }
1373
+ );
1374
+ } else {
1375
+ finalRun = await client.beta.threads.runs.retrieve(thread.id, runId);
1376
+ await new Promise((resolve) => setTimeout(resolve, 500));
1377
+ }
1378
+ }
1379
+ }
1380
+ /**
1381
+ * Waits for the assistant tool calls and handles them.
1382
+ *
1383
+ * @param {OpenAI} client - The OpenAI client.
1384
+ * @param {OpenAI.Beta.Threads.Run} run - The run object.
1385
+ * @param {OpenAI.Beta.Threads.Thread} thread - The thread object.
1386
+ * @param {string} userId - The user id.
1387
+ * @returns {Promise<OpenAI.Beta.Threads.Run>} The run object.
1388
+ */
1389
+ async waitAndHandleAssistantToolCalls(client, run, thread, userId) {
1390
+ const defaultUserId = this.client?.userId;
1391
+ while (["queued", "in_progress", "requires_action"].includes(run.status)) {
1392
+ const tool_outputs = await this.handleAssistantMessage(
1393
+ run,
1394
+ userId ?? defaultUserId
1395
+ );
1396
+ if (run.status === "requires_action") {
1397
+ run = await client.beta.threads.runs.submitToolOutputs(
1398
+ thread.id,
1399
+ run.id,
1400
+ {
1401
+ tool_outputs
1402
+ }
1403
+ );
1404
+ } else {
1405
+ run = await client.beta.threads.runs.retrieve(thread.id, run.id);
1406
+ await new Promise((resolve) => setTimeout(resolve, 500));
1407
+ }
1408
+ }
1409
+ return run;
1410
+ }
1411
+ };
1412
+ export {
1413
+ BaseComposioToolset,
1414
+ BaseTelemetryTransport,
1415
+ Composio,
1416
+ ComposioToolset,
1417
+ OpenAIToolset,
1418
+ jsonSchemaToModel
1419
+ };