@composio/core 0.1.12-alpha.9 → 0.1.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -3
- package/dist/index.cjs +2714 -1241
- package/dist/index.d.cts +1304 -296
- package/dist/index.d.ts +1304 -296
- package/dist/index.js +2686 -1238
- package/package.json +6 -3
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
|
|
9
|
+
import ComposioClient3 from "@composio/client";
|
|
10
10
|
|
|
11
11
|
// src/types/tool.types.ts
|
|
12
12
|
import { z } from "zod";
|
|
@@ -15,12 +15,38 @@ var ToolkitSchema = z.object({
|
|
|
15
15
|
name: z.string().describe("The name of the toolkit"),
|
|
16
16
|
logo: z.string().describe("The logo of the toolkit").optional()
|
|
17
17
|
});
|
|
18
|
+
var JSONSchemaType = z.enum([
|
|
19
|
+
"string",
|
|
20
|
+
"number",
|
|
21
|
+
"integer",
|
|
22
|
+
"boolean",
|
|
23
|
+
"object",
|
|
24
|
+
"array",
|
|
25
|
+
"null"
|
|
26
|
+
]);
|
|
27
|
+
var JSONSchemaProperty = z.object({
|
|
28
|
+
type: JSONSchemaType.optional(),
|
|
29
|
+
description: z.string().optional(),
|
|
30
|
+
title: z.string().optional(),
|
|
31
|
+
default: z.any().optional(),
|
|
32
|
+
properties: z.lazy(() => z.record(z.string(), JSONSchemaProperty)).optional(),
|
|
33
|
+
required: z.array(z.string()).optional(),
|
|
34
|
+
items: z.lazy(() => JSONSchemaProperty).optional()
|
|
35
|
+
});
|
|
36
|
+
var ParametersSchema = z.object({
|
|
37
|
+
type: z.literal("object"),
|
|
38
|
+
properties: z.record(z.string(), JSONSchemaProperty),
|
|
39
|
+
required: z.array(z.string()).optional(),
|
|
40
|
+
title: z.string().optional(),
|
|
41
|
+
description: z.string().optional(),
|
|
42
|
+
additionalProperties: z.boolean().optional()
|
|
43
|
+
});
|
|
18
44
|
var ToolSchema = z.object({
|
|
19
45
|
slug: z.string().describe('The slug of the tool. eg. "GOOGLE_SEARCH"'),
|
|
20
46
|
name: z.string().describe(`The name of the tool. eg. "Google Search"`),
|
|
21
47
|
description: z.string().optional().describe("The description of the tool"),
|
|
22
|
-
inputParameters:
|
|
23
|
-
outputParameters:
|
|
48
|
+
inputParameters: ParametersSchema.optional().describe("The input parameters of the tool"),
|
|
49
|
+
outputParameters: ParametersSchema.optional().describe("The output parameters of the tool"),
|
|
24
50
|
tags: z.optional(z.array(z.string())).describe("The tags of the tool. eg: Important").default([]),
|
|
25
51
|
toolkit: z.optional(ToolkitSchema).describe("The toolkit of the tool"),
|
|
26
52
|
version: z.optional(z.string()).describe('The version of the tool, e.g. "1.0.0"')
|
|
@@ -30,14 +56,27 @@ var ToolListResponseSchema = z.object({
|
|
|
30
56
|
nextCursor: z.string().nullable().optional(),
|
|
31
57
|
totalPages: z.number()
|
|
32
58
|
});
|
|
33
|
-
var
|
|
34
|
-
tools: z.array(z.string())
|
|
59
|
+
var ToolListFilterByToolsSchema = z.object({
|
|
60
|
+
tools: z.array(z.string())
|
|
61
|
+
});
|
|
62
|
+
var ToolListFilterByToolkitsSchema = z.object({
|
|
63
|
+
toolkits: z.array(z.string()),
|
|
64
|
+
important: z.boolean().optional(),
|
|
65
|
+
cursor: z.string().optional(),
|
|
66
|
+
limit: z.number().optional(),
|
|
67
|
+
search: z.string().optional()
|
|
68
|
+
});
|
|
69
|
+
var ToolListFilterBySearchSchema = z.object({
|
|
70
|
+
search: z.string(),
|
|
71
|
+
toolkits: z.array(z.string()).optional(),
|
|
35
72
|
cursor: z.string().optional(),
|
|
36
|
-
|
|
37
|
-
limit: z.string().optional(),
|
|
38
|
-
search: z.string().optional(),
|
|
39
|
-
toolkits: z.array(z.string()).optional()
|
|
73
|
+
limit: z.number().optional()
|
|
40
74
|
});
|
|
75
|
+
var ToolListParamsSchema = z.union([
|
|
76
|
+
ToolListFilterByToolsSchema,
|
|
77
|
+
ToolListFilterByToolkitsSchema,
|
|
78
|
+
ToolListFilterBySearchSchema
|
|
79
|
+
]);
|
|
41
80
|
var CustomAuthParamsSchema = z.object({
|
|
42
81
|
baseURL: z.string().optional(),
|
|
43
82
|
body: z.record(z.string(), z.unknown()).optional(),
|
|
@@ -65,16 +104,31 @@ var ToolExecuteResponseSchema = z.object({
|
|
|
65
104
|
logId: z.string().optional(),
|
|
66
105
|
sessionInfo: z.unknown().optional()
|
|
67
106
|
});
|
|
107
|
+
var ToolProxyParamsSchema = z.object({
|
|
108
|
+
endpoint: z.string(),
|
|
109
|
+
method: z.enum(["GET", "POST", "PUT", "DELETE", "PATCH"]),
|
|
110
|
+
body: z.unknown().optional(),
|
|
111
|
+
parameters: z.array(
|
|
112
|
+
z.object({
|
|
113
|
+
in: z.enum(["query", "header"]),
|
|
114
|
+
name: z.string(),
|
|
115
|
+
value: z.union([z.string(), z.number()])
|
|
116
|
+
})
|
|
117
|
+
),
|
|
118
|
+
connectedAccountId: z.string().optional()
|
|
119
|
+
});
|
|
68
120
|
|
|
69
121
|
// src/models/CustomTools.ts
|
|
70
122
|
import zodToJsonSchema from "zod-to-json-schema";
|
|
71
123
|
|
|
124
|
+
// src/utils/logger.ts
|
|
125
|
+
import chalk from "chalk";
|
|
126
|
+
|
|
72
127
|
// src/utils/env.ts
|
|
73
128
|
var getEnvVariable = (name, defaultValue = void 0) => {
|
|
74
129
|
try {
|
|
75
130
|
return process.env[name] || defaultValue;
|
|
76
131
|
} catch (_e) {
|
|
77
|
-
logger_default.error(`Error getting environment variable ${name}:`, _e);
|
|
78
132
|
return defaultValue;
|
|
79
133
|
}
|
|
80
134
|
};
|
|
@@ -93,7 +147,7 @@ var LOG_LEVELS = {
|
|
|
93
147
|
// Debug information
|
|
94
148
|
};
|
|
95
149
|
var getLogLevel = () => {
|
|
96
|
-
const envLevel = getEnvVariable("
|
|
150
|
+
const envLevel = getEnvVariable("COMPOSIO_LOG_LEVEL", "info")?.toLowerCase();
|
|
97
151
|
return envLevel && envLevel in LOG_LEVELS ? envLevel : "info";
|
|
98
152
|
};
|
|
99
153
|
var Logger = class {
|
|
@@ -106,12 +160,25 @@ var Logger = class {
|
|
|
106
160
|
this.console = console;
|
|
107
161
|
}
|
|
108
162
|
formatMessage(args) {
|
|
109
|
-
const formattedArgs = args.map((arg) =>
|
|
163
|
+
const formattedArgs = args.map((arg, index) => {
|
|
164
|
+
if (typeof arg === "object") {
|
|
165
|
+
return JSON.stringify(arg);
|
|
166
|
+
} else {
|
|
167
|
+
if (index === 0) {
|
|
168
|
+
if (args.length > 1) {
|
|
169
|
+
return chalk.yellow(`${arg}`);
|
|
170
|
+
} else {
|
|
171
|
+
return String(arg);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
return String(arg);
|
|
175
|
+
}
|
|
176
|
+
}).join("\n");
|
|
110
177
|
if (!this.includeTimestamp) {
|
|
111
178
|
return formattedArgs;
|
|
112
179
|
}
|
|
113
180
|
const timestamp = (/* @__PURE__ */ new Date()).toISOString();
|
|
114
|
-
return `${timestamp} - ${formattedArgs}`;
|
|
181
|
+
return `${chalk.gray(timestamp)} - ${formattedArgs}`;
|
|
115
182
|
}
|
|
116
183
|
shouldLog(level) {
|
|
117
184
|
return LOG_LEVELS[level] <= LOG_LEVELS[this.level];
|
|
@@ -141,34 +208,240 @@ var logger = new Logger();
|
|
|
141
208
|
var logger_default = logger;
|
|
142
209
|
|
|
143
210
|
// src/errors/ComposioError.ts
|
|
144
|
-
|
|
211
|
+
import chalk2 from "chalk";
|
|
212
|
+
import { ZodError } from "zod";
|
|
213
|
+
import { BadRequestError } from "@composio/client";
|
|
214
|
+
var ComposioError = class _ComposioError extends Error {
|
|
215
|
+
/** @readonly Error name */
|
|
145
216
|
name = "ComposioError";
|
|
146
217
|
code;
|
|
147
|
-
statusCode;
|
|
148
|
-
cause;
|
|
149
|
-
meta;
|
|
150
218
|
possibleFixes;
|
|
219
|
+
errorId;
|
|
220
|
+
/**
|
|
221
|
+
* Creates a new ComposioError
|
|
222
|
+
* @param message Error message
|
|
223
|
+
* @param options Additional error options
|
|
224
|
+
*/
|
|
151
225
|
constructor(message, options = {}) {
|
|
152
226
|
super(message);
|
|
153
|
-
this.code = options.code;
|
|
154
|
-
this.statusCode = options.statusCode;
|
|
155
|
-
this.cause = options.cause;
|
|
156
|
-
this.meta = options.meta;
|
|
157
|
-
this.possibleFixes = options.possibleFixes;
|
|
158
227
|
if (Error.captureStackTrace) {
|
|
159
228
|
Error.captureStackTrace(this, this.constructor);
|
|
160
229
|
}
|
|
230
|
+
const statusCode = options.statusCode || (options.cause instanceof BadRequestError ? options.cause.status : void 0);
|
|
231
|
+
this.code = `TS-SDK::${options.code}`;
|
|
232
|
+
this.possibleFixes = options.possibleFixes;
|
|
233
|
+
this.definePropertyIfExists("statusCode", statusCode);
|
|
234
|
+
this.definePropertyIfExists("cause", options.cause);
|
|
235
|
+
const combinedStack = options.cause instanceof Error ? _ComposioError.combineStackTraces(options.cause.stack, this.stack) : options.stack ?? this.stack;
|
|
236
|
+
this.definePropertyIfExists("stack", combinedStack);
|
|
237
|
+
if (options.meta && Object.keys(options.meta).length > 0) {
|
|
238
|
+
this.definePropertyIfExists("meta", options.meta);
|
|
239
|
+
}
|
|
161
240
|
}
|
|
162
|
-
|
|
163
|
-
|
|
241
|
+
/**
|
|
242
|
+
* Helper method to define a property only if it has a value
|
|
243
|
+
* @param propertyName Name of the property to define
|
|
244
|
+
* @param value Value to assign to the property
|
|
245
|
+
* @private
|
|
246
|
+
*/
|
|
247
|
+
definePropertyIfExists(propertyName, value) {
|
|
248
|
+
if (value !== void 0) {
|
|
249
|
+
Object.defineProperty(this, propertyName, {
|
|
250
|
+
value,
|
|
251
|
+
enumerable: true,
|
|
252
|
+
writable: false,
|
|
253
|
+
configurable: true
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
/**
|
|
258
|
+
* Helper method to combine stack traces when wrapping errors
|
|
259
|
+
* This ensures the full call chain is preserved
|
|
260
|
+
* @param originalStack The stack of the error being wrapped
|
|
261
|
+
* @param currentStack The stack of the wrapper error
|
|
262
|
+
* @returns Combined stack trace
|
|
263
|
+
* @private
|
|
264
|
+
*/
|
|
265
|
+
static combineStackTraces(originalStack, currentStack) {
|
|
266
|
+
if (!originalStack) return currentStack;
|
|
267
|
+
if (!currentStack) return originalStack;
|
|
268
|
+
const currentHeader = currentStack.split("\n")[0];
|
|
269
|
+
const originalStackBody = originalStack.split("\n").slice(1).join("\n");
|
|
270
|
+
return `${currentHeader}
|
|
271
|
+
${currentStack.split("\n").slice(1).join("\n")}
|
|
272
|
+
|
|
273
|
+
Caused by:
|
|
274
|
+
${originalStackBody}`;
|
|
275
|
+
}
|
|
276
|
+
/**
|
|
277
|
+
* Extract and normalize error data for formatting
|
|
278
|
+
* @param includeStack Whether to include stack trace information
|
|
279
|
+
* @returns Structured error data for formatting
|
|
280
|
+
* @private
|
|
281
|
+
*/
|
|
282
|
+
getErrorData(includeStack = false) {
|
|
283
|
+
const data = {
|
|
164
284
|
name: this.name,
|
|
165
|
-
message: this.message
|
|
166
|
-
code: this.code,
|
|
167
|
-
statusCode: this.statusCode,
|
|
168
|
-
cause: this.cause instanceof Error ? this.cause.message : this.cause,
|
|
169
|
-
meta: this.meta,
|
|
170
|
-
possibleFixes: this.possibleFixes?.length ? this.possibleFixes.join("\n") : void 0
|
|
285
|
+
message: this.message
|
|
171
286
|
};
|
|
287
|
+
const { cause, code, stack, statusCode, meta, possibleFixes } = this;
|
|
288
|
+
if (cause !== void 0) {
|
|
289
|
+
const rawCause = cause;
|
|
290
|
+
data.cause = rawCause instanceof Error ? rawCause.message : String(rawCause);
|
|
291
|
+
}
|
|
292
|
+
if (code) {
|
|
293
|
+
data.code = code;
|
|
294
|
+
}
|
|
295
|
+
if (statusCode !== void 0) {
|
|
296
|
+
data.statusCode = statusCode;
|
|
297
|
+
}
|
|
298
|
+
if (meta) {
|
|
299
|
+
data.meta = meta;
|
|
300
|
+
}
|
|
301
|
+
if (possibleFixes) {
|
|
302
|
+
data.possibleFixes = possibleFixes;
|
|
303
|
+
}
|
|
304
|
+
if (includeStack && stack) {
|
|
305
|
+
if (stack.includes("Caused by:")) {
|
|
306
|
+
const [currentStack, causeStack] = stack.split("Caused by:");
|
|
307
|
+
data.stack = [
|
|
308
|
+
...currentStack.split("\n").slice(1),
|
|
309
|
+
"Caused by:",
|
|
310
|
+
...causeStack.split("\n")
|
|
311
|
+
];
|
|
312
|
+
} else {
|
|
313
|
+
data.stack = stack.split("\n").slice(1);
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
return data;
|
|
317
|
+
}
|
|
318
|
+
/**
|
|
319
|
+
* Prints a user-friendly, colorful representation of the error to the logger
|
|
320
|
+
* @param includeStack Whether to include the stack trace in the output (default: false)
|
|
321
|
+
*/
|
|
322
|
+
prettyPrint(includeStack = false) {
|
|
323
|
+
const data = this.getErrorData(includeStack);
|
|
324
|
+
let output = "\n" + chalk2.bgRed.white.bold(" ERROR ") + " " + chalk2.white.bold(data.message) + "\n";
|
|
325
|
+
if (data.code) {
|
|
326
|
+
output += chalk2.yellow(`Error Code: ${data.code}`) + "\n";
|
|
327
|
+
}
|
|
328
|
+
if (data.statusCode !== void 0) {
|
|
329
|
+
output += chalk2.yellow(`Status: ${data.statusCode}`) + "\n";
|
|
330
|
+
}
|
|
331
|
+
if (data.cause) {
|
|
332
|
+
output += chalk2.gray("Reason:") + "\n";
|
|
333
|
+
output += " " + chalk2.white(data.cause) + "\n";
|
|
334
|
+
}
|
|
335
|
+
if (data.meta) {
|
|
336
|
+
output += chalk2.gray("Additional Information:") + "\n";
|
|
337
|
+
output += " " + chalk2.white(JSON.stringify(data.meta, null, 2).replace(/\n/g, "\n ")) + "\n";
|
|
338
|
+
}
|
|
339
|
+
if (data.possibleFixes?.length) {
|
|
340
|
+
output += "\n" + chalk2.cyan.bold("Try the following:") + "\n";
|
|
341
|
+
const fixes = data.possibleFixes?.map((fix, index) => ` ${index + 1}. ` + chalk2.white(fix));
|
|
342
|
+
output += fixes?.join("\n") + "\n";
|
|
343
|
+
}
|
|
344
|
+
if (data.stack?.length) {
|
|
345
|
+
output += "\n" + chalk2.gray("Stack Trace:") + "\n";
|
|
346
|
+
output += chalk2.gray(data.stack.join("\n")) + "\n";
|
|
347
|
+
}
|
|
348
|
+
output += "\n";
|
|
349
|
+
logger_default.error(output);
|
|
350
|
+
}
|
|
351
|
+
/**
|
|
352
|
+
* Static factory method to create and pretty print an error in one step
|
|
353
|
+
* @param message Error message
|
|
354
|
+
* @param options Error options
|
|
355
|
+
* @param includeStack Whether to include the stack trace in the output
|
|
356
|
+
* @returns The created error instance
|
|
357
|
+
*/
|
|
358
|
+
static createAndPrint(message, options = {}, includeStack = false) {
|
|
359
|
+
const error = new _ComposioError(message, options);
|
|
360
|
+
error.prettyPrint(includeStack);
|
|
361
|
+
return error;
|
|
362
|
+
}
|
|
363
|
+
/**
|
|
364
|
+
* Utility function to handle errors in a consistent way
|
|
365
|
+
* This properly displays the error and exits the process if needed
|
|
366
|
+
* @param error The error to handle
|
|
367
|
+
* @param options Options for error handling
|
|
368
|
+
*/
|
|
369
|
+
static handle(error, options = {}) {
|
|
370
|
+
const { includeStack = false, exitProcess = false, exitCode = 1 } = options;
|
|
371
|
+
if (error instanceof _ComposioError) {
|
|
372
|
+
error.prettyPrint(includeStack);
|
|
373
|
+
} else if (error instanceof ZodError) {
|
|
374
|
+
this.handleZodError(error, includeStack);
|
|
375
|
+
} else if (error instanceof Error) {
|
|
376
|
+
this.handleStandardError(error, includeStack);
|
|
377
|
+
} else {
|
|
378
|
+
this.handleUnknownError(error);
|
|
379
|
+
}
|
|
380
|
+
if (exitProcess && typeof process !== "undefined") {
|
|
381
|
+
process.exit(exitCode);
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
/**
|
|
385
|
+
* Helper method to handle Zod validation errors
|
|
386
|
+
* @param error The Zod error to handle
|
|
387
|
+
* @param includeStack Whether to include the stack trace
|
|
388
|
+
* @private
|
|
389
|
+
*/
|
|
390
|
+
static handleZodError(error, includeStack) {
|
|
391
|
+
logger_default.error("\n" + chalk2.bgRed.white.bold(" ERROR ") + " " + chalk2.white.bold(error.message));
|
|
392
|
+
logger_default.error(chalk2.gray("Invalid parameters:"));
|
|
393
|
+
error.errors.forEach((err) => {
|
|
394
|
+
logger_default.error(chalk2.yellow(err.path.join(".")) + " " + chalk2.white(err.message));
|
|
395
|
+
});
|
|
396
|
+
logger_default.error(chalk2.gray("Expected parameters:"));
|
|
397
|
+
error.errors.forEach((err) => {
|
|
398
|
+
logger_default.error(chalk2.yellow(err.path.join(".")) + " " + chalk2.white(err.message));
|
|
399
|
+
});
|
|
400
|
+
if (includeStack) {
|
|
401
|
+
logger_default.error("\n" + chalk2.gray("Validation Errors:"));
|
|
402
|
+
error.errors.forEach((err) => {
|
|
403
|
+
const path = err.path.join(".");
|
|
404
|
+
logger_default.error(
|
|
405
|
+
chalk2.gray(" \u2022 ") + chalk2.yellow(path ? `${path}: ` : "") + chalk2.white(err.message)
|
|
406
|
+
);
|
|
407
|
+
});
|
|
408
|
+
if (error.stack) {
|
|
409
|
+
logger_default.error("\n" + chalk2.gray("Stack Trace:"));
|
|
410
|
+
const stackLines = error.stack.split("\n").slice(1);
|
|
411
|
+
logger_default.error(chalk2.gray(stackLines.join("\n")));
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
logger_default.error("");
|
|
415
|
+
}
|
|
416
|
+
/**
|
|
417
|
+
* Helper method to handle standard Error objects
|
|
418
|
+
* @param error The standard error to handle
|
|
419
|
+
* @param includeStack Whether to include the stack trace
|
|
420
|
+
* @private
|
|
421
|
+
*/
|
|
422
|
+
static handleStandardError(error, includeStack) {
|
|
423
|
+
logger_default.error("\n" + chalk2.bgRed.white.bold(" ERROR ") + " " + chalk2.white.bold(error.message));
|
|
424
|
+
if (includeStack && error.stack) {
|
|
425
|
+
logger_default.error("\n" + chalk2.gray("Stack Trace:"));
|
|
426
|
+
const stackLines = error.stack.split("\n").slice(1);
|
|
427
|
+
logger_default.error(chalk2.gray(stackLines.join("\n")));
|
|
428
|
+
}
|
|
429
|
+
logger_default.error("");
|
|
430
|
+
}
|
|
431
|
+
/**
|
|
432
|
+
* Helper method to handle unknown error types
|
|
433
|
+
* @param error The unknown error value
|
|
434
|
+
* @private
|
|
435
|
+
*/
|
|
436
|
+
static handleUnknownError(error) {
|
|
437
|
+
logger_default.error(
|
|
438
|
+
"\n" + chalk2.bgRed.white.bold(" ERROR ") + " " + chalk2.white.bold("Unknown error occurred")
|
|
439
|
+
);
|
|
440
|
+
if (error !== null && error !== void 0) {
|
|
441
|
+
logger_default.error(chalk2.gray("Error details:"));
|
|
442
|
+
logger_default.error(" " + chalk2.white(String(error)));
|
|
443
|
+
}
|
|
444
|
+
logger_default.error("");
|
|
172
445
|
}
|
|
173
446
|
};
|
|
174
447
|
|
|
@@ -183,11 +456,11 @@ var ToolErrorCodes = {
|
|
|
183
456
|
GLOBAL_EXECUTE_TOOL_FN_NOT_SET: "GLOBAL_EXECUTE_TOOL_FN_NOT_SET"
|
|
184
457
|
};
|
|
185
458
|
var ComposioProviderNotDefinedError = class extends ComposioError {
|
|
186
|
-
constructor(message = "Provider not defined",
|
|
459
|
+
constructor(message = "Provider not defined", options = {}) {
|
|
187
460
|
super(message, {
|
|
461
|
+
...options,
|
|
188
462
|
code: ToolErrorCodes.TOOLSET_NOT_DEFINED,
|
|
189
|
-
|
|
190
|
-
possibleFixes: [
|
|
463
|
+
possibleFixes: options.possibleFixes || [
|
|
191
464
|
"Ensure that the provider is defined in the Composio project and passed into the tool instance"
|
|
192
465
|
]
|
|
193
466
|
});
|
|
@@ -195,281 +468,948 @@ var ComposioProviderNotDefinedError = class extends ComposioError {
|
|
|
195
468
|
}
|
|
196
469
|
};
|
|
197
470
|
var ComposioToolNotFoundError = class extends ComposioError {
|
|
198
|
-
constructor(message = "Tool not found",
|
|
471
|
+
constructor(message = "Tool not found", options = {}) {
|
|
199
472
|
super(message, {
|
|
473
|
+
...options,
|
|
200
474
|
code: ToolErrorCodes.TOOL_NOT_FOUND,
|
|
201
|
-
|
|
202
|
-
|
|
475
|
+
possibleFixes: options.possibleFixes || [
|
|
476
|
+
"Ensure the tool slug is correct and exists in the Composio project"
|
|
477
|
+
]
|
|
203
478
|
});
|
|
204
479
|
this.name = "ComposioToolNotFoundError";
|
|
205
480
|
}
|
|
206
481
|
};
|
|
207
482
|
var ComposioInvalidModifierError = class extends ComposioError {
|
|
208
|
-
constructor(message = "Invalid modifier",
|
|
483
|
+
constructor(message = "Invalid modifier", options = {}) {
|
|
209
484
|
super(message, {
|
|
485
|
+
...options,
|
|
210
486
|
code: ToolErrorCodes.INVALID_MODIFIER,
|
|
211
|
-
|
|
212
|
-
|
|
487
|
+
possibleFixes: options.possibleFixes || [
|
|
488
|
+
"Ensure the modifier is a function and returns a valid result"
|
|
489
|
+
]
|
|
213
490
|
});
|
|
214
491
|
this.name = "ComposioInvalidModifierError";
|
|
215
492
|
}
|
|
216
493
|
};
|
|
217
494
|
var ComposioCustomToolsNotInitializedError = class extends ComposioError {
|
|
218
|
-
constructor(message = "Custom tools not initialized",
|
|
495
|
+
constructor(message = "Custom tools not initialized", options = {}) {
|
|
219
496
|
super(message, {
|
|
497
|
+
...options,
|
|
220
498
|
code: ToolErrorCodes.CUSTOM_TOOLS_NOT_INITIALIZED,
|
|
221
|
-
|
|
222
|
-
|
|
499
|
+
possibleFixes: options.possibleFixes || [
|
|
500
|
+
"Ensure the custom tools class is initialized in the Tools instance"
|
|
501
|
+
]
|
|
223
502
|
});
|
|
224
503
|
this.name = "ComposioCustomToolsNotInitializedError";
|
|
225
504
|
}
|
|
226
505
|
};
|
|
227
506
|
var ComposioToolExecutionError = class extends ComposioError {
|
|
228
507
|
error;
|
|
229
|
-
constructor(
|
|
508
|
+
constructor(message = "Tool execution error", options = {}) {
|
|
509
|
+
const { originalError, ...restOptions } = options;
|
|
230
510
|
super(message, {
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
possibleFixes:
|
|
511
|
+
...restOptions,
|
|
512
|
+
code: options.code || ToolErrorCodes.TOOL_EXECUTION_ERROR,
|
|
513
|
+
cause: options.cause || originalError,
|
|
514
|
+
possibleFixes: options.possibleFixes || [
|
|
515
|
+
"Ensure the tool is correctly configured and the input is valid"
|
|
516
|
+
]
|
|
235
517
|
});
|
|
236
|
-
this.error = error;
|
|
518
|
+
this.error = originalError || (options.cause instanceof Error ? options.cause : options.cause ? new Error(String(options.cause)) : new Error("Unknown error"));
|
|
237
519
|
this.name = "ComposioToolExecutionError";
|
|
238
520
|
}
|
|
239
521
|
};
|
|
240
522
|
var ComposioInvalidExecuteFunctionError = class extends ComposioError {
|
|
241
|
-
constructor(message = "Invalid execute function",
|
|
523
|
+
constructor(message = "Invalid execute function", options = {}) {
|
|
242
524
|
super(message, {
|
|
525
|
+
...options,
|
|
243
526
|
code: ToolErrorCodes.INVALID_EXECUTE_FUNCTION,
|
|
244
|
-
|
|
245
|
-
|
|
527
|
+
possibleFixes: options.possibleFixes || [
|
|
528
|
+
"Ensure the execute function is a valid function and returns a valid result"
|
|
529
|
+
]
|
|
246
530
|
});
|
|
247
531
|
this.name = "ComposioInvalidExecuteFunctionError";
|
|
248
532
|
}
|
|
249
533
|
};
|
|
250
534
|
var ComposioGlobalExecuteToolFnNotSetError = class extends ComposioError {
|
|
251
|
-
constructor(message = "Global execute tool function not set",
|
|
535
|
+
constructor(message = "Global execute tool function not set", options = {}) {
|
|
252
536
|
super(message, {
|
|
537
|
+
...options,
|
|
253
538
|
code: ToolErrorCodes.GLOBAL_EXECUTE_TOOL_FN_NOT_SET,
|
|
254
|
-
|
|
255
|
-
|
|
539
|
+
possibleFixes: options.possibleFixes || [
|
|
540
|
+
"Ensure the global execute tool function is set in the provider"
|
|
541
|
+
]
|
|
256
542
|
});
|
|
257
543
|
this.name = "ComposioGlobalExecuteToolFnNotSetError";
|
|
258
544
|
}
|
|
259
545
|
};
|
|
260
546
|
|
|
261
|
-
// src/errors/
|
|
547
|
+
// src/errors/ConnectedAccountsErrors.ts
|
|
262
548
|
var ConnectedAccountErrorCodes = {
|
|
263
549
|
CONNECTED_ACCOUNT_NOT_FOUND: "CONNECTED_ACCOUNT_NOT_FOUND"
|
|
264
550
|
};
|
|
265
551
|
var ComposioConnectedAccountNotFoundError = class extends ComposioError {
|
|
266
|
-
constructor(message = "Connected account not found",
|
|
552
|
+
constructor(message = "Connected account not found", options = {}) {
|
|
267
553
|
super(message, {
|
|
554
|
+
...options,
|
|
268
555
|
code: ConnectedAccountErrorCodes.CONNECTED_ACCOUNT_NOT_FOUND,
|
|
269
556
|
statusCode: 404,
|
|
270
|
-
|
|
271
|
-
possibleFixes: [
|
|
557
|
+
possibleFixes: options.possibleFixes || [
|
|
272
558
|
"Ensure the connected account exists and is active in your Composio dashboard"
|
|
273
559
|
]
|
|
274
560
|
});
|
|
561
|
+
this.name = "ComposioConnectedAccountNotFoundError";
|
|
275
562
|
}
|
|
276
563
|
};
|
|
277
564
|
|
|
278
|
-
// src/
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
inputParameters: {
|
|
309
|
-
title: name,
|
|
310
|
-
type: "object",
|
|
311
|
-
description,
|
|
312
|
-
properties: paramsSchemaJson.properties,
|
|
313
|
-
required: paramsSchemaJson.required
|
|
314
|
-
},
|
|
315
|
-
// the output parameters are not used yet
|
|
316
|
-
outputParameters: {
|
|
317
|
-
type: "object",
|
|
318
|
-
title: `Response for ${name}`,
|
|
319
|
-
properties: []
|
|
320
|
-
},
|
|
321
|
-
tags: [],
|
|
322
|
-
toolkit: { name: "custom", slug: "custom" }
|
|
323
|
-
};
|
|
324
|
-
this.customToolsRegistry.set(slug.toLowerCase(), {
|
|
325
|
-
options: toolOptions,
|
|
326
|
-
schema: toolSchema
|
|
327
|
-
});
|
|
328
|
-
return toolSchema;
|
|
565
|
+
// src/telemetry/Telemetry.ts
|
|
566
|
+
import { ComposioError as ComposioClientError } from "@composio/client";
|
|
567
|
+
|
|
568
|
+
// src/types/telemetry.types.ts
|
|
569
|
+
var TELEMETRY_EVENTS = {
|
|
570
|
+
SDK_INITIALIZED: "SDK_INITIALIZED",
|
|
571
|
+
SDK_METHOD_INVOKED: "SDK_METHOD_INVOKED",
|
|
572
|
+
SDK_METHOD_ERROR: "SDK_METHOD_ERROR",
|
|
573
|
+
CLI_INVOKED: "CLI_INVOKED"
|
|
574
|
+
};
|
|
575
|
+
|
|
576
|
+
// src/utils/constants.ts
|
|
577
|
+
var COMPOSIO_DIR = ".composio";
|
|
578
|
+
var USER_DATA_FILE_NAME = "user_data.json";
|
|
579
|
+
var DEFAULT_BASE_URL = "https://backend.composio.dev";
|
|
580
|
+
var TELEMETRY_URL = "https://app.composio.dev";
|
|
581
|
+
var IS_DEVELOPMENT_OR_CI = process.env.DEVELOPMENT || process.env.CI || false;
|
|
582
|
+
|
|
583
|
+
// src/telemetry/BatchProcessor.ts
|
|
584
|
+
var BatchProcessor = class {
|
|
585
|
+
batch = [];
|
|
586
|
+
time;
|
|
587
|
+
batchSize;
|
|
588
|
+
processBatchCallback;
|
|
589
|
+
timer = null;
|
|
590
|
+
constructor(time = 2e3, batchSize = 100, processBatchCallback) {
|
|
591
|
+
this.batch = [];
|
|
592
|
+
this.time = time;
|
|
593
|
+
this.batchSize = batchSize;
|
|
594
|
+
this.processBatchCallback = processBatchCallback;
|
|
329
595
|
}
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
const tools = [];
|
|
337
|
-
if (toolSlugs) {
|
|
338
|
-
for (const slug of toolSlugs) {
|
|
339
|
-
const tool = this.customToolsRegistry.get(slug.toLowerCase());
|
|
340
|
-
if (tool) {
|
|
341
|
-
tools.push(tool.schema);
|
|
342
|
-
}
|
|
343
|
-
}
|
|
344
|
-
} else {
|
|
345
|
-
return Array.from(this.customToolsRegistry.values()).map((tool) => tool.schema);
|
|
596
|
+
pushItem(item) {
|
|
597
|
+
this.batch.push(item);
|
|
598
|
+
if (this.batch.length >= this.batchSize) {
|
|
599
|
+
this.processBatch();
|
|
600
|
+
} else if (!this.timer) {
|
|
601
|
+
this.timer = setTimeout(() => this.processBatch(), this.time);
|
|
346
602
|
}
|
|
347
|
-
return tools;
|
|
348
603
|
}
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
*/
|
|
354
|
-
async getCustomToolBySlug(slug) {
|
|
355
|
-
if (!slug) {
|
|
356
|
-
throw new Error("Tool slug is required");
|
|
604
|
+
processBatch() {
|
|
605
|
+
if (this.batch.length > 0) {
|
|
606
|
+
this.processBatchCallback(this.batch);
|
|
607
|
+
this.batch = [];
|
|
357
608
|
}
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
} catch (error) {
|
|
362
|
-
logger_default.error(`Error getting custom tool: ${error}`);
|
|
363
|
-
return void 0;
|
|
609
|
+
if (this.timer) {
|
|
610
|
+
clearTimeout(this.timer);
|
|
611
|
+
this.timer = null;
|
|
364
612
|
}
|
|
365
613
|
}
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
await this.client.toolkits.retrieve(toolkitSlug);
|
|
375
|
-
} catch (error) {
|
|
376
|
-
throw new ComposioToolNotFoundError(`Toolkit with slug ${toolkitSlug} not found`, {
|
|
377
|
-
toolkitSlug,
|
|
378
|
-
error
|
|
379
|
-
});
|
|
380
|
-
}
|
|
381
|
-
const connectedAccounts = await this.client.connectedAccounts.list({
|
|
382
|
-
toolkit_slugs: [toolkitSlug],
|
|
383
|
-
user_ids: [metadata.userId]
|
|
384
|
-
});
|
|
385
|
-
if (!connectedAccounts.items.length) {
|
|
386
|
-
throw new ComposioConnectedAccountNotFoundError(
|
|
387
|
-
`No connected accounts found for toolkit ${toolkitSlug}`,
|
|
388
|
-
{
|
|
389
|
-
toolkitSlug
|
|
390
|
-
}
|
|
614
|
+
};
|
|
615
|
+
|
|
616
|
+
// src/telemetry/transports/BrowserTransport.ts
|
|
617
|
+
var BrowserTelemetryTransport = class {
|
|
618
|
+
send(payload) {
|
|
619
|
+
if (typeof window === "undefined") {
|
|
620
|
+
return Promise.reject(
|
|
621
|
+
new Error("BrowserTelemetryTransport can only be used in browser environments")
|
|
391
622
|
);
|
|
392
623
|
}
|
|
393
|
-
return
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
624
|
+
return new Promise((resolve) => {
|
|
625
|
+
try {
|
|
626
|
+
const xhr = new XMLHttpRequest();
|
|
627
|
+
xhr.open(payload.method, payload.url, true);
|
|
628
|
+
xhr.setRequestHeader("Content-Type", "application/json");
|
|
629
|
+
Object.entries(payload.headers || {}).forEach(([key, value]) => {
|
|
630
|
+
xhr.setRequestHeader(key, value);
|
|
631
|
+
});
|
|
632
|
+
xhr.onload = function() {
|
|
633
|
+
resolve();
|
|
634
|
+
};
|
|
635
|
+
xhr.send(JSON.stringify(payload.data));
|
|
636
|
+
} catch (error) {
|
|
637
|
+
logger_default.error("Error sending error to telemetry", error);
|
|
638
|
+
resolve();
|
|
639
|
+
}
|
|
640
|
+
});
|
|
641
|
+
}
|
|
642
|
+
};
|
|
643
|
+
|
|
644
|
+
// src/telemetry/transports/ProcessTransport.ts
|
|
645
|
+
import chalk3 from "chalk";
|
|
646
|
+
var ProcessTelemetryTransport = class {
|
|
647
|
+
send(payload) {
|
|
648
|
+
if (typeof window !== "undefined") {
|
|
649
|
+
return Promise.reject(
|
|
650
|
+
new Error("ProcessTelemetryTransport can only be used in Node.js environments")
|
|
651
|
+
);
|
|
408
652
|
}
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
653
|
+
return new Promise((resolve) => {
|
|
654
|
+
try {
|
|
655
|
+
const url = new URL(payload.url);
|
|
656
|
+
const protocol = url.protocol === "https:" ? "https" : "http";
|
|
657
|
+
const port = url.port || (url.protocol === "https:" ? 443 : 80);
|
|
658
|
+
const args = [
|
|
659
|
+
"-e",
|
|
660
|
+
`
|
|
661
|
+
const http = require('${protocol}');
|
|
662
|
+
const options = {
|
|
663
|
+
hostname: '${url.hostname}',
|
|
664
|
+
path: '${url.pathname}${url.search}',
|
|
665
|
+
port: ${port},
|
|
666
|
+
method: '${payload.method}',
|
|
667
|
+
headers: ${JSON.stringify(payload.headers)}
|
|
668
|
+
};
|
|
669
|
+
|
|
670
|
+
const req = http.request(options, (res) => {
|
|
671
|
+
res.on('data', () => {});
|
|
672
|
+
res.on('end', () => {
|
|
673
|
+
process.exit(0);
|
|
674
|
+
});
|
|
675
|
+
});
|
|
676
|
+
|
|
677
|
+
req.on('error', () => {
|
|
678
|
+
process.exit(0);
|
|
679
|
+
});
|
|
680
|
+
|
|
681
|
+
req.write(JSON.stringify(${JSON.stringify(payload.data)}));
|
|
682
|
+
req.end();
|
|
683
|
+
`
|
|
684
|
+
];
|
|
685
|
+
import("child_process").then(({ spawn }) => {
|
|
686
|
+
spawn("node", args, {
|
|
687
|
+
stdio: "ignore",
|
|
688
|
+
detached: false,
|
|
689
|
+
shell: false
|
|
690
|
+
}).unref();
|
|
691
|
+
resolve();
|
|
692
|
+
}).catch((error) => {
|
|
693
|
+
logger_default.error("Error sending telemetry", error);
|
|
694
|
+
resolve();
|
|
695
|
+
});
|
|
696
|
+
logger_default.debug(chalk3.yellow("Process Telemetry"), JSON.stringify(payload, null, 2));
|
|
697
|
+
} catch (error) {
|
|
698
|
+
logger_default.error("Error sending telemetry", error);
|
|
699
|
+
resolve();
|
|
421
700
|
}
|
|
422
|
-
|
|
701
|
+
});
|
|
702
|
+
}
|
|
703
|
+
};
|
|
704
|
+
|
|
705
|
+
// src/utils/uuid.ts
|
|
706
|
+
import { v4 as uuidv4 } from "uuid";
|
|
707
|
+
function getRandomUUID() {
|
|
708
|
+
return uuidv4();
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
// src/telemetry/Telemetry.ts
|
|
712
|
+
var TelemetryService = class {
|
|
713
|
+
telemetryMetadata;
|
|
714
|
+
transport;
|
|
715
|
+
isTelemetryDisabled = true;
|
|
716
|
+
batchProcessor = new BatchProcessor(100, 10, async (data) => {
|
|
717
|
+
await this.sendTelemetry(data);
|
|
718
|
+
});
|
|
719
|
+
setup(metadata, transport) {
|
|
720
|
+
this.telemetryMetadata = metadata;
|
|
721
|
+
this.isTelemetryDisabled = false;
|
|
722
|
+
const isBrowser = typeof window !== "undefined";
|
|
723
|
+
if (transport) {
|
|
724
|
+
this.transport = transport;
|
|
725
|
+
} else if (isBrowser) {
|
|
726
|
+
this.transport = new BrowserTelemetryTransport();
|
|
727
|
+
this.telemetryMetadata.transport = "browser";
|
|
728
|
+
} else {
|
|
729
|
+
this.transport = new ProcessTelemetryTransport();
|
|
730
|
+
this.telemetryMetadata.transport = "process";
|
|
423
731
|
}
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
732
|
+
this.sendTelemetry([
|
|
733
|
+
{
|
|
734
|
+
eventName: TELEMETRY_EVENTS.SDK_INITIALIZED,
|
|
735
|
+
data: {}
|
|
736
|
+
}
|
|
737
|
+
]);
|
|
738
|
+
}
|
|
739
|
+
/**
|
|
740
|
+
* Instrument the telemetry for the given instance.
|
|
741
|
+
*
|
|
742
|
+
* You can pass the instance and the file name of the instance to instrument the telemetry.
|
|
743
|
+
* This will instrument all the methods of the instance and log the telemetry for each method call.
|
|
744
|
+
* @param instance - any instance that extends InstrumentedInstance
|
|
745
|
+
* @param fileName - the file name of the instance
|
|
746
|
+
* @returns
|
|
747
|
+
*/
|
|
748
|
+
instrument(instance, fileName) {
|
|
749
|
+
const proto = Object.getPrototypeOf(instance);
|
|
750
|
+
const methodNames = Object.getOwnPropertyNames(proto).filter((key) => {
|
|
751
|
+
const descriptor = Object.getOwnPropertyDescriptor(proto, key);
|
|
752
|
+
return key !== "constructor" && descriptor && typeof descriptor.value === "function" && descriptor.value.constructor.name === "AsyncFunction";
|
|
753
|
+
});
|
|
754
|
+
const instrumentedClassName = (instance.constructor?.name || fileName) ?? "unknown";
|
|
755
|
+
for (const name of methodNames) {
|
|
756
|
+
const originalMethod = instance[name];
|
|
757
|
+
instance[name] = async (...args) => {
|
|
758
|
+
const telemetryPayload = {
|
|
759
|
+
eventName: TELEMETRY_EVENTS.SDK_METHOD_INVOKED,
|
|
760
|
+
data: {
|
|
761
|
+
fileName: instrumentedClassName,
|
|
762
|
+
method: name,
|
|
763
|
+
params: args
|
|
764
|
+
}
|
|
765
|
+
};
|
|
766
|
+
this.batchProcessor.pushItem(telemetryPayload);
|
|
767
|
+
try {
|
|
768
|
+
return await originalMethod.apply(instance, args);
|
|
769
|
+
} catch (error) {
|
|
770
|
+
if (error instanceof Error) {
|
|
771
|
+
if (!error.errorId) {
|
|
772
|
+
error.errorId = getRandomUUID();
|
|
773
|
+
this.prepareAndSendErrorTelemetry(error, instrumentedClassName, name, args);
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
throw error;
|
|
777
|
+
}
|
|
778
|
+
};
|
|
428
779
|
}
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
780
|
+
return instance;
|
|
781
|
+
}
|
|
782
|
+
/**
|
|
783
|
+
* Check if the telemetry should be sent.
|
|
784
|
+
* @returns true if the telemetry should be sent, false otherwise
|
|
785
|
+
*/
|
|
786
|
+
shouldSendTelemetry() {
|
|
787
|
+
const devEnvironments = ["test", "development", "CI"];
|
|
788
|
+
const nodeEnv = (getEnvVariable("NODE_ENV", "development") || "").toLowerCase();
|
|
789
|
+
const isDevEnvironment = devEnvironments.includes(nodeEnv);
|
|
790
|
+
const isTelemetryDisabledByEnv = getEnvVariable("TELEMETRY_DISABLED", "false") === "true";
|
|
791
|
+
return this.transport && !this.isTelemetryDisabled && !isTelemetryDisabledByEnv && !isDevEnvironment;
|
|
792
|
+
}
|
|
793
|
+
/**
|
|
794
|
+
* Prepare and send the error telemetry.
|
|
795
|
+
*
|
|
796
|
+
* @TODO This currently blocks the thread and sends the telemetry to the server.
|
|
797
|
+
*
|
|
798
|
+
* @param {unknown} error - The error to send.
|
|
799
|
+
* @param {string} instrumentedClassName - The class name of the instrumented class.
|
|
800
|
+
* @param {string} name - The name of the method that threw the error.
|
|
801
|
+
*/
|
|
802
|
+
prepareAndSendErrorTelemetry(error, instrumentedClassName, name, args) {
|
|
803
|
+
if (error instanceof ComposioClientError) {
|
|
804
|
+
const telemetryPayload = {
|
|
805
|
+
error_id: error.errorId || "",
|
|
806
|
+
error_message: error.message,
|
|
807
|
+
original_error: error.cause || error,
|
|
808
|
+
current_stack: error.stack ? error.stack.split("\n") : [],
|
|
809
|
+
description: `Original Call : ${this.telemetryMetadata?.source}:${instrumentedClassName}.${name}(${JSON.stringify(args)})`
|
|
810
|
+
};
|
|
811
|
+
this.sendErrorTelemetry(telemetryPayload);
|
|
812
|
+
} else if (error instanceof ComposioError) {
|
|
813
|
+
const telemetryPayload = {
|
|
814
|
+
error_id: error.errorId || "",
|
|
815
|
+
error_message: error.message,
|
|
816
|
+
original_error: error.cause || error,
|
|
817
|
+
current_stack: error.stack ? error.stack.split("\n") : [],
|
|
818
|
+
error_code: error.code,
|
|
819
|
+
possible_fix: error.possibleFixes?.join("\n"),
|
|
820
|
+
description: `Original Call : ${instrumentedClassName}.${name}(${JSON.stringify(args)})`
|
|
821
|
+
};
|
|
822
|
+
this.sendErrorTelemetry(telemetryPayload);
|
|
823
|
+
} else if (error instanceof Error) {
|
|
824
|
+
const telemetryPayload = {
|
|
825
|
+
error_id: error.errorId || "",
|
|
826
|
+
error_message: error instanceof Error ? error.name : "Unknown error",
|
|
827
|
+
original_error: error,
|
|
828
|
+
current_stack: error.stack ? error.stack.split("\n") : [],
|
|
829
|
+
description: `Original Call : ${this.telemetryMetadata?.source}:${instrumentedClassName}.${name}(${JSON.stringify(args)})`
|
|
830
|
+
};
|
|
831
|
+
this.sendErrorTelemetry(telemetryPayload);
|
|
832
|
+
}
|
|
833
|
+
}
|
|
834
|
+
/**
|
|
835
|
+
* Send the telemetry payload to the server.
|
|
836
|
+
* @param payload - the telemetry payload to send
|
|
837
|
+
* @returns
|
|
838
|
+
*/
|
|
839
|
+
async sendTelemetry(payload) {
|
|
840
|
+
if (!this.shouldSendTelemetry()) {
|
|
841
|
+
return;
|
|
842
|
+
}
|
|
843
|
+
const url = `${TELEMETRY_URL}/api/sdk_metrics/telemetry`;
|
|
844
|
+
const reqPayload = {
|
|
845
|
+
data: payload.map((p) => ({
|
|
846
|
+
...p,
|
|
847
|
+
sdk_meta: this.telemetryMetadata
|
|
848
|
+
})),
|
|
849
|
+
url,
|
|
850
|
+
method: "POST",
|
|
851
|
+
headers: { "Content-Type": "application/json" }
|
|
434
852
|
};
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
)
|
|
853
|
+
this.transport.send(reqPayload);
|
|
854
|
+
}
|
|
855
|
+
// @TODO: check if this will send the error telemetry to the server
|
|
856
|
+
async sendErrorTelemetry(payload) {
|
|
857
|
+
if (!this.shouldSendTelemetry()) {
|
|
858
|
+
return;
|
|
859
|
+
}
|
|
860
|
+
const url = `${TELEMETRY_URL}/api/sdk_metrics/error`;
|
|
861
|
+
const reqPayload = {
|
|
862
|
+
data: {
|
|
863
|
+
...payload,
|
|
864
|
+
sdk_meta: this.telemetryMetadata
|
|
865
|
+
},
|
|
866
|
+
url,
|
|
867
|
+
method: "POST",
|
|
868
|
+
headers: { "Content-Type": "application/json" }
|
|
869
|
+
};
|
|
870
|
+
this.transport.send(reqPayload);
|
|
440
871
|
}
|
|
441
872
|
};
|
|
873
|
+
var telemetry = new TelemetryService();
|
|
442
874
|
|
|
443
|
-
// src/
|
|
444
|
-
import {
|
|
875
|
+
// src/types/connectedAccounts.types.ts
|
|
876
|
+
import { z as z2 } from "zod";
|
|
877
|
+
var ConnectedAccountStatuses = {
|
|
878
|
+
INITIALIZING: "INITIALIZING",
|
|
879
|
+
INITIATED: "INITIATED",
|
|
880
|
+
ACTIVE: "ACTIVE",
|
|
881
|
+
FAILED: "FAILED",
|
|
882
|
+
EXPIRED: "EXPIRED"
|
|
883
|
+
};
|
|
884
|
+
var ConnectedAccountStatusSchema = z2.enum([
|
|
885
|
+
ConnectedAccountStatuses.INITIALIZING,
|
|
886
|
+
ConnectedAccountStatuses.INITIATED,
|
|
887
|
+
ConnectedAccountStatuses.ACTIVE,
|
|
888
|
+
ConnectedAccountStatuses.FAILED,
|
|
889
|
+
ConnectedAccountStatuses.EXPIRED
|
|
890
|
+
]);
|
|
891
|
+
var CreateConnectedAccountParamsSchema = z2.object({
|
|
892
|
+
authConfig: z2.object({
|
|
893
|
+
id: z2.string()
|
|
894
|
+
}),
|
|
895
|
+
connection: z2.object({
|
|
896
|
+
data: z2.record(z2.string(), z2.unknown()).optional(),
|
|
897
|
+
callbackUrl: z2.string().optional(),
|
|
898
|
+
userId: z2.string().optional()
|
|
899
|
+
})
|
|
900
|
+
});
|
|
901
|
+
var DefaultCreateConnectedAccountParamsSchema = z2.object({
|
|
902
|
+
auth_config: z2.object({
|
|
903
|
+
id: z2.string()
|
|
904
|
+
}),
|
|
905
|
+
connection: z2.object({
|
|
906
|
+
data: z2.record(z2.string(), z2.unknown()).optional(),
|
|
907
|
+
callback_url: z2.string().optional(),
|
|
908
|
+
user_id: z2.string().optional()
|
|
909
|
+
})
|
|
910
|
+
});
|
|
911
|
+
var CreateConnectedAccountOptionsSchema = z2.object({
|
|
912
|
+
callbackUrl: z2.string().optional(),
|
|
913
|
+
data: z2.record(z2.string(), z2.unknown()).optional()
|
|
914
|
+
});
|
|
915
|
+
var CreateConnectedAccountResponseSchema = z2.object({
|
|
916
|
+
id: z2.string(),
|
|
917
|
+
status: ConnectedAccountStatusSchema,
|
|
918
|
+
redirectUrl: z2.string().nullable()
|
|
919
|
+
});
|
|
920
|
+
var ConnectedAccountAuthSchemes = {
|
|
921
|
+
OAUTH2: "OAUTH2",
|
|
922
|
+
OAUTH1: "OAUTH1",
|
|
923
|
+
OAUTH1A: "OAUTH1A",
|
|
924
|
+
API_KEY: "API_KEY",
|
|
925
|
+
BASIC: "BASIC",
|
|
926
|
+
BILLCOM_AUTH: "BILLCOM_AUTH",
|
|
927
|
+
BEARER_TOKEN: "BEARER_TOKEN",
|
|
928
|
+
GOOGLE_SERVICE_ACCOUNT: "GOOGLE_SERVICE_ACCOUNT",
|
|
929
|
+
NO_AUTH: "NO_AUTH",
|
|
930
|
+
BASIC_WITH_JWT: "BASIC_WITH_JWT",
|
|
931
|
+
COMPOSIO_LINK: "COMPOSIO_LINK",
|
|
932
|
+
CALCOM_AUTH: "CALCOM_AUTH",
|
|
933
|
+
SNOWFLAKE: "SNOWFLAKE"
|
|
934
|
+
};
|
|
935
|
+
var ConnectedAccountAuthSchemesSchema = z2.enum([
|
|
936
|
+
ConnectedAccountAuthSchemes.OAUTH2,
|
|
937
|
+
ConnectedAccountAuthSchemes.OAUTH1,
|
|
938
|
+
ConnectedAccountAuthSchemes.OAUTH1A,
|
|
939
|
+
ConnectedAccountAuthSchemes.API_KEY,
|
|
940
|
+
ConnectedAccountAuthSchemes.BASIC,
|
|
941
|
+
ConnectedAccountAuthSchemes.BILLCOM_AUTH,
|
|
942
|
+
ConnectedAccountAuthSchemes.BEARER_TOKEN,
|
|
943
|
+
ConnectedAccountAuthSchemes.GOOGLE_SERVICE_ACCOUNT,
|
|
944
|
+
ConnectedAccountAuthSchemes.NO_AUTH,
|
|
945
|
+
ConnectedAccountAuthSchemes.BASIC_WITH_JWT,
|
|
946
|
+
ConnectedAccountAuthSchemes.COMPOSIO_LINK,
|
|
947
|
+
ConnectedAccountAuthSchemes.CALCOM_AUTH,
|
|
948
|
+
ConnectedAccountAuthSchemes.SNOWFLAKE
|
|
949
|
+
]);
|
|
950
|
+
var ConnectedAccountAuthConfigSchema = z2.object({
|
|
951
|
+
id: z2.string(),
|
|
952
|
+
authScheme: ConnectedAccountAuthSchemesSchema,
|
|
953
|
+
isComposioManaged: z2.boolean(),
|
|
954
|
+
isDisabled: z2.boolean()
|
|
955
|
+
});
|
|
956
|
+
var ConnectedAccountRetrieveResponseSchema = z2.object({
|
|
957
|
+
id: z2.string(),
|
|
958
|
+
authConfig: ConnectedAccountAuthConfigSchema,
|
|
959
|
+
userId: z2.string(),
|
|
960
|
+
data: z2.record(z2.string(), z2.unknown()),
|
|
961
|
+
params: z2.record(z2.string(), z2.unknown()).optional(),
|
|
962
|
+
status: ConnectedAccountStatusSchema,
|
|
963
|
+
statusReason: z2.string().nullable(),
|
|
964
|
+
toolkit: z2.object({
|
|
965
|
+
slug: z2.string()
|
|
966
|
+
}),
|
|
967
|
+
testRequestEndpoint: z2.string().optional(),
|
|
968
|
+
isDisabled: z2.boolean(),
|
|
969
|
+
createdAt: z2.string(),
|
|
970
|
+
updatedAt: z2.string()
|
|
971
|
+
});
|
|
972
|
+
var ConnectedAccountListParamsSchema = z2.object({
|
|
973
|
+
authConfigIds: z2.array(z2.string()).nullable().optional().describe("The auth config ids of the connected accounts"),
|
|
974
|
+
cursor: z2.number().nullable().optional().describe("The cursor to paginate through the connected accounts"),
|
|
975
|
+
labels: z2.array(z2.string()).nullable().optional().describe("The labels of the connected accounts"),
|
|
976
|
+
limit: z2.number().nullable().optional().describe("The limit of the connected accounts to return"),
|
|
977
|
+
orderBy: z2.enum(["created_at", "updated_at"]).optional().describe("The order by of the connected accounts"),
|
|
978
|
+
statuses: z2.array(ConnectedAccountStatusSchema).nullable().optional().describe("The statuses of the connected accounts"),
|
|
979
|
+
toolkitSlugs: z2.array(z2.string()).nullable().optional().describe("The toolkit slugs of the connected accounts"),
|
|
980
|
+
userIds: z2.array(z2.string()).nullable().optional().describe("The user ids of the connected accounts")
|
|
981
|
+
});
|
|
982
|
+
var ConnectedAccountListResponseSchema = z2.object({
|
|
983
|
+
items: z2.array(ConnectedAccountRetrieveResponseSchema).describe("The list of connected accounts"),
|
|
984
|
+
nextCursor: z2.string().nullable().describe("The next cursor to paginate through the connected accounts"),
|
|
985
|
+
totalPages: z2.number().describe("The total number of pages of connected accounts")
|
|
986
|
+
});
|
|
987
|
+
|
|
988
|
+
// src/errors/AuthConfigErrors.ts
|
|
989
|
+
var AuthConfigErrorCodes = {
|
|
990
|
+
AUTH_CONFIG_NOT_FOUND: "AUTH_CONFIG_NOT_FOUND"
|
|
991
|
+
};
|
|
992
|
+
var ComposioAuthConfigNotFoundError = class extends ComposioError {
|
|
993
|
+
constructor(message = "Auth config not found", options = {}) {
|
|
994
|
+
super(message, {
|
|
995
|
+
...options,
|
|
996
|
+
code: AuthConfigErrorCodes.AUTH_CONFIG_NOT_FOUND,
|
|
997
|
+
possibleFixes: options.possibleFixes || [
|
|
998
|
+
"Check if the auth config exists",
|
|
999
|
+
"Check if the auth config id is correct",
|
|
1000
|
+
"Check if the auth config is enabled"
|
|
1001
|
+
]
|
|
1002
|
+
});
|
|
1003
|
+
this.name = "ComposioAuthConfigNotFoundError";
|
|
1004
|
+
}
|
|
1005
|
+
};
|
|
1006
|
+
|
|
1007
|
+
// src/errors/ConnectionRequestErrors.ts
|
|
1008
|
+
var ConnectionRequestErrorCodes = {
|
|
1009
|
+
CONNECTION_REQUEST_TIMEOUT: "CONNECTION_REQUEST_TIMEOUT",
|
|
1010
|
+
CONNECTION_REQUEST_FAILED: "CONNECTION_REQUEST_FAILED"
|
|
1011
|
+
};
|
|
1012
|
+
var ConnectionRequestTimeoutError = class extends ComposioError {
|
|
1013
|
+
constructor(message = "Connection request timed out", options = {}) {
|
|
1014
|
+
super(message, {
|
|
1015
|
+
...options,
|
|
1016
|
+
code: ConnectionRequestErrorCodes.CONNECTION_REQUEST_TIMEOUT
|
|
1017
|
+
});
|
|
1018
|
+
this.name = "ConnectionRequestTimeoutError";
|
|
1019
|
+
}
|
|
1020
|
+
};
|
|
1021
|
+
var ConnectionRequestFailedError = class extends ComposioError {
|
|
1022
|
+
constructor(message = "Connection request failed", options = {}) {
|
|
1023
|
+
super(message, {
|
|
1024
|
+
...options,
|
|
1025
|
+
code: ConnectionRequestErrorCodes.CONNECTION_REQUEST_FAILED
|
|
1026
|
+
});
|
|
1027
|
+
this.name = "ConnectionRequestFailedError";
|
|
1028
|
+
}
|
|
1029
|
+
};
|
|
1030
|
+
|
|
1031
|
+
// src/errors/ToolkitErrors.ts
|
|
1032
|
+
var ToolkitErrorCodes = {
|
|
1033
|
+
TOOLKIT_NOT_FOUND: "TOOLKIT_NOT_FOUND"
|
|
1034
|
+
};
|
|
1035
|
+
var ComposioToolkitNotFoundError = class extends ComposioError {
|
|
1036
|
+
constructor(message = "Toolkit not found", options = {}) {
|
|
1037
|
+
super(message, {
|
|
1038
|
+
...options,
|
|
1039
|
+
code: "TOOLKIT_NOT_FOUND",
|
|
1040
|
+
possibleFixes: options.possibleFixes || [
|
|
1041
|
+
"Ensure the toolkit is correctly configured and the slug is valid"
|
|
1042
|
+
]
|
|
1043
|
+
});
|
|
1044
|
+
this.name = "ComposioToolkitNotFoundError";
|
|
1045
|
+
}
|
|
1046
|
+
};
|
|
1047
|
+
var ComposioToolkitFetchError = class extends ComposioError {
|
|
1048
|
+
constructor(message = "Failed to fetch toolkit", options = {}) {
|
|
1049
|
+
super(message, {
|
|
1050
|
+
...options,
|
|
1051
|
+
code: "TOOLKIT_FETCH_ERROR",
|
|
1052
|
+
possibleFixes: options.possibleFixes || [
|
|
1053
|
+
"Ensure the toolkit slug is valid",
|
|
1054
|
+
"Ensure you are using the correct API key",
|
|
1055
|
+
"Ensure you are using the correct API endpoint / Base URL and it is working"
|
|
1056
|
+
]
|
|
1057
|
+
});
|
|
1058
|
+
this.name = "ComposioToolkitFetchError";
|
|
1059
|
+
}
|
|
1060
|
+
};
|
|
1061
|
+
|
|
1062
|
+
// src/errors/ValidationErrors.ts
|
|
1063
|
+
import { ZodError as ZodError2 } from "zod";
|
|
445
1064
|
var ValidationErrorCodes = {
|
|
446
1065
|
VALIDATION_ERROR: "VALIDATION_ERROR"
|
|
447
1066
|
};
|
|
448
1067
|
var ValidationError = class extends ComposioError {
|
|
449
|
-
|
|
450
|
-
|
|
1068
|
+
constructor(message = "Input validation failed", options = {}) {
|
|
1069
|
+
const { cause: providedZodError, ...restOptions } = options;
|
|
451
1070
|
let zodErrorInstance;
|
|
452
|
-
if (
|
|
453
|
-
zodErrorInstance =
|
|
1071
|
+
if (providedZodError instanceof ZodError2) {
|
|
1072
|
+
zodErrorInstance = providedZodError;
|
|
1073
|
+
} else {
|
|
1074
|
+
zodErrorInstance = new ZodError2([
|
|
454
1075
|
{
|
|
455
1076
|
path: [],
|
|
456
1077
|
message: "Invalid input",
|
|
457
1078
|
code: "custom"
|
|
458
1079
|
}
|
|
459
1080
|
]);
|
|
460
|
-
} else {
|
|
461
|
-
zodErrorInstance = zodError;
|
|
462
1081
|
}
|
|
463
1082
|
const issues = zodErrorInstance.issues.map(
|
|
464
1083
|
(issue) => `[${issue.code}] ${issue.path.join(".")} - ${issue.message}`
|
|
465
1084
|
);
|
|
466
1085
|
super(message, {
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
1086
|
+
...restOptions,
|
|
1087
|
+
code: options.code || ValidationErrorCodes.VALIDATION_ERROR,
|
|
1088
|
+
possibleFixes: issues,
|
|
1089
|
+
cause: zodErrorInstance
|
|
470
1090
|
});
|
|
471
|
-
this.zodError = zodErrorInstance;
|
|
472
1091
|
this.name = "ValidationError";
|
|
1092
|
+
const userFriendlyMessage = this.generateUserFriendlyMessage();
|
|
1093
|
+
this.message = `${message}: ${userFriendlyMessage}`;
|
|
1094
|
+
}
|
|
1095
|
+
generateUserFriendlyMessage() {
|
|
1096
|
+
if (this.cause instanceof ZodError2 && this.cause.issues.length > 0) {
|
|
1097
|
+
const issue = this.cause.issues[0];
|
|
1098
|
+
const path = issue.path.join(".");
|
|
1099
|
+
const param = path || "parameter";
|
|
1100
|
+
if (issue.code === "invalid_type") {
|
|
1101
|
+
return `The ${param} should be a ${issue.expected}, but you provided a ${issue.received}`;
|
|
1102
|
+
}
|
|
1103
|
+
return issue.message;
|
|
1104
|
+
}
|
|
1105
|
+
return "Please check your input parameters";
|
|
1106
|
+
}
|
|
1107
|
+
};
|
|
1108
|
+
|
|
1109
|
+
// src/errors/SDKErrors.ts
|
|
1110
|
+
var SDKErrorCodes = {
|
|
1111
|
+
NO_API_KEY_PROVIDED: "NO_API_KEY_PROVIDED"
|
|
1112
|
+
};
|
|
1113
|
+
var ComposioNoAPIKeyError = class extends ComposioError {
|
|
1114
|
+
constructor(message = "No Composio API key provided", options = {}) {
|
|
1115
|
+
const defaultCause = "Couldn't find an API key in the params, environment variables or in the user config file";
|
|
1116
|
+
super(message, {
|
|
1117
|
+
...options,
|
|
1118
|
+
code: "NO_API_KEY",
|
|
1119
|
+
cause: options.cause || defaultCause,
|
|
1120
|
+
possibleFixes: options.possibleFixes || [
|
|
1121
|
+
"Ensure you have an API key passed in the params, or in environment variable (COMPOSIO_API_KEY) or in the user config file",
|
|
1122
|
+
"To get an API key, please sign up at https://composio.dev/signup",
|
|
1123
|
+
"You can also use the Composio CLI to create a project and get an API key"
|
|
1124
|
+
],
|
|
1125
|
+
statusCode: 401
|
|
1126
|
+
});
|
|
1127
|
+
this.name = "ComposioNoAPIKeyError";
|
|
1128
|
+
}
|
|
1129
|
+
};
|
|
1130
|
+
|
|
1131
|
+
// src/models/CustomTools.ts
|
|
1132
|
+
var CustomTools = class {
|
|
1133
|
+
client;
|
|
1134
|
+
customToolsRegistry;
|
|
1135
|
+
constructor(client) {
|
|
1136
|
+
if (!client) {
|
|
1137
|
+
throw new ComposioError("ComposioClient is required");
|
|
1138
|
+
}
|
|
1139
|
+
this.client = client;
|
|
1140
|
+
this.customToolsRegistry = /* @__PURE__ */ new Map();
|
|
1141
|
+
telemetry.instrument(this);
|
|
1142
|
+
}
|
|
1143
|
+
/**
|
|
1144
|
+
* Create a custom tool and registers it in the registry.
|
|
1145
|
+
* This is just an in memory registry and is not persisted.
|
|
1146
|
+
* @param {CustomToolOptions} toolOptions CustomToolOptions
|
|
1147
|
+
* @returns {Tool} The tool created
|
|
1148
|
+
*
|
|
1149
|
+
* @example
|
|
1150
|
+
* ```typescript
|
|
1151
|
+
* // Create a custom tool with input parameters
|
|
1152
|
+
* const customTool = await composio.customTools.createTool({
|
|
1153
|
+
* name: 'My Custom Tool',
|
|
1154
|
+
* description: 'A tool that performs a custom operation',
|
|
1155
|
+
* slug: 'MY_CUSTOM_TOOL',
|
|
1156
|
+
* inputParams: z.object({
|
|
1157
|
+
* query: z.string().describe('The search query'),
|
|
1158
|
+
* limit: z.number().optional().describe('Maximum number of results')
|
|
1159
|
+
* }),
|
|
1160
|
+
* execute: async (input, authCredentials, executeToolRequest) => {
|
|
1161
|
+
* // Custom implementation logic
|
|
1162
|
+
* return {
|
|
1163
|
+
* data: { results: ['result1', 'result2'] }
|
|
1164
|
+
* };
|
|
1165
|
+
* }
|
|
1166
|
+
* });
|
|
1167
|
+
* ```
|
|
1168
|
+
*/
|
|
1169
|
+
async createTool(toolOptions) {
|
|
1170
|
+
const { slug, execute, inputParams, name, description } = toolOptions;
|
|
1171
|
+
if (!slug || !execute || !inputParams || !name) {
|
|
1172
|
+
throw new Error("Invalid tool options");
|
|
1173
|
+
}
|
|
1174
|
+
const paramsSchema = await zodToJsonSchema(inputParams, {
|
|
1175
|
+
name: "input"
|
|
1176
|
+
});
|
|
1177
|
+
const paramsSchemaJson = paramsSchema.definitions.input;
|
|
1178
|
+
const toolSchema = {
|
|
1179
|
+
name,
|
|
1180
|
+
slug,
|
|
1181
|
+
description,
|
|
1182
|
+
inputParameters: {
|
|
1183
|
+
title: name,
|
|
1184
|
+
type: "object",
|
|
1185
|
+
description,
|
|
1186
|
+
properties: paramsSchemaJson.properties,
|
|
1187
|
+
required: paramsSchemaJson.required
|
|
1188
|
+
},
|
|
1189
|
+
// the output parameters are not used yet
|
|
1190
|
+
outputParameters: {
|
|
1191
|
+
type: "object",
|
|
1192
|
+
title: `Response for ${name}`,
|
|
1193
|
+
properties: {}
|
|
1194
|
+
},
|
|
1195
|
+
tags: [],
|
|
1196
|
+
// this is never set to the user provided toolkitslug so that we can differentiate
|
|
1197
|
+
// the toolkitslug is used via the execute function.
|
|
1198
|
+
toolkit: { name: "custom", slug: "custom" }
|
|
1199
|
+
};
|
|
1200
|
+
this.customToolsRegistry.set(slug.toLowerCase(), {
|
|
1201
|
+
options: toolOptions,
|
|
1202
|
+
schema: toolSchema
|
|
1203
|
+
});
|
|
1204
|
+
return toolSchema;
|
|
1205
|
+
}
|
|
1206
|
+
/**
|
|
1207
|
+
* Get all the custom tools from the registry.
|
|
1208
|
+
* @param {string[]} param0.toolSlugs The slugs of the tools to get
|
|
1209
|
+
* @returns {ToolList} The list of tools
|
|
1210
|
+
*
|
|
1211
|
+
* @example
|
|
1212
|
+
* ```typescript
|
|
1213
|
+
* // Get all custom tools
|
|
1214
|
+
* const allTools = await composio.customTools.getCustomTools({});
|
|
1215
|
+
*
|
|
1216
|
+
* // Get specific custom tools by slug
|
|
1217
|
+
* const specificTools = await composio.customTools.getCustomTools({
|
|
1218
|
+
* toolSlugs: ['MY_CUSTOM_TOOL', 'ANOTHER_CUSTOM_TOOL']
|
|
1219
|
+
* });
|
|
1220
|
+
* ```
|
|
1221
|
+
*/
|
|
1222
|
+
async getCustomTools({ toolSlugs }) {
|
|
1223
|
+
const tools = [];
|
|
1224
|
+
if (toolSlugs) {
|
|
1225
|
+
for (const slug of toolSlugs) {
|
|
1226
|
+
const tool = this.customToolsRegistry.get(slug.toLowerCase());
|
|
1227
|
+
if (tool) {
|
|
1228
|
+
tools.push(tool.schema);
|
|
1229
|
+
}
|
|
1230
|
+
}
|
|
1231
|
+
} else {
|
|
1232
|
+
return Array.from(this.customToolsRegistry.values()).map((tool) => tool.schema);
|
|
1233
|
+
}
|
|
1234
|
+
return tools;
|
|
1235
|
+
}
|
|
1236
|
+
/**
|
|
1237
|
+
* Get a custom tool by slug from the registry.
|
|
1238
|
+
* @param {string} slug The slug of the tool to get
|
|
1239
|
+
* @returns {Tool} The tool
|
|
1240
|
+
*
|
|
1241
|
+
* @example
|
|
1242
|
+
* ```typescript
|
|
1243
|
+
* // Get a specific custom tool by its slug
|
|
1244
|
+
* const myTool = await composio.customTools.getCustomToolBySlug('MY_CUSTOM_TOOL');
|
|
1245
|
+
* if (myTool) {
|
|
1246
|
+
* console.log(`Found tool: ${myTool.name}`);
|
|
1247
|
+
* } else {
|
|
1248
|
+
* console.log('Tool not found');
|
|
1249
|
+
* }
|
|
1250
|
+
* ```
|
|
1251
|
+
*/
|
|
1252
|
+
async getCustomToolBySlug(slug) {
|
|
1253
|
+
if (!slug) {
|
|
1254
|
+
throw new Error("Tool slug is required");
|
|
1255
|
+
}
|
|
1256
|
+
try {
|
|
1257
|
+
const tool = this.customToolsRegistry.get(slug.toLowerCase());
|
|
1258
|
+
return tool?.schema;
|
|
1259
|
+
} catch (error) {
|
|
1260
|
+
logger_default.error(`Error getting custom tool: ${error}`);
|
|
1261
|
+
return void 0;
|
|
1262
|
+
}
|
|
1263
|
+
}
|
|
1264
|
+
/**
|
|
1265
|
+
* Get the connected account for the user and toolkit.
|
|
1266
|
+
* @param {string} toolkitSlug The slug of the toolkit
|
|
1267
|
+
* @param {ExecuteMetadata} metadata The metadata of the execution
|
|
1268
|
+
* @returns {ConnectedAccount} The connected account
|
|
1269
|
+
*/
|
|
1270
|
+
async getConnectedAccountForToolkit(toolkitSlug, userId, connectedAccountId) {
|
|
1271
|
+
try {
|
|
1272
|
+
await this.client.toolkits.retrieve(toolkitSlug);
|
|
1273
|
+
} catch (error) {
|
|
1274
|
+
throw new ComposioToolNotFoundError(`Toolkit with slug ${toolkitSlug} not found`, {
|
|
1275
|
+
cause: error
|
|
1276
|
+
});
|
|
1277
|
+
}
|
|
1278
|
+
const connectedAccounts = await this.client.connectedAccounts.list({
|
|
1279
|
+
toolkit_slugs: [toolkitSlug],
|
|
1280
|
+
user_ids: [userId]
|
|
1281
|
+
});
|
|
1282
|
+
if (!connectedAccounts.items.length) {
|
|
1283
|
+
throw new ComposioConnectedAccountNotFoundError(
|
|
1284
|
+
`No connected accounts found for toolkit ${toolkitSlug}`
|
|
1285
|
+
);
|
|
1286
|
+
}
|
|
1287
|
+
const connectedAccount = connectedAccountId ? connectedAccounts.items.find((item) => item.id === connectedAccountId) : connectedAccounts.items[0];
|
|
1288
|
+
if (!connectedAccount) {
|
|
1289
|
+
throw new ComposioConnectedAccountNotFoundError(
|
|
1290
|
+
`Connected account not found for toolkit ${toolkitSlug} for user ${userId}`
|
|
1291
|
+
);
|
|
1292
|
+
}
|
|
1293
|
+
const connectedAccountResponse = await ConnectedAccountRetrieveResponseSchema.safeParse({
|
|
1294
|
+
id: connectedAccount.id,
|
|
1295
|
+
authConfig: {
|
|
1296
|
+
id: connectedAccount.auth_config.id,
|
|
1297
|
+
authScheme: connectedAccount.auth_config.auth_scheme,
|
|
1298
|
+
isComposioManaged: connectedAccount.auth_config.is_composio_managed,
|
|
1299
|
+
isDisabled: connectedAccount.auth_config.is_disabled
|
|
1300
|
+
},
|
|
1301
|
+
userId: connectedAccount.user_id,
|
|
1302
|
+
data: connectedAccount.data || {},
|
|
1303
|
+
status: connectedAccount.status,
|
|
1304
|
+
statusReason: connectedAccount.status_reason,
|
|
1305
|
+
toolkit: {
|
|
1306
|
+
slug: connectedAccount.toolkit.slug
|
|
1307
|
+
},
|
|
1308
|
+
testRequestEndpoint: connectedAccount.test_request_endpoint,
|
|
1309
|
+
isDisabled: connectedAccount.is_disabled,
|
|
1310
|
+
createdAt: connectedAccount.created_at,
|
|
1311
|
+
updatedAt: connectedAccount.updated_at
|
|
1312
|
+
});
|
|
1313
|
+
if (!connectedAccountResponse.success) {
|
|
1314
|
+
throw new ValidationError(
|
|
1315
|
+
`Validation error for connected account of ${toolkitSlug} for user ${userId}`,
|
|
1316
|
+
{
|
|
1317
|
+
cause: connectedAccountResponse.error
|
|
1318
|
+
}
|
|
1319
|
+
);
|
|
1320
|
+
}
|
|
1321
|
+
return connectedAccountResponse.data;
|
|
1322
|
+
}
|
|
1323
|
+
/**
|
|
1324
|
+
* Execute a custom tool
|
|
1325
|
+
*
|
|
1326
|
+
* @description If a toolkit is used, the connected account id is used to execute the tool.
|
|
1327
|
+
* If a connected account id is provided, it is used to execute the tool.
|
|
1328
|
+
* If a connected account id is not provided, the first connected account for the toolkit is used.
|
|
1329
|
+
*
|
|
1330
|
+
* @param {slug} slug The slug of the tool to execute
|
|
1331
|
+
* @param {Record<string, unknown>} inputParams The input parameters for the tool
|
|
1332
|
+
* @param {ExecuteMetadata} metadata The metadata of the execution
|
|
1333
|
+
* @returns {Promise<ToolExecuteResponse>} The response from the tool
|
|
1334
|
+
*/
|
|
1335
|
+
async executeCustomTool(slug, body) {
|
|
1336
|
+
const tool = this.customToolsRegistry.get(slug.toLowerCase());
|
|
1337
|
+
if (!tool) {
|
|
1338
|
+
throw new ComposioToolNotFoundError(`Tool with slug ${slug} not found`);
|
|
1339
|
+
}
|
|
1340
|
+
let authCredentials = {};
|
|
1341
|
+
const { toolkitSlug, execute, inputParams } = tool.options;
|
|
1342
|
+
let connectedAccountId = body.connectedAccountId;
|
|
1343
|
+
if (toolkitSlug && toolkitSlug !== "custom") {
|
|
1344
|
+
const connectedAccount = await this.getConnectedAccountForToolkit(
|
|
1345
|
+
toolkitSlug,
|
|
1346
|
+
body.userId,
|
|
1347
|
+
body.connectedAccountId
|
|
1348
|
+
);
|
|
1349
|
+
logger_default.debug(
|
|
1350
|
+
`[CustomTool] Connected account for ${toolkitSlug} found for user ${body.userId}`,
|
|
1351
|
+
JSON.stringify(connectedAccount, null, 2)
|
|
1352
|
+
);
|
|
1353
|
+
if (!connectedAccount) {
|
|
1354
|
+
throw new ComposioConnectedAccountNotFoundError(
|
|
1355
|
+
`Connected account not found for toolkit ${toolkitSlug} for user ${body.userId}`,
|
|
1356
|
+
{
|
|
1357
|
+
meta: {
|
|
1358
|
+
toolkitSlug,
|
|
1359
|
+
userId: body.userId
|
|
1360
|
+
}
|
|
1361
|
+
}
|
|
1362
|
+
);
|
|
1363
|
+
}
|
|
1364
|
+
authCredentials = connectedAccount.data;
|
|
1365
|
+
connectedAccountId = connectedAccount.id;
|
|
1366
|
+
}
|
|
1367
|
+
if (typeof execute !== "function") {
|
|
1368
|
+
throw new ComposioInvalidExecuteFunctionError("Invalid execute function", {
|
|
1369
|
+
meta: {
|
|
1370
|
+
toolSlug: slug
|
|
1371
|
+
}
|
|
1372
|
+
});
|
|
1373
|
+
}
|
|
1374
|
+
const executeToolRequest = async (data) => {
|
|
1375
|
+
if (toolkitSlug && toolkitSlug === "custom") {
|
|
1376
|
+
throw new ComposioInvalidExecuteFunctionError(
|
|
1377
|
+
"Custom tools without a toolkit cannot be executed using the executeToolRequest function",
|
|
1378
|
+
{
|
|
1379
|
+
possibleFixes: [
|
|
1380
|
+
"Please manually execute the tool using your logic.",
|
|
1381
|
+
"Pass a toolkit slug to execute the tool on behalf of a toolkit credentials"
|
|
1382
|
+
]
|
|
1383
|
+
}
|
|
1384
|
+
);
|
|
1385
|
+
}
|
|
1386
|
+
const parameters = data.parameters?.map((param) => ({
|
|
1387
|
+
name: param.name,
|
|
1388
|
+
type: param.in,
|
|
1389
|
+
value: param.value.toString()
|
|
1390
|
+
}));
|
|
1391
|
+
const response = await this.client.tools.proxy({
|
|
1392
|
+
endpoint: data.endpoint,
|
|
1393
|
+
method: data.method,
|
|
1394
|
+
parameters,
|
|
1395
|
+
body: data.body,
|
|
1396
|
+
connected_account_id: data.connectedAccountId ?? connectedAccountId
|
|
1397
|
+
});
|
|
1398
|
+
return {
|
|
1399
|
+
data: response.data,
|
|
1400
|
+
error: null,
|
|
1401
|
+
successful: true,
|
|
1402
|
+
logId: void 0,
|
|
1403
|
+
sessionInfo: void 0
|
|
1404
|
+
};
|
|
1405
|
+
};
|
|
1406
|
+
const parsedInput = inputParams.safeParse(body.arguments);
|
|
1407
|
+
if (!parsedInput.success) {
|
|
1408
|
+
throw new ValidationError("Invalid input parameters", {
|
|
1409
|
+
cause: parsedInput.error
|
|
1410
|
+
});
|
|
1411
|
+
}
|
|
1412
|
+
return execute(parsedInput.data, authCredentials, executeToolRequest);
|
|
473
1413
|
}
|
|
474
1414
|
};
|
|
475
1415
|
|
|
@@ -492,6 +1432,7 @@ var Tools = class {
|
|
|
492
1432
|
this.provider._setExecuteToolFn(this.execute);
|
|
493
1433
|
this.getRawComposioToolBySlug = this.getRawComposioToolBySlug.bind(this);
|
|
494
1434
|
this.getRawComposioTools = this.getRawComposioTools.bind(this);
|
|
1435
|
+
telemetry.instrument(this);
|
|
495
1436
|
}
|
|
496
1437
|
/**
|
|
497
1438
|
* Transforms tool data from snake_case API format to camelCase for internal SDK use.
|
|
@@ -635,32 +1576,45 @@ var Tools = class {
|
|
|
635
1576
|
* );
|
|
636
1577
|
* ```
|
|
637
1578
|
*/
|
|
638
|
-
async getRawComposioTools(userId, query
|
|
1579
|
+
async getRawComposioTools(userId, query, modifier) {
|
|
1580
|
+
if ("tools" in query && "toolkits" in query) {
|
|
1581
|
+
throw new ValidationError(
|
|
1582
|
+
"Invalid tool list parameters. You should not use tools and toolkits filter together."
|
|
1583
|
+
);
|
|
1584
|
+
}
|
|
639
1585
|
const queryParams = ToolListParamsSchema.safeParse(query);
|
|
640
1586
|
if (queryParams.error) {
|
|
641
|
-
throw new ValidationError(
|
|
1587
|
+
throw new ValidationError("Invalid tool list parameters", {
|
|
1588
|
+
cause: queryParams.error
|
|
1589
|
+
});
|
|
1590
|
+
}
|
|
1591
|
+
if (!("tools" in queryParams.data || "toolkits" in queryParams.data || "search" in queryParams.data)) {
|
|
1592
|
+
throw new ValidationError(
|
|
1593
|
+
"Invalid tool list parameters, atleast one of the following parameters is required: tools, toolkits, search"
|
|
1594
|
+
);
|
|
642
1595
|
}
|
|
643
1596
|
const tools = await this.client.tools.list({
|
|
644
|
-
tool_slugs: queryParams.data.tools,
|
|
645
|
-
toolkit_slug: queryParams.data.toolkits?.join(","),
|
|
646
|
-
cursor: queryParams.data.cursor,
|
|
647
|
-
important: queryParams.data.important,
|
|
648
|
-
limit: queryParams.data.limit,
|
|
649
|
-
search: queryParams.data.search
|
|
1597
|
+
tool_slugs: "tools" in queryParams.data ? queryParams.data.tools?.join(",") : void 0,
|
|
1598
|
+
toolkit_slug: "toolkits" in queryParams.data ? queryParams.data.toolkits?.join(",") : void 0,
|
|
1599
|
+
cursor: "cursor" in queryParams.data ? queryParams.data.cursor : void 0,
|
|
1600
|
+
important: "important" in queryParams.data ? queryParams.data.important ? "true" : "false" : void 0,
|
|
1601
|
+
limit: "limit" in queryParams.data ? queryParams.data.limit?.toString() : void 0,
|
|
1602
|
+
search: "search" in queryParams.data ? queryParams.data.search : void 0
|
|
650
1603
|
});
|
|
651
1604
|
if (!tools) {
|
|
652
1605
|
return [];
|
|
653
1606
|
}
|
|
654
1607
|
const caseTransformedTools = tools.items.map((tool) => this.transformToolCases(tool));
|
|
655
1608
|
const customTools = await this.customTools.getCustomTools({
|
|
656
|
-
toolSlugs: queryParams.data.tools
|
|
1609
|
+
toolSlugs: "tools" in queryParams.data ? queryParams.data.tools : void 0
|
|
657
1610
|
});
|
|
658
1611
|
let modifiedTools = [...caseTransformedTools, ...customTools];
|
|
659
1612
|
if (modifier) {
|
|
660
1613
|
if (typeof modifier === "function") {
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
1614
|
+
const modifiedPromises = modifiedTools.map(
|
|
1615
|
+
(tool) => modifier(tool.slug, tool.toolkit?.slug ?? "unknown", tool)
|
|
1616
|
+
);
|
|
1617
|
+
modifiedTools = await Promise.all(modifiedPromises);
|
|
664
1618
|
} else {
|
|
665
1619
|
throw new ComposioInvalidModifierError("Invalid schema modifier. Not a function.");
|
|
666
1620
|
}
|
|
@@ -681,23 +1635,28 @@ var Tools = class {
|
|
|
681
1635
|
async getRawComposioToolBySlug(userId, slug, modifier) {
|
|
682
1636
|
const customTool = await this.customTools.getCustomToolBySlug(slug);
|
|
683
1637
|
if (customTool) {
|
|
1638
|
+
logger_default.debug(`Found ${slug} to be a custom tool`, JSON.stringify(customTool, null, 2));
|
|
684
1639
|
return customTool;
|
|
1640
|
+
} else {
|
|
1641
|
+
logger_default.debug(`Tool ${slug} is not a custom tool. Fetching from Composio API`);
|
|
685
1642
|
}
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
1643
|
+
let tool;
|
|
1644
|
+
try {
|
|
1645
|
+
tool = await this.client.tools.retrieve(slug);
|
|
1646
|
+
} catch (error) {
|
|
1647
|
+
throw new ComposioToolNotFoundError(`Unable to retrieve tool with slug ${slug}`, {
|
|
1648
|
+
cause: error
|
|
1649
|
+
});
|
|
691
1650
|
}
|
|
692
|
-
let
|
|
1651
|
+
let modifiedTool = this.transformToolCases(tool);
|
|
693
1652
|
if (modifier) {
|
|
694
1653
|
if (typeof modifier === "function") {
|
|
695
|
-
|
|
1654
|
+
modifiedTool = await modifier(slug, modifiedTool.toolkit?.slug ?? "unknown", modifiedTool);
|
|
696
1655
|
} else {
|
|
697
1656
|
throw new ComposioInvalidModifierError("Invalid schema modifier. Not a function.");
|
|
698
1657
|
}
|
|
699
1658
|
}
|
|
700
|
-
return
|
|
1659
|
+
return modifiedTool;
|
|
701
1660
|
}
|
|
702
1661
|
/**
|
|
703
1662
|
* Get a tool or list of tools based on the provided arguments.
|
|
@@ -711,17 +1670,19 @@ var Tools = class {
|
|
|
711
1670
|
async get(userId, arg2, options) {
|
|
712
1671
|
const executeToolFn = this.createExecuteToolFn(userId, options);
|
|
713
1672
|
if (typeof arg2 === "string") {
|
|
714
|
-
const tool = await this.getRawComposioToolBySlug(userId, arg2, options?.
|
|
1673
|
+
const tool = await this.getRawComposioToolBySlug(userId, arg2, options?.modifySchema);
|
|
715
1674
|
return this.provider.wrapTools([tool], executeToolFn);
|
|
716
1675
|
} else {
|
|
717
|
-
const tools = await this.getRawComposioTools(userId, arg2, options?.
|
|
1676
|
+
const tools = await this.getRawComposioTools(userId, arg2, options?.modifySchema);
|
|
718
1677
|
return this.provider.wrapTools(tools, executeToolFn);
|
|
719
1678
|
}
|
|
720
1679
|
}
|
|
721
1680
|
/**
|
|
722
1681
|
* @internal
|
|
1682
|
+
* @description
|
|
723
1683
|
* Creates a function that executes a tool.
|
|
724
|
-
* This function is used by agentic
|
|
1684
|
+
* This function is used by agentic toolsets to execute the tool
|
|
1685
|
+
*
|
|
725
1686
|
* @param {string} userId - The user id
|
|
726
1687
|
* @param {ExecuteToolModifiers} modifiers - The modifiers to be applied to the tool
|
|
727
1688
|
* @returns {ExecuteToolFn} The execute tool function
|
|
@@ -748,26 +1709,19 @@ var Tools = class {
|
|
|
748
1709
|
* @returns The response from the tool execution
|
|
749
1710
|
*/
|
|
750
1711
|
async handleCustomToolExecution(tool, body, modifiers) {
|
|
751
|
-
if (modifiers?.
|
|
752
|
-
if (typeof modifiers.
|
|
753
|
-
body = modifiers.
|
|
1712
|
+
if (modifiers?.beforeExecute) {
|
|
1713
|
+
if (typeof modifiers.beforeExecute === "function") {
|
|
1714
|
+
body = await modifiers.beforeExecute(tool.slug, "unknown", body);
|
|
754
1715
|
} else {
|
|
755
|
-
throw new ComposioInvalidModifierError(
|
|
756
|
-
"Invalid beforeToolExecute modifier. Not a function."
|
|
757
|
-
);
|
|
1716
|
+
throw new ComposioInvalidModifierError("Invalid beforeExecute modifier. Not a function.");
|
|
758
1717
|
}
|
|
759
1718
|
}
|
|
760
|
-
let result = await this.customTools.executeCustomTool(tool.slug, body
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
if (modifiers?.afterToolExecute) {
|
|
765
|
-
if (typeof modifiers.afterToolExecute === "function") {
|
|
766
|
-
result = modifiers.afterToolExecute(tool.slug, "unkown", result);
|
|
1719
|
+
let result = await this.customTools.executeCustomTool(tool.slug, body);
|
|
1720
|
+
if (modifiers?.afterExecute) {
|
|
1721
|
+
if (typeof modifiers.afterExecute === "function") {
|
|
1722
|
+
result = await modifiers.afterExecute(tool.slug, "unknown", result);
|
|
767
1723
|
} else {
|
|
768
|
-
throw new ComposioInvalidModifierError(
|
|
769
|
-
"Invalid afterToolExecute modifier. Not a function."
|
|
770
|
-
);
|
|
1724
|
+
throw new ComposioInvalidModifierError("Invalid afterExecute modifier. Not a function.");
|
|
771
1725
|
}
|
|
772
1726
|
}
|
|
773
1727
|
return result;
|
|
@@ -781,13 +1735,11 @@ var Tools = class {
|
|
|
781
1735
|
* @returns The response from the tool execution
|
|
782
1736
|
*/
|
|
783
1737
|
async handleComposioToolExecution(tool, body, modifiers) {
|
|
784
|
-
if (modifiers?.
|
|
785
|
-
if (typeof modifiers.
|
|
786
|
-
body = modifiers.
|
|
1738
|
+
if (modifiers?.beforeExecute) {
|
|
1739
|
+
if (typeof modifiers.beforeExecute === "function") {
|
|
1740
|
+
body = await modifiers.beforeExecute(tool.slug, tool.toolkit?.slug ?? "unknown", body);
|
|
787
1741
|
} else {
|
|
788
|
-
throw new ComposioInvalidModifierError(
|
|
789
|
-
"Invalid beforeToolExecute modifier. Not a function."
|
|
790
|
-
);
|
|
1742
|
+
throw new ComposioInvalidModifierError("Invalid beforeExecute modifier. Not a function.");
|
|
791
1743
|
}
|
|
792
1744
|
}
|
|
793
1745
|
let connectedAccountId = body.connectedAccountId;
|
|
@@ -804,13 +1756,11 @@ var Tools = class {
|
|
|
804
1756
|
text: body.text
|
|
805
1757
|
});
|
|
806
1758
|
result = this.transformToolExecuteResponse(result);
|
|
807
|
-
if (modifiers?.
|
|
808
|
-
if (typeof modifiers.
|
|
809
|
-
result = modifiers.
|
|
1759
|
+
if (modifiers?.afterExecute) {
|
|
1760
|
+
if (typeof modifiers.afterExecute === "function") {
|
|
1761
|
+
result = await modifiers.afterExecute(tool.slug, tool.toolkit?.slug ?? "unknown", result);
|
|
810
1762
|
} else {
|
|
811
|
-
throw new ComposioInvalidModifierError(
|
|
812
|
-
"Invalid afterToolExecute modifier. Not a function."
|
|
813
|
-
);
|
|
1763
|
+
throw new ComposioInvalidModifierError("Invalid afterExecute modifier. Not a function.");
|
|
814
1764
|
}
|
|
815
1765
|
}
|
|
816
1766
|
return result;
|
|
@@ -843,11 +1793,11 @@ var Tools = class {
|
|
|
843
1793
|
* userId: 'default',
|
|
844
1794
|
* arguments: { owner: 'composio', repo: 'sdk' }
|
|
845
1795
|
* }, {
|
|
846
|
-
*
|
|
1796
|
+
* beforeExecute: (toolSlug, toolkitSlug, params) => {
|
|
847
1797
|
* // Modify params before execution
|
|
848
1798
|
* return params;
|
|
849
1799
|
* },
|
|
850
|
-
*
|
|
1800
|
+
* afterExecute: (toolSlug, toolkitSlug, result) => {
|
|
851
1801
|
* // Transform result after execution
|
|
852
1802
|
* return result;
|
|
853
1803
|
* }
|
|
@@ -872,18 +1822,28 @@ var Tools = class {
|
|
|
872
1822
|
return this.handleComposioToolExecution(composioTool, body, modifiers);
|
|
873
1823
|
}
|
|
874
1824
|
} catch (error) {
|
|
875
|
-
throw new ComposioToolExecutionError(
|
|
876
|
-
|
|
877
|
-
|
|
1825
|
+
throw new ComposioToolExecutionError(`Error executing tool ${slug}`, {
|
|
1826
|
+
originalError: error,
|
|
1827
|
+
meta: {
|
|
1828
|
+
toolSlug: slug,
|
|
1829
|
+
body
|
|
1830
|
+
}
|
|
878
1831
|
});
|
|
879
1832
|
}
|
|
880
1833
|
}
|
|
881
1834
|
/**
|
|
882
1835
|
* Fetches the list of all available tools in the Composio SDK.
|
|
883
1836
|
*
|
|
884
|
-
* This method is mostly used by the CLI
|
|
1837
|
+
* This method is mostly used by the CLI to get the list of tools.
|
|
885
1838
|
* No filtering is done on the tools, the list is cached in the backend, no further optimization is required.
|
|
886
|
-
* @returns {
|
|
1839
|
+
* @returns {Promise<ToolRetrieveEnumResponse>} The complete list of all available tools with their metadata
|
|
1840
|
+
*
|
|
1841
|
+
* @example
|
|
1842
|
+
* ```typescript
|
|
1843
|
+
* // Get all available tools as an enum
|
|
1844
|
+
* const toolsEnum = await composio.tools.getToolsEnum();
|
|
1845
|
+
* console.log(toolsEnum.items);
|
|
1846
|
+
* ```
|
|
887
1847
|
*/
|
|
888
1848
|
async getToolsEnum() {
|
|
889
1849
|
return this.client.tools.retrieveEnum();
|
|
@@ -895,18 +1855,69 @@ var Tools = class {
|
|
|
895
1855
|
*
|
|
896
1856
|
* @param {string} slug - The ID of the tool to find input for
|
|
897
1857
|
* @param {ToolGetInputParams} body - The parameters to be passed to the tool
|
|
898
|
-
* @returns
|
|
1858
|
+
* @returns {Promise<ToolGetInputResponse>} The input parameters schema for the specified tool
|
|
1859
|
+
*
|
|
1860
|
+
* @example
|
|
1861
|
+
* ```typescript
|
|
1862
|
+
* // Get input parameters for a specific tool
|
|
1863
|
+
* const inputParams = await composio.tools.getInput('GITHUB_CREATE_ISSUE', {
|
|
1864
|
+
* userId: 'default'
|
|
1865
|
+
* });
|
|
1866
|
+
* console.log(inputParams.schema);
|
|
1867
|
+
* ```
|
|
899
1868
|
*/
|
|
900
1869
|
async getInput(slug, body) {
|
|
901
1870
|
return this.client.tools.getInput(slug, body);
|
|
902
1871
|
}
|
|
903
1872
|
/**
|
|
904
|
-
* Proxies a custom request to a toolkit/integration
|
|
905
|
-
*
|
|
906
|
-
*
|
|
1873
|
+
* Proxies a custom request to a toolkit/integration.
|
|
1874
|
+
*
|
|
1875
|
+
* This method allows sending custom requests to a specific toolkit or integration
|
|
1876
|
+
* when you need more flexibility than the standard tool execution methods provide.
|
|
1877
|
+
*
|
|
1878
|
+
* @param {ToolProxyParams} body - The parameters for the proxy request including toolkit slug and custom data
|
|
1879
|
+
* @returns {Promise<ToolProxyResponse>} The response from the proxied request
|
|
1880
|
+
*
|
|
1881
|
+
* @example
|
|
1882
|
+
* ```typescript
|
|
1883
|
+
* // Send a custom request to a toolkit
|
|
1884
|
+
* const response = await composio.tools.proxyExecute({
|
|
1885
|
+
* toolkitSlug: 'github',
|
|
1886
|
+
* userId: 'default',
|
|
1887
|
+
* data: {
|
|
1888
|
+
* endpoint: '/repos/owner/repo/issues',
|
|
1889
|
+
* method: 'GET'
|
|
1890
|
+
* }
|
|
1891
|
+
* });
|
|
1892
|
+
* console.log(response.data);
|
|
1893
|
+
* ```
|
|
907
1894
|
*/
|
|
908
1895
|
async proxyExecute(body) {
|
|
909
|
-
|
|
1896
|
+
const toolProxyParams = ToolProxyParamsSchema.safeParse(body);
|
|
1897
|
+
if (!toolProxyParams.success) {
|
|
1898
|
+
throw new ValidationError("Invalid tool proxy parameters", { cause: toolProxyParams.error });
|
|
1899
|
+
}
|
|
1900
|
+
const parameters = [];
|
|
1901
|
+
const parameterTypes = {
|
|
1902
|
+
header: "header",
|
|
1903
|
+
query: "query"
|
|
1904
|
+
};
|
|
1905
|
+
if (toolProxyParams.data.parameters) {
|
|
1906
|
+
parameters.push(
|
|
1907
|
+
...Object.entries(toolProxyParams.data.parameters).map(([key, value]) => ({
|
|
1908
|
+
name: key,
|
|
1909
|
+
type: value.in === "header" ? parameterTypes.header : parameterTypes.query,
|
|
1910
|
+
value: value.value.toString()
|
|
1911
|
+
}))
|
|
1912
|
+
);
|
|
1913
|
+
}
|
|
1914
|
+
return this.client.tools.proxy({
|
|
1915
|
+
endpoint: toolProxyParams.data.endpoint,
|
|
1916
|
+
method: toolProxyParams.data.method,
|
|
1917
|
+
body: toolProxyParams.data.body,
|
|
1918
|
+
connected_account_id: toolProxyParams.data.connectedAccountId,
|
|
1919
|
+
parameters
|
|
1920
|
+
});
|
|
910
1921
|
}
|
|
911
1922
|
/**
|
|
912
1923
|
* Creates a custom tool that can be used within the Composio SDK.
|
|
@@ -919,120 +1930,130 @@ var Tools = class {
|
|
|
919
1930
|
*
|
|
920
1931
|
* @example
|
|
921
1932
|
* ```typescript
|
|
922
|
-
*
|
|
1933
|
+
* // creating a custom tool with a toolkit
|
|
1934
|
+
* await composio.tools.createCustomTool({
|
|
923
1935
|
* name: 'My Custom Tool',
|
|
924
1936
|
* description: 'A custom tool that does something specific',
|
|
925
1937
|
* slug: 'MY_CUSTOM_TOOL',
|
|
926
|
-
*
|
|
927
|
-
*
|
|
928
|
-
*
|
|
929
|
-
*
|
|
930
|
-
*
|
|
931
|
-
*
|
|
932
|
-
*
|
|
933
|
-
* outputParameters: {
|
|
934
|
-
* result: {
|
|
935
|
-
* type: 'string',
|
|
936
|
-
* description: 'The result of the operation'
|
|
937
|
-
* }
|
|
938
|
-
* },
|
|
939
|
-
* handler: async (params, context) => {
|
|
1938
|
+
* userId: 'default',
|
|
1939
|
+
* connectedAccountId: '123',
|
|
1940
|
+
* toolkitSlug: 'github',
|
|
1941
|
+
* inputParameters: z.object({
|
|
1942
|
+
* param1: z.string().describe('First parameter'),
|
|
1943
|
+
* }),
|
|
1944
|
+
* execute: async (input, authCredentials, executeToolRequest) => {
|
|
940
1945
|
* // Custom logic here
|
|
941
1946
|
* return { data: { result: 'Success!' } };
|
|
942
1947
|
* }
|
|
943
1948
|
* });
|
|
944
1949
|
* ```
|
|
1950
|
+
*
|
|
1951
|
+
* @example
|
|
1952
|
+
* ```typescript
|
|
1953
|
+
* // creating a custom tool without a toolkit
|
|
1954
|
+
* await composio.tools.createCustomTool({
|
|
1955
|
+
* name: 'My Custom Tool',
|
|
1956
|
+
* description: 'A custom tool that does something specific',
|
|
1957
|
+
* slug: 'MY_CUSTOM_TOOL',
|
|
1958
|
+
* inputParameters: z.object({
|
|
1959
|
+
* param1: z.string().describe('First parameter'),
|
|
1960
|
+
* }),
|
|
1961
|
+
* execute: async (input) => {
|
|
1962
|
+
* // Custom logic here
|
|
1963
|
+
* return { data: { result: 'Success!' } };
|
|
1964
|
+
* }
|
|
1965
|
+
* });
|
|
945
1966
|
*/
|
|
946
1967
|
async createCustomTool(body) {
|
|
947
1968
|
return this.customTools.createTool(body);
|
|
948
1969
|
}
|
|
949
1970
|
};
|
|
950
1971
|
|
|
1972
|
+
// src/models/Toolkits.ts
|
|
1973
|
+
import ComposioClient2 from "@composio/client";
|
|
1974
|
+
|
|
951
1975
|
// src/types/toolkit.types.ts
|
|
952
|
-
import { z as
|
|
953
|
-
var ToolkitMangedByEnumSchema =
|
|
954
|
-
var ToolkitSortByEnumSchema =
|
|
955
|
-
var ToolkitsListParamsSchema =
|
|
956
|
-
category:
|
|
957
|
-
isLocal:
|
|
1976
|
+
import { z as z3 } from "zod";
|
|
1977
|
+
var ToolkitMangedByEnumSchema = z3.enum(["all", "composio", "project"]);
|
|
1978
|
+
var ToolkitSortByEnumSchema = z3.enum(["usage", "alphabetically"]);
|
|
1979
|
+
var ToolkitsListParamsSchema = z3.object({
|
|
1980
|
+
category: z3.string().optional(),
|
|
1981
|
+
isLocal: z3.boolean().optional(),
|
|
958
1982
|
managedBy: ToolkitMangedByEnumSchema.optional(),
|
|
959
1983
|
sortBy: ToolkitSortByEnumSchema.optional()
|
|
960
1984
|
});
|
|
961
|
-
var ToolKitMetaSchema =
|
|
962
|
-
categories:
|
|
963
|
-
|
|
964
|
-
slug:
|
|
965
|
-
name:
|
|
1985
|
+
var ToolKitMetaSchema = z3.object({
|
|
1986
|
+
categories: z3.array(
|
|
1987
|
+
z3.object({
|
|
1988
|
+
slug: z3.string(),
|
|
1989
|
+
name: z3.string()
|
|
966
1990
|
})
|
|
967
1991
|
).optional(),
|
|
968
|
-
appUrl:
|
|
969
|
-
createdAt:
|
|
970
|
-
description:
|
|
971
|
-
logo:
|
|
972
|
-
toolsCount:
|
|
973
|
-
triggersCount:
|
|
974
|
-
updatedAt:
|
|
1992
|
+
appUrl: z3.string().optional(),
|
|
1993
|
+
createdAt: z3.string().optional(),
|
|
1994
|
+
description: z3.string().optional(),
|
|
1995
|
+
logo: z3.string().optional(),
|
|
1996
|
+
toolsCount: z3.number().optional(),
|
|
1997
|
+
triggersCount: z3.number().optional(),
|
|
1998
|
+
updatedAt: z3.string().optional()
|
|
975
1999
|
});
|
|
976
|
-
var ToolKitItemSchema =
|
|
977
|
-
name:
|
|
978
|
-
slug:
|
|
2000
|
+
var ToolKitItemSchema = z3.object({
|
|
2001
|
+
name: z3.string(),
|
|
2002
|
+
slug: z3.string(),
|
|
979
2003
|
meta: ToolKitMetaSchema,
|
|
980
|
-
isLocalToolkit:
|
|
981
|
-
authSchemes:
|
|
982
|
-
composioManagedAuthSchemes:
|
|
983
|
-
noAuth:
|
|
2004
|
+
isLocalToolkit: z3.boolean(),
|
|
2005
|
+
authSchemes: z3.array(z3.string()).optional(),
|
|
2006
|
+
composioManagedAuthSchemes: z3.array(z3.string()).optional(),
|
|
2007
|
+
noAuth: z3.boolean().optional()
|
|
984
2008
|
});
|
|
985
|
-
var ToolKitListResponseSchema =
|
|
986
|
-
items:
|
|
987
|
-
nextCursor:
|
|
988
|
-
totalPages:
|
|
2009
|
+
var ToolKitListResponseSchema = z3.object({
|
|
2010
|
+
items: z3.array(ToolKitItemSchema),
|
|
2011
|
+
nextCursor: z3.string().nullable(),
|
|
2012
|
+
totalPages: z3.number()
|
|
989
2013
|
});
|
|
990
|
-
var ToolkitAuthFieldSchema =
|
|
991
|
-
name:
|
|
992
|
-
displayName:
|
|
993
|
-
type:
|
|
994
|
-
default:
|
|
2014
|
+
var ToolkitAuthFieldSchema = z3.object({
|
|
2015
|
+
name: z3.string(),
|
|
2016
|
+
displayName: z3.string(),
|
|
2017
|
+
type: z3.string(),
|
|
2018
|
+
default: z3.string().nullable().optional()
|
|
995
2019
|
});
|
|
996
|
-
var ToolkitAuthConfigDetailsSchema =
|
|
997
|
-
name:
|
|
998
|
-
mode:
|
|
999
|
-
fields:
|
|
1000
|
-
authConfigCreation:
|
|
1001
|
-
optional:
|
|
1002
|
-
required:
|
|
2020
|
+
var ToolkitAuthConfigDetailsSchema = z3.object({
|
|
2021
|
+
name: z3.string(),
|
|
2022
|
+
mode: z3.string(),
|
|
2023
|
+
fields: z3.object({
|
|
2024
|
+
authConfigCreation: z3.object({
|
|
2025
|
+
optional: z3.array(ToolkitAuthFieldSchema),
|
|
2026
|
+
required: z3.array(ToolkitAuthFieldSchema)
|
|
1003
2027
|
}),
|
|
1004
|
-
connectedAccountInitiation:
|
|
1005
|
-
optional:
|
|
1006
|
-
required:
|
|
2028
|
+
connectedAccountInitiation: z3.object({
|
|
2029
|
+
optional: z3.array(ToolkitAuthFieldSchema),
|
|
2030
|
+
required: z3.array(ToolkitAuthFieldSchema)
|
|
1007
2031
|
})
|
|
1008
2032
|
}),
|
|
1009
|
-
proxy:
|
|
1010
|
-
baseUrl:
|
|
2033
|
+
proxy: z3.object({
|
|
2034
|
+
baseUrl: z3.string().optional()
|
|
1011
2035
|
}).optional()
|
|
1012
2036
|
});
|
|
1013
|
-
var ToolkitRetrieveResponseSchema =
|
|
1014
|
-
name:
|
|
1015
|
-
slug:
|
|
2037
|
+
var ToolkitRetrieveResponseSchema = z3.object({
|
|
2038
|
+
name: z3.string(),
|
|
2039
|
+
slug: z3.string(),
|
|
1016
2040
|
meta: ToolKitMetaSchema,
|
|
1017
|
-
isLocalToolkit:
|
|
1018
|
-
composioManagedAuthSchemes:
|
|
1019
|
-
authConfigDetails:
|
|
2041
|
+
isLocalToolkit: z3.boolean(),
|
|
2042
|
+
composioManagedAuthSchemes: z3.array(z3.string()).optional(),
|
|
2043
|
+
authConfigDetails: z3.array(ToolkitAuthConfigDetailsSchema).optional()
|
|
1020
2044
|
});
|
|
1021
|
-
var ToolkitCategorySchema =
|
|
1022
|
-
id:
|
|
1023
|
-
name:
|
|
2045
|
+
var ToolkitCategorySchema = z3.object({
|
|
2046
|
+
id: z3.string(),
|
|
2047
|
+
name: z3.string()
|
|
1024
2048
|
});
|
|
1025
|
-
var ToolkitRetrieveCategoriesResponseSchema =
|
|
1026
|
-
items:
|
|
1027
|
-
nextCursor:
|
|
1028
|
-
totalPages:
|
|
2049
|
+
var ToolkitRetrieveCategoriesResponseSchema = z3.object({
|
|
2050
|
+
items: z3.array(ToolkitCategorySchema),
|
|
2051
|
+
nextCursor: z3.string().nullable(),
|
|
2052
|
+
totalPages: z3.number()
|
|
1029
2053
|
});
|
|
1030
2054
|
|
|
1031
|
-
// src/models/Toolkits.ts
|
|
1032
|
-
import { ZodError as ZodError3 } from "zod";
|
|
1033
|
-
|
|
1034
2055
|
// src/types/authConfigs.types.ts
|
|
1035
|
-
import { z as
|
|
2056
|
+
import { z as z4 } from "zod";
|
|
1036
2057
|
var AuthConfigTypes = {
|
|
1037
2058
|
CUSTOM: "use_custom_auth",
|
|
1038
2059
|
COMPOSIO_MANAGED: "use_composio_managed_auth"
|
|
@@ -1052,7 +2073,7 @@ var AuthSchemeTypes = {
|
|
|
1052
2073
|
CALCOM_AUTH: "CALCOM_AUTH",
|
|
1053
2074
|
SNOWFLAKE: "SNOWFLAKE"
|
|
1054
2075
|
};
|
|
1055
|
-
var AuthSchemeEnum =
|
|
2076
|
+
var AuthSchemeEnum = z4.enum([
|
|
1056
2077
|
"OAUTH2",
|
|
1057
2078
|
"OAUTH1",
|
|
1058
2079
|
"OAUTH1A",
|
|
@@ -1067,67 +2088,67 @@ var AuthSchemeEnum = z3.enum([
|
|
|
1067
2088
|
"CALCOM_AUTH",
|
|
1068
2089
|
"SNOWFLAKE"
|
|
1069
2090
|
]);
|
|
1070
|
-
var CreateCustomAuthConfigParamsSchema =
|
|
1071
|
-
type:
|
|
1072
|
-
name:
|
|
1073
|
-
credentials:
|
|
2091
|
+
var CreateCustomAuthConfigParamsSchema = z4.object({
|
|
2092
|
+
type: z4.literal("use_custom_auth"),
|
|
2093
|
+
name: z4.string().optional(),
|
|
2094
|
+
credentials: z4.record(z4.string(), z4.union([z4.string(), z4.number(), z4.boolean()])),
|
|
1074
2095
|
authScheme: AuthSchemeEnum
|
|
1075
2096
|
});
|
|
1076
|
-
var CreateComposioManagedAuthConfigParamsSchema =
|
|
1077
|
-
type:
|
|
1078
|
-
name:
|
|
1079
|
-
credentials:
|
|
2097
|
+
var CreateComposioManagedAuthConfigParamsSchema = z4.object({
|
|
2098
|
+
type: z4.literal("use_composio_managed_auth"),
|
|
2099
|
+
name: z4.string().optional(),
|
|
2100
|
+
credentials: z4.record(z4.string(), z4.union([z4.string(), z4.number(), z4.boolean()])).optional()
|
|
1080
2101
|
});
|
|
1081
|
-
var CreateAuthConfigParamsSchema =
|
|
2102
|
+
var CreateAuthConfigParamsSchema = z4.discriminatedUnion("type", [
|
|
1082
2103
|
CreateCustomAuthConfigParamsSchema,
|
|
1083
2104
|
CreateComposioManagedAuthConfigParamsSchema
|
|
1084
2105
|
]);
|
|
1085
|
-
var CreateAuthConfigResponseSchema =
|
|
1086
|
-
id:
|
|
1087
|
-
authScheme:
|
|
1088
|
-
isComposioManaged:
|
|
1089
|
-
toolkit:
|
|
2106
|
+
var CreateAuthConfigResponseSchema = z4.object({
|
|
2107
|
+
id: z4.string(),
|
|
2108
|
+
authScheme: z4.string(),
|
|
2109
|
+
isComposioManaged: z4.boolean(),
|
|
2110
|
+
toolkit: z4.string()
|
|
1090
2111
|
});
|
|
1091
|
-
var AuthConfigRetrieveResponseSchema =
|
|
1092
|
-
id:
|
|
1093
|
-
name:
|
|
1094
|
-
toolkit:
|
|
1095
|
-
logo:
|
|
1096
|
-
slug:
|
|
2112
|
+
var AuthConfigRetrieveResponseSchema = z4.object({
|
|
2113
|
+
id: z4.string(),
|
|
2114
|
+
name: z4.string(),
|
|
2115
|
+
toolkit: z4.object({
|
|
2116
|
+
logo: z4.string(),
|
|
2117
|
+
slug: z4.string()
|
|
1097
2118
|
}),
|
|
1098
|
-
noOfConnections:
|
|
1099
|
-
status:
|
|
1100
|
-
uuid:
|
|
2119
|
+
noOfConnections: z4.number(),
|
|
2120
|
+
status: z4.enum(["ENABLED", "DISABLED"]),
|
|
2121
|
+
uuid: z4.string(),
|
|
1101
2122
|
authScheme: AuthSchemeEnum.optional(),
|
|
1102
|
-
credentials:
|
|
1103
|
-
expectedInputFields:
|
|
1104
|
-
isComposioManaged:
|
|
1105
|
-
createdBy:
|
|
1106
|
-
createdAt:
|
|
1107
|
-
lastUpdatedAt:
|
|
2123
|
+
credentials: z4.record(z4.string(), z4.unknown()).optional(),
|
|
2124
|
+
expectedInputFields: z4.array(z4.unknown()).optional(),
|
|
2125
|
+
isComposioManaged: z4.boolean().optional(),
|
|
2126
|
+
createdBy: z4.string().optional(),
|
|
2127
|
+
createdAt: z4.string().optional(),
|
|
2128
|
+
lastUpdatedAt: z4.string().optional()
|
|
1108
2129
|
});
|
|
1109
|
-
var AuthConfigListParamsSchema =
|
|
1110
|
-
cursor:
|
|
1111
|
-
isComposioManaged:
|
|
1112
|
-
limit:
|
|
1113
|
-
|
|
2130
|
+
var AuthConfigListParamsSchema = z4.object({
|
|
2131
|
+
cursor: z4.string().optional(),
|
|
2132
|
+
isComposioManaged: z4.boolean().optional(),
|
|
2133
|
+
limit: z4.number().optional(),
|
|
2134
|
+
toolkit: z4.string().optional()
|
|
1114
2135
|
});
|
|
1115
|
-
var AuthConfigListResponseSchema =
|
|
1116
|
-
items:
|
|
1117
|
-
nextCursor:
|
|
1118
|
-
totalPages:
|
|
2136
|
+
var AuthConfigListResponseSchema = z4.object({
|
|
2137
|
+
items: z4.array(AuthConfigRetrieveResponseSchema),
|
|
2138
|
+
nextCursor: z4.string().nullable(),
|
|
2139
|
+
totalPages: z4.number()
|
|
1119
2140
|
});
|
|
1120
|
-
var AuthCustomConfigUpdateParamsSchema =
|
|
1121
|
-
credentials:
|
|
1122
|
-
type:
|
|
1123
|
-
restrictToFollowingTools:
|
|
2141
|
+
var AuthCustomConfigUpdateParamsSchema = z4.object({
|
|
2142
|
+
credentials: z4.record(z4.string(), z4.union([z4.string(), z4.unknown()])),
|
|
2143
|
+
type: z4.literal("custom"),
|
|
2144
|
+
restrictToFollowingTools: z4.array(z4.string()).optional()
|
|
1124
2145
|
});
|
|
1125
|
-
var AuthDefaultConfigUpdateParamsSchema =
|
|
1126
|
-
scopes:
|
|
1127
|
-
type:
|
|
1128
|
-
restrictToFollowingTools:
|
|
2146
|
+
var AuthDefaultConfigUpdateParamsSchema = z4.object({
|
|
2147
|
+
scopes: z4.string(),
|
|
2148
|
+
type: z4.literal("default"),
|
|
2149
|
+
restrictToFollowingTools: z4.array(z4.string()).optional()
|
|
1129
2150
|
});
|
|
1130
|
-
var AuthConfigUpdateParamsSchema =
|
|
2151
|
+
var AuthConfigUpdateParamsSchema = z4.discriminatedUnion("type", [
|
|
1131
2152
|
AuthCustomConfigUpdateParamsSchema,
|
|
1132
2153
|
AuthDefaultConfigUpdateParamsSchema
|
|
1133
2154
|
]);
|
|
@@ -1137,6 +2158,7 @@ var AuthConfigs = class {
|
|
|
1137
2158
|
client;
|
|
1138
2159
|
constructor(client) {
|
|
1139
2160
|
this.client = client;
|
|
2161
|
+
telemetry.instrument(this);
|
|
1140
2162
|
}
|
|
1141
2163
|
/**
|
|
1142
2164
|
* Protected getter for the client instance.
|
|
@@ -1178,7 +2200,9 @@ var AuthConfigs = class {
|
|
|
1178
2200
|
lastUpdatedAt: authConfig.last_updated_at
|
|
1179
2201
|
});
|
|
1180
2202
|
if (result.error) {
|
|
1181
|
-
throw new ValidationError(
|
|
2203
|
+
throw new ValidationError("Failed to parse auth config response", {
|
|
2204
|
+
cause: result.error
|
|
2205
|
+
});
|
|
1182
2206
|
}
|
|
1183
2207
|
return result.data;
|
|
1184
2208
|
}
|
|
@@ -1199,7 +2223,7 @@ var AuthConfigs = class {
|
|
|
1199
2223
|
*
|
|
1200
2224
|
* // List auth configs for a specific toolkit
|
|
1201
2225
|
* const githubConfigs = await composio.authConfigs.list({
|
|
1202
|
-
*
|
|
2226
|
+
* toolkit: 'github'
|
|
1203
2227
|
* });
|
|
1204
2228
|
*
|
|
1205
2229
|
* // List Composio-managed auth configs
|
|
@@ -1213,8 +2237,8 @@ var AuthConfigs = class {
|
|
|
1213
2237
|
const result = await this.client.authConfigs.list({
|
|
1214
2238
|
cursor: parsedQuery?.cursor,
|
|
1215
2239
|
is_composio_managed: parsedQuery?.isComposioManaged,
|
|
1216
|
-
limit: parsedQuery?.limit
|
|
1217
|
-
toolkit_slug: parsedQuery?.
|
|
2240
|
+
limit: parsedQuery?.limit,
|
|
2241
|
+
toolkit_slug: parsedQuery?.toolkit
|
|
1218
2242
|
});
|
|
1219
2243
|
const parsedResult = AuthConfigListResponseSchema.safeParse({
|
|
1220
2244
|
items: result.items.map((item) => this.parseAuthConfigRetrieveResponse(item)),
|
|
@@ -1222,7 +2246,9 @@ var AuthConfigs = class {
|
|
|
1222
2246
|
totalPages: result.total_pages
|
|
1223
2247
|
});
|
|
1224
2248
|
if (parsedResult.error) {
|
|
1225
|
-
throw new ValidationError(
|
|
2249
|
+
throw new ValidationError("Failed to parse auth config list response", {
|
|
2250
|
+
cause: parsedResult.error
|
|
2251
|
+
});
|
|
1226
2252
|
}
|
|
1227
2253
|
return parsedResult.data;
|
|
1228
2254
|
}
|
|
@@ -1247,7 +2273,9 @@ var AuthConfigs = class {
|
|
|
1247
2273
|
async create(toolkit, options = { type: "use_composio_managed_auth" }) {
|
|
1248
2274
|
const parsedOptions = CreateAuthConfigParamsSchema.safeParse(options);
|
|
1249
2275
|
if (parsedOptions.error) {
|
|
1250
|
-
throw new ValidationError(
|
|
2276
|
+
throw new ValidationError("Failed to parse auth config create options", {
|
|
2277
|
+
cause: parsedOptions.error
|
|
2278
|
+
});
|
|
1251
2279
|
}
|
|
1252
2280
|
const result = await this.client.authConfigs.create({
|
|
1253
2281
|
toolkit: {
|
|
@@ -1262,7 +2290,9 @@ var AuthConfigs = class {
|
|
|
1262
2290
|
toolkit: result.toolkit.slug
|
|
1263
2291
|
});
|
|
1264
2292
|
if (parsedResult.error) {
|
|
1265
|
-
throw new ValidationError(
|
|
2293
|
+
throw new ValidationError("Failed to parse auth config create response", {
|
|
2294
|
+
cause: parsedResult.error
|
|
2295
|
+
});
|
|
1266
2296
|
}
|
|
1267
2297
|
return parsedResult.data;
|
|
1268
2298
|
}
|
|
@@ -1322,7 +2352,9 @@ var AuthConfigs = class {
|
|
|
1322
2352
|
async update(nanoid, data) {
|
|
1323
2353
|
const parsedData = AuthConfigUpdateParamsSchema.safeParse(data);
|
|
1324
2354
|
if (parsedData.error) {
|
|
1325
|
-
throw new ValidationError(
|
|
2355
|
+
throw new ValidationError("Failed to parse auth config update data", {
|
|
2356
|
+
cause: parsedData.error
|
|
2357
|
+
});
|
|
1326
2358
|
}
|
|
1327
2359
|
return this.client.authConfigs.update(
|
|
1328
2360
|
nanoid,
|
|
@@ -1335,257 +2367,97 @@ var AuthConfigs = class {
|
|
|
1335
2367
|
scopes: parsedData.data.scopes,
|
|
1336
2368
|
restrict_to_following_tools: parsedData.data.restrictToFollowingTools
|
|
1337
2369
|
}
|
|
1338
|
-
);
|
|
1339
|
-
}
|
|
1340
|
-
/**
|
|
1341
|
-
* Deletes an authentication configuration.
|
|
1342
|
-
*
|
|
1343
|
-
* This method permanently removes an auth config from the Composio platform.
|
|
1344
|
-
* This action cannot be undone and will prevent any connected accounts that use
|
|
1345
|
-
* this auth config from functioning.
|
|
1346
|
-
*
|
|
1347
|
-
* @param {string} nanoid - The unique identifier of the auth config to delete
|
|
1348
|
-
* @returns {Promise<AuthConfigDeleteResponse>} The deletion response
|
|
1349
|
-
* @throws {Error} If the auth config doesn't exist or cannot be deleted
|
|
1350
|
-
*
|
|
1351
|
-
* @example
|
|
1352
|
-
* ```typescript
|
|
1353
|
-
* // Delete an auth config
|
|
1354
|
-
* await composio.authConfigs.delete('auth_abc123');
|
|
1355
|
-
* ```
|
|
1356
|
-
*/
|
|
1357
|
-
async delete(nanoid) {
|
|
1358
|
-
return this.client.authConfigs.delete(nanoid);
|
|
1359
|
-
}
|
|
1360
|
-
/**
|
|
1361
|
-
* Updates the status of an authentication configuration.
|
|
1362
|
-
*
|
|
1363
|
-
* This method allows you to enable or disable an auth config. When disabled,
|
|
1364
|
-
* the auth config cannot be used to create new connected accounts or authenticate
|
|
1365
|
-
* with third-party services.
|
|
1366
|
-
*
|
|
1367
|
-
* @param {string} status - The status to set ('ENABLED' or 'DISABLED')
|
|
1368
|
-
* @param {string} nanoid - The unique identifier of the auth config
|
|
1369
|
-
* @returns {Promise<AuthConfigUpdateStatusResponse>} The updated auth config details
|
|
1370
|
-
* @throws {Error} If the auth config cannot be found or the status cannot be updated
|
|
1371
|
-
*
|
|
1372
|
-
* @example
|
|
1373
|
-
* ```typescript
|
|
1374
|
-
* // Disable an auth config
|
|
1375
|
-
* await composio.authConfigs.updateStatus('DISABLED', 'auth_abc123');
|
|
1376
|
-
*
|
|
1377
|
-
* // Enable an auth config
|
|
1378
|
-
* await composio.authConfigs.updateStatus('ENABLED', 'auth_abc123');
|
|
1379
|
-
* ```
|
|
1380
|
-
*/
|
|
1381
|
-
async updateStatus(status, nanoid) {
|
|
1382
|
-
return this.client.authConfigs.updateStatus(status, { nanoid });
|
|
1383
|
-
}
|
|
1384
|
-
/**
|
|
1385
|
-
* Enables an authentication configuration.
|
|
1386
|
-
*
|
|
1387
|
-
* This is a convenience method that calls updateStatus with 'ENABLED'.
|
|
1388
|
-
* When enabled, the auth config can be used to create new connected accounts
|
|
1389
|
-
* and authenticate with third-party services.
|
|
1390
|
-
*
|
|
1391
|
-
* @param {string} nanoid - The unique identifier of the auth config to enable
|
|
1392
|
-
* @returns {Promise<AuthConfigUpdateStatusResponse>} The updated auth config details
|
|
1393
|
-
* @throws {Error} If the auth config cannot be found or enabled
|
|
1394
|
-
*
|
|
1395
|
-
* @example
|
|
1396
|
-
* ```typescript
|
|
1397
|
-
* // Enable an auth config
|
|
1398
|
-
* await composio.authConfigs.enable('auth_abc123');
|
|
1399
|
-
* ```
|
|
1400
|
-
*/
|
|
1401
|
-
async enable(nanoid) {
|
|
1402
|
-
return this.client.authConfigs.updateStatus("ENABLED", { nanoid });
|
|
1403
|
-
}
|
|
1404
|
-
/**
|
|
1405
|
-
* Disables an authentication configuration.
|
|
1406
|
-
*
|
|
1407
|
-
* This is a convenience method that calls updateStatus with 'DISABLED'.
|
|
1408
|
-
* When disabled, the auth config cannot be used to create new connected accounts
|
|
1409
|
-
* or authenticate with third-party services, but existing connections may continue to work.
|
|
1410
|
-
*
|
|
1411
|
-
* @param {string} nanoid - The unique identifier of the auth config to disable
|
|
1412
|
-
* @returns {Promise<AuthConfigUpdateStatusResponse>} The updated auth config details
|
|
1413
|
-
* @throws {Error} If the auth config cannot be found or disabled
|
|
1414
|
-
*
|
|
1415
|
-
* @example
|
|
1416
|
-
* ```typescript
|
|
1417
|
-
* // Disable an auth config
|
|
1418
|
-
* await composio.authConfigs.disable('auth_abc123');
|
|
1419
|
-
* ```
|
|
1420
|
-
*/
|
|
1421
|
-
async disable(nanoid) {
|
|
1422
|
-
return this.client.authConfigs.updateStatus("DISABLED", { nanoid });
|
|
1423
|
-
}
|
|
1424
|
-
};
|
|
1425
|
-
|
|
1426
|
-
// src/errors/AuthConfigErrors.ts
|
|
1427
|
-
var AuthConfigErrorCodes = {
|
|
1428
|
-
AUTH_CONFIG_NOT_FOUND: "AUTH_CONFIG_NOT_FOUND"
|
|
1429
|
-
};
|
|
1430
|
-
var ComposioAuthConfigNotFoundError = class extends ComposioError {
|
|
1431
|
-
constructor(message, meta) {
|
|
1432
|
-
super(message, {
|
|
1433
|
-
code: AuthConfigErrorCodes.AUTH_CONFIG_NOT_FOUND,
|
|
1434
|
-
cause: meta,
|
|
1435
|
-
possibleFixes: [
|
|
1436
|
-
"Check if the auth config exists",
|
|
1437
|
-
"Check if the auth config id is correct",
|
|
1438
|
-
"Check if the auth config is enabled"
|
|
1439
|
-
]
|
|
1440
|
-
});
|
|
1441
|
-
this.name = "ComposioAuthConfigNotFoundError";
|
|
1442
|
-
}
|
|
1443
|
-
};
|
|
1444
|
-
|
|
1445
|
-
// src/types/connectedAccounts.types.ts
|
|
1446
|
-
import { z as z4 } from "zod";
|
|
1447
|
-
var ConnectedAccountStatuses = {
|
|
1448
|
-
ACTIVE: "ACTIVE",
|
|
1449
|
-
INACTIVE: "INACTIVE",
|
|
1450
|
-
DELETED: "DELETED",
|
|
1451
|
-
INITIATED: "INITIATED",
|
|
1452
|
-
EXPIRED: "EXPIRED",
|
|
1453
|
-
FAILED: "FAILED"
|
|
1454
|
-
};
|
|
1455
|
-
var ConnectedAccountStatusSchema = z4.enum([
|
|
1456
|
-
ConnectedAccountStatuses.ACTIVE,
|
|
1457
|
-
ConnectedAccountStatuses.INACTIVE,
|
|
1458
|
-
ConnectedAccountStatuses.DELETED,
|
|
1459
|
-
ConnectedAccountStatuses.INITIATED,
|
|
1460
|
-
ConnectedAccountStatuses.EXPIRED,
|
|
1461
|
-
ConnectedAccountStatuses.FAILED
|
|
1462
|
-
]);
|
|
1463
|
-
var CreateConnectedAccountParamsSchema = z4.object({
|
|
1464
|
-
authConfig: z4.object({
|
|
1465
|
-
id: z4.string()
|
|
1466
|
-
}),
|
|
1467
|
-
connection: z4.object({
|
|
1468
|
-
data: z4.record(z4.string(), z4.unknown()).optional(),
|
|
1469
|
-
callbackUrl: z4.string().optional(),
|
|
1470
|
-
userId: z4.string().optional()
|
|
1471
|
-
})
|
|
1472
|
-
});
|
|
1473
|
-
var DefaultCreateConnectedAccountParamsSchema = z4.object({
|
|
1474
|
-
auth_config: z4.object({
|
|
1475
|
-
id: z4.string()
|
|
1476
|
-
}),
|
|
1477
|
-
connection: z4.object({
|
|
1478
|
-
data: z4.record(z4.string(), z4.unknown()).optional(),
|
|
1479
|
-
callback_url: z4.string().optional(),
|
|
1480
|
-
user_id: z4.string().optional()
|
|
1481
|
-
})
|
|
1482
|
-
});
|
|
1483
|
-
var CreateConnectedAccountOptionsSchema = z4.object({
|
|
1484
|
-
callbackUrl: z4.string().optional(),
|
|
1485
|
-
data: z4.record(z4.string(), z4.unknown()).optional()
|
|
1486
|
-
});
|
|
1487
|
-
var CreateConnectedAccountResponseSchema = z4.object({
|
|
1488
|
-
id: z4.string(),
|
|
1489
|
-
status: ConnectedAccountStatusSchema,
|
|
1490
|
-
redirectUrl: z4.string().nullable()
|
|
1491
|
-
});
|
|
1492
|
-
var ConnectedAccountAuthSchemes = {
|
|
1493
|
-
OAUTH2: "OAUTH2",
|
|
1494
|
-
OAUTH1: "OAUTH1",
|
|
1495
|
-
OAUTH1A: "OAUTH1A",
|
|
1496
|
-
API_KEY: "API_KEY",
|
|
1497
|
-
BASIC: "BASIC",
|
|
1498
|
-
BILLCOM_AUTH: "BILLCOM_AUTH",
|
|
1499
|
-
BEARER_TOKEN: "BEARER_TOKEN",
|
|
1500
|
-
GOOGLE_SERVICE_ACCOUNT: "GOOGLE_SERVICE_ACCOUNT",
|
|
1501
|
-
NO_AUTH: "NO_AUTH",
|
|
1502
|
-
BASIC_WITH_JWT: "BASIC_WITH_JWT",
|
|
1503
|
-
COMPOSIO_LINK: "COMPOSIO_LINK",
|
|
1504
|
-
CALCOM_AUTH: "CALCOM_AUTH",
|
|
1505
|
-
SNOWFLAKE: "SNOWFLAKE"
|
|
1506
|
-
};
|
|
1507
|
-
var ConnectedAccountAuthSchemesSchema = z4.enum([
|
|
1508
|
-
ConnectedAccountAuthSchemes.OAUTH2,
|
|
1509
|
-
ConnectedAccountAuthSchemes.OAUTH1,
|
|
1510
|
-
ConnectedAccountAuthSchemes.OAUTH1A,
|
|
1511
|
-
ConnectedAccountAuthSchemes.API_KEY,
|
|
1512
|
-
ConnectedAccountAuthSchemes.BASIC,
|
|
1513
|
-
ConnectedAccountAuthSchemes.BILLCOM_AUTH,
|
|
1514
|
-
ConnectedAccountAuthSchemes.BEARER_TOKEN,
|
|
1515
|
-
ConnectedAccountAuthSchemes.GOOGLE_SERVICE_ACCOUNT,
|
|
1516
|
-
ConnectedAccountAuthSchemes.NO_AUTH,
|
|
1517
|
-
ConnectedAccountAuthSchemes.BASIC_WITH_JWT,
|
|
1518
|
-
ConnectedAccountAuthSchemes.COMPOSIO_LINK,
|
|
1519
|
-
ConnectedAccountAuthSchemes.CALCOM_AUTH,
|
|
1520
|
-
ConnectedAccountAuthSchemes.SNOWFLAKE
|
|
1521
|
-
]);
|
|
1522
|
-
var ConnectedAccountAuthConfigSchema = z4.object({
|
|
1523
|
-
id: z4.string(),
|
|
1524
|
-
authScheme: ConnectedAccountAuthSchemesSchema,
|
|
1525
|
-
isComposioManaged: z4.boolean(),
|
|
1526
|
-
isDisabled: z4.boolean()
|
|
1527
|
-
});
|
|
1528
|
-
var ConnectedAccountRetrieveResponseSchema = z4.object({
|
|
1529
|
-
id: z4.string(),
|
|
1530
|
-
authConfig: ConnectedAccountAuthConfigSchema,
|
|
1531
|
-
userId: z4.string(),
|
|
1532
|
-
data: z4.record(z4.string(), z4.unknown()),
|
|
1533
|
-
params: z4.record(z4.string(), z4.unknown()).optional(),
|
|
1534
|
-
status: ConnectedAccountStatusSchema,
|
|
1535
|
-
statusReason: z4.string().nullable(),
|
|
1536
|
-
toolkit: z4.object({
|
|
1537
|
-
slug: z4.string()
|
|
1538
|
-
}),
|
|
1539
|
-
testRequestEndpoint: z4.string().optional(),
|
|
1540
|
-
isDisabled: z4.boolean(),
|
|
1541
|
-
createdAt: z4.string(),
|
|
1542
|
-
updatedAt: z4.string()
|
|
1543
|
-
});
|
|
1544
|
-
var ConnectedAccountListParamsSchema = z4.object({
|
|
1545
|
-
authConfigIds: z4.array(z4.string()).nullable().optional().describe("The auth config ids of the connected accounts"),
|
|
1546
|
-
cursor: z4.number().nullable().optional().describe("The cursor to paginate through the connected accounts"),
|
|
1547
|
-
labels: z4.array(z4.string()).nullable().optional().describe("The labels of the connected accounts"),
|
|
1548
|
-
limit: z4.number().nullable().optional().describe("The limit of the connected accounts to return"),
|
|
1549
|
-
orderBy: z4.enum(["created_at", "updated_at"]).optional().describe("The order by of the connected accounts"),
|
|
1550
|
-
statuses: z4.array(ConnectedAccountStatusSchema).nullable().optional().describe("The statuses of the connected accounts"),
|
|
1551
|
-
toolkitSlugs: z4.array(z4.string()).nullable().optional().describe("The toolkit slugs of the connected accounts"),
|
|
1552
|
-
userIds: z4.array(z4.string()).nullable().optional().describe("The user ids of the connected accounts")
|
|
1553
|
-
});
|
|
1554
|
-
var ConnectedAccountListResponseSchema = z4.object({
|
|
1555
|
-
items: z4.array(ConnectedAccountRetrieveResponseSchema).describe("The list of connected accounts"),
|
|
1556
|
-
nextCursor: z4.string().nullable().describe("The next cursor to paginate through the connected accounts"),
|
|
1557
|
-
totalPages: z4.number().describe("The total number of pages of connected accounts")
|
|
1558
|
-
});
|
|
1559
|
-
|
|
1560
|
-
// src/models/ConnectionRequest.ts
|
|
1561
|
-
import ComposioClient from "@composio/client";
|
|
1562
|
-
import { ZodError as ZodError2 } from "zod";
|
|
1563
|
-
|
|
1564
|
-
// src/errors/ConnectionRequestError.ts
|
|
1565
|
-
var ConnectionRequestErrorCodes = {
|
|
1566
|
-
CONNECTION_REQUEST_TIMEOUT: "CONNECTION_REQUEST_TIMEOUT",
|
|
1567
|
-
CONNECTION_REQUEST_FAILED: "CONNECTION_REQUEST_FAILED"
|
|
1568
|
-
};
|
|
1569
|
-
var ConnectionRequestTimeoutError = class extends ComposioError {
|
|
1570
|
-
constructor(message = "Connection request timed out", meta = {}) {
|
|
1571
|
-
super(message, {
|
|
1572
|
-
code: ConnectionRequestErrorCodes.CONNECTION_REQUEST_TIMEOUT,
|
|
1573
|
-
meta
|
|
1574
|
-
});
|
|
1575
|
-
this.name = "ConnectionRequestTimeoutError";
|
|
2370
|
+
);
|
|
1576
2371
|
}
|
|
1577
|
-
|
|
1578
|
-
|
|
1579
|
-
|
|
1580
|
-
|
|
1581
|
-
|
|
1582
|
-
|
|
1583
|
-
|
|
1584
|
-
|
|
2372
|
+
/**
|
|
2373
|
+
* Deletes an authentication configuration.
|
|
2374
|
+
*
|
|
2375
|
+
* This method permanently removes an auth config from the Composio platform.
|
|
2376
|
+
* This action cannot be undone and will prevent any connected accounts that use
|
|
2377
|
+
* this auth config from functioning.
|
|
2378
|
+
*
|
|
2379
|
+
* @param {string} nanoid - The unique identifier of the auth config to delete
|
|
2380
|
+
* @returns {Promise<AuthConfigDeleteResponse>} The deletion response
|
|
2381
|
+
* @throws {Error} If the auth config doesn't exist or cannot be deleted
|
|
2382
|
+
*
|
|
2383
|
+
* @example
|
|
2384
|
+
* ```typescript
|
|
2385
|
+
* // Delete an auth config
|
|
2386
|
+
* await composio.authConfigs.delete('auth_abc123');
|
|
2387
|
+
* ```
|
|
2388
|
+
*/
|
|
2389
|
+
async delete(nanoid) {
|
|
2390
|
+
return this.client.authConfigs.delete(nanoid);
|
|
2391
|
+
}
|
|
2392
|
+
/**
|
|
2393
|
+
* Updates the status of an authentication configuration.
|
|
2394
|
+
*
|
|
2395
|
+
* This method allows you to enable or disable an auth config. When disabled,
|
|
2396
|
+
* the auth config cannot be used to create new connected accounts or authenticate
|
|
2397
|
+
* with third-party services.
|
|
2398
|
+
*
|
|
2399
|
+
* @param {string} status - The status to set ('ENABLED' or 'DISABLED')
|
|
2400
|
+
* @param {string} nanoid - The unique identifier of the auth config
|
|
2401
|
+
* @returns {Promise<AuthConfigUpdateStatusResponse>} The updated auth config details
|
|
2402
|
+
* @throws {Error} If the auth config cannot be found or the status cannot be updated
|
|
2403
|
+
*
|
|
2404
|
+
* @example
|
|
2405
|
+
* ```typescript
|
|
2406
|
+
* // Disable an auth config
|
|
2407
|
+
* await composio.authConfigs.updateStatus('DISABLED', 'auth_abc123');
|
|
2408
|
+
*
|
|
2409
|
+
* // Enable an auth config
|
|
2410
|
+
* await composio.authConfigs.updateStatus('ENABLED', 'auth_abc123');
|
|
2411
|
+
* ```
|
|
2412
|
+
*/
|
|
2413
|
+
async updateStatus(status, nanoid) {
|
|
2414
|
+
return this.client.authConfigs.updateStatus(status, { nanoid });
|
|
2415
|
+
}
|
|
2416
|
+
/**
|
|
2417
|
+
* Enables an authentication configuration.
|
|
2418
|
+
*
|
|
2419
|
+
* This is a convenience method that calls updateStatus with 'ENABLED'.
|
|
2420
|
+
* When enabled, the auth config can be used to create new connected accounts
|
|
2421
|
+
* and authenticate with third-party services.
|
|
2422
|
+
*
|
|
2423
|
+
* @param {string} nanoid - The unique identifier of the auth config to enable
|
|
2424
|
+
* @returns {Promise<AuthConfigUpdateStatusResponse>} The updated auth config details
|
|
2425
|
+
* @throws {Error} If the auth config cannot be found or enabled
|
|
2426
|
+
*
|
|
2427
|
+
* @example
|
|
2428
|
+
* ```typescript
|
|
2429
|
+
* // Enable an auth config
|
|
2430
|
+
* await composio.authConfigs.enable('auth_abc123');
|
|
2431
|
+
* ```
|
|
2432
|
+
*/
|
|
2433
|
+
async enable(nanoid) {
|
|
2434
|
+
return this.client.authConfigs.updateStatus("ENABLED", { nanoid });
|
|
2435
|
+
}
|
|
2436
|
+
/**
|
|
2437
|
+
* Disables an authentication configuration.
|
|
2438
|
+
*
|
|
2439
|
+
* This is a convenience method that calls updateStatus with 'DISABLED'.
|
|
2440
|
+
* When disabled, the auth config cannot be used to create new connected accounts
|
|
2441
|
+
* or authenticate with third-party services, but existing connections may continue to work.
|
|
2442
|
+
*
|
|
2443
|
+
* @param {string} nanoid - The unique identifier of the auth config to disable
|
|
2444
|
+
* @returns {Promise<AuthConfigUpdateStatusResponse>} The updated auth config details
|
|
2445
|
+
* @throws {Error} If the auth config cannot be found or disabled
|
|
2446
|
+
*
|
|
2447
|
+
* @example
|
|
2448
|
+
* ```typescript
|
|
2449
|
+
* // Disable an auth config
|
|
2450
|
+
* await composio.authConfigs.disable('auth_abc123');
|
|
2451
|
+
* ```
|
|
2452
|
+
*/
|
|
2453
|
+
async disable(nanoid) {
|
|
2454
|
+
return this.client.authConfigs.updateStatus("DISABLED", { nanoid });
|
|
1585
2455
|
}
|
|
1586
2456
|
};
|
|
1587
2457
|
|
|
1588
2458
|
// src/models/ConnectionRequest.ts
|
|
2459
|
+
import ComposioClient from "@composio/client";
|
|
2460
|
+
import { ZodError as ZodError3 } from "zod";
|
|
1589
2461
|
var ConnectionRequest = class {
|
|
1590
2462
|
client;
|
|
1591
2463
|
id;
|
|
@@ -1596,6 +2468,7 @@ var ConnectionRequest = class {
|
|
|
1596
2468
|
this.id = connectedAccountId;
|
|
1597
2469
|
this.status = status || ConnectedAccountStatuses.INITIATED;
|
|
1598
2470
|
this.redirectUrl = redirectUrl;
|
|
2471
|
+
telemetry.instrument(this);
|
|
1599
2472
|
}
|
|
1600
2473
|
/**
|
|
1601
2474
|
* Transforms the raw connected account response from the Composio API to the SDK format.
|
|
@@ -1630,7 +2503,7 @@ var ConnectionRequest = class {
|
|
|
1630
2503
|
return parsedResponse;
|
|
1631
2504
|
} catch (error) {
|
|
1632
2505
|
logger_default.error("Error transforming response", error);
|
|
1633
|
-
if (error instanceof
|
|
2506
|
+
if (error instanceof ZodError3) {
|
|
1634
2507
|
logger_default.error(JSON.stringify(error.errors, null, 2));
|
|
1635
2508
|
}
|
|
1636
2509
|
throw error;
|
|
@@ -1674,7 +2547,9 @@ var ConnectionRequest = class {
|
|
|
1674
2547
|
throw new ComposioConnectedAccountNotFoundError(
|
|
1675
2548
|
`Connected account with id ${this.id} not found`,
|
|
1676
2549
|
{
|
|
1677
|
-
|
|
2550
|
+
meta: {
|
|
2551
|
+
connectedAccountId: this.id
|
|
2552
|
+
}
|
|
1678
2553
|
}
|
|
1679
2554
|
);
|
|
1680
2555
|
} else {
|
|
@@ -1683,8 +2558,7 @@ var ConnectionRequest = class {
|
|
|
1683
2558
|
}
|
|
1684
2559
|
const terminalErrorStates = [
|
|
1685
2560
|
ConnectedAccountStatuses.FAILED,
|
|
1686
|
-
ConnectedAccountStatuses.EXPIRED
|
|
1687
|
-
ConnectedAccountStatuses.DELETED
|
|
2561
|
+
ConnectedAccountStatuses.EXPIRED
|
|
1688
2562
|
];
|
|
1689
2563
|
const start = Date.now();
|
|
1690
2564
|
const pollInterval = 1e3;
|
|
@@ -1699,10 +2573,12 @@ var ConnectionRequest = class {
|
|
|
1699
2573
|
throw new ConnectionRequestFailedError(
|
|
1700
2574
|
`Connection request failed with status: ${response.status}${response.status_reason ? `, reason: ${response.status_reason}` : ""}`,
|
|
1701
2575
|
{
|
|
1702
|
-
|
|
1703
|
-
|
|
1704
|
-
|
|
1705
|
-
|
|
2576
|
+
meta: {
|
|
2577
|
+
userId: response.user_id,
|
|
2578
|
+
connectedAccountId: this.id,
|
|
2579
|
+
status: response.status,
|
|
2580
|
+
statusReason: response.status_reason
|
|
2581
|
+
}
|
|
1706
2582
|
}
|
|
1707
2583
|
);
|
|
1708
2584
|
}
|
|
@@ -1713,6 +2589,23 @@ var ConnectionRequest = class {
|
|
|
1713
2589
|
}
|
|
1714
2590
|
throw new ConnectionRequestTimeoutError(`Connection request timed out for ${this.id}`);
|
|
1715
2591
|
}
|
|
2592
|
+
/**
|
|
2593
|
+
* Returns a JSON-serializable representation of the connection request
|
|
2594
|
+
* Excludes the private client property to avoid cyclic reference issues
|
|
2595
|
+
*/
|
|
2596
|
+
toJSON() {
|
|
2597
|
+
return {
|
|
2598
|
+
id: this.id,
|
|
2599
|
+
status: this.status,
|
|
2600
|
+
redirectUrl: this.redirectUrl
|
|
2601
|
+
};
|
|
2602
|
+
}
|
|
2603
|
+
/**
|
|
2604
|
+
* Returns a string representation of the connection request
|
|
2605
|
+
*/
|
|
2606
|
+
toString() {
|
|
2607
|
+
return JSON.stringify(this.toJSON(), null, 2);
|
|
2608
|
+
}
|
|
1716
2609
|
};
|
|
1717
2610
|
|
|
1718
2611
|
// src/models/ConnectedAccounts.ts
|
|
@@ -1720,6 +2613,7 @@ var ConnectedAccounts = class {
|
|
|
1720
2613
|
client;
|
|
1721
2614
|
constructor(client) {
|
|
1722
2615
|
this.client = client;
|
|
2616
|
+
telemetry.instrument(this);
|
|
1723
2617
|
}
|
|
1724
2618
|
transformConnectedAccountRetrieveResponse(response) {
|
|
1725
2619
|
const result = ConnectedAccountRetrieveResponseSchema.safeParse({
|
|
@@ -1739,7 +2633,9 @@ var ConnectedAccounts = class {
|
|
|
1739
2633
|
testRequestEndpoint: response.test_request_endpoint
|
|
1740
2634
|
});
|
|
1741
2635
|
if (!result.success) {
|
|
1742
|
-
throw new ValidationError(
|
|
2636
|
+
throw new ValidationError("Failed to parse connected account retrieve response", {
|
|
2637
|
+
cause: result.error
|
|
2638
|
+
});
|
|
1743
2639
|
}
|
|
1744
2640
|
return result.data;
|
|
1745
2641
|
}
|
|
@@ -1772,7 +2668,9 @@ var ConnectedAccounts = class {
|
|
|
1772
2668
|
if (query) {
|
|
1773
2669
|
const parsedQuery = ConnectedAccountListParamsSchema.safeParse(query);
|
|
1774
2670
|
if (!parsedQuery.success) {
|
|
1775
|
-
throw new ValidationError(
|
|
2671
|
+
throw new ValidationError("Failed to parse connected account list query", {
|
|
2672
|
+
cause: parsedQuery.error
|
|
2673
|
+
});
|
|
1776
2674
|
}
|
|
1777
2675
|
rawQuery = {
|
|
1778
2676
|
auth_config_ids: parsedQuery.data.authConfigIds,
|
|
@@ -1792,7 +2690,9 @@ var ConnectedAccounts = class {
|
|
|
1792
2690
|
totalPages: result.total_pages
|
|
1793
2691
|
});
|
|
1794
2692
|
if (!parsedResponse.success) {
|
|
1795
|
-
throw new ValidationError(
|
|
2693
|
+
throw new ValidationError("Failed to parse connected account list response", {
|
|
2694
|
+
cause: parsedResponse.error
|
|
2695
|
+
});
|
|
1796
2696
|
}
|
|
1797
2697
|
return parsedResponse.data;
|
|
1798
2698
|
}
|
|
@@ -1932,8 +2832,21 @@ var ConnectedAccounts = class {
|
|
|
1932
2832
|
* Update the status of a connected account
|
|
1933
2833
|
* @param {string} nanoid - Unique identifier of the connected account
|
|
1934
2834
|
* @param {ConnectedAccountUpdateStatusParams} params - Parameters for updating the status
|
|
1935
|
-
* @param {RequestOptions} options - Request options
|
|
1936
2835
|
* @returns {Promise<ConnectedAccountUpdateStatusResponse>} Updated connected account details
|
|
2836
|
+
*
|
|
2837
|
+
* @example
|
|
2838
|
+
* ```typescript
|
|
2839
|
+
* // Enable a connected account
|
|
2840
|
+
* const updatedAccount = await composio.connectedAccounts.updateStatus('conn_abc123', {
|
|
2841
|
+
* enabled: true
|
|
2842
|
+
* });
|
|
2843
|
+
*
|
|
2844
|
+
* // Disable a connected account with a reason
|
|
2845
|
+
* const disabledAccount = await composio.connectedAccounts.updateStatus('conn_abc123', {
|
|
2846
|
+
* enabled: false,
|
|
2847
|
+
* reason: 'Token expired'
|
|
2848
|
+
* });
|
|
2849
|
+
* ```
|
|
1937
2850
|
*/
|
|
1938
2851
|
async updateStatus(nanoid, params) {
|
|
1939
2852
|
return this.client.connectedAccounts.updateStatus(nanoid, params);
|
|
@@ -1941,8 +2854,14 @@ var ConnectedAccounts = class {
|
|
|
1941
2854
|
/**
|
|
1942
2855
|
* Enable a connected account
|
|
1943
2856
|
* @param {string} nanoid - Unique identifier of the connected account
|
|
1944
|
-
* @param {RequestOptions} options - Request options
|
|
1945
2857
|
* @returns {Promise<ConnectedAccountUpdateStatusResponse>} Updated connected account details
|
|
2858
|
+
*
|
|
2859
|
+
* @example
|
|
2860
|
+
* ```typescript
|
|
2861
|
+
* // Enable a previously disabled connected account
|
|
2862
|
+
* const enabledAccount = await composio.connectedAccounts.enable('conn_abc123');
|
|
2863
|
+
* console.log(enabledAccount.isDisabled); // false
|
|
2864
|
+
* ```
|
|
1946
2865
|
*/
|
|
1947
2866
|
async enable(nanoid) {
|
|
1948
2867
|
return this.client.connectedAccounts.updateStatus(nanoid, { enabled: true });
|
|
@@ -1950,8 +2869,20 @@ var ConnectedAccounts = class {
|
|
|
1950
2869
|
/**
|
|
1951
2870
|
* Disable a connected account
|
|
1952
2871
|
* @param {string} nanoid - Unique identifier of the connected account
|
|
1953
|
-
* @param {RequestOptions} options - Request options
|
|
1954
2872
|
* @returns {Promise<ConnectedAccountUpdateStatusResponse>} Updated connected account details
|
|
2873
|
+
*
|
|
2874
|
+
* @example
|
|
2875
|
+
* ```typescript
|
|
2876
|
+
* // Disable a connected account
|
|
2877
|
+
* const disabledAccount = await composio.connectedAccounts.disable('conn_abc123');
|
|
2878
|
+
* console.log(disabledAccount.isDisabled); // true
|
|
2879
|
+
*
|
|
2880
|
+
* // You can also use updateStatus with a reason
|
|
2881
|
+
* // const disabledAccount = await composio.connectedAccounts.updateStatus('conn_abc123', {
|
|
2882
|
+
* // enabled: false,
|
|
2883
|
+
* // reason: 'No longer needed'
|
|
2884
|
+
* // });
|
|
2885
|
+
* ```
|
|
1955
2886
|
*/
|
|
1956
2887
|
async disable(nanoid) {
|
|
1957
2888
|
return this.client.connectedAccounts.updateStatus(nanoid, { enabled: false });
|
|
@@ -1964,6 +2895,7 @@ var Toolkits = class {
|
|
|
1964
2895
|
constructor(client) {
|
|
1965
2896
|
this.client = client;
|
|
1966
2897
|
this.authorize = this.authorize.bind(this);
|
|
2898
|
+
telemetry.instrument(this);
|
|
1967
2899
|
}
|
|
1968
2900
|
/**
|
|
1969
2901
|
* Retrieves a list of toolkits based on the provided query parameters.
|
|
@@ -1977,42 +2909,46 @@ var Toolkits = class {
|
|
|
1977
2909
|
* @private
|
|
1978
2910
|
*/
|
|
1979
2911
|
async getToolkits(query) {
|
|
1980
|
-
|
|
1981
|
-
|
|
1982
|
-
|
|
1983
|
-
|
|
1984
|
-
|
|
1985
|
-
sort_by: parsedQuery.sortBy
|
|
1986
|
-
});
|
|
1987
|
-
const parsedResult = ToolKitListResponseSchema.parse({
|
|
1988
|
-
items: result.items.map((item) => {
|
|
1989
|
-
const parsedItem = ToolKitItemSchema.parse({
|
|
1990
|
-
name: item.name,
|
|
1991
|
-
slug: item.slug,
|
|
1992
|
-
meta: item.meta,
|
|
1993
|
-
isLocalToolkit: item.is_local_toolkit,
|
|
1994
|
-
authSchemes: item.auth_schemes,
|
|
1995
|
-
composioManagedAuthSchemes: item.composio_managed_auth_schemes,
|
|
1996
|
-
noAuth: item.no_auth
|
|
2912
|
+
try {
|
|
2913
|
+
const parsedQuery = ToolkitsListParamsSchema.safeParse(query);
|
|
2914
|
+
if (!parsedQuery.success) {
|
|
2915
|
+
throw new ValidationError("Failed to parse toolkit list query", {
|
|
2916
|
+
cause: parsedQuery.error
|
|
1997
2917
|
});
|
|
1998
|
-
|
|
1999
|
-
|
|
2000
|
-
|
|
2001
|
-
|
|
2002
|
-
|
|
2003
|
-
|
|
2004
|
-
|
|
2005
|
-
|
|
2006
|
-
|
|
2007
|
-
|
|
2008
|
-
|
|
2009
|
-
|
|
2010
|
-
|
|
2011
|
-
|
|
2012
|
-
|
|
2013
|
-
|
|
2918
|
+
}
|
|
2919
|
+
const result = await this.client.toolkits.list({
|
|
2920
|
+
category: parsedQuery.data.category,
|
|
2921
|
+
is_local: parsedQuery.data.isLocal,
|
|
2922
|
+
managed_by: parsedQuery.data.managedBy,
|
|
2923
|
+
sort_by: parsedQuery.data.sortBy
|
|
2924
|
+
});
|
|
2925
|
+
const parsedResult = ToolKitListResponseSchema.safeParse({
|
|
2926
|
+
items: result.items.map((item) => {
|
|
2927
|
+
const parsedItem = ToolKitItemSchema.parse({
|
|
2928
|
+
name: item.name,
|
|
2929
|
+
slug: item.slug,
|
|
2930
|
+
meta: item.meta,
|
|
2931
|
+
isLocalToolkit: item.is_local_toolkit,
|
|
2932
|
+
authSchemes: item.auth_schemes,
|
|
2933
|
+
composioManagedAuthSchemes: item.composio_managed_auth_schemes,
|
|
2934
|
+
noAuth: item.no_auth
|
|
2935
|
+
});
|
|
2936
|
+
return parsedItem;
|
|
2937
|
+
}),
|
|
2938
|
+
nextCursor: result.next_cursor,
|
|
2939
|
+
totalPages: result.total_pages
|
|
2940
|
+
});
|
|
2941
|
+
if (!parsedResult.success) {
|
|
2942
|
+
throw new ValidationError("Failed to parse toolkit list response", {
|
|
2943
|
+
cause: parsedResult.error
|
|
2944
|
+
});
|
|
2945
|
+
}
|
|
2946
|
+
return parsedResult.data;
|
|
2947
|
+
} catch (error) {
|
|
2948
|
+
throw new ComposioToolkitFetchError("Failed to fetch toolkits", {
|
|
2949
|
+
cause: error
|
|
2950
|
+
});
|
|
2014
2951
|
}
|
|
2015
|
-
return this.getToolkits(arg);
|
|
2016
2952
|
}
|
|
2017
2953
|
/**
|
|
2018
2954
|
* Retrieves a specific toolkit by its slug identifier.
|
|
@@ -2030,7 +2966,7 @@ var Toolkits = class {
|
|
|
2030
2966
|
async getToolkitBySlug(slug) {
|
|
2031
2967
|
try {
|
|
2032
2968
|
const result = await this.client.toolkits.retrieve(slug);
|
|
2033
|
-
const parsedResult = ToolkitRetrieveResponseSchema.
|
|
2969
|
+
const parsedResult = ToolkitRetrieveResponseSchema.safeParse({
|
|
2034
2970
|
name: result.name,
|
|
2035
2971
|
slug: result.slug,
|
|
2036
2972
|
meta: {
|
|
@@ -2055,16 +2991,41 @@ var Toolkits = class {
|
|
|
2055
2991
|
}
|
|
2056
2992
|
}))
|
|
2057
2993
|
});
|
|
2058
|
-
|
|
2994
|
+
if (!parsedResult.success) {
|
|
2995
|
+
throw new ValidationError("Failed to parse toolkit response", {
|
|
2996
|
+
cause: parsedResult.error
|
|
2997
|
+
});
|
|
2998
|
+
}
|
|
2999
|
+
return parsedResult.data;
|
|
2059
3000
|
} catch (error) {
|
|
2060
|
-
if (error instanceof
|
|
2061
|
-
throw new
|
|
3001
|
+
if (error instanceof ComposioClient2.NotFoundError) {
|
|
3002
|
+
throw new ComposioToolkitNotFoundError(`Toolkit with slug ${slug} not found`, {
|
|
3003
|
+
meta: {
|
|
3004
|
+
slug
|
|
3005
|
+
},
|
|
3006
|
+
cause: error
|
|
3007
|
+
});
|
|
2062
3008
|
}
|
|
2063
|
-
throw new
|
|
2064
|
-
|
|
3009
|
+
throw new ComposioToolkitFetchError(`Couldn't fetch Toolkit with slug: ${slug}`, {
|
|
3010
|
+
meta: {
|
|
3011
|
+
slug
|
|
3012
|
+
},
|
|
3013
|
+
cause: error
|
|
2065
3014
|
});
|
|
2066
3015
|
}
|
|
2067
3016
|
}
|
|
3017
|
+
/**
|
|
3018
|
+
* Implementation method that handles both overloads for retrieving toolkits.
|
|
3019
|
+
*
|
|
3020
|
+
* @param {string | ToolkitListParams} arg - Either a toolkit slug or query parameters
|
|
3021
|
+
* @returns {Promise<ToolkitRetrieveResponse | ToolKitListResponse>} The toolkit or list of toolkits
|
|
3022
|
+
*/
|
|
3023
|
+
async get(arg) {
|
|
3024
|
+
if (typeof arg === "string") {
|
|
3025
|
+
return this.getToolkitBySlug(arg);
|
|
3026
|
+
}
|
|
3027
|
+
return this.getToolkits(arg);
|
|
3028
|
+
}
|
|
2068
3029
|
/**
|
|
2069
3030
|
* Retrieves all toolkit categories available in the Composio SDK.
|
|
2070
3031
|
*
|
|
@@ -2112,7 +3073,7 @@ var Toolkits = class {
|
|
|
2112
3073
|
const composioAuthConfig = new AuthConfigs(this.client);
|
|
2113
3074
|
let authConfigIdToUse;
|
|
2114
3075
|
const authConfig = await composioAuthConfig.list({
|
|
2115
|
-
toolkitSlug
|
|
3076
|
+
toolkit: toolkitSlug
|
|
2116
3077
|
});
|
|
2117
3078
|
authConfigIdToUse = authConfig.items[0]?.id;
|
|
2118
3079
|
if (!authConfigIdToUse) {
|
|
@@ -2124,7 +3085,9 @@ var Toolkits = class {
|
|
|
2124
3085
|
authConfigIdToUse = authConfig2.id;
|
|
2125
3086
|
} else {
|
|
2126
3087
|
throw new ComposioAuthConfigNotFoundError("No auth config found for toolkit", {
|
|
2127
|
-
|
|
3088
|
+
meta: {
|
|
3089
|
+
toolkitSlug
|
|
3090
|
+
}
|
|
2128
3091
|
});
|
|
2129
3092
|
}
|
|
2130
3093
|
}
|
|
@@ -2133,474 +3096,662 @@ var Toolkits = class {
|
|
|
2133
3096
|
}
|
|
2134
3097
|
};
|
|
2135
3098
|
|
|
2136
|
-
// src/
|
|
2137
|
-
|
|
2138
|
-
var
|
|
2139
|
-
var
|
|
2140
|
-
|
|
2141
|
-
|
|
2142
|
-
|
|
2143
|
-
|
|
2144
|
-
|
|
2145
|
-
|
|
2146
|
-
|
|
2147
|
-
|
|
2148
|
-
|
|
2149
|
-
|
|
2150
|
-
|
|
2151
|
-
|
|
3099
|
+
// src/types/triggers.types.ts
|
|
3100
|
+
import { z as z5 } from "zod";
|
|
3101
|
+
var TriggerStatusEnum = z5.enum(["enable", "disable"]);
|
|
3102
|
+
var TriggerSubscribeParamSchema = z5.object({
|
|
3103
|
+
toolkits: z5.array(z5.string()).optional(),
|
|
3104
|
+
triggerId: z5.string().optional(),
|
|
3105
|
+
connectedAccountId: z5.string().optional(),
|
|
3106
|
+
authConfigId: z5.string().optional(),
|
|
3107
|
+
triggerSlug: z5.array(z5.string()).optional(),
|
|
3108
|
+
triggerData: z5.string().optional(),
|
|
3109
|
+
userId: z5.string().optional()
|
|
3110
|
+
});
|
|
3111
|
+
var TriggerInstanceListActiveParamsSchema = z5.object({
|
|
3112
|
+
authConfigIds: z5.array(z5.string()).nullable().optional(),
|
|
3113
|
+
connectedAccountIds: z5.array(z5.string()).nullable().optional(),
|
|
3114
|
+
limit: z5.number().optional(),
|
|
3115
|
+
page: z5.number().optional(),
|
|
3116
|
+
showDisabled: z5.boolean().nullable().optional(),
|
|
3117
|
+
triggerIds: z5.array(z5.string()).nullable().optional(),
|
|
3118
|
+
triggerNames: z5.array(z5.string()).nullable().optional()
|
|
3119
|
+
});
|
|
3120
|
+
var TriggerInstanceListActiveResponseItemSchema = z5.object({
|
|
3121
|
+
id: z5.string(),
|
|
3122
|
+
connectedAccountId: z5.string(),
|
|
3123
|
+
disabledAt: z5.string().nullable(),
|
|
3124
|
+
state: z5.record(z5.unknown()),
|
|
3125
|
+
triggerConfig: z5.record(z5.unknown()),
|
|
3126
|
+
triggerName: z5.string(),
|
|
3127
|
+
updatedAt: z5.string(),
|
|
3128
|
+
triggerData: z5.string().optional(),
|
|
3129
|
+
uuid: z5.string().optional()
|
|
3130
|
+
});
|
|
3131
|
+
var TriggerInstanceListActiveResponseSchema = z5.object({
|
|
3132
|
+
items: z5.array(TriggerInstanceListActiveResponseItemSchema),
|
|
3133
|
+
nextCursor: z5.string().nullable(),
|
|
3134
|
+
totalPages: z5.number()
|
|
3135
|
+
});
|
|
3136
|
+
var TriggerInstanceUpsertParamsSchema = z5.object({
|
|
3137
|
+
connectedAccountId: z5.string().optional(),
|
|
3138
|
+
triggerConfig: z5.record(z5.unknown()).optional()
|
|
3139
|
+
});
|
|
3140
|
+
var TriggerInstanceUpsertResponseSchema = z5.object({
|
|
3141
|
+
triggerId: z5.string()
|
|
3142
|
+
});
|
|
3143
|
+
var TriggerInstanceManageUpdateParamsSchema = z5.object({
|
|
3144
|
+
status: z5.enum(["enable", "disable"])
|
|
3145
|
+
});
|
|
3146
|
+
var TriggerInstanceManageUpdateResponseSchema = z5.object({
|
|
3147
|
+
status: z5.enum(["success"])
|
|
3148
|
+
});
|
|
3149
|
+
var TriggerInstanceManageDeleteResponseSchema = z5.object({
|
|
3150
|
+
triggerId: z5.string()
|
|
3151
|
+
});
|
|
3152
|
+
var IncomingTriggerPayloadSchema = z5.object({
|
|
3153
|
+
id: z5.string().describe("The ID of the trigger"),
|
|
3154
|
+
triggerSlug: z5.string().describe("The slug of the trigger that triggered the event"),
|
|
3155
|
+
toolkitSlug: z5.string().describe("The slug of the toolkit that triggered the event"),
|
|
3156
|
+
userId: z5.string().describe("The ID of the user that triggered the event"),
|
|
3157
|
+
payload: z5.record(z5.unknown()).describe("The payload of the trigger").optional(),
|
|
3158
|
+
originalPayload: z5.record(z5.unknown()).describe("The original payload of the trigger").optional(),
|
|
3159
|
+
metadata: z5.object({
|
|
3160
|
+
id: z5.string(),
|
|
3161
|
+
toolkitSlug: z5.string(),
|
|
3162
|
+
triggerSlug: z5.string(),
|
|
3163
|
+
triggerData: z5.string().optional(),
|
|
3164
|
+
triggerConfig: z5.record(z5.unknown()),
|
|
3165
|
+
connectedAccount: z5.object({
|
|
3166
|
+
id: z5.string(),
|
|
3167
|
+
uuid: z5.string(),
|
|
3168
|
+
authConfigId: z5.string(),
|
|
3169
|
+
authConfigUUID: z5.string(),
|
|
3170
|
+
userId: z5.string(),
|
|
3171
|
+
status: z5.enum(["ACTIVE", "INACTIVE"])
|
|
3172
|
+
})
|
|
3173
|
+
})
|
|
3174
|
+
});
|
|
3175
|
+
|
|
3176
|
+
// src/services/internal/InternalService.types.ts
|
|
3177
|
+
import { z as z6 } from "zod";
|
|
3178
|
+
var SDKRealtimeCredentialsResponseSchema = z6.object({
|
|
3179
|
+
projectId: z6.string().describe("The project ID"),
|
|
3180
|
+
pusherKey: z6.string().describe("The Pusher key"),
|
|
3181
|
+
pusherCluster: z6.string().describe("The Pusher cluster")
|
|
3182
|
+
});
|
|
3183
|
+
|
|
3184
|
+
// src/services/internal/InternalService.ts
|
|
3185
|
+
var SDK_REALTIME_CREDENTIALS_ENDPOINT = "/api/v3/internal/sdk/realtime/credentials";
|
|
3186
|
+
var InternalService = class {
|
|
3187
|
+
constructor(client) {
|
|
3188
|
+
this.client = client;
|
|
3189
|
+
this.client = client;
|
|
3190
|
+
}
|
|
3191
|
+
/**
|
|
3192
|
+
* Get the SDK realtime credentials
|
|
3193
|
+
* @returns {SDKRealtimeCredentialsResponse} The SDK realtime credentials
|
|
3194
|
+
*/
|
|
3195
|
+
async getSDKRealtimeCredentials() {
|
|
3196
|
+
const response = await this.client.request({
|
|
3197
|
+
method: "get",
|
|
3198
|
+
path: SDK_REALTIME_CREDENTIALS_ENDPOINT
|
|
3199
|
+
});
|
|
3200
|
+
const parsedResponse = SDKRealtimeCredentialsResponseSchema.safeParse({
|
|
3201
|
+
pusherKey: response.pusher_key,
|
|
3202
|
+
projectId: response.project_id,
|
|
3203
|
+
pusherCluster: response.pusher_cluster
|
|
3204
|
+
});
|
|
3205
|
+
logger_default.debug(
|
|
3206
|
+
`[InternalService] SDK realtime credentials: ${JSON.stringify(parsedResponse, null, 2)}`
|
|
3207
|
+
);
|
|
3208
|
+
if (!parsedResponse.success) {
|
|
3209
|
+
throw new ValidationError(`Failed to parse SDK realtime credentials`, {
|
|
3210
|
+
cause: parsedResponse.error
|
|
3211
|
+
});
|
|
3212
|
+
}
|
|
3213
|
+
return parsedResponse.data;
|
|
3214
|
+
}
|
|
3215
|
+
};
|
|
3216
|
+
|
|
3217
|
+
// src/errors/TriggerErrors.ts
|
|
3218
|
+
import { ComposioError as ComposioError2 } from "@composio/client";
|
|
3219
|
+
var TriggerErrorCodes = {
|
|
3220
|
+
TRIGGER_FAILED_TO_GET_SDK_REALTIME_CREDENTIALS: "TRIGGER_FAILED_TO_GET_SDK_REALTIME_CREDENTIALS",
|
|
3221
|
+
TRIGGER_FAILED_TO_CREATE_PUSHER_CLIENT: "TRIGGER_FAILED_TO_CREATE_PUSHER_CLIENT",
|
|
3222
|
+
TRIGGER_FAILED_TO_SUBSCRIBE_TO_PUSHER_CHANNEL: "TRIGGER_FAILED_TO_SUBSCRIBE_TO_PUSHER_CHANNEL",
|
|
3223
|
+
TRIGGER_FAILED_TO_UNSUBSCRIBE_FROM_PUSHER_CHANNEL: "TRIGGER_FAILED_TO_UNSUBSCRIBE_FROM_PUSHER_CHANNEL"
|
|
3224
|
+
};
|
|
3225
|
+
var ComposioFailedToGetSDKRealtimeCredentialsError = class extends ComposioError2 {
|
|
3226
|
+
name = "ComposioFailedToGetSDKRealtimeCredentialsError";
|
|
3227
|
+
code = TriggerErrorCodes.TRIGGER_FAILED_TO_GET_SDK_REALTIME_CREDENTIALS;
|
|
3228
|
+
statusCode = 500;
|
|
3229
|
+
possibleFixes = ["Please contact support."];
|
|
3230
|
+
constructor(message, options) {
|
|
3231
|
+
super(message, options);
|
|
3232
|
+
}
|
|
3233
|
+
};
|
|
3234
|
+
var ComposioFailedToCreatePusherClientError = class extends ComposioError2 {
|
|
3235
|
+
name = "ComposioFailedToCreatePusherClientError";
|
|
3236
|
+
code = TriggerErrorCodes.TRIGGER_FAILED_TO_CREATE_PUSHER_CLIENT;
|
|
3237
|
+
statusCode = 500;
|
|
3238
|
+
possibleFixes = ["Please contact support."];
|
|
3239
|
+
constructor(message, options) {
|
|
3240
|
+
super(message, options);
|
|
3241
|
+
}
|
|
3242
|
+
};
|
|
3243
|
+
var ComposioFailedToSubscribeToPusherChannelError = class extends ComposioError2 {
|
|
3244
|
+
name = "ComposioFailedToSubscribeToPusherChannelError";
|
|
3245
|
+
code = TriggerErrorCodes.TRIGGER_FAILED_TO_SUBSCRIBE_TO_PUSHER_CHANNEL;
|
|
3246
|
+
statusCode = 500;
|
|
3247
|
+
possibleFixes = ["Please contact support."];
|
|
3248
|
+
constructor(message, options) {
|
|
3249
|
+
super(message, options);
|
|
3250
|
+
}
|
|
3251
|
+
};
|
|
3252
|
+
|
|
3253
|
+
// src/services/pusher/Pusher.ts
|
|
3254
|
+
var PusherService = class {
|
|
3255
|
+
// these values are set via the Apollo API `/internal/sdk/realtime/credentials` endpoint
|
|
3256
|
+
clientId;
|
|
3257
|
+
pusherKey;
|
|
3258
|
+
pusherCluster;
|
|
3259
|
+
pusherChannel;
|
|
3260
|
+
// these details are set via the client SDK
|
|
3261
|
+
pusherBaseURL;
|
|
3262
|
+
apiKey;
|
|
3263
|
+
pusherClient;
|
|
3264
|
+
composioClient;
|
|
3265
|
+
constructor(client) {
|
|
3266
|
+
this.composioClient = client;
|
|
3267
|
+
this.pusherBaseURL = client.baseURL;
|
|
3268
|
+
this.apiKey = client.apiKey ?? process.env.COMPOSIO_API_KEY ?? "";
|
|
3269
|
+
telemetry.instrument(this);
|
|
3270
|
+
}
|
|
3271
|
+
/**
|
|
3272
|
+
* Creates a Pusher client
|
|
3273
|
+
*
|
|
3274
|
+
* This method is called when the Pusher client is first used.
|
|
3275
|
+
* It will fetch the SDK realtime credentials from the Apollo API and create a Pusher client.
|
|
3276
|
+
*/
|
|
3277
|
+
async getPusherClient() {
|
|
3278
|
+
if (!this.pusherClient) {
|
|
3279
|
+
const internalService = new InternalService(this.composioClient);
|
|
3280
|
+
let sdkRealtimeCredentials;
|
|
3281
|
+
try {
|
|
3282
|
+
sdkRealtimeCredentials = await internalService.getSDKRealtimeCredentials();
|
|
3283
|
+
} catch (error) {
|
|
3284
|
+
throw new ComposioFailedToGetSDKRealtimeCredentialsError(
|
|
3285
|
+
"Failed to get SDK realtime credentials",
|
|
3286
|
+
{
|
|
3287
|
+
cause: error
|
|
3288
|
+
}
|
|
3289
|
+
);
|
|
3290
|
+
}
|
|
3291
|
+
this.clientId = sdkRealtimeCredentials.projectId;
|
|
3292
|
+
this.pusherKey = sdkRealtimeCredentials.pusherKey;
|
|
3293
|
+
this.pusherCluster = sdkRealtimeCredentials.pusherCluster;
|
|
3294
|
+
this.pusherChannel = `private-${this.clientId}_triggers`;
|
|
3295
|
+
logger_default.debug(
|
|
3296
|
+
`[PusherService] Creating Pusher client for client ID: ${this.clientId} in cluster ${this.pusherCluster}`
|
|
3297
|
+
);
|
|
3298
|
+
try {
|
|
3299
|
+
const { default: Pusher } = await import("pusher-js");
|
|
3300
|
+
this.pusherClient = new Pusher(this.pusherKey, {
|
|
3301
|
+
cluster: this.pusherCluster,
|
|
3302
|
+
channelAuthorization: {
|
|
3303
|
+
endpoint: `${this.pusherBaseURL}/api/v3/internal/sdk/realtime/auth`,
|
|
3304
|
+
headers: {
|
|
3305
|
+
"x-api-key": this.apiKey
|
|
3306
|
+
},
|
|
3307
|
+
transport: "ajax"
|
|
3308
|
+
}
|
|
3309
|
+
});
|
|
3310
|
+
} catch (error) {
|
|
3311
|
+
throw new ComposioFailedToCreatePusherClientError("Failed to create Pusher client", {
|
|
3312
|
+
cause: error
|
|
3313
|
+
});
|
|
3314
|
+
}
|
|
3315
|
+
}
|
|
3316
|
+
return this.pusherClient;
|
|
3317
|
+
}
|
|
3318
|
+
/**
|
|
3319
|
+
* Binds a chunked event to a Pusher client
|
|
3320
|
+
*
|
|
3321
|
+
*
|
|
3322
|
+
* @param channel - The Pusher client to bind the event to
|
|
3323
|
+
* @param event - The event to bind to
|
|
3324
|
+
* @param callback - The function to call when the event is received
|
|
3325
|
+
*/
|
|
3326
|
+
bindWithChunking(channel, event, callback) {
|
|
3327
|
+
try {
|
|
3328
|
+
channel.bind(event, callback);
|
|
3329
|
+
const events = {};
|
|
3330
|
+
channel.bind("chunked-" + event, (data) => {
|
|
3331
|
+
try {
|
|
3332
|
+
const typedData = data;
|
|
3333
|
+
if (!typedData || typeof typedData.id !== "string" || typeof typedData.index !== "number") {
|
|
3334
|
+
throw new Error("Invalid chunked trigger data format");
|
|
3335
|
+
}
|
|
3336
|
+
if (!events.hasOwnProperty(typedData.id)) {
|
|
3337
|
+
events[typedData.id] = { chunks: [], receivedFinal: false };
|
|
3338
|
+
}
|
|
3339
|
+
const ev = events[typedData.id];
|
|
3340
|
+
ev.chunks[typedData.index] = typedData.chunk;
|
|
3341
|
+
if (typedData.final) ev.receivedFinal = true;
|
|
3342
|
+
if (ev.receivedFinal && ev.chunks.length === Object.keys(ev.chunks).length) {
|
|
3343
|
+
try {
|
|
3344
|
+
const parsedData = JSON.parse(ev.chunks.join(""));
|
|
3345
|
+
callback(parsedData);
|
|
3346
|
+
} catch (parseError) {
|
|
3347
|
+
const errorMessage = parseError instanceof Error ? parseError.message : String(parseError);
|
|
3348
|
+
logger_default.error("Failed to parse chunked data:", errorMessage);
|
|
3349
|
+
} finally {
|
|
3350
|
+
delete events[typedData.id];
|
|
3351
|
+
}
|
|
3352
|
+
}
|
|
3353
|
+
} catch (error) {
|
|
3354
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
3355
|
+
logger_default.error("Error processing chunked trigger data:", errorMessage);
|
|
3356
|
+
if (data && typeof data === "object" && "id" in data) {
|
|
3357
|
+
delete events[data.id];
|
|
3358
|
+
}
|
|
3359
|
+
}
|
|
3360
|
+
});
|
|
3361
|
+
} catch (error) {
|
|
3362
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
3363
|
+
logger_default.error("Failed to bind chunked events:", error);
|
|
3364
|
+
throw new Error(`Failed to bind chunked events: ${errorMessage}`);
|
|
3365
|
+
}
|
|
3366
|
+
}
|
|
3367
|
+
/**
|
|
3368
|
+
* Subscribes to pusher to receive events from the server
|
|
3369
|
+
*
|
|
3370
|
+
* This method is used to subscribe to a Pusher channel.
|
|
3371
|
+
* It will create a Pusher client if it doesn't exist.
|
|
3372
|
+
*
|
|
3373
|
+
* @param channelName - The name of the Pusher channel to subscribe to
|
|
3374
|
+
* @param event - The event to subscribe to
|
|
3375
|
+
* @param fn - The function to call when the event is received
|
|
3376
|
+
*/
|
|
3377
|
+
async subscribe(fn) {
|
|
3378
|
+
try {
|
|
3379
|
+
logger_default.debug(`[PusherService] Subscribing to channel: ${this.pusherChannel}`);
|
|
3380
|
+
const pusherClient = await this.getPusherClient();
|
|
3381
|
+
const channel = await pusherClient.subscribe(this.pusherChannel);
|
|
3382
|
+
channel.bind("pusher:subscription_error", (data) => {
|
|
3383
|
+
const error = data.error ? String(data.error) : "Unknown subscription error";
|
|
3384
|
+
throw new ComposioFailedToSubscribeToPusherChannelError(
|
|
3385
|
+
`Trigger subscription error: ${error}`,
|
|
3386
|
+
{
|
|
3387
|
+
cause: error
|
|
3388
|
+
}
|
|
3389
|
+
);
|
|
3390
|
+
});
|
|
3391
|
+
const safeCallback = (data) => {
|
|
3392
|
+
try {
|
|
3393
|
+
fn(data);
|
|
3394
|
+
} catch (error) {
|
|
3395
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
3396
|
+
logger_default.error("\u274C Error in trigger callback:", errorMessage);
|
|
2152
3397
|
}
|
|
2153
|
-
}
|
|
3398
|
+
};
|
|
3399
|
+
this.bindWithChunking(channel, "trigger_to_client", safeCallback);
|
|
3400
|
+
logger_default.info(`\u2705 Subscribed to triggers. You should start receiving events now.`);
|
|
3401
|
+
} catch (error) {
|
|
3402
|
+
throw new ComposioFailedToSubscribeToPusherChannelError(
|
|
3403
|
+
"Failed to subscribe to Pusher channel",
|
|
3404
|
+
{
|
|
3405
|
+
cause: error
|
|
3406
|
+
}
|
|
3407
|
+
);
|
|
2154
3408
|
}
|
|
2155
|
-
return _PusherUtils.pusherClient;
|
|
2156
3409
|
}
|
|
2157
3410
|
/**
|
|
2158
|
-
*
|
|
2159
|
-
*
|
|
2160
|
-
*
|
|
2161
|
-
*
|
|
2162
|
-
*
|
|
3411
|
+
* Unsubscribes from a Pusher channel
|
|
3412
|
+
*
|
|
3413
|
+
* This method is used to unsubscribe from a Pusher channel.
|
|
3414
|
+
* It will create a Pusher client if it doesn't exist.
|
|
3415
|
+
*
|
|
3416
|
+
* @param channelName - The name of the Pusher channel to unsubscribe from
|
|
2163
3417
|
*/
|
|
2164
|
-
|
|
3418
|
+
async unsubscribe() {
|
|
2165
3419
|
try {
|
|
2166
|
-
|
|
3420
|
+
logger_default.debug(`[PusherService] Unsubscribing from channel: ${this.pusherChannel}`);
|
|
3421
|
+
const pusherClient = await this.getPusherClient();
|
|
3422
|
+
await pusherClient.unsubscribe(this.pusherChannel);
|
|
3423
|
+
logger_default.info(`\u2705 Unsubscribed from triggers.`);
|
|
2167
3424
|
} catch (error) {
|
|
2168
|
-
|
|
2169
|
-
|
|
3425
|
+
throw new ComposioFailedToSubscribeToPusherChannelError(
|
|
3426
|
+
"Failed to unsubscribe from Pusher channel",
|
|
3427
|
+
{
|
|
3428
|
+
cause: error
|
|
3429
|
+
}
|
|
2170
3430
|
);
|
|
2171
3431
|
}
|
|
2172
3432
|
}
|
|
2173
|
-
/**
|
|
2174
|
-
* Unsubscribes from a Pusher channel.
|
|
2175
|
-
* @param {string} channelName - The name of the channel to unsubscribe from.
|
|
2176
|
-
* @returns {void}
|
|
2177
|
-
*/
|
|
2178
|
-
static async unsubscribe(channelName) {
|
|
2179
|
-
_PusherUtils.pusherClient.unsubscribe(channelName);
|
|
2180
|
-
}
|
|
2181
|
-
/**
|
|
2182
|
-
* Binds an event to a channel with support for chunked messages.
|
|
2183
|
-
* @param {PusherClient} channel - The Pusher channel to bind the event to.
|
|
2184
|
-
* @param {string} event - The event to bind to the channel.
|
|
2185
|
-
* @param {(data: unknown) => void} callback - The callback function to execute when the event is triggered.
|
|
2186
|
-
*/
|
|
2187
|
-
static bindWithChunking(channel, event, callback) {
|
|
2188
|
-
channel.bind(event, callback);
|
|
2189
|
-
const events = {};
|
|
2190
|
-
channel.bind("chunked-" + event, (data) => {
|
|
2191
|
-
const typedData = data;
|
|
2192
|
-
if (!events.hasOwnProperty(typedData.id)) {
|
|
2193
|
-
events[typedData.id] = { chunks: [], receivedFinal: false };
|
|
2194
|
-
}
|
|
2195
|
-
const ev = events[typedData.id];
|
|
2196
|
-
ev.chunks[typedData.index] = typedData.chunk;
|
|
2197
|
-
if (typedData.final) ev.receivedFinal = true;
|
|
2198
|
-
if (ev.receivedFinal && ev.chunks.length === Object.keys(ev.chunks).length) {
|
|
2199
|
-
callback(JSON.parse(ev.chunks.join("")));
|
|
2200
|
-
delete events[typedData.id];
|
|
2201
|
-
}
|
|
2202
|
-
});
|
|
2203
|
-
}
|
|
2204
|
-
/**
|
|
2205
|
-
* Subscribes to a trigger channel for a client and handles chunked data.
|
|
2206
|
-
* @param {string} clientId - The unique identifier for the client subscribing to the events.
|
|
2207
|
-
* @param {(data: TriggerData) => void} fn - The callback function to execute when trigger data is received.
|
|
2208
|
-
*/
|
|
2209
|
-
static triggerSubscribe(clientId, fn) {
|
|
2210
|
-
const channel = _PusherUtils.pusherClient.subscribe(
|
|
2211
|
-
`private-${clientId}_triggers`
|
|
2212
|
-
);
|
|
2213
|
-
_PusherUtils.bindWithChunking(
|
|
2214
|
-
channel,
|
|
2215
|
-
"trigger_to_client",
|
|
2216
|
-
fn
|
|
2217
|
-
);
|
|
2218
|
-
logger_default.info(
|
|
2219
|
-
`Subscribed to triggers. You should start receiving events now.`
|
|
2220
|
-
);
|
|
2221
|
-
}
|
|
2222
|
-
static triggerUnsubscribe(clientId) {
|
|
2223
|
-
_PusherUtils.pusherClient.unsubscribe(`${clientId}_triggers`);
|
|
2224
|
-
}
|
|
2225
|
-
};
|
|
2226
|
-
|
|
2227
|
-
// src/models/Session.ts
|
|
2228
|
-
var Session = class {
|
|
2229
|
-
client;
|
|
2230
|
-
constructor(client) {
|
|
2231
|
-
this.client = client;
|
|
2232
|
-
}
|
|
2233
|
-
/**
|
|
2234
|
-
* Get the active session info
|
|
2235
|
-
* @returns {Promise<SessionGetInfoResponse>} Session info
|
|
2236
|
-
*/
|
|
2237
|
-
async getInfo() {
|
|
2238
|
-
return this.client.auth.session.getInfo();
|
|
2239
|
-
}
|
|
2240
3433
|
};
|
|
2241
3434
|
|
|
2242
3435
|
// src/models/Triggers.ts
|
|
2243
3436
|
var Triggers = class {
|
|
2244
3437
|
client;
|
|
3438
|
+
pusherService;
|
|
2245
3439
|
constructor(client) {
|
|
2246
3440
|
this.client = client;
|
|
3441
|
+
this.pusherService = new PusherService(client);
|
|
3442
|
+
telemetry.instrument(this);
|
|
2247
3443
|
}
|
|
2248
3444
|
/**
|
|
2249
|
-
*
|
|
2250
|
-
* @returns {Promise<TriggerInstance[]>} List of trigger instances
|
|
2251
|
-
*/
|
|
2252
|
-
async list(query, options) {
|
|
2253
|
-
return this.client.triggerInstances.listActive(query, options);
|
|
2254
|
-
}
|
|
2255
|
-
/**
|
|
2256
|
-
* Create a new trigger instance
|
|
2257
|
-
*
|
|
2258
|
-
* @param {string} slug - The slug of the trigger instance
|
|
2259
|
-
* @param {TriggerInstanceUpsertParams} body - The parameters to create the trigger instance
|
|
2260
|
-
* @returns {Promise<TriggerInstanceUpsertResponse>} The created trigger instance
|
|
2261
|
-
*/
|
|
2262
|
-
async create(slug, body, options) {
|
|
2263
|
-
return this.client.triggerInstances.upsert(slug, body, options);
|
|
2264
|
-
}
|
|
2265
|
-
/**
|
|
2266
|
-
* Update an existing trigger instance
|
|
3445
|
+
* Parse the trigger instance list active item
|
|
2267
3446
|
*
|
|
2268
|
-
* @param
|
|
2269
|
-
* @
|
|
2270
|
-
* @returns {Promise<TriggerInstanceUpsertResponse>} The updated trigger instance
|
|
3447
|
+
* @param response - The response from the composio client
|
|
3448
|
+
* @returns The parsed trigger instance list active item
|
|
2271
3449
|
*/
|
|
2272
|
-
|
|
2273
|
-
|
|
3450
|
+
parseTriggerInstanceListActiveItem(response) {
|
|
3451
|
+
const parsed = TriggerInstanceListActiveResponseItemSchema.safeParse({
|
|
3452
|
+
id: response.id,
|
|
3453
|
+
connectedAccountId: response.connected_account_id,
|
|
3454
|
+
disabledAt: response.disabled_at,
|
|
3455
|
+
state: response.state,
|
|
3456
|
+
triggerConfig: response.trigger_config,
|
|
3457
|
+
triggerName: response.trigger_name,
|
|
3458
|
+
updatedAt: response.updated_at,
|
|
3459
|
+
triggerData: response.trigger_data,
|
|
3460
|
+
uuid: response.uuid
|
|
3461
|
+
});
|
|
3462
|
+
if (!parsed.success) {
|
|
3463
|
+
throw new ValidationError(`Invalid trigger instance list active item`, {
|
|
3464
|
+
cause: parsed.error
|
|
3465
|
+
});
|
|
3466
|
+
}
|
|
3467
|
+
return parsed.data;
|
|
2274
3468
|
}
|
|
2275
3469
|
/**
|
|
2276
|
-
*
|
|
3470
|
+
* Fetch list of all the active triggers
|
|
2277
3471
|
*
|
|
2278
|
-
* @param {
|
|
2279
|
-
* @returns
|
|
2280
|
-
*/
|
|
2281
|
-
async delete(slug) {
|
|
2282
|
-
return this.client.triggerInstances.removeUpsert(slug);
|
|
2283
|
-
}
|
|
2284
|
-
/**
|
|
2285
|
-
* Update the status of a trigger
|
|
3472
|
+
* @param {TriggerInstanceListActiveParams} query - The query parameters to filter the trigger instances
|
|
3473
|
+
* @returns {Promise<TriggerInstanceListActiveResponse>} List of trigger instances
|
|
2286
3474
|
*
|
|
2287
|
-
* @
|
|
2288
|
-
* @
|
|
2289
|
-
* @param {RequestOptions} options - Request options
|
|
2290
|
-
* @returns {Promise<TriggerInstanceUpsertResponse>} The updated trigger instance
|
|
2291
|
-
*/
|
|
2292
|
-
async updateStatus(status, params, options) {
|
|
2293
|
-
return this.client.triggerInstances.updateStatus(status, params, options);
|
|
2294
|
-
}
|
|
2295
|
-
/**
|
|
2296
|
-
* Disable a trigger instance
|
|
3475
|
+
* @throws {ValidationError} If the parameters are invalid
|
|
3476
|
+
* @throws {Error} If the client is not authenticated
|
|
2297
3477
|
*
|
|
2298
|
-
* @
|
|
2299
|
-
*
|
|
2300
|
-
*
|
|
3478
|
+
* @example
|
|
3479
|
+
* ```ts
|
|
3480
|
+
* const triggers = await triggers.listActive({
|
|
3481
|
+
* authConfigIds: ['123'],
|
|
3482
|
+
* connectedAccountIds: ['456'],
|
|
3483
|
+
* });
|
|
3484
|
+
* ```
|
|
2301
3485
|
*/
|
|
2302
|
-
async
|
|
2303
|
-
|
|
3486
|
+
async listActive(query) {
|
|
3487
|
+
const parsedParams = TriggerInstanceListActiveParamsSchema.safeParse(query ?? {});
|
|
3488
|
+
if (!parsedParams.success) {
|
|
3489
|
+
throw new ValidationError(`Invalid parameters passed to list triggers`, {
|
|
3490
|
+
cause: parsedParams.error
|
|
3491
|
+
});
|
|
3492
|
+
}
|
|
3493
|
+
const result = await this.client.triggerInstances.listActive(
|
|
3494
|
+
query ? {
|
|
3495
|
+
auth_config_ids: parsedParams.data.authConfigIds,
|
|
3496
|
+
connected_account_ids: parsedParams.data.connectedAccountIds,
|
|
3497
|
+
limit: parsedParams.data.limit,
|
|
3498
|
+
page: parsedParams.data.page,
|
|
3499
|
+
show_disabled: parsedParams.data.showDisabled,
|
|
3500
|
+
trigger_ids: parsedParams.data.triggerIds,
|
|
3501
|
+
trigger_names: parsedParams.data.triggerNames
|
|
3502
|
+
} : void 0
|
|
3503
|
+
);
|
|
3504
|
+
const parsedResult = TriggerInstanceListActiveResponseSchema.safeParse({
|
|
3505
|
+
items: result.items.map((item) => this.parseTriggerInstanceListActiveItem(item)),
|
|
3506
|
+
nextCursor: result.next_cursor,
|
|
3507
|
+
totalPages: result.total_pages
|
|
3508
|
+
});
|
|
3509
|
+
if (!parsedResult.success) {
|
|
3510
|
+
throw new ValidationError(`Invalid trigger instance list active response`, {
|
|
3511
|
+
cause: parsedResult.error
|
|
3512
|
+
});
|
|
3513
|
+
}
|
|
3514
|
+
return parsedResult.data;
|
|
2304
3515
|
}
|
|
2305
3516
|
/**
|
|
2306
|
-
*
|
|
3517
|
+
* Create a new trigger instance
|
|
2307
3518
|
*
|
|
2308
3519
|
* @param {string} slug - The slug of the trigger instance
|
|
2309
|
-
* @param {
|
|
2310
|
-
* @returns {Promise<TriggerInstanceUpsertResponse>} The
|
|
2311
|
-
*/
|
|
2312
|
-
async
|
|
2313
|
-
|
|
2314
|
-
|
|
2315
|
-
|
|
2316
|
-
|
|
2317
|
-
|
|
2318
|
-
|
|
2319
|
-
|
|
2320
|
-
|
|
2321
|
-
|
|
2322
|
-
* @param {RequestOptions} options - Request options
|
|
2323
|
-
* @returns {Promise<TriggersTypeListResponse>} The list of trigger types
|
|
2324
|
-
*/
|
|
2325
|
-
async listTypes(query, options) {
|
|
2326
|
-
return this.client.triggersTypes.list(query, options);
|
|
2327
|
-
}
|
|
2328
|
-
/**
|
|
2329
|
-
* Retrieve a trigger type by its slug
|
|
2330
|
-
*
|
|
2331
|
-
* @param {string} slug - The slug of the trigger type
|
|
2332
|
-
* @param {RequestOptions} options - request options
|
|
2333
|
-
* @returns {Promise<TriggersTypeRetrieveResponse>} The trigger type object
|
|
2334
|
-
*/
|
|
2335
|
-
async getType(slug, options) {
|
|
2336
|
-
return this.client.triggersTypes.retrieve(slug, options);
|
|
2337
|
-
}
|
|
2338
|
-
/**
|
|
2339
|
-
* Fetches the list of all the available trigger enums
|
|
2340
|
-
*
|
|
2341
|
-
* This method is used by the CLI where filters are not required.
|
|
2342
|
-
* @param options
|
|
2343
|
-
* @returns
|
|
2344
|
-
*/
|
|
2345
|
-
async listEnum(options) {
|
|
2346
|
-
return this.client.triggersTypes.retrieveEnum(options);
|
|
2347
|
-
}
|
|
2348
|
-
async subscribe(fn, filters = {}) {
|
|
2349
|
-
if (!fn) throw new Error("Function is required for trigger subscription");
|
|
2350
|
-
const session = new Session(this.client);
|
|
2351
|
-
const sessionInfo = await session.getInfo();
|
|
2352
|
-
const clientId = sessionInfo.project?.id;
|
|
2353
|
-
if (!clientId) throw new Error("Client ID not found");
|
|
2354
|
-
if (!this.client.apiKey) throw new Error("API key not found");
|
|
2355
|
-
await PusherUtils.getPusherClient(this.client.baseURL, this.client.apiKey);
|
|
2356
|
-
const shouldSendTrigger = (data) => {
|
|
2357
|
-
if (Object.keys(filters).length === 0) return true;
|
|
2358
|
-
else {
|
|
2359
|
-
return (!filters.appName || data.appName.toLowerCase() === filters.appName.toLowerCase()) && (!filters.triggerId || data.metadata.id.toLowerCase() === filters.triggerId.toLowerCase()) && (!filters.connectionId || data.metadata.connectionId.toLowerCase() === filters.connectionId.toLowerCase()) && (!filters.triggerName || data.metadata.triggerName.toLowerCase() === filters.triggerName.toLowerCase()) && (!filters.entityId || data.metadata.connection.clientUniqueUserId.toLowerCase() === filters.entityId.toLowerCase()) && (!filters.integrationId || data.metadata.connection.integrationId.toLowerCase() === filters.integrationId.toLowerCase());
|
|
2360
|
-
}
|
|
2361
|
-
};
|
|
2362
|
-
logger_default.debug("Subscribing to triggers", filters);
|
|
2363
|
-
PusherUtils.triggerSubscribe(clientId, (data) => {
|
|
2364
|
-
if (shouldSendTrigger(data)) {
|
|
2365
|
-
fn(data);
|
|
2366
|
-
}
|
|
2367
|
-
});
|
|
2368
|
-
}
|
|
2369
|
-
async unsubscribe() {
|
|
2370
|
-
const session = new Session(this.client);
|
|
2371
|
-
const sessionInfo = await session.getInfo();
|
|
2372
|
-
const clientId = sessionInfo.project?.id;
|
|
2373
|
-
if (!clientId) throw new Error("Client ID not found");
|
|
2374
|
-
PusherUtils.triggerUnsubscribe(clientId);
|
|
2375
|
-
}
|
|
2376
|
-
};
|
|
2377
|
-
|
|
2378
|
-
// src/types/telemetry.types.ts
|
|
2379
|
-
var TELEMETRY_EVENTS = {
|
|
2380
|
-
SDK_INITIALIZED: "SDK_INITIALIZED",
|
|
2381
|
-
SDK_METHOD_INVOKED: "SDK_METHOD_INVOKED",
|
|
2382
|
-
SDK_METHOD_ERROR: "SDK_METHOD_ERROR",
|
|
2383
|
-
CLI_INVOKED: "CLI_INVOKED"
|
|
2384
|
-
};
|
|
2385
|
-
|
|
2386
|
-
// src/utils/constants.ts
|
|
2387
|
-
var COMPOSIO_DIR = ".composio";
|
|
2388
|
-
var USER_DATA_FILE_NAME = "user_data.json";
|
|
2389
|
-
var DEFAULT_BASE_URL = "https://backend.composio.dev";
|
|
2390
|
-
var TELEMETRY_URL = "https://app.composio.dev";
|
|
2391
|
-
var IS_DEVELOPMENT_OR_CI = process.env.DEVELOPMENT || process.env.CI || false;
|
|
2392
|
-
|
|
2393
|
-
// src/telemetry/BatchProcessor.ts
|
|
2394
|
-
var BatchProcessor = class {
|
|
2395
|
-
batch = [];
|
|
2396
|
-
time;
|
|
2397
|
-
batchSize;
|
|
2398
|
-
processBatchCallback;
|
|
2399
|
-
timer = null;
|
|
2400
|
-
constructor(time = 2e3, batchSize = 100, processBatchCallback) {
|
|
2401
|
-
this.batch = [];
|
|
2402
|
-
this.time = time;
|
|
2403
|
-
this.batchSize = batchSize;
|
|
2404
|
-
this.processBatchCallback = processBatchCallback;
|
|
2405
|
-
}
|
|
2406
|
-
pushItem(item) {
|
|
2407
|
-
this.batch.push(item);
|
|
2408
|
-
if (this.batch.length >= this.batchSize) {
|
|
2409
|
-
this.processBatch();
|
|
2410
|
-
} else if (!this.timer) {
|
|
2411
|
-
this.timer = setTimeout(() => this.processBatch(), this.time);
|
|
2412
|
-
}
|
|
2413
|
-
}
|
|
2414
|
-
processBatch() {
|
|
2415
|
-
if (this.batch.length > 0) {
|
|
2416
|
-
this.processBatchCallback(this.batch);
|
|
2417
|
-
this.batch = [];
|
|
2418
|
-
}
|
|
2419
|
-
if (this.timer) {
|
|
2420
|
-
clearTimeout(this.timer);
|
|
2421
|
-
this.timer = null;
|
|
2422
|
-
}
|
|
2423
|
-
}
|
|
2424
|
-
};
|
|
2425
|
-
|
|
2426
|
-
// src/telemetry/transports/BrowserTransport.ts
|
|
2427
|
-
var BrowserTelemetryTransport = class {
|
|
2428
|
-
send(payload) {
|
|
2429
|
-
if (typeof window === "undefined") {
|
|
2430
|
-
return Promise.reject(
|
|
2431
|
-
new Error("BrowserTelemetryTransport can only be used in browser environments")
|
|
2432
|
-
);
|
|
2433
|
-
}
|
|
2434
|
-
return new Promise((resolve) => {
|
|
2435
|
-
try {
|
|
2436
|
-
const xhr = new XMLHttpRequest();
|
|
2437
|
-
xhr.open(payload.method, payload.url, true);
|
|
2438
|
-
xhr.setRequestHeader("Content-Type", "application/json");
|
|
2439
|
-
Object.entries(payload.headers || {}).forEach(([key, value]) => {
|
|
2440
|
-
xhr.setRequestHeader(key, value);
|
|
2441
|
-
});
|
|
2442
|
-
xhr.onload = function() {
|
|
2443
|
-
resolve();
|
|
2444
|
-
};
|
|
2445
|
-
xhr.send(JSON.stringify(payload.data));
|
|
2446
|
-
} catch (error) {
|
|
2447
|
-
logger_default.error("Error sending error to telemetry", error);
|
|
2448
|
-
resolve();
|
|
2449
|
-
}
|
|
2450
|
-
});
|
|
2451
|
-
}
|
|
2452
|
-
};
|
|
2453
|
-
|
|
2454
|
-
// src/telemetry/transports/ProcessTransport.ts
|
|
2455
|
-
var ProcessTelemetryTransport = class {
|
|
2456
|
-
send(payload) {
|
|
2457
|
-
if (typeof window !== "undefined") {
|
|
2458
|
-
return Promise.reject(
|
|
2459
|
-
new Error("ProcessTelemetryTransport can only be used in Node.js environments")
|
|
2460
|
-
);
|
|
2461
|
-
}
|
|
2462
|
-
return new Promise((resolve) => {
|
|
2463
|
-
try {
|
|
2464
|
-
const url = new URL(payload.url);
|
|
2465
|
-
const protocol = url.protocol === "https:" ? "https" : "http";
|
|
2466
|
-
const port = url.port || (url.protocol === "https:" ? 443 : 80);
|
|
2467
|
-
const args = [
|
|
2468
|
-
"-e",
|
|
2469
|
-
`
|
|
2470
|
-
const http = require('${protocol}');
|
|
2471
|
-
const options = {
|
|
2472
|
-
hostname: '${url.hostname}',
|
|
2473
|
-
path: '${url.pathname}${url.search}',
|
|
2474
|
-
port: ${port},
|
|
2475
|
-
method: '${payload.method}',
|
|
2476
|
-
headers: ${JSON.stringify(payload.headers)}
|
|
2477
|
-
};
|
|
2478
|
-
|
|
2479
|
-
const req = http.request(options, (res) => {
|
|
2480
|
-
res.on('data', () => {});
|
|
2481
|
-
res.on('end', () => {
|
|
2482
|
-
process.exit(0);
|
|
2483
|
-
});
|
|
2484
|
-
});
|
|
2485
|
-
|
|
2486
|
-
req.on('error', () => {
|
|
2487
|
-
process.exit(0);
|
|
2488
|
-
});
|
|
2489
|
-
|
|
2490
|
-
req.write(JSON.stringify(${JSON.stringify(payload.data)}));
|
|
2491
|
-
req.end();
|
|
2492
|
-
`
|
|
2493
|
-
];
|
|
2494
|
-
import("child_process").then(({ spawn }) => {
|
|
2495
|
-
spawn("node", args, {
|
|
2496
|
-
stdio: "ignore",
|
|
2497
|
-
detached: true,
|
|
2498
|
-
shell: false
|
|
2499
|
-
}).unref();
|
|
2500
|
-
resolve();
|
|
2501
|
-
}).catch(() => {
|
|
2502
|
-
resolve();
|
|
2503
|
-
});
|
|
2504
|
-
} catch (error) {
|
|
2505
|
-
logger_default.error("Error sending telemetry", error);
|
|
2506
|
-
resolve();
|
|
2507
|
-
}
|
|
3520
|
+
* @param {TriggerInstanceUpsertParams} body - The parameters to create the trigger instance
|
|
3521
|
+
* @returns {Promise<TriggerInstanceUpsertResponse>} The created trigger instance
|
|
3522
|
+
*/
|
|
3523
|
+
async create(slug, body) {
|
|
3524
|
+
const parsedBody = TriggerInstanceUpsertParamsSchema.safeParse(body);
|
|
3525
|
+
if (!parsedBody.success) {
|
|
3526
|
+
throw new ValidationError(`Invalid parameters passed to create trigger`, {
|
|
3527
|
+
cause: parsedBody.error
|
|
3528
|
+
});
|
|
3529
|
+
}
|
|
3530
|
+
const result = await this.client.triggerInstances.upsert(slug, {
|
|
3531
|
+
connected_account_id: parsedBody.data.connectedAccountId,
|
|
3532
|
+
trigger_config: parsedBody.data.triggerConfig
|
|
2508
3533
|
});
|
|
2509
|
-
|
|
2510
|
-
|
|
2511
|
-
|
|
2512
|
-
|
|
2513
|
-
|
|
2514
|
-
|
|
2515
|
-
|
|
2516
|
-
batchProcessor = new BatchProcessor(100, 10, async (data) => {
|
|
2517
|
-
await this.sendTelemetry(data);
|
|
2518
|
-
});
|
|
2519
|
-
constructor(metadata, transport) {
|
|
2520
|
-
this.telemetryMetadata = metadata;
|
|
2521
|
-
const isBrowser = typeof window !== "undefined";
|
|
2522
|
-
if (transport) {
|
|
2523
|
-
this.transport = transport;
|
|
2524
|
-
} else if (isBrowser) {
|
|
2525
|
-
this.transport = new BrowserTelemetryTransport();
|
|
2526
|
-
} else {
|
|
2527
|
-
this.transport = new ProcessTelemetryTransport();
|
|
3534
|
+
const parsedResult = TriggerInstanceUpsertResponseSchema.safeParse({
|
|
3535
|
+
triggerId: result.trigger_id
|
|
3536
|
+
});
|
|
3537
|
+
if (!parsedResult.success) {
|
|
3538
|
+
throw new ValidationError(`Invalid trigger instance upsert response`, {
|
|
3539
|
+
cause: parsedResult.error
|
|
3540
|
+
});
|
|
2528
3541
|
}
|
|
2529
|
-
|
|
2530
|
-
{
|
|
2531
|
-
eventName: TELEMETRY_EVENTS.SDK_INITIALIZED,
|
|
2532
|
-
data: {},
|
|
2533
|
-
sdk_meta: this.telemetryMetadata
|
|
2534
|
-
}
|
|
2535
|
-
]);
|
|
3542
|
+
return parsedResult.data;
|
|
2536
3543
|
}
|
|
2537
3544
|
/**
|
|
2538
|
-
*
|
|
3545
|
+
* Update an existing trigger instance
|
|
2539
3546
|
*
|
|
2540
|
-
*
|
|
2541
|
-
*
|
|
2542
|
-
* @
|
|
2543
|
-
|
|
3547
|
+
* @param {string} slug - The slug of the trigger instance
|
|
3548
|
+
* @param {TriggerInstanceManageUpdateParams} body - The parameters to create the trigger instance
|
|
3549
|
+
* @returns {Promise<TriggerInstanceUpsertResponse>} The updated trigger instance
|
|
3550
|
+
*/
|
|
3551
|
+
async update(slug, body) {
|
|
3552
|
+
return this.client.triggerInstances.manage.update(slug, body);
|
|
3553
|
+
}
|
|
3554
|
+
/**
|
|
3555
|
+
* Delete a trigger instance
|
|
3556
|
+
*
|
|
3557
|
+
* @param {string} triggerId - The slug of the trigger instance
|
|
2544
3558
|
* @returns
|
|
2545
3559
|
*/
|
|
2546
|
-
|
|
2547
|
-
const
|
|
2548
|
-
const
|
|
2549
|
-
|
|
2550
|
-
return key !== "constructor" && descriptor && typeof descriptor.value === "function" && descriptor.value.constructor.name === "AsyncFunction";
|
|
3560
|
+
async delete(triggerId) {
|
|
3561
|
+
const result = await this.client.triggerInstances.manage.delete(triggerId);
|
|
3562
|
+
const parsedResult = TriggerInstanceManageDeleteResponseSchema.safeParse({
|
|
3563
|
+
triggerId: result.trigger_id
|
|
2551
3564
|
});
|
|
2552
|
-
|
|
2553
|
-
|
|
2554
|
-
|
|
2555
|
-
|
|
2556
|
-
const telemetryPayload = {
|
|
2557
|
-
eventName: TELEMETRY_EVENTS.SDK_METHOD_INVOKED,
|
|
2558
|
-
data: {
|
|
2559
|
-
fileName: instrumentedClassName,
|
|
2560
|
-
method: name,
|
|
2561
|
-
params: args
|
|
2562
|
-
},
|
|
2563
|
-
sdk_meta: this.telemetryMetadata
|
|
2564
|
-
};
|
|
2565
|
-
this.batchProcessor.pushItem(telemetryPayload);
|
|
2566
|
-
try {
|
|
2567
|
-
return await originalMethod.apply(instance, args);
|
|
2568
|
-
} catch (error) {
|
|
2569
|
-
const telemetryPayload2 = {
|
|
2570
|
-
eventName: TELEMETRY_EVENTS.SDK_METHOD_ERROR,
|
|
2571
|
-
data: {
|
|
2572
|
-
fileName: instrumentedClassName,
|
|
2573
|
-
method: name,
|
|
2574
|
-
params: args,
|
|
2575
|
-
error
|
|
2576
|
-
},
|
|
2577
|
-
sdk_meta: this.telemetryMetadata
|
|
2578
|
-
};
|
|
2579
|
-
this.batchProcessor.pushItem(telemetryPayload2);
|
|
2580
|
-
throw error;
|
|
2581
|
-
}
|
|
2582
|
-
};
|
|
3565
|
+
if (!parsedResult.success) {
|
|
3566
|
+
throw new ValidationError(`Invalid trigger instance manage delete response`, {
|
|
3567
|
+
cause: parsedResult.error
|
|
3568
|
+
});
|
|
2583
3569
|
}
|
|
2584
|
-
return
|
|
3570
|
+
return parsedResult.data;
|
|
2585
3571
|
}
|
|
2586
3572
|
/**
|
|
2587
|
-
*
|
|
2588
|
-
*
|
|
3573
|
+
* Disable a trigger instance
|
|
3574
|
+
*
|
|
3575
|
+
* @param {string} triggerId - The id of the trigger instance
|
|
3576
|
+
* @returns {Promise<TriggerInstanceUpsertResponse>} The updated trigger instance
|
|
3577
|
+
*/
|
|
3578
|
+
async disable(triggerId) {
|
|
3579
|
+
return this.client.triggerInstances.manage.update(triggerId, {
|
|
3580
|
+
status: "disable"
|
|
3581
|
+
});
|
|
3582
|
+
}
|
|
3583
|
+
/**
|
|
3584
|
+
* Enable a trigger instance
|
|
3585
|
+
*
|
|
3586
|
+
* @param {string} triggerId - The id of the trigger instance
|
|
3587
|
+
* @returns {Promise<TriggerInstanceUpsertResponse>} The updated trigger instance
|
|
3588
|
+
*/
|
|
3589
|
+
async enable(triggerId) {
|
|
3590
|
+
return this.client.triggerInstances.manage.update(triggerId, {
|
|
3591
|
+
status: "enable"
|
|
3592
|
+
});
|
|
3593
|
+
}
|
|
3594
|
+
/**
|
|
3595
|
+
* @TODO Learn about trigger types
|
|
3596
|
+
*/
|
|
3597
|
+
/**
|
|
3598
|
+
* List all the trigger types
|
|
3599
|
+
*
|
|
3600
|
+
* @param {TriggersTypeListParams} query - The query parameters to filter the trigger types
|
|
3601
|
+
* @param {RequestOptions} options - Request options
|
|
3602
|
+
* @returns {Promise<TriggersTypeListResponse>} The list of trigger types
|
|
3603
|
+
*/
|
|
3604
|
+
async listTypes(query) {
|
|
3605
|
+
return this.client.triggersTypes.list(query);
|
|
3606
|
+
}
|
|
3607
|
+
/**
|
|
3608
|
+
* Retrieve a trigger type by its slug
|
|
3609
|
+
*
|
|
3610
|
+
* @param {string} slug - The slug of the trigger type
|
|
3611
|
+
* @param {RequestOptions} options - request options
|
|
3612
|
+
* @returns {Promise<TriggersTypeRetrieveResponse>} The trigger type object
|
|
3613
|
+
*/
|
|
3614
|
+
async getType(slug) {
|
|
3615
|
+
return this.client.triggersTypes.retrieve(slug);
|
|
3616
|
+
}
|
|
3617
|
+
/**
|
|
3618
|
+
* Fetches the list of all the available trigger enums
|
|
3619
|
+
*
|
|
3620
|
+
* This method is used by the CLI where filters are not required.
|
|
3621
|
+
* @param options
|
|
2589
3622
|
* @returns
|
|
2590
3623
|
*/
|
|
2591
|
-
async
|
|
2592
|
-
|
|
2593
|
-
|
|
2594
|
-
|
|
3624
|
+
async listEnum() {
|
|
3625
|
+
return this.client.triggersTypes.retrieveEnum();
|
|
3626
|
+
}
|
|
3627
|
+
/**
|
|
3628
|
+
* Subscribe to all the triggers
|
|
3629
|
+
*
|
|
3630
|
+
* @param fn - The function to call when a trigger is received
|
|
3631
|
+
* @param filters - The filters to apply to the triggers
|
|
3632
|
+
*
|
|
3633
|
+
* @example
|
|
3634
|
+
* ```ts
|
|
3635
|
+
*
|
|
3636
|
+
* triggers.subscribe((data) => {
|
|
3637
|
+
* console.log(data);
|
|
3638
|
+
* }, );
|
|
3639
|
+
* ```
|
|
3640
|
+
*/
|
|
3641
|
+
async subscribe(fn, filters = {}) {
|
|
3642
|
+
if (!fn) throw new Error("Function is required for trigger subscription");
|
|
3643
|
+
const parsedFilters = TriggerSubscribeParamSchema.safeParse(filters);
|
|
3644
|
+
if (!parsedFilters.success) {
|
|
3645
|
+
throw new ValidationError(`Invalid parameters passed to subscribe to triggers`, {
|
|
3646
|
+
cause: parsedFilters.error
|
|
3647
|
+
});
|
|
2595
3648
|
}
|
|
2596
|
-
const
|
|
2597
|
-
|
|
2598
|
-
|
|
2599
|
-
|
|
2600
|
-
|
|
2601
|
-
|
|
3649
|
+
const shouldSendTriggerAfterFilters = (data) => {
|
|
3650
|
+
if (parsedFilters.data.toolkits?.length && !parsedFilters.data.toolkits.map((toolkit) => toolkit.toLowerCase()).includes(data.toolkitSlug.toLowerCase())) {
|
|
3651
|
+
logger_default.debug(
|
|
3652
|
+
"Trigger does not match toolkits filter",
|
|
3653
|
+
JSON.stringify(parsedFilters.data.toolkits, null, 2)
|
|
3654
|
+
);
|
|
3655
|
+
return false;
|
|
3656
|
+
}
|
|
3657
|
+
if (parsedFilters.data.triggerId && parsedFilters.data.triggerId !== data.id) {
|
|
3658
|
+
logger_default.debug(
|
|
3659
|
+
"Trigger does not match triggerId filter",
|
|
3660
|
+
JSON.stringify(parsedFilters.data.triggerId, null, 2)
|
|
3661
|
+
);
|
|
3662
|
+
return false;
|
|
3663
|
+
}
|
|
3664
|
+
if (parsedFilters.data.connectedAccountId && parsedFilters.data.connectedAccountId !== data.metadata.connectedAccount.id) {
|
|
3665
|
+
logger_default.debug(
|
|
3666
|
+
"Trigger does not match connectedAccountId filter",
|
|
3667
|
+
JSON.stringify(parsedFilters.data.connectedAccountId, null, 2)
|
|
3668
|
+
);
|
|
3669
|
+
return false;
|
|
3670
|
+
}
|
|
3671
|
+
if (parsedFilters.data.triggerSlug?.length && !parsedFilters.data.triggerSlug.map((triggerSlug) => triggerSlug.toLowerCase()).includes(data.triggerSlug.toLowerCase())) {
|
|
3672
|
+
logger_default.debug(
|
|
3673
|
+
"Trigger does not match triggerSlug filter",
|
|
3674
|
+
JSON.stringify(parsedFilters.data.triggerSlug, null, 2)
|
|
3675
|
+
);
|
|
3676
|
+
return false;
|
|
3677
|
+
}
|
|
3678
|
+
if (parsedFilters.data.triggerData && parsedFilters.data.triggerData !== data.metadata.triggerData) {
|
|
3679
|
+
logger_default.debug(
|
|
3680
|
+
"Trigger does not match triggerData filter",
|
|
3681
|
+
JSON.stringify(parsedFilters.data.triggerData, null, 2)
|
|
3682
|
+
);
|
|
3683
|
+
return false;
|
|
3684
|
+
}
|
|
3685
|
+
if (parsedFilters.data.userId && parsedFilters.data.userId !== data.metadata.connectedAccount.userId) {
|
|
3686
|
+
logger_default.debug(
|
|
3687
|
+
"Trigger does not match userId filter",
|
|
3688
|
+
JSON.stringify(parsedFilters.data.userId, null, 2)
|
|
3689
|
+
);
|
|
3690
|
+
return false;
|
|
3691
|
+
}
|
|
3692
|
+
logger_default.debug("Trigger matches all filters", JSON.stringify(parsedFilters.data, null, 2));
|
|
3693
|
+
return true;
|
|
2602
3694
|
};
|
|
2603
|
-
|
|
3695
|
+
logger_default.debug("\u{1F504} Subscribing to triggers with filters: ", JSON.stringify(filters, null, 2));
|
|
3696
|
+
await this.pusherService.subscribe((_data) => {
|
|
3697
|
+
logger_default.debug("Received raw trigger data", JSON.stringify(_data, null, 2));
|
|
3698
|
+
const data = _data;
|
|
3699
|
+
const parsedData = IncomingTriggerPayloadSchema.safeParse({
|
|
3700
|
+
id: data.metadata.id,
|
|
3701
|
+
triggerSlug: data.metadata.triggerName,
|
|
3702
|
+
toolkitSlug: data.appName,
|
|
3703
|
+
userId: data.metadata.connection?.clientUniqueUserId,
|
|
3704
|
+
payload: data.payload,
|
|
3705
|
+
originalPayload: data.originalPayload,
|
|
3706
|
+
metadata: {
|
|
3707
|
+
id: data.metadata.id,
|
|
3708
|
+
triggerConfig: data.metadata.triggerConfig,
|
|
3709
|
+
triggerSlug: data.metadata.triggerName,
|
|
3710
|
+
toolkitSlug: data.appName,
|
|
3711
|
+
triggerData: data.metadata.triggerData,
|
|
3712
|
+
connectedAccount: {
|
|
3713
|
+
id: data.metadata.connection?.connectedAccountNanoId,
|
|
3714
|
+
uuid: data.metadata.connection?.id,
|
|
3715
|
+
authConfigId: data.metadata.connection?.authConfigNanoId,
|
|
3716
|
+
authConfigUUID: data.metadata.connection?.integrationId,
|
|
3717
|
+
userId: data.metadata.connection?.clientUniqueUserId,
|
|
3718
|
+
status: data.metadata.connection?.status
|
|
3719
|
+
}
|
|
3720
|
+
}
|
|
3721
|
+
});
|
|
3722
|
+
logger_default.debug("Parsed trigger data", JSON.stringify(parsedData.data, null, 2));
|
|
3723
|
+
if (parsedData.error) {
|
|
3724
|
+
throw new ValidationError(`Invalid trigger payload`, {
|
|
3725
|
+
cause: parsedData.error
|
|
3726
|
+
});
|
|
3727
|
+
}
|
|
3728
|
+
if (shouldSendTriggerAfterFilters(parsedData.data)) {
|
|
3729
|
+
try {
|
|
3730
|
+
fn(parsedData.data);
|
|
3731
|
+
} catch (error) {
|
|
3732
|
+
logger_default.error("\u274C Error in trigger callback:", error);
|
|
3733
|
+
}
|
|
3734
|
+
} else {
|
|
3735
|
+
logger_default.debug("Trigger does not match filters", JSON.stringify(parsedFilters.data, null, 2));
|
|
3736
|
+
}
|
|
3737
|
+
});
|
|
3738
|
+
}
|
|
3739
|
+
/**
|
|
3740
|
+
* Unsubscribe from all the triggers
|
|
3741
|
+
*
|
|
3742
|
+
* @returns {Promise<void>}
|
|
3743
|
+
*
|
|
3744
|
+
* @example
|
|
3745
|
+
* ```ts
|
|
3746
|
+
* composio.trigger.subscribe((data) => {
|
|
3747
|
+
* console.log(data);
|
|
3748
|
+
* });
|
|
3749
|
+
*
|
|
3750
|
+
* await triggers.unsubscribe();
|
|
3751
|
+
* ```
|
|
3752
|
+
*/
|
|
3753
|
+
async unsubscribe() {
|
|
3754
|
+
await this.pusherService.unsubscribe();
|
|
2604
3755
|
}
|
|
2605
3756
|
};
|
|
2606
3757
|
|
|
@@ -2611,6 +3762,7 @@ var userDataPath = () => {
|
|
|
2611
3762
|
const os = __require("os");
|
|
2612
3763
|
return path.join(os.homedir(), COMPOSIO_DIR, USER_DATA_FILE_NAME);
|
|
2613
3764
|
} catch (_error) {
|
|
3765
|
+
logger_default.debug("Environment", `Unable to get user data path`);
|
|
2614
3766
|
return null;
|
|
2615
3767
|
}
|
|
2616
3768
|
};
|
|
@@ -2620,6 +3772,7 @@ var getUserDataJson = () => {
|
|
|
2620
3772
|
const data = fs.readFileSync(userDataPath(), "utf8");
|
|
2621
3773
|
return JSON.parse(data);
|
|
2622
3774
|
} catch (_error) {
|
|
3775
|
+
logger_default.debug("Environment", "No user data file found");
|
|
2623
3776
|
return {};
|
|
2624
3777
|
}
|
|
2625
3778
|
};
|
|
@@ -2628,27 +3781,33 @@ function getSDKConfig(baseUrl, apiKey) {
|
|
|
2628
3781
|
const { api_key: apiKeyFromUserConfig, base_url: baseURLFromUserConfig } = userData;
|
|
2629
3782
|
const baseURLParsed = baseUrl || getEnvVariable("COMPOSIO_BASE_URL") || baseURLFromUserConfig || DEFAULT_BASE_URL;
|
|
2630
3783
|
const apiKeyParsed = apiKey || getEnvVariable("COMPOSIO_API_KEY") || apiKeyFromUserConfig || "";
|
|
3784
|
+
if (!apiKeyParsed) {
|
|
3785
|
+
ComposioError.handle(new ComposioNoAPIKeyError(), {
|
|
3786
|
+
exitProcess: true
|
|
3787
|
+
});
|
|
3788
|
+
}
|
|
3789
|
+
logger_default.debug("Environment", `API Key: ${apiKeyParsed}`);
|
|
3790
|
+
logger_default.debug("Environment", `Base URL: ${baseURLParsed}`);
|
|
2631
3791
|
return { baseURL: baseURLParsed, apiKey: apiKeyParsed };
|
|
2632
3792
|
}
|
|
2633
3793
|
|
|
2634
3794
|
// src/utils/version.ts
|
|
2635
|
-
|
|
2636
|
-
const v1 = version1.split(".").map(Number);
|
|
2637
|
-
const v2 = version2.split(".").map(Number);
|
|
2638
|
-
for (let i = 0; i < 3; i++) {
|
|
2639
|
-
if (v1[i] > v2[i]) return true;
|
|
2640
|
-
if (v1[i] < v2[i]) return false;
|
|
2641
|
-
}
|
|
2642
|
-
return false;
|
|
2643
|
-
}
|
|
3795
|
+
import semver from "semver";
|
|
2644
3796
|
async function checkForLatestVersionFromNPM(currentVersion) {
|
|
2645
3797
|
try {
|
|
2646
|
-
const packageName = "composio
|
|
3798
|
+
const packageName = "@composio/core";
|
|
2647
3799
|
const currentVersionFromPackageJson = currentVersion;
|
|
3800
|
+
if (!semver.valid(currentVersionFromPackageJson)) {
|
|
3801
|
+
return;
|
|
3802
|
+
}
|
|
3803
|
+
const prerelease = semver.prerelease(currentVersionFromPackageJson);
|
|
3804
|
+
if (prerelease && (String(prerelease[0]).includes("alpha") || String(prerelease[0]).includes("beta"))) {
|
|
3805
|
+
return;
|
|
3806
|
+
}
|
|
2648
3807
|
const response = await fetch(`https://registry.npmjs.org/${packageName}/latest`);
|
|
2649
3808
|
const data = await response.json();
|
|
2650
3809
|
const latestVersion = data.version;
|
|
2651
|
-
if (
|
|
3810
|
+
if (semver.gt(latestVersion, currentVersionFromPackageJson) && !IS_DEVELOPMENT_OR_CI) {
|
|
2652
3811
|
logger_default.info(
|
|
2653
3812
|
`\u{1F680} Upgrade available! Your composio-core version (${currentVersionFromPackageJson}) is behind. Latest version: ${latestVersion}.`
|
|
2654
3813
|
);
|
|
@@ -2675,11 +3834,12 @@ var BaseProvider = class {
|
|
|
2675
3834
|
}
|
|
2676
3835
|
/**
|
|
2677
3836
|
* @public
|
|
2678
|
-
*
|
|
2679
|
-
* This function is used by
|
|
3837
|
+
* Global function to execute a tool.
|
|
3838
|
+
* This function is used by providerds to implement helper functions to execute tools.
|
|
2680
3839
|
* This is a 1:1 mapping of the `execute` method in the `Tools` class.
|
|
2681
3840
|
* @param {string} toolSlug - The slug of the tool to execute.
|
|
2682
|
-
* @param {
|
|
3841
|
+
* @param {ToolExecuteParams} body - The body of the tool execution.
|
|
3842
|
+
* @param {ExecuteToolModifiers} modifers - The modifiers of the tool execution.
|
|
2683
3843
|
* @returns {Promise<string>} The result of the tool execution.
|
|
2684
3844
|
*/
|
|
2685
3845
|
executeTool(toolSlug, body, modifers) {
|
|
@@ -2700,10 +3860,54 @@ var BaseAgenticProvider = class extends BaseProvider {
|
|
|
2700
3860
|
var OpenAIProvider = class extends BaseNonAgenticProvider {
|
|
2701
3861
|
name = "openai";
|
|
2702
3862
|
/**
|
|
2703
|
-
*
|
|
2704
|
-
*
|
|
2705
|
-
*
|
|
2706
|
-
*
|
|
3863
|
+
* Creates a new instance of the OpenAIProvider.
|
|
3864
|
+
*
|
|
3865
|
+
* This is the default provider for the Composio SDK and is automatically
|
|
3866
|
+
* available without additional installation.
|
|
3867
|
+
*
|
|
3868
|
+
* @example
|
|
3869
|
+
* ```typescript
|
|
3870
|
+
* // The OpenAIProvider is used by default when initializing Composio
|
|
3871
|
+
* const composio = new Composio({
|
|
3872
|
+
* apiKey: 'your-api-key'
|
|
3873
|
+
* });
|
|
3874
|
+
*
|
|
3875
|
+
* // You can also explicitly specify it
|
|
3876
|
+
* const composio = new Composio({
|
|
3877
|
+
* apiKey: 'your-api-key',
|
|
3878
|
+
* provider: new OpenAIProvider()
|
|
3879
|
+
* });
|
|
3880
|
+
* ```
|
|
3881
|
+
*/
|
|
3882
|
+
constructor() {
|
|
3883
|
+
super();
|
|
3884
|
+
}
|
|
3885
|
+
/**
|
|
3886
|
+
* Wraps a Composio tool in the OpenAI function calling format.
|
|
3887
|
+
*
|
|
3888
|
+
* This method transforms a Composio tool definition into the format
|
|
3889
|
+
* expected by OpenAI's function calling API.
|
|
3890
|
+
*
|
|
3891
|
+
* @param tool - The Composio tool to wrap
|
|
3892
|
+
* @returns The wrapped tool in OpenAI format
|
|
3893
|
+
*
|
|
3894
|
+
* @example
|
|
3895
|
+
* ```typescript
|
|
3896
|
+
* // Wrap a single tool for use with OpenAI
|
|
3897
|
+
* const composioTool = {
|
|
3898
|
+
* slug: 'SEARCH_TOOL',
|
|
3899
|
+
* description: 'Search for information',
|
|
3900
|
+
* inputParameters: {
|
|
3901
|
+
* type: 'object',
|
|
3902
|
+
* properties: {
|
|
3903
|
+
* query: { type: 'string' }
|
|
3904
|
+
* },
|
|
3905
|
+
* required: ['query']
|
|
3906
|
+
* }
|
|
3907
|
+
* };
|
|
3908
|
+
*
|
|
3909
|
+
* const openAITool = provider.wrapTool(composioTool);
|
|
3910
|
+
* ```
|
|
2707
3911
|
*/
|
|
2708
3912
|
wrapTool = (tool) => {
|
|
2709
3913
|
const formattedSchema = {
|
|
@@ -2716,14 +3920,78 @@ var OpenAIProvider = class extends BaseNonAgenticProvider {
|
|
|
2716
3920
|
function: formattedSchema
|
|
2717
3921
|
};
|
|
2718
3922
|
};
|
|
3923
|
+
/**
|
|
3924
|
+
* Wraps multiple Composio tools in the OpenAI function calling format.
|
|
3925
|
+
*
|
|
3926
|
+
* This method transforms a list of Composio tools into the format
|
|
3927
|
+
* expected by OpenAI's function calling API.
|
|
3928
|
+
*
|
|
3929
|
+
* @param tools - Array of Composio tools to wrap
|
|
3930
|
+
* @returns Array of wrapped tools in OpenAI format
|
|
3931
|
+
*
|
|
3932
|
+
* @example
|
|
3933
|
+
* ```typescript
|
|
3934
|
+
* // Wrap multiple tools for use with OpenAI
|
|
3935
|
+
* const composioTools = [
|
|
3936
|
+
* {
|
|
3937
|
+
* slug: 'SEARCH_TOOL',
|
|
3938
|
+
* description: 'Search for information',
|
|
3939
|
+
* inputParameters: {
|
|
3940
|
+
* type: 'object',
|
|
3941
|
+
* properties: {
|
|
3942
|
+
* query: { type: 'string' }
|
|
3943
|
+
* }
|
|
3944
|
+
* }
|
|
3945
|
+
* },
|
|
3946
|
+
* {
|
|
3947
|
+
* slug: 'WEATHER_TOOL',
|
|
3948
|
+
* description: 'Get weather information',
|
|
3949
|
+
* inputParameters: {
|
|
3950
|
+
* type: 'object',
|
|
3951
|
+
* properties: {
|
|
3952
|
+
* location: { type: 'string' }
|
|
3953
|
+
* }
|
|
3954
|
+
* }
|
|
3955
|
+
* }
|
|
3956
|
+
* ];
|
|
3957
|
+
*
|
|
3958
|
+
* const openAITools = provider.wrapTools(composioTools);
|
|
3959
|
+
* ```
|
|
3960
|
+
*/
|
|
2719
3961
|
wrapTools = (tools) => {
|
|
2720
3962
|
return tools.map((tool) => this.wrapTool(tool));
|
|
2721
3963
|
};
|
|
2722
3964
|
/**
|
|
2723
|
-
*
|
|
2724
|
-
*
|
|
2725
|
-
*
|
|
2726
|
-
*
|
|
3965
|
+
* Executes a tool call from OpenAI's chat completion.
|
|
3966
|
+
*
|
|
3967
|
+
* This method processes a tool call from OpenAI's chat completion API,
|
|
3968
|
+
* executes the corresponding Composio tool, and returns the result.
|
|
3969
|
+
*
|
|
3970
|
+
* @param {string} userId - The user ID for authentication and tracking
|
|
3971
|
+
* @param {OpenAI.ChatCompletionMessageToolCall} tool - The tool call from OpenAI
|
|
3972
|
+
* @param {ExecuteToolFnOptions} [options] - Optional execution options
|
|
3973
|
+
* @param {ExecuteToolModifiers} [modifiers] - Optional execution modifiers
|
|
3974
|
+
* @returns {Promise<string>} The result of the tool call as a JSON string
|
|
3975
|
+
*
|
|
3976
|
+
* @example
|
|
3977
|
+
* ```typescript
|
|
3978
|
+
* // Execute a tool call from OpenAI
|
|
3979
|
+
* const toolCall = {
|
|
3980
|
+
* id: 'call_abc123',
|
|
3981
|
+
* type: 'function',
|
|
3982
|
+
* function: {
|
|
3983
|
+
* name: 'SEARCH_TOOL',
|
|
3984
|
+
* arguments: '{"query":"composio documentation"}'
|
|
3985
|
+
* }
|
|
3986
|
+
* };
|
|
3987
|
+
*
|
|
3988
|
+
* const result = await provider.executeToolCall(
|
|
3989
|
+
* 'user123',
|
|
3990
|
+
* toolCall,
|
|
3991
|
+
* { connectedAccountId: 'conn_xyz456' }
|
|
3992
|
+
* );
|
|
3993
|
+
* console.log(JSON.parse(result));
|
|
3994
|
+
* ```
|
|
2727
3995
|
*/
|
|
2728
3996
|
async executeToolCall(userId, tool, options, modifiers) {
|
|
2729
3997
|
const payload = {
|
|
@@ -2736,13 +4004,48 @@ var OpenAIProvider = class extends BaseNonAgenticProvider {
|
|
|
2736
4004
|
return JSON.stringify(result);
|
|
2737
4005
|
}
|
|
2738
4006
|
/**
|
|
2739
|
-
*
|
|
4007
|
+
* Handles tool calls from OpenAI's chat completion response.
|
|
2740
4008
|
*
|
|
2741
|
-
*
|
|
2742
|
-
*
|
|
2743
|
-
*
|
|
4009
|
+
* This method processes tool calls from an OpenAI chat completion response,
|
|
4010
|
+
* executes each tool call, and returns the results.
|
|
4011
|
+
*
|
|
4012
|
+
* @param {string} userId - The user ID for authentication and tracking
|
|
4013
|
+
* @param {OpenAI.ChatCompletion} chatCompletion - The chat completion response from OpenAI
|
|
4014
|
+
* @param {ExecuteToolFnOptions} [options] - Optional execution options
|
|
4015
|
+
* @param {ExecuteToolModifiers} [modifiers] - Optional execution modifiers
|
|
4016
|
+
* @returns {Promise<string[]>} Array of tool execution results as JSON strings
|
|
4017
|
+
*
|
|
4018
|
+
* @example
|
|
4019
|
+
* ```typescript
|
|
4020
|
+
* // Handle tool calls from a chat completion response
|
|
4021
|
+
* const chatCompletion = {
|
|
4022
|
+
* choices: [
|
|
4023
|
+
* {
|
|
4024
|
+
* message: {
|
|
4025
|
+
* tool_calls: [
|
|
4026
|
+
* {
|
|
4027
|
+
* id: 'call_abc123',
|
|
4028
|
+
* type: 'function',
|
|
4029
|
+
* function: {
|
|
4030
|
+
* name: 'SEARCH_TOOL',
|
|
4031
|
+
* arguments: '{"query":"composio documentation"}'
|
|
4032
|
+
* }
|
|
4033
|
+
* }
|
|
4034
|
+
* ]
|
|
4035
|
+
* }
|
|
4036
|
+
* }
|
|
4037
|
+
* ]
|
|
4038
|
+
* };
|
|
4039
|
+
*
|
|
4040
|
+
* const results = await provider.handleToolCalls(
|
|
4041
|
+
* 'user123',
|
|
4042
|
+
* chatCompletion,
|
|
4043
|
+
* { connectedAccountId: 'conn_xyz456' }
|
|
4044
|
+
* );
|
|
4045
|
+
* console.log(results); // Array of tool execution results
|
|
4046
|
+
* ```
|
|
2744
4047
|
*/
|
|
2745
|
-
async
|
|
4048
|
+
async handleToolCalls(userId, chatCompletion, options, modifiers) {
|
|
2746
4049
|
const outputs = [];
|
|
2747
4050
|
for (const message of chatCompletion.choices) {
|
|
2748
4051
|
if (message.message.tool_calls) {
|
|
@@ -2754,11 +4057,51 @@ var OpenAIProvider = class extends BaseNonAgenticProvider {
|
|
|
2754
4057
|
return outputs;
|
|
2755
4058
|
}
|
|
2756
4059
|
/**
|
|
2757
|
-
* Handles all the tool calls from the
|
|
4060
|
+
* Handles all the tool calls from the OpenAI Assistant API.
|
|
2758
4061
|
*
|
|
2759
|
-
*
|
|
2760
|
-
*
|
|
2761
|
-
*
|
|
4062
|
+
* This method processes tool calls from an OpenAI Assistant run,
|
|
4063
|
+
* executes each tool call, and returns the tool outputs for submission.
|
|
4064
|
+
*
|
|
4065
|
+
* @param {string} userId - The user ID for authentication and tracking
|
|
4066
|
+
* @param {OpenAI.Beta.Threads.Run} run - The Assistant run object containing tool calls
|
|
4067
|
+
* @param {ExecuteToolFnOptions} [options] - Optional execution options
|
|
4068
|
+
* @param {ExecuteToolModifiers} [modifiers] - Optional execution modifiers
|
|
4069
|
+
* @returns {Promise<OpenAI.Beta.Threads.Runs.RunSubmitToolOutputsParams.ToolOutput[]>} Array of tool outputs for submission
|
|
4070
|
+
*
|
|
4071
|
+
* @example
|
|
4072
|
+
* ```typescript
|
|
4073
|
+
* // Handle tool calls from an OpenAI Assistant run
|
|
4074
|
+
* const run = {
|
|
4075
|
+
* id: 'run_abc123',
|
|
4076
|
+
* required_action: {
|
|
4077
|
+
* submit_tool_outputs: {
|
|
4078
|
+
* tool_calls: [
|
|
4079
|
+
* {
|
|
4080
|
+
* id: 'call_xyz789',
|
|
4081
|
+
* type: 'function',
|
|
4082
|
+
* function: {
|
|
4083
|
+
* name: 'SEARCH_TOOL',
|
|
4084
|
+
* arguments: '{"query":"composio documentation"}'
|
|
4085
|
+
* }
|
|
4086
|
+
* }
|
|
4087
|
+
* ]
|
|
4088
|
+
* }
|
|
4089
|
+
* }
|
|
4090
|
+
* };
|
|
4091
|
+
*
|
|
4092
|
+
* const toolOutputs = await provider.handleAssistantMessage(
|
|
4093
|
+
* 'user123',
|
|
4094
|
+
* run,
|
|
4095
|
+
* { connectedAccountId: 'conn_xyz456' }
|
|
4096
|
+
* );
|
|
4097
|
+
*
|
|
4098
|
+
* // Submit tool outputs back to OpenAI
|
|
4099
|
+
* await openai.beta.threads.runs.submitToolOutputs(
|
|
4100
|
+
* thread.id,
|
|
4101
|
+
* run.id,
|
|
4102
|
+
* { tool_outputs: toolOutputs }
|
|
4103
|
+
* );
|
|
4104
|
+
* ```
|
|
2762
4105
|
*/
|
|
2763
4106
|
async handleAssistantMessage(userId, run, options, modifiers) {
|
|
2764
4107
|
const tool_calls = run.required_action?.submit_tool_outputs?.tool_calls || [];
|
|
@@ -2783,11 +4126,43 @@ var OpenAIProvider = class extends BaseNonAgenticProvider {
|
|
|
2783
4126
|
/**
|
|
2784
4127
|
* Waits for the assistant stream and handles the tool calls.
|
|
2785
4128
|
*
|
|
2786
|
-
*
|
|
2787
|
-
*
|
|
2788
|
-
*
|
|
2789
|
-
*
|
|
2790
|
-
* @
|
|
4129
|
+
* This method processes an OpenAI Assistant stream, handles any tool calls
|
|
4130
|
+
* that require action, and yields each event from the stream. It's designed
|
|
4131
|
+
* for streaming Assistant responses while handling tool calls in real-time.
|
|
4132
|
+
*
|
|
4133
|
+
* @param {string} userId - The user ID for authentication and tracking
|
|
4134
|
+
* @param {OpenAI} client - The OpenAI client instance
|
|
4135
|
+
* @param {Stream<OpenAI.Beta.Assistants.AssistantStreamEvent>} runStream - The Assistant run stream
|
|
4136
|
+
* @param {OpenAI.Beta.Threads.Thread} thread - The thread object
|
|
4137
|
+
* @param {ExecuteToolFnOptions} [options] - Optional execution options
|
|
4138
|
+
* @param {ExecuteToolModifiers} [modifiers] - Optional execution modifiers
|
|
4139
|
+
* @returns {AsyncGenerator<OpenAI.Beta.Assistants.AssistantStreamEvent, void, unknown>} Generator yielding stream events
|
|
4140
|
+
*
|
|
4141
|
+
* @example
|
|
4142
|
+
* ```typescript
|
|
4143
|
+
* // Process an OpenAI Assistant stream with tool calls
|
|
4144
|
+
* const thread = await openai.beta.threads.create();
|
|
4145
|
+
* const runStream = openai.beta.threads.runs.stream(thread.id, {
|
|
4146
|
+
* assistant_id: 'asst_abc123',
|
|
4147
|
+
* tools: provider.wrapTools(composioTools)
|
|
4148
|
+
* });
|
|
4149
|
+
*
|
|
4150
|
+
* // Process the stream and handle tool calls
|
|
4151
|
+
* const streamProcessor = provider.waitAndHandleAssistantStreamToolCalls(
|
|
4152
|
+
* 'user123',
|
|
4153
|
+
* openai,
|
|
4154
|
+
* runStream,
|
|
4155
|
+
* thread,
|
|
4156
|
+
* { connectedAccountId: 'conn_xyz456' }
|
|
4157
|
+
* );
|
|
4158
|
+
*
|
|
4159
|
+
* // Consume the stream events
|
|
4160
|
+
* for await (const event of streamProcessor) {
|
|
4161
|
+
* if (event.event === 'thread.message.delta') {
|
|
4162
|
+
* console.log(event.data.delta.content);
|
|
4163
|
+
* }
|
|
4164
|
+
* }
|
|
4165
|
+
* ```
|
|
2791
4166
|
*/
|
|
2792
4167
|
async *waitAndHandleAssistantStreamToolCalls(userId, client, runStream, thread, options, modifiers) {
|
|
2793
4168
|
let runId = null;
|
|
@@ -2839,11 +4214,45 @@ var OpenAIProvider = class extends BaseNonAgenticProvider {
|
|
|
2839
4214
|
/**
|
|
2840
4215
|
* Waits for the assistant tool calls and handles them.
|
|
2841
4216
|
*
|
|
2842
|
-
*
|
|
2843
|
-
*
|
|
2844
|
-
*
|
|
2845
|
-
*
|
|
2846
|
-
* @
|
|
4217
|
+
* This method polls an OpenAI Assistant run until it completes or requires action,
|
|
4218
|
+
* handles any tool calls, and returns the final run object. It's designed for
|
|
4219
|
+
* non-streaming Assistant interactions.
|
|
4220
|
+
*
|
|
4221
|
+
* @param {string} userId - The user ID for authentication and tracking
|
|
4222
|
+
* @param {OpenAI} client - The OpenAI client instance
|
|
4223
|
+
* @param {OpenAI.Beta.Threads.Run} run - The initial run object
|
|
4224
|
+
* @param {OpenAI.Beta.Threads.Thread} thread - The thread object
|
|
4225
|
+
* @param {ExecuteToolFnOptions} [options] - Optional execution options
|
|
4226
|
+
* @param {ExecuteToolModifiers} [modifiers] - Optional execution modifiers
|
|
4227
|
+
* @returns {Promise<OpenAI.Beta.Threads.Run>} The final run object after completion
|
|
4228
|
+
*
|
|
4229
|
+
* @example
|
|
4230
|
+
* ```typescript
|
|
4231
|
+
* // Process an OpenAI Assistant run with tool calls
|
|
4232
|
+
* const thread = await openai.beta.threads.create();
|
|
4233
|
+
* await openai.beta.threads.messages.create(thread.id, {
|
|
4234
|
+
* role: 'user',
|
|
4235
|
+
* content: 'Find information about Composio'
|
|
4236
|
+
* });
|
|
4237
|
+
*
|
|
4238
|
+
* let run = await openai.beta.threads.runs.create(thread.id, {
|
|
4239
|
+
* assistant_id: 'asst_abc123',
|
|
4240
|
+
* tools: provider.wrapTools(composioTools)
|
|
4241
|
+
* });
|
|
4242
|
+
*
|
|
4243
|
+
* // Wait for the run to complete, handling any tool calls
|
|
4244
|
+
* run = await provider.waitAndHandleAssistantToolCalls(
|
|
4245
|
+
* 'user123',
|
|
4246
|
+
* openai,
|
|
4247
|
+
* run,
|
|
4248
|
+
* thread,
|
|
4249
|
+
* { connectedAccountId: 'conn_xyz456' }
|
|
4250
|
+
* );
|
|
4251
|
+
*
|
|
4252
|
+
* // Get the final messages after run completion
|
|
4253
|
+
* const messages = await openai.beta.threads.messages.list(thread.id);
|
|
4254
|
+
* console.log(messages.data[0].content);
|
|
4255
|
+
* ```
|
|
2847
4256
|
*/
|
|
2848
4257
|
async waitAndHandleAssistantToolCalls(userId, client, run, thread, options, modifiers) {
|
|
2849
4258
|
while (["queued", "in_progress", "requires_action"].includes(run.status)) {
|
|
@@ -2862,13 +4271,7 @@ var OpenAIProvider = class extends BaseNonAgenticProvider {
|
|
|
2862
4271
|
};
|
|
2863
4272
|
|
|
2864
4273
|
// package.json
|
|
2865
|
-
var version = "0.1.12
|
|
2866
|
-
|
|
2867
|
-
// src/utils/uuid.ts
|
|
2868
|
-
import { v4 as uuidv4 } from "uuid";
|
|
2869
|
-
function getRandomUUID() {
|
|
2870
|
-
return uuidv4();
|
|
2871
|
-
}
|
|
4274
|
+
var version = "0.1.12";
|
|
2872
4275
|
|
|
2873
4276
|
// src/composio.ts
|
|
2874
4277
|
var Composio = class {
|
|
@@ -2882,7 +4285,6 @@ var Composio = class {
|
|
|
2882
4285
|
* @type {ComposioConfig<TProvider>}
|
|
2883
4286
|
*/
|
|
2884
4287
|
config;
|
|
2885
|
-
telemetry;
|
|
2886
4288
|
/**
|
|
2887
4289
|
* Core models for Composio.
|
|
2888
4290
|
*/
|
|
@@ -2895,13 +4297,36 @@ var Composio = class {
|
|
|
2895
4297
|
// connected accounts
|
|
2896
4298
|
connectedAccounts;
|
|
2897
4299
|
/**
|
|
2898
|
-
*
|
|
2899
|
-
*
|
|
2900
|
-
*
|
|
2901
|
-
*
|
|
2902
|
-
*
|
|
2903
|
-
* @param {
|
|
2904
|
-
* @param {
|
|
4300
|
+
* Creates a new instance of the Composio SDK.
|
|
4301
|
+
*
|
|
4302
|
+
* The constructor initializes the SDK with the provided configuration options,
|
|
4303
|
+
* sets up the API client, and initializes all core models (tools, toolkits, etc.).
|
|
4304
|
+
*
|
|
4305
|
+
* @param {ComposioConfig<TProvider>} config - Configuration options for the Composio SDK
|
|
4306
|
+
* @param {string} [config.apiKey] - The API key for authenticating with the Composio API
|
|
4307
|
+
* @param {string} [config.baseURL] - The base URL for the Composio API (defaults to production URL)
|
|
4308
|
+
* @param {boolean} [config.allowTracking=true] - Whether to allow anonymous usage analytics
|
|
4309
|
+
* @param {boolean} [config.allowTracing=true] - Whether to allow request tracing for debugging
|
|
4310
|
+
* @param {TProvider} [config.provider] - The provider to use for this Composio instance (defaults to OpenAIProvider)
|
|
4311
|
+
* @param {BaseTelemetryTransport} [config.telemetryTransport] - Custom telemetry transport implementation
|
|
4312
|
+
*
|
|
4313
|
+
* @example
|
|
4314
|
+
* ```typescript
|
|
4315
|
+
* // Initialize with default configuration
|
|
4316
|
+
* const composio = new Composio();
|
|
4317
|
+
*
|
|
4318
|
+
* // Initialize with custom API key and base URL
|
|
4319
|
+
* const composio = new Composio({
|
|
4320
|
+
* apiKey: 'your-api-key',
|
|
4321
|
+
* baseURL: 'https://api.composio.dev'
|
|
4322
|
+
* });
|
|
4323
|
+
*
|
|
4324
|
+
* // Initialize with custom provider
|
|
4325
|
+
* const composio = new Composio({
|
|
4326
|
+
* apiKey: 'your-api-key',
|
|
4327
|
+
* provider: new CustomProvider()
|
|
4328
|
+
* });
|
|
4329
|
+
* ```
|
|
2905
4330
|
*/
|
|
2906
4331
|
constructor(config) {
|
|
2907
4332
|
const { baseURL: baseURLParsed, apiKey: apiKeyParsed } = getSDKConfig(
|
|
@@ -2909,55 +4334,46 @@ var Composio = class {
|
|
|
2909
4334
|
config?.apiKey
|
|
2910
4335
|
);
|
|
2911
4336
|
if (IS_DEVELOPMENT_OR_CI) {
|
|
2912
|
-
logger_default.
|
|
4337
|
+
logger_default.debug(`Initializing Composio w API Key: [REDACTED] and baseURL: ${baseURLParsed}`);
|
|
2913
4338
|
}
|
|
2914
|
-
this.client = new
|
|
4339
|
+
this.client = new ComposioClient3({
|
|
2915
4340
|
apiKey: apiKeyParsed,
|
|
2916
4341
|
baseURL: baseURLParsed
|
|
2917
4342
|
});
|
|
2918
4343
|
this.config = {
|
|
2919
4344
|
...config,
|
|
2920
|
-
allowTracking: config
|
|
4345
|
+
allowTracking: config?.allowTracking ?? true,
|
|
4346
|
+
allowTracing: config?.allowTracing ?? true
|
|
2921
4347
|
};
|
|
2922
|
-
this.provider = config
|
|
4348
|
+
this.provider = config?.provider ?? new OpenAIProvider();
|
|
2923
4349
|
this.tools = new Tools(this.client, this.provider);
|
|
2924
4350
|
this.toolkits = new Toolkits(this.client);
|
|
2925
4351
|
this.triggers = new Triggers(this.client);
|
|
2926
4352
|
this.authConfigs = new AuthConfigs(this.client);
|
|
2927
4353
|
this.connectedAccounts = new ConnectedAccounts(this.client);
|
|
2928
|
-
if (this.config.allowTracking
|
|
2929
|
-
|
|
4354
|
+
if (this.config.allowTracking) {
|
|
4355
|
+
telemetry.setup(
|
|
2930
4356
|
{
|
|
2931
4357
|
apiKey: apiKeyParsed ?? "",
|
|
2932
4358
|
baseUrl: baseURLParsed ?? "",
|
|
2933
|
-
frameworkRuntime: "
|
|
2934
|
-
|
|
2935
|
-
|
|
2936
|
-
|
|
4359
|
+
frameworkRuntime: this.provider?.name ?? "unknown",
|
|
4360
|
+
isAgentic: this.provider?._isAgentic || false,
|
|
4361
|
+
source: "javascript",
|
|
4362
|
+
version,
|
|
4363
|
+
sdkType: "Typescript-V3",
|
|
2937
4364
|
isBrowser: typeof window !== "undefined",
|
|
2938
|
-
|
|
4365
|
+
// @TODO: Users might want to pass their own session id
|
|
4366
|
+
// @TODO: We shouldn't be doing this as people might always have one session id throughout the process in server
|
|
4367
|
+
sessionId: this.config.allowTracing ? getRandomUUID() : void 0
|
|
2939
4368
|
// @TODO: get the session id
|
|
2940
4369
|
},
|
|
2941
|
-
config
|
|
4370
|
+
config?.telemetryTransport
|
|
2942
4371
|
);
|
|
2943
4372
|
}
|
|
4373
|
+
telemetry.instrument(this);
|
|
4374
|
+
telemetry.instrument(this.provider);
|
|
2944
4375
|
checkForLatestVersionFromNPM(version);
|
|
2945
4376
|
}
|
|
2946
|
-
/**
|
|
2947
|
-
* Initialize the instrumentations and telemetry for the Composio SDK.
|
|
2948
|
-
* @param {TelemetryMetadata} config - The configuration for the telemetry.
|
|
2949
|
-
* @param {BaseTelemetryTransport} transport - The transport for the telemetry.
|
|
2950
|
-
*/
|
|
2951
|
-
initializeTelemetry(config, transport) {
|
|
2952
|
-
this.telemetry = new Telemetry(config, transport);
|
|
2953
|
-
this.telemetry.instrumentTelemetry(this);
|
|
2954
|
-
this.telemetry.instrumentTelemetry(this.tools);
|
|
2955
|
-
this.telemetry.instrumentTelemetry(this.toolkits);
|
|
2956
|
-
this.telemetry.instrumentTelemetry(this.triggers);
|
|
2957
|
-
this.telemetry.instrumentTelemetry(this.authConfigs);
|
|
2958
|
-
this.telemetry.instrumentTelemetry(this.connectedAccounts);
|
|
2959
|
-
this.telemetry.instrumentTelemetry(this.provider);
|
|
2960
|
-
}
|
|
2961
4377
|
/**
|
|
2962
4378
|
* Get the Composio SDK client.
|
|
2963
4379
|
* @returns {ComposioClient} The Composio API client.
|
|
@@ -2982,43 +4398,50 @@ var ComposioProvider = class extends BaseNonAgenticProvider {
|
|
|
2982
4398
|
};
|
|
2983
4399
|
|
|
2984
4400
|
// src/telemetry/TelemetryTransport.ts
|
|
4401
|
+
import chalk4 from "chalk";
|
|
2985
4402
|
var BaseTelemetryTransport = class {
|
|
2986
4403
|
};
|
|
4404
|
+
var ConsoleTelemetryTransport = class {
|
|
4405
|
+
send(payload) {
|
|
4406
|
+
logger_default.debug(chalk4.yellow("telemetry"), JSON.stringify(payload, null, 2));
|
|
4407
|
+
return Promise.resolve();
|
|
4408
|
+
}
|
|
4409
|
+
};
|
|
2987
4410
|
|
|
2988
4411
|
// src/utils/jsonSchema.ts
|
|
2989
|
-
import { z as
|
|
4412
|
+
import { z as z7 } from "zod";
|
|
2990
4413
|
function jsonSchemaPropertiesToTSTypes(value) {
|
|
2991
4414
|
if (!value.type) {
|
|
2992
|
-
return
|
|
4415
|
+
return z7.object({});
|
|
2993
4416
|
}
|
|
2994
4417
|
let zodType;
|
|
2995
4418
|
switch (value.type) {
|
|
2996
4419
|
case "string":
|
|
2997
|
-
zodType =
|
|
4420
|
+
zodType = z7.string().describe(
|
|
2998
4421
|
(value.description || "") + (value.examples ? `
|
|
2999
4422
|
Examples: ${value.examples.join(", ")}` : "")
|
|
3000
4423
|
);
|
|
3001
4424
|
break;
|
|
3002
4425
|
case "number":
|
|
3003
|
-
zodType =
|
|
4426
|
+
zodType = z7.number().describe(
|
|
3004
4427
|
(value.description || "") + (value.examples ? `
|
|
3005
4428
|
Examples: ${value.examples.join(", ")}` : "")
|
|
3006
4429
|
);
|
|
3007
4430
|
break;
|
|
3008
4431
|
case "integer":
|
|
3009
|
-
zodType =
|
|
4432
|
+
zodType = z7.number().int().describe(
|
|
3010
4433
|
(value.description || "") + (value.examples ? `
|
|
3011
4434
|
Examples: ${value.examples.join(", ")}` : "")
|
|
3012
4435
|
);
|
|
3013
4436
|
break;
|
|
3014
4437
|
case "boolean":
|
|
3015
|
-
zodType =
|
|
4438
|
+
zodType = z7.boolean().describe(
|
|
3016
4439
|
(value.description || "") + (value.examples ? `
|
|
3017
4440
|
Examples: ${value.examples.join(", ")}` : "")
|
|
3018
4441
|
);
|
|
3019
4442
|
break;
|
|
3020
4443
|
case "array":
|
|
3021
|
-
zodType =
|
|
4444
|
+
zodType = z7.array(
|
|
3022
4445
|
jsonSchemaPropertiesToTSTypes(
|
|
3023
4446
|
value.items
|
|
3024
4447
|
)
|
|
@@ -3028,24 +4451,24 @@ Examples: ${value.examples.join(", ")}` : "")
|
|
|
3028
4451
|
);
|
|
3029
4452
|
break;
|
|
3030
4453
|
case "object":
|
|
3031
|
-
zodType =
|
|
4454
|
+
zodType = jsonSchemaToZodSchema(value).describe(
|
|
3032
4455
|
(value.description || "") + (value.examples ? `
|
|
3033
4456
|
Examples: ${value.examples.join(", ")}` : "")
|
|
3034
4457
|
);
|
|
3035
4458
|
break;
|
|
3036
4459
|
case "null":
|
|
3037
|
-
zodType =
|
|
4460
|
+
zodType = z7.null().describe(value.description || "");
|
|
3038
4461
|
break;
|
|
3039
4462
|
default:
|
|
3040
4463
|
throw new Error(`Unsupported JSON schema type: ${value.type}`);
|
|
3041
4464
|
}
|
|
3042
4465
|
return zodType;
|
|
3043
4466
|
}
|
|
3044
|
-
function
|
|
4467
|
+
function jsonSchemaToZodSchema(jsonSchema) {
|
|
3045
4468
|
const properties = jsonSchema.properties;
|
|
3046
4469
|
const requiredFields = jsonSchema.required || [];
|
|
3047
4470
|
if (!properties) {
|
|
3048
|
-
return
|
|
4471
|
+
return z7.object({});
|
|
3049
4472
|
}
|
|
3050
4473
|
const zodSchema = {};
|
|
3051
4474
|
for (const [key, _] of Object.entries(properties)) {
|
|
@@ -3057,7 +4480,7 @@ function jsonSchemaToModel(jsonSchema) {
|
|
|
3057
4480
|
schema
|
|
3058
4481
|
)
|
|
3059
4482
|
);
|
|
3060
|
-
zodType =
|
|
4483
|
+
zodType = z7.union(anyOfTypes).describe(
|
|
3061
4484
|
(value.description || "") + (value.examples ? `
|
|
3062
4485
|
Examples: ${value.examples.join(", ")}` : "")
|
|
3063
4486
|
);
|
|
@@ -3067,7 +4490,7 @@ Examples: ${value.examples.join(", ")}` : "")
|
|
|
3067
4490
|
schema
|
|
3068
4491
|
)
|
|
3069
4492
|
);
|
|
3070
|
-
zodType =
|
|
4493
|
+
zodType = z7.intersection(
|
|
3071
4494
|
allOfTypes[0],
|
|
3072
4495
|
allOfTypes.slice(1).reduce((acc, schema) => acc.and(schema), allOfTypes[0])
|
|
3073
4496
|
).describe(
|
|
@@ -3091,17 +4514,42 @@ Examples: ${value.examples.join(", ")}` : "")
|
|
|
3091
4514
|
zodSchema[key] = zodType.optional();
|
|
3092
4515
|
}
|
|
3093
4516
|
}
|
|
3094
|
-
return
|
|
4517
|
+
return z7.object(zodSchema);
|
|
3095
4518
|
}
|
|
3096
4519
|
export {
|
|
4520
|
+
AuthConfigErrorCodes,
|
|
3097
4521
|
AuthConfigTypes,
|
|
3098
4522
|
AuthSchemeTypes,
|
|
3099
4523
|
BaseAgenticProvider,
|
|
3100
4524
|
BaseNonAgenticProvider,
|
|
3101
4525
|
BaseTelemetryTransport,
|
|
3102
4526
|
Composio,
|
|
4527
|
+
ComposioAuthConfigNotFoundError,
|
|
4528
|
+
ComposioConnectedAccountNotFoundError,
|
|
4529
|
+
ComposioCustomToolsNotInitializedError,
|
|
4530
|
+
ComposioError,
|
|
4531
|
+
ComposioGlobalExecuteToolFnNotSetError,
|
|
4532
|
+
ComposioInvalidExecuteFunctionError,
|
|
4533
|
+
ComposioInvalidModifierError,
|
|
4534
|
+
ComposioNoAPIKeyError,
|
|
3103
4535
|
ComposioProvider,
|
|
4536
|
+
ComposioProviderNotDefinedError,
|
|
4537
|
+
ComposioToolExecutionError,
|
|
4538
|
+
ComposioToolNotFoundError,
|
|
4539
|
+
ComposioToolkitFetchError,
|
|
4540
|
+
ComposioToolkitNotFoundError,
|
|
4541
|
+
ConnectedAccountErrorCodes,
|
|
4542
|
+
ConnectionRequestErrorCodes,
|
|
4543
|
+
ConnectionRequestFailedError,
|
|
4544
|
+
ConnectionRequestTimeoutError,
|
|
4545
|
+
ConsoleTelemetryTransport,
|
|
3104
4546
|
OpenAIProvider,
|
|
4547
|
+
SDKErrorCodes,
|
|
4548
|
+
ToolErrorCodes,
|
|
3105
4549
|
ToolListParamsSchema,
|
|
3106
|
-
|
|
4550
|
+
ToolkitErrorCodes,
|
|
4551
|
+
ValidationError,
|
|
4552
|
+
ValidationErrorCodes,
|
|
4553
|
+
jsonSchemaToZodSchema,
|
|
4554
|
+
logger_default as logger
|
|
3107
4555
|
};
|