Open History to see the last commit
1import { undoNullWidening } from '@tanstack/ai-utils'
2import {
3 isStrictModeCompatible,
4 makeStructuredOutputCompatibleWithMap,
5} from './schema-converter'
6import type { JSONSchema, Tool } from '@tanstack/ai'
7import type { NullWideningMap } from '@tanstack/ai-utils'
8import type { StructuredOutputCompatibility } from './schema-converter'
9
10type ToolInputNormalizer = (toolName: string, input: unknown) => unknown
11
12type SchemaConverterWithMap = (
13 schema: Record<string, any>,
14 originalRequired?: Array<string>,
15) => StructuredOutputCompatibility
16
17/**
18 * Build the inverse transform for the strict tool schemas sent in one request.
19 * Pass the same converter the request used so subclass schema tweaks stay
20 * aligned with undo. Non-strict tools are excluded because they were not
21 * null-widened on the wire.
22 */
23export function createToolInputNormalizer(
24 tools: Array<Tool> | undefined,
25 convertSchema: SchemaConverterWithMap = makeStructuredOutputCompatibleWithMap,
26): ToolInputNormalizer {
27 const maps = new Map<string, NullWideningMap>()
28 const seenNames = new Set<string>()
29 const ambiguousNames = new Set<string>()
30
31 for (const tool of tools ?? []) {
32 if (ambiguousNames.has(tool.name)) continue
33 if (seenNames.has(tool.name)) {
34 maps.delete(tool.name)
35 ambiguousNames.add(tool.name)
36 continue
37 }
38 seenNames.add(tool.name)
39
40 const inputSchema = (tool.inputSchema ?? {
41 type: 'object',
42 properties: {},
43 required: [],
44 }) as JSONSchema
45 if (!isStrictModeCompatible(inputSchema)) continue
46
47 const { nullWideningMap } = convertSchema(
48 inputSchema,
49 inputSchema.required || [],
50 )
51 if (nullWideningMap) maps.set(tool.name, nullWideningMap)
52 }
53
54 return (toolName, input) => undoNullWidening(input, maps.get(toolName))
55}