Open History to see the last commit
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
49}
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 }
60}
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 })
75}
76
77function specDescriptor(
78 providerId: string,
79 endpointCount: number,
80): { grain: SpecGrain; endpointCount: number } {
81 return {
82 grain: resolveSpecGrain(getProvider(providerId)),
83 endpointCount,
84 }
85}
86
87type ModelRow = typeof models.$inferSelect
88
89const upstreamModel = alias(models, 'upstream_model')
90const aliasTarget = alias(models, 'alias_target')
91const catalogSelection = {
92 row: models,
93 upstream: {
94 provider: upstreamModel.providerId,
95 rawId: upstreamModel.rawId,
96 aliases: upstreamModel.aliases,
97 },
98 aliasOf: aliasTarget.rawId,
99}
100
101/**
102 * An alias row's stated target, served only while a live row at the same
103 * provider has that exact raw id (issue #709). The evidence stays on the
104 * row; a target that is gone or not yet listed reads as null.
105 */
106function aliasTargetOn(row: typeof models) {
107 return and(
108 eq(aliasTarget.providerId, row.providerId),
109 eq(aliasTarget.rawId, row.aliasOf),
110 isNull(aliasTarget.deprecatedAt),
111 )
112}
113interface UpstreamRow {
114 provider: string
115 rawId: string
116 aliases: Array<string> | null
117}
118
119// The stored link is only as fresh as the last reconcile, so it is served
120// only while the row's current evidence still names that target. The
121// evidence is its provenance: a link with no source, or a source with no
122// link, would each read as a claim nobody made.
123function linkMatch(
124 row: ModelRow,
125 upstream: UpstreamRow | null | undefined,
126): 'published' | 'normalized' | null {
127 const stated = row.upstreamRawId
128 if (!upstream || stated === null || !row.upstreamSource) return null
129 const ids = [upstream.rawId, ...(upstream.aliases ?? [])]
130 if (ids.includes(stated)) return 'published'
131 return ids.includes(stated.replaceAll('.', '-')) ? 'normalized' : null
132}
133
134function modelFactSources(
135 row: ModelRow,
136 match: ReturnType<typeof linkMatch>,
137 aliasOf: string | null,
138): ModelFactSources | null {
139 const sources = (row.factSources as ModelFactSources | null) ?? null
140 // Like sameAs: a stated target that resolves to no live row serves
141 // neither the link nor its source. A stated silence is always served.
142 let stored = sources
143 if (sources?.aliasOf && aliasOf === null) {
144 const { aliasOf: target, ...rest } = sources
145 if (target.path !== 'unstated')
146 stored = Object.keys(rest).length > 0 ? rest : null
147 }
148 const go = openCodeGoFacts(row.providerId, row.rawId).factSources
149 const withGo = Object.keys(go).length === 0 ? stored : { ...stored, ...go }
150 // A listing yes is stored on the row and wins over the probe.
151 // A probe still fills an id the listing does not name.
152 const trainingSource =
153 row.trainsOnRequestData === true && stored?.trainsOnRequestData
154 ? stored.trainsOnRequestData
155 : withGo?.trainsOnRequestData
156 const merged =
157 trainingSource && withGo
158 ? { ...withGo, trainsOnRequestData: trainingSource }
159 : withGo
160 if (match === null) return merged
161 const source = row.upstreamSource as FactSource
162 return {
163 ...merged,
164 sameAs: match === 'published' ? source : { ...source, normalized: true },
165 }
166}
167
168function encodeEndpointId(endpointId: string): string {
169 return endpointId.split('/').map(encodeURIComponent).join('/')
170}
171
172function toApiModel(
173 row: ModelRow,
174 opts: {
175 includeFactSources?: boolean
176 pricing?: 'compact' | 'full'
177 upstream?: UpstreamRow | null
178 /** The live target of `row.aliasOf`, resolved by the query. */
179 aliasOf?: string | null
180 } = {},
181) {
182 const schemaEndpointId = resolveSchemaEndpointId({
183 providerId: row.providerId,
184 rawId: row.rawId,
185 activity: row.activity,
186 capabilities: row.capabilities,
187 schemaEndpointId: row.schemaEndpointId,
188 })
189 const schemaPath =
190 schemaEndpointId !== null && row.activity !== null
191 ? `/v1/schemas/${row.providerId}/${row.activity}/${encodeEndpointId(schemaEndpointId)}`
192 : null
193 const schemaLink =
194 schemaPath === null
195 ? undefined
196 : halGet(schemaPath, { example: `${schemaPath}?kind=input` })
197 const match = linkMatch(row, opts.upstream)
198 const aliasOf = opts.aliasOf ?? null
199 const go = openCodeGoFacts(row.providerId, row.rawId)
200 return {
201 id: row.id,
202 provider: row.providerId,
203 rawId: row.rawId,
204 sameAs:
205 match && opts.upstream
206 ? { provider: opts.upstream.provider, rawId: opts.upstream.rawId }
207 : null,
208 activity: row.activity,
209 displayName: row.displayName,
210 schemaEndpointId,
211 contextWindow: row.contextWindow,
212 maxOutput: row.maxOutput,
213 modalities: row.modalities,
214 pricing: servePricing(row.pricing, opts.pricing ?? 'compact'),
215 pricingRange: row.pricingRange ?? null,
216 capabilities: row.capabilities,
217 providerMetadata: row.providerMetadata,
218 reasoning: row.reasoning,
219 serverTools: row.serverTools,
220 requestMap: row.requestMap,
221 requiredRequestHeaders: go.requiredRequestHeaders,
222 trainsOnRequestData:
223 row.trainsOnRequestData === true ? true : go.trainsOnRequestData,
224 aliases: storedAliases(row.aliases),
225 aliasOf,
226 releasedAt: row.releasedAt,
227 knowledgeCutoff: row.knowledgeCutoff,
228 openWeights: row.openWeights,
229 weightsUrl: row.weightsUrl,
230 firstSeenAt: row.firstSeenAt,
231 lastSeenAt: row.lastSeenAt,
232 deprecatedAt: row.deprecatedAt,
233 deprecation: row.deprecation,
234 ...(opts.includeFactSources !== false
235 ? {
236 factSources: withSourceSilentEvidence(
237 row,
238 schemaEndpointId,
239 modelFactSources(row, match, aliasOf),
240 sourceSilentEvidenceLedger,
241 ),
242 }
243 : {}),
244 _links: {
245 ...modelLinks(row.providerId),
246 ...(schemaLink ? { schema: schemaLink } : {}),
247 },
248 }
249}
250
251export type ApiModel = ReturnType<typeof toApiModel>
252
253function providerLinks(providerId: string) {
254 const openapi = openApiLink(providerId)
255 return {
256 self: halGet(`/v1/providers/${providerId}`),
257 models: halGet(`/v1/providers/${providerId}/models`),
258 schemas: halGet(`/v1/schemas/${providerId}`),
259 ...(openapi ? { openapi } : {}),
260 }
261}
262
263/** GET /v1/providers — status, counts, spec grain, and links. */
264export async function listProvidersCatalog(db: Db) {
265 const status = await getServiceStatus(db)
266 return {
267 providers: status.providers.map((p) => ({
268 ...p,
269 spec: specDescriptor(p.id, p.counts.endpoints),
270 _links: providerLinks(p.id),
271 })),
272 _links: { self: halGet('/v1/providers'), catalog: halGet('/v1/models') },
273 }
274}
275
276/**
277 * GET /v1/providers/{provider} — one provider's status row plus live model
278 * counts per activity: the `?activity=` values `GET /v1/openapi/{provider}`
279 * and `GET /v1/models` accept. Null for an unknown provider.
280 */
281export async function getProviderCatalog(db: Db, providerId: string) {
282 const status = await getServiceStatus(db)
283 const provider = status.providers.find((p) => p.id === providerId)
284 if (!provider) return null
285 const rows = await db
286 .select({ activity: models.activity, count: sql<number>`count(*)` })
287 .from(models)
288 .where(and(eq(models.providerId, providerId), isNull(models.deprecatedAt)))
289 .groupBy(models.activity)
290 const activities: Partial<Record<Activity, number>> = {}
291 for (const row of rows) {
292 if (row.activity) activities[row.activity] = row.count
293 }
294 return {
295 ...provider,
296 spec: specDescriptor(providerId, provider.counts.endpoints),
297 activities,
298 _links: providerLinks(providerId),
299 }
300}
301
302/** GET /v1/models — the cross-provider, filterable catalog. */
303export async function listModelsCatalog(db: Db, filters: ModelFilters = {}) {
304 const conditions: Array<SQL> = []
305 if (!filters.includeDeprecated) conditions.push(isNull(models.deprecatedAt))
306 if (filters.activity) conditions.push(eq(models.activity, filters.activity))
307 if (filters.provider) conditions.push(eq(models.providerId, filters.provider))
308 if (filters.capability) {
309 // The flag is a bound value, quoted as one JSON path key.
310 conditions.push(
311 sql`json_extract(${models.capabilities}, ${`$.${JSON.stringify(filters.capability)}`}) = 1`,
312 )
313 }
314 if (filters.q) {
315 const needle = `%${filters.q.toLowerCase()}%`
316 const textMatch = or(
317 like(models.id, needle),
318 like(models.rawId, needle),
319 like(sql`lower(coalesce(${models.displayName}, ''))`, needle),
320 )
321 if (textMatch) conditions.push(textMatch)
322 }
323
324 const rows = await db
325 .select(catalogSelection)
326 .from(models)
327 .leftJoin(upstreamModel, eq(models.sameAsModelId, upstreamModel.id))
328 .leftJoin(aliasTarget, aliasTargetOn(models))
329 .where(conditions.length > 0 ? and(...conditions) : undefined)
330 .orderBy(models.id)
331 return {
332 count: rows.length,
333 models: rows.map(({ row, upstream, aliasOf }) =>
334 toApiModel(row, {
335 includeFactSources: filters.provenance !== false,
336 pricing: filters.pricing === true ? 'full' : 'compact',
337 upstream,
338 aliasOf,
339 }),
340 ),
341 _links: {
342 self: halGet(
343 '/v1/models{?activity,provider,capability,q,provenance,pricing}',
344 {
345 example: '/v1/models?activity=chat&q=claude',
346 },
347 ),
348 providers: halGet('/v1/providers'),
349 },
350 }
351}
352
353/** GET /v1/providers/{provider}/models. Returns null for unknown providers. */
354export async function listProviderModels(
355 db: Db,
356 providerId: string,
357 provenance = true,
358) {
359 const provider = await db.query.providers.findFirst({
360 where: eq(providers.id, providerId),
361 })
362 if (!provider) return null
363 const rows = await db
364 .select(catalogSelection)
365 .from(models)
366 .leftJoin(upstreamModel, eq(models.sameAsModelId, upstreamModel.id))
367 .leftJoin(aliasTarget, aliasTargetOn(models))
368 .where(eq(models.providerId, providerId))
369 .orderBy(models.id)
370 return {
371 provider: provider.id,
372 count: rows.length,
373 models: rows.map(({ row, upstream, aliasOf }) =>
374 toApiModel(row, {
375 pricing: 'compact',
376 upstream,
377 aliasOf,
378 includeFactSources: provenance,
379 }),
380 ),
381 _links: modelLinks(provider.id),
382 }
383}
384
385/**
386 * GET /v1/models/{provider}/{modelId} — accepts the model slug or the raw
387 * provider id. Returns null when not found.
388 */
389export async function getModelDetail(
390 db: Db,
391 providerId: string,
392 modelId: string,
393) {
394 const direct = await db.query.models.findFirst({
395 where: and(
396 eq(models.providerId, providerId),
397 or(eq(models.id, modelId), eq(models.rawId, modelId)),
398 ),
399 })
400 const aliasHits = direct
401 ? []
402 : await db
403 .select()
404 .from(models)
405 .where(
406 and(
407 eq(models.providerId, providerId),
408 sql`exists (select 1 from json_each(${models.aliases}) where json_each.value = ${modelId})`,
409 ),
410 )
411 const row = direct ?? resolveAlias(modelId, aliasHits)
412 if (!row) return null
413 const [upstream] = row.sameAsModelId
414 ? await db
415 .select({
416 provider: models.providerId,
417 rawId: models.rawId,
418 aliases: models.aliases,
419 })
420 .from(models)
421 .where(eq(models.id, row.sameAsModelId))
422 : []
423 const [target] = row.aliasOf
424 ? await db
425 .select({ rawId: aliasTarget.rawId })
426 .from(models)
427 .innerJoin(aliasTarget, aliasTargetOn(models))
428 .where(eq(models.id, row.id))
429 : []
430 const body = toApiModel(row, {
431 includeFactSources: true,
432 pricing: 'full',
433 upstream,
434 aliasOf: target?.rawId ?? null,
435 })
436 const joinIds = openRouterJoinIds(providerId, row.rawId)
437 if (joinIds.length === 0) return { ...body, discrepancies: [] }
438 const matches = await db
439 .select()
440 .from(models)
441 .where(
442 and(eq(models.providerId, 'openrouter'), inArray(models.rawId, joinIds)),
443 )
444 const byRaw = new Map(matches.map((match) => [match.rawId, match]))
445 const openrouter = joinIds
446 .map((id) => byRaw.get(id))
447 .find((match) => match !== undefined)
448 const discrepancies = openrouter
449 ? factDiscrepancies(
450 {
451 contextWindow: row.contextWindow,
452 maxOutput: row.maxOutput,
453 modalities: row.modalities,
454 capabilities: row.capabilities,
455 factSources: (row.factSources as ModelFactSources | null) ?? null,
456 },
457 {
458 rawId: openrouter.rawId,
459 contextWindow: openrouter.contextWindow,
460 maxOutput: openrouter.maxOutput,
461 modalities: openrouter.modalities,
462 capabilities: openrouter.capabilities,
463 },
464 )
465 : []
466 return { ...body, discrepancies }
467}
468
469/** Valid provider ids, for 404 remediation messages. */
470export async function knownProviderIds(db: Db): Promise<Array<string>> {
471 const rows = await db.select({ id: providers.id }).from(providers)
472 return rows.map((r) => r.id).sort()
473}