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 SameAsInference,
20 SpecGrain,
21} from '#/server/providers/types.ts'
22import {
23 firstParty,
24 linkedFromCount,
25 loadMakerContext,
26} from '#/server/first-party.ts'
27import type { MakerContext } from '#/server/first-party.ts'
28import {
29 factDiscrepancies,
30 openRouterJoinIds,
31} from '#/server/providers/fact-sources.ts'
32import {
33 resolveAlias,
34 storedAliases,
35} from '#/server/providers/provider-aliases.ts'
36import { servePricing } from '#/server/rate-card.ts'
37import { openCodeGoFacts } from '#/server/providers/opencode-go-facts.ts'
38import { resolveSchemaEndpointId } from '#/server/schema-binding.ts'
39import { getServiceStatus } from '#/server/status.ts'
40import { sourceSilentEvidenceLedger } from './source-silent.ts'
41import { withSourceSilentEvidence } from './source-silent-facts.ts'
42
43export interface ModelFilters {
44 activity?: Activity
45 provider?: string
46 /** A flag the model's capability map states as `true`. */
47 capability?: string
48 /** Free-text match against id, raw id, and display name. */
49 q?: string
50 /** Deprecated models are excluded unless set. */
51 includeDeprecated?: boolean
52 /** Include per-field `factSources` by default; false explicitly omits them. */
53 provenance?: boolean
54 /** Include the full rate card on list rows (default: compact projection). */
55 pricing?: boolean
56}
57
58const OPENAPI_CONTENT_TYPE = 'application/openapi+json'
59
60function modelLinks(providerId: string) {
61 const openapi = openApiLink(providerId)
62 return {
63 provider: halGet(`/v1/providers/${providerId}/models`),
64 schemas: halGet(`/v1/schemas/${providerId}`),
65 ...(openapi ? { openapi } : {}),
66 }
67}
68
69function openApiLink(providerId: string) {
70 const config = getProvider(providerId)
71 if (!config?.connect) return undefined
72 const grain = resolveSpecGrain(config)
73 if (grain === 'model') {
74 return halGet(`/v1/openapi/${providerId}{?model,activity}`, {
75 contentType: OPENAPI_CONTENT_TYPE,
76 example: `/v1/openapi/${providerId}?model=fal-ai/flux/dev`,
77 })
78 }
79 return halGet(`/v1/openapi/${providerId}`, {
80 contentType: OPENAPI_CONTENT_TYPE,
81 })
82}
83
84function specDescriptor(
85 providerId: string,
86 endpointCount: number,
87): { grain: SpecGrain; endpointCount: number } {
88 return {
89 grain: resolveSpecGrain(getProvider(providerId)),
90 endpointCount,
91 }
92}
93
94type ModelRow = typeof models.$inferSelect
95
96const upstreamModel = alias(models, 'upstream_model')
97const rootModel = alias(models, 'root_model')
98const aliasTarget = alias(models, 'alias_target')
99const catalogSelection = {
100 row: models,
101 upstream: {
102 provider: upstreamModel.providerId,
103 rawId: upstreamModel.rawId,
104 aliases: upstreamModel.aliases,
105 },
106 root: { provider: rootModel.providerId, rawId: rootModel.rawId },
107 aliasOf: aliasTarget.rawId,
108 linkedFrom: linkedFromCount,
109}
110
111/**
112 * An alias row's stated target, served only while a live row at the same
113 * provider has that exact raw id (issue #709). The evidence stays on the
114 * row; a target that is gone or not yet listed reads as null.
115 */
116function aliasTargetOn(row: typeof models) {
117 return and(
118 eq(aliasTarget.providerId, row.providerId),
119 eq(aliasTarget.rawId, row.aliasOf),
120 isNull(aliasTarget.deprecatedAt),
121 )
122}
123interface UpstreamRow {
124 provider: string
125 rawId: string
126 aliases: Array<string> | null
127}
128
129type LinkMatch = 'published' | 'normalized' | 'inferred' | null
130
131// The stored link is only as fresh as the last reconcile, so it is served
132// only while the row's current evidence still names that target. The
133// evidence is its provenance: a link with no source, or a source with no
134// link, would each read as a claim nobody made.
135// A name-inferred link (issue #719) is served with the inference it was
136// written with, and only on a row that states no upstream.
137function linkMatch(
138 row: ModelRow,
139 upstream: UpstreamRow | null | undefined,
140): LinkMatch {
141 const stated = row.upstreamRawId
142 if (upstream && stated === null && row.sameAsInference) return 'inferred'
143 if (!upstream || stated === null || !row.upstreamSource) return null
144 const ids = [upstream.rawId, ...(upstream.aliases ?? [])]
145 if (ids.includes(stated)) return 'published'
146 return ids.includes(stated.replaceAll('.', '-')) ? 'normalized' : null
147}
148
149function sameAsSource(
150 row: ModelRow,
151 match: Exclude<LinkMatch, null>,
152): NonNullable<ModelFactSources['sameAs']> {
153 if (match === 'inferred') {
154 const inference = row.sameAsInference as SameAsInference
155 return { derivation: 'name-inferred', ...inference }
156 }
157 const source = row.upstreamSource as FactSource
158 return match === 'published' ? source : { ...source, normalized: true }
159}
160
161function modelFactSources(
162 row: ModelRow,
163 match: LinkMatch,
164 aliasOf: string | null,
165 firstPartySource: ModelFactSources['firstParty'],
166): ModelFactSources | null {
167 const sources = (row.factSources as ModelFactSources | null) ?? null
168 // Like sameAs: a stated target that resolves to no live row serves
169 // neither the link nor its source. A stated silence is always served.
170 let stored = sources
171 if (sources?.aliasOf && aliasOf === null) {
172 const { aliasOf: target, ...rest } = sources
173 if (target.path !== 'unstated')
174 stored = Object.keys(rest).length > 0 ? rest : null
175 }
176 const go = openCodeGoFacts(row.providerId, row.rawId).factSources
177 const withGo = Object.keys(go).length === 0 ? stored : { ...stored, ...go }
178 // A listing yes is stored on the row and wins over the probe.
179 // A probe still fills an id the listing does not name.
180 const trainingSource =
181 row.trainsOnRequestData === true && stored?.trainsOnRequestData
182 ? stored.trainsOnRequestData
183 : withGo?.trainsOnRequestData
184 const merged =
185 trainingSource && withGo
186 ? { ...withGo, trainsOnRequestData: trainingSource }
187 : withGo
188 const out = {
189 ...merged,
190 ...(match === null ? {} : { sameAs: sameAsSource(row, match) }),
191 ...(firstPartySource ? { firstParty: firstPartySource } : {}),
192 }
193 return Object.keys(out).length > 0 || merged !== null ? out : null
194}
195
196function encodeEndpointId(endpointId: string): string {
197 return endpointId.split('/').map(encodeURIComponent).join('/')
198}
199
200function toApiModel(
201 row: ModelRow,
202 opts: {
203 includeFactSources?: boolean
204 pricing?: 'compact' | 'full'
205 upstream?: UpstreamRow | null
206 /** The end of the sameAs chain when it is more than one hop away. */
207 root?: { provider: string; rawId: string } | null
208 /** The live target of `row.aliasOf`, resolved by the query. */
209 aliasOf?: string | null
210 /** Rows whose sameAs chain ends at this row. */
211 linkedFrom?: number
212 makers?: MakerContext
213 } = {},
214) {
215 const schemaEndpointId = resolveSchemaEndpointId({
216 providerId: row.providerId,
217 rawId: row.rawId,
218 activity: row.activity,
219 capabilities: row.capabilities,
220 schemaEndpointId: row.schemaEndpointId,
221 })
222 const schemaPath =
223 schemaEndpointId !== null && row.activity !== null
224 ? `/v1/schemas/${row.providerId}/${row.activity}/${encodeEndpointId(schemaEndpointId)}`
225 : null
226 const schemaLink =
227 schemaPath === null
228 ? undefined
229 : halGet(schemaPath, { example: `${schemaPath}?kind=input` })
230 const match = linkMatch(row, opts.upstream)
231 const aliasOf = opts.aliasOf ?? null
232 const go = openCodeGoFacts(row.providerId, row.rawId)
233 const sameAs =
234 match && opts.upstream
235 ? { provider: opts.upstream.provider, rawId: opts.upstream.rawId }
236 : null
237 const stored = (row.factSources as ModelFactSources | null) ?? null
238 const party = opts.makers
239 ? firstParty(
240 {
241 providerId: row.providerId,
242 maker: row.maker,
243 makerSource: stored?.maker,
244 sameAsProvider: sameAs?.provider ?? null,
245 linkedFrom: opts.linkedFrom ?? 0,
246 },
247 opts.makers,
248 )
249 : { value: null }
250 return {
251 id: row.id,
252 provider: row.providerId,
253 rawId: row.rawId,
254 sameAs,
255 sameAsRoot: sameAs && (opts.root ?? sameAs),
256 firstParty: party.value,
257 activity: row.activity,
258 displayName: row.displayName,
259 schemaEndpointId,
260 contextWindow: row.contextWindow,
261 maxOutput: row.maxOutput,
262 modalities: row.modalities,
263 pricing: servePricing(row.pricing, opts.pricing ?? 'compact'),
264 pricingRange: row.pricingRange ?? null,
265 capabilities: row.capabilities,
266 providerMetadata: row.providerMetadata,
267 reasoning: row.reasoning,
268 serverTools: row.serverTools,
269 requestMap: row.requestMap,
270 requiredRequestHeaders: go.requiredRequestHeaders,
271 trainsOnRequestData:
272 row.trainsOnRequestData === true ? true : go.trainsOnRequestData,
273 aliases: storedAliases(row.aliases),
274 aliasOf,
275 releasedAt: row.releasedAt,
276 knowledgeCutoff: row.knowledgeCutoff,
277 openWeights: row.openWeights,
278 weightsUrl: row.weightsUrl,
279 maker: row.maker,
280 firstSeenAt: row.firstSeenAt,
281 lastSeenAt: row.lastSeenAt,
282 deprecatedAt: row.deprecatedAt,
283 deprecation: row.deprecation,
284 ...(opts.includeFactSources !== false
285 ? {
286 factSources: withSourceSilentEvidence(
287 row,
288 schemaEndpointId,
289 modelFactSources(row, match, aliasOf, party.source),
290 sourceSilentEvidenceLedger,
291 ),
292 }
293 : {}),
294 _links: {
295 ...modelLinks(row.providerId),
296 ...(schemaLink ? { schema: schemaLink } : {}),
297 },
298 }
299}
300
301export type ApiModel = ReturnType<typeof toApiModel>
302
303function providerLinks(providerId: string) {
304 const openapi = openApiLink(providerId)
305 return {
306 self: halGet(`/v1/providers/${providerId}`),
307 models: halGet(`/v1/providers/${providerId}/models`),
308 schemas: halGet(`/v1/schemas/${providerId}`),
309 ...(openapi ? { openapi } : {}),
310 }
311}
312
313/** GET /v1/providers — status, counts, spec grain, and links. */
314export async function listProvidersCatalog(db: Db) {
315 const status = await getServiceStatus(db)
316 return {
317 providers: status.providers.map((p) => ({
318 ...p,
319 spec: specDescriptor(p.id, p.counts.endpoints),
320 _links: providerLinks(p.id),
321 })),
322 _links: { self: halGet('/v1/providers'), catalog: halGet('/v1/models') },
323 }
324}
325
326/**
327 * GET /v1/providers/{provider} — one provider's status row plus live model
328 * counts per activity: the `?activity=` values `GET /v1/openapi/{provider}`
329 * and `GET /v1/models` accept. Null for an unknown provider.
330 */
331export async function getProviderCatalog(db: Db, providerId: string) {
332 const status = await getServiceStatus(db)
333 const provider = status.providers.find((p) => p.id === providerId)
334 if (!provider) return null
335 const rows = await db
336 .select({ activity: models.activity, count: sql<number>`count(*)` })
337 .from(models)
338 .where(and(eq(models.providerId, providerId), isNull(models.deprecatedAt)))
339 .groupBy(models.activity)
340 const activities: Partial<Record<Activity, number>> = {}
341 for (const row of rows) {
342 if (row.activity) activities[row.activity] = row.count
343 }
344 return {
345 ...provider,
346 spec: specDescriptor(providerId, provider.counts.endpoints),
347 activities,
348 _links: providerLinks(providerId),
349 }
350}
351
352/**
353 * Catalog rows with their link targets: sameAs and its chain root are
354 * primary-key joins; the linked-from count reads the two link indexes.
355 */
356function catalogRows(db: Db) {
357 return db
358 .select(catalogSelection)
359 .from(models)
360 .leftJoin(upstreamModel, eq(models.sameAsModelId, upstreamModel.id))
361 .leftJoin(rootModel, eq(models.rootModelId, rootModel.id))
362 .leftJoin(aliasTarget, aliasTargetOn(models))
363 .$dynamic()
364}
365
366/** GET /v1/models — the cross-provider, filterable catalog. */
367export async function listModelsCatalog(db: Db, filters: ModelFilters = {}) {
368 const conditions: Array<SQL> = []
369 if (!filters.includeDeprecated) conditions.push(isNull(models.deprecatedAt))
370 if (filters.activity) conditions.push(eq(models.activity, filters.activity))
371 if (filters.provider) conditions.push(eq(models.providerId, filters.provider))
372 if (filters.capability) {
373 // The flag is a bound value, quoted as one JSON path key.
374 conditions.push(
375 sql`json_extract(${models.capabilities}, ${`$.${JSON.stringify(filters.capability)}`}) = 1`,
376 )
377 }
378 if (filters.q) {
379 const needle = `%${filters.q.toLowerCase()}%`
380 const textMatch = or(
381 like(models.id, needle),
382 like(models.rawId, needle),
383 like(sql`lower(coalesce(${models.displayName}, ''))`, needle),
384 )
385 if (textMatch) conditions.push(textMatch)
386 }
387
388 const [rows, makers] = await Promise.all([
389 catalogRows(db)
390 .where(conditions.length > 0 ? and(...conditions) : undefined)
391 .orderBy(models.id),
392 loadMakerContext(db),
393 ])
394 return {
395 count: rows.length,
396 models: rows.map(({ row, ...links }) =>
397 toApiModel(row, {
398 includeFactSources: filters.provenance !== false,
399 pricing: filters.pricing === true ? 'full' : 'compact',
400 ...links,
401 makers,
402 }),
403 ),
404 _links: {
405 self: halGet(
406 '/v1/models{?activity,provider,capability,q,provenance,pricing}',
407 {
408 example: '/v1/models?activity=chat&q=claude',
409 },
410 ),
411 providers: halGet('/v1/providers'),
412 },
413 }
414}
415
416/** GET /v1/providers/{provider}/models. Returns null for unknown providers. */
417export async function listProviderModels(
418 db: Db,
419 providerId: string,
420 provenance = true,
421) {
422 const provider = await db.query.providers.findFirst({
423 where: eq(providers.id, providerId),
424 })
425 if (!provider) return null
426 const [rows, makers] = await Promise.all([
427 catalogRows(db).where(eq(models.providerId, providerId)).orderBy(models.id),
428 loadMakerContext(db),
429 ])
430 return {
431 provider: provider.id,
432 count: rows.length,
433 models: rows.map(({ row, ...links }) =>
434 toApiModel(row, {
435 pricing: 'compact',
436 ...links,
437 makers,
438 includeFactSources: provenance,
439 }),
440 ),
441 _links: modelLinks(provider.id),
442 }
443}
444
445/**
446 * GET /v1/models/{provider}/{modelId} — accepts the model slug or the raw
447 * provider id. Returns null when not found.
448 */
449export async function getModelDetail(
450 db: Db,
451 providerId: string,
452 modelId: string,
453) {
454 const direct = await db.query.models.findFirst({
455 where: and(
456 eq(models.providerId, providerId),
457 or(eq(models.id, modelId), eq(models.rawId, modelId)),
458 ),
459 })
460 const aliasHits = direct
461 ? []
462 : await db
463 .select()
464 .from(models)
465 .where(
466 and(
467 eq(models.providerId, providerId),
468 sql`exists (select 1 from json_each(${models.aliases}) where json_each.value = ${modelId})`,
469 ),
470 )
471 const resolved = direct ?? resolveAlias(modelId, aliasHits)
472 if (!resolved) return null
473 const [[selected], makers] = await Promise.all([
474 catalogRows(db).where(eq(models.id, resolved.id)),
475 loadMakerContext(db),
476 ])
477 if (!selected) return null
478 const { row, ...links } = selected
479 const body = toApiModel(row, {
480 includeFactSources: true,
481 pricing: 'full',
482 ...links,
483 makers,
484 })
485 const joinIds = openRouterJoinIds(providerId, row.rawId)
486 if (joinIds.length === 0) return { ...body, discrepancies: [] }
487 const matches = await db
488 .select()
489 .from(models)
490 .where(
491 and(eq(models.providerId, 'openrouter'), inArray(models.rawId, joinIds)),
492 )
493 const byRaw = new Map(matches.map((match) => [match.rawId, match]))
494 const openrouter = joinIds
495 .map((id) => byRaw.get(id))
496 .find((match) => match !== undefined)
497 const discrepancies = openrouter
498 ? factDiscrepancies(
499 {
500 contextWindow: row.contextWindow,
501 maxOutput: row.maxOutput,
502 modalities: row.modalities,
503 capabilities: row.capabilities,
504 factSources: (row.factSources as ModelFactSources | null) ?? null,
505 },
506 {
507 rawId: openrouter.rawId,
508 contextWindow: openrouter.contextWindow,
509 maxOutput: openrouter.maxOutput,
510 modalities: openrouter.modalities,
511 capabilities: openrouter.capabilities,
512 },
513 )
514 : []
515 return { ...body, discrepancies }
516}
517
518/** Valid provider ids, for 404 remediation messages. */
519export async function knownProviderIds(db: Db): Promise<Array<string>> {
520 const rows = await db.select({ id: providers.id }).from(providers)
521 return rows.map((r) => r.id).sort()
522}