@composio/core 0.1.0-rc.4 → 0.1.0-rc.7

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 CHANGED
@@ -1,164 +1,204 @@
1
- var __getOwnPropNames = Object.getOwnPropertyNames;
2
1
  var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
3
2
  get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
4
3
  }) : x)(function(x) {
5
4
  if (typeof require !== "undefined") return require.apply(this, arguments);
6
5
  throw Error('Dynamic require of "' + x + '" is not supported');
7
6
  });
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.4",
18
- description: "",
19
- main: "dist/index.js",
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: [
34
- "README.md",
35
- "dist"
36
- ],
37
- scripts: {
38
- build: "tsup",
39
- test: 'echo "Error: no test specified" && exit 1'
40
- },
41
- keywords: [],
42
- author: "",
43
- license: "ISC",
44
- packageManager: "pnpm@10.8.0",
45
- devDependencies: {
46
- tsup: "^8.4.0",
47
- tsx: "^4.19.3",
48
- typescript: "^5.8.3"
49
- },
50
- dependencies: {
51
- "@composio/client": "0.1.0-alpha.8",
52
- openai: "^4.94.0",
53
- "pusher-js": "^8.4.0",
54
- zod: "^3.24.2"
55
- }
56
- };
57
- }
58
- });
59
7
 
60
8
  // src/composio.ts
61
9
  import ComposioClient from "@composio/client";
62
10
 
63
- // src/models/Tools.ts
64
- var Tools = class {
65
- FILE_NAME = "core/models/Tools.ts";
11
+ // src/types/tool.types.ts
12
+ import { z } from "zod";
13
+ var ToolkitSchema = z.object({
14
+ slug: z.string().describe("The slug of the toolkit"),
15
+ name: z.string().describe("The name of the toolkit"),
16
+ logo: z.string().describe("The logo of the toolkit").optional()
17
+ });
18
+ var ToolSchema = z.object({
19
+ slug: z.string().describe('The slug of the tool. eg. "GOOGLE_SEARCH"'),
20
+ name: z.string().describe(`The name of the tool. eg. "Google Search"`),
21
+ description: z.string().optional().describe("The description of the tool"),
22
+ inputParameters: z.record(z.string(), z.unknown()).optional().describe("The input parameters of the tool"),
23
+ outputParameters: z.record(z.string(), z.unknown()).optional().describe("The output parameters of the tool"),
24
+ tags: z.optional(z.array(z.string())).describe("The tags of the tool. eg: Important").default([]),
25
+ toolkit: z.optional(ToolkitSchema).describe("The toolkit of the tool"),
26
+ version: z.optional(z.string()).describe('The version of the tool, e.g. "1.0.0"')
27
+ });
28
+ var ToolListResponseSchema = z.object({
29
+ items: z.array(ToolSchema),
30
+ nextCursor: z.string().nullable().optional(),
31
+ totalPages: z.number()
32
+ });
33
+ var ToolListParamsSchema = z.object({
34
+ cursor: z.string().optional(),
35
+ important: z.string().optional(),
36
+ limit: z.string().optional(),
37
+ search: z.string().optional(),
38
+ toolkitSlug: z.string().optional(),
39
+ toolSlugs: z.array(z.string()).optional()
40
+ });
41
+ var CustomAuthParamsSchema = z.object({
42
+ baseURL: z.string().optional(),
43
+ body: z.record(z.string(), z.unknown()).optional(),
44
+ parameters: z.array(
45
+ z.object({
46
+ in: z.enum(["query", "header"]),
47
+ name: z.string(),
48
+ value: z.union([z.string(), z.number()])
49
+ })
50
+ )
51
+ });
52
+ var ToolExecuteParamsSchema = z.object({
53
+ allowTracing: z.boolean().optional(),
54
+ connectedAccountId: z.string().optional(),
55
+ customAuthParams: CustomAuthParamsSchema.optional(),
56
+ arguments: z.record(z.string(), z.unknown()).optional(),
57
+ userId: z.string(),
58
+ version: z.string().optional(),
59
+ text: z.string().optional()
60
+ });
61
+ var ToolExecuteResponseSchema = z.object({
62
+ data: z.record(z.string(), z.unknown()),
63
+ error: z.string().nullable(),
64
+ successful: z.boolean(),
65
+ logId: z.string().optional(),
66
+ sessionInfo: z.unknown().optional()
67
+ });
68
+
69
+ // src/models/CustomTools.ts
70
+ import zodToJsonSchema from "zod-to-json-schema";
71
+ var CustomTools = class {
66
72
  client;
73
+ customToolsRegistry = /* @__PURE__ */ new Map();
67
74
  constructor(client) {
68
75
  this.client = client;
69
76
  }
70
77
  /**
71
- * Lists all tools available in the Composio SDK.
72
- * This method fetches the tools from the Composio API and wraps them using the toolset.
73
- * @returns {Tools[]>} List of tools
78
+ * Create a custom tool and registers it in the registry.
79
+ * This is just an in memory registry and is not persisted.
80
+ * @param {CustomToolOptions} toolOptions CustomToolOptions
81
+ * @returns {Tool} The tool created
74
82
  */
75
- async list(query = {}) {
76
- const tools = await this.client.tools.list(query);
77
- if (!tools) {
78
- return {
79
- items: [],
80
- next_cursor: null,
81
- total_pages: 0
82
- };
83
+ async createTool(toolOptions) {
84
+ const { slug, execute, inputParams, name, description } = toolOptions;
85
+ if (!slug || !execute || !inputParams || !name) {
86
+ throw new Error("Invalid tool options");
83
87
  }
84
- return tools;
85
- }
86
- /**
87
- * Retrieves a tool by its Slug.
88
- * @param slug The ID of the tool to be retrieved
89
- * @returns {Promise<Tool>} The tool
90
- */
91
- async get(slug) {
92
- return this.client.tools.retrieve(slug);
93
- }
94
- /**
95
- * Exectes a given tool with the provided parameters.
96
- *
97
- * This method calls the Composio API to execute the tool and returns the response.
98
- *
99
- * @param {string} slug - The ID of the tool to be executed
100
- * @param {ToolExecuteParams} body - The parameters to be passed to the tool
101
- * @returns {Promise<ToolExecuteResponse>} - The response from the tool execution
102
- */
103
- async execute(slug, body) {
104
- return this.client.tools.execute(slug, body);
105
- }
106
- /**
107
- * Fetches the list of all available tools in the Composio SDK.
108
- *
109
- * This method is mostly used by the CLI to get the list of tools.
110
- * No filtering is done on the tools, the list is cached in the backend, no further optimization is required.
111
- * @returns {string} - The list of all available tools as a string
112
- */
113
- async getToolsEnum() {
114
- return this.client.tools.retrieveEnum();
88
+ const paramsSchema = await zodToJsonSchema(inputParams, {
89
+ name: "input"
90
+ });
91
+ const paramsSchemaJson = paramsSchema.definitions.input;
92
+ const toolSchema = {
93
+ name,
94
+ slug,
95
+ description,
96
+ inputParameters: {
97
+ title: name,
98
+ type: "object",
99
+ description,
100
+ properties: paramsSchemaJson.properties,
101
+ required: paramsSchemaJson.required
102
+ },
103
+ // the output parameters are not used yet
104
+ outputParameters: {
105
+ type: "object",
106
+ title: `Response for ${name}`,
107
+ properties: []
108
+ },
109
+ tags: [],
110
+ toolkit: { name: "custom", slug: "custom" }
111
+ };
112
+ this.customToolsRegistry.set(slug.toLowerCase(), {
113
+ options: toolOptions,
114
+ schema: toolSchema
115
+ });
116
+ return toolSchema;
115
117
  }
116
118
  /**
117
- * Fetches the input parameters for a given tool.
118
- *
119
- * This method is used to get the input parameters for a tool before executing it.
120
- *
121
- * @param {string} slug - The ID of the tool to find input for
122
- * @param {ToolGetInputParams} body - The parameters to be passed to the tool
123
- * @returns
119
+ * Get all the custom tools from the registry.
120
+ * @param {string[]} param0.toolSlugs The slugs of the tools to get
121
+ * @returns {ToolList} The list of tools
124
122
  */
125
- async getInput(slug, body) {
126
- return this.client.tools.getInput(slug, body);
127
- }
128
- };
129
-
130
- // src/models/Toolkits.ts
131
- var Toolkits = class {
132
- FILE_NAME = "core/models/Toolkits.ts";
133
- client;
134
- constructor(client) {
135
- this.client = client;
123
+ async getCustomTools({ toolSlugs }) {
124
+ const tools = [];
125
+ if (toolSlugs) {
126
+ for (const slug of toolSlugs) {
127
+ const tool = this.customToolsRegistry.get(slug.toLowerCase());
128
+ if (tool) {
129
+ tools.push(tool.schema);
130
+ }
131
+ }
132
+ } else {
133
+ return Array.from(this.customToolsRegistry.values()).map((tool) => tool.schema);
134
+ }
135
+ return tools;
136
136
  }
137
137
  /**
138
- * List all toolkits available in the Composio SDK.
139
- * This method fetches the toolkits from the Composio API.
140
- * @returns {Promise<Toolkit[]>} List of toolkits
138
+ * Get a custom tool by slug from the registry.
139
+ * @param {string} slug The slug of the tool to get
140
+ * @returns {Tool} The tool
141
141
  */
142
- async list(query, options) {
143
- return this.client.toolkits.list(query, options);
142
+ async getCustomToolBySlug(slug) {
143
+ const tool = this.customToolsRegistry.get(slug.toLowerCase());
144
+ if (!tool) {
145
+ return null;
146
+ }
147
+ return tool.schema;
144
148
  }
145
149
  /**
146
- * Fetches a toolkit by its Slug.
147
- * This method retrieves the toolkit from the Composio API.
148
- * @param slug - The ID of the toolkit to be retrieved
149
- * @param options - Request options
150
- * @returns {Promise<ToolkitRetrieveResponse>} The toolkit object
150
+ * Get the connected account for the user and toolkit.
151
+ * @param {string} toolkitSlug The slug of the toolkit
152
+ * @param {ExecuteMetadata} metadata The metadata of the execution
153
+ * @returns {ConnectedAccount} The connected account
151
154
  */
152
- async get(slug, options) {
153
- return this.client.toolkits.retrieve(slug, options);
155
+ async getConnectedAccount(toolkitSlug, metadata) {
156
+ const connectedAccounts = await this.client.connectedAccounts.list({
157
+ toolkit_slug: toolkitSlug,
158
+ user_id: metadata.userId
159
+ });
160
+ if (!connectedAccounts.items.length) {
161
+ throw new Error(`No connected accounts found for toolkit ${toolkitSlug}`);
162
+ }
163
+ return metadata.connectedAccountId ? connectedAccounts.items.find((item) => item.id === metadata.connectedAccountId) : connectedAccounts.items[0];
154
164
  }
155
165
  /**
156
- * Fetches all categories available in the Composio SDK
157
- *
158
- * @returns {Promise<ToolkitRetrieveCategoriesResponse>} List of categories
166
+ * Execute a custom tool
167
+ * @param {slug} slug The slug of the tool to execute
168
+ * @param {Record<string, unknown>} inputParams The input parameters for the tool
169
+ * @param {ExecuteMetadata} metadata The metadata of the execution
170
+ * @returns {Promise<ToolExecuteResponse>} The response from the tool
159
171
  */
160
- async listCategories(options) {
161
- return this.client.toolkits.retrieveCategories(options);
172
+ async executeCustomTool(slug, inputParams, metadata) {
173
+ const tool = this.customToolsRegistry.get(slug.toLowerCase());
174
+ if (!tool) {
175
+ throw new Error(`Tool with slug ${slug} not found`);
176
+ }
177
+ let authCredentials = {};
178
+ const { toolkitSlug, execute } = tool.options;
179
+ if (toolkitSlug) {
180
+ const connectedAccount = await this.getConnectedAccount(toolkitSlug, metadata);
181
+ if (!connectedAccount) {
182
+ throw new Error(
183
+ `Connected account not found for toolkit ${toolkitSlug} for user ${metadata.userId}`
184
+ );
185
+ }
186
+ authCredentials = connectedAccount.data?.connectionParams;
187
+ }
188
+ if (typeof execute !== "function") {
189
+ throw new Error("Invalid execute function");
190
+ }
191
+ const executeToolRequest = async (data) => {
192
+ return this.client.tools.proxy({
193
+ ...data,
194
+ connected_account_id: metadata.connectedAccountId
195
+ });
196
+ };
197
+ return execute(
198
+ inputParams,
199
+ authCredentials,
200
+ executeToolRequest
201
+ );
162
202
  }
163
203
  };
164
204
 
@@ -167,6 +207,7 @@ var getEnvVariable = (name, defaultValue = void 0) => {
167
207
  try {
168
208
  return process.env[name] || defaultValue;
169
209
  } catch (_e) {
210
+ logger_default.error(`Error getting environment variable ${name}:`, _e);
170
211
  return defaultValue;
171
212
  }
172
213
  };
@@ -235,6 +276,306 @@ var Logger = class {
235
276
  var logger = new Logger();
236
277
  var logger_default = logger;
237
278
 
279
+ // src/models/Tools.ts
280
+ var Tools = class {
281
+ client;
282
+ customTools;
283
+ toolset;
284
+ constructor(client, toolset) {
285
+ this.client = client;
286
+ this.customTools = new CustomTools(client);
287
+ this.toolset = toolset;
288
+ }
289
+ /**
290
+ * Transform the tool cases
291
+ * @param {ToolRetrieveResponse | ComposioToolListResponse['items'][0]} tool - The tool to transform
292
+ * @returns {Tool} The transformed tool
293
+ */
294
+ transformToolCases(tool) {
295
+ return ToolSchema.parse({
296
+ ...tool,
297
+ inputParameters: tool.input_parameters,
298
+ outputParameters: tool.output_parameters
299
+ });
300
+ }
301
+ /**
302
+ * Transform the tool execute response to camelcase
303
+ * @param {ComposioToolExecuteResponse} response - The response to transform
304
+ * @returns {ToolExecuteResponse} The transformed response
305
+ */
306
+ transformToolExecuteResponse(response) {
307
+ return ToolExecuteResponseSchema.parse({
308
+ data: response.data,
309
+ error: response.error,
310
+ successful: response.successful,
311
+ logId: response.log_id,
312
+ sessionInfo: response.session_info
313
+ });
314
+ }
315
+ /**
316
+ * Check if the connected account exists for the given tools.
317
+ * @param {string} userId - The user id.
318
+ * @param {ToolList} tools - The tools to check.
319
+ * @returns {Promise<boolean>} True if the connected account exists for the given tools, false otherwise.
320
+ */
321
+ async checkIfConnectedAccountExistsForTools(userId, tools) {
322
+ if (!tools.length) {
323
+ return true;
324
+ }
325
+ const connectedAccounts = await this.client.connectedAccounts.list({
326
+ user_id: userId
327
+ });
328
+ if (connectedAccounts.items.length === 0) {
329
+ return false;
330
+ }
331
+ const connectedToolkitSlugs = connectedAccounts.items.reduce(
332
+ (acc, account) => {
333
+ if (account.toolkit.slug) {
334
+ acc[account.toolkit.slug] = true;
335
+ }
336
+ return acc;
337
+ },
338
+ {}
339
+ );
340
+ const toolSlugs = tools.reduce(
341
+ (acc, tool) => {
342
+ acc[tool.slug] = true;
343
+ return acc;
344
+ },
345
+ {}
346
+ );
347
+ for (const tool of Object.keys(toolSlugs)) {
348
+ if (!connectedToolkitSlugs[tool]) {
349
+ logger_default.warn(`Tool ${tool} requires a connected account but no connected account was found`);
350
+ return false;
351
+ }
352
+ }
353
+ return true;
354
+ }
355
+ /**
356
+ * Get the connected account id for a given tool
357
+ * @param {string} userId - The user id
358
+ * @param {string} toolSlug - The tool slug
359
+ * @returns {Promise<string | null>} The connected account id or null if the toolkit is a no auth app
360
+ */
361
+ async getConnectedAccountIdForTool(userId, toolSlug) {
362
+ const tool = await this.getComposioToolBySlug(userId, toolSlug);
363
+ if (!tool.toolkit) {
364
+ throw new Error(`Unable to find toolkit for tool ${toolSlug}`);
365
+ }
366
+ const toolkit = await this.client.toolkits.retrieve(tool.toolkit.slug);
367
+ if (!toolkit) {
368
+ throw new Error(`Unable to find toolkit for tool ${toolSlug}`);
369
+ }
370
+ const isNoAuthApp = toolkit.auth_config_details?.some(
371
+ (authConfigDetails) => authConfigDetails.mode === "NO_AUTH"
372
+ );
373
+ if (!isNoAuthApp) {
374
+ const connectedAccounts = await this.client.connectedAccounts.list({
375
+ user_id: userId,
376
+ toolkit_slug: tool.toolkit.slug
377
+ });
378
+ if (connectedAccounts.items.length === 0) {
379
+ throw new Error("No connected accounts found");
380
+ }
381
+ logger_default.warn(
382
+ `Using the first connected account for tool ${toolSlug}. To change this behaviour please explicitly pass a connectedAccountId for the tool`
383
+ );
384
+ return connectedAccounts.items[0].id;
385
+ }
386
+ return null;
387
+ }
388
+ /**
389
+ * Lists all tools available in the Composio SDK as well as custom tools.
390
+ * This method fetches the tools from the Composio API and wraps them using the toolset.
391
+ * @returns {ToolList} List of tools
392
+ */
393
+ async getComposioTools(userId, query = {}, modifier) {
394
+ const queryParams = ToolListParamsSchema.safeParse(query);
395
+ if (queryParams.error) {
396
+ throw new Error(JSON.stringify(queryParams.error.flatten()));
397
+ }
398
+ const tools = await this.client.tools.list({
399
+ cursor: queryParams.data.cursor,
400
+ important: queryParams.data.important,
401
+ limit: queryParams.data.limit,
402
+ search: queryParams.data.search,
403
+ toolkit_slug: queryParams.data.toolkitSlug,
404
+ tool_slugs: queryParams.data.toolSlugs?.join(",")
405
+ });
406
+ if (!tools) {
407
+ return [];
408
+ }
409
+ const caseTransformedTools = tools.items.map((tool) => this.transformToolCases(tool));
410
+ const customTools = await this.customTools.getCustomTools({
411
+ toolSlugs: queryParams.data.toolSlugs
412
+ });
413
+ let modifiedTools = [...caseTransformedTools, ...customTools];
414
+ if (modifier) {
415
+ if (typeof modifier === "function") {
416
+ modifiedTools = modifiedTools.map((tool) => {
417
+ return modifier(tool.slug, tool);
418
+ });
419
+ } else {
420
+ throw new Error("Invalid schema modifier. Not a function.");
421
+ }
422
+ }
423
+ return modifiedTools;
424
+ }
425
+ /**
426
+ * Retrieves a tool by its Slug.
427
+ * @param slug The ID of the tool to be retrieved
428
+ * @returns {Promise<Tool>} The tool
429
+ */
430
+ async getComposioToolBySlug(userId, slug, modifier) {
431
+ const customTool = await this.customTools.getCustomToolBySlug(slug);
432
+ if (customTool) {
433
+ return customTool;
434
+ }
435
+ const tool = await this.client.tools.retrieve(slug);
436
+ if (!tool) {
437
+ throw new Error(`Tool with slug ${slug} not found`);
438
+ }
439
+ let modifiedToool = this.transformToolCases(tool);
440
+ if (modifier) {
441
+ if (typeof modifier === "function") {
442
+ modifiedToool = modifier(slug, modifiedToool);
443
+ } else {
444
+ throw new Error("Invalid schema modifier. Not a function.");
445
+ }
446
+ }
447
+ return modifiedToool;
448
+ }
449
+ async get(userId, arg1, options) {
450
+ if (typeof arg1 === "string") {
451
+ return this.toolset.getToolBySlug(userId, arg1, options);
452
+ } else {
453
+ return this.toolset.getTools(userId, arg1, options);
454
+ }
455
+ }
456
+ /**
457
+ * Exectes a given tool with the provided parameters.
458
+ *
459
+ * This method calls the Composio API to execute the tool and returns the response.
460
+ *
461
+ * @param {string} slug - The ID of the tool to be executed
462
+ * @param {ToolExecuteParams} body - The parameters to be passed to the tool
463
+ * @returns {Promise<ToolExecuteResponse>} - The response from the tool execution
464
+ */
465
+ async execute(slug, body, modifiers) {
466
+ if (modifiers && modifiers.beforeToolExecute) {
467
+ if (typeof modifiers.beforeToolExecute === "function") {
468
+ body = modifiers.beforeToolExecute(slug, body);
469
+ } else {
470
+ throw new Error("Invalid beforeToolExecute modifier. Not a function.");
471
+ }
472
+ }
473
+ let result;
474
+ const customTool = await this.customTools.getCustomToolBySlug(slug);
475
+ if (customTool) {
476
+ result = await this.customTools.executeCustomTool(slug, body, {
477
+ userId: body.userId || "default",
478
+ connectedAccountId: body.connectedAccountId
479
+ });
480
+ } else {
481
+ let connectedAccountId = body.connectedAccountId;
482
+ if (!connectedAccountId) {
483
+ connectedAccountId = await this.getConnectedAccountIdForTool(body.userId, slug) || void 0;
484
+ }
485
+ result = await this.client.tools.execute(slug, {
486
+ allow_tracing: body.allowTracing,
487
+ connected_account_id: body.connectedAccountId,
488
+ custom_auth_params: body.customAuthParams,
489
+ arguments: body.arguments,
490
+ entity_id: body.userId,
491
+ version: body.version,
492
+ text: body.text
493
+ });
494
+ result = this.transformToolExecuteResponse(result);
495
+ }
496
+ if (modifiers && modifiers.afterToolExecute) {
497
+ if (typeof modifiers.afterToolExecute === "function") {
498
+ result = modifiers.afterToolExecute(slug, result);
499
+ } else {
500
+ throw new Error("Invalid afterToolExecute modifier. Not a function.");
501
+ }
502
+ }
503
+ return result;
504
+ }
505
+ /**
506
+ * Fetches the list of all available tools in the Composio SDK.
507
+ *
508
+ * This method is mostly used by the CLI to get the list of tools.
509
+ * No filtering is done on the tools, the list is cached in the backend, no further optimization is required.
510
+ * @returns {string} - The list of all available tools as a string
511
+ */
512
+ async getToolsEnum() {
513
+ return this.client.tools.retrieveEnum();
514
+ }
515
+ /**
516
+ * Fetches the input parameters for a given tool.
517
+ *
518
+ * This method is used to get the input parameters for a tool before executing it.
519
+ *
520
+ * @param {string} slug - The ID of the tool to find input for
521
+ * @param {ToolGetInputParams} body - The parameters to be passed to the tool
522
+ * @returns
523
+ */
524
+ async getInput(slug, body) {
525
+ return this.client.tools.getInput(slug, body);
526
+ }
527
+ /**
528
+ * Proxies a custom request to a toolkit/integration
529
+ * @param body
530
+ * @returns
531
+ */
532
+ async proxyExecute(body) {
533
+ return this.client.tools.proxy(body);
534
+ }
535
+ /**
536
+ * Execute a custom tool
537
+ * @param body
538
+ * @returns
539
+ */
540
+ async createCustomTool(body) {
541
+ return this.customTools.createTool(body);
542
+ }
543
+ };
544
+
545
+ // src/models/Toolkits.ts
546
+ var Toolkits = class {
547
+ client;
548
+ constructor(client) {
549
+ this.client = client;
550
+ }
551
+ /**
552
+ * List all toolkits available in the Composio SDK.
553
+ * This method fetches the toolkits from the Composio API.
554
+ * @returns {Promise<Toolkit[]>} List of toolkits
555
+ */
556
+ async getToolkits(query, options) {
557
+ return this.client.toolkits.list(query, options);
558
+ }
559
+ /**
560
+ * Fetches a toolkit by its Slug.
561
+ * This method retrieves the toolkit from the Composio API.
562
+ * @param slug - The ID of the toolkit to be retrieved
563
+ * @param options - Request options
564
+ * @returns {Promise<ToolkitRetrieveResponse>} The toolkit object
565
+ */
566
+ async getToolkitBySlug(slug, options) {
567
+ return this.client.toolkits.retrieve(slug, options);
568
+ }
569
+ /**
570
+ * Fetches all categories available in the Composio SDK
571
+ *
572
+ * @returns {Promise<ToolkitRetrieveCategoriesResponse>} List of categories
573
+ */
574
+ async listCategories(options) {
575
+ return this.client.toolkits.retrieveCategories(options);
576
+ }
577
+ };
578
+
238
579
  // src/utils/pusher.ts
239
580
  var PUSHER_KEY = process.env.CLIENT_PUSHER_KEY || "ff9f18c208855d77a152";
240
581
  var PUSHER_CLUSTER = "mt1";
@@ -328,7 +669,6 @@ var PusherUtils = class _PusherUtils {
328
669
 
329
670
  // src/models/Session.ts
330
671
  var Session = class {
331
- FILE_NAME = "core/models/Session.ts";
332
672
  client;
333
673
  constructor(client) {
334
674
  this.client = client;
@@ -344,7 +684,6 @@ var Session = class {
344
684
 
345
685
  // src/models/Triggers.ts
346
686
  var Triggers = class {
347
- FILE_NAME = "core/models/Triggers.ts";
348
687
  client;
349
688
  constructor(client) {
350
689
  this.client = client;
@@ -404,11 +743,7 @@ var Triggers = class {
404
743
  * @returns {Promise<TriggerInstanceUpsertResponse>} The updated trigger instance
405
744
  */
406
745
  async disable(slug, options) {
407
- return this.client.triggerInstances.updateStatus(
408
- "disable",
409
- { slug },
410
- options
411
- );
746
+ return this.client.triggerInstances.updateStatus("disable", { slug }, options);
412
747
  }
413
748
  /**
414
749
  * Enable a trigger instance
@@ -418,18 +753,14 @@ var Triggers = class {
418
753
  * @returns {Promise<TriggerInstanceUpsertResponse>} The updated trigger instance
419
754
  */
420
755
  async enable(slug, options) {
421
- return this.client.triggerInstances.updateStatus(
422
- "enable",
423
- { slug },
424
- options
425
- );
756
+ return this.client.triggerInstances.updateStatus("enable", { slug }, options);
426
757
  }
427
758
  /**
428
759
  * @TODO Learn about trigger types
429
760
  */
430
761
  /**
431
762
  * List all the trigger types
432
- *
763
+ *
433
764
  * @param {TriggersTypeListParams} query - The query parameters to filter the trigger types
434
765
  * @param {RequestOptions} options - Request options
435
766
  * @returns {Promise<TriggersTypeListResponse>} The list of trigger types
@@ -439,7 +770,7 @@ var Triggers = class {
439
770
  }
440
771
  /**
441
772
  * Retrieve a trigger type by its slug
442
- *
773
+ *
443
774
  * @param {string} slug - The slug of the trigger type
444
775
  * @param {RequestOptions} options - request options
445
776
  * @returns {Promise<TriggersTypeRetrieveResponse>} The trigger type object
@@ -449,10 +780,10 @@ var Triggers = class {
449
780
  }
450
781
  /**
451
782
  * Fetches the list of all the available trigger enums
452
- *
783
+ *
453
784
  * This method is used by the CLI where filters are not required.
454
- * @param options
455
- * @returns
785
+ * @param options
786
+ * @returns
456
787
  */
457
788
  async listEnum(options) {
458
789
  return this.client.triggersTypes.retrieveEnum(options);
@@ -463,10 +794,7 @@ var Triggers = class {
463
794
  const sessionInfo = await session.getInfo();
464
795
  const clientId = sessionInfo.project?.id;
465
796
  if (!clientId) throw new Error("Client ID not found");
466
- await PusherUtils.getPusherClient(
467
- this.client.baseURL,
468
- this.client.apiKey
469
- );
797
+ await PusherUtils.getPusherClient(this.client.baseURL, this.client.apiKey);
470
798
  const shouldSendTrigger = (data) => {
471
799
  if (Object.keys(filters).length === 0) return true;
472
800
  else {
@@ -480,57 +808,12 @@ var Triggers = class {
480
808
  }
481
809
  });
482
810
  }
483
- async unsubscribe() {
484
- const session = new Session(this.client);
485
- const sessionInfo = await session.getInfo();
486
- const clientId = sessionInfo.project?.id;
487
- if (!clientId) throw new Error("Client ID not found");
488
- PusherUtils.triggerUnsubscribe(clientId);
489
- }
490
- };
491
-
492
- // src/toolset/BaseToolset.ts
493
- var BaseComposioToolset = class {
494
- client;
495
- DEFAULT_ENTITY_ID = "default";
496
- /**
497
- * Set the client for the toolset. This is automatically done by the Composio class.
498
- * @param client - The Composio client.
499
- */
500
- setClient(client) {
501
- this.client = client;
502
- }
503
- /**
504
- * Get a tool from the client.
505
- * @param slug - The slug of the tool.
506
- * @returns The tool.
507
- */
508
- async getTool(slug) {
509
- const tool = await this.client?.tools.get(slug);
510
- return this._wrapTool(tool);
511
- }
512
- /**
513
- * Ensure the client is initialized.
514
- * This is automatically done by the Composio class.
515
- */
516
- ensureClient() {
517
- if (!this.client) {
518
- throw new Error("Client not initialized. Make sure the toolset is properly initialized with Composio.");
519
- }
520
- }
521
- };
522
-
523
- // src/toolset/ComposioToolset.ts
524
- var ComposioToolset = class extends BaseComposioToolset {
525
- FILE_NAME = "core/toolset/ComposioToolset.ts";
526
- _wrapTool = (tool) => {
527
- return tool;
528
- };
529
- async getTools(params) {
530
- const tools = await this.client?.tools.list(params);
531
- return tools?.items.map((tool) => this._wrapTool(tool)) ?? [];
532
- }
533
- async test() {
811
+ async unsubscribe() {
812
+ const session = new Session(this.client);
813
+ const sessionInfo = await session.getInfo();
814
+ const clientId = sessionInfo.project?.id;
815
+ if (!clientId) throw new Error("Client ID not found");
816
+ PusherUtils.triggerUnsubscribe(clientId);
534
817
  }
535
818
  };
536
819
 
@@ -617,9 +900,161 @@ var AuthConfigs = class {
617
900
  }
618
901
  };
619
902
 
903
+ // src/types/connectedAccounts.types.ts
904
+ import { z as z2 } from "zod";
905
+ var ConnectedAccountStatuses = {
906
+ ACTIVE: "ACTIVE",
907
+ INACTIVE: "INACTIVE",
908
+ PENDING: "DELETED",
909
+ INITIATED: "INITIATED",
910
+ EXPIRED: "EXPIRED",
911
+ FAILED: "FAILED"
912
+ };
913
+ var ConnectedAccountStatusSchema = z2.enum([
914
+ ConnectedAccountStatuses.ACTIVE,
915
+ ConnectedAccountStatuses.INACTIVE,
916
+ ConnectedAccountStatuses.PENDING,
917
+ ConnectedAccountStatuses.INITIATED,
918
+ ConnectedAccountStatuses.EXPIRED,
919
+ ConnectedAccountStatuses.FAILED
920
+ ]);
921
+ var CreateConnectedAccountParamsSchema = z2.object({
922
+ authConfig: z2.object({
923
+ id: z2.string()
924
+ }),
925
+ connection: z2.object({
926
+ data: z2.record(z2.string(), z2.unknown()).optional(),
927
+ rediretUrl: z2.string().optional(),
928
+ userId: z2.string().optional()
929
+ })
930
+ });
931
+ var CreateConnectedAccountResponseSchema = z2.object({
932
+ id: z2.string(),
933
+ status: ConnectedAccountStatusSchema,
934
+ redirectUrl: z2.string().nullable()
935
+ });
936
+ var ConnectedAccountAuthSchemes = {
937
+ OAUTH2: "OAUTH2",
938
+ OAUTH1: "OAUTH1",
939
+ OAUTH1A: "OAUTH1A",
940
+ API_KEY: "API_KEY",
941
+ BASIC: "BASIC",
942
+ BILLCOM_AUTH: "BILLCOM_AUTH",
943
+ BEARER_TOKEN: "BEARER_TOKEN",
944
+ GOOGLE_SERVICE_ACCOUNT: "GOOGLE_SERVICE_ACCOUNT",
945
+ NO_AUTH: "NO_AUTH",
946
+ BASIC_WITH_JWT: "BASIC_WITH_JWT",
947
+ COMPOSIO_LINK: "COMPOSIO_LINK",
948
+ CALCOM_AUTH: "CALCOM_AUTH",
949
+ SNOWFLAKE: "SNOWFLAKE"
950
+ };
951
+ var ConnectedAccountAuthSchemesSchema = z2.enum([
952
+ ConnectedAccountAuthSchemes.OAUTH2,
953
+ ConnectedAccountAuthSchemes.OAUTH1,
954
+ ConnectedAccountAuthSchemes.OAUTH1A,
955
+ ConnectedAccountAuthSchemes.API_KEY,
956
+ ConnectedAccountAuthSchemes.BASIC,
957
+ ConnectedAccountAuthSchemes.BILLCOM_AUTH,
958
+ ConnectedAccountAuthSchemes.BEARER_TOKEN,
959
+ ConnectedAccountAuthSchemes.GOOGLE_SERVICE_ACCOUNT,
960
+ ConnectedAccountAuthSchemes.NO_AUTH,
961
+ ConnectedAccountAuthSchemes.BASIC_WITH_JWT,
962
+ ConnectedAccountAuthSchemes.COMPOSIO_LINK,
963
+ ConnectedAccountAuthSchemes.CALCOM_AUTH,
964
+ ConnectedAccountAuthSchemes.SNOWFLAKE
965
+ ]);
966
+ var ConnectedAccountAuthConfigSchema = z2.object({
967
+ id: z2.string(),
968
+ authScheme: ConnectedAccountAuthSchemesSchema,
969
+ isComposioManaged: z2.boolean(),
970
+ isDisabled: z2.boolean()
971
+ });
972
+ var ConnectedAccountRetrieveResponseSchema = z2.object({
973
+ id: z2.string(),
974
+ uuid: z2.string(),
975
+ authConfig: ConnectedAccountAuthConfigSchema,
976
+ userId: z2.string(),
977
+ data: z2.record(z2.string(), z2.unknown()),
978
+ params: z2.record(z2.string(), z2.unknown()),
979
+ status: ConnectedAccountStatusSchema,
980
+ statusReason: z2.string().nullable(),
981
+ toolkit: z2.object({
982
+ slug: z2.string()
983
+ }),
984
+ testRequestEndpoint: z2.string().optional(),
985
+ isDisabled: z2.boolean(),
986
+ createdAt: z2.string(),
987
+ updatedAt: z2.string()
988
+ });
989
+
990
+ // src/models/ConnectionRequest.ts
991
+ var ConnectionRequest = class {
992
+ FILE_NAME = "core/models/ConnectionRequest.ts";
993
+ client;
994
+ connectedAccountId;
995
+ connectedAccountStatus;
996
+ constructor(client, connectedAccountId, connectedAccountStatus) {
997
+ this.client = client;
998
+ this.connectedAccountId = connectedAccountId;
999
+ this.connectedAccountStatus = connectedAccountStatus;
1000
+ }
1001
+ /**
1002
+ * Transform the response from the Composio API to the SDK format
1003
+ * @param response
1004
+ * @returns
1005
+ */
1006
+ async transformResponse(response) {
1007
+ return {
1008
+ ...response,
1009
+ userId: response.user_id,
1010
+ // Add the missing userId property
1011
+ authConfig: {
1012
+ ...response.auth_config,
1013
+ authScheme: response.auth_config.auth_scheme,
1014
+ isComposioManaged: response.auth_config.is_composio_managed,
1015
+ isDisabled: response.auth_config.is_disabled
1016
+ },
1017
+ statusReason: response.status_reason,
1018
+ isDisabled: response.is_disabled,
1019
+ createdAt: response.created_at,
1020
+ updatedAt: response.updated_at,
1021
+ testRequestEndpoint: response.test_request_endpoint
1022
+ };
1023
+ }
1024
+ /**
1025
+ * Wait for the connection to be established.
1026
+ * The function will poll the Composio API every second until the connection is established or the timeout is reached.
1027
+ * @param {number} timeout - The time in milliseconds to wait for the connection to be established. Default is 30 seconds.
1028
+ * @returns
1029
+ */
1030
+ async waitForConnection(timeout = 6e4) {
1031
+ if (this.connectedAccountStatus === ConnectedAccountStatuses.ACTIVE) {
1032
+ const response = await this.client.connectedAccounts.retrieve(this.connectedAccountId);
1033
+ return Promise.resolve(this.transformResponse(response));
1034
+ }
1035
+ return new Promise((resolve, reject) => {
1036
+ const interval = setInterval(async () => {
1037
+ try {
1038
+ const response = await this.client.connectedAccounts.retrieve(this.connectedAccountId);
1039
+ if (response.status === ConnectedAccountStatuses.ACTIVE) {
1040
+ clearInterval(interval);
1041
+ resolve(this.transformResponse(response));
1042
+ }
1043
+ } catch (error) {
1044
+ clearInterval(interval);
1045
+ reject(error);
1046
+ }
1047
+ }, 1e3);
1048
+ setTimeout(() => {
1049
+ clearInterval(interval);
1050
+ reject(new Error("Connection request timed out"));
1051
+ }, timeout);
1052
+ });
1053
+ }
1054
+ };
1055
+
620
1056
  // src/models/ConnectedAccounts.ts
621
1057
  var ConnectedAccounts = class {
622
- FILE_NAME = "core/models/ConnectedAccounts.ts";
623
1058
  client;
624
1059
  constructor(client) {
625
1060
  this.client = client;
@@ -697,6 +1132,27 @@ var ConnectedAccounts = class {
697
1132
  async disable(nanoid, options) {
698
1133
  return this.client.connectedAccounts.updateStatus(nanoid, { enabled: false }, options);
699
1134
  }
1135
+ /**
1136
+ * Compound function to create a new connected account.
1137
+ * This function creates a new connected account and returns a connection request.
1138
+ * Users can then wait for the connection to be established using the `waitForConnection` method.
1139
+ * @param {CreateConnectedAccountParams} data - Data for creating a new connected account
1140
+ * @returns {Promise<ConnectionRequest>} Connection request object
1141
+ */
1142
+ async createConnectedAccount(data) {
1143
+ const { authConfig, connection } = data;
1144
+ const response = await this.create({
1145
+ auth_config: {
1146
+ id: authConfig.id
1147
+ },
1148
+ connection: {
1149
+ data: connection.data,
1150
+ redirect_uri: connection.rediretUrl,
1151
+ user_id: connection.userId
1152
+ }
1153
+ });
1154
+ return new ConnectionRequest(this.client, response.id, response.status);
1155
+ }
700
1156
  };
701
1157
 
702
1158
  // src/types/telemetry.types.ts
@@ -751,7 +1207,9 @@ var BatchProcessor = class {
751
1207
  var BrowserTelemetryTransport = class {
752
1208
  send(payload) {
753
1209
  if (typeof window === "undefined") {
754
- return Promise.reject(new Error("BrowserTelemetryTransport can only be used in browser environments"));
1210
+ return Promise.reject(
1211
+ new Error("BrowserTelemetryTransport can only be used in browser environments")
1212
+ );
755
1213
  }
756
1214
  return new Promise((resolve) => {
757
1215
  try {
@@ -766,6 +1224,7 @@ var BrowserTelemetryTransport = class {
766
1224
  };
767
1225
  xhr.send(JSON.stringify(payload.data));
768
1226
  } catch (error) {
1227
+ logger_default.error("Error sending error to telemetry", error);
769
1228
  resolve();
770
1229
  }
771
1230
  });
@@ -776,7 +1235,9 @@ var BrowserTelemetryTransport = class {
776
1235
  var ProcessTelemetryTransport = class {
777
1236
  send(payload) {
778
1237
  if (typeof window !== "undefined") {
779
- return Promise.reject(new Error("ProcessTelemetryTransport can only be used in Node.js environments"));
1238
+ return Promise.reject(
1239
+ new Error("ProcessTelemetryTransport can only be used in Node.js environments")
1240
+ );
780
1241
  }
781
1242
  return new Promise((resolve) => {
782
1243
  try {
@@ -810,14 +1271,18 @@ var ProcessTelemetryTransport = class {
810
1271
  req.end();
811
1272
  `
812
1273
  ];
813
- const { spawn } = __require("child_process");
814
- spawn("node", args, {
815
- stdio: "ignore",
816
- detached: true,
817
- shell: false
818
- }).unref();
819
- resolve();
1274
+ import("child_process").then(({ spawn }) => {
1275
+ spawn("node", args, {
1276
+ stdio: "ignore",
1277
+ detached: true,
1278
+ shell: false
1279
+ }).unref();
1280
+ resolve();
1281
+ }).catch(() => {
1282
+ resolve();
1283
+ });
820
1284
  } catch (error) {
1285
+ logger_default.error("Error sending telemetry", error);
821
1286
  resolve();
822
1287
  }
823
1288
  });
@@ -841,20 +1306,22 @@ var Telemetry = class {
841
1306
  } else {
842
1307
  this.transport = new ProcessTelemetryTransport();
843
1308
  }
844
- this.sendTelemetry([{
845
- eventName: TELEMETRY_EVENTS.SDK_INITIALIZED,
846
- data: {},
847
- sdk_meta: this.telemetryMetadata
848
- }]);
1309
+ this.sendTelemetry([
1310
+ {
1311
+ eventName: TELEMETRY_EVENTS.SDK_INITIALIZED,
1312
+ data: {},
1313
+ sdk_meta: this.telemetryMetadata
1314
+ }
1315
+ ]);
849
1316
  }
850
1317
  /**
851
1318
  * Instrument the telemetry for the given instance.
852
- *
1319
+ *
853
1320
  * You can pass the instance and the file name of the instance to instrument the telemetry.
854
1321
  * This will instrument all the methods of the instance and log the telemetry for each method call.
855
1322
  * @param instance - any instance that extends InstrumentedInstance
856
1323
  * @param fileName - the file name of the instance
857
- * @returns
1324
+ * @returns
858
1325
  */
859
1326
  instrumentTelemetry(instance, fileName) {
860
1327
  const proto = Object.getPrototypeOf(instance);
@@ -862,13 +1329,14 @@ var Telemetry = class {
862
1329
  const descriptor = Object.getOwnPropertyDescriptor(proto, key);
863
1330
  return key !== "constructor" && descriptor && typeof descriptor.value === "function" && descriptor.value.constructor.name === "AsyncFunction";
864
1331
  });
1332
+ const instrumentedClassName = instance.constructor?.name || fileName || "unknown";
865
1333
  for (const name of methodNames) {
866
1334
  const originalMethod = instance[name];
867
1335
  instance[name] = async (...args) => {
868
1336
  const telemetryPayload = {
869
1337
  eventName: TELEMETRY_EVENTS.SDK_METHOD_INVOKED,
870
1338
  data: {
871
- fileName: instance.FILE_NAME ?? fileName ?? "unknown",
1339
+ fileName: instrumentedClassName,
872
1340
  method: name,
873
1341
  params: args
874
1342
  },
@@ -881,7 +1349,7 @@ var Telemetry = class {
881
1349
  const telemetryPayload2 = {
882
1350
  eventName: TELEMETRY_EVENTS.SDK_METHOD_ERROR,
883
1351
  data: {
884
- fileName: instance.FILE_NAME ?? fileName ?? "unknown",
1352
+ fileName: instrumentedClassName,
885
1353
  method: name,
886
1354
  params: args,
887
1355
  error
@@ -893,88 +1361,305 @@ var Telemetry = class {
893
1361
  }
894
1362
  };
895
1363
  }
896
- return instance;
1364
+ return instance;
1365
+ }
1366
+ /**
1367
+ * Send the telemetry payload to the server.
1368
+ * @param payload - the telemetry payload to send
1369
+ * @returns
1370
+ */
1371
+ async sendTelemetry(payload) {
1372
+ const isTelemetryDisabled = getEnvVariable("TELEMETRY_DISABLED", "false") === "true";
1373
+ if (isTelemetryDisabled) {
1374
+ return;
1375
+ }
1376
+ const url = `${TELEMETRY_URL}/api/sdk_metrics/telemetry`;
1377
+ const reqPayload = {
1378
+ data: payload,
1379
+ url,
1380
+ method: "POST",
1381
+ headers: { "Content-Type": "application/json" }
1382
+ };
1383
+ this.transport.send(reqPayload);
1384
+ }
1385
+ };
1386
+
1387
+ // src/utils/sdk.ts
1388
+ var userDataPath = () => {
1389
+ try {
1390
+ const path = __require("path");
1391
+ const os = __require("os");
1392
+ return path.join(os.homedir(), COMPOSIO_DIR, USER_DATA_FILE_NAME);
1393
+ } catch (_error) {
1394
+ return null;
1395
+ }
1396
+ };
1397
+ var getUserDataJson = () => {
1398
+ try {
1399
+ const fs = __require("fs");
1400
+ const data = fs.readFileSync(userDataPath(), "utf8");
1401
+ return JSON.parse(data);
1402
+ } catch (_error) {
1403
+ return {};
1404
+ }
1405
+ };
1406
+ function getSDKConfig(baseUrl, apiKey) {
1407
+ const userData = getUserDataJson();
1408
+ const { api_key: apiKeyFromUserConfig, base_url: baseURLFromUserConfig } = userData;
1409
+ const baseURLParsed = baseUrl || getEnvVariable("COMPOSIO_BASE_URL") || baseURLFromUserConfig || DEFAULT_BASE_URL;
1410
+ const apiKeyParsed = apiKey || getEnvVariable("COMPOSIO_API_KEY") || apiKeyFromUserConfig || "";
1411
+ return { baseURL: baseURLParsed, apiKey: apiKeyParsed };
1412
+ }
1413
+
1414
+ // src/utils/version.ts
1415
+ function isNewerVersion(version1, version2) {
1416
+ const v1 = version1.split(".").map(Number);
1417
+ const v2 = version2.split(".").map(Number);
1418
+ for (let i = 0; i < 3; i++) {
1419
+ if (v1[i] > v2[i]) return true;
1420
+ if (v1[i] < v2[i]) return false;
1421
+ }
1422
+ return false;
1423
+ }
1424
+ async function checkForLatestVersionFromNPM(currentVersion) {
1425
+ try {
1426
+ const packageName = "composio-core";
1427
+ const currentVersionFromPackageJson = currentVersion;
1428
+ const response = await fetch(`https://registry.npmjs.org/${packageName}/latest`);
1429
+ const data = await response.json();
1430
+ const latestVersion = data.version;
1431
+ if (isNewerVersion(latestVersion, currentVersionFromPackageJson) && !IS_DEVELOPMENT_OR_CI) {
1432
+ logger_default.info(
1433
+ `\u{1F680} Upgrade available! Your composio-core version (${currentVersionFromPackageJson}) is behind. Latest version: ${latestVersion}.`
1434
+ );
1435
+ }
1436
+ } catch (_error) {
1437
+ }
1438
+ }
1439
+
1440
+ // src/toolset/BaseToolset.ts
1441
+ var BaseNonAgenticToolset = class {
1442
+ composio;
1443
+ setComposio(composio) {
1444
+ this.composio = composio;
1445
+ }
1446
+ getComposio() {
1447
+ if (!this.composio) {
1448
+ throw new Error(
1449
+ "Client not initialized. Make sure the toolset is properly initialized with Composio."
1450
+ );
1451
+ }
1452
+ return this.composio;
1453
+ }
1454
+ };
1455
+ var BaseAgenticToolset = class {
1456
+ composio;
1457
+ setComposio(composio) {
1458
+ this.composio = composio;
1459
+ }
1460
+ getComposio() {
1461
+ if (!this.composio) {
1462
+ throw new Error(
1463
+ "Client not initialized. Make sure the toolset is properly initialized with Composio."
1464
+ );
1465
+ }
1466
+ return this.composio;
1467
+ }
1468
+ };
1469
+
1470
+ // src/toolset/OpenAIToolset.ts
1471
+ var OpenAIToolset = class extends BaseNonAgenticToolset {
1472
+ /**
1473
+ * Absract method to wrap a tool in the toolset.
1474
+ * This method is implemented by the toolset.
1475
+ * @param tool - The tool to wrap.
1476
+ * @returns The wrapped tool.
1477
+ */
1478
+ wrapTool = (tool) => {
1479
+ const formattedSchema = {
1480
+ name: tool.slug,
1481
+ description: tool.description,
1482
+ parameters: tool.inputParameters
1483
+ };
1484
+ return {
1485
+ type: "function",
1486
+ function: formattedSchema
1487
+ };
1488
+ };
1489
+ /**
1490
+ * Get all the tools from the Composio in OpenAI format.
1491
+ * @param params - The parameters for the tool list.
1492
+ * @param modifiers - Optional modifiers to transform tool schemas
1493
+ * @returns The tools.
1494
+ */
1495
+ async getTools(userId, params, modifiers) {
1496
+ const tools = await this.getComposio()?.tools.getComposioTools(
1497
+ userId,
1498
+ params,
1499
+ modifiers?.modifyToolSchema
1500
+ );
1501
+ return tools?.map((tool) => this.wrapTool(tool)) ?? [];
1502
+ }
1503
+ async getToolBySlug(userId, slug, modifiers) {
1504
+ const tool = await this.getComposio().tools.getComposioToolBySlug(
1505
+ userId,
1506
+ slug,
1507
+ modifiers?.modifyToolSchema
1508
+ );
1509
+ return this.wrapTool(tool);
1510
+ }
1511
+ /**
1512
+ * Execute a tool call.
1513
+ * @param {OpenAI.ChatCompletionMessageToolCall} tool - The tool to execute.
1514
+ * @param {string} userId - The user id.
1515
+ * @returns {Promise<string>} The result of the tool call.
1516
+ */
1517
+ async executeToolCall(userId, tool, modifiers) {
1518
+ const toolSchema = await this.getComposio().tools.getComposioToolBySlug(
1519
+ userId,
1520
+ tool.function.name
1521
+ );
1522
+ const appSlug = toolSchema?.toolkit?.slug.toLowerCase();
1523
+ if (!appSlug) {
1524
+ throw new Error("App slug not found");
1525
+ }
1526
+ const payload = {
1527
+ userId,
1528
+ arguments: JSON.parse(tool.function.arguments)
1529
+ };
1530
+ const results = await this.getComposio().tools.execute(toolSchema.slug, payload, modifiers);
1531
+ return JSON.stringify(results);
1532
+ }
1533
+ /**
1534
+ * Handle the tool call from the assistant.
1535
+ *
1536
+ * @param {OpenAI.ChatCompletion} chatCompletion - The chat completion object.
1537
+ * @param {string} userId - The user id.
1538
+ * @returns {Promise<string[]>} The results of the tool call.
1539
+ */
1540
+ async handleToolCall(userId, chatCompletion, modifiers) {
1541
+ const outputs = [];
1542
+ for (const message of chatCompletion.choices) {
1543
+ if (message.message.tool_calls) {
1544
+ outputs.push(await this.executeToolCall(userId, message.message.tool_calls[0], modifiers));
1545
+ }
1546
+ }
1547
+ return outputs;
1548
+ }
1549
+ /**
1550
+ * Handles all the tool calls from the assistant.
1551
+ *
1552
+ * @param {OpenAI.Beta.Threads.Run} run - The run object.
1553
+ * @param {string} userId - The user id.
1554
+ * @returns {Promise<OpenAI.Beta.Threads.Runs.RunSubmitToolOutputsParams.ToolOutput[]>} The tool outputs.
1555
+ */
1556
+ async handleAssistantMessage(userId, run, modifiers) {
1557
+ const tool_calls = run.required_action?.submit_tool_outputs?.tool_calls || [];
1558
+ const tool_outputs = await Promise.all(
1559
+ tool_calls.map(async (tool_call) => {
1560
+ logger_default.debug(`Executing tool call: ${tool_call.id}`);
1561
+ const tool_response = await this.executeToolCall(
1562
+ userId,
1563
+ tool_call,
1564
+ modifiers
1565
+ );
1566
+ logger_default.debug(`Tool call ${tool_call.id} executed with response: ${tool_response}`);
1567
+ return {
1568
+ tool_call_id: tool_call.id,
1569
+ output: JSON.stringify(tool_response)
1570
+ };
1571
+ })
1572
+ );
1573
+ return tool_outputs;
1574
+ }
1575
+ /**
1576
+ * Waits for the assistant stream and handles the tool calls.
1577
+ *
1578
+ * @param {OpenAI} client - The OpenAI client.
1579
+ * @param {Stream<OpenAI.Beta.Assistants.AssistantStreamEvent>} runStream - The run stream.
1580
+ * @param {OpenAI.Beta.Threads.Thread} thread - The thread object.
1581
+ * @param {string} userId - The user id.
1582
+ * @returns {AsyncGenerator<OpenAI.Beta.Assistants.AssistantStreamEvent, void, unknown>} The run stream.
1583
+ */
1584
+ async *waitAndHandleAssistantStreamToolCalls(userId, client, runStream, thread, modifiers) {
1585
+ let runId = null;
1586
+ for await (const event of runStream) {
1587
+ yield event;
1588
+ if (event.event === "thread.run.created") {
1589
+ const { id } = event.data;
1590
+ runId = id;
1591
+ }
1592
+ if (!runId) {
1593
+ continue;
1594
+ }
1595
+ if (event.event === "thread.run.requires_action") {
1596
+ const toolOutputs = await this.handleAssistantMessage(userId, event.data, modifiers);
1597
+ await client.beta.threads.runs.submitToolOutputs(thread.id, runId, {
1598
+ tool_outputs: toolOutputs
1599
+ });
1600
+ }
1601
+ if ([
1602
+ "thread.run.completed",
1603
+ "thread.run.failed",
1604
+ "thread.run.cancelled",
1605
+ "thread.run.expired"
1606
+ ].includes(event.event)) {
1607
+ break;
1608
+ }
1609
+ }
1610
+ if (!runId) {
1611
+ throw new Error("No run ID found");
1612
+ }
1613
+ let finalRun = await client.beta.threads.runs.retrieve(thread.id, runId);
1614
+ while (["queued", "in_progress", "requires_action"].includes(finalRun.status)) {
1615
+ if (finalRun.status === "requires_action") {
1616
+ const toolOutputs = await this.handleAssistantMessage(userId, finalRun, modifiers);
1617
+ finalRun = await client.beta.threads.runs.submitToolOutputs(thread.id, runId, {
1618
+ tool_outputs: toolOutputs
1619
+ });
1620
+ } else {
1621
+ finalRun = await client.beta.threads.runs.retrieve(thread.id, runId);
1622
+ await new Promise((resolve) => setTimeout(resolve, 500));
1623
+ }
1624
+ }
897
1625
  }
898
1626
  /**
899
- * Send the telemetry payload to the server.
900
- * @param payload - the telemetry payload to send
901
- * @returns
1627
+ * Waits for the assistant tool calls and handles them.
1628
+ *
1629
+ * @param {OpenAI} client - The OpenAI client.
1630
+ * @param {OpenAI.Beta.Threads.Run} run - The run object.
1631
+ * @param {OpenAI.Beta.Threads.Thread} thread - The thread object.
1632
+ * @param {string} userId - The user id.
1633
+ * @returns {Promise<OpenAI.Beta.Threads.Run>} The run object.
902
1634
  */
903
- async sendTelemetry(payload) {
904
- const isTelemetryDisabled = getEnvVariable("TELEMETRY_DISABLED", "false") === "true";
905
- if (isTelemetryDisabled) {
906
- return;
1635
+ async waitAndHandleAssistantToolCalls(userId, client, run, thread, modifiers) {
1636
+ while (["queued", "in_progress", "requires_action"].includes(run.status)) {
1637
+ const tool_outputs = await this.handleAssistantMessage(userId, run, modifiers);
1638
+ if (run.status === "requires_action") {
1639
+ run = await client.beta.threads.runs.submitToolOutputs(thread.id, run.id, {
1640
+ tool_outputs
1641
+ });
1642
+ } else {
1643
+ run = await client.beta.threads.runs.retrieve(thread.id, run.id);
1644
+ await new Promise((resolve) => setTimeout(resolve, 500));
1645
+ }
907
1646
  }
908
- const url = `${TELEMETRY_URL}/api/sdk_metrics/telemetry`;
909
- const reqPayload = {
910
- data: payload,
911
- url,
912
- method: "POST",
913
- headers: { "Content-Type": "application/json" }
914
- };
915
- this.transport.send(reqPayload);
1647
+ return run;
916
1648
  }
917
1649
  };
918
1650
 
919
- // src/utils/sdk.ts
920
- var userDataPath = () => {
921
- try {
922
- const path = __require("path");
923
- const os = __require("os");
924
- return path.join(os.homedir(), COMPOSIO_DIR, USER_DATA_FILE_NAME);
925
- } catch (_error) {
926
- return null;
927
- }
928
- };
929
- var getUserDataJson = () => {
930
- try {
931
- const fs = __require("fs");
932
- const data = fs.readFileSync(userDataPath(), "utf8");
933
- return JSON.parse(data);
934
- } catch (_error) {
935
- return {};
936
- }
937
- };
938
- function getSDKConfig(baseUrl, apiKey) {
939
- const userData = getUserDataJson();
940
- const { api_key: apiKeyFromUserConfig, base_url: baseURLFromUserConfig } = userData;
941
- const baseURLParsed = baseUrl || getEnvVariable("COMPOSIO_BASE_URL") || baseURLFromUserConfig || DEFAULT_BASE_URL;
942
- const apiKeyParsed = apiKey || getEnvVariable("COMPOSIO_API_KEY") || apiKeyFromUserConfig || "";
943
- return { baseURL: baseURLParsed, apiKey: apiKeyParsed };
944
- }
1651
+ // package.json
1652
+ var version = "0.1.0-rc.7";
945
1653
 
946
- // src/utils/version.ts
947
- function isNewerVersion(version1, version2) {
948
- const v1 = version1.split(".").map(Number);
949
- const v2 = version2.split(".").map(Number);
950
- for (let i = 0; i < 3; i++) {
951
- if (v1[i] > v2[i]) return true;
952
- if (v1[i] < v2[i]) return false;
953
- }
954
- return false;
955
- }
956
- async function checkForLatestVersionFromNPM() {
957
- try {
958
- const packageName = "composio-core";
959
- const currentVersionFromPackageJson = require_package().version;
960
- const response = await fetch(
961
- `https://registry.npmjs.org/${packageName}/latest`
962
- );
963
- const data = await response.json();
964
- const latestVersion = data.version;
965
- if (isNewerVersion(latestVersion, currentVersionFromPackageJson) && !IS_DEVELOPMENT_OR_CI) {
966
- logger_default.info(
967
- `\u{1F680} Upgrade available! Your composio-core version (${currentVersionFromPackageJson}) is behind. Latest version: ${latestVersion}.`
968
- );
969
- }
970
- } catch (_error) {
971
- }
1654
+ // src/utils/uuid.ts
1655
+ import { v4 as uuidv4 } from "uuid";
1656
+ function getRandomUUID() {
1657
+ return uuidv4();
972
1658
  }
973
1659
 
974
1660
  // src/composio.ts
975
1661
  var Composio = class {
976
1662
  DEFAULT_USER_ID = "default";
977
- FILE_NAME = "core/composio.ts";
978
1663
  /**
979
1664
  * The Composio API client.
980
1665
  * @type {ComposioClient}
@@ -982,15 +1667,10 @@ var Composio = class {
982
1667
  client;
983
1668
  /**
984
1669
  * The configuration for the Composio SDK.
985
- * @type {ComposioConfig<TTool, TToolset>}
1670
+ * @type {ComposioConfig<TToolset>}
986
1671
  */
987
1672
  config;
988
1673
  telemetry;
989
- /**
990
- * Context variables for the Composio SDK.
991
- */
992
- userId;
993
- connectedAccountIds;
994
1674
  /**
995
1675
  * Core models for Composio.
996
1676
  */
@@ -999,7 +1679,9 @@ var Composio = class {
999
1679
  triggers;
1000
1680
  toolset;
1001
1681
  authConfigs;
1682
+ // connected accounts
1002
1683
  connectedAccounts;
1684
+ createConnectedAccount;
1003
1685
  /**
1004
1686
  * @param {Object} config Configuration for the Composio SDK.
1005
1687
  * @param {string} config.apiKey The API key for the Composio SDK.
@@ -1007,7 +1689,7 @@ var Composio = class {
1007
1689
  * @param {string} config.runtime The runtime for the Composio SDK.
1008
1690
  * @param {boolean} config.allowTracking Whether to allow analytics / tracking. Defaults to true.
1009
1691
  * @param {boolean} config.allowTracing Whether to allow tracing. Defaults to true.
1010
- * @param {TS} config.toolset The toolset to use for this Composio instance.
1692
+ * @param {TToolset} config.toolset The toolset to use for this Composio instance.
1011
1693
  */
1012
1694
  constructor(config) {
1013
1695
  const { baseURL: baseURLParsed, apiKey: apiKeyParsed } = getSDKConfig(
@@ -1015,46 +1697,41 @@ var Composio = class {
1015
1697
  config?.apiKey
1016
1698
  );
1017
1699
  if (IS_DEVELOPMENT_OR_CI) {
1018
- logger_default.info(
1019
- `Initializing Composio w API Key: [REDACTED] and baseURL: ${baseURLParsed}`
1020
- );
1021
- }
1022
- if (config.userId && config.connectedAccountIds) {
1023
- logger_default.warn(
1024
- "When both userId and connectedAccountIds are provided, preference will be given to connectedAccountIds"
1025
- );
1700
+ logger_default.info(`Initializing Composio w API Key: [REDACTED] and baseURL: ${baseURLParsed}`);
1026
1701
  }
1027
1702
  this.client = new ComposioClient({
1028
1703
  apiKey: apiKeyParsed,
1029
1704
  baseURL: baseURLParsed
1030
1705
  });
1031
- this.client;
1032
1706
  this.config = {
1033
1707
  ...config,
1034
1708
  allowTracking: config.allowTracking ?? true
1035
1709
  };
1036
- this.userId = config.userId ?? this.DEFAULT_USER_ID;
1037
- this.connectedAccountIds = config.connectedAccountIds ?? {};
1038
- this.toolset = config.toolset ?? new ComposioToolset();
1039
- this.toolset.setClient(this);
1040
- this.tools = new Tools(this.client);
1710
+ this.toolset = config.toolset ?? new OpenAIToolset();
1711
+ this.toolset.setComposio(this);
1712
+ this.tools = new Tools(this.client, this.toolset);
1041
1713
  this.toolkits = new Toolkits(this.client);
1042
1714
  this.triggers = new Triggers(this.client);
1043
1715
  this.authConfigs = new AuthConfigs(this.client);
1044
1716
  this.connectedAccounts = new ConnectedAccounts(this.client);
1717
+ this.createConnectedAccount = this.connectedAccounts.createConnectedAccount;
1045
1718
  if (this.config.allowTracking ?? true) {
1046
- this.initializeTelemetry({
1047
- apiKey: apiKeyParsed ?? "",
1048
- baseUrl: baseURLParsed ?? "",
1049
- frameworkRuntime: "node",
1050
- source: "node",
1051
- // @TODO: get the source
1052
- sessionId: this.userId,
1053
- composioVersion: require_package().version,
1054
- isBrowser: typeof window !== "undefined"
1055
- }, config.telemetryTransport);
1719
+ this.initializeTelemetry(
1720
+ {
1721
+ apiKey: apiKeyParsed ?? "",
1722
+ baseUrl: baseURLParsed ?? "",
1723
+ frameworkRuntime: "node",
1724
+ source: "node",
1725
+ // @TODO: get the source
1726
+ composioVersion: version,
1727
+ isBrowser: typeof window !== "undefined",
1728
+ sessionId: getRandomUUID()
1729
+ // @TODO: get the session id
1730
+ },
1731
+ config.telemetryTransport
1732
+ );
1056
1733
  }
1057
- checkForLatestVersionFromNPM();
1734
+ checkForLatestVersionFromNPM(version);
1058
1735
  }
1059
1736
  /**
1060
1737
  * Initialize the instrumentations and telemetry for the Composio SDK.
@@ -1071,77 +1748,103 @@ var Composio = class {
1071
1748
  this.telemetry.instrumentTelemetry(this.connectedAccounts);
1072
1749
  this.telemetry.instrumentTelemetry(this.toolset);
1073
1750
  }
1074
- /**
1075
- * Get the connected account id for the given app name.
1076
- * @param appName - The name of the app.
1077
- * @returns {string | undefined} The connected account id for the given app name.
1078
- */
1079
- getConnectedAccountId(appName) {
1080
- return this.connectedAccountIds?.[appName];
1081
- }
1082
1751
  /**
1083
1752
  * Get the Composio SDK client.
1084
1753
  * @returns {ComposioClient} The Composio API client.
1085
1754
  */
1086
1755
  getClient() {
1087
1756
  if (!this.client) {
1088
- throw new Error(
1089
- "Composio client is not initialized. Please initialize it first."
1090
- );
1757
+ throw new Error("Composio client is not initialized. Please initialize it first.");
1091
1758
  }
1092
1759
  return this.client;
1093
1760
  }
1094
1761
  /**
1095
- * Generic function to get all the tools
1096
- * @returns {Promise<ReturnType<TToolset["getTool"]>>} Promise with list of tools
1762
+ * Fetch all the tools from Composio.
1763
+ * @param {ToolListParams} params Parameters to fetch the tools.
1764
+ * @param {ToolsetOptions<TToolset>} modifiers Modifiers to apply to the tools.
1765
+ * @returns {Promise<ReturnType<TToolset['getTools']>>} The tools from the toolset.
1097
1766
  */
1098
- async getTool(slug) {
1099
- return this.toolset.getTool(slug);
1767
+ getTools(userId, filters, modifiers) {
1768
+ return this.tools.get(userId, filters, modifiers);
1100
1769
  }
1101
1770
  /**
1102
- * Generic function to get all the tools
1103
- * @param query - Query parameters for the tools
1104
- * @returns {Promise<ReturnType<TToolset["getTools">} Promise with list/records of tools
1771
+ * Fetch a tool from Composio by its slug.
1772
+ * @param {string} slug slug of the tool
1773
+ * @param {ToolsetOptions<TToolset>} modifiers to be applied to the tool
1774
+ * @returns {Promise<ReturnType<TToolset['getToolBySlug']>>} The tool from the toolset.
1105
1775
  */
1106
- async getTools(query) {
1107
- return this.toolset.getTools(query);
1776
+ getToolBySlug(userId, slug, modifiers) {
1777
+ return this.tools.get(userId, slug, modifiers);
1778
+ }
1779
+ };
1780
+
1781
+ // src/toolset/ComposioToolset.ts
1782
+ var ComposioToolset = class extends BaseNonAgenticToolset {
1783
+ FILE_NAME = "core/toolset/ComposioToolset.ts";
1784
+ constructor() {
1785
+ super();
1786
+ }
1787
+ wrapTool = (tool) => {
1788
+ return tool;
1789
+ };
1790
+ async getTools(userId, params, options) {
1791
+ const tools = await this.getComposio().tools.getComposioTools(
1792
+ userId,
1793
+ params,
1794
+ options?.modifyToolSchema
1795
+ );
1796
+ return tools?.map((tool) => this.wrapTool(tool)) ?? [];
1797
+ }
1798
+ async getToolBySlug(userId, slug, modifiers) {
1799
+ const tool = await this.getComposio().tools.getComposioToolBySlug(
1800
+ userId,
1801
+ slug,
1802
+ modifiers?.modifyToolSchema
1803
+ );
1804
+ return this.wrapTool(tool);
1805
+ }
1806
+ async test() {
1108
1807
  }
1109
1808
  };
1110
1809
 
1810
+ // src/telemetry/TelemetryTransport.ts
1811
+ var BaseTelemetryTransport = class {
1812
+ };
1813
+
1111
1814
  // src/utils/jsonSchema.ts
1112
- import z from "zod";
1815
+ import { z as z3 } from "zod";
1113
1816
  function jsonSchemaPropertiesToTSTypes(value) {
1114
1817
  if (!value.type) {
1115
- return z.object({});
1818
+ return z3.object({});
1116
1819
  }
1117
1820
  let zodType;
1118
1821
  switch (value.type) {
1119
1822
  case "string":
1120
- zodType = z.string().describe(
1823
+ zodType = z3.string().describe(
1121
1824
  (value.description || "") + (value.examples ? `
1122
1825
  Examples: ${value.examples.join(", ")}` : "")
1123
1826
  );
1124
1827
  break;
1125
1828
  case "number":
1126
- zodType = z.number().describe(
1829
+ zodType = z3.number().describe(
1127
1830
  (value.description || "") + (value.examples ? `
1128
1831
  Examples: ${value.examples.join(", ")}` : "")
1129
1832
  );
1130
1833
  break;
1131
1834
  case "integer":
1132
- zodType = z.number().int().describe(
1835
+ zodType = z3.number().int().describe(
1133
1836
  (value.description || "") + (value.examples ? `
1134
1837
  Examples: ${value.examples.join(", ")}` : "")
1135
1838
  );
1136
1839
  break;
1137
1840
  case "boolean":
1138
- zodType = z.boolean().describe(
1841
+ zodType = z3.boolean().describe(
1139
1842
  (value.description || "") + (value.examples ? `
1140
1843
  Examples: ${value.examples.join(", ")}` : "")
1141
1844
  );
1142
1845
  break;
1143
1846
  case "array":
1144
- zodType = z.array(
1847
+ zodType = z3.array(
1145
1848
  jsonSchemaPropertiesToTSTypes(
1146
1849
  value.items
1147
1850
  )
@@ -1157,7 +1860,7 @@ Examples: ${value.examples.join(", ")}` : "")
1157
1860
  );
1158
1861
  break;
1159
1862
  case "null":
1160
- zodType = z.null().describe(value.description || "");
1863
+ zodType = z3.null().describe(value.description || "");
1161
1864
  break;
1162
1865
  default:
1163
1866
  throw new Error(`Unsupported JSON schema type: ${value.type}`);
@@ -1168,7 +1871,7 @@ function jsonSchemaToModel(jsonSchema) {
1168
1871
  const properties = jsonSchema.properties;
1169
1872
  const requiredFields = jsonSchema.required || [];
1170
1873
  if (!properties) {
1171
- return z.object({});
1874
+ return z3.object({});
1172
1875
  }
1173
1876
  const zodSchema = {};
1174
1877
  for (const [key, _] of Object.entries(properties)) {
@@ -1180,7 +1883,7 @@ function jsonSchemaToModel(jsonSchema) {
1180
1883
  schema
1181
1884
  )
1182
1885
  );
1183
- zodType = z.union(anyOfTypes).describe(
1886
+ zodType = z3.union(anyOfTypes).describe(
1184
1887
  (value.description || "") + (value.examples ? `
1185
1888
  Examples: ${value.examples.join(", ")}` : "")
1186
1889
  );
@@ -1190,12 +1893,9 @@ Examples: ${value.examples.join(", ")}` : "")
1190
1893
  schema
1191
1894
  )
1192
1895
  );
1193
- zodType = z.intersection(
1896
+ zodType = z3.intersection(
1194
1897
  allOfTypes[0],
1195
- allOfTypes.slice(1).reduce(
1196
- (acc, schema) => acc.and(schema),
1197
- allOfTypes[0]
1198
- )
1898
+ allOfTypes.slice(1).reduce((acc, schema) => acc.and(schema), allOfTypes[0])
1199
1899
  ).describe(
1200
1900
  (value.description || "") + (value.examples ? `
1201
1901
  Examples: ${value.examples.join(", ")}` : "")
@@ -1217,206 +1917,15 @@ Examples: ${value.examples.join(", ")}` : "")
1217
1917
  zodSchema[key] = zodType.optional();
1218
1918
  }
1219
1919
  }
1220
- return z.object(zodSchema);
1920
+ return z3.object(zodSchema);
1221
1921
  }
1222
-
1223
- // src/telemetry/TelemetryTransport.ts
1224
- var BaseTelemetryTransport = class {
1225
- };
1226
-
1227
- // src/toolset/OpenAIToolset.ts
1228
- var OpenAIToolset = class extends BaseComposioToolset {
1229
- static FRAMEWORK_NAME = "openai";
1230
- FILE_NAME = "toolsets/openai/src/index.ts";
1231
- /**
1232
- * Absract method to wrap a tool in the toolset.
1233
- * This method is implemented by the toolset.
1234
- * @param tool - The tool to wrap.
1235
- * @returns The wrapped tool.
1236
- */
1237
- _wrapTool = (tool) => {
1238
- const formattedSchema = {
1239
- name: tool.slug,
1240
- description: tool.description,
1241
- parameters: tool.input_parameters
1242
- };
1243
- return {
1244
- type: "function",
1245
- function: formattedSchema
1246
- };
1247
- };
1248
- /**
1249
- * Get all the tools from the Composio in OpenAI format.
1250
- * @param params - The parameters for the tool list.
1251
- * @returns The tools.
1252
- */
1253
- async getTools(params) {
1254
- const tools = await this.client?.tools.list(params);
1255
- return tools?.items.map((tool) => this._wrapTool(tool)) ?? [];
1256
- }
1257
- /**
1258
- * Execute a tool call.
1259
- * @param {OpenAI.ChatCompletionMessageToolCall} tool - The tool to execute.
1260
- * @param {string} userId - The user id.
1261
- * @returns {Promise<string>} The result of the tool call.
1262
- */
1263
- async executeToolCall(tool, userId) {
1264
- if (!this.client) {
1265
- throw new Error("Client not set");
1266
- }
1267
- const toolSchema = await this.client.tools.get(tool.function.name);
1268
- const appName = toolSchema?.toolkit?.name.toLowerCase();
1269
- const connectedAccountId = this.client.getConnectedAccountId(appName);
1270
- const payload = {
1271
- entity_id: userId ?? this.client.userId,
1272
- connected_account_id: connectedAccountId,
1273
- arguments: JSON.parse(tool.function.arguments)
1274
- };
1275
- const results = await this.client.tools.execute(toolSchema.slug, payload);
1276
- return JSON.stringify(results);
1277
- }
1278
- /**
1279
- * Handle the tool call from the assistant.
1280
- *
1281
- * @param {OpenAI.ChatCompletion} chatCompletion - The chat completion object.
1282
- * @param {string} userId - The user id.
1283
- * @returns {Promise<string[]>} The results of the tool call.
1284
- */
1285
- async handleToolCall(chatCompletion, userId) {
1286
- const outputs = [];
1287
- for (const message of chatCompletion.choices) {
1288
- if (message.message.tool_calls) {
1289
- outputs.push(
1290
- await this.executeToolCall(message.message.tool_calls[0], userId)
1291
- );
1292
- }
1293
- }
1294
- return outputs;
1295
- }
1296
- /**
1297
- * Handles all the tool calls from the assistant.
1298
- *
1299
- * @param {OpenAI.Beta.Threads.Run} run - The run object.
1300
- * @param {string} userId - The user id.
1301
- * @returns {Promise<OpenAI.Beta.Threads.Runs.RunSubmitToolOutputsParams.ToolOutput[]>} The tool outputs.
1302
- */
1303
- async handleAssistantMessage(run, userId) {
1304
- const tool_calls = run.required_action?.submit_tool_outputs?.tool_calls || [];
1305
- const tool_outputs = await Promise.all(
1306
- tool_calls.map(async (tool_call) => {
1307
- logger_default.debug(`Executing tool call: ${tool_call.id}`);
1308
- const tool_response = await this.executeToolCall(
1309
- tool_call,
1310
- userId
1311
- );
1312
- logger_default.debug(`Tool call ${tool_call.id} executed with response: ${tool_response}`);
1313
- return {
1314
- tool_call_id: tool_call.id,
1315
- output: JSON.stringify(tool_response)
1316
- };
1317
- })
1318
- );
1319
- return tool_outputs;
1320
- }
1321
- /**
1322
- * Waits for the assistant stream and handles the tool calls.
1323
- *
1324
- * @param {OpenAI} client - The OpenAI client.
1325
- * @param {Stream<OpenAI.Beta.Assistants.AssistantStreamEvent>} runStream - The run stream.
1326
- * @param {OpenAI.Beta.Threads.Thread} thread - The thread object.
1327
- * @param {string} userId - The user id.
1328
- * @returns {AsyncGenerator<OpenAI.Beta.Assistants.AssistantStreamEvent, void, unknown>} The run stream.
1329
- */
1330
- async *waitAndHandleAssistantStreamToolCalls(client, runStream, thread, userId) {
1331
- const defaultUserId = this.client?.userId;
1332
- let runId = null;
1333
- for await (const event of runStream) {
1334
- yield event;
1335
- if (event.event === "thread.run.created") {
1336
- const { id } = event.data;
1337
- runId = id;
1338
- }
1339
- if (!runId) {
1340
- continue;
1341
- }
1342
- if (event.event === "thread.run.requires_action") {
1343
- const toolOutputs = await this.handleAssistantMessage(
1344
- event.data,
1345
- userId ?? defaultUserId
1346
- );
1347
- await client.beta.threads.runs.submitToolOutputs(thread.id, runId, {
1348
- tool_outputs: toolOutputs
1349
- });
1350
- }
1351
- if ([
1352
- "thread.run.completed",
1353
- "thread.run.failed",
1354
- "thread.run.cancelled",
1355
- "thread.run.expired"
1356
- ].includes(event.event)) {
1357
- break;
1358
- }
1359
- }
1360
- if (!runId) {
1361
- throw new Error("No run ID found");
1362
- }
1363
- let finalRun = await client.beta.threads.runs.retrieve(thread.id, runId);
1364
- while (["queued", "in_progress", "requires_action"].includes(finalRun.status)) {
1365
- if (finalRun.status === "requires_action") {
1366
- const toolOutputs = await this.handleAssistantMessage(
1367
- finalRun,
1368
- userId ?? defaultUserId
1369
- );
1370
- finalRun = await client.beta.threads.runs.submitToolOutputs(
1371
- thread.id,
1372
- runId,
1373
- {
1374
- tool_outputs: toolOutputs
1375
- }
1376
- );
1377
- } else {
1378
- finalRun = await client.beta.threads.runs.retrieve(thread.id, runId);
1379
- await new Promise((resolve) => setTimeout(resolve, 500));
1380
- }
1381
- }
1382
- }
1383
- /**
1384
- * Waits for the assistant tool calls and handles them.
1385
- *
1386
- * @param {OpenAI} client - The OpenAI client.
1387
- * @param {OpenAI.Beta.Threads.Run} run - The run object.
1388
- * @param {OpenAI.Beta.Threads.Thread} thread - The thread object.
1389
- * @param {string} userId - The user id.
1390
- * @returns {Promise<OpenAI.Beta.Threads.Run>} The run object.
1391
- */
1392
- async waitAndHandleAssistantToolCalls(client, run, thread, userId) {
1393
- const defaultUserId = this.client?.userId;
1394
- while (["queued", "in_progress", "requires_action"].includes(run.status)) {
1395
- const tool_outputs = await this.handleAssistantMessage(
1396
- run,
1397
- userId ?? defaultUserId
1398
- );
1399
- if (run.status === "requires_action") {
1400
- run = await client.beta.threads.runs.submitToolOutputs(
1401
- thread.id,
1402
- run.id,
1403
- {
1404
- tool_outputs
1405
- }
1406
- );
1407
- } else {
1408
- run = await client.beta.threads.runs.retrieve(thread.id, run.id);
1409
- await new Promise((resolve) => setTimeout(resolve, 500));
1410
- }
1411
- }
1412
- return run;
1413
- }
1414
- };
1415
1922
  export {
1416
- BaseComposioToolset,
1923
+ BaseAgenticToolset,
1924
+ BaseNonAgenticToolset,
1417
1925
  BaseTelemetryTransport,
1418
1926
  Composio,
1419
1927
  ComposioToolset,
1420
1928
  OpenAIToolset,
1929
+ ToolListParamsSchema,
1421
1930
  jsonSchemaToModel
1422
1931
  };