@composio/core 0.1.0-rc.5 → 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
@@ -30,11 +30,13 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
30
30
  // src/index.ts
31
31
  var index_exports = {};
32
32
  __export(index_exports, {
33
- BaseComposioToolset: () => BaseComposioToolset,
33
+ BaseAgenticToolset: () => BaseAgenticToolset,
34
+ BaseNonAgenticToolset: () => BaseNonAgenticToolset,
34
35
  BaseTelemetryTransport: () => BaseTelemetryTransport,
35
36
  Composio: () => Composio,
36
37
  ComposioToolset: () => ComposioToolset,
37
38
  OpenAIToolset: () => OpenAIToolset,
39
+ ToolListParamsSchema: () => ToolListParamsSchema,
38
40
  jsonSchemaToModel: () => jsonSchemaToModel
39
41
  });
40
42
  module.exports = __toCommonJS(index_exports);
@@ -42,105 +44,197 @@ module.exports = __toCommonJS(index_exports);
42
44
  // src/composio.ts
43
45
  var import_client = __toESM(require("@composio/client"), 1);
44
46
 
45
- // src/models/Tools.ts
46
- var Tools = class {
47
- 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 {
48
108
  client;
109
+ customToolsRegistry = /* @__PURE__ */ new Map();
49
110
  constructor(client) {
50
111
  this.client = client;
51
112
  }
52
113
  /**
53
- * Lists all tools available in the Composio SDK.
54
- * This method fetches the tools from the Composio API and wraps them using the toolset.
55
- * @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
56
118
  */
57
- async list(query = {}) {
58
- const tools = await this.client.tools.list(query);
59
- if (!tools) {
60
- return {
61
- items: [],
62
- next_cursor: null,
63
- total_pages: 0
64
- };
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");
65
123
  }
66
- return tools;
67
- }
68
- /**
69
- * Retrieves a tool by its Slug.
70
- * @param slug The ID of the tool to be retrieved
71
- * @returns {Promise<Tool>} The tool
72
- */
73
- async get(slug) {
74
- return this.client.tools.retrieve(slug);
75
- }
76
- /**
77
- * Exectes a given tool with the provided parameters.
78
- *
79
- * This method calls the Composio API to execute the tool and returns the response.
80
- *
81
- * @param {string} slug - The ID of the tool to be executed
82
- * @param {ToolExecuteParams} body - The parameters to be passed to the tool
83
- * @returns {Promise<ToolExecuteResponse>} - The response from the tool execution
84
- */
85
- async execute(slug, body) {
86
- return this.client.tools.execute(slug, body);
87
- }
88
- /**
89
- * Fetches the list of all available tools in the Composio SDK.
90
- *
91
- * This method is mostly used by the CLI to get the list of tools.
92
- * No filtering is done on the tools, the list is cached in the backend, no further optimization is required.
93
- * @returns {string} - The list of all available tools as a string
94
- */
95
- async getToolsEnum() {
96
- 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;
97
153
  }
98
154
  /**
99
- * Fetches the input parameters for a given tool.
100
- *
101
- * This method is used to get the input parameters for a tool before executing it.
102
- *
103
- * @param {string} slug - The ID of the tool to find input for
104
- * @param {ToolGetInputParams} body - The parameters to be passed to the tool
105
- * @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
106
158
  */
107
- async getInput(slug, body) {
108
- return this.client.tools.getInput(slug, body);
109
- }
110
- };
111
-
112
- // src/models/Toolkits.ts
113
- var Toolkits = class {
114
- FILE_NAME = "core/models/Toolkits.ts";
115
- client;
116
- constructor(client) {
117
- 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;
118
172
  }
119
173
  /**
120
- * List all toolkits available in the Composio SDK.
121
- * This method fetches the toolkits from the Composio API.
122
- * @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
123
177
  */
124
- async list(query, options) {
125
- 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;
126
184
  }
127
185
  /**
128
- * Fetches a toolkit by its Slug.
129
- * This method retrieves the toolkit from the Composio API.
130
- * @param slug - The ID of the toolkit to be retrieved
131
- * @param options - Request options
132
- * @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
133
190
  */
134
- async get(slug, options) {
135
- 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];
136
200
  }
137
201
  /**
138
- * Fetches all categories available in the Composio SDK
139
- *
140
- * @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
141
207
  */
142
- async listCategories(options) {
143
- 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
+ );
144
238
  }
145
239
  };
146
240
 
@@ -218,6 +312,306 @@ var Logger = class {
218
312
  var logger = new Logger();
219
313
  var logger_default = logger;
220
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
+
221
615
  // src/utils/pusher.ts
222
616
  var PUSHER_KEY = process.env.CLIENT_PUSHER_KEY || "ff9f18c208855d77a152";
223
617
  var PUSHER_CLUSTER = "mt1";
@@ -311,7 +705,6 @@ var PusherUtils = class _PusherUtils {
311
705
 
312
706
  // src/models/Session.ts
313
707
  var Session = class {
314
- FILE_NAME = "core/models/Session.ts";
315
708
  client;
316
709
  constructor(client) {
317
710
  this.client = client;
@@ -327,7 +720,6 @@ var Session = class {
327
720
 
328
721
  // src/models/Triggers.ts
329
722
  var Triggers = class {
330
- FILE_NAME = "core/models/Triggers.ts";
331
723
  client;
332
724
  constructor(client) {
333
725
  this.client = client;
@@ -461,68 +853,21 @@ var Triggers = class {
461
853
  }
462
854
  };
463
855
 
464
- // src/toolset/BaseToolset.ts
465
- var BaseComposioToolset = class {
856
+ // src/models/AuthConfigs.ts
857
+ var AuthConfigs = class {
858
+ FILE_NAME = "core/models/AuthConfigs.ts";
466
859
  client;
467
- DEFAULT_ENTITY_ID = "default";
468
- /**
469
- * Set the client for the toolset. This is automatically done by the Composio class.
470
- * @param client - The Composio client.
471
- */
472
- setClient(client) {
860
+ constructor(client) {
473
861
  this.client = client;
474
862
  }
475
863
  /**
476
- * Get a tool from the client.
477
- * @param slug - The slug of the tool.
478
- * @returns The tool.
864
+ * List all auth configs
865
+ * @param {AuthConfigListParams} query - Query parameters for filtering auth configs
866
+ * @param {RequestOptions} options - Request options
867
+ * @returns {Promise<AuthConfigListResponse>} List of auth configs
479
868
  */
480
- async getTool(slug) {
481
- const tool = await this.client?.tools.get(slug);
482
- return this._wrapTool(tool);
483
- }
484
- /**
485
- * Ensure the client is initialized.
486
- * This is automatically done by the Composio class.
487
- */
488
- ensureClient() {
489
- if (!this.client) {
490
- throw new Error(
491
- "Client not initialized. Make sure the toolset is properly initialized with Composio."
492
- );
493
- }
494
- }
495
- };
496
-
497
- // src/toolset/ComposioToolset.ts
498
- var ComposioToolset = class extends BaseComposioToolset {
499
- FILE_NAME = "core/toolset/ComposioToolset.ts";
500
- _wrapTool = (tool) => {
501
- return tool;
502
- };
503
- async getTools(params) {
504
- const tools = await this.client?.tools.list(params);
505
- return tools?.items.map((tool) => this._wrapTool(tool)) ?? [];
506
- }
507
- async test() {
508
- }
509
- };
510
-
511
- // src/models/AuthConfigs.ts
512
- var AuthConfigs = class {
513
- FILE_NAME = "core/models/AuthConfigs.ts";
514
- client;
515
- constructor(client) {
516
- this.client = client;
517
- }
518
- /**
519
- * List all auth configs
520
- * @param {AuthConfigListParams} query - Query parameters for filtering auth configs
521
- * @param {RequestOptions} options - Request options
522
- * @returns {Promise<AuthConfigListResponse>} List of auth configs
523
- */
524
- async list(query, options) {
525
- return this.client.authConfigs.list(query, options);
869
+ async list(query, options) {
870
+ return this.client.authConfigs.list(query, options);
526
871
  }
527
872
  /**
528
873
  * Create a new auth config
@@ -591,9 +936,161 @@ var AuthConfigs = class {
591
936
  }
592
937
  };
593
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
+
594
1092
  // src/models/ConnectedAccounts.ts
595
1093
  var ConnectedAccounts = class {
596
- FILE_NAME = "core/models/ConnectedAccounts.ts";
597
1094
  client;
598
1095
  constructor(client) {
599
1096
  this.client = client;
@@ -671,6 +1168,27 @@ var ConnectedAccounts = class {
671
1168
  async disable(nanoid, options) {
672
1169
  return this.client.connectedAccounts.updateStatus(nanoid, { enabled: false }, options);
673
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
+ }
674
1192
  };
675
1193
 
676
1194
  // src/types/telemetry.types.ts
@@ -847,13 +1365,14 @@ var Telemetry = class {
847
1365
  const descriptor = Object.getOwnPropertyDescriptor(proto, key);
848
1366
  return key !== "constructor" && descriptor && typeof descriptor.value === "function" && descriptor.value.constructor.name === "AsyncFunction";
849
1367
  });
1368
+ const instrumentedClassName = instance.constructor?.name || fileName || "unknown";
850
1369
  for (const name of methodNames) {
851
1370
  const originalMethod = instance[name];
852
1371
  instance[name] = async (...args) => {
853
1372
  const telemetryPayload = {
854
1373
  eventName: TELEMETRY_EVENTS.SDK_METHOD_INVOKED,
855
1374
  data: {
856
- fileName: instance.FILE_NAME ?? fileName ?? "unknown",
1375
+ fileName: instrumentedClassName,
857
1376
  method: name,
858
1377
  params: args
859
1378
  },
@@ -866,7 +1385,7 @@ var Telemetry = class {
866
1385
  const telemetryPayload2 = {
867
1386
  eventName: TELEMETRY_EVENTS.SDK_METHOD_ERROR,
868
1387
  data: {
869
- fileName: instance.FILE_NAME ?? fileName ?? "unknown",
1388
+ fileName: instrumentedClassName,
870
1389
  method: name,
871
1390
  params: args,
872
1391
  error
@@ -928,9 +1447,6 @@ function getSDKConfig(baseUrl, apiKey) {
928
1447
  return { baseURL: baseURLParsed, apiKey: apiKeyParsed };
929
1448
  }
930
1449
 
931
- // package.json
932
- var version = "0.1.0-rc.5";
933
-
934
1450
  // src/utils/version.ts
935
1451
  function isNewerVersion(version1, version2) {
936
1452
  const v1 = version1.split(".").map(Number);
@@ -941,10 +1457,10 @@ function isNewerVersion(version1, version2) {
941
1457
  }
942
1458
  return false;
943
1459
  }
944
- async function checkForLatestVersionFromNPM() {
1460
+ async function checkForLatestVersionFromNPM(currentVersion) {
945
1461
  try {
946
1462
  const packageName = "composio-core";
947
- const currentVersionFromPackageJson = version;
1463
+ const currentVersionFromPackageJson = currentVersion;
948
1464
  const response = await fetch(`https://registry.npmjs.org/${packageName}/latest`);
949
1465
  const data = await response.json();
950
1466
  const latestVersion = data.version;
@@ -957,10 +1473,229 @@ async function checkForLatestVersionFromNPM() {
957
1473
  }
958
1474
  }
959
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
+ }
1661
+ }
1662
+ /**
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.
1670
+ */
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
+ }
1682
+ }
1683
+ return run;
1684
+ }
1685
+ };
1686
+
1687
+ // package.json
1688
+ var version = "0.1.0-rc.7";
1689
+
1690
+ // src/utils/uuid.ts
1691
+ var import_uuid = require("uuid");
1692
+ function getRandomUUID() {
1693
+ return (0, import_uuid.v4)();
1694
+ }
1695
+
960
1696
  // src/composio.ts
961
1697
  var Composio = class {
962
1698
  DEFAULT_USER_ID = "default";
963
- FILE_NAME = "core/composio.ts";
964
1699
  /**
965
1700
  * The Composio API client.
966
1701
  * @type {ComposioClient}
@@ -968,15 +1703,10 @@ var Composio = class {
968
1703
  client;
969
1704
  /**
970
1705
  * The configuration for the Composio SDK.
971
- * @type {ComposioConfig<TTool, TToolset>}
1706
+ * @type {ComposioConfig<TToolset>}
972
1707
  */
973
1708
  config;
974
1709
  telemetry;
975
- /**
976
- * Context variables for the Composio SDK.
977
- */
978
- userId;
979
- connectedAccountIds;
980
1710
  /**
981
1711
  * Core models for Composio.
982
1712
  */
@@ -985,7 +1715,9 @@ var Composio = class {
985
1715
  triggers;
986
1716
  toolset;
987
1717
  authConfigs;
1718
+ // connected accounts
988
1719
  connectedAccounts;
1720
+ createConnectedAccount;
989
1721
  /**
990
1722
  * @param {Object} config Configuration for the Composio SDK.
991
1723
  * @param {string} config.apiKey The API key for the Composio SDK.
@@ -993,7 +1725,7 @@ var Composio = class {
993
1725
  * @param {string} config.runtime The runtime for the Composio SDK.
994
1726
  * @param {boolean} config.allowTracking Whether to allow analytics / tracking. Defaults to true.
995
1727
  * @param {boolean} config.allowTracing Whether to allow tracing. Defaults to true.
996
- * @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.
997
1729
  */
998
1730
  constructor(config) {
999
1731
  const { baseURL: baseURLParsed, apiKey: apiKeyParsed } = getSDKConfig(
@@ -1003,11 +1735,6 @@ var Composio = class {
1003
1735
  if (IS_DEVELOPMENT_OR_CI) {
1004
1736
  logger_default.info(`Initializing Composio w API Key: [REDACTED] and baseURL: ${baseURLParsed}`);
1005
1737
  }
1006
- if (config.userId && config.connectedAccountIds) {
1007
- logger_default.warn(
1008
- "When both userId and connectedAccountIds are provided, preference will be given to connectedAccountIds"
1009
- );
1010
- }
1011
1738
  this.client = new import_client.default({
1012
1739
  apiKey: apiKeyParsed,
1013
1740
  baseURL: baseURLParsed
@@ -1016,15 +1743,14 @@ var Composio = class {
1016
1743
  ...config,
1017
1744
  allowTracking: config.allowTracking ?? true
1018
1745
  };
1019
- this.userId = config.userId ?? this.DEFAULT_USER_ID;
1020
- this.connectedAccountIds = config.connectedAccountIds ?? {};
1021
- this.toolset = config.toolset ?? new ComposioToolset();
1022
- this.toolset.setClient(this);
1023
- 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);
1024
1749
  this.toolkits = new Toolkits(this.client);
1025
1750
  this.triggers = new Triggers(this.client);
1026
1751
  this.authConfigs = new AuthConfigs(this.client);
1027
1752
  this.connectedAccounts = new ConnectedAccounts(this.client);
1753
+ this.createConnectedAccount = this.connectedAccounts.createConnectedAccount;
1028
1754
  if (this.config.allowTracking ?? true) {
1029
1755
  this.initializeTelemetry(
1030
1756
  {
@@ -1033,14 +1759,15 @@ var Composio = class {
1033
1759
  frameworkRuntime: "node",
1034
1760
  source: "node",
1035
1761
  // @TODO: get the source
1036
- sessionId: this.userId,
1037
1762
  composioVersion: version,
1038
- isBrowser: typeof window !== "undefined"
1763
+ isBrowser: typeof window !== "undefined",
1764
+ sessionId: getRandomUUID()
1765
+ // @TODO: get the session id
1039
1766
  },
1040
1767
  config.telemetryTransport
1041
1768
  );
1042
1769
  }
1043
- checkForLatestVersionFromNPM();
1770
+ checkForLatestVersionFromNPM(version);
1044
1771
  }
1045
1772
  /**
1046
1773
  * Initialize the instrumentations and telemetry for the Composio SDK.
@@ -1057,14 +1784,6 @@ var Composio = class {
1057
1784
  this.telemetry.instrumentTelemetry(this.connectedAccounts);
1058
1785
  this.telemetry.instrumentTelemetry(this.toolset);
1059
1786
  }
1060
- /**
1061
- * Get the connected account id for the given app name.
1062
- * @param appName - The name of the app.
1063
- * @returns {string | undefined} The connected account id for the given app name.
1064
- */
1065
- getConnectedAccountId(appName) {
1066
- return this.connectedAccountIds?.[appName];
1067
- }
1068
1787
  /**
1069
1788
  * Get the Composio SDK client.
1070
1789
  * @returns {ComposioClient} The Composio API client.
@@ -1076,56 +1795,92 @@ var Composio = class {
1076
1795
  return this.client;
1077
1796
  }
1078
1797
  /**
1079
- * Generic function to get all the tools
1080
- * @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.
1081
1802
  */
1082
- async getTool(slug) {
1083
- return this.toolset.getTool(slug);
1803
+ getTools(userId, filters, modifiers) {
1804
+ return this.tools.get(userId, filters, modifiers);
1084
1805
  }
1085
1806
  /**
1086
- * Generic function to get all the tools
1087
- * @param query - Query parameters for the tools
1088
- * @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.
1089
1811
  */
1090
- async getTools(query) {
1091
- return this.toolset.getTools(query);
1812
+ getToolBySlug(userId, slug, modifiers) {
1813
+ return this.tools.get(userId, slug, modifiers);
1092
1814
  }
1093
1815
  };
1094
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() {
1843
+ }
1844
+ };
1845
+
1846
+ // src/telemetry/TelemetryTransport.ts
1847
+ var BaseTelemetryTransport = class {
1848
+ };
1849
+
1095
1850
  // src/utils/jsonSchema.ts
1096
- var import_zod = require("zod");
1851
+ var import_zod3 = require("zod");
1097
1852
  function jsonSchemaPropertiesToTSTypes(value) {
1098
1853
  if (!value.type) {
1099
- return import_zod.z.object({});
1854
+ return import_zod3.z.object({});
1100
1855
  }
1101
1856
  let zodType;
1102
1857
  switch (value.type) {
1103
1858
  case "string":
1104
- zodType = import_zod.z.string().describe(
1859
+ zodType = import_zod3.z.string().describe(
1105
1860
  (value.description || "") + (value.examples ? `
1106
1861
  Examples: ${value.examples.join(", ")}` : "")
1107
1862
  );
1108
1863
  break;
1109
1864
  case "number":
1110
- zodType = import_zod.z.number().describe(
1865
+ zodType = import_zod3.z.number().describe(
1111
1866
  (value.description || "") + (value.examples ? `
1112
1867
  Examples: ${value.examples.join(", ")}` : "")
1113
1868
  );
1114
1869
  break;
1115
1870
  case "integer":
1116
- zodType = import_zod.z.number().int().describe(
1871
+ zodType = import_zod3.z.number().int().describe(
1117
1872
  (value.description || "") + (value.examples ? `
1118
1873
  Examples: ${value.examples.join(", ")}` : "")
1119
1874
  );
1120
1875
  break;
1121
1876
  case "boolean":
1122
- zodType = import_zod.z.boolean().describe(
1877
+ zodType = import_zod3.z.boolean().describe(
1123
1878
  (value.description || "") + (value.examples ? `
1124
1879
  Examples: ${value.examples.join(", ")}` : "")
1125
1880
  );
1126
1881
  break;
1127
1882
  case "array":
1128
- zodType = import_zod.z.array(
1883
+ zodType = import_zod3.z.array(
1129
1884
  jsonSchemaPropertiesToTSTypes(
1130
1885
  value.items
1131
1886
  )
@@ -1141,7 +1896,7 @@ Examples: ${value.examples.join(", ")}` : "")
1141
1896
  );
1142
1897
  break;
1143
1898
  case "null":
1144
- zodType = import_zod.z.null().describe(value.description || "");
1899
+ zodType = import_zod3.z.null().describe(value.description || "");
1145
1900
  break;
1146
1901
  default:
1147
1902
  throw new Error(`Unsupported JSON schema type: ${value.type}`);
@@ -1152,7 +1907,7 @@ function jsonSchemaToModel(jsonSchema) {
1152
1907
  const properties = jsonSchema.properties;
1153
1908
  const requiredFields = jsonSchema.required || [];
1154
1909
  if (!properties) {
1155
- return import_zod.z.object({});
1910
+ return import_zod3.z.object({});
1156
1911
  }
1157
1912
  const zodSchema = {};
1158
1913
  for (const [key, _] of Object.entries(properties)) {
@@ -1164,7 +1919,7 @@ function jsonSchemaToModel(jsonSchema) {
1164
1919
  schema
1165
1920
  )
1166
1921
  );
1167
- zodType = import_zod.z.union(anyOfTypes).describe(
1922
+ zodType = import_zod3.z.union(anyOfTypes).describe(
1168
1923
  (value.description || "") + (value.examples ? `
1169
1924
  Examples: ${value.examples.join(", ")}` : "")
1170
1925
  );
@@ -1174,7 +1929,7 @@ Examples: ${value.examples.join(", ")}` : "")
1174
1929
  schema
1175
1930
  )
1176
1931
  );
1177
- zodType = import_zod.z.intersection(
1932
+ zodType = import_zod3.z.intersection(
1178
1933
  allOfTypes[0],
1179
1934
  allOfTypes.slice(1).reduce((acc, schema) => acc.and(schema), allOfTypes[0])
1180
1935
  ).describe(
@@ -1198,207 +1953,16 @@ Examples: ${value.examples.join(", ")}` : "")
1198
1953
  zodSchema[key] = zodType.optional();
1199
1954
  }
1200
1955
  }
1201
- return import_zod.z.object(zodSchema);
1956
+ return import_zod3.z.object(zodSchema);
1202
1957
  }
1203
-
1204
- // src/telemetry/TelemetryTransport.ts
1205
- var BaseTelemetryTransport = class {
1206
- };
1207
-
1208
- // src/toolset/OpenAIToolset.ts
1209
- var OpenAIToolset = class extends BaseComposioToolset {
1210
- static FRAMEWORK_NAME = "openai";
1211
- FILE_NAME = "toolsets/openai/src/index.ts";
1212
- /**
1213
- * Absract method to wrap a tool in the toolset.
1214
- * This method is implemented by the toolset.
1215
- * @param tool - The tool to wrap.
1216
- * @returns The wrapped tool.
1217
- */
1218
- _wrapTool = (tool) => {
1219
- const formattedSchema = {
1220
- name: tool.slug,
1221
- description: tool.description,
1222
- parameters: tool.input_parameters
1223
- };
1224
- return {
1225
- type: "function",
1226
- function: formattedSchema
1227
- };
1228
- };
1229
- /**
1230
- * Get all the tools from the Composio in OpenAI format.
1231
- * @param params - The parameters for the tool list.
1232
- * @returns The tools.
1233
- */
1234
- async getTools(params) {
1235
- const tools = await this.client?.tools.list(params);
1236
- return tools?.items.map((tool) => this._wrapTool(tool)) ?? [];
1237
- }
1238
- /**
1239
- * Execute a tool call.
1240
- * @param {OpenAI.ChatCompletionMessageToolCall} tool - The tool to execute.
1241
- * @param {string} userId - The user id.
1242
- * @returns {Promise<string>} The result of the tool call.
1243
- */
1244
- async executeToolCall(tool, userId) {
1245
- if (!this.client) {
1246
- throw new Error("Client not set");
1247
- }
1248
- const toolSchema = await this.client.tools.get(tool.function.name);
1249
- const appName = toolSchema?.toolkit?.name.toLowerCase();
1250
- const connectedAccountId = this.client.getConnectedAccountId(appName);
1251
- const payload = {
1252
- entity_id: userId ?? this.client.userId,
1253
- connected_account_id: connectedAccountId,
1254
- arguments: JSON.parse(tool.function.arguments)
1255
- };
1256
- const results = await this.client.tools.execute(toolSchema.slug, payload);
1257
- return JSON.stringify(results);
1258
- }
1259
- /**
1260
- * Handle the tool call from the assistant.
1261
- *
1262
- * @param {OpenAI.ChatCompletion} chatCompletion - The chat completion object.
1263
- * @param {string} userId - The user id.
1264
- * @returns {Promise<string[]>} The results of the tool call.
1265
- */
1266
- async handleToolCall(chatCompletion, userId) {
1267
- const outputs = [];
1268
- for (const message of chatCompletion.choices) {
1269
- if (message.message.tool_calls) {
1270
- outputs.push(
1271
- await this.executeToolCall(message.message.tool_calls[0], userId)
1272
- );
1273
- }
1274
- }
1275
- return outputs;
1276
- }
1277
- /**
1278
- * Handles all the tool calls from the assistant.
1279
- *
1280
- * @param {OpenAI.Beta.Threads.Run} run - The run object.
1281
- * @param {string} userId - The user id.
1282
- * @returns {Promise<OpenAI.Beta.Threads.Runs.RunSubmitToolOutputsParams.ToolOutput[]>} The tool outputs.
1283
- */
1284
- async handleAssistantMessage(run, userId) {
1285
- const tool_calls = run.required_action?.submit_tool_outputs?.tool_calls || [];
1286
- const tool_outputs = await Promise.all(
1287
- tool_calls.map(async (tool_call) => {
1288
- logger_default.debug(`Executing tool call: ${tool_call.id}`);
1289
- const tool_response = await this.executeToolCall(
1290
- tool_call,
1291
- userId
1292
- );
1293
- logger_default.debug(`Tool call ${tool_call.id} executed with response: ${tool_response}`);
1294
- return {
1295
- tool_call_id: tool_call.id,
1296
- output: JSON.stringify(tool_response)
1297
- };
1298
- })
1299
- );
1300
- return tool_outputs;
1301
- }
1302
- /**
1303
- * Waits for the assistant stream and handles the tool calls.
1304
- *
1305
- * @param {OpenAI} client - The OpenAI client.
1306
- * @param {Stream<OpenAI.Beta.Assistants.AssistantStreamEvent>} runStream - The run stream.
1307
- * @param {OpenAI.Beta.Threads.Thread} thread - The thread object.
1308
- * @param {string} userId - The user id.
1309
- * @returns {AsyncGenerator<OpenAI.Beta.Assistants.AssistantStreamEvent, void, unknown>} The run stream.
1310
- */
1311
- async *waitAndHandleAssistantStreamToolCalls(client, runStream, thread, userId) {
1312
- const defaultUserId = this.client?.userId;
1313
- let runId = null;
1314
- for await (const event of runStream) {
1315
- yield event;
1316
- if (event.event === "thread.run.created") {
1317
- const { id } = event.data;
1318
- runId = id;
1319
- }
1320
- if (!runId) {
1321
- continue;
1322
- }
1323
- if (event.event === "thread.run.requires_action") {
1324
- const toolOutputs = await this.handleAssistantMessage(
1325
- event.data,
1326
- userId ?? defaultUserId
1327
- );
1328
- await client.beta.threads.runs.submitToolOutputs(thread.id, runId, {
1329
- tool_outputs: toolOutputs
1330
- });
1331
- }
1332
- if ([
1333
- "thread.run.completed",
1334
- "thread.run.failed",
1335
- "thread.run.cancelled",
1336
- "thread.run.expired"
1337
- ].includes(event.event)) {
1338
- break;
1339
- }
1340
- }
1341
- if (!runId) {
1342
- throw new Error("No run ID found");
1343
- }
1344
- let finalRun = await client.beta.threads.runs.retrieve(thread.id, runId);
1345
- while (["queued", "in_progress", "requires_action"].includes(finalRun.status)) {
1346
- if (finalRun.status === "requires_action") {
1347
- const toolOutputs = await this.handleAssistantMessage(
1348
- finalRun,
1349
- userId ?? defaultUserId
1350
- );
1351
- finalRun = await client.beta.threads.runs.submitToolOutputs(
1352
- thread.id,
1353
- runId,
1354
- {
1355
- tool_outputs: toolOutputs
1356
- }
1357
- );
1358
- } else {
1359
- finalRun = await client.beta.threads.runs.retrieve(thread.id, runId);
1360
- await new Promise((resolve) => setTimeout(resolve, 500));
1361
- }
1362
- }
1363
- }
1364
- /**
1365
- * Waits for the assistant tool calls and handles them.
1366
- *
1367
- * @param {OpenAI} client - The OpenAI client.
1368
- * @param {OpenAI.Beta.Threads.Run} run - The run object.
1369
- * @param {OpenAI.Beta.Threads.Thread} thread - The thread object.
1370
- * @param {string} userId - The user id.
1371
- * @returns {Promise<OpenAI.Beta.Threads.Run>} The run object.
1372
- */
1373
- async waitAndHandleAssistantToolCalls(client, run, thread, userId) {
1374
- const defaultUserId = this.client?.userId;
1375
- while (["queued", "in_progress", "requires_action"].includes(run.status)) {
1376
- const tool_outputs = await this.handleAssistantMessage(
1377
- run,
1378
- userId ?? defaultUserId
1379
- );
1380
- if (run.status === "requires_action") {
1381
- run = await client.beta.threads.runs.submitToolOutputs(
1382
- thread.id,
1383
- run.id,
1384
- {
1385
- tool_outputs
1386
- }
1387
- );
1388
- } else {
1389
- run = await client.beta.threads.runs.retrieve(thread.id, run.id);
1390
- await new Promise((resolve) => setTimeout(resolve, 500));
1391
- }
1392
- }
1393
- return run;
1394
- }
1395
- };
1396
1958
  // Annotate the CommonJS export names for ESM import in node:
1397
1959
  0 && (module.exports = {
1398
- BaseComposioToolset,
1960
+ BaseAgenticToolset,
1961
+ BaseNonAgenticToolset,
1399
1962
  BaseTelemetryTransport,
1400
1963
  Composio,
1401
1964
  ComposioToolset,
1402
1965
  OpenAIToolset,
1966
+ ToolListParamsSchema,
1403
1967
  jsonSchemaToModel
1404
1968
  });