import { undoNullWidening } from '@tanstack/ai-utils' import { makeStructuredOutputCompatible } from './schema-converter' import type { JSONSchema, Tool } from '@tanstack/ai' import type { NullWideningMap } from '@tanstack/ai-utils' /** * Responses API function tool format. * * Matches OpenRouter's `ResponsesRequestToolFunction` shape exactly: * { type: 'function', name: string, description?: string, parameters: object, strict?: boolean } */ export interface ResponsesFunctionTool { type: 'function' name: string description?: string | null parameters: Record | null strict: boolean | null } /** * Converts a standard Tool to the Responses API FunctionTool format. * * Tool schemas are already converted to JSON Schema in the ai layer. * We apply OpenAI-compatible transformations for strict mode: * - All properties in required array * - Optional fields made nullable * - additionalProperties: false * * This enables strict mode for all tools automatically. */ export function convertFunctionToolToResponsesFormat( tool: Tool, schemaConverter: ( schema: Record, required: Array, ) => Record = makeStructuredOutputCompatible, ): ResponsesFunctionTool { const inputSchema = (tool.inputSchema ?? { type: 'object', properties: {}, required: [], }) as JSONSchema // Shallow-copy the converter's result before mutating — a subclass-supplied // schemaConverter has no contract requirement to return a fresh object; // mutating in place could corrupt the caller's tool definition. const jsonSchema = { ...schemaConverter(inputSchema, inputSchema.required || []), } jsonSchema.additionalProperties = false return { type: 'function', name: tool.name, description: tool.description, parameters: jsonSchema, strict: true, } } function allowsNull(schema: JSONSchema | undefined): boolean { if (!schema || typeof schema !== 'object') return false if (schema.type === 'null') return true if (Array.isArray(schema.type) && schema.type.includes('null')) return true if (Array.isArray(schema.enum) && schema.enum.includes(null)) return true return Array.isArray(schema.anyOf) && schema.anyOf.some(allowsNull) } /** * zod 4 writes a recursive reference as `allOf: [{ $ref }]`. The converter * emits the bare `$ref` (wrapped in `anyOf` when the field was optional). */ function unwrapSingleRefAllOf(schema: JSONSchema): JSONSchema { const allOf = schema.allOf if ( !Array.isArray(allOf) || allOf.length !== 1 || !allOf[0] || typeof allOf[0].$ref !== 'string' ) { return schema } const { allOf: _allOf, ...rest } = schema return { ...rest, ...allOf[0] } } function pointerToken(name: string): string { return name.replace(/~/g, '~0').replace(/\//g, '~1') } type DefinitionMaps = Map /** * One shared map per definition, filled in place. A `$ref` holds that object * (or a copy that shares `properties`), so a recursive schema stays cyclic * instead of walking forever. `undoNullWidening` walks the data, so it ends. */ function definitionMaps( original: JSONSchema, wire: JSONSchema, ): DefinitionMaps { const maps: DefinitionMaps = new Map() const slots: Array<{ map: NullWideningMap properties: Record originalDef: JSONSchema | undefined wireDef: JSONSchema | undefined }> = [] for (const pool of ['$defs', 'definitions'] as const) { const originalDefs = original[pool] const wireDefs = wire[pool] if (!originalDefs || !wireDefs) continue for (const name of Object.keys(wireDefs)) { const properties: Record = {} const map: NullWideningMap = { properties } maps.set(`#/${pool}/${pointerToken(name)}`, map) slots.push({ map, properties, originalDef: originalDefs[name], wireDef: wireDefs[name], }) } } for (const slot of slots) { const filled = diffNullWidening(slot.originalDef, slot.wireDef, maps) if (!filled) continue if (filled.properties) Object.assign(slot.properties, filled.properties) if (filled.items) slot.map.items = filled.items if (filled.widened) slot.map.widened = true } return maps } /** * Diff the original tool schema against the strict wire schema and mark every * position where the converter added `null`. Diffing the actual wire schema * keeps the map aligned with a subclass-supplied `schemaConverter`. A field * that already allowed `null` (`.nullable()`, `.nullish()`) is not marked, so * its `null` survives. `$ref` properties use the shared definition map, so * nulls synthesized inside `$defs` / `definitions` are stripped too. */ function diffNullWidening( original: JSONSchema | undefined, wire: JSONSchema | undefined, maps?: DefinitionMaps, ): NullWideningMap | undefined { if (!original || !wire || typeof original !== 'object') return undefined const defs = maps ?? definitionMaps(original, wire) const source = unwrapSingleRefAllOf(original) const sent = unwrapSingleRefAllOf(wire) if (typeof source.$ref === 'string') { const defMap = defs.get(source.$ref) const widened = allowsNull(sent) && !allowsNull(source) if (defMap) return widened ? { ...defMap, widened: true } : defMap return widened ? { widened: true } : undefined } const map: NullWideningMap = {} if (allowsNull(sent) && !allowsNull(source)) map.widened = true if (source.properties && sent.properties) { // Entries, not assignment: `map['__proto__'] = x` sets the prototype and // drops a property that is really named `__proto__`. const properties: Array<[string, NullWideningMap]> = [] for (const key of Object.keys(sent.properties)) { const child = diffNullWidening( source.properties[key], sent.properties[key], defs, ) if (child) properties.push([key, child]) } if (properties.length > 0) map.properties = Object.fromEntries(properties) } if ( source.items && sent.items && !Array.isArray(source.items) && !Array.isArray(sent.items) ) { const items = diffNullWidening(source.items, sent.items, defs) if (items) map.items = items } // A `.nullable()` object reaches the wire as `anyOf: [object, null]`, and // the converter widens inside the object variant. Descend into that one // variant. A union of several shapes is ambiguous, so it is left alone. const nonNullVariants = (schema: JSONSchema) => (schema.anyOf ?? []).filter((variant) => variant.type !== 'null') const originalVariants = nonNullVariants(source) const wireVariants = nonNullVariants(sent) if (originalVariants.length === 1 && wireVariants.length === 1) { const inner = diffNullWidening(originalVariants[0], wireVariants[0], defs) if (inner?.properties) map.properties = inner.properties if (inner?.items) map.items = inner.items } return Object.keys(map).length > 0 ? map : undefined } /** * Build the inverse of the strict null-widening applied to the tools of one * request. Strict tools reach the model with every optional field promoted to * required + nullable, so the model sends `null` for an omitted optional. The * returned function strips exactly those synthesized nulls, so the engine * validates the input against the original schema and `execute` sees the * field as absent. Pass the same converter the request used. */ export function createToolInputNormalizer( tools: Array | undefined, schemaConverter?: Parameters[1], ): (toolName: string, input: unknown) => unknown { const maps = new Map() for (const tool of tools ?? []) { const map = diffNullWidening( tool.inputSchema, convertFunctionToolToResponsesFormat(tool, schemaConverter).parameters ?? undefined, ) if (map) maps.set(tool.name, map) } return (toolName, input) => undoNullWidening(input, maps.get(toolName)) }