@composio/core 0.17.0 → 0.18.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 (41) hide show
  1. package/dist/{CustomTool-Uip-fhPw.d.mts → CustomTool-BKhHv2hJ.d.mts} +1 -1
  2. package/dist/{CustomTool-l-j5HtEf.mjs → CustomTool-C4tv-GL1.mjs} +1 -1
  3. package/dist/FileToolModifier.utils.neutral-D_YkHwZP.mjs +188 -0
  4. package/dist/{Telemetry-DuGJSwUt.mjs → Telemetry-CBtSnWrm.mjs} +27 -11
  5. package/dist/cancellation-jUVItfHw.mjs +704 -0
  6. package/dist/{composio-B27X6i6A.d.mts → composio-CldtZUyC.d.mts} +256 -250
  7. package/dist/{customTool.types-B2Ava_j5.d.mts → customTool.types-DC5fPOOi.d.mts} +178 -178
  8. package/dist/docs/reference/sdk-reference/typescript/session-files.mdx +1 -1
  9. package/dist/{errors-BcEUHZbq.mjs → errors-DyZt79fi.mjs} +3 -0
  10. package/dist/experimental/index.d.mts +2 -2
  11. package/dist/experimental/index.mjs +1 -1
  12. package/dist/{fileUtils.node-B1Wn848p.mjs → fileUtils.node-BwpUOF0s.mjs} +2 -2
  13. package/dist/index.d.mts +104 -5
  14. package/dist/index.mjs +61 -27
  15. package/dist/models/Files.node.mjs +2 -2
  16. package/dist/{sensitiveFileUploadPaths-BVEt0peg.mjs → sensitiveFileUploadPaths-B0w8dqpv.mjs} +23 -6
  17. package/dist/ssrfGuard.node-DlxO8uzr.mjs +307 -0
  18. package/dist/{types-DdZJuMm2.d.mts → types-BgsRW-XH.d.mts} +2 -2
  19. package/dist/utils/config-defaults/ConfigDefaults.node.d.mts +1 -1
  20. package/dist/utils/config-defaults/ConfigDefaults.workerd.d.mts +1 -1
  21. package/dist/utils/modifiers/FileToolModifier.node.d.mts +1 -1
  22. package/dist/utils/modifiers/FileToolModifier.node.mjs +57 -101
  23. package/dist/utils/modifiers/FileToolModifier.workerd.d.mts +1 -1
  24. package/dist/utils/modifiers/FileToolModifier.workerd.mjs +1 -1
  25. package/dist/utils/ssrfGuard.node.d.mts +14 -5
  26. package/dist/utils/ssrfGuard.node.mjs +1 -161
  27. package/package.json +7 -3
  28. package/src/errors/ToolErrors.ts +1 -0
  29. package/src/errors/ValidationErrors.ts +2 -0
  30. package/src/index.ts +6 -0
  31. package/src/models/ToolRouterSession.ts +36 -8
  32. package/src/models/Tools.ts +102 -39
  33. package/src/services/telemetry/TelemetryService.ts +27 -12
  34. package/src/utils/jsonSchema.ts +505 -27
  35. package/src/utils/modifiers/FileToolModifier.node.ts +85 -181
  36. package/src/utils/modifiers/FileToolModifier.utils.neutral.ts +199 -0
  37. package/src/utils/pinnedDispatcher.node.ts +118 -0
  38. package/src/utils/sensitiveFileUploadPaths.ts +36 -9
  39. package/src/utils/ssrfGuard.node.ts +89 -11
  40. package/dist/FileToolModifier.utils.neutral-B5rT711M.mjs +0 -72
  41. package/dist/cancellation-NVtGf3St.mjs +0 -364
@@ -1,163 +1,3 @@
1
- import { t as ComposioBlockedInternalUrlError } from "../SsrfErrors-DNJt57GL.mjs";
2
- import { lookup } from "node:dns/promises";
3
- import { isIP } from "node:net";
1
+ import { i as ssrfSafeFetchWhereSupported, n as isBlockedIp, r as ssrfSafeFetch, t as assertSafeFetchTarget } from "../ssrfGuard.node-DlxO8uzr.mjs";
4
2
 
5
- //#region src/utils/ssrfGuard.node.ts
6
- /**
7
- * SSRF guard for user-supplied URL file inputs.
8
- *
9
- * `composio.files.upload(url)`, Tool Router session file uploads, and automatic
10
- * file upload during tool execution fetch arbitrary user-provided URLs. Without
11
- * a guard, a caller (or a tool argument produced by an LLM) can point the SDK at
12
- * internal infrastructure — loopback, RFC1918 ranges, link-local cloud-metadata
13
- * endpoints (`169.254.169.254`), or a public URL that 3xx-redirects into internal
14
- * space — turning the SDK into a server-side request forgery probe.
15
- *
16
- * This module validates the *resolved* address (not just the hostname string,
17
- * which defeats decimal/octal/hex IP obfuscation) before every fetch, and
18
- * follows redirects manually so each hop is re-validated.
19
- *
20
- * Known residual: a DNS name could resolve to a public address here and rebind
21
- * to an internal one before the underlying `fetch` connects (a TOCTOU / DNS
22
- * rebinding window). Closing that fully requires pinning the validated IP at
23
- * connect time (a custom dispatcher), which is out of scope for this guard.
24
- */
25
- const MAX_REDIRECTS = 5;
26
- const ipv4ToLong = (ip) => {
27
- const [a, b, c, d] = ip.split(".").map(Number);
28
- return (a << 24 >>> 0 | b << 16 | c << 8 | d) >>> 0;
29
- };
30
- const IPV4_BLOCKED_CIDRS = [
31
- ["0.0.0.0", 8],
32
- ["10.0.0.0", 8],
33
- ["100.64.0.0", 10],
34
- ["127.0.0.0", 8],
35
- ["169.254.0.0", 16],
36
- ["172.16.0.0", 12],
37
- ["192.0.0.0", 24],
38
- ["192.0.2.0", 24],
39
- ["192.168.0.0", 16],
40
- ["198.18.0.0", 15],
41
- ["198.51.100.0", 24],
42
- ["203.0.113.0", 24],
43
- ["224.0.0.0", 4],
44
- ["240.0.0.0", 4]
45
- ];
46
- const isBlockedIpv4Long = (long) => IPV4_BLOCKED_CIDRS.some(([base, bits]) => {
47
- const mask = bits === 0 ? 0 : 4294967295 << 32 - bits >>> 0;
48
- return (long & mask) === (ipv4ToLong(base) & mask);
49
- });
50
- /**
51
- * Expand an IPv6 string into its 8 16-bit groups, converting any trailing
52
- * dotted-quad (e.g. `::ffff:1.2.3.4`) into hex groups first. Returns `null` when
53
- * the input cannot be parsed.
54
- */
55
- const expandIpv6 = (ip) => {
56
- let addr = ip;
57
- const v4Match = addr.match(/^(.*:)(\d+\.\d+\.\d+\.\d+)$/);
58
- if (v4Match) {
59
- const long = ipv4ToLong(v4Match[2]);
60
- addr = `${v4Match[1]}${(long >>> 16 & 65535).toString(16)}:${(long & 65535).toString(16)}`;
61
- }
62
- const halves = addr.split("::");
63
- if (halves.length > 2) return null;
64
- const head = halves[0] ? halves[0].split(":") : [];
65
- const tail = halves.length === 2 ? halves[1] ? halves[1].split(":") : [] : [];
66
- let groups;
67
- if (halves.length === 2) {
68
- const missing = 8 - head.length - tail.length;
69
- if (missing < 0) return null;
70
- groups = [
71
- ...head,
72
- ...Array(missing).fill("0"),
73
- ...tail
74
- ];
75
- } else groups = head;
76
- if (groups.length !== 8) return null;
77
- return groups.map((g) => parseInt(g || "0", 16));
78
- };
79
- const isBlockedIpv6 = (ip) => {
80
- const h = expandIpv6(ip);
81
- if (!h) return true;
82
- if (h.every((x) => x === 0)) return true;
83
- if (h.slice(0, 7).every((x) => x === 0) && h[7] === 1) return true;
84
- const isMappedOrCompat = h[0] === 0 && h[1] === 0 && h[2] === 0 && h[3] === 0 && h[4] === 0 && (h[5] === 65535 || h[5] === 0);
85
- const isNat64 = h[0] === 100 && h[1] === 65435 && h[2] === 0 && h[3] === 0 && h[4] === 0 && h[5] === 0;
86
- if (isMappedOrCompat || isNat64) return isBlockedIpv4Long((h[6] << 16 >>> 0 | h[7]) >>> 0);
87
- if ((h[0] & 65024) === 64512) return true;
88
- if ((h[0] & 65472) === 65152) return true;
89
- if ((h[0] & 65280) === 65280) return true;
90
- return false;
91
- };
92
- /**
93
- * True when `ip` is a private, loopback, link-local, or otherwise
94
- * non-publicly-routable address. Fails closed (returns `true`) for anything that
95
- * is not a valid IPv4/IPv6 literal.
96
- */
97
- const isBlockedIp = (ip) => {
98
- const family = isIP(ip);
99
- if (family === 4) return isBlockedIpv4Long(ipv4ToLong(ip));
100
- if (family === 6) return isBlockedIpv6(ip);
101
- return true;
102
- };
103
- /**
104
- * Validate a single URL: it must be http(s), its host must resolve, and every
105
- * resolved address must be publicly routable. Throws
106
- * {@link ComposioBlockedInternalUrlError} otherwise.
107
- */
108
- const assertSafeFetchTarget = async (rawUrl) => {
109
- let url;
110
- try {
111
- url = new URL(rawUrl);
112
- } catch {
113
- throw new ComposioBlockedInternalUrlError("Refusing to fetch a malformed URL", { url: rawUrl });
114
- }
115
- if (url.protocol !== "http:" && url.protocol !== "https:") throw new ComposioBlockedInternalUrlError(`Refusing to fetch a non-http(s) URL (scheme "${url.protocol}")`, { url: rawUrl });
116
- const host = url.hostname.replace(/^\[|\]$/g, "");
117
- let resolved;
118
- try {
119
- resolved = await lookup(host, {
120
- all: true,
121
- verbatim: true
122
- });
123
- } catch {
124
- throw new ComposioBlockedInternalUrlError(`Could not resolve host "${host}"`, { url: rawUrl });
125
- }
126
- for (const { address } of resolved) if (isBlockedIp(address)) throw new ComposioBlockedInternalUrlError(`Refusing to fetch "${host}" — it resolves to a private, loopback, or link-local address`, {
127
- url: rawUrl,
128
- resolvedIp: address
129
- });
130
- };
131
- /**
132
- * Drop-in replacement for `fetch` that blocks SSRF. Validates the target before
133
- * connecting and re-validates every redirect hop (redirects are followed
134
- * manually up to {@link MAX_REDIRECTS}). Intermediate redirect bodies are
135
- * cancelled; non-redirect responses are returned unchanged.
136
- */
137
- const ssrfSafeFetch = async (rawUrl, init = {}, maxRedirects = MAX_REDIRECTS) => {
138
- let currentUrl = rawUrl;
139
- for (let hop = 0; hop <= maxRedirects; hop++) {
140
- await assertSafeFetchTarget(currentUrl);
141
- const response = await fetch(currentUrl, {
142
- ...init,
143
- redirect: "manual"
144
- });
145
- if (!(response.status >= 300 && response.status < 400 && response.headers.has("location"))) return response;
146
- await response.body?.cancel().catch(() => void 0);
147
- currentUrl = new URL(response.headers.get("location"), currentUrl).toString();
148
- }
149
- throw new ComposioBlockedInternalUrlError(`Refusing to fetch: too many redirects (max ${maxRedirects})`, { url: rawUrl });
150
- };
151
- /**
152
- * {@link ssrfSafeFetch} for call sites that must keep working on every runtime.
153
- *
154
- * `ssrfSafeFetch` fails closed in edge runtimes, which is right for a URL the
155
- * caller chose to upload — the alternative is fetching it unvalidated — but not
156
- * for Tool Router session file transfers, where refusing would remove a working
157
- * feature from Workers rather than close a hole reachable there. On Node this
158
- * is the full guard; only the edge build differs.
159
- */
160
- const ssrfSafeFetchWhereSupported = ssrfSafeFetch;
161
-
162
- //#endregion
163
3
  export { assertSafeFetchTarget, isBlockedIp, ssrfSafeFetch, ssrfSafeFetchWhereSupported };
package/package.json CHANGED
@@ -1,7 +1,10 @@
1
1
  {
2
2
  "name": "@composio/core",
3
3
  "type": "module",
4
- "version": "0.17.0",
4
+ "engines": {
5
+ "node": ">=22.22.3"
6
+ },
7
+ "version": "0.18.0",
5
8
  "description": "",
6
9
  "main": "dist/index.mjs",
7
10
  "publishConfig": {
@@ -95,7 +98,7 @@
95
98
  "tsx": "^4.23.12",
96
99
  "typedoc": "^0.28.20",
97
100
  "typescript": "npm:@typescript/typescript6@^6.0.2",
98
- "vitest": "^4.1.10",
101
+ "vitest": "^4.1.11",
99
102
  "zod": "^4.4.3"
100
103
  },
101
104
  "peerDependencies": {
@@ -109,8 +112,9 @@
109
112
  "picocolors": "^1.1.1",
110
113
  "pusher-js": "^8.6.0",
111
114
  "semver": "^7.8.5",
115
+ "undici": "^7.29.0",
112
116
  "zod-to-json-schema": "^3.25.2",
113
- "@composio/json-schema-to-zod": "0.3.0"
117
+ "@composio/json-schema-to-zod": "0.3.1"
114
118
  },
115
119
  "gitHead": "4fae6e54d5c150fba955cc5fa314281da5a1e064",
116
120
  "repository": {
@@ -204,6 +204,7 @@ export class ComposioToolVersionRequiredError extends ComposioError {
204
204
  'Set dangerouslySkipVersionCheck to true (this might cause unexpected behavior when new versions of the tools are released)',
205
205
  ],
206
206
  });
207
+ this.name = 'ComposioToolVersionRequiredError';
207
208
  }
208
209
  }
209
210
  export interface ComposioAPIServerErrorBody {
@@ -78,6 +78,7 @@ export class JsonSchemaToZodError extends ComposioError {
78
78
  ...options,
79
79
  code: options.code || ValidationErrorCodes.JSON_SCHEMA_TO_ZOD_ERROR,
80
80
  });
81
+ this.name = 'JsonSchemaToZodError';
81
82
  }
82
83
  }
83
84
 
@@ -95,5 +96,6 @@ export class JsonSchemaRefResolutionError extends ComposioError {
95
96
  ...options,
96
97
  code: options.code || ValidationErrorCodes.JSON_SCHEMA_REF_RESOLUTION_ERROR,
97
98
  });
99
+ this.name = 'JsonSchemaRefResolutionError';
98
100
  }
99
101
  }
package/src/index.ts CHANGED
@@ -9,12 +9,18 @@ export {
9
9
  deduplicateJsonSchemaRequiredArrays,
10
10
  ensureObjectTypeOnProperties,
11
11
  jsonSchemaToZodSchema,
12
+ omitNullToolArguments,
12
13
  removeNonRequiredProperties,
14
+ toStrictJsonSchema,
13
15
  } from './utils/jsonSchema';
14
16
  export type {
15
17
  DereferenceJsonSchemaOptions,
16
18
  UnresolvedRefReason,
17
19
  UnresolvedRefStrategy,
20
+ StrictSchemaChange,
21
+ StrictSchemaChangeReason,
22
+ StrictSchemaIncompatibility,
23
+ StrictJsonSchemaResult,
18
24
  } from './utils/jsonSchema';
19
25
  export { getExtensionFromMimeType } from './utils/mime';
20
26
  export { normalizeToolArguments } from './utils/toolArguments';
@@ -41,7 +41,11 @@ import { ACL_ONLY_FOR_SHARED_ERROR_FRAGMENT, serializeExperimentalForWire } from
41
41
  import { z } from 'zod/v3';
42
42
  import { transform } from '../utils/transform';
43
43
  import { ToolkitConnectionStateSchema } from '../types/toolRouter.types';
44
- import { ComposioAclOnlyForSharedError, ValidationError } from '../errors';
44
+ import {
45
+ ComposioAclOnlyForSharedError,
46
+ ComposioInvalidModifierError,
47
+ ValidationError,
48
+ } from '../errors';
45
49
  import { Tools } from './Tools';
46
50
  import { ToolRouterSessionFilesMount } from './ToolRouterSessionFileMount';
47
51
  import type {
@@ -51,7 +55,7 @@ import type {
51
55
  RegisteredCustomTool,
52
56
  RegisteredCustomToolkit,
53
57
  } from '../types/customTool.types';
54
- import type { Tool, ToolExecuteResponse } from '../types/tool.types';
58
+ import { ToolSchema, type Tool, type ToolExecuteResponse } from '../types/tool.types';
55
59
  import type { SessionProxyExecuteParams } from '../types/toolRouter.types';
56
60
  import type {
57
61
  SessionExecuteParams,
@@ -190,13 +194,14 @@ export class ToolRouterSession<
190
194
  requestOptions?: ComposioRequestOptions
191
195
  ): Promise<ReturnType<TProvider['wrapTools']>> {
192
196
  const ToolsModel = new Tools<TToolCollection, TTool, TProvider>(this.client, this.config);
193
- const tools = await ToolsModel.getRawToolRouterSessionTools(
197
+ const rawTools = await ToolsModel.getRawToolRouterSessionTools(
194
198
  this.sessionId,
195
- modifiers?.modifySchema ? { modifySchema: modifiers.modifySchema } : undefined,
199
+ undefined,
196
200
  requestOptions
197
201
  );
202
+ const tools = await this.applySchemaModifier(rawTools, modifiers?.modifySchema);
198
203
  const sessionTools = await this.addPreloadedCustomTools(tools, modifiers);
199
- const toolBySlug = new Map(sessionTools.map(tool => [tool.slug.toUpperCase(), tool]));
204
+ const rawToolBySlug = new Map(rawTools.map(tool => [tool.slug.toUpperCase(), tool]));
200
205
 
201
206
  if (this.hasCustomTools()) {
202
207
  // Create an execute function that splits local/remote tools in COMPOSIO_MULTI_EXECUTE_TOOL
@@ -205,7 +210,7 @@ export class ToolRouterSession<
205
210
  input: Record<string, unknown>
206
211
  ): Promise<ToolExecuteResponse> => {
207
212
  if (toolSlug === COMPOSIO_MULTI_EXECUTE_TOOL) {
208
- return this.routeMultiExecute(input, ToolsModel, sessionTools, modifiers);
213
+ return this.routeMultiExecute(input, ToolsModel, rawTools, modifiers);
209
214
  }
210
215
  const customTool = findCustomTool(this.customToolsMap, toolSlug);
211
216
  if (customTool) {
@@ -217,7 +222,7 @@ export class ToolRouterSession<
217
222
  toolSlug,
218
223
  input,
219
224
  modifiers,
220
- toolBySlug.get(toolSlug.toUpperCase())
225
+ rawToolBySlug.get(toolSlug.toUpperCase())
221
226
  );
222
227
  };
223
228
 
@@ -233,10 +238,33 @@ export class ToolRouterSession<
233
238
  }
234
239
 
235
240
  // Standard path (no local tools)
236
- const wrappedTools = ToolsModel.wrapToolsForToolRouter(this.sessionId, sessionTools, modifiers);
241
+ const wrappedTools = modifiers?.modifySchema
242
+ ? ToolsModel.wrapToolsForToolRouter(this.sessionId, sessionTools, modifiers, rawTools)
243
+ : ToolsModel.wrapToolsForToolRouter(this.sessionId, sessionTools, modifiers);
237
244
  return wrappedTools as ReturnType<TProvider['wrapTools']>;
238
245
  }
239
246
 
247
+ private async applySchemaModifier(
248
+ tools: Tool[],
249
+ modifier?: SessionMetaToolOptions['modifySchema']
250
+ ): Promise<Tool[]> {
251
+ if (!modifier) {
252
+ return tools;
253
+ }
254
+ if (typeof modifier !== 'function') {
255
+ throw new ComposioInvalidModifierError('Invalid schema modifier. Not a function.');
256
+ }
257
+ return Promise.all(
258
+ tools.map(tool =>
259
+ modifier({
260
+ toolSlug: tool.slug,
261
+ toolkitSlug: tool.toolkit?.slug ?? 'unknown',
262
+ schema: ToolSchema.parse(tool),
263
+ })
264
+ )
265
+ );
266
+ }
267
+
240
268
  private async addPreloadedCustomTools(
241
269
  tools: Tool[],
242
270
  modifiers?: SessionMetaToolOptions
@@ -54,7 +54,11 @@ import { handleToolExecutionError } from '../errors/ToolErrors';
54
54
  import type { SessionExecuteParams } from '@composio/client/resources/tool-router/session/session.mjs';
55
55
  import { CONFIG_DEFAULTS } from '../utils/config-defaults';
56
56
  import { resolveEffectiveUploadAllowlist } from '../utils/fileDirs';
57
- import { schemaHasFileUploadable } from '../utils/modifiers/FileToolModifier.utils.neutral';
57
+ import {
58
+ dropEmptyFileUploads,
59
+ schemaHasFileUploadable,
60
+ } from '../utils/modifiers/FileToolModifier.utils.neutral';
61
+ import { dereferenceJsonSchema } from '../utils/jsonSchema';
58
62
  import { ComposioRequestOptions } from '../types/requestOptions.types';
59
63
  import { withCancellation } from '../utils/cancellation';
60
64
  import { ComposioRequestCancelledError } from '../errors/SDKErrors';
@@ -268,12 +272,56 @@ export class Tools<
268
272
  if (requestOptions?.signal?.aborted) {
269
273
  throw new ComposioRequestCancelledError();
270
274
  }
275
+ let modifiedParams = await this.applyFileUploadModifiers(
276
+ tool,
277
+ { toolSlug, toolkitSlug, params },
278
+ modifiers?.beforeFileUpload,
279
+ requestOptions
280
+ );
281
+
282
+ // apply the before execute modifiers
283
+ if (modifiers?.beforeExecute) {
284
+ if (typeof modifiers.beforeExecute === 'function') {
285
+ modifiedParams = await modifiers.beforeExecute({
286
+ toolSlug,
287
+ toolkitSlug,
288
+ params: modifiedParams,
289
+ });
290
+ if (requestOptions?.signal?.aborted) {
291
+ throw new ComposioRequestCancelledError();
292
+ }
293
+ } else {
294
+ throw new ComposioInvalidModifierError('Invalid beforeExecute modifier. Not a function.');
295
+ }
296
+ }
297
+ return modifiedParams;
298
+ }
299
+
300
+ /**
301
+ * Applies schema-aware file preprocessing shared by direct and Tool Router
302
+ * session execution. This always runs before the caller's `beforeExecute`
303
+ * hook so the hook observes the exact arguments sent to the backend.
304
+ */
305
+ private async applyFileUploadModifiers(
306
+ tool: Tool,
307
+ {
308
+ toolSlug,
309
+ toolkitSlug,
310
+ params,
311
+ }: {
312
+ toolSlug: string;
313
+ toolkitSlug: string;
314
+ params: ToolExecuteParams;
315
+ },
316
+ beforeFileUpload?: ExecuteToolModifiers['beforeFileUpload'],
317
+ requestOptions?: ComposioRequestOptions
318
+ ): Promise<ToolExecuteParams> {
271
319
  let modifiedParams = params;
272
320
  // if auto upload download files is enabled, upload the files to the Composio API
273
321
  if (this.autoUploadDownloadFiles) {
274
322
  const fileToolModifier = new FileToolModifier(this.client, {
275
323
  ...this.fileUploadPathOptions,
276
- beforeFileUpload: modifiers?.beforeFileUpload,
324
+ beforeFileUpload,
277
325
  });
278
326
  modifiedParams = await fileToolModifier.fileUploadModifier(tool, {
279
327
  toolSlug,
@@ -284,40 +332,37 @@ export class Tools<
284
332
  if (requestOptions?.signal?.aborted) {
285
333
  throw new ComposioRequestCancelledError();
286
334
  }
287
- } else if (
288
- schemaHasFileUploadable(tool.inputParameters) &&
289
- !this.warnedAutoUploadDisabledForTool.has(toolSlug)
290
- ) {
291
- // With auto-upload off, the raw `{ name, mimetype, s3key }` shape is
292
- // what the LLM / caller sees on `tool.inputParameters`. LLMs can't
293
- // produce a valid `s3key` and will hallucinate one, which then fails
294
- // at the staging-lookup step on the backend. Nudge the caller toward
295
- // manual staging or opting into auto-upload.
296
- this.warnedAutoUploadDisabledForTool.add(toolSlug);
297
- logger.warn(
298
- `Tool "${toolSlug}" (toolkit "${toolkitSlug}") has a file-uploadable input, but ` +
299
- `\`dangerouslyAllowAutoUploadDownloadFiles\` is disabled. The SDK will forward ` +
300
- `the file argument as-is; if it isn't already a staged ` +
301
- `{ name, mimetype, s3key } descriptor, the backend will reject the call. Either:\n` +
302
- ` 1) Stage the file yourself: \`const f = await composio.files.upload({ file, toolSlug, toolkitSlug }); ` +
303
- `await composio.tools.execute('${toolSlug}', { userId, arguments: { <fileField>: f } })\`, or\n` +
304
- ` 2) Enable auto-upload with a scoped allowlist: ` +
305
- `\`new Composio({ dangerouslyAllowAutoUploadDownloadFiles: true, fileUploadDirs: ['/safe/dir'] })\`.`
306
- );
307
- }
308
- // apply the before execute modifiers
309
- if (modifiers?.beforeExecute) {
310
- if (typeof modifiers.beforeExecute === 'function') {
311
- modifiedParams = await modifiers.beforeExecute({
312
- toolSlug,
313
- toolkitSlug,
314
- params: modifiedParams,
315
- });
316
- if (requestOptions?.signal?.aborted) {
317
- throw new ComposioRequestCancelledError();
318
- }
319
- } else {
320
- throw new ComposioInvalidModifierError('Invalid beforeExecute modifier. Not a function.');
335
+ } else if (tool.inputParameters && schemaHasFileUploadable(tool.inputParameters)) {
336
+ // Auto-upload is opt-in, but "no file" must still be sent as an
337
+ // omitted key rather than `''`, which the backend rejects
338
+ // (https://github.com/ComposioHQ/composio/issues/4233).
339
+ if (modifiedParams.arguments) {
340
+ modifiedParams = {
341
+ ...modifiedParams,
342
+ arguments: (await dropEmptyFileUploads(
343
+ modifiedParams.arguments,
344
+ dereferenceJsonSchema(tool.inputParameters, { onUnresolved: 'sentinel' })
345
+ )) as ToolExecuteParams['arguments'],
346
+ };
347
+ }
348
+
349
+ if (!this.warnedAutoUploadDisabledForTool.has(toolSlug)) {
350
+ // With auto-upload off, the raw `{ name, mimetype, s3key }` shape is
351
+ // what the LLM / caller sees on `tool.inputParameters`. LLMs can't
352
+ // produce a valid `s3key` and will hallucinate one, which then fails
353
+ // at the staging-lookup step on the backend. Nudge the caller toward
354
+ // manual staging or opting into auto-upload.
355
+ this.warnedAutoUploadDisabledForTool.add(toolSlug);
356
+ logger.warn(
357
+ `Tool "${toolSlug}" (toolkit "${toolkitSlug}") has a file-uploadable input, but ` +
358
+ `\`dangerouslyAllowAutoUploadDownloadFiles\` is disabled. The SDK will forward ` +
359
+ `the file argument as-is; if it isn't already a staged ` +
360
+ `{ name, mimetype, s3key } descriptor, the backend will reject the call. Either:\n` +
361
+ ` 1) Stage the file yourself: \`const f = await composio.files.upload({ file, toolSlug, toolkitSlug }); ` +
362
+ `await composio.tools.execute('${toolSlug}', { userId, arguments: { <fileField>: f } })\`, or\n` +
363
+ ` 2) Enable auto-upload with a scoped allowlist: ` +
364
+ `\`new Composio({ dangerouslyAllowAutoUploadDownloadFiles: true, fileUploadDirs: ['/safe/dir'] })\`.`
365
+ );
321
366
  }
322
367
  }
323
368
  return modifiedParams;
@@ -851,9 +896,10 @@ export class Tools<
851
896
  wrapToolsForToolRouter(
852
897
  sessionId: string,
853
898
  tools: Tool[],
854
- modifiers?: SessionExecuteMetaModifiers
899
+ modifiers?: SessionExecuteMetaModifiers,
900
+ rawTools: Tool[] = tools.map(tool => ToolSchema.parse(tool))
855
901
  ): Tool[] {
856
- const executeToolFn = this.createExecuteToolFnForToolRouter(sessionId, tools, modifiers);
902
+ const executeToolFn = this.createExecuteToolFnForToolRouter(sessionId, rawTools, modifiers);
857
903
  return this.provider.wrapTools(tools, executeToolFn) as Tool[];
858
904
  }
859
905
 
@@ -1150,9 +1196,25 @@ export class Tools<
1150
1196
  });
1151
1197
  }
1152
1198
 
1153
- // Apply beforeExecute modifier if provided
1154
1199
  let modifiedParams = body.arguments ?? {};
1155
1200
  const toolkitSlug = tool?.toolkit?.slug ?? 'composio';
1201
+
1202
+ if (tool) {
1203
+ const fileModifiedParams = await this.applyFileUploadModifiers(
1204
+ tool,
1205
+ {
1206
+ toolSlug,
1207
+ toolkitSlug,
1208
+ params: { arguments: modifiedParams },
1209
+ },
1210
+ undefined,
1211
+ requestOptions
1212
+ );
1213
+ modifiedParams = fileModifiedParams.arguments ?? {};
1214
+ }
1215
+
1216
+ // Apply beforeExecute modifier after file preprocessing so the hook sees
1217
+ // the same arguments that will be sent to the Tool Router.
1156
1218
  if (modifiers?.beforeExecute) {
1157
1219
  modifiedParams = await modifiers.beforeExecute({
1158
1220
  toolSlug,
@@ -1308,6 +1370,7 @@ export class Tools<
1308
1370
  * @deprecated The `customConnectionData` proxy param is deprecated and will be
1309
1371
  * removed in a future release. Use `customAuthParams` instead.
1310
1372
  */
1373
+ // oxlint-disable-next-line typescript/ban-ts-comment -- generated client versions disagree about this deprecated field
1311
1374
  // @ts-ignore
1312
1375
  custom_connection_data: toolProxyParams.data.customConnectionData,
1313
1376
  } as ComposioToolProxyParams;
@@ -2,22 +2,43 @@ import logger from '../../utils/logger';
2
2
  import { TelemetryMetricPayloadBody, TelemetryPayload } from './TelemetryService.types';
3
3
 
4
4
  const TELEMETRY_URL = 'https://telemetry.composio.dev/v1';
5
+ const TELEMETRY_TIMEOUT_MS = 3_000;
5
6
 
6
7
  export class TelemetryService {
7
8
  /**
8
- * Sends a metric to the Telemetry API.
9
- * @param payload - The payload to send to the Telemetry API.
10
- * @returns The response from the Telemetry API.
9
+ * POSTs a best-effort telemetry payload, bounding the request so a stalled
10
+ * endpoint cannot leave it pending indefinitely.
11
+ *
12
+ * A hand-rolled timer rather than AbortSignal.timeout so it can be cleared the
13
+ * moment the response lands: an uncleared timer is itself pending work, which on
14
+ * workerd pins the request context open for the full timeout on every successful
15
+ * send. Mirrors the bound applied to the npm version check.
11
16
  */
12
- static async sendMetric(payload: TelemetryMetricPayloadBody) {
17
+ private static async postWithTimeout(url: string, payload: unknown) {
18
+ const controller = new AbortController();
19
+ const timer = setTimeout(() => controller.abort(), TELEMETRY_TIMEOUT_MS);
13
20
  try {
14
- const result = await fetch(`${TELEMETRY_URL}/metrics/invocations`, {
21
+ return await fetch(url, {
15
22
  method: 'POST',
16
23
  headers: {
17
24
  'Content-Type': 'application/json',
18
25
  },
19
26
  body: JSON.stringify(payload),
27
+ signal: controller.signal,
20
28
  });
29
+ } finally {
30
+ clearTimeout(timer);
31
+ }
32
+ }
33
+
34
+ /**
35
+ * Sends a metric to the Telemetry API.
36
+ * @param payload - The payload to send to the Telemetry API.
37
+ * @returns The response from the Telemetry API.
38
+ */
39
+ static async sendMetric(payload: TelemetryMetricPayloadBody) {
40
+ try {
41
+ const result = await this.postWithTimeout(`${TELEMETRY_URL}/metrics/invocations`, payload);
21
42
  return result;
22
43
  } catch (error) {
23
44
  // ignore error for now; telemetry failures should never affect SDK calls
@@ -32,13 +53,7 @@ export class TelemetryService {
32
53
  */
33
54
  static async sendErrorLog(payload: TelemetryPayload) {
34
55
  try {
35
- const result = await fetch(`${TELEMETRY_URL}/errors`, {
36
- method: 'POST',
37
- headers: {
38
- 'Content-Type': 'application/json',
39
- },
40
- body: JSON.stringify(payload),
41
- });
56
+ const result = await this.postWithTimeout(`${TELEMETRY_URL}/errors`, payload);
42
57
  return result;
43
58
  } catch (error) {
44
59
  // ignore error for now; telemetry failures should never affect SDK calls