@composio/core 0.4.0 → 0.5.1

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.
@@ -0,0 +1,852 @@
1
+ import { t as __exportAll } from "./chunk-0j-ceAHr.mjs";
2
+ import { BadRequestError, ComposioError } from "@composio/client";
3
+ import { ZodError } from "zod/v3";
4
+ import chalk from "chalk";
5
+ import crypto from "node:crypto";
6
+ import { platform } from "#platform";
7
+
8
+ //#region src/utils/env.ts
9
+ const getEnvVariable = (name, defaultValue = void 0) => {
10
+ try {
11
+ return process.env[name] || defaultValue;
12
+ } catch (_e) {
13
+ return defaultValue;
14
+ }
15
+ };
16
+ /**
17
+ * Method to return all the envs based on a specific prefix
18
+ * @param prefix
19
+ * @example
20
+ * COMPOSIO_TOOLKIT_VERSION_GITHUB=20250902_00
21
+ * COMPOSIO_TOOLKIT_VERSION_SLACK=20250902_00
22
+ * COMPOSIO_TOOLKIT_VERSION_GMAIL=latest
23
+ * @returns {Record<string, unknown>}
24
+ * @returns
25
+ */
26
+ const getEnvsWithPrefix = (prefix) => {
27
+ try {
28
+ if (process && process.env) return Object.fromEntries(Object.entries(process.env).filter(([key]) => key.startsWith(prefix)));
29
+ else return {};
30
+ } catch (error) {
31
+ return {};
32
+ }
33
+ };
34
+
35
+ //#endregion
36
+ //#region src/utils/constants.ts
37
+ var constants_exports = /* @__PURE__ */ __exportAll({
38
+ CLIENT_PUSHER_KEY: () => CLIENT_PUSHER_KEY,
39
+ COMPOSIO_DIR: () => COMPOSIO_DIR,
40
+ COMPOSIO_LOG_LEVEL: () => COMPOSIO_LOG_LEVEL,
41
+ DEFAULT_BASE_URL: () => DEFAULT_BASE_URL,
42
+ DEFAULT_WEB_URL: () => DEFAULT_WEB_URL,
43
+ IS_DEVELOPMENT_OR_CI: () => IS_DEVELOPMENT_OR_CI,
44
+ TELEMETRY_URL: () => TELEMETRY_URL$1,
45
+ TEMP_FILES_DIRECTORY_NAME: () => TEMP_FILES_DIRECTORY_NAME,
46
+ USER_DATA_FILE_NAME: () => USER_DATA_FILE_NAME
47
+ });
48
+ const COMPOSIO_DIR = ".composio";
49
+ const USER_DATA_FILE_NAME = "user_data.json";
50
+ const TEMP_FILES_DIRECTORY_NAME = "files";
51
+ const DEFAULT_BASE_URL = "https://backend.composio.dev";
52
+ const DEFAULT_WEB_URL = "https://platform.composio.dev";
53
+ const TELEMETRY_URL$1 = "https://app.composio.dev";
54
+ const CLIENT_PUSHER_KEY = getEnvVariable("CLIENT_PUSHER_KEY") || "ff9f18c208855d77a152";
55
+ const COMPOSIO_LOG_LEVEL = getEnvVariable("COMPOSIO_LOG_LEVEL");
56
+ const IS_DEVELOPMENT_OR_CI = getEnvVariable("DEVELOPMENT") || getEnvVariable("CI") || false;
57
+
58
+ //#endregion
59
+ //#region src/utils/logger.ts
60
+ const LOG_LEVELS = {
61
+ silent: -1,
62
+ error: 0,
63
+ warn: 1,
64
+ info: 2,
65
+ debug: 3
66
+ };
67
+ /**
68
+ * Get the current log level from environment variables.
69
+ * Defaults to 'info' if not set or invalid.
70
+ * @returns {LogLevel} The current log level
71
+ */
72
+ const getLogLevel = () => {
73
+ const envLevel = (COMPOSIO_LOG_LEVEL ?? "info")?.toLowerCase();
74
+ return envLevel && envLevel in LOG_LEVELS ? envLevel : "info";
75
+ };
76
+ var Logger = class {
77
+ level;
78
+ includeTimestamp;
79
+ console;
80
+ constructor(options = {}) {
81
+ this.level = options.level ?? getLogLevel();
82
+ this.includeTimestamp = options.includeTimestamp ?? true;
83
+ this.console = console;
84
+ }
85
+ formatMessage(args) {
86
+ const formattedArgs = args.map((arg, index) => {
87
+ if (typeof arg === "object") return JSON.stringify(arg);
88
+ else {
89
+ if (index === 0) if (args.length > 1) return chalk.yellow(`${arg}`);
90
+ else return String(arg);
91
+ return String(arg);
92
+ }
93
+ }).join("\n");
94
+ if (!this.includeTimestamp) return formattedArgs;
95
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
96
+ return `${chalk.gray(timestamp)} - ${formattedArgs}`;
97
+ }
98
+ shouldLog(level) {
99
+ return LOG_LEVELS[level] <= LOG_LEVELS[this.level];
100
+ }
101
+ error(...args) {
102
+ if (this.shouldLog("error")) this.console.error(this.formatMessage(args));
103
+ }
104
+ warn(...args) {
105
+ if (this.shouldLog("warn")) this.console.warn(this.formatMessage(args));
106
+ }
107
+ info(...args) {
108
+ if (this.shouldLog("info")) this.console.info(this.formatMessage(args));
109
+ }
110
+ debug(...args) {
111
+ if (this.shouldLog("debug")) this.console.debug(this.formatMessage(args));
112
+ }
113
+ };
114
+ const logger = new Logger();
115
+ var logger_default = logger;
116
+
117
+ //#endregion
118
+ //#region src/errors/ComposioError.ts
119
+ /**
120
+ * @fileoverview Error class for Composio.
121
+ *
122
+ * This error class is used to create custom errors for Composio.
123
+ * It extends the built-in Error class and adds additional properties for code, status code, cause, meta, and possible fixes.
124
+ *
125
+ * @author Musthaq Ahamad <musthaq@composio.dev>
126
+ * @module errors/ComposioError
127
+ * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error}
128
+ */
129
+ /**
130
+ * Base error class for all Composio errors
131
+ */
132
+ var ComposioError$1 = class ComposioError$1 extends Error {
133
+ /** @readonly Error name */
134
+ name = "ComposioError";
135
+ code;
136
+ possibleFixes;
137
+ errorId;
138
+ /**
139
+ * Creates a new ComposioError
140
+ * @param message Error message
141
+ * @param options Additional error options
142
+ */
143
+ constructor(message, options = {}) {
144
+ super(message);
145
+ if (Error.captureStackTrace) Error.captureStackTrace(this, this.constructor);
146
+ const statusCode = options.statusCode || (options.cause instanceof BadRequestError ? options.cause.status : void 0);
147
+ this.code = `TS-SDK::${options.code}`;
148
+ this.possibleFixes = options.possibleFixes;
149
+ this.definePropertyIfExists("statusCode", statusCode);
150
+ this.definePropertyIfExists("cause", options.cause);
151
+ const combinedStack = options.cause instanceof Error ? ComposioError$1.combineStackTraces(options.cause.stack, this.stack) : options.stack ?? this.stack;
152
+ this.definePropertyIfExists("stack", combinedStack);
153
+ if (options.meta && Object.keys(options.meta).length > 0) this.definePropertyIfExists("meta", options.meta);
154
+ }
155
+ /**
156
+ * Helper method to define a property only if it has a value
157
+ * @param propertyName Name of the property to define
158
+ * @param value Value to assign to the property
159
+ * @private
160
+ */
161
+ definePropertyIfExists(propertyName, value) {
162
+ if (value !== void 0) Object.defineProperty(this, propertyName, {
163
+ value,
164
+ enumerable: true,
165
+ writable: false,
166
+ configurable: true
167
+ });
168
+ }
169
+ /**
170
+ * Helper method to combine stack traces when wrapping errors
171
+ * This ensures the full call chain is preserved
172
+ * @param originalStack The stack of the error being wrapped
173
+ * @param currentStack The stack of the wrapper error
174
+ * @returns Combined stack trace
175
+ * @private
176
+ */
177
+ static combineStackTraces(originalStack, currentStack) {
178
+ if (!originalStack) return currentStack;
179
+ if (!currentStack) return originalStack;
180
+ const currentHeader = currentStack.split("\n")[0];
181
+ const originalStackBody = originalStack.split("\n").slice(1).join("\n");
182
+ return `${currentHeader}\n${currentStack.split("\n").slice(1).join("\n")}\n\nCaused by:\n${originalStackBody}`;
183
+ }
184
+ /**
185
+ * Extract and normalize error data for formatting
186
+ * @param includeStack Whether to include stack trace information
187
+ * @returns Structured error data for formatting
188
+ * @private
189
+ */
190
+ getErrorData(includeStack = false) {
191
+ const data = {
192
+ name: this.name,
193
+ message: this.message
194
+ };
195
+ const { cause, code, stack, statusCode, meta, possibleFixes } = this;
196
+ if (cause !== void 0) {
197
+ const rawCause = cause;
198
+ data.cause = rawCause instanceof Error ? rawCause.message : String(rawCause);
199
+ }
200
+ if (code) data.code = code;
201
+ if (statusCode !== void 0) data.statusCode = statusCode;
202
+ if (meta) data.meta = meta;
203
+ if (possibleFixes) data.possibleFixes = possibleFixes;
204
+ if (includeStack && stack) if (stack.includes("Caused by:")) {
205
+ const [currentStack, causeStack] = stack.split("Caused by:");
206
+ data.stack = [
207
+ ...currentStack.split("\n").slice(1),
208
+ "Caused by:",
209
+ ...causeStack.split("\n")
210
+ ];
211
+ } else data.stack = stack.split("\n").slice(1);
212
+ return data;
213
+ }
214
+ /**
215
+ * Prints a user-friendly, colorful representation of the error to the logger
216
+ * @param includeStack Whether to include the stack trace in the output (default: false)
217
+ */
218
+ prettyPrint(includeStack = false) {
219
+ const data = this.getErrorData(includeStack);
220
+ let output = "\n" + chalk.bgRed.white.bold(" ERROR ") + " " + chalk.white.bold(data.message) + "\n";
221
+ if (data.code) output += chalk.yellow(`Error Code: ${data.code}`) + "\n";
222
+ if (data.statusCode !== void 0) output += chalk.yellow(`Status: ${data.statusCode}`) + "\n";
223
+ if (data.cause) {
224
+ output += chalk.gray("Reason:") + "\n";
225
+ output += " " + chalk.white(data.cause) + "\n";
226
+ }
227
+ if (data.meta) {
228
+ output += chalk.gray("Additional Information:") + "\n";
229
+ output += " " + chalk.white(JSON.stringify(data.meta, null, 2).replace(/\n/g, "\n ")) + "\n";
230
+ }
231
+ if (data.possibleFixes?.length) {
232
+ output += "\n" + chalk.cyan.bold("Try the following:") + "\n";
233
+ const fixes = data.possibleFixes?.map((fix, index) => ` ${index + 1}. ` + chalk.white(fix));
234
+ output += fixes?.join("\n") + "\n";
235
+ }
236
+ if (data.stack?.length) {
237
+ output += "\n" + chalk.gray("Stack Trace:") + "\n";
238
+ output += chalk.gray(data.stack.join("\n")) + "\n";
239
+ }
240
+ output += "\n";
241
+ logger_default.error(output);
242
+ }
243
+ /**
244
+ * Static factory method to create and pretty print an error in one step
245
+ * @param message Error message
246
+ * @param options Error options
247
+ * @param includeStack Whether to include the stack trace in the output
248
+ * @returns The created error instance
249
+ */
250
+ static createAndPrint(message, options = {}, includeStack = false) {
251
+ const error = new ComposioError$1(message, options);
252
+ error.prettyPrint(includeStack);
253
+ return error;
254
+ }
255
+ /**
256
+ * Utility function to handle errors in a consistent way
257
+ * This properly displays the error without throwing
258
+ * @param error The error to handle
259
+ * @param options Options for error handling
260
+ */
261
+ static handle(error, options = {}) {
262
+ const { includeStack = false, exitProcess = false } = options;
263
+ if (error instanceof ComposioError$1) error.prettyPrint(includeStack);
264
+ else if (error instanceof ZodError) this.handleZodError(error, includeStack);
265
+ else if (error instanceof Error) this.handleStandardError(error, includeStack);
266
+ else this.handleUnknownError(error);
267
+ if (exitProcess) this.throwError(error);
268
+ }
269
+ /**
270
+ * Utility function to handle errors and then throw them
271
+ * This properly displays the error and then throws it, allowing callers to catch it.
272
+ * Use this for fatal errors that should stop execution.
273
+ * @param error The error to handle and throw
274
+ * @param includeStack Whether to include the stack trace in the output
275
+ * @throws ComposioError - Always throws after displaying the error
276
+ */
277
+ static handleAndThrow(error, includeStack = false) {
278
+ this.handle(error, { includeStack });
279
+ this.throwError(error);
280
+ }
281
+ /**
282
+ * Helper method to throw an error as a ComposioError
283
+ * @param error The error to throw
284
+ * @private
285
+ */
286
+ static throwError(error) {
287
+ if (error instanceof ComposioError$1) throw error;
288
+ else if (error instanceof Error) throw new ComposioError$1(error.message, { cause: error });
289
+ else throw new ComposioError$1(String(error));
290
+ }
291
+ /**
292
+ * Helper method to handle Zod validation errors
293
+ * @param error The Zod error to handle
294
+ * @param includeStack Whether to include the stack trace
295
+ * @private
296
+ */
297
+ static handleZodError(error, includeStack) {
298
+ logger_default.error("\n" + chalk.bgRed.white.bold(" ERROR ") + " " + chalk.white.bold(error.message));
299
+ logger_default.error(chalk.gray("Invalid parameters:"));
300
+ error.errors.forEach((err) => {
301
+ logger_default.error(chalk.yellow(err.path.join(".")) + " " + chalk.white(err.message));
302
+ });
303
+ logger_default.error(chalk.gray("Expected parameters:"));
304
+ error.errors.forEach((err) => {
305
+ logger_default.error(chalk.yellow(err.path.join(".")) + " " + chalk.white(err.message));
306
+ });
307
+ if (includeStack) {
308
+ logger_default.error("\n" + chalk.gray("Validation Errors:"));
309
+ error.errors.forEach((err) => {
310
+ const path = err.path.join(".");
311
+ logger_default.error(chalk.gray(" • ") + chalk.yellow(path ? `${path}: ` : "") + chalk.white(err.message));
312
+ });
313
+ if (error.stack) {
314
+ logger_default.error("\n" + chalk.gray("Stack Trace:"));
315
+ const stackLines = error.stack.split("\n").slice(1);
316
+ logger_default.error(chalk.gray(stackLines.join("\n")));
317
+ }
318
+ }
319
+ logger_default.error("");
320
+ }
321
+ /**
322
+ * Helper method to handle standard Error objects
323
+ * @param error The standard error to handle
324
+ * @param includeStack Whether to include the stack trace
325
+ * @private
326
+ */
327
+ static handleStandardError(error, includeStack) {
328
+ logger_default.error("\n" + chalk.bgRed.white.bold(" ERROR ") + " " + chalk.white.bold(error.message));
329
+ if (includeStack && error.stack) {
330
+ logger_default.error("\n" + chalk.gray("Stack Trace:"));
331
+ const stackLines = error.stack.split("\n").slice(1);
332
+ logger_default.error(chalk.gray(stackLines.join("\n")));
333
+ }
334
+ logger_default.error("");
335
+ }
336
+ /**
337
+ * Helper method to handle unknown error types
338
+ * @param error The unknown error value
339
+ * @private
340
+ */
341
+ static handleUnknownError(error) {
342
+ logger_default.error("\n" + chalk.bgRed.white.bold(" ERROR ") + " " + chalk.white.bold("Unknown error occurred"));
343
+ if (error !== null && error !== void 0) {
344
+ logger_default.error(chalk.gray("Error details:"));
345
+ logger_default.error(" " + chalk.white(String(error)));
346
+ }
347
+ logger_default.error("");
348
+ }
349
+ };
350
+
351
+ //#endregion
352
+ //#region src/types/telemetry.types.ts
353
+ const TELEMETRY_EVENTS = {
354
+ SDK_INITIALIZED: "SDK_INITIALIZED",
355
+ SDK_METHOD_INVOKED: "SDK_METHOD_INVOKED",
356
+ SDK_METHOD_ERROR: "SDK_METHOD_ERROR",
357
+ CLI_INVOKED: "CLI_INVOKED"
358
+ };
359
+
360
+ //#endregion
361
+ //#region src/telemetry/BatchProcessor.ts
362
+ var BatchProcessor = class {
363
+ batch = [];
364
+ time;
365
+ batchSize;
366
+ processBatchCallback;
367
+ timer = null;
368
+ constructor(time = 2e3, batchSize = 100, processBatchCallback) {
369
+ this.batch = [];
370
+ this.time = time;
371
+ this.batchSize = batchSize;
372
+ this.processBatchCallback = processBatchCallback;
373
+ }
374
+ pushItem(item) {
375
+ this.batch.push(item);
376
+ if (this.batch.length >= this.batchSize) this.processBatch();
377
+ else if (!this.timer) this.timer = setTimeout(() => this.processBatch(), this.time);
378
+ }
379
+ processBatch() {
380
+ if (this.batch.length > 0) {
381
+ this.processBatchCallback(this.batch);
382
+ this.batch = [];
383
+ }
384
+ if (this.timer) {
385
+ clearTimeout(this.timer);
386
+ this.timer = null;
387
+ }
388
+ }
389
+ };
390
+
391
+ //#endregion
392
+ //#region src/utils/uuid.ts
393
+ function getRandomUUID() {
394
+ return globalThis.crypto.randomUUID();
395
+ }
396
+ function getRandomShortId() {
397
+ return getRandomUUID().slice(0, 8).replace(/-/g, "");
398
+ }
399
+
400
+ //#endregion
401
+ //#region src/services/telemetry/TelemetryService.ts
402
+ const TELEMETRY_URL = "https://telemetry.composio.dev/v1";
403
+ var TelemetryService = class {
404
+ /**
405
+ * Sends a metric to the Telemetry API.
406
+ * @param payload - The payload to send to the Telemetry API.
407
+ * @returns The response from the Telemetry API.
408
+ */
409
+ static async sendMetric(payload) {
410
+ try {
411
+ return await fetch(`${TELEMETRY_URL}/metrics/invocations`, {
412
+ method: "POST",
413
+ headers: { "Content-Type": "application/json" },
414
+ body: JSON.stringify(payload)
415
+ });
416
+ } catch (error) {
417
+ logger_default.debug("Error sending metric telemetry", error);
418
+ }
419
+ }
420
+ /**
421
+ * Sends an error log to the Telemetry API.
422
+ * @param payload - The payload to send to the Telemetry API.
423
+ * @returns The response from the Telemetry API.
424
+ */
425
+ static async sendErrorLog(payload) {
426
+ try {
427
+ return await fetch(`${TELEMETRY_URL}/errors`, {
428
+ method: "POST",
429
+ headers: { "Content-Type": "application/json" },
430
+ body: JSON.stringify(payload)
431
+ });
432
+ } catch (error) {
433
+ logger_default.debug("Error sending error telemetry", error);
434
+ }
435
+ }
436
+ };
437
+
438
+ //#endregion
439
+ //#region src/telemetry/Telemetry.ts
440
+ /**
441
+ * The Telemetry class is used to log the telemetry for any given instance which extends InstrumentedInstance.
442
+ *
443
+ * This class is used to instrument the telemetry for the given instance and send the telemetry to the server.
444
+ * This class is also used to create a global error handler for the given instance.
445
+ *
446
+ * @example
447
+ *
448
+ * const telemetry = new Telemetry({...});
449
+ * const composio = new Composio({...})
450
+ *
451
+ * telemetry.instrument(composio);
452
+ * telemetry.instrument(composio.tools);
453
+ * telemetry.instrument(composio.toolkits);
454
+ * telemetry.instrument(composio.triggers);
455
+ *
456
+ */
457
+ var TelemetryTransport = class {
458
+ telemetryMetadata;
459
+ isTelemetryDisabled = true;
460
+ telemetrySource;
461
+ telemetrySourceName = "typescript-sdk";
462
+ telemetryServiceName = "sdk";
463
+ telemetryLanguage = "typescript";
464
+ batchProcessor = new BatchProcessor(200, 10, async (data) => {
465
+ logger_default.debug("Sending batch of telemetry metrics", data);
466
+ await TelemetryService.sendMetric(data);
467
+ });
468
+ setup(metadata) {
469
+ this.telemetryMetadata = metadata;
470
+ this.isTelemetryDisabled = false;
471
+ this.telemetrySource = {
472
+ host: this.telemetryMetadata?.host ?? this.telemetrySourceName,
473
+ service: this.telemetryServiceName,
474
+ language: this.telemetryLanguage,
475
+ version: this.telemetryMetadata?.version,
476
+ platform: this.telemetryMetadata?.isBrowser ? "browser" : "node",
477
+ environment: getEnvVariable("NODE_ENV", "production")
478
+ };
479
+ this.sendMetric([{
480
+ functionName: TELEMETRY_EVENTS.SDK_INITIALIZED,
481
+ durationMs: 0,
482
+ timestamp: Date.now() / 1e3,
483
+ props: {},
484
+ source: this.telemetrySource,
485
+ metadata: { provider: this.telemetryMetadata?.provider ?? "openai" },
486
+ error: void 0
487
+ }]);
488
+ }
489
+ /**
490
+ * Instrument the telemetry for the given instance.
491
+ *
492
+ * You can pass the instance and the file name of the instance to instrument the telemetry.
493
+ * This will instrument all the methods of the instance and log the telemetry for each method call.
494
+ * @param instance - any instance that extends InstrumentedInstance
495
+ * @param fileName - the file name of the instance
496
+ * @returns
497
+ */
498
+ instrument(instance, fileName) {
499
+ const proto = Object.getPrototypeOf(instance);
500
+ const methodNames = Object.getOwnPropertyNames(proto).filter((key) => {
501
+ const descriptor = Object.getOwnPropertyDescriptor(proto, key);
502
+ return key !== "constructor" && descriptor && typeof descriptor.value === "function" && descriptor.value.constructor.name === "AsyncFunction";
503
+ });
504
+ const instrumentedClassName = fileName ?? instance.constructor?.name ?? "unknown";
505
+ for (const name of methodNames) {
506
+ const originalMethod = instance[name];
507
+ instance[name] = async (...args) => {
508
+ const telemetryEnabled = this.shouldSendTelemetry();
509
+ const startTime = telemetryEnabled ? Date.now() : void 0;
510
+ try {
511
+ const result = await originalMethod.apply(instance, args);
512
+ if (telemetryEnabled && startTime !== void 0) {
513
+ const durationMs = Date.now() - startTime;
514
+ const telemetryPayload = {
515
+ functionName: `${instrumentedClassName}.${name}`,
516
+ durationMs,
517
+ timestamp: startTime / 1e3,
518
+ props: {
519
+ fileName: instrumentedClassName,
520
+ method: name,
521
+ params: args
522
+ },
523
+ metadata: { provider: this.telemetryMetadata?.provider ?? "openai" },
524
+ error: void 0,
525
+ source: this.telemetrySource
526
+ };
527
+ this.batchProcessor.pushItem(telemetryPayload);
528
+ }
529
+ return result;
530
+ } catch (error) {
531
+ if (error instanceof Error) {
532
+ if (!error.errorId) {
533
+ error.errorId = getRandomUUID();
534
+ if (telemetryEnabled && startTime !== void 0) {
535
+ const durationMs = Date.now() - startTime;
536
+ await this.prepareAndSendErrorTelemetry(error, instrumentedClassName, name, args, startTime, durationMs);
537
+ }
538
+ }
539
+ }
540
+ throw error;
541
+ }
542
+ };
543
+ }
544
+ return instance;
545
+ }
546
+ /**
547
+ * Check if the telemetry should be sent.
548
+ * @returns true if the telemetry should be sent, false otherwise
549
+ */
550
+ shouldSendTelemetry() {
551
+ const telemetryDisabledEnvironments = ["test", "ci"];
552
+ const nodeEnv = (getEnvVariable("NODE_ENV", "development") || "").toLowerCase();
553
+ const isDisabledEnvironment = telemetryDisabledEnvironments.includes(nodeEnv);
554
+ const isTelemetryDisabledByEnv = getEnvVariable("TELEMETRY_DISABLED", "false") === "true";
555
+ return !this.isTelemetryDisabled && !isTelemetryDisabledByEnv && !isDisabledEnvironment;
556
+ }
557
+ /**
558
+ * Prepare and send the error telemetry.
559
+ *
560
+ * @TODO This currently blocks the thread and sends the telemetry to the server.
561
+ *
562
+ * @param {unknown} error - The error to send.
563
+ * @param {string} instrumentedClassName - The class name of the instrumented class.
564
+ * @param {string} name - The name of the method that threw the error.
565
+ * @param {unknown[]} args - The arguments passed to the method.
566
+ * @param {number} startTime - The start time of the method invocation in milliseconds.
567
+ * @param {number} durationMs - The duration of the method invocation in milliseconds.
568
+ */
569
+ async prepareAndSendErrorTelemetry(error, instrumentedClassName, name, args, startTime, durationMs) {
570
+ const telemetryPayload = {
571
+ functionName: `${instrumentedClassName}.${name}`,
572
+ durationMs,
573
+ timestamp: startTime / 1e3,
574
+ props: {
575
+ fileName: instrumentedClassName,
576
+ method: name,
577
+ params: args
578
+ },
579
+ metadata: { provider: this.telemetryMetadata?.provider ?? "openai" },
580
+ source: this.telemetrySource
581
+ };
582
+ if (error instanceof ComposioError) telemetryPayload.error = {
583
+ errorId: error.errorId,
584
+ name: error.name,
585
+ message: error.message,
586
+ stack: error.stack
587
+ };
588
+ else if (error instanceof ComposioError$1) telemetryPayload.error = {
589
+ errorId: error.errorId,
590
+ name: error.name,
591
+ code: error.code,
592
+ message: error.message,
593
+ stack: error.stack
594
+ };
595
+ else if (error instanceof Error) telemetryPayload.error = {
596
+ errorId: error.errorId,
597
+ name: error.name ?? "Unknown error",
598
+ message: error.message,
599
+ stack: error.stack
600
+ };
601
+ await this.sendErrorTelemetry(telemetryPayload);
602
+ }
603
+ /**
604
+ * Send the telemetry payload to the server.
605
+ * @param payload - the telemetry payload to send
606
+ * @returns
607
+ */
608
+ async sendMetric(payload) {
609
+ if (!this.shouldSendTelemetry()) {
610
+ logger_default.debug("Telemetry is disabled, skipping metric telemetry", payload);
611
+ return;
612
+ }
613
+ try {
614
+ logger_default.debug("SDK Metric", payload);
615
+ await TelemetryService.sendMetric(payload);
616
+ } catch (error) {
617
+ logger_default.error("Error sending metric telemetry", error);
618
+ }
619
+ }
620
+ async sendErrorTelemetry(payload) {
621
+ if (!this.shouldSendTelemetry()) {
622
+ logger_default.debug("Telemetry is disabled, skipping metric telemetry", payload);
623
+ return;
624
+ }
625
+ try {
626
+ logger_default.debug("SDK Error Telemetry", payload);
627
+ await TelemetryService.sendErrorLog(payload);
628
+ } catch (error) {
629
+ logger_default.error("Error sending error telemetry", error);
630
+ }
631
+ }
632
+ };
633
+ const telemetry = new TelemetryTransport();
634
+
635
+ //#endregion
636
+ //#region src/utils/fileUtils.ts
637
+ const getExtensionFromMimeType = (mimeType) => {
638
+ const mimeToExt = {
639
+ "text/plain": "txt",
640
+ "text/html": "html",
641
+ "text/css": "css",
642
+ "text/javascript": "js",
643
+ "application/json": "json",
644
+ "application/xml": "xml",
645
+ "application/pdf": "pdf",
646
+ "application/zip": "zip",
647
+ "application/x-zip-compressed": "zip",
648
+ "application/gzip": "gz",
649
+ "application/x-tar": "tar",
650
+ "application/msword": "doc",
651
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document": "docx",
652
+ "application/vnd.ms-excel": "xls",
653
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": "xlsx",
654
+ "application/vnd.ms-powerpoint": "ppt",
655
+ "application/vnd.openxmlformats-officedocument.presentationml.presentation": "pptx",
656
+ "image/jpeg": "jpg",
657
+ "image/jpg": "jpg",
658
+ "image/png": "png",
659
+ "image/gif": "gif",
660
+ "image/svg+xml": "svg",
661
+ "image/webp": "webp",
662
+ "image/bmp": "bmp",
663
+ "image/tiff": "tiff",
664
+ "audio/mpeg": "mp3",
665
+ "audio/wav": "wav",
666
+ "audio/ogg": "ogg",
667
+ "video/mp4": "mp4",
668
+ "video/mpeg": "mpeg",
669
+ "video/quicktime": "mov",
670
+ "video/x-msvideo": "avi",
671
+ "video/webm": "webm"
672
+ };
673
+ const cleanMimeType = mimeType.split(";")[0].toLowerCase().trim();
674
+ if (mimeToExt[cleanMimeType]) return mimeToExt[cleanMimeType];
675
+ const parts = cleanMimeType.split("/");
676
+ if (parts.length === 2) {
677
+ const cleanSubtype = parts[1].toLowerCase();
678
+ if (cleanSubtype.includes("+")) {
679
+ const plusParts = cleanSubtype.split("+");
680
+ const prefix = plusParts[0];
681
+ const suffix = plusParts[plusParts.length - 1];
682
+ if ([
683
+ "svg",
684
+ "atom",
685
+ "rss"
686
+ ].includes(prefix)) return prefix;
687
+ if ([
688
+ "json",
689
+ "xml",
690
+ "yaml",
691
+ "zip",
692
+ "gzip"
693
+ ].includes(suffix)) return suffix;
694
+ return suffix;
695
+ }
696
+ return cleanSubtype || "txt";
697
+ }
698
+ return "txt";
699
+ };
700
+ const generateTimestampedFilename = (extension, prefix) => {
701
+ return `${prefix || "file_ts"}${Date.now()}${getRandomShortId()}.${extension}`;
702
+ };
703
+ const readFileContent = async (filePath) => {
704
+ try {
705
+ if (!platform.supportsFileSystem) throw new Error("File system operations are not supported in this runtime environment");
706
+ const content = platform.readFileSync(filePath);
707
+ return {
708
+ fileName: generateTimestampedFilename(filePath.split(".").pop() || "txt"),
709
+ content: Buffer.isBuffer(content) ? content.toString("base64") : Buffer.from(content).toString("base64"),
710
+ mimeType: "application/octet-stream"
711
+ };
712
+ } catch (error) {
713
+ throw new Error(`Error reading file at ${filePath}: ${error}`);
714
+ }
715
+ };
716
+ const readFileContentFromURL = async (path) => {
717
+ const response = await fetch(path);
718
+ if (!response.ok) throw new Error(`Failed to fetch file: ${response.statusText}`);
719
+ const arrayBuffer = await response.arrayBuffer();
720
+ const content = Buffer.from(arrayBuffer);
721
+ const mimeType = response.headers.get("content-type") || "application/octet-stream";
722
+ const pathname = new URL(path).pathname;
723
+ let fileName = platform.basename(pathname);
724
+ if (!fileName || fileName === "/") fileName = generateTimestampedFilename(getExtensionFromMimeType(mimeType));
725
+ else if (!fileName.includes(".")) fileName = generateTimestampedFilename(getExtensionFromMimeType(mimeType));
726
+ return {
727
+ content: content.toString("base64"),
728
+ mimeType,
729
+ fileName
730
+ };
731
+ };
732
+ const uploadFileToS3 = async (fileName, content, toolSlug, toolkitSlug, mimeType, client) => {
733
+ const response = await client.files.createPresignedURL({
734
+ filename: fileName,
735
+ mimetype: mimeType,
736
+ md5: crypto.createHash("md5").update(Buffer.from(content, "base64")).digest("hex"),
737
+ tool_slug: toolSlug,
738
+ toolkit_slug: toolkitSlug
739
+ });
740
+ const { key, type } = response;
741
+ if (type === "new" || type === "update") {
742
+ logger_default.debug(`Uploading ${key} file to S3: ${key}`);
743
+ const buffer = Buffer.from(content, "base64");
744
+ const signedURL = response.type === "update" ? response.update_presigned_url : response.new_presigned_url;
745
+ const uploadResponse = await fetch(signedURL, {
746
+ method: "PUT",
747
+ body: buffer,
748
+ headers: {
749
+ "Content-Type": mimeType,
750
+ "Content-Length": buffer.length.toString()
751
+ }
752
+ });
753
+ if (!uploadResponse.ok) throw new Error(`Failed to upload file to S3: ${uploadResponse.statusText}`);
754
+ } else logger_default.debug(`File already exists in S3: ${key}`);
755
+ return key;
756
+ };
757
+ const readFile = async (file) => {
758
+ if (file instanceof File) {
759
+ const content = await file.arrayBuffer();
760
+ return {
761
+ fileName: file.name,
762
+ content: Buffer.from(content).toString("base64"),
763
+ mimeType: file.type
764
+ };
765
+ } else if (typeof file === "string") if (file.startsWith("http")) return await readFileContentFromURL(file);
766
+ else return await readFileContent(file);
767
+ throw new Error("Invalid file type");
768
+ };
769
+ const getFileDataAfterUploadingToS3 = async (file, { toolSlug, toolkitSlug, client }) => {
770
+ if (!file) throw new Error("Either path or blob must be provided");
771
+ const fileData = await readFile(file);
772
+ logger_default.debug(`Uploading file to S3...`);
773
+ const s3key = await uploadFileToS3(platform.basename(fileData.fileName), fileData.content, toolSlug, toolkitSlug, fileData.mimeType, client);
774
+ logger_default.debug(`Done! File uploaded to S3: ${s3key}`, JSON.stringify(fileData, null, 2));
775
+ return {
776
+ name: fileData.fileName,
777
+ mimetype: fileData.mimeType,
778
+ s3key
779
+ };
780
+ };
781
+ const downloadFileFromS3 = async ({ toolSlug, s3Url, mimeType }) => {
782
+ const response = await fetch(s3Url);
783
+ if (!response.ok) throw new Error(`Failed to download file: ${response.statusText}`);
784
+ const data = await response.arrayBuffer();
785
+ const fileName = generateTimestampedFilename(getExtensionFromMimeType(mimeType), `${toolSlug}_`);
786
+ return {
787
+ name: fileName,
788
+ mimeType,
789
+ s3Url,
790
+ filePath: saveFile(fileName, Buffer.from(data), true)
791
+ };
792
+ };
793
+ /**
794
+ * Gets the Composio directory.
795
+ * @param createDirIfNotExists - Whether to create the directory if it doesn't exist.
796
+ * @returns The path to the Composio directory.
797
+ */
798
+ const getComposioDir = (createDirIfNotExists = false) => {
799
+ try {
800
+ const homeDir = platform.homedir();
801
+ if (!homeDir) return null;
802
+ const composioDir = platform.joinPath(homeDir, COMPOSIO_DIR);
803
+ if (createDirIfNotExists && platform.supportsFileSystem && !platform.existsSync(composioDir)) platform.mkdirSync(composioDir);
804
+ return composioDir;
805
+ } catch (_error) {
806
+ return null;
807
+ }
808
+ };
809
+ /**
810
+ * Gets the Composio temporary files directory.
811
+ * @param createDirIfNotExists - Whether to create the directory if it doesn't exist.
812
+ * @returns The path to the Composio temporary files directory.
813
+ */
814
+ const getComposioTempFilesDir = (createDirIfNotExists = false) => {
815
+ try {
816
+ const homeDir = platform.homedir();
817
+ if (!homeDir) return null;
818
+ const composioFilesDir = platform.joinPath(homeDir, COMPOSIO_DIR, TEMP_FILES_DIRECTORY_NAME);
819
+ if (createDirIfNotExists && platform.supportsFileSystem && !platform.existsSync(composioFilesDir)) platform.mkdirSync(composioFilesDir);
820
+ return composioFilesDir;
821
+ } catch (_error) {
822
+ return null;
823
+ }
824
+ };
825
+ /**
826
+ * Saves a file to the Composio directory.
827
+ * @param file - The name of the file to save.
828
+ * @param content - The content of the file to save. Can be a string or Buffer.
829
+ * @param isTempFile - Whether the file is a temporary file.
830
+ * @returns The path to the saved file.
831
+ */
832
+ const saveFile = (file, content, isTempFile = false) => {
833
+ try {
834
+ if (!platform.supportsFileSystem) {
835
+ logger_default.debug("File system operations are not supported in this runtime environment");
836
+ return null;
837
+ }
838
+ const composioFilesDir = isTempFile ? getComposioTempFilesDir(true) : getComposioDir(true);
839
+ if (!composioFilesDir) return null;
840
+ const filePath = platform.joinPath(composioFilesDir, platform.basename(file));
841
+ logger_default.info(`Saving file to: ${filePath}`);
842
+ if (Buffer.isBuffer(content)) platform.writeFileSync(filePath, content);
843
+ else platform.writeFileSync(filePath, content, "utf8");
844
+ return filePath;
845
+ } catch (_error) {
846
+ logger_default.debug(`Error saving file: ${_error}`);
847
+ return null;
848
+ }
849
+ };
850
+
851
+ //#endregion
852
+ export { logger_default as a, DEFAULT_BASE_URL as c, constants_exports as d, getEnvVariable as f, ComposioError$1 as i, IS_DEVELOPMENT_OR_CI as l, getFileDataAfterUploadingToS3 as n, COMPOSIO_DIR as o, getEnvsWithPrefix as p, telemetry as r, COMPOSIO_LOG_LEVEL as s, downloadFileFromS3 as t, USER_DATA_FILE_NAME as u };