zodToJsonSchema.ts
1 /** 2 * Converts Zod v4 schemas to JSON Schema using native toJSONSchema. 3 */ 4 5 import { toJSONSchema, type ZodTypeAny } from 'zod/v4' 6 7 export type JsonSchema7Type = Record<string, unknown> 8 9 // toolToAPISchema() runs this for every tool on every API request (~60-250 10 // times/turn). Tool schemas are wrapped with lazySchema() which guarantees the 11 // same ZodTypeAny reference per session, so we can cache by identity. 12 const cache = new WeakMap<ZodTypeAny, JsonSchema7Type>() 13 14 /** 15 * Converts a Zod v4 schema to JSON Schema format. 16 */ 17 export function zodToJsonSchema(schema: ZodTypeAny): JsonSchema7Type { 18 const hit = cache.get(schema) 19 if (hit) return hit 20 const result = toJSONSchema(schema) as JsonSchema7Type 21 cache.set(schema, result) 22 return result 23 }