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, asc, eq, gt, 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
22/**
23 * OpenCode publishes its own catalog at models.dev. Issue #197 drops that
24 * URL for every other provider; for OpenCode it still supplies routes and
25 * schema versions. Prices are not exempt: Zen reads its console page (#314).
26 */
27export function modelsDevIsFirstParty(providerId: string): boolean {
28 return providerId === 'opencode' || providerId === 'opencode-go'
29}
30
31const SETTLED_PREFIX = 'models-dev-settled:'
32
33function settledKey(providerId: string): string {
34 return `${SETTLED_PREFIX}${providerId}`
35}
36
37export function isModelsDevRateCard(pricing: unknown): boolean {
38 return parseStoredRateCard(pricing)?.source.url === MODELS_DEV_API_URL
39}
40
41/** A models.dev card is not a price to keep across a null incoming list. */
42export function storedCardIsPrior(pricing: unknown): boolean {
43 return parseStoredRateCard(pricing) !== null && !isModelsDevRateCard(pricing)
44}
45
46function collectSourceUrls(value: unknown, urls: Array<string>): void {
47 if (Array.isArray(value)) {
48 for (const item of value) collectSourceUrls(item, urls)
49 return
50 }
51 if (typeof value !== 'object' || value === null) return
52 for (const [key, child] of Object.entries(value)) {
53 if (key === 'sourceUrl' && typeof child === 'string' && child.length > 0) {
54 urls.push(child)
55 } else {
56 collectSourceUrls(child, urls)
57 }
58 }
59}
60
61function hasFirstPartyProvenance(row: {
62 pricing: unknown
63 factSources: unknown
64}): boolean {
65 const urls: Array<string> = []
66 const card = parseStoredRateCard(row.pricing)
67 if (card?.source.url) urls.push(card.source.url)
68 collectSourceUrls(row.factSources, urls)
69 return urls.some((url) => url !== MODELS_DEV_API_URL)
70}
71
72/** Delete schema versions derived from the models.dev document. */
73export async function dropModelsDevSchemaVersions(
74 db: Db,
75 providerId: string,
76): Promise<void> {
77 if (modelsDevIsFirstParty(providerId)) return
78 const rows = await db
79 .select({ id: schemaVersions.id })
80 .from(schemaVersions)
81 .innerJoin(endpoints, eq(schemaVersions.endpointId, endpoints.id))
82 .where(
83 and(
84 eq(endpoints.providerId, providerId),
85 eq(schemaVersions.sourceUrl, MODELS_DEV_API_URL),
86 ),
87 )
88 for (let i = 0; i < rows.length; i += 90) {
89 const ids = rows.slice(i, i + 90).map((row) => row.id)
90 await db.delete(schemaVersions).where(inArray(schemaVersions.id, ids))
91 }
92}
93
94/**
95 * Rows per models.dev card clear. One `UPDATE … SET pricing, fact_sources =
96 * CASE` over a provider's whole catalog (OpenRouter) spends D1's 10-second
97 * resource window by itself (issue #625). Twenty stays under the
98 * 100-parameter cap and rewrites one page of rows per statement.
99 */
100export const MODELS_DEV_CARD_CHUNK = 20
101
102/**
103 * Null every stored card whose source is models.dev, and drop the pricing
104 * fact that pointed at it. Docs cards use a different source URL and stay.
105 * Matching ids are read in keyset pages and cleared by primary key, so a
106 * provider with many cards never rewrites them in one statement.
107 */
108export async function nullModelsDevRateCards(
109 db: Db,
110 providerId: string,
111): Promise<void> {
112 let after: string | undefined
113 for (;;) {
114 const rows = await db
115 .select({ id: models.id })
116 .from(models)
117 .where(
118 and(
119 eq(models.providerId, providerId),
120 sql`json_extract(${models.pricing}, '$.source.url') = ${MODELS_DEV_API_URL}`,
121 after === undefined ? undefined : gt(models.id, after),
122 ),
123 )
124 .orderBy(asc(models.id))
125 .limit(MODELS_DEV_CARD_CHUNK)
126 const last = rows.at(-1)
127 if (!last) return
128 await db
129 .update(models)
130 .set({
131 pricing: null,
132 factSources: sql`CASE
133 WHEN json_remove(${models.factSources}, '$.pricing') = '{}' THEN NULL
134 ELSE json_remove(${models.factSources}, '$.pricing')
135 END`,
136 })
137 .where(
138 inArray(
139 models.id,
140 rows.map((row) => row.id),
141 ),
142 )
143 if (rows.length < MODELS_DEV_CARD_CHUNK) return
144 after = last.id
145 }
146}
147
148async function catalogSettled(db: Db, providerId: string): Promise<boolean> {
149 const row = await db.query.cacheMeta.findFirst({
150 where: eq(cacheMeta.key, settledKey(providerId)),
151 })
152 return row !== undefined
153}
154
155/** Remember that this provider's catalog is no longer the models.dev snapshot. */
156export async function markModelsDevCatalogSettled(
157 db: Db,
158 providerId: string,
159 now: number,
160): Promise<void> {
161 if (await catalogSettled(db, providerId)) return
162 await db
163 .insert(cacheMeta)
164 .values({
165 key: settledKey(providerId),
166 fetchedAt: now,
167 staleTime: 0,
168 })
169 .onConflictDoNothing()
170}
171
172/**
173 * Deprecate active rows when this provider has never published a first-party
174 * list. Returns how many rows were deprecated. A later real list clears
175 * `deprecatedAt` for ids it returns; a later skip does not run this again.
176 */
177export async function deprecateFrozenModelsDevCatalog(
178 db: Db,
179 providerId: string,
180 now: number,
181): Promise<number> {
182 if (await catalogSettled(db, providerId)) return 0
183 const rows = await db
184 .select()
185 .from(models)
186 .where(eq(models.providerId, providerId))
187 if (rows.some(hasFirstPartyProvenance)) {
188 await markModelsDevCatalogSettled(db, providerId, now)
189 return 0
190 }
191 let removed = 0
192 for (const row of rows) {
193 if (row.deprecatedAt !== null) continue
194 await db
195 .update(models)
196 .set({ deprecatedAt: now })
197 .where(eq(models.id, row.id))
198 await db.insert(changes).values({
199 id: crypto.randomUUID(),
200 type: 'model.removed',
201 providerId,
202 subjectId: row.id,
203 summary: `Model ${row.rawId} no longer listed`,
204 createdAt: now,
205 })
206 removed++
207 }
208 await markModelsDevCatalogSettled(db, providerId, now)
209 return removed
210}