@composio/core 0.13.0 → 0.14.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 (63) hide show
  1. package/README.md +62 -247
  2. package/dist/BaseProvider-lCxnjFKQ.d.mts +29395 -0
  3. package/dist/{CustomTool-D9qwyMrv.mjs → CustomTool-C_5NvBsX.mjs} +17 -15
  4. package/dist/{CustomTool-DrJpOhY2.d.mts → CustomTool-CmokRT9q.d.mts} +1 -1
  5. package/dist/{FileModifierErrors-3fSwIWoa.mjs → SsrfErrors-BQRozkeU.mjs} +33 -1
  6. package/dist/{Telemetry-DhGI_J4G.mjs → Telemetry-llfvticE.mjs} +40 -8
  7. package/dist/{jsonSchema-CFKdONpP.mjs → cancellation-W65QRyj2.mjs} +64 -19
  8. package/dist/{composio-DHIKRdeG.d.mts → composio-6C8kHtqc.d.mts} +1079 -1092
  9. package/dist/{customTool.types-CKH2R2ia.d.mts → customTool.types-kFhNYuzh.d.mts} +602 -549
  10. package/dist/docs/reference/sdk-reference/typescript/index.mdx +1 -22
  11. package/dist/docs/reference/sdk-reference/typescript/session.mdx +23 -0
  12. package/dist/docs/reference/sdk-reference/typescript/sessions.mdx +24 -0
  13. package/dist/{errors-DSIlYfl5.mjs → errors-B165yJUQ.mjs} +74 -74
  14. package/dist/experimental/index.d.mts +2 -2
  15. package/dist/experimental/index.mjs +1 -1
  16. package/dist/{fileUtils.node-BiO1JQsJ.mjs → fileUtils.node-iPFi2o4i.mjs} +182 -68
  17. package/dist/index.d.mts +1459 -1401
  18. package/dist/index.mjs +1437 -1375
  19. package/dist/models/Files.node.mjs +2 -2
  20. package/dist/platform/node.d.mts +1 -1
  21. package/dist/platform/node.mjs +3 -0
  22. package/dist/platform/workerd.d.mts +1 -1
  23. package/dist/platform/workerd.mjs +3 -0
  24. package/dist/sensitiveFileUploadPaths-B1OLsd8F.mjs +114 -0
  25. package/dist/{types-DdoCRzLj.d.mts → types-DY1r-kN9.d.mts} +9 -0
  26. package/dist/{types-D4Id3wXA.d.mts → types-yCrveqAj.d.mts} +2 -2
  27. package/dist/utils/config-defaults/ConfigDefaults.node.d.mts +1 -1
  28. package/dist/utils/config-defaults/ConfigDefaults.workerd.d.mts +1 -1
  29. package/dist/utils/modifiers/FileToolModifier.node.d.mts +1 -1
  30. package/dist/utils/modifiers/FileToolModifier.node.mjs +5 -5
  31. package/dist/utils/modifiers/FileToolModifier.workerd.d.mts +1 -1
  32. package/package.json +10 -10
  33. package/src/errors/SsrfErrors.ts +47 -0
  34. package/src/errors/index.ts +3 -0
  35. package/src/index.ts +10 -0
  36. package/src/lib/toolRouterSessionDelete.ts +30 -0
  37. package/src/models/CustomTool.ts +1 -3
  38. package/src/models/ToolRouter.ts +15 -0
  39. package/src/models/ToolRouterSession.ts +50 -16
  40. package/src/models/Tools.ts +32 -2
  41. package/src/models/Triggers.ts +16 -76
  42. package/src/platform/node.ts +4 -0
  43. package/src/platform/types.ts +10 -0
  44. package/src/platform/workerd.ts +6 -0
  45. package/src/provider/OpenAIProvider.ts +19 -14
  46. package/src/telemetry/Telemetry.ts +9 -6
  47. package/src/telemetry/redact.ts +40 -0
  48. package/src/types/tool.types.ts +36 -32
  49. package/src/types/toolRouter.types.ts +13 -0
  50. package/src/utils/fileUtils.node.ts +27 -4
  51. package/src/utils/jsonSchema.ts +58 -0
  52. package/src/utils/modifiers/FileToolModifier.node.ts +2 -1
  53. package/src/utils/sdk.ts +5 -4
  54. package/src/utils/{sensitiveFileUploadPaths.node.ts → sensitiveFileUploadPaths.ts} +29 -13
  55. package/src/utils/ssrfGuard.node.ts +202 -0
  56. package/src/utils/toolkitVersion.ts +21 -2
  57. package/dist/BaseProvider-BBnsv9kS.d.mts +0 -29425
  58. package/dist/BaseProvider-Brb3o86-.d.mts +0 -29425
  59. package/dist/CustomTool-Dmi6ti3I.d.mts +0 -74
  60. package/dist/buffer-PcbMMsgm.mjs +0 -33
  61. package/dist/composio-vMwhASRc.d.mts +0 -5698
  62. package/dist/customTool.types-DXin7Cfc.d.mts +0 -2773
  63. package/dist/types-qTbYYBJw.d.mts +0 -12
@@ -1,5 +1,5 @@
1
- import { t as telemetry } from "../Telemetry-DhGI_J4G.mjs";
2
- import { n as getFileDataAfterUploadingToS3, t as downloadFileFromS3 } from "../fileUtils.node-BiO1JQsJ.mjs";
1
+ import { t as telemetry } from "../Telemetry-llfvticE.mjs";
2
+ import { n as getFileDataAfterUploadingToS3, t as downloadFileFromS3 } from "../fileUtils.node-iPFi2o4i.mjs";
3
3
 
4
4
  //#region src/models/Files.node.ts
5
5
  var Files = class {
@@ -1,4 +1,4 @@
1
- import { t as Platform } from "../types-DdoCRzLj.mjs";
1
+ import { t as Platform } from "../types-DY1r-kN9.mjs";
2
2
 
3
3
  //#region src/platform/node.d.ts
4
4
  /**
@@ -31,6 +31,9 @@ const platform = {
31
31
  existsSync(filePath) {
32
32
  return fs$1.existsSync(filePath);
33
33
  },
34
+ realpathSync(filePath) {
35
+ return fs$1.realpathSync(filePath);
36
+ },
34
37
  mkdirSync(dirPath) {
35
38
  fs$1.mkdirSync(dirPath, { recursive: true });
36
39
  },
@@ -1,4 +1,4 @@
1
- import { t as Platform } from "../types-DdoCRzLj.mjs";
1
+ import { t as Platform } from "../types-DY1r-kN9.mjs";
2
2
 
3
3
  //#region src/platform/workerd.d.ts
4
4
  /**
@@ -28,6 +28,9 @@ const platform = {
28
28
  existsSync(_filePath) {
29
29
  return false;
30
30
  },
31
+ realpathSync(filePath) {
32
+ return filePath;
33
+ },
31
34
  mkdirSync(_dirPath) {},
32
35
  readFileSync(_filePath, _encoding) {
33
36
  throw new Error("File system operations are not supported in this runtime environment (Cloudflare Workers/Edge). Use environment variables or external storage services instead.");
@@ -0,0 +1,114 @@
1
+ import { s as ComposioSensitiveFilePathBlockedError } from "./SsrfErrors-BQRozkeU.mjs";
2
+ import { platform } from "#platform";
3
+
4
+ //#region src/utils/uuid.ts
5
+ function getRandomUUID() {
6
+ return globalThis.crypto.randomUUID();
7
+ }
8
+ function getRandomShortId() {
9
+ return getRandomUUID().slice(0, 8).replace(/-/g, "");
10
+ }
11
+
12
+ //#endregion
13
+ //#region src/utils/buffer.ts
14
+ /**
15
+ * Convert ArrayBuffer to base64.
16
+ */
17
+ function arrayBufferToBase64(buffer) {
18
+ const bytes = new Uint8Array(buffer);
19
+ let binary = "";
20
+ for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
21
+ return btoa(binary);
22
+ }
23
+ const base64ToUint8Array = (base64) => {
24
+ const binary = atob(base64);
25
+ const bytes = new Uint8Array(binary.length);
26
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
27
+ return bytes;
28
+ };
29
+ const uint8ArrayToBase64 = (bytes) => {
30
+ let binary = "";
31
+ for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
32
+ return btoa(binary);
33
+ };
34
+
35
+ //#endregion
36
+ //#region src/utils/sensitiveFileUploadPaths.ts
37
+ /**
38
+ * Blocks accidental upload of local files from well-known secret/credential locations
39
+ * during auto file upload (and {@link getFileDataAfterUploadingToS3}).
40
+ *
41
+ * This is the single canonical guard shared by the core SDK and downstream
42
+ * packages (e.g. `@composio/cli`). Filesystem access goes through the `#platform`
43
+ * abstraction so this module stays free of static `node:*` imports and is safe to
44
+ * re-export from the package root (edge/workerd builds included).
45
+ */
46
+ /**
47
+ * Path segments (a single path component) that indicate a sensitive directory when
48
+ * they appear anywhere in a resolved local path. Compared case-insensitively on Windows.
49
+ */
50
+ const BUILTIN_FILE_UPLOAD_PATH_DENY_SEGMENTS = [
51
+ ".ssh",
52
+ ".aws",
53
+ ".azure",
54
+ ".gnupg",
55
+ ".kube",
56
+ ".docker",
57
+ ".claude",
58
+ ".password-store",
59
+ "keychains"
60
+ ];
61
+ const SECRET_LIKE_BASENAME = /^(\.env(\.|$)|\.netrc$|\.pgpass$)/i;
62
+ /** Default SSH private key basenames (public keys like id_rsa.pub are allowed). */
63
+ const DEFAULT_PRIVATE_KEY_BASENAME = /^id_(rsa|ed25519|ecdsa|dsa|ecdsa_sk)(\.old)?$/i;
64
+ const isWindows = typeof process !== "undefined" && process.platform === "win32";
65
+ /**
66
+ * Returns normalized path segments, resolving symlinks when the path exists.
67
+ */
68
+ function normalizePathSegments(filePath) {
69
+ const absolute = platform.resolvePath(filePath);
70
+ let resolved = absolute;
71
+ try {
72
+ if (platform.existsSync(absolute)) resolved = platform.realpathSync(absolute);
73
+ } catch {}
74
+ return resolved.split(/[/\\]+/).filter(Boolean);
75
+ }
76
+ /**
77
+ * True if the path is under a built-in or extra deny segment, or the basename
78
+ * looks like an env / netrc / default SSH private key name.
79
+ */
80
+ function isBlockedSensitiveFileUploadPath(filePath, additionalDenySegments) {
81
+ return getSensitiveFileUploadPathBlockReason(filePath, additionalDenySegments) != null;
82
+ }
83
+ function getSensitiveFileUploadPathBlockReason(filePath, additionalDenySegments) {
84
+ const segments = normalizePathSegments(filePath);
85
+ const deny = new Set([...BUILTIN_FILE_UPLOAD_PATH_DENY_SEGMENTS, ...(additionalDenySegments ?? []).map((s) => s.trim()).filter(Boolean)].map((s) => isWindows ? s.toLowerCase() : s));
86
+ const segmentsForMatch = isWindows ? segments.map((s) => s.toLowerCase()) : segments;
87
+ for (let i = 0; i < segments.length; i++) if (deny.has(segmentsForMatch[i])) return `path segment "${segments[i]}" is in the sensitive file upload denylist`;
88
+ const basename = segments.length > 0 ? segments[segments.length - 1] : "";
89
+ if (basename) {
90
+ if (SECRET_LIKE_BASENAME.test(basename) || DEFAULT_PRIVATE_KEY_BASENAME.test(basename)) return `file name "${basename}" looks like a credential, env, or private key file`;
91
+ if (basename.toLowerCase() === "credentials") return "file name \"credentials\" is often used for cloud/API credential stores";
92
+ }
93
+ return null;
94
+ }
95
+ /**
96
+ * Default remediation hint appended to the block message. Assumes an SDK caller
97
+ * that exposes `sensitiveFileUploadProtection`. Callers without such an opt-out
98
+ * (e.g. `@composio/cli`) should pass their own `remediation` so the message does
99
+ * not advertise an option the caller cannot honor.
100
+ */
101
+ const DEFAULT_REMEDIATION = "To upload from this path anyway, set sensitiveFileUploadProtection: false on Composio (not recommended) or use a copy outside sensitive locations.";
102
+ /**
103
+ * @throws {ComposioSensitiveFilePathBlockedError} if the path is not allowed
104
+ */
105
+ function assertSafeFileUploadPath(filePath, options) {
106
+ const reason = getSensitiveFileUploadPathBlockReason(filePath, options?.additionalDenySegments);
107
+ if (reason) throw new ComposioSensitiveFilePathBlockedError(`Refusing to upload: ${reason}. ${options?.remediation ?? DEFAULT_REMEDIATION}`, { meta: {
108
+ filePath,
109
+ reason
110
+ } });
111
+ }
112
+
113
+ //#endregion
114
+ export { base64ToUint8Array as a, getRandomUUID as c, arrayBufferToBase64 as i, assertSafeFileUploadPath as n, uint8ArrayToBase64 as o, isBlockedSensitiveFileUploadPath as r, getRandomShortId as s, BUILTIN_FILE_UPLOAD_PATH_DENY_SEGMENTS as t };
@@ -37,6 +37,15 @@ interface Platform {
37
37
  * @returns True if the path exists, false otherwise.
38
38
  */
39
39
  existsSync(filePath: string): boolean;
40
+ /**
41
+ * Resolves symlinks in a path, returning the canonical absolute path. On Node
42
+ * this is `fs.realpathSync`; on edge runtimes without a filesystem it returns
43
+ * the input path unchanged (best-effort). Used to prevent a symlink from
44
+ * smuggling an upload past the sensitive-path denylist.
45
+ * @param filePath - The path to canonicalize.
46
+ * @returns The resolved path, or the input path if it cannot be resolved.
47
+ */
48
+ realpathSync(filePath: string): string;
40
49
  /**
41
50
  * Creates a directory at the given path, including parent directories if needed.
42
51
  * @param dirPath - The directory path to create.
@@ -1,5 +1,5 @@
1
- import { n as BaseComposioProvider } from "./BaseProvider-BBnsv9kS.mjs";
2
- import { n as ComposioConfig } from "./composio-DHIKRdeG.mjs";
1
+ import { n as BaseComposioProvider } from "./BaseProvider-lCxnjFKQ.mjs";
2
+ import { n as ComposioConfig } from "./composio-6C8kHtqc.mjs";
3
3
 
4
4
  //#region src/utils/config-defaults/types.d.ts
5
5
  /**
@@ -1,4 +1,4 @@
1
- import { t as ConfigDefaults } from "../../types-D4Id3wXA.mjs";
1
+ import { t as ConfigDefaults } from "../../types-yCrveqAj.mjs";
2
2
 
3
3
  //#region src/utils/config-defaults/ConfigDefaults.node.d.ts
4
4
  declare const CONFIG_DEFAULTS: ConfigDefaults;
@@ -1,4 +1,4 @@
1
- import { t as ConfigDefaults } from "../../types-D4Id3wXA.mjs";
1
+ import { t as ConfigDefaults } from "../../types-yCrveqAj.mjs";
2
2
 
3
3
  //#region src/utils/config-defaults/ConfigDefaults.workerd.d.ts
4
4
  declare const CONFIG_DEFAULTS: ConfigDefaults;
@@ -1,4 +1,4 @@
1
- import { gn as Tool, xn as ToolExecuteResponse, yn as ToolExecuteParams } from "../../BaseProvider-BBnsv9kS.mjs";
1
+ import { gn as Tool, xn as ToolExecuteResponse, yn as ToolExecuteParams } from "../../BaseProvider-lCxnjFKQ.mjs";
2
2
  import ComposioClient from "@composio/client";
3
3
 
4
4
  //#region src/utils/modifiers/FileToolModifier.node.d.ts
@@ -1,8 +1,8 @@
1
- import { a as ComposioSensitiveFilePathBlockedError, c as logger, i as ComposioFileUploadPathNotAllowedError, n as ComposioFileUploadAbortedError, r as ComposioFileUploadError, t as ComposioFileNotFoundError } from "../../FileModifierErrors-3fSwIWoa.mjs";
2
- import { b as ComposioRequestCancelledError } from "../../errors-DSIlYfl5.mjs";
1
+ import { a as ComposioFileUploadError, i as ComposioFileUploadAbortedError, o as ComposioFileUploadPathNotAllowedError, r as ComposioFileNotFoundError, s as ComposioSensitiveFilePathBlockedError, u as logger } from "../../SsrfErrors-BQRozkeU.mjs";
2
+ import { f as ComposioRequestCancelledError } from "../../errors-B165yJUQ.mjs";
3
3
  import { i as transformProperties, n as schemaHasFileProperty, t as isPlainObject } from "../../FileToolModifier.utils.neutral-B5rT711M.mjs";
4
- import { i as withCancellation, t as dereferenceJsonSchema } from "../../jsonSchema-CFKdONpP.mjs";
5
- import { n as getFileDataAfterUploadingToS3, t as downloadFileFromS3 } from "../../fileUtils.node-BiO1JQsJ.mjs";
4
+ import { r as dereferenceJsonSchema, t as withCancellation } from "../../cancellation-W65QRyj2.mjs";
5
+ import { n as getFileDataAfterUploadingToS3, r as isHttpUrl, t as downloadFileFromS3 } from "../../fileUtils.node-iPFi2o4i.mjs";
6
6
 
7
7
  //#region src/utils/modifiers/FileToolModifier.node.ts
8
8
  /**
@@ -68,7 +68,7 @@ const hydrateFiles = async (value, schema, ctx) => {
68
68
  return out;
69
69
  };
70
70
  if (typeof value === "string") {
71
- const pathOrUrl = await runBeforeFileUpload(value, value.startsWith("http") ? "url" : "path");
71
+ const pathOrUrl = await runBeforeFileUpload(value, isHttpUrl(value) ? "url" : "path");
72
72
  logger.debug(`Uploading file "${pathOrUrl}"`);
73
73
  return getFileDataAfterUploadingToS3(pathOrUrl, {
74
74
  toolSlug: ctx.toolSlug,
@@ -1,4 +1,4 @@
1
- import { gn as Tool, xn as ToolExecuteResponse, yn as ToolExecuteParams } from "../../BaseProvider-BBnsv9kS.mjs";
1
+ import { gn as Tool, xn as ToolExecuteResponse, yn as ToolExecuteParams } from "../../BaseProvider-lCxnjFKQ.mjs";
2
2
  import ComposioClient from "@composio/client";
3
3
 
4
4
  //#region src/utils/modifiers/FileToolModifier.workerd.d.ts
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@composio/core",
3
3
  "type": "module",
4
- "version": "0.13.0",
4
+ "version": "0.14.0",
5
5
  "description": "",
6
6
  "main": "dist/index.mjs",
7
7
  "publishConfig": {
@@ -86,24 +86,24 @@
86
86
  "@type-challenges/utils": "^0.1.1",
87
87
  "@types/semver": "^7.7.1",
88
88
  "tsdown": "^0.22.3",
89
- "tsx": "^4.22.4",
90
- "typedoc": "^0.28.19",
89
+ "tsx": "^4.23.0",
90
+ "typedoc": "^0.28.20",
91
91
  "typescript": "^6.0.3",
92
- "vitest": "^4.1.9",
92
+ "vitest": "^4.1.10",
93
93
  "zod": "^4.4.3"
94
94
  },
95
95
  "peerDependencies": {
96
- "zod": "^3.25 || ^4"
96
+ "zod": ">=3.25.76 <5"
97
97
  },
98
98
  "dependencies": {
99
- "@composio/client": "0.1.0-alpha.74",
99
+ "@composio/client": "0.1.0-alpha.75",
100
100
  "@types/json-schema": "^7.0.15",
101
- "openai": "^6.42.0",
101
+ "openai": "^6.45.0",
102
102
  "picocolors": "^1.1.1",
103
103
  "pusher-js": "^8.5.0",
104
- "semver": "^7.8.4",
104
+ "semver": "^7.8.5",
105
105
  "zod-to-json-schema": "^3.25.2",
106
- "@composio/json-schema-to-zod": "0.2.0"
106
+ "@composio/json-schema-to-zod": "0.2.1"
107
107
  },
108
108
  "gitHead": "4fae6e54d5c150fba955cc5fa314281da5a1e064",
109
109
  "repository": {
@@ -114,7 +114,7 @@
114
114
  "bugs": {
115
115
  "url": "https://github.com/ComposioHQ/composio/issues"
116
116
  },
117
- "homepage": "https://github.com/ComposioHQ/composio/tree/main/ts/packages/core#readme",
117
+ "homepage": "https://github.com/ComposioHQ/composio/tree/next/ts/packages/core#readme",
118
118
  "scripts": {
119
119
  "clean": "git clean -xdf node_modules",
120
120
  "build": "pnpm exec tsdown",
@@ -0,0 +1,47 @@
1
+ import { ComposioError, ComposioErrorOptions } from './ComposioError';
2
+
3
+ export const SsrfErrorCodes = {
4
+ BLOCKED_INTERNAL_URL: 'BLOCKED_INTERNAL_URL',
5
+ } as const;
6
+
7
+ export interface ComposioBlockedInternalUrlErrorOptions extends Omit<ComposioErrorOptions, 'code'> {
8
+ /** The user-supplied URL that was refused. */
9
+ url?: string;
10
+ /** The resolved address that tripped the guard, when known. */
11
+ resolvedIp?: string;
12
+ }
13
+
14
+ /**
15
+ * Thrown when a URL file input resolves to a private, loopback, link-local, or
16
+ * otherwise internal address, or points at a non-http(s) scheme. Guards against
17
+ * turning `composio.files.upload(url)` (and automatic upload during tool
18
+ * execution) into a server-side request forgery (SSRF) probe of internal
19
+ * infrastructure such as cloud metadata endpoints (`169.254.169.254`).
20
+ */
21
+ export class ComposioBlockedInternalUrlError extends ComposioError {
22
+ constructor(
23
+ message: string = 'Refusing to fetch an internal or non-public URL',
24
+ options: ComposioBlockedInternalUrlErrorOptions = {}
25
+ ) {
26
+ const { url, resolvedIp, meta: optionsMeta, ...rest } = options;
27
+
28
+ const meta: Record<string, unknown> = {
29
+ ...optionsMeta,
30
+ ...(url && { url }),
31
+ ...(resolvedIp && { resolvedIp }),
32
+ };
33
+
34
+ super(message, {
35
+ ...rest,
36
+ code: SsrfErrorCodes.BLOCKED_INTERNAL_URL,
37
+ meta: Object.keys(meta).length > 0 ? meta : undefined,
38
+ possibleFixes: options.possibleFixes ?? [
39
+ 'Use a publicly reachable http(s) URL',
40
+ 'Do not point file inputs at localhost, link-local, or private-network hosts',
41
+ 'If the source is internal, download it yourself and pass a File/Blob instead of a URL',
42
+ ],
43
+ });
44
+
45
+ this.name = 'ComposioBlockedInternalUrlError';
46
+ }
47
+ }
@@ -39,3 +39,6 @@ export * from './RemoteFileErrors';
39
39
 
40
40
  // File modifier / auto upload
41
41
  export * from './FileModifierErrors';
42
+
43
+ // SSRF guard (URL file inputs)
44
+ export * from './SsrfErrors';
package/src/index.ts CHANGED
@@ -6,6 +6,7 @@ export { BaseNonAgenticProvider, BaseAgenticProvider } from './provider/BaseProv
6
6
  export type { BaseComposioProvider } from './provider/BaseProvider';
7
7
  export {
8
8
  dereferenceJsonSchema,
9
+ deduplicateJsonSchemaRequiredArrays,
9
10
  jsonSchemaToZodSchema,
10
11
  removeNonRequiredProperties,
11
12
  } from './utils/jsonSchema';
@@ -16,6 +17,15 @@ export type {
16
17
  } from './utils/jsonSchema';
17
18
  export { getExtensionFromMimeType } from './utils/mime';
18
19
  export { normalizeToolArguments } from './utils/toolArguments';
20
+ // Sensitive-file-upload denylist guard. This is the single canonical
21
+ // implementation; downstream packages (e.g. `@composio/cli`) import it here so
22
+ // every local-file upload path enforces the same denylist. Safe in the edge
23
+ // bundle: the module routes filesystem access through `#platform`.
24
+ export {
25
+ assertSafeFileUploadPath,
26
+ isBlockedSensitiveFileUploadPath,
27
+ BUILTIN_FILE_UPLOAD_PATH_DENY_SEGMENTS,
28
+ } from './utils/sensitiveFileUploadPaths';
19
29
  export {
20
30
  sanitizeSchemaPropertyKeys,
21
31
  restoreOriginalKeys,
@@ -0,0 +1,30 @@
1
+ import type ComposioClient from '@composio/client';
2
+ import type { ComposioRequestOptions } from '../types/requestOptions.types';
3
+ import type { ToolRouterSessionDeleteResponse } from '../types/toolRouter.types';
4
+ import { ToolRouterSessionDeleteResponseSchema } from '../types/toolRouter.types';
5
+ import { withCancellation } from '../utils/cancellation';
6
+
7
+ type ToolRouterSessionDeleteWireResponse = {
8
+ session_id: string;
9
+ deleted: true;
10
+ };
11
+
12
+ export async function deleteToolRouterSession(
13
+ client: ComposioClient,
14
+ sessionId: string,
15
+ requestOptions?: ComposioRequestOptions
16
+ ): Promise<ToolRouterSessionDeleteResponse> {
17
+ const response = await withCancellation(
18
+ () =>
19
+ client.delete<ToolRouterSessionDeleteWireResponse>(
20
+ `/api/v3.1/tool_router/session/${encodeURIComponent(sessionId)}`,
21
+ requestOptions
22
+ ),
23
+ requestOptions?.signal
24
+ );
25
+
26
+ return ToolRouterSessionDeleteResponseSchema.parse({
27
+ sessionId: response.session_id,
28
+ deleted: response.deleted,
29
+ });
30
+ }
@@ -483,9 +483,7 @@ export function buildCustomToolsMapFromResponse(
483
483
  tools: CustomTool[],
484
484
  toolkits: CustomToolkit[] | undefined,
485
485
  experimental:
486
- | SessionCreateResponse['experimental']
487
- | SessionRetrieveResponse['experimental']
488
- | undefined
486
+ SessionCreateResponse['experimental'] | SessionRetrieveResponse['experimental'] | undefined
489
487
  ): CustomToolsMap {
490
488
  const byFinalSlug = new Map<string, CustomToolsMapEntry>();
491
489
  const byOriginalSlug = new Map<string, CustomToolsMapEntry>();
@@ -29,6 +29,7 @@ import {
29
29
  ToolRouterMCPServerConfig,
30
30
  ToolRouterSessionMetadata,
31
31
  SessionPreset,
32
+ type ToolRouterSessionDeleteResponse,
32
33
  } from '../types/toolRouter.types';
33
34
  import { ToolRouterCreateSessionConfigSchema } from '../types/toolRouter.types';
34
35
  import {
@@ -55,6 +56,7 @@ import { PRELOAD_TOOLS_ALL } from '../lib/toolRouterConstants';
55
56
  import { ToolRouterSession } from './ToolRouterSession';
56
57
  import { ComposioRequestOptions } from '../types/requestOptions.types';
57
58
  import { withCancellation } from '../utils/cancellation';
59
+ import { deleteToolRouterSession } from '../lib/toolRouterSessionDelete';
58
60
  import {
59
61
  assertNoCustomToolSlugsInPreload,
60
62
  buildCustomToolsMap,
@@ -388,4 +390,17 @@ export class ToolRouter<
388
390
  metadata
389
391
  );
390
392
  }
393
+
394
+ /**
395
+ * Delete a tool router session by ID.
396
+ *
397
+ * Deleted sessions immediately stop being retrievable or executable. Deleting
398
+ * a missing or already-deleted session surfaces the backend 404.
399
+ */
400
+ async delete(
401
+ id: string,
402
+ requestOptions?: ComposioRequestOptions
403
+ ): Promise<ToolRouterSessionDeleteResponse> {
404
+ return deleteToolRouterSession(this.client, id, requestOptions);
405
+ }
391
406
  }
@@ -22,6 +22,7 @@ import {
22
22
  ToolRouterSessionWarning,
23
23
  ToolRouterUpdateSessionConfig,
24
24
  ToolRouterUpdateSessionConfigSchema,
25
+ type ToolRouterSessionDeleteResponse,
25
26
  } from '../types/toolRouter.types';
26
27
  import {
27
28
  transformSearchResponse,
@@ -71,6 +72,7 @@ import {
71
72
  import { transformProxyParams } from './proxyParamsTransform';
72
73
  import { inlineCustomToolsExperimental } from './inlineCustomToolsPayload';
73
74
  import { transformToolRouterUpdateParams } from '../lib/toolRouterParams';
75
+ import { deleteToolRouterSession } from '../lib/toolRouterSessionDelete';
74
76
 
75
77
  const COMPOSIO_MULTI_EXECUTE_TOOL = 'COMPOSIO_MULTI_EXECUTE_TOOL';
76
78
  export const DIRECT_CUSTOM_TOOL_DESCRIPTION_PREFIX =
@@ -647,6 +649,16 @@ export class ToolRouterSession<
647
649
  this.warnings = response.warnings ?? [];
648
650
  }
649
651
 
652
+ /**
653
+ * Delete this session.
654
+ *
655
+ * Deleted sessions immediately stop being retrievable or executable. Deleting
656
+ * an already-deleted session surfaces the backend 404.
657
+ */
658
+ async delete(requestOptions?: ComposioRequestOptions): Promise<ToolRouterSessionDeleteResponse> {
659
+ return deleteToolRouterSession(this.client, this.sessionId, requestOptions);
660
+ }
661
+
650
662
  // ── Private helpers ──────────────────────────────────────────
651
663
 
652
664
  /** Check if this session has any custom tools bound. */
@@ -754,11 +766,23 @@ export class ToolRouterSession<
754
766
  );
755
767
  }
756
768
 
757
- const [localResults, remoteResult] = await Promise.all([
769
+ const [localResults, remoteOutcome] = await Promise.all([
758
770
  Promise.all(localPromises),
759
- remotePromise,
771
+ remotePromise
772
+ ? remotePromise.then(result => ({ result })).catch(error => ({ error }))
773
+ : undefined,
760
774
  ]);
761
775
 
776
+ const remoteTransportFailed = !!remoteOutcome && 'error' in remoteOutcome;
777
+ const remoteTransportError = remoteTransportFailed ? remoteOutcome.error : null;
778
+ const remoteErrorMessage = remoteTransportFailed
779
+ ? (remoteTransportError instanceof Error
780
+ ? remoteTransportError.message
781
+ : String(remoteTransportError)) || 'Remote tool execution failed'
782
+ : null;
783
+ const remoteResult =
784
+ remoteOutcome && 'result' in remoteOutcome ? remoteOutcome.result : undefined;
785
+
762
786
  // If only local tools, return the single/first result unwrapped
763
787
  if (remoteIndices.length === 0 && localResults.length === 1) {
764
788
  return localResults[0].result;
@@ -772,9 +796,15 @@ export class ToolRouterSession<
772
796
  ? remoteResult.data
773
797
  : {}
774
798
  ) as Record<string, unknown>;
775
- const remoteResults = (
776
- Array.isArray(remoteData.results) ? remoteData.results : []
777
- ) as unknown[];
799
+ const remoteResults = remoteErrorMessage
800
+ ? remoteIndices.map(index => ({
801
+ response: { successful: false, data: {}, error: remoteErrorMessage },
802
+ tool_slug: parsed[index].tool_slug,
803
+ error: remoteErrorMessage,
804
+ }))
805
+ : ((Array.isArray(remoteData.results) ? remoteData.results : []) as Array<
806
+ Record<string, unknown>
807
+ >);
778
808
 
779
809
  // Build local result entries matching backend format
780
810
  const localEntries = localResults.map(({ index, result }) => ({
@@ -784,20 +814,22 @@ export class ToolRouterSession<
784
814
  ...(result.error ? { error: result.error } : {}),
785
815
  },
786
816
  tool_slug: parsed[index].tool_slug,
817
+ index,
787
818
  ...(result.error ? { error: result.error } : {}),
788
819
  }));
789
820
 
790
- // Merge and re-index sequentially so there are no collisions
821
+ // Restore original request order, then re-index sequentially so there are no collisions.
791
822
  const merged: Array<Record<string, unknown>> = [
792
- ...(remoteResults as Array<Record<string, unknown>>),
793
- ...localEntries,
794
- ];
795
- const allResults = merged.map(
796
- (entry, i): Record<string, unknown> => ({
823
+ ...remoteResults.map((entry, remotePosition) => ({
797
824
  ...entry,
798
- index: i,
799
- })
800
- );
825
+ index: remoteIndices[remotePosition] ?? remotePosition,
826
+ })),
827
+ ...localEntries,
828
+ ].sort((a, b) => Number(a.index) - Number(b.index));
829
+ const allResults = merged.map((entry, i): Record<string, unknown> => ({
830
+ ...entry,
831
+ index: i,
832
+ }));
801
833
  const failedCount = allResults.filter(r => r.error).length;
802
834
  const mergedData: Record<string, unknown> = {
803
835
  ...remoteData,
@@ -805,13 +837,15 @@ export class ToolRouterSession<
805
837
  };
806
838
  if (
807
839
  localEntries.length > 0 &&
808
- ['total_count', 'success_count', 'error_count'].some(key => key in remoteData)
840
+ (remoteErrorMessage ||
841
+ ['total_count', 'success_count', 'error_count'].some(key => key in remoteData))
809
842
  ) {
810
843
  mergedData.total_count = allResults.length;
811
844
  mergedData.success_count = allResults.length - failedCount;
812
845
  mergedData.error_count = failedCount;
813
846
  }
814
- const remoteError = typeof remoteResult?.error === 'string' ? remoteResult.error : null;
847
+ const remoteError =
848
+ remoteErrorMessage ?? (typeof remoteResult?.error === 'string' ? remoteResult.error : null);
815
849
  const hasAnyError = localResults.some(r => r.result.error) || !!remoteError;
816
850
 
817
851
  return {
@@ -114,6 +114,11 @@ export class Tools<
114
114
  */
115
115
  private readonly warnedAutoUploadDisabledForTool = new Set<string>();
116
116
 
117
+ /**
118
+ * Lazily-built sibling client with retries disabled; see `clientWithoutRetries`.
119
+ */
120
+ private clientWithoutRetriesCache?: ComposioClient;
121
+
117
122
  constructor(client: ComposioClient, config?: ComposioConfig<TProvider>) {
118
123
  if (!client) {
119
124
  throw new Error('ComposioClient is required');
@@ -146,6 +151,27 @@ export class Tools<
146
151
  telemetry.instrument(this, 'Tools');
147
152
  }
148
153
 
154
+ /**
155
+ * A cached sibling client that never retries requests, mirroring Python's
156
+ * `client.without_retries`.
157
+ *
158
+ * Used for non-idempotent writes (`tools.execute` / `tools.proxy`), where a
159
+ * silent retry after a read timeout can duplicate a side effect (e.g. send an
160
+ * email twice). Reads keep the default retry behaviour, and so do other writes
161
+ * (`toolRouter.session.execute`, auth-config and connected-account mutations):
162
+ * the durable fix there is backend-honoured idempotency keys, tracked
163
+ * separately.
164
+ *
165
+ * Cached rather than rebuilt per call because `withOptions` constructs a fresh
166
+ * client; its options never change, so one per `Tools` instance suffices.
167
+ */
168
+ private get clientWithoutRetries(): ComposioClient {
169
+ if (!this.clientWithoutRetriesCache) {
170
+ this.clientWithoutRetriesCache = this.client.withOptions({ maxRetries: 0 });
171
+ }
172
+ return this.clientWithoutRetriesCache;
173
+ }
174
+
149
175
  /**
150
176
  * Transforms tool data from snake_case API format to camelCase for internal SDK use.
151
177
  *
@@ -919,7 +945,9 @@ export class Tools<
919
945
  text: body.text,
920
946
  };
921
947
  const result = await withCancellation(
922
- () => this.client.tools.execute(tool.slug, executeBody, requestOptions),
948
+ // Disable retries: tool execution is a non-idempotent write, and a
949
+ // silent retry after a read timeout can duplicate the side effect.
950
+ () => this.clientWithoutRetries.tools.execute(tool.slug, executeBody, requestOptions),
923
951
  requestOptions?.signal
924
952
  );
925
953
  // transform the response to the ToolExecuteResponse format
@@ -1253,7 +1281,9 @@ export class Tools<
1253
1281
  custom_connection_data: toolProxyParams.data.customConnectionData,
1254
1282
  } as ComposioToolProxyParams;
1255
1283
  return withCancellation(
1256
- () => this.client.tools.proxy(proxyBody, requestOptions),
1284
+ // Disable retries: a proxied call is a non-idempotent write, and a silent
1285
+ // retry after a read timeout can duplicate the side effect.
1286
+ () => this.clientWithoutRetries.tools.proxy(proxyBody, requestOptions),
1257
1287
  requestOptions?.signal
1258
1288
  );
1259
1289
  }