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

schemas-api.ts

310 lines8.8 KB

1/**
2 * Schema read queries (PLAN.md task 4.3). Endpoint ids exposed publicly are
3 * the PR #622 path-derived ids (`v1/messages`, `chat/completions`, …) — the
4 * db id minus the `${providerId}/` prefix. Stored schema text is parsed and
5 * re-serialised verbatim (JSON.stringify preserves insertion order), so the
6 * served bytes match what the sync engine wrote to D1.
7 */
8import { and, eq, isNull } from 'drizzle-orm'
9​
10import type { Db } from '#/db/index.ts'
11import { endpoints, providers, schemaVersions } from '#/db/schema.ts'
12import type { Activity } from '#/db/schema.ts'
13import { halGet } from '#/server/hal.ts'
14import { pinModelField, resolveEndpointAlias } from '#/server/schema-binding.ts'
15​
16export function publicEndpointId(dbId: string, providerId: string): string {
17 return dbId.startsWith(`${providerId}/`)
18 ? dbId.slice(providerId.length + 1)
19 : dbId
21​
22export async function providerExists(
23 db: Db,
24 providerId: string,
25): Promise<boolean> {
26 const row = await db.query.providers.findFirst({
27 where: eq(providers.id, providerId),
28 columns: { id: true },
29 })
30 return row !== undefined
32​
33export interface ProviderSchemaGroup {
34 provider: string
35 count: number
36 activities: Partial<Record<Activity, Array<string>>>
38​
39/**
40 * GET /v1/schemas — the system-wide schema index: every provider that has
41 * extracted schemas, with its activities and endpoint ids. The one URL an
42 * agent (or the /schemas page) needs to discover every schema on the system.
43 */
44export async function getSystemSchemaIndex(db: Db) {
45 const rows = await db
46 .select({
47 id: endpoints.id,
48 providerId: endpoints.providerId,
49 activity: endpoints.activity,
50 })
51 .from(endpoints)
52 .orderBy(endpoints.id)
53​
54 const byProvider = new Map<string, ProviderSchemaGroup>()
55 for (const row of rows) {
56 let group = byProvider.get(row.providerId)
57 if (!group) {
58 group = { provider: row.providerId, count: 0, activities: {} }
59 byProvider.set(row.providerId, group)
60 }
61 group.count++
62 ;(group.activities[row.activity] ??= []).push(
63 publicEndpointId(row.id, row.providerId),
64 )
65 }
66​
67 const providerGroups = [...byProvider.values()].sort((a, b) =>
68 a.provider.localeCompare(b.provider),
69 )
70 return {
71 count: rows.length,
72 providers: providerGroups,
73 _links: {
74 self: halGet('/v1/schemas'),
75 provider: halGet('/v1/schemas/{provider}'),
76 activity: halGet('/v1/schemas/{provider}/{activity}'),
77 schema: halGet(
78 '/v1/schemas/{provider}/{activity}/{endpointId}{?kind,version}',
79 ),
80 },
81 }
83​
84/** GET /v1/schemas/{provider} — activities + endpoint ids. */
85export async function getProviderSchemaIndex(db: Db, providerId: string) {
86 const rows = await db
87 .select({ id: endpoints.id, activity: endpoints.activity })
88 .from(endpoints)
89 .where(eq(endpoints.providerId, providerId))
90 .orderBy(endpoints.id)
91​
92 const activities: Partial<Record<Activity, Array<string>>> = {}
93 for (const row of rows) {
94 ;(activities[row.activity] ??= []).push(
95 publicEndpointId(row.id, providerId),
96 )
97 }
98 return {
99 provider: providerId,
100 count: rows.length,
101 activities,
102 _links: {
103 self: halGet(`/v1/schemas/${providerId}`),
104 activity: halGet(`/v1/schemas/${providerId}/{activity}`),
105 schema: halGet(
106 `/v1/schemas/${providerId}/{activity}/{endpointId}{?kind,version}`,
107 ),
108 },
109 }
111​
112interface SchemaPair {
113 input?: unknown
114 output?: unknown
116​
117/**
118 * GET /v1/schemas/{provider}/{activity} — endpoint-id-keyed map of current
119 * input/output schemas (the PR's `endpoint-schema-map` shape).
120 */
121export async function getActivitySchemaMap(
122 db: Db,
123 providerId: string,
124 activity: Activity,
125) {
126 const rows = await db
127 .select({
128 endpointId: endpoints.id,
129 kind: schemaVersions.kind,
130 schema: schemaVersions.schema,
131 })
132 .from(endpoints)
133 .leftJoin(
134 schemaVersions,
135 and(
136 eq(schemaVersions.endpointId, endpoints.id),
137 isNull(schemaVersions.supersededAt),
138 ),
139 )
140 .where(
141 and(
142 eq(endpoints.providerId, providerId),
143 eq(endpoints.activity, activity),
144 ),
145 )
146 .orderBy(endpoints.id)
147​
148 const map: Record<string, SchemaPair> = {}
149 for (const row of rows) {
150 const id = publicEndpointId(row.endpointId, providerId)
151 if (row.kind === null || row.schema === null) {
152 map[id] = { input: null, output: null }
153 } else {
154 ;(map[id] ??= {})[row.kind] = JSON.parse(row.schema) as unknown
155 }
156 }
157 return {
158 provider: providerId,
159 activity,
160 count: Object.keys(map).length,
161 endpoints: map,
162 _links: {
163 self: halGet(`/v1/schemas/${providerId}/${activity}`),
164 schema: halGet(
165 `/v1/schemas/${providerId}/${activity}/{endpointId}{?kind,version}`,
166 ),
167 },
168 }
170​
171export interface SchemaProvenance {
172 /** Upstream document the schema was derived from. */
173 sourceUrl: string | null
174 /** SHA-256 of that document as fetched (see SpecSource.hash). */
175 sourceHash: string | null
176 /** When this version was derived (the row's createdAt). */
177 fetchedAt: number
178 /** Extraction-pipeline version that produced contentHash. */
179 extractorVersion: string | null
180 /**
181 * How the content was arrived at — a trust ladder, strongest first:
182 * `upstream-spec` (extracted from a spec the provider publishes and we
183 * re-fetch every sync), `generated` (derived each sync from a
184 * provider-published artifact that is not a spec, e.g. SDK sources),
185 * `probe-verified` (hand-written but confirmed against live API calls on
186 * `verifiedAt`), `docs-derived` (hand-written from prose docs and NOT
187 * confirmed). The first two self-heal; the last two are point-in-time
188 * claims that can go stale. Null on versions synced before this was
189 * recorded.
190 */
191 derivation:
192 | 'upstream-spec'
193 | 'generated'
194 | 'probe-verified'
195 | 'docs-derived'
196 | null
197 /**
198 * `YYYY-MM-DD` the claim was last confirmed against the live API. Set for
199 * `probe-verified`; null for the self-healing derivations, whose freshness
200 * is `fetchedAt`.
201 */
202 verifiedAt: string | null
204​
205export function schemaProvenance(
206 row: typeof schemaVersions.$inferSelect,
207): SchemaProvenance {
208 return {
209 sourceUrl: row.sourceUrl,
210 sourceHash: row.sourceHash,
211 fetchedAt: row.createdAt,
212 extractorVersion: row.extractorVersion,
213 derivation: row.derivation,
214 verifiedAt: row.verifiedAt,
215 }
217​
218export interface EndpointSchemaResult {
219 provider: string
220 activity: Activity
221 endpointId: string
222 kind: 'input' | 'output'
223 contentHash: string
224 specRevision: string | null
225 provenance: SchemaProvenance
226 createdAt: number
227 supersededAt: number | null
228 schema: unknown
229 /**
230 * Set when `{endpointId}` was a listed model rawId/slug aliased onto
231 * the canonical generation route. The served `endpointId` is that route.
232 */
233 aliasedFrom?: string
235​
236/**
237 * GET /v1/schemas/{provider}/{activity}/{endpointId}?kind=&version= —
238 * a single self-contained JSON Schema; current version unless a content
239 * hash is passed. Returns null when the endpoint/kind/version is unknown.
240 */
241export async function getEndpointSchema(
242 db: Db,
243 providerId: string,
244 activity: Activity,
245 endpointId: string,
246 kind: 'input' | 'output' = 'input',
247 version?: string,
248): Promise<EndpointSchemaResult | null> {
249 const resolved = await resolveEndpointAlias(
250 db,
251 providerId,
252 endpointId,
253 activity,
254 )
255 if (!resolved) return null
256​
257 const row = await db.query.schemaVersions.findFirst({
258 where: and(
259 eq(schemaVersions.endpointId, resolved.dbId),
260 eq(schemaVersions.kind, kind),
261 version !== undefined
262 ? eq(schemaVersions.contentHash, version)
263 : isNull(schemaVersions.supersededAt),
264 ),
265 })
266 if (!row) return null
267​
268 const schema = JSON.parse(row.schema) as unknown
269 const pinned =
270 resolved.pinRawId !== null && kind === 'input'
271 ? pinModelField(schema, resolved.pinRawId)
272 : schema
273​
274 return {
275 provider: providerId,
276 activity,
277 endpointId: resolved.publicId,
278 kind,
279 contentHash: row.contentHash,
280 specRevision: row.specRevision,
281 provenance: schemaProvenance(row),
282 createdAt: row.createdAt,
283 supersededAt: row.supersededAt,
284 schema: pinned,
285 ...(resolved.pinRawId !== null ? { aliasedFrom: resolved.pinRawId } : {}),
286 }
288​
289/** Endpoint-id hints for 404 remediation (capped). */
290export async function knownEndpointIds(
291 db: Db,
292 providerId: string,
293 activity?: Activity,
294 limit = 25,
295): Promise<Array<string>> {
296 const rows = await db
297 .select({ id: endpoints.id })
298 .from(endpoints)
299 .where(
300 activity
301 ? and(
302 eq(endpoints.providerId, providerId),
303 eq(endpoints.activity, activity),
304 )
305 : eq(endpoints.providerId, providerId),
306 )
307 .orderBy(endpoints.id)
308 .limit(limit)
309 return rows.map((r) => publicEndpointId(r.id, providerId))