@composio/core 0.1.8-alpha.0 → 0.1.10-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -31,12 +31,12 @@ var ToolListResponseSchema = z.object({
31
31
  totalPages: z.number()
32
32
  });
33
33
  var ToolListParamsSchema = z.object({
34
+ tools: z.array(z.string()).optional(),
34
35
  cursor: z.string().optional(),
35
36
  important: z.string().optional(),
36
37
  limit: z.string().optional(),
37
38
  search: z.string().optional(),
38
- toolkits: z.array(z.string()).optional(),
39
- tools: z.array(z.string()).optional()
39
+ toolkits: z.array(z.string()).optional()
40
40
  });
41
41
  var CustomAuthParamsSchema = z.object({
42
42
  baseURL: z.string().optional(),
@@ -68,11 +68,223 @@ var ToolExecuteResponseSchema = z.object({
68
68
 
69
69
  // src/models/CustomTools.ts
70
70
  import zodToJsonSchema from "zod-to-json-schema";
71
+
72
+ // src/utils/env.ts
73
+ var getEnvVariable = (name, defaultValue = void 0) => {
74
+ try {
75
+ return process.env[name] || defaultValue;
76
+ } catch (_e) {
77
+ logger_default.error(`Error getting environment variable ${name}:`, _e);
78
+ return defaultValue;
79
+ }
80
+ };
81
+
82
+ // src/utils/logger.ts
83
+ var LOG_LEVELS = {
84
+ silent: -1,
85
+ // No logs
86
+ error: 0,
87
+ // Highest priority - critical errors
88
+ warn: 1,
89
+ // Warning messages
90
+ info: 2,
91
+ // General information
92
+ debug: 3
93
+ // Debug information
94
+ };
95
+ var getLogLevel = () => {
96
+ const envLevel = getEnvVariable("COMPOSIO_LOGGING_LEVEL", "info")?.toLowerCase();
97
+ return envLevel && envLevel in LOG_LEVELS ? envLevel : "info";
98
+ };
99
+ var Logger = class {
100
+ level;
101
+ includeTimestamp;
102
+ console;
103
+ constructor(options = {}) {
104
+ this.level = options.level ?? getLogLevel();
105
+ this.includeTimestamp = options.includeTimestamp ?? true;
106
+ this.console = console;
107
+ }
108
+ formatMessage(args) {
109
+ const formattedArgs = args.map((arg) => typeof arg === "object" ? JSON.stringify(arg) : String(arg)).join("\n");
110
+ if (!this.includeTimestamp) {
111
+ return formattedArgs;
112
+ }
113
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
114
+ return `${timestamp} - ${formattedArgs}`;
115
+ }
116
+ shouldLog(level) {
117
+ return LOG_LEVELS[level] <= LOG_LEVELS[this.level];
118
+ }
119
+ error(...args) {
120
+ if (this.shouldLog("error")) {
121
+ this.console.error(this.formatMessage(args));
122
+ }
123
+ }
124
+ warn(...args) {
125
+ if (this.shouldLog("warn")) {
126
+ this.console.warn(this.formatMessage(args));
127
+ }
128
+ }
129
+ info(...args) {
130
+ if (this.shouldLog("info")) {
131
+ this.console.info(this.formatMessage(args));
132
+ }
133
+ }
134
+ debug(...args) {
135
+ if (this.shouldLog("debug")) {
136
+ this.console.debug(this.formatMessage(args));
137
+ }
138
+ }
139
+ };
140
+ var logger = new Logger();
141
+ var logger_default = logger;
142
+
143
+ // src/errors/ComposioError.ts
144
+ var ComposioError = class extends Error {
145
+ name = "ComposioError";
146
+ code;
147
+ statusCode;
148
+ cause;
149
+ meta;
150
+ possibleFixes;
151
+ constructor(message, options = {}) {
152
+ super(message);
153
+ this.code = options.code;
154
+ this.statusCode = options.statusCode;
155
+ this.cause = options.cause;
156
+ this.meta = options.meta;
157
+ this.possibleFixes = options.possibleFixes;
158
+ if (Error.captureStackTrace) {
159
+ Error.captureStackTrace(this, this.constructor);
160
+ }
161
+ }
162
+ toJSON() {
163
+ return {
164
+ name: this.name,
165
+ message: this.message,
166
+ code: this.code,
167
+ statusCode: this.statusCode,
168
+ cause: this.cause instanceof Error ? this.cause.message : this.cause,
169
+ meta: this.meta,
170
+ possibleFixes: this.possibleFixes?.length ? this.possibleFixes.join("\n") : void 0
171
+ };
172
+ }
173
+ };
174
+
175
+ // src/errors/ToolErrors.ts
176
+ var ToolErrorCodes = {
177
+ TOOLSET_NOT_DEFINED: "TOOLSET_NOT_DEFINED",
178
+ TOOL_NOT_FOUND: "TOOL_NOT_FOUND",
179
+ INVALID_MODIFIER: "INVALID_MODIFIER",
180
+ CUSTOM_TOOLS_NOT_INITIALIZED: "CUSTOM_TOOLS_NOT_INITIALIZED",
181
+ TOOL_EXECUTION_ERROR: "TOOL_EXECUTION_ERROR",
182
+ INVALID_EXECUTE_FUNCTION: "INVALID_EXECUTE_FUNCTION",
183
+ GLOBAL_EXECUTE_TOOL_FN_NOT_SET: "GLOBAL_EXECUTE_TOOL_FN_NOT_SET"
184
+ };
185
+ var ComposioToolsetNotDefinedError = class extends ComposioError {
186
+ constructor(message = "Toolset not defined", meta = {}) {
187
+ super(message, {
188
+ code: ToolErrorCodes.TOOLSET_NOT_DEFINED,
189
+ meta,
190
+ possibleFixes: [
191
+ "Ensure that the toolset is defined in the Composio project and passed into the tool instance"
192
+ ]
193
+ });
194
+ this.name = "ComposioToolsetNotDefinedError";
195
+ }
196
+ };
197
+ var ComposioToolNotFoundError = class extends ComposioError {
198
+ constructor(message = "Tool not found", meta = {}) {
199
+ super(message, {
200
+ code: ToolErrorCodes.TOOL_NOT_FOUND,
201
+ meta,
202
+ possibleFixes: ["Ensure the tool slug is correct and exists in the Composio project"]
203
+ });
204
+ this.name = "ComposioToolNotFoundError";
205
+ }
206
+ };
207
+ var ComposioInvalidModifierError = class extends ComposioError {
208
+ constructor(message = "Invalid modifier", meta = {}) {
209
+ super(message, {
210
+ code: ToolErrorCodes.INVALID_MODIFIER,
211
+ meta,
212
+ possibleFixes: ["Ensure the modifier is a function and returns a valid result"]
213
+ });
214
+ this.name = "ComposioInvalidModifierError";
215
+ }
216
+ };
217
+ var ComposioCustomToolsNotInitializedError = class extends ComposioError {
218
+ constructor(message = "Custom tools not initialized", meta = {}) {
219
+ super(message, {
220
+ code: ToolErrorCodes.CUSTOM_TOOLS_NOT_INITIALIZED,
221
+ meta,
222
+ possibleFixes: ["Ensure the custom tools class is initialized in the Tools instance"]
223
+ });
224
+ this.name = "ComposioCustomToolsNotInitializedError";
225
+ }
226
+ };
227
+ var ComposioToolExecutionError = class extends ComposioError {
228
+ error;
229
+ constructor(error, message = "Tool execution error", meta = {}) {
230
+ super(message, {
231
+ code: ToolErrorCodes.TOOL_EXECUTION_ERROR,
232
+ cause: error,
233
+ meta,
234
+ possibleFixes: ["Ensure the tool is correctly configured and the input is valid"]
235
+ });
236
+ this.error = error;
237
+ this.name = "ComposioToolExecutionError";
238
+ }
239
+ };
240
+ var ComposioInvalidExecuteFunctionError = class extends ComposioError {
241
+ constructor(message = "Invalid execute function", meta = {}) {
242
+ super(message, {
243
+ code: ToolErrorCodes.INVALID_EXECUTE_FUNCTION,
244
+ meta,
245
+ possibleFixes: ["Ensure the execute function is a valid function and returns a valid result"]
246
+ });
247
+ this.name = "ComposioInvalidExecuteFunctionError";
248
+ }
249
+ };
250
+ var ComposioGlobalExecuteToolFnNotSetError = class extends ComposioError {
251
+ constructor(message = "Global execute tool function not set", meta = {}) {
252
+ super(message, {
253
+ code: ToolErrorCodes.GLOBAL_EXECUTE_TOOL_FN_NOT_SET,
254
+ meta,
255
+ possibleFixes: ["Ensure the global execute tool function is set in the toolset"]
256
+ });
257
+ this.name = "ComposioGlobalExecuteToolFnNotSetError";
258
+ }
259
+ };
260
+
261
+ // src/errors/ConnectedAccountsError.ts
262
+ var ConnectedAccountErrorCodes = {
263
+ CONNECTED_ACCOUNT_NOT_FOUND: "CONNECTED_ACCOUNT_NOT_FOUND"
264
+ };
265
+ var ComposioConnectedAccountNotFoundError = class extends ComposioError {
266
+ constructor(message = "Connected account not found", meta = {}) {
267
+ super(message, {
268
+ code: ConnectedAccountErrorCodes.CONNECTED_ACCOUNT_NOT_FOUND,
269
+ statusCode: 404,
270
+ meta,
271
+ possibleFixes: [
272
+ "Ensure the connected account exists and is active in your Composio dashboard"
273
+ ]
274
+ });
275
+ }
276
+ };
277
+
278
+ // src/models/CustomTools.ts
71
279
  var CustomTools = class {
72
280
  client;
73
- customToolsRegistry = /* @__PURE__ */ new Map();
281
+ customToolsRegistry;
74
282
  constructor(client) {
283
+ if (!client) {
284
+ throw new ComposioError("ComposioClient is required");
285
+ }
75
286
  this.client = client;
287
+ this.customToolsRegistry = /* @__PURE__ */ new Map();
76
288
  }
77
289
  /**
78
290
  * Create a custom tool and registers it in the registry.
@@ -140,11 +352,16 @@ var CustomTools = class {
140
352
  * @returns {Tool} The tool
141
353
  */
142
354
  async getCustomToolBySlug(slug) {
143
- const tool = this.customToolsRegistry.get(slug.toLowerCase());
144
- if (!tool) {
145
- return null;
355
+ if (!slug) {
356
+ throw new Error("Tool slug is required");
357
+ }
358
+ try {
359
+ const tool = this.customToolsRegistry.get(slug.toLowerCase());
360
+ return tool?.schema;
361
+ } catch (error) {
362
+ logger_default.error(`Error getting custom tool: ${error}`);
363
+ return void 0;
146
364
  }
147
- return tool.schema;
148
365
  }
149
366
  /**
150
367
  * Get the connected account for the user and toolkit.
@@ -153,12 +370,25 @@ var CustomTools = class {
153
370
  * @returns {ConnectedAccount} The connected account
154
371
  */
155
372
  async getConnectedAccount(toolkitSlug, metadata) {
373
+ try {
374
+ await this.client.toolkits.retrieve(toolkitSlug);
375
+ } catch (error) {
376
+ throw new ComposioToolNotFoundError(`Toolkit with slug ${toolkitSlug} not found`, {
377
+ toolkitSlug,
378
+ error
379
+ });
380
+ }
156
381
  const connectedAccounts = await this.client.connectedAccounts.list({
157
382
  toolkit_slug: toolkitSlug,
158
383
  user_id: metadata.userId
159
384
  });
160
385
  if (!connectedAccounts.items.length) {
161
- throw new Error(`No connected accounts found for toolkit ${toolkitSlug}`);
386
+ throw new ComposioConnectedAccountNotFoundError(
387
+ `No connected accounts found for toolkit ${toolkitSlug}`,
388
+ {
389
+ toolkitSlug
390
+ }
391
+ );
162
392
  }
163
393
  return metadata.connectedAccountId ? connectedAccounts.items.find((item) => item.id === metadata.connectedAccountId) : connectedAccounts.items[0];
164
394
  }
@@ -172,21 +402,29 @@ var CustomTools = class {
172
402
  async executeCustomTool(slug, inputParams, metadata) {
173
403
  const tool = this.customToolsRegistry.get(slug.toLowerCase());
174
404
  if (!tool) {
175
- throw new Error(`Tool with slug ${slug} not found`);
405
+ throw new ComposioToolNotFoundError(`Tool with slug ${slug} not found`, {
406
+ toolSlug: slug
407
+ });
176
408
  }
177
409
  let authCredentials = {};
178
410
  const { toolkitSlug, execute } = tool.options;
179
- if (toolkitSlug) {
411
+ if (toolkitSlug && toolkitSlug !== "custom") {
180
412
  const connectedAccount = await this.getConnectedAccount(toolkitSlug, metadata);
181
413
  if (!connectedAccount) {
182
- throw new Error(
183
- `Connected account not found for toolkit ${toolkitSlug} for user ${metadata.userId}`
414
+ throw new ComposioConnectedAccountNotFoundError(
415
+ `Connected account not found for toolkit ${toolkitSlug} for user ${metadata.userId}`,
416
+ {
417
+ toolkitSlug,
418
+ userId: metadata.userId
419
+ }
184
420
  );
185
421
  }
186
422
  authCredentials = connectedAccount.data?.connectionParams;
187
423
  }
188
424
  if (typeof execute !== "function") {
189
- throw new Error("Invalid execute function");
425
+ throw new ComposioInvalidExecuteFunctionError("Invalid execute function", {
426
+ toolSlug: slug
427
+ });
190
428
  }
191
429
  const executeToolRequest = async (data) => {
192
430
  return this.client.tools.proxy({
@@ -202,79 +440,42 @@ var CustomTools = class {
202
440
  }
203
441
  };
204
442
 
205
- // src/utils/env.ts
206
- var getEnvVariable = (name, defaultValue = void 0) => {
207
- try {
208
- return process.env[name] || defaultValue;
209
- } catch (_e) {
210
- logger_default.error(`Error getting environment variable ${name}:`, _e);
211
- return defaultValue;
212
- }
213
- };
214
-
215
- // src/utils/logger.ts
216
- var LOG_LEVELS = {
217
- silent: -1,
218
- // No logs
219
- error: 0,
220
- // Highest priority - critical errors
221
- warn: 1,
222
- // Warning messages
223
- info: 2,
224
- // General information
225
- debug: 3
226
- // Debug information
227
- };
228
- var getLogLevel = () => {
229
- const envLevel = getEnvVariable(
230
- "COMPOSIO_LOGGING_LEVEL",
231
- "info"
232
- )?.toLowerCase();
233
- return envLevel && envLevel in LOG_LEVELS ? envLevel : "info";
443
+ // src/errors/ValidationError.ts
444
+ import { ZodError } from "zod";
445
+ var ValidationErrorCodes = {
446
+ VALIDATION_ERROR: "VALIDATION_ERROR"
234
447
  };
235
- var Logger = class {
236
- level;
237
- includeTimestamp;
238
- console;
239
- constructor(options = {}) {
240
- this.level = options.level ?? getLogLevel();
241
- this.includeTimestamp = options.includeTimestamp ?? true;
242
- this.console = console;
243
- }
244
- formatMessage(args) {
245
- const formattedArgs = args.map((arg) => typeof arg === "object" ? JSON.stringify(arg) : String(arg)).join(" ");
246
- if (!this.includeTimestamp) {
247
- return formattedArgs;
248
- }
249
- const timestamp = (/* @__PURE__ */ new Date()).toISOString();
250
- return `${timestamp} - ${formattedArgs}`;
251
- }
252
- shouldLog(level) {
253
- return LOG_LEVELS[level] <= LOG_LEVELS[this.level];
254
- }
255
- error(...args) {
256
- if (this.shouldLog("error")) {
257
- this.console.error(this.formatMessage(args));
258
- }
259
- }
260
- warn(...args) {
261
- if (this.shouldLog("warn")) {
262
- this.console.warn(this.formatMessage(args));
263
- }
264
- }
265
- info(...args) {
266
- if (this.shouldLog("info")) {
267
- this.console.info(this.formatMessage(args));
268
- }
269
- }
270
- debug(...args) {
271
- if (this.shouldLog("debug")) {
272
- this.console.debug(this.formatMessage(args));
448
+ var ValidationError = class extends ComposioError {
449
+ zodError;
450
+ constructor(zodError, message = "Input validation failed") {
451
+ let zodErrorInstance;
452
+ if (!(zodError instanceof ZodError)) {
453
+ zodErrorInstance = new ZodError([
454
+ {
455
+ path: [],
456
+ message: "Invalid input",
457
+ code: "custom"
458
+ }
459
+ ]);
460
+ } else {
461
+ zodErrorInstance = zodError;
273
462
  }
463
+ super(message, {
464
+ code: ValidationErrorCodes.VALIDATION_ERROR,
465
+ meta: {
466
+ issues: JSON.stringify(
467
+ zodErrorInstance.issues.map((issue) => ({
468
+ path: issue.path.join("."),
469
+ message: issue.message,
470
+ code: issue.code
471
+ }))
472
+ )
473
+ },
474
+ cause: zodErrorInstance
475
+ });
476
+ this.zodError = zodErrorInstance;
274
477
  }
275
478
  };
276
- var logger = new Logger();
277
- var logger_default = logger;
278
479
 
279
480
  // src/models/Tools.ts
280
481
  var Tools = class {
@@ -282,9 +483,18 @@ var Tools = class {
282
483
  customTools;
283
484
  toolset;
284
485
  constructor(client, toolset) {
486
+ if (!client) {
487
+ throw new Error("ComposioClient is required");
488
+ }
489
+ if (!toolset) {
490
+ throw new ComposioToolsetNotDefinedError("Toolset not passed into Tools instance");
491
+ }
285
492
  this.client = client;
286
493
  this.customTools = new CustomTools(client);
287
494
  this.toolset = toolset;
495
+ this.execute = this.execute.bind(this);
496
+ this.getComposioToolBySlug = this.getComposioToolBySlug.bind(this);
497
+ this.getComposioTools = this.getComposioTools.bind(this);
288
498
  }
289
499
  /**
290
500
  * Transform the tool cases
@@ -318,12 +528,12 @@ var Tools = class {
318
528
  * @param {ToolList} tools - The tools to check.
319
529
  * @returns {Promise<boolean>} True if the connected account exists for the given tools, false otherwise.
320
530
  */
321
- async checkIfConnectedAccountExistsForTools(userId, tools) {
531
+ async checkIfConnectedAccountExistsForTools(userIds, tools) {
322
532
  if (!tools.length) {
323
533
  return true;
324
534
  }
325
535
  const connectedAccounts = await this.client.connectedAccounts.list({
326
- user_id: userId
536
+ user_ids: userIds
327
537
  });
328
538
  if (connectedAccounts.items.length === 0) {
329
539
  return false;
@@ -372,8 +582,8 @@ var Tools = class {
372
582
  );
373
583
  if (!isNoAuthApp) {
374
584
  const connectedAccounts = await this.client.connectedAccounts.list({
375
- user_id: userId,
376
- toolkit_slug: tool.toolkit.slug
585
+ user_ids: [userId],
586
+ toolkit_slugs: [tool.toolkit.slug]
377
587
  });
378
588
  if (connectedAccounts.items.length === 0) {
379
589
  throw new Error("No connected accounts found");
@@ -393,15 +603,15 @@ var Tools = class {
393
603
  async getComposioTools(userId, query = {}, modifier) {
394
604
  const queryParams = ToolListParamsSchema.safeParse(query);
395
605
  if (queryParams.error) {
396
- throw new Error(JSON.stringify(queryParams.error.flatten()));
606
+ throw new ValidationError(queryParams.error);
397
607
  }
398
608
  const tools = await this.client.tools.list({
609
+ tool_slugs: queryParams.data.tools,
610
+ toolkit_slug: queryParams.data.toolkits?.join(","),
399
611
  cursor: queryParams.data.cursor,
400
612
  important: queryParams.data.important,
401
613
  limit: queryParams.data.limit,
402
- search: queryParams.data.search,
403
- toolkit_slug: queryParams.data.toolkits?.join(","),
404
- tool_slugs: queryParams.data.tools?.join(",")
614
+ search: queryParams.data.search
405
615
  });
406
616
  if (!tools) {
407
617
  return [];
@@ -414,10 +624,10 @@ var Tools = class {
414
624
  if (modifier) {
415
625
  if (typeof modifier === "function") {
416
626
  modifiedTools = modifiedTools.map((tool) => {
417
- return modifier(tool.slug, tool);
627
+ return modifier(tool.slug, tool.toolkit?.slug || "unkown", tool);
418
628
  });
419
629
  } else {
420
- throw new Error("Invalid schema modifier. Not a function.");
630
+ throw new ComposioInvalidModifierError("Invalid schema modifier. Not a function.");
421
631
  }
422
632
  }
423
633
  return modifiedTools;
@@ -426,6 +636,11 @@ var Tools = class {
426
636
  * Retrieves a tool by its Slug.
427
637
  * @param slug The ID of the tool to be retrieved
428
638
  * @returns {Promise<Tool>} The tool
639
+ *
640
+ * @example
641
+ * ```ts
642
+ * const tool = await composio.tools.getComposioToolBySlug('default', 'github');
643
+ * ```
429
644
  */
430
645
  async getComposioToolBySlug(userId, slug, modifier) {
431
646
  const customTool = await this.customTools.getCustomToolBySlug(slug);
@@ -434,18 +649,27 @@ var Tools = class {
434
649
  }
435
650
  const tool = await this.client.tools.retrieve(slug);
436
651
  if (!tool) {
437
- throw new Error(`Tool with slug ${slug} not found`);
652
+ throw new ComposioToolNotFoundError(
653
+ `[getComposioToolBySlug] Tool with slug ${slug} not found`
654
+ );
438
655
  }
439
656
  let modifiedToool = this.transformToolCases(tool);
440
657
  if (modifier) {
441
658
  if (typeof modifier === "function") {
442
- modifiedToool = modifier(slug, modifiedToool);
659
+ modifiedToool = modifier(slug, modifiedToool.toolkit?.slug || "unkown", modifiedToool);
443
660
  } else {
444
- throw new Error("Invalid schema modifier. Not a function.");
661
+ throw new ComposioInvalidModifierError("Invalid schema modifier. Not a function.");
445
662
  }
446
663
  }
447
664
  return modifiedToool;
448
665
  }
666
+ /**
667
+ * Get a tool by its slug
668
+ * @param userId - The user id
669
+ * @param arg2 - The slug of the tool or the filters for the tools
670
+ * @param options - The options for the tools
671
+ * @returns The tool or the tools
672
+ */
449
673
  async get(userId, arg2, options) {
450
674
  const executeToolFn = this.createExecuteToolFn(userId, options);
451
675
  if (typeof arg2 === "string") {
@@ -457,6 +681,7 @@ var Tools = class {
457
681
  }
458
682
  }
459
683
  /**
684
+ * @internal
460
685
  * Creates a function that executes a tool.
461
686
  * This function is used by agentic the toolsets to execute the tool
462
687
  * @param {string} userId - The user id
@@ -476,6 +701,82 @@ var Tools = class {
476
701
  };
477
702
  return executeToolFn;
478
703
  }
704
+ /**
705
+ * @internal
706
+ * Handles the execution of a custom tool
707
+ * @param tool - The tool to execute
708
+ * @param body - The body of the tool execution
709
+ * @param modifiers - The modifiers to be applied to the tool execution
710
+ * @returns The response from the tool execution
711
+ */
712
+ async handleCustomToolExecution(tool, body, modifiers) {
713
+ if (modifiers?.beforeToolExecute) {
714
+ if (typeof modifiers.beforeToolExecute === "function") {
715
+ body = modifiers.beforeToolExecute(tool.slug, "unkown", body);
716
+ } else {
717
+ throw new ComposioInvalidModifierError(
718
+ "Invalid beforeToolExecute modifier. Not a function."
719
+ );
720
+ }
721
+ }
722
+ let result = await this.customTools.executeCustomTool(tool.slug, body, {
723
+ userId: body.userId || "default",
724
+ connectedAccountId: body.connectedAccountId
725
+ });
726
+ if (modifiers?.afterToolExecute) {
727
+ if (typeof modifiers.afterToolExecute === "function") {
728
+ result = modifiers.afterToolExecute(tool.slug, "unkown", result);
729
+ } else {
730
+ throw new ComposioInvalidModifierError(
731
+ "Invalid afterToolExecute modifier. Not a function."
732
+ );
733
+ }
734
+ }
735
+ return result;
736
+ }
737
+ /**
738
+ * @internal
739
+ * Handles the execution of a composio tool
740
+ * @param tool - The tool to execute
741
+ * @param body - The body of the tool execution
742
+ * @param modifiers - The modifiers to be applied to the tool execution
743
+ * @returns The response from the tool execution
744
+ */
745
+ async handleComposioToolExecution(tool, body, modifiers) {
746
+ if (modifiers?.beforeToolExecute) {
747
+ if (typeof modifiers.beforeToolExecute === "function") {
748
+ body = modifiers.beforeToolExecute(tool.slug, tool.toolkit?.slug || "unkown", body);
749
+ } else {
750
+ throw new ComposioInvalidModifierError(
751
+ "Invalid beforeToolExecute modifier. Not a function."
752
+ );
753
+ }
754
+ }
755
+ let connectedAccountId = body.connectedAccountId;
756
+ if (!connectedAccountId) {
757
+ connectedAccountId = await this.getConnectedAccountIdForTool(body.userId, tool.slug) || void 0;
758
+ }
759
+ let result = await this.client.tools.execute(tool.slug, {
760
+ allow_tracing: body.allowTracing,
761
+ connected_account_id: body.connectedAccountId,
762
+ custom_auth_params: body.customAuthParams,
763
+ arguments: body.arguments,
764
+ entity_id: body.userId,
765
+ version: body.version,
766
+ text: body.text
767
+ });
768
+ result = this.transformToolExecuteResponse(result);
769
+ if (modifiers?.afterToolExecute) {
770
+ if (typeof modifiers.afterToolExecute === "function") {
771
+ result = modifiers.afterToolExecute(tool.slug, tool.toolkit?.slug || "unkown", result);
772
+ } else {
773
+ throw new ComposioInvalidModifierError(
774
+ "Invalid afterToolExecute modifier. Not a function."
775
+ );
776
+ }
777
+ }
778
+ return result;
779
+ }
479
780
  /**
480
781
  * Exectes a given tool with the provided parameters.
481
782
  *
@@ -486,44 +787,28 @@ var Tools = class {
486
787
  * @returns {Promise<ToolExecuteResponse>} - The response from the tool execution
487
788
  */
488
789
  async execute(slug, body, modifiers) {
489
- if (modifiers && modifiers.beforeToolExecute) {
490
- if (typeof modifiers.beforeToolExecute === "function") {
491
- body = modifiers.beforeToolExecute(slug, body);
492
- } else {
493
- throw new Error("Invalid beforeToolExecute modifier. Not a function.");
494
- }
495
- }
496
- let result;
497
- const customTool = await this.customTools.getCustomToolBySlug(slug);
498
- if (customTool) {
499
- result = await this.customTools.executeCustomTool(slug, body, {
500
- userId: body.userId || "default",
501
- connectedAccountId: body.connectedAccountId
502
- });
503
- } else {
504
- let connectedAccountId = body.connectedAccountId;
505
- if (!connectedAccountId) {
506
- connectedAccountId = await this.getConnectedAccountIdForTool(body.userId, slug) || void 0;
507
- }
508
- result = await this.client.tools.execute(slug, {
509
- allow_tracing: body.allowTracing,
510
- connected_account_id: body.connectedAccountId,
511
- custom_auth_params: body.customAuthParams,
512
- arguments: body.arguments,
513
- entity_id: body.userId,
514
- version: body.version,
515
- text: body.text
516
- });
517
- result = this.transformToolExecuteResponse(result);
790
+ if (!this.customTools) {
791
+ throw new ComposioCustomToolsNotInitializedError(
792
+ "CustomTools not initialized. Make sure Tools class is properly constructed."
793
+ );
518
794
  }
519
- if (modifiers && modifiers.afterToolExecute) {
520
- if (typeof modifiers.afterToolExecute === "function") {
521
- result = modifiers.afterToolExecute(slug, result);
795
+ try {
796
+ const customTool = await this.customTools.getCustomToolBySlug(slug);
797
+ if (customTool) {
798
+ return this.handleCustomToolExecution(customTool, body, modifiers);
522
799
  } else {
523
- throw new Error("Invalid afterToolExecute modifier. Not a function.");
800
+ const composioTool = await this.getComposioToolBySlug(body.userId, slug);
801
+ if (!composioTool) {
802
+ throw new ComposioToolNotFoundError(`Tool with slug ${slug} not found`);
803
+ }
804
+ return this.handleComposioToolExecution(composioTool, body, modifiers);
524
805
  }
806
+ } catch (error) {
807
+ throw new ComposioToolExecutionError(error, `Error executing tool ${slug}`, {
808
+ toolSlug: slug,
809
+ body
810
+ });
525
811
  }
526
- return result;
527
812
  }
528
813
  /**
529
814
  * Fetches the list of all available tools in the Composio SDK.
@@ -567,7 +852,7 @@ var Tools = class {
567
852
 
568
853
  // src/types/toolkit.types.ts
569
854
  import { z as z2 } from "zod";
570
- var ToolkitMangedByEnumSchema = z2.enum(["all", "composio_managed", "project_managed"]);
855
+ var ToolkitMangedByEnumSchema = z2.enum(["all", "composio", "project"]);
571
856
  var ToolkitSortByEnumSchema = z2.enum(["usage", "alphabetically"]);
572
857
  var ToolkitsListParamsSchema = z2.object({
573
858
  category: z2.string().optional(),
@@ -578,16 +863,17 @@ var ToolkitsListParamsSchema = z2.object({
578
863
  var ToolKitMetaSchema = z2.object({
579
864
  categories: z2.array(
580
865
  z2.object({
581
- id: z2.string(),
866
+ slug: z2.string(),
582
867
  name: z2.string()
583
868
  })
584
- ),
585
- createdAt: z2.string(),
586
- description: z2.string(),
587
- logo: z2.string(),
588
- toolsCount: z2.number(),
589
- triggersCount: z2.number(),
590
- updatedAt: z2.string()
869
+ ).optional(),
870
+ appUrl: z2.string().optional(),
871
+ createdAt: z2.string().optional(),
872
+ description: z2.string().optional(),
873
+ logo: z2.string().optional(),
874
+ toolsCount: z2.number().optional(),
875
+ triggersCount: z2.number().optional(),
876
+ updatedAt: z2.string().optional()
591
877
  });
592
878
  var ToolKitItemSchema = z2.object({
593
879
  name: z2.string(),
@@ -612,21 +898,19 @@ var ToolkitAuthFieldSchema = z2.object({
612
898
  var ToolkitAuthConfigDetailsSchema = z2.object({
613
899
  name: z2.string(),
614
900
  mode: z2.string(),
615
- fields: z2.array(
616
- z2.object({
617
- authConfigCreation: z2.object({
618
- optional: z2.array(ToolkitAuthFieldSchema),
619
- required: z2.array(ToolkitAuthFieldSchema)
620
- }),
621
- connectedAccountInitiation: z2.object({
622
- optional: z2.array(ToolkitAuthFieldSchema),
623
- required: z2.array(ToolkitAuthFieldSchema)
624
- })
901
+ fields: z2.object({
902
+ authConfigCreation: z2.object({
903
+ optional: z2.array(ToolkitAuthFieldSchema),
904
+ required: z2.array(ToolkitAuthFieldSchema)
905
+ }),
906
+ connectedAccountInitiation: z2.object({
907
+ optional: z2.array(ToolkitAuthFieldSchema),
908
+ required: z2.array(ToolkitAuthFieldSchema)
625
909
  })
626
- ),
910
+ }),
627
911
  proxy: z2.object({
628
- baseUrul: z2.string()
629
- })
912
+ baseUrl: z2.string().optional()
913
+ }).optional()
630
914
  });
631
915
  var ToolkitRetrieveResponseSchema = z2.object({
632
916
  name: z2.string(),
@@ -647,335 +931,7 @@ var ToolkitRetrieveCategoriesResponseSchema = z2.object({
647
931
  });
648
932
 
649
933
  // src/models/Toolkits.ts
650
- var Toolkits = class {
651
- client;
652
- constructor(client) {
653
- this.client = client;
654
- }
655
- /**
656
- * List all toolkits available in the Composio SDK.
657
- * This method fetches the toolkits from the Composio API.
658
- * @returns {Promise<Toolkit[]>} List of toolkits
659
- */
660
- async getToolkits(query) {
661
- const parsedQuery = ToolkitsListParamsSchema.parse(query);
662
- const result = await this.client.toolkits.list({
663
- category: parsedQuery.category,
664
- is_local: parsedQuery.isLocal,
665
- managed_by: parsedQuery.managedBy,
666
- sort_by: parsedQuery.sortBy
667
- });
668
- const parsedResult = ToolKitListResponseSchema.parse({
669
- items: result.items.map((item) => {
670
- const parsedItem = ToolKitItemSchema.parse({
671
- name: item.name,
672
- slug: item.slug,
673
- meta: item.meta,
674
- isLocalToolkit: item.is_local_toolkit,
675
- authSchemes: item.auth_schemes,
676
- composioManagedAuthSchemes: item.composio_managed_auth_schemes,
677
- noAuth: item.no_auth
678
- });
679
- return parsedItem;
680
- }),
681
- nextCursor: result.next_cursor,
682
- totalPages: result.total_pages
683
- });
684
- return parsedResult;
685
- }
686
- /**
687
- * Fetches a toolkit by its Slug.
688
- * This method retrieves the toolkit from the Composio API.
689
- * @param slug - The ID of the toolkit to be retrieved
690
- * @param options - Request options
691
- * @returns {Promise<ToolkitRetrieveResponse>} The toolkit object
692
- */
693
- async getToolkitBySlug(slug) {
694
- const result = await this.client.toolkits.retrieve(slug);
695
- const parsedResult = ToolkitRetrieveResponseSchema.parse({
696
- name: result.name,
697
- slug: result.slug,
698
- meta: result.meta,
699
- isLocalToolkit: result.is_local_toolkit,
700
- composioManagedAuthSchemes: result.composio_managed_auth_schemes,
701
- authConfigDetails: result.auth_config_details
702
- });
703
- return parsedResult;
704
- }
705
- /**
706
- * Fetches a toolkit by its Slug or a list of toolkits.
707
- * This method retrieves the toolkit from the Composio API.
708
- * @param arg - The ID of the toolkit to be retrieved or a list of parameters
709
- * @returns {Promise<ToolkitRetrieveResponse | ToolKitListResponse>} The toolkit object or a list of toolkits
710
- */
711
- async get(arg) {
712
- if (typeof arg === "string") {
713
- return this.getToolkitBySlug(arg);
714
- }
715
- return this.getToolkits(arg);
716
- }
717
- /**
718
- * Fetches all categories available in the Composio SDK
719
- *
720
- * @returns {Promise<ToolkitRetrieveCategoriesResponse>} List of categories
721
- */
722
- async listCategories() {
723
- const result = await this.client.toolkits.retrieveCategories();
724
- const parsedResult = ToolkitRetrieveCategoriesResponseSchema.parse({
725
- items: result.items.map((item) => {
726
- const parsedItem = ToolkitCategorySchema.parse({
727
- id: item.id,
728
- name: item.name
729
- });
730
- return parsedItem;
731
- }),
732
- nextCursor: result.next_cursor,
733
- totalPages: result.total_pages
734
- });
735
- return parsedResult;
736
- }
737
- };
738
-
739
- // src/utils/pusher.ts
740
- var PUSHER_KEY = process.env.CLIENT_PUSHER_KEY || "ff9f18c208855d77a152";
741
- var PUSHER_CLUSTER = "mt1";
742
- var PusherUtils = class _PusherUtils {
743
- static pusherClient;
744
- static getPusherClient(baseURL, apiKey) {
745
- if (!_PusherUtils.pusherClient) {
746
- const PusherClient = __require("pusher-js");
747
- _PusherUtils.pusherClient = new PusherClient(PUSHER_KEY, {
748
- cluster: PUSHER_CLUSTER,
749
- channelAuthorization: {
750
- endpoint: `${baseURL}/api/v1/client/auth/pusher_auth`,
751
- headers: {
752
- "x-api-key": apiKey
753
- },
754
- transport: "ajax"
755
- }
756
- });
757
- }
758
- return _PusherUtils.pusherClient;
759
- }
760
- /**
761
- * Subscribes to a Pusher channel and binds an event to a callback function.
762
- * @param {string} channelName - The name of the channel to subscribe to.
763
- * @param {string} event - The event to bind to the channel.
764
- * @param {(data: Record<string, unknown>) => void} fn - The callback function to execute when the event is triggered.
765
- * @returns {PusherClient} The Pusher client instance.
766
- */
767
- static async subscribe(channelName, event, fn) {
768
- try {
769
- await _PusherUtils.pusherClient.subscribe(channelName).bind(event, fn);
770
- } catch (error) {
771
- logger_default.error(
772
- `Error subscribing to ${channelName} with event ${event}: ${error}`
773
- );
774
- }
775
- }
776
- /**
777
- * Unsubscribes from a Pusher channel.
778
- * @param {string} channelName - The name of the channel to unsubscribe from.
779
- * @returns {void}
780
- */
781
- static async unsubscribe(channelName) {
782
- _PusherUtils.pusherClient.unsubscribe(channelName);
783
- }
784
- /**
785
- * Binds an event to a channel with support for chunked messages.
786
- * @param {PusherClient} channel - The Pusher channel to bind the event to.
787
- * @param {string} event - The event to bind to the channel.
788
- * @param {(data: unknown) => void} callback - The callback function to execute when the event is triggered.
789
- */
790
- static bindWithChunking(channel, event, callback) {
791
- channel.bind(event, callback);
792
- const events = {};
793
- channel.bind("chunked-" + event, (data) => {
794
- const typedData = data;
795
- if (!events.hasOwnProperty(typedData.id)) {
796
- events[typedData.id] = { chunks: [], receivedFinal: false };
797
- }
798
- const ev = events[typedData.id];
799
- ev.chunks[typedData.index] = typedData.chunk;
800
- if (typedData.final) ev.receivedFinal = true;
801
- if (ev.receivedFinal && ev.chunks.length === Object.keys(ev.chunks).length) {
802
- callback(JSON.parse(ev.chunks.join("")));
803
- delete events[typedData.id];
804
- }
805
- });
806
- }
807
- /**
808
- * Subscribes to a trigger channel for a client and handles chunked data.
809
- * @param {string} clientId - The unique identifier for the client subscribing to the events.
810
- * @param {(data: TriggerData) => void} fn - The callback function to execute when trigger data is received.
811
- */
812
- static triggerSubscribe(clientId, fn) {
813
- const channel = _PusherUtils.pusherClient.subscribe(
814
- `private-${clientId}_triggers`
815
- );
816
- _PusherUtils.bindWithChunking(
817
- channel,
818
- "trigger_to_client",
819
- fn
820
- );
821
- logger_default.info(
822
- `Subscribed to triggers. You should start receiving events now.`
823
- );
824
- }
825
- static triggerUnsubscribe(clientId) {
826
- _PusherUtils.pusherClient.unsubscribe(`${clientId}_triggers`);
827
- }
828
- };
829
-
830
- // src/models/Session.ts
831
- var Session = class {
832
- client;
833
- constructor(client) {
834
- this.client = client;
835
- }
836
- /**
837
- * Get the active session info
838
- * @returns {Promise<SessionGetInfoResponse>} Session info
839
- */
840
- async getInfo() {
841
- return this.client.auth.session.getInfo();
842
- }
843
- };
844
-
845
- // src/models/Triggers.ts
846
- var Triggers = class {
847
- client;
848
- constructor(client) {
849
- this.client = client;
850
- }
851
- /**
852
- * Fetch list of all the active triggers
853
- * @returns {Promise<TriggerInstance[]>} List of trigger instances
854
- */
855
- async list(query, options) {
856
- return this.client.triggerInstances.listActive(query, options);
857
- }
858
- /**
859
- * Create a new trigger instance
860
- *
861
- * @param {string} slug - The slug of the trigger instance
862
- * @param {TriggerInstanceUpsertParams} body - The parameters to create the trigger instance
863
- * @returns {Promise<TriggerInstanceUpsertResponse>} The created trigger instance
864
- */
865
- async create(slug, body, options) {
866
- return this.client.triggerInstances.upsert(slug, body, options);
867
- }
868
- /**
869
- * Update an existing trigger instance
870
- *
871
- * @param {string} slug - The slug of the trigger instance
872
- * @param {TriggerInstanceUpsertParams} body - The parameters to create the trigger instance
873
- * @returns {Promise<TriggerInstanceUpsertResponse>} The updated trigger instance
874
- */
875
- async update(slug, body, options) {
876
- return this.client.triggerInstances.upsert(slug, body, options);
877
- }
878
- /**
879
- * Delete a trigger instance
880
- *
881
- * @param {string} slug - The slug of the trigger instance
882
- * @returns
883
- */
884
- async delete(slug) {
885
- return this.client.triggerInstances.removeUpsert(slug);
886
- }
887
- /**
888
- * Update the status of a trigger
889
- *
890
- * @param {TriggerStatusEnum} status - The new status of the trigger
891
- * @param {TriggerInstanceUpdateStatusParams} params - The parameters to update the trigger instance
892
- * @param {RequestOptions} options - Request options
893
- * @returns {Promise<TriggerInstanceUpsertResponse>} The updated trigger instance
894
- */
895
- async updateStatus(status, params, options) {
896
- return this.client.triggerInstances.updateStatus(status, params, options);
897
- }
898
- /**
899
- * Disable a trigger instance
900
- *
901
- * @param {string} slug - The slug of the trigger instance
902
- * @param {RequestOptions options - Request options
903
- * @returns {Promise<TriggerInstanceUpsertResponse>} The updated trigger instance
904
- */
905
- async disable(slug, options) {
906
- return this.client.triggerInstances.updateStatus("disable", { slug }, options);
907
- }
908
- /**
909
- * Enable a trigger instance
910
- *
911
- * @param {string} slug - The slug of the trigger instance
912
- * @param {RequestOptions options - Request options
913
- * @returns {Promise<TriggerInstanceUpsertResponse>} The updated trigger instance
914
- */
915
- async enable(slug, options) {
916
- return this.client.triggerInstances.updateStatus("enable", { slug }, options);
917
- }
918
- /**
919
- * @TODO Learn about trigger types
920
- */
921
- /**
922
- * List all the trigger types
923
- *
924
- * @param {TriggersTypeListParams} query - The query parameters to filter the trigger types
925
- * @param {RequestOptions} options - Request options
926
- * @returns {Promise<TriggersTypeListResponse>} The list of trigger types
927
- */
928
- async listTypes(query, options) {
929
- return this.client.triggersTypes.list(query, options);
930
- }
931
- /**
932
- * Retrieve a trigger type by its slug
933
- *
934
- * @param {string} slug - The slug of the trigger type
935
- * @param {RequestOptions} options - request options
936
- * @returns {Promise<TriggersTypeRetrieveResponse>} The trigger type object
937
- */
938
- async getType(slug, options) {
939
- return this.client.triggersTypes.retrieve(slug, options);
940
- }
941
- /**
942
- * Fetches the list of all the available trigger enums
943
- *
944
- * This method is used by the CLI where filters are not required.
945
- * @param options
946
- * @returns
947
- */
948
- async listEnum(options) {
949
- return this.client.triggersTypes.retrieveEnum(options);
950
- }
951
- async subscribe(fn, filters = {}) {
952
- if (!fn) throw new Error("Function is required for trigger subscription");
953
- const session = new Session(this.client);
954
- const sessionInfo = await session.getInfo();
955
- const clientId = sessionInfo.project?.id;
956
- if (!clientId) throw new Error("Client ID not found");
957
- await PusherUtils.getPusherClient(this.client.baseURL, this.client.apiKey);
958
- const shouldSendTrigger = (data) => {
959
- if (Object.keys(filters).length === 0) return true;
960
- else {
961
- return (!filters.appName || data.appName.toLowerCase() === filters.appName.toLowerCase()) && (!filters.triggerId || data.metadata.id.toLowerCase() === filters.triggerId.toLowerCase()) && (!filters.connectionId || data.metadata.connectionId.toLowerCase() === filters.connectionId.toLowerCase()) && (!filters.triggerName || data.metadata.triggerName.toLowerCase() === filters.triggerName.toLowerCase()) && (!filters.entityId || data.metadata.connection.clientUniqueUserId.toLowerCase() === filters.entityId.toLowerCase()) && (!filters.integrationId || data.metadata.connection.integrationId.toLowerCase() === filters.integrationId.toLowerCase());
962
- }
963
- };
964
- logger_default.debug("Subscribing to triggers", filters);
965
- PusherUtils.triggerSubscribe(clientId, (data) => {
966
- if (shouldSendTrigger(data)) {
967
- fn(data);
968
- }
969
- });
970
- }
971
- async unsubscribe() {
972
- const session = new Session(this.client);
973
- const sessionInfo = await session.getInfo();
974
- const clientId = sessionInfo.project?.id;
975
- if (!clientId) throw new Error("Client ID not found");
976
- PusherUtils.triggerUnsubscribe(clientId);
977
- }
978
- };
934
+ import { ZodError as ZodError3 } from "zod";
979
935
 
980
936
  // src/types/authConfigs.types.ts
981
937
  import { z as z3 } from "zod";
@@ -1063,9 +1019,20 @@ var AuthConfigListResponseSchema = z3.object({
1063
1019
  nextCursor: z3.string().optional(),
1064
1020
  totalPages: z3.number()
1065
1021
  });
1066
- var AuthConfigUpdateParamsSchema = z3.object({
1067
- credentials: z3.record(z3.string(), z3.union([z3.string(), z3.number(), z3.boolean()]))
1022
+ var AuthCustomConfigUpdateParamsSchema = z3.object({
1023
+ credentials: z3.record(z3.string(), z3.union([z3.string(), z3.unknown()])),
1024
+ type: z3.literal("custom"),
1025
+ restrictToFollowingTools: z3.array(z3.string()).optional()
1026
+ });
1027
+ var AuthDefaultConfigUpdateParamsSchema = z3.object({
1028
+ scopes: z3.string(),
1029
+ type: z3.literal("default"),
1030
+ restrictToFollowingTools: z3.array(z3.string()).optional()
1068
1031
  });
1032
+ var AuthConfigUpdateParamsSchema = z3.discriminatedUnion("type", [
1033
+ AuthCustomConfigUpdateParamsSchema,
1034
+ AuthDefaultConfigUpdateParamsSchema
1035
+ ]);
1069
1036
 
1070
1037
  // src/models/AuthConfigs.ts
1071
1038
  var AuthConfigs = class {
@@ -1073,8 +1040,16 @@ var AuthConfigs = class {
1073
1040
  constructor(client) {
1074
1041
  this.client = client;
1075
1042
  }
1043
+ /**
1044
+ * Protected getter for the client instance.
1045
+ * This is primarily used for testing purposes.
1046
+ * @protected
1047
+ */
1048
+ getClient() {
1049
+ return this.client;
1050
+ }
1076
1051
  parseAuthConfigRetrieveResponse(authConfig) {
1077
- return AuthConfigRetrieveResponseSchema.parse({
1052
+ const result = AuthConfigRetrieveResponseSchema.safeParse({
1078
1053
  id: authConfig.id,
1079
1054
  name: authConfig.name,
1080
1055
  noOfConnections: authConfig.no_of_connections,
@@ -1092,6 +1067,10 @@ var AuthConfigs = class {
1092
1067
  createdAt: authConfig.created_at,
1093
1068
  lastUpdatedAt: authConfig.last_updated_at
1094
1069
  });
1070
+ if (result.error) {
1071
+ throw new ValidationError(result.error);
1072
+ }
1073
+ return result.data;
1095
1074
  }
1096
1075
  /**
1097
1076
  * List all auth configs
@@ -1107,11 +1086,15 @@ var AuthConfigs = class {
1107
1086
  limit: parsedQuery?.limit?.toString(),
1108
1087
  toolkit_slug: parsedQuery?.toolkitSlug
1109
1088
  });
1110
- return AuthConfigListResponseSchema.parse({
1089
+ const parsedResult = AuthConfigListResponseSchema.safeParse({
1111
1090
  items: result.items.map((item) => this.parseAuthConfigRetrieveResponse(item)),
1112
1091
  nextCursor: result.next_cursor,
1113
1092
  totalPages: result.total_pages
1114
1093
  });
1094
+ if (parsedResult.error) {
1095
+ throw new ValidationError(parsedResult.error);
1096
+ }
1097
+ return parsedResult.data;
1115
1098
  }
1116
1099
  /**
1117
1100
  * Create a new auth config
@@ -1132,19 +1115,26 @@ var AuthConfigs = class {
1132
1115
  * @link https://docs.composio.dev/reference/auth-configs/create-auth-config
1133
1116
  */
1134
1117
  async create(toolkit, options) {
1135
- const parsedOptions = CreateAuthConfigParamsSchema.parse(options);
1118
+ const parsedOptions = CreateAuthConfigParamsSchema.safeParse(options);
1119
+ if (parsedOptions.error) {
1120
+ throw new ValidationError(parsedOptions.error);
1121
+ }
1136
1122
  const result = await this.client.authConfigs.create({
1137
1123
  toolkit: {
1138
1124
  slug: toolkit
1139
1125
  },
1140
- auth_config: parsedOptions
1126
+ auth_config: parsedOptions.data
1141
1127
  });
1142
- return CreateAuthConfigResponseSchema.parse({
1128
+ const parsedResult = CreateAuthConfigResponseSchema.safeParse({
1143
1129
  id: result.auth_config.id,
1144
1130
  authScheme: result.auth_config.auth_scheme,
1145
1131
  isComposioManaged: result.auth_config.is_composio_managed,
1146
1132
  toolkit: result.toolkit.slug
1147
1133
  });
1134
+ if (parsedResult.error) {
1135
+ throw new ValidationError(parsedResult.error);
1136
+ }
1137
+ return parsedResult.data;
1148
1138
  }
1149
1139
  /**
1150
1140
  * Get an auth config by nanoid
@@ -1164,11 +1154,22 @@ var AuthConfigs = class {
1164
1154
  * @returns {Promise<AuthConfigUpdateResponse>} Updated auth config
1165
1155
  */
1166
1156
  async update(nanoid, data) {
1167
- return this.client.authConfigs.update(nanoid, {
1168
- auth_config: {
1169
- credentials: data.credentials
1157
+ const parsedData = AuthConfigUpdateParamsSchema.safeParse(data);
1158
+ if (parsedData.error) {
1159
+ throw new ValidationError(parsedData.error);
1160
+ }
1161
+ return this.client.authConfigs.update(
1162
+ nanoid,
1163
+ parsedData.data.type === "custom" ? {
1164
+ type: "custom",
1165
+ credentials: parsedData.data.credentials,
1166
+ restrict_to_following_tools: parsedData.data.restrictToFollowingTools
1167
+ } : {
1168
+ type: "default",
1169
+ scopes: parsedData.data.scopes,
1170
+ restrict_to_following_tools: parsedData.data.restrictToFollowingTools
1170
1171
  }
1171
- });
1172
+ );
1172
1173
  }
1173
1174
  /**
1174
1175
  * Delete an auth config
@@ -1209,12 +1210,31 @@ var AuthConfigs = class {
1209
1210
  }
1210
1211
  };
1211
1212
 
1213
+ // src/errors/AuthConfigErrors.ts
1214
+ var AuthConfigErrorCodes = {
1215
+ AUTH_CONFIG_NOT_FOUND: "AUTH_CONFIG_NOT_FOUND"
1216
+ };
1217
+ var ComposioAuthConfigNotFoundError = class extends ComposioError {
1218
+ constructor(message, meta) {
1219
+ super(message, {
1220
+ code: AuthConfigErrorCodes.AUTH_CONFIG_NOT_FOUND,
1221
+ cause: meta,
1222
+ possibleFixes: [
1223
+ "Check if the auth config exists",
1224
+ "Check if the auth config id is correct",
1225
+ "Check if the auth config is enabled"
1226
+ ]
1227
+ });
1228
+ this.name = "ComposioAuthConfigNotFoundError";
1229
+ }
1230
+ };
1231
+
1212
1232
  // src/types/connectedAccounts.types.ts
1213
1233
  import { z as z4 } from "zod";
1214
1234
  var ConnectedAccountStatuses = {
1215
1235
  ACTIVE: "ACTIVE",
1216
1236
  INACTIVE: "INACTIVE",
1217
- PENDING: "DELETED",
1237
+ DELETED: "DELETED",
1218
1238
  INITIATED: "INITIATED",
1219
1239
  EXPIRED: "EXPIRED",
1220
1240
  FAILED: "FAILED"
@@ -1222,7 +1242,7 @@ var ConnectedAccountStatuses = {
1222
1242
  var ConnectedAccountStatusSchema = z4.enum([
1223
1243
  ConnectedAccountStatuses.ACTIVE,
1224
1244
  ConnectedAccountStatuses.INACTIVE,
1225
- ConnectedAccountStatuses.PENDING,
1245
+ ConnectedAccountStatuses.DELETED,
1226
1246
  ConnectedAccountStatuses.INITIATED,
1227
1247
  ConnectedAccountStatuses.EXPIRED,
1228
1248
  ConnectedAccountStatuses.FAILED
@@ -1310,15 +1330,43 @@ var ConnectedAccountRetrieveResponseSchema = z4.object({
1310
1330
  });
1311
1331
 
1312
1332
  // src/models/ConnectionRequest.ts
1313
- import { ZodError } from "zod";
1333
+ import { ZodError as ZodError2 } from "zod";
1334
+
1335
+ // src/errors/ConnectionRequestError.ts
1336
+ var ConnectionRequestErrorCodes = {
1337
+ CONNECTION_REQUEST_TIMEOUT: "CONNECTION_REQUEST_TIMEOUT",
1338
+ CONNECTION_REQUEST_FAILED: "CONNECTION_REQUEST_FAILED"
1339
+ };
1340
+ var ConnectionRequestTimeoutError = class extends ComposioError {
1341
+ constructor(message = "Connection request timed out", meta = {}) {
1342
+ super(message, {
1343
+ code: ConnectionRequestErrorCodes.CONNECTION_REQUEST_TIMEOUT,
1344
+ meta
1345
+ });
1346
+ this.name = "ConnectionRequestTimeoutError";
1347
+ }
1348
+ };
1349
+ var ConnectionRequestFailedError = class extends ComposioError {
1350
+ constructor(message = "Connection request failed", meta = {}) {
1351
+ super(message, {
1352
+ code: ConnectionRequestErrorCodes.CONNECTION_REQUEST_FAILED,
1353
+ meta
1354
+ });
1355
+ this.name = "ConnectionRequestFailedError";
1356
+ }
1357
+ };
1358
+
1359
+ // src/models/ConnectionRequest.ts
1314
1360
  var ConnectionRequest = class {
1315
1361
  client;
1316
1362
  connectedAccountId;
1317
1363
  connectedAccountStatus;
1318
- constructor(client, connectedAccountId, connectedAccountStatus) {
1364
+ redirectUrl;
1365
+ constructor(client, connectedAccountId, connectedAccountStatus, redirectUrl) {
1319
1366
  this.client = client;
1320
1367
  this.connectedAccountId = connectedAccountId;
1321
1368
  this.connectedAccountStatus = connectedAccountStatus;
1369
+ this.redirectUrl = redirectUrl;
1322
1370
  }
1323
1371
  /**
1324
1372
  * Transform the response from the Composio API to the SDK format
@@ -1345,145 +1393,550 @@ var ConnectionRequest = class {
1345
1393
  });
1346
1394
  return parsedResponse;
1347
1395
  } catch (error) {
1348
- logger_default.error("Error transforming response", error);
1349
- if (error instanceof ZodError) {
1350
- logger_default.error(JSON.stringify(error.errors, null, 2));
1351
- }
1352
- throw error;
1396
+ logger_default.error("Error transforming response", error);
1397
+ if (error instanceof ZodError2) {
1398
+ logger_default.error(JSON.stringify(error.errors, null, 2));
1399
+ }
1400
+ throw error;
1401
+ }
1402
+ }
1403
+ /**
1404
+ * Wait for the connection to be established.
1405
+ * The function will poll the Composio API every second until the connection is established or the timeout is reached.
1406
+ * @param {number} timeout - The time in milliseconds to wait for the connection to be established. Default is 30 seconds.
1407
+ * @returns
1408
+ */
1409
+ async waitForConnection(timeout = 6e4) {
1410
+ if (this.connectedAccountStatus === ConnectedAccountStatuses.ACTIVE) {
1411
+ const response = await this.client.connectedAccounts.retrieve(this.connectedAccountId);
1412
+ return this.transformResponse(response);
1413
+ }
1414
+ const terminalErrorStates = [
1415
+ ConnectedAccountStatuses.FAILED,
1416
+ ConnectedAccountStatuses.EXPIRED,
1417
+ ConnectedAccountStatuses.DELETED
1418
+ ];
1419
+ const start = Date.now();
1420
+ const pollInterval = 1e3;
1421
+ while (Date.now() - start < timeout) {
1422
+ try {
1423
+ const response = await this.client.connectedAccounts.retrieve(this.connectedAccountId);
1424
+ if (response.status === ConnectedAccountStatuses.ACTIVE) {
1425
+ return this.transformResponse(response);
1426
+ }
1427
+ if (terminalErrorStates.includes(response.status)) {
1428
+ throw new ConnectionRequestFailedError(
1429
+ `Connection request failed with status: ${response.status}${response.status_reason ? `, reason: ${response.status_reason}` : ""}`,
1430
+ {
1431
+ userId: response.user_id,
1432
+ connectedAccountId: this.connectedAccountId,
1433
+ status: response.status,
1434
+ statusReason: response.status_reason
1435
+ }
1436
+ );
1437
+ }
1438
+ await new Promise((resolve) => setTimeout(resolve, pollInterval));
1439
+ } catch (error) {
1440
+ throw error;
1441
+ }
1442
+ }
1443
+ throw new ConnectionRequestTimeoutError(
1444
+ `Connection request timed out for ${this.connectedAccountId}`
1445
+ );
1446
+ }
1447
+ };
1448
+
1449
+ // src/models/ConnectedAccounts.ts
1450
+ var ConnectedAccounts = class {
1451
+ client;
1452
+ constructor(client) {
1453
+ this.client = client;
1454
+ }
1455
+ /**
1456
+ * List all connected accounts
1457
+ * @param {ConnectedAccountListParams} query - Query parameters for filtering connected accounts
1458
+ * @param {RequestOptions} options - Request options
1459
+ * @returns {Promise<ConnectedAccountListResponse>} List of connected accounts
1460
+ */
1461
+ async list(query) {
1462
+ return this.client.connectedAccounts.list(query);
1463
+ }
1464
+ /**
1465
+ * Compound function to create a new connected account.
1466
+ * This function creates a new connected account and returns a connection request.
1467
+ * Users can then wait for the connection to be established using the `waitForConnection` method.
1468
+ * @param {string} userId - User ID of the connected account
1469
+ * @param {string} authConfigId - Auth config ID of the connected account
1470
+ * @param {CreateConnectedAccountOptions} data - Data for creating a new connected account
1471
+ * @returns {Promise<ConnectionRequest>} Connection request object
1472
+ *
1473
+ * @example
1474
+ * const connectionRequest = await composio.createConnectedAccount('user_123', 'auth_config_123', {
1475
+ * data: {
1476
+ * name: 'My Connected Account',
1477
+ * },
1478
+ * });
1479
+ *
1480
+ * @link https://docs.composio.dev/reference/connected-accounts/create-connected-account
1481
+ */
1482
+ async initiate(userId, authConfigId, options) {
1483
+ const response = await this.client.connectedAccounts.create({
1484
+ auth_config: {
1485
+ id: authConfigId
1486
+ },
1487
+ connection: {
1488
+ data: options?.data,
1489
+ redirect_uri: options?.redirectUrl,
1490
+ user_id: userId
1491
+ }
1492
+ });
1493
+ return new ConnectionRequest(this.client, response.id, response.status, response.redirect_uri);
1494
+ }
1495
+ /**
1496
+ * Get a connected account by nanoid
1497
+ * @param {string} nanoid - Unique identifier of the connected account
1498
+ * @param {RequestOptions} options - Request options
1499
+ * @returns {Promise<ConnectedAccountRetrieveResponse>} Connected account details
1500
+ */
1501
+ async get(nanoid) {
1502
+ return this.client.connectedAccounts.retrieve(nanoid);
1503
+ }
1504
+ /**
1505
+ * Delete a connected account
1506
+ * @param {string} nanoid - Unique identifier of the connected account to delete
1507
+ * @param {RequestOptions} options - Request options
1508
+ * @returns {Promise<ConnectedAccountDeleteResponse>} Response from deletion
1509
+ */
1510
+ async delete(nanoid) {
1511
+ return this.client.connectedAccounts.delete(nanoid);
1512
+ }
1513
+ /**
1514
+ * Refresh a connected account's credentials
1515
+ * @param {string} nanoid - Unique identifier of the connected account to refresh
1516
+ * @param {RequestOptions} options - Request options
1517
+ * @returns {Promise<ConnectedAccountRefreshResponse>} Refreshed connected account details
1518
+ */
1519
+ async refresh(nanoid) {
1520
+ return this.client.connectedAccounts.refresh(nanoid);
1521
+ }
1522
+ /**
1523
+ * Update the status of a connected account
1524
+ * @param {string} nanoid - Unique identifier of the connected account
1525
+ * @param {ConnectedAccountUpdateStatusParams} params - Parameters for updating the status
1526
+ * @param {RequestOptions} options - Request options
1527
+ * @returns {Promise<ConnectedAccountUpdateStatusResponse>} Updated connected account details
1528
+ */
1529
+ async updateStatus(nanoid, params) {
1530
+ return this.client.connectedAccounts.updateStatus(nanoid, params);
1531
+ }
1532
+ /**
1533
+ * Enable a connected account
1534
+ * @param {string} nanoid - Unique identifier of the connected account
1535
+ * @param {RequestOptions} options - Request options
1536
+ * @returns {Promise<ConnectedAccountUpdateStatusResponse>} Updated connected account details
1537
+ */
1538
+ async enable(nanoid) {
1539
+ return this.client.connectedAccounts.updateStatus(nanoid, { enabled: true });
1540
+ }
1541
+ /**
1542
+ * Disable a connected account
1543
+ * @param {string} nanoid - Unique identifier of the connected account
1544
+ * @param {RequestOptions} options - Request options
1545
+ * @returns {Promise<ConnectedAccountUpdateStatusResponse>} Updated connected account details
1546
+ */
1547
+ async disable(nanoid) {
1548
+ return this.client.connectedAccounts.updateStatus(nanoid, { enabled: false });
1549
+ }
1550
+ };
1551
+
1552
+ // src/models/Toolkits.ts
1553
+ var Toolkits = class {
1554
+ client;
1555
+ constructor(client) {
1556
+ this.client = client;
1557
+ this.authorize = this.authorize.bind(this);
1558
+ }
1559
+ /**
1560
+ * List all toolkits available in the Composio SDK.
1561
+ * This method fetches the toolkits from the Composio API.
1562
+ * @returns {Promise<Toolkit[]>} List of toolkits
1563
+ */
1564
+ async getToolkits(query) {
1565
+ const parsedQuery = ToolkitsListParamsSchema.parse(query);
1566
+ const result = await this.client.toolkits.list({
1567
+ category: parsedQuery.category,
1568
+ is_local: parsedQuery.isLocal,
1569
+ managed_by: parsedQuery.managedBy,
1570
+ sort_by: parsedQuery.sortBy
1571
+ });
1572
+ const parsedResult = ToolKitListResponseSchema.parse({
1573
+ items: result.items.map((item) => {
1574
+ const parsedItem = ToolKitItemSchema.parse({
1575
+ name: item.name,
1576
+ slug: item.slug,
1577
+ meta: item.meta,
1578
+ isLocalToolkit: item.is_local_toolkit,
1579
+ authSchemes: item.auth_schemes,
1580
+ composioManagedAuthSchemes: item.composio_managed_auth_schemes,
1581
+ noAuth: item.no_auth
1582
+ });
1583
+ return parsedItem;
1584
+ }),
1585
+ nextCursor: result.next_cursor,
1586
+ totalPages: result.total_pages
1587
+ });
1588
+ return parsedResult;
1589
+ }
1590
+ /**
1591
+ * Fetches a toolkit by its Slug.
1592
+ * This method retrieves the toolkit from the Composio API.
1593
+ * @param slug - The ID of the toolkit to be retrieved
1594
+ * @param options - Request options
1595
+ * @returns {Promise<ToolkitRetrieveResponse>} The toolkit object
1596
+ */
1597
+ async getToolkitBySlug(slug) {
1598
+ try {
1599
+ const result = await this.client.toolkits.retrieve(slug);
1600
+ const parsedResult = ToolkitRetrieveResponseSchema.parse({
1601
+ name: result.name,
1602
+ slug: result.slug,
1603
+ meta: {
1604
+ ...result.meta,
1605
+ createdAt: result.meta.created_at,
1606
+ updatedAt: result.meta.updated_at,
1607
+ toolsCount: result.meta.tools_count,
1608
+ triggersCount: result.meta.triggers_count
1609
+ // appUrl: result.meta.app_url, @TODO Update the client type to include this
1610
+ },
1611
+ isLocalToolkit: result.is_local_toolkit,
1612
+ composioManagedAuthSchemes: result.composio_managed_auth_schemes,
1613
+ authConfigDetails: result.auth_config_details?.map((authConfig) => ({
1614
+ name: authConfig.name,
1615
+ mode: authConfig.mode,
1616
+ fields: {
1617
+ authConfigCreation: authConfig.fields.auth_config_creation,
1618
+ connectedAccountInitiation: authConfig.fields.connected_account_initiation
1619
+ },
1620
+ proxy: {
1621
+ baseUrl: authConfig.proxy?.base_url
1622
+ }
1623
+ }))
1624
+ });
1625
+ return parsedResult;
1626
+ } catch (error) {
1627
+ if (error instanceof ZodError3) {
1628
+ throw new ValidationError(error);
1629
+ }
1630
+ throw new ComposioToolNotFoundError(`Toolkit with slug ${slug} not found`, {
1631
+ slug
1632
+ });
1633
+ }
1634
+ }
1635
+ /**
1636
+ * Fetches a toolkit by its Slug or a list of toolkits.
1637
+ * This method retrieves the toolkit from the Composio API.
1638
+ * @param arg - The ID of the toolkit to be retrieved or a list of parameters
1639
+ * @returns {Promise<ToolkitRetrieveResponse | ToolKitListResponse>} The toolkit object or a list of toolkits
1640
+ */
1641
+ async get(arg) {
1642
+ if (typeof arg === "string") {
1643
+ return this.getToolkitBySlug(arg);
1644
+ }
1645
+ return this.getToolkits(arg);
1646
+ }
1647
+ /**
1648
+ * Fetches all categories available in the Composio SDK
1649
+ *
1650
+ * @returns {Promise<ToolkitRetrieveCategoriesResponse>} List of categories
1651
+ */
1652
+ async listCategories() {
1653
+ const result = await this.client.toolkits.retrieveCategories();
1654
+ const parsedResult = ToolkitRetrieveCategoriesResponseSchema.parse({
1655
+ items: result.items.map((item) => {
1656
+ const parsedItem = ToolkitCategorySchema.parse({
1657
+ id: item.id,
1658
+ name: item.name
1659
+ });
1660
+ return parsedItem;
1661
+ }),
1662
+ nextCursor: result.next_cursor,
1663
+ totalPages: result.total_pages
1664
+ });
1665
+ return parsedResult;
1666
+ }
1667
+ /**
1668
+ * Authorizes a user to use a toolkit.
1669
+ * This method will create an auth config if one doesn't exist and initiate a connection request.
1670
+ * @param {string} userId - The user id of the user to authorize
1671
+ * @param {string} toolkitSlug - The slug of the toolkit to authorize
1672
+ * @param {string} authConfigId - The id of the auth config to use
1673
+ * @returns {Promise<ConnectionRequest>} The connection request object
1674
+ */
1675
+ async authorize(userId, toolkitSlug) {
1676
+ const toolkit = await this.getToolkitBySlug(toolkitSlug);
1677
+ const composioAuthConfig = new AuthConfigs(this.client);
1678
+ let authConfigIdToUse;
1679
+ const authConfig = await composioAuthConfig.list({
1680
+ toolkitSlug
1681
+ });
1682
+ authConfigIdToUse = authConfig.items[0]?.id;
1683
+ if (!authConfigIdToUse) {
1684
+ if (toolkit.authConfigDetails && toolkit.authConfigDetails.length > 0) {
1685
+ const authConfig2 = await composioAuthConfig.create(toolkitSlug, {
1686
+ type: "use_composio_managed_auth",
1687
+ name: `${toolkit.name} Auth Config`
1688
+ });
1689
+ authConfigIdToUse = authConfig2.id;
1690
+ } else {
1691
+ throw new ComposioAuthConfigNotFoundError("No auth config found for toolkit", {
1692
+ toolkitSlug
1693
+ });
1694
+ }
1695
+ }
1696
+ const composioConnectedAccount = new ConnectedAccounts(this.client);
1697
+ return await composioConnectedAccount.initiate(userId, authConfigIdToUse);
1698
+ }
1699
+ };
1700
+
1701
+ // src/utils/pusher.ts
1702
+ var PUSHER_KEY = process.env.CLIENT_PUSHER_KEY || "ff9f18c208855d77a152";
1703
+ var PUSHER_CLUSTER = "mt1";
1704
+ var PusherUtils = class _PusherUtils {
1705
+ static pusherClient;
1706
+ static getPusherClient(baseURL, apiKey) {
1707
+ if (!_PusherUtils.pusherClient) {
1708
+ const PusherClient = __require("pusher-js");
1709
+ _PusherUtils.pusherClient = new PusherClient(PUSHER_KEY, {
1710
+ cluster: PUSHER_CLUSTER,
1711
+ channelAuthorization: {
1712
+ endpoint: `${baseURL}/api/v1/client/auth/pusher_auth`,
1713
+ headers: {
1714
+ "x-api-key": apiKey
1715
+ },
1716
+ transport: "ajax"
1717
+ }
1718
+ });
1719
+ }
1720
+ return _PusherUtils.pusherClient;
1721
+ }
1722
+ /**
1723
+ * Subscribes to a Pusher channel and binds an event to a callback function.
1724
+ * @param {string} channelName - The name of the channel to subscribe to.
1725
+ * @param {string} event - The event to bind to the channel.
1726
+ * @param {(data: Record<string, unknown>) => void} fn - The callback function to execute when the event is triggered.
1727
+ * @returns {PusherClient} The Pusher client instance.
1728
+ */
1729
+ static async subscribe(channelName, event, fn) {
1730
+ try {
1731
+ await _PusherUtils.pusherClient.subscribe(channelName).bind(event, fn);
1732
+ } catch (error) {
1733
+ logger_default.error(
1734
+ `Error subscribing to ${channelName} with event ${event}: ${error}`
1735
+ );
1353
1736
  }
1354
1737
  }
1355
1738
  /**
1356
- * Wait for the connection to be established.
1357
- * The function will poll the Composio API every second until the connection is established or the timeout is reached.
1358
- * @param {number} timeout - The time in milliseconds to wait for the connection to be established. Default is 30 seconds.
1359
- * @returns
1739
+ * Unsubscribes from a Pusher channel.
1740
+ * @param {string} channelName - The name of the channel to unsubscribe from.
1741
+ * @returns {void}
1360
1742
  */
1361
- async waitForConnection(timeout = 6e4) {
1362
- if (this.connectedAccountStatus === ConnectedAccountStatuses.ACTIVE) {
1363
- const response = await this.client.connectedAccounts.retrieve(this.connectedAccountId);
1364
- return Promise.resolve(this.transformResponse(response));
1365
- }
1366
- return new Promise((resolve, reject) => {
1367
- const interval = setInterval(async () => {
1368
- try {
1369
- const response = await this.client.connectedAccounts.retrieve(this.connectedAccountId);
1370
- if (response.status === ConnectedAccountStatuses.ACTIVE) {
1371
- clearInterval(interval);
1372
- resolve(this.transformResponse(response));
1373
- }
1374
- } catch (error) {
1375
- clearInterval(interval);
1376
- reject(error);
1377
- }
1378
- }, 1e3);
1379
- setTimeout(() => {
1380
- clearInterval(interval);
1381
- reject(new Error("Connection request timed out"));
1382
- }, timeout);
1743
+ static async unsubscribe(channelName) {
1744
+ _PusherUtils.pusherClient.unsubscribe(channelName);
1745
+ }
1746
+ /**
1747
+ * Binds an event to a channel with support for chunked messages.
1748
+ * @param {PusherClient} channel - The Pusher channel to bind the event to.
1749
+ * @param {string} event - The event to bind to the channel.
1750
+ * @param {(data: unknown) => void} callback - The callback function to execute when the event is triggered.
1751
+ */
1752
+ static bindWithChunking(channel, event, callback) {
1753
+ channel.bind(event, callback);
1754
+ const events = {};
1755
+ channel.bind("chunked-" + event, (data) => {
1756
+ const typedData = data;
1757
+ if (!events.hasOwnProperty(typedData.id)) {
1758
+ events[typedData.id] = { chunks: [], receivedFinal: false };
1759
+ }
1760
+ const ev = events[typedData.id];
1761
+ ev.chunks[typedData.index] = typedData.chunk;
1762
+ if (typedData.final) ev.receivedFinal = true;
1763
+ if (ev.receivedFinal && ev.chunks.length === Object.keys(ev.chunks).length) {
1764
+ callback(JSON.parse(ev.chunks.join("")));
1765
+ delete events[typedData.id];
1766
+ }
1383
1767
  });
1384
1768
  }
1769
+ /**
1770
+ * Subscribes to a trigger channel for a client and handles chunked data.
1771
+ * @param {string} clientId - The unique identifier for the client subscribing to the events.
1772
+ * @param {(data: TriggerData) => void} fn - The callback function to execute when trigger data is received.
1773
+ */
1774
+ static triggerSubscribe(clientId, fn) {
1775
+ const channel = _PusherUtils.pusherClient.subscribe(
1776
+ `private-${clientId}_triggers`
1777
+ );
1778
+ _PusherUtils.bindWithChunking(
1779
+ channel,
1780
+ "trigger_to_client",
1781
+ fn
1782
+ );
1783
+ logger_default.info(
1784
+ `Subscribed to triggers. You should start receiving events now.`
1785
+ );
1786
+ }
1787
+ static triggerUnsubscribe(clientId) {
1788
+ _PusherUtils.pusherClient.unsubscribe(`${clientId}_triggers`);
1789
+ }
1385
1790
  };
1386
1791
 
1387
- // src/models/ConnectedAccounts.ts
1388
- var ConnectedAccounts = class {
1792
+ // src/models/Session.ts
1793
+ var Session = class {
1389
1794
  client;
1390
1795
  constructor(client) {
1391
1796
  this.client = client;
1392
1797
  }
1393
1798
  /**
1394
- * List all connected accounts
1395
- * @param {ConnectedAccountListParams} query - Query parameters for filtering connected accounts
1396
- * @param {RequestOptions} options - Request options
1397
- * @returns {Promise<ConnectedAccountListResponse>} List of connected accounts
1799
+ * Get the active session info
1800
+ * @returns {Promise<SessionGetInfoResponse>} Session info
1398
1801
  */
1399
- async list(query) {
1400
- return this.client.connectedAccounts.list(query);
1802
+ async getInfo() {
1803
+ return this.client.auth.session.getInfo();
1804
+ }
1805
+ };
1806
+
1807
+ // src/models/Triggers.ts
1808
+ var Triggers = class {
1809
+ client;
1810
+ constructor(client) {
1811
+ this.client = client;
1401
1812
  }
1402
1813
  /**
1403
- * Compound function to create a new connected account.
1404
- * This function creates a new connected account and returns a connection request.
1405
- * Users can then wait for the connection to be established using the `waitForConnection` method.
1406
- * @param {string} userId - User ID of the connected account
1407
- * @param {string} authConfigId - Auth config ID of the connected account
1408
- * @param {CreateConnectedAccountOptions} data - Data for creating a new connected account
1409
- * @returns {Promise<ConnectionRequest>} Connection request object
1814
+ * Fetch list of all the active triggers
1815
+ * @returns {Promise<TriggerInstance[]>} List of trigger instances
1816
+ */
1817
+ async list(query, options) {
1818
+ return this.client.triggerInstances.listActive(query, options);
1819
+ }
1820
+ /**
1821
+ * Create a new trigger instance
1410
1822
  *
1411
- * @example
1412
- * const connectionRequest = await composio.createConnectedAccount('user_123', 'auth_config_123', {
1413
- * data: {
1414
- * name: 'My Connected Account',
1415
- * },
1416
- * });
1823
+ * @param {string} slug - The slug of the trigger instance
1824
+ * @param {TriggerInstanceUpsertParams} body - The parameters to create the trigger instance
1825
+ * @returns {Promise<TriggerInstanceUpsertResponse>} The created trigger instance
1826
+ */
1827
+ async create(slug, body, options) {
1828
+ return this.client.triggerInstances.upsert(slug, body, options);
1829
+ }
1830
+ /**
1831
+ * Update an existing trigger instance
1417
1832
  *
1418
- * @link https://docs.composio.dev/reference/connected-accounts/create-connected-account
1833
+ * @param {string} slug - The slug of the trigger instance
1834
+ * @param {TriggerInstanceUpsertParams} body - The parameters to create the trigger instance
1835
+ * @returns {Promise<TriggerInstanceUpsertResponse>} The updated trigger instance
1419
1836
  */
1420
- async create(userId, authConfigId, options) {
1421
- const response = await this.client.connectedAccounts.create({
1422
- auth_config: {
1423
- id: authConfigId
1424
- },
1425
- connection: {
1426
- data: options?.data,
1427
- redirect_uri: options?.redirectUrl,
1428
- user_id: userId
1429
- }
1430
- });
1431
- return new ConnectionRequest(this.client, response.id, response.status);
1837
+ async update(slug, body, options) {
1838
+ return this.client.triggerInstances.upsert(slug, body, options);
1432
1839
  }
1433
1840
  /**
1434
- * Get a connected account by nanoid
1435
- * @param {string} nanoid - Unique identifier of the connected account
1436
- * @param {RequestOptions} options - Request options
1437
- * @returns {Promise<ConnectedAccountRetrieveResponse>} Connected account details
1841
+ * Delete a trigger instance
1842
+ *
1843
+ * @param {string} slug - The slug of the trigger instance
1844
+ * @returns
1438
1845
  */
1439
- async get(nanoid) {
1440
- return this.client.connectedAccounts.retrieve(nanoid);
1846
+ async delete(slug) {
1847
+ return this.client.triggerInstances.removeUpsert(slug);
1441
1848
  }
1442
1849
  /**
1443
- * Delete a connected account
1444
- * @param {string} nanoid - Unique identifier of the connected account to delete
1850
+ * Update the status of a trigger
1851
+ *
1852
+ * @param {TriggerStatusEnum} status - The new status of the trigger
1853
+ * @param {TriggerInstanceUpdateStatusParams} params - The parameters to update the trigger instance
1445
1854
  * @param {RequestOptions} options - Request options
1446
- * @returns {Promise<ConnectedAccountDeleteResponse>} Response from deletion
1855
+ * @returns {Promise<TriggerInstanceUpsertResponse>} The updated trigger instance
1447
1856
  */
1448
- async delete(nanoid) {
1449
- return this.client.connectedAccounts.delete(nanoid);
1857
+ async updateStatus(status, params, options) {
1858
+ return this.client.triggerInstances.updateStatus(status, params, options);
1450
1859
  }
1451
1860
  /**
1452
- * Refresh a connected account's credentials
1453
- * @param {string} nanoid - Unique identifier of the connected account to refresh
1454
- * @param {RequestOptions} options - Request options
1455
- * @returns {Promise<ConnectedAccountRefreshResponse>} Refreshed connected account details
1861
+ * Disable a trigger instance
1862
+ *
1863
+ * @param {string} slug - The slug of the trigger instance
1864
+ * @param {RequestOptions options - Request options
1865
+ * @returns {Promise<TriggerInstanceUpsertResponse>} The updated trigger instance
1456
1866
  */
1457
- async refresh(nanoid) {
1458
- return this.client.connectedAccounts.refresh(nanoid);
1867
+ async disable(slug, options) {
1868
+ return this.client.triggerInstances.updateStatus("disable", { slug }, options);
1459
1869
  }
1460
1870
  /**
1461
- * Update the status of a connected account
1462
- * @param {string} nanoid - Unique identifier of the connected account
1463
- * @param {ConnectedAccountUpdateStatusParams} params - Parameters for updating the status
1464
- * @param {RequestOptions} options - Request options
1465
- * @returns {Promise<ConnectedAccountUpdateStatusResponse>} Updated connected account details
1871
+ * Enable a trigger instance
1872
+ *
1873
+ * @param {string} slug - The slug of the trigger instance
1874
+ * @param {RequestOptions options - Request options
1875
+ * @returns {Promise<TriggerInstanceUpsertResponse>} The updated trigger instance
1466
1876
  */
1467
- async updateStatus(nanoid, params) {
1468
- return this.client.connectedAccounts.updateStatus(nanoid, params);
1877
+ async enable(slug, options) {
1878
+ return this.client.triggerInstances.updateStatus("enable", { slug }, options);
1469
1879
  }
1470
1880
  /**
1471
- * Enable a connected account
1472
- * @param {string} nanoid - Unique identifier of the connected account
1881
+ * @TODO Learn about trigger types
1882
+ */
1883
+ /**
1884
+ * List all the trigger types
1885
+ *
1886
+ * @param {TriggersTypeListParams} query - The query parameters to filter the trigger types
1473
1887
  * @param {RequestOptions} options - Request options
1474
- * @returns {Promise<ConnectedAccountUpdateStatusResponse>} Updated connected account details
1888
+ * @returns {Promise<TriggersTypeListResponse>} The list of trigger types
1475
1889
  */
1476
- async enable(nanoid) {
1477
- return this.client.connectedAccounts.updateStatus(nanoid, { enabled: true });
1890
+ async listTypes(query, options) {
1891
+ return this.client.triggersTypes.list(query, options);
1478
1892
  }
1479
1893
  /**
1480
- * Disable a connected account
1481
- * @param {string} nanoid - Unique identifier of the connected account
1482
- * @param {RequestOptions} options - Request options
1483
- * @returns {Promise<ConnectedAccountUpdateStatusResponse>} Updated connected account details
1894
+ * Retrieve a trigger type by its slug
1895
+ *
1896
+ * @param {string} slug - The slug of the trigger type
1897
+ * @param {RequestOptions} options - request options
1898
+ * @returns {Promise<TriggersTypeRetrieveResponse>} The trigger type object
1484
1899
  */
1485
- async disable(nanoid) {
1486
- return this.client.connectedAccounts.updateStatus(nanoid, { enabled: false });
1900
+ async getType(slug, options) {
1901
+ return this.client.triggersTypes.retrieve(slug, options);
1902
+ }
1903
+ /**
1904
+ * Fetches the list of all the available trigger enums
1905
+ *
1906
+ * This method is used by the CLI where filters are not required.
1907
+ * @param options
1908
+ * @returns
1909
+ */
1910
+ async listEnum(options) {
1911
+ return this.client.triggersTypes.retrieveEnum(options);
1912
+ }
1913
+ async subscribe(fn, filters = {}) {
1914
+ if (!fn) throw new Error("Function is required for trigger subscription");
1915
+ const session = new Session(this.client);
1916
+ const sessionInfo = await session.getInfo();
1917
+ const clientId = sessionInfo.project?.id;
1918
+ if (!clientId) throw new Error("Client ID not found");
1919
+ if (!this.client.apiKey) throw new Error("API key not found");
1920
+ await PusherUtils.getPusherClient(this.client.baseURL, this.client.apiKey);
1921
+ const shouldSendTrigger = (data) => {
1922
+ if (Object.keys(filters).length === 0) return true;
1923
+ else {
1924
+ return (!filters.appName || data.appName.toLowerCase() === filters.appName.toLowerCase()) && (!filters.triggerId || data.metadata.id.toLowerCase() === filters.triggerId.toLowerCase()) && (!filters.connectionId || data.metadata.connectionId.toLowerCase() === filters.connectionId.toLowerCase()) && (!filters.triggerName || data.metadata.triggerName.toLowerCase() === filters.triggerName.toLowerCase()) && (!filters.entityId || data.metadata.connection.clientUniqueUserId.toLowerCase() === filters.entityId.toLowerCase()) && (!filters.integrationId || data.metadata.connection.integrationId.toLowerCase() === filters.integrationId.toLowerCase());
1925
+ }
1926
+ };
1927
+ logger_default.debug("Subscribing to triggers", filters);
1928
+ PusherUtils.triggerSubscribe(clientId, (data) => {
1929
+ if (shouldSendTrigger(data)) {
1930
+ fn(data);
1931
+ }
1932
+ });
1933
+ }
1934
+ async unsubscribe() {
1935
+ const session = new Session(this.client);
1936
+ const sessionInfo = await session.getInfo();
1937
+ const clientId = sessionInfo.project?.id;
1938
+ if (!clientId) throw new Error("Client ID not found");
1939
+ PusherUtils.triggerUnsubscribe(clientId);
1487
1940
  }
1488
1941
  };
1489
1942
 
@@ -1780,7 +2233,7 @@ var BaseToolset = class {
1780
2233
  /**
1781
2234
  * @internal
1782
2235
  * Set the function to execute a tool.
1783
- * This is set automatically injected by the core SDK.
2236
+ * This is set automatically and injected by the core SDK.
1784
2237
  */
1785
2238
  _setExecuteToolFn(executeToolFn) {
1786
2239
  this._globalExecuteToolFn = executeToolFn;
@@ -1795,6 +2248,9 @@ var BaseToolset = class {
1795
2248
  * @returns {Promise<string>} The result of the tool execution.
1796
2249
  */
1797
2250
  executeTool(toolSlug, body, modifers) {
2251
+ if (!this._globalExecuteToolFn) {
2252
+ throw new ComposioGlobalExecuteToolFnNotSetError("executeToolFn is not set");
2253
+ }
1798
2254
  return this._globalExecuteToolFn(toolSlug, body, modifers);
1799
2255
  }
1800
2256
  };
@@ -1837,8 +2293,8 @@ var OpenAIToolset = class extends BaseNonAgenticToolset {
1837
2293
  async executeToolCall(userId, tool, options, modifiers) {
1838
2294
  const payload = {
1839
2295
  arguments: JSON.parse(tool.function.arguments),
1840
- connectedAccountId: options.connectedAccountId,
1841
- customAuthParams: options.customAuthParams,
2296
+ connectedAccountId: options?.connectedAccountId,
2297
+ customAuthParams: options?.customAuthParams,
1842
2298
  userId
1843
2299
  };
1844
2300
  const result = await this.executeTool(tool.function.name, payload, modifiers);
@@ -1971,7 +2427,7 @@ var OpenAIToolset = class extends BaseNonAgenticToolset {
1971
2427
  };
1972
2428
 
1973
2429
  // package.json
1974
- var version = "0.1.8-alpha.0";
2430
+ var version = "0.1.10-alpha.0";
1975
2431
 
1976
2432
  // src/utils/uuid.ts
1977
2433
  import { v4 as uuidv4 } from "uuid";
@@ -2004,7 +2460,7 @@ var Composio = class {
2004
2460
  createAuthConfig;
2005
2461
  // connected accounts
2006
2462
  connectedAccounts;
2007
- createConnectedAccount;
2463
+ initiateConnection;
2008
2464
  /**
2009
2465
  * @param {Object} config Configuration for the Composio SDK.
2010
2466
  * @param {string} config.apiKey The API key for the Composio SDK.
@@ -2038,7 +2494,7 @@ var Composio = class {
2038
2494
  this.authConfigs = new AuthConfigs(this.client);
2039
2495
  this.createAuthConfig = this.authConfigs.create.bind(this.authConfigs);
2040
2496
  this.connectedAccounts = new ConnectedAccounts(this.client);
2041
- this.createConnectedAccount = this.connectedAccounts.create.bind(this.connectedAccounts);
2497
+ this.initiateConnection = this.connectedAccounts.initiate.bind(this.connectedAccounts);
2042
2498
  if (this.config.allowTracking ?? true) {
2043
2499
  this.initializeTelemetry(
2044
2500
  {