@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.
- package/dist/{CustomTool-Uip-fhPw.d.mts → CustomTool-BKhHv2hJ.d.mts} +1 -1
- package/dist/{CustomTool-l-j5HtEf.mjs → CustomTool-C4tv-GL1.mjs} +1 -1
- package/dist/FileToolModifier.utils.neutral-D_YkHwZP.mjs +188 -0
- package/dist/{Telemetry-DuGJSwUt.mjs → Telemetry-CBtSnWrm.mjs} +27 -11
- package/dist/cancellation-jUVItfHw.mjs +704 -0
- package/dist/{composio-B27X6i6A.d.mts → composio-CldtZUyC.d.mts} +256 -250
- package/dist/{customTool.types-B2Ava_j5.d.mts → customTool.types-DC5fPOOi.d.mts} +178 -178
- package/dist/docs/reference/sdk-reference/typescript/session-files.mdx +1 -1
- package/dist/{errors-BcEUHZbq.mjs → errors-DyZt79fi.mjs} +3 -0
- package/dist/experimental/index.d.mts +2 -2
- package/dist/experimental/index.mjs +1 -1
- package/dist/{fileUtils.node-B1Wn848p.mjs → fileUtils.node-BwpUOF0s.mjs} +2 -2
- package/dist/index.d.mts +104 -5
- package/dist/index.mjs +61 -27
- package/dist/models/Files.node.mjs +2 -2
- package/dist/{sensitiveFileUploadPaths-BVEt0peg.mjs → sensitiveFileUploadPaths-B0w8dqpv.mjs} +23 -6
- package/dist/ssrfGuard.node-DlxO8uzr.mjs +307 -0
- package/dist/{types-DdZJuMm2.d.mts → types-BgsRW-XH.d.mts} +2 -2
- package/dist/utils/config-defaults/ConfigDefaults.node.d.mts +1 -1
- package/dist/utils/config-defaults/ConfigDefaults.workerd.d.mts +1 -1
- package/dist/utils/modifiers/FileToolModifier.node.d.mts +1 -1
- package/dist/utils/modifiers/FileToolModifier.node.mjs +57 -101
- package/dist/utils/modifiers/FileToolModifier.workerd.d.mts +1 -1
- package/dist/utils/modifiers/FileToolModifier.workerd.mjs +1 -1
- package/dist/utils/ssrfGuard.node.d.mts +14 -5
- package/dist/utils/ssrfGuard.node.mjs +1 -161
- package/package.json +7 -3
- package/src/errors/ToolErrors.ts +1 -0
- package/src/errors/ValidationErrors.ts +2 -0
- package/src/index.ts +6 -0
- package/src/models/ToolRouterSession.ts +36 -8
- package/src/models/Tools.ts +102 -39
- package/src/services/telemetry/TelemetryService.ts +27 -12
- package/src/utils/jsonSchema.ts +505 -27
- package/src/utils/modifiers/FileToolModifier.node.ts +85 -181
- package/src/utils/modifiers/FileToolModifier.utils.neutral.ts +199 -0
- package/src/utils/pinnedDispatcher.node.ts +118 -0
- package/src/utils/sensitiveFileUploadPaths.ts +36 -9
- package/src/utils/ssrfGuard.node.ts +89 -11
- package/dist/FileToolModifier.utils.neutral-B5rT711M.mjs +0 -72
- package/dist/cancellation-NVtGf3St.mjs +0 -364
|
@@ -31,10 +31,29 @@ const SECRET_LIKE_BASENAME = /^(\.env(\.|$)|\.netrc$|\.pgpass$)/i;
|
|
|
31
31
|
/** Default SSH private key basenames (public keys like id_rsa.pub are allowed). */
|
|
32
32
|
const DEFAULT_PRIVATE_KEY_BASENAME = /^id_(rsa|ed25519|ecdsa|dsa|ecdsa_sk)(\.old)?$/i;
|
|
33
33
|
|
|
34
|
+
const splitSegments = (aPath: string): string[] => aPath.split(/[/\\]+/).filter(Boolean);
|
|
35
|
+
|
|
34
36
|
/**
|
|
35
37
|
* Returns normalized path segments, resolving symlinks when the path exists.
|
|
38
|
+
*
|
|
39
|
+
* Both the written path and the symlink-resolved one are returned, because a
|
|
40
|
+
* denied segment can be hidden by a symlink in either direction:
|
|
41
|
+
*
|
|
42
|
+
* - `~/innocent-name` -> `~/nested/.aws/creds` hides `.aws` from the written
|
|
43
|
+
* path, so the denylist has to see the resolved one.
|
|
44
|
+
* - `~/.claude` -> `/state/claude` hides `.claude` from the *resolved* path,
|
|
45
|
+
* so the denylist also has to see the written one. Dotfile managers
|
|
46
|
+
* (chezmoi, stow, yadm) and containerised home directories produce exactly
|
|
47
|
+
* this layout.
|
|
48
|
+
*
|
|
49
|
+
* Matching only the resolved path silently turns the denylist off for the
|
|
50
|
+
* second case.
|
|
36
51
|
*/
|
|
37
|
-
function normalizePath(filePath: string): {
|
|
52
|
+
function normalizePath(filePath: string): {
|
|
53
|
+
resolvedPath: string;
|
|
54
|
+
segments: string[];
|
|
55
|
+
writtenSegments: string[];
|
|
56
|
+
} {
|
|
38
57
|
const absolute = platform.resolvePath(filePath);
|
|
39
58
|
let resolved = absolute;
|
|
40
59
|
try {
|
|
@@ -46,7 +65,8 @@ function normalizePath(filePath: string): { resolvedPath: string; segments: stri
|
|
|
46
65
|
}
|
|
47
66
|
return {
|
|
48
67
|
resolvedPath: resolved,
|
|
49
|
-
segments: resolved
|
|
68
|
+
segments: splitSegments(resolved),
|
|
69
|
+
writtenSegments: splitSegments(absolute),
|
|
50
70
|
};
|
|
51
71
|
}
|
|
52
72
|
|
|
@@ -65,7 +85,7 @@ function getSensitiveFileUploadPathBlockReason(
|
|
|
65
85
|
filePath: string,
|
|
66
86
|
additionalDenySegments?: string[]
|
|
67
87
|
): string | null {
|
|
68
|
-
const { resolvedPath, segments } = normalizePath(filePath);
|
|
88
|
+
const { resolvedPath, segments, writtenSegments } = normalizePath(filePath);
|
|
69
89
|
const isCaseSensitive = platform.isFileSystemCaseSensitive?.(resolvedPath) ?? true;
|
|
70
90
|
const normalizeSegment = (segment: string) => (isCaseSensitive ? segment : segment.toLowerCase());
|
|
71
91
|
const deny = new Set(
|
|
@@ -75,15 +95,22 @@ function getSensitiveFileUploadPathBlockReason(
|
|
|
75
95
|
].map(normalizeSegment)
|
|
76
96
|
);
|
|
77
97
|
|
|
78
|
-
const
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
98
|
+
for (const candidate of [segments, writtenSegments]) {
|
|
99
|
+
const segmentsForMatch = isCaseSensitive ? candidate : candidate.map(normalizeSegment);
|
|
100
|
+
for (let i = 0; i < candidate.length; i++) {
|
|
101
|
+
if (deny.has(segmentsForMatch[i]!)) {
|
|
102
|
+
return `path segment "${candidate[i]}" is in the sensitive file upload denylist`;
|
|
103
|
+
}
|
|
82
104
|
}
|
|
83
105
|
}
|
|
84
106
|
|
|
85
|
-
|
|
86
|
-
|
|
107
|
+
// Same two directions as the segment scan: `~/.env -> /state/config` hides a
|
|
108
|
+
// denied basename from the resolved path, and a symlink pointing *at* a
|
|
109
|
+
// credential file hides it from the written one.
|
|
110
|
+
const basenames = [segments.at(-1), writtenSegments.at(-1)].filter(
|
|
111
|
+
(name): name is string => !!name
|
|
112
|
+
);
|
|
113
|
+
for (const basename of basenames) {
|
|
87
114
|
if (SECRET_LIKE_BASENAME.test(basename) || DEFAULT_PRIVATE_KEY_BASENAME.test(basename)) {
|
|
88
115
|
return `file name "${basename}" looks like a credential, env, or private key file`;
|
|
89
116
|
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { lookup } from 'node:dns/promises'; // we're in a Node.js-specific module
|
|
2
2
|
import { isIP } from 'node:net';
|
|
3
3
|
import { ComposioBlockedInternalUrlError } from '../errors/SsrfErrors';
|
|
4
|
+
import { createPinnedDispatcher, hasCustomGlobalDispatcher } from './pinnedDispatcher.node';
|
|
4
5
|
|
|
5
6
|
/**
|
|
6
7
|
* SSRF guard for user-supplied URL file inputs.
|
|
@@ -16,14 +17,43 @@ import { ComposioBlockedInternalUrlError } from '../errors/SsrfErrors';
|
|
|
16
17
|
* which defeats decimal/octal/hex IP obfuscation) before every fetch, and
|
|
17
18
|
* follows redirects manually so each hop is re-validated.
|
|
18
19
|
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
20
|
+
* The address that was validated is also the address connected to: `fetch` gets
|
|
21
|
+
* a dispatcher pinned to it (see {@link createPinnedDispatcher}), so the
|
|
22
|
+
* hostname is never resolved a second time. Without that, a name could resolve
|
|
23
|
+
* to a public address during validation and rebind to an internal one before
|
|
24
|
+
* the connect — a TOCTOU window the Python guard closes the same way.
|
|
25
|
+
*
|
|
26
|
+
* Residual: a hop whose effective dispatcher is a configured route — a
|
|
27
|
+
* caller-supplied `init.dispatcher`, a non-stock global dispatcher (a
|
|
28
|
+
* `ProxyAgent` or `EnvHttpProxyAgent` installed via `setGlobalDispatcher`), or
|
|
29
|
+
* the runtime's env-proxy mode (`NODE_USE_ENV_PROXY`) — keeps only the
|
|
30
|
+
* pre-flight validation. Pinning would dial the validated address instead of
|
|
31
|
+
* the proxy, and the proxy resolves the hostname itself where the SDK cannot
|
|
32
|
+
* see or pin that resolution. The Python guard carries the same residual for
|
|
33
|
+
* the same reason (`_proxy_applies`).
|
|
23
34
|
*/
|
|
24
35
|
|
|
25
36
|
const MAX_REDIRECTS = 5;
|
|
26
37
|
|
|
38
|
+
/**
|
|
39
|
+
* Whether the runtime would route `url` through an env proxy the SDK cannot
|
|
40
|
+
* see into. Only meaningful when `NODE_USE_ENV_PROXY` opts the built-in
|
|
41
|
+
* `fetch` into env proxies (Node >= 24); without that flag the runtime's
|
|
42
|
+
* `fetch` ignores `HTTP_PROXY`/`HTTPS_PROXY` entirely, so mirroring Python's
|
|
43
|
+
* bare env-var check would drop pinning for users whose fetch never proxied.
|
|
44
|
+
*
|
|
45
|
+
* `NO_PROXY=*` is the one bypass honored precisely (nothing is proxied, so
|
|
46
|
+
* pinning is safe again); per-host `NO_PROXY` entries are treated
|
|
47
|
+
* conservatively as proxied rather than parsed.
|
|
48
|
+
*/
|
|
49
|
+
const envProxyApplies = (url: URL): boolean => {
|
|
50
|
+
const useEnvProxy = ['1', 'true'].includes((process.env.NODE_USE_ENV_PROXY ?? '').toLowerCase());
|
|
51
|
+
if (!useEnvProxy) return false;
|
|
52
|
+
if ((process.env.NO_PROXY ?? process.env.no_proxy ?? '') === '*') return false;
|
|
53
|
+
const schemeVar = url.protocol === 'https:' ? 'HTTPS_PROXY' : 'HTTP_PROXY';
|
|
54
|
+
return Boolean(process.env[schemeVar] ?? process.env[schemeVar.toLowerCase()]);
|
|
55
|
+
};
|
|
56
|
+
|
|
27
57
|
const ipv4ToLong = (ip: string): number => {
|
|
28
58
|
const [a, b, c, d] = ip.split('.').map(Number);
|
|
29
59
|
return (((a << 24) >>> 0) | (b << 16) | (c << 8) | d) >>> 0;
|
|
@@ -133,8 +163,12 @@ export const isBlockedIp = (ip: string): boolean => {
|
|
|
133
163
|
* Validate a single URL: it must be http(s), its host must resolve, and every
|
|
134
164
|
* resolved address must be publicly routable. Throws
|
|
135
165
|
* {@link ComposioBlockedInternalUrlError} otherwise.
|
|
166
|
+
*
|
|
167
|
+
* @returns the validated addresses to connect to, in resolver order. Callers
|
|
168
|
+
* must connect to *those* rather than let the client resolve the hostname
|
|
169
|
+
* again; see {@link ssrfSafeFetch}.
|
|
136
170
|
*/
|
|
137
|
-
export const assertSafeFetchTarget = async (rawUrl: string): Promise<
|
|
171
|
+
export const assertSafeFetchTarget = async (rawUrl: string): Promise<string[]> => {
|
|
138
172
|
let url: URL;
|
|
139
173
|
try {
|
|
140
174
|
url = new URL(rawUrl);
|
|
@@ -158,6 +192,10 @@ export const assertSafeFetchTarget = async (rawUrl: string): Promise<void> => {
|
|
|
158
192
|
throw new ComposioBlockedInternalUrlError(`Could not resolve host "${host}"`, { url: rawUrl });
|
|
159
193
|
}
|
|
160
194
|
|
|
195
|
+
if (resolved.length === 0) {
|
|
196
|
+
throw new ComposioBlockedInternalUrlError(`Could not resolve host "${host}"`, { url: rawUrl });
|
|
197
|
+
}
|
|
198
|
+
|
|
161
199
|
for (const { address } of resolved) {
|
|
162
200
|
if (isBlockedIp(address)) {
|
|
163
201
|
throw new ComposioBlockedInternalUrlError(
|
|
@@ -166,13 +204,22 @@ export const assertSafeFetchTarget = async (rawUrl: string): Promise<void> => {
|
|
|
166
204
|
);
|
|
167
205
|
}
|
|
168
206
|
}
|
|
207
|
+
|
|
208
|
+
// Every answer was validated, so all of them are safe to connect to, and
|
|
209
|
+
// resolver order is the system's own address preference.
|
|
210
|
+
return resolved.map(({ address }) => address);
|
|
169
211
|
};
|
|
170
212
|
|
|
171
213
|
/**
|
|
172
|
-
* Drop-in replacement for `fetch` that blocks SSRF. Validates the target
|
|
173
|
-
*
|
|
174
|
-
* manually up to {@link MAX_REDIRECTS}).
|
|
175
|
-
* cancelled; non-redirect responses are
|
|
214
|
+
* Drop-in replacement for `fetch` that blocks SSRF. Validates the target, then
|
|
215
|
+
* connects to the address it validated, and re-validates and re-pins every
|
|
216
|
+
* redirect hop (redirects are followed manually up to {@link MAX_REDIRECTS}).
|
|
217
|
+
* Intermediate redirect bodies are cancelled; non-redirect responses are
|
|
218
|
+
* returned unchanged.
|
|
219
|
+
*
|
|
220
|
+
* A hop whose effective dispatcher is a configured route (caller-supplied
|
|
221
|
+
* `init.dispatcher`, non-stock global dispatcher, env-proxy mode) is *not*
|
|
222
|
+
* pinned — see the module residual above.
|
|
176
223
|
*/
|
|
177
224
|
export const ssrfSafeFetch = async (
|
|
178
225
|
rawUrl: string,
|
|
@@ -182,9 +229,40 @@ export const ssrfSafeFetch = async (
|
|
|
182
229
|
let currentUrl = rawUrl;
|
|
183
230
|
|
|
184
231
|
for (let hop = 0; hop <= maxRedirects; hop++) {
|
|
185
|
-
await assertSafeFetchTarget(currentUrl);
|
|
232
|
+
const addresses = await assertSafeFetchTarget(currentUrl);
|
|
233
|
+
|
|
234
|
+
// Pinning replaces the connect target; through a configured route that
|
|
235
|
+
// would dial the validated origin instead of the route's next hop (the
|
|
236
|
+
// proxy), so those hops keep the pre-flight check only.
|
|
237
|
+
const callerDispatcher = (init as RequestInit & { dispatcher?: unknown }).dispatcher;
|
|
238
|
+
const respectConfiguredRoute =
|
|
239
|
+
callerDispatcher !== undefined ||
|
|
240
|
+
envProxyApplies(new URL(currentUrl)) ||
|
|
241
|
+
hasCustomGlobalDispatcher();
|
|
242
|
+
|
|
243
|
+
const dispatcher = respectConfiguredRoute ? undefined : await createPinnedDispatcher(addresses);
|
|
186
244
|
|
|
187
|
-
|
|
245
|
+
let response: Response;
|
|
246
|
+
try {
|
|
247
|
+
// `dispatcher` is a Node-only extension to `RequestInit`.
|
|
248
|
+
response = await fetch(
|
|
249
|
+
currentUrl,
|
|
250
|
+
(dispatcher === undefined
|
|
251
|
+
? { ...init, redirect: 'manual' }
|
|
252
|
+
: { ...init, redirect: 'manual', dispatcher }) as RequestInit
|
|
253
|
+
);
|
|
254
|
+
} catch (error) {
|
|
255
|
+
if (dispatcher !== undefined) {
|
|
256
|
+
await dispatcher.close().catch(() => undefined);
|
|
257
|
+
}
|
|
258
|
+
throw error;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
// `close()` is graceful: it waits for the in-flight request — including a
|
|
262
|
+
// body still being streamed to the caller — before releasing the socket.
|
|
263
|
+
if (dispatcher !== undefined) {
|
|
264
|
+
void dispatcher.close().catch(() => undefined);
|
|
265
|
+
}
|
|
188
266
|
|
|
189
267
|
const isRedirect =
|
|
190
268
|
response.status >= 300 && response.status < 400 && response.headers.has('location');
|
|
@@ -1,72 +0,0 @@
|
|
|
1
|
-
//#region src/utils/modifiers/FileToolModifier.utils.neutral.ts
|
|
2
|
-
function isPlainObject(val) {
|
|
3
|
-
return typeof val === "object" && val !== null && !Array.isArray(val);
|
|
4
|
-
}
|
|
5
|
-
/**
|
|
6
|
-
* Transforms a single JSON schema property, recursively handling nested properties,
|
|
7
|
-
* anyOf, oneOf, and allOf.
|
|
8
|
-
*/
|
|
9
|
-
const transformSchema = (property) => {
|
|
10
|
-
if (property.file_uploadable) return {
|
|
11
|
-
title: property.title,
|
|
12
|
-
description: property.description,
|
|
13
|
-
format: "path",
|
|
14
|
-
type: "string",
|
|
15
|
-
file_uploadable: true
|
|
16
|
-
};
|
|
17
|
-
const newProperty = { ...property };
|
|
18
|
-
if (property.type === "object" && property.properties) newProperty.properties = transformProperties(property.properties);
|
|
19
|
-
if (property.anyOf) newProperty.anyOf = property.anyOf.map(transformSchema);
|
|
20
|
-
if (property.oneOf) newProperty.oneOf = property.oneOf.map(transformSchema);
|
|
21
|
-
if (property.allOf) newProperty.allOf = property.allOf.map(transformSchema);
|
|
22
|
-
if (property.items) if (Array.isArray(property.items)) newProperty.items = property.items.map(transformSchema);
|
|
23
|
-
else newProperty.items = transformSchema(property.items);
|
|
24
|
-
return newProperty;
|
|
25
|
-
};
|
|
26
|
-
/**
|
|
27
|
-
* Transforms the properties of the tool schema to include the file upload URL.
|
|
28
|
-
*
|
|
29
|
-
* Attaches the format: 'path' to the properties that are file uploadable for agents.
|
|
30
|
-
*
|
|
31
|
-
* @param properties - The properties of the tool schema.
|
|
32
|
-
* @returns The transformed properties.
|
|
33
|
-
*/
|
|
34
|
-
const transformProperties = (properties) => {
|
|
35
|
-
const newProperties = {};
|
|
36
|
-
for (const [key, property] of Object.entries(properties)) newProperties[key] = transformSchema(property);
|
|
37
|
-
return newProperties;
|
|
38
|
-
};
|
|
39
|
-
/**
|
|
40
|
-
* Recursively checks if a schema (or any of its variants) contains a specific file property.
|
|
41
|
-
*/
|
|
42
|
-
const schemaHasFileProperty = (schema, property) => {
|
|
43
|
-
if (!schema) return false;
|
|
44
|
-
if (schema[property]) return true;
|
|
45
|
-
if (schema.properties) {
|
|
46
|
-
for (const prop of Object.values(schema.properties)) if (schemaHasFileProperty(prop, property)) return true;
|
|
47
|
-
}
|
|
48
|
-
if (schema.anyOf) {
|
|
49
|
-
for (const variant of schema.anyOf) if (schemaHasFileProperty(variant, property)) return true;
|
|
50
|
-
}
|
|
51
|
-
if (schema.oneOf) {
|
|
52
|
-
for (const variant of schema.oneOf) if (schemaHasFileProperty(variant, property)) return true;
|
|
53
|
-
}
|
|
54
|
-
if (schema.allOf) {
|
|
55
|
-
for (const variant of schema.allOf) if (schemaHasFileProperty(variant, property)) return true;
|
|
56
|
-
}
|
|
57
|
-
if (schema.items) {
|
|
58
|
-
if (Array.isArray(schema.items)) {
|
|
59
|
-
for (const item of schema.items) if (schemaHasFileProperty(item, property)) return true;
|
|
60
|
-
} else if (schemaHasFileProperty(schema.items, property)) return true;
|
|
61
|
-
}
|
|
62
|
-
return false;
|
|
63
|
-
};
|
|
64
|
-
/**
|
|
65
|
-
* Recursively checks if a schema (or any of its variants) contains file_uploadable properties.
|
|
66
|
-
*/
|
|
67
|
-
const schemaHasFileUploadable = (schema) => {
|
|
68
|
-
return schemaHasFileProperty(schema, "file_uploadable");
|
|
69
|
-
};
|
|
70
|
-
|
|
71
|
-
//#endregion
|
|
72
|
-
export { transformProperties as i, schemaHasFileProperty as n, schemaHasFileUploadable as r, isPlainObject as t };
|
|
@@ -1,364 +0,0 @@
|
|
|
1
|
-
import { i as logger } from "./SsrfErrors-DNJt57GL.mjs";
|
|
2
|
-
import { f as ComposioRequestCancelledError, g as JsonSchemaToZodError, h as JsonSchemaRefResolutionError, m as isRequestAbortError } from "./errors-BcEUHZbq.mjs";
|
|
3
|
-
import { t as isPlainObject } from "./FileToolModifier.utils.neutral-B5rT711M.mjs";
|
|
4
|
-
import { jsonSchemaToZod } from "@composio/json-schema-to-zod";
|
|
5
|
-
|
|
6
|
-
//#region src/utils/jsonSchema.ts
|
|
7
|
-
const MAX_REF_CHAIN_DEPTH = 100;
|
|
8
|
-
const MAX_NODE_DEPTH = 512;
|
|
9
|
-
const CYCLE_BREAK_SENTINEL = {
|
|
10
|
-
type: "object",
|
|
11
|
-
additionalProperties: true
|
|
12
|
-
};
|
|
13
|
-
/**
|
|
14
|
-
* In-band hint attached to the cycle-break sentinel when lenient mode
|
|
15
|
-
* substitutes it for a dangling `$ref`. Makes the degradation visible to
|
|
16
|
-
* LLMs that read the wrapped tool's schema — without it the LLM sees a
|
|
17
|
-
* useless permissive object and no prose context. Wording is intentionally
|
|
18
|
-
* context-neutral ("Schema shape", not "Output shape") because the helper
|
|
19
|
-
* is used for both `inputParameters` and `outputParameters`. Overridden
|
|
20
|
-
* when the caller's `$ref` node carries its own `description` sibling
|
|
21
|
-
* (Draft 2020-12 sibling-keyword semantics).
|
|
22
|
-
*/
|
|
23
|
-
const UNRESOLVED_REF_DESCRIPTION = "Schema shape unresolved at the source — validate loosely. See https://github.com/ComposioHQ/composio/issues/3307.";
|
|
24
|
-
const POLLUTING_KEYS = /* @__PURE__ */ new Set([
|
|
25
|
-
"__proto__",
|
|
26
|
-
"constructor",
|
|
27
|
-
"prototype"
|
|
28
|
-
]);
|
|
29
|
-
const REF_RESOLUTION_FIXES = ["Ensure the $ref pointer matches a path in $defs or definitions", "External $ref pointers (http://, https://, file://, …) are not resolved by the SDK"];
|
|
30
|
-
const decodePointerSegment = (segment) => segment.replace(/~1/g, "/").replace(/~0/g, "~");
|
|
31
|
-
const tryStep = (cursor, segment) => {
|
|
32
|
-
if (cursor === null || typeof cursor !== "object") return {
|
|
33
|
-
kind: "unresolved",
|
|
34
|
-
reason: "missing-target",
|
|
35
|
-
failedAt: segment
|
|
36
|
-
};
|
|
37
|
-
if (Array.isArray(cursor)) {
|
|
38
|
-
const i = Number(segment);
|
|
39
|
-
if (!Number.isInteger(i) || i < 0 || i >= cursor.length) return {
|
|
40
|
-
kind: "unresolved",
|
|
41
|
-
reason: "missing-target",
|
|
42
|
-
failedAt: segment
|
|
43
|
-
};
|
|
44
|
-
return {
|
|
45
|
-
kind: "ok",
|
|
46
|
-
value: cursor[i]
|
|
47
|
-
};
|
|
48
|
-
}
|
|
49
|
-
const obj = cursor;
|
|
50
|
-
if (!Object.prototype.hasOwnProperty.call(obj, segment)) return {
|
|
51
|
-
kind: "unresolved",
|
|
52
|
-
reason: "missing-target",
|
|
53
|
-
failedAt: segment
|
|
54
|
-
};
|
|
55
|
-
return {
|
|
56
|
-
kind: "ok",
|
|
57
|
-
value: obj[segment]
|
|
58
|
-
};
|
|
59
|
-
};
|
|
60
|
-
const tryResolvePointer = (root, pointer) => {
|
|
61
|
-
if (pointer === "#" || pointer === "") return {
|
|
62
|
-
kind: "ok",
|
|
63
|
-
value: root
|
|
64
|
-
};
|
|
65
|
-
if (!pointer.startsWith("#/")) return {
|
|
66
|
-
kind: "unresolved",
|
|
67
|
-
reason: "malformed-pointer"
|
|
68
|
-
};
|
|
69
|
-
const segments = pointer.slice(2).split("/").map(decodePointerSegment);
|
|
70
|
-
let cursor = root;
|
|
71
|
-
for (const seg of segments) {
|
|
72
|
-
const step = tryStep(cursor, seg);
|
|
73
|
-
if (step.kind === "unresolved") return step;
|
|
74
|
-
cursor = step.value;
|
|
75
|
-
}
|
|
76
|
-
return {
|
|
77
|
-
kind: "ok",
|
|
78
|
-
value: cursor
|
|
79
|
-
};
|
|
80
|
-
};
|
|
81
|
-
const throwResolutionError = (pointer, result) => {
|
|
82
|
-
if (result.reason === "malformed-pointer") throw new JsonSchemaRefResolutionError(`Unsupported $ref pointer: ${pointer}`, {
|
|
83
|
-
meta: { ref: pointer },
|
|
84
|
-
possibleFixes: REF_RESOLUTION_FIXES
|
|
85
|
-
});
|
|
86
|
-
throw new JsonSchemaRefResolutionError(`Cannot resolve $ref ${pointer}`, {
|
|
87
|
-
meta: {
|
|
88
|
-
ref: pointer,
|
|
89
|
-
...result.failedAt !== void 0 ? { failedAt: result.failedAt } : {}
|
|
90
|
-
},
|
|
91
|
-
possibleFixes: REF_RESOLUTION_FIXES
|
|
92
|
-
});
|
|
93
|
-
};
|
|
94
|
-
/**
|
|
95
|
-
* Inlines internal JSON Schema `$ref` pointers (`#/$defs/...` and legacy
|
|
96
|
-
* `#/definitions/...`) so the returned schema can be safely handed to
|
|
97
|
-
* consumers that don't tolerate unresolved references (e.g. AJV in
|
|
98
|
-
* `@mastra/schema-compat`). External (`http://`, `https://`, …) refs are
|
|
99
|
-
* left untouched. Cycles are broken with `{ type: 'object',
|
|
100
|
-
* additionalProperties: true }`. The input is never mutated.
|
|
101
|
-
*
|
|
102
|
-
* By default, unresolved internal refs throw `JsonSchemaRefResolutionError`.
|
|
103
|
-
* Pass `{ onUnresolved: 'sentinel' }` to replace the offending node with the
|
|
104
|
-
* cycle-break sentinel instead — appropriate for schemas sourced from an
|
|
105
|
-
* upstream service the caller cannot edit (the Composio API ships some
|
|
106
|
-
* `outputParameters` with a `$ref` into `#/$defs/...` but never declares
|
|
107
|
-
* `$defs`; see https://github.com/ComposioHQ/composio/issues/3307).
|
|
108
|
-
*
|
|
109
|
-
* @throws {JsonSchemaRefResolutionError} on malformed pointers, missing
|
|
110
|
-
* targets (strict mode only), or chains past the depth cap (both modes).
|
|
111
|
-
*/
|
|
112
|
-
function dereferenceJsonSchema(schema, options) {
|
|
113
|
-
if (!isPlainObject(schema)) return schema;
|
|
114
|
-
const strategy = options?.onUnresolved ?? "throw";
|
|
115
|
-
const onReplace = options?.onReplace;
|
|
116
|
-
const root = schema;
|
|
117
|
-
const visiting = /* @__PURE__ */ new WeakSet();
|
|
118
|
-
const cloneChildren = (obj, visitedRefs, chainDepth, nodeDepth) => Object.fromEntries(Object.entries(obj).filter(([k]) => !POLLUTING_KEYS.has(k)).map(([k, v]) => [k, walk(v, visitedRefs, chainDepth, nodeDepth + 1)]));
|
|
119
|
-
function walk(node, visitedRefs, chainDepth, nodeDepth) {
|
|
120
|
-
if (nodeDepth >= MAX_NODE_DEPTH) throw new JsonSchemaRefResolutionError(`JSON Schema node depth exceeded cap (${MAX_NODE_DEPTH})`, { possibleFixes: REF_RESOLUTION_FIXES });
|
|
121
|
-
if (Array.isArray(node)) {
|
|
122
|
-
if (visiting.has(node)) return { ...CYCLE_BREAK_SENTINEL };
|
|
123
|
-
visiting.add(node);
|
|
124
|
-
try {
|
|
125
|
-
return node.map((item) => walk(item, visitedRefs, chainDepth, nodeDepth + 1));
|
|
126
|
-
} finally {
|
|
127
|
-
visiting.delete(node);
|
|
128
|
-
}
|
|
129
|
-
}
|
|
130
|
-
if (!isPlainObject(node)) return node;
|
|
131
|
-
if (visiting.has(node)) return { ...CYCLE_BREAK_SENTINEL };
|
|
132
|
-
visiting.add(node);
|
|
133
|
-
try {
|
|
134
|
-
const ref = typeof node.$ref === "string" ? node.$ref : null;
|
|
135
|
-
if (ref === null || !ref.startsWith("#")) {
|
|
136
|
-
if (ref !== null) logger.warn(`Leaving external $ref untouched: ${ref}`);
|
|
137
|
-
return cloneChildren(node, visitedRefs, chainDepth, nodeDepth);
|
|
138
|
-
}
|
|
139
|
-
if (chainDepth >= MAX_REF_CHAIN_DEPTH) throw new JsonSchemaRefResolutionError(`JSON Schema $ref chain exceeded depth cap (${MAX_REF_CHAIN_DEPTH}): ${ref}`, {
|
|
140
|
-
meta: { ref },
|
|
141
|
-
possibleFixes: REF_RESOLUTION_FIXES
|
|
142
|
-
});
|
|
143
|
-
if (visitedRefs.has(ref)) return { ...CYCLE_BREAK_SENTINEL };
|
|
144
|
-
const result = tryResolvePointer(root, ref);
|
|
145
|
-
let target;
|
|
146
|
-
if (result.kind === "ok") target = result.value;
|
|
147
|
-
else if (strategy === "sentinel") {
|
|
148
|
-
onReplace?.(ref, result.reason);
|
|
149
|
-
target = {
|
|
150
|
-
...CYCLE_BREAK_SENTINEL,
|
|
151
|
-
description: UNRESOLVED_REF_DESCRIPTION
|
|
152
|
-
};
|
|
153
|
-
} else throwResolutionError(ref, result);
|
|
154
|
-
const nextRefs = new Set(visitedRefs).add(ref);
|
|
155
|
-
const resolved = walk(target, nextRefs, chainDepth + 1, nodeDepth + 1);
|
|
156
|
-
const siblings = { ...node };
|
|
157
|
-
delete siblings.$ref;
|
|
158
|
-
if (Object.keys(siblings).length === 0 || !isPlainObject(resolved)) return resolved;
|
|
159
|
-
return {
|
|
160
|
-
...resolved,
|
|
161
|
-
...cloneChildren(siblings, visitedRefs, chainDepth, nodeDepth)
|
|
162
|
-
};
|
|
163
|
-
} finally {
|
|
164
|
-
visiting.delete(node);
|
|
165
|
-
}
|
|
166
|
-
}
|
|
167
|
-
const out = walk(root, /* @__PURE__ */ new Set(), 0, 0);
|
|
168
|
-
if (isPlainObject(out)) {
|
|
169
|
-
delete out.$defs;
|
|
170
|
-
delete out.definitions;
|
|
171
|
-
}
|
|
172
|
-
return out;
|
|
173
|
-
}
|
|
174
|
-
/**
|
|
175
|
-
* Returns a deep-cloned JSON Schema in which every node that carries a
|
|
176
|
-
* `properties` keyword also carries `type: "object"` when it has no explicit
|
|
177
|
-
* `type`. OpenAI tolerates the omission, but Google Gemini enforces OpenAPI
|
|
178
|
-
* 3.0 strictly and rejects function declarations whose nested objects are
|
|
179
|
-
* missing the `type` (see https://github.com/ComposioHQ/composio/issues/4022).
|
|
180
|
-
*
|
|
181
|
-
* The function follows JSON Schema's schema-bearing keywords while keeping
|
|
182
|
-
* property maps and instance values as containers. Nodes that already declare
|
|
183
|
-
* a `type` are left untouched.
|
|
184
|
-
*/
|
|
185
|
-
function ensureObjectTypeOnProperties(schema) {
|
|
186
|
-
const schemaKeywords = /* @__PURE__ */ new Set([
|
|
187
|
-
"additionalItems",
|
|
188
|
-
"additionalProperties",
|
|
189
|
-
"contains",
|
|
190
|
-
"contentSchema",
|
|
191
|
-
"else",
|
|
192
|
-
"if",
|
|
193
|
-
"not",
|
|
194
|
-
"propertyNames",
|
|
195
|
-
"then",
|
|
196
|
-
"unevaluatedItems",
|
|
197
|
-
"unevaluatedProperties"
|
|
198
|
-
]);
|
|
199
|
-
const schemaArrayKeywords = /* @__PURE__ */ new Set([
|
|
200
|
-
"allOf",
|
|
201
|
-
"anyOf",
|
|
202
|
-
"oneOf",
|
|
203
|
-
"prefixItems"
|
|
204
|
-
]);
|
|
205
|
-
const schemaMapKeywords = /* @__PURE__ */ new Set([
|
|
206
|
-
"$defs",
|
|
207
|
-
"definitions",
|
|
208
|
-
"dependentSchemas",
|
|
209
|
-
"patternProperties",
|
|
210
|
-
"properties"
|
|
211
|
-
]);
|
|
212
|
-
function walk(value, mode, depth = 0) {
|
|
213
|
-
if (depth > MAX_NODE_DEPTH) throw new RangeError(`JSON Schema exceeds maximum nesting depth of ${MAX_NODE_DEPTH}`);
|
|
214
|
-
if (Array.isArray(value)) {
|
|
215
|
-
const itemMode = mode === "schema-array" ? "schema" : "value";
|
|
216
|
-
return value.map((item) => walk(item, itemMode, depth + 1));
|
|
217
|
-
}
|
|
218
|
-
if (!isPlainObject(value)) return value;
|
|
219
|
-
const clone = {};
|
|
220
|
-
for (const [key, child] of Object.entries(value)) {
|
|
221
|
-
let childMode = "value";
|
|
222
|
-
if (mode === "schema-map") childMode = "schema";
|
|
223
|
-
else if (mode === "dependencies-map") childMode = Array.isArray(child) ? "value" : "schema";
|
|
224
|
-
else if (mode === "schema") {
|
|
225
|
-
if (schemaMapKeywords.has(key)) childMode = "schema-map";
|
|
226
|
-
else if (schemaArrayKeywords.has(key) || key === "items" && Array.isArray(child)) childMode = "schema-array";
|
|
227
|
-
else if (schemaKeywords.has(key) || key === "items") childMode = "schema";
|
|
228
|
-
else if (key === "dependencies") childMode = "dependencies-map";
|
|
229
|
-
}
|
|
230
|
-
Object.defineProperty(clone, key, {
|
|
231
|
-
configurable: true,
|
|
232
|
-
enumerable: true,
|
|
233
|
-
value: walk(child, childMode, depth + 1),
|
|
234
|
-
writable: true
|
|
235
|
-
});
|
|
236
|
-
}
|
|
237
|
-
if (mode === "schema" && clone.properties !== void 0 && clone.type === void 0) clone.type = "object";
|
|
238
|
-
return clone;
|
|
239
|
-
}
|
|
240
|
-
return walk(schema, "schema");
|
|
241
|
-
}
|
|
242
|
-
/**
|
|
243
|
-
* Returns a deep-cloned JSON Schema whose `required` arrays contain each entry
|
|
244
|
-
* at most once. Duplicate entries are invalid in JSON Schema 2020-12 but do
|
|
245
|
-
* not change the schema's meaning, so preserving the first occurrence is safe.
|
|
246
|
-
*
|
|
247
|
-
* Tool schemas originate both from the Composio API and direct provider calls.
|
|
248
|
-
* Keeping this normalization provider-agnostic lets every SDK provider receive
|
|
249
|
-
* canonical API schemas, while providers that further transform a schema can
|
|
250
|
-
* reapply it at their own emission boundary.
|
|
251
|
-
*/
|
|
252
|
-
function deduplicateJsonSchemaRequiredArrays(schema) {
|
|
253
|
-
const seenSchemaValues = /* @__PURE__ */ new WeakMap();
|
|
254
|
-
const seenInstanceValues = /* @__PURE__ */ new WeakMap();
|
|
255
|
-
const instanceValueKeywords = /* @__PURE__ */ new Set([
|
|
256
|
-
"const",
|
|
257
|
-
"default",
|
|
258
|
-
"enum",
|
|
259
|
-
"examples"
|
|
260
|
-
]);
|
|
261
|
-
function walk(value, isSchema, depth = 0) {
|
|
262
|
-
if (depth > MAX_NODE_DEPTH) throw new RangeError(`JSON Schema exceeds maximum nesting depth of ${MAX_NODE_DEPTH}`);
|
|
263
|
-
const seen = isSchema ? seenSchemaValues : seenInstanceValues;
|
|
264
|
-
if (Array.isArray(value)) {
|
|
265
|
-
const existing = seen.get(value);
|
|
266
|
-
if (existing) return existing;
|
|
267
|
-
const clone = [];
|
|
268
|
-
seen.set(value, clone);
|
|
269
|
-
for (const item of value) clone.push(walk(item, isSchema, depth + 1));
|
|
270
|
-
return clone;
|
|
271
|
-
}
|
|
272
|
-
if (!isPlainObject(value)) return value;
|
|
273
|
-
const existing = seen.get(value);
|
|
274
|
-
if (existing) return existing;
|
|
275
|
-
const clone = {};
|
|
276
|
-
seen.set(value, clone);
|
|
277
|
-
for (const [key, child] of Object.entries(value)) Object.defineProperty(clone, key, {
|
|
278
|
-
configurable: true,
|
|
279
|
-
enumerable: true,
|
|
280
|
-
value: isSchema && key === "required" && Array.isArray(child) ? [...new Set(walk(child, false, depth + 1))] : walk(child, isSchema && !instanceValueKeywords.has(key), depth + 1),
|
|
281
|
-
writable: true
|
|
282
|
-
});
|
|
283
|
-
return clone;
|
|
284
|
-
}
|
|
285
|
-
return walk(schema, true);
|
|
286
|
-
}
|
|
287
|
-
/**
|
|
288
|
-
* Removes all non-required properties from the schema
|
|
289
|
-
*
|
|
290
|
-
* if no items are required, the schema is returned as is
|
|
291
|
-
* @param schema - The JSON schema to remove non-required properties from
|
|
292
|
-
* @returns The JSON schema with all non-required properties removed
|
|
293
|
-
*/
|
|
294
|
-
const removeNonRequiredProperties = (schema) => {
|
|
295
|
-
if (schema && schema.type === "object" && schema.required?.length) schema.properties = Object.fromEntries(Object.entries(schema.properties || {}).filter(([key]) => schema.required.includes(key)));
|
|
296
|
-
schema.additionalProperties = false;
|
|
297
|
-
return schema;
|
|
298
|
-
};
|
|
299
|
-
/**
|
|
300
|
-
* Convert a JSON schema to a Zod schema
|
|
301
|
-
* @param jsonSchema - The JSON schema to convert
|
|
302
|
-
* @param strict - Eliminates all non-required properties from the schema
|
|
303
|
-
* @returns The Zod schema
|
|
304
|
-
*
|
|
305
|
-
* @throws {JsonSchemaToZodError} If the JSON schema is invalid
|
|
306
|
-
*
|
|
307
|
-
* @example
|
|
308
|
-
* ```ts
|
|
309
|
-
* const zodSchema = jsonSchemaToZodSchema({
|
|
310
|
-
* type: 'object',
|
|
311
|
-
* properties: {
|
|
312
|
-
* name: { type: 'string' },
|
|
313
|
-
* },
|
|
314
|
-
* });
|
|
315
|
-
*
|
|
316
|
-
* console.log(zodSchema);
|
|
317
|
-
* ```
|
|
318
|
-
*
|
|
319
|
-
* @example
|
|
320
|
-
* ```ts
|
|
321
|
-
* const zodSchema = jsonSchemaToZodSchema({
|
|
322
|
-
* type: 'object',
|
|
323
|
-
* properties: {
|
|
324
|
-
* name: { type: 'string' },
|
|
325
|
-
* age: { type: 'number' },
|
|
326
|
-
* },
|
|
327
|
-
* required: ['name'],
|
|
328
|
-
* }, { strict: true });
|
|
329
|
-
*
|
|
330
|
-
* console.log(zodSchema);
|
|
331
|
-
*
|
|
332
|
-
* // Output:
|
|
333
|
-
* // z.object({
|
|
334
|
-
* // name: z.string(),
|
|
335
|
-
* // })
|
|
336
|
-
* ```
|
|
337
|
-
*/
|
|
338
|
-
function jsonSchemaToZodSchema(jsonSchema, { strict } = { strict: false }) {
|
|
339
|
-
try {
|
|
340
|
-
let schema = jsonSchema;
|
|
341
|
-
if (strict && schema) schema = removeNonRequiredProperties(schema);
|
|
342
|
-
return jsonSchemaToZod(schema);
|
|
343
|
-
} catch (error) {
|
|
344
|
-
throw new JsonSchemaToZodError("Failed to convert JSON Schema to Zod Schema", { cause: error });
|
|
345
|
-
}
|
|
346
|
-
}
|
|
347
|
-
|
|
348
|
-
//#endregion
|
|
349
|
-
//#region src/utils/cancellation.ts
|
|
350
|
-
/** @internal */
|
|
351
|
-
async function withCancellation(call, signal) {
|
|
352
|
-
try {
|
|
353
|
-
return await call();
|
|
354
|
-
} catch (error) {
|
|
355
|
-
if (signal?.aborted && isRequestAbortError(error)) {
|
|
356
|
-
const underlyingMessage = error instanceof Error ? error.message : "";
|
|
357
|
-
throw new ComposioRequestCancelledError(underlyingMessage ? `Request was cancelled by the caller: ${underlyingMessage}` : "Request was cancelled by the caller", { cause: error instanceof Error ? error : void 0 });
|
|
358
|
-
}
|
|
359
|
-
throw error;
|
|
360
|
-
}
|
|
361
|
-
}
|
|
362
|
-
|
|
363
|
-
//#endregion
|
|
364
|
-
export { jsonSchemaToZodSchema as a, ensureObjectTypeOnProperties as i, deduplicateJsonSchemaRequiredArrays as n, removeNonRequiredProperties as o, dereferenceJsonSchema as r, withCancellation as t };
|