Skip to content
Source
Sign inSign up
TanStack/schemas
Open History to see the last commit

fact-sources.ts

539 lines16.4 KB

1/**
2 * Catalog-fact merge for issue #53: listing/docs first, then capability
3 * flags walked from the bound generation request schema. Each stored
4 * value keeps the winning rung. `generated` OpenAI-borrowed specs are
5 * skipped — walking them would stamp OpenAI's tools onto DeepSeek etc.
6 *
7 * Modalities are never walked. A request schema names the media parts a
8 * route accepts (`image_url`, `input_audio`), not what one model takes; it
9 * has no key for text and none for output. Walked, it gave every model on
10 * a route the same `{ input: ['image', 'audio'], output: [] }`.
11 */
12import { isCapabilityMap, supportedFlags } from '#/lib/capabilities.ts'
13​
14import { undatedId } from './model-facts.ts'
15import type {
16 Derivation,
17 FactDerivation,
18 FactSource,
19 ModelFactSources,
20 ModelInfo,
21} from './types.ts'
22​
23/** OpenRouter `supported_parameters` names plus native extras we already store. */
24const PROPERTY_TO_FLAG: Record<string, string> = {
25 tools: 'tools',
26 tool_choice: 'tool_choice',
27 toolConfig: 'tool_choice',
28 max_tokens: 'max_tokens',
29 max_completion_tokens: 'max_tokens',
30 max_output_tokens: 'max_tokens',
31 maxOutputTokens: 'max_tokens',
32 temperature: 'temperature',
33 top_p: 'top_p',
34 topP: 'top_p',
35 top_k: 'top_k',
36 topK: 'top_k',
37 stop: 'stop',
38 seed: 'seed',
39 frequency_penalty: 'frequency_penalty',
40 presence_penalty: 'presence_penalty',
41 response_format: 'response_format',
42 reasoning: 'reasoning',
43 thinking: 'reasoning',
44 include_reasoning: 'include_reasoning',
45 reasoning_effort: 'reasoning_effort',
46 effort: 'reasoning_effort',
47 structured_outputs: 'structured_outputs',
48 responseSchema: 'structured_outputs',
49 responseMimeType: 'response_format',
51​
52const NESTED_CONTAINERS = new Set([
53 'generationConfig',
54 'generation_config',
55 'output_config',
56 'thinking',
57 'reasoning',
58])
59​
60/**
61 * `factSources.modalities.path` for a row whose own docs were read and state
62 * no modalities: the field is null because the source is silent.
63 */
64export const MODALITIES_SOURCE_SILENT = 'silent'
65​
66function isRecord(value: unknown): value is Record<string, unknown> {
67 return typeof value === 'object' && value !== null && !Array.isArray(value)
69​
70function isStringArray(value: unknown): value is Array<string> {
71 return Array.isArray(value) && value.every((item) => typeof item === 'string')
73​
74export function emptySources(sources: ModelFactSources): boolean {
75 return (
76 sources.contextWindow === undefined &&
77 sources.maxOutput === undefined &&
78 sources.modalities === undefined &&
79 sources.pricing === undefined &&
80 sources.reasoning === undefined &&
81 sources.knowledgeCutoff === undefined &&
82 sources.openWeights === undefined &&
83 sources.requestMap === undefined &&
84 (sources.capabilities === undefined ||
85 Object.keys(sources.capabilities).length === 0) &&
86 (sources.serverTools === undefined ||
87 Object.keys(sources.serverTools).length === 0)
88 )
90​
91function listingSource(): FactSource {
92 return { derivation: 'listing' }
94​
95export function listingSources(info: ModelInfo): ModelFactSources {
96 const out: ModelFactSources = {}
97 if (info.contextWindow != null) out.contextWindow = listingSource()
98 if (info.maxOutput != null) out.maxOutput = listingSource()
99 if (info.modalities != null) out.modalities = listingSource()
100 if (info.pricing != null) out.pricing = listingSource()
101 if (info.reasoning != null) out.reasoning = listingSource()
102 if (info.knowledgeCutoff != null) out.knowledgeCutoff = listingSource()
103 if (info.openWeights != null) out.openWeights = listingSource()
104 // A stated no is sourced like a stated yes, under the same record.
105 const flags = [
106 ...(isStringArray(info.capabilities) ? info.capabilities : []),
107 ...(info.unsupportedCapabilities ?? []),
108 ]
109 if (flags.length > 0) {
110 out.capabilities = Object.fromEntries(
111 flags.map((flag) => [flag, listingSource()]),
112 )
113 }
114 if (info.serverTools != null && info.serverTools.length > 0) {
115 out.serverTools = Object.fromEntries(
116 info.serverTools.map((tool) => [tool, listingSource()]),
117 )
118 }
119 if (!info.factSources) return out
120 const capabilities =
121 out.capabilities || info.factSources.capabilities
122 ? { ...out.capabilities, ...info.factSources.capabilities }
123 : undefined
124 const serverTools =
125 out.serverTools || info.factSources.serverTools
126 ? { ...out.serverTools, ...info.factSources.serverTools }
127 : undefined
128 return {
129 ...out,
130 ...info.factSources,
131 ...(capabilities ? { capabilities } : {}),
132 ...(serverTools ? { serverTools } : {}),
133 }
135​
136/** Attach `docs-derived` provenance to every stated fact on a docs page. */
137export function tagDocsFacts(
138 facts: Pick<
139 ModelInfo,
140 | 'contextWindow'
141 | 'maxOutput'
142 | 'modalities'
143 | 'capabilities'
144 | 'pricing'
145 | 'reasoning'
146 | 'serverTools'
147 >,
148 sourceUrl: string,
149 sourceHash?: string,
150): ModelFactSources {
151 const src = (path: string): FactSource => ({
152 derivation: 'docs-derived',
153 sourceUrl,
154 ...(sourceHash ? { sourceHash } : {}),
155 path,
156 })
157 const out: ModelFactSources = {}
158 if (facts.pricing != null) out.pricing = src('Pricing')
159 if (facts.contextWindow != null) out.contextWindow = src('contextWindow')
160 if (facts.maxOutput != null) out.maxOutput = src('maxOutput')
161 if (facts.modalities != null) out.modalities = src('modalities')
162 if (isStringArray(facts.capabilities) && facts.capabilities.length > 0) {
163 out.capabilities = Object.fromEntries(
164 facts.capabilities.map((flag) => [flag, src(`capabilities.${flag}`)]),
165 )
166 }
167 if (facts.reasoning != null) out.reasoning = src('reasoning')
168 if (facts.serverTools != null && facts.serverTools.length > 0) {
169 out.serverTools = Object.fromEntries(
170 facts.serverTools.map((tool) => [tool, src(`serverTools.${tool}`)]),
171 )
172 }
173 return out
175​
176function resolveRef(
177 root: Record<string, unknown>,
178 node: unknown,
179 depth = 0,
180): unknown {
181 if (depth > 8 || !isRecord(node) || typeof node.$ref !== 'string') return node
182 const ref = node.$ref
183 if (!ref.startsWith('#/$defs/')) return node
184 const defs = isRecord(root.$defs) ? root.$defs : {}
185 const name = ref.slice('#/$defs/'.length)
186 const target = defs[name]
187 return target === undefined ? node : resolveRef(root, target, depth + 1)
189​
190function propertiesOf(
191 root: Record<string, unknown>,
192 node: unknown,
193): Record<string, unknown> {
194 const resolved = resolveRef(root, node)
195 if (!isRecord(resolved)) return {}
196 const own = isRecord(resolved.properties) ? resolved.properties : {}
197 const out: Record<string, unknown> = { ...own }
198 const combiners = [resolved.allOf, resolved.anyOf, resolved.oneOf]
199 for (const list of combiners) {
200 if (!Array.isArray(list)) continue
201 for (const item of list) {
202 Object.assign(out, propertiesOf(root, item))
203 }
204 }
205 return out
207​
208/** Top-level request-body property names, including allOf/anyOf/oneOf. */
209export function requestSchemaPropertyNames(schema: unknown): Set<string> {
210 if (!isRecord(schema)) return new Set()
211 return new Set(Object.keys(propertiesOf(schema, schema)))
213​
214/**
215 * One `[model id, request schema]` per entry of a `model` discriminator.
216 * A union walked whole would give every model its siblings' fields.
217 */
218export function modelBranchSchemas(schema: unknown): Array<[string, unknown]> {
219 if (!isRecord(schema) || !isRecord(schema.discriminator)) return []
220 const { propertyName, mapping } = schema.discriminator
221 if (propertyName !== 'model' || !isRecord(mapping)) return []
222 const { oneOf: _oneOf, anyOf: _anyOf, discriminator: _d, ...rest } = schema
223 // The branch joins `allOf`: a `$ref` beside the union's shared `properties`
224 // would replace them when resolved.
225 const shared: Array<unknown> = Array.isArray(rest.allOf) ? rest.allOf : []
226 return Object.entries(mapping).flatMap(([rawId, ref]) =>
227 typeof ref === 'string'
228 ? [
229 [
230 rawId,
231 {
232 ...rest,
233 allOf: [
234 ...shared,
235 { $ref: `#/$defs/${ref.slice(ref.lastIndexOf('/') + 1)}` },
236 ],
237 },
238 ] satisfies [string, unknown],
239 ]
240 : [],
241 )
243​
244export interface SchemaWalk {
245 flags: Array<string>
246 sources: ModelFactSources
248​
249/**
250 * Walk a bundled request schema for OpenRouter parameter names.
251 * `generated` schemas are skipped by the caller.
252 */
253export function walkRequestSchema(
254 schema: unknown,
255 meta: {
256 derivation: FactDerivation
257 endpointId: string
258 sourceUrl?: string | null
259 sourceHash?: string | null
260 fetchedAt?: number
261 },
262): SchemaWalk | null {
263 if (!isRecord(schema)) return null
264 const props = propertiesOf(schema, schema)
265 const flags = new Map<string, string>()
266 const note = (name: string, pointer: string) => {
267 const flag = PROPERTY_TO_FLAG[name]
268 if (flag && !flags.has(flag)) flags.set(flag, pointer)
269 }
270 for (const [name, node] of Object.entries(props)) {
271 note(name, `/properties/${name}`)
272 if (!NESTED_CONTAINERS.has(name)) continue
273 const nested = propertiesOf(schema, node)
274 for (const nestedName of Object.keys(nested)) {
275 note(nestedName, `/properties/${name}/properties/${nestedName}`)
276 }
277 }
278 if (flags.has('response_format')) {
279 const rf = resolveRef(schema, props.response_format)
280 const rfProps = propertiesOf(schema, rf)
281 if ('json_schema' in rfProps || 'schema' in rfProps) {
282 flags.set('structured_outputs', '/properties/response_format')
283 }
284 }
285 if (flags.has('structured_outputs') && !flags.has('response_format')) {
286 flags.set('response_format', '/properties/responseSchema')
287 }
288​
289 const source = (path: string): FactSource => ({
290 derivation: meta.derivation,
291 endpointId: meta.endpointId,
292 path,
293 ...(meta.sourceUrl ? { sourceUrl: meta.sourceUrl } : {}),
294 ...(meta.sourceHash ? { sourceHash: meta.sourceHash } : {}),
295 ...(meta.fetchedAt !== undefined ? { fetchedAt: meta.fetchedAt } : {}),
296 })
297​
298 if (flags.size === 0) return null
299 return {
300 flags: [...flags.keys()],
301 sources: {
302 capabilities: Object.fromEntries(
303 [...flags].map(([flag, path]) => [flag, source(path)]),
304 ),
305 },
306 }
308​
309export interface MergedFacts {
310 contextWindow: number | null
311 maxOutput: number | null
312 modalities: unknown
313 pricing: unknown
314 capabilities: unknown
315 factSources: ModelFactSources | null
317​
318/**
319 * Listing/docs win on a field they stated. Schema fills remaining
320 * capability flags, and nothing else: modalities the listing does not
321 * state stay null. Host-native capability objects and `exactCapabilities`
322 * listings are left alone, and so is a flag the listing says the model
323 * does not support: a shared schema that carries the field does not
324 * outrank the provider's own no.
325 */
326export function mergeListingAndSchema(
327 listing: ModelInfo,
328 walk: SchemaWalk | null,
329): MergedFacts {
330 const listed = listingSources(listing)
331 const capabilitiesIsObject = isRecord(listing.capabilities)
332 const closed = capabilitiesIsObject || listing.exactCapabilities === true
333​
334 let capabilities: unknown = listing.capabilities ?? null
335 const capSources: Record<string, FactSource> = {
336 ...(listed.capabilities ?? {}),
337 }
338 if (!closed && walk && walk.flags.length > 0) {
339 const have = new Set(isStringArray(capabilities) ? capabilities : [])
340 const refused = new Set(listing.unsupportedCapabilities)
341 for (const flag of walk.flags) {
342 if (have.has(flag) || refused.has(flag)) continue
343 have.add(flag)
344 const src = walk.sources.capabilities?.[flag]
345 if (src) capSources[flag] = src
346 }
347 capabilities = have.size > 0 ? [...have] : null
348 }
349​
350 const sources: ModelFactSources = { ...listed }
351 if (Object.keys(capSources).length > 0 && !capabilitiesIsObject) {
352 sources.capabilities = capSources
353 }
354​
355 return {
356 contextWindow: listing.contextWindow ?? null,
357 maxOutput: listing.maxOutput ?? null,
358 modalities: listing.modalities ?? null,
359 pricing: listing.pricing ?? null,
360 capabilities,
361 factSources: emptySources(sources) ? null : sources,
362 }
364​
365export function schemaRung(
366 derivation: Derivation | null,
367): FactDerivation | null {
368 if (derivation === null || derivation === 'generated') return null
369 return derivation
371​
372export interface FactDiscrepancy {
373 field: string
374 ours: unknown
375 openrouter: unknown
376 oursDerivation: FactDerivation | null
377 openrouterId: string
379​
380const OPENROUTER_AUTHOR: Record<string, string> = {
381 openai: 'openai',
382 anthropic: 'anthropic',
383 gemini: 'google',
384 grok: 'x-ai',
385 mistral: 'mistralai',
386 groq: 'groq',
387 cohere: 'cohere',
388 together: 'together',
389 deepseek: 'deepseek',
390 perplexity: 'perplexity',
391 moonshot: 'moonshotai',
392 fireworks: 'fireworks',
393 cerebras: 'cerebras',
394 novita: 'novita',
395 jina: 'jina',
396 sambanova: 'sambanova',
397 hyperbolic: 'hyperbolic',
399​
400export function openRouterJoinIds(
401 providerId: string,
402 rawId: string,
403): Array<string> {
404 const author = OPENROUTER_AUTHOR[providerId]
405 if (!author) return []
406 const ids = [`${author}/${rawId}`]
407 const undated = undatedId(rawId)
408 if (undated !== rawId) ids.push(`${author}/${undated}`)
409 const dotted = undated.replace(/(\d+)-(\d+)$/, '$1.$2')
410 if (dotted !== undated) ids.push(`${author}/${dotted}`)
411 if (providerId === 'grok') {
412 // xAI pins `-MMDD` snapshots and splits reasoning modes into ids;
413 // OpenRouter lists one `x-ai/grok-4.20` for both.
414 const family = undated
415 .replace(/-\d{4}(?=-|$)/, '')
416 .replace(/-(non-)?reasoning$/, '')
417 if (family !== undated) ids.push(`${author}/${family}`)
418 }
419 return ids
421​
422function sortedStrings(value: unknown): Array<string> | null {
423 if (!isStringArray(value)) return null
424 return [...value].sort()
426​
427function modalitiesOf(
428 value: unknown,
429): { input: Array<string>; output: Array<string> } | null {
430 if (!isRecord(value)) return null
431 const hasInput = isStringArray(value.input)
432 const hasOutput = isStringArray(value.output)
433 if (!hasInput && !hasOutput) return null
434 return {
435 input: sortedStrings(value.input) ?? [],
436 output: sortedStrings(value.output) ?? [],
437 }
439​
440function capDerivation(
441 sources: ModelFactSources | null,
442 flag: string,
443): FactDerivation | null {
444 return sources?.capabilities?.[flag]?.derivation ?? null
446​
447/** First-party vs OpenRouter. Objects (FAL/etc) are not compared as flags. */
448export function factDiscrepancies(
449 ours: {
450 contextWindow: unknown
451 maxOutput: unknown
452 modalities: unknown
453 capabilities: unknown
454 factSources: ModelFactSources | null
455 },
456 openrouter: {
457 rawId: string
458 contextWindow: unknown
459 maxOutput: unknown
460 modalities: unknown
461 capabilities: unknown
462 },
463): Array<FactDiscrepancy> {
464 const out: Array<FactDiscrepancy> = []
465 const push = (
466 field: string,
467 oursValue: unknown,
468 theirs: unknown,
469 oursDerivation: FactDerivation | null,
470 ) => {
471 out.push({
472 field,
473 ours: oursValue,
474 openrouter: theirs,
475 oursDerivation,
476 openrouterId: openrouter.rawId,
477 })
478 }
479 if (ours.contextWindow !== openrouter.contextWindow) {
480 push(
481 'contextWindow',
482 ours.contextWindow,
483 openrouter.contextWindow,
484 ours.factSources?.contextWindow?.derivation ?? null,
485 )
486 }
487 if (ours.maxOutput !== openrouter.maxOutput) {
488 push(
489 'maxOutput',
490 ours.maxOutput,
491 openrouter.maxOutput,
492 ours.factSources?.maxOutput?.derivation ?? null,
493 )
494 }
495 const oursMod = modalitiesOf(ours.modalities)
496 const theirMod = modalitiesOf(openrouter.modalities)
497 if (oursMod !== null || theirMod !== null) {
498 if (
499 oursMod === null ||
500 theirMod === null ||
501 JSON.stringify(oursMod) !== JSON.stringify(theirMod)
502 ) {
503 push(
504 'modalities',
505 ours.modalities,
506 openrouter.modalities,
507 ours.factSources?.modalities?.derivation ?? null,
508 )
509 }
510 }
511 // Stored maps: what each side says yes to. A `false` and a missing key
512 // both read as "not listed" here, as a missing list entry did.
513 const oursCaps = isCapabilityMap(ours.capabilities)
514 ? supportedFlags(ours.capabilities).sort()
515 : null
516 const theirCaps = isCapabilityMap(openrouter.capabilities)
517 ? supportedFlags(openrouter.capabilities).sort()
518 : null
519 if (oursCaps !== null && theirCaps !== null) {
520 const theirSet = new Set(theirCaps)
521 const oursSet = new Set(oursCaps)
522 for (const flag of oursCaps) {
523 if (!theirSet.has(flag)) {
524 push(
525 `capabilities.${flag}`,
526 true,
527 false,
528 capDerivation(ours.factSources, flag),
529 )
530 }
531 }
532 for (const flag of theirCaps) {
533 if (!oursSet.has(flag)) {
534 push(`capabilities.${flag}`, false, true, null)
535 }
536 }
537 }
538 return out