@composio/core 0.1.12-alpha.11 → 0.1.12-alpha.13

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
@@ -63,12 +63,13 @@ __export(index_exports, {
63
63
  ToolkitErrorCodes: () => ToolkitErrorCodes,
64
64
  ValidationError: () => ValidationError,
65
65
  ValidationErrorCodes: () => ValidationErrorCodes,
66
- jsonSchemaToModel: () => jsonSchemaToModel
66
+ jsonSchemaToZodSchema: () => jsonSchemaToZodSchema,
67
+ logger: () => logger_default
67
68
  });
68
69
  module.exports = __toCommonJS(index_exports);
69
70
 
70
71
  // src/composio.ts
71
- var import_client5 = __toESM(require("@composio/client"), 1);
72
+ var import_client6 = __toESM(require("@composio/client"), 1);
72
73
 
73
74
  // src/types/tool.types.ts
74
75
  var import_zod = require("zod");
@@ -77,12 +78,38 @@ var ToolkitSchema = import_zod.z.object({
77
78
  name: import_zod.z.string().describe("The name of the toolkit"),
78
79
  logo: import_zod.z.string().describe("The logo of the toolkit").optional()
79
80
  });
81
+ var JSONSchemaType = import_zod.z.enum([
82
+ "string",
83
+ "number",
84
+ "integer",
85
+ "boolean",
86
+ "object",
87
+ "array",
88
+ "null"
89
+ ]);
90
+ var JSONSchemaProperty = import_zod.z.object({
91
+ type: JSONSchemaType.optional(),
92
+ description: import_zod.z.string().optional(),
93
+ title: import_zod.z.string().optional(),
94
+ default: import_zod.z.any().optional(),
95
+ properties: import_zod.z.lazy(() => import_zod.z.record(import_zod.z.string(), JSONSchemaProperty)).optional(),
96
+ required: import_zod.z.array(import_zod.z.string()).optional(),
97
+ items: import_zod.z.lazy(() => JSONSchemaProperty).optional()
98
+ });
99
+ var ParametersSchema = import_zod.z.object({
100
+ type: import_zod.z.literal("object"),
101
+ properties: import_zod.z.record(import_zod.z.string(), JSONSchemaProperty),
102
+ required: import_zod.z.array(import_zod.z.string()).optional(),
103
+ title: import_zod.z.string().optional(),
104
+ description: import_zod.z.string().optional(),
105
+ additionalProperties: import_zod.z.boolean().optional()
106
+ });
80
107
  var ToolSchema = import_zod.z.object({
81
108
  slug: import_zod.z.string().describe('The slug of the tool. eg. "GOOGLE_SEARCH"'),
82
109
  name: import_zod.z.string().describe(`The name of the tool. eg. "Google Search"`),
83
110
  description: import_zod.z.string().optional().describe("The description of the tool"),
84
- inputParameters: import_zod.z.record(import_zod.z.string(), import_zod.z.unknown()).optional().describe("The input parameters of the tool"),
85
- outputParameters: import_zod.z.record(import_zod.z.string(), import_zod.z.unknown()).optional().describe("The output parameters of the tool"),
111
+ inputParameters: ParametersSchema.optional().describe("The input parameters of the tool"),
112
+ outputParameters: ParametersSchema.optional().describe("The output parameters of the tool"),
86
113
  tags: import_zod.z.optional(import_zod.z.array(import_zod.z.string())).describe("The tags of the tool. eg: Important").default([]),
87
114
  toolkit: import_zod.z.optional(ToolkitSchema).describe("The toolkit of the tool"),
88
115
  version: import_zod.z.optional(import_zod.z.string()).describe('The version of the tool, e.g. "1.0.0"')
@@ -92,14 +119,27 @@ var ToolListResponseSchema = import_zod.z.object({
92
119
  nextCursor: import_zod.z.string().nullable().optional(),
93
120
  totalPages: import_zod.z.number()
94
121
  });
95
- var ToolListParamsSchema = import_zod.z.object({
96
- tools: import_zod.z.array(import_zod.z.string()).optional(),
122
+ var ToolListFilterByToolsSchema = import_zod.z.object({
123
+ tools: import_zod.z.array(import_zod.z.string())
124
+ });
125
+ var ToolListFilterByToolkitsSchema = import_zod.z.object({
126
+ toolkits: import_zod.z.array(import_zod.z.string()),
127
+ important: import_zod.z.boolean().optional(),
97
128
  cursor: import_zod.z.string().optional(),
98
- important: import_zod.z.string().optional(),
99
- limit: import_zod.z.string().optional(),
100
- search: import_zod.z.string().optional(),
101
- toolkits: import_zod.z.array(import_zod.z.string()).optional()
129
+ limit: import_zod.z.number().optional(),
130
+ search: import_zod.z.string().optional()
102
131
  });
132
+ var ToolListFilterBySearchSchema = import_zod.z.object({
133
+ search: import_zod.z.string(),
134
+ toolkits: import_zod.z.array(import_zod.z.string()).optional(),
135
+ cursor: import_zod.z.string().optional(),
136
+ limit: import_zod.z.number().optional()
137
+ });
138
+ var ToolListParamsSchema = import_zod.z.union([
139
+ ToolListFilterByToolsSchema,
140
+ ToolListFilterByToolkitsSchema,
141
+ ToolListFilterBySearchSchema
142
+ ]);
103
143
  var CustomAuthParamsSchema = import_zod.z.object({
104
144
  baseURL: import_zod.z.string().optional(),
105
145
  body: import_zod.z.record(import_zod.z.string(), import_zod.z.unknown()).optional(),
@@ -234,18 +274,19 @@ var ComposioError = class _ComposioError extends Error {
234
274
  */
235
275
  constructor(message, options = {}) {
236
276
  super(message);
277
+ if (Error.captureStackTrace) {
278
+ Error.captureStackTrace(this, this.constructor);
279
+ }
237
280
  const statusCode = options.statusCode || (options.cause instanceof import_client.BadRequestError ? options.cause.status : void 0);
238
281
  this.code = `TS-SDK::${options.code}`;
239
282
  this.possibleFixes = options.possibleFixes;
240
283
  this.definePropertyIfExists("statusCode", statusCode);
241
284
  this.definePropertyIfExists("cause", options.cause);
242
- this.definePropertyIfExists("stack", options.stack);
285
+ const combinedStack = options.cause instanceof Error ? _ComposioError.combineStackTraces(options.cause.stack, this.stack) : options.stack ?? this.stack;
286
+ this.definePropertyIfExists("stack", combinedStack);
243
287
  if (options.meta && Object.keys(options.meta).length > 0) {
244
288
  this.definePropertyIfExists("meta", options.meta);
245
289
  }
246
- if (Error.captureStackTrace) {
247
- Error.captureStackTrace(this, this.constructor);
248
- }
249
290
  }
250
291
  /**
251
292
  * Helper method to define a property only if it has a value
@@ -263,6 +304,25 @@ var ComposioError = class _ComposioError extends Error {
263
304
  });
264
305
  }
265
306
  }
307
+ /**
308
+ * Helper method to combine stack traces when wrapping errors
309
+ * This ensures the full call chain is preserved
310
+ * @param originalStack The stack of the error being wrapped
311
+ * @param currentStack The stack of the wrapper error
312
+ * @returns Combined stack trace
313
+ * @private
314
+ */
315
+ static combineStackTraces(originalStack, currentStack) {
316
+ if (!originalStack) return currentStack;
317
+ if (!currentStack) return originalStack;
318
+ const currentHeader = currentStack.split("\n")[0];
319
+ const originalStackBody = originalStack.split("\n").slice(1).join("\n");
320
+ return `${currentHeader}
321
+ ${currentStack.split("\n").slice(1).join("\n")}
322
+
323
+ Caused by:
324
+ ${originalStackBody}`;
325
+ }
266
326
  /**
267
327
  * Extract and normalize error data for formatting
268
328
  * @param includeStack Whether to include stack trace information
@@ -292,7 +352,16 @@ var ComposioError = class _ComposioError extends Error {
292
352
  data.possibleFixes = possibleFixes;
293
353
  }
294
354
  if (includeStack && stack) {
295
- data.stack = stack.split("\n").slice(1);
355
+ if (stack.includes("Caused by:")) {
356
+ const [currentStack, causeStack] = stack.split("Caused by:");
357
+ data.stack = [
358
+ ...currentStack.split("\n").slice(1),
359
+ "Caused by:",
360
+ ...causeStack.split("\n")
361
+ ];
362
+ } else {
363
+ data.stack = stack.split("\n").slice(1);
364
+ }
296
365
  }
297
366
  return data;
298
367
  }
@@ -496,7 +565,7 @@ var ComposioToolExecutionError = class extends ComposioError {
496
565
  "Ensure the tool is correctly configured and the input is valid"
497
566
  ]
498
567
  });
499
- this.error = originalError || (options.cause instanceof Error ? options.cause : new Error(String(options.cause)));
568
+ this.error = originalError || (options.cause instanceof Error ? options.cause : options.cause ? new Error(String(options.cause)) : new Error("Unknown error"));
500
569
  this.name = "ComposioToolExecutionError";
501
570
  }
502
571
  };
@@ -732,7 +801,7 @@ var TelemetryService = class {
732
801
  const descriptor = Object.getOwnPropertyDescriptor(proto, key);
733
802
  return key !== "constructor" && descriptor && typeof descriptor.value === "function" && descriptor.value.constructor.name === "AsyncFunction";
734
803
  });
735
- const instrumentedClassName = instance.constructor?.name || fileName || "unknown";
804
+ const instrumentedClassName = (instance.constructor?.name || fileName) ?? "unknown";
736
805
  for (const name of methodNames) {
737
806
  const originalMethod = instance[name];
738
807
  instance[name] = async (...args) => {
@@ -748,9 +817,11 @@ var TelemetryService = class {
748
817
  try {
749
818
  return await originalMethod.apply(instance, args);
750
819
  } catch (error) {
751
- if (error instanceof Error && !error.errorId) {
752
- error.errorId = getRandomUUID();
753
- this.prepareAndSendErrorTelemetry(error, instrumentedClassName, name, args);
820
+ if (error instanceof Error) {
821
+ if (!error.errorId) {
822
+ error.errorId = getRandomUUID();
823
+ this.prepareAndSendErrorTelemetry(error, instrumentedClassName, name, args);
824
+ }
754
825
  }
755
826
  throw error;
756
827
  }
@@ -784,7 +855,7 @@ var TelemetryService = class {
784
855
  error_id: error.errorId || "",
785
856
  error_message: error.message,
786
857
  original_error: error.cause || error,
787
- current_stack: error.stack?.split("\n") || [],
858
+ current_stack: error.stack ? error.stack.split("\n") : [],
788
859
  description: `Original Call : ${this.telemetryMetadata?.source}:${instrumentedClassName}.${name}(${JSON.stringify(args)})`
789
860
  };
790
861
  this.sendErrorTelemetry(telemetryPayload);
@@ -793,7 +864,7 @@ var TelemetryService = class {
793
864
  error_id: error.errorId || "",
794
865
  error_message: error.message,
795
866
  original_error: error.cause || error,
796
- current_stack: error.stack?.split("\n") || [],
867
+ current_stack: error.stack ? error.stack.split("\n") : [],
797
868
  error_code: error.code,
798
869
  possible_fix: error.possibleFixes?.join("\n"),
799
870
  description: `Original Call : ${instrumentedClassName}.${name}(${JSON.stringify(args)})`
@@ -804,7 +875,7 @@ var TelemetryService = class {
804
875
  error_id: error.errorId || "",
805
876
  error_message: error instanceof Error ? error.name : "Unknown error",
806
877
  original_error: error,
807
- current_stack: error.stack?.split("\n") || [],
878
+ current_stack: error.stack ? error.stack.split("\n") : [],
808
879
  description: `Original Call : ${this.telemetryMetadata?.source}:${instrumentedClassName}.${name}(${JSON.stringify(args)})`
809
880
  };
810
881
  this.sendErrorTelemetry(telemetryPayload);
@@ -893,7 +964,7 @@ var CustomTools = class {
893
964
  outputParameters: {
894
965
  type: "object",
895
966
  title: `Response for ${name}`,
896
- properties: []
967
+ properties: {}
897
968
  },
898
969
  tags: [],
899
970
  toolkit: { name: "custom", slug: "custom" }
@@ -951,8 +1022,7 @@ var CustomTools = class {
951
1022
  await this.client.toolkits.retrieve(toolkitSlug);
952
1023
  } catch (error) {
953
1024
  throw new ComposioToolNotFoundError(`Toolkit with slug ${toolkitSlug} not found`, {
954
- toolkitSlug,
955
- error
1025
+ cause: error
956
1026
  });
957
1027
  }
958
1028
  const connectedAccounts = await this.client.connectedAccounts.list({
@@ -961,10 +1031,7 @@ var CustomTools = class {
961
1031
  });
962
1032
  if (!connectedAccounts.items.length) {
963
1033
  throw new ComposioConnectedAccountNotFoundError(
964
- `No connected accounts found for toolkit ${toolkitSlug}`,
965
- {
966
- toolkitSlug
967
- }
1034
+ `No connected accounts found for toolkit ${toolkitSlug}`
968
1035
  );
969
1036
  }
970
1037
  return metadata.connectedAccountId ? connectedAccounts.items.find((item) => item.id === metadata.connectedAccountId) : connectedAccounts.items[0];
@@ -979,9 +1046,7 @@ var CustomTools = class {
979
1046
  async executeCustomTool(slug, inputParams, metadata) {
980
1047
  const tool = this.customToolsRegistry.get(slug.toLowerCase());
981
1048
  if (!tool) {
982
- throw new ComposioToolNotFoundError(`Tool with slug ${slug} not found`, {
983
- toolSlug: slug
984
- });
1049
+ throw new ComposioToolNotFoundError(`Tool with slug ${slug} not found`);
985
1050
  }
986
1051
  let authCredentials = {};
987
1052
  const { toolkitSlug, execute } = tool.options;
@@ -991,8 +1056,10 @@ var CustomTools = class {
991
1056
  throw new ComposioConnectedAccountNotFoundError(
992
1057
  `Connected account not found for toolkit ${toolkitSlug} for user ${metadata.userId}`,
993
1058
  {
994
- toolkitSlug,
995
- userId: metadata.userId
1059
+ meta: {
1060
+ toolkitSlug,
1061
+ userId: metadata.userId
1062
+ }
996
1063
  }
997
1064
  );
998
1065
  }
@@ -1000,7 +1067,9 @@ var CustomTools = class {
1000
1067
  }
1001
1068
  if (typeof execute !== "function") {
1002
1069
  throw new ComposioInvalidExecuteFunctionError("Invalid execute function", {
1003
- toolSlug: slug
1070
+ meta: {
1071
+ toolSlug: slug
1072
+ }
1004
1073
  });
1005
1074
  }
1006
1075
  const executeToolRequest = async (data) => {
@@ -1227,34 +1296,45 @@ var Tools = class {
1227
1296
  * );
1228
1297
  * ```
1229
1298
  */
1230
- async getRawComposioTools(userId, query = {}, modifier) {
1299
+ async getRawComposioTools(userId, query, modifier) {
1300
+ if ("tools" in query && "toolkits" in query) {
1301
+ throw new ValidationError(
1302
+ "Invalid tool list parameters. You should not use tools and toolkits filter together."
1303
+ );
1304
+ }
1231
1305
  const queryParams = ToolListParamsSchema.safeParse(query);
1232
1306
  if (queryParams.error) {
1233
1307
  throw new ValidationError("Invalid tool list parameters", {
1234
1308
  cause: queryParams.error
1235
1309
  });
1236
1310
  }
1311
+ if (!("tools" in queryParams.data || "toolkits" in queryParams.data || "search" in queryParams.data)) {
1312
+ throw new ValidationError(
1313
+ "Invalid tool list parameters, atleast one of the following parameters is required: tools, toolkits, search"
1314
+ );
1315
+ }
1237
1316
  const tools = await this.client.tools.list({
1238
- tool_slugs: queryParams.data.tools,
1239
- toolkit_slug: queryParams.data.toolkits?.join(","),
1240
- cursor: queryParams.data.cursor,
1241
- important: queryParams.data.important,
1242
- limit: queryParams.data.limit,
1243
- search: queryParams.data.search
1317
+ tool_slugs: "tools" in queryParams.data ? queryParams.data.tools?.join(",") : void 0,
1318
+ toolkit_slug: "toolkits" in queryParams.data ? queryParams.data.toolkits?.join(",") : void 0,
1319
+ cursor: "cursor" in queryParams.data ? queryParams.data.cursor : void 0,
1320
+ important: "important" in queryParams.data ? queryParams.data.important ? "true" : "false" : void 0,
1321
+ limit: "limit" in queryParams.data ? queryParams.data.limit?.toString() : void 0,
1322
+ search: "search" in queryParams.data ? queryParams.data.search : void 0
1244
1323
  });
1245
1324
  if (!tools) {
1246
1325
  return [];
1247
1326
  }
1248
1327
  const caseTransformedTools = tools.items.map((tool) => this.transformToolCases(tool));
1249
1328
  const customTools = await this.customTools.getCustomTools({
1250
- toolSlugs: queryParams.data.tools
1329
+ toolSlugs: "tools" in queryParams.data ? queryParams.data.tools : void 0
1251
1330
  });
1252
1331
  let modifiedTools = [...caseTransformedTools, ...customTools];
1253
1332
  if (modifier) {
1254
1333
  if (typeof modifier === "function") {
1255
- modifiedTools = modifiedTools.map((tool) => {
1256
- return modifier(tool.slug, tool.toolkit?.slug || "unkown", tool);
1257
- });
1334
+ const modifiedPromises = modifiedTools.map(
1335
+ (tool) => modifier(tool.slug, tool.toolkit?.slug ?? "unknown", tool)
1336
+ );
1337
+ modifiedTools = await Promise.all(modifiedPromises);
1258
1338
  } else {
1259
1339
  throw new ComposioInvalidModifierError("Invalid schema modifier. Not a function.");
1260
1340
  }
@@ -1285,15 +1365,15 @@ var Tools = class {
1285
1365
  cause: error
1286
1366
  });
1287
1367
  }
1288
- let modifiedToool = this.transformToolCases(tool);
1368
+ let modifiedTool = this.transformToolCases(tool);
1289
1369
  if (modifier) {
1290
1370
  if (typeof modifier === "function") {
1291
- modifiedToool = modifier(slug, modifiedToool.toolkit?.slug || "unkown", modifiedToool);
1371
+ modifiedTool = await modifier(slug, modifiedTool.toolkit?.slug ?? "unknown", modifiedTool);
1292
1372
  } else {
1293
1373
  throw new ComposioInvalidModifierError("Invalid schema modifier. Not a function.");
1294
1374
  }
1295
1375
  }
1296
- return modifiedToool;
1376
+ return modifiedTool;
1297
1377
  }
1298
1378
  /**
1299
1379
  * Get a tool or list of tools based on the provided arguments.
@@ -1316,8 +1396,10 @@ var Tools = class {
1316
1396
  }
1317
1397
  /**
1318
1398
  * @internal
1399
+ * @description
1319
1400
  * Creates a function that executes a tool.
1320
- * This function is used by agentic the toolsets to execute the tool
1401
+ * This function is used by agentic toolsets to execute the tool
1402
+ *
1321
1403
  * @param {string} userId - The user id
1322
1404
  * @param {ExecuteToolModifiers} modifiers - The modifiers to be applied to the tool
1323
1405
  * @returns {ExecuteToolFn} The execute tool function
@@ -1346,7 +1428,7 @@ var Tools = class {
1346
1428
  async handleCustomToolExecution(tool, body, modifiers) {
1347
1429
  if (modifiers?.beforeExecute) {
1348
1430
  if (typeof modifiers.beforeExecute === "function") {
1349
- body = modifiers.beforeExecute(tool.slug, "unkown", body);
1431
+ body = await modifiers.beforeExecute(tool.slug, "unknown", body);
1350
1432
  } else {
1351
1433
  throw new ComposioInvalidModifierError("Invalid beforeExecute modifier. Not a function.");
1352
1434
  }
@@ -1357,7 +1439,7 @@ var Tools = class {
1357
1439
  });
1358
1440
  if (modifiers?.afterExecute) {
1359
1441
  if (typeof modifiers.afterExecute === "function") {
1360
- result = modifiers.afterExecute(tool.slug, "unkown", result);
1442
+ result = await modifiers.afterExecute(tool.slug, "unknown", result);
1361
1443
  } else {
1362
1444
  throw new ComposioInvalidModifierError("Invalid afterExecute modifier. Not a function.");
1363
1445
  }
@@ -1375,7 +1457,7 @@ var Tools = class {
1375
1457
  async handleComposioToolExecution(tool, body, modifiers) {
1376
1458
  if (modifiers?.beforeExecute) {
1377
1459
  if (typeof modifiers.beforeExecute === "function") {
1378
- body = modifiers.beforeExecute(tool.slug, tool.toolkit?.slug || "unkown", body);
1460
+ body = await modifiers.beforeExecute(tool.slug, tool.toolkit?.slug ?? "unknown", body);
1379
1461
  } else {
1380
1462
  throw new ComposioInvalidModifierError("Invalid beforeExecute modifier. Not a function.");
1381
1463
  }
@@ -1396,7 +1478,7 @@ var Tools = class {
1396
1478
  result = this.transformToolExecuteResponse(result);
1397
1479
  if (modifiers?.afterExecute) {
1398
1480
  if (typeof modifiers.afterExecute === "function") {
1399
- result = modifiers.afterExecute(tool.slug, tool.toolkit?.slug || "unkown", result);
1481
+ result = await modifiers.afterExecute(tool.slug, tool.toolkit?.slug ?? "unknown", result);
1400
1482
  } else {
1401
1483
  throw new ComposioInvalidModifierError("Invalid afterExecute modifier. Not a function.");
1402
1484
  }
@@ -1801,7 +1883,7 @@ var AuthConfigListParamsSchema = import_zod5.z.object({
1801
1883
  });
1802
1884
  var AuthConfigListResponseSchema = import_zod5.z.object({
1803
1885
  items: import_zod5.z.array(AuthConfigRetrieveResponseSchema),
1804
- nextCursor: import_zod5.z.string().optional(),
1886
+ nextCursor: import_zod5.z.string().nullable(),
1805
1887
  totalPages: import_zod5.z.number()
1806
1888
  });
1807
1889
  var AuthCustomConfigUpdateParamsSchema = import_zod5.z.object({
@@ -1903,7 +1985,7 @@ var AuthConfigs = class {
1903
1985
  const result = await this.client.authConfigs.list({
1904
1986
  cursor: parsedQuery?.cursor,
1905
1987
  is_composio_managed: parsedQuery?.isComposioManaged,
1906
- limit: parsedQuery?.limit?.toString(),
1988
+ limit: parsedQuery?.limit,
1907
1989
  toolkit_slug: parsedQuery?.toolkit
1908
1990
  });
1909
1991
  const parsedResult = AuthConfigListResponseSchema.safeParse({
@@ -2124,20 +2206,18 @@ var AuthConfigs = class {
2124
2206
  // src/types/connectedAccounts.types.ts
2125
2207
  var import_zod6 = require("zod");
2126
2208
  var ConnectedAccountStatuses = {
2127
- ACTIVE: "ACTIVE",
2128
- INACTIVE: "INACTIVE",
2129
- DELETED: "DELETED",
2209
+ INITIALIZING: "INITIALIZING",
2130
2210
  INITIATED: "INITIATED",
2131
- EXPIRED: "EXPIRED",
2132
- FAILED: "FAILED"
2211
+ ACTIVE: "ACTIVE",
2212
+ FAILED: "FAILED",
2213
+ EXPIRED: "EXPIRED"
2133
2214
  };
2134
2215
  var ConnectedAccountStatusSchema = import_zod6.z.enum([
2135
- ConnectedAccountStatuses.ACTIVE,
2136
- ConnectedAccountStatuses.INACTIVE,
2137
- ConnectedAccountStatuses.DELETED,
2216
+ ConnectedAccountStatuses.INITIALIZING,
2138
2217
  ConnectedAccountStatuses.INITIATED,
2139
- ConnectedAccountStatuses.EXPIRED,
2140
- ConnectedAccountStatuses.FAILED
2218
+ ConnectedAccountStatuses.ACTIVE,
2219
+ ConnectedAccountStatuses.FAILED,
2220
+ ConnectedAccountStatuses.EXPIRED
2141
2221
  ]);
2142
2222
  var CreateConnectedAccountParamsSchema = import_zod6.z.object({
2143
2223
  authConfig: import_zod6.z.object({
@@ -2339,8 +2419,7 @@ var ConnectionRequest = class {
2339
2419
  }
2340
2420
  const terminalErrorStates = [
2341
2421
  ConnectedAccountStatuses.FAILED,
2342
- ConnectedAccountStatuses.EXPIRED,
2343
- ConnectedAccountStatuses.DELETED
2422
+ ConnectedAccountStatuses.EXPIRED
2344
2423
  ];
2345
2424
  const start = Date.now();
2346
2425
  const pollInterval = 1e3;
@@ -2371,6 +2450,23 @@ var ConnectionRequest = class {
2371
2450
  }
2372
2451
  throw new ConnectionRequestTimeoutError(`Connection request timed out for ${this.id}`);
2373
2452
  }
2453
+ /**
2454
+ * Returns a JSON-serializable representation of the connection request
2455
+ * Excludes the private client property to avoid cyclic reference issues
2456
+ */
2457
+ toJSON() {
2458
+ return {
2459
+ id: this.id,
2460
+ status: this.status,
2461
+ redirectUrl: this.redirectUrl
2462
+ };
2463
+ }
2464
+ /**
2465
+ * Returns a string representation of the connection request
2466
+ */
2467
+ toString() {
2468
+ return JSON.stringify(this.toJSON(), null, 2);
2469
+ }
2374
2470
  };
2375
2471
 
2376
2472
  // src/models/ConnectedAccounts.ts
@@ -2830,126 +2926,422 @@ var Toolkits = class {
2830
2926
  }
2831
2927
  };
2832
2928
 
2833
- // src/utils/pusher.ts
2834
- var PUSHER_KEY = process.env.CLIENT_PUSHER_KEY || "ff9f18c208855d77a152";
2835
- var PUSHER_CLUSTER = "mt1";
2836
- var PusherUtils = class _PusherUtils {
2837
- static pusherClient;
2838
- static getPusherClient(baseURL, apiKey) {
2839
- if (!_PusherUtils.pusherClient) {
2840
- const PusherClient = require("pusher-js");
2841
- _PusherUtils.pusherClient = new PusherClient(PUSHER_KEY, {
2842
- cluster: PUSHER_CLUSTER,
2843
- channelAuthorization: {
2844
- endpoint: `${baseURL}/api/v1/client/auth/pusher_auth`,
2845
- headers: {
2846
- "x-api-key": apiKey
2847
- },
2848
- transport: "ajax"
2849
- }
2850
- });
2851
- }
2852
- return _PusherUtils.pusherClient;
2929
+ // src/types/triggers.types.ts
2930
+ var import_zod8 = require("zod");
2931
+ var TriggerStatusEnum = import_zod8.z.enum(["enable", "disable"]);
2932
+ var TriggerSubscribeParamSchema = import_zod8.z.object({
2933
+ toolkits: import_zod8.z.array(import_zod8.z.string()).optional(),
2934
+ triggerId: import_zod8.z.string().optional(),
2935
+ connectedAccountId: import_zod8.z.string().optional(),
2936
+ authConfigId: import_zod8.z.string().optional(),
2937
+ triggerSlug: import_zod8.z.array(import_zod8.z.string()).optional(),
2938
+ triggerData: import_zod8.z.string().optional(),
2939
+ userId: import_zod8.z.string().optional()
2940
+ });
2941
+ var TriggerInstanceListActiveParamsSchema = import_zod8.z.object({
2942
+ authConfigIds: import_zod8.z.array(import_zod8.z.string()).nullable().optional(),
2943
+ connectedAccountIds: import_zod8.z.array(import_zod8.z.string()).nullable().optional(),
2944
+ limit: import_zod8.z.number().optional(),
2945
+ page: import_zod8.z.number().optional(),
2946
+ showDisabled: import_zod8.z.boolean().nullable().optional(),
2947
+ triggerIds: import_zod8.z.array(import_zod8.z.string()).nullable().optional(),
2948
+ triggerNames: import_zod8.z.array(import_zod8.z.string()).nullable().optional()
2949
+ });
2950
+ var TriggerInstanceListActiveResponseItemSchema = import_zod8.z.object({
2951
+ id: import_zod8.z.string(),
2952
+ connectedAccountId: import_zod8.z.string(),
2953
+ disabledAt: import_zod8.z.string().nullable(),
2954
+ state: import_zod8.z.record(import_zod8.z.unknown()),
2955
+ triggerConfig: import_zod8.z.record(import_zod8.z.unknown()),
2956
+ triggerName: import_zod8.z.string(),
2957
+ updatedAt: import_zod8.z.string(),
2958
+ triggerData: import_zod8.z.string().optional(),
2959
+ uuid: import_zod8.z.string().optional()
2960
+ });
2961
+ var TriggerInstanceListActiveResponseSchema = import_zod8.z.object({
2962
+ items: import_zod8.z.array(TriggerInstanceListActiveResponseItemSchema),
2963
+ nextCursor: import_zod8.z.string().nullable(),
2964
+ totalPages: import_zod8.z.number()
2965
+ });
2966
+ var TriggerInstanceUpsertParamsSchema = import_zod8.z.object({
2967
+ connectedAccountId: import_zod8.z.string().optional(),
2968
+ triggerConfig: import_zod8.z.record(import_zod8.z.unknown()).optional()
2969
+ });
2970
+ var TriggerInstanceUpsertResponseSchema = import_zod8.z.object({
2971
+ triggerId: import_zod8.z.string()
2972
+ });
2973
+ var TriggerInstanceManageUpdateParamsSchema = import_zod8.z.object({
2974
+ status: import_zod8.z.enum(["enable", "disable"])
2975
+ });
2976
+ var TriggerInstanceManageUpdateResponseSchema = import_zod8.z.object({
2977
+ status: import_zod8.z.enum(["success"])
2978
+ });
2979
+ var TriggerInstanceManageDeleteResponseSchema = import_zod8.z.object({
2980
+ triggerId: import_zod8.z.string()
2981
+ });
2982
+ var IncomingTriggerPayloadSchema = import_zod8.z.object({
2983
+ id: import_zod8.z.string().describe("The ID of the trigger"),
2984
+ triggerSlug: import_zod8.z.string().describe("The slug of the trigger that triggered the event"),
2985
+ toolkitSlug: import_zod8.z.string().describe("The slug of the toolkit that triggered the event"),
2986
+ userId: import_zod8.z.string().describe("The ID of the user that triggered the event"),
2987
+ payload: import_zod8.z.record(import_zod8.z.unknown()).describe("The payload of the trigger").optional(),
2988
+ originalPayload: import_zod8.z.record(import_zod8.z.unknown()).describe("The original payload of the trigger").optional(),
2989
+ metadata: import_zod8.z.object({
2990
+ id: import_zod8.z.string(),
2991
+ toolkitSlug: import_zod8.z.string(),
2992
+ triggerSlug: import_zod8.z.string(),
2993
+ triggerData: import_zod8.z.string().optional(),
2994
+ triggerConfig: import_zod8.z.record(import_zod8.z.unknown()),
2995
+ connectedAccount: import_zod8.z.object({
2996
+ id: import_zod8.z.string(),
2997
+ uuid: import_zod8.z.string(),
2998
+ authConfigId: import_zod8.z.string(),
2999
+ authConfigUUID: import_zod8.z.string(),
3000
+ userId: import_zod8.z.string(),
3001
+ status: import_zod8.z.enum(["ACTIVE", "INACTIVE"])
3002
+ })
3003
+ })
3004
+ });
3005
+
3006
+ // src/services/internal/InternalService.types.ts
3007
+ var import_zod9 = require("zod");
3008
+ var SDKRealtimeCredentialsResponseSchema = import_zod9.z.object({
3009
+ projectId: import_zod9.z.string().describe("The project ID"),
3010
+ pusherKey: import_zod9.z.string().describe("The Pusher key"),
3011
+ pusherCluster: import_zod9.z.string().describe("The Pusher cluster")
3012
+ });
3013
+
3014
+ // src/services/internal/InternalService.ts
3015
+ var SDK_REALTIME_CREDENTIALS_ENDPOINT = "/api/v3/internal/sdk/realtime/credentials";
3016
+ var InternalService = class {
3017
+ constructor(client) {
3018
+ this.client = client;
3019
+ this.client = client;
2853
3020
  }
2854
3021
  /**
2855
- * Subscribes to a Pusher channel and binds an event to a callback function.
2856
- * @param {string} channelName - The name of the channel to subscribe to.
2857
- * @param {string} event - The event to bind to the channel.
2858
- * @param {(data: Record<string, unknown>) => void} fn - The callback function to execute when the event is triggered.
2859
- * @returns {PusherClient} The Pusher client instance.
3022
+ * Get the SDK realtime credentials
3023
+ * @returns {SDKRealtimeCredentialsResponse} The SDK realtime credentials
2860
3024
  */
2861
- static async subscribe(channelName, event, fn) {
2862
- try {
2863
- await _PusherUtils.pusherClient.subscribe(channelName).bind(event, fn);
2864
- } catch (error) {
2865
- logger_default.error(
2866
- `Error subscribing to ${channelName} with event ${event}: ${error}`
2867
- );
3025
+ async getSDKRealtimeCredentials() {
3026
+ const response = await this.client.request({
3027
+ method: "get",
3028
+ path: SDK_REALTIME_CREDENTIALS_ENDPOINT
3029
+ });
3030
+ const parsedResponse = SDKRealtimeCredentialsResponseSchema.safeParse({
3031
+ pusherKey: response.pusher_key,
3032
+ projectId: response.project_id,
3033
+ pusherCluster: response.pusher_cluster
3034
+ });
3035
+ logger_default.debug(
3036
+ `[InternalService] SDK realtime credentials: ${JSON.stringify(parsedResponse, null, 2)}`
3037
+ );
3038
+ if (!parsedResponse.success) {
3039
+ throw new ValidationError(`Failed to parse SDK realtime credentials`, {
3040
+ cause: parsedResponse.error
3041
+ });
2868
3042
  }
3043
+ return parsedResponse.data;
2869
3044
  }
2870
- /**
2871
- * Unsubscribes from a Pusher channel.
2872
- * @param {string} channelName - The name of the channel to unsubscribe from.
2873
- * @returns {void}
2874
- */
2875
- static async unsubscribe(channelName) {
2876
- _PusherUtils.pusherClient.unsubscribe(channelName);
3045
+ };
3046
+
3047
+ // src/errors/TriggerErrors.ts
3048
+ var import_client5 = require("@composio/client");
3049
+ var TriggerErrorCodes = {
3050
+ TRIGGER_FAILED_TO_GET_SDK_REALTIME_CREDENTIALS: "TRIGGER_FAILED_TO_GET_SDK_REALTIME_CREDENTIALS",
3051
+ TRIGGER_FAILED_TO_CREATE_PUSHER_CLIENT: "TRIGGER_FAILED_TO_CREATE_PUSHER_CLIENT",
3052
+ TRIGGER_FAILED_TO_SUBSCRIBE_TO_PUSHER_CHANNEL: "TRIGGER_FAILED_TO_SUBSCRIBE_TO_PUSHER_CHANNEL",
3053
+ TRIGGER_FAILED_TO_UNSUBSCRIBE_FROM_PUSHER_CHANNEL: "TRIGGER_FAILED_TO_UNSUBSCRIBE_FROM_PUSHER_CHANNEL"
3054
+ };
3055
+ var ComposioFailedToGetSDKRealtimeCredentialsError = class extends import_client5.ComposioError {
3056
+ name = "ComposioFailedToGetSDKRealtimeCredentialsError";
3057
+ code = TriggerErrorCodes.TRIGGER_FAILED_TO_GET_SDK_REALTIME_CREDENTIALS;
3058
+ statusCode = 500;
3059
+ possibleFixes = ["Please contact support."];
3060
+ constructor(message, options) {
3061
+ super(message, options);
3062
+ }
3063
+ };
3064
+ var ComposioFailedToCreatePusherClientError = class extends import_client5.ComposioError {
3065
+ name = "ComposioFailedToCreatePusherClientError";
3066
+ code = TriggerErrorCodes.TRIGGER_FAILED_TO_CREATE_PUSHER_CLIENT;
3067
+ statusCode = 500;
3068
+ possibleFixes = ["Please contact support."];
3069
+ constructor(message, options) {
3070
+ super(message, options);
3071
+ }
3072
+ };
3073
+ var ComposioFailedToSubscribeToPusherChannelError = class extends import_client5.ComposioError {
3074
+ name = "ComposioFailedToSubscribeToPusherChannelError";
3075
+ code = TriggerErrorCodes.TRIGGER_FAILED_TO_SUBSCRIBE_TO_PUSHER_CHANNEL;
3076
+ statusCode = 500;
3077
+ possibleFixes = ["Please contact support."];
3078
+ constructor(message, options) {
3079
+ super(message, options);
3080
+ }
3081
+ };
3082
+
3083
+ // src/services/pusher/Pusher.ts
3084
+ var PusherService = class {
3085
+ // these values are set via the Apollo API `/internal/sdk/realtime/credentials` endpoint
3086
+ clientId;
3087
+ pusherKey;
3088
+ pusherCluster;
3089
+ pusherChannel;
3090
+ // these details are set via the client SDK
3091
+ pusherBaseURL;
3092
+ apiKey;
3093
+ pusherClient;
3094
+ composioClient;
3095
+ constructor(client) {
3096
+ this.composioClient = client;
3097
+ this.pusherBaseURL = client.baseURL;
3098
+ this.apiKey = client.apiKey ?? process.env.COMPOSIO_API_KEY ?? "";
3099
+ telemetry.instrument(this);
2877
3100
  }
2878
3101
  /**
2879
- * Binds an event to a channel with support for chunked messages.
2880
- * @param {PusherClient} channel - The Pusher channel to bind the event to.
2881
- * @param {string} event - The event to bind to the channel.
2882
- * @param {(data: unknown) => void} callback - The callback function to execute when the event is triggered.
3102
+ * Creates a Pusher client
3103
+ *
3104
+ * This method is called when the Pusher client is first used.
3105
+ * It will fetch the SDK realtime credentials from the Apollo API and create a Pusher client.
2883
3106
  */
2884
- static bindWithChunking(channel, event, callback) {
2885
- channel.bind(event, callback);
2886
- const events = {};
2887
- channel.bind("chunked-" + event, (data) => {
2888
- const typedData = data;
2889
- if (!events.hasOwnProperty(typedData.id)) {
2890
- events[typedData.id] = { chunks: [], receivedFinal: false };
3107
+ async getPusherClient() {
3108
+ if (!this.pusherClient) {
3109
+ const internalService = new InternalService(this.composioClient);
3110
+ let sdkRealtimeCredentials;
3111
+ try {
3112
+ sdkRealtimeCredentials = await internalService.getSDKRealtimeCredentials();
3113
+ } catch (error) {
3114
+ throw new ComposioFailedToGetSDKRealtimeCredentialsError(
3115
+ "Failed to get SDK realtime credentials",
3116
+ {
3117
+ cause: error
3118
+ }
3119
+ );
2891
3120
  }
2892
- const ev = events[typedData.id];
2893
- ev.chunks[typedData.index] = typedData.chunk;
2894
- if (typedData.final) ev.receivedFinal = true;
2895
- if (ev.receivedFinal && ev.chunks.length === Object.keys(ev.chunks).length) {
2896
- callback(JSON.parse(ev.chunks.join("")));
2897
- delete events[typedData.id];
3121
+ this.clientId = sdkRealtimeCredentials.projectId;
3122
+ this.pusherKey = sdkRealtimeCredentials.pusherKey;
3123
+ this.pusherCluster = sdkRealtimeCredentials.pusherCluster;
3124
+ this.pusherChannel = `private-${this.clientId}_triggers`;
3125
+ logger_default.debug(
3126
+ `[PusherService] Creating Pusher client for client ID: ${this.clientId} in cluster ${this.pusherCluster}`
3127
+ );
3128
+ try {
3129
+ const { default: Pusher } = await import("pusher-js");
3130
+ this.pusherClient = new Pusher(this.pusherKey, {
3131
+ cluster: this.pusherCluster,
3132
+ channelAuthorization: {
3133
+ endpoint: `${this.pusherBaseURL}/api/v3/internal/sdk/realtime/auth`,
3134
+ headers: {
3135
+ "x-api-key": this.apiKey
3136
+ },
3137
+ transport: "ajax"
3138
+ }
3139
+ });
3140
+ } catch (error) {
3141
+ throw new ComposioFailedToCreatePusherClientError("Failed to create Pusher client", {
3142
+ cause: error
3143
+ });
2898
3144
  }
2899
- });
3145
+ }
3146
+ return this.pusherClient;
2900
3147
  }
2901
3148
  /**
2902
- * Subscribes to a trigger channel for a client and handles chunked data.
2903
- * @param {string} clientId - The unique identifier for the client subscribing to the events.
2904
- * @param {(data: TriggerData) => void} fn - The callback function to execute when trigger data is received.
3149
+ * Binds a chunked event to a Pusher client
3150
+ *
3151
+ *
3152
+ * @param channel - The Pusher client to bind the event to
3153
+ * @param event - The event to bind to
3154
+ * @param callback - The function to call when the event is received
2905
3155
  */
2906
- static triggerSubscribe(clientId, fn) {
2907
- const channel = _PusherUtils.pusherClient.subscribe(
2908
- `private-${clientId}_triggers`
2909
- );
2910
- _PusherUtils.bindWithChunking(
2911
- channel,
2912
- "trigger_to_client",
2913
- fn
2914
- );
2915
- logger_default.info(
2916
- `Subscribed to triggers. You should start receiving events now.`
2917
- );
2918
- }
2919
- static triggerUnsubscribe(clientId) {
2920
- _PusherUtils.pusherClient.unsubscribe(`${clientId}_triggers`);
3156
+ bindWithChunking(channel, event, callback) {
3157
+ try {
3158
+ channel.bind(event, callback);
3159
+ const events = {};
3160
+ channel.bind("chunked-" + event, (data) => {
3161
+ try {
3162
+ const typedData = data;
3163
+ if (!typedData || typeof typedData.id !== "string" || typeof typedData.index !== "number") {
3164
+ throw new Error("Invalid chunked trigger data format");
3165
+ }
3166
+ if (!events.hasOwnProperty(typedData.id)) {
3167
+ events[typedData.id] = { chunks: [], receivedFinal: false };
3168
+ }
3169
+ const ev = events[typedData.id];
3170
+ ev.chunks[typedData.index] = typedData.chunk;
3171
+ if (typedData.final) ev.receivedFinal = true;
3172
+ if (ev.receivedFinal && ev.chunks.length === Object.keys(ev.chunks).length) {
3173
+ try {
3174
+ const parsedData = JSON.parse(ev.chunks.join(""));
3175
+ callback(parsedData);
3176
+ } catch (parseError) {
3177
+ const errorMessage = parseError instanceof Error ? parseError.message : String(parseError);
3178
+ logger_default.error("Failed to parse chunked data:", errorMessage);
3179
+ } finally {
3180
+ delete events[typedData.id];
3181
+ }
3182
+ }
3183
+ } catch (error) {
3184
+ const errorMessage = error instanceof Error ? error.message : String(error);
3185
+ logger_default.error("Error processing chunked trigger data:", errorMessage);
3186
+ if (data && typeof data === "object" && "id" in data) {
3187
+ delete events[data.id];
3188
+ }
3189
+ }
3190
+ });
3191
+ } catch (error) {
3192
+ const errorMessage = error instanceof Error ? error.message : String(error);
3193
+ logger_default.error("Failed to bind chunked events:", error);
3194
+ throw new Error(`Failed to bind chunked events: ${errorMessage}`);
3195
+ }
2921
3196
  }
2922
- };
2923
-
2924
- // src/models/Session.ts
2925
- var Session = class {
2926
- client;
2927
- constructor(client) {
2928
- this.client = client;
2929
- telemetry.instrument(this);
3197
+ /**
3198
+ * Subscribes to pusher to receive events from the server
3199
+ *
3200
+ * This method is used to subscribe to a Pusher channel.
3201
+ * It will create a Pusher client if it doesn't exist.
3202
+ *
3203
+ * @param channelName - The name of the Pusher channel to subscribe to
3204
+ * @param event - The event to subscribe to
3205
+ * @param fn - The function to call when the event is received
3206
+ */
3207
+ async subscribe(fn) {
3208
+ try {
3209
+ logger_default.debug(`[PusherService] Subscribing to channel: ${this.pusherChannel}`);
3210
+ const pusherClient = await this.getPusherClient();
3211
+ const channel = await pusherClient.subscribe(this.pusherChannel);
3212
+ channel.bind("pusher:subscription_error", (data) => {
3213
+ const error = data.error ? String(data.error) : "Unknown subscription error";
3214
+ throw new ComposioFailedToSubscribeToPusherChannelError(
3215
+ `Trigger subscription error: ${error}`,
3216
+ {
3217
+ cause: error
3218
+ }
3219
+ );
3220
+ });
3221
+ const safeCallback = (data) => {
3222
+ try {
3223
+ fn(data);
3224
+ } catch (error) {
3225
+ const errorMessage = error instanceof Error ? error.message : String(error);
3226
+ logger_default.error("\u274C Error in trigger callback:", errorMessage);
3227
+ }
3228
+ };
3229
+ this.bindWithChunking(channel, "trigger_to_client", safeCallback);
3230
+ logger_default.info(`\u2705 Subscribed to triggers. You should start receiving events now.`);
3231
+ } catch (error) {
3232
+ throw new ComposioFailedToSubscribeToPusherChannelError(
3233
+ "Failed to subscribe to Pusher channel",
3234
+ {
3235
+ cause: error
3236
+ }
3237
+ );
3238
+ }
2930
3239
  }
2931
3240
  /**
2932
- * Get the active session info
2933
- * @returns {Promise<SessionGetInfoResponse>} Session info
3241
+ * Unsubscribes from a Pusher channel
3242
+ *
3243
+ * This method is used to unsubscribe from a Pusher channel.
3244
+ * It will create a Pusher client if it doesn't exist.
3245
+ *
3246
+ * @param channelName - The name of the Pusher channel to unsubscribe from
2934
3247
  */
2935
- async getInfo() {
2936
- return this.client.auth.session.getInfo();
3248
+ async unsubscribe() {
3249
+ try {
3250
+ logger_default.debug(`[PusherService] Unsubscribing from channel: ${this.pusherChannel}`);
3251
+ const pusherClient = await this.getPusherClient();
3252
+ await pusherClient.unsubscribe(this.pusherChannel);
3253
+ logger_default.info(`\u2705 Unsubscribed from triggers.`);
3254
+ } catch (error) {
3255
+ throw new ComposioFailedToSubscribeToPusherChannelError(
3256
+ "Failed to unsubscribe from Pusher channel",
3257
+ {
3258
+ cause: error
3259
+ }
3260
+ );
3261
+ }
2937
3262
  }
2938
3263
  };
2939
3264
 
2940
3265
  // src/models/Triggers.ts
2941
3266
  var Triggers = class {
2942
3267
  client;
3268
+ pusherService;
2943
3269
  constructor(client) {
2944
3270
  this.client = client;
3271
+ this.pusherService = new PusherService(client);
2945
3272
  telemetry.instrument(this);
2946
3273
  }
3274
+ /**
3275
+ * Parse the trigger instance list active item
3276
+ *
3277
+ * @param response - The response from the composio client
3278
+ * @returns The parsed trigger instance list active item
3279
+ */
3280
+ parseTriggerInstanceListActiveItem(response) {
3281
+ const parsed = TriggerInstanceListActiveResponseItemSchema.safeParse({
3282
+ id: response.id,
3283
+ connectedAccountId: response.connected_account_id,
3284
+ disabledAt: response.disabled_at,
3285
+ state: response.state,
3286
+ triggerConfig: response.trigger_config,
3287
+ triggerName: response.trigger_name,
3288
+ updatedAt: response.updated_at,
3289
+ triggerData: response.trigger_data,
3290
+ uuid: response.uuid
3291
+ });
3292
+ if (!parsed.success) {
3293
+ throw new ValidationError(`Invalid trigger instance list active item`, {
3294
+ cause: parsed.error
3295
+ });
3296
+ }
3297
+ return parsed.data;
3298
+ }
2947
3299
  /**
2948
3300
  * Fetch list of all the active triggers
2949
- * @returns {Promise<TriggerInstance[]>} List of trigger instances
3301
+ *
3302
+ * @param {TriggerInstanceListActiveParams} query - The query parameters to filter the trigger instances
3303
+ * @returns {Promise<TriggerInstanceListActiveResponse>} List of trigger instances
3304
+ *
3305
+ * @throws {ValidationError} If the parameters are invalid
3306
+ * @throws {Error} If the client is not authenticated
3307
+ *
3308
+ * @example
3309
+ * ```ts
3310
+ * const triggers = await triggers.listActive({
3311
+ * authConfigIds: ['123'],
3312
+ * connectedAccountIds: ['456'],
3313
+ * });
3314
+ * ```
2950
3315
  */
2951
- async list(query, options) {
2952
- return this.client.triggerInstances.listActive(query, options);
3316
+ async listActive(query) {
3317
+ const parsedParams = TriggerInstanceListActiveParamsSchema.safeParse(query ?? {});
3318
+ if (!parsedParams.success) {
3319
+ throw new ValidationError(`Invalid parameters passed to list triggers`, {
3320
+ cause: parsedParams.error
3321
+ });
3322
+ }
3323
+ const result = await this.client.triggerInstances.listActive(
3324
+ query ? {
3325
+ auth_config_ids: parsedParams.data.authConfigIds,
3326
+ connected_account_ids: parsedParams.data.connectedAccountIds,
3327
+ limit: parsedParams.data.limit,
3328
+ page: parsedParams.data.page,
3329
+ show_disabled: parsedParams.data.showDisabled,
3330
+ trigger_ids: parsedParams.data.triggerIds,
3331
+ trigger_names: parsedParams.data.triggerNames
3332
+ } : void 0
3333
+ );
3334
+ const parsedResult = TriggerInstanceListActiveResponseSchema.safeParse({
3335
+ items: result.items.map((item) => this.parseTriggerInstanceListActiveItem(item)),
3336
+ nextCursor: result.next_cursor,
3337
+ totalPages: result.total_pages
3338
+ });
3339
+ if (!parsedResult.success) {
3340
+ throw new ValidationError(`Invalid trigger instance list active response`, {
3341
+ cause: parsedResult.error
3342
+ });
3343
+ }
3344
+ return parsedResult.data;
2953
3345
  }
2954
3346
  /**
2955
3347
  * Create a new trigger instance
@@ -2958,58 +3350,76 @@ var Triggers = class {
2958
3350
  * @param {TriggerInstanceUpsertParams} body - The parameters to create the trigger instance
2959
3351
  * @returns {Promise<TriggerInstanceUpsertResponse>} The created trigger instance
2960
3352
  */
2961
- async create(slug, body, options) {
2962
- return this.client.triggerInstances.upsert(slug, body, options);
3353
+ async create(slug, body) {
3354
+ const parsedBody = TriggerInstanceUpsertParamsSchema.safeParse(body);
3355
+ if (!parsedBody.success) {
3356
+ throw new ValidationError(`Invalid parameters passed to create trigger`, {
3357
+ cause: parsedBody.error
3358
+ });
3359
+ }
3360
+ const result = await this.client.triggerInstances.upsert(slug, {
3361
+ connected_account_id: parsedBody.data.connectedAccountId,
3362
+ trigger_config: parsedBody.data.triggerConfig
3363
+ });
3364
+ const parsedResult = TriggerInstanceUpsertResponseSchema.safeParse({
3365
+ triggerId: result.trigger_id
3366
+ });
3367
+ if (!parsedResult.success) {
3368
+ throw new ValidationError(`Invalid trigger instance upsert response`, {
3369
+ cause: parsedResult.error
3370
+ });
3371
+ }
3372
+ return parsedResult.data;
2963
3373
  }
2964
3374
  /**
2965
3375
  * Update an existing trigger instance
2966
3376
  *
2967
3377
  * @param {string} slug - The slug of the trigger instance
2968
- * @param {TriggerInstanceUpsertParams} body - The parameters to create the trigger instance
3378
+ * @param {TriggerInstanceManageUpdateParams} body - The parameters to create the trigger instance
2969
3379
  * @returns {Promise<TriggerInstanceUpsertResponse>} The updated trigger instance
2970
3380
  */
2971
- async update(slug, body, options) {
2972
- return this.client.triggerInstances.upsert(slug, body, options);
3381
+ async update(slug, body) {
3382
+ return this.client.triggerInstances.manage.update(slug, body);
2973
3383
  }
2974
3384
  /**
2975
3385
  * Delete a trigger instance
2976
3386
  *
2977
- * @param {string} slug - The slug of the trigger instance
3387
+ * @param {string} triggerId - The slug of the trigger instance
2978
3388
  * @returns
2979
3389
  */
2980
- async delete(slug) {
2981
- return this.client.triggerInstances.removeUpsert(slug);
2982
- }
2983
- /**
2984
- * Update the status of a trigger
2985
- *
2986
- * @param {TriggerStatusEnum} status - The new status of the trigger
2987
- * @param {TriggerInstanceUpdateStatusParams} params - The parameters to update the trigger instance
2988
- * @param {RequestOptions} options - Request options
2989
- * @returns {Promise<TriggerInstanceUpsertResponse>} The updated trigger instance
2990
- */
2991
- async updateStatus(status, params, options) {
2992
- return this.client.triggerInstances.updateStatus(status, params, options);
3390
+ async delete(triggerId) {
3391
+ const result = await this.client.triggerInstances.manage.delete(triggerId);
3392
+ const parsedResult = TriggerInstanceManageDeleteResponseSchema.safeParse({
3393
+ triggerId: result.trigger_id
3394
+ });
3395
+ if (!parsedResult.success) {
3396
+ throw new ValidationError(`Invalid trigger instance manage delete response`, {
3397
+ cause: parsedResult.error
3398
+ });
3399
+ }
3400
+ return parsedResult.data;
2993
3401
  }
2994
3402
  /**
2995
3403
  * Disable a trigger instance
2996
3404
  *
2997
- * @param {string} slug - The slug of the trigger instance
2998
- * @param {RequestOptions options - Request options
3405
+ * @param {string} triggerId - The id of the trigger instance
2999
3406
  * @returns {Promise<TriggerInstanceUpsertResponse>} The updated trigger instance
3000
3407
  */
3001
- async disable(slug, options) {
3002
- return this.client.triggerInstances.updateStatus("disable", { slug }, options);
3408
+ async disable(triggerId) {
3409
+ return this.client.triggerInstances.manage.update(triggerId, {
3410
+ status: "disable"
3411
+ });
3003
3412
  }
3004
3413
  /**
3005
3414
  * Enable a trigger instance
3006
3415
  *
3007
- * @param {string} slug - The slug of the trigger instance
3008
- * @param {RequestOptions options - Request options
3416
+ * @param {string} triggerId - The id of the trigger instance
3009
3417
  * @returns {Promise<TriggerInstanceUpsertResponse>} The updated trigger instance
3010
3418
  */
3011
- async enable(slug, options) {
3012
- return this.client.triggerInstances.updateStatus("enable", { slug }, options);
3419
+ async enable(triggerId) {
3420
+ return this.client.triggerInstances.manage.update(triggerId, {
3421
+ status: "enable"
3422
+ });
3013
3423
  }
3014
3424
  /**
3015
3425
  * @TODO Learn about trigger types
@@ -3021,8 +3431,8 @@ var Triggers = class {
3021
3431
  * @param {RequestOptions} options - Request options
3022
3432
  * @returns {Promise<TriggersTypeListResponse>} The list of trigger types
3023
3433
  */
3024
- async listTypes(query, options) {
3025
- return this.client.triggersTypes.list(query, options);
3434
+ async listTypes(query) {
3435
+ return this.client.triggersTypes.list(query);
3026
3436
  }
3027
3437
  /**
3028
3438
  * Retrieve a trigger type by its slug
@@ -3031,8 +3441,8 @@ var Triggers = class {
3031
3441
  * @param {RequestOptions} options - request options
3032
3442
  * @returns {Promise<TriggersTypeRetrieveResponse>} The trigger type object
3033
3443
  */
3034
- async getType(slug, options) {
3035
- return this.client.triggersTypes.retrieve(slug, options);
3444
+ async getType(slug) {
3445
+ return this.client.triggersTypes.retrieve(slug);
3036
3446
  }
3037
3447
  /**
3038
3448
  * Fetches the list of all the available trigger enums
@@ -3041,36 +3451,137 @@ var Triggers = class {
3041
3451
  * @param options
3042
3452
  * @returns
3043
3453
  */
3044
- async listEnum(options) {
3045
- return this.client.triggersTypes.retrieveEnum(options);
3454
+ async listEnum() {
3455
+ return this.client.triggersTypes.retrieveEnum();
3046
3456
  }
3457
+ /**
3458
+ * Subscribe to all the triggers
3459
+ *
3460
+ * @param fn - The function to call when a trigger is received
3461
+ * @param filters - The filters to apply to the triggers
3462
+ *
3463
+ * @example
3464
+ * ```ts
3465
+ *
3466
+ * triggers.subscribe((data) => {
3467
+ * console.log(data);
3468
+ * }, );
3469
+ * ```
3470
+ */
3047
3471
  async subscribe(fn, filters = {}) {
3048
3472
  if (!fn) throw new Error("Function is required for trigger subscription");
3049
- const session = new Session(this.client);
3050
- const sessionInfo = await session.getInfo();
3051
- const clientId = sessionInfo.project?.id;
3052
- if (!clientId) throw new Error("Client ID not found");
3053
- if (!this.client.apiKey) throw new Error("API key not found");
3054
- await PusherUtils.getPusherClient(this.client.baseURL, this.client.apiKey);
3055
- const shouldSendTrigger = (data) => {
3056
- if (Object.keys(filters).length === 0) return true;
3057
- else {
3058
- 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());
3473
+ const parsedFilters = TriggerSubscribeParamSchema.safeParse(filters);
3474
+ if (!parsedFilters.success) {
3475
+ throw new ValidationError(`Invalid parameters passed to subscribe to triggers`, {
3476
+ cause: parsedFilters.error
3477
+ });
3478
+ }
3479
+ const shouldSendTriggerAfterFilters = (data) => {
3480
+ if (parsedFilters.data.toolkits?.length && !parsedFilters.data.toolkits.map((toolkit) => toolkit.toLowerCase()).includes(data.toolkitSlug.toLowerCase())) {
3481
+ logger_default.debug(
3482
+ "Trigger does not match toolkits filter",
3483
+ JSON.stringify(parsedFilters.data.toolkits, null, 2)
3484
+ );
3485
+ return false;
3486
+ }
3487
+ if (parsedFilters.data.triggerId && parsedFilters.data.triggerId !== data.id) {
3488
+ logger_default.debug(
3489
+ "Trigger does not match triggerId filter",
3490
+ JSON.stringify(parsedFilters.data.triggerId, null, 2)
3491
+ );
3492
+ return false;
3059
3493
  }
3494
+ if (parsedFilters.data.connectedAccountId && parsedFilters.data.connectedAccountId !== data.metadata.connectedAccount.id) {
3495
+ logger_default.debug(
3496
+ "Trigger does not match connectedAccountId filter",
3497
+ JSON.stringify(parsedFilters.data.connectedAccountId, null, 2)
3498
+ );
3499
+ return false;
3500
+ }
3501
+ if (parsedFilters.data.triggerSlug?.length && !parsedFilters.data.triggerSlug.map((triggerSlug) => triggerSlug.toLowerCase()).includes(data.triggerSlug.toLowerCase())) {
3502
+ logger_default.debug(
3503
+ "Trigger does not match triggerSlug filter",
3504
+ JSON.stringify(parsedFilters.data.triggerSlug, null, 2)
3505
+ );
3506
+ return false;
3507
+ }
3508
+ if (parsedFilters.data.triggerData && parsedFilters.data.triggerData !== data.metadata.triggerData) {
3509
+ logger_default.debug(
3510
+ "Trigger does not match triggerData filter",
3511
+ JSON.stringify(parsedFilters.data.triggerData, null, 2)
3512
+ );
3513
+ return false;
3514
+ }
3515
+ if (parsedFilters.data.userId && parsedFilters.data.userId !== data.metadata.connectedAccount.userId) {
3516
+ logger_default.debug(
3517
+ "Trigger does not match userId filter",
3518
+ JSON.stringify(parsedFilters.data.userId, null, 2)
3519
+ );
3520
+ return false;
3521
+ }
3522
+ logger_default.debug("Trigger matches all filters", JSON.stringify(parsedFilters.data, null, 2));
3523
+ return true;
3060
3524
  };
3061
- logger_default.debug("Subscribing to triggers", filters);
3062
- PusherUtils.triggerSubscribe(clientId, (data) => {
3063
- if (shouldSendTrigger(data)) {
3064
- fn(data);
3525
+ logger_default.debug("\u{1F504} Subscribing to triggers with filters: ", JSON.stringify(filters, null, 2));
3526
+ await this.pusherService.subscribe((_data) => {
3527
+ logger_default.debug("Received raw trigger data", JSON.stringify(_data, null, 2));
3528
+ const data = _data;
3529
+ const parsedData = IncomingTriggerPayloadSchema.safeParse({
3530
+ id: data.metadata.id,
3531
+ triggerSlug: data.metadata.triggerName,
3532
+ toolkitSlug: data.appName,
3533
+ userId: data.metadata.connection?.clientUniqueUserId,
3534
+ payload: data.payload,
3535
+ originalPayload: data.originalPayload,
3536
+ metadata: {
3537
+ id: data.metadata.id,
3538
+ triggerConfig: data.metadata.triggerConfig,
3539
+ triggerSlug: data.metadata.triggerName,
3540
+ toolkitSlug: data.appName,
3541
+ triggerData: data.metadata.triggerData,
3542
+ connectedAccount: {
3543
+ id: data.metadata.connection?.connectedAccountNanoId,
3544
+ uuid: data.metadata.connection?.id,
3545
+ authConfigId: data.metadata.connection?.authConfigNanoId,
3546
+ authConfigUUID: data.metadata.connection?.integrationId,
3547
+ userId: data.metadata.connection?.clientUniqueUserId,
3548
+ status: data.metadata.connection?.status
3549
+ }
3550
+ }
3551
+ });
3552
+ logger_default.debug("Parsed trigger data", JSON.stringify(parsedData.data, null, 2));
3553
+ if (parsedData.error) {
3554
+ throw new ValidationError(`Invalid trigger payload`, {
3555
+ cause: parsedData.error
3556
+ });
3557
+ }
3558
+ if (shouldSendTriggerAfterFilters(parsedData.data)) {
3559
+ try {
3560
+ fn(parsedData.data);
3561
+ } catch (error) {
3562
+ logger_default.error("\u274C Error in trigger callback:", error);
3563
+ }
3564
+ } else {
3565
+ logger_default.debug("Trigger does not match filters", JSON.stringify(parsedFilters.data, null, 2));
3065
3566
  }
3066
3567
  });
3067
3568
  }
3569
+ /**
3570
+ * Unsubscribe from all the triggers
3571
+ *
3572
+ * @returns {Promise<void>}
3573
+ *
3574
+ * @example
3575
+ * ```ts
3576
+ * composio.trigger.subscribe((data) => {
3577
+ * console.log(data);
3578
+ * });
3579
+ *
3580
+ * await triggers.unsubscribe();
3581
+ * ```
3582
+ */
3068
3583
  async unsubscribe() {
3069
- const session = new Session(this.client);
3070
- const sessionInfo = await session.getInfo();
3071
- const clientId = sessionInfo.project?.id;
3072
- if (!clientId) throw new Error("Client ID not found");
3073
- PusherUtils.triggerUnsubscribe(clientId);
3584
+ await this.pusherService.unsubscribe();
3074
3585
  }
3075
3586
  };
3076
3587
 
@@ -3153,7 +3664,7 @@ var BaseProvider = class {
3153
3664
  }
3154
3665
  /**
3155
3666
  * @public
3156
- * Gloabl function to execute a tool.
3667
+ * Global function to execute a tool.
3157
3668
  * This function is used by provider providers to implement helper functions to execute tools.
3158
3669
  * This is a 1:1 mapping of the `execute` method in the `Tools` class.
3159
3670
  * @param {string} toolSlug - The slug of the tool to execute.
@@ -3220,7 +3731,7 @@ var OpenAIProvider = class extends BaseNonAgenticProvider {
3220
3731
  * @param {string} userId - The user id.
3221
3732
  * @returns {Promise<string[]>} The results of the tool call.
3222
3733
  */
3223
- async handleToolCall(userId, chatCompletion, options, modifiers) {
3734
+ async handleToolCalls(userId, chatCompletion, options, modifiers) {
3224
3735
  const outputs = [];
3225
3736
  for (const message of chatCompletion.choices) {
3226
3737
  if (message.message.tool_calls) {
@@ -3340,7 +3851,7 @@ var OpenAIProvider = class extends BaseNonAgenticProvider {
3340
3851
  };
3341
3852
 
3342
3853
  // package.json
3343
- var version = "0.1.12-alpha.11";
3854
+ var version = "0.1.12-alpha.13";
3344
3855
 
3345
3856
  // src/composio.ts
3346
3857
  var Composio = class {
@@ -3382,7 +3893,7 @@ var Composio = class {
3382
3893
  if (IS_DEVELOPMENT_OR_CI) {
3383
3894
  logger_default.debug(`Initializing Composio w API Key: [REDACTED] and baseURL: ${baseURLParsed}`);
3384
3895
  }
3385
- this.client = new import_client5.default({
3896
+ this.client = new import_client6.default({
3386
3897
  apiKey: apiKeyParsed,
3387
3898
  baseURL: baseURLParsed
3388
3899
  });
@@ -3402,7 +3913,7 @@ var Composio = class {
3402
3913
  {
3403
3914
  apiKey: apiKeyParsed ?? "",
3404
3915
  baseUrl: baseURLParsed ?? "",
3405
- frameworkRuntime: this.provider?.name || "unknown",
3916
+ frameworkRuntime: this.provider?.name ?? "unknown",
3406
3917
  isAgentic: this.provider?._isAgentic || false,
3407
3918
  source: "javascript",
3408
3919
  version,
@@ -3455,39 +3966,39 @@ var ConsoleTelemetryTransport = class {
3455
3966
  };
3456
3967
 
3457
3968
  // src/utils/jsonSchema.ts
3458
- var import_zod8 = require("zod");
3969
+ var import_zod10 = require("zod");
3459
3970
  function jsonSchemaPropertiesToTSTypes(value) {
3460
3971
  if (!value.type) {
3461
- return import_zod8.z.object({});
3972
+ return import_zod10.z.object({});
3462
3973
  }
3463
3974
  let zodType;
3464
3975
  switch (value.type) {
3465
3976
  case "string":
3466
- zodType = import_zod8.z.string().describe(
3977
+ zodType = import_zod10.z.string().describe(
3467
3978
  (value.description || "") + (value.examples ? `
3468
3979
  Examples: ${value.examples.join(", ")}` : "")
3469
3980
  );
3470
3981
  break;
3471
3982
  case "number":
3472
- zodType = import_zod8.z.number().describe(
3983
+ zodType = import_zod10.z.number().describe(
3473
3984
  (value.description || "") + (value.examples ? `
3474
3985
  Examples: ${value.examples.join(", ")}` : "")
3475
3986
  );
3476
3987
  break;
3477
3988
  case "integer":
3478
- zodType = import_zod8.z.number().int().describe(
3989
+ zodType = import_zod10.z.number().int().describe(
3479
3990
  (value.description || "") + (value.examples ? `
3480
3991
  Examples: ${value.examples.join(", ")}` : "")
3481
3992
  );
3482
3993
  break;
3483
3994
  case "boolean":
3484
- zodType = import_zod8.z.boolean().describe(
3995
+ zodType = import_zod10.z.boolean().describe(
3485
3996
  (value.description || "") + (value.examples ? `
3486
3997
  Examples: ${value.examples.join(", ")}` : "")
3487
3998
  );
3488
3999
  break;
3489
4000
  case "array":
3490
- zodType = import_zod8.z.array(
4001
+ zodType = import_zod10.z.array(
3491
4002
  jsonSchemaPropertiesToTSTypes(
3492
4003
  value.items
3493
4004
  )
@@ -3497,24 +4008,24 @@ Examples: ${value.examples.join(", ")}` : "")
3497
4008
  );
3498
4009
  break;
3499
4010
  case "object":
3500
- zodType = jsonSchemaToModel(value).describe(
4011
+ zodType = jsonSchemaToZodSchema(value).describe(
3501
4012
  (value.description || "") + (value.examples ? `
3502
4013
  Examples: ${value.examples.join(", ")}` : "")
3503
4014
  );
3504
4015
  break;
3505
4016
  case "null":
3506
- zodType = import_zod8.z.null().describe(value.description || "");
4017
+ zodType = import_zod10.z.null().describe(value.description || "");
3507
4018
  break;
3508
4019
  default:
3509
4020
  throw new Error(`Unsupported JSON schema type: ${value.type}`);
3510
4021
  }
3511
4022
  return zodType;
3512
4023
  }
3513
- function jsonSchemaToModel(jsonSchema) {
4024
+ function jsonSchemaToZodSchema(jsonSchema) {
3514
4025
  const properties = jsonSchema.properties;
3515
4026
  const requiredFields = jsonSchema.required || [];
3516
4027
  if (!properties) {
3517
- return import_zod8.z.object({});
4028
+ return import_zod10.z.object({});
3518
4029
  }
3519
4030
  const zodSchema = {};
3520
4031
  for (const [key, _] of Object.entries(properties)) {
@@ -3526,7 +4037,7 @@ function jsonSchemaToModel(jsonSchema) {
3526
4037
  schema
3527
4038
  )
3528
4039
  );
3529
- zodType = import_zod8.z.union(anyOfTypes).describe(
4040
+ zodType = import_zod10.z.union(anyOfTypes).describe(
3530
4041
  (value.description || "") + (value.examples ? `
3531
4042
  Examples: ${value.examples.join(", ")}` : "")
3532
4043
  );
@@ -3536,7 +4047,7 @@ Examples: ${value.examples.join(", ")}` : "")
3536
4047
  schema
3537
4048
  )
3538
4049
  );
3539
- zodType = import_zod8.z.intersection(
4050
+ zodType = import_zod10.z.intersection(
3540
4051
  allOfTypes[0],
3541
4052
  allOfTypes.slice(1).reduce((acc, schema) => acc.and(schema), allOfTypes[0])
3542
4053
  ).describe(
@@ -3560,7 +4071,7 @@ Examples: ${value.examples.join(", ")}` : "")
3560
4071
  zodSchema[key] = zodType.optional();
3561
4072
  }
3562
4073
  }
3563
- return import_zod8.z.object(zodSchema);
4074
+ return import_zod10.z.object(zodSchema);
3564
4075
  }
3565
4076
  // Annotate the CommonJS export names for ESM import in node:
3566
4077
  0 && (module.exports = {
@@ -3597,5 +4108,6 @@ Examples: ${value.examples.join(", ")}` : "")
3597
4108
  ToolkitErrorCodes,
3598
4109
  ValidationError,
3599
4110
  ValidationErrorCodes,
3600
- jsonSchemaToModel
4111
+ jsonSchemaToZodSchema,
4112
+ logger
3601
4113
  });