@composio/core 0.21.0 → 0.23.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 (59) hide show
  1. package/dist/{CustomTool-BHOYxLZX.d.mts → CustomTool-CnHdegDK.d.mts} +1 -1
  2. package/dist/{CustomTool-B-_VjWpy.mjs → CustomTool-CnJxXr07.mjs} +1 -1
  3. package/dist/{Telemetry-JRJJYS4I.mjs → Telemetry-41JkqpZ7.mjs} +3 -2
  4. package/dist/{cancellation-DV8CIi52.mjs → cancellation-BQibgpRG.mjs} +166 -34
  5. package/dist/{composio-BTZsFajb.d.mts → composio-Dq708dZS.d.mts} +81 -185
  6. package/dist/{customTool.types-D_w21L56.d.mts → customTool.types-B8lVpHOP.d.mts} +77 -59
  7. package/dist/docs/reference/sdk-reference/typescript/logs.mdx +4 -4
  8. package/dist/docs/reference/sdk-reference/typescript/remote-file.mdx +1 -1
  9. package/dist/docs/reference/sdk-reference/typescript/session.mdx +2 -2
  10. package/dist/docs/reference/sdk-reference/typescript/tools.mdx +2 -2
  11. package/dist/docs/reference/sdk-reference/typescript/usage.mdx +2 -2
  12. package/dist/{errors-Dyiu3ifQ.mjs → errors-BN15NcCW.mjs} +34 -2
  13. package/dist/experimental/index.d.mts +2 -2
  14. package/dist/experimental/index.mjs +1 -1
  15. package/dist/index.d.mts +46 -6
  16. package/dist/index.mjs +315 -363
  17. package/dist/models/Files.node.mjs +1 -1
  18. package/dist/platform/node.d.mts +1 -1
  19. package/dist/platform/node.mjs +13 -0
  20. package/dist/platform/workerd.d.mts +1 -1
  21. package/dist/platform/workerd.mjs +3 -0
  22. package/dist/{types-D5A2wzBl.d.mts → types-DuVZKrXO.d.mts} +2 -0
  23. package/dist/{types-CgRsUGqm.d.mts → types-eTw8Yw7Y.d.mts} +2 -2
  24. package/dist/utils/config-defaults/ConfigDefaults.node.d.mts +1 -1
  25. package/dist/utils/config-defaults/ConfigDefaults.workerd.d.mts +1 -1
  26. package/dist/utils/modifiers/FileToolModifier.node.d.mts +1 -1
  27. package/dist/utils/modifiers/FileToolModifier.node.mjs +2 -2
  28. package/dist/utils/modifiers/FileToolModifier.workerd.d.mts +1 -1
  29. package/package.json +10 -7
  30. package/src/errors/ToolRouterErrors.ts +65 -0
  31. package/src/lib/toolRouterParams.ts +8 -10
  32. package/src/models/AuthConfigs.ts +0 -9
  33. package/src/models/ConnectionRequest.ts +21 -18
  34. package/src/models/CustomToolkits.ts +1 -1
  35. package/src/models/Logs.ts +2 -2
  36. package/src/models/RemoteFile.ts +24 -5
  37. package/src/models/SessionContext.ts +24 -4
  38. package/src/models/ToolRouter.ts +3 -3
  39. package/src/models/ToolRouterSession.ts +45 -13
  40. package/src/models/Tools.ts +21 -37
  41. package/src/models/Usage.ts +2 -1
  42. package/src/models/customToolExecution.ts +10 -0
  43. package/src/platform/node.ts +16 -0
  44. package/src/platform/types.ts +3 -0
  45. package/src/platform/workerd.ts +4 -0
  46. package/src/provider/BaseProvider.ts +2 -1
  47. package/src/provider/OpenAIProvider.ts +0 -283
  48. package/src/telemetry/Telemetry.ts +4 -2
  49. package/src/types/logs.types.ts +9 -1
  50. package/src/types/tool.types.ts +8 -3
  51. package/src/types/toolRouter.types.ts +27 -19
  52. package/src/types/usage.types.ts +2 -0
  53. package/src/utils/jsonSchema.ts +191 -36
  54. package/src/utils/retries.ts +20 -0
  55. package/src/utils/safePath.ts +135 -54
  56. package/src/utils/session.ts +31 -2
  57. package/src/utils/transformers/logs.ts +3 -2
  58. package/src/utils/transformers/toolRouterResponseTransform.ts +69 -12
  59. package/src/utils/transformers/usage.ts +1 -0
@@ -4,8 +4,12 @@ import type { BaseComposioProvider } from '../provider/BaseProvider';
4
4
  import type { ComposioConfig } from '../composio';
5
5
  import type { ComposioRequestOptions } from '../types/requestOptions.types';
6
6
  import { withCancellation } from '../utils/cancellation';
7
+ import { withoutRetries } from '../utils/retries';
7
8
  import { ComposioRequestCancelledError } from '../errors/SDKErrors';
8
- import { ComposioSessionConfigConflictError } from '../errors/ToolRouterErrors';
9
+ import {
10
+ ComposioSessionConfigConflictError,
11
+ ComposioToolInputRequiredError,
12
+ } from '../errors/ToolRouterErrors';
9
13
  import {
10
14
  ToolRouterMCPServerConfig,
11
15
  SessionExperimental,
@@ -33,6 +37,7 @@ import {
33
37
  type ToolRouterSessionDeleteResponse,
34
38
  } from '../types/toolRouter.types';
35
39
  import {
40
+ assertNotInputRequired,
36
41
  transformSearchResponse,
37
42
  transformExecuteResponse,
38
43
  } from '../utils/transformers/toolRouterResponseTransform';
@@ -167,7 +172,7 @@ export class ToolRouterSession<
167
172
  execute: {},
168
173
  search: {},
169
174
  preload: { tools: [] },
170
- premium_usage: false,
175
+ instant: false,
171
176
  };
172
177
  if (customToolsMap && !userId) {
173
178
  throw new Error('userId is required when custom tools are bound to a session.');
@@ -678,6 +683,7 @@ export class ToolRouterSession<
678
683
  * @param options - Optional execution options
679
684
  * @param options.account - Account identifier for direct app tool execution. Accepted on every project: in multi-account sessions it picks the account; on single-account projects it must match one of the session's active connections for the toolkit. Helper/meta tools either ignore this top-level field or define their own account-selection fields.
680
685
  * @returns The tool execution result
686
+ * @throws {ComposioToolInputRequiredError} If the tool needs input from the user (for example an approval) before it can run
681
687
  */
682
688
  async execute(
683
689
  toolSlug: string,
@@ -703,6 +709,7 @@ export class ToolRouterSession<
703
709
  data: result.data,
704
710
  error: result.error,
705
711
  logId: '',
712
+ resultType: result.successful ? 'completed' : 'failed',
706
713
  };
707
714
  }
708
715
  assertUnambiguousCustomToolSlug(this.customToolsMap, toolSlug);
@@ -723,10 +730,15 @@ export class ToolRouterSession<
723
730
  }
724
731
 
725
732
  const response = await withCancellation(
726
- () => this.client.toolRouter.session.execute(this.sessionId, executeParams, requestOptions),
733
+ () =>
734
+ this.client.toolRouter.session.execute(
735
+ this.sessionId,
736
+ executeParams,
737
+ withoutRetries(requestOptions)
738
+ ),
727
739
  requestOptions?.signal
728
740
  );
729
- const transformed = transformExecuteResponse(response);
741
+ const transformed = transformExecuteResponse(response, toolSlug);
730
742
  return ToolRouterSessionExecuteResponseSchema.parse(transformed);
731
743
  }
732
744
 
@@ -736,6 +748,7 @@ export class ToolRouterSession<
736
748
  *
737
749
  * @param params - Proxy request parameters (toolkit, endpoint, method, body, headers/query params)
738
750
  * @returns The proxied API response with status, data, headers
751
+ * @throws {ComposioToolInputRequiredError} If the call needs input from the user before it can run
739
752
  */
740
753
  async proxyExecute(
741
754
  params: SessionProxyExecuteParams,
@@ -749,10 +762,18 @@ export class ToolRouterSession<
749
762
  const clientParams = transformProxyParams(validated.data);
750
763
  const response = await withCancellation(
751
764
  () =>
752
- this.client.toolRouter.session.proxyExecute(this.sessionId, clientParams, requestOptions),
765
+ this.client.toolRouter.session.proxyExecute(
766
+ this.sessionId,
767
+ clientParams,
768
+ withoutRetries(requestOptions)
769
+ ),
753
770
  requestOptions?.signal
754
771
  );
755
772
 
773
+ assertNotInputRequired(
774
+ response,
775
+ `${validated.data.method} proxy call for toolkit ${validated.data.toolkit}`
776
+ );
756
777
  return {
757
778
  status: response.status,
758
779
  data: response.data,
@@ -1037,6 +1058,12 @@ export class ToolRouterSession<
1037
1058
 
1038
1059
  const remoteTransportFailed = !!remoteOutcome && 'error' in remoteOutcome;
1039
1060
  const remoteTransportError = remoteTransportFailed ? remoteOutcome.error : null;
1061
+ // An input request is not a per-tool failure: rethrow it so the caller gets
1062
+ // `inputRequests` and `requestState`.
1063
+ // Accepted: local tools in this batch already ran and their results are discarded.
1064
+ if (remoteTransportError instanceof ComposioToolInputRequiredError) {
1065
+ throw remoteTransportError;
1066
+ }
1040
1067
  const remoteErrorMessage = remoteTransportFailed
1041
1068
  ? (remoteTransportError instanceof Error
1042
1069
  ? remoteTransportError.message
@@ -1108,18 +1135,23 @@ export class ToolRouterSession<
1108
1135
  }
1109
1136
  const remoteError =
1110
1137
  remoteErrorMessage ?? (typeof remoteResult?.error === 'string' ? remoteResult.error : null);
1111
- const hasAnyError = localResults.some(r => r.result.error) || !!remoteError;
1138
+ // A failed execution can carry no error text, so success is read from each
1139
+ // result's own verdict and not from the absence of an error message.
1140
+ const hasAnyFailure =
1141
+ localResults.some(r => !r.result.successful) ||
1142
+ remoteResult?.successful === false ||
1143
+ !!remoteError;
1112
1144
 
1113
1145
  return {
1114
1146
  data: mergedData,
1115
- error: hasAnyError
1116
- ? remoteError && failedCount === 0
1117
- ? remoteError
1118
- : `${failedCount} out of ${allResults.length} tools failed`
1147
+ error: hasAnyFailure
1148
+ ? failedCount > 0
1149
+ ? `${failedCount} out of ${allResults.length} tools failed`
1150
+ : remoteError
1119
1151
  : null,
1120
- successful: !hasAnyError,
1121
- ...(remoteResult?.premiumCharge !== undefined && {
1122
- premiumCharge: remoteResult.premiumCharge,
1152
+ successful: !hasAnyFailure,
1153
+ ...(remoteResult?.instantCharge !== undefined && {
1154
+ instantCharge: remoteResult.instantCharge,
1123
1155
  }),
1124
1156
  };
1125
1157
  }
@@ -62,7 +62,11 @@ import {
62
62
  import { dereferenceJsonSchema } from '../utils/jsonSchema';
63
63
  import { ComposioRequestOptions } from '../types/requestOptions.types';
64
64
  import { withCancellation } from '../utils/cancellation';
65
- import { transformExecuteResponse } from '../utils/transformers/toolRouterResponseTransform';
65
+ import { withoutRetries } from '../utils/retries';
66
+ import {
67
+ isExecutionSuccessful,
68
+ transformExecuteResponse,
69
+ } from '../utils/transformers/toolRouterResponseTransform';
66
70
  import { ComposioRequestCancelledError } from '../errors/SDKErrors';
67
71
 
68
72
  const TOOL_ROUTER_SESSION_TOOLS_PAGE_LIMIT = 500;
@@ -120,11 +124,6 @@ export class Tools<
120
124
  */
121
125
  private readonly warnedAutoUploadDisabledForTool = new Set<string>();
122
126
 
123
- /**
124
- * Lazily-built sibling client with retries disabled; see `clientWithoutRetries`.
125
- */
126
- private clientWithoutRetriesCache?: ComposioClient;
127
-
128
127
  constructor(client: ComposioClient, config?: ComposioConfig<TProvider>) {
129
128
  if (!client) {
130
129
  throw new Error('ComposioClient is required');
@@ -157,27 +156,6 @@ export class Tools<
157
156
  telemetry.instrument(this, 'Tools');
158
157
  }
159
158
 
160
- /**
161
- * A cached sibling client that never retries requests, mirroring Python's
162
- * `client.without_retries`.
163
- *
164
- * Used for non-idempotent writes (`tools.execute` / `tools.proxy`), where a
165
- * silent retry after a read timeout can duplicate a side effect (e.g. send an
166
- * email twice). Reads keep the default retry behaviour, and so do other writes
167
- * (`toolRouter.session.execute`, auth-config and connected-account mutations):
168
- * the durable fix there is backend-honoured idempotency keys, tracked
169
- * separately.
170
- *
171
- * Cached rather than rebuilt per call because `withOptions` constructs a fresh
172
- * client; its options never change, so one per `Tools` instance suffices.
173
- */
174
- private get clientWithoutRetries(): ComposioClient {
175
- if (!this.clientWithoutRetriesCache) {
176
- this.clientWithoutRetriesCache = this.client.withOptions({ maxRetries: 0 });
177
- }
178
- return this.clientWithoutRetriesCache;
179
- }
180
-
181
159
  /**
182
160
  * Transforms tool data from snake_case API format to camelCase for internal SDK use.
183
161
  *
@@ -1022,9 +1000,7 @@ export class Tools<
1022
1000
  text: body.text,
1023
1001
  };
1024
1002
  const result = await withCancellation(
1025
- // Disable retries: tool execution is a non-idempotent write, and a
1026
- // silent retry after a read timeout can duplicate the side effect.
1027
- () => this.clientWithoutRetries.tools.execute(tool.slug, executeBody, requestOptions),
1003
+ () => this.client.tools.execute(tool.slug, executeBody, withoutRetries(requestOptions)),
1028
1004
  requestOptions?.signal
1029
1005
  );
1030
1006
  // transform the response to the ToolExecuteResponse format
@@ -1254,17 +1230,25 @@ export class Tools<
1254
1230
  }
1255
1231
 
1256
1232
  const response = await withCancellation(
1257
- () => this.client.toolRouter.session.execute(body.sessionId, executePayload, requestOptions),
1233
+ () =>
1234
+ this.client.toolRouter.session.execute(
1235
+ body.sessionId,
1236
+ executePayload,
1237
+ withoutRetries(requestOptions)
1238
+ ),
1258
1239
  requestOptions?.signal
1259
1240
  );
1260
1241
 
1261
- const { data, error, logId, premiumCharge } = transformExecuteResponse(response);
1242
+ const { data, error, logId, resultType, instantCharge } = transformExecuteResponse(
1243
+ response,
1244
+ toolSlug
1245
+ );
1262
1246
  let result: ToolExecuteResponse = {
1263
1247
  data,
1264
1248
  error,
1265
- successful: !error,
1249
+ successful: isExecutionSuccessful({ resultType }),
1266
1250
  logId,
1267
- ...(premiumCharge !== undefined && { premiumCharge }),
1251
+ ...(instantCharge !== undefined && { instantCharge }),
1268
1252
  };
1269
1253
 
1270
1254
  // Apply afterExecute modifier if provided
@@ -1352,6 +1336,7 @@ export class Tools<
1352
1336
  * @param {string} body.endpoint - Path relative to the toolkit's base URL, or an absolute URL
1353
1337
  * @param {'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'} body.method - HTTP method
1354
1338
  * @param {string} [body.connectedAccountId] - The connected account to authenticate as
1339
+ * @param {string} [body.userId] - The user the connected account belongs to. Projects with 2FA enabled check it against the connected account and may require it
1355
1340
  * @param {unknown} [body.body] - JSON request body
1356
1341
  * @param {Array<{ in: 'query' | 'header'; name: string; value: string | number }>} [body.parameters] - Extra query parameters or headers
1357
1342
  * @returns {Promise<ToolProxyResponse>} The upstream status, headers, and parsed body
@@ -1399,6 +1384,7 @@ export class Tools<
1399
1384
  method: toolProxyParams.data.method,
1400
1385
  body: toolProxyParams.data.body,
1401
1386
  connected_account_id: toolProxyParams.data.connectedAccountId,
1387
+ user_id: toolProxyParams.data.userId,
1402
1388
  parameters: parameters,
1403
1389
  /**
1404
1390
  * @deprecated The `customConnectionData` proxy param is deprecated and will be
@@ -1409,9 +1395,7 @@ export class Tools<
1409
1395
  custom_connection_data: toolProxyParams.data.customConnectionData,
1410
1396
  } as ComposioToolProxyParams;
1411
1397
  return withCancellation(
1412
- // Disable retries: a proxied call is a non-idempotent write, and a silent
1413
- // retry after a read timeout can duplicate the side effect.
1414
- () => this.clientWithoutRetries.tools.proxy(proxyBody, requestOptions),
1398
+ () => this.client.tools.proxy(proxyBody, withoutRetries(requestOptions)),
1415
1399
  requestOptions?.signal
1416
1400
  );
1417
1401
  }
@@ -32,6 +32,7 @@ import {
32
32
  * ```typescript
33
33
  * const summary = await composio.experimental.usage.summary();
34
34
  * console.log(summary.entities.tool_calls?.totalQuantity);
35
+ * console.log(summary.instantCharge); // exact USD string
35
36
  *
36
37
  * const byTool = await composio.experimental.usage.breakdown('tool_calls', {
37
38
  * groupBy: 'tool_slug',
@@ -52,7 +53,7 @@ export class Usage {
52
53
  * **Experimental — shape may change in future releases.**
53
54
  *
54
55
  * @param {UsageSummaryParams} [params] - Optional range, `entityTypes` and filters
55
- * @returns {Promise<UsageSummaryResponse>} Totals keyed by entity type
56
+ * @returns {Promise<UsageSummaryResponse>} Totals keyed by entity type and the exact USD Instant charge
56
57
  * @throws {ValidationError} If the params fail validation
57
58
  *
58
59
  * @example
@@ -10,6 +10,7 @@ import type {
10
10
  import type { ToolExecuteResponse } from '../types/tool.types';
11
11
  import { ValidationError } from '../errors';
12
12
  import { ComposioRequestCancelledError, isRequestAbortError } from '../errors/SDKErrors';
13
+ import { ComposioToolInputRequiredError } from '../errors/ToolRouterErrors';
13
14
 
14
15
  /**
15
16
  * Find a custom tool entry by slug.
@@ -59,6 +60,9 @@ export function assertUnambiguousCustomToolSlug(
59
60
  * and wraps the result into the standard response format.
60
61
  *
61
62
  * Callers provide a pre-built SessionContext (which may include sibling routing).
63
+ *
64
+ * @throws {ComposioToolInputRequiredError} If a call the tool made through the
65
+ * session context needs user input before it can run
62
66
  */
63
67
  export async function executeCustomTool(
64
68
  entry: CustomToolsMapEntry,
@@ -103,6 +107,12 @@ export async function executeCustomTool(
103
107
  if (err instanceof ComposioRequestCancelledError) {
104
108
  throw err;
105
109
  }
110
+ // `ctx.execute()` / `ctx.proxyExecute()` asked for user input: nothing ran.
111
+ // Flattening it into a failed result would drop the questions and the
112
+ // request state the caller needs to answer them.
113
+ if (err instanceof ComposioToolInputRequiredError) {
114
+ throw err;
115
+ }
106
116
  if (options?.signal?.aborted && isRequestAbortError(err)) {
107
117
  throw new ComposioRequestCancelledError(undefined, {
108
118
  cause: err instanceof Error ? err : undefined,
@@ -108,4 +108,20 @@ export const platform = {
108
108
  fs.writeFileSync(filePath, content);
109
109
  }
110
110
  },
111
+
112
+ writeFileExclusiveSync(filePath: string, content: Uint8Array): void {
113
+ const fd = fs.openSync(filePath, 'wx');
114
+ try {
115
+ try {
116
+ fs.writeFileSync(fd, content);
117
+ } finally {
118
+ fs.closeSync(fd);
119
+ }
120
+ } catch (error) {
121
+ // The path was created here, so a failed write or close must not leave
122
+ // a partial file that a retry would treat as an existing download.
123
+ fs.rmSync(filePath, { force: true });
124
+ throw error;
125
+ }
126
+ },
111
127
  } as Platform;
@@ -85,6 +85,9 @@ export interface Platform {
85
85
  writeFileSync(filePath: string, content: Uint8Array, encoding?: never): void;
86
86
  writeFileSync(filePath: string, content: string, encoding: Uint8ArrayEncoding): void;
87
87
 
88
+ /** Writes a new file, failing if its path already exists. A failed write removes the file. */
89
+ writeFileExclusiveSync(filePath: string, content: Uint8Array): void;
90
+
88
91
  /**
89
92
  * Indicates whether this platform supports file system operations.
90
93
  * Edge runtimes like Cloudflare Workers return false.
@@ -108,4 +108,8 @@ export const platform: Platform = {
108
108
  'Use environment variables or external storage services instead.'
109
109
  );
110
110
  },
111
+
112
+ writeFileExclusiveSync(_filePath: string, _content: Uint8Array): never {
113
+ throw new Error('File system operations are not supported in this runtime environment.');
114
+ },
111
115
  };
@@ -8,6 +8,7 @@ import {
8
8
  ToolCallExecutionTarget,
9
9
  } from '../types/provider.types';
10
10
  import { McpUrlResponse, McpServerGetResponse } from '../types/mcp.types';
11
+ import { isExecutionSuccessful } from '../utils/transformers/toolRouterResponseTransform';
11
12
 
12
13
  /**
13
14
  * @internal
@@ -108,7 +109,7 @@ abstract class BaseProvider<TMcpResponse> {
108
109
  const result = await target.execute(toolSlug, arguments_);
109
110
  return {
110
111
  ...result,
111
- successful: result.error === null,
112
+ successful: isExecutionSuccessful(result),
112
113
  };
113
114
  }
114
115
 
@@ -8,10 +8,8 @@
8
8
  * This will be shipped with the SDK and users don't need to install it separately.
9
9
  */
10
10
  import { OpenAI } from 'openai';
11
- import { Stream } from 'openai/streaming';
12
11
  import { BaseNonAgenticProvider } from './BaseProvider';
13
12
  import { Tool } from '../types/tool.types';
14
- import logger from '../utils/logger';
15
13
  import { ExecuteToolModifiers } from '../types/modifiers.types';
16
14
  import {
17
15
  ExecuteToolFnOptions,
@@ -296,285 +294,4 @@ export class OpenAIProvider extends BaseNonAgenticProvider<
296
294
  }
297
295
  return outputs;
298
296
  }
299
-
300
- /**
301
- * Handles all the tool calls from the OpenAI Assistant API.
302
- *
303
- * This method processes tool calls from an OpenAI Assistant run,
304
- * executes each tool call, and returns the tool outputs for submission.
305
- *
306
- * @deprecated Assistant API is deprecated, please use responses or chat completions instead. This method will be removed in the next major version.
307
- *
308
- * @param {string} userId - The user ID for authentication and tracking
309
- * @param {OpenAI.Beta.Threads.Run} run - The Assistant run object containing tool calls
310
- * @param {ExecuteToolFnOptions} [options] - Optional execution options
311
- * @param {ExecuteToolModifiers} [modifiers] - Optional execution modifiers
312
- * @returns {Promise<OpenAI.Beta.Threads.Runs.RunSubmitToolOutputsParams.ToolOutput[]>} Array of tool outputs for submission
313
- *
314
- *
315
- * @example
316
- * ```typescript
317
- * // Handle tool calls from an OpenAI Assistant run
318
- * const run = {
319
- * id: 'run_abc123',
320
- * required_action: {
321
- * submit_tool_outputs: {
322
- * tool_calls: [
323
- * {
324
- * id: 'call_xyz789',
325
- * type: 'function',
326
- * function: {
327
- * name: 'SEARCH_TOOL',
328
- * arguments: '{"query":"composio documentation"}'
329
- * }
330
- * }
331
- * ]
332
- * }
333
- * }
334
- * };
335
- *
336
- * const toolOutputs = await provider.handleAssistantMessage(
337
- * 'user123',
338
- * run,
339
- * { connectedAccountId: 'conn_xyz456' }
340
- * );
341
- *
342
- * // Submit tool outputs back to OpenAI
343
- * await openai.beta.threads.runs.submitToolOutputs(
344
- * thread.id,
345
- * run.id,
346
- * { tool_outputs: toolOutputs }
347
- * );
348
- * ```
349
- */
350
- async handleAssistantMessage(
351
- userId: string,
352
- run: OpenAI.Beta.Threads.Run,
353
- options?: ExecuteToolFnOptions,
354
- modifiers?: ExecuteToolModifiers
355
- ) {
356
- const tool_calls = run.required_action?.submit_tool_outputs?.tool_calls || [];
357
- const tool_outputs: Array<OpenAI.Beta.Threads.Runs.RunSubmitToolOutputsParams.ToolOutput> =
358
- await Promise.all(
359
- tool_calls.map(async tool_call => {
360
- logger.debug(`Executing tool call: ${tool_call.id}`);
361
-
362
- // Execute each tool call and get the response
363
- const tool_response = await this.executeToolCall(
364
- userId,
365
- tool_call as OpenAI.ChatCompletionMessageFunctionToolCall,
366
- options,
367
- modifiers
368
- );
369
-
370
- logger.debug(`Tool call ${tool_call.id} executed with response: ${tool_response}`);
371
-
372
- return {
373
- tool_call_id: tool_call.id,
374
- output: JSON.stringify(tool_response),
375
- };
376
- })
377
- );
378
- return tool_outputs;
379
- }
380
-
381
- /**
382
- * Waits for the assistant stream and handles the tool calls.
383
- *
384
- * This method processes an OpenAI Assistant stream, handles any tool calls
385
- * that require action, and yields each event from the stream. It's designed
386
- * for streaming Assistant responses while handling tool calls in real-time.
387
- *
388
- * @deprecated Assistant API is deprecated, please use responses or chat completions instead. It will be removed in the next major version.
389
- *
390
- * @param {string} userId - The user ID for authentication and tracking
391
- * @param {OpenAI} client - The OpenAI client instance
392
- * @param {Stream<OpenAI.Beta.Assistants.AssistantStreamEvent>} runStream - The Assistant run stream
393
- * @param {OpenAI.Beta.Threads.Thread} thread - The thread object
394
- * @param {ExecuteToolFnOptions} [options] - Optional execution options
395
- * @param {ExecuteToolModifiers} [modifiers] - Optional execution modifiers
396
- * @returns {AsyncGenerator<OpenAI.Beta.Assistants.AssistantStreamEvent, void, unknown>} Generator yielding stream events
397
- *
398
- *
399
- *
400
- * @example
401
- * ```typescript
402
- * // Process an OpenAI Assistant stream with tool calls
403
- * const thread = await openai.beta.threads.create();
404
- * const runStream = openai.beta.threads.runs.stream(thread.id, {
405
- * assistant_id: 'asst_abc123',
406
- * tools: provider.wrapTools(composioTools)
407
- * });
408
- *
409
- * // Process the stream and handle tool calls
410
- * const streamProcessor = provider.waitAndHandleAssistantStreamToolCalls(
411
- * 'user123',
412
- * openai,
413
- * runStream,
414
- * thread,
415
- * { connectedAccountId: 'conn_xyz456' }
416
- * );
417
- *
418
- * // Consume the stream events
419
- * for await (const event of streamProcessor) {
420
- * if (event.event === 'thread.message.delta') {
421
- * console.log(event.data.delta.content);
422
- * }
423
- * }
424
- * ```
425
- */
426
- async *waitAndHandleAssistantStreamToolCalls(
427
- userId: string,
428
- client: OpenAI,
429
- runStream: Stream<OpenAI.Beta.Assistants.AssistantStreamEvent>,
430
- thread: OpenAI.Beta.Threads.Thread,
431
- options?: ExecuteToolFnOptions,
432
- modifiers?: ExecuteToolModifiers
433
- ) {
434
- // @TODO: Log the run stream
435
- let runId = null;
436
-
437
- // Start processing the runStream events
438
- for await (const event of runStream) {
439
- yield event; // Yield each event from the stream as it arrives
440
-
441
- if (event.event === 'thread.run.created') {
442
- const { id } = event.data;
443
- runId = id;
444
- }
445
-
446
- if (!runId) {
447
- continue;
448
- }
449
-
450
- // Handle the 'requires_action' event
451
- if (event.event === 'thread.run.requires_action') {
452
- const toolOutputs = await this.handleAssistantMessage(
453
- userId,
454
- event.data,
455
- options,
456
- modifiers
457
- );
458
-
459
- // Submit the tool outputs
460
- await client.beta.threads.runs.submitToolOutputs(runId, {
461
- thread_id: thread.id,
462
- tool_outputs: toolOutputs,
463
- });
464
- }
465
-
466
- // Break if the run status becomes inactive
467
- if (
468
- [
469
- 'thread.run.completed',
470
- 'thread.run.failed',
471
- 'thread.run.cancelled',
472
- 'thread.run.expired',
473
- ].includes(event.event)
474
- ) {
475
- break;
476
- }
477
- }
478
-
479
- if (!runId) {
480
- throw new Error('No run ID found');
481
- }
482
-
483
- // Handle any final actions after the stream ends
484
- let finalRun = await client.beta.threads.runs.retrieve(runId, {
485
- thread_id: thread.id,
486
- });
487
-
488
- while (['queued', 'in_progress', 'requires_action'].includes(finalRun.status)) {
489
- if (finalRun.status === 'requires_action') {
490
- const toolOutputs = await this.handleAssistantMessage(userId, finalRun, options, modifiers);
491
-
492
- // Submit tool outputs
493
- finalRun = await client.beta.threads.runs.submitToolOutputs(runId, {
494
- thread_id: thread.id,
495
- tool_outputs: toolOutputs,
496
- });
497
- } else {
498
- // Update the run status
499
- finalRun = await client.beta.threads.runs.retrieve(runId, {
500
- thread_id: thread.id,
501
- });
502
- await new Promise(resolve => setTimeout(resolve, 500)); // Wait before rechecking
503
- }
504
- }
505
- }
506
-
507
- /**
508
- * Waits for the assistant tool calls and handles them.
509
- *
510
- * This method polls an OpenAI Assistant run until it completes or requires action,
511
- * handles any tool calls, and returns the final run object. It's designed for
512
- * non-streaming Assistant interactions.
513
- *
514
- * @deprecated Assistant API is deprecated, please use responses or chat completions instead. It will be removed in the next major version.
515
- *
516
- * @param {string} userId - The user ID for authentication and tracking
517
- * @param {OpenAI} client - The OpenAI client instance
518
- * @param {OpenAI.Beta.Threads.Run} run - The initial run object
519
- * @param {OpenAI.Beta.Threads.Thread} thread - The thread object
520
- * @param {ExecuteToolFnOptions} [options] - Optional execution options
521
- * @param {ExecuteToolModifiers} [modifiers] - Optional execution modifiers
522
- * @returns {Promise<OpenAI.Beta.Threads.Run>} The final run object after completion
523
- *
524
- * @example
525
- * ```typescript
526
- * // Process an OpenAI Assistant run with tool calls
527
- * const thread = await openai.beta.threads.create();
528
- * await openai.beta.threads.messages.create(thread.id, {
529
- * role: 'user',
530
- * content: 'Find information about Composio'
531
- * });
532
- *
533
- * let run = await openai.beta.threads.runs.create(thread.id, {
534
- * assistant_id: 'asst_abc123',
535
- * tools: provider.wrapTools(composioTools)
536
- * });
537
- *
538
- * // Wait for the run to complete, handling any tool calls
539
- * run = await provider.waitAndHandleAssistantToolCalls(
540
- * 'user123',
541
- * openai,
542
- * run,
543
- * thread,
544
- * { connectedAccountId: 'conn_xyz456' }
545
- * );
546
- *
547
- * // Get the final messages after run completion
548
- * const messages = await openai.beta.threads.messages.list(thread.id);
549
- * console.log(messages.data[0].content);
550
- * ```
551
- */
552
- async waitAndHandleAssistantToolCalls(
553
- userId: string,
554
- client: OpenAI,
555
- run: OpenAI.Beta.Threads.Run,
556
- thread: OpenAI.Beta.Threads.Thread,
557
- options?: ExecuteToolFnOptions,
558
- modifiers?: ExecuteToolModifiers
559
- ) {
560
- while (['queued', 'in_progress', 'requires_action'].includes(run.status)) {
561
- // logger.debug(`Current run status: ${run.status}`);
562
- const tool_outputs = await this.handleAssistantMessage(userId, run, options, modifiers);
563
- if (run.status === 'requires_action') {
564
- // logger.debug(
565
- // `Submitting tool outputs for run ID: ${run.id} in thread ID: ${thread.id}`
566
- // );
567
- run = await client.beta.threads.runs.submitToolOutputs(run.id, {
568
- thread_id: thread.id,
569
- tool_outputs: tool_outputs,
570
- });
571
- } else {
572
- run = await client.beta.threads.runs.retrieve(run.id, {
573
- thread_id: thread.id,
574
- });
575
- await new Promise(resolve => setTimeout(resolve, 500));
576
- }
577
- }
578
- return run;
579
- }
580
297
  }
@@ -94,8 +94,10 @@ export class TelemetryTransport {
94
94
  */
95
95
  instrument<T extends object>(instance: T, fileName?: string) {
96
96
  const proto = Object.getPrototypeOf(instance);
97
- const methodNames = Object.getOwnPropertyNames(proto).filter(key => {
98
- const descriptor = Object.getOwnPropertyDescriptor(proto, key);
97
+ // Objects returned by factory functions carry their methods as own properties.
98
+ const methodSource = proto === Object.prototype || proto === null ? instance : proto;
99
+ const methodNames = Object.getOwnPropertyNames(methodSource).filter(key => {
100
+ const descriptor = Object.getOwnPropertyDescriptor(methodSource, key);
99
101
  return (
100
102
  key !== 'constructor' &&
101
103
  descriptor &&