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