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