Open History to see the last commit
1/**
2 * Completeness: the share of the facts `@tanstack/ai-models` needs that a
3 * provider's rows carry. The one definition behind `pnpm run gap:report`
4 * (`scripts/gap-report.ts`) and `completeness` on `GET /v1/status`, so the
5 * CLI and the site cannot disagree. No Node or Workers dependencies.
6 *
7 * Each activity has its own fact set (`ACTIVITY_FACTS`). A row whose
8 * activity is null is a gap (`unclassified`); a row whose activity has no
9 * fact set is listed with `facts: null` and never scored. `originLink` is
10 * scored on every row, whatever its activity.
11 *
12 * `docs/source-silent/<provider>.md` lists facts a provider does not publish;
13 * those are left out of that provider's score and listed under `silent`.
14 */
15import { isCapabilityMap, supportedFlags } from './capabilities.ts'
16import { modelLedgerScope, parseLedgerEntry } from './source-silence-ledger.ts'
17
18export const FACT_KEYS = [
19 'contextWindow',
20 'maxOutput',
21 'modalities',
22 'priced',
23 'cacheRead',
24 'capabilities',
25 'reasoning',
26 'efforts',
27 'requestMap',
28 'endpoint',
29 'replayReasoningContent',
30 'outputModalities',
31 'activity',
32 'originLink',
33] as const
34
35export type FactKey = (typeof FACT_KEYS)[number]
36
37const MEDIA_FACTS = [
38 'priced',
39 'endpoint',
40 'modalities',
41 'outputModalities',
42] as const satisfies ReadonlyArray<FactKey>
43
44/** The bucket a row with a null activity is counted in. */
45export const UNCLASSIFIED = 'unclassified'
46
47/**
48 * The facts scored per activity. An activity not listed here has no fact
49 * set: its rows show as `facts: null` and do not change the score. A row
50 * with no activity is in `unclassified`, whose one fact it always lacks.
51 */
52export const ACTIVITY_FACTS = {
53 chat: [
54 'contextWindow',
55 'maxOutput',
56 'modalities',
57 'priced',
58 'cacheRead',
59 'capabilities',
60 'reasoning',
61 'efforts',
62 'requestMap',
63 'endpoint',
64 'replayReasoningContent',
65 ],
66 image: MEDIA_FACTS,
67 video: MEDIA_FACTS,
68 audio: MEDIA_FACTS,
69 [UNCLASSIFIED]: ['activity'],
70} as const satisfies Record<string, ReadonlyArray<FactKey>>
71
72export type ScoredActivity = keyof typeof ACTIVITY_FACTS
73
74/** The chat facts, in table order. */
75export const CHAT_FACT_KEYS: ReadonlyArray<FactKey> = ACTIVITY_FACTS.chat
76
77/**
78 * Row shapes `@tanstack/ai-models` cannot read correctly, counted apart from
79 * the score (issue #323). The score counts a fact as filled; a flag says the
80 * stored value still leaves the catalog to guess.
81 */
82export const FLAG_KEYS = [
83 'mandatoryUnknown',
84 'reasoningUnknown',
85 'outputModalitiesEmpty',
86 'mandatoryWithNone',
87] as const
88
89export type FlagKey = (typeof FLAG_KEYS)[number]
90
91/** The fields of a `/v1/models` row the report reads. */
92export type ModelRow = {
93 provider: string
94 /** Exact native model id, never the slugged catalog id. */
95 rawId?: string
96 aliases?: Array<string> | null
97 /** The upstream row this one is linked to, as `/v1/models` serves it. */
98 sameAs?: { provider: string; rawId: string } | null
99 activity?: string | null
100 contextWindow?: number | null
101 maxOutput?: number | null
102 modalities?: { input?: unknown; output?: unknown } | null
103 pricing?: {
104 tables?: { rate?: Record<string, unknown> }
105 source?: { url?: string }
106 } | null
107 capabilities?: unknown
108 reasoning?: {
109 mode?: string
110 mandatory?: boolean | null
111 efforts?: Array<string>
112 } | null
113 requestMap?: unknown
114 schemaEndpointId?: string | null
115 /**
116 * `cacheRead.path === 'not-offered'` is a stated absence: the provider's
117 * pricing table shows a cached-input cell that is "-" or blank. That
118 * fills the fact. It is not a price.
119 */
120 factSources?: {
121 cacheRead?: { path?: string } | null
122 } | null
123}
124
125export type FactTally = { have: number; need: number }
126
127export type ActivityReport = {
128 rows: number
129 /** Null when the activity has no fact set: its rows are not scored. */
130 facts: Partial<Record<FactKey, FactTally>> | null
131 /** Applicable missing rows excluded by exact model-scoped evidence. */
132 modelSilent: Partial<Record<FactKey, number>>
133 /** Facts filled and needed, ledgered ones left out. */
134 filled: number
135 needed: number
136 /** 0 to 1; null when `facts` is null. 1 when every needed fact is ledgered. */
137 score: number | null
138}
139
140export type ProviderReport = {
141 provider: string
142 rows: number
143 /** Rows with a null activity, counted in `activities.unclassified`. */
144 noActivity: number
145 fromModelsDev: number
146 /** By activity, plus `unclassified` for rows with none. */
147 activities: Partial<Record<string, ActivityReport>>
148 /**
149 * Rows whose id matches a row at another provider and that no row links
150 * to, plus every row with `sameAs` set. `have` counts `sameAs` set.
151 */
152 originLink: FactTally & { modelSilent: number }
153 silent: Array<FactKey>
154 /**
155 * 0 to 1 over every scored activity and `originLink`. Null when nothing
156 * is scored: every row's activity has no fact set and no row needs a link.
157 */
158 score: number | null
159 /** Raw ids of the chat rows each flag matches. */
160 flags: Record<FlagKey, Array<string>>
161}
162
163export type GapReport = {
164 generatedAt: string
165 providers: Array<ProviderReport>
166}
167
168/**
169 * Ledger facts served as `factSources` evidence and never scored: the gap
170 * report does not count them, so an entry changes no score.
171 */
172export const EVIDENCE_KEYS = ['serverTools'] as const
173
174export type LedgerKey = FactKey | (typeof EVIDENCE_KEYS)[number]
175
176/** Provider id or provider/exact-raw-id → facts its sources do not publish. */
177export type Ledger = Map<string, Set<LedgerKey>>
178
179function isLedgerKey(value: string): value is LedgerKey {
180 return ([...FACT_KEYS, ...EVIDENCE_KEYS] as ReadonlyArray<string>).includes(
181 value,
182 )
183}
184
185function isScoredActivity(value: string): value is ScoredActivity {
186 return Object.hasOwn(ACTIVITY_FACTS, value)
187}
188
189/** Ledger entries are list lines: `- <provider>: <fact> — <why>`. */
190export function parseLedger(markdown: string): Ledger {
191 const ledger: Ledger = new Map()
192 for (const line of markdown.split('\n')) {
193 const entry = parseLedgerEntry(line)
194 if (!entry) continue
195 const { scope, fact } = entry
196 if (!isLedgerKey(fact)) {
197 throw new Error(
198 `source-silent ledger: unknown fact "${fact}" in: ${line}`,
199 )
200 }
201 // Activity is our classification, not something a provider publishes.
202 if (fact === 'activity') {
203 throw new Error(
204 `source-silent ledger: classify the row, do not ledger it: ${line}`,
205 )
206 }
207 const facts = ledger.get(scope) ?? new Set<LedgerKey>()
208 facts.add(fact)
209 ledger.set(scope, facts)
210 }
211 return ledger
212}
213
214/**
215 * The ids a row matches another provider's row by: its raw id and aliases,
216 * each also with dots read as hyphens. The same tiers `reconcileSameAs`
217 * (`src/server/ingest/model-identity.ts`) links by.
218 */
219export function originIdKeys(row: Pick<ModelRow, 'rawId' | 'aliases'>) {
220 const ids = row.rawId === undefined ? [] : [row.rawId]
221 ids.push(...(row.aliases ?? []))
222 return new Set(ids.flatMap((id) => [id, id.replaceAll('.', '-')]))
223}
224
225/** Which rows need an origin link; built once over the whole catalog. */
226export type OriginIndex = {
227 providersById: Map<string, Set<string>>
228 /** `provider/rawId` of every row some other row links to. */
229 targets: Set<string>
230}
231
232const NO_ORIGINS: OriginIndex = { providersById: new Map(), targets: new Set() }
233
234export function originIndex(rows: Array<ModelRow>): OriginIndex {
235 const providersById = new Map<string, Set<string>>()
236 const targets = new Set<string>()
237 for (const row of rows) {
238 for (const key of originIdKeys(row)) {
239 const set = providersById.get(key) ?? new Set<string>()
240 set.add(row.provider)
241 providersById.set(key, set)
242 }
243 if (row.sameAs)
244 targets.add(modelLedgerScope(row.sameAs.provider, row.sameAs.rawId))
245 }
246 return { providersById, targets }
247}
248
249/**
250 * A row with `sameAs` set needs a link and has one. Otherwise it needs one
251 * when an id key matches a row at another provider, unless a row links to
252 * it: a link target is the origin, not the copy.
253 */
254function needsOriginLink(row: ModelRow, origins: OriginIndex): boolean {
255 if (row.sameAs) return true
256 if (
257 row.rawId !== undefined &&
258 origins.targets.has(modelLedgerScope(row.provider, row.rawId))
259 ) {
260 return false
261 }
262 return [...originIdKeys(row)].some((key) =>
263 [...(origins.providersById.get(key) ?? [])].some(
264 (provider) => provider !== row.provider,
265 ),
266 )
267}
268
269/**
270 * Public endpoint id, query and leading slash stripped. The route's wire
271 * is this path. There is no provider list.
272 */
273function endpointPath(endpointId: string | null | undefined): string {
274 if (!endpointId) return ''
275 return endpointId.split('?')[0]?.replace(/^\/+/, '') ?? ''
276}
277
278/**
279 * OpenAI-compatible chat wire: `chat/completions`, `completions`, or
280 * `responses`. `ChatRequestMap` describes that wire.
281 */
282function openAiCompatRoute(row: ModelRow): boolean {
283 return /(?:^|\/)(?:chat\/completions|responses|completions)$/.test(
284 endpointPath(row.schemaEndpointId),
285 )
286}
287
288/**
289 * `reasoning_content` is the chat-completions field. Anthropic thinking
290 * blocks, Gemini thought signatures, Responses reasoning items, and
291 * Converse replay on other paths, so those routes are not scored.
292 */
293function reasoningContentRoute(row: ModelRow): boolean {
294 return /(?:^|\/)chat\/completions$/.test(endpointPath(row.schemaEndpointId))
295}
296
297function reasons(row: ModelRow): boolean {
298 return (
299 row.reasoning != null ||
300 supportedFlags(row.capabilities).includes('reasoning')
301 )
302}
303
304function isModelsDev(row: ModelRow): boolean {
305 const url = row.pricing?.source?.url
306 if (!url) return false
307 try {
308 const { hostname } = new URL(url)
309 return hostname === 'models.dev' || hostname.endsWith('.models.dev')
310 } catch {
311 return false
312 }
313}
314
315/**
316 * The rate rows a lever must appear in: the base row, or, for a card with
317 * no base (BytePlus off-peak/peak, picked by a required lever), every row.
318 * Empty when absent or a models.dev price.
319 */
320function rateRows(row: ModelRow): Array<Record<string, unknown>> {
321 if (isModelsDev(row)) return []
322 const rate = row.pricing?.tables?.rate
323 if (!rate) return []
324 const rows = 'base' in rate ? [rate.base] : Object.values(rate)
325 return rows.every((r) => typeof r === 'object' && r !== null)
326 ? (rows as Array<Record<string, unknown>>)
327 : []
328}
329
330// Listing-compiled cards use OpenRouter's key names, parsed cards ours.
331function hasRate(row: ModelRow, ...keys: Array<string>): boolean {
332 const rows = rateRows(row)
333 return (
334 rows.length > 0 &&
335 rows.every((r) => keys.some((key) => typeof r[key] === 'number'))
336 )
337}
338
339const nonEmpty = (value: unknown) => Array.isArray(value) && value.length > 0
340
341/**
342 * `need`: the fact applies to this row. `have`: the row carries it. Only
343 * the facts of the row's activity are asked (`ACTIVITY_FACTS`), and
344 * `originLink` of every row.
345 */
346const FACTS: Record<
347 FactKey,
348 {
349 need?: (row: ModelRow, origins: OriginIndex) => boolean
350 have: (row: ModelRow) => boolean
351 }
352> = {
353 contextWindow: { have: (row) => row.contextWindow != null },
354 maxOutput: { have: (row) => row.maxOutput != null },
355 modalities: { have: (row) => nonEmpty(row.modalities?.input) },
356 outputModalities: { have: (row) => nonEmpty(row.modalities?.output) },
357 // Chat needs token rates; an image, video or audio card bills other
358 // units, so any stored card that is not a models.dev price fills it.
359 priced: {
360 have: (row) =>
361 row.activity === 'chat'
362 ? hasRate(row, 'input_tokens', 'prompt') &&
363 hasRate(row, 'output_tokens', 'completion')
364 : row.pricing != null && !isModelsDev(row),
365 },
366 cacheRead: {
367 have: (row) =>
368 hasRate(row, 'cache_read_tokens', 'input_cache_read') ||
369 row.factSources?.cacheRead?.path === 'not-offered',
370 },
371 capabilities: { have: (row) => isCapabilityMap(row.capabilities) },
372 // Filled by any stored object, whatever its `mandatory`: null there means
373 // the source is silent on turning thinking off, which is a stored fact.
374 reasoning: {
375 need: (row) =>
376 row.reasoning != null ||
377 supportedFlags(row.capabilities).includes('reasoning'),
378 have: (row) => row.reasoning != null,
379 },
380 // Only `effort` and `adaptive` rows need effort names; a `toggle` or
381 // `budget` row needs none. `mandatory` plays no part: efforts with
382 // `mandatory: null` is filled, and the `mandatoryUnknown` flag counts it.
383 efforts: {
384 need: (row) =>
385 row.reasoning?.mode === 'effort' || row.reasoning?.mode === 'adaptive',
386 have: (row) => (row.reasoning?.efforts?.length ?? 0) > 0,
387 },
388 requestMap: {
389 need: openAiCompatRoute,
390 have: (row) => row.requestMap != null,
391 },
392 endpoint: { have: (row) => row.schemaEndpointId != null },
393 replayReasoningContent: {
394 need: (row) => reasoningContentRoute(row) && reasons(row),
395 have: (row) =>
396 typeof row.requestMap === 'object' &&
397 row.requestMap !== null &&
398 !Array.isArray(row.requestMap) &&
399 typeof (row.requestMap as Record<string, unknown>)
400 .replayReasoningContent === 'boolean',
401 },
402 activity: { have: (row) => row.activity != null },
403 originLink: { need: needsOriginLink, have: (row) => row.sameAs != null },
404}
405
406/**
407 * `reasoningUnknown` is the `reasoning` gap, so a `reasoning` ledger entry
408 * for the provider or the exact model clears it. No ledger entry clears
409 * the other flags: each is a stored value in the wrong shape.
410 */
411const FLAGS: Record<
412 FlagKey,
413 { silencedBy?: FactKey; match: (row: ModelRow) => boolean }
414> = {
415 // The catalog cannot tell if it can offer an off level.
416 mandatoryUnknown: {
417 match: (row) =>
418 row.reasoning?.mode === 'effort' && row.reasoning.mandatory === null,
419 },
420 // The catalog has to guess the mode and the levels.
421 reasoningUnknown: {
422 silencedBy: 'reasoning',
423 match: (row) =>
424 FACTS.reasoning.need?.(row, NO_ORIGINS) === true &&
425 !FACTS.reasoning.have(row),
426 },
427 // The catalog reads `[]` as unknown; an unknown list is stored as null.
428 outputModalitiesEmpty: {
429 match: (row) => {
430 const output = row.modalities?.output
431 return Array.isArray(output) && output.length === 0
432 },
433 },
434 // Thinking cannot be turned off, yet `none` turns it off.
435 mandatoryWithNone: {
436 match: (row) =>
437 row.reasoning?.mandatory === true &&
438 (row.reasoning.efforts?.includes('none') ?? false),
439 },
440}
441
442/** One applicable fact of one row. */
443export type RowFact = {
444 fact: FactKey
445 have: boolean
446 /** Provider-wide ledgered, or missing and ledgered for this exact model. */
447 silent: boolean
448}
449
450/** The row's bucket in `ProviderReport.activities`. */
451export function activityBucket(row: Pick<ModelRow, 'activity'>): string {
452 return row.activity ?? UNCLASSIFIED
453}
454
455/**
456 * The facts that apply to one row and whether it carries each: its
457 * activity's set, then `originLink`. Empty for an activity with no fact
458 * set when no link applies. Without `origins` the link is asked only of a
459 * row with `sameAs` set, which has it.
460 */
461export function scoreRow(
462 row: ModelRow,
463 ledger: Ledger = new Map(),
464 origins: OriginIndex = NO_ORIGINS,
465): Array<RowFact> {
466 const bucket = activityBucket(row)
467 const keys: Array<FactKey> = [
468 ...(isScoredActivity(bucket) ? ACTIVITY_FACTS[bucket] : []),
469 'originLink',
470 ]
471 const providerSilent = ledger.get(row.provider)
472 const modelSilent =
473 row.rawId === undefined
474 ? undefined
475 : ledger.get(modelLedgerScope(row.provider, row.rawId))
476 return keys.flatMap((fact): Array<RowFact> => {
477 const { need, have } = FACTS[fact]
478 if (need && !need(row, origins)) return []
479 const has = have(row)
480 const silent =
481 providerSilent?.has(fact) === true ||
482 (!has && modelSilent?.has(fact) === true)
483 return [{ fact, have: has, silent }]
484 })
485}
486
487/** Filled of needed for one row, and the names of the facts it lacks. */
488export function rowCompleteness(facts: Array<RowFact>): {
489 filled: number
490 needed: number
491 missing: Array<FactKey>
492} {
493 const counted = facts.filter((f) => !f.silent)
494 return {
495 filled: counted.filter((f) => f.have).length,
496 needed: counted.length,
497 missing: counted.filter((f) => !f.have).map((f) => f.fact),
498 }
499}
500
501/** Facts filled and needed across a provider, ledgered ones left out. */
502export function scoredFacts(
503 report: Pick<ProviderReport, 'activities' | 'originLink' | 'silent'>,
504): FactTally {
505 let have = 0
506 let need = 0
507 for (const activity of Object.values(report.activities)) {
508 have += activity?.filled ?? 0
509 need += activity?.needed ?? 0
510 }
511 if (!report.silent.includes('originLink')) {
512 have += report.originLink.have
513 need += report.originLink.need - report.originLink.modelSilent
514 }
515 return { have, need }
516}
517
518const ratio = ({ have, need }: FactTally, rows: number): number | null =>
519 need > 0 ? have / need : rows > 0 ? 1 : null
520
521export function buildReport(
522 rows: Array<ModelRow>,
523 ledger: Ledger = new Map(),
524 now: Date = new Date(),
525): GapReport {
526 const origins = originIndex(rows)
527 const byProvider = new Map<string, Array<ModelRow>>()
528 for (const row of rows) {
529 const group = byProvider.get(row.provider)
530 if (group) group.push(row)
531 else byProvider.set(row.provider, [row])
532 }
533
534 const providers = [...byProvider].map(([provider, group]): ProviderReport => {
535 const silent = FACT_KEYS.filter((key) => ledger.get(provider)?.has(key))
536 const activities: Record<string, ActivityReport> = {}
537 const originLink = { have: 0, need: 0, modelSilent: 0 }
538 for (const row of group) {
539 const bucket = activityBucket(row)
540 const report = (activities[bucket] ??= {
541 rows: 0,
542 facts: isScoredActivity(bucket)
543 ? Object.fromEntries(
544 ACTIVITY_FACTS[bucket].map((key) => [key, { have: 0, need: 0 }]),
545 )
546 : null,
547 modelSilent: {},
548 filled: 0,
549 needed: 0,
550 score: null,
551 })
552 report.rows += 1
553 for (const { fact, have, silent: rowSilent } of scoreRow(
554 row,
555 ledger,
556 origins,
557 )) {
558 const providerSilent = silent.includes(fact)
559 const modelSilent = rowSilent && !providerSilent
560 if (fact === 'originLink') {
561 originLink.need += 1
562 if (have) originLink.have += 1
563 if (modelSilent) originLink.modelSilent += 1
564 continue
565 }
566 const tally = report.facts?.[fact]
567 if (!tally) continue
568 tally.need += 1
569 if (have) tally.have += 1
570 if (modelSilent) {
571 report.modelSilent[fact] = (report.modelSilent[fact] ?? 0) + 1
572 }
573 if (providerSilent || modelSilent) continue
574 report.needed += 1
575 if (have) report.filled += 1
576 }
577 }
578 for (const report of Object.values(activities)) {
579 report.score = report.facts
580 ? ratio({ have: report.filled, need: report.needed }, report.rows)
581 : null
582 }
583 const chat = group.filter((row) => row.activity === 'chat')
584 const modelLedgered = (row: ModelRow, key: FactKey) =>
585 row.rawId !== undefined &&
586 ledger.get(modelLedgerScope(provider, row.rawId))?.has(key)
587 const flags = Object.fromEntries(
588 FLAG_KEYS.map((key) => {
589 const { silencedBy, match } = FLAGS[key]
590 const isSilent = (row: ModelRow) =>
591 silencedBy !== undefined &&
592 (silent.includes(silencedBy) || modelLedgered(row, silencedBy))
593 return [
594 key,
595 chat
596 .filter((row) => match(row) && !isSilent(row))
597 .map((row) => row.rawId ?? ''),
598 ]
599 }),
600 ) as ProviderReport['flags']
601
602 const total = scoredFacts({ activities, originLink, silent })
603 const scoredRows = Object.values(activities)
604 .filter((a) => a.facts !== null)
605 .reduce((sum, a) => sum + a.rows, originLink.need)
606 return {
607 provider,
608 rows: group.length,
609 noActivity: activities[UNCLASSIFIED]?.rows ?? 0,
610 fromModelsDev: group.filter(isModelsDev).length,
611 activities,
612 originLink,
613 silent,
614 score: ratio(total, scoredRows),
615 flags,
616 }
617 })
618
619 const rank = (score: number | null) => score ?? Number.POSITIVE_INFINITY
620 providers.sort(
621 (a, b) =>
622 rank(a.score) - rank(b.score) || a.provider.localeCompare(b.provider),
623 )
624 return { generatedAt: now.toISOString(), providers }
625}