@composio/core 0.27.0 → 0.29.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 (64) hide show
  1. package/README.md +2 -0
  2. package/dist/{CustomTool-BYHB7sPs.mjs → CustomTool-Bd1KdWvo.mjs} +9 -8
  3. package/dist/{CustomTool-CqPoLUD6.d.mts → CustomTool-CMW-d2ZN.d.mts} +10 -9
  4. package/dist/{Telemetry-41JkqpZ7.mjs → Telemetry-D2PJwXKx.mjs} +1 -1
  5. package/dist/{cancellation-ZoRh6EJQ.mjs → cancellation-BoJjs34Y.mjs} +1 -1
  6. package/dist/{composio-BUa10iB3.d.mts → composio-D5UV5HXN.d.mts} +799 -100
  7. package/dist/{customTool.types-gX421uPT.d.mts → customTool.types-B9fs34dv.d.mts} +105 -60
  8. package/dist/docs/reference/sdk-reference/typescript/composio.mdx +1 -1
  9. package/dist/docs/reference/sdk-reference/typescript/connected-accounts.mdx +2 -2
  10. package/dist/docs/reference/sdk-reference/typescript/custom-toolkits.mdx +86 -3
  11. package/dist/docs/reference/sdk-reference/typescript/experimental.mdx +1 -1
  12. package/dist/docs/reference/sdk-reference/typescript/session-configs.mdx +1 -1
  13. package/dist/docs/reference/sdk-reference/typescript/session.mdx +51 -13
  14. package/dist/docs/reference/sdk-reference/typescript/sessions.mdx +6 -6
  15. package/dist/docs/reference/sdk-reference/typescript/tools.mdx +4 -4
  16. package/dist/docs/reference/sdk-reference/typescript/triggers.mdx +5 -1
  17. package/dist/{errors-Cly0vXFh.mjs → errors-BK6Xc7Ia.mjs} +65 -1
  18. package/dist/experimental/index.d.mts +3 -3
  19. package/dist/experimental/index.mjs +1 -1
  20. package/dist/{fileUtils.node-DNLhLg0W.mjs → fileUtils.node-ILI1IjnZ.mjs} +4 -3
  21. package/dist/index.d.mts +46 -16
  22. package/dist/index.mjs +2973 -2778
  23. package/dist/models/Files.node.mjs +2 -2
  24. package/dist/sensitiveFileUploadPaths-BaEORC7-.mjs +588 -0
  25. package/dist/{types-DXxfzBX3.d.mts → types-CaP2SytR.d.mts} +2 -2
  26. package/dist/utils/config-defaults/ConfigDefaults.node.d.mts +1 -1
  27. package/dist/utils/config-defaults/ConfigDefaults.workerd.d.mts +1 -1
  28. package/dist/utils/modifiers/FileToolModifier.node.d.mts +1 -1
  29. package/dist/utils/modifiers/FileToolModifier.node.mjs +3 -3
  30. package/dist/utils/modifiers/FileToolModifier.workerd.d.mts +1 -1
  31. package/package.json +7 -6
  32. package/src/errors/ToolErrors.ts +73 -1
  33. package/src/experimental/index.ts +6 -1
  34. package/src/lib/toolRouterParams.ts +68 -33
  35. package/src/lib/toolRouterSessionDelete.ts +1 -10
  36. package/src/models/ConnectedAccounts.ts +3 -3
  37. package/src/models/ConnectionRequest.ts +38 -34
  38. package/src/models/CustomTool.ts +26 -31
  39. package/src/models/CustomToolkits.ts +116 -10
  40. package/src/models/Experimental.ts +1 -1
  41. package/src/models/MCP.ts +1 -2
  42. package/src/models/SessionConfigs.ts +11 -3
  43. package/src/models/SessionContext.ts +4 -4
  44. package/src/models/ToolRouter.ts +26 -17
  45. package/src/models/ToolRouterSession.ts +39 -24
  46. package/src/models/Tools.ts +60 -14
  47. package/src/models/Triggers.ts +12 -5
  48. package/src/models/inlineCustomToolsPayload.ts +3 -3
  49. package/src/models/proxyParamsTransform.ts +1 -1
  50. package/src/types/customTool.types.ts +62 -33
  51. package/src/types/customToolkits.types.ts +91 -11
  52. package/src/types/sessionConfigs.types.ts +21 -7
  53. package/src/types/toolRouter.types.ts +53 -24
  54. package/src/types/triggers.types.ts +14 -0
  55. package/src/utils/fileUtils.node.ts +5 -2
  56. package/src/utils/mime.ts +347 -1
  57. package/src/utils/rateLimit.ts +25 -0
  58. package/src/utils/transformers/connectedAccounts.ts +2 -7
  59. package/src/utils/transformers/customToolkits.ts +79 -10
  60. package/src/utils/transformers/sessionConfigs.ts +3 -3
  61. package/src/utils/transformers/toolRouterResponseTransform.ts +23 -75
  62. package/src/utils/transformers/toolkits.ts +7 -13
  63. package/src/utils/transformers/triggers.ts +28 -18
  64. package/dist/sensitiveFileUploadPaths-BlLp-Yo2.mjs +0 -189
package/package.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "engines": {
5
5
  "node": ">=22.22.3"
6
6
  },
7
- "version": "0.27.0",
7
+ "version": "0.29.0",
8
8
  "description": "",
9
9
  "main": "dist/index.mjs",
10
10
  "publishConfig": {
@@ -111,31 +111,32 @@
111
111
  ],
112
112
  "license": "ISC",
113
113
  "devDependencies": {
114
- "@hono/node-server": "^2.1.4",
114
+ "@hono/node-server": "^2.1.5",
115
115
  "@type-challenges/utils": "^0.1.1",
116
116
  "@types/semver": "^7.8.0",
117
117
  "ajv": "^8.20.0",
118
118
  "fast-check": "^4.10.2",
119
119
  "hono": "^4.13.13",
120
+ "mime": "^4.1.1",
120
121
  "tsdown": "^0.23.1",
121
122
  "tsx": "^4.23.15",
122
123
  "typedoc": "^0.28.20",
123
124
  "typescript": "npm:@typescript/typescript6@^6.0.2",
124
- "vitest": "^5.0.3",
125
+ "vitest": "^5.0.5",
125
126
  "zod": "^4.5.4"
126
127
  },
127
128
  "peerDependencies": {
128
129
  "zod": ">=3.25.76 <5"
129
130
  },
130
131
  "dependencies": {
131
- "@composio/client": "2.0.0-rc.19",
132
+ "@composio/client": "2.1.0",
132
133
  "@types/json-schema": "^7.0.15",
133
134
  "is-fs-case-sensitive": "^2.0.0",
134
- "openai": "^7.32.0",
135
+ "openai": "^7.39.0",
135
136
  "picocolors": "^1.1.1",
136
137
  "pusher-js": "^8.6.0",
137
138
  "semver": "^7.8.5",
138
- "undici": "^7.30.0",
139
+ "undici": "^7.30.1",
139
140
  "zod-to-json-schema": "^3.25.2",
140
141
  "@composio/json-schema-to-zod": "0.4.0"
141
142
  },
@@ -1,6 +1,7 @@
1
1
  import { APIError } from '@composio/client';
2
2
  import { ComposioError, ComposioErrorOptions } from './ComposioError';
3
3
  import { ComposioConnectedAccountNotFoundError } from './ConnectedAccountsErrors';
4
+ import { getRetryAfterSeconds, isRateLimitResponse } from '../utils/rateLimit';
4
5
 
5
6
  export const ToolErrorCodes = {
6
7
  TOOLSET_NOT_DEFINED: 'TOOLSET_NOT_DEFINED',
@@ -54,7 +55,7 @@ export class ComposioToolNotFoundError extends ComposioError {
54
55
  export class ComposioToolFetchError extends ComposioError {
55
56
  constructor(
56
57
  message: string = 'Failed to fetch tool',
57
- options: Omit<ComposioErrorOptions, 'code' | 'statusCode'> = {}
58
+ options: Omit<ComposioErrorOptions, 'code'> = {}
58
59
  ) {
59
60
  super(message, {
60
61
  ...options,
@@ -69,6 +70,41 @@ export class ComposioToolFetchError extends ComposioError {
69
70
  }
70
71
  }
71
72
 
73
+ /** Error options for a 429. Leaves out an unknown wait, as `ComposioError` does for unset fields. */
74
+ const rateLimitOptions = (cause: APIError, meta: Record<string, unknown>) => {
75
+ const retryAfterSeconds = getRetryAfterSeconds(cause);
76
+ return {
77
+ retryAfterSeconds,
78
+ cause,
79
+ statusCode: 429,
80
+ meta: retryAfterSeconds === undefined ? meta : { ...meta, retryAfterSeconds },
81
+ possibleFixes: [
82
+ retryAfterSeconds === undefined
83
+ ? 'Wait before retrying'
84
+ : `Wait ${Math.ceil(retryAfterSeconds)} seconds, then retry`,
85
+ 'Reduce how many requests your organization sends per minute',
86
+ ],
87
+ };
88
+ };
89
+
90
+ /**
91
+ * A tool schema fetch rejected with a 429. It is a `ComposioToolFetchError`, so existing handlers
92
+ * still catch it. Use `isComposioRateLimitError` to catch rate limits from fetching and executing.
93
+ */
94
+ export class ComposioToolFetchRateLimitError extends ComposioToolFetchError {
95
+ /** How long the API asked to wait, when the response said. */
96
+ declare public readonly retryAfterSeconds?: number;
97
+
98
+ constructor(message: string, cause: APIError, meta: Record<string, unknown> = {}) {
99
+ const { retryAfterSeconds, ...options } = rateLimitOptions(cause, meta);
100
+ super(message, options);
101
+ if (retryAfterSeconds !== undefined) {
102
+ this.retryAfterSeconds = retryAfterSeconds;
103
+ }
104
+ this.name = 'ComposioToolFetchRateLimitError';
105
+ }
106
+ }
107
+
72
108
  export class ComposioInvalidModifierError extends ComposioError {
73
109
  constructor(
74
110
  message: string = 'Invalid modifier',
@@ -101,6 +137,34 @@ export class ComposioToolExecutionError extends ComposioError {
101
137
  }
102
138
  }
103
139
 
140
+ /**
141
+ * A tool execution rejected with a 429. It is a `ComposioToolExecutionError`, so existing handlers
142
+ * still catch it. Use `isComposioRateLimitError` to catch rate limits from fetching and executing.
143
+ */
144
+ export class ComposioToolExecutionRateLimitError extends ComposioToolExecutionError {
145
+ /** How long the API asked to wait, when the response said. */
146
+ declare public readonly retryAfterSeconds?: number;
147
+
148
+ constructor(message: string, cause: APIError, meta: Record<string, unknown> = {}) {
149
+ const { retryAfterSeconds, ...options } = rateLimitOptions(cause, meta);
150
+ super(message, options);
151
+ if (retryAfterSeconds !== undefined) {
152
+ this.retryAfterSeconds = retryAfterSeconds;
153
+ }
154
+ this.name = 'ComposioToolExecutionRateLimitError';
155
+ }
156
+ }
157
+
158
+ /** Whether an error from fetching or executing a tool is the API rejecting the request with a 429. */
159
+ export function isComposioRateLimitError(
160
+ error: unknown
161
+ ): error is ComposioToolFetchRateLimitError | ComposioToolExecutionRateLimitError {
162
+ return (
163
+ error instanceof ComposioToolFetchRateLimitError ||
164
+ error instanceof ComposioToolExecutionRateLimitError
165
+ );
166
+ }
167
+
104
168
  export class ComposioInvalidToolArgumentsError extends ComposioError {
105
169
  constructor(
106
170
  message: string = 'Invalid tool arguments',
@@ -259,6 +323,14 @@ export const handleToolExecutionError = (tool: string, actualError: Error): Comp
259
323
  }
260
324
  }
261
325
 
326
+ if (isRateLimitResponse(actualError)) {
327
+ return new ComposioToolExecutionRateLimitError(
328
+ `Rate limited while executing the tool ${tool}`,
329
+ actualError,
330
+ { slug: tool }
331
+ );
332
+ }
333
+
262
334
  // Default error for all other cases
263
335
  return new ComposioToolExecutionError(`Error executing the tool ${tool}`, {
264
336
  cause: actualError,
@@ -19,10 +19,15 @@ export {
19
19
  createCustomToolkit as experimental_createToolkit,
20
20
  } from '../models/CustomTool';
21
21
  export type {
22
+ LocalTool,
23
+ CreateLocalToolParams,
24
+ LocalToolExecuteFn,
25
+ SessionContext,
26
+ LocalToolkit,
27
+ CreateLocalToolkitParams,
22
28
  CustomTool,
23
29
  CreateCustomToolParams,
24
30
  CustomToolExecuteFn,
25
- SessionContext,
26
31
  CustomToolkit,
27
32
  CreateCustomToolkitParams,
28
33
  } from '../types/customTool.types';
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  SessionCreateParams,
3
3
  SessionPatchParams,
4
- } from '@composio/client/resources/tool-router/session/session.mjs';
4
+ } from '@composio/client/resources/tool-router/session';
5
5
  import {
6
6
  ToolRouterConfigTags,
7
7
  ToolRouterConfigTools,
@@ -21,6 +21,7 @@ import {
21
21
  ToolRouterProxyExecute,
22
22
  ToolRouterHook,
23
23
  } from '../types/toolRouter.types';
24
+ import type { LocalTool, LocalToolkit } from '../types/customTool.types';
24
25
  import { ValidationError } from '../errors';
25
26
  import { z } from 'zod';
26
27
  import type { TypeOf } from 'zod/v3';
@@ -85,7 +86,9 @@ export const transformToolRouterToolsParams = (
85
86
 
86
87
  export const transformToolRouterTagsParams = (
87
88
  params?: ToolRouterConfigTags
88
- ): SessionCreateParams.Tags['tags'] | undefined => {
89
+ ):
90
+ | Extract<NonNullable<SessionCreateParams['tools']>[string], { tags: unknown }>['tags']
91
+ | undefined => {
89
92
  if (!params) {
90
93
  return undefined;
91
94
  }
@@ -102,7 +105,7 @@ export const transformToolRouterTagsParams = (
102
105
 
103
106
  export const transformToolRouterManageConnectionsParams = (
104
107
  params?: boolean | z.infer<typeof ToolRouterConfigManageConnectionsSchema>
105
- ): SessionCreateParams.ManageConnections => {
108
+ ): NonNullable<SessionCreateParams['manage_connections']> => {
106
109
  if (params === undefined) {
107
110
  // Default case when params is undefined
108
111
  return {
@@ -143,9 +146,48 @@ export const resolveToolRouterSandboxConfig = (
143
146
  return config.sandbox ?? config.workbench;
144
147
  };
145
148
 
149
+ /** Local tools options, accepted under their current names and the deprecated `custom*` aliases. */
150
+ export type LocalToolsOptions = {
151
+ localTools?: LocalTool[];
152
+ localToolkits?: LocalToolkit[];
153
+ /** @deprecated Use `localTools` instead. */
154
+ customTools?: LocalTool[];
155
+ /** @deprecated Use `localToolkits` instead. */
156
+ customToolkits?: LocalToolkit[];
157
+ };
158
+
159
+ /**
160
+ * Resolves local tools and toolkits from `localTools` / `localToolkits` or
161
+ * their deprecated `customTools` / `customToolkits` aliases. `source` picks
162
+ * the option path named in the error: `experimental.*` on create, bare on use.
163
+ */
164
+ export const resolveLocalToolsOptions = (
165
+ options: LocalToolsOptions | undefined,
166
+ source: 'create' | 'use'
167
+ ): { tools?: LocalTool[]; toolkits?: LocalToolkit[] } => {
168
+ if (options?.localTools !== undefined && options.customTools !== undefined) {
169
+ throw new ValidationError(
170
+ source === 'create'
171
+ ? 'Pass either experimental.localTools or experimental.customTools, not both. experimental.customTools is a deprecated alias for experimental.localTools.'
172
+ : 'Pass either localTools or customTools, not both. customTools is a deprecated alias for localTools.'
173
+ );
174
+ }
175
+ if (options?.localToolkits !== undefined && options.customToolkits !== undefined) {
176
+ throw new ValidationError(
177
+ source === 'create'
178
+ ? 'Pass either experimental.localToolkits or experimental.customToolkits, not both. experimental.customToolkits is a deprecated alias for experimental.localToolkits.'
179
+ : 'Pass either localToolkits or customToolkits, not both. customToolkits is a deprecated alias for localToolkits.'
180
+ );
181
+ }
182
+ return {
183
+ tools: options?.localTools ?? options?.customTools,
184
+ toolkits: options?.localToolkits ?? options?.customToolkits,
185
+ };
186
+ };
187
+
146
188
  export const transformToolRouterSandboxParams = (
147
189
  params?: ParsedCreateSessionConfig['sandbox'] | ParsedCreateSessionConfig['workbench']
148
- ): SessionCreateParams.Workbench | undefined => {
190
+ ): NonNullable<SessionCreateParams['workbench']> | undefined => {
149
191
  if (!params) {
150
192
  return undefined;
151
193
  }
@@ -165,54 +207,48 @@ export const transformToolRouterWorkbenchParams = transformToolRouterSandboxPara
165
207
  * PATCH-safe variant of transformToolRouterManageConnectionsParams.
166
208
  * Does NOT apply defaults — only includes fields explicitly present in the input.
167
209
  */
168
- /** Widens the listed keys of a generated request type so `null` can travel on the wire. */
210
+ /**
211
+ * Widens the listed keys of a generated request type so `null` can travel on
212
+ * the wire. The spec does not mark these nullable until ComposioHQ/platform#13157
213
+ * lands.
214
+ */
169
215
  type WithNull<T, K extends keyof T> = Omit<T, K> & { [P in K]?: NonNullable<T[P]> | null };
170
216
 
171
217
  /**
172
218
  * `manage_connections` as sent by `session.update()`. Only the supplied
173
- * subfields travel; `callback_url: null` removes the stored callback, which
174
- * the generated client types as string-only.
219
+ * subfields travel; `callback_url: null` removes the stored callback.
175
220
  */
176
221
  export type SessionPatchManageConnectionsBody = WithNull<
177
- SessionPatchParams.ManageConnections,
222
+ NonNullable<SessionPatchParams['manage_connections']>,
178
223
  'callback_url'
179
224
  >;
180
225
 
181
226
  /** `multi_account` as sent by `session.update()`; `null` removes the stored maximum. */
182
227
  export type SessionPatchMultiAccountBody = WithNull<
183
- SessionPatchParams.MultiAccount,
228
+ NonNullable<SessionPatchParams['multi_account']>,
184
229
  'max_accounts_per_toolkit'
185
230
  >;
186
231
 
187
232
  /** `experimental` as sent by `session.update()`; `null` removes a stored leaf. */
188
233
  export type SessionPatchExperimentalBody = WithNull<
189
- SessionPatchParams.Experimental,
234
+ NonNullable<SessionPatchParams['experimental']>,
190
235
  'permissions' | 'link_url_overwrite' | 'fast_mode' | 'submit_feedback'
191
236
  >;
192
237
 
193
- /** A hook as the API takes it, in snake_case. The generated client does not type `hooks` yet. */
194
- export type SessionHookBody = {
195
- type: 'before_execute' | 'after_execute';
196
- id: string;
197
- name?: string;
198
- applies_to: 'all' | { toolkits: string[] };
199
- handler:
200
- | { type: 'condition_check'; condition: string; action: 'block' }
201
- | { type: 'prompt_injection_check'; action: 'block' };
202
- };
203
-
204
- /** Request body of `sessions.create()`: the generated `SessionCreateParams` plus `hooks`. */
205
- export type SessionCreateBody = SessionCreateParams & { hooks?: SessionHookBody[] };
206
-
207
- /** `hooks` as sent on create and update: `appliesTo` becomes `applies_to`. */
208
- export const transformToolRouterHooksParams = (hooks: ToolRouterHook[]): SessionHookBody[] =>
238
+ /**
239
+ * `hooks` as sent on create and update: `appliesTo` becomes `applies_to`.
240
+ * Create and patch take the same hook shape.
241
+ */
242
+ export const transformToolRouterHooksParams = (
243
+ hooks: ToolRouterHook[]
244
+ ): NonNullable<SessionCreateParams['hooks']> =>
209
245
  hooks.map(({ appliesTo, ...hook }) => ({ ...hook, applies_to: appliesTo }));
210
246
 
211
247
  /**
212
248
  * Request body of `session.update()`. Extends the generated `SessionPatchParams`
213
- * with the nullable policy blocks (`null` removes the stored override), `hooks`
214
- * and the `expected_config_version` root precondition, none of which the
215
- * generated client types yet.
249
+ * with the nullable policy blocks (`null` removes the stored override) and the
250
+ * `expected_config_version` root precondition, which the spec does not declare
251
+ * until ComposioHQ/platform#13157 lands.
216
252
  */
217
253
  export type SessionPatchBody = Omit<
218
254
  WithNull<
@@ -224,7 +260,6 @@ export type SessionPatchBody = Omit<
224
260
  manage_connections?: SessionPatchManageConnectionsBody | null;
225
261
  multi_account?: SessionPatchMultiAccountBody | null;
226
262
  experimental?: SessionPatchExperimentalBody | null;
227
- hooks?: SessionHookBody[] | null;
228
263
  expected_config_version?: number;
229
264
  };
230
265
 
@@ -312,7 +347,7 @@ const transformToolRouterUpdateExperimentalParams = (
312
347
  */
313
348
  export const transformToolRouterUpdateSandboxParams = (
314
349
  params: Partial<ToolRouterSandboxConfig>
315
- ): SessionPatchParams.Workbench => {
350
+ ): NonNullable<SessionPatchParams['workbench']> => {
316
351
  const result: Record<string, unknown> = {};
317
352
  if (params.enable !== undefined) {
318
353
  result.enable = params.enable;
@@ -326,7 +361,7 @@ export const transformToolRouterUpdateSandboxParams = (
326
361
  if (params.sandboxSize !== undefined) {
327
362
  result.sandbox_size = params.sandboxSize;
328
363
  }
329
- return result as SessionPatchParams.Workbench;
364
+ return result as NonNullable<SessionPatchParams['workbench']>;
330
365
  };
331
366
 
332
367
  /** @deprecated Renamed — use `transformToolRouterUpdateSandboxParams` instead. `workbench` is a backwards-compatible alias for `sandbox`. */
@@ -334,7 +369,7 @@ export const transformToolRouterUpdateWorkbenchParams = transformToolRouterUpdat
334
369
 
335
370
  export const transformToolRouterMultiAccountParams = (
336
371
  params?: ParsedCreateSessionConfig['multiAccount']
337
- ): SessionCreateParams.MultiAccount | undefined => {
372
+ ): NonNullable<SessionCreateParams['multi_account']> | undefined => {
338
373
  if (!params) {
339
374
  return undefined;
340
375
  }
@@ -4,22 +4,13 @@ import type { ToolRouterSessionDeleteResponse } from '../types/toolRouter.types'
4
4
  import { ToolRouterSessionDeleteResponseSchema } from '../types/toolRouter.types';
5
5
  import { withCancellation } from '../utils/cancellation';
6
6
 
7
- type ToolRouterSessionDeleteWireResponse = {
8
- session_id: string;
9
- deleted: true;
10
- };
11
-
12
7
  export async function deleteToolRouterSession(
13
8
  client: ComposioClient,
14
9
  sessionId: string,
15
10
  requestOptions?: ComposioRequestOptions
16
11
  ): Promise<ToolRouterSessionDeleteResponse> {
17
12
  const response = await withCancellation(
18
- () =>
19
- client.delete<ToolRouterSessionDeleteWireResponse>(
20
- `/api/v3.1/tool_router/session/${encodeURIComponent(sessionId)}`,
21
- requestOptions
22
- ),
13
+ () => client.toolRouter.session.delete(sessionId, requestOptions),
23
14
  requestOptions?.signal
24
15
  );
25
16
 
@@ -253,7 +253,7 @@ export class ConnectedAccounts {
253
253
  connection: {
254
254
  callback_url: options?.callbackUrl,
255
255
  user_id: userId,
256
- state: state as ConnectedAccountCreateParamsRaw.Connection['state'],
256
+ state: state as NonNullable<ConnectedAccountCreateParamsRaw['connection']>['state'],
257
257
  ...(options?.alias != null && { alias: options.alias }),
258
258
  },
259
259
  };
@@ -456,8 +456,8 @@ export class ConnectedAccounts {
456
456
  /**
457
457
  * Waits for a connection request to complete and become active.
458
458
  *
459
- * This method continuously polls the Composio API to check the status of a connection
460
- * until it either becomes active, enters a terminal error state, or times out.
459
+ * This method polls the Composio API, backing off from 1 second to 5 seconds between polls,
460
+ * to check the status of a connection until it either becomes active, enters a terminal error state, or times out.
461
461
  *
462
462
  * @param {string} connectedAccountId - The ID of the connected account to wait for
463
463
  * @param {number} [timeout=60000] - Maximum time to wait in milliseconds (default: 60 seconds)
@@ -19,6 +19,11 @@ import { ComposioConnectedAccountNotFoundError } from '../errors/ConnectedAccoun
19
19
  import { telemetry } from '../telemetry/Telemetry';
20
20
  import { transformConnectedAccountResponse } from '../utils/transformers/connectedAccounts';
21
21
  import { ConnectionRequest, ConnectionRequestState } from '../types/connectionRequest.types';
22
+ import { getRetryAfterSeconds, isRateLimitResponse } from '../utils/rateLimit';
23
+
24
+ const INITIAL_POLL_DELAY_MS = 1000;
25
+ const MAX_POLL_DELAY_MS = 5000;
26
+ const POLL_DELAY_GROWTH = 1.5;
22
27
 
23
28
  /**
24
29
  * Creates a connection request object with methods to manage the connection lifecycle.
@@ -55,8 +60,12 @@ export function createConnectionRequest(
55
60
  /**
56
61
  * Waits for the connection request to complete and become active.
57
62
  *
58
- * This method continuously polls the Composio API to check the status of the connection request
59
- * until it either becomes active, enters a terminal error state, or times out.
63
+ * This method polls the Composio API to check the status of the connection request until it
64
+ * either becomes active, enters a terminal error state, or times out. The delay between polls
65
+ * grows from 1 second to 5 seconds, so a connection can be up to 5 seconds old when this returns.
66
+ * A rate-limited poll doesn't fail the wait: once the client's own retries run out, it waits as
67
+ * long as the response asks, up to the timeout, and polls again. The client's retries can carry
68
+ * the wait past the timeout, because they aren't bound by it.
60
69
  *
61
70
  * @param {number} [timeout=60000] - Maximum time to wait in milliseconds before timing out (default: 60 seconds)
62
71
  * @returns {Promise<ConnectedAccountRetrieveResponse>} The final connected account response when successful
@@ -104,49 +113,44 @@ export function createConnectionRequest(
104
113
  }
105
114
  };
106
115
 
107
- try {
108
- const response = await client.connectedAccounts.retrieve(request.id);
109
- request.status = response.status;
110
- if (response.status === ConnectedAccountStatuses.ACTIVE) {
111
- return transformConnectedAccountResponse(response);
112
- }
113
- failIfTerminal(response);
114
- } catch (error) {
115
- if (error instanceof ComposioClient.NotFoundError) {
116
- throw new ComposioConnectedAccountNotFoundError(
117
- `Connected account with id ${request.id} not found`,
118
- {
119
- meta: {
120
- connectedAccountId: request.id,
121
- },
122
- }
123
- );
124
- } else {
125
- throw error;
126
- }
127
- }
116
+ const deadline = Date.now() + timeout;
117
+ let pollDelay = INITIAL_POLL_DELAY_MS;
128
118
 
129
- const start = Date.now();
130
- const pollInterval = 1000;
131
-
132
- while (Date.now() - start < timeout) {
119
+ while (true) {
120
+ let delay = pollDelay;
133
121
  try {
134
122
  const response = await client.connectedAccounts.retrieve(request.id);
135
-
136
123
  request.status = response.status;
137
124
  if (response.status === ConnectedAccountStatuses.ACTIVE) {
138
125
  return transformConnectedAccountResponse(response);
139
126
  }
140
-
141
127
  failIfTerminal(response);
142
-
143
- await new Promise(resolve => setTimeout(resolve, pollInterval));
144
128
  } catch (error) {
145
- throw error;
129
+ if (error instanceof ComposioClient.NotFoundError) {
130
+ throw new ComposioConnectedAccountNotFoundError(
131
+ `Connected account with id ${request.id} not found`,
132
+ {
133
+ meta: {
134
+ connectedAccountId: request.id,
135
+ },
136
+ }
137
+ );
138
+ }
139
+ if (!isRateLimitResponse(error)) {
140
+ throw error;
141
+ }
142
+ delay = Math.max(delay, (getRetryAfterSeconds(error) ?? 0) * 1000);
146
143
  }
147
- }
148
144
 
149
- throw new ConnectionRequestTimeoutError(`Connection request timed out for ${request.id}`);
145
+ const remaining = deadline - Date.now();
146
+ // Written so a NaN timeout times out rather than polling forever.
147
+ if (!(remaining > 0)) {
148
+ throw new ConnectionRequestTimeoutError(`Connection request timed out for ${request.id}`);
149
+ }
150
+ // This delay stops at the deadline, so the last poll happens as the time runs out.
151
+ await new Promise(resolve => setTimeout(resolve, Math.min(delay, remaining)));
152
+ pollDelay = Math.min(pollDelay * POLL_DELAY_GROWTH, MAX_POLL_DELAY_MS);
153
+ }
150
154
  }
151
155
 
152
156
  return request;