@devries-cameron20 / composio-1 / commits / b62954ecc
Fork 0

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

fix(json-schema-to-zod): keep every pattern enforced by the whole-schema guard

The guard's interpreter compiles patterns with the u flag, so the previous rewrite dropped a `pattern` it could not respell (such as `^\k_$`) and merged `patternProperties` keys that respelled the same, leaving guard-only nodes ($ref targets, typeless schemas) unenforced. - Test `pattern` through an interpreter format that compiles it without the u flag, exactly like the native string parser. - Respell `patternProperties` keys with a complete Annex B to Unicode translation, keep keys that respell the same as separate entries, and follow the renames in local $refs. - Cover the serialized LangChain tool parameters, not just the Zod kind.

jkomyno committed Sep 29, 2026 at 15:36 UTC b62954ecc3198b512a63a2b04dcd2e3eef81432d
5 files changed +449 -48
ts/packages/json-schema-to-zod/src/utils/unicode-pattern.ts new
+184
@@ -0,0 +1,184 @@
1 +const compilesAsUnicode = (pattern: string): boolean => {
2 + try {
3 + new RegExp(pattern, 'u');
4 + return true;
5 + } catch {
6 + return false;
7 + }
8 +};
9 +
10 +const REGEX_SYNTAX_CHARACTERS = new Set('^$\\.*+?()[]{}|/');
11 +const CHARACTER_CLASS_ESCAPES = new Set('dDwWsS');
12 +const CONTROL_ESCAPES = new Set('fnrtv');
13 +const HEX_DIGIT = /^[0-9A-Fa-f]$/;
14 +const QUANTIFIER = /^\{\d+(?:,\d*)?\}/;
15 +
16 +const hexEscape = (code: number): string => `\\x${code.toString(16).padStart(2, '0')}`;
17 +
18 +/** Capturing group count and whether any is named, as the parser counts them. */
19 +const scanGroups = (pattern: string): { count: number; named: boolean } => {
20 + let count = 0;
21 + let named = false;
22 + let inClass = false;
23 + for (let index = 0; index < pattern.length; index++) {
24 + const char = pattern[index];
25 + if (char === '\\') {
26 + index++;
27 + } else if (inClass) {
28 + inClass = char !== ']';
29 + } else if (char === '[') {
30 + inClass = true;
31 + } else if (char === '(') {
32 + if (pattern[index + 1] !== '?') {
33 + count++;
34 + } else if (pattern[index + 2] === '<' && !'=!'.includes(pattern[index + 3] ?? '')) {
35 + count++;
36 + named = true;
37 + }
38 + }
39 + }
40 + return { count, named };
41 +};
42 +
43 +/**
44 + * A legacy octal escape (a `\` digit sequence that is not a backreference) as
45 + * a hex escape. Returns the replacement and how many digits it consumed.
46 + */
47 +const legacyOctalEscape = (pattern: string, index: number): [string, number] => {
48 + const first = pattern[index];
49 + if (first === '8' || first === '9') {
50 + return [first, 1];
51 + }
52 + const maxDigits = first <= '3' ? 3 : 2;
53 + let digits = first;
54 + while (digits.length < maxDigits && /^[0-7]$/.test(pattern[index + digits.length] ?? '')) {
55 + digits += pattern[index + digits.length];
56 + }
57 + return [hexEscape(parseInt(digits, 8)), digits.length];
58 +};
59 +
60 +/**
61 + * The interpreter compiles every pattern with the `u` flag, while
62 + * `compilePattern` and the native parsers deliberately do not. This spells a
63 + * pattern written for the legacy (Annex B) grammar in the Unicode grammar with
64 + * the same meaning: identity escapes such as `\_`, `\:` or `\k` become the
65 + * literal character, incomplete `\x`, `\u` and `\c` escapes and legacy octal
66 + * escapes are spelled out, lone `{`, `}` and `]` are escaped, and a hyphen
67 + * next to a class escape (`[\w-.]`), which is a literal there, is escaped.
68 + *
69 + * Returns `undefined` for the few legacy constructs with no Unicode spelling,
70 + * such as a quantified lookahead. Matching differs only for astral
71 + * characters, which `.` and negated classes treat as one character, not two.
72 + */
73 +export const toUnicodePattern = (pattern: string): string | undefined => {
74 + const { count: groupCount, named: hasNamedGroups } = scanGroups(pattern);
75 +
76 + let rewritten = '';
77 + let inClass = false;
78 + let previousAtomWasClassEscape = false;
79 + let index = 0;
80 + while (index < pattern.length) {
81 + const char = pattern[index];
82 +
83 + if (char !== '\\' && inClass) {
84 + if (char === ']') {
85 + inClass = false;
86 + rewritten += char;
87 + } else if (
88 + char === '-' &&
89 + (previousAtomWasClassEscape ||
90 + (pattern[index + 1] === '\\' && CHARACTER_CLASS_ESCAPES.has(pattern[index + 2] ?? '')))
91 + ) {
92 + rewritten += '\\-';
93 + } else {
94 + rewritten += char;
95 + }
96 + previousAtomWasClassEscape = false;
97 + index++;
98 + continue;
99 + }
100 +
101 + if (char !== '\\') {
102 + const quantifier = char === '{' ? QUANTIFIER.exec(pattern.slice(index)) : null;
103 + if (char === '[') {
104 + inClass = true;
105 + const opening = pattern[index + 1] === '^' ? '[^' : '[';
106 + rewritten += opening;
107 + index += opening.length;
108 + } else if (quantifier) {
109 + rewritten += quantifier[0];
110 + index += quantifier[0].length;
111 + } else {
112 + rewritten += char === '{' || char === '}' || char === ']' ? `\\${char}` : char;
113 + index++;
114 + }
115 + continue;
116 + }
117 +
118 + const escaped = pattern[index + 1];
119 + if (escaped === undefined) {
120 + return undefined;
121 + }
122 + previousAtomWasClassEscape = false;
123 +
124 + if (CHARACTER_CLASS_ESCAPES.has(escaped)) {
125 + previousAtomWasClassEscape = inClass;
126 + rewritten += `\\${escaped}`;
127 + index += 2;
128 + } else if (
129 + CONTROL_ESCAPES.has(escaped) ||
130 + REGEX_SYNTAX_CHARACTERS.has(escaped) ||
131 + escaped === 'b' ||
132 + (escaped === 'B' && !inClass) ||
133 + (escaped === '-' && inClass) ||
134 + (escaped === 'k' && hasNamedGroups && !inClass)
135 + ) {
136 + rewritten += `\\${escaped}`;
137 + index += 2;
138 + } else if (escaped === 'c') {
139 + const letter = pattern[index + 2] ?? '';
140 + if (/^[A-Za-z]$/.test(letter)) {
141 + rewritten += `\\c${letter}`;
142 + index += 3;
143 + } else if (inClass && /^[0-9_]$/.test(letter)) {
144 + rewritten += hexEscape(letter.charCodeAt(0) % 32);
145 + index += 3;
146 + } else {
147 + // Without a control letter, `\c` is a literal backslash and the `c`
148 + // that follows is an ordinary character.
149 + rewritten += '\\\\';
150 + index++;
151 + }
152 + } else if (escaped === 'x' || escaped === 'u') {
153 + const length = escaped === 'x' ? 2 : 4;
154 + const digits = pattern.slice(index + 2, index + 2 + length);
155 + if (digits.length === length && [...digits].every(digit => HEX_DIGIT.test(digit))) {
156 + rewritten += `\\${escaped}${digits}`;
157 + index += 2 + length;
158 + } else {
159 + rewritten += escaped;
160 + index += 2;
161 + }
162 + } else if (/^[0-9]$/.test(escaped)) {
163 + const decimal = /^\d+/.exec(pattern.slice(index + 1))?.[0] ?? escaped;
164 + if (escaped === '0' && !/^[0-9]$/.test(pattern[index + 2] ?? '')) {
165 + rewritten += '\\0';
166 + index += 2;
167 + } else if (!inClass && escaped !== '0' && Number(decimal) <= groupCount) {
168 + rewritten += `\\${decimal}`;
169 + index += 1 + decimal.length;
170 + } else {
171 + const [replacement, consumed] = legacyOctalEscape(pattern, index + 1);
172 + rewritten += replacement;
173 + index += 1 + consumed;
174 + }
175 + } else {
176 + // Every other escape is an identity escape: the character itself, which
177 + // is not special where it stands.
178 + rewritten += escaped;
179 + index += 2;
180 + }
181 + }
182 +
183 + return compilesAsUnicode(rewritten) ? rewritten : undefined;
184 +};
ts/packages/json-schema-to-zod/src/whole-schema-validation.ts
+107 -48
@@ -1,8 +1,9 @@
1 -import { encodePointer, Validator } from '@cfworker/json-schema';
1 +import { encodePointer, format, Validator } from '@cfworker/json-schema';
2 import type { Schema as InterpreterSchema } from '@cfworker/json-schema';
3 import { z } from 'zod/v3';
4
5 import type { JsonSchema, JsonSchemaObject } from './types';
6 +import { toUnicodePattern } from './utils/unicode-pattern';
7
8 const REQUIRES_WHOLE_SCHEMA_VALIDATION = new Set([
9 '$ref',
@@ -161,51 +162,98 @@ export const guardSchemaAt = (
162 { ...refs.root, $ref: `#/${refs.path.map(part => encodePointer(String(part))).join('/')}` }
163 : node;
164
164 -const compilesAsUnicode = (pattern: string): boolean => {
165 +const patternKeyRenames = new WeakMap<object, ReadonlyMap<string, string>>();
166 +
167 +/**
168 + * The Unicode spelling of each `patternProperties` key. Two keys that spell
169 + * the same way (`^a\_b$` and `^a_b$`) stay separate entries: the later one is
170 + * wrapped in a non-capturing group, which matches the same names, so neither
171 + * value schema is dropped. A key with no Unicode spelling is kept as is and
172 + * surfaces as a guard failure rather than an unenforced constraint.
173 + */
174 +const renamePatternKeys = (patternProperties: object): ReadonlyMap<string, string> => {
175 + const cached = patternKeyRenames.get(patternProperties);
176 + if (cached) {
177 + return cached;
178 + }
179 +
180 + const renames = new Map<string, string>();
181 + const used = new Set<string>();
182 + for (const key of Object.keys(patternProperties)) {
183 + let renamed = toUnicodePattern(key) ?? key;
184 + while (used.has(renamed)) {
185 + renamed = `(?:${renamed})`;
186 + }
187 + used.add(renamed);
188 + renames.set(key, renamed);
189 + }
190 + patternKeyRenames.set(patternProperties, renames);
191 + return renames;
192 +};
193 +
194 +const decodePointerSegment = (segment: string): string => {
195 try {
166 - new RegExp(pattern, 'u');
167 - return true;
196 + return decodeURI(segment).replace(/~1/g, '/').replace(/~0/g, '~');
197 } catch {
169 - return false;
198 + return segment;
199 }
200 };
201
173 -const REGEX_SYNTAX_CHARACTERS = new Set('^$\\.*+?()[]{}|/');
174 -
202 /**
176 - * The interpreter compiles every pattern with the `u` flag, while
177 - * `compilePattern` deliberately does not. Tool schemas routinely use identity
178 - * escapes such as `\_` or `\:` that are literal characters without the flag
179 - * and a SyntaxError with it, so those escapes are dropped. Returns `undefined`
180 - * when the pattern still has no Unicode-mode spelling.
203 + * A local `$ref` rewritten to address the renamed `patternProperties` keys of
204 + * the interpreter copy. `root` is the unrenamed document it points into.
205 */
182 -const toUnicodePattern = (pattern: string): string | undefined => {
183 - if (compilesAsUnicode(pattern)) {
184 - return pattern;
206 +const renameRefThroughPatternKeys = (ref: string, root: unknown): string => {
207 + if (!ref.startsWith('#/')) {
208 + return ref;
209 }
210
187 - let rewritten = '';
188 - let inClass = false;
189 - for (let index = 0; index < pattern.length; index++) {
190 - const char = pattern[index];
191 - if (char === '\\' && index + 1 < pattern.length) {
192 - const escaped = pattern[++index];
193 - const keepEscape =
194 - /[A-Za-z0-9]/.test(escaped) ||
195 - REGEX_SYNTAX_CHARACTERS.has(escaped) ||
196 - (inClass && escaped === '-');
197 - rewritten += keepEscape ? `\\${escaped}` : escaped;
198 - continue;
211 + const segments = ref.slice(2).split('/');
212 + let node: unknown = root;
213 + let changed = false;
214 + const renamed = segments.map((segment, index) => {
215 + const key = decodePointerSegment(segment);
216 + let result = segment;
217 + if (
218 + index > 0 &&
219 + decodePointerSegment(segments[index - 1]) === 'patternProperties' &&
220 + isObject(node)
221 + ) {
222 + const renamedKey = renamePatternKeys(node).get(key);
223 + if (renamedKey !== undefined && renamedKey !== key) {
224 + result = encodePointer(renamedKey);
225 + changed = true;
226 + }
227 }
200 - if (char === '[') {
201 - inClass = true;
202 - } else if (char === ']') {
203 - inClass = false;
228 + node =
229 + isObject(node) || Array.isArray(node) ? (node as Record<string, unknown>)[key] : undefined;
230 + return result;
231 + });
232 +
233 + return changed ? `#/${renamed.join('/')}` : ref;
234 +};
235 +
236 +const PATTERN_FORMAT_PREFIX = 'composio-pattern:';
237 +
238 +/**
239 + * Registers `pattern` as an interpreter format that tests it exactly as the
240 + * native string parser does, without the `u` flag, and returns the format
241 + * name. The name is derived from the pattern, so every schema using the same
242 + * pattern shares one entry. Returns `undefined` for a pattern that does not
243 + * compile at all, which the interpreter then reports as it always has.
244 + */
245 +const patternFormat = (pattern: string): string | undefined => {
246 + const name = `${PATTERN_FORMAT_PREFIX}${pattern}`;
247 + if (!Object.hasOwn(format, name)) {
248 + let regex: RegExp;
249 + try {
250 + regex = new RegExp(pattern);
251 + } catch {
252 + return undefined;
253 }
205 - rewritten += char;
254 + format[name] = value => regex.test(value);
255 }
207 -
208 - return compilesAsUnicode(rewritten) ? rewritten : undefined;
256 + return name;
257 };
258
259 /**
@@ -215,11 +263,15 @@ const toUnicodePattern = (pattern: string): string | undefined => {
263 * - OpenAPI 3.0 / Draft 4 spell exclusive bounds as a boolean flag next to
264 * `minimum`/`maximum`. The interpreter ignores the flag, so it receives the
265 * numeric spelling the native number parser already honors.
218 - * - Patterns get their Unicode-mode spelling (see `toUnicodePattern`). A
219 - * `pattern` without one is left to the native string parser, which compiles
220 - * it without the flag, instead of failing every value.
266 + * - The interpreter compiles patterns with the `u` flag, which refuses legacy
267 + * syntax tool schemas use, such as `\_`. A `pattern` becomes a format that
268 + * tests it without the flag, exactly like the native string parser. A
269 + * `patternProperties` key cannot leave the interpreter, so it gets its
270 + * Unicode spelling (`toUnicodePattern`), and local `$ref`s through a renamed
271 + * key follow the rename. `root` is the unmodified document those refs
272 + * address.
273 */
222 -const prepareInterpreterSchema = (value: unknown, seen: WeakSet<object>): void => {
274 +const prepareInterpreterSchema = (value: unknown, seen: WeakSet<object>, root: unknown): void => {
275 if (!isObject(value) || seen.has(value)) {
276 return;
277 }
@@ -238,18 +290,25 @@ const prepareInterpreterSchema = (value: unknown, seen: WeakSet<object>): void =
290 delete value.exclusiveMaximum;
291 }
292
241 - if (typeof value.pattern === 'string') {
242 - const pattern = toUnicodePattern(value.pattern);
243 - if (pattern === undefined) {
244 - delete value.pattern;
293 + if (typeof value.$ref === 'string') {
294 + value.$ref = renameRefThroughPatternKeys(value.$ref, root);
295 + }
296 + const patternFormatName =
297 + typeof value.pattern === 'string' ? patternFormat(value.pattern) : undefined;
298 + if (patternFormatName !== undefined) {
299 + delete value.pattern;
300 + if (value.format === undefined) {
301 + value.format = patternFormatName;
302 } else {
246 - value.pattern = pattern;
303 + const allOf = Array.isArray(value.allOf) ? value.allOf : [];
304 + value.allOf = [...allOf, { format: patternFormatName }];
305 }
306 }
307 if (isObject(value.patternProperties)) {
308 + const renames = renamePatternKeys(value.patternProperties);
309 value.patternProperties = Object.fromEntries(
310 Object.entries(value.patternProperties).map(([pattern, schema]) => [
252 - toUnicodePattern(pattern) ?? pattern,
311 + renames.get(pattern) ?? pattern,
312 schema,
313 ])
314 );
@@ -257,12 +316,12 @@ const prepareInterpreterSchema = (value: unknown, seen: WeakSet<object>): void =
316
317 for (const [key, child] of Object.entries(value)) {
318 if (SCHEMA_MAP_KEYWORDS.has(key) && isObject(child)) {
260 - Object.values(child).forEach(nested => prepareInterpreterSchema(nested, seen));
319 + Object.values(child).forEach(nested => prepareInterpreterSchema(nested, seen, root));
320 } else if (SCHEMA_ARRAY_KEYWORDS.has(key) && Array.isArray(child)) {
262 - child.forEach(nested => prepareInterpreterSchema(nested, seen));
321 + child.forEach(nested => prepareInterpreterSchema(nested, seen, root));
322 } else if (SCHEMA_VALUE_KEYWORDS.has(key)) {
323 (Array.isArray(child) ? child : [child]).forEach(nested =>
265 - prepareInterpreterSchema(nested, seen)
324 + prepareInterpreterSchema(nested, seen, root)
325 );
326 }
327 }
@@ -316,7 +375,7 @@ export const withWholeSchemaValidation = (
375 parsedSchema: z.ZodTypeAny
376 ): z.ZodTypeAny => {
377 const interpreterSchema = structuredClone(jsonSchema);
319 - prepareInterpreterSchema(interpreterSchema, new WeakSet());
378 + prepareInterpreterSchema(interpreterSchema, new WeakSet(), jsonSchema);
379 const validator = new Validator(interpreterSchema as InterpreterSchema, '7', false);
380
381 // Validate the source value before defaults and other Zod transforms run.
ts/packages/json-schema-to-zod/test/semantic-regressions.test.ts
+42
@@ -358,6 +358,48 @@ describe('whole-schema semantic regressions', () => {
358 expect(parsed.safeParse({ ref: 'a-b' }).success).toBe(false);
359 });
360
361 + it.each([
362 + { name: 'a legacy identity escape', pattern: '^\\k_$', valid: 'k_', invalid: 'wrong' },
363 + { name: 'a quantified lookahead', pattern: '^(?=a){2}ab$', valid: 'ab', invalid: 'b' },
364 + ])('enforces $name in a pattern only the guard sees', ({ pattern, valid, invalid }) => {
365 + const schema: JsonSchema = {
366 + type: 'object',
367 + properties: { handle: { $ref: '#/$defs/handle' } },
368 + $defs: { handle: { type: 'string', pattern } },
369 + };
370 + const parsed = jsonSchemaToZod(schema);
371 +
372 + expect(parsed.safeParse({ handle: valid }).success).toBe(true);
373 + expect(parsed.safeParse({ handle: invalid }).success).toBe(false);
374 + });
375 +
376 + it('enforces every patternProperties key, including keys that differ only in escapes', () => {
377 + const schema: JsonSchema = {
378 + patternProperties: {
379 + '^a\\_b$': { type: 'integer', minimum: 10 },
380 + '^a_b$': { type: 'integer' },
381 + '^\\k_$': { type: 'string' },
382 + },
383 + };
384 + const parsed = jsonSchemaToZod(schema);
385 +
386 + expect(parsed.safeParse({ a_b: 12, k_: 'ok' }).success).toBe(true);
387 + expect(parsed.safeParse({ a_b: 2 }).success).toBe(false);
388 + expect(parsed.safeParse({ k_: 1 }).success).toBe(false);
389 + });
390 +
391 + it('resolves references nested under a patternProperties key that needs a rewrite', () => {
392 + const schema: JsonSchema = {
393 + type: 'object',
394 + patternProperties: { '^x\\_': { $ref: '#/$defs/label' } },
395 + $defs: { label: { type: 'string' } },
396 + };
397 + const parsed = jsonSchemaToZod(schema);
398 +
399 + expect(parsed.safeParse({ x_1: 'ok' }).success).toBe(true);
400 + expect(parsed.safeParse({ x_1: 1 }).success).toBe(false);
401 + });
402 +
403 it('compares decimal multiples by their JSON number spelling', () => {
404 const schema: JsonSchema = { type: 'number', multipleOf: 0.1 };
405 expect(jsonSchemaToZod(schema).safeParse(0.3).success).toBe(true);
ts/packages/json-schema-to-zod/test/unicode-pattern.test.ts new
+86
@@ -0,0 +1,86 @@
1 +import fc from 'fast-check';
2 +import { describe, expect, it } from 'vitest';
3 +
4 +import { toUnicodePattern } from '../src/utils/unicode-pattern';
5 +
6 +const compiles = (pattern: string, flags?: string): boolean => {
7 + try {
8 + new RegExp(pattern, flags);
9 + return true;
10 + } catch {
11 + return false;
12 + }
13 +};
14 +
15 +const legacyCases: ReadonlyArray<{ pattern: string; matches: string[]; rejects: string[] }> = [
16 + { pattern: '^[a-z\\_]+$', matches: ['a_b'], rejects: ['A'] },
17 + { pattern: '^\\k_$', matches: ['k_'], rejects: ['wrong', '\\k_'] },
18 + { pattern: '^a\\:b\\@c$', matches: ['a:b@c'], rejects: ['ab'] },
19 + { pattern: '^a{$', matches: ['a{'], rejects: ['a'] },
20 + { pattern: '^}]$', matches: ['}]'], rejects: [']'] },
21 + { pattern: '^\\x4$', matches: ['x4'], rejects: ['\x04'] },
22 + { pattern: '^\\u12$', matches: ['u12'], rejects: ['\u0012'] },
23 + { pattern: '^\\p{L}$', matches: ['p{L}'], rejects: ['a'] },
24 + { pattern: '^\\u{2}$', matches: ['uu'], rejects: ['\u0002'] },
25 + { pattern: '^\\c$', matches: ['\\c'], rejects: ['c'] },
26 + { pattern: '^[\\c1]$', matches: ['\x11'], rejects: ['1'] },
27 + { pattern: '^\\1$', matches: ['\x01'], rejects: ['1'] },
28 + { pattern: '^(a)\\1\\2$', matches: ['aa\x02'], rejects: ['aa'] },
29 + { pattern: '^\\8$', matches: ['8'], rejects: ['\\8'] },
30 + { pattern: '^[\\w-.]+$', matches: ['a-b.c'], rejects: ['a b'] },
31 + { pattern: '^[.-\\d]$', matches: ['-', '5'], rejects: ['/'] },
32 + { pattern: '^[\\B]$', matches: ['B'], rejects: ['b'] },
33 +];
34 +
35 +describe('toUnicodePattern', () => {
36 + it.each(legacyCases)('gives $pattern its legacy meaning', ({ pattern, matches, rejects }) => {
37 + const unicode = toUnicodePattern(pattern);
38 + expect(unicode).toBeDefined();
39 +
40 + for (const value of [...matches, ...rejects]) {
41 + expect(new RegExp(unicode!, 'u').test(value), value).toBe(new RegExp(pattern).test(value));
42 + }
43 + expect(matches.every(value => new RegExp(pattern).test(value))).toBe(true);
44 + expect(rejects.some(value => new RegExp(pattern).test(value))).toBe(false);
45 + });
46 +
47 + it('keeps patterns that already mean the same in both grammars', () => {
48 + expect(toUnicodePattern('^[a-z]+(?:-[a-z]+)*$')).toBe('^[a-z]+(?:-[a-z]+)*$');
49 + expect(toUnicodePattern('^(?<year>\\d{4})-\\k<year>$')).toBe('^(?<year>\\d{4})-\\k<year>$');
50 + });
51 +
52 + it('returns undefined for a quantified lookahead, which has no Unicode spelling', () => {
53 + expect(compiles('^(?=a){2}a$')).toBe(true);
54 + expect(toUnicodePattern('^(?=a){2}a$')).toBeUndefined();
55 + });
56 +
57 + it('matches exactly what the legacy pattern matches on ASCII input', () => {
58 + const pattern = fc
59 + .array(
60 + fc.constantFrom(
61 + ...'ab_:-.^$*+?()[]{}|/\\0189cdkpuxBDSWw,'.split(''),
62 + '\\',
63 + '\\\\',
64 + '{2}',
65 + '{1,3}'
66 + ),
67 + { maxLength: 12 }
68 + )
69 + .map(parts => parts.join(''))
70 + .filter(candidate => compiles(candidate));
71 + const input = fc.string({ unit: fc.constantFrom(...'ab_:-.^${}[]\\/ 019cdkpuxBw,'.split('')) });
72 +
73 + fc.assert(
74 + fc.property(pattern, fc.array(input, { maxLength: 8 }), (candidate, values) => {
75 + const unicode = toUnicodePattern(candidate);
76 + if (unicode === undefined) {
77 + return;
78 + }
79 + for (const value of values) {
80 + expect(new RegExp(unicode, 'u').test(value)).toBe(new RegExp(candidate).test(value));
81 + }
82 + }),
83 + { numRuns: 2000 }
84 + );
85 + });
86 +});
ts/packages/providers/langchain/test/langchain.test.ts
+30
@@ -2,6 +2,7 @@ import { describe, it, expect, beforeEach, vi } from 'vitest';
2 import { LangchainProvider } from '../src';
3 import { Tool } from '@composio/core';
4 import { DynamicStructuredTool } from '@langchain/core/tools';
5 +import { convertToOpenAITool } from '@langchain/core/utils/function_calling';
6
7 describe('LangchainProvider', () => {
8 let provider: LangchainProvider;
@@ -155,6 +156,35 @@ describe('LangchainProvider', () => {
156 expect(() => JSON.parse(result as string)).not.toThrow();
157 });
158
159 + it('should serialize tool parameters with an object root when a parameter uses anyOf', () => {
160 + const wrappedTool = provider.wrapTool(
161 + {
162 + ...sampleTool,
163 + inputParameters: {
164 + type: 'object',
165 + properties: {
166 + query: { type: 'string' },
167 + limit: { anyOf: [{ type: 'integer' }, { type: 'null' }] },
168 + },
169 + required: ['query'],
170 + },
171 + },
172 + executeToolFn
173 + );
174 +
175 + const parameters = convertToOpenAITool(wrappedTool).function.parameters;
176 +
177 + expect(parameters).toMatchObject({
178 + type: 'object',
179 + properties: {
180 + query: { type: 'string' },
181 + limit: { anyOf: [{ type: 'integer' }, { type: 'null' }] },
182 + },
183 + required: ['query'],
184 + });
185 + expect(parameters).not.toHaveProperty('allOf');
186 + });
187 +
188 it('should normalize a stringified-JSON input to an object before executing (issue #2406)', async () => {
189 const wrappedTool = provider.wrapTool(sampleTool, executeToolFn);
190