@composio/core 0.29.0 → 0.30.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 (70) hide show
  1. package/README.md +23 -0
  2. package/dist/{CustomTool-Bd1KdWvo.mjs → CustomTool-9Vlb4XaS.mjs} +4 -7
  3. package/dist/{CustomTool-CMW-d2ZN.d.mts → CustomTool-Dzk3iqfP.d.mts} +2 -4
  4. package/dist/FileModifierErrors-WrqokuIF.mjs +199 -0
  5. package/dist/{FileToolModifier.utils.neutral-DWFpnsj2.mjs → FileToolModifier.utils.neutral-BQP85ZJj.mjs} +1 -2
  6. package/dist/{SsrfErrors-DiQldIdC.mjs → SsrfErrors-BSVMW915.mjs} +49 -26
  7. package/dist/{Telemetry-D2PJwXKx.mjs → Telemetry-a7SOQXcg.mjs} +6 -10
  8. package/dist/{composio-D5UV5HXN.d.mts → composio-DaokW5sV.d.mts} +229 -284
  9. package/dist/{customTool.types-B9fs34dv.d.mts → customTool.types-CpJbzxT6.d.mts} +182 -245
  10. package/dist/docs/error-consistency.md +3 -3
  11. package/dist/docs/reference/sdk-reference/typescript/composio.mdx +1 -0
  12. package/dist/docs/reference/sdk-reference/typescript/custom-toolkits.mdx +6 -11
  13. package/dist/docs/reference/sdk-reference/typescript/experimental.mdx +1 -1
  14. package/dist/docs/reference/sdk-reference/typescript/index.mdx +1 -1
  15. package/dist/docs/reference/sdk-reference/typescript/remote-file.mdx +1 -1
  16. package/dist/{errors-BK6Xc7Ia.mjs → errors-xC13uvaA.mjs} +56 -139
  17. package/dist/experimental/index.d.mts +16 -2
  18. package/dist/experimental/index.mjs +1 -1
  19. package/dist/{fileUtils.node-ILI1IjnZ.mjs → fileUtils.node-CAwIbWYH.mjs} +6 -8
  20. package/dist/{files.types-DeMC_mAW.d.mts → files.types-Dg6HcEzs.d.mts} +0 -2
  21. package/dist/index.d.mts +40 -75
  22. package/dist/index.mjs +281 -243
  23. package/dist/{cancellation-BoJjs34Y.mjs → jsonSchema-Cc4EtHRw.mjs} +5 -22
  24. package/dist/models/Files.node.d.mts +32 -13
  25. package/dist/models/Files.node.mjs +36 -19
  26. package/dist/models/Files.workerd.d.mts +8 -3
  27. package/dist/models/Files.workerd.mjs +1 -2
  28. package/dist/platform/node.d.mts +2 -4
  29. package/dist/platform/node.mjs +15 -16
  30. package/dist/platform/workerd.d.mts +2 -4
  31. package/dist/platform/workerd.mjs +1 -2
  32. package/dist/requestOptions.types-DWrTcbss.d.mts +38 -0
  33. package/dist/rolldown-runtime-ad2WFvuA.mjs +17 -0
  34. package/dist/{sensitiveFileUploadPaths-BaEORC7-.mjs → sensitiveFileUploadPaths-CSyJ3Ku8.mjs} +22 -12
  35. package/dist/{ssrfGuard.node-BZ270bcu.mjs → ssrfGuard.node-CdIkwqVu.mjs} +3 -5
  36. package/dist/{types-CaP2SytR.d.mts → types-DQdUb7OG.d.mts} +2 -4
  37. package/dist/{types-DuVZKrXO.d.mts → types-Ds6XbK1m.d.mts} +0 -2
  38. package/dist/utils/config-defaults/ConfigDefaults.node.d.mts +2 -4
  39. package/dist/utils/config-defaults/ConfigDefaults.node.mjs +1 -2
  40. package/dist/utils/config-defaults/ConfigDefaults.workerd.d.mts +2 -4
  41. package/dist/utils/config-defaults/ConfigDefaults.workerd.mjs +1 -2
  42. package/dist/utils/modifiers/FileToolModifier.node.d.mts +2 -4
  43. package/dist/utils/modifiers/FileToolModifier.node.mjs +7 -8
  44. package/dist/utils/modifiers/FileToolModifier.workerd.d.mts +2 -4
  45. package/dist/utils/modifiers/FileToolModifier.workerd.mjs +2 -3
  46. package/dist/utils/ssrfGuard.node.d.mts +1 -3
  47. package/dist/utils/ssrfGuard.node.mjs +1 -1
  48. package/dist/utils/ssrfGuard.workerd.d.mts +1 -3
  49. package/dist/utils/ssrfGuard.workerd.mjs +2 -3
  50. package/docs/error-consistency.md +3 -3
  51. package/package.json +12 -13
  52. package/src/composio.ts +12 -0
  53. package/src/errors/ComposioError.ts +40 -16
  54. package/src/errors/ConnectedAccountsErrors.ts +2 -2
  55. package/src/errors/ToolErrors.ts +107 -30
  56. package/src/errors/apiErrorDetails.ts +40 -0
  57. package/src/models/ConnectionRequest.ts +12 -4
  58. package/src/models/CustomToolkits.ts +11 -17
  59. package/src/models/Experimental.ts +2 -7
  60. package/src/models/Files.node.ts +68 -37
  61. package/src/models/RemoteFile.ts +22 -16
  62. package/src/models/SessionContext.ts +6 -7
  63. package/src/models/ToolRouterSession.ts +16 -23
  64. package/src/models/Tools.ts +218 -20
  65. package/src/models/Triggers.ts +8 -2
  66. package/src/types/customToolkits.types.ts +4 -9
  67. package/src/utils/cancellation.ts +5 -1
  68. package/dist/FileModifierErrors-CdGSABoq.mjs +0 -97
  69. package/dist/rolldown-runtime-w6R9maHv.mjs +0 -18
  70. package/src/models/inlineCustomToolsPayload.ts +0 -17
@@ -1,4 +1,3 @@
1
- //#region src/utils/ssrfGuard.node.d.ts
2
1
  export interface SsrfSafeFetchOptions {
3
2
  /** Maximum number of redirects to follow. Defaults to 5. */
4
3
  maxRedirects?: number;
@@ -46,5 +45,4 @@ export declare const ssrfSafeFetch: (rawUrl: string, init?: RequestInit, options
46
45
  * feature from Workers rather than close a hole reachable there. On Node this
47
46
  * is the full guard; only the edge build differs.
48
47
  */
49
- export declare const ssrfSafeFetchWhereSupported: (rawUrl: string, init?: RequestInit, optionsOrMaxRedirects?: SsrfSafeFetchOptions | number) => Promise<Response>;
50
- //#endregion
48
+ export declare const ssrfSafeFetchWhereSupported: (rawUrl: string, init?: RequestInit, optionsOrMaxRedirects?: SsrfSafeFetchOptions | number) => Promise<Response>;
@@ -1,3 +1,3 @@
1
- import { i as ssrfSafeFetchWhereSupported, n as isBlockedIp, r as ssrfSafeFetch, t as assertSafeFetchTarget } from "../ssrfGuard.node-BZ270bcu.mjs";
1
+ import { i as ssrfSafeFetchWhereSupported, n as isBlockedIp, r as ssrfSafeFetch, t as assertSafeFetchTarget } from "../ssrfGuard.node-CdIkwqVu.mjs";
2
2
 
3
3
  export { assertSafeFetchTarget, isBlockedIp, ssrfSafeFetch, ssrfSafeFetchWhereSupported };
@@ -1,4 +1,3 @@
1
- //#region src/utils/ssrfGuard.workerd.d.ts
2
1
  export interface SsrfSafeFetchOptions {
3
2
  /** Maximum number of redirects to follow. Defaults to 5. */
4
3
  maxRedirects?: number;
@@ -25,5 +24,4 @@ export declare const ssrfSafeFetch: (rawUrl: string, _init?: RequestInit, _optio
25
24
  * check, and its `fetch` does not originate inside the caller's network. The
26
25
  * Node build applies the full guard.
27
26
  */
28
- export declare const ssrfSafeFetchWhereSupported: (rawUrl: string, init?: RequestInit) => Promise<Response>;
29
- //#endregion
27
+ export declare const ssrfSafeFetchWhereSupported: (rawUrl: string, init?: RequestInit) => Promise<Response>;
@@ -1,6 +1,6 @@
1
- import { t as ComposioBlockedInternalUrlError } from "../SsrfErrors-DiQldIdC.mjs";
1
+ import { t as ComposioBlockedInternalUrlError } from "../SsrfErrors-BSVMW915.mjs";
2
2
 
3
- //#region src/utils/ssrfGuard.workerd.ts
3
+ // src/utils/ssrfGuard.workerd.ts
4
4
  /**
5
5
  * Edge runtimes do not expose the DNS resolution APIs needed to prove that a
6
6
  * hostname is publicly routable before connecting. Fail closed instead of
@@ -25,5 +25,4 @@ const ssrfSafeFetch = async (rawUrl, _init = {}, _optionsOrMaxRedirects = {}) =>
25
25
  */
26
26
  const ssrfSafeFetchWhereSupported = async (rawUrl, init = {}) => fetch(rawUrl, init);
27
27
 
28
- //#endregion
29
28
  export { ssrfSafeFetch, ssrfSafeFetchWhereSupported };
@@ -44,9 +44,9 @@ Some error classes have specific requirements:
44
44
  new ValidationError('Message', { cause: someZodError });
45
45
  ```
46
46
 
47
- 2. **ComposioToolExecutionError**: Accepts an `originalError` in the options.
47
+ 2. **ComposioToolExecutionError**: Keeps the failure it wraps as `cause`. The base `ComposioError` reads `statusCode`, `requestId`, and `apiErrorCode` from an `APIError` cause.
48
48
  ```typescript
49
- new ComposioToolExecutionError('Message', { originalError: someError });
49
+ new ComposioToolExecutionError('Message', { cause: someError });
50
50
  ```
51
51
 
52
52
  ## Using Error Classes
@@ -72,7 +72,7 @@ try {
72
72
  } catch (error) {
73
73
  // Handle tool execution errors
74
74
  throw new ComposioToolExecutionError('Tool failed', {
75
- originalError: error,
75
+ cause: error,
76
76
  meta: { toolId: 'some-tool' },
77
77
  });
78
78
 
package/package.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "engines": {
5
5
  "node": ">=22.22.3"
6
6
  },
7
- "version": "0.29.0",
7
+ "version": "0.30.0",
8
8
  "description": "",
9
9
  "main": "dist/index.mjs",
10
10
  "publishConfig": {
@@ -111,34 +111,33 @@
111
111
  ],
112
112
  "license": "ISC",
113
113
  "devDependencies": {
114
- "@hono/node-server": "^2.1.5",
115
- "@type-challenges/utils": "^0.1.1",
114
+ "@hono/node-server": "^2.1.6",
116
115
  "@types/semver": "^7.8.0",
117
116
  "ajv": "^8.20.0",
118
117
  "fast-check": "^4.10.2",
119
- "hono": "^4.13.13",
120
- "mime": "^4.1.1",
121
- "tsdown": "^0.23.1",
118
+ "hono": "^4.13.18",
119
+ "mime": "^4.1.2",
120
+ "tsdown": "^0.23.7",
122
121
  "tsx": "^4.23.15",
123
122
  "typedoc": "^0.28.20",
124
123
  "typescript": "npm:@typescript/typescript6@^6.0.2",
125
- "vitest": "^5.0.5",
126
- "zod": "^4.5.4"
124
+ "vitest": "^5.1.0",
125
+ "zod": "^4.6.7"
127
126
  },
128
127
  "peerDependencies": {
129
128
  "zod": ">=3.25.76 <5"
130
129
  },
131
130
  "dependencies": {
132
- "@composio/client": "2.1.0",
131
+ "@composio/client": "2.1.33",
133
132
  "@types/json-schema": "^7.0.15",
134
133
  "is-fs-case-sensitive": "^2.0.0",
135
- "openai": "^7.39.0",
134
+ "openai": "^7.55.0",
136
135
  "picocolors": "^1.1.1",
137
136
  "pusher-js": "^8.6.0",
138
- "semver": "^7.8.5",
139
- "undici": "^7.30.1",
137
+ "semver": "^7.8.6",
138
+ "undici": "^7.30.2",
140
139
  "zod-to-json-schema": "^3.25.2",
141
- "@composio/json-schema-to-zod": "0.4.0"
140
+ "@composio/json-schema-to-zod": "0.4.1"
142
141
  },
143
142
  "gitHead": "4fae6e54d5c150fba955cc5fa314281da5a1e064",
144
143
  "repository": {
package/src/composio.ts CHANGED
@@ -8,6 +8,7 @@ import { Triggers } from './models/Triggers';
8
8
  import { AuthConfigs } from './models/AuthConfigs';
9
9
  import { ConnectedAccounts } from './models/ConnectedAccounts';
10
10
  import { Experimental } from './models/Experimental';
11
+ import { CustomToolkits } from './models/CustomToolkits';
11
12
  import { MCP } from './models/MCP';
12
13
  import { Webhooks } from './models/Webhooks';
13
14
  import { Logs } from './models/Logs';
@@ -353,6 +354,16 @@ export class Composio<
353
354
  logs: Logs;
354
355
  /** Public transfer keys of the organization's customer-managed keyring */
355
356
  keyring: Keyring;
357
+ /**
358
+ * Register and manage project-owned custom toolkits, such as a remote MCP
359
+ * server (`create()` / `update()` / `sync()` / `delete()`).
360
+ *
361
+ * @example
362
+ * ```typescript
363
+ * await composio.customToolkits.sync('CUSTOM_MY_TOOLKIT');
364
+ * ```
365
+ */
366
+ customToolkits: CustomToolkits;
356
367
  /**
357
368
  * Experimental SDK methods whose shape may change in future releases.
358
369
  * Prefer domain-specific mounts (for example
@@ -576,6 +587,7 @@ export class Composio<
576
587
  this.logs = new Logs(this.client);
577
588
  this.keyring = new Keyring(this.client);
578
589
  this.experimental = new Experimental(this.client);
590
+ this.customToolkits = this.experimental.customToolkits;
579
591
  this.sessions = new Sessions(this.client, this.config);
580
592
  this.toolRouter = this.sessions;
581
593
  this.sessionConfigs = new SessionConfigs(this.client);
@@ -10,8 +10,9 @@
10
10
  */
11
11
  import pc from 'picocolors';
12
12
  import { ZodError } from 'zod/v3';
13
- import { BadRequestError } from '@composio/client';
13
+ import { APIError } from '@composio/client';
14
14
  import logger from '../utils/logger';
15
+ import { sanitizeApiErrorText } from './apiErrorDetails';
15
16
 
16
17
  /**
17
18
  * Options for error handling
@@ -31,8 +32,12 @@ export interface ErrorHandleOptions {
31
32
  export type ComposioErrorOptions = {
32
33
  /** Error code for categorizing errors */
33
34
  code?: string;
34
- /** HTTP status code associated with the error */
35
+ /** HTTP status code associated with the error. Defaults to the status of an `APIError` cause. */
35
36
  statusCode?: number;
37
+ /** Request id the API assigned. Defaults to the request id of an `APIError` cause. */
38
+ requestId?: string;
39
+ /** Numeric `error.code` of a Composio API error response. Defaults to the code of an `APIError` cause. */
40
+ apiErrorCode?: number;
36
41
  /** The underlying cause of the error */
37
42
  cause?: unknown;
38
43
  /** Additional metadata associated with the error */
@@ -52,6 +57,7 @@ interface ErrorFormatData {
52
57
  message: string;
53
58
  code?: string;
54
59
  statusCode?: number;
60
+ apiErrorCode?: number;
55
61
  cause?: string;
56
62
  meta?: Record<string, unknown>;
57
63
  possibleFixes?: string[];
@@ -67,6 +73,14 @@ export class ComposioError extends Error {
67
73
  public code?: string;
68
74
  public possibleFixes?: string[];
69
75
  public errorId?: string;
76
+ /** HTTP status of the response behind the error, when there was one. */
77
+ declare public readonly statusCode?: number;
78
+ /** Request id the Composio API assigned to the request behind the error, when it sent one. */
79
+ declare public readonly requestId?: string;
80
+ /** Numeric `error.code` the Composio API sent, when the response carried one. */
81
+ declare public readonly apiErrorCode?: number;
82
+ /** Additional metadata associated with the error. */
83
+ declare public readonly meta?: Record<string, unknown>;
70
84
 
71
85
  /**
72
86
  * Creates a new ComposioError
@@ -81,10 +95,11 @@ export class ComposioError extends Error {
81
95
  Error.captureStackTrace(this, this.constructor);
82
96
  }
83
97
 
84
- // Process the status code - either from options or from the cause if it's a BadRequestError
85
- const statusCode =
86
- options.statusCode ||
87
- (options.cause instanceof BadRequestError ? options.cause.status : undefined);
98
+ // Transport metadata: explicit options win, otherwise read it from an API error cause
99
+ const apiCause = options.cause instanceof APIError ? options.cause : undefined;
100
+ const statusCode = options.statusCode ?? apiCause?.status;
101
+ const requestId = options.requestId ?? apiCause?.requestId;
102
+ const apiErrorCode = options.apiErrorCode ?? apiCause?.details?.code;
88
103
 
89
104
  this.code = `TS-SDK::${options.code}`;
90
105
  // format the possible fixes
@@ -93,6 +108,8 @@ export class ComposioError extends Error {
93
108
  // Only define properties that have values to avoid showing undefined in error display
94
109
  // Node.js by default shows all the properties of the error object, so we are doing it conditionally
95
110
  this.definePropertyIfExists('statusCode', statusCode);
111
+ this.definePropertyIfExists('requestId', requestId);
112
+ this.definePropertyIfExists('apiErrorCode', apiErrorCode);
96
113
  this.definePropertyIfExists('cause', options.cause);
97
114
 
98
115
  const combinedStack =
@@ -156,19 +173,17 @@ export class ComposioError extends Error {
156
173
  message: this.message,
157
174
  };
158
175
 
159
- const { cause, code, stack, statusCode, meta, possibleFixes } = this as unknown as {
160
- cause: unknown;
161
- code: string | undefined;
162
- stack: string | undefined;
163
- statusCode: number | undefined;
164
- meta: Record<string, unknown> | undefined;
165
- possibleFixes: string[] | undefined;
166
- };
176
+ const { cause, code, stack, statusCode, apiErrorCode, meta, possibleFixes } = this;
167
177
 
168
- // Format cause properly if it exists
178
+ // Format cause properly if it exists. An API cause is server-controlled text.
169
179
  if (cause !== undefined) {
170
180
  const rawCause = cause;
171
- data.cause = rawCause instanceof Error ? rawCause.message : String(rawCause);
181
+ data.cause =
182
+ rawCause instanceof APIError
183
+ ? sanitizeApiErrorText(rawCause.message)
184
+ : rawCause instanceof Error
185
+ ? rawCause.message
186
+ : sanitizeApiErrorText(String(rawCause));
172
187
  }
173
188
 
174
189
  // Add code if exists
@@ -181,6 +196,11 @@ export class ComposioError extends Error {
181
196
  data.statusCode = statusCode;
182
197
  }
183
198
 
199
+ // Add the API's numeric error code if exists
200
+ if (apiErrorCode !== undefined) {
201
+ data.apiErrorCode = apiErrorCode;
202
+ }
203
+
184
204
  // Add meta if exists
185
205
  if (meta) {
186
206
  data.meta = meta;
@@ -226,6 +246,10 @@ export class ComposioError extends Error {
226
246
  output += pc.yellow(`Status: ${data.statusCode}`) + '\n';
227
247
  }
228
248
 
249
+ if (data.apiErrorCode !== undefined) {
250
+ output += pc.yellow(`API Error Code: ${data.apiErrorCode}`) + '\n';
251
+ }
252
+
229
253
  if (data.cause) {
230
254
  output += pc.gray('Reason:') + '\n';
231
255
  output += ' ' + pc.white(data.cause) + '\n';
@@ -15,12 +15,12 @@ export const ConnectedAccountErrorCodes = {
15
15
  export class ComposioConnectedAccountNotFoundError extends ComposioError {
16
16
  constructor(
17
17
  message: string = 'Connected account not found',
18
- options: Omit<ComposioErrorOptions, 'code' | 'statusCode'> = {}
18
+ options: Omit<ComposioErrorOptions, 'code'> = {}
19
19
  ) {
20
20
  super(message, {
21
21
  ...options,
22
22
  code: ConnectedAccountErrorCodes.CONNECTED_ACCOUNT_NOT_FOUND,
23
- statusCode: 404,
23
+ statusCode: options.statusCode ?? 404,
24
24
  possibleFixes: options.possibleFixes || [
25
25
  'Ensure the connected account exists and is active in your Composio dashboard',
26
26
  ],
@@ -1,12 +1,18 @@
1
- import { APIError } from '@composio/client';
1
+ import { APIError, type APIErrorBody } from '@composio/client';
2
2
  import { ComposioError, ComposioErrorOptions } from './ComposioError';
3
3
  import { ComposioConnectedAccountNotFoundError } from './ConnectedAccountsErrors';
4
4
  import { getRetryAfterSeconds, isRateLimitResponse } from '../utils/rateLimit';
5
+ import {
6
+ apiErrorSuggestedFixes,
7
+ sanitizeApiErrorText,
8
+ withApiErrorMessage,
9
+ } from './apiErrorDetails';
5
10
 
6
11
  export const ToolErrorCodes = {
7
12
  TOOLSET_NOT_DEFINED: 'TOOLSET_NOT_DEFINED',
8
13
  TOOL_NOT_FOUND: 'TOOL_NOT_FOUND',
9
14
  TOOL_FETCH_ERROR: 'TOOL_FETCH_ERROR',
15
+ TOOL_SCHEMA_INVALID: 'TOOL_SCHEMA_INVALID',
10
16
  INVALID_MODIFIER: 'INVALID_MODIFIER',
11
17
  TOOL_EXECUTION_ERROR: 'TOOL_EXECUTION_ERROR',
12
18
  INVALID_TOOL_ARGUMENTS: 'INVALID_TOOL_ARGUMENTS',
@@ -70,6 +76,30 @@ export class ComposioToolFetchError extends ComposioError {
70
76
  }
71
77
  }
72
78
 
79
+ /**
80
+ * Error thrown when a tool was retrieved but its declared parameters cannot be
81
+ * parsed, so the tool cannot be offered. Distinct from
82
+ * `ComposioToolNotFoundError`: the tool exists, its schema is what is broken,
83
+ * and a caller that treats `TOOL_NOT_FOUND` as "no such tool" would otherwise
84
+ * report a real tool as missing.
85
+ */
86
+ export class ComposioToolSchemaInvalidError extends ComposioError {
87
+ constructor(
88
+ message: string = 'Tool schema is invalid',
89
+ options: Omit<ComposioErrorOptions, 'code' | 'statusCode'> = {}
90
+ ) {
91
+ super(message, {
92
+ ...options,
93
+ code: ToolErrorCodes.TOOL_SCHEMA_INVALID,
94
+ possibleFixes: options.possibleFixes || [
95
+ 'The tool exists but its declared input schema could not be parsed',
96
+ 'Report the tool slug to Composio so the schema can be corrected',
97
+ ],
98
+ });
99
+ this.name = 'ComposioToolSchemaInvalidError';
100
+ }
101
+ }
102
+
73
103
  /** Error options for a 429. Leaves out an unknown wait, as `ComposioError` does for unset fields. */
74
104
  const rateLimitOptions = (cause: APIError, meta: Record<string, unknown>) => {
75
105
  const retryAfterSeconds = getRetryAfterSeconds(cause);
@@ -78,7 +108,7 @@ const rateLimitOptions = (cause: APIError, meta: Record<string, unknown>) => {
78
108
  cause,
79
109
  statusCode: 429,
80
110
  meta: retryAfterSeconds === undefined ? meta : { ...meta, retryAfterSeconds },
81
- possibleFixes: [
111
+ possibleFixes: apiErrorSuggestedFixes(cause.details) ?? [
82
112
  retryAfterSeconds === undefined
83
113
  ? 'Wait before retrying'
84
114
  : `Wait ${Math.ceil(retryAfterSeconds)} seconds, then retry`,
@@ -121,8 +151,14 @@ export class ComposioInvalidModifierError extends ComposioError {
121
151
  }
122
152
  }
123
153
 
154
+ /** Options for a `ComposioToolExecutionError`. */
155
+ export type ComposioToolExecutionErrorOptions = ComposioErrorOptions;
156
+
124
157
  export class ComposioToolExecutionError extends ComposioError {
125
- constructor(message: string = 'Tool execution error', options: ComposioErrorOptions = {}) {
158
+ constructor(
159
+ message: string = 'Tool execution error',
160
+ options: ComposioToolExecutionErrorOptions = {}
161
+ ) {
126
162
  super(message, {
127
163
  ...options,
128
164
  code: options.code || ToolErrorCodes.TOOL_EXECUTION_ERROR,
@@ -295,47 +331,88 @@ export class ComposioToolVersionRequiredError extends ComposioError {
295
331
  this.name = 'ComposioToolVersionRequiredError';
296
332
  }
297
333
  }
298
- export interface ComposioAPIServerErrorBody {
299
- error: {
300
- message: string;
301
- code: number;
302
- status: number;
303
- request_id: string;
304
- suggested_fix: string;
305
- };
306
- }
334
+ /** The error envelope of a Composio API error response, as `@composio/client` validates it. */
335
+ export type ComposioAPIServerErrorBody = APIErrorBody;
336
+
337
+ type APIErrorDetails = NonNullable<APIError['details']>;
307
338
 
308
339
  // Map of error codes to their corresponding error constructors
309
- const ERROR_CODE_HANDLERS = new Map<number, (message: string) => ComposioError>([
310
- [1803, msg => new ComposioConnectedAccountNotFoundError(msg)],
340
+ const ERROR_CODE_HANDLERS = new Map<
341
+ number,
342
+ (details: APIErrorDetails, cause: APIError) => ComposioError
343
+ >([
344
+ [
345
+ 1803,
346
+ (details, cause) =>
347
+ new ComposioConnectedAccountNotFoundError(
348
+ sanitizeApiErrorText(details.message || 'An error occurred'),
349
+ {
350
+ cause,
351
+ statusCode: cause.status,
352
+ possibleFixes: apiErrorSuggestedFixes(details),
353
+ }
354
+ ),
355
+ ],
311
356
  // Add more error code handlers here as needed
312
357
  ]);
313
358
 
359
+ /** What to try when the API rejected an execution without a `suggested_fix`, by HTTP status. */
360
+ const fallbackExecutionFixes = (status: number | undefined): string[] => {
361
+ if (status === 401) {
362
+ return ['Ensure you are using a valid Composio API key for this project'];
363
+ }
364
+ if (status === 402) {
365
+ return ['Check the plan and billing limits of your Composio organization'];
366
+ }
367
+ if (status === 403) {
368
+ return ['Ensure your API key and the connected account are allowed to run this tool'];
369
+ }
370
+ if (status === 410) {
371
+ return ['The tool or the resource it acts on is no longer available; see the error message'];
372
+ }
373
+ if (status !== undefined && status >= 500) {
374
+ return [
375
+ 'The Composio API failed to process the request; retry later',
376
+ 'If it keeps failing, contact Composio support with the request id',
377
+ ];
378
+ }
379
+ return ['Ensure the tool slug is correct and the input arguments for the tool is valid'];
380
+ };
381
+
314
382
  export const handleToolExecutionError = (tool: string, actualError: Error): ComposioError => {
315
- // Handle specific API error codes
316
- if (actualError instanceof APIError && actualError.error) {
317
- const errorBody = actualError.error as ComposioAPIServerErrorBody;
318
- const errorCode = errorBody?.error?.code;
319
- const errorMessage = errorBody?.error?.message;
383
+ // Already an SDK error, including a caller cancellation: keep its type.
384
+ if (actualError instanceof ComposioError) {
385
+ return actualError;
386
+ }
320
387
 
321
- if (errorCode && ERROR_CODE_HANDLERS.has(errorCode)) {
322
- return ERROR_CODE_HANDLERS.get(errorCode)!(errorMessage || 'An error occurred');
323
- }
388
+ const apiError = actualError instanceof APIError ? actualError : undefined;
389
+ const details = apiError?.details;
390
+
391
+ // Handle specific API error codes
392
+ if (apiError && details && ERROR_CODE_HANDLERS.has(details.code)) {
393
+ return ERROR_CODE_HANDLERS.get(details.code)!(details, apiError);
324
394
  }
325
395
 
326
396
  if (isRateLimitResponse(actualError)) {
327
397
  return new ComposioToolExecutionRateLimitError(
328
- `Rate limited while executing the tool ${tool}`,
398
+ withApiErrorMessage(`Rate limited while executing the tool ${tool}`, actualError.details),
329
399
  actualError,
330
400
  { slug: tool }
331
401
  );
332
402
  }
333
403
 
334
- // Default error for all other cases
335
- return new ComposioToolExecutionError(`Error executing the tool ${tool}`, {
336
- cause: actualError,
337
- possibleFixes: [
338
- 'Ensure the tool slug is correct and the input arguments for the tool is valid',
339
- ],
340
- });
404
+ // Keep the reason of a failure that never reached the API (timeout,
405
+ // connection error, a non-API throw). An HTTP response without the error
406
+ // envelope keeps the tool context alone, as its raw body is unvalidated.
407
+ const originalMessage = apiError?.status === undefined ? actualError.message : undefined;
408
+
409
+ // Default error for all other cases. `statusCode`, `requestId` and `apiErrorCode`
410
+ // come from the APIError cause.
411
+ return new ComposioToolExecutionError(
412
+ withApiErrorMessage(`Error executing the tool ${tool}`, details, originalMessage),
413
+ {
414
+ cause: actualError,
415
+ possibleFixes: apiErrorSuggestedFixes(details) ?? fallbackExecutionFixes(apiError?.status),
416
+ }
417
+ );
341
418
  };
@@ -0,0 +1,40 @@
1
+ /**
2
+ * @fileoverview Helpers for lifting the Composio API error envelope onto SDK errors.
3
+ *
4
+ * Not exported from the error barrel: these are implementation details shared by
5
+ * the tool error classes and the models that wrap API failures.
6
+ *
7
+ * @module errors/apiErrorDetails
8
+ */
9
+ import type { APIError } from '@composio/client';
10
+
11
+ // CSI, OSC, and other ESC sequences a terminal would act on.
12
+ const ANSI_ESCAPE = /\u001b(?:\[[0-?]*[ -/]*[@-~]|\][^\u0007\u001b]*(?:\u0007|\u001b\\)|[@-_])/g;
13
+ // C0/C1 controls, DEL, and the Unicode line separators that can forge output lines.
14
+ const CONTROL_CHARACTERS = /[\u0000-\u001f\u007f-\u009f\u2028\u2029]/g;
15
+
16
+ /** Make a server-controlled string safe to print in a terminal or a single log line. */
17
+ export const sanitizeApiErrorText = (value: string): string =>
18
+ value.replace(ANSI_ESCAPE, ' ').replace(CONTROL_CHARACTERS, ' ').replace(/\s+/g, ' ').trim();
19
+
20
+ /**
21
+ * Prefix a message with the API's own message, when the response carried one.
22
+ * `fallback` is the underlying error's message for failures without an HTTP
23
+ * response, such as a timeout or a connection error.
24
+ */
25
+ export const withApiErrorMessage = (
26
+ message: string,
27
+ details: APIError['details'],
28
+ fallback?: string
29
+ ): string => {
30
+ const reason = details?.message ?? fallback;
31
+ const safeReason = reason ? sanitizeApiErrorText(reason) : '';
32
+ return safeReason ? `${message}: ${safeReason}` : message;
33
+ };
34
+
35
+ /** The API's `suggested_fix` as a one-item list, or nothing so the caller's default applies. */
36
+ export const apiErrorSuggestedFixes = (details: APIError['details']): string[] | undefined => {
37
+ const fix = details?.suggested_fix;
38
+ const safeFix = fix ? sanitizeApiErrorText(fix) : '';
39
+ return safeFix ? [safeFix] : undefined;
40
+ };
@@ -64,8 +64,9 @@ export function createConnectionRequest(
64
64
  * either becomes active, enters a terminal error state, or times out. The delay between polls
65
65
  * grows from 1 second to 5 seconds, so a connection can be up to 5 seconds old when this returns.
66
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.
67
+ * long as the response asks before polling again. If that delay reaches the timeout, the wait
68
+ * times out without another poll. The client's retries can carry the wait past the timeout,
69
+ * because they aren't bound by it.
69
70
  *
70
71
  * @param {number} [timeout=60000] - Maximum time to wait in milliseconds before timing out (default: 60 seconds)
71
72
  * @returns {Promise<ConnectedAccountRetrieveResponse>} The final connected account response when successful
@@ -118,6 +119,7 @@ export function createConnectionRequest(
118
119
 
119
120
  while (true) {
120
121
  let delay = pollDelay;
122
+ let rateLimited = false;
121
123
  try {
122
124
  const response = await client.connectedAccounts.retrieve(request.id);
123
125
  request.status = response.status;
@@ -139,18 +141,24 @@ export function createConnectionRequest(
139
141
  if (!isRateLimitResponse(error)) {
140
142
  throw error;
141
143
  }
144
+ rateLimited = true;
142
145
  delay = Math.max(delay, (getRetryAfterSeconds(error) ?? 0) * 1000);
143
146
  }
144
147
 
145
148
  const remaining = deadline - Date.now();
146
149
  // Written so a NaN timeout times out rather than polling forever.
147
150
  if (!(remaining > 0)) {
148
- throw new ConnectionRequestTimeoutError(`Connection request timed out for ${request.id}`);
151
+ break;
149
152
  }
150
- // This delay stops at the deadline, so the last poll happens as the time runs out.
151
153
  await new Promise(resolve => setTimeout(resolve, Math.min(delay, remaining)));
154
+ // A rate-limited poll must not start a fresh client retry cycle at the deadline.
155
+ if (rateLimited && Date.now() >= deadline) {
156
+ break;
157
+ }
152
158
  pollDelay = Math.min(pollDelay * POLL_DELAY_GROWTH, MAX_POLL_DELAY_MS);
153
159
  }
160
+
161
+ throw new ConnectionRequestTimeoutError(`Connection request timed out for ${request.id}`);
154
162
  }
155
163
 
156
164
  return request;