Open History to see the last commit
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
20}
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
31}
32
33export interface ProviderSchemaGroup {
34 provider: string
35 count: number
36 activities: Partial<Record<Activity, Array<string>>>
37}
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 }
82}
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 }
110}
111
112interface SchemaPair {
113 input?: unknown
114 output?: unknown
115}
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 === 'stream') continue
152 if (row.kind === null || row.schema === null) {
153 map[id] = { input: null, output: null }
154 } else {
155 ;(map[id] ??= {})[row.kind] = JSON.parse(row.schema) as unknown
156 }
157 }
158 return {
159 provider: providerId,
160 activity,
161 count: Object.keys(map).length,
162 endpoints: map,
163 _links: {
164 self: halGet(`/v1/schemas/${providerId}/${activity}`),
165 schema: halGet(
166 `/v1/schemas/${providerId}/${activity}/{endpointId}{?kind,version}`,
167 ),
168 },
169 }
170}
171
172export interface SchemaProvenance {
173 /** Upstream document the schema was derived from. */
174 sourceUrl: string | null
175 /** SHA-256 of that document as fetched (see SpecSource.hash). */
176 sourceHash: string | null
177 /** When this version was derived (the row's createdAt). */
178 fetchedAt: number
179 /** Extraction-pipeline version that produced contentHash. */
180 extractorVersion: string | null
181 /**
182 * How the content was arrived at — a trust ladder, strongest first:
183 * `upstream-spec` (extracted from a spec the provider publishes and we
184 * re-fetch every sync), `generated` (derived each sync from a
185 * provider-published artifact that is not a spec, e.g. SDK sources),
186 * `probe-verified` (hand-written but confirmed against live API calls on
187 * `verifiedAt`), `docs-derived` (hand-written from prose docs and NOT
188 * confirmed). The first two self-heal; the last two are point-in-time
189 * claims that can go stale. Null on versions synced before this was
190 * recorded.
191 */
192 derivation:
193 | 'upstream-spec'
194 | 'generated'
195 | 'probe-verified'
196 | 'docs-derived'
197 | null
198 /**
199 * `YYYY-MM-DD` the claim was last confirmed against the live API. Set for
200 * `probe-verified`; null for the self-healing derivations, whose freshness
201 * is `fetchedAt`.
202 */
203 verifiedAt: string | null
204}
205
206export function schemaProvenance(
207 row: typeof schemaVersions.$inferSelect,
208): SchemaProvenance {
209 return {
210 sourceUrl: row.sourceUrl,
211 sourceHash: row.sourceHash,
212 fetchedAt: row.createdAt,
213 extractorVersion: row.extractorVersion,
214 derivation: row.derivation,
215 verifiedAt: row.verifiedAt,
216 }
217}
218
219export interface EndpointSchemaResult {
220 provider: string
221 activity: Activity
222 endpointId: string
223 kind: 'input' | 'output'
224 contentHash: string
225 specRevision: string | null
226 provenance: SchemaProvenance
227 createdAt: number
228 supersededAt: number | null
229 schema: unknown
230 /**
231 * Set when `{endpointId}` was a listed model rawId/slug aliased onto
232 * the canonical generation route. The served `endpointId` is that route.
233 */
234 aliasedFrom?: string
235}
236
237/**
238 * GET /v1/schemas/{provider}/{activity}/{endpointId}?kind=&version= —
239 * a single self-contained JSON Schema; current version unless a content
240 * hash is passed. Returns null when the endpoint/kind/version is unknown.
241 */
242export async function getEndpointSchema(
243 db: Db,
244 providerId: string,
245 activity: Activity,
246 endpointId: string,
247 kind: 'input' | 'output' = 'input',
248 version?: string,
249): Promise<EndpointSchemaResult | null> {
250 const resolved = await resolveEndpointAlias(
251 db,
252 providerId,
253 endpointId,
254 activity,
255 )
256 if (!resolved) return null
257
258 const row = await db.query.schemaVersions.findFirst({
259 where: and(
260 eq(schemaVersions.endpointId, resolved.dbId),
261 eq(schemaVersions.kind, kind),
262 version !== undefined
263 ? eq(schemaVersions.contentHash, version)
264 : isNull(schemaVersions.supersededAt),
265 ),
266 })
267 if (!row) return null
268
269 const schema = JSON.parse(row.schema) as unknown
270 const pinned =
271 resolved.pinRawId !== null && kind === 'input'
272 ? pinModelField(schema, resolved.pinRawId)
273 : schema
274
275 return {
276 provider: providerId,
277 activity,
278 endpointId: resolved.publicId,
279 kind,
280 contentHash: row.contentHash,
281 specRevision: row.specRevision,
282 provenance: schemaProvenance(row),
283 createdAt: row.createdAt,
284 supersededAt: row.supersededAt,
285 schema: pinned,
286 ...(resolved.pinRawId !== null ? { aliasedFrom: resolved.pinRawId } : {}),
287 }
288}
289
290/** Endpoint-id hints for 404 remediation (capped). */
291export async function knownEndpointIds(
292 db: Db,
293 providerId: string,
294 activity?: Activity,
295 limit = 25,
296): Promise<Array<string>> {
297 const rows = await db
298 .select({ id: endpoints.id })
299 .from(endpoints)
300 .where(
301 activity
302 ? and(
303 eq(endpoints.providerId, providerId),
304 eq(endpoints.activity, activity),
305 )
306 : eq(endpoints.providerId, providerId),
307 )
308 .orderBy(endpoints.id)
309 .limit(limit)
310 return rows.map((r) => publicEndpointId(r.id, providerId))
311}