@composio/core 0.11.0 → 0.13.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.
Files changed (193) hide show
  1. package/dist/BaseProvider-BBnsv9kS.d.mts +29425 -0
  2. package/dist/{BaseProvider-CVbQxTNa.d.cts → BaseProvider-Brb3o86-.d.mts} +91 -44
  3. package/dist/CustomTool-D9qwyMrv.mjs +468 -0
  4. package/dist/{CustomTool-C-IUByoU.d.cts → CustomTool-Dmi6ti3I.d.mts} +2 -4
  5. package/dist/{CustomTool-CChQSp44.d.mts → CustomTool-DrJpOhY2.d.mts} +2 -4
  6. package/dist/{FileModifierErrors-C7z16Dfi.mjs → FileModifierErrors-3fSwIWoa.mjs} +35 -36
  7. package/dist/{Telemetry-DQax33Gh.mjs → Telemetry-DhGI_J4G.mjs} +15 -15
  8. package/dist/{composio-pcA13w87.d.cts → composio-DHIKRdeG.d.mts} +641 -380
  9. package/dist/{composio-BlASKqjQ.d.mts → composio-vMwhASRc.d.mts} +1390 -1129
  10. package/dist/{customTool.types-QtkAZQma.d.cts → customTool.types-CKH2R2ia.d.mts} +487 -189
  11. package/dist/{customTool.types-DLIORcYN.d.mts → customTool.types-DXin7Cfc.d.mts} +924 -626
  12. package/dist/docs/error-consistency.md +97 -0
  13. package/dist/docs/reference/sdk-reference/typescript/auth-configs.mdx +306 -0
  14. package/dist/docs/reference/sdk-reference/typescript/composio.mdx +205 -0
  15. package/dist/docs/reference/sdk-reference/typescript/connected-accounts.mdx +488 -0
  16. package/dist/docs/reference/sdk-reference/typescript/experimental.mdx +94 -0
  17. package/dist/docs/reference/sdk-reference/typescript/index.mdx +67 -0
  18. package/dist/docs/reference/sdk-reference/typescript/mcp.mdx +304 -0
  19. package/dist/docs/reference/sdk-reference/typescript/meta.json +17 -0
  20. package/dist/docs/reference/sdk-reference/typescript/remote-file.mdx +107 -0
  21. package/dist/docs/reference/sdk-reference/typescript/session-files.mdx +163 -0
  22. package/dist/docs/reference/sdk-reference/typescript/session.mdx +229 -0
  23. package/dist/docs/reference/sdk-reference/typescript/sessions.mdx +131 -0
  24. package/dist/docs/reference/sdk-reference/typescript/toolkits.mdx +169 -0
  25. package/dist/docs/reference/sdk-reference/typescript/tools.mdx +453 -0
  26. package/dist/docs/reference/sdk-reference/typescript/triggers.mdx +434 -0
  27. package/dist/{CustomTool-D5s-aADw.mjs → errors-DSIlYfl5.mjs} +72 -459
  28. package/dist/experimental/index.d.mts +2 -3
  29. package/dist/experimental/index.mjs +1 -3
  30. package/dist/{fileUtils.node-Dq7ebZPC.mjs → fileUtils.node-BiO1JQsJ.mjs} +26 -25
  31. package/dist/index.d.mts +1708 -2400
  32. package/dist/index.mjs +2632 -2006
  33. package/dist/jsonSchema-CFKdONpP.mjs +251 -0
  34. package/dist/models/Files.node.d.mts +1 -2
  35. package/dist/models/Files.node.mjs +3 -4
  36. package/dist/models/Files.workerd.d.mts +0 -1
  37. package/dist/platform/node.d.mts +1 -2
  38. package/dist/platform/workerd.d.mts +1 -2
  39. package/dist/{chunk-CWQeghP5.mjs → rolldown-runtime-w6R9maHv.mjs} +3 -5
  40. package/dist/{types-J2KCXP8R.d.mts → types-D4Id3wXA.d.mts} +2 -3
  41. package/dist/{types-DRG5qLxI.d.cts → types-qTbYYBJw.d.mts} +2 -3
  42. package/dist/utils/config-defaults/ConfigDefaults.node.d.mts +1 -4
  43. package/dist/utils/config-defaults/ConfigDefaults.workerd.d.mts +1 -4
  44. package/dist/utils/config-defaults/ConfigDefaults.workerd.mjs +3 -0
  45. package/dist/utils/json-schema.d.mts +2 -0
  46. package/dist/utils/json-schema.mjs +3 -0
  47. package/dist/utils/modifiers/FileToolModifier.node.d.mts +3 -1
  48. package/dist/utils/modifiers/FileToolModifier.node.mjs +44 -24
  49. package/dist/utils/modifiers/FileToolModifier.workerd.d.mts +3 -1
  50. package/dist/utils/modifiers/FileToolModifier.workerd.mjs +1 -1
  51. package/docs/error-consistency.md +97 -0
  52. package/package.json +40 -88
  53. package/src/composio.ts +509 -0
  54. package/src/errors/AuthConfigErrors.ts +23 -0
  55. package/src/errors/ComposioError.ts +408 -0
  56. package/src/errors/ConnectedAccountsErrors.ts +158 -0
  57. package/src/errors/ConnectionRequestErrors.ts +32 -0
  58. package/src/errors/FileModifierErrors.ts +100 -0
  59. package/src/errors/PusherErrors.ts +28 -0
  60. package/src/errors/RemoteFileErrors.ts +62 -0
  61. package/src/errors/SDKErrors.ts +92 -0
  62. package/src/errors/ToolErrors.ts +244 -0
  63. package/src/errors/ToolkitErrors.ts +39 -0
  64. package/src/errors/TriggerErrors.ts +120 -0
  65. package/src/errors/ValidationErrors.ts +99 -0
  66. package/src/errors/index.ts +41 -0
  67. package/src/experimental/index.ts +28 -0
  68. package/src/index.ts +64 -0
  69. package/src/lib/toolRouterConstants.ts +1 -0
  70. package/src/lib/toolRouterParams.ts +306 -0
  71. package/src/models/AuthConfigs.ts +398 -0
  72. package/src/models/AuthScheme.ts +206 -0
  73. package/src/models/ConnectedAccounts.ts +735 -0
  74. package/src/models/ConnectionRequest.ts +150 -0
  75. package/src/models/CustomTool.ts +676 -0
  76. package/src/models/Experimental.ts +202 -0
  77. package/src/models/Files.node.ts +93 -0
  78. package/src/models/Files.workerd.ts +49 -0
  79. package/src/models/MCP.ts +478 -0
  80. package/src/models/RemoteFile.ts +172 -0
  81. package/src/models/SessionContext.ts +147 -0
  82. package/src/models/Sessions.ts +21 -0
  83. package/src/models/ToolRouter.ts +391 -0
  84. package/src/models/ToolRouterSession.ts +827 -0
  85. package/src/models/ToolRouterSessionFileMount.ts +389 -0
  86. package/src/models/Toolkits.ts +412 -0
  87. package/src/models/Tools.ts +1260 -0
  88. package/src/models/Triggers.ts +1381 -0
  89. package/src/models/customToolExecution.ts +118 -0
  90. package/src/models/inlineCustomToolsPayload.ts +17 -0
  91. package/src/models/proxyParamsTransform.ts +26 -0
  92. package/src/provider/BaseProvider.ts +138 -0
  93. package/src/provider/ComposioProvider.ts +29 -0
  94. package/src/provider/OpenAIProvider.ts +547 -0
  95. package/src/services/internal/InternalService.ts +50 -0
  96. package/src/services/internal/InternalService.types.ts +14 -0
  97. package/src/services/pusher/Pusher.ts +230 -0
  98. package/src/services/telemetry/TelemetryService.ts +48 -0
  99. package/src/services/telemetry/TelemetryService.types.ts +67 -0
  100. package/src/telemetry/BatchProcessor.ts +77 -0
  101. package/src/telemetry/README.md +123 -0
  102. package/src/telemetry/Telemetry.ts +356 -0
  103. package/src/types/ToolRouterSessionFilesMount.types.ts +96 -0
  104. package/src/types/authConfigs.types.ts +174 -0
  105. package/src/types/composio.types.ts +1 -0
  106. package/src/types/connectedAccountAuthStates.types.ts +852 -0
  107. package/src/types/connectedAccounts.types.ts +395 -0
  108. package/src/types/connectionRequest.types.ts +16 -0
  109. package/src/types/customTool.types.ts +261 -0
  110. package/{dist/files.types-lo4zZd87.d.cts → src/types/files.types.ts} +3 -5
  111. package/src/types/mcp.experimental.types.ts +163 -0
  112. package/src/types/mcp.types.ts +362 -0
  113. package/src/types/modifiers.types.ts +663 -0
  114. package/src/types/org.types.ts +0 -0
  115. package/src/types/provider.types.ts +41 -0
  116. package/src/types/pusher.types.ts +18 -0
  117. package/src/types/requestOptions.types.ts +62 -0
  118. package/src/types/telemetry.types.ts +89 -0
  119. package/src/types/tool.types.ts +408 -0
  120. package/src/types/toolRouter.types.ts +761 -0
  121. package/src/types/toolkit.types.ts +130 -0
  122. package/src/types/triggers.types.ts +401 -0
  123. package/src/types/webhookEvents.types.ts +219 -0
  124. package/src/utils/buffer.ts +30 -0
  125. package/src/utils/cancellation.ts +22 -0
  126. package/src/utils/config-defaults/ConfigDefaults.node.ts +7 -0
  127. package/src/utils/config-defaults/ConfigDefaults.workerd.ts +10 -0
  128. package/src/utils/config-defaults/index.ts +1 -0
  129. package/src/utils/config-defaults/types.ts +14 -0
  130. package/src/utils/constants.ts +22 -0
  131. package/src/utils/crypto.ts +34 -0
  132. package/src/utils/env.ts +34 -0
  133. package/src/utils/fileDirs.ts +81 -0
  134. package/src/utils/fileUtils.node.ts +458 -0
  135. package/src/utils/json-schema.ts +1 -0
  136. package/src/utils/jsonSchema.ts +355 -0
  137. package/src/utils/logger.ts +99 -0
  138. package/src/utils/mime.ts +75 -0
  139. package/src/utils/modifiers/FileToolModifier.node.ts +477 -0
  140. package/src/utils/modifiers/FileToolModifier.utils.neutral.ts +132 -0
  141. package/src/utils/modifiers/FileToolModifier.workerd.ts +51 -0
  142. package/src/utils/pagination.ts +73 -0
  143. package/src/utils/pusher.ts +286 -0
  144. package/src/utils/schemaPropertyKeys.ts +433 -0
  145. package/src/utils/sdk.ts +110 -0
  146. package/src/utils/sensitiveFileUploadPaths.node.ts +105 -0
  147. package/src/utils/session.ts +114 -0
  148. package/src/utils/toolArguments.ts +73 -0
  149. package/src/utils/toolkitVersion.ts +26 -0
  150. package/src/utils/transform.ts +42 -0
  151. package/src/utils/transformers/authConfigs.ts +107 -0
  152. package/src/utils/transformers/connectedAccounts.ts +119 -0
  153. package/src/utils/transformers/mcp.ts +164 -0
  154. package/src/utils/transformers/toolRouterResponseTransform.ts +160 -0
  155. package/src/utils/transformers/toolkits.ts +100 -0
  156. package/src/utils/transformers/triggers.ts +118 -0
  157. package/src/utils/uploadDirAllowlist.node.ts +178 -0
  158. package/src/utils/uuid.ts +7 -0
  159. package/src/utils/version.ts +58 -0
  160. package/src/utils/zodSchema.ts +90 -0
  161. package/dist/BaseProvider-BvHvJLXc.d.mts +0 -29378
  162. package/dist/CustomTool-D3-NreIm.cjs +0 -1341
  163. package/dist/FileModifierErrors-BYJBHiay.cjs +0 -554
  164. package/dist/FileToolModifier.utils.neutral-DSBQs9-i.cjs +0 -96
  165. package/dist/Telemetry-BQ_pl5AK.cjs +0 -360
  166. package/dist/buffer-BjWptbNH.cjs +0 -63
  167. package/dist/chunk-CQwRTUmo.cjs +0 -53
  168. package/dist/experimental/index.cjs +0 -5
  169. package/dist/experimental/index.d.cts +0 -3
  170. package/dist/fileUtils.node-DtnSRMWa.cjs +0 -462
  171. package/dist/index.cjs +0 -8523
  172. package/dist/index.d.cts +0 -6065
  173. package/dist/models/Files.node.cjs +0 -55
  174. package/dist/models/Files.node.d.cts +0 -56
  175. package/dist/models/Files.workerd.cjs +0 -29
  176. package/dist/models/Files.workerd.d.cts +0 -13
  177. package/dist/platform/node.cjs +0 -55
  178. package/dist/platform/node.d.cts +0 -11
  179. package/dist/platform/workerd.cjs +0 -42
  180. package/dist/platform/workerd.d.cts +0 -12
  181. package/dist/types-pDNm1lYs.d.cts +0 -69
  182. package/dist/utils/config-defaults/ConfigDefaults.node.cjs +0 -10
  183. package/dist/utils/config-defaults/ConfigDefaults.node.d.cts +0 -7
  184. package/dist/utils/config-defaults/ConfigDefaults.workerd.cjs +0 -10
  185. package/dist/utils/config-defaults/ConfigDefaults.workerd.d.cts +0 -7
  186. package/dist/utils/modifiers/FileToolModifier.node.cjs +0 -224
  187. package/dist/utils/modifiers/FileToolModifier.node.d.cts +0 -22
  188. package/dist/utils/modifiers/FileToolModifier.workerd.cjs +0 -27
  189. package/dist/utils/modifiers/FileToolModifier.workerd.d.cts +0 -20
  190. /package/dist/{FileToolModifier.utils.neutral-BpSceNK8.mjs → FileToolModifier.utils.neutral-B5rT711M.mjs} +0 -0
  191. /package/dist/{buffer-yOtEsT4J.mjs → buffer-PcbMMsgm.mjs} +0 -0
  192. /package/dist/{files.types-BXDWA_zS.d.mts → files.types-DeMC_mAW.d.mts} +0 -0
  193. /package/dist/{types-HpJQ8K9l.d.mts → types-DdoCRzLj.d.mts} +0 -0
@@ -0,0 +1,547 @@
1
+ /**
2
+ * OpenAI ToolSet
3
+ *
4
+ * Author: Musthaq Ahamad <musthaq@composio.dev>
5
+ * Legacy Reference: https://github.com/ComposioHQ/composio/blob/master/js/src/toolsets/openai.ts
6
+ *
7
+ * This is a default provider for Composio SDK.
8
+ * This will be shipped with the SDK and users don't need to install it separately.
9
+ */
10
+ import { OpenAI } from 'openai';
11
+ import { Stream } from 'openai/streaming';
12
+ import { BaseNonAgenticProvider } from './BaseProvider';
13
+ import { Tool, ToolExecuteParams } from '../types/tool.types';
14
+ import logger from '../utils/logger';
15
+ import { ExecuteToolModifiers } from '../types/modifiers.types';
16
+ import { ExecuteToolFnOptions } from '../types/provider.types';
17
+ import { McpUrlResponse, McpServerGetResponse } from '../types/mcp.types';
18
+ import { normalizeToolArguments } from '../utils/toolArguments';
19
+
20
+ export type OpenAiTool = OpenAI.ChatCompletionTool;
21
+ export type OpenAiToolCollection = Array<OpenAiTool>;
22
+
23
+ export class OpenAIProvider extends BaseNonAgenticProvider<
24
+ OpenAiToolCollection,
25
+ OpenAiTool,
26
+ McpServerGetResponse
27
+ > {
28
+ readonly name = 'openai';
29
+
30
+ /**
31
+ * Creates a new instance of the OpenAIProvider.
32
+ *
33
+ * This is the default provider for the Composio SDK and is automatically
34
+ * available without additional installation.
35
+ *
36
+ * @example
37
+ * ```typescript
38
+ * // The OpenAIProvider is used by default when initializing Composio
39
+ * const composio = new Composio({
40
+ * apiKey: 'your-api-key'
41
+ * });
42
+ *
43
+ * // You can also explicitly specify it
44
+ * const composio = new Composio({
45
+ * apiKey: 'your-api-key',
46
+ * provider: new OpenAIProvider()
47
+ * });
48
+ * ```
49
+ */
50
+ constructor() {
51
+ super();
52
+ }
53
+
54
+ /**
55
+ * Transform MCP URL response into OpenAI-specific format.
56
+ * OpenAI uses the standard format by default.
57
+ *
58
+ * @param data - The MCP URL response data
59
+ * @returns Standard MCP server response format
60
+ */
61
+ override wrapMcpServerResponse(data: McpUrlResponse): McpServerGetResponse {
62
+ return data.map(item => ({
63
+ url: new URL(item.url),
64
+ name: item.name,
65
+ }));
66
+ }
67
+
68
+ /**
69
+ * Wraps a Composio tool in the OpenAI function calling format.
70
+ *
71
+ * This method transforms a Composio tool definition into the format
72
+ * expected by OpenAI's function calling API.
73
+ *
74
+ * @param tool - The Composio tool to wrap
75
+ * @returns The wrapped tool in OpenAI format
76
+ *
77
+ * @example
78
+ * ```typescript
79
+ * // Wrap a single tool for use with OpenAI
80
+ * const composioTool = {
81
+ * slug: 'SEARCH_TOOL',
82
+ * description: 'Search for information',
83
+ * inputParameters: {
84
+ * type: 'object',
85
+ * properties: {
86
+ * query: { type: 'string' }
87
+ * },
88
+ * required: ['query']
89
+ * }
90
+ * };
91
+ *
92
+ * const openAITool = provider.wrapTool(composioTool);
93
+ * ```
94
+ */
95
+ override wrapTool = (tool: Tool): OpenAiTool => {
96
+ const formattedSchema: OpenAI.FunctionDefinition = {
97
+ name: tool.slug,
98
+ description: tool.description,
99
+ parameters: tool.inputParameters,
100
+ };
101
+ return {
102
+ type: 'function',
103
+ function: formattedSchema,
104
+ };
105
+ };
106
+
107
+ /**
108
+ * Wraps multiple Composio tools in the OpenAI function calling format.
109
+ *
110
+ * This method transforms a list of Composio tools into the format
111
+ * expected by OpenAI's function calling API.
112
+ *
113
+ * @param tools - Array of Composio tools to wrap
114
+ * @returns Array of wrapped tools in OpenAI format
115
+ *
116
+ * @example
117
+ * ```typescript
118
+ * // Wrap multiple tools for use with OpenAI
119
+ * const composioTools = [
120
+ * {
121
+ * slug: 'SEARCH_TOOL',
122
+ * description: 'Search for information',
123
+ * inputParameters: {
124
+ * type: 'object',
125
+ * properties: {
126
+ * query: { type: 'string' }
127
+ * }
128
+ * }
129
+ * },
130
+ * {
131
+ * slug: 'WEATHER_TOOL',
132
+ * description: 'Get weather information',
133
+ * inputParameters: {
134
+ * type: 'object',
135
+ * properties: {
136
+ * location: { type: 'string' }
137
+ * }
138
+ * }
139
+ * }
140
+ * ];
141
+ *
142
+ * const openAITools = provider.wrapTools(composioTools);
143
+ * ```
144
+ */
145
+ override wrapTools = (tools: Tool[]): OpenAiToolCollection => {
146
+ return tools.map(tool => this.wrapTool(tool));
147
+ };
148
+
149
+ /**
150
+ * Executes a tool call from OpenAI's chat completion.
151
+ *
152
+ * This method processes a tool call from OpenAI's chat completion API,
153
+ * executes the corresponding Composio tool, and returns the result.
154
+ *
155
+ * @param {string} userId - The user ID for authentication and tracking
156
+ * @param {OpenAI.ChatCompletionMessageToolCall} tool - The tool call from OpenAI
157
+ * @param {ExecuteToolFnOptions} [options] - Optional execution options
158
+ * @param {ExecuteToolModifiers} [modifiers] - Optional execution modifiers
159
+ * @returns {Promise<string>} The result of the tool call as a JSON string
160
+ *
161
+ * @example
162
+ * ```typescript
163
+ * // Execute a tool call from OpenAI
164
+ * const toolCall = {
165
+ * id: 'call_abc123',
166
+ * type: 'function',
167
+ * function: {
168
+ * name: 'SEARCH_TOOL',
169
+ * arguments: '{"query":"composio documentation"}'
170
+ * }
171
+ * };
172
+ *
173
+ * const result = await provider.executeToolCall(
174
+ * 'user123',
175
+ * toolCall,
176
+ * { connectedAccountId: 'conn_xyz456' }
177
+ * );
178
+ * console.log(JSON.parse(result));
179
+ * ```
180
+ */
181
+ async executeToolCall(
182
+ userId: string,
183
+ tool: OpenAI.ChatCompletionMessageFunctionToolCall,
184
+ options?: ExecuteToolFnOptions,
185
+ modifiers?: ExecuteToolModifiers
186
+ ): Promise<string> {
187
+ const payload: ToolExecuteParams = {
188
+ // OpenAI always serializes tool arguments as a JSON string; normalize tolerates
189
+ // empty / object-shaped payloads too (issue #2406).
190
+ arguments: normalizeToolArguments(tool.function.arguments, tool.function.name),
191
+ connectedAccountId: options?.connectedAccountId,
192
+ customAuthParams: options?.customAuthParams,
193
+ customConnectionData: options?.customConnectionData,
194
+ userId: userId,
195
+ };
196
+ const result = await this.executeTool(tool.function.name, payload, modifiers);
197
+ return JSON.stringify(result);
198
+ }
199
+
200
+ /**
201
+ * Handles tool calls from OpenAI's chat completion response.
202
+ *
203
+ * This method processes tool calls from an OpenAI chat completion response,
204
+ * executes each tool call, and returns the results.
205
+ *
206
+ * @param {string} userId - The user ID for authentication and tracking
207
+ * @param {OpenAI.ChatCompletion} chatCompletion - The chat completion response from OpenAI
208
+ * @param {ExecuteToolFnOptions} [options] - Optional execution options
209
+ * @param {ExecuteToolModifiers} [modifiers] - Optional execution modifiers
210
+ * @returns {Promise<string[]>} Array of tool execution results as JSON strings
211
+ *
212
+ * @example
213
+ * ```typescript
214
+ * // Handle tool calls from a chat completion response
215
+ * const chatCompletion = {
216
+ * choices: [
217
+ * {
218
+ * message: {
219
+ * tool_calls: [
220
+ * {
221
+ * id: 'call_abc123',
222
+ * type: 'function',
223
+ * function: {
224
+ * name: 'SEARCH_TOOL',
225
+ * arguments: '{"query":"composio documentation"}'
226
+ * }
227
+ * }
228
+ * ]
229
+ * }
230
+ * }
231
+ * ]
232
+ * };
233
+ *
234
+ * const results = await provider.handleToolCalls(
235
+ * 'user123',
236
+ * chatCompletion,
237
+ * { connectedAccountId: 'conn_xyz456' }
238
+ * );
239
+ * console.log(results); // Array of tool execution results
240
+ * ```
241
+ */
242
+ async handleToolCalls(
243
+ userId: string,
244
+ chatCompletion: OpenAI.ChatCompletion,
245
+ options?: ExecuteToolFnOptions,
246
+ modifiers?: ExecuteToolModifiers
247
+ ): Promise<OpenAI.ChatCompletionToolMessageParam[]> {
248
+ const outputs: OpenAI.ChatCompletionToolMessageParam[] = [];
249
+ for (const message of chatCompletion.choices) {
250
+ if (message.message.tool_calls && message.message.tool_calls[0].type === 'function') {
251
+ const toolResult = await this.executeToolCall(
252
+ userId,
253
+ message.message.tool_calls[0],
254
+ options,
255
+ modifiers
256
+ );
257
+ outputs.push({
258
+ role: 'tool',
259
+ tool_call_id: message.message.tool_calls[0].id,
260
+ content: toolResult,
261
+ });
262
+ }
263
+ }
264
+ return outputs;
265
+ }
266
+
267
+ /**
268
+ * Handles all the tool calls from the OpenAI Assistant API.
269
+ *
270
+ * This method processes tool calls from an OpenAI Assistant run,
271
+ * executes each tool call, and returns the tool outputs for submission.
272
+ *
273
+ * @deprecated Assistant API is deprecated, please use responses or chat completions instead. This method will be removed in the next major version.
274
+ *
275
+ * @param {string} userId - The user ID for authentication and tracking
276
+ * @param {OpenAI.Beta.Threads.Run} run - The Assistant run object containing tool calls
277
+ * @param {ExecuteToolFnOptions} [options] - Optional execution options
278
+ * @param {ExecuteToolModifiers} [modifiers] - Optional execution modifiers
279
+ * @returns {Promise<OpenAI.Beta.Threads.Runs.RunSubmitToolOutputsParams.ToolOutput[]>} Array of tool outputs for submission
280
+ *
281
+ *
282
+ * @example
283
+ * ```typescript
284
+ * // Handle tool calls from an OpenAI Assistant run
285
+ * const run = {
286
+ * id: 'run_abc123',
287
+ * required_action: {
288
+ * submit_tool_outputs: {
289
+ * tool_calls: [
290
+ * {
291
+ * id: 'call_xyz789',
292
+ * type: 'function',
293
+ * function: {
294
+ * name: 'SEARCH_TOOL',
295
+ * arguments: '{"query":"composio documentation"}'
296
+ * }
297
+ * }
298
+ * ]
299
+ * }
300
+ * }
301
+ * };
302
+ *
303
+ * const toolOutputs = await provider.handleAssistantMessage(
304
+ * 'user123',
305
+ * run,
306
+ * { connectedAccountId: 'conn_xyz456' }
307
+ * );
308
+ *
309
+ * // Submit tool outputs back to OpenAI
310
+ * await openai.beta.threads.runs.submitToolOutputs(
311
+ * thread.id,
312
+ * run.id,
313
+ * { tool_outputs: toolOutputs }
314
+ * );
315
+ * ```
316
+ */
317
+ async handleAssistantMessage(
318
+ userId: string,
319
+ run: OpenAI.Beta.Threads.Run,
320
+ options?: ExecuteToolFnOptions,
321
+ modifiers?: ExecuteToolModifiers
322
+ ) {
323
+ const tool_calls = run.required_action?.submit_tool_outputs?.tool_calls || [];
324
+ const tool_outputs: Array<OpenAI.Beta.Threads.Runs.RunSubmitToolOutputsParams.ToolOutput> =
325
+ await Promise.all(
326
+ tool_calls.map(async tool_call => {
327
+ logger.debug(`Executing tool call: ${tool_call.id}`);
328
+
329
+ // Execute each tool call and get the response
330
+ const tool_response = await this.executeToolCall(
331
+ userId,
332
+ tool_call as OpenAI.ChatCompletionMessageFunctionToolCall,
333
+ options,
334
+ modifiers
335
+ );
336
+
337
+ logger.debug(`Tool call ${tool_call.id} executed with response: ${tool_response}`);
338
+
339
+ return {
340
+ tool_call_id: tool_call.id,
341
+ output: JSON.stringify(tool_response),
342
+ };
343
+ })
344
+ );
345
+ return tool_outputs;
346
+ }
347
+
348
+ /**
349
+ * Waits for the assistant stream and handles the tool calls.
350
+ *
351
+ * This method processes an OpenAI Assistant stream, handles any tool calls
352
+ * that require action, and yields each event from the stream. It's designed
353
+ * for streaming Assistant responses while handling tool calls in real-time.
354
+ *
355
+ * @deprecated Assistant API is deprecated, please use responses or chat completions instead. It will be removed in the next major version.
356
+ *
357
+ * @param {string} userId - The user ID for authentication and tracking
358
+ * @param {OpenAI} client - The OpenAI client instance
359
+ * @param {Stream<OpenAI.Beta.Assistants.AssistantStreamEvent>} runStream - The Assistant run stream
360
+ * @param {OpenAI.Beta.Threads.Thread} thread - The thread object
361
+ * @param {ExecuteToolFnOptions} [options] - Optional execution options
362
+ * @param {ExecuteToolModifiers} [modifiers] - Optional execution modifiers
363
+ * @returns {AsyncGenerator<OpenAI.Beta.Assistants.AssistantStreamEvent, void, unknown>} Generator yielding stream events
364
+ *
365
+ *
366
+ *
367
+ * @example
368
+ * ```typescript
369
+ * // Process an OpenAI Assistant stream with tool calls
370
+ * const thread = await openai.beta.threads.create();
371
+ * const runStream = openai.beta.threads.runs.stream(thread.id, {
372
+ * assistant_id: 'asst_abc123',
373
+ * tools: provider.wrapTools(composioTools)
374
+ * });
375
+ *
376
+ * // Process the stream and handle tool calls
377
+ * const streamProcessor = provider.waitAndHandleAssistantStreamToolCalls(
378
+ * 'user123',
379
+ * openai,
380
+ * runStream,
381
+ * thread,
382
+ * { connectedAccountId: 'conn_xyz456' }
383
+ * );
384
+ *
385
+ * // Consume the stream events
386
+ * for await (const event of streamProcessor) {
387
+ * if (event.event === 'thread.message.delta') {
388
+ * console.log(event.data.delta.content);
389
+ * }
390
+ * }
391
+ * ```
392
+ */
393
+ async *waitAndHandleAssistantStreamToolCalls(
394
+ userId: string,
395
+ client: OpenAI,
396
+ runStream: Stream<OpenAI.Beta.Assistants.AssistantStreamEvent>,
397
+ thread: OpenAI.Beta.Threads.Thread,
398
+ options?: ExecuteToolFnOptions,
399
+ modifiers?: ExecuteToolModifiers
400
+ ) {
401
+ // @TODO: Log the run stream
402
+ let runId = null;
403
+
404
+ // Start processing the runStream events
405
+ for await (const event of runStream) {
406
+ yield event; // Yield each event from the stream as it arrives
407
+
408
+ if (event.event === 'thread.run.created') {
409
+ const { id } = event.data;
410
+ runId = id;
411
+ }
412
+
413
+ if (!runId) {
414
+ continue;
415
+ }
416
+
417
+ // Handle the 'requires_action' event
418
+ if (event.event === 'thread.run.requires_action') {
419
+ const toolOutputs = await this.handleAssistantMessage(
420
+ userId,
421
+ event.data,
422
+ options,
423
+ modifiers
424
+ );
425
+
426
+ // Submit the tool outputs
427
+ await client.beta.threads.runs.submitToolOutputs(runId, {
428
+ thread_id: thread.id,
429
+ tool_outputs: toolOutputs,
430
+ });
431
+ }
432
+
433
+ // Break if the run status becomes inactive
434
+ if (
435
+ [
436
+ 'thread.run.completed',
437
+ 'thread.run.failed',
438
+ 'thread.run.cancelled',
439
+ 'thread.run.expired',
440
+ ].includes(event.event)
441
+ ) {
442
+ break;
443
+ }
444
+ }
445
+
446
+ if (!runId) {
447
+ throw new Error('No run ID found');
448
+ }
449
+
450
+ // Handle any final actions after the stream ends
451
+ let finalRun = await client.beta.threads.runs.retrieve(runId, {
452
+ thread_id: thread.id,
453
+ });
454
+
455
+ while (['queued', 'in_progress', 'requires_action'].includes(finalRun.status)) {
456
+ if (finalRun.status === 'requires_action') {
457
+ const toolOutputs = await this.handleAssistantMessage(userId, finalRun, options, modifiers);
458
+
459
+ // Submit tool outputs
460
+ finalRun = await client.beta.threads.runs.submitToolOutputs(runId, {
461
+ thread_id: thread.id,
462
+ tool_outputs: toolOutputs,
463
+ });
464
+ } else {
465
+ // Update the run status
466
+ finalRun = await client.beta.threads.runs.retrieve(runId, {
467
+ thread_id: thread.id,
468
+ });
469
+ await new Promise(resolve => setTimeout(resolve, 500)); // Wait before rechecking
470
+ }
471
+ }
472
+ }
473
+
474
+ /**
475
+ * Waits for the assistant tool calls and handles them.
476
+ *
477
+ * This method polls an OpenAI Assistant run until it completes or requires action,
478
+ * handles any tool calls, and returns the final run object. It's designed for
479
+ * non-streaming Assistant interactions.
480
+ *
481
+ * @deprecated Assistant API is deprecated, please use responses or chat completions instead. It will be removed in the next major version.
482
+ *
483
+ * @param {string} userId - The user ID for authentication and tracking
484
+ * @param {OpenAI} client - The OpenAI client instance
485
+ * @param {OpenAI.Beta.Threads.Run} run - The initial run object
486
+ * @param {OpenAI.Beta.Threads.Thread} thread - The thread object
487
+ * @param {ExecuteToolFnOptions} [options] - Optional execution options
488
+ * @param {ExecuteToolModifiers} [modifiers] - Optional execution modifiers
489
+ * @returns {Promise<OpenAI.Beta.Threads.Run>} The final run object after completion
490
+ *
491
+ * @example
492
+ * ```typescript
493
+ * // Process an OpenAI Assistant run with tool calls
494
+ * const thread = await openai.beta.threads.create();
495
+ * await openai.beta.threads.messages.create(thread.id, {
496
+ * role: 'user',
497
+ * content: 'Find information about Composio'
498
+ * });
499
+ *
500
+ * let run = await openai.beta.threads.runs.create(thread.id, {
501
+ * assistant_id: 'asst_abc123',
502
+ * tools: provider.wrapTools(composioTools)
503
+ * });
504
+ *
505
+ * // Wait for the run to complete, handling any tool calls
506
+ * run = await provider.waitAndHandleAssistantToolCalls(
507
+ * 'user123',
508
+ * openai,
509
+ * run,
510
+ * thread,
511
+ * { connectedAccountId: 'conn_xyz456' }
512
+ * );
513
+ *
514
+ * // Get the final messages after run completion
515
+ * const messages = await openai.beta.threads.messages.list(thread.id);
516
+ * console.log(messages.data[0].content);
517
+ * ```
518
+ */
519
+ async waitAndHandleAssistantToolCalls(
520
+ userId: string,
521
+ client: OpenAI,
522
+ run: OpenAI.Beta.Threads.Run,
523
+ thread: OpenAI.Beta.Threads.Thread,
524
+ options?: ExecuteToolFnOptions,
525
+ modifiers?: ExecuteToolModifiers
526
+ ) {
527
+ while (['queued', 'in_progress', 'requires_action'].includes(run.status)) {
528
+ // logger.debug(`Current run status: ${run.status}`);
529
+ const tool_outputs = await this.handleAssistantMessage(userId, run, options, modifiers);
530
+ if (run.status === 'requires_action') {
531
+ // logger.debug(
532
+ // `Submitting tool outputs for run ID: ${run.id} in thread ID: ${thread.id}`
533
+ // );
534
+ run = await client.beta.threads.runs.submitToolOutputs(run.id, {
535
+ thread_id: thread.id,
536
+ tool_outputs: tool_outputs,
537
+ });
538
+ } else {
539
+ run = await client.beta.threads.runs.retrieve(run.id, {
540
+ thread_id: thread.id,
541
+ });
542
+ await new Promise(resolve => setTimeout(resolve, 500));
543
+ }
544
+ }
545
+ return run;
546
+ }
547
+ }
@@ -0,0 +1,50 @@
1
+ /**
2
+ * @internal
3
+ * This service is used to get the SDK realtime credentials.
4
+ * It is used to get the Pusher key and project ID for the SDK realtime credentials.
5
+ * These are the endpoints which are not exposed to the public via the client SDKs.
6
+ */
7
+ import ComposioClitent from '@composio/client';
8
+ import {
9
+ ComposioSDKRealtimeCredentialsResponse,
10
+ SDKRealtimeCredentialsResponse,
11
+ SDKRealtimeCredentialsResponseSchema,
12
+ } from './InternalService.types';
13
+ import { ValidationError } from '../../errors';
14
+ import logger from '../../utils/logger';
15
+ const SDK_REALTIME_CREDENTIALS_ENDPOINT = '/api/v3/internal/sdk/realtime/credentials';
16
+
17
+ export class InternalService {
18
+ constructor(private readonly client: ComposioClitent) {
19
+ this.client = client;
20
+ }
21
+
22
+ /**
23
+ * Get the SDK realtime credentials
24
+ * @returns {SDKRealtimeCredentialsResponse} The SDK realtime credentials
25
+ */
26
+ async getSDKRealtimeCredentials(): Promise<SDKRealtimeCredentialsResponse> {
27
+ const response = await this.client.request<ComposioSDKRealtimeCredentialsResponse>({
28
+ method: 'get',
29
+ path: SDK_REALTIME_CREDENTIALS_ENDPOINT,
30
+ });
31
+
32
+ const parsedResponse = SDKRealtimeCredentialsResponseSchema.safeParse({
33
+ pusherKey: response.pusher_key,
34
+ projectId: response.project_id,
35
+ pusherCluster: response.pusher_cluster,
36
+ });
37
+
38
+ logger.debug(
39
+ `[InternalService] SDK realtime credentials: ${JSON.stringify(parsedResponse, null, 2)}`
40
+ );
41
+
42
+ if (!parsedResponse.success) {
43
+ throw new ValidationError(`Failed to parse SDK realtime credentials`, {
44
+ cause: parsedResponse.error,
45
+ });
46
+ }
47
+
48
+ return parsedResponse.data;
49
+ }
50
+ }
@@ -0,0 +1,14 @@
1
+ import { z } from 'zod/v3';
2
+
3
+ export interface ComposioSDKRealtimeCredentialsResponse {
4
+ pusher_key: string;
5
+ project_id: string;
6
+ pusher_cluster: string;
7
+ }
8
+
9
+ export const SDKRealtimeCredentialsResponseSchema = z.object({
10
+ projectId: z.string().describe('The project ID'),
11
+ pusherKey: z.string().describe('The Pusher key'),
12
+ pusherCluster: z.string().describe('The Pusher cluster'),
13
+ });
14
+ export type SDKRealtimeCredentialsResponse = z.infer<typeof SDKRealtimeCredentialsResponseSchema>;