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