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

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"')
@@ -95,8 +122,8 @@ var ToolListResponseSchema = import_zod.z.object({
95
122
  var ToolListParamsSchema = import_zod.z.object({
96
123
  tools: import_zod.z.array(import_zod.z.string()).optional(),
97
124
  cursor: import_zod.z.string().optional(),
98
- important: import_zod.z.string().optional(),
99
- limit: import_zod.z.string().optional(),
125
+ important: import_zod.z.boolean().optional(),
126
+ limit: import_zod.z.number().optional(),
100
127
  search: import_zod.z.string().optional(),
101
128
  toolkits: import_zod.z.array(import_zod.z.string()).optional()
102
129
  });
@@ -234,18 +261,19 @@ var ComposioError = class _ComposioError extends Error {
234
261
  */
235
262
  constructor(message, options = {}) {
236
263
  super(message);
264
+ if (Error.captureStackTrace) {
265
+ Error.captureStackTrace(this, this.constructor);
266
+ }
237
267
  const statusCode = options.statusCode || (options.cause instanceof import_client.BadRequestError ? options.cause.status : void 0);
238
268
  this.code = `TS-SDK::${options.code}`;
239
269
  this.possibleFixes = options.possibleFixes;
240
270
  this.definePropertyIfExists("statusCode", statusCode);
241
271
  this.definePropertyIfExists("cause", options.cause);
242
- this.definePropertyIfExists("stack", options.stack);
272
+ const combinedStack = options.cause instanceof Error ? _ComposioError.combineStackTraces(options.cause.stack, this.stack) : options.stack ?? this.stack;
273
+ this.definePropertyIfExists("stack", combinedStack);
243
274
  if (options.meta && Object.keys(options.meta).length > 0) {
244
275
  this.definePropertyIfExists("meta", options.meta);
245
276
  }
246
- if (Error.captureStackTrace) {
247
- Error.captureStackTrace(this, this.constructor);
248
- }
249
277
  }
250
278
  /**
251
279
  * Helper method to define a property only if it has a value
@@ -263,6 +291,25 @@ var ComposioError = class _ComposioError extends Error {
263
291
  });
264
292
  }
265
293
  }
294
+ /**
295
+ * Helper method to combine stack traces when wrapping errors
296
+ * This ensures the full call chain is preserved
297
+ * @param originalStack The stack of the error being wrapped
298
+ * @param currentStack The stack of the wrapper error
299
+ * @returns Combined stack trace
300
+ * @private
301
+ */
302
+ static combineStackTraces(originalStack, currentStack) {
303
+ if (!originalStack) return currentStack;
304
+ if (!currentStack) return originalStack;
305
+ const currentHeader = currentStack.split("\n")[0];
306
+ const originalStackBody = originalStack.split("\n").slice(1).join("\n");
307
+ return `${currentHeader}
308
+ ${currentStack.split("\n").slice(1).join("\n")}
309
+
310
+ Caused by:
311
+ ${originalStackBody}`;
312
+ }
266
313
  /**
267
314
  * Extract and normalize error data for formatting
268
315
  * @param includeStack Whether to include stack trace information
@@ -292,7 +339,16 @@ var ComposioError = class _ComposioError extends Error {
292
339
  data.possibleFixes = possibleFixes;
293
340
  }
294
341
  if (includeStack && stack) {
295
- data.stack = stack.split("\n").slice(1);
342
+ if (stack.includes("Caused by:")) {
343
+ const [currentStack, causeStack] = stack.split("Caused by:");
344
+ data.stack = [
345
+ ...currentStack.split("\n").slice(1),
346
+ "Caused by:",
347
+ ...causeStack.split("\n")
348
+ ];
349
+ } else {
350
+ data.stack = stack.split("\n").slice(1);
351
+ }
296
352
  }
297
353
  return data;
298
354
  }
@@ -496,7 +552,7 @@ var ComposioToolExecutionError = class extends ComposioError {
496
552
  "Ensure the tool is correctly configured and the input is valid"
497
553
  ]
498
554
  });
499
- this.error = originalError || (options.cause instanceof Error ? options.cause : new Error(String(options.cause)));
555
+ this.error = originalError || (options.cause instanceof Error ? options.cause : options.cause ? new Error(String(options.cause)) : new Error("Unknown error"));
500
556
  this.name = "ComposioToolExecutionError";
501
557
  }
502
558
  };
@@ -732,7 +788,7 @@ var TelemetryService = class {
732
788
  const descriptor = Object.getOwnPropertyDescriptor(proto, key);
733
789
  return key !== "constructor" && descriptor && typeof descriptor.value === "function" && descriptor.value.constructor.name === "AsyncFunction";
734
790
  });
735
- const instrumentedClassName = instance.constructor?.name || fileName || "unknown";
791
+ const instrumentedClassName = (instance.constructor?.name || fileName) ?? "unknown";
736
792
  for (const name of methodNames) {
737
793
  const originalMethod = instance[name];
738
794
  instance[name] = async (...args) => {
@@ -748,9 +804,11 @@ var TelemetryService = class {
748
804
  try {
749
805
  return await originalMethod.apply(instance, args);
750
806
  } catch (error) {
751
- if (error instanceof Error && !error.errorId) {
752
- error.errorId = getRandomUUID();
753
- this.prepareAndSendErrorTelemetry(error, instrumentedClassName, name, args);
807
+ if (error instanceof Error) {
808
+ if (!error.errorId) {
809
+ error.errorId = getRandomUUID();
810
+ this.prepareAndSendErrorTelemetry(error, instrumentedClassName, name, args);
811
+ }
754
812
  }
755
813
  throw error;
756
814
  }
@@ -784,7 +842,7 @@ var TelemetryService = class {
784
842
  error_id: error.errorId || "",
785
843
  error_message: error.message,
786
844
  original_error: error.cause || error,
787
- current_stack: error.stack?.split("\n") || [],
845
+ current_stack: error.stack ? error.stack.split("\n") : [],
788
846
  description: `Original Call : ${this.telemetryMetadata?.source}:${instrumentedClassName}.${name}(${JSON.stringify(args)})`
789
847
  };
790
848
  this.sendErrorTelemetry(telemetryPayload);
@@ -793,7 +851,7 @@ var TelemetryService = class {
793
851
  error_id: error.errorId || "",
794
852
  error_message: error.message,
795
853
  original_error: error.cause || error,
796
- current_stack: error.stack?.split("\n") || [],
854
+ current_stack: error.stack ? error.stack.split("\n") : [],
797
855
  error_code: error.code,
798
856
  possible_fix: error.possibleFixes?.join("\n"),
799
857
  description: `Original Call : ${instrumentedClassName}.${name}(${JSON.stringify(args)})`
@@ -804,7 +862,7 @@ var TelemetryService = class {
804
862
  error_id: error.errorId || "",
805
863
  error_message: error instanceof Error ? error.name : "Unknown error",
806
864
  original_error: error,
807
- current_stack: error.stack?.split("\n") || [],
865
+ current_stack: error.stack ? error.stack.split("\n") : [],
808
866
  description: `Original Call : ${this.telemetryMetadata?.source}:${instrumentedClassName}.${name}(${JSON.stringify(args)})`
809
867
  };
810
868
  this.sendErrorTelemetry(telemetryPayload);
@@ -951,8 +1009,7 @@ var CustomTools = class {
951
1009
  await this.client.toolkits.retrieve(toolkitSlug);
952
1010
  } catch (error) {
953
1011
  throw new ComposioToolNotFoundError(`Toolkit with slug ${toolkitSlug} not found`, {
954
- toolkitSlug,
955
- error
1012
+ cause: error
956
1013
  });
957
1014
  }
958
1015
  const connectedAccounts = await this.client.connectedAccounts.list({
@@ -961,10 +1018,7 @@ var CustomTools = class {
961
1018
  });
962
1019
  if (!connectedAccounts.items.length) {
963
1020
  throw new ComposioConnectedAccountNotFoundError(
964
- `No connected accounts found for toolkit ${toolkitSlug}`,
965
- {
966
- toolkitSlug
967
- }
1021
+ `No connected accounts found for toolkit ${toolkitSlug}`
968
1022
  );
969
1023
  }
970
1024
  return metadata.connectedAccountId ? connectedAccounts.items.find((item) => item.id === metadata.connectedAccountId) : connectedAccounts.items[0];
@@ -979,9 +1033,7 @@ var CustomTools = class {
979
1033
  async executeCustomTool(slug, inputParams, metadata) {
980
1034
  const tool = this.customToolsRegistry.get(slug.toLowerCase());
981
1035
  if (!tool) {
982
- throw new ComposioToolNotFoundError(`Tool with slug ${slug} not found`, {
983
- toolSlug: slug
984
- });
1036
+ throw new ComposioToolNotFoundError(`Tool with slug ${slug} not found`);
985
1037
  }
986
1038
  let authCredentials = {};
987
1039
  const { toolkitSlug, execute } = tool.options;
@@ -991,8 +1043,10 @@ var CustomTools = class {
991
1043
  throw new ComposioConnectedAccountNotFoundError(
992
1044
  `Connected account not found for toolkit ${toolkitSlug} for user ${metadata.userId}`,
993
1045
  {
994
- toolkitSlug,
995
- userId: metadata.userId
1046
+ meta: {
1047
+ toolkitSlug,
1048
+ userId: metadata.userId
1049
+ }
996
1050
  }
997
1051
  );
998
1052
  }
@@ -1000,7 +1054,9 @@ var CustomTools = class {
1000
1054
  }
1001
1055
  if (typeof execute !== "function") {
1002
1056
  throw new ComposioInvalidExecuteFunctionError("Invalid execute function", {
1003
- toolSlug: slug
1057
+ meta: {
1058
+ toolSlug: slug
1059
+ }
1004
1060
  });
1005
1061
  }
1006
1062
  const executeToolRequest = async (data) => {
@@ -1235,11 +1291,11 @@ var Tools = class {
1235
1291
  });
1236
1292
  }
1237
1293
  const tools = await this.client.tools.list({
1238
- tool_slugs: queryParams.data.tools,
1294
+ tool_slugs: queryParams.data.tools?.join(","),
1239
1295
  toolkit_slug: queryParams.data.toolkits?.join(","),
1240
1296
  cursor: queryParams.data.cursor,
1241
- important: queryParams.data.important,
1242
- limit: queryParams.data.limit,
1297
+ important: typeof queryParams.data.important === "undefined" ? void 0 : queryParams.data.important ? "true" : "false",
1298
+ limit: queryParams.data.limit?.toString(),
1243
1299
  search: queryParams.data.search
1244
1300
  });
1245
1301
  if (!tools) {
@@ -1253,7 +1309,7 @@ var Tools = class {
1253
1309
  if (modifier) {
1254
1310
  if (typeof modifier === "function") {
1255
1311
  modifiedTools = modifiedTools.map((tool) => {
1256
- return modifier(tool.slug, tool.toolkit?.slug || "unkown", tool);
1312
+ return modifier(tool.slug, tool.toolkit?.slug ?? "unknown", tool);
1257
1313
  });
1258
1314
  } else {
1259
1315
  throw new ComposioInvalidModifierError("Invalid schema modifier. Not a function.");
@@ -1285,15 +1341,15 @@ var Tools = class {
1285
1341
  cause: error
1286
1342
  });
1287
1343
  }
1288
- let modifiedToool = this.transformToolCases(tool);
1344
+ let modifiedTool = this.transformToolCases(tool);
1289
1345
  if (modifier) {
1290
1346
  if (typeof modifier === "function") {
1291
- modifiedToool = modifier(slug, modifiedToool.toolkit?.slug || "unkown", modifiedToool);
1347
+ modifiedTool = modifier(slug, modifiedTool.toolkit?.slug ?? "unknown", modifiedTool);
1292
1348
  } else {
1293
1349
  throw new ComposioInvalidModifierError("Invalid schema modifier. Not a function.");
1294
1350
  }
1295
1351
  }
1296
- return modifiedToool;
1352
+ return modifiedTool;
1297
1353
  }
1298
1354
  /**
1299
1355
  * Get a tool or list of tools based on the provided arguments.
@@ -1346,7 +1402,7 @@ var Tools = class {
1346
1402
  async handleCustomToolExecution(tool, body, modifiers) {
1347
1403
  if (modifiers?.beforeExecute) {
1348
1404
  if (typeof modifiers.beforeExecute === "function") {
1349
- body = modifiers.beforeExecute(tool.slug, "unkown", body);
1405
+ body = modifiers.beforeExecute(tool.slug, "unknown", body);
1350
1406
  } else {
1351
1407
  throw new ComposioInvalidModifierError("Invalid beforeExecute modifier. Not a function.");
1352
1408
  }
@@ -1357,7 +1413,7 @@ var Tools = class {
1357
1413
  });
1358
1414
  if (modifiers?.afterExecute) {
1359
1415
  if (typeof modifiers.afterExecute === "function") {
1360
- result = modifiers.afterExecute(tool.slug, "unkown", result);
1416
+ result = modifiers.afterExecute(tool.slug, "unknown", result);
1361
1417
  } else {
1362
1418
  throw new ComposioInvalidModifierError("Invalid afterExecute modifier. Not a function.");
1363
1419
  }
@@ -1375,7 +1431,7 @@ var Tools = class {
1375
1431
  async handleComposioToolExecution(tool, body, modifiers) {
1376
1432
  if (modifiers?.beforeExecute) {
1377
1433
  if (typeof modifiers.beforeExecute === "function") {
1378
- body = modifiers.beforeExecute(tool.slug, tool.toolkit?.slug || "unkown", body);
1434
+ body = modifiers.beforeExecute(tool.slug, tool.toolkit?.slug ?? "unknown", body);
1379
1435
  } else {
1380
1436
  throw new ComposioInvalidModifierError("Invalid beforeExecute modifier. Not a function.");
1381
1437
  }
@@ -1396,7 +1452,7 @@ var Tools = class {
1396
1452
  result = this.transformToolExecuteResponse(result);
1397
1453
  if (modifiers?.afterExecute) {
1398
1454
  if (typeof modifiers.afterExecute === "function") {
1399
- result = modifiers.afterExecute(tool.slug, tool.toolkit?.slug || "unkown", result);
1455
+ result = modifiers.afterExecute(tool.slug, tool.toolkit?.slug ?? "unknown", result);
1400
1456
  } else {
1401
1457
  throw new ComposioInvalidModifierError("Invalid afterExecute modifier. Not a function.");
1402
1458
  }
@@ -1801,7 +1857,7 @@ var AuthConfigListParamsSchema = import_zod5.z.object({
1801
1857
  });
1802
1858
  var AuthConfigListResponseSchema = import_zod5.z.object({
1803
1859
  items: import_zod5.z.array(AuthConfigRetrieveResponseSchema),
1804
- nextCursor: import_zod5.z.string().optional(),
1860
+ nextCursor: import_zod5.z.string().nullable(),
1805
1861
  totalPages: import_zod5.z.number()
1806
1862
  });
1807
1863
  var AuthCustomConfigUpdateParamsSchema = import_zod5.z.object({
@@ -1903,7 +1959,7 @@ var AuthConfigs = class {
1903
1959
  const result = await this.client.authConfigs.list({
1904
1960
  cursor: parsedQuery?.cursor,
1905
1961
  is_composio_managed: parsedQuery?.isComposioManaged,
1906
- limit: parsedQuery?.limit?.toString(),
1962
+ limit: parsedQuery?.limit,
1907
1963
  toolkit_slug: parsedQuery?.toolkit
1908
1964
  });
1909
1965
  const parsedResult = AuthConfigListResponseSchema.safeParse({
@@ -2124,20 +2180,18 @@ var AuthConfigs = class {
2124
2180
  // src/types/connectedAccounts.types.ts
2125
2181
  var import_zod6 = require("zod");
2126
2182
  var ConnectedAccountStatuses = {
2127
- ACTIVE: "ACTIVE",
2128
- INACTIVE: "INACTIVE",
2129
- DELETED: "DELETED",
2183
+ INITIALIZING: "INITIALIZING",
2130
2184
  INITIATED: "INITIATED",
2131
- EXPIRED: "EXPIRED",
2132
- FAILED: "FAILED"
2185
+ ACTIVE: "ACTIVE",
2186
+ FAILED: "FAILED",
2187
+ EXPIRED: "EXPIRED"
2133
2188
  };
2134
2189
  var ConnectedAccountStatusSchema = import_zod6.z.enum([
2135
- ConnectedAccountStatuses.ACTIVE,
2136
- ConnectedAccountStatuses.INACTIVE,
2137
- ConnectedAccountStatuses.DELETED,
2190
+ ConnectedAccountStatuses.INITIALIZING,
2138
2191
  ConnectedAccountStatuses.INITIATED,
2139
- ConnectedAccountStatuses.EXPIRED,
2140
- ConnectedAccountStatuses.FAILED
2192
+ ConnectedAccountStatuses.ACTIVE,
2193
+ ConnectedAccountStatuses.FAILED,
2194
+ ConnectedAccountStatuses.EXPIRED
2141
2195
  ]);
2142
2196
  var CreateConnectedAccountParamsSchema = import_zod6.z.object({
2143
2197
  authConfig: import_zod6.z.object({
@@ -2339,8 +2393,7 @@ var ConnectionRequest = class {
2339
2393
  }
2340
2394
  const terminalErrorStates = [
2341
2395
  ConnectedAccountStatuses.FAILED,
2342
- ConnectedAccountStatuses.EXPIRED,
2343
- ConnectedAccountStatuses.DELETED
2396
+ ConnectedAccountStatuses.EXPIRED
2344
2397
  ];
2345
2398
  const start = Date.now();
2346
2399
  const pollInterval = 1e3;
@@ -2371,6 +2424,23 @@ var ConnectionRequest = class {
2371
2424
  }
2372
2425
  throw new ConnectionRequestTimeoutError(`Connection request timed out for ${this.id}`);
2373
2426
  }
2427
+ /**
2428
+ * Returns a JSON-serializable representation of the connection request
2429
+ * Excludes the private client property to avoid cyclic reference issues
2430
+ */
2431
+ toJSON() {
2432
+ return {
2433
+ id: this.id,
2434
+ status: this.status,
2435
+ redirectUrl: this.redirectUrl
2436
+ };
2437
+ }
2438
+ /**
2439
+ * Returns a string representation of the connection request
2440
+ */
2441
+ toString() {
2442
+ return JSON.stringify(this.toJSON(), null, 2);
2443
+ }
2374
2444
  };
2375
2445
 
2376
2446
  // src/models/ConnectedAccounts.ts
@@ -2830,126 +2900,422 @@ var Toolkits = class {
2830
2900
  }
2831
2901
  };
2832
2902
 
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;
2903
+ // src/types/triggers.types.ts
2904
+ var import_zod8 = require("zod");
2905
+ var TriggerStatusEnum = import_zod8.z.enum(["enable", "disable"]);
2906
+ var TriggerSubscribeParamSchema = import_zod8.z.object({
2907
+ toolkits: import_zod8.z.array(import_zod8.z.string()).optional(),
2908
+ triggerId: import_zod8.z.string().optional(),
2909
+ connectedAccountId: import_zod8.z.string().optional(),
2910
+ authConfigId: import_zod8.z.string().optional(),
2911
+ triggerSlug: import_zod8.z.array(import_zod8.z.string()).optional(),
2912
+ triggerData: import_zod8.z.string().optional(),
2913
+ userId: import_zod8.z.string().optional()
2914
+ });
2915
+ var TriggerInstanceListActiveParamsSchema = import_zod8.z.object({
2916
+ authConfigIds: import_zod8.z.array(import_zod8.z.string()).nullable().optional(),
2917
+ connectedAccountIds: import_zod8.z.array(import_zod8.z.string()).nullable().optional(),
2918
+ limit: import_zod8.z.number().optional(),
2919
+ page: import_zod8.z.number().optional(),
2920
+ showDisabled: import_zod8.z.boolean().nullable().optional(),
2921
+ triggerIds: import_zod8.z.array(import_zod8.z.string()).nullable().optional(),
2922
+ triggerNames: import_zod8.z.array(import_zod8.z.string()).nullable().optional()
2923
+ });
2924
+ var TriggerInstanceListActiveResponseItemSchema = import_zod8.z.object({
2925
+ id: import_zod8.z.string(),
2926
+ connectedAccountId: import_zod8.z.string(),
2927
+ disabledAt: import_zod8.z.string().nullable(),
2928
+ state: import_zod8.z.record(import_zod8.z.unknown()),
2929
+ triggerConfig: import_zod8.z.record(import_zod8.z.unknown()),
2930
+ triggerName: import_zod8.z.string(),
2931
+ updatedAt: import_zod8.z.string(),
2932
+ triggerData: import_zod8.z.string().optional(),
2933
+ uuid: import_zod8.z.string().optional()
2934
+ });
2935
+ var TriggerInstanceListActiveResponseSchema = import_zod8.z.object({
2936
+ items: import_zod8.z.array(TriggerInstanceListActiveResponseItemSchema),
2937
+ nextCursor: import_zod8.z.string().nullable(),
2938
+ totalPages: import_zod8.z.number()
2939
+ });
2940
+ var TriggerInstanceUpsertParamsSchema = import_zod8.z.object({
2941
+ connectedAccountId: import_zod8.z.string().optional(),
2942
+ triggerConfig: import_zod8.z.record(import_zod8.z.unknown()).optional()
2943
+ });
2944
+ var TriggerInstanceUpsertResponseSchema = import_zod8.z.object({
2945
+ triggerId: import_zod8.z.string()
2946
+ });
2947
+ var TriggerInstanceManageUpdateParamsSchema = import_zod8.z.object({
2948
+ status: import_zod8.z.enum(["enable", "disable"])
2949
+ });
2950
+ var TriggerInstanceManageUpdateResponseSchema = import_zod8.z.object({
2951
+ status: import_zod8.z.enum(["success"])
2952
+ });
2953
+ var TriggerInstanceManageDeleteResponseSchema = import_zod8.z.object({
2954
+ triggerId: import_zod8.z.string()
2955
+ });
2956
+ var IncomingTriggerPayloadSchema = import_zod8.z.object({
2957
+ id: import_zod8.z.string().describe("The ID of the trigger"),
2958
+ triggerSlug: import_zod8.z.string().describe("The slug of the trigger that triggered the event"),
2959
+ toolkitSlug: import_zod8.z.string().describe("The slug of the toolkit that triggered the event"),
2960
+ userId: import_zod8.z.string().describe("The ID of the user that triggered the event"),
2961
+ payload: import_zod8.z.record(import_zod8.z.unknown()).describe("The payload of the trigger").optional(),
2962
+ originalPayload: import_zod8.z.record(import_zod8.z.unknown()).describe("The original payload of the trigger").optional(),
2963
+ metadata: import_zod8.z.object({
2964
+ id: import_zod8.z.string(),
2965
+ toolkitSlug: import_zod8.z.string(),
2966
+ triggerSlug: import_zod8.z.string(),
2967
+ triggerData: import_zod8.z.string().optional(),
2968
+ triggerConfig: import_zod8.z.record(import_zod8.z.unknown()),
2969
+ connectedAccount: import_zod8.z.object({
2970
+ id: import_zod8.z.string(),
2971
+ uuid: import_zod8.z.string(),
2972
+ authConfigId: import_zod8.z.string(),
2973
+ authConfigUUID: import_zod8.z.string(),
2974
+ userId: import_zod8.z.string(),
2975
+ status: import_zod8.z.enum(["ACTIVE", "INACTIVE"])
2976
+ })
2977
+ })
2978
+ });
2979
+
2980
+ // src/services/internal/InternalService.types.ts
2981
+ var import_zod9 = require("zod");
2982
+ var SDKRealtimeCredentialsResponseSchema = import_zod9.z.object({
2983
+ projectId: import_zod9.z.string().describe("The project ID"),
2984
+ pusherKey: import_zod9.z.string().describe("The Pusher key"),
2985
+ pusherCluster: import_zod9.z.string().describe("The Pusher cluster")
2986
+ });
2987
+
2988
+ // src/services/internal/InternalService.ts
2989
+ var SDK_REALTIME_CREDENTIALS_ENDPOINT = "/api/v3/internal/sdk/realtime/credentials";
2990
+ var InternalService = class {
2991
+ constructor(client) {
2992
+ this.client = client;
2993
+ this.client = client;
2853
2994
  }
2854
2995
  /**
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.
2996
+ * Get the SDK realtime credentials
2997
+ * @returns {SDKRealtimeCredentialsResponse} The SDK realtime credentials
2860
2998
  */
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
- );
2999
+ async getSDKRealtimeCredentials() {
3000
+ const response = await this.client.request({
3001
+ method: "get",
3002
+ path: SDK_REALTIME_CREDENTIALS_ENDPOINT
3003
+ });
3004
+ const parsedResponse = SDKRealtimeCredentialsResponseSchema.safeParse({
3005
+ pusherKey: response.pusher_key,
3006
+ projectId: response.project_id,
3007
+ pusherCluster: response.pusher_cluster
3008
+ });
3009
+ logger_default.debug(
3010
+ `[InternalService] SDK realtime credentials: ${JSON.stringify(parsedResponse, null, 2)}`
3011
+ );
3012
+ if (!parsedResponse.success) {
3013
+ throw new ValidationError(`Failed to parse SDK realtime credentials`, {
3014
+ cause: parsedResponse.error
3015
+ });
2868
3016
  }
3017
+ return parsedResponse.data;
2869
3018
  }
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);
3019
+ };
3020
+
3021
+ // src/errors/TriggerErrors.ts
3022
+ var import_client5 = require("@composio/client");
3023
+ var TriggerErrorCodes = {
3024
+ TRIGGER_FAILED_TO_GET_SDK_REALTIME_CREDENTIALS: "TRIGGER_FAILED_TO_GET_SDK_REALTIME_CREDENTIALS",
3025
+ TRIGGER_FAILED_TO_CREATE_PUSHER_CLIENT: "TRIGGER_FAILED_TO_CREATE_PUSHER_CLIENT",
3026
+ TRIGGER_FAILED_TO_SUBSCRIBE_TO_PUSHER_CHANNEL: "TRIGGER_FAILED_TO_SUBSCRIBE_TO_PUSHER_CHANNEL",
3027
+ TRIGGER_FAILED_TO_UNSUBSCRIBE_FROM_PUSHER_CHANNEL: "TRIGGER_FAILED_TO_UNSUBSCRIBE_FROM_PUSHER_CHANNEL"
3028
+ };
3029
+ var ComposioFailedToGetSDKRealtimeCredentialsError = class extends import_client5.ComposioError {
3030
+ name = "ComposioFailedToGetSDKRealtimeCredentialsError";
3031
+ code = TriggerErrorCodes.TRIGGER_FAILED_TO_GET_SDK_REALTIME_CREDENTIALS;
3032
+ statusCode = 500;
3033
+ possibleFixes = ["Please contact support."];
3034
+ constructor(message, options) {
3035
+ super(message, options);
3036
+ }
3037
+ };
3038
+ var ComposioFailedToCreatePusherClientError = class extends import_client5.ComposioError {
3039
+ name = "ComposioFailedToCreatePusherClientError";
3040
+ code = TriggerErrorCodes.TRIGGER_FAILED_TO_CREATE_PUSHER_CLIENT;
3041
+ statusCode = 500;
3042
+ possibleFixes = ["Please contact support."];
3043
+ constructor(message, options) {
3044
+ super(message, options);
3045
+ }
3046
+ };
3047
+ var ComposioFailedToSubscribeToPusherChannelError = class extends import_client5.ComposioError {
3048
+ name = "ComposioFailedToSubscribeToPusherChannelError";
3049
+ code = TriggerErrorCodes.TRIGGER_FAILED_TO_SUBSCRIBE_TO_PUSHER_CHANNEL;
3050
+ statusCode = 500;
3051
+ possibleFixes = ["Please contact support."];
3052
+ constructor(message, options) {
3053
+ super(message, options);
3054
+ }
3055
+ };
3056
+
3057
+ // src/services/pusher/Pusher.ts
3058
+ var PusherService = class {
3059
+ // these values are set via the Apollo API `/internal/sdk/realtime/credentials` endpoint
3060
+ clientId;
3061
+ pusherKey;
3062
+ pusherCluster;
3063
+ pusherChannel;
3064
+ // these details are set via the client SDK
3065
+ pusherBaseURL;
3066
+ apiKey;
3067
+ pusherClient;
3068
+ composioClient;
3069
+ constructor(client) {
3070
+ this.composioClient = client;
3071
+ this.pusherBaseURL = client.baseURL;
3072
+ this.apiKey = client.apiKey ?? process.env.COMPOSIO_API_KEY ?? "";
3073
+ telemetry.instrument(this);
2877
3074
  }
2878
3075
  /**
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.
3076
+ * Creates a Pusher client
3077
+ *
3078
+ * This method is called when the Pusher client is first used.
3079
+ * It will fetch the SDK realtime credentials from the Apollo API and create a Pusher client.
2883
3080
  */
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 };
3081
+ async getPusherClient() {
3082
+ if (!this.pusherClient) {
3083
+ const internalService = new InternalService(this.composioClient);
3084
+ let sdkRealtimeCredentials;
3085
+ try {
3086
+ sdkRealtimeCredentials = await internalService.getSDKRealtimeCredentials();
3087
+ } catch (error) {
3088
+ throw new ComposioFailedToGetSDKRealtimeCredentialsError(
3089
+ "Failed to get SDK realtime credentials",
3090
+ {
3091
+ cause: error
3092
+ }
3093
+ );
2891
3094
  }
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];
3095
+ this.clientId = sdkRealtimeCredentials.projectId;
3096
+ this.pusherKey = sdkRealtimeCredentials.pusherKey;
3097
+ this.pusherCluster = sdkRealtimeCredentials.pusherCluster;
3098
+ this.pusherChannel = `private-${this.clientId}_triggers`;
3099
+ logger_default.debug(
3100
+ `[PusherService] Creating Pusher client for client ID: ${this.clientId} in cluster ${this.pusherCluster}`
3101
+ );
3102
+ try {
3103
+ const { default: Pusher } = await import("pusher-js");
3104
+ this.pusherClient = new Pusher(this.pusherKey, {
3105
+ cluster: this.pusherCluster,
3106
+ channelAuthorization: {
3107
+ endpoint: `${this.pusherBaseURL}/api/v3/internal/sdk/realtime/auth`,
3108
+ headers: {
3109
+ "x-api-key": this.apiKey
3110
+ },
3111
+ transport: "ajax"
3112
+ }
3113
+ });
3114
+ } catch (error) {
3115
+ throw new ComposioFailedToCreatePusherClientError("Failed to create Pusher client", {
3116
+ cause: error
3117
+ });
2898
3118
  }
2899
- });
3119
+ }
3120
+ return this.pusherClient;
2900
3121
  }
2901
3122
  /**
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.
3123
+ * Binds a chunked event to a Pusher client
3124
+ *
3125
+ *
3126
+ * @param channel - The Pusher client to bind the event to
3127
+ * @param event - The event to bind to
3128
+ * @param callback - The function to call when the event is received
2905
3129
  */
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`);
3130
+ bindWithChunking(channel, event, callback) {
3131
+ try {
3132
+ channel.bind(event, callback);
3133
+ const events = {};
3134
+ channel.bind("chunked-" + event, (data) => {
3135
+ try {
3136
+ const typedData = data;
3137
+ if (!typedData || typeof typedData.id !== "string" || typeof typedData.index !== "number") {
3138
+ throw new Error("Invalid chunked trigger data format");
3139
+ }
3140
+ if (!events.hasOwnProperty(typedData.id)) {
3141
+ events[typedData.id] = { chunks: [], receivedFinal: false };
3142
+ }
3143
+ const ev = events[typedData.id];
3144
+ ev.chunks[typedData.index] = typedData.chunk;
3145
+ if (typedData.final) ev.receivedFinal = true;
3146
+ if (ev.receivedFinal && ev.chunks.length === Object.keys(ev.chunks).length) {
3147
+ try {
3148
+ const parsedData = JSON.parse(ev.chunks.join(""));
3149
+ callback(parsedData);
3150
+ } catch (parseError) {
3151
+ const errorMessage = parseError instanceof Error ? parseError.message : String(parseError);
3152
+ logger_default.error("Failed to parse chunked data:", errorMessage);
3153
+ } finally {
3154
+ delete events[typedData.id];
3155
+ }
3156
+ }
3157
+ } catch (error) {
3158
+ const errorMessage = error instanceof Error ? error.message : String(error);
3159
+ logger_default.error("Error processing chunked trigger data:", errorMessage);
3160
+ if (data && typeof data === "object" && "id" in data) {
3161
+ delete events[data.id];
3162
+ }
3163
+ }
3164
+ });
3165
+ } catch (error) {
3166
+ const errorMessage = error instanceof Error ? error.message : String(error);
3167
+ logger_default.error("Failed to bind chunked events:", error);
3168
+ throw new Error(`Failed to bind chunked events: ${errorMessage}`);
3169
+ }
2921
3170
  }
2922
- };
2923
-
2924
- // src/models/Session.ts
2925
- var Session = class {
2926
- client;
2927
- constructor(client) {
2928
- this.client = client;
2929
- telemetry.instrument(this);
3171
+ /**
3172
+ * Subscribes to pusher to receive events from the server
3173
+ *
3174
+ * This method is used to subscribe to a Pusher channel.
3175
+ * It will create a Pusher client if it doesn't exist.
3176
+ *
3177
+ * @param channelName - The name of the Pusher channel to subscribe to
3178
+ * @param event - The event to subscribe to
3179
+ * @param fn - The function to call when the event is received
3180
+ */
3181
+ async subscribe(fn) {
3182
+ try {
3183
+ logger_default.debug(`[PusherService] Subscribing to channel: ${this.pusherChannel}`);
3184
+ const pusherClient = await this.getPusherClient();
3185
+ const channel = await pusherClient.subscribe(this.pusherChannel);
3186
+ channel.bind("pusher:subscription_error", (data) => {
3187
+ const error = data.error ? String(data.error) : "Unknown subscription error";
3188
+ throw new ComposioFailedToSubscribeToPusherChannelError(
3189
+ `Trigger subscription error: ${error}`,
3190
+ {
3191
+ cause: error
3192
+ }
3193
+ );
3194
+ });
3195
+ const safeCallback = (data) => {
3196
+ try {
3197
+ fn(data);
3198
+ } catch (error) {
3199
+ const errorMessage = error instanceof Error ? error.message : String(error);
3200
+ logger_default.error("\u274C Error in trigger callback:", errorMessage);
3201
+ }
3202
+ };
3203
+ this.bindWithChunking(channel, "trigger_to_client", safeCallback);
3204
+ logger_default.info(`\u2705 Subscribed to triggers. You should start receiving events now.`);
3205
+ } catch (error) {
3206
+ throw new ComposioFailedToSubscribeToPusherChannelError(
3207
+ "Failed to subscribe to Pusher channel",
3208
+ {
3209
+ cause: error
3210
+ }
3211
+ );
3212
+ }
2930
3213
  }
2931
3214
  /**
2932
- * Get the active session info
2933
- * @returns {Promise<SessionGetInfoResponse>} Session info
3215
+ * Unsubscribes from a Pusher channel
3216
+ *
3217
+ * This method is used to unsubscribe from a Pusher channel.
3218
+ * It will create a Pusher client if it doesn't exist.
3219
+ *
3220
+ * @param channelName - The name of the Pusher channel to unsubscribe from
2934
3221
  */
2935
- async getInfo() {
2936
- return this.client.auth.session.getInfo();
3222
+ async unsubscribe() {
3223
+ try {
3224
+ logger_default.debug(`[PusherService] Unsubscribing from channel: ${this.pusherChannel}`);
3225
+ const pusherClient = await this.getPusherClient();
3226
+ await pusherClient.unsubscribe(this.pusherChannel);
3227
+ logger_default.info(`\u2705 Unsubscribed from triggers.`);
3228
+ } catch (error) {
3229
+ throw new ComposioFailedToSubscribeToPusherChannelError(
3230
+ "Failed to unsubscribe from Pusher channel",
3231
+ {
3232
+ cause: error
3233
+ }
3234
+ );
3235
+ }
2937
3236
  }
2938
3237
  };
2939
3238
 
2940
3239
  // src/models/Triggers.ts
2941
3240
  var Triggers = class {
2942
3241
  client;
3242
+ pusherService;
2943
3243
  constructor(client) {
2944
3244
  this.client = client;
3245
+ this.pusherService = new PusherService(client);
2945
3246
  telemetry.instrument(this);
2946
3247
  }
3248
+ /**
3249
+ * Parse the trigger instance list active item
3250
+ *
3251
+ * @param response - The response from the composio client
3252
+ * @returns The parsed trigger instance list active item
3253
+ */
3254
+ parseTriggerInstanceListActiveItem(response) {
3255
+ const parsed = TriggerInstanceListActiveResponseItemSchema.safeParse({
3256
+ id: response.id,
3257
+ connectedAccountId: response.connected_account_id,
3258
+ disabledAt: response.disabled_at,
3259
+ state: response.state,
3260
+ triggerConfig: response.trigger_config,
3261
+ triggerName: response.trigger_name,
3262
+ updatedAt: response.updated_at,
3263
+ triggerData: response.trigger_data,
3264
+ uuid: response.uuid
3265
+ });
3266
+ if (!parsed.success) {
3267
+ throw new ValidationError(`Invalid trigger instance list active item`, {
3268
+ cause: parsed.error
3269
+ });
3270
+ }
3271
+ return parsed.data;
3272
+ }
2947
3273
  /**
2948
3274
  * Fetch list of all the active triggers
2949
- * @returns {Promise<TriggerInstance[]>} List of trigger instances
3275
+ *
3276
+ * @param {TriggerInstanceListActiveParams} query - The query parameters to filter the trigger instances
3277
+ * @returns {Promise<TriggerInstanceListActiveResponse>} List of trigger instances
3278
+ *
3279
+ * @throws {ValidationError} If the parameters are invalid
3280
+ * @throws {Error} If the client is not authenticated
3281
+ *
3282
+ * @example
3283
+ * ```ts
3284
+ * const triggers = await triggers.listActive({
3285
+ * authConfigIds: ['123'],
3286
+ * connectedAccountIds: ['456'],
3287
+ * });
3288
+ * ```
2950
3289
  */
2951
- async list(query, options) {
2952
- return this.client.triggerInstances.listActive(query, options);
3290
+ async listActive(query) {
3291
+ const parsedParams = TriggerInstanceListActiveParamsSchema.safeParse(query ?? {});
3292
+ if (!parsedParams.success) {
3293
+ throw new ValidationError(`Invalid parameters passed to list triggers`, {
3294
+ cause: parsedParams.error
3295
+ });
3296
+ }
3297
+ const result = await this.client.triggerInstances.listActive(
3298
+ query ? {
3299
+ auth_config_ids: parsedParams.data.authConfigIds,
3300
+ connected_account_ids: parsedParams.data.connectedAccountIds,
3301
+ limit: parsedParams.data.limit,
3302
+ page: parsedParams.data.page,
3303
+ show_disabled: parsedParams.data.showDisabled,
3304
+ trigger_ids: parsedParams.data.triggerIds,
3305
+ trigger_names: parsedParams.data.triggerNames
3306
+ } : void 0
3307
+ );
3308
+ const parsedResult = TriggerInstanceListActiveResponseSchema.safeParse({
3309
+ items: result.items.map((item) => this.parseTriggerInstanceListActiveItem(item)),
3310
+ nextCursor: result.next_cursor,
3311
+ totalPages: result.total_pages
3312
+ });
3313
+ if (!parsedResult.success) {
3314
+ throw new ValidationError(`Invalid trigger instance list active response`, {
3315
+ cause: parsedResult.error
3316
+ });
3317
+ }
3318
+ return parsedResult.data;
2953
3319
  }
2954
3320
  /**
2955
3321
  * Create a new trigger instance
@@ -2958,58 +3324,76 @@ var Triggers = class {
2958
3324
  * @param {TriggerInstanceUpsertParams} body - The parameters to create the trigger instance
2959
3325
  * @returns {Promise<TriggerInstanceUpsertResponse>} The created trigger instance
2960
3326
  */
2961
- async create(slug, body, options) {
2962
- return this.client.triggerInstances.upsert(slug, body, options);
3327
+ async create(slug, body) {
3328
+ const parsedBody = TriggerInstanceUpsertParamsSchema.safeParse(body);
3329
+ if (!parsedBody.success) {
3330
+ throw new ValidationError(`Invalid parameters passed to create trigger`, {
3331
+ cause: parsedBody.error
3332
+ });
3333
+ }
3334
+ const result = await this.client.triggerInstances.upsert(slug, {
3335
+ connected_account_id: parsedBody.data.connectedAccountId,
3336
+ trigger_config: parsedBody.data.triggerConfig
3337
+ });
3338
+ const parsedResult = TriggerInstanceUpsertResponseSchema.safeParse({
3339
+ triggerId: result.trigger_id
3340
+ });
3341
+ if (!parsedResult.success) {
3342
+ throw new ValidationError(`Invalid trigger instance upsert response`, {
3343
+ cause: parsedResult.error
3344
+ });
3345
+ }
3346
+ return parsedResult.data;
2963
3347
  }
2964
3348
  /**
2965
3349
  * Update an existing trigger instance
2966
3350
  *
2967
3351
  * @param {string} slug - The slug of the trigger instance
2968
- * @param {TriggerInstanceUpsertParams} body - The parameters to create the trigger instance
3352
+ * @param {TriggerInstanceManageUpdateParams} body - The parameters to create the trigger instance
2969
3353
  * @returns {Promise<TriggerInstanceUpsertResponse>} The updated trigger instance
2970
3354
  */
2971
- async update(slug, body, options) {
2972
- return this.client.triggerInstances.upsert(slug, body, options);
3355
+ async update(slug, body) {
3356
+ return this.client.triggerInstances.manage.update(slug, body);
2973
3357
  }
2974
3358
  /**
2975
3359
  * Delete a trigger instance
2976
3360
  *
2977
- * @param {string} slug - The slug of the trigger instance
3361
+ * @param {string} triggerId - The slug of the trigger instance
2978
3362
  * @returns
2979
3363
  */
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);
3364
+ async delete(triggerId) {
3365
+ const result = await this.client.triggerInstances.manage.delete(triggerId);
3366
+ const parsedResult = TriggerInstanceManageDeleteResponseSchema.safeParse({
3367
+ triggerId: result.trigger_id
3368
+ });
3369
+ if (!parsedResult.success) {
3370
+ throw new ValidationError(`Invalid trigger instance manage delete response`, {
3371
+ cause: parsedResult.error
3372
+ });
3373
+ }
3374
+ return parsedResult.data;
2993
3375
  }
2994
3376
  /**
2995
3377
  * Disable a trigger instance
2996
3378
  *
2997
- * @param {string} slug - The slug of the trigger instance
2998
- * @param {RequestOptions options - Request options
3379
+ * @param {string} triggerId - The id of the trigger instance
2999
3380
  * @returns {Promise<TriggerInstanceUpsertResponse>} The updated trigger instance
3000
3381
  */
3001
- async disable(slug, options) {
3002
- return this.client.triggerInstances.updateStatus("disable", { slug }, options);
3382
+ async disable(triggerId) {
3383
+ return this.client.triggerInstances.manage.update(triggerId, {
3384
+ status: "disable"
3385
+ });
3003
3386
  }
3004
3387
  /**
3005
3388
  * Enable a trigger instance
3006
3389
  *
3007
- * @param {string} slug - The slug of the trigger instance
3008
- * @param {RequestOptions options - Request options
3390
+ * @param {string} triggerId - The id of the trigger instance
3009
3391
  * @returns {Promise<TriggerInstanceUpsertResponse>} The updated trigger instance
3010
3392
  */
3011
- async enable(slug, options) {
3012
- return this.client.triggerInstances.updateStatus("enable", { slug }, options);
3393
+ async enable(triggerId) {
3394
+ return this.client.triggerInstances.manage.update(triggerId, {
3395
+ status: "enable"
3396
+ });
3013
3397
  }
3014
3398
  /**
3015
3399
  * @TODO Learn about trigger types
@@ -3021,8 +3405,8 @@ var Triggers = class {
3021
3405
  * @param {RequestOptions} options - Request options
3022
3406
  * @returns {Promise<TriggersTypeListResponse>} The list of trigger types
3023
3407
  */
3024
- async listTypes(query, options) {
3025
- return this.client.triggersTypes.list(query, options);
3408
+ async listTypes(query) {
3409
+ return this.client.triggersTypes.list(query);
3026
3410
  }
3027
3411
  /**
3028
3412
  * Retrieve a trigger type by its slug
@@ -3031,8 +3415,8 @@ var Triggers = class {
3031
3415
  * @param {RequestOptions} options - request options
3032
3416
  * @returns {Promise<TriggersTypeRetrieveResponse>} The trigger type object
3033
3417
  */
3034
- async getType(slug, options) {
3035
- return this.client.triggersTypes.retrieve(slug, options);
3418
+ async getType(slug) {
3419
+ return this.client.triggersTypes.retrieve(slug);
3036
3420
  }
3037
3421
  /**
3038
3422
  * Fetches the list of all the available trigger enums
@@ -3041,36 +3425,137 @@ var Triggers = class {
3041
3425
  * @param options
3042
3426
  * @returns
3043
3427
  */
3044
- async listEnum(options) {
3045
- return this.client.triggersTypes.retrieveEnum(options);
3428
+ async listEnum() {
3429
+ return this.client.triggersTypes.retrieveEnum();
3046
3430
  }
3431
+ /**
3432
+ * Subscribe to all the triggers
3433
+ *
3434
+ * @param fn - The function to call when a trigger is received
3435
+ * @param filters - The filters to apply to the triggers
3436
+ *
3437
+ * @example
3438
+ * ```ts
3439
+ *
3440
+ * triggers.subscribe((data) => {
3441
+ * console.log(data);
3442
+ * }, );
3443
+ * ```
3444
+ */
3047
3445
  async subscribe(fn, filters = {}) {
3048
3446
  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());
3447
+ const parsedFilters = TriggerSubscribeParamSchema.safeParse(filters);
3448
+ if (!parsedFilters.success) {
3449
+ throw new ValidationError(`Invalid parameters passed to subscribe to triggers`, {
3450
+ cause: parsedFilters.error
3451
+ });
3452
+ }
3453
+ const shouldSendTriggerAfterFilters = (data) => {
3454
+ if (parsedFilters.data.toolkits?.length && !parsedFilters.data.toolkits.map((toolkit) => toolkit.toLowerCase()).includes(data.toolkitSlug.toLowerCase())) {
3455
+ logger_default.debug(
3456
+ "Trigger does not match toolkits filter",
3457
+ JSON.stringify(parsedFilters.data.toolkits, null, 2)
3458
+ );
3459
+ return false;
3460
+ }
3461
+ if (parsedFilters.data.triggerId && parsedFilters.data.triggerId !== data.id) {
3462
+ logger_default.debug(
3463
+ "Trigger does not match triggerId filter",
3464
+ JSON.stringify(parsedFilters.data.triggerId, null, 2)
3465
+ );
3466
+ return false;
3467
+ }
3468
+ if (parsedFilters.data.connectedAccountId && parsedFilters.data.connectedAccountId !== data.metadata.connectedAccount.id) {
3469
+ logger_default.debug(
3470
+ "Trigger does not match connectedAccountId filter",
3471
+ JSON.stringify(parsedFilters.data.connectedAccountId, null, 2)
3472
+ );
3473
+ return false;
3474
+ }
3475
+ if (parsedFilters.data.triggerSlug?.length && !parsedFilters.data.triggerSlug.map((triggerSlug) => triggerSlug.toLowerCase()).includes(data.triggerSlug.toLowerCase())) {
3476
+ logger_default.debug(
3477
+ "Trigger does not match triggerSlug filter",
3478
+ JSON.stringify(parsedFilters.data.triggerSlug, null, 2)
3479
+ );
3480
+ return false;
3481
+ }
3482
+ if (parsedFilters.data.triggerData && parsedFilters.data.triggerData !== data.metadata.triggerData) {
3483
+ logger_default.debug(
3484
+ "Trigger does not match triggerData filter",
3485
+ JSON.stringify(parsedFilters.data.triggerData, null, 2)
3486
+ );
3487
+ return false;
3059
3488
  }
3489
+ if (parsedFilters.data.userId && parsedFilters.data.userId !== data.metadata.connectedAccount.userId) {
3490
+ logger_default.debug(
3491
+ "Trigger does not match userId filter",
3492
+ JSON.stringify(parsedFilters.data.userId, null, 2)
3493
+ );
3494
+ return false;
3495
+ }
3496
+ logger_default.debug("Trigger matches all filters", JSON.stringify(parsedFilters.data, null, 2));
3497
+ return true;
3060
3498
  };
3061
- logger_default.debug("Subscribing to triggers", filters);
3062
- PusherUtils.triggerSubscribe(clientId, (data) => {
3063
- if (shouldSendTrigger(data)) {
3064
- fn(data);
3499
+ logger_default.debug("\u{1F504} Subscribing to triggers with filters: ", JSON.stringify(filters, null, 2));
3500
+ await this.pusherService.subscribe((_data) => {
3501
+ logger_default.debug("Received raw trigger data", JSON.stringify(_data, null, 2));
3502
+ const data = _data;
3503
+ const parsedData = IncomingTriggerPayloadSchema.safeParse({
3504
+ id: data.metadata.id,
3505
+ triggerSlug: data.metadata.triggerName,
3506
+ toolkitSlug: data.appName,
3507
+ userId: data.metadata.connection?.clientUniqueUserId,
3508
+ payload: data.payload,
3509
+ originalPayload: data.originalPayload,
3510
+ metadata: {
3511
+ id: data.metadata.id,
3512
+ triggerConfig: data.metadata.triggerConfig,
3513
+ triggerSlug: data.metadata.triggerName,
3514
+ toolkitSlug: data.appName,
3515
+ triggerData: data.metadata.triggerData,
3516
+ connectedAccount: {
3517
+ id: data.metadata.connection?.connectedAccountNanoId,
3518
+ uuid: data.metadata.connection?.id,
3519
+ authConfigId: data.metadata.connection?.authConfigNanoId,
3520
+ authConfigUUID: data.metadata.connection?.integrationId,
3521
+ userId: data.metadata.connection?.clientUniqueUserId,
3522
+ status: data.metadata.connection?.status
3523
+ }
3524
+ }
3525
+ });
3526
+ logger_default.debug("Parsed trigger data", JSON.stringify(parsedData.data, null, 2));
3527
+ if (parsedData.error) {
3528
+ throw new ValidationError(`Invalid trigger payload`, {
3529
+ cause: parsedData.error
3530
+ });
3531
+ }
3532
+ if (shouldSendTriggerAfterFilters(parsedData.data)) {
3533
+ try {
3534
+ fn(parsedData.data);
3535
+ } catch (error) {
3536
+ logger_default.error("\u274C Error in trigger callback:", error);
3537
+ }
3538
+ } else {
3539
+ logger_default.debug("Trigger does not match filters", JSON.stringify(parsedFilters.data, null, 2));
3065
3540
  }
3066
3541
  });
3067
3542
  }
3543
+ /**
3544
+ * Unsubscribe from all the triggers
3545
+ *
3546
+ * @returns {Promise<void>}
3547
+ *
3548
+ * @example
3549
+ * ```ts
3550
+ * composio.trigger.subscribe((data) => {
3551
+ * console.log(data);
3552
+ * });
3553
+ *
3554
+ * await triggers.unsubscribe();
3555
+ * ```
3556
+ */
3068
3557
  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);
3558
+ await this.pusherService.unsubscribe();
3074
3559
  }
3075
3560
  };
3076
3561
 
@@ -3153,7 +3638,7 @@ var BaseProvider = class {
3153
3638
  }
3154
3639
  /**
3155
3640
  * @public
3156
- * Gloabl function to execute a tool.
3641
+ * Global function to execute a tool.
3157
3642
  * This function is used by provider providers to implement helper functions to execute tools.
3158
3643
  * This is a 1:1 mapping of the `execute` method in the `Tools` class.
3159
3644
  * @param {string} toolSlug - The slug of the tool to execute.
@@ -3220,7 +3705,7 @@ var OpenAIProvider = class extends BaseNonAgenticProvider {
3220
3705
  * @param {string} userId - The user id.
3221
3706
  * @returns {Promise<string[]>} The results of the tool call.
3222
3707
  */
3223
- async handleToolCall(userId, chatCompletion, options, modifiers) {
3708
+ async handleToolCalls(userId, chatCompletion, options, modifiers) {
3224
3709
  const outputs = [];
3225
3710
  for (const message of chatCompletion.choices) {
3226
3711
  if (message.message.tool_calls) {
@@ -3340,7 +3825,7 @@ var OpenAIProvider = class extends BaseNonAgenticProvider {
3340
3825
  };
3341
3826
 
3342
3827
  // package.json
3343
- var version = "0.1.12-alpha.11";
3828
+ var version = "0.1.12-alpha.12";
3344
3829
 
3345
3830
  // src/composio.ts
3346
3831
  var Composio = class {
@@ -3382,7 +3867,7 @@ var Composio = class {
3382
3867
  if (IS_DEVELOPMENT_OR_CI) {
3383
3868
  logger_default.debug(`Initializing Composio w API Key: [REDACTED] and baseURL: ${baseURLParsed}`);
3384
3869
  }
3385
- this.client = new import_client5.default({
3870
+ this.client = new import_client6.default({
3386
3871
  apiKey: apiKeyParsed,
3387
3872
  baseURL: baseURLParsed
3388
3873
  });
@@ -3402,7 +3887,7 @@ var Composio = class {
3402
3887
  {
3403
3888
  apiKey: apiKeyParsed ?? "",
3404
3889
  baseUrl: baseURLParsed ?? "",
3405
- frameworkRuntime: this.provider?.name || "unknown",
3890
+ frameworkRuntime: this.provider?.name ?? "unknown",
3406
3891
  isAgentic: this.provider?._isAgentic || false,
3407
3892
  source: "javascript",
3408
3893
  version,
@@ -3455,39 +3940,39 @@ var ConsoleTelemetryTransport = class {
3455
3940
  };
3456
3941
 
3457
3942
  // src/utils/jsonSchema.ts
3458
- var import_zod8 = require("zod");
3943
+ var import_zod10 = require("zod");
3459
3944
  function jsonSchemaPropertiesToTSTypes(value) {
3460
3945
  if (!value.type) {
3461
- return import_zod8.z.object({});
3946
+ return import_zod10.z.object({});
3462
3947
  }
3463
3948
  let zodType;
3464
3949
  switch (value.type) {
3465
3950
  case "string":
3466
- zodType = import_zod8.z.string().describe(
3951
+ zodType = import_zod10.z.string().describe(
3467
3952
  (value.description || "") + (value.examples ? `
3468
3953
  Examples: ${value.examples.join(", ")}` : "")
3469
3954
  );
3470
3955
  break;
3471
3956
  case "number":
3472
- zodType = import_zod8.z.number().describe(
3957
+ zodType = import_zod10.z.number().describe(
3473
3958
  (value.description || "") + (value.examples ? `
3474
3959
  Examples: ${value.examples.join(", ")}` : "")
3475
3960
  );
3476
3961
  break;
3477
3962
  case "integer":
3478
- zodType = import_zod8.z.number().int().describe(
3963
+ zodType = import_zod10.z.number().int().describe(
3479
3964
  (value.description || "") + (value.examples ? `
3480
3965
  Examples: ${value.examples.join(", ")}` : "")
3481
3966
  );
3482
3967
  break;
3483
3968
  case "boolean":
3484
- zodType = import_zod8.z.boolean().describe(
3969
+ zodType = import_zod10.z.boolean().describe(
3485
3970
  (value.description || "") + (value.examples ? `
3486
3971
  Examples: ${value.examples.join(", ")}` : "")
3487
3972
  );
3488
3973
  break;
3489
3974
  case "array":
3490
- zodType = import_zod8.z.array(
3975
+ zodType = import_zod10.z.array(
3491
3976
  jsonSchemaPropertiesToTSTypes(
3492
3977
  value.items
3493
3978
  )
@@ -3497,24 +3982,24 @@ Examples: ${value.examples.join(", ")}` : "")
3497
3982
  );
3498
3983
  break;
3499
3984
  case "object":
3500
- zodType = jsonSchemaToModel(value).describe(
3985
+ zodType = jsonSchemaToZodSchema(value).describe(
3501
3986
  (value.description || "") + (value.examples ? `
3502
3987
  Examples: ${value.examples.join(", ")}` : "")
3503
3988
  );
3504
3989
  break;
3505
3990
  case "null":
3506
- zodType = import_zod8.z.null().describe(value.description || "");
3991
+ zodType = import_zod10.z.null().describe(value.description || "");
3507
3992
  break;
3508
3993
  default:
3509
3994
  throw new Error(`Unsupported JSON schema type: ${value.type}`);
3510
3995
  }
3511
3996
  return zodType;
3512
3997
  }
3513
- function jsonSchemaToModel(jsonSchema) {
3998
+ function jsonSchemaToZodSchema(jsonSchema) {
3514
3999
  const properties = jsonSchema.properties;
3515
4000
  const requiredFields = jsonSchema.required || [];
3516
4001
  if (!properties) {
3517
- return import_zod8.z.object({});
4002
+ return import_zod10.z.object({});
3518
4003
  }
3519
4004
  const zodSchema = {};
3520
4005
  for (const [key, _] of Object.entries(properties)) {
@@ -3526,7 +4011,7 @@ function jsonSchemaToModel(jsonSchema) {
3526
4011
  schema
3527
4012
  )
3528
4013
  );
3529
- zodType = import_zod8.z.union(anyOfTypes).describe(
4014
+ zodType = import_zod10.z.union(anyOfTypes).describe(
3530
4015
  (value.description || "") + (value.examples ? `
3531
4016
  Examples: ${value.examples.join(", ")}` : "")
3532
4017
  );
@@ -3536,7 +4021,7 @@ Examples: ${value.examples.join(", ")}` : "")
3536
4021
  schema
3537
4022
  )
3538
4023
  );
3539
- zodType = import_zod8.z.intersection(
4024
+ zodType = import_zod10.z.intersection(
3540
4025
  allOfTypes[0],
3541
4026
  allOfTypes.slice(1).reduce((acc, schema) => acc.and(schema), allOfTypes[0])
3542
4027
  ).describe(
@@ -3560,7 +4045,7 @@ Examples: ${value.examples.join(", ")}` : "")
3560
4045
  zodSchema[key] = zodType.optional();
3561
4046
  }
3562
4047
  }
3563
- return import_zod8.z.object(zodSchema);
4048
+ return import_zod10.z.object(zodSchema);
3564
4049
  }
3565
4050
  // Annotate the CommonJS export names for ESM import in node:
3566
4051
  0 && (module.exports = {
@@ -3597,5 +4082,6 @@ Examples: ${value.examples.join(", ")}` : "")
3597
4082
  ToolkitErrorCodes,
3598
4083
  ValidationError,
3599
4084
  ValidationErrorCodes,
3600
- jsonSchemaToModel
4085
+ jsonSchemaToZodSchema,
4086
+ logger
3601
4087
  });