@composio/core 0.28.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 (85) hide show
  1. package/README.md +25 -0
  2. package/dist/{CustomTool-BYHB7sPs.mjs → CustomTool-9Vlb4XaS.mjs} +12 -14
  3. package/dist/{CustomTool-DyypijT6.d.mts → CustomTool-Dzk3iqfP.d.mts} +10 -11
  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-CwHMpKXb.d.mts → composio-DaokW5sV.d.mts} +220 -254
  9. package/dist/{customTool.types-DoItUHkO.d.mts → customTool.types-CpJbzxT6.d.mts} +255 -274
  10. package/dist/docs/error-consistency.md +3 -3
  11. package/dist/docs/reference/sdk-reference/typescript/composio.mdx +2 -1
  12. package/dist/docs/reference/sdk-reference/typescript/connected-accounts.mdx +2 -2
  13. package/dist/docs/reference/sdk-reference/typescript/custom-toolkits.mdx +88 -10
  14. package/dist/docs/reference/sdk-reference/typescript/experimental.mdx +1 -1
  15. package/dist/docs/reference/sdk-reference/typescript/index.mdx +1 -1
  16. package/dist/docs/reference/sdk-reference/typescript/remote-file.mdx +1 -1
  17. package/dist/docs/reference/sdk-reference/typescript/session-configs.mdx +1 -1
  18. package/dist/docs/reference/sdk-reference/typescript/session.mdx +48 -10
  19. package/dist/docs/reference/sdk-reference/typescript/sessions.mdx +6 -6
  20. package/dist/docs/reference/sdk-reference/typescript/tools.mdx +4 -4
  21. package/dist/docs/reference/sdk-reference/typescript/triggers.mdx +5 -1
  22. package/dist/{errors-Cly0vXFh.mjs → errors-xC13uvaA.mjs} +116 -135
  23. package/dist/experimental/index.d.mts +17 -3
  24. package/dist/experimental/index.mjs +1 -1
  25. package/dist/{fileUtils.node-ILI1IjnZ.mjs → fileUtils.node-CAwIbWYH.mjs} +6 -8
  26. package/dist/{files.types-DeMC_mAW.d.mts → files.types-Dg6HcEzs.d.mts} +0 -2
  27. package/dist/index.d.mts +73 -78
  28. package/dist/index.mjs +393 -290
  29. package/dist/{cancellation-ZoRh6EJQ.mjs → jsonSchema-Cc4EtHRw.mjs} +5 -22
  30. package/dist/models/Files.node.d.mts +32 -13
  31. package/dist/models/Files.node.mjs +36 -19
  32. package/dist/models/Files.workerd.d.mts +8 -3
  33. package/dist/models/Files.workerd.mjs +1 -2
  34. package/dist/platform/node.d.mts +2 -4
  35. package/dist/platform/node.mjs +15 -16
  36. package/dist/platform/workerd.d.mts +2 -4
  37. package/dist/platform/workerd.mjs +1 -2
  38. package/dist/requestOptions.types-DWrTcbss.d.mts +38 -0
  39. package/dist/rolldown-runtime-ad2WFvuA.mjs +17 -0
  40. package/dist/{sensitiveFileUploadPaths-BaEORC7-.mjs → sensitiveFileUploadPaths-CSyJ3Ku8.mjs} +22 -12
  41. package/dist/{ssrfGuard.node-BZ270bcu.mjs → ssrfGuard.node-CdIkwqVu.mjs} +3 -5
  42. package/dist/{types-DWZWePfZ.d.mts → types-DQdUb7OG.d.mts} +2 -4
  43. package/dist/{types-DuVZKrXO.d.mts → types-Ds6XbK1m.d.mts} +0 -2
  44. package/dist/utils/config-defaults/ConfigDefaults.node.d.mts +2 -4
  45. package/dist/utils/config-defaults/ConfigDefaults.node.mjs +1 -2
  46. package/dist/utils/config-defaults/ConfigDefaults.workerd.d.mts +2 -4
  47. package/dist/utils/config-defaults/ConfigDefaults.workerd.mjs +1 -2
  48. package/dist/utils/modifiers/FileToolModifier.node.d.mts +2 -4
  49. package/dist/utils/modifiers/FileToolModifier.node.mjs +7 -8
  50. package/dist/utils/modifiers/FileToolModifier.workerd.d.mts +2 -4
  51. package/dist/utils/modifiers/FileToolModifier.workerd.mjs +2 -3
  52. package/dist/utils/ssrfGuard.node.d.mts +1 -3
  53. package/dist/utils/ssrfGuard.node.mjs +1 -1
  54. package/dist/utils/ssrfGuard.workerd.d.mts +1 -3
  55. package/dist/utils/ssrfGuard.workerd.mjs +2 -3
  56. package/docs/error-consistency.md +3 -3
  57. package/package.json +12 -13
  58. package/src/composio.ts +12 -0
  59. package/src/errors/ComposioError.ts +40 -16
  60. package/src/errors/ConnectedAccountsErrors.ts +2 -2
  61. package/src/errors/ToolErrors.ts +177 -28
  62. package/src/errors/apiErrorDetails.ts +40 -0
  63. package/src/experimental/index.ts +6 -1
  64. package/src/lib/toolRouterParams.ts +40 -0
  65. package/src/models/ConnectedAccounts.ts +2 -2
  66. package/src/models/ConnectionRequest.ts +44 -32
  67. package/src/models/CustomTool.ts +25 -30
  68. package/src/models/CustomToolkits.ts +16 -22
  69. package/src/models/Experimental.ts +2 -7
  70. package/src/models/Files.node.ts +68 -37
  71. package/src/models/RemoteFile.ts +22 -16
  72. package/src/models/SessionContext.ts +6 -7
  73. package/src/models/ToolRouter.ts +24 -14
  74. package/src/models/ToolRouterSession.ts +38 -31
  75. package/src/models/Tools.ts +274 -30
  76. package/src/models/Triggers.ts +8 -2
  77. package/src/types/customTool.types.ts +49 -28
  78. package/src/types/customToolkits.types.ts +7 -12
  79. package/src/types/toolRouter.types.ts +39 -17
  80. package/src/utils/cancellation.ts +5 -1
  81. package/src/utils/rateLimit.ts +25 -0
  82. package/src/utils/transformers/customToolkits.ts +2 -2
  83. package/dist/FileModifierErrors-CdGSABoq.mjs +0 -97
  84. package/dist/rolldown-runtime-w6R9maHv.mjs +0 -18
  85. 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.28.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.0.1",
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,11 +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
+ import { getRetryAfterSeconds, isRateLimitResponse } from '../utils/rateLimit';
5
+ import {
6
+ apiErrorSuggestedFixes,
7
+ sanitizeApiErrorText,
8
+ withApiErrorMessage,
9
+ } from './apiErrorDetails';
4
10
 
5
11
  export const ToolErrorCodes = {
6
12
  TOOLSET_NOT_DEFINED: 'TOOLSET_NOT_DEFINED',
7
13
  TOOL_NOT_FOUND: 'TOOL_NOT_FOUND',
8
14
  TOOL_FETCH_ERROR: 'TOOL_FETCH_ERROR',
15
+ TOOL_SCHEMA_INVALID: 'TOOL_SCHEMA_INVALID',
9
16
  INVALID_MODIFIER: 'INVALID_MODIFIER',
10
17
  TOOL_EXECUTION_ERROR: 'TOOL_EXECUTION_ERROR',
11
18
  INVALID_TOOL_ARGUMENTS: 'INVALID_TOOL_ARGUMENTS',
@@ -54,7 +61,7 @@ export class ComposioToolNotFoundError extends ComposioError {
54
61
  export class ComposioToolFetchError extends ComposioError {
55
62
  constructor(
56
63
  message: string = 'Failed to fetch tool',
57
- options: Omit<ComposioErrorOptions, 'code' | 'statusCode'> = {}
64
+ options: Omit<ComposioErrorOptions, 'code'> = {}
58
65
  ) {
59
66
  super(message, {
60
67
  ...options,
@@ -69,6 +76,65 @@ export class ComposioToolFetchError extends ComposioError {
69
76
  }
70
77
  }
71
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
+
103
+ /** Error options for a 429. Leaves out an unknown wait, as `ComposioError` does for unset fields. */
104
+ const rateLimitOptions = (cause: APIError, meta: Record<string, unknown>) => {
105
+ const retryAfterSeconds = getRetryAfterSeconds(cause);
106
+ return {
107
+ retryAfterSeconds,
108
+ cause,
109
+ statusCode: 429,
110
+ meta: retryAfterSeconds === undefined ? meta : { ...meta, retryAfterSeconds },
111
+ possibleFixes: apiErrorSuggestedFixes(cause.details) ?? [
112
+ retryAfterSeconds === undefined
113
+ ? 'Wait before retrying'
114
+ : `Wait ${Math.ceil(retryAfterSeconds)} seconds, then retry`,
115
+ 'Reduce how many requests your organization sends per minute',
116
+ ],
117
+ };
118
+ };
119
+
120
+ /**
121
+ * A tool schema fetch rejected with a 429. It is a `ComposioToolFetchError`, so existing handlers
122
+ * still catch it. Use `isComposioRateLimitError` to catch rate limits from fetching and executing.
123
+ */
124
+ export class ComposioToolFetchRateLimitError extends ComposioToolFetchError {
125
+ /** How long the API asked to wait, when the response said. */
126
+ declare public readonly retryAfterSeconds?: number;
127
+
128
+ constructor(message: string, cause: APIError, meta: Record<string, unknown> = {}) {
129
+ const { retryAfterSeconds, ...options } = rateLimitOptions(cause, meta);
130
+ super(message, options);
131
+ if (retryAfterSeconds !== undefined) {
132
+ this.retryAfterSeconds = retryAfterSeconds;
133
+ }
134
+ this.name = 'ComposioToolFetchRateLimitError';
135
+ }
136
+ }
137
+
72
138
  export class ComposioInvalidModifierError extends ComposioError {
73
139
  constructor(
74
140
  message: string = 'Invalid modifier',
@@ -85,8 +151,14 @@ export class ComposioInvalidModifierError extends ComposioError {
85
151
  }
86
152
  }
87
153
 
154
+ /** Options for a `ComposioToolExecutionError`. */
155
+ export type ComposioToolExecutionErrorOptions = ComposioErrorOptions;
156
+
88
157
  export class ComposioToolExecutionError extends ComposioError {
89
- constructor(message: string = 'Tool execution error', options: ComposioErrorOptions = {}) {
158
+ constructor(
159
+ message: string = 'Tool execution error',
160
+ options: ComposioToolExecutionErrorOptions = {}
161
+ ) {
90
162
  super(message, {
91
163
  ...options,
92
164
  code: options.code || ToolErrorCodes.TOOL_EXECUTION_ERROR,
@@ -101,6 +173,34 @@ export class ComposioToolExecutionError extends ComposioError {
101
173
  }
102
174
  }
103
175
 
176
+ /**
177
+ * A tool execution rejected with a 429. It is a `ComposioToolExecutionError`, so existing handlers
178
+ * still catch it. Use `isComposioRateLimitError` to catch rate limits from fetching and executing.
179
+ */
180
+ export class ComposioToolExecutionRateLimitError extends ComposioToolExecutionError {
181
+ /** How long the API asked to wait, when the response said. */
182
+ declare public readonly retryAfterSeconds?: number;
183
+
184
+ constructor(message: string, cause: APIError, meta: Record<string, unknown> = {}) {
185
+ const { retryAfterSeconds, ...options } = rateLimitOptions(cause, meta);
186
+ super(message, options);
187
+ if (retryAfterSeconds !== undefined) {
188
+ this.retryAfterSeconds = retryAfterSeconds;
189
+ }
190
+ this.name = 'ComposioToolExecutionRateLimitError';
191
+ }
192
+ }
193
+
194
+ /** Whether an error from fetching or executing a tool is the API rejecting the request with a 429. */
195
+ export function isComposioRateLimitError(
196
+ error: unknown
197
+ ): error is ComposioToolFetchRateLimitError | ComposioToolExecutionRateLimitError {
198
+ return (
199
+ error instanceof ComposioToolFetchRateLimitError ||
200
+ error instanceof ComposioToolExecutionRateLimitError
201
+ );
202
+ }
203
+
104
204
  export class ComposioInvalidToolArgumentsError extends ComposioError {
105
205
  constructor(
106
206
  message: string = 'Invalid tool arguments',
@@ -231,39 +331,88 @@ export class ComposioToolVersionRequiredError extends ComposioError {
231
331
  this.name = 'ComposioToolVersionRequiredError';
232
332
  }
233
333
  }
234
- export interface ComposioAPIServerErrorBody {
235
- error: {
236
- message: string;
237
- code: number;
238
- status: number;
239
- request_id: string;
240
- suggested_fix: string;
241
- };
242
- }
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']>;
243
338
 
244
339
  // Map of error codes to their corresponding error constructors
245
- const ERROR_CODE_HANDLERS = new Map<number, (message: string) => ComposioError>([
246
- [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
+ ],
247
356
  // Add more error code handlers here as needed
248
357
  ]);
249
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
+
250
382
  export const handleToolExecutionError = (tool: string, actualError: Error): ComposioError => {
383
+ // Already an SDK error, including a caller cancellation: keep its type.
384
+ if (actualError instanceof ComposioError) {
385
+ return actualError;
386
+ }
387
+
388
+ const apiError = actualError instanceof APIError ? actualError : undefined;
389
+ const details = apiError?.details;
390
+
251
391
  // Handle specific API error codes
252
- if (actualError instanceof APIError && actualError.error) {
253
- const errorBody = actualError.error as ComposioAPIServerErrorBody;
254
- const errorCode = errorBody?.error?.code;
255
- const errorMessage = errorBody?.error?.message;
392
+ if (apiError && details && ERROR_CODE_HANDLERS.has(details.code)) {
393
+ return ERROR_CODE_HANDLERS.get(details.code)!(details, apiError);
394
+ }
256
395
 
257
- if (errorCode && ERROR_CODE_HANDLERS.has(errorCode)) {
258
- return ERROR_CODE_HANDLERS.get(errorCode)!(errorMessage || 'An error occurred');
259
- }
396
+ if (isRateLimitResponse(actualError)) {
397
+ return new ComposioToolExecutionRateLimitError(
398
+ withApiErrorMessage(`Rate limited while executing the tool ${tool}`, actualError.details),
399
+ actualError,
400
+ { slug: tool }
401
+ );
260
402
  }
261
403
 
262
- // Default error for all other cases
263
- return new ComposioToolExecutionError(`Error executing the tool ${tool}`, {
264
- cause: actualError,
265
- possibleFixes: [
266
- 'Ensure the tool slug is correct and the input arguments for the tool is valid',
267
- ],
268
- });
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
+ );
269
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
+ };
@@ -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';
@@ -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';
@@ -145,6 +146,45 @@ export const resolveToolRouterSandboxConfig = (
145
146
  return config.sandbox ?? config.workbench;
146
147
  };
147
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
+
148
188
  export const transformToolRouterSandboxParams = (
149
189
  params?: ParsedCreateSessionConfig['sandbox'] | ParsedCreateSessionConfig['workbench']
150
190
  ): NonNullable<SessionCreateParams['workbench']> | undefined => {