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

fact-sources.ts

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