Open History to see the last commit
1/**
2 * models.dev is not a catalog source (issue #197). Stored cards and schema
3 * versions that name its API are dropped. A skipping adapter is not an empty
4 * list: an empty list would also deprecate a later first-party row the next
5 * time a key is missing. The frozen models.dev snapshot is retired once.
6 * After a real list settles the provider, a skip leaves those rows alone.
7 */
8import { and, eq, inArray, sql } from 'drizzle-orm'
9
10import type { Db } from '#/db/index.ts'
11import {
12 cacheMeta,
13 changes,
14 endpoints,
15 models,
16 schemaVersions,
17} from '#/db/schema.ts'
18import { parseStoredRateCard } from '#/server/rate-card.ts'
19
20export const MODELS_DEV_API_URL = 'https://models.dev/api.json'
21
22const SETTLED_PREFIX = 'models-dev-settled:'
23
24function settledKey(providerId: string): string {
25 return `${SETTLED_PREFIX}${providerId}`
26}
27
28export function isModelsDevRateCard(pricing: unknown): boolean {
29 return parseStoredRateCard(pricing)?.source.url === MODELS_DEV_API_URL
30}
31
32/** A models.dev card is not a price to keep across a null incoming list. */
33export function storedCardIsPrior(pricing: unknown): boolean {
34 return parseStoredRateCard(pricing) !== null && !isModelsDevRateCard(pricing)
35}
36
37function collectSourceUrls(value: unknown, urls: Array<string>): void {
38 if (Array.isArray(value)) {
39 for (const item of value) collectSourceUrls(item, urls)
40 return
41 }
42 if (typeof value !== 'object' || value === null) return
43 for (const [key, child] of Object.entries(value)) {
44 if (key === 'sourceUrl' && typeof child === 'string' && child.length > 0) {
45 urls.push(child)
46 } else {
47 collectSourceUrls(child, urls)
48 }
49 }
50}
51
52function hasFirstPartyProvenance(row: {
53 pricing: unknown
54 factSources: unknown
55}): boolean {
56 const urls: Array<string> = []
57 const card = parseStoredRateCard(row.pricing)
58 if (card?.source.url) urls.push(card.source.url)
59 collectSourceUrls(row.factSources, urls)
60 return urls.some((url) => url !== MODELS_DEV_API_URL)
61}
62
63/** Delete schema versions derived from the models.dev document. */
64export async function dropModelsDevSchemaVersions(
65 db: Db,
66 providerId: string,
67): Promise<void> {
68 const rows = await db
69 .select({ id: schemaVersions.id })
70 .from(schemaVersions)
71 .innerJoin(endpoints, eq(schemaVersions.endpointId, endpoints.id))
72 .where(
73 and(
74 eq(endpoints.providerId, providerId),
75 eq(schemaVersions.sourceUrl, MODELS_DEV_API_URL),
76 ),
77 )
78 for (let i = 0; i < rows.length; i += 90) {
79 const ids = rows.slice(i, i + 90).map((row) => row.id)
80 await db.delete(schemaVersions).where(inArray(schemaVersions.id, ids))
81 }
82}
83
84/**
85 * Null every stored card whose source is models.dev, and drop the pricing
86 * fact that pointed at it. Docs cards use a different source URL and stay.
87 */
88export async function nullModelsDevRateCards(
89 db: Db,
90 providerId: string,
91): Promise<void> {
92 await db
93 .update(models)
94 .set({
95 pricing: null,
96 factSources: sql`CASE
97 WHEN json_remove(${models.factSources}, '$.pricing') = '{}' THEN NULL
98 ELSE json_remove(${models.factSources}, '$.pricing')
99 END`,
100 })
101 .where(
102 and(
103 eq(models.providerId, providerId),
104 sql`json_extract(${models.pricing}, '$.source.url') = ${MODELS_DEV_API_URL}`,
105 ),
106 )
107}
108
109async function catalogSettled(db: Db, providerId: string): Promise<boolean> {
110 const row = await db.query.cacheMeta.findFirst({
111 where: eq(cacheMeta.key, settledKey(providerId)),
112 })
113 return row !== undefined
114}
115
116/** Remember that this provider's catalog is no longer the models.dev snapshot. */
117export async function markModelsDevCatalogSettled(
118 db: Db,
119 providerId: string,
120 now: number,
121): Promise<void> {
122 if (await catalogSettled(db, providerId)) return
123 await db
124 .insert(cacheMeta)
125 .values({
126 key: settledKey(providerId),
127 fetchedAt: now,
128 staleTime: 0,
129 })
130 .onConflictDoNothing()
131}
132
133/**
134 * Deprecate active rows when this provider has never published a first-party
135 * list. Returns how many rows were deprecated. A later real list clears
136 * `deprecatedAt` for ids it returns; a later skip does not run this again.
137 */
138export async function deprecateFrozenModelsDevCatalog(
139 db: Db,
140 providerId: string,
141 now: number,
142): Promise<number> {
143 if (await catalogSettled(db, providerId)) return 0
144 const rows = await db
145 .select()
146 .from(models)
147 .where(eq(models.providerId, providerId))
148 if (rows.some(hasFirstPartyProvenance)) {
149 await markModelsDevCatalogSettled(db, providerId, now)
150 return 0
151 }
152 let removed = 0
153 for (const row of rows) {
154 if (row.deprecatedAt !== null) continue
155 await db
156 .update(models)
157 .set({ deprecatedAt: now })
158 .where(eq(models.id, row.id))
159 await db.insert(changes).values({
160 id: crypto.randomUUID(),
161 type: 'model.removed',
162 providerId,
163 subjectId: row.id,
164 summary: `Model ${row.rawId} no longer listed`,
165 createdAt: now,
166 })
167 removed++
168 }
169 await markModelsDevCatalogSettled(db, providerId, now)
170 return removed
171}