@composio/core 0.1.11-alpha.0 → 0.1.12-alpha.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -6,7 +6,7 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
6
6
  });
7
7
 
8
8
  // src/composio.ts
9
- import ComposioClient from "@composio/client";
9
+ import ComposioClient2 from "@composio/client";
10
10
 
11
11
  // src/types/tool.types.ts
12
12
  import { z } from "zod";
@@ -69,12 +69,14 @@ var ToolExecuteResponseSchema = z.object({
69
69
  // src/models/CustomTools.ts
70
70
  import zodToJsonSchema from "zod-to-json-schema";
71
71
 
72
+ // src/utils/logger.ts
73
+ import chalk from "chalk";
74
+
72
75
  // src/utils/env.ts
73
76
  var getEnvVariable = (name, defaultValue = void 0) => {
74
77
  try {
75
78
  return process.env[name] || defaultValue;
76
79
  } catch (_e) {
77
- logger_default.error(`Error getting environment variable ${name}:`, _e);
78
80
  return defaultValue;
79
81
  }
80
82
  };
@@ -93,7 +95,7 @@ var LOG_LEVELS = {
93
95
  // Debug information
94
96
  };
95
97
  var getLogLevel = () => {
96
- const envLevel = getEnvVariable("COMPOSIO_LOGGING_LEVEL", "info")?.toLowerCase();
98
+ const envLevel = getEnvVariable("COMPOSIO_LOG_LEVEL", "info")?.toLowerCase();
97
99
  return envLevel && envLevel in LOG_LEVELS ? envLevel : "info";
98
100
  };
99
101
  var Logger = class {
@@ -111,7 +113,7 @@ var Logger = class {
111
113
  return formattedArgs;
112
114
  }
113
115
  const timestamp = (/* @__PURE__ */ new Date()).toISOString();
114
- return `${timestamp} - ${formattedArgs}`;
116
+ return `${chalk.gray(timestamp)} - ${formattedArgs}`;
115
117
  }
116
118
  shouldLog(level) {
117
119
  return LOG_LEVELS[level] <= LOG_LEVELS[this.level];
@@ -275,6 +277,265 @@ var ComposioConnectedAccountNotFoundError = class extends ComposioError {
275
277
  }
276
278
  };
277
279
 
280
+ // src/types/telemetry.types.ts
281
+ var TELEMETRY_EVENTS = {
282
+ SDK_INITIALIZED: "SDK_INITIALIZED",
283
+ SDK_METHOD_INVOKED: "SDK_METHOD_INVOKED",
284
+ SDK_METHOD_ERROR: "SDK_METHOD_ERROR",
285
+ CLI_INVOKED: "CLI_INVOKED"
286
+ };
287
+
288
+ // src/utils/constants.ts
289
+ var COMPOSIO_DIR = ".composio";
290
+ var USER_DATA_FILE_NAME = "user_data.json";
291
+ var DEFAULT_BASE_URL = "https://backend.composio.dev";
292
+ var TELEMETRY_URL = "https://app.composio.dev";
293
+ var IS_DEVELOPMENT_OR_CI = process.env.DEVELOPMENT || process.env.CI || false;
294
+
295
+ // src/telemetry/BatchProcessor.ts
296
+ var BatchProcessor = class {
297
+ batch = [];
298
+ time;
299
+ batchSize;
300
+ processBatchCallback;
301
+ timer = null;
302
+ constructor(time = 2e3, batchSize = 100, processBatchCallback) {
303
+ this.batch = [];
304
+ this.time = time;
305
+ this.batchSize = batchSize;
306
+ this.processBatchCallback = processBatchCallback;
307
+ }
308
+ pushItem(item) {
309
+ this.batch.push(item);
310
+ if (this.batch.length >= this.batchSize) {
311
+ this.processBatch();
312
+ } else if (!this.timer) {
313
+ this.timer = setTimeout(() => this.processBatch(), this.time);
314
+ }
315
+ }
316
+ processBatch() {
317
+ if (this.batch.length > 0) {
318
+ this.processBatchCallback(this.batch);
319
+ this.batch = [];
320
+ }
321
+ if (this.timer) {
322
+ clearTimeout(this.timer);
323
+ this.timer = null;
324
+ }
325
+ }
326
+ };
327
+
328
+ // src/telemetry/transports/BrowserTransport.ts
329
+ var BrowserTelemetryTransport = class {
330
+ send(payload) {
331
+ if (typeof window === "undefined") {
332
+ return Promise.reject(
333
+ new Error("BrowserTelemetryTransport can only be used in browser environments")
334
+ );
335
+ }
336
+ return new Promise((resolve) => {
337
+ try {
338
+ const xhr = new XMLHttpRequest();
339
+ xhr.open(payload.method, payload.url, true);
340
+ xhr.setRequestHeader("Content-Type", "application/json");
341
+ Object.entries(payload.headers || {}).forEach(([key, value]) => {
342
+ xhr.setRequestHeader(key, value);
343
+ });
344
+ xhr.onload = function() {
345
+ resolve();
346
+ };
347
+ xhr.send(JSON.stringify(payload.data));
348
+ } catch (error) {
349
+ logger_default.error("Error sending error to telemetry", error);
350
+ resolve();
351
+ }
352
+ });
353
+ }
354
+ };
355
+
356
+ // src/telemetry/transports/ProcessTransport.ts
357
+ import chalk2 from "chalk";
358
+ var ProcessTelemetryTransport = class {
359
+ send(payload) {
360
+ if (typeof window !== "undefined") {
361
+ return Promise.reject(
362
+ new Error("ProcessTelemetryTransport can only be used in Node.js environments")
363
+ );
364
+ }
365
+ return new Promise((resolve) => {
366
+ try {
367
+ const url = new URL(payload.url);
368
+ const protocol = url.protocol === "https:" ? "https" : "http";
369
+ const port = url.port || (url.protocol === "https:" ? 443 : 80);
370
+ const args = [
371
+ "-e",
372
+ `
373
+ const http = require('${protocol}');
374
+ const options = {
375
+ hostname: '${url.hostname}',
376
+ path: '${url.pathname}${url.search}',
377
+ port: ${port},
378
+ method: '${payload.method}',
379
+ headers: ${JSON.stringify(payload.headers)}
380
+ };
381
+
382
+ const req = http.request(options, (res) => {
383
+ res.on('data', () => {});
384
+ res.on('end', () => {
385
+ process.exit(0);
386
+ });
387
+ });
388
+
389
+ req.on('error', () => {
390
+ process.exit(0);
391
+ });
392
+
393
+ req.write(JSON.stringify(${JSON.stringify(payload.data)}));
394
+ req.end();
395
+ `
396
+ ];
397
+ import("child_process").then(({ spawn }) => {
398
+ spawn("node", args, {
399
+ stdio: "ignore",
400
+ detached: true,
401
+ shell: false
402
+ }).unref();
403
+ resolve();
404
+ }).catch(() => {
405
+ resolve();
406
+ });
407
+ logger_default.debug(chalk2.yellow("Process telemetry"), JSON.stringify(payload, null, 2));
408
+ } catch (error) {
409
+ logger_default.error("Error sending telemetry", error);
410
+ resolve();
411
+ }
412
+ });
413
+ }
414
+ };
415
+
416
+ // src/telemetry/Telemetry.ts
417
+ var TelemetryService = class {
418
+ telemetryMetadata;
419
+ transport;
420
+ isTelemetryDisabled = true;
421
+ batchProcessor = new BatchProcessor(100, 10, async (data) => {
422
+ await this.sendTelemetry(data);
423
+ });
424
+ setup(metadata, transport) {
425
+ this.telemetryMetadata = metadata;
426
+ this.isTelemetryDisabled = false;
427
+ const isBrowser = typeof window !== "undefined";
428
+ if (transport) {
429
+ this.transport = transport;
430
+ } else if (isBrowser) {
431
+ this.transport = new BrowserTelemetryTransport();
432
+ this.telemetryMetadata.transport = "browser";
433
+ } else {
434
+ this.transport = new ProcessTelemetryTransport();
435
+ this.telemetryMetadata.transport = "process";
436
+ }
437
+ this.sendTelemetry([
438
+ {
439
+ eventName: TELEMETRY_EVENTS.SDK_INITIALIZED,
440
+ data: {},
441
+ sdk_meta: this.telemetryMetadata
442
+ }
443
+ ]);
444
+ }
445
+ /**
446
+ * Instrument the telemetry for the given instance.
447
+ *
448
+ * You can pass the instance and the file name of the instance to instrument the telemetry.
449
+ * This will instrument all the methods of the instance and log the telemetry for each method call.
450
+ * @param instance - any instance that extends InstrumentedInstance
451
+ * @param fileName - the file name of the instance
452
+ * @returns
453
+ */
454
+ instrument(instance, fileName) {
455
+ const proto = Object.getPrototypeOf(instance);
456
+ const methodNames = Object.getOwnPropertyNames(proto).filter((key) => {
457
+ const descriptor = Object.getOwnPropertyDescriptor(proto, key);
458
+ return key !== "constructor" && descriptor && typeof descriptor.value === "function" && descriptor.value.constructor.name === "AsyncFunction";
459
+ });
460
+ const instrumentedClassName = instance.constructor?.name || fileName || "unknown";
461
+ for (const name of methodNames) {
462
+ const originalMethod = instance[name];
463
+ instance[name] = async (...args) => {
464
+ const telemetryPayload = {
465
+ eventName: TELEMETRY_EVENTS.SDK_METHOD_INVOKED,
466
+ data: {
467
+ fileName: instrumentedClassName,
468
+ method: name,
469
+ params: args
470
+ },
471
+ sdk_meta: this.telemetryMetadata
472
+ };
473
+ this.batchProcessor.pushItem(telemetryPayload);
474
+ try {
475
+ return await originalMethod.apply(instance, args);
476
+ } catch (error) {
477
+ const telemetryPayload2 = {
478
+ eventName: TELEMETRY_EVENTS.SDK_METHOD_ERROR,
479
+ data: {
480
+ fileName: instrumentedClassName,
481
+ method: name,
482
+ params: args,
483
+ error
484
+ },
485
+ sdk_meta: this.telemetryMetadata
486
+ };
487
+ this.batchProcessor.pushItem(telemetryPayload2);
488
+ throw error;
489
+ }
490
+ };
491
+ }
492
+ return instance;
493
+ }
494
+ /**
495
+ * Check if the telemetry should be sent.
496
+ * @returns true if the telemetry should be sent, false otherwise
497
+ */
498
+ shouldSendTelemetry() {
499
+ const devEnvironments = ["test", "development", "CI"];
500
+ const nodeEnv = (getEnvVariable("NODE_ENV", "development") || "").toLowerCase();
501
+ const isDevEnvironment = devEnvironments.includes(nodeEnv);
502
+ const isTelemetryDisabledByEnv = getEnvVariable("TELEMETRY_DISABLED", "false") === "true";
503
+ return this.transport && !this.isTelemetryDisabled && !isTelemetryDisabledByEnv && !isDevEnvironment;
504
+ }
505
+ /**
506
+ * Send the telemetry payload to the server.
507
+ * @param payload - the telemetry payload to send
508
+ * @returns
509
+ */
510
+ async sendTelemetry(payload) {
511
+ if (!this.shouldSendTelemetry()) {
512
+ return;
513
+ }
514
+ const url = `${TELEMETRY_URL}/api/sdk_metrics/telemetry`;
515
+ const reqPayload = {
516
+ data: payload,
517
+ url,
518
+ method: "POST",
519
+ headers: { "Content-Type": "application/json" }
520
+ };
521
+ this.transport.send(reqPayload);
522
+ }
523
+ async sendErrorTelemetry(error) {
524
+ if (!this.shouldSendTelemetry()) {
525
+ return;
526
+ }
527
+ const url = `${TELEMETRY_URL}/api/sdk_metrics/error`;
528
+ const reqPayload = {
529
+ data: { error },
530
+ url,
531
+ method: "POST",
532
+ headers: { "Content-Type": "application/json" }
533
+ };
534
+ this.transport.send(reqPayload);
535
+ }
536
+ };
537
+ var telemetry = new TelemetryService();
538
+
278
539
  // src/models/CustomTools.ts
279
540
  var CustomTools = class {
280
541
  client;
@@ -285,6 +546,7 @@ var CustomTools = class {
285
546
  }
286
547
  this.client = client;
287
548
  this.customToolsRegistry = /* @__PURE__ */ new Map();
549
+ telemetry.instrument(this);
288
550
  }
289
551
  /**
290
552
  * Create a custom tool and registers it in the registry.
@@ -379,8 +641,8 @@ var CustomTools = class {
379
641
  });
380
642
  }
381
643
  const connectedAccounts = await this.client.connectedAccounts.list({
382
- toolkit_slug: toolkitSlug,
383
- user_id: metadata.userId
644
+ toolkit_slugs: [toolkitSlug],
645
+ user_ids: [metadata.userId]
384
646
  });
385
647
  if (!connectedAccounts.items.length) {
386
648
  throw new ComposioConnectedAccountNotFoundError(
@@ -447,7 +709,7 @@ var ValidationErrorCodes = {
447
709
  };
448
710
  var ValidationError = class extends ComposioError {
449
711
  zodError;
450
- constructor(zodError, message = "Input validation failed") {
712
+ constructor(zodError, message = "Input validation failed", meta) {
451
713
  let zodErrorInstance;
452
714
  if (!(zodError instanceof ZodError)) {
453
715
  zodErrorInstance = new ZodError([
@@ -460,20 +722,16 @@ var ValidationError = class extends ComposioError {
460
722
  } else {
461
723
  zodErrorInstance = zodError;
462
724
  }
725
+ const issues = zodErrorInstance.issues.map(
726
+ (issue) => `[${issue.code}] ${issue.path.join(".")} - ${issue.message}`
727
+ );
463
728
  super(message, {
464
729
  code: ValidationErrorCodes.VALIDATION_ERROR,
465
- meta: {
466
- issues: JSON.stringify(
467
- zodErrorInstance.issues.map((issue) => ({
468
- path: issue.path.join("."),
469
- message: issue.message,
470
- code: issue.code
471
- }))
472
- )
473
- },
474
- cause: zodErrorInstance
730
+ meta,
731
+ cause: issues.join("\n")
475
732
  });
476
733
  this.zodError = zodErrorInstance;
734
+ this.name = "ValidationError";
477
735
  }
478
736
  };
479
737
 
@@ -493,13 +751,21 @@ var Tools = class {
493
751
  this.customTools = new CustomTools(client);
494
752
  this.provider = provider;
495
753
  this.execute = this.execute.bind(this);
754
+ this.provider._setExecuteToolFn(this.execute);
496
755
  this.getRawComposioToolBySlug = this.getRawComposioToolBySlug.bind(this);
497
756
  this.getRawComposioTools = this.getRawComposioTools.bind(this);
757
+ telemetry.instrument(this);
498
758
  }
499
759
  /**
500
- * Transform the tool cases
501
- * @param {ToolRetrieveResponse | ComposioToolListResponse['items'][0]} tool - The tool to transform
502
- * @returns {Tool} The transformed tool
760
+ * Transforms tool data from snake_case API format to camelCase for internal SDK use.
761
+ *
762
+ * This method standardizes the property naming convention for tools retrieved from the Composio API,
763
+ * making them more consistent with JavaScript/TypeScript conventions.
764
+ *
765
+ * @param {ToolRetrieveResponse | ComposioToolListResponse['items'][0]} tool - The tool object to transform
766
+ * @returns {Tool} The transformed tool with camelCase properties
767
+ *
768
+ * @private
503
769
  */
504
770
  transformToolCases(tool) {
505
771
  return ToolSchema.parse({
@@ -509,9 +775,15 @@ var Tools = class {
509
775
  });
510
776
  }
511
777
  /**
512
- * Transform the tool execute response to camelcase
513
- * @param {ComposioToolExecuteResponse} response - The response to transform
514
- * @returns {ToolExecuteResponse} The transformed response
778
+ * Transforms tool execution response from snake_case API format to camelCase.
779
+ *
780
+ * This method converts the response received from the Composio API to a standardized format
781
+ * with consistent property naming that follows JavaScript/TypeScript conventions.
782
+ *
783
+ * @param {ComposioToolExecuteResponse} response - The raw API response to transform
784
+ * @returns {ToolExecuteResponse} The transformed response with camelCase properties
785
+ *
786
+ * @private
515
787
  */
516
788
  transformToolExecuteResponse(response) {
517
789
  return ToolExecuteResponseSchema.parse({
@@ -596,9 +868,35 @@ var Tools = class {
596
868
  return null;
597
869
  }
598
870
  /**
599
- * Lists all tools available in the Composio SDK as well as custom tools.
600
- * This method fetches the tools from the Composio API and wraps them using the provider.
601
- * @returns {ToolList} List of tools
871
+ * Lists all tools available in the Composio SDK including custom tools.
872
+ *
873
+ * This method fetches tools from the Composio API in raw format and combines them with
874
+ * any registered custom tools. The response can be filtered and modified as needed.
875
+ *
876
+ * @param {string} userId - The user ID for whom to fetch the tools
877
+ * @param {ToolListParams} [query={}] - Optional query parameters to filter the tools
878
+ * @param {TransformToolSchemaModifier} [modifier] - Optional function to transform tool schemas
879
+ * @returns {Promise<ToolList>} List of tools matching the query criteria
880
+ *
881
+ * @example
882
+ * ```typescript
883
+ * // Get all tools
884
+ * const tools = await composio.tools.getRawComposioTools('default');
885
+ *
886
+ * // Get tools with filters
887
+ * const githubTools = await composio.tools.getRawComposioTools('default', {
888
+ * toolkits: ['github'],
889
+ * important: true
890
+ * });
891
+ *
892
+ * // Get tools with schema transformation
893
+ * const tools = await composio.tools.getRawComposioTools('default', {},
894
+ * (toolSlug, toolkitSlug, tool) => {
895
+ * // Add custom properties to tool schema
896
+ * return {...tool, customProperty: 'value'};
897
+ * }
898
+ * );
899
+ * ```
602
900
  */
603
901
  async getRawComposioTools(userId, query = {}, modifier) {
604
902
  const queryParams = ToolListParamsSchema.safeParse(query);
@@ -634,6 +932,7 @@ var Tools = class {
634
932
  }
635
933
  /**
636
934
  * Retrieves a tool by its Slug.
935
+ * This method is used to get the raw tools from the composio API.
637
936
  * @param slug The ID of the tool to be retrieved
638
937
  * @returns {Promise<Tool>} The tool
639
938
  *
@@ -664,19 +963,21 @@ var Tools = class {
664
963
  return modifiedToool;
665
964
  }
666
965
  /**
667
- * Get a tool by its slug
668
- * @param userId - The user id
669
- * @param arg2 - The slug of the tool or the filters for the tools
670
- * @param options - The options for the tools
671
- * @returns The tool or the tools
966
+ * Get a tool or list of tools based on the provided arguments.
967
+ * This is an implementation method that handles both overloads.
968
+ *
969
+ * @param {string} userId - The user id to get the tool(s) for
970
+ * @param {ToolListParams | string} arg2 - Either a slug string or filters object
971
+ * @param {ProviderOptions<TProvider>} [options] - Optional provider options
972
+ * @returns {Promise<TToolCollection>} The tool collection
672
973
  */
673
974
  async get(userId, arg2, options) {
674
975
  const executeToolFn = this.createExecuteToolFn(userId, options);
675
976
  if (typeof arg2 === "string") {
676
- const tool = await this.getRawComposioToolBySlug(userId, arg2, options?.modifyToolSchema);
677
- return this.provider.wrapTool(tool, executeToolFn);
977
+ const tool = await this.getRawComposioToolBySlug(userId, arg2, options?.modifySchema);
978
+ return this.provider.wrapTools([tool], executeToolFn);
678
979
  } else {
679
- const tools = await this.getRawComposioTools(userId, arg2, options?.modifyToolSchema);
980
+ const tools = await this.getRawComposioTools(userId, arg2, options?.modifySchema);
680
981
  return this.provider.wrapTools(tools, executeToolFn);
681
982
  }
682
983
  }
@@ -710,26 +1011,22 @@ var Tools = class {
710
1011
  * @returns The response from the tool execution
711
1012
  */
712
1013
  async handleCustomToolExecution(tool, body, modifiers) {
713
- if (modifiers?.beforeToolExecute) {
714
- if (typeof modifiers.beforeToolExecute === "function") {
715
- body = modifiers.beforeToolExecute(tool.slug, "unkown", body);
1014
+ if (modifiers?.beforeExecute) {
1015
+ if (typeof modifiers.beforeExecute === "function") {
1016
+ body = modifiers.beforeExecute(tool.slug, "unkown", body);
716
1017
  } else {
717
- throw new ComposioInvalidModifierError(
718
- "Invalid beforeToolExecute modifier. Not a function."
719
- );
1018
+ throw new ComposioInvalidModifierError("Invalid beforeExecute modifier. Not a function.");
720
1019
  }
721
1020
  }
722
1021
  let result = await this.customTools.executeCustomTool(tool.slug, body, {
723
1022
  userId: body.userId || "default",
724
1023
  connectedAccountId: body.connectedAccountId
725
1024
  });
726
- if (modifiers?.afterToolExecute) {
727
- if (typeof modifiers.afterToolExecute === "function") {
728
- result = modifiers.afterToolExecute(tool.slug, "unkown", result);
1025
+ if (modifiers?.afterExecute) {
1026
+ if (typeof modifiers.afterExecute === "function") {
1027
+ result = modifiers.afterExecute(tool.slug, "unkown", result);
729
1028
  } else {
730
- throw new ComposioInvalidModifierError(
731
- "Invalid afterToolExecute modifier. Not a function."
732
- );
1029
+ throw new ComposioInvalidModifierError("Invalid afterExecute modifier. Not a function.");
733
1030
  }
734
1031
  }
735
1032
  return result;
@@ -743,13 +1040,11 @@ var Tools = class {
743
1040
  * @returns The response from the tool execution
744
1041
  */
745
1042
  async handleComposioToolExecution(tool, body, modifiers) {
746
- if (modifiers?.beforeToolExecute) {
747
- if (typeof modifiers.beforeToolExecute === "function") {
748
- body = modifiers.beforeToolExecute(tool.slug, tool.toolkit?.slug || "unkown", body);
1043
+ if (modifiers?.beforeExecute) {
1044
+ if (typeof modifiers.beforeExecute === "function") {
1045
+ body = modifiers.beforeExecute(tool.slug, tool.toolkit?.slug || "unkown", body);
749
1046
  } else {
750
- throw new ComposioInvalidModifierError(
751
- "Invalid beforeToolExecute modifier. Not a function."
752
- );
1047
+ throw new ComposioInvalidModifierError("Invalid beforeExecute modifier. Not a function.");
753
1048
  }
754
1049
  }
755
1050
  let connectedAccountId = body.connectedAccountId;
@@ -766,25 +1061,53 @@ var Tools = class {
766
1061
  text: body.text
767
1062
  });
768
1063
  result = this.transformToolExecuteResponse(result);
769
- if (modifiers?.afterToolExecute) {
770
- if (typeof modifiers.afterToolExecute === "function") {
771
- result = modifiers.afterToolExecute(tool.slug, tool.toolkit?.slug || "unkown", result);
1064
+ if (modifiers?.afterExecute) {
1065
+ if (typeof modifiers.afterExecute === "function") {
1066
+ result = modifiers.afterExecute(tool.slug, tool.toolkit?.slug || "unkown", result);
772
1067
  } else {
773
- throw new ComposioInvalidModifierError(
774
- "Invalid afterToolExecute modifier. Not a function."
775
- );
1068
+ throw new ComposioInvalidModifierError("Invalid afterExecute modifier. Not a function.");
776
1069
  }
777
1070
  }
778
1071
  return result;
779
1072
  }
780
1073
  /**
781
- * Exectes a given tool with the provided parameters.
1074
+ * Executes a given tool with the provided parameters.
782
1075
  *
783
- * This method calls the Composio API to execute the tool and returns the response.
1076
+ * This method calls the Composio API or a custom tool handler to execute the tool and returns the response.
1077
+ * It automatically determines whether to use a custom tool or a Composio API tool based on the slug.
784
1078
  *
785
- * @param {string} slug - The ID of the tool to be executed
1079
+ * @param {string} slug - The slug/ID of the tool to be executed
786
1080
  * @param {ToolExecuteParams} body - The parameters to be passed to the tool
1081
+ * @param {ExecuteToolModifiers} [modifiers] - Optional modifiers to transform the request or response
787
1082
  * @returns {Promise<ToolExecuteResponse>} - The response from the tool execution
1083
+ *
1084
+ * @throws {ComposioCustomToolsNotInitializedError} If the CustomTools instance is not initialized
1085
+ * @throws {ComposioToolNotFoundError} If the tool with the given slug is not found
1086
+ * @throws {ComposioToolExecutionError} If there is an error during tool execution
1087
+ *
1088
+ * @example
1089
+ * ```typescript
1090
+ * // Execute a Composio API tool
1091
+ * const result = await composio.tools.execute('HACKERNEWS_GET_USER', {
1092
+ * userId: 'default',
1093
+ * arguments: { userId: 'pg' }
1094
+ * });
1095
+ *
1096
+ * // Execute with modifiers
1097
+ * const result = await composio.tools.execute('GITHUB_GET_ISSUES', {
1098
+ * userId: 'default',
1099
+ * arguments: { owner: 'composio', repo: 'sdk' }
1100
+ * }, {
1101
+ * beforeExecute: (toolSlug, toolkitSlug, params) => {
1102
+ * // Modify params before execution
1103
+ * return params;
1104
+ * },
1105
+ * afterExecute: (toolSlug, toolkitSlug, result) => {
1106
+ * // Transform result after execution
1107
+ * return result;
1108
+ * }
1109
+ * });
1110
+ * ```
788
1111
  */
789
1112
  async execute(slug, body, modifiers) {
790
1113
  if (!this.customTools) {
@@ -841,9 +1164,39 @@ var Tools = class {
841
1164
  return this.client.tools.proxy(body);
842
1165
  }
843
1166
  /**
844
- * Execute a custom tool
845
- * @param body
846
- * @returns
1167
+ * Creates a custom tool that can be used within the Composio SDK.
1168
+ *
1169
+ * Custom tools allow you to extend the functionality of Composio with your own implementations
1170
+ * while keeping a consistent interface for both built-in and custom tools.
1171
+ *
1172
+ * @param {CustomToolOptions} body - The configuration for the custom tool
1173
+ * @returns {Promise<Tool>} The created custom tool
1174
+ *
1175
+ * @example
1176
+ * ```typescript
1177
+ * const customTool = await composio.tools.createCustomTool({
1178
+ * name: 'My Custom Tool',
1179
+ * description: 'A custom tool that does something specific',
1180
+ * slug: 'MY_CUSTOM_TOOL',
1181
+ * inputParameters: {
1182
+ * param1: {
1183
+ * type: 'string',
1184
+ * description: 'First parameter',
1185
+ * required: true
1186
+ * }
1187
+ * },
1188
+ * outputParameters: {
1189
+ * result: {
1190
+ * type: 'string',
1191
+ * description: 'The result of the operation'
1192
+ * }
1193
+ * },
1194
+ * handler: async (params, context) => {
1195
+ * // Custom logic here
1196
+ * return { data: { result: 'Success!' } };
1197
+ * }
1198
+ * });
1199
+ * ```
847
1200
  */
848
1201
  async createCustomTool(body) {
849
1202
  return this.customTools.createTool(body);
@@ -1001,7 +1354,7 @@ var AuthConfigRetrieveResponseSchema = z3.object({
1001
1354
  status: z3.enum(["ENABLED", "DISABLED"]),
1002
1355
  uuid: z3.string(),
1003
1356
  authScheme: AuthSchemeEnum.optional(),
1004
- credentials: z3.record(z3.string(), z3.union([z3.string(), z3.number(), z3.boolean()])),
1357
+ credentials: z3.record(z3.string(), z3.unknown()).optional(),
1005
1358
  expectedInputFields: z3.array(z3.unknown()).optional(),
1006
1359
  isComposioManaged: z3.boolean().optional(),
1007
1360
  createdBy: z3.string().optional(),
@@ -1039,6 +1392,7 @@ var AuthConfigs = class {
1039
1392
  client;
1040
1393
  constructor(client) {
1041
1394
  this.client = client;
1395
+ telemetry.instrument(this);
1042
1396
  }
1043
1397
  /**
1044
1398
  * Protected getter for the client instance.
@@ -1048,6 +1402,18 @@ var AuthConfigs = class {
1048
1402
  getClient() {
1049
1403
  return this.client;
1050
1404
  }
1405
+ /**
1406
+ * Transforms an auth config response from API format to SDK format.
1407
+ *
1408
+ * This method converts property names from snake_case to camelCase and reorganizes
1409
+ * the data structure to match the SDK's standardized format for auth configurations.
1410
+ *
1411
+ * @param {ComposioAuthConfigRetrieveResponse} authConfig - The raw API response to transform
1412
+ * @returns {AuthConfigRetrieveResponse} The transformed auth config data
1413
+ * @throws {ValidationError} If the response fails validation against the expected schema
1414
+ *
1415
+ * @private
1416
+ */
1051
1417
  parseAuthConfigRetrieveResponse(authConfig) {
1052
1418
  const result = AuthConfigRetrieveResponseSchema.safeParse({
1053
1419
  id: authConfig.id,
@@ -1073,10 +1439,30 @@ var AuthConfigs = class {
1073
1439
  return result.data;
1074
1440
  }
1075
1441
  /**
1076
- * List all auth configs
1077
- * @param {AuthConfigListParams} query - Query parameters for filtering auth configs
1078
- * @param {RequestOptions} options - Request options
1079
- * @returns {Promise<AuthConfigListResponse>} List of auth configs
1442
+ * Lists authentication configurations based on provided filter criteria.
1443
+ *
1444
+ * This method retrieves auth configs from the Composio API, transforms them to the SDK format,
1445
+ * and supports filtering by various parameters.
1446
+ *
1447
+ * @param {AuthConfigListParams} [query] - Optional query parameters for filtering auth configs
1448
+ * @returns {Promise<AuthConfigListResponse>} A paginated list of auth configurations
1449
+ * @throws {ValidationError} If the query parameters or response fail validation
1450
+ *
1451
+ * @example
1452
+ * ```typescript
1453
+ * // List all auth configs
1454
+ * const allConfigs = await composio.authConfigs.list();
1455
+ *
1456
+ * // List auth configs for a specific toolkit
1457
+ * const githubConfigs = await composio.authConfigs.list({
1458
+ * toolkitSlug: 'github'
1459
+ * });
1460
+ *
1461
+ * // List Composio-managed auth configs
1462
+ * const managedConfigs = await composio.authConfigs.list({
1463
+ * isComposioManaged: true
1464
+ * });
1465
+ * ```
1080
1466
  */
1081
1467
  async list(query) {
1082
1468
  const parsedQuery = query ? AuthConfigListParamsSchema.parse(query) : void 0;
@@ -1114,7 +1500,7 @@ var AuthConfigs = class {
1114
1500
  *
1115
1501
  * @link https://docs.composio.dev/reference/auth-configs/create-auth-config
1116
1502
  */
1117
- async create(toolkit, options) {
1503
+ async create(toolkit, options = { type: "use_composio_managed_auth" }) {
1118
1504
  const parsedOptions = CreateAuthConfigParamsSchema.safeParse(options);
1119
1505
  if (parsedOptions.error) {
1120
1506
  throw new ValidationError(parsedOptions.error);
@@ -1137,21 +1523,57 @@ var AuthConfigs = class {
1137
1523
  return parsedResult.data;
1138
1524
  }
1139
1525
  /**
1140
- * Get an auth config by nanoid
1141
- * @param {string} nanoid - Unique identifier of the auth config
1142
- * @param {RequestOptions} options - Request options
1143
- * @returns {Promise<AuthConfigRetrieveResponse>} Auth config details
1526
+ * Retrieves a specific authentication configuration by its ID.
1527
+ *
1528
+ * This method fetches detailed information about a single auth config
1529
+ * and transforms the response to the SDK's standardized format.
1530
+ *
1531
+ * @param {string} nanoid - The unique identifier of the auth config to retrieve
1532
+ * @returns {Promise<AuthConfigRetrieveResponse>} The auth config details
1533
+ * @throws {Error} If the auth config cannot be found or an API error occurs
1534
+ * @throws {ValidationError} If the response fails validation
1535
+ *
1536
+ * @example
1537
+ * ```typescript
1538
+ * // Get an auth config by ID
1539
+ * const authConfig = await composio.authConfigs.get('auth_abc123');
1540
+ * console.log(authConfig.name); // e.g., 'GitHub Auth'
1541
+ * console.log(authConfig.toolkit.slug); // e.g., 'github'
1542
+ * ```
1144
1543
  */
1145
1544
  async get(nanoid) {
1146
1545
  const result = await this.client.authConfigs.retrieve(nanoid);
1147
1546
  return this.parseAuthConfigRetrieveResponse(result);
1148
1547
  }
1149
1548
  /**
1150
- * Update an auth config
1151
- * @param {string} nanoid - Unique identifier of the auth config to update
1152
- * @param {AuthConfigUpdateParams} data - Data to update
1153
- * @param {RequestOptions} options - Request options
1154
- * @returns {Promise<AuthConfigUpdateResponse>} Updated auth config
1549
+ * Updates an existing authentication configuration.
1550
+ *
1551
+ * This method allows you to modify properties of an auth config such as credentials,
1552
+ * scopes, or tool restrictions. The update type (custom or default) determines which
1553
+ * fields can be updated.
1554
+ *
1555
+ * @param {string} nanoid - The unique identifier of the auth config to update
1556
+ * @param {AuthConfigUpdateParams} data - The data to update, which can be either custom or default type
1557
+ * @returns {Promise<AuthConfigUpdateResponse>} The updated auth config
1558
+ * @throws {ValidationError} If the update parameters are invalid
1559
+ * @throws {Error} If the auth config cannot be found or updated
1560
+ *
1561
+ * @example
1562
+ * ```typescript
1563
+ * // Update a custom auth config with new credentials
1564
+ * const updatedConfig = await composio.authConfigs.update('auth_abc123', {
1565
+ * type: 'custom',
1566
+ * credentials: {
1567
+ * apiKey: 'new-api-key-value'
1568
+ * }
1569
+ * });
1570
+ *
1571
+ * // Update a default auth config with new scopes
1572
+ * const updatedConfig = await composio.authConfigs.update('auth_abc123', {
1573
+ * type: 'default',
1574
+ * scopes: ['read:user', 'repo']
1575
+ * });
1576
+ * ```
1155
1577
  */
1156
1578
  async update(nanoid, data) {
1157
1579
  const parsedData = AuthConfigUpdateParamsSchema.safeParse(data);
@@ -1172,38 +1594,85 @@ var AuthConfigs = class {
1172
1594
  );
1173
1595
  }
1174
1596
  /**
1175
- * Delete an auth config
1176
- * @param {string} nanoid - Unique identifier of the auth config to delete
1177
- * @param {RequestOptions} options - Request options
1178
- * @returns {Promise<AuthConfigDeleteResponse>} Response from deletion
1597
+ * Deletes an authentication configuration.
1598
+ *
1599
+ * This method permanently removes an auth config from the Composio platform.
1600
+ * This action cannot be undone and will prevent any connected accounts that use
1601
+ * this auth config from functioning.
1602
+ *
1603
+ * @param {string} nanoid - The unique identifier of the auth config to delete
1604
+ * @returns {Promise<AuthConfigDeleteResponse>} The deletion response
1605
+ * @throws {Error} If the auth config doesn't exist or cannot be deleted
1606
+ *
1607
+ * @example
1608
+ * ```typescript
1609
+ * // Delete an auth config
1610
+ * await composio.authConfigs.delete('auth_abc123');
1611
+ * ```
1179
1612
  */
1180
1613
  async delete(nanoid) {
1181
1614
  return this.client.authConfigs.delete(nanoid);
1182
1615
  }
1183
1616
  /**
1184
- * Update the status of an auth config
1185
- * @param {string} status - The status to update the auth config to
1186
- * @param {string} nanoid - Unique identifier of the auth config
1187
- * @param {RequestOptions} options - Request options
1188
- * @returns {Promise<AuthConfigUpdateStatusResponse>} Updated auth config details
1617
+ * Updates the status of an authentication configuration.
1618
+ *
1619
+ * This method allows you to enable or disable an auth config. When disabled,
1620
+ * the auth config cannot be used to create new connected accounts or authenticate
1621
+ * with third-party services.
1622
+ *
1623
+ * @param {string} status - The status to set ('ENABLED' or 'DISABLED')
1624
+ * @param {string} nanoid - The unique identifier of the auth config
1625
+ * @returns {Promise<AuthConfigUpdateStatusResponse>} The updated auth config details
1626
+ * @throws {Error} If the auth config cannot be found or the status cannot be updated
1627
+ *
1628
+ * @example
1629
+ * ```typescript
1630
+ * // Disable an auth config
1631
+ * await composio.authConfigs.updateStatus('DISABLED', 'auth_abc123');
1632
+ *
1633
+ * // Enable an auth config
1634
+ * await composio.authConfigs.updateStatus('ENABLED', 'auth_abc123');
1635
+ * ```
1189
1636
  */
1190
1637
  async updateStatus(status, nanoid) {
1191
1638
  return this.client.authConfigs.updateStatus(status, { nanoid });
1192
1639
  }
1193
1640
  /**
1194
- * Enable an auth config
1195
- * @param {string} nanoid - Unique identifier of the auth config
1196
- * @param {RequestOptions} options - Request options
1197
- * @returns {Promise<AuthConfigUpdateStatusResponse>} Updated auth config details
1641
+ * Enables an authentication configuration.
1642
+ *
1643
+ * This is a convenience method that calls updateStatus with 'ENABLED'.
1644
+ * When enabled, the auth config can be used to create new connected accounts
1645
+ * and authenticate with third-party services.
1646
+ *
1647
+ * @param {string} nanoid - The unique identifier of the auth config to enable
1648
+ * @returns {Promise<AuthConfigUpdateStatusResponse>} The updated auth config details
1649
+ * @throws {Error} If the auth config cannot be found or enabled
1650
+ *
1651
+ * @example
1652
+ * ```typescript
1653
+ * // Enable an auth config
1654
+ * await composio.authConfigs.enable('auth_abc123');
1655
+ * ```
1198
1656
  */
1199
1657
  async enable(nanoid) {
1200
1658
  return this.client.authConfigs.updateStatus("ENABLED", { nanoid });
1201
1659
  }
1202
1660
  /**
1203
- * Disable an auth config
1204
- * @param {string} nanoid - Unique identifier of the auth config
1205
- * @param {RequestOptions} options - Request options
1206
- * @returns {Promise<AuthConfigUpdateStatusResponse>} Updated auth config details
1661
+ * Disables an authentication configuration.
1662
+ *
1663
+ * This is a convenience method that calls updateStatus with 'DISABLED'.
1664
+ * When disabled, the auth config cannot be used to create new connected accounts
1665
+ * or authenticate with third-party services, but existing connections may continue to work.
1666
+ *
1667
+ * @param {string} nanoid - The unique identifier of the auth config to disable
1668
+ * @returns {Promise<AuthConfigUpdateStatusResponse>} The updated auth config details
1669
+ * @throws {Error} If the auth config cannot be found or disabled
1670
+ *
1671
+ * @example
1672
+ * ```typescript
1673
+ * // Disable an auth config
1674
+ * await composio.authConfigs.disable('auth_abc123');
1675
+ * ```
1207
1676
  */
1208
1677
  async disable(nanoid) {
1209
1678
  return this.client.authConfigs.updateStatus("DISABLED", { nanoid });
@@ -1253,7 +1722,7 @@ var CreateConnectedAccountParamsSchema = z4.object({
1253
1722
  }),
1254
1723
  connection: z4.object({
1255
1724
  data: z4.record(z4.string(), z4.unknown()).optional(),
1256
- redirectUrl: z4.string().optional(),
1725
+ callbackUrl: z4.string().optional(),
1257
1726
  userId: z4.string().optional()
1258
1727
  })
1259
1728
  });
@@ -1263,12 +1732,12 @@ var DefaultCreateConnectedAccountParamsSchema = z4.object({
1263
1732
  }),
1264
1733
  connection: z4.object({
1265
1734
  data: z4.record(z4.string(), z4.unknown()).optional(),
1266
- redirect_uri: z4.string().optional(),
1735
+ callback_url: z4.string().optional(),
1267
1736
  user_id: z4.string().optional()
1268
1737
  })
1269
1738
  });
1270
1739
  var CreateConnectedAccountOptionsSchema = z4.object({
1271
- redirectUrl: z4.string().optional(),
1740
+ callbackUrl: z4.string().optional(),
1272
1741
  data: z4.record(z4.string(), z4.unknown()).optional()
1273
1742
  });
1274
1743
  var CreateConnectedAccountResponseSchema = z4.object({
@@ -1317,7 +1786,7 @@ var ConnectedAccountRetrieveResponseSchema = z4.object({
1317
1786
  authConfig: ConnectedAccountAuthConfigSchema,
1318
1787
  userId: z4.string(),
1319
1788
  data: z4.record(z4.string(), z4.unknown()),
1320
- params: z4.record(z4.string(), z4.unknown()),
1789
+ params: z4.record(z4.string(), z4.unknown()).optional(),
1321
1790
  status: ConnectedAccountStatusSchema,
1322
1791
  statusReason: z4.string().nullable(),
1323
1792
  toolkit: z4.object({
@@ -1328,8 +1797,24 @@ var ConnectedAccountRetrieveResponseSchema = z4.object({
1328
1797
  createdAt: z4.string(),
1329
1798
  updatedAt: z4.string()
1330
1799
  });
1800
+ var ConnectedAccountListParamsSchema = z4.object({
1801
+ authConfigIds: z4.array(z4.string()).nullable().optional().describe("The auth config ids of the connected accounts"),
1802
+ cursor: z4.number().nullable().optional().describe("The cursor to paginate through the connected accounts"),
1803
+ labels: z4.array(z4.string()).nullable().optional().describe("The labels of the connected accounts"),
1804
+ limit: z4.number().nullable().optional().describe("The limit of the connected accounts to return"),
1805
+ orderBy: z4.enum(["created_at", "updated_at"]).optional().describe("The order by of the connected accounts"),
1806
+ statuses: z4.array(ConnectedAccountStatusSchema).nullable().optional().describe("The statuses of the connected accounts"),
1807
+ toolkitSlugs: z4.array(z4.string()).nullable().optional().describe("The toolkit slugs of the connected accounts"),
1808
+ userIds: z4.array(z4.string()).nullable().optional().describe("The user ids of the connected accounts")
1809
+ });
1810
+ var ConnectedAccountListResponseSchema = z4.object({
1811
+ items: z4.array(ConnectedAccountRetrieveResponseSchema).describe("The list of connected accounts"),
1812
+ nextCursor: z4.string().nullable().describe("The next cursor to paginate through the connected accounts"),
1813
+ totalPages: z4.number().describe("The total number of pages of connected accounts")
1814
+ });
1331
1815
 
1332
1816
  // src/models/ConnectionRequest.ts
1817
+ import ComposioClient from "@composio/client";
1333
1818
  import { ZodError as ZodError2 } from "zod";
1334
1819
 
1335
1820
  // src/errors/ConnectionRequestError.ts
@@ -1359,19 +1844,27 @@ var ConnectionRequestFailedError = class extends ComposioError {
1359
1844
  // src/models/ConnectionRequest.ts
1360
1845
  var ConnectionRequest = class {
1361
1846
  client;
1362
- connectedAccountId;
1363
- connectedAccountStatus;
1847
+ id;
1848
+ status;
1364
1849
  redirectUrl;
1365
- constructor(client, connectedAccountId, connectedAccountStatus, redirectUrl) {
1850
+ constructor(client, connectedAccountId, status, redirectUrl) {
1366
1851
  this.client = client;
1367
- this.connectedAccountId = connectedAccountId;
1368
- this.connectedAccountStatus = connectedAccountStatus;
1852
+ this.id = connectedAccountId;
1853
+ this.status = status || ConnectedAccountStatuses.INITIATED;
1369
1854
  this.redirectUrl = redirectUrl;
1855
+ telemetry.instrument(this);
1370
1856
  }
1371
1857
  /**
1372
- * Transform the response from the Composio API to the SDK format
1373
- * @param response
1374
- * @returns
1858
+ * Transforms the raw connected account response from the Composio API to the SDK format.
1859
+ *
1860
+ * This method converts property names from snake_case to camelCase and reorganizes
1861
+ * the data structure to match the SDK's standardized format.
1862
+ *
1863
+ * @param {OriginalConnectedAccountResponse} response - The raw API response to transform
1864
+ * @returns {Promise<ConnectedAccountRetrieveResponse>} The transformed response
1865
+ * @throws {ZodError} If the response fails validation against the expected schema
1866
+ *
1867
+ * @private
1375
1868
  */
1376
1869
  async transformResponse(response) {
1377
1870
  try {
@@ -1401,15 +1894,49 @@ var ConnectionRequest = class {
1401
1894
  }
1402
1895
  }
1403
1896
  /**
1404
- * Wait for the connection to be established.
1405
- * The function will poll the Composio API every second until the connection is established or the timeout is reached.
1406
- * @param {number} timeout - The time in milliseconds to wait for the connection to be established. Default is 30 seconds.
1407
- * @returns
1897
+ * Waits for the connection request to complete and become active.
1898
+ *
1899
+ * This method continuously polls the Composio API to check the status of the connection request
1900
+ * until it either becomes active, enters a terminal error state, or times out.
1901
+ *
1902
+ * @param {number} [timeout=60000] - Maximum time to wait in milliseconds before timing out (default: 60 seconds)
1903
+ * @returns {Promise<ConnectedAccountRetrieveResponse>} The final connected account response when successful
1904
+ * @throws {ComposioConnectedAccountNotFoundError} If the connected account cannot be found
1905
+ * @throws {ConnectionRequestFailedError} If the connection enters a failed, expired, or deleted state
1906
+ * @throws {ConnectionRequestTimeoutError} If the connection request does not complete within the timeout period
1907
+ *
1908
+ * @example
1909
+ * ```typescript
1910
+ * // Wait for connection with default timeout (60 seconds)
1911
+ * try {
1912
+ * const connection = await connectionRequest.waitForConnection();
1913
+ * console.log('Connection established:', connection.id);
1914
+ * } catch (error) {
1915
+ * console.error('Connection failed:', error.message);
1916
+ * }
1917
+ *
1918
+ * // Wait for connection with custom timeout (2 minutes)
1919
+ * const connection = await connectionRequest.waitForConnection(120000);
1920
+ * ```
1408
1921
  */
1409
1922
  async waitForConnection(timeout = 6e4) {
1410
- if (this.connectedAccountStatus === ConnectedAccountStatuses.ACTIVE) {
1411
- const response = await this.client.connectedAccounts.retrieve(this.connectedAccountId);
1412
- return this.transformResponse(response);
1923
+ try {
1924
+ const response = await this.client.connectedAccounts.retrieve(this.id);
1925
+ if (response.status === ConnectedAccountStatuses.ACTIVE) {
1926
+ this.status = ConnectedAccountStatuses.ACTIVE;
1927
+ return this.transformResponse(response);
1928
+ }
1929
+ } catch (error) {
1930
+ if (error instanceof ComposioClient.NotFoundError) {
1931
+ throw new ComposioConnectedAccountNotFoundError(
1932
+ `Connected account with id ${this.id} not found`,
1933
+ {
1934
+ connectedAccountId: this.id
1935
+ }
1936
+ );
1937
+ } else {
1938
+ throw error;
1939
+ }
1413
1940
  }
1414
1941
  const terminalErrorStates = [
1415
1942
  ConnectedAccountStatuses.FAILED,
@@ -1420,7 +1947,8 @@ var ConnectionRequest = class {
1420
1947
  const pollInterval = 1e3;
1421
1948
  while (Date.now() - start < timeout) {
1422
1949
  try {
1423
- const response = await this.client.connectedAccounts.retrieve(this.connectedAccountId);
1950
+ const response = await this.client.connectedAccounts.retrieve(this.id);
1951
+ this.status = response.status;
1424
1952
  if (response.status === ConnectedAccountStatuses.ACTIVE) {
1425
1953
  return this.transformResponse(response);
1426
1954
  }
@@ -1429,7 +1957,7 @@ var ConnectionRequest = class {
1429
1957
  `Connection request failed with status: ${response.status}${response.status_reason ? `, reason: ${response.status_reason}` : ""}`,
1430
1958
  {
1431
1959
  userId: response.user_id,
1432
- connectedAccountId: this.connectedAccountId,
1960
+ connectedAccountId: this.id,
1433
1961
  status: response.status,
1434
1962
  statusReason: response.status_reason
1435
1963
  }
@@ -1440,9 +1968,7 @@ var ConnectionRequest = class {
1440
1968
  throw error;
1441
1969
  }
1442
1970
  }
1443
- throw new ConnectionRequestTimeoutError(
1444
- `Connection request timed out for ${this.connectedAccountId}`
1445
- );
1971
+ throw new ConnectionRequestTimeoutError(`Connection request timed out for ${this.id}`);
1446
1972
  }
1447
1973
  };
1448
1974
 
@@ -1451,15 +1977,97 @@ var ConnectedAccounts = class {
1451
1977
  client;
1452
1978
  constructor(client) {
1453
1979
  this.client = client;
1980
+ telemetry.instrument(this);
1981
+ }
1982
+ transformConnectedAccountRetrieveResponse(response) {
1983
+ const result = ConnectedAccountRetrieveResponseSchema.safeParse({
1984
+ ...response,
1985
+ userId: response.user_id,
1986
+ // Add the missing userId property
1987
+ authConfig: {
1988
+ ...response.auth_config,
1989
+ authScheme: response.auth_config.auth_scheme,
1990
+ isComposioManaged: response.auth_config.is_composio_managed,
1991
+ isDisabled: response.auth_config.is_disabled
1992
+ },
1993
+ statusReason: response.status_reason,
1994
+ isDisabled: response.is_disabled,
1995
+ createdAt: response.created_at,
1996
+ updatedAt: response.updated_at,
1997
+ testRequestEndpoint: response.test_request_endpoint
1998
+ });
1999
+ if (!result.success) {
2000
+ throw new ValidationError(result.error);
2001
+ }
2002
+ return result.data;
1454
2003
  }
1455
2004
  /**
1456
- * List all connected accounts
1457
- * @param {ConnectedAccountListParams} query - Query parameters for filtering connected accounts
1458
- * @param {RequestOptions} options - Request options
1459
- * @returns {Promise<ConnectedAccountListResponse>} List of connected accounts
2005
+ * Lists all connected accounts based on provided filter criteria.
2006
+ *
2007
+ * This method retrieves connected accounts from the Composio API with optional filtering.
2008
+ *
2009
+ * @param {ConnectedAccountListParams} [query] - Optional query parameters for filtering connected accounts
2010
+ * @returns {Promise<ConnectedAccountListResponse>} A paginated list of connected accounts
2011
+ * @throws {ValidationError} If the query fails validation against the expected schema
2012
+ * @example
2013
+ * ```typescript
2014
+ * // List all connected accounts
2015
+ * const allAccounts = await composio.connectedAccounts.list();
2016
+ *
2017
+ * // List accounts for a specific user
2018
+ * const userAccounts = await composio.connectedAccounts.list({
2019
+ * userIds: ['user123']
2020
+ * });
2021
+ *
2022
+ * // List accounts for a specific toolkit
2023
+ * const githubAccounts = await composio.connectedAccounts.list({
2024
+ * toolkitSlugs: ['github']
2025
+ * });
2026
+ * ```
1460
2027
  */
1461
2028
  async list(query) {
1462
- return this.client.connectedAccounts.list(query);
2029
+ let rawQuery = void 0;
2030
+ if (query) {
2031
+ const parsedQuery = ConnectedAccountListParamsSchema.safeParse(query);
2032
+ if (!parsedQuery.success) {
2033
+ throw new ValidationError(parsedQuery.error);
2034
+ }
2035
+ rawQuery = {
2036
+ auth_config_ids: parsedQuery.data.authConfigIds,
2037
+ cursor: parsedQuery.data.cursor,
2038
+ labels: parsedQuery.data.labels,
2039
+ limit: parsedQuery.data.limit,
2040
+ order_by: parsedQuery.data.orderBy,
2041
+ statuses: parsedQuery.data.statuses,
2042
+ toolkit_slugs: parsedQuery.data.toolkitSlugs,
2043
+ user_ids: parsedQuery.data.userIds
2044
+ };
2045
+ }
2046
+ const result = await this.client.connectedAccounts.list(rawQuery);
2047
+ const parsedResponse = ConnectedAccountListResponseSchema.safeParse({
2048
+ items: result.items.map(this.transformConnectedAccountRetrieveResponse),
2049
+ nextCursor: result.next_cursor,
2050
+ totalPages: result.total_pages
2051
+ });
2052
+ if (!parsedResponse.success) {
2053
+ throw new ValidationError(parsedResponse.error);
2054
+ }
2055
+ return parsedResponse.data;
2056
+ }
2057
+ /**
2058
+ * Transforms connected account data from API format to SDK format.
2059
+ *
2060
+ * This method converts property names from snake_case to camelCase and reorganizes
2061
+ * the data structure to match the SDK's standardized format for connected accounts.
2062
+ *
2063
+ * @param {ConnectedAccountRetrieveResponseRaw} response - The raw API response to transform
2064
+ * @returns {ConnectedAccountRetrieveResponse} The transformed connected account data
2065
+ * @throws {ValidationError} If the response fails validation against the expected schema
2066
+ *
2067
+ * @private
2068
+ */
2069
+ transformConnectedAccountResponse(response) {
2070
+ return this.transformConnectedAccountRetrieveResponse(response);
1463
2071
  }
1464
2072
  /**
1465
2073
  * Compound function to create a new connected account.
@@ -1486,35 +2094,94 @@ var ConnectedAccounts = class {
1486
2094
  },
1487
2095
  connection: {
1488
2096
  data: options?.data,
1489
- redirect_uri: options?.redirectUrl,
2097
+ callback_url: options?.callbackUrl,
1490
2098
  user_id: userId
1491
2099
  }
1492
2100
  });
1493
- return new ConnectionRequest(this.client, response.id, response.status, response.redirect_uri);
2101
+ return new ConnectionRequest(this.client, response.id, response.status, response.redirect_url);
1494
2102
  }
1495
2103
  /**
1496
- * Get a connected account by nanoid
1497
- * @param {string} nanoid - Unique identifier of the connected account
1498
- * @param {RequestOptions} options - Request options
1499
- * @returns {Promise<ConnectedAccountRetrieveResponse>} Connected account details
2104
+ * Waits for a connection request to complete and become active.
2105
+ *
2106
+ * This method continuously polls the Composio API to check the status of a connection
2107
+ * until it either becomes active, enters a terminal error state, or times out.
2108
+ *
2109
+ * @param {string} connectedAccountId - The ID of the connected account to wait for
2110
+ * @param {number} [timeout=60000] - Maximum time to wait in milliseconds (default: 60 seconds)
2111
+ * @returns {Promise<ConnectedAccountRetrieveResponse>} The finalized connected account data
2112
+ * @throws {ComposioConnectedAccountNotFoundError} If the connected account cannot be found
2113
+ * @throws {ConnectionRequestFailedError} If the connection enters a failed, expired, or deleted state
2114
+ * @throws {ConnectionRequestTimeoutError} If the connection does not complete within the timeout period
2115
+ *
2116
+ * @example
2117
+ * ```typescript
2118
+ * // Wait for a connection to complete with default timeout
2119
+ * const connectedAccount = await composio.connectedAccounts.waitForConnection('conn_123abc');
2120
+ *
2121
+ * // Wait with a custom timeout of 2 minutes
2122
+ * const connectedAccount = await composio.connectedAccounts.waitForConnection('conn_123abc', 120000);
2123
+ * ```
2124
+ */
2125
+ async waitForConnection(connectedAccountId, timeout = 6e4) {
2126
+ const connectionRequest = new ConnectionRequest(this.client, connectedAccountId);
2127
+ return connectionRequest.waitForConnection(timeout);
2128
+ }
2129
+ /**
2130
+ * Retrieves a specific connected account by its ID.
2131
+ *
2132
+ * This method fetches detailed information about a single connected account
2133
+ * and transforms the response to the SDK's standardized format.
2134
+ *
2135
+ * @param {string} nanoid - The unique identifier of the connected account
2136
+ * @returns {Promise<ConnectedAccountRetrieveResponse>} The connected account details
2137
+ * @throws {Error} If the connected account cannot be found or an API error occurs
2138
+ *
2139
+ * @example
2140
+ * ```typescript
2141
+ * // Get a connected account by ID
2142
+ * const account = await composio.connectedAccounts.get('conn_abc123');
2143
+ * console.log(account.status); // e.g., 'ACTIVE'
2144
+ * console.log(account.toolkit.slug); // e.g., 'github'
2145
+ * ```
1500
2146
  */
1501
2147
  async get(nanoid) {
1502
- return this.client.connectedAccounts.retrieve(nanoid);
2148
+ const response = await this.client.connectedAccounts.retrieve(nanoid);
2149
+ return this.transformConnectedAccountResponse(response);
1503
2150
  }
1504
2151
  /**
1505
- * Delete a connected account
1506
- * @param {string} nanoid - Unique identifier of the connected account to delete
1507
- * @param {RequestOptions} options - Request options
1508
- * @returns {Promise<ConnectedAccountDeleteResponse>} Response from deletion
2152
+ * Deletes a connected account.
2153
+ *
2154
+ * This method permanently removes a connected account from the Composio platform.
2155
+ * This action cannot be undone and will revoke any access tokens associated with the account.
2156
+ *
2157
+ * @param {string} nanoid - The unique identifier of the connected account to delete
2158
+ * @returns {Promise<ConnectedAccountDeleteResponse>} The deletion response
2159
+ * @throws {Error} If the account doesn't exist or cannot be deleted
2160
+ *
2161
+ * @example
2162
+ * ```typescript
2163
+ * // Delete a connected account
2164
+ * await composio.connectedAccounts.delete('conn_abc123');
2165
+ * ```
1509
2166
  */
1510
2167
  async delete(nanoid) {
1511
2168
  return this.client.connectedAccounts.delete(nanoid);
1512
2169
  }
1513
2170
  /**
1514
- * Refresh a connected account's credentials
1515
- * @param {string} nanoid - Unique identifier of the connected account to refresh
1516
- * @param {RequestOptions} options - Request options
1517
- * @returns {Promise<ConnectedAccountRefreshResponse>} Refreshed connected account details
2171
+ * Refreshes a connected account's authentication credentials.
2172
+ *
2173
+ * This method attempts to refresh OAuth tokens or other credentials associated with
2174
+ * the connected account. This is useful when a token has expired or is about to expire.
2175
+ *
2176
+ * @param {string} nanoid - The unique identifier of the connected account to refresh
2177
+ * @returns {Promise<ConnectedAccountRefreshResponse>} The response containing the refreshed account details
2178
+ * @throws {Error} If the account doesn't exist or credentials cannot be refreshed
2179
+ *
2180
+ * @example
2181
+ * ```typescript
2182
+ * // Refresh a connected account's credentials
2183
+ * const refreshedAccount = await composio.connectedAccounts.refresh('conn_abc123');
2184
+ * ```
1518
2185
  */
1519
2186
  async refresh(nanoid) {
1520
2187
  return this.client.connectedAccounts.refresh(nanoid);
@@ -1555,11 +2222,18 @@ var Toolkits = class {
1555
2222
  constructor(client) {
1556
2223
  this.client = client;
1557
2224
  this.authorize = this.authorize.bind(this);
2225
+ telemetry.instrument(this);
1558
2226
  }
1559
2227
  /**
1560
- * List all toolkits available in the Composio SDK.
1561
- * This method fetches the toolkits from the Composio API.
1562
- * @returns {Promise<Toolkit[]>} List of toolkits
2228
+ * Retrieves a list of toolkits based on the provided query parameters.
2229
+ *
2230
+ * This method fetches toolkits from the Composio API and transforms the response
2231
+ * from snake_case to camelCase format for consistency with JavaScript/TypeScript conventions.
2232
+ *
2233
+ * @param {ToolkitListParams} query - The query parameters to filter toolkits
2234
+ * @returns {Promise<ToolKitListResponse>} The transformed list of toolkits
2235
+ *
2236
+ * @private
1563
2237
  */
1564
2238
  async getToolkits(query) {
1565
2239
  const parsedQuery = ToolkitsListParamsSchema.parse(query);
@@ -1588,11 +2262,29 @@ var Toolkits = class {
1588
2262
  return parsedResult;
1589
2263
  }
1590
2264
  /**
1591
- * Fetches a toolkit by its Slug.
1592
- * This method retrieves the toolkit from the Composio API.
1593
- * @param slug - The ID of the toolkit to be retrieved
1594
- * @param options - Request options
1595
- * @returns {Promise<ToolkitRetrieveResponse>} The toolkit object
2265
+ * Implementation method that handles both overloads for retrieving toolkits.
2266
+ *
2267
+ * @param {string | ToolkitListParams} arg - Either a toolkit slug or query parameters
2268
+ * @returns {Promise<ToolkitRetrieveResponse | ToolKitListResponse>} The toolkit or list of toolkits
2269
+ */
2270
+ async get(arg) {
2271
+ if (typeof arg === "string") {
2272
+ return this.getToolkitBySlug(arg);
2273
+ }
2274
+ return this.getToolkits(arg);
2275
+ }
2276
+ /**
2277
+ * Retrieves a specific toolkit by its slug identifier.
2278
+ *
2279
+ * This method fetches a single toolkit from the Composio API and transforms
2280
+ * the response to use camelCase property naming consistent with JavaScript/TypeScript conventions.
2281
+ *
2282
+ * @param {string} slug - The unique slug identifier of the toolkit to retrieve
2283
+ * @returns {Promise<ToolkitRetrieveResponse>} The transformed toolkit object
2284
+ * @throws {ValidationError} If the response cannot be properly parsed
2285
+ * @throws {ComposioToolNotFoundError} If no toolkit with the given slug exists
2286
+ *
2287
+ * @private
1596
2288
  */
1597
2289
  async getToolkitBySlug(slug) {
1598
2290
  try {
@@ -1633,21 +2325,19 @@ var Toolkits = class {
1633
2325
  }
1634
2326
  }
1635
2327
  /**
1636
- * Fetches a toolkit by its Slug or a list of toolkits.
1637
- * This method retrieves the toolkit from the Composio API.
1638
- * @param arg - The ID of the toolkit to be retrieved or a list of parameters
1639
- * @returns {Promise<ToolkitRetrieveResponse | ToolKitListResponse>} The toolkit object or a list of toolkits
1640
- */
1641
- async get(arg) {
1642
- if (typeof arg === "string") {
1643
- return this.getToolkitBySlug(arg);
1644
- }
1645
- return this.getToolkits(arg);
1646
- }
1647
- /**
1648
- * Fetches all categories available in the Composio SDK
2328
+ * Retrieves all toolkit categories available in the Composio SDK.
1649
2329
  *
1650
- * @returns {Promise<ToolkitRetrieveCategoriesResponse>} List of categories
2330
+ * This method fetches the complete list of categories from the Composio API
2331
+ * and transforms the response to use camelCase property naming.
2332
+ *
2333
+ * @returns {Promise<ToolkitRetrieveCategoriesResponse>} The list of toolkit categories
2334
+ *
2335
+ * @example
2336
+ * ```typescript
2337
+ * // Get all toolkit categories
2338
+ * const categories = await composio.toolkits.listCategories();
2339
+ * console.log(categories.items); // Array of category objects
2340
+ * ```
1651
2341
  */
1652
2342
  async listCategories() {
1653
2343
  const result = await this.client.toolkits.retrieveCategories();
@@ -1669,8 +2359,12 @@ var Toolkits = class {
1669
2359
  * This method will create an auth config if one doesn't exist and initiate a connection request.
1670
2360
  * @param {string} userId - The user id of the user to authorize
1671
2361
  * @param {string} toolkitSlug - The slug of the toolkit to authorize
1672
- * @param {string} authConfigId - The id of the auth config to use
1673
2362
  * @returns {Promise<ConnectionRequest>} The connection request object
2363
+ *
2364
+ * @example
2365
+ * ```typescript
2366
+ * const connectionRequest = await composio.toolkits.authorize(userId, 'github');
2367
+ * ```
1674
2368
  */
1675
2369
  async authorize(userId, toolkitSlug) {
1676
2370
  const toolkit = await this.getToolkitBySlug(toolkitSlug);
@@ -1794,6 +2488,7 @@ var Session = class {
1794
2488
  client;
1795
2489
  constructor(client) {
1796
2490
  this.client = client;
2491
+ telemetry.instrument(this);
1797
2492
  }
1798
2493
  /**
1799
2494
  * Get the active session info
@@ -1809,6 +2504,7 @@ var Triggers = class {
1809
2504
  client;
1810
2505
  constructor(client) {
1811
2506
  this.client = client;
2507
+ telemetry.instrument(this);
1812
2508
  }
1813
2509
  /**
1814
2510
  * Fetch list of all the active triggers
@@ -1940,235 +2636,6 @@ var Triggers = class {
1940
2636
  }
1941
2637
  };
1942
2638
 
1943
- // src/types/telemetry.types.ts
1944
- var TELEMETRY_EVENTS = {
1945
- SDK_INITIALIZED: "SDK_INITIALIZED",
1946
- SDK_METHOD_INVOKED: "SDK_METHOD_INVOKED",
1947
- SDK_METHOD_ERROR: "SDK_METHOD_ERROR",
1948
- CLI_INVOKED: "CLI_INVOKED"
1949
- };
1950
-
1951
- // src/utils/constants.ts
1952
- var COMPOSIO_DIR = ".composio";
1953
- var USER_DATA_FILE_NAME = "user_data.json";
1954
- var DEFAULT_BASE_URL = "https://backend.composio.dev";
1955
- var TELEMETRY_URL = "https://app.composio.dev";
1956
- var IS_DEVELOPMENT_OR_CI = process.env.DEVELOPMENT || process.env.CI || false;
1957
-
1958
- // src/telemetry/BatchProcessor.ts
1959
- var BatchProcessor = class {
1960
- batch = [];
1961
- time;
1962
- batchSize;
1963
- processBatchCallback;
1964
- timer = null;
1965
- constructor(time = 2e3, batchSize = 100, processBatchCallback) {
1966
- this.batch = [];
1967
- this.time = time;
1968
- this.batchSize = batchSize;
1969
- this.processBatchCallback = processBatchCallback;
1970
- }
1971
- pushItem(item) {
1972
- this.batch.push(item);
1973
- if (this.batch.length >= this.batchSize) {
1974
- this.processBatch();
1975
- } else if (!this.timer) {
1976
- this.timer = setTimeout(() => this.processBatch(), this.time);
1977
- }
1978
- }
1979
- processBatch() {
1980
- if (this.batch.length > 0) {
1981
- this.processBatchCallback(this.batch);
1982
- this.batch = [];
1983
- }
1984
- if (this.timer) {
1985
- clearTimeout(this.timer);
1986
- this.timer = null;
1987
- }
1988
- }
1989
- };
1990
-
1991
- // src/telemetry/transports/BrowserTransport.ts
1992
- var BrowserTelemetryTransport = class {
1993
- send(payload) {
1994
- if (typeof window === "undefined") {
1995
- return Promise.reject(
1996
- new Error("BrowserTelemetryTransport can only be used in browser environments")
1997
- );
1998
- }
1999
- return new Promise((resolve) => {
2000
- try {
2001
- const xhr = new XMLHttpRequest();
2002
- xhr.open(payload.method, payload.url, true);
2003
- xhr.setRequestHeader("Content-Type", "application/json");
2004
- Object.entries(payload.headers || {}).forEach(([key, value]) => {
2005
- xhr.setRequestHeader(key, value);
2006
- });
2007
- xhr.onload = function() {
2008
- resolve();
2009
- };
2010
- xhr.send(JSON.stringify(payload.data));
2011
- } catch (error) {
2012
- logger_default.error("Error sending error to telemetry", error);
2013
- resolve();
2014
- }
2015
- });
2016
- }
2017
- };
2018
-
2019
- // src/telemetry/transports/ProcessTransport.ts
2020
- var ProcessTelemetryTransport = class {
2021
- send(payload) {
2022
- if (typeof window !== "undefined") {
2023
- return Promise.reject(
2024
- new Error("ProcessTelemetryTransport can only be used in Node.js environments")
2025
- );
2026
- }
2027
- return new Promise((resolve) => {
2028
- try {
2029
- const url = new URL(payload.url);
2030
- const protocol = url.protocol === "https:" ? "https" : "http";
2031
- const port = url.port || (url.protocol === "https:" ? 443 : 80);
2032
- const args = [
2033
- "-e",
2034
- `
2035
- const http = require('${protocol}');
2036
- const options = {
2037
- hostname: '${url.hostname}',
2038
- path: '${url.pathname}${url.search}',
2039
- port: ${port},
2040
- method: '${payload.method}',
2041
- headers: ${JSON.stringify(payload.headers)}
2042
- };
2043
-
2044
- const req = http.request(options, (res) => {
2045
- res.on('data', () => {});
2046
- res.on('end', () => {
2047
- process.exit(0);
2048
- });
2049
- });
2050
-
2051
- req.on('error', () => {
2052
- process.exit(0);
2053
- });
2054
-
2055
- req.write(JSON.stringify(${JSON.stringify(payload.data)}));
2056
- req.end();
2057
- `
2058
- ];
2059
- import("child_process").then(({ spawn }) => {
2060
- spawn("node", args, {
2061
- stdio: "ignore",
2062
- detached: true,
2063
- shell: false
2064
- }).unref();
2065
- resolve();
2066
- }).catch(() => {
2067
- resolve();
2068
- });
2069
- } catch (error) {
2070
- logger_default.error("Error sending telemetry", error);
2071
- resolve();
2072
- }
2073
- });
2074
- }
2075
- };
2076
-
2077
- // src/telemetry/Telemetry.ts
2078
- var Telemetry = class {
2079
- telemetryMetadata;
2080
- transport;
2081
- batchProcessor = new BatchProcessor(100, 10, async (data) => {
2082
- await this.sendTelemetry(data);
2083
- });
2084
- constructor(metadata, transport) {
2085
- this.telemetryMetadata = metadata;
2086
- const isBrowser = typeof window !== "undefined";
2087
- if (transport) {
2088
- this.transport = transport;
2089
- } else if (isBrowser) {
2090
- this.transport = new BrowserTelemetryTransport();
2091
- } else {
2092
- this.transport = new ProcessTelemetryTransport();
2093
- }
2094
- this.sendTelemetry([
2095
- {
2096
- eventName: TELEMETRY_EVENTS.SDK_INITIALIZED,
2097
- data: {},
2098
- sdk_meta: this.telemetryMetadata
2099
- }
2100
- ]);
2101
- }
2102
- /**
2103
- * Instrument the telemetry for the given instance.
2104
- *
2105
- * You can pass the instance and the file name of the instance to instrument the telemetry.
2106
- * This will instrument all the methods of the instance and log the telemetry for each method call.
2107
- * @param instance - any instance that extends InstrumentedInstance
2108
- * @param fileName - the file name of the instance
2109
- * @returns
2110
- */
2111
- instrumentTelemetry(instance, fileName) {
2112
- const proto = Object.getPrototypeOf(instance);
2113
- const methodNames = Object.getOwnPropertyNames(proto).filter((key) => {
2114
- const descriptor = Object.getOwnPropertyDescriptor(proto, key);
2115
- return key !== "constructor" && descriptor && typeof descriptor.value === "function" && descriptor.value.constructor.name === "AsyncFunction";
2116
- });
2117
- const instrumentedClassName = instance.constructor?.name || fileName || "unknown";
2118
- for (const name of methodNames) {
2119
- const originalMethod = instance[name];
2120
- instance[name] = async (...args) => {
2121
- const telemetryPayload = {
2122
- eventName: TELEMETRY_EVENTS.SDK_METHOD_INVOKED,
2123
- data: {
2124
- fileName: instrumentedClassName,
2125
- method: name,
2126
- params: args
2127
- },
2128
- sdk_meta: this.telemetryMetadata
2129
- };
2130
- this.batchProcessor.pushItem(telemetryPayload);
2131
- try {
2132
- return await originalMethod.apply(instance, args);
2133
- } catch (error) {
2134
- const telemetryPayload2 = {
2135
- eventName: TELEMETRY_EVENTS.SDK_METHOD_ERROR,
2136
- data: {
2137
- fileName: instrumentedClassName,
2138
- method: name,
2139
- params: args,
2140
- error
2141
- },
2142
- sdk_meta: this.telemetryMetadata
2143
- };
2144
- this.batchProcessor.pushItem(telemetryPayload2);
2145
- throw error;
2146
- }
2147
- };
2148
- }
2149
- return instance;
2150
- }
2151
- /**
2152
- * Send the telemetry payload to the server.
2153
- * @param payload - the telemetry payload to send
2154
- * @returns
2155
- */
2156
- async sendTelemetry(payload) {
2157
- const isTelemetryDisabled = getEnvVariable("TELEMETRY_DISABLED", "false") === "true";
2158
- if (isTelemetryDisabled) {
2159
- return;
2160
- }
2161
- const url = `${TELEMETRY_URL}/api/sdk_metrics/telemetry`;
2162
- const reqPayload = {
2163
- data: payload,
2164
- url,
2165
- method: "POST",
2166
- headers: { "Content-Type": "application/json" }
2167
- };
2168
- this.transport.send(reqPayload);
2169
- }
2170
- };
2171
-
2172
2639
  // src/utils/sdk.ts
2173
2640
  var userDataPath = () => {
2174
2641
  try {
@@ -2197,23 +2664,22 @@ function getSDKConfig(baseUrl, apiKey) {
2197
2664
  }
2198
2665
 
2199
2666
  // src/utils/version.ts
2200
- function isNewerVersion(version1, version2) {
2201
- const v1 = version1.split(".").map(Number);
2202
- const v2 = version2.split(".").map(Number);
2203
- for (let i = 0; i < 3; i++) {
2204
- if (v1[i] > v2[i]) return true;
2205
- if (v1[i] < v2[i]) return false;
2206
- }
2207
- return false;
2208
- }
2667
+ import semver from "semver";
2209
2668
  async function checkForLatestVersionFromNPM(currentVersion) {
2210
2669
  try {
2211
- const packageName = "composio-core";
2670
+ const packageName = "@composio/core";
2212
2671
  const currentVersionFromPackageJson = currentVersion;
2672
+ if (!semver.valid(currentVersionFromPackageJson)) {
2673
+ return;
2674
+ }
2675
+ const prerelease = semver.prerelease(currentVersionFromPackageJson);
2676
+ if (prerelease && (String(prerelease[0]).includes("alpha") || String(prerelease[0]).includes("beta"))) {
2677
+ return;
2678
+ }
2213
2679
  const response = await fetch(`https://registry.npmjs.org/${packageName}/latest`);
2214
2680
  const data = await response.json();
2215
2681
  const latestVersion = data.version;
2216
- if (isNewerVersion(latestVersion, currentVersionFromPackageJson) && !IS_DEVELOPMENT_OR_CI) {
2682
+ if (semver.gt(latestVersion, currentVersionFromPackageJson) && !IS_DEVELOPMENT_OR_CI) {
2217
2683
  logger_default.info(
2218
2684
  `\u{1F680} Upgrade available! Your composio-core version (${currentVersionFromPackageJson}) is behind. Latest version: ${latestVersion}.`
2219
2685
  );
@@ -2427,7 +2893,7 @@ var OpenAIProvider = class extends BaseNonAgenticProvider {
2427
2893
  };
2428
2894
 
2429
2895
  // package.json
2430
- var version = "0.1.11-alpha.0";
2896
+ var version = "0.1.12-alpha.10";
2431
2897
 
2432
2898
  // src/utils/uuid.ts
2433
2899
  import { v4 as uuidv4 } from "uuid";
@@ -2447,7 +2913,6 @@ var Composio = class {
2447
2913
  * @type {ComposioConfig<TProvider>}
2448
2914
  */
2449
2915
  config;
2450
- telemetry;
2451
2916
  /**
2452
2917
  * Core models for Composio.
2453
2918
  */
@@ -2457,10 +2922,8 @@ var Composio = class {
2457
2922
  provider;
2458
2923
  // auth configs
2459
2924
  authConfigs;
2460
- createAuthConfig;
2461
2925
  // connected accounts
2462
2926
  connectedAccounts;
2463
- initiateConnection;
2464
2927
  /**
2465
2928
  * @param {Object} config Configuration for the Composio SDK.
2466
2929
  * @param {string} config.apiKey The API key for the Composio SDK.
@@ -2478,56 +2941,44 @@ var Composio = class {
2478
2941
  if (IS_DEVELOPMENT_OR_CI) {
2479
2942
  logger_default.info(`Initializing Composio w API Key: [REDACTED] and baseURL: ${baseURLParsed}`);
2480
2943
  }
2481
- this.client = new ComposioClient({
2944
+ this.client = new ComposioClient2({
2482
2945
  apiKey: apiKeyParsed,
2483
2946
  baseURL: baseURLParsed
2484
2947
  });
2485
2948
  this.config = {
2486
2949
  ...config,
2487
- allowTracking: config.allowTracking ?? true
2950
+ allowTracking: config.allowTracking ?? true,
2951
+ allowTracing: config.allowTracing ?? true
2488
2952
  };
2489
2953
  this.provider = config.provider ?? new OpenAIProvider();
2490
2954
  this.tools = new Tools(this.client, this.provider);
2491
- this.provider._setExecuteToolFn(this.tools.execute);
2492
2955
  this.toolkits = new Toolkits(this.client);
2493
2956
  this.triggers = new Triggers(this.client);
2494
2957
  this.authConfigs = new AuthConfigs(this.client);
2495
- this.createAuthConfig = this.authConfigs.create.bind(this.authConfigs);
2496
2958
  this.connectedAccounts = new ConnectedAccounts(this.client);
2497
- this.initiateConnection = this.connectedAccounts.initiate.bind(this.connectedAccounts);
2498
- if (this.config.allowTracking ?? true) {
2499
- this.initializeTelemetry(
2959
+ if (this.config.allowTracking) {
2960
+ telemetry.setup(
2500
2961
  {
2501
2962
  apiKey: apiKeyParsed ?? "",
2502
2963
  baseUrl: baseURLParsed ?? "",
2503
- frameworkRuntime: "node",
2504
- source: "node",
2505
- // @TODO: get the source
2506
- composioVersion: version,
2964
+ framework: this.provider?.name || "unknown",
2965
+ isAgentic: this.provider?._isAgentic || false,
2966
+ source: "javascript",
2967
+ version,
2968
+ sdkType: "Typescript-V3",
2507
2969
  isBrowser: typeof window !== "undefined",
2508
- sessionId: getRandomUUID()
2970
+ // @TODO: Users might want to pass their own session id
2971
+ // @TODO: We shouldn't be doing this as people might always have one session id throughout the process in server
2972
+ sessionId: this.config.allowTracing ? getRandomUUID() : void 0
2509
2973
  // @TODO: get the session id
2510
2974
  },
2511
2975
  config.telemetryTransport
2512
2976
  );
2513
2977
  }
2978
+ telemetry.instrument(this);
2979
+ telemetry.instrument(this.provider);
2514
2980
  checkForLatestVersionFromNPM(version);
2515
2981
  }
2516
- /**
2517
- * Initialize the instrumentations and telemetry for the Composio SDK.
2518
- * @param {TelemetryMetadata} config - The configuration for the telemetry.
2519
- * @param {BaseTelemetryTransport} transport - The transport for the telemetry.
2520
- */
2521
- initializeTelemetry(config, transport) {
2522
- this.telemetry = new Telemetry(config, transport);
2523
- this.telemetry.instrumentTelemetry(this);
2524
- this.telemetry.instrumentTelemetry(this.tools);
2525
- this.telemetry.instrumentTelemetry(this.toolkits);
2526
- this.telemetry.instrumentTelemetry(this.triggers);
2527
- this.telemetry.instrumentTelemetry(this.authConfigs);
2528
- this.telemetry.instrumentTelemetry(this.connectedAccounts);
2529
- this.telemetry.instrumentTelemetry(this.provider);
2530
- }
2531
2982
  /**
2532
2983
  * Get the Composio SDK client.
2533
2984
  * @returns {ComposioClient} The Composio API client.
@@ -2538,24 +2989,6 @@ var Composio = class {
2538
2989
  }
2539
2990
  return this.client;
2540
2991
  }
2541
- /**
2542
- * Fetch all the tools from Composio.
2543
- * @param {ToolListParams} params Parameters to fetch the tools.
2544
- * @param {ProviderOptions<TProvider>} modifiers Modifiers to apply to the tools.
2545
- * @returns {Promise<ReturnType<TProvider['getTools']>>} The tools from the provider.
2546
- */
2547
- getTools(userId, filters, modifiers) {
2548
- return this.tools.get(userId, filters, modifiers);
2549
- }
2550
- /**
2551
- * Fetch a tool from Composio by its slug.
2552
- * @param {string} slug slug of the tool
2553
- * @param {ProviderOptions<TProvider>} modifiers to be applied to the tool
2554
- * @returns {Promise<ReturnType<TProvider['getToolBySlug']>>} The tool from the provider.
2555
- */
2556
- getToolBySlug(userId, slug, modifiers) {
2557
- return this.tools.get(userId, slug, modifiers);
2558
- }
2559
2992
  };
2560
2993
 
2561
2994
  // src/provider/ComposioProvider.ts
@@ -2570,8 +3003,15 @@ var ComposioProvider = class extends BaseNonAgenticProvider {
2570
3003
  };
2571
3004
 
2572
3005
  // src/telemetry/TelemetryTransport.ts
3006
+ import chalk3 from "chalk";
2573
3007
  var BaseTelemetryTransport = class {
2574
3008
  };
3009
+ var ConsoleTelemetryTransport = class {
3010
+ send(payload) {
3011
+ logger_default.debug(chalk3.yellow("telemetry"), JSON.stringify(payload, null, 2));
3012
+ return Promise.resolve();
3013
+ }
3014
+ };
2575
3015
 
2576
3016
  // src/utils/jsonSchema.ts
2577
3017
  import { z as z5 } from "zod";
@@ -2689,6 +3129,7 @@ export {
2689
3129
  BaseTelemetryTransport,
2690
3130
  Composio,
2691
3131
  ComposioProvider,
3132
+ ConsoleTelemetryTransport,
2692
3133
  OpenAIProvider,
2693
3134
  ToolListParamsSchema,
2694
3135
  jsonSchemaToModel