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

retire-models-dev.ts

181 lines5.4 KB

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​
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'
30​
31const SETTLED_PREFIX = 'models-dev-settled:'
32​
33function settledKey(providerId: string): string {
34 return `${SETTLED_PREFIX}${providerId}`
36​
37export function isModelsDevRateCard(pricing: unknown): boolean {
38 return parseStoredRateCard(pricing)?.source.url === MODELS_DEV_API_URL
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)
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 }
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)
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 }
93​
94/**
95 * Null every stored card whose source is models.dev, and drop the pricing
96 * fact that pointed at it. Docs cards use a different source URL and stay.
97 */
98export async function nullModelsDevRateCards(
99 db: Db,
100 providerId: string,
101): Promise<void> {
102 await db
103 .update(models)
104 .set({
105 pricing: null,
106 factSources: sql`CASE
107 WHEN json_remove(${models.factSources}, '$.pricing') = '{}' THEN NULL
108 ELSE json_remove(${models.factSources}, '$.pricing')
109 END`,
110 })
111 .where(
112 and(
113 eq(models.providerId, providerId),
114 sql`json_extract(${models.pricing}, '$.source.url') = ${MODELS_DEV_API_URL}`,
115 ),
116 )
118​
119async function catalogSettled(db: Db, providerId: string): Promise<boolean> {
120 const row = await db.query.cacheMeta.findFirst({
121 where: eq(cacheMeta.key, settledKey(providerId)),
122 })
123 return row !== undefined
125​
126/** Remember that this provider's catalog is no longer the models.dev snapshot. */
127export async function markModelsDevCatalogSettled(
128 db: Db,
129 providerId: string,
130 now: number,
131): Promise<void> {
132 if (await catalogSettled(db, providerId)) return
133 await db
134 .insert(cacheMeta)
135 .values({
136 key: settledKey(providerId),
137 fetchedAt: now,
138 staleTime: 0,
139 })
140 .onConflictDoNothing()
142​
143/**
144 * Deprecate active rows when this provider has never published a first-party
145 * list. Returns how many rows were deprecated. A later real list clears
146 * `deprecatedAt` for ids it returns; a later skip does not run this again.
147 */
148export async function deprecateFrozenModelsDevCatalog(
149 db: Db,
150 providerId: string,
151 now: number,
152): Promise<number> {
153 if (await catalogSettled(db, providerId)) return 0
154 const rows = await db
155 .select()
156 .from(models)
157 .where(eq(models.providerId, providerId))
158 if (rows.some(hasFirstPartyProvenance)) {
159 await markModelsDevCatalogSettled(db, providerId, now)
160 return 0
161 }
162 let removed = 0
163 for (const row of rows) {
164 if (row.deprecatedAt !== null) continue
165 await db
166 .update(models)
167 .set({ deprecatedAt: now })
168 .where(eq(models.id, row.id))
169 await db.insert(changes).values({
170 id: crypto.randomUUID(),
171 type: 'model.removed',
172 providerId,
173 subjectId: row.id,
174 summary: `Model ${row.rawId} no longer listed`,
175 createdAt: now,
176 })
177 removed++
178 }
179 await markModelsDevCatalogSettled(db, providerId, now)
180 return removed