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