@composio/core 0.1.0-rc.5 → 0.1.3-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1174 -464
- package/dist/index.d.cts +1304 -150
- package/dist/index.d.ts +1304 -150
- package/dist/index.js +1171 -463
- package/package.json +9 -4
package/dist/index.js
CHANGED
|
@@ -8,105 +8,197 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
|
|
|
8
8
|
// src/composio.ts
|
|
9
9
|
import ComposioClient from "@composio/client";
|
|
10
10
|
|
|
11
|
-
// src/
|
|
12
|
-
|
|
13
|
-
|
|
11
|
+
// src/types/tool.types.ts
|
|
12
|
+
import { z } from "zod";
|
|
13
|
+
var ToolkitSchema = z.object({
|
|
14
|
+
slug: z.string().describe("The slug of the toolkit"),
|
|
15
|
+
name: z.string().describe("The name of the toolkit"),
|
|
16
|
+
logo: z.string().describe("The logo of the toolkit").optional()
|
|
17
|
+
});
|
|
18
|
+
var ToolSchema = z.object({
|
|
19
|
+
slug: z.string().describe('The slug of the tool. eg. "GOOGLE_SEARCH"'),
|
|
20
|
+
name: z.string().describe(`The name of the tool. eg. "Google Search"`),
|
|
21
|
+
description: z.string().optional().describe("The description of the tool"),
|
|
22
|
+
inputParameters: z.record(z.string(), z.unknown()).optional().describe("The input parameters of the tool"),
|
|
23
|
+
outputParameters: z.record(z.string(), z.unknown()).optional().describe("The output parameters of the tool"),
|
|
24
|
+
tags: z.optional(z.array(z.string())).describe("The tags of the tool. eg: Important").default([]),
|
|
25
|
+
toolkit: z.optional(ToolkitSchema).describe("The toolkit of the tool"),
|
|
26
|
+
version: z.optional(z.string()).describe('The version of the tool, e.g. "1.0.0"')
|
|
27
|
+
});
|
|
28
|
+
var ToolListResponseSchema = z.object({
|
|
29
|
+
items: z.array(ToolSchema),
|
|
30
|
+
nextCursor: z.string().nullable().optional(),
|
|
31
|
+
totalPages: z.number()
|
|
32
|
+
});
|
|
33
|
+
var ToolListParamsSchema = z.object({
|
|
34
|
+
cursor: z.string().optional(),
|
|
35
|
+
important: z.string().optional(),
|
|
36
|
+
limit: z.string().optional(),
|
|
37
|
+
search: z.string().optional(),
|
|
38
|
+
toolkits: z.string().optional(),
|
|
39
|
+
tools: z.array(z.string()).optional()
|
|
40
|
+
});
|
|
41
|
+
var CustomAuthParamsSchema = z.object({
|
|
42
|
+
baseURL: z.string().optional(),
|
|
43
|
+
body: z.record(z.string(), z.unknown()).optional(),
|
|
44
|
+
parameters: z.array(
|
|
45
|
+
z.object({
|
|
46
|
+
in: z.enum(["query", "header"]),
|
|
47
|
+
name: z.string(),
|
|
48
|
+
value: z.union([z.string(), z.number()])
|
|
49
|
+
})
|
|
50
|
+
)
|
|
51
|
+
});
|
|
52
|
+
var ToolExecuteParamsSchema = z.object({
|
|
53
|
+
allowTracing: z.boolean().optional(),
|
|
54
|
+
connectedAccountId: z.string().optional(),
|
|
55
|
+
customAuthParams: CustomAuthParamsSchema.optional(),
|
|
56
|
+
arguments: z.record(z.string(), z.unknown()).optional(),
|
|
57
|
+
userId: z.string(),
|
|
58
|
+
version: z.string().optional(),
|
|
59
|
+
text: z.string().optional()
|
|
60
|
+
});
|
|
61
|
+
var ToolExecuteResponseSchema = z.object({
|
|
62
|
+
data: z.record(z.string(), z.unknown()),
|
|
63
|
+
error: z.string().nullable(),
|
|
64
|
+
successful: z.boolean(),
|
|
65
|
+
logId: z.string().optional(),
|
|
66
|
+
sessionInfo: z.unknown().optional()
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
// src/models/CustomTools.ts
|
|
70
|
+
import zodToJsonSchema from "zod-to-json-schema";
|
|
71
|
+
var CustomTools = class {
|
|
14
72
|
client;
|
|
73
|
+
customToolsRegistry = /* @__PURE__ */ new Map();
|
|
15
74
|
constructor(client) {
|
|
16
75
|
this.client = client;
|
|
17
76
|
}
|
|
18
77
|
/**
|
|
19
|
-
*
|
|
20
|
-
* This
|
|
21
|
-
* @
|
|
78
|
+
* Create a custom tool and registers it in the registry.
|
|
79
|
+
* This is just an in memory registry and is not persisted.
|
|
80
|
+
* @param {CustomToolOptions} toolOptions CustomToolOptions
|
|
81
|
+
* @returns {Tool} The tool created
|
|
22
82
|
*/
|
|
23
|
-
async
|
|
24
|
-
const
|
|
25
|
-
if (!
|
|
26
|
-
|
|
27
|
-
items: [],
|
|
28
|
-
next_cursor: null,
|
|
29
|
-
total_pages: 0
|
|
30
|
-
};
|
|
83
|
+
async createTool(toolOptions) {
|
|
84
|
+
const { slug, execute, inputParams, name, description } = toolOptions;
|
|
85
|
+
if (!slug || !execute || !inputParams || !name) {
|
|
86
|
+
throw new Error("Invalid tool options");
|
|
31
87
|
}
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
88
|
+
const paramsSchema = await zodToJsonSchema(inputParams, {
|
|
89
|
+
name: "input"
|
|
90
|
+
});
|
|
91
|
+
const paramsSchemaJson = paramsSchema.definitions.input;
|
|
92
|
+
const toolSchema = {
|
|
93
|
+
name,
|
|
94
|
+
slug,
|
|
95
|
+
description,
|
|
96
|
+
inputParameters: {
|
|
97
|
+
title: name,
|
|
98
|
+
type: "object",
|
|
99
|
+
description,
|
|
100
|
+
properties: paramsSchemaJson.properties,
|
|
101
|
+
required: paramsSchemaJson.required
|
|
102
|
+
},
|
|
103
|
+
// the output parameters are not used yet
|
|
104
|
+
outputParameters: {
|
|
105
|
+
type: "object",
|
|
106
|
+
title: `Response for ${name}`,
|
|
107
|
+
properties: []
|
|
108
|
+
},
|
|
109
|
+
tags: [],
|
|
110
|
+
toolkit: { name: "custom", slug: "custom" }
|
|
111
|
+
};
|
|
112
|
+
this.customToolsRegistry.set(slug.toLowerCase(), {
|
|
113
|
+
options: toolOptions,
|
|
114
|
+
schema: toolSchema
|
|
115
|
+
});
|
|
116
|
+
return toolSchema;
|
|
53
117
|
}
|
|
54
118
|
/**
|
|
55
|
-
*
|
|
56
|
-
*
|
|
57
|
-
*
|
|
58
|
-
* No filtering is done on the tools, the list is cached in the backend, no further optimization is required.
|
|
59
|
-
* @returns {string} - The list of all available tools as a string
|
|
119
|
+
* Get all the custom tools from the registry.
|
|
120
|
+
* @param {string[]} param0.toolSlugs The slugs of the tools to get
|
|
121
|
+
* @returns {ToolList} The list of tools
|
|
60
122
|
*/
|
|
61
|
-
async
|
|
62
|
-
|
|
123
|
+
async getCustomTools({ toolSlugs }) {
|
|
124
|
+
const tools = [];
|
|
125
|
+
if (toolSlugs) {
|
|
126
|
+
for (const slug of toolSlugs) {
|
|
127
|
+
const tool = this.customToolsRegistry.get(slug.toLowerCase());
|
|
128
|
+
if (tool) {
|
|
129
|
+
tools.push(tool.schema);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
} else {
|
|
133
|
+
return Array.from(this.customToolsRegistry.values()).map((tool) => tool.schema);
|
|
134
|
+
}
|
|
135
|
+
return tools;
|
|
63
136
|
}
|
|
64
137
|
/**
|
|
65
|
-
*
|
|
66
|
-
*
|
|
67
|
-
*
|
|
68
|
-
*
|
|
69
|
-
* @param {string} slug - The ID of the tool to find input for
|
|
70
|
-
* @param {ToolGetInputParams} body - The parameters to be passed to the tool
|
|
71
|
-
* @returns
|
|
138
|
+
* Get a custom tool by slug from the registry.
|
|
139
|
+
* @param {string} slug The slug of the tool to get
|
|
140
|
+
* @returns {Tool} The tool
|
|
72
141
|
*/
|
|
73
|
-
async
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
var Toolkits = class {
|
|
80
|
-
FILE_NAME = "core/models/Toolkits.ts";
|
|
81
|
-
client;
|
|
82
|
-
constructor(client) {
|
|
83
|
-
this.client = client;
|
|
84
|
-
}
|
|
85
|
-
/**
|
|
86
|
-
* List all toolkits available in the Composio SDK.
|
|
87
|
-
* This method fetches the toolkits from the Composio API.
|
|
88
|
-
* @returns {Promise<Toolkit[]>} List of toolkits
|
|
89
|
-
*/
|
|
90
|
-
async list(query, options) {
|
|
91
|
-
return this.client.toolkits.list(query, options);
|
|
142
|
+
async getCustomToolBySlug(slug) {
|
|
143
|
+
const tool = this.customToolsRegistry.get(slug.toLowerCase());
|
|
144
|
+
if (!tool) {
|
|
145
|
+
return null;
|
|
146
|
+
}
|
|
147
|
+
return tool.schema;
|
|
92
148
|
}
|
|
93
149
|
/**
|
|
94
|
-
*
|
|
95
|
-
*
|
|
96
|
-
* @param
|
|
97
|
-
* @
|
|
98
|
-
* @returns {Promise<ToolkitRetrieveResponse>} The toolkit object
|
|
150
|
+
* Get the connected account for the user and toolkit.
|
|
151
|
+
* @param {string} toolkitSlug The slug of the toolkit
|
|
152
|
+
* @param {ExecuteMetadata} metadata The metadata of the execution
|
|
153
|
+
* @returns {ConnectedAccount} The connected account
|
|
99
154
|
*/
|
|
100
|
-
async
|
|
101
|
-
|
|
155
|
+
async getConnectedAccount(toolkitSlug, metadata) {
|
|
156
|
+
const connectedAccounts = await this.client.connectedAccounts.list({
|
|
157
|
+
toolkit_slug: toolkitSlug,
|
|
158
|
+
user_id: metadata.userId
|
|
159
|
+
});
|
|
160
|
+
if (!connectedAccounts.items.length) {
|
|
161
|
+
throw new Error(`No connected accounts found for toolkit ${toolkitSlug}`);
|
|
162
|
+
}
|
|
163
|
+
return metadata.connectedAccountId ? connectedAccounts.items.find((item) => item.id === metadata.connectedAccountId) : connectedAccounts.items[0];
|
|
102
164
|
}
|
|
103
165
|
/**
|
|
104
|
-
*
|
|
105
|
-
*
|
|
106
|
-
* @
|
|
166
|
+
* Execute a custom tool
|
|
167
|
+
* @param {slug} slug The slug of the tool to execute
|
|
168
|
+
* @param {Record<string, unknown>} inputParams The input parameters for the tool
|
|
169
|
+
* @param {ExecuteMetadata} metadata The metadata of the execution
|
|
170
|
+
* @returns {Promise<ToolExecuteResponse>} The response from the tool
|
|
107
171
|
*/
|
|
108
|
-
async
|
|
109
|
-
|
|
172
|
+
async executeCustomTool(slug, inputParams, metadata) {
|
|
173
|
+
const tool = this.customToolsRegistry.get(slug.toLowerCase());
|
|
174
|
+
if (!tool) {
|
|
175
|
+
throw new Error(`Tool with slug ${slug} not found`);
|
|
176
|
+
}
|
|
177
|
+
let authCredentials = {};
|
|
178
|
+
const { toolkitSlug, execute } = tool.options;
|
|
179
|
+
if (toolkitSlug) {
|
|
180
|
+
const connectedAccount = await this.getConnectedAccount(toolkitSlug, metadata);
|
|
181
|
+
if (!connectedAccount) {
|
|
182
|
+
throw new Error(
|
|
183
|
+
`Connected account not found for toolkit ${toolkitSlug} for user ${metadata.userId}`
|
|
184
|
+
);
|
|
185
|
+
}
|
|
186
|
+
authCredentials = connectedAccount.data?.connectionParams;
|
|
187
|
+
}
|
|
188
|
+
if (typeof execute !== "function") {
|
|
189
|
+
throw new Error("Invalid execute function");
|
|
190
|
+
}
|
|
191
|
+
const executeToolRequest = async (data) => {
|
|
192
|
+
return this.client.tools.proxy({
|
|
193
|
+
...data,
|
|
194
|
+
connected_account_id: metadata.connectedAccountId
|
|
195
|
+
});
|
|
196
|
+
};
|
|
197
|
+
return execute(
|
|
198
|
+
inputParams,
|
|
199
|
+
authCredentials,
|
|
200
|
+
executeToolRequest
|
|
201
|
+
);
|
|
110
202
|
}
|
|
111
203
|
};
|
|
112
204
|
|
|
@@ -181,8 +273,468 @@ var Logger = class {
|
|
|
181
273
|
}
|
|
182
274
|
}
|
|
183
275
|
};
|
|
184
|
-
var logger = new Logger();
|
|
185
|
-
var logger_default = logger;
|
|
276
|
+
var logger = new Logger();
|
|
277
|
+
var logger_default = logger;
|
|
278
|
+
|
|
279
|
+
// src/models/Tools.ts
|
|
280
|
+
var Tools = class {
|
|
281
|
+
client;
|
|
282
|
+
customTools;
|
|
283
|
+
toolset;
|
|
284
|
+
constructor(client, toolset) {
|
|
285
|
+
this.client = client;
|
|
286
|
+
this.customTools = new CustomTools(client);
|
|
287
|
+
this.toolset = toolset;
|
|
288
|
+
}
|
|
289
|
+
/**
|
|
290
|
+
* Transform the tool cases
|
|
291
|
+
* @param {ToolRetrieveResponse | ComposioToolListResponse['items'][0]} tool - The tool to transform
|
|
292
|
+
* @returns {Tool} The transformed tool
|
|
293
|
+
*/
|
|
294
|
+
transformToolCases(tool) {
|
|
295
|
+
return ToolSchema.parse({
|
|
296
|
+
...tool,
|
|
297
|
+
inputParameters: tool.input_parameters,
|
|
298
|
+
outputParameters: tool.output_parameters
|
|
299
|
+
});
|
|
300
|
+
}
|
|
301
|
+
/**
|
|
302
|
+
* Transform the tool execute response to camelcase
|
|
303
|
+
* @param {ComposioToolExecuteResponse} response - The response to transform
|
|
304
|
+
* @returns {ToolExecuteResponse} The transformed response
|
|
305
|
+
*/
|
|
306
|
+
transformToolExecuteResponse(response) {
|
|
307
|
+
return ToolExecuteResponseSchema.parse({
|
|
308
|
+
data: response.data,
|
|
309
|
+
error: response.error,
|
|
310
|
+
successful: response.successful,
|
|
311
|
+
logId: response.log_id,
|
|
312
|
+
sessionInfo: response.session_info
|
|
313
|
+
});
|
|
314
|
+
}
|
|
315
|
+
/**
|
|
316
|
+
* Check if the connected account exists for the given tools.
|
|
317
|
+
* @param {string} userId - The user id.
|
|
318
|
+
* @param {ToolList} tools - The tools to check.
|
|
319
|
+
* @returns {Promise<boolean>} True if the connected account exists for the given tools, false otherwise.
|
|
320
|
+
*/
|
|
321
|
+
async checkIfConnectedAccountExistsForTools(userId, tools) {
|
|
322
|
+
if (!tools.length) {
|
|
323
|
+
return true;
|
|
324
|
+
}
|
|
325
|
+
const connectedAccounts = await this.client.connectedAccounts.list({
|
|
326
|
+
user_id: userId
|
|
327
|
+
});
|
|
328
|
+
if (connectedAccounts.items.length === 0) {
|
|
329
|
+
return false;
|
|
330
|
+
}
|
|
331
|
+
const connectedToolkitSlugs = connectedAccounts.items.reduce(
|
|
332
|
+
(acc, account) => {
|
|
333
|
+
if (account.toolkit.slug) {
|
|
334
|
+
acc[account.toolkit.slug] = true;
|
|
335
|
+
}
|
|
336
|
+
return acc;
|
|
337
|
+
},
|
|
338
|
+
{}
|
|
339
|
+
);
|
|
340
|
+
const toolSlugs = tools.reduce(
|
|
341
|
+
(acc, tool) => {
|
|
342
|
+
acc[tool.slug] = true;
|
|
343
|
+
return acc;
|
|
344
|
+
},
|
|
345
|
+
{}
|
|
346
|
+
);
|
|
347
|
+
for (const tool of Object.keys(toolSlugs)) {
|
|
348
|
+
if (!connectedToolkitSlugs[tool]) {
|
|
349
|
+
logger_default.warn(`Tool ${tool} requires a connected account but no connected account was found`);
|
|
350
|
+
return false;
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
return true;
|
|
354
|
+
}
|
|
355
|
+
/**
|
|
356
|
+
* Get the connected account id for a given tool
|
|
357
|
+
* @param {string} userId - The user id
|
|
358
|
+
* @param {string} toolSlug - The tool slug
|
|
359
|
+
* @returns {Promise<string | null>} The connected account id or null if the toolkit is a no auth app
|
|
360
|
+
*/
|
|
361
|
+
async getConnectedAccountIdForTool(userId, toolSlug) {
|
|
362
|
+
const tool = await this.getComposioToolBySlug(userId, toolSlug);
|
|
363
|
+
if (!tool.toolkit) {
|
|
364
|
+
throw new Error(`Unable to find toolkit for tool ${toolSlug}`);
|
|
365
|
+
}
|
|
366
|
+
const toolkit = await this.client.toolkits.retrieve(tool.toolkit.slug);
|
|
367
|
+
if (!toolkit) {
|
|
368
|
+
throw new Error(`Unable to find toolkit for tool ${toolSlug}`);
|
|
369
|
+
}
|
|
370
|
+
const isNoAuthApp = toolkit.auth_config_details?.some(
|
|
371
|
+
(authConfigDetails) => authConfigDetails.mode === "NO_AUTH"
|
|
372
|
+
);
|
|
373
|
+
if (!isNoAuthApp) {
|
|
374
|
+
const connectedAccounts = await this.client.connectedAccounts.list({
|
|
375
|
+
user_id: userId,
|
|
376
|
+
toolkit_slug: tool.toolkit.slug
|
|
377
|
+
});
|
|
378
|
+
if (connectedAccounts.items.length === 0) {
|
|
379
|
+
throw new Error("No connected accounts found");
|
|
380
|
+
}
|
|
381
|
+
logger_default.warn(
|
|
382
|
+
`Using the first connected account for tool ${toolSlug}. To change this behaviour please explicitly pass a connectedAccountId for the tool`
|
|
383
|
+
);
|
|
384
|
+
return connectedAccounts.items[0].id;
|
|
385
|
+
}
|
|
386
|
+
return null;
|
|
387
|
+
}
|
|
388
|
+
/**
|
|
389
|
+
* Lists all tools available in the Composio SDK as well as custom tools.
|
|
390
|
+
* This method fetches the tools from the Composio API and wraps them using the toolset.
|
|
391
|
+
* @returns {ToolList} List of tools
|
|
392
|
+
*/
|
|
393
|
+
async getComposioTools(userId, query = {}, modifier) {
|
|
394
|
+
const queryParams = ToolListParamsSchema.safeParse(query);
|
|
395
|
+
if (queryParams.error) {
|
|
396
|
+
throw new Error(JSON.stringify(queryParams.error.flatten()));
|
|
397
|
+
}
|
|
398
|
+
const tools = await this.client.tools.list({
|
|
399
|
+
cursor: queryParams.data.cursor,
|
|
400
|
+
important: queryParams.data.important,
|
|
401
|
+
limit: queryParams.data.limit,
|
|
402
|
+
search: queryParams.data.search,
|
|
403
|
+
toolkit_slug: queryParams.data.toolkits,
|
|
404
|
+
tool_slugs: queryParams.data.tools?.join(",")
|
|
405
|
+
});
|
|
406
|
+
if (!tools) {
|
|
407
|
+
return [];
|
|
408
|
+
}
|
|
409
|
+
const caseTransformedTools = tools.items.map((tool) => this.transformToolCases(tool));
|
|
410
|
+
const customTools = await this.customTools.getCustomTools({
|
|
411
|
+
toolSlugs: queryParams.data.tools
|
|
412
|
+
});
|
|
413
|
+
let modifiedTools = [...caseTransformedTools, ...customTools];
|
|
414
|
+
if (modifier) {
|
|
415
|
+
if (typeof modifier === "function") {
|
|
416
|
+
modifiedTools = modifiedTools.map((tool) => {
|
|
417
|
+
return modifier(tool.slug, tool);
|
|
418
|
+
});
|
|
419
|
+
} else {
|
|
420
|
+
throw new Error("Invalid schema modifier. Not a function.");
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
return modifiedTools;
|
|
424
|
+
}
|
|
425
|
+
/**
|
|
426
|
+
* Retrieves a tool by its Slug.
|
|
427
|
+
* @param slug The ID of the tool to be retrieved
|
|
428
|
+
* @returns {Promise<Tool>} The tool
|
|
429
|
+
*/
|
|
430
|
+
async getComposioToolBySlug(userId, slug, modifier) {
|
|
431
|
+
const customTool = await this.customTools.getCustomToolBySlug(slug);
|
|
432
|
+
if (customTool) {
|
|
433
|
+
return customTool;
|
|
434
|
+
}
|
|
435
|
+
const tool = await this.client.tools.retrieve(slug);
|
|
436
|
+
if (!tool) {
|
|
437
|
+
throw new Error(`Tool with slug ${slug} not found`);
|
|
438
|
+
}
|
|
439
|
+
let modifiedToool = this.transformToolCases(tool);
|
|
440
|
+
if (modifier) {
|
|
441
|
+
if (typeof modifier === "function") {
|
|
442
|
+
modifiedToool = modifier(slug, modifiedToool);
|
|
443
|
+
} else {
|
|
444
|
+
throw new Error("Invalid schema modifier. Not a function.");
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
return modifiedToool;
|
|
448
|
+
}
|
|
449
|
+
async get(userId, arg2, options) {
|
|
450
|
+
const executeToolFn = this.createExecuteToolFn(userId, options);
|
|
451
|
+
if (typeof arg2 === "string") {
|
|
452
|
+
const tool = await this.getComposioToolBySlug(userId, arg2, options?.modifyToolSchema);
|
|
453
|
+
return this.toolset.wrapTool(tool, executeToolFn);
|
|
454
|
+
} else {
|
|
455
|
+
const tools = await this.getComposioTools(userId, arg2, options?.modifyToolSchema);
|
|
456
|
+
return this.toolset.wrapTools(tools, executeToolFn);
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
/**
|
|
460
|
+
* Creates a function that executes a tool.
|
|
461
|
+
* This function is used by agentic the toolsets to execute the tool
|
|
462
|
+
* @param {string} userId - The user id
|
|
463
|
+
* @param {ExecuteToolModifiers} modifiers - The modifiers to be applied to the tool
|
|
464
|
+
* @returns {ExecuteToolFn} The execute tool function
|
|
465
|
+
*/
|
|
466
|
+
createExecuteToolFn(userId, modifiers) {
|
|
467
|
+
const executeToolFn = async (toolSlug, input) => {
|
|
468
|
+
return await this.execute(
|
|
469
|
+
toolSlug,
|
|
470
|
+
{
|
|
471
|
+
userId,
|
|
472
|
+
arguments: input
|
|
473
|
+
},
|
|
474
|
+
modifiers
|
|
475
|
+
);
|
|
476
|
+
};
|
|
477
|
+
return executeToolFn;
|
|
478
|
+
}
|
|
479
|
+
/**
|
|
480
|
+
* Exectes a given tool with the provided parameters.
|
|
481
|
+
*
|
|
482
|
+
* This method calls the Composio API to execute the tool and returns the response.
|
|
483
|
+
*
|
|
484
|
+
* @param {string} slug - The ID of the tool to be executed
|
|
485
|
+
* @param {ToolExecuteParams} body - The parameters to be passed to the tool
|
|
486
|
+
* @returns {Promise<ToolExecuteResponse>} - The response from the tool execution
|
|
487
|
+
*/
|
|
488
|
+
async execute(slug, body, modifiers) {
|
|
489
|
+
if (modifiers && modifiers.beforeToolExecute) {
|
|
490
|
+
if (typeof modifiers.beforeToolExecute === "function") {
|
|
491
|
+
body = modifiers.beforeToolExecute(slug, body);
|
|
492
|
+
} else {
|
|
493
|
+
throw new Error("Invalid beforeToolExecute modifier. Not a function.");
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
let result;
|
|
497
|
+
const customTool = await this.customTools.getCustomToolBySlug(slug);
|
|
498
|
+
if (customTool) {
|
|
499
|
+
result = await this.customTools.executeCustomTool(slug, body, {
|
|
500
|
+
userId: body.userId || "default",
|
|
501
|
+
connectedAccountId: body.connectedAccountId
|
|
502
|
+
});
|
|
503
|
+
} else {
|
|
504
|
+
let connectedAccountId = body.connectedAccountId;
|
|
505
|
+
if (!connectedAccountId) {
|
|
506
|
+
connectedAccountId = await this.getConnectedAccountIdForTool(body.userId, slug) || void 0;
|
|
507
|
+
}
|
|
508
|
+
result = await this.client.tools.execute(slug, {
|
|
509
|
+
allow_tracing: body.allowTracing,
|
|
510
|
+
connected_account_id: body.connectedAccountId,
|
|
511
|
+
custom_auth_params: body.customAuthParams,
|
|
512
|
+
arguments: body.arguments,
|
|
513
|
+
entity_id: body.userId,
|
|
514
|
+
version: body.version,
|
|
515
|
+
text: body.text
|
|
516
|
+
});
|
|
517
|
+
result = this.transformToolExecuteResponse(result);
|
|
518
|
+
}
|
|
519
|
+
if (modifiers && modifiers.afterToolExecute) {
|
|
520
|
+
if (typeof modifiers.afterToolExecute === "function") {
|
|
521
|
+
result = modifiers.afterToolExecute(slug, result);
|
|
522
|
+
} else {
|
|
523
|
+
throw new Error("Invalid afterToolExecute modifier. Not a function.");
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
return result;
|
|
527
|
+
}
|
|
528
|
+
/**
|
|
529
|
+
* Fetches the list of all available tools in the Composio SDK.
|
|
530
|
+
*
|
|
531
|
+
* This method is mostly used by the CLI to get the list of tools.
|
|
532
|
+
* No filtering is done on the tools, the list is cached in the backend, no further optimization is required.
|
|
533
|
+
* @returns {string} - The list of all available tools as a string
|
|
534
|
+
*/
|
|
535
|
+
async getToolsEnum() {
|
|
536
|
+
return this.client.tools.retrieveEnum();
|
|
537
|
+
}
|
|
538
|
+
/**
|
|
539
|
+
* Fetches the input parameters for a given tool.
|
|
540
|
+
*
|
|
541
|
+
* This method is used to get the input parameters for a tool before executing it.
|
|
542
|
+
*
|
|
543
|
+
* @param {string} slug - The ID of the tool to find input for
|
|
544
|
+
* @param {ToolGetInputParams} body - The parameters to be passed to the tool
|
|
545
|
+
* @returns
|
|
546
|
+
*/
|
|
547
|
+
async getInput(slug, body) {
|
|
548
|
+
return this.client.tools.getInput(slug, body);
|
|
549
|
+
}
|
|
550
|
+
/**
|
|
551
|
+
* Proxies a custom request to a toolkit/integration
|
|
552
|
+
* @param body
|
|
553
|
+
* @returns
|
|
554
|
+
*/
|
|
555
|
+
async proxyExecute(body) {
|
|
556
|
+
return this.client.tools.proxy(body);
|
|
557
|
+
}
|
|
558
|
+
/**
|
|
559
|
+
* Execute a custom tool
|
|
560
|
+
* @param body
|
|
561
|
+
* @returns
|
|
562
|
+
*/
|
|
563
|
+
async createCustomTool(body) {
|
|
564
|
+
return this.customTools.createTool(body);
|
|
565
|
+
}
|
|
566
|
+
};
|
|
567
|
+
|
|
568
|
+
// src/types/toolkit.types.ts
|
|
569
|
+
import { z as z2 } from "zod";
|
|
570
|
+
var ToolkitMangedByEnumSchema = z2.enum(["all", "composio_managed", "project_managed"]);
|
|
571
|
+
var ToolkitSortByEnumSchema = z2.enum(["usage", "alphabetically"]);
|
|
572
|
+
var ToolkitsListParamsSchema = z2.object({
|
|
573
|
+
category: z2.string().optional(),
|
|
574
|
+
isLocal: z2.boolean().optional(),
|
|
575
|
+
managedBy: ToolkitMangedByEnumSchema.optional(),
|
|
576
|
+
sortBy: ToolkitSortByEnumSchema.optional()
|
|
577
|
+
});
|
|
578
|
+
var ToolKitMetaSchema = z2.object({
|
|
579
|
+
categories: z2.array(
|
|
580
|
+
z2.object({
|
|
581
|
+
id: z2.string(),
|
|
582
|
+
name: z2.string()
|
|
583
|
+
})
|
|
584
|
+
),
|
|
585
|
+
createdAt: z2.string(),
|
|
586
|
+
description: z2.string(),
|
|
587
|
+
logo: z2.string(),
|
|
588
|
+
toolsCount: z2.number(),
|
|
589
|
+
triggersCount: z2.number(),
|
|
590
|
+
updatedAt: z2.string()
|
|
591
|
+
});
|
|
592
|
+
var ToolKitItemSchema = z2.object({
|
|
593
|
+
name: z2.string(),
|
|
594
|
+
slug: z2.string(),
|
|
595
|
+
meta: ToolKitMetaSchema,
|
|
596
|
+
isLocalToolkit: z2.boolean(),
|
|
597
|
+
authSchemes: z2.array(z2.string()).optional(),
|
|
598
|
+
composioManagedAuthSchemes: z2.array(z2.string()).optional(),
|
|
599
|
+
noAuth: z2.boolean().optional()
|
|
600
|
+
});
|
|
601
|
+
var ToolKitListResponseSchema = z2.object({
|
|
602
|
+
items: z2.array(ToolKitItemSchema),
|
|
603
|
+
nextCursor: z2.string().nullable(),
|
|
604
|
+
totalPages: z2.number()
|
|
605
|
+
});
|
|
606
|
+
var ToolkitAuthFieldSchema = z2.object({
|
|
607
|
+
name: z2.string(),
|
|
608
|
+
displayName: z2.string(),
|
|
609
|
+
type: z2.string(),
|
|
610
|
+
default: z2.string().nullable().optional()
|
|
611
|
+
});
|
|
612
|
+
var ToolkitAuthConfigDetailsSchema = z2.object({
|
|
613
|
+
name: z2.string(),
|
|
614
|
+
mode: z2.string(),
|
|
615
|
+
fields: z2.array(
|
|
616
|
+
z2.object({
|
|
617
|
+
authConfigCreation: z2.object({
|
|
618
|
+
optional: z2.array(ToolkitAuthFieldSchema),
|
|
619
|
+
required: z2.array(ToolkitAuthFieldSchema)
|
|
620
|
+
}),
|
|
621
|
+
connectedAccountInitiation: z2.object({
|
|
622
|
+
optional: z2.array(ToolkitAuthFieldSchema),
|
|
623
|
+
required: z2.array(ToolkitAuthFieldSchema)
|
|
624
|
+
})
|
|
625
|
+
})
|
|
626
|
+
),
|
|
627
|
+
proxy: z2.object({
|
|
628
|
+
baseUrul: z2.string()
|
|
629
|
+
})
|
|
630
|
+
});
|
|
631
|
+
var ToolkitRetrieveResponseSchema = z2.object({
|
|
632
|
+
name: z2.string(),
|
|
633
|
+
slug: z2.string(),
|
|
634
|
+
meta: ToolKitMetaSchema,
|
|
635
|
+
isLocalToolkit: z2.boolean(),
|
|
636
|
+
composioManagedAuthSchemes: z2.array(z2.string()).optional(),
|
|
637
|
+
authConfigDetails: z2.array(ToolkitAuthConfigDetailsSchema).optional()
|
|
638
|
+
});
|
|
639
|
+
var ToolkitCategorySchema = z2.object({
|
|
640
|
+
id: z2.string(),
|
|
641
|
+
name: z2.string()
|
|
642
|
+
});
|
|
643
|
+
var ToolkitRetrieveCategoriesResponseSchema = z2.object({
|
|
644
|
+
items: z2.array(ToolkitCategorySchema),
|
|
645
|
+
nextCursor: z2.string().nullable(),
|
|
646
|
+
totalPages: z2.number()
|
|
647
|
+
});
|
|
648
|
+
|
|
649
|
+
// src/models/Toolkits.ts
|
|
650
|
+
var Toolkits = class {
|
|
651
|
+
client;
|
|
652
|
+
constructor(client) {
|
|
653
|
+
this.client = client;
|
|
654
|
+
}
|
|
655
|
+
/**
|
|
656
|
+
* List all toolkits available in the Composio SDK.
|
|
657
|
+
* This method fetches the toolkits from the Composio API.
|
|
658
|
+
* @returns {Promise<Toolkit[]>} List of toolkits
|
|
659
|
+
*/
|
|
660
|
+
async getToolkits(query) {
|
|
661
|
+
const parsedQuery = ToolkitsListParamsSchema.parse(query);
|
|
662
|
+
const result = await this.client.toolkits.list({
|
|
663
|
+
category: parsedQuery.category,
|
|
664
|
+
is_local: parsedQuery.isLocal,
|
|
665
|
+
managed_by: parsedQuery.managedBy,
|
|
666
|
+
sort_by: parsedQuery.sortBy
|
|
667
|
+
});
|
|
668
|
+
const parsedResult = ToolKitListResponseSchema.parse({
|
|
669
|
+
items: result.items.map((item) => {
|
|
670
|
+
const parsedItem = ToolKitItemSchema.parse({
|
|
671
|
+
name: item.name,
|
|
672
|
+
slug: item.slug,
|
|
673
|
+
meta: item.meta,
|
|
674
|
+
isLocalToolkit: item.is_local_toolkit,
|
|
675
|
+
authSchemes: item.auth_schemes,
|
|
676
|
+
composioManagedAuthSchemes: item.composio_managed_auth_schemes,
|
|
677
|
+
noAuth: item.no_auth
|
|
678
|
+
});
|
|
679
|
+
return parsedItem;
|
|
680
|
+
}),
|
|
681
|
+
nextCursor: result.next_cursor,
|
|
682
|
+
totalPages: result.total_pages
|
|
683
|
+
});
|
|
684
|
+
return parsedResult;
|
|
685
|
+
}
|
|
686
|
+
/**
|
|
687
|
+
* Fetches a toolkit by its Slug.
|
|
688
|
+
* This method retrieves the toolkit from the Composio API.
|
|
689
|
+
* @param slug - The ID of the toolkit to be retrieved
|
|
690
|
+
* @param options - Request options
|
|
691
|
+
* @returns {Promise<ToolkitRetrieveResponse>} The toolkit object
|
|
692
|
+
*/
|
|
693
|
+
async getToolkitBySlug(slug) {
|
|
694
|
+
const result = await this.client.toolkits.retrieve(slug);
|
|
695
|
+
const parsedResult = ToolkitRetrieveResponseSchema.parse({
|
|
696
|
+
name: result.name,
|
|
697
|
+
slug: result.slug,
|
|
698
|
+
meta: result.meta,
|
|
699
|
+
isLocalToolkit: result.is_local_toolkit,
|
|
700
|
+
composioManagedAuthSchemes: result.composio_managed_auth_schemes,
|
|
701
|
+
authConfigDetails: result.auth_config_details
|
|
702
|
+
});
|
|
703
|
+
return parsedResult;
|
|
704
|
+
}
|
|
705
|
+
/**
|
|
706
|
+
* Fetches a toolkit by its Slug or a list of toolkits.
|
|
707
|
+
* This method retrieves the toolkit from the Composio API.
|
|
708
|
+
* @param arg - The ID of the toolkit to be retrieved or a list of parameters
|
|
709
|
+
* @returns {Promise<ToolkitRetrieveResponse | ToolKitListResponse>} The toolkit object or a list of toolkits
|
|
710
|
+
*/
|
|
711
|
+
async get(arg) {
|
|
712
|
+
if (typeof arg === "string") {
|
|
713
|
+
return this.getToolkitBySlug(arg);
|
|
714
|
+
}
|
|
715
|
+
return this.getToolkits(arg);
|
|
716
|
+
}
|
|
717
|
+
/**
|
|
718
|
+
* Fetches all categories available in the Composio SDK
|
|
719
|
+
*
|
|
720
|
+
* @returns {Promise<ToolkitRetrieveCategoriesResponse>} List of categories
|
|
721
|
+
*/
|
|
722
|
+
async listCategories() {
|
|
723
|
+
const result = await this.client.toolkits.retrieveCategories();
|
|
724
|
+
const parsedResult = ToolkitRetrieveCategoriesResponseSchema.parse({
|
|
725
|
+
items: result.items.map((item) => {
|
|
726
|
+
const parsedItem = ToolkitCategorySchema.parse({
|
|
727
|
+
id: item.id,
|
|
728
|
+
name: item.name
|
|
729
|
+
});
|
|
730
|
+
return parsedItem;
|
|
731
|
+
}),
|
|
732
|
+
nextCursor: result.next_cursor,
|
|
733
|
+
totalPages: result.total_pages
|
|
734
|
+
});
|
|
735
|
+
return parsedResult;
|
|
736
|
+
}
|
|
737
|
+
};
|
|
186
738
|
|
|
187
739
|
// src/utils/pusher.ts
|
|
188
740
|
var PUSHER_KEY = process.env.CLIENT_PUSHER_KEY || "ff9f18c208855d77a152";
|
|
@@ -277,7 +829,6 @@ var PusherUtils = class _PusherUtils {
|
|
|
277
829
|
|
|
278
830
|
// src/models/Session.ts
|
|
279
831
|
var Session = class {
|
|
280
|
-
FILE_NAME = "core/models/Session.ts";
|
|
281
832
|
client;
|
|
282
833
|
constructor(client) {
|
|
283
834
|
this.client = client;
|
|
@@ -293,7 +844,6 @@ var Session = class {
|
|
|
293
844
|
|
|
294
845
|
// src/models/Triggers.ts
|
|
295
846
|
var Triggers = class {
|
|
296
|
-
FILE_NAME = "core/models/Triggers.ts";
|
|
297
847
|
client;
|
|
298
848
|
constructor(client) {
|
|
299
849
|
this.client = client;
|
|
@@ -427,53 +977,6 @@ var Triggers = class {
|
|
|
427
977
|
}
|
|
428
978
|
};
|
|
429
979
|
|
|
430
|
-
// src/toolset/BaseToolset.ts
|
|
431
|
-
var BaseComposioToolset = class {
|
|
432
|
-
client;
|
|
433
|
-
DEFAULT_ENTITY_ID = "default";
|
|
434
|
-
/**
|
|
435
|
-
* Set the client for the toolset. This is automatically done by the Composio class.
|
|
436
|
-
* @param client - The Composio client.
|
|
437
|
-
*/
|
|
438
|
-
setClient(client) {
|
|
439
|
-
this.client = client;
|
|
440
|
-
}
|
|
441
|
-
/**
|
|
442
|
-
* Get a tool from the client.
|
|
443
|
-
* @param slug - The slug of the tool.
|
|
444
|
-
* @returns The tool.
|
|
445
|
-
*/
|
|
446
|
-
async getTool(slug) {
|
|
447
|
-
const tool = await this.client?.tools.get(slug);
|
|
448
|
-
return this._wrapTool(tool);
|
|
449
|
-
}
|
|
450
|
-
/**
|
|
451
|
-
* Ensure the client is initialized.
|
|
452
|
-
* This is automatically done by the Composio class.
|
|
453
|
-
*/
|
|
454
|
-
ensureClient() {
|
|
455
|
-
if (!this.client) {
|
|
456
|
-
throw new Error(
|
|
457
|
-
"Client not initialized. Make sure the toolset is properly initialized with Composio."
|
|
458
|
-
);
|
|
459
|
-
}
|
|
460
|
-
}
|
|
461
|
-
};
|
|
462
|
-
|
|
463
|
-
// src/toolset/ComposioToolset.ts
|
|
464
|
-
var ComposioToolset = class extends BaseComposioToolset {
|
|
465
|
-
FILE_NAME = "core/toolset/ComposioToolset.ts";
|
|
466
|
-
_wrapTool = (tool) => {
|
|
467
|
-
return tool;
|
|
468
|
-
};
|
|
469
|
-
async getTools(params) {
|
|
470
|
-
const tools = await this.client?.tools.list(params);
|
|
471
|
-
return tools?.items.map((tool) => this._wrapTool(tool)) ?? [];
|
|
472
|
-
}
|
|
473
|
-
async test() {
|
|
474
|
-
}
|
|
475
|
-
};
|
|
476
|
-
|
|
477
980
|
// src/models/AuthConfigs.ts
|
|
478
981
|
var AuthConfigs = class {
|
|
479
982
|
FILE_NAME = "core/models/AuthConfigs.ts";
|
|
@@ -557,9 +1060,176 @@ var AuthConfigs = class {
|
|
|
557
1060
|
}
|
|
558
1061
|
};
|
|
559
1062
|
|
|
1063
|
+
// src/types/connectedAccounts.types.ts
|
|
1064
|
+
import { z as z3 } from "zod";
|
|
1065
|
+
var ConnectedAccountStatuses = {
|
|
1066
|
+
ACTIVE: "ACTIVE",
|
|
1067
|
+
INACTIVE: "INACTIVE",
|
|
1068
|
+
PENDING: "DELETED",
|
|
1069
|
+
INITIATED: "INITIATED",
|
|
1070
|
+
EXPIRED: "EXPIRED",
|
|
1071
|
+
FAILED: "FAILED"
|
|
1072
|
+
};
|
|
1073
|
+
var ConnectedAccountStatusSchema = z3.enum([
|
|
1074
|
+
ConnectedAccountStatuses.ACTIVE,
|
|
1075
|
+
ConnectedAccountStatuses.INACTIVE,
|
|
1076
|
+
ConnectedAccountStatuses.PENDING,
|
|
1077
|
+
ConnectedAccountStatuses.INITIATED,
|
|
1078
|
+
ConnectedAccountStatuses.EXPIRED,
|
|
1079
|
+
ConnectedAccountStatuses.FAILED
|
|
1080
|
+
]);
|
|
1081
|
+
var CreateConnectedAccountParamsSchema = z3.object({
|
|
1082
|
+
authConfig: z3.object({
|
|
1083
|
+
id: z3.string()
|
|
1084
|
+
}),
|
|
1085
|
+
connection: z3.object({
|
|
1086
|
+
data: z3.record(z3.string(), z3.unknown()).optional(),
|
|
1087
|
+
redirectUrl: z3.string().optional(),
|
|
1088
|
+
userId: z3.string().optional()
|
|
1089
|
+
})
|
|
1090
|
+
});
|
|
1091
|
+
var DefaultCreateConnectedAccountParamsSchema = z3.object({
|
|
1092
|
+
auth_config: z3.object({
|
|
1093
|
+
id: z3.string()
|
|
1094
|
+
}),
|
|
1095
|
+
connection: z3.object({
|
|
1096
|
+
data: z3.record(z3.string(), z3.unknown()).optional(),
|
|
1097
|
+
redirect_uri: z3.string().optional(),
|
|
1098
|
+
user_id: z3.string().optional()
|
|
1099
|
+
})
|
|
1100
|
+
});
|
|
1101
|
+
var CreateConnectedAccountOptionsSchema = z3.object({
|
|
1102
|
+
redirectUrl: z3.string().optional(),
|
|
1103
|
+
data: z3.record(z3.string(), z3.unknown()).optional()
|
|
1104
|
+
});
|
|
1105
|
+
var CreateConnectedAccountResponseSchema = z3.object({
|
|
1106
|
+
id: z3.string(),
|
|
1107
|
+
status: ConnectedAccountStatusSchema,
|
|
1108
|
+
redirectUrl: z3.string().nullable()
|
|
1109
|
+
});
|
|
1110
|
+
var ConnectedAccountAuthSchemes = {
|
|
1111
|
+
OAUTH2: "OAUTH2",
|
|
1112
|
+
OAUTH1: "OAUTH1",
|
|
1113
|
+
OAUTH1A: "OAUTH1A",
|
|
1114
|
+
API_KEY: "API_KEY",
|
|
1115
|
+
BASIC: "BASIC",
|
|
1116
|
+
BILLCOM_AUTH: "BILLCOM_AUTH",
|
|
1117
|
+
BEARER_TOKEN: "BEARER_TOKEN",
|
|
1118
|
+
GOOGLE_SERVICE_ACCOUNT: "GOOGLE_SERVICE_ACCOUNT",
|
|
1119
|
+
NO_AUTH: "NO_AUTH",
|
|
1120
|
+
BASIC_WITH_JWT: "BASIC_WITH_JWT",
|
|
1121
|
+
COMPOSIO_LINK: "COMPOSIO_LINK",
|
|
1122
|
+
CALCOM_AUTH: "CALCOM_AUTH",
|
|
1123
|
+
SNOWFLAKE: "SNOWFLAKE"
|
|
1124
|
+
};
|
|
1125
|
+
var ConnectedAccountAuthSchemesSchema = z3.enum([
|
|
1126
|
+
ConnectedAccountAuthSchemes.OAUTH2,
|
|
1127
|
+
ConnectedAccountAuthSchemes.OAUTH1,
|
|
1128
|
+
ConnectedAccountAuthSchemes.OAUTH1A,
|
|
1129
|
+
ConnectedAccountAuthSchemes.API_KEY,
|
|
1130
|
+
ConnectedAccountAuthSchemes.BASIC,
|
|
1131
|
+
ConnectedAccountAuthSchemes.BILLCOM_AUTH,
|
|
1132
|
+
ConnectedAccountAuthSchemes.BEARER_TOKEN,
|
|
1133
|
+
ConnectedAccountAuthSchemes.GOOGLE_SERVICE_ACCOUNT,
|
|
1134
|
+
ConnectedAccountAuthSchemes.NO_AUTH,
|
|
1135
|
+
ConnectedAccountAuthSchemes.BASIC_WITH_JWT,
|
|
1136
|
+
ConnectedAccountAuthSchemes.COMPOSIO_LINK,
|
|
1137
|
+
ConnectedAccountAuthSchemes.CALCOM_AUTH,
|
|
1138
|
+
ConnectedAccountAuthSchemes.SNOWFLAKE
|
|
1139
|
+
]);
|
|
1140
|
+
var ConnectedAccountAuthConfigSchema = z3.object({
|
|
1141
|
+
id: z3.string(),
|
|
1142
|
+
authScheme: ConnectedAccountAuthSchemesSchema,
|
|
1143
|
+
isComposioManaged: z3.boolean(),
|
|
1144
|
+
isDisabled: z3.boolean()
|
|
1145
|
+
});
|
|
1146
|
+
var ConnectedAccountRetrieveResponseSchema = z3.object({
|
|
1147
|
+
id: z3.string(),
|
|
1148
|
+
uuid: z3.string(),
|
|
1149
|
+
authConfig: ConnectedAccountAuthConfigSchema,
|
|
1150
|
+
userId: z3.string(),
|
|
1151
|
+
data: z3.record(z3.string(), z3.unknown()),
|
|
1152
|
+
params: z3.record(z3.string(), z3.unknown()),
|
|
1153
|
+
status: ConnectedAccountStatusSchema,
|
|
1154
|
+
statusReason: z3.string().nullable(),
|
|
1155
|
+
toolkit: z3.object({
|
|
1156
|
+
slug: z3.string()
|
|
1157
|
+
}),
|
|
1158
|
+
testRequestEndpoint: z3.string().optional(),
|
|
1159
|
+
isDisabled: z3.boolean(),
|
|
1160
|
+
createdAt: z3.string(),
|
|
1161
|
+
updatedAt: z3.string()
|
|
1162
|
+
});
|
|
1163
|
+
|
|
1164
|
+
// src/models/ConnectionRequest.ts
|
|
1165
|
+
var ConnectionRequest = class {
|
|
1166
|
+
FILE_NAME = "core/models/ConnectionRequest.ts";
|
|
1167
|
+
client;
|
|
1168
|
+
connectedAccountId;
|
|
1169
|
+
connectedAccountStatus;
|
|
1170
|
+
constructor(client, connectedAccountId, connectedAccountStatus) {
|
|
1171
|
+
this.client = client;
|
|
1172
|
+
this.connectedAccountId = connectedAccountId;
|
|
1173
|
+
this.connectedAccountStatus = connectedAccountStatus;
|
|
1174
|
+
}
|
|
1175
|
+
/**
|
|
1176
|
+
* Transform the response from the Composio API to the SDK format
|
|
1177
|
+
* @param response
|
|
1178
|
+
* @returns
|
|
1179
|
+
*/
|
|
1180
|
+
async transformResponse(response) {
|
|
1181
|
+
const parsedResponse = ConnectedAccountRetrieveResponseSchema.parse({
|
|
1182
|
+
...response,
|
|
1183
|
+
userId: response.user_id,
|
|
1184
|
+
// Add the missing userId property
|
|
1185
|
+
authConfig: {
|
|
1186
|
+
...response.auth_config,
|
|
1187
|
+
authScheme: response.auth_config.auth_scheme,
|
|
1188
|
+
isComposioManaged: response.auth_config.is_composio_managed,
|
|
1189
|
+
isDisabled: response.auth_config.is_disabled
|
|
1190
|
+
},
|
|
1191
|
+
statusReason: response.status_reason,
|
|
1192
|
+
isDisabled: response.is_disabled,
|
|
1193
|
+
createdAt: response.created_at,
|
|
1194
|
+
updatedAt: response.updated_at,
|
|
1195
|
+
testRequestEndpoint: response.test_request_endpoint
|
|
1196
|
+
});
|
|
1197
|
+
return parsedResponse;
|
|
1198
|
+
}
|
|
1199
|
+
/**
|
|
1200
|
+
* Wait for the connection to be established.
|
|
1201
|
+
* The function will poll the Composio API every second until the connection is established or the timeout is reached.
|
|
1202
|
+
* @param {number} timeout - The time in milliseconds to wait for the connection to be established. Default is 30 seconds.
|
|
1203
|
+
* @returns
|
|
1204
|
+
*/
|
|
1205
|
+
async waitForConnection(timeout = 6e4) {
|
|
1206
|
+
if (this.connectedAccountStatus === ConnectedAccountStatuses.ACTIVE) {
|
|
1207
|
+
const response = await this.client.connectedAccounts.retrieve(this.connectedAccountId);
|
|
1208
|
+
return Promise.resolve(this.transformResponse(response));
|
|
1209
|
+
}
|
|
1210
|
+
return new Promise((resolve, reject) => {
|
|
1211
|
+
const interval = setInterval(async () => {
|
|
1212
|
+
try {
|
|
1213
|
+
const response = await this.client.connectedAccounts.retrieve(this.connectedAccountId);
|
|
1214
|
+
if (response.status === ConnectedAccountStatuses.ACTIVE) {
|
|
1215
|
+
clearInterval(interval);
|
|
1216
|
+
resolve(this.transformResponse(response));
|
|
1217
|
+
}
|
|
1218
|
+
} catch (error) {
|
|
1219
|
+
clearInterval(interval);
|
|
1220
|
+
reject(error);
|
|
1221
|
+
}
|
|
1222
|
+
}, 1e3);
|
|
1223
|
+
setTimeout(() => {
|
|
1224
|
+
clearInterval(interval);
|
|
1225
|
+
reject(new Error("Connection request timed out"));
|
|
1226
|
+
}, timeout);
|
|
1227
|
+
});
|
|
1228
|
+
}
|
|
1229
|
+
};
|
|
1230
|
+
|
|
560
1231
|
// src/models/ConnectedAccounts.ts
|
|
561
1232
|
var ConnectedAccounts = class {
|
|
562
|
-
FILE_NAME = "core/models/ConnectedAccounts.ts";
|
|
563
1233
|
client;
|
|
564
1234
|
constructor(client) {
|
|
565
1235
|
this.client = client;
|
|
@@ -570,8 +1240,8 @@ var ConnectedAccounts = class {
|
|
|
570
1240
|
* @param {RequestOptions} options - Request options
|
|
571
1241
|
* @returns {Promise<ConnectedAccountListResponse>} List of connected accounts
|
|
572
1242
|
*/
|
|
573
|
-
async list(query
|
|
574
|
-
return this.client.connectedAccounts.list(query
|
|
1243
|
+
async list(query) {
|
|
1244
|
+
return this.client.connectedAccounts.list(query);
|
|
575
1245
|
}
|
|
576
1246
|
/**
|
|
577
1247
|
* Create a new connected account
|
|
@@ -579,8 +1249,8 @@ var ConnectedAccounts = class {
|
|
|
579
1249
|
* @param {RequestOptions} options - Request options
|
|
580
1250
|
* @returns {Promise<ConnectedAccountCreateResponse>} Created connected account
|
|
581
1251
|
*/
|
|
582
|
-
async create(data
|
|
583
|
-
return this.client.connectedAccounts.create(data
|
|
1252
|
+
async create(data) {
|
|
1253
|
+
return this.client.connectedAccounts.create(data);
|
|
584
1254
|
}
|
|
585
1255
|
/**
|
|
586
1256
|
* Get a connected account by nanoid
|
|
@@ -588,8 +1258,8 @@ var ConnectedAccounts = class {
|
|
|
588
1258
|
* @param {RequestOptions} options - Request options
|
|
589
1259
|
* @returns {Promise<ConnectedAccountRetrieveResponse>} Connected account details
|
|
590
1260
|
*/
|
|
591
|
-
async get(nanoid
|
|
592
|
-
return this.client.connectedAccounts.retrieve(nanoid
|
|
1261
|
+
async get(nanoid) {
|
|
1262
|
+
return this.client.connectedAccounts.retrieve(nanoid);
|
|
593
1263
|
}
|
|
594
1264
|
/**
|
|
595
1265
|
* Delete a connected account
|
|
@@ -597,8 +1267,8 @@ var ConnectedAccounts = class {
|
|
|
597
1267
|
* @param {RequestOptions} options - Request options
|
|
598
1268
|
* @returns {Promise<ConnectedAccountDeleteResponse>} Response from deletion
|
|
599
1269
|
*/
|
|
600
|
-
async delete(nanoid
|
|
601
|
-
return this.client.connectedAccounts.delete(nanoid
|
|
1270
|
+
async delete(nanoid) {
|
|
1271
|
+
return this.client.connectedAccounts.delete(nanoid);
|
|
602
1272
|
}
|
|
603
1273
|
/**
|
|
604
1274
|
* Refresh a connected account's credentials
|
|
@@ -606,8 +1276,8 @@ var ConnectedAccounts = class {
|
|
|
606
1276
|
* @param {RequestOptions} options - Request options
|
|
607
1277
|
* @returns {Promise<ConnectedAccountRefreshResponse>} Refreshed connected account details
|
|
608
1278
|
*/
|
|
609
|
-
async refresh(nanoid
|
|
610
|
-
return this.client.connectedAccounts.refresh(nanoid
|
|
1279
|
+
async refresh(nanoid) {
|
|
1280
|
+
return this.client.connectedAccounts.refresh(nanoid);
|
|
611
1281
|
}
|
|
612
1282
|
/**
|
|
613
1283
|
* Update the status of a connected account
|
|
@@ -616,8 +1286,8 @@ var ConnectedAccounts = class {
|
|
|
616
1286
|
* @param {RequestOptions} options - Request options
|
|
617
1287
|
* @returns {Promise<ConnectedAccountUpdateStatusResponse>} Updated connected account details
|
|
618
1288
|
*/
|
|
619
|
-
async updateStatus(nanoid, params
|
|
620
|
-
return this.client.connectedAccounts.updateStatus(nanoid, params
|
|
1289
|
+
async updateStatus(nanoid, params) {
|
|
1290
|
+
return this.client.connectedAccounts.updateStatus(nanoid, params);
|
|
621
1291
|
}
|
|
622
1292
|
/**
|
|
623
1293
|
* Enable a connected account
|
|
@@ -625,8 +1295,8 @@ var ConnectedAccounts = class {
|
|
|
625
1295
|
* @param {RequestOptions} options - Request options
|
|
626
1296
|
* @returns {Promise<ConnectedAccountUpdateStatusResponse>} Updated connected account details
|
|
627
1297
|
*/
|
|
628
|
-
async enable(nanoid
|
|
629
|
-
return this.client.connectedAccounts.updateStatus(nanoid, { enabled: true }
|
|
1298
|
+
async enable(nanoid) {
|
|
1299
|
+
return this.client.connectedAccounts.updateStatus(nanoid, { enabled: true });
|
|
630
1300
|
}
|
|
631
1301
|
/**
|
|
632
1302
|
* Disable a connected account
|
|
@@ -634,8 +1304,29 @@ var ConnectedAccounts = class {
|
|
|
634
1304
|
* @param {RequestOptions} options - Request options
|
|
635
1305
|
* @returns {Promise<ConnectedAccountUpdateStatusResponse>} Updated connected account details
|
|
636
1306
|
*/
|
|
637
|
-
async disable(nanoid
|
|
638
|
-
return this.client.connectedAccounts.updateStatus(nanoid, { enabled: false }
|
|
1307
|
+
async disable(nanoid) {
|
|
1308
|
+
return this.client.connectedAccounts.updateStatus(nanoid, { enabled: false });
|
|
1309
|
+
}
|
|
1310
|
+
/**
|
|
1311
|
+
* Compound function to create a new connected account.
|
|
1312
|
+
* This function creates a new connected account and returns a connection request.
|
|
1313
|
+
* Users can then wait for the connection to be established using the `waitForConnection` method.
|
|
1314
|
+
* @param {CreateConnectedAccountParams} data - Data for creating a new connected account
|
|
1315
|
+
* @returns {Promise<ConnectionRequest>} Connection request object
|
|
1316
|
+
*/
|
|
1317
|
+
async createConnectedAccount(userId, authConfigId, options) {
|
|
1318
|
+
const { redirectUrl, data } = options;
|
|
1319
|
+
const response = await this.create({
|
|
1320
|
+
auth_config: {
|
|
1321
|
+
id: authConfigId
|
|
1322
|
+
},
|
|
1323
|
+
connection: {
|
|
1324
|
+
data,
|
|
1325
|
+
redirect_uri: redirectUrl,
|
|
1326
|
+
user_id: userId
|
|
1327
|
+
}
|
|
1328
|
+
});
|
|
1329
|
+
return new ConnectionRequest(this.client, response.id, response.status);
|
|
639
1330
|
}
|
|
640
1331
|
};
|
|
641
1332
|
|
|
@@ -813,13 +1504,14 @@ var Telemetry = class {
|
|
|
813
1504
|
const descriptor = Object.getOwnPropertyDescriptor(proto, key);
|
|
814
1505
|
return key !== "constructor" && descriptor && typeof descriptor.value === "function" && descriptor.value.constructor.name === "AsyncFunction";
|
|
815
1506
|
});
|
|
1507
|
+
const instrumentedClassName = instance.constructor?.name || fileName || "unknown";
|
|
816
1508
|
for (const name of methodNames) {
|
|
817
1509
|
const originalMethod = instance[name];
|
|
818
1510
|
instance[name] = async (...args) => {
|
|
819
1511
|
const telemetryPayload = {
|
|
820
1512
|
eventName: TELEMETRY_EVENTS.SDK_METHOD_INVOKED,
|
|
821
1513
|
data: {
|
|
822
|
-
fileName:
|
|
1514
|
+
fileName: instrumentedClassName,
|
|
823
1515
|
method: name,
|
|
824
1516
|
params: args
|
|
825
1517
|
},
|
|
@@ -832,7 +1524,7 @@ var Telemetry = class {
|
|
|
832
1524
|
const telemetryPayload2 = {
|
|
833
1525
|
eventName: TELEMETRY_EVENTS.SDK_METHOD_ERROR,
|
|
834
1526
|
data: {
|
|
835
|
-
fileName:
|
|
1527
|
+
fileName: instrumentedClassName,
|
|
836
1528
|
method: name,
|
|
837
1529
|
params: args,
|
|
838
1530
|
error
|
|
@@ -844,89 +1536,294 @@ var Telemetry = class {
|
|
|
844
1536
|
}
|
|
845
1537
|
};
|
|
846
1538
|
}
|
|
847
|
-
return instance;
|
|
1539
|
+
return instance;
|
|
1540
|
+
}
|
|
1541
|
+
/**
|
|
1542
|
+
* Send the telemetry payload to the server.
|
|
1543
|
+
* @param payload - the telemetry payload to send
|
|
1544
|
+
* @returns
|
|
1545
|
+
*/
|
|
1546
|
+
async sendTelemetry(payload) {
|
|
1547
|
+
const isTelemetryDisabled = getEnvVariable("TELEMETRY_DISABLED", "false") === "true";
|
|
1548
|
+
if (isTelemetryDisabled) {
|
|
1549
|
+
return;
|
|
1550
|
+
}
|
|
1551
|
+
const url = `${TELEMETRY_URL}/api/sdk_metrics/telemetry`;
|
|
1552
|
+
const reqPayload = {
|
|
1553
|
+
data: payload,
|
|
1554
|
+
url,
|
|
1555
|
+
method: "POST",
|
|
1556
|
+
headers: { "Content-Type": "application/json" }
|
|
1557
|
+
};
|
|
1558
|
+
this.transport.send(reqPayload);
|
|
1559
|
+
}
|
|
1560
|
+
};
|
|
1561
|
+
|
|
1562
|
+
// src/utils/sdk.ts
|
|
1563
|
+
var userDataPath = () => {
|
|
1564
|
+
try {
|
|
1565
|
+
const path = __require("path");
|
|
1566
|
+
const os = __require("os");
|
|
1567
|
+
return path.join(os.homedir(), COMPOSIO_DIR, USER_DATA_FILE_NAME);
|
|
1568
|
+
} catch (_error) {
|
|
1569
|
+
return null;
|
|
1570
|
+
}
|
|
1571
|
+
};
|
|
1572
|
+
var getUserDataJson = () => {
|
|
1573
|
+
try {
|
|
1574
|
+
const fs = __require("fs");
|
|
1575
|
+
const data = fs.readFileSync(userDataPath(), "utf8");
|
|
1576
|
+
return JSON.parse(data);
|
|
1577
|
+
} catch (_error) {
|
|
1578
|
+
return {};
|
|
1579
|
+
}
|
|
1580
|
+
};
|
|
1581
|
+
function getSDKConfig(baseUrl, apiKey) {
|
|
1582
|
+
const userData = getUserDataJson();
|
|
1583
|
+
const { api_key: apiKeyFromUserConfig, base_url: baseURLFromUserConfig } = userData;
|
|
1584
|
+
const baseURLParsed = baseUrl || getEnvVariable("COMPOSIO_BASE_URL") || baseURLFromUserConfig || DEFAULT_BASE_URL;
|
|
1585
|
+
const apiKeyParsed = apiKey || getEnvVariable("COMPOSIO_API_KEY") || apiKeyFromUserConfig || "";
|
|
1586
|
+
return { baseURL: baseURLParsed, apiKey: apiKeyParsed };
|
|
1587
|
+
}
|
|
1588
|
+
|
|
1589
|
+
// src/utils/version.ts
|
|
1590
|
+
function isNewerVersion(version1, version2) {
|
|
1591
|
+
const v1 = version1.split(".").map(Number);
|
|
1592
|
+
const v2 = version2.split(".").map(Number);
|
|
1593
|
+
for (let i = 0; i < 3; i++) {
|
|
1594
|
+
if (v1[i] > v2[i]) return true;
|
|
1595
|
+
if (v1[i] < v2[i]) return false;
|
|
1596
|
+
}
|
|
1597
|
+
return false;
|
|
1598
|
+
}
|
|
1599
|
+
async function checkForLatestVersionFromNPM(currentVersion) {
|
|
1600
|
+
try {
|
|
1601
|
+
const packageName = "composio-core";
|
|
1602
|
+
const currentVersionFromPackageJson = currentVersion;
|
|
1603
|
+
const response = await fetch(`https://registry.npmjs.org/${packageName}/latest`);
|
|
1604
|
+
const data = await response.json();
|
|
1605
|
+
const latestVersion = data.version;
|
|
1606
|
+
if (isNewerVersion(latestVersion, currentVersionFromPackageJson) && !IS_DEVELOPMENT_OR_CI) {
|
|
1607
|
+
logger_default.info(
|
|
1608
|
+
`\u{1F680} Upgrade available! Your composio-core version (${currentVersionFromPackageJson}) is behind. Latest version: ${latestVersion}.`
|
|
1609
|
+
);
|
|
1610
|
+
}
|
|
1611
|
+
} catch (_error) {
|
|
1612
|
+
}
|
|
1613
|
+
}
|
|
1614
|
+
|
|
1615
|
+
// src/toolset/BaseToolset.ts
|
|
1616
|
+
var BaseToolset = class {
|
|
1617
|
+
/**
|
|
1618
|
+
* @internal
|
|
1619
|
+
* The function to execute a tool.
|
|
1620
|
+
* This is set automatically injected by the core SDK.
|
|
1621
|
+
*/
|
|
1622
|
+
_globalExecuteToolFn;
|
|
1623
|
+
/**
|
|
1624
|
+
* @internal
|
|
1625
|
+
* Set the function to execute a tool.
|
|
1626
|
+
* This is set automatically injected by the core SDK.
|
|
1627
|
+
*/
|
|
1628
|
+
_setExecuteToolFn(executeToolFn) {
|
|
1629
|
+
this._globalExecuteToolFn = executeToolFn;
|
|
1630
|
+
}
|
|
1631
|
+
/**
|
|
1632
|
+
* @public
|
|
1633
|
+
* Gloabl function to execute a tool.
|
|
1634
|
+
* This function is used by toolset providers to implement helper functions to execute tools.
|
|
1635
|
+
* This is a 1:1 mapping of the `execute` method in the `Tools` class.
|
|
1636
|
+
* @param {string} toolSlug - The slug of the tool to execute.
|
|
1637
|
+
* @param {Record<string, unknown>} input - The input to the tool.
|
|
1638
|
+
* @returns {Promise<string>} The result of the tool execution.
|
|
1639
|
+
*/
|
|
1640
|
+
executeTool(toolSlug, body, modifers) {
|
|
1641
|
+
return this._globalExecuteToolFn(toolSlug, body, modifers);
|
|
1642
|
+
}
|
|
1643
|
+
};
|
|
1644
|
+
var BaseNonAgenticToolset = class extends BaseToolset {
|
|
1645
|
+
_isAgentic = false;
|
|
1646
|
+
};
|
|
1647
|
+
var BaseAgenticToolset = class extends BaseToolset {
|
|
1648
|
+
_isAgentic = true;
|
|
1649
|
+
};
|
|
1650
|
+
|
|
1651
|
+
// src/toolset/OpenAIToolset.ts
|
|
1652
|
+
var OpenAIToolset = class extends BaseNonAgenticToolset {
|
|
1653
|
+
name = "openai";
|
|
1654
|
+
/**
|
|
1655
|
+
* Absract method to wrap a tool in the toolset.
|
|
1656
|
+
* This method is implemented by the toolset.
|
|
1657
|
+
* @param tool - The tool to wrap.
|
|
1658
|
+
* @returns The wrapped tool.
|
|
1659
|
+
*/
|
|
1660
|
+
wrapTool = (tool) => {
|
|
1661
|
+
const formattedSchema = {
|
|
1662
|
+
name: tool.slug,
|
|
1663
|
+
description: tool.description,
|
|
1664
|
+
parameters: tool.inputParameters
|
|
1665
|
+
};
|
|
1666
|
+
return {
|
|
1667
|
+
type: "function",
|
|
1668
|
+
function: formattedSchema
|
|
1669
|
+
};
|
|
1670
|
+
};
|
|
1671
|
+
wrapTools = (tools) => {
|
|
1672
|
+
return tools.map((tool) => this.wrapTool(tool));
|
|
1673
|
+
};
|
|
1674
|
+
/**
|
|
1675
|
+
* Execute a tool call.
|
|
1676
|
+
* @param {OpenAI.ChatCompletionMessageToolCall} tool - The tool to execute.
|
|
1677
|
+
* @param {string} userId - The user id.
|
|
1678
|
+
* @returns {Promise<string>} The result of the tool call.
|
|
1679
|
+
*/
|
|
1680
|
+
async executeToolCall(userId, tool, options, modifiers) {
|
|
1681
|
+
const payload = {
|
|
1682
|
+
arguments: JSON.parse(tool.function.arguments),
|
|
1683
|
+
connectedAccountId: options.connectedAccountId,
|
|
1684
|
+
customAuthParams: options.customAuthParams,
|
|
1685
|
+
userId
|
|
1686
|
+
};
|
|
1687
|
+
const result = await this.executeTool(tool.function.name, payload, modifiers);
|
|
1688
|
+
return JSON.stringify(result);
|
|
1689
|
+
}
|
|
1690
|
+
/**
|
|
1691
|
+
* Handle the tool call from the assistant.
|
|
1692
|
+
*
|
|
1693
|
+
* @param {OpenAI.ChatCompletion} chatCompletion - The chat completion object.
|
|
1694
|
+
* @param {string} userId - The user id.
|
|
1695
|
+
* @returns {Promise<string[]>} The results of the tool call.
|
|
1696
|
+
*/
|
|
1697
|
+
async handleToolCall(userId, chatCompletion, options, modifiers) {
|
|
1698
|
+
const outputs = [];
|
|
1699
|
+
for (const message of chatCompletion.choices) {
|
|
1700
|
+
if (message.message.tool_calls) {
|
|
1701
|
+
outputs.push(
|
|
1702
|
+
await this.executeToolCall(userId, message.message.tool_calls[0], options, modifiers)
|
|
1703
|
+
);
|
|
1704
|
+
}
|
|
1705
|
+
}
|
|
1706
|
+
return outputs;
|
|
1707
|
+
}
|
|
1708
|
+
/**
|
|
1709
|
+
* Handles all the tool calls from the assistant.
|
|
1710
|
+
*
|
|
1711
|
+
* @param {OpenAI.Beta.Threads.Run} run - The run object.
|
|
1712
|
+
* @param {string} userId - The user id.
|
|
1713
|
+
* @returns {Promise<OpenAI.Beta.Threads.Runs.RunSubmitToolOutputsParams.ToolOutput[]>} The tool outputs.
|
|
1714
|
+
*/
|
|
1715
|
+
async handleAssistantMessage(userId, run, options, modifiers) {
|
|
1716
|
+
const tool_calls = run.required_action?.submit_tool_outputs?.tool_calls || [];
|
|
1717
|
+
const tool_outputs = await Promise.all(
|
|
1718
|
+
tool_calls.map(async (tool_call) => {
|
|
1719
|
+
logger_default.debug(`Executing tool call: ${tool_call.id}`);
|
|
1720
|
+
const tool_response = await this.executeToolCall(
|
|
1721
|
+
userId,
|
|
1722
|
+
tool_call,
|
|
1723
|
+
options,
|
|
1724
|
+
modifiers
|
|
1725
|
+
);
|
|
1726
|
+
logger_default.debug(`Tool call ${tool_call.id} executed with response: ${tool_response}`);
|
|
1727
|
+
return {
|
|
1728
|
+
tool_call_id: tool_call.id,
|
|
1729
|
+
output: JSON.stringify(tool_response)
|
|
1730
|
+
};
|
|
1731
|
+
})
|
|
1732
|
+
);
|
|
1733
|
+
return tool_outputs;
|
|
1734
|
+
}
|
|
1735
|
+
/**
|
|
1736
|
+
* Waits for the assistant stream and handles the tool calls.
|
|
1737
|
+
*
|
|
1738
|
+
* @param {OpenAI} client - The OpenAI client.
|
|
1739
|
+
* @param {Stream<OpenAI.Beta.Assistants.AssistantStreamEvent>} runStream - The run stream.
|
|
1740
|
+
* @param {OpenAI.Beta.Threads.Thread} thread - The thread object.
|
|
1741
|
+
* @param {string} userId - The user id.
|
|
1742
|
+
* @returns {AsyncGenerator<OpenAI.Beta.Assistants.AssistantStreamEvent, void, unknown>} The run stream.
|
|
1743
|
+
*/
|
|
1744
|
+
async *waitAndHandleAssistantStreamToolCalls(userId, client, runStream, thread, options, modifiers) {
|
|
1745
|
+
let runId = null;
|
|
1746
|
+
for await (const event of runStream) {
|
|
1747
|
+
yield event;
|
|
1748
|
+
if (event.event === "thread.run.created") {
|
|
1749
|
+
const { id } = event.data;
|
|
1750
|
+
runId = id;
|
|
1751
|
+
}
|
|
1752
|
+
if (!runId) {
|
|
1753
|
+
continue;
|
|
1754
|
+
}
|
|
1755
|
+
if (event.event === "thread.run.requires_action") {
|
|
1756
|
+
const toolOutputs = await this.handleAssistantMessage(
|
|
1757
|
+
userId,
|
|
1758
|
+
event.data,
|
|
1759
|
+
options,
|
|
1760
|
+
modifiers
|
|
1761
|
+
);
|
|
1762
|
+
await client.beta.threads.runs.submitToolOutputs(thread.id, runId, {
|
|
1763
|
+
tool_outputs: toolOutputs
|
|
1764
|
+
});
|
|
1765
|
+
}
|
|
1766
|
+
if ([
|
|
1767
|
+
"thread.run.completed",
|
|
1768
|
+
"thread.run.failed",
|
|
1769
|
+
"thread.run.cancelled",
|
|
1770
|
+
"thread.run.expired"
|
|
1771
|
+
].includes(event.event)) {
|
|
1772
|
+
break;
|
|
1773
|
+
}
|
|
1774
|
+
}
|
|
1775
|
+
if (!runId) {
|
|
1776
|
+
throw new Error("No run ID found");
|
|
1777
|
+
}
|
|
1778
|
+
let finalRun = await client.beta.threads.runs.retrieve(thread.id, runId);
|
|
1779
|
+
while (["queued", "in_progress", "requires_action"].includes(finalRun.status)) {
|
|
1780
|
+
if (finalRun.status === "requires_action") {
|
|
1781
|
+
const toolOutputs = await this.handleAssistantMessage(userId, finalRun, options, modifiers);
|
|
1782
|
+
finalRun = await client.beta.threads.runs.submitToolOutputs(thread.id, runId, {
|
|
1783
|
+
tool_outputs: toolOutputs
|
|
1784
|
+
});
|
|
1785
|
+
} else {
|
|
1786
|
+
finalRun = await client.beta.threads.runs.retrieve(thread.id, runId);
|
|
1787
|
+
await new Promise((resolve) => setTimeout(resolve, 500));
|
|
1788
|
+
}
|
|
1789
|
+
}
|
|
848
1790
|
}
|
|
849
1791
|
/**
|
|
850
|
-
*
|
|
851
|
-
*
|
|
852
|
-
* @
|
|
1792
|
+
* Waits for the assistant tool calls and handles them.
|
|
1793
|
+
*
|
|
1794
|
+
* @param {OpenAI} client - The OpenAI client.
|
|
1795
|
+
* @param {OpenAI.Beta.Threads.Run} run - The run object.
|
|
1796
|
+
* @param {OpenAI.Beta.Threads.Thread} thread - The thread object.
|
|
1797
|
+
* @param {string} userId - The user id.
|
|
1798
|
+
* @returns {Promise<OpenAI.Beta.Threads.Run>} The run object.
|
|
853
1799
|
*/
|
|
854
|
-
async
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
1800
|
+
async waitAndHandleAssistantToolCalls(userId, client, run, thread, options, modifiers) {
|
|
1801
|
+
while (["queued", "in_progress", "requires_action"].includes(run.status)) {
|
|
1802
|
+
const tool_outputs = await this.handleAssistantMessage(userId, run, options, modifiers);
|
|
1803
|
+
if (run.status === "requires_action") {
|
|
1804
|
+
run = await client.beta.threads.runs.submitToolOutputs(thread.id, run.id, {
|
|
1805
|
+
tool_outputs
|
|
1806
|
+
});
|
|
1807
|
+
} else {
|
|
1808
|
+
run = await client.beta.threads.runs.retrieve(thread.id, run.id);
|
|
1809
|
+
await new Promise((resolve) => setTimeout(resolve, 500));
|
|
1810
|
+
}
|
|
858
1811
|
}
|
|
859
|
-
|
|
860
|
-
const reqPayload = {
|
|
861
|
-
data: payload,
|
|
862
|
-
url,
|
|
863
|
-
method: "POST",
|
|
864
|
-
headers: { "Content-Type": "application/json" }
|
|
865
|
-
};
|
|
866
|
-
this.transport.send(reqPayload);
|
|
867
|
-
}
|
|
868
|
-
};
|
|
869
|
-
|
|
870
|
-
// src/utils/sdk.ts
|
|
871
|
-
var userDataPath = () => {
|
|
872
|
-
try {
|
|
873
|
-
const path = __require("path");
|
|
874
|
-
const os = __require("os");
|
|
875
|
-
return path.join(os.homedir(), COMPOSIO_DIR, USER_DATA_FILE_NAME);
|
|
876
|
-
} catch (_error) {
|
|
877
|
-
return null;
|
|
878
|
-
}
|
|
879
|
-
};
|
|
880
|
-
var getUserDataJson = () => {
|
|
881
|
-
try {
|
|
882
|
-
const fs = __require("fs");
|
|
883
|
-
const data = fs.readFileSync(userDataPath(), "utf8");
|
|
884
|
-
return JSON.parse(data);
|
|
885
|
-
} catch (_error) {
|
|
886
|
-
return {};
|
|
1812
|
+
return run;
|
|
887
1813
|
}
|
|
888
1814
|
};
|
|
889
|
-
function getSDKConfig(baseUrl, apiKey) {
|
|
890
|
-
const userData = getUserDataJson();
|
|
891
|
-
const { api_key: apiKeyFromUserConfig, base_url: baseURLFromUserConfig } = userData;
|
|
892
|
-
const baseURLParsed = baseUrl || getEnvVariable("COMPOSIO_BASE_URL") || baseURLFromUserConfig || DEFAULT_BASE_URL;
|
|
893
|
-
const apiKeyParsed = apiKey || getEnvVariable("COMPOSIO_API_KEY") || apiKeyFromUserConfig || "";
|
|
894
|
-
return { baseURL: baseURLParsed, apiKey: apiKeyParsed };
|
|
895
|
-
}
|
|
896
1815
|
|
|
897
1816
|
// package.json
|
|
898
|
-
var version = "0.1.
|
|
1817
|
+
var version = "0.1.1-alpha.0";
|
|
899
1818
|
|
|
900
|
-
// src/utils/
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
for (let i = 0; i < 3; i++) {
|
|
905
|
-
if (v1[i] > v2[i]) return true;
|
|
906
|
-
if (v1[i] < v2[i]) return false;
|
|
907
|
-
}
|
|
908
|
-
return false;
|
|
909
|
-
}
|
|
910
|
-
async function checkForLatestVersionFromNPM() {
|
|
911
|
-
try {
|
|
912
|
-
const packageName = "composio-core";
|
|
913
|
-
const currentVersionFromPackageJson = version;
|
|
914
|
-
const response = await fetch(`https://registry.npmjs.org/${packageName}/latest`);
|
|
915
|
-
const data = await response.json();
|
|
916
|
-
const latestVersion = data.version;
|
|
917
|
-
if (isNewerVersion(latestVersion, currentVersionFromPackageJson) && !IS_DEVELOPMENT_OR_CI) {
|
|
918
|
-
logger_default.info(
|
|
919
|
-
`\u{1F680} Upgrade available! Your composio-core version (${currentVersionFromPackageJson}) is behind. Latest version: ${latestVersion}.`
|
|
920
|
-
);
|
|
921
|
-
}
|
|
922
|
-
} catch (_error) {
|
|
923
|
-
}
|
|
1819
|
+
// src/utils/uuid.ts
|
|
1820
|
+
import { v4 as uuidv4 } from "uuid";
|
|
1821
|
+
function getRandomUUID() {
|
|
1822
|
+
return uuidv4();
|
|
924
1823
|
}
|
|
925
1824
|
|
|
926
1825
|
// src/composio.ts
|
|
927
1826
|
var Composio = class {
|
|
928
|
-
DEFAULT_USER_ID = "default";
|
|
929
|
-
FILE_NAME = "core/composio.ts";
|
|
930
1827
|
/**
|
|
931
1828
|
* The Composio API client.
|
|
932
1829
|
* @type {ComposioClient}
|
|
@@ -934,15 +1831,10 @@ var Composio = class {
|
|
|
934
1831
|
client;
|
|
935
1832
|
/**
|
|
936
1833
|
* The configuration for the Composio SDK.
|
|
937
|
-
* @type {ComposioConfig<
|
|
1834
|
+
* @type {ComposioConfig<TToolset>}
|
|
938
1835
|
*/
|
|
939
1836
|
config;
|
|
940
1837
|
telemetry;
|
|
941
|
-
/**
|
|
942
|
-
* Context variables for the Composio SDK.
|
|
943
|
-
*/
|
|
944
|
-
userId;
|
|
945
|
-
connectedAccountIds;
|
|
946
1838
|
/**
|
|
947
1839
|
* Core models for Composio.
|
|
948
1840
|
*/
|
|
@@ -951,7 +1843,9 @@ var Composio = class {
|
|
|
951
1843
|
triggers;
|
|
952
1844
|
toolset;
|
|
953
1845
|
authConfigs;
|
|
1846
|
+
// connected accounts
|
|
954
1847
|
connectedAccounts;
|
|
1848
|
+
createConnectedAccount;
|
|
955
1849
|
/**
|
|
956
1850
|
* @param {Object} config Configuration for the Composio SDK.
|
|
957
1851
|
* @param {string} config.apiKey The API key for the Composio SDK.
|
|
@@ -959,7 +1853,7 @@ var Composio = class {
|
|
|
959
1853
|
* @param {string} config.runtime The runtime for the Composio SDK.
|
|
960
1854
|
* @param {boolean} config.allowTracking Whether to allow analytics / tracking. Defaults to true.
|
|
961
1855
|
* @param {boolean} config.allowTracing Whether to allow tracing. Defaults to true.
|
|
962
|
-
* @param {
|
|
1856
|
+
* @param {TToolset} config.toolset The toolset to use for this Composio instance.
|
|
963
1857
|
*/
|
|
964
1858
|
constructor(config) {
|
|
965
1859
|
const { baseURL: baseURLParsed, apiKey: apiKeyParsed } = getSDKConfig(
|
|
@@ -969,11 +1863,6 @@ var Composio = class {
|
|
|
969
1863
|
if (IS_DEVELOPMENT_OR_CI) {
|
|
970
1864
|
logger_default.info(`Initializing Composio w API Key: [REDACTED] and baseURL: ${baseURLParsed}`);
|
|
971
1865
|
}
|
|
972
|
-
if (config.userId && config.connectedAccountIds) {
|
|
973
|
-
logger_default.warn(
|
|
974
|
-
"When both userId and connectedAccountIds are provided, preference will be given to connectedAccountIds"
|
|
975
|
-
);
|
|
976
|
-
}
|
|
977
1866
|
this.client = new ComposioClient({
|
|
978
1867
|
apiKey: apiKeyParsed,
|
|
979
1868
|
baseURL: baseURLParsed
|
|
@@ -982,15 +1871,14 @@ var Composio = class {
|
|
|
982
1871
|
...config,
|
|
983
1872
|
allowTracking: config.allowTracking ?? true
|
|
984
1873
|
};
|
|
985
|
-
this.
|
|
986
|
-
this.
|
|
987
|
-
this.toolset
|
|
988
|
-
this.toolset.setClient(this);
|
|
989
|
-
this.tools = new Tools(this.client);
|
|
1874
|
+
this.toolset = config.toolset ?? new OpenAIToolset();
|
|
1875
|
+
this.tools = new Tools(this.client, this.toolset);
|
|
1876
|
+
this.toolset._setExecuteToolFn(this.tools.execute);
|
|
990
1877
|
this.toolkits = new Toolkits(this.client);
|
|
991
1878
|
this.triggers = new Triggers(this.client);
|
|
992
1879
|
this.authConfigs = new AuthConfigs(this.client);
|
|
993
1880
|
this.connectedAccounts = new ConnectedAccounts(this.client);
|
|
1881
|
+
this.createConnectedAccount = this.connectedAccounts.createConnectedAccount;
|
|
994
1882
|
if (this.config.allowTracking ?? true) {
|
|
995
1883
|
this.initializeTelemetry(
|
|
996
1884
|
{
|
|
@@ -999,14 +1887,15 @@ var Composio = class {
|
|
|
999
1887
|
frameworkRuntime: "node",
|
|
1000
1888
|
source: "node",
|
|
1001
1889
|
// @TODO: get the source
|
|
1002
|
-
sessionId: this.userId,
|
|
1003
1890
|
composioVersion: version,
|
|
1004
|
-
isBrowser: typeof window !== "undefined"
|
|
1891
|
+
isBrowser: typeof window !== "undefined",
|
|
1892
|
+
sessionId: getRandomUUID()
|
|
1893
|
+
// @TODO: get the session id
|
|
1005
1894
|
},
|
|
1006
1895
|
config.telemetryTransport
|
|
1007
1896
|
);
|
|
1008
1897
|
}
|
|
1009
|
-
checkForLatestVersionFromNPM();
|
|
1898
|
+
checkForLatestVersionFromNPM(version);
|
|
1010
1899
|
}
|
|
1011
1900
|
/**
|
|
1012
1901
|
* Initialize the instrumentations and telemetry for the Composio SDK.
|
|
@@ -1023,14 +1912,6 @@ var Composio = class {
|
|
|
1023
1912
|
this.telemetry.instrumentTelemetry(this.connectedAccounts);
|
|
1024
1913
|
this.telemetry.instrumentTelemetry(this.toolset);
|
|
1025
1914
|
}
|
|
1026
|
-
/**
|
|
1027
|
-
* Get the connected account id for the given app name.
|
|
1028
|
-
* @param appName - The name of the app.
|
|
1029
|
-
* @returns {string | undefined} The connected account id for the given app name.
|
|
1030
|
-
*/
|
|
1031
|
-
getConnectedAccountId(appName) {
|
|
1032
|
-
return this.connectedAccountIds?.[appName];
|
|
1033
|
-
}
|
|
1034
1915
|
/**
|
|
1035
1916
|
* Get the Composio SDK client.
|
|
1036
1917
|
* @returns {ComposioClient} The Composio API client.
|
|
@@ -1042,56 +1923,74 @@ var Composio = class {
|
|
|
1042
1923
|
return this.client;
|
|
1043
1924
|
}
|
|
1044
1925
|
/**
|
|
1045
|
-
*
|
|
1046
|
-
* @
|
|
1926
|
+
* Fetch all the tools from Composio.
|
|
1927
|
+
* @param {ToolListParams} params Parameters to fetch the tools.
|
|
1928
|
+
* @param {ToolsetOptions<TToolset>} modifiers Modifiers to apply to the tools.
|
|
1929
|
+
* @returns {Promise<ReturnType<TToolset['getTools']>>} The tools from the toolset.
|
|
1047
1930
|
*/
|
|
1048
|
-
|
|
1049
|
-
return this.
|
|
1931
|
+
getTools(userId, filters, modifiers) {
|
|
1932
|
+
return this.tools.get(userId, filters, modifiers);
|
|
1050
1933
|
}
|
|
1051
1934
|
/**
|
|
1052
|
-
*
|
|
1053
|
-
* @param
|
|
1054
|
-
* @
|
|
1935
|
+
* Fetch a tool from Composio by its slug.
|
|
1936
|
+
* @param {string} slug slug of the tool
|
|
1937
|
+
* @param {ToolsetOptions<TToolset>} modifiers to be applied to the tool
|
|
1938
|
+
* @returns {Promise<ReturnType<TToolset['getToolBySlug']>>} The tool from the toolset.
|
|
1055
1939
|
*/
|
|
1056
|
-
|
|
1057
|
-
return this.
|
|
1940
|
+
getToolBySlug(userId, slug, modifiers) {
|
|
1941
|
+
return this.tools.get(userId, slug, modifiers);
|
|
1942
|
+
}
|
|
1943
|
+
};
|
|
1944
|
+
|
|
1945
|
+
// src/toolset/ComposioToolset.ts
|
|
1946
|
+
var ComposioToolset = class extends BaseNonAgenticToolset {
|
|
1947
|
+
name = "ComposioToolset";
|
|
1948
|
+
wrapTool = (tool) => {
|
|
1949
|
+
return tool;
|
|
1950
|
+
};
|
|
1951
|
+
wrapTools(tools) {
|
|
1952
|
+
return tools.map((tool) => this.wrapTool(tool));
|
|
1058
1953
|
}
|
|
1059
1954
|
};
|
|
1060
1955
|
|
|
1956
|
+
// src/telemetry/TelemetryTransport.ts
|
|
1957
|
+
var BaseTelemetryTransport = class {
|
|
1958
|
+
};
|
|
1959
|
+
|
|
1061
1960
|
// src/utils/jsonSchema.ts
|
|
1062
|
-
import { z } from "zod";
|
|
1961
|
+
import { z as z4 } from "zod";
|
|
1063
1962
|
function jsonSchemaPropertiesToTSTypes(value) {
|
|
1064
1963
|
if (!value.type) {
|
|
1065
|
-
return
|
|
1964
|
+
return z4.object({});
|
|
1066
1965
|
}
|
|
1067
1966
|
let zodType;
|
|
1068
1967
|
switch (value.type) {
|
|
1069
1968
|
case "string":
|
|
1070
|
-
zodType =
|
|
1969
|
+
zodType = z4.string().describe(
|
|
1071
1970
|
(value.description || "") + (value.examples ? `
|
|
1072
1971
|
Examples: ${value.examples.join(", ")}` : "")
|
|
1073
1972
|
);
|
|
1074
1973
|
break;
|
|
1075
1974
|
case "number":
|
|
1076
|
-
zodType =
|
|
1975
|
+
zodType = z4.number().describe(
|
|
1077
1976
|
(value.description || "") + (value.examples ? `
|
|
1078
1977
|
Examples: ${value.examples.join(", ")}` : "")
|
|
1079
1978
|
);
|
|
1080
1979
|
break;
|
|
1081
1980
|
case "integer":
|
|
1082
|
-
zodType =
|
|
1981
|
+
zodType = z4.number().int().describe(
|
|
1083
1982
|
(value.description || "") + (value.examples ? `
|
|
1084
1983
|
Examples: ${value.examples.join(", ")}` : "")
|
|
1085
1984
|
);
|
|
1086
1985
|
break;
|
|
1087
1986
|
case "boolean":
|
|
1088
|
-
zodType =
|
|
1987
|
+
zodType = z4.boolean().describe(
|
|
1089
1988
|
(value.description || "") + (value.examples ? `
|
|
1090
1989
|
Examples: ${value.examples.join(", ")}` : "")
|
|
1091
1990
|
);
|
|
1092
1991
|
break;
|
|
1093
1992
|
case "array":
|
|
1094
|
-
zodType =
|
|
1993
|
+
zodType = z4.array(
|
|
1095
1994
|
jsonSchemaPropertiesToTSTypes(
|
|
1096
1995
|
value.items
|
|
1097
1996
|
)
|
|
@@ -1107,7 +2006,7 @@ Examples: ${value.examples.join(", ")}` : "")
|
|
|
1107
2006
|
);
|
|
1108
2007
|
break;
|
|
1109
2008
|
case "null":
|
|
1110
|
-
zodType =
|
|
2009
|
+
zodType = z4.null().describe(value.description || "");
|
|
1111
2010
|
break;
|
|
1112
2011
|
default:
|
|
1113
2012
|
throw new Error(`Unsupported JSON schema type: ${value.type}`);
|
|
@@ -1118,7 +2017,7 @@ function jsonSchemaToModel(jsonSchema) {
|
|
|
1118
2017
|
const properties = jsonSchema.properties;
|
|
1119
2018
|
const requiredFields = jsonSchema.required || [];
|
|
1120
2019
|
if (!properties) {
|
|
1121
|
-
return
|
|
2020
|
+
return z4.object({});
|
|
1122
2021
|
}
|
|
1123
2022
|
const zodSchema = {};
|
|
1124
2023
|
for (const [key, _] of Object.entries(properties)) {
|
|
@@ -1130,7 +2029,7 @@ function jsonSchemaToModel(jsonSchema) {
|
|
|
1130
2029
|
schema
|
|
1131
2030
|
)
|
|
1132
2031
|
);
|
|
1133
|
-
zodType =
|
|
2032
|
+
zodType = z4.union(anyOfTypes).describe(
|
|
1134
2033
|
(value.description || "") + (value.examples ? `
|
|
1135
2034
|
Examples: ${value.examples.join(", ")}` : "")
|
|
1136
2035
|
);
|
|
@@ -1140,7 +2039,7 @@ Examples: ${value.examples.join(", ")}` : "")
|
|
|
1140
2039
|
schema
|
|
1141
2040
|
)
|
|
1142
2041
|
);
|
|
1143
|
-
zodType =
|
|
2042
|
+
zodType = z4.intersection(
|
|
1144
2043
|
allOfTypes[0],
|
|
1145
2044
|
allOfTypes.slice(1).reduce((acc, schema) => acc.and(schema), allOfTypes[0])
|
|
1146
2045
|
).describe(
|
|
@@ -1164,206 +2063,15 @@ Examples: ${value.examples.join(", ")}` : "")
|
|
|
1164
2063
|
zodSchema[key] = zodType.optional();
|
|
1165
2064
|
}
|
|
1166
2065
|
}
|
|
1167
|
-
return
|
|
2066
|
+
return z4.object(zodSchema);
|
|
1168
2067
|
}
|
|
1169
|
-
|
|
1170
|
-
// src/telemetry/TelemetryTransport.ts
|
|
1171
|
-
var BaseTelemetryTransport = class {
|
|
1172
|
-
};
|
|
1173
|
-
|
|
1174
|
-
// src/toolset/OpenAIToolset.ts
|
|
1175
|
-
var OpenAIToolset = class extends BaseComposioToolset {
|
|
1176
|
-
static FRAMEWORK_NAME = "openai";
|
|
1177
|
-
FILE_NAME = "toolsets/openai/src/index.ts";
|
|
1178
|
-
/**
|
|
1179
|
-
* Absract method to wrap a tool in the toolset.
|
|
1180
|
-
* This method is implemented by the toolset.
|
|
1181
|
-
* @param tool - The tool to wrap.
|
|
1182
|
-
* @returns The wrapped tool.
|
|
1183
|
-
*/
|
|
1184
|
-
_wrapTool = (tool) => {
|
|
1185
|
-
const formattedSchema = {
|
|
1186
|
-
name: tool.slug,
|
|
1187
|
-
description: tool.description,
|
|
1188
|
-
parameters: tool.input_parameters
|
|
1189
|
-
};
|
|
1190
|
-
return {
|
|
1191
|
-
type: "function",
|
|
1192
|
-
function: formattedSchema
|
|
1193
|
-
};
|
|
1194
|
-
};
|
|
1195
|
-
/**
|
|
1196
|
-
* Get all the tools from the Composio in OpenAI format.
|
|
1197
|
-
* @param params - The parameters for the tool list.
|
|
1198
|
-
* @returns The tools.
|
|
1199
|
-
*/
|
|
1200
|
-
async getTools(params) {
|
|
1201
|
-
const tools = await this.client?.tools.list(params);
|
|
1202
|
-
return tools?.items.map((tool) => this._wrapTool(tool)) ?? [];
|
|
1203
|
-
}
|
|
1204
|
-
/**
|
|
1205
|
-
* Execute a tool call.
|
|
1206
|
-
* @param {OpenAI.ChatCompletionMessageToolCall} tool - The tool to execute.
|
|
1207
|
-
* @param {string} userId - The user id.
|
|
1208
|
-
* @returns {Promise<string>} The result of the tool call.
|
|
1209
|
-
*/
|
|
1210
|
-
async executeToolCall(tool, userId) {
|
|
1211
|
-
if (!this.client) {
|
|
1212
|
-
throw new Error("Client not set");
|
|
1213
|
-
}
|
|
1214
|
-
const toolSchema = await this.client.tools.get(tool.function.name);
|
|
1215
|
-
const appName = toolSchema?.toolkit?.name.toLowerCase();
|
|
1216
|
-
const connectedAccountId = this.client.getConnectedAccountId(appName);
|
|
1217
|
-
const payload = {
|
|
1218
|
-
entity_id: userId ?? this.client.userId,
|
|
1219
|
-
connected_account_id: connectedAccountId,
|
|
1220
|
-
arguments: JSON.parse(tool.function.arguments)
|
|
1221
|
-
};
|
|
1222
|
-
const results = await this.client.tools.execute(toolSchema.slug, payload);
|
|
1223
|
-
return JSON.stringify(results);
|
|
1224
|
-
}
|
|
1225
|
-
/**
|
|
1226
|
-
* Handle the tool call from the assistant.
|
|
1227
|
-
*
|
|
1228
|
-
* @param {OpenAI.ChatCompletion} chatCompletion - The chat completion object.
|
|
1229
|
-
* @param {string} userId - The user id.
|
|
1230
|
-
* @returns {Promise<string[]>} The results of the tool call.
|
|
1231
|
-
*/
|
|
1232
|
-
async handleToolCall(chatCompletion, userId) {
|
|
1233
|
-
const outputs = [];
|
|
1234
|
-
for (const message of chatCompletion.choices) {
|
|
1235
|
-
if (message.message.tool_calls) {
|
|
1236
|
-
outputs.push(
|
|
1237
|
-
await this.executeToolCall(message.message.tool_calls[0], userId)
|
|
1238
|
-
);
|
|
1239
|
-
}
|
|
1240
|
-
}
|
|
1241
|
-
return outputs;
|
|
1242
|
-
}
|
|
1243
|
-
/**
|
|
1244
|
-
* Handles all the tool calls from the assistant.
|
|
1245
|
-
*
|
|
1246
|
-
* @param {OpenAI.Beta.Threads.Run} run - The run object.
|
|
1247
|
-
* @param {string} userId - The user id.
|
|
1248
|
-
* @returns {Promise<OpenAI.Beta.Threads.Runs.RunSubmitToolOutputsParams.ToolOutput[]>} The tool outputs.
|
|
1249
|
-
*/
|
|
1250
|
-
async handleAssistantMessage(run, userId) {
|
|
1251
|
-
const tool_calls = run.required_action?.submit_tool_outputs?.tool_calls || [];
|
|
1252
|
-
const tool_outputs = await Promise.all(
|
|
1253
|
-
tool_calls.map(async (tool_call) => {
|
|
1254
|
-
logger_default.debug(`Executing tool call: ${tool_call.id}`);
|
|
1255
|
-
const tool_response = await this.executeToolCall(
|
|
1256
|
-
tool_call,
|
|
1257
|
-
userId
|
|
1258
|
-
);
|
|
1259
|
-
logger_default.debug(`Tool call ${tool_call.id} executed with response: ${tool_response}`);
|
|
1260
|
-
return {
|
|
1261
|
-
tool_call_id: tool_call.id,
|
|
1262
|
-
output: JSON.stringify(tool_response)
|
|
1263
|
-
};
|
|
1264
|
-
})
|
|
1265
|
-
);
|
|
1266
|
-
return tool_outputs;
|
|
1267
|
-
}
|
|
1268
|
-
/**
|
|
1269
|
-
* Waits for the assistant stream and handles the tool calls.
|
|
1270
|
-
*
|
|
1271
|
-
* @param {OpenAI} client - The OpenAI client.
|
|
1272
|
-
* @param {Stream<OpenAI.Beta.Assistants.AssistantStreamEvent>} runStream - The run stream.
|
|
1273
|
-
* @param {OpenAI.Beta.Threads.Thread} thread - The thread object.
|
|
1274
|
-
* @param {string} userId - The user id.
|
|
1275
|
-
* @returns {AsyncGenerator<OpenAI.Beta.Assistants.AssistantStreamEvent, void, unknown>} The run stream.
|
|
1276
|
-
*/
|
|
1277
|
-
async *waitAndHandleAssistantStreamToolCalls(client, runStream, thread, userId) {
|
|
1278
|
-
const defaultUserId = this.client?.userId;
|
|
1279
|
-
let runId = null;
|
|
1280
|
-
for await (const event of runStream) {
|
|
1281
|
-
yield event;
|
|
1282
|
-
if (event.event === "thread.run.created") {
|
|
1283
|
-
const { id } = event.data;
|
|
1284
|
-
runId = id;
|
|
1285
|
-
}
|
|
1286
|
-
if (!runId) {
|
|
1287
|
-
continue;
|
|
1288
|
-
}
|
|
1289
|
-
if (event.event === "thread.run.requires_action") {
|
|
1290
|
-
const toolOutputs = await this.handleAssistantMessage(
|
|
1291
|
-
event.data,
|
|
1292
|
-
userId ?? defaultUserId
|
|
1293
|
-
);
|
|
1294
|
-
await client.beta.threads.runs.submitToolOutputs(thread.id, runId, {
|
|
1295
|
-
tool_outputs: toolOutputs
|
|
1296
|
-
});
|
|
1297
|
-
}
|
|
1298
|
-
if ([
|
|
1299
|
-
"thread.run.completed",
|
|
1300
|
-
"thread.run.failed",
|
|
1301
|
-
"thread.run.cancelled",
|
|
1302
|
-
"thread.run.expired"
|
|
1303
|
-
].includes(event.event)) {
|
|
1304
|
-
break;
|
|
1305
|
-
}
|
|
1306
|
-
}
|
|
1307
|
-
if (!runId) {
|
|
1308
|
-
throw new Error("No run ID found");
|
|
1309
|
-
}
|
|
1310
|
-
let finalRun = await client.beta.threads.runs.retrieve(thread.id, runId);
|
|
1311
|
-
while (["queued", "in_progress", "requires_action"].includes(finalRun.status)) {
|
|
1312
|
-
if (finalRun.status === "requires_action") {
|
|
1313
|
-
const toolOutputs = await this.handleAssistantMessage(
|
|
1314
|
-
finalRun,
|
|
1315
|
-
userId ?? defaultUserId
|
|
1316
|
-
);
|
|
1317
|
-
finalRun = await client.beta.threads.runs.submitToolOutputs(
|
|
1318
|
-
thread.id,
|
|
1319
|
-
runId,
|
|
1320
|
-
{
|
|
1321
|
-
tool_outputs: toolOutputs
|
|
1322
|
-
}
|
|
1323
|
-
);
|
|
1324
|
-
} else {
|
|
1325
|
-
finalRun = await client.beta.threads.runs.retrieve(thread.id, runId);
|
|
1326
|
-
await new Promise((resolve) => setTimeout(resolve, 500));
|
|
1327
|
-
}
|
|
1328
|
-
}
|
|
1329
|
-
}
|
|
1330
|
-
/**
|
|
1331
|
-
* Waits for the assistant tool calls and handles them.
|
|
1332
|
-
*
|
|
1333
|
-
* @param {OpenAI} client - The OpenAI client.
|
|
1334
|
-
* @param {OpenAI.Beta.Threads.Run} run - The run object.
|
|
1335
|
-
* @param {OpenAI.Beta.Threads.Thread} thread - The thread object.
|
|
1336
|
-
* @param {string} userId - The user id.
|
|
1337
|
-
* @returns {Promise<OpenAI.Beta.Threads.Run>} The run object.
|
|
1338
|
-
*/
|
|
1339
|
-
async waitAndHandleAssistantToolCalls(client, run, thread, userId) {
|
|
1340
|
-
const defaultUserId = this.client?.userId;
|
|
1341
|
-
while (["queued", "in_progress", "requires_action"].includes(run.status)) {
|
|
1342
|
-
const tool_outputs = await this.handleAssistantMessage(
|
|
1343
|
-
run,
|
|
1344
|
-
userId ?? defaultUserId
|
|
1345
|
-
);
|
|
1346
|
-
if (run.status === "requires_action") {
|
|
1347
|
-
run = await client.beta.threads.runs.submitToolOutputs(
|
|
1348
|
-
thread.id,
|
|
1349
|
-
run.id,
|
|
1350
|
-
{
|
|
1351
|
-
tool_outputs
|
|
1352
|
-
}
|
|
1353
|
-
);
|
|
1354
|
-
} else {
|
|
1355
|
-
run = await client.beta.threads.runs.retrieve(thread.id, run.id);
|
|
1356
|
-
await new Promise((resolve) => setTimeout(resolve, 500));
|
|
1357
|
-
}
|
|
1358
|
-
}
|
|
1359
|
-
return run;
|
|
1360
|
-
}
|
|
1361
|
-
};
|
|
1362
2068
|
export {
|
|
1363
|
-
|
|
2069
|
+
BaseAgenticToolset,
|
|
2070
|
+
BaseNonAgenticToolset,
|
|
1364
2071
|
BaseTelemetryTransport,
|
|
1365
2072
|
Composio,
|
|
1366
2073
|
ComposioToolset,
|
|
1367
2074
|
OpenAIToolset,
|
|
2075
|
+
ToolListParamsSchema,
|
|
1368
2076
|
jsonSchemaToModel
|
|
1369
2077
|
};
|