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

catalog.ts

433 lines13.6 KB

1/**
2 * Catalog queries (PLAN.md task 4.2): providers, cross-provider model
3 * catalog with filters, and single-model detail. Route handlers stay thin —
4 * these functions are exercised directly by worker tests.
5 */
6import { and, eq, inArray, isNull, like, or, sql } from 'drizzle-orm'
7import type { SQL } from 'drizzle-orm'
8import { alias } from 'drizzle-orm/sqlite-core'
9​
10import type { Db } from '#/db/index.ts'
11import { models, providers } from '#/db/schema.ts'
12import type { Activity } from '#/db/schema.ts'
13import { halGet } from '#/server/hal.ts'
14import { getProvider } from '#/server/providers/index.ts'
15import { resolveSpecGrain } from '#/server/providers/connect.ts'
16import type {
17 FactSource,
18 ModelFactSources,
19 SpecGrain,
20} from '#/server/providers/types.ts'
21import {
22 factDiscrepancies,
23 openRouterJoinIds,
24} from '#/server/providers/fact-sources.ts'
25import {
26 resolveAlias,
27 storedAliases,
28} from '#/server/providers/provider-aliases.ts'
29import { servePricing } from '#/server/rate-card.ts'
30import { openCodeGoFacts } from '#/server/providers/opencode-go-facts.ts'
31import { resolveSchemaEndpointId } from '#/server/schema-binding.ts'
32import { getServiceStatus } from '#/server/status.ts'
33import { sourceSilentEvidenceLedger } from './source-silent.ts'
34import { withSourceSilentEvidence } from './source-silent-facts.ts'
35​
36export interface ModelFilters {
37 activity?: Activity
38 provider?: string
39 /** A flag the model's capability map states as `true`. */
40 capability?: string
41 /** Free-text match against id, raw id, and display name. */
42 q?: string
43 /** Deprecated models are excluded unless set. */
44 includeDeprecated?: boolean
45 /** Include per-field `factSources` by default; false explicitly omits them. */
46 provenance?: boolean
47 /** Include the full rate card on list rows (default: compact projection). */
48 pricing?: boolean
50​
51const OPENAPI_CONTENT_TYPE = 'application/openapi+json'
52​
53function modelLinks(providerId: string) {
54 const openapi = openApiLink(providerId)
55 return {
56 provider: halGet(`/v1/providers/${providerId}/models`),
57 schemas: halGet(`/v1/schemas/${providerId}`),
58 ...(openapi ? { openapi } : {}),
59 }
61​
62function openApiLink(providerId: string) {
63 const config = getProvider(providerId)
64 if (!config?.connect) return undefined
65 const grain = resolveSpecGrain(config)
66 if (grain === 'model') {
67 return halGet(`/v1/openapi/${providerId}{?model,activity}`, {
68 contentType: OPENAPI_CONTENT_TYPE,
69 example: `/v1/openapi/${providerId}?model=fal-ai/flux/dev`,
70 })
71 }
72 return halGet(`/v1/openapi/${providerId}`, {
73 contentType: OPENAPI_CONTENT_TYPE,
74 })
76​
77function specDescriptor(
78 providerId: string,
79 endpointCount: number,
80): { grain: SpecGrain; endpointCount: number } {
81 return {
82 grain: resolveSpecGrain(getProvider(providerId)),
83 endpointCount,
84 }
86​
87type ModelRow = typeof models.$inferSelect
88​
89const upstreamModel = alias(models, 'upstream_model')
90const catalogSelection = {
91 row: models,
92 upstream: {
93 provider: upstreamModel.providerId,
94 rawId: upstreamModel.rawId,
95 aliases: upstreamModel.aliases,
96 },
98interface UpstreamRow {
99 provider: string
100 rawId: string
101 aliases: Array<string> | null
103​
104// The stored link is only as fresh as the last reconcile, so it is served
105// only while the row's current evidence still names that target. The
106// evidence is its provenance: a link with no source, or a source with no
107// link, would each read as a claim nobody made.
108function linkMatch(
109 row: ModelRow,
110 upstream: UpstreamRow | null | undefined,
111): 'published' | 'normalized' | null {
112 const stated = row.upstreamRawId
113 if (!upstream || stated === null || !row.upstreamSource) return null
114 const ids = [upstream.rawId, ...(upstream.aliases ?? [])]
115 if (ids.includes(stated)) return 'published'
116 return ids.includes(stated.replaceAll('.', '-')) ? 'normalized' : null
118​
119function modelFactSources(
120 row: ModelRow,
121 match: ReturnType<typeof linkMatch>,
122): ModelFactSources | null {
123 const stored = (row.factSources as ModelFactSources | null) ?? null
124 const go = openCodeGoFacts(row.providerId, row.rawId).factSources
125 const withGo = Object.keys(go).length === 0 ? stored : { ...stored, ...go }
126 // A privacy-table yes is stored on the row and wins over the probe.
127 // A probe still fills an id the table does not name.
128 const trainingSource =
129 row.trainsOnRequestData === true && stored?.trainsOnRequestData
130 ? stored.trainsOnRequestData
131 : withGo?.trainsOnRequestData
132 const merged =
133 trainingSource && withGo
134 ? { ...withGo, trainsOnRequestData: trainingSource }
135 : withGo
136 if (match === null) return merged
137 const source = row.upstreamSource as FactSource
138 return {
139 ...merged,
140 sameAs: match === 'published' ? source : { ...source, normalized: true },
141 }
143​
144function encodeEndpointId(endpointId: string): string {
145 return endpointId.split('/').map(encodeURIComponent).join('/')
147​
148function toApiModel(
149 row: ModelRow,
150 opts: {
151 includeFactSources?: boolean
152 pricing?: 'compact' | 'full'
153 upstream?: UpstreamRow | null
154 } = {},
155) {
156 const schemaEndpointId = resolveSchemaEndpointId({
157 providerId: row.providerId,
158 rawId: row.rawId,
159 activity: row.activity,
160 capabilities: row.capabilities,
161 schemaEndpointId: row.schemaEndpointId,
162 })
163 const schemaPath =
164 schemaEndpointId !== null && row.activity !== null
165 ? `/v1/schemas/${row.providerId}/${row.activity}/${encodeEndpointId(schemaEndpointId)}`
166 : null
167 const schemaLink =
168 schemaPath === null
169 ? undefined
170 : halGet(schemaPath, { example: `${schemaPath}?kind=input` })
171 const match = linkMatch(row, opts.upstream)
172 const go = openCodeGoFacts(row.providerId, row.rawId)
173 return {
174 id: row.id,
175 provider: row.providerId,
176 rawId: row.rawId,
177 sameAs:
178 match && opts.upstream
179 ? { provider: opts.upstream.provider, rawId: opts.upstream.rawId }
180 : null,
181 activity: row.activity,
182 displayName: row.displayName,
183 schemaEndpointId,
184 contextWindow: row.contextWindow,
185 maxOutput: row.maxOutput,
186 modalities: row.modalities,
187 pricing: servePricing(row.pricing, opts.pricing ?? 'compact'),
188 pricingRange: row.pricingRange ?? null,
189 capabilities: row.capabilities,
190 providerMetadata: row.providerMetadata,
191 reasoning: row.reasoning,
192 serverTools: row.serverTools,
193 requestMap: row.requestMap,
194 requiredRequestHeaders: go.requiredRequestHeaders,
195 trainsOnRequestData:
196 row.trainsOnRequestData === true ? true : go.trainsOnRequestData,
197 aliases: storedAliases(row.aliases),
198 releasedAt: row.releasedAt,
199 knowledgeCutoff: row.knowledgeCutoff,
200 openWeights: row.openWeights,
201 weightsUrl: row.weightsUrl,
202 firstSeenAt: row.firstSeenAt,
203 lastSeenAt: row.lastSeenAt,
204 deprecatedAt: row.deprecatedAt,
205 deprecation: row.deprecation,
206 ...(opts.includeFactSources !== false
207 ? {
208 factSources: withSourceSilentEvidence(
209 row,
210 schemaEndpointId,
211 modelFactSources(row, match),
212 sourceSilentEvidenceLedger,
213 ),
214 }
215 : {}),
216 _links: {
217 ...modelLinks(row.providerId),
218 ...(schemaLink ? { schema: schemaLink } : {}),
219 },
220 }
222​
223export type ApiModel = ReturnType<typeof toApiModel>
224​
225function providerLinks(providerId: string) {
226 const openapi = openApiLink(providerId)
227 return {
228 self: halGet(`/v1/providers/${providerId}`),
229 models: halGet(`/v1/providers/${providerId}/models`),
230 schemas: halGet(`/v1/schemas/${providerId}`),
231 ...(openapi ? { openapi } : {}),
232 }
234​
235/** GET /v1/providers — status, counts, spec grain, and links. */
236export async function listProvidersCatalog(db: Db) {
237 const status = await getServiceStatus(db)
238 return {
239 providers: status.providers.map((p) => ({
240 ...p,
241 spec: specDescriptor(p.id, p.counts.endpoints),
242 _links: providerLinks(p.id),
243 })),
244 _links: { self: halGet('/v1/providers'), catalog: halGet('/v1/models') },
245 }
247​
248/**
249 * GET /v1/providers/{provider} — one provider's status row plus live model
250 * counts per activity: the `?activity=` values `GET /v1/openapi/{provider}`
251 * and `GET /v1/models` accept. Null for an unknown provider.
252 */
253export async function getProviderCatalog(db: Db, providerId: string) {
254 const status = await getServiceStatus(db)
255 const provider = status.providers.find((p) => p.id === providerId)
256 if (!provider) return null
257 const rows = await db
258 .select({ activity: models.activity, count: sql<number>`count(*)` })
259 .from(models)
260 .where(and(eq(models.providerId, providerId), isNull(models.deprecatedAt)))
261 .groupBy(models.activity)
262 const activities: Partial<Record<Activity, number>> = {}
263 for (const row of rows) {
264 if (row.activity) activities[row.activity] = row.count
265 }
266 return {
267 ...provider,
268 spec: specDescriptor(providerId, provider.counts.endpoints),
269 activities,
270 _links: providerLinks(providerId),
271 }
273​
274/** GET /v1/models — the cross-provider, filterable catalog. */
275export async function listModelsCatalog(db: Db, filters: ModelFilters = {}) {
276 const conditions: Array<SQL> = []
277 if (!filters.includeDeprecated) conditions.push(isNull(models.deprecatedAt))
278 if (filters.activity) conditions.push(eq(models.activity, filters.activity))
279 if (filters.provider) conditions.push(eq(models.providerId, filters.provider))
280 if (filters.capability) {
281 // The flag is a bound value, quoted as one JSON path key.
282 conditions.push(
283 sql`json_extract(${models.capabilities}, ${`$.${JSON.stringify(filters.capability)}`}) = 1`,
284 )
285 }
286 if (filters.q) {
287 const needle = `%${filters.q.toLowerCase()}%`
288 const textMatch = or(
289 like(models.id, needle),
290 like(models.rawId, needle),
291 like(sql`lower(coalesce(${models.displayName}, ''))`, needle),
292 )
293 if (textMatch) conditions.push(textMatch)
294 }
295​
296 const rows = await db
297 .select(catalogSelection)
298 .from(models)
299 .leftJoin(upstreamModel, eq(models.sameAsModelId, upstreamModel.id))
300 .where(conditions.length > 0 ? and(...conditions) : undefined)
301 .orderBy(models.id)
302 return {
303 count: rows.length,
304 models: rows.map(({ row, upstream }) =>
305 toApiModel(row, {
306 includeFactSources: filters.provenance !== false,
307 pricing: filters.pricing === true ? 'full' : 'compact',
308 upstream,
309 }),
310 ),
311 _links: {
312 self: halGet(
313 '/v1/models{?activity,provider,capability,q,provenance,pricing}',
314 {
315 example: '/v1/models?activity=chat&q=claude',
316 },
317 ),
318 providers: halGet('/v1/providers'),
319 },
320 }
322​
323/** GET /v1/providers/{provider}/models. Returns null for unknown providers. */
324export async function listProviderModels(
325 db: Db,
326 providerId: string,
327 provenance = true,
328) {
329 const provider = await db.query.providers.findFirst({
330 where: eq(providers.id, providerId),
331 })
332 if (!provider) return null
333 const rows = await db
334 .select(catalogSelection)
335 .from(models)
336 .leftJoin(upstreamModel, eq(models.sameAsModelId, upstreamModel.id))
337 .where(eq(models.providerId, providerId))
338 .orderBy(models.id)
339 return {
340 provider: provider.id,
341 count: rows.length,
342 models: rows.map(({ row, upstream }) =>
343 toApiModel(row, {
344 pricing: 'compact',
345 upstream,
346 includeFactSources: provenance,
347 }),
348 ),
349 _links: modelLinks(provider.id),
350 }
352​
353/**
354 * GET /v1/models/{provider}/{modelId} — accepts the model slug or the raw
355 * provider id. Returns null when not found.
356 */
357export async function getModelDetail(
358 db: Db,
359 providerId: string,
360 modelId: string,
361) {
362 const direct = await db.query.models.findFirst({
363 where: and(
364 eq(models.providerId, providerId),
365 or(eq(models.id, modelId), eq(models.rawId, modelId)),
366 ),
367 })
368 const aliasHits = direct
369 ? []
370 : await db
371 .select()
372 .from(models)
373 .where(
374 and(
375 eq(models.providerId, providerId),
376 sql`exists (select 1 from json_each(${models.aliases}) where json_each.value = ${modelId})`,
377 ),
378 )
379 const row = direct ?? resolveAlias(modelId, aliasHits)
380 if (!row) return null
381 const [upstream] = row.sameAsModelId
382 ? await db
383 .select({
384 provider: models.providerId,
385 rawId: models.rawId,
386 aliases: models.aliases,
387 })
388 .from(models)
389 .where(eq(models.id, row.sameAsModelId))
390 : []
391 const body = toApiModel(row, {
392 includeFactSources: true,
393 pricing: 'full',
394 upstream,
395 })
396 const joinIds = openRouterJoinIds(providerId, row.rawId)
397 if (joinIds.length === 0) return { ...body, discrepancies: [] }
398 const matches = await db
399 .select()
400 .from(models)
401 .where(
402 and(eq(models.providerId, 'openrouter'), inArray(models.rawId, joinIds)),
403 )
404 const byRaw = new Map(matches.map((match) => [match.rawId, match]))
405 const openrouter = joinIds
406 .map((id) => byRaw.get(id))
407 .find((match) => match !== undefined)
408 const discrepancies = openrouter
409 ? factDiscrepancies(
410 {
411 contextWindow: row.contextWindow,
412 maxOutput: row.maxOutput,
413 modalities: row.modalities,
414 capabilities: row.capabilities,
415 factSources: (row.factSources as ModelFactSources | null) ?? null,
416 },
417 {
418 rawId: openrouter.rawId,
419 contextWindow: openrouter.contextWindow,
420 maxOutput: openrouter.maxOutput,
421 modalities: openrouter.modalities,
422 capabilities: openrouter.capabilities,
423 },
424 )
425 : []
426 return { ...body, discrepancies }
428​
429/** Valid provider ids, for 404 remediation messages. */
430export async function knownProviderIds(db: Db): Promise<Array<string>> {
431 const rows = await db.select({ id: providers.id }).from(providers)
432 return rows.map((r) => r.id).sort()