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

schema.ts

739 lines25.9 KB

1import { relations, sql } from 'drizzle-orm'
2import {
3 sqliteTable,
4 text,
5 integer,
6 index,
7 check,
8 primaryKey,
9} from 'drizzle-orm/sqlite-core'
10import type { AnySQLiteColumn } from 'drizzle-orm/sqlite-core'
11​
12import type { CapabilityMap } from '#/lib/capabilities.ts'
13import type { PricingRange } from '#/server/rate-card.ts'
14import type {
15 ModelDeprecation,
16 SameAsInference,
17} from '#/server/providers/types.ts'
18​
19export const user = sqliteTable('user', {
20 id: text('id').primaryKey(),
21 name: text('name').notNull(),
22 email: text('email').notNull().unique(),
23 emailVerified: integer('email_verified', { mode: 'boolean' })
24 .default(false)
25 .notNull(),
26 image: text('image'),
27 createdAt: integer('created_at', { mode: 'timestamp_ms' }).notNull(),
28 updatedAt: integer('updated_at', { mode: 'timestamp_ms' })
29 .$onUpdate(() => new Date())
30 .notNull(),
31})
32​
33export const session = sqliteTable(
34 'session',
35 {
36 id: text('id').primaryKey(),
37 expiresAt: integer('expires_at', { mode: 'timestamp_ms' }).notNull(),
38 token: text('token').notNull().unique(),
39 createdAt: integer('created_at', { mode: 'timestamp_ms' }).notNull(),
40 updatedAt: integer('updated_at', { mode: 'timestamp_ms' })
41 .$onUpdate(() => new Date())
42 .notNull(),
43 ipAddress: text('ip_address'),
44 userAgent: text('user_agent'),
45 userId: text('user_id')
46 .notNull()
47 .references(() => user.id, { onDelete: 'cascade' }),
48 },
49 (table) => [index('session_userId_idx').on(table.userId)],
51​
52export const account = sqliteTable(
53 'account',
54 {
55 id: text('id').primaryKey(),
56 accountId: text('account_id').notNull(),
57 providerId: text('provider_id').notNull(),
58 userId: text('user_id')
59 .notNull()
60 .references(() => user.id, { onDelete: 'cascade' }),
61 accessToken: text('access_token'),
62 refreshToken: text('refresh_token'),
63 idToken: text('id_token'),
64 accessTokenExpiresAt: integer('access_token_expires_at', {
65 mode: 'timestamp_ms',
66 }),
67 refreshTokenExpiresAt: integer('refresh_token_expires_at', {
68 mode: 'timestamp_ms',
69 }),
70 scope: text('scope'),
71 password: text('password'),
72 createdAt: integer('created_at', { mode: 'timestamp_ms' }).notNull(),
73 updatedAt: integer('updated_at', { mode: 'timestamp_ms' })
74 .$onUpdate(() => new Date())
75 .notNull(),
76 },
77 (table) => [index('account_userId_idx').on(table.userId)],
79​
80export const verification = sqliteTable(
81 'verification',
82 {
83 id: text('id').primaryKey(),
84 identifier: text('identifier').notNull(),
85 value: text('value').notNull(),
86 expiresAt: integer('expires_at', { mode: 'timestamp_ms' }).notNull(),
87 createdAt: integer('created_at', { mode: 'timestamp_ms' }).notNull(),
88 updatedAt: integer('updated_at', { mode: 'timestamp_ms' })
89 .$onUpdate(() => new Date())
90 .notNull(),
91 },
92 (table) => [index('verification_identifier_idx').on(table.identifier)],
94​
95export const agentHost = sqliteTable(
96 'agent_host',
97 {
98 id: text('id').primaryKey(),
99 name: text('name'),
100 userId: text('user_id').references(() => user.id, { onDelete: 'cascade' }),
101 defaultCapabilities: text('default_capabilities'),
102 publicKey: text('public_key'),
103 kid: text('kid'),
104 jwksUrl: text('jwks_url'),
105 enrollmentTokenHash: text('enrollment_token_hash'),
106 enrollmentTokenExpiresAt: integer('enrollment_token_expires_at', {
107 mode: 'timestamp_ms',
108 }),
109 status: text('status').default('active').notNull(),
110 activatedAt: integer('activated_at', { mode: 'timestamp_ms' }),
111 expiresAt: integer('expires_at', { mode: 'timestamp_ms' }),
112 lastUsedAt: integer('last_used_at', { mode: 'timestamp_ms' }),
113 createdAt: integer('created_at', { mode: 'timestamp_ms' }).notNull(),
114 updatedAt: integer('updated_at', { mode: 'timestamp_ms' }).notNull(),
115 },
116 (table) => [
117 index('agentHost_userId_idx').on(table.userId),
118 index('agentHost_kid_idx').on(table.kid),
119 index('agentHost_enrollmentTokenHash_idx').on(table.enrollmentTokenHash),
120 index('agentHost_status_idx').on(table.status),
121 ],
123​
124export const agent = sqliteTable(
125 'agent',
126 {
127 id: text('id').primaryKey(),
128 name: text('name').notNull(),
129 userId: text('user_id').references(() => user.id, { onDelete: 'cascade' }),
130 hostId: text('host_id')
131 .notNull()
132 .references(() => agentHost.id, { onDelete: 'cascade' }),
133 status: text('status').default('active').notNull(),
134 mode: text('mode').default('delegated').notNull(),
135 publicKey: text('public_key').notNull(),
136 kid: text('kid'),
137 jwksUrl: text('jwks_url'),
138 lastUsedAt: integer('last_used_at', { mode: 'timestamp_ms' }),
139 activatedAt: integer('activated_at', { mode: 'timestamp_ms' }),
140 expiresAt: integer('expires_at', { mode: 'timestamp_ms' }),
141 metadata: text('metadata'),
142 createdAt: integer('created_at', { mode: 'timestamp_ms' }).notNull(),
143 updatedAt: integer('updated_at', { mode: 'timestamp_ms' }).notNull(),
144 },
145 (table) => [
146 index('agent_userId_idx').on(table.userId),
147 index('agent_hostId_idx').on(table.hostId),
148 index('agent_status_idx').on(table.status),
149 index('agent_kid_idx').on(table.kid),
150 ],
152​
153export const agentCapabilityGrant = sqliteTable(
154 'agent_capability_grant',
155 {
156 id: text('id').primaryKey(),
157 agentId: text('agent_id')
158 .notNull()
159 .references(() => agent.id, { onDelete: 'cascade' }),
160 capability: text('capability').notNull(),
161 deniedBy: text('denied_by').references(() => user.id, {
162 onDelete: 'cascade',
163 }),
164 grantedBy: text('granted_by').references(() => user.id, {
165 onDelete: 'cascade',
166 }),
167 expiresAt: integer('expires_at', { mode: 'timestamp_ms' }),
168 createdAt: integer('created_at', { mode: 'timestamp_ms' }).notNull(),
169 updatedAt: integer('updated_at', { mode: 'timestamp_ms' }).notNull(),
170 status: text('status').default('active').notNull(),
171 reason: text('reason'),
172 constraints: text('constraints'),
173 },
174 (table) => [
175 index('agentCapabilityGrant_agentId_idx').on(table.agentId),
176 index('agentCapabilityGrant_capability_idx').on(table.capability),
177 index('agentCapabilityGrant_grantedBy_idx').on(table.grantedBy),
178 index('agentCapabilityGrant_status_idx').on(table.status),
179 ],
181​
182export const approvalRequest = sqliteTable(
183 'approval_request',
184 {
185 id: text('id').primaryKey(),
186 method: text('method').notNull(),
187 agentId: text('agent_id').references(() => agent.id, {
188 onDelete: 'cascade',
189 }),
190 hostId: text('host_id').references(() => agentHost.id, {
191 onDelete: 'cascade',
192 }),
193 userId: text('user_id').references(() => user.id, { onDelete: 'cascade' }),
194 capabilities: text('capabilities'),
195 status: text('status').default('pending').notNull(),
196 userCodeHash: text('user_code_hash'),
197 loginHint: text('login_hint'),
198 bindingMessage: text('binding_message'),
199 clientNotificationToken: text('client_notification_token'),
200 clientNotificationEndpoint: text('client_notification_endpoint'),
201 deliveryMode: text('delivery_mode'),
202 interval: integer('interval').notNull(),
203 lastPolledAt: integer('last_polled_at', { mode: 'timestamp_ms' }),
204 expiresAt: integer('expires_at', { mode: 'timestamp_ms' }).notNull(),
205 createdAt: integer('created_at', { mode: 'timestamp_ms' }).notNull(),
206 updatedAt: integer('updated_at', { mode: 'timestamp_ms' }).notNull(),
207 },
208 (table) => [
209 index('approvalRequest_agentId_idx').on(table.agentId),
210 index('approvalRequest_hostId_idx').on(table.hostId),
211 index('approvalRequest_userId_idx').on(table.userId),
212 index('approvalRequest_status_idx').on(table.status),
213 ],
215​
216export const apikey = sqliteTable(
217 'apikey',
218 {
219 id: text('id').primaryKey(),
220 configId: text('config_id').default('default').notNull(),
221 name: text('name'),
222 start: text('start'),
223 referenceId: text('reference_id').notNull(),
224 prefix: text('prefix'),
225 key: text('key').notNull(),
226 refillInterval: integer('refill_interval'),
227 refillAmount: integer('refill_amount'),
228 lastRefillAt: integer('last_refill_at', { mode: 'timestamp_ms' }),
229 enabled: integer('enabled', { mode: 'boolean' }).default(true),
230 rateLimitEnabled: integer('rate_limit_enabled', {
231 mode: 'boolean',
232 }).default(true),
233 rateLimitTimeWindow: integer('rate_limit_time_window').default(86400000),
234 rateLimitMax: integer('rate_limit_max').default(10),
235 requestCount: integer('request_count').default(0),
236 remaining: integer('remaining'),
237 lastRequest: integer('last_request', { mode: 'timestamp_ms' }),
238 expiresAt: integer('expires_at', { mode: 'timestamp_ms' }),
239 createdAt: integer('created_at', { mode: 'timestamp_ms' }).notNull(),
240 updatedAt: integer('updated_at', { mode: 'timestamp_ms' }).notNull(),
241 permissions: text('permissions'),
242 metadata: text('metadata'),
243 },
244 (table) => [
245 index('apikey_configId_idx').on(table.configId),
246 index('apikey_referenceId_idx').on(table.referenceId),
247 index('apikey_key_idx').on(table.key),
248 ],
250​
251export const userRelations = relations(user, ({ many }) => ({
252 sessions: many(session),
253 accounts: many(account),
254 agentHosts: many(agentHost),
255 agents: many(agent),
256 agentCapabilityGrants: many(agentCapabilityGrant),
257 approvalRequests: many(approvalRequest),
258}))
259​
260export const sessionRelations = relations(session, ({ one }) => ({
261 user: one(user, {
262 fields: [session.userId],
263 references: [user.id],
264 }),
265}))
266​
267export const accountRelations = relations(account, ({ one }) => ({
268 user: one(user, {
269 fields: [account.userId],
270 references: [user.id],
271 }),
272}))
273​
274export const agentHostRelations = relations(agentHost, ({ one, many }) => ({
275 user: one(user, {
276 fields: [agentHost.userId],
277 references: [user.id],
278 }),
279 agents: many(agent),
280 approvalRequests: many(approvalRequest),
281}))
282​
283export const agentRelations = relations(agent, ({ one, many }) => ({
284 user: one(user, {
285 fields: [agent.userId],
286 references: [user.id],
287 }),
288 agentHost: one(agentHost, {
289 fields: [agent.hostId],
290 references: [agentHost.id],
291 }),
292 agentCapabilityGrants: many(agentCapabilityGrant),
293 approvalRequests: many(approvalRequest),
294}))
295​
296export const agentCapabilityGrantDeniedByRelations = relations(
297 agentCapabilityGrant,
298 ({ one }) => ({
299 user: one(user, {
300 fields: [agentCapabilityGrant.deniedBy],
301 references: [user.id],
302 }),
303 }),
305​
306export const agentCapabilityGrantGrantedByRelations = relations(
307 agentCapabilityGrant,
308 ({ one }) => ({
309 user: one(user, {
310 fields: [agentCapabilityGrant.grantedBy],
311 references: [user.id],
312 }),
313 }),
315​
316export const agentCapabilityGrantRelations = relations(
317 agentCapabilityGrant,
318 ({ one }) => ({
319 agent: one(agent, {
320 fields: [agentCapabilityGrant.agentId],
321 references: [agent.id],
322 }),
323 }),
325​
326export const approvalRequestRelations = relations(
327 approvalRequest,
328 ({ one }) => ({
329 agent: one(agent, {
330 fields: [approvalRequest.agentId],
331 references: [agent.id],
332 }),
333 agentHost: one(agentHost, {
334 fields: [approvalRequest.hostId],
335 references: [agentHost.id],
336 }),
337 user: one(user, {
338 fields: [approvalRequest.userId],
339 references: [user.id],
340 }),
341 }),
343​
344// ---------------------------------------------------------------------------
345// Core domain tables (PLAN.md task 1.1).
346// Conventions: ids are lowercase kebab/slug text; times are unix epoch seconds
347// (plain integers — the timestamp_ms columns above are better-auth-generated).
348// ---------------------------------------------------------------------------
349​
350export const activities = [
351 'chat',
352 'image',
353 'video',
354 'audio',
355 'embeddings',
356 'moderation',
357 'world',
358 'decision',
359 'search',
360] as const
361export type Activity = (typeof activities)[number]
362​
363export const changeTypes = [
364 'model.added',
365 'model.removed',
366 'model.updated',
367 'catalog.shape_changed',
368 'model.deprecated',
369 'schema.added',
370 'schema.updated',
371 'endpoint.added',
372 'endpoint.removed',
373] as const
374export type ChangeType = (typeof changeTypes)[number]
375​
376export const providers = sqliteTable('providers', {
377 id: text('id').primaryKey(),
378 displayName: text('display_name').notNull(),
379 specSourceUrl: text('spec_source_url').notNull(),
380 modelsEndpoint: text('models_endpoint'),
381 authEnvVar: text('auth_env_var'),
382 lastPolledAt: integer('last_polled_at'),
383 lastSyncedAt: integer('last_synced_at'),
384 status: text('status', {
385 enum: ['active', 'degraded', 'disabled'],
386 })
387 .notNull()
388 .default('active'),
389 // Mirrors ProviderConfig.makesOwnModels (issue #719): the provider makes
390 // the models it lists. Read by the name tier of reconcileSameAs and by
391 // the catalog's firstParty.
392 makesOwnModels: integer('makes_own_models', { mode: 'boolean' })
393 .notNull()
394 .default(false),
395})
396​
397/** Names other providers' model ids use for a provider (`google` → gemini). */
398export const providerModelNamespaces = sqliteTable(
399 'provider_model_namespaces',
400 {
401 namespace: text('namespace').notNull(),
402 providerId: text('provider_id')
403 .notNull()
404 .references(() => providers.id, { onDelete: 'cascade' }),
405 },
406 (table) => [
407 primaryKey({ columns: [table.namespace, table.providerId] }),
408 index('provider_model_namespaces_providerId_idx').on(table.providerId),
409 ],
411​
412export const models = sqliteTable(
413 'models',
414 {
415 id: text('id').primaryKey(),
416 providerId: text('provider_id')
417 .notNull()
418 .references(() => providers.id, { onDelete: 'cascade' }),
419 rawId: text('raw_id').notNull(),
420 activity: text('activity', { enum: activities }),
421 displayName: text('display_name'),
422 contextWindow: integer('context_window'),
423 maxOutput: integer('max_output'),
424 modalities: text('modalities', { mode: 'json' }),
425 pricing: text('pricing', { mode: 'json' }),
426 // Min/max over a routed id's per-route cards (issue #406); a bound,
427 // never the billed price. Null on a row with one billed card.
428 pricingRange: text('pricing_range', {
429 mode: 'json',
430 }).$type<PricingRange | null>(),
431 // A flag map: `{ tools: true, reasoning: false }`. true = the provider
432 // states support, false = it states none, key absent = unknown, null =
433 // nothing known. Booleans only.
434 capabilities: text('capabilities', {
435 mode: 'json',
436 }).$type<CapabilityMap | null>(),
437 // The provider's own listing object, as published and not normalised
438 // (fal category, Ark features, ElevenLabs languages, …). Never flags.
439 providerMetadata: text('provider_metadata', { mode: 'json' }).$type<Record<
440 string,
441 unknown
442 > | null>(),
443 // Thinking configuration and provider-hosted tool type ids (issue #77).
444 reasoning: text('reasoning', { mode: 'json' }),
445 serverTools: text('server_tools', { mode: 'json' }),
446 // Wire map for thinking, token limits, and roles (issue #95). Null until
447 // verified. `reasoning` stays the readable fact.
448 requestMap: text('request_map', { mode: 'json' }),
449 // Caller ids that resolve to this dated row (issue #112).
450 aliases: text('aliases', { mode: 'json' }).$type<Array<string> | null>(),
451 // The raw id the provider states this alias row resolves to, within the
452 // same provider (issue #709). Evidence only: the catalog serves it while
453 // a live row has that id; factSources.aliasOf is its source.
454 aliasOf: text('alias_of'),
455 // The provider's own statement of its upstream model (issue #199); it
456 // can precede the target row's arrival. The namespace resolves through
457 // providers / provider_model_namespaces.
458 upstreamProvider: text('upstream_provider'),
459 upstreamRawId: text('upstream_raw_id'),
460 upstreamSource: text('upstream_source', { mode: 'json' }),
461 // Resolved link, written only by reconcileSameAs; never the row's facts.
462 sameAsModelId: text('same_as_model_id').references(
463 (): AnySQLiteColumn => models.id,
464 { onDelete: 'set null' },
465 ),
466 // The end of the sameAs chain when it is more than one hop away
467 // (issue #719); null when sameAs is itself the root. Written only by
468 // reconcileSameAs.
469 rootModelId: text('root_model_id').references(
470 (): AnySQLiteColumn => models.id,
471 { onDelete: 'set null' },
472 ),
473 // Evidence for a name-inferred sameAs (issue #719): the normalised key
474 // and the rows it matched. Null on a stated link and on no link.
475 sameAsInference: text('same_as_inference', {
476 mode: 'json',
477 }).$type<SameAsInference | null>(),
478 // Per-field provenance for catalog facts (issue #53). JSON ModelFactSources.
479 factSources: text('fact_sources', { mode: 'json' }),
480 // Generation route decided from listing data the read path cannot see
481 // (Gemini's supportedGenerationMethods → :predict vs :generateContent).
482 // Null → config binds at read time; Gemini still reads leftover
483 // methods from capabilities until the poller rewrites the row.
484 schemaEndpointId: text('schema_endpoint_id'),
485 // The provider's own stated release/created date; null when it reports
486 // none. `firstSeenAt` below folds the same date in and cannot say which.
487 releasedAt: integer('released_at'),
488 // `YYYY-MM` or `YYYY-MM-DD`, as precise as the provider states it.
489 knowledgeCutoff: text('knowledge_cutoff'),
490 // Stated by the provider itself, never inferred; null = unstated.
491 openWeights: integer('open_weights', { mode: 'boolean' }),
492 weightsUrl: text('weights_url'),
493 // Who made the model, as the host's own source names it (issue #710).
494 // Null when it names none; factSources.maker says which.
495 maker: text('maker'),
496 // True when this id's own source states it trains on request data.
497 // Null when that source says it does not, or does not mention the id.
498 trainsOnRequestData: integer('trains_on_request_data', { mode: 'boolean' }),
499 // Upstream release date when the provider reports one (backdated by the
500 // poller, issue #1); otherwise when our poller first observed the model.
501 firstSeenAt: integer('first_seen_at').notNull(),
502 lastSeenAt: integer('last_seen_at').notNull(),
503 deprecatedAt: integer('deprecated_at'),
504 // The provider's deprecations page entry (issue #410), as it states it.
505 // Set means deprecatedAt is set too; null = the page names no such row
506 // or this provider has no page we read.
507 deprecation: text('deprecation', {
508 mode: 'json',
509 }).$type<ModelDeprecation | null>(),
510 },
511 (table) => [
512 index('models_providerId_idx').on(table.providerId),
513 // The catalog's alias-target join (issue #709) looks up by both.
514 index('models_providerId_rawId_idx').on(table.providerId, table.rawId),
515 index('models_activity_idx').on(table.activity),
516 index('models_sameAsModelId_idx').on(table.sameAsModelId),
517 index('models_rootModelId_idx').on(table.rootModelId),
518 // firstParty reads which providers' rows name a maker (issue #719).
519 index('models_maker_providerId_idx').on(table.maker, table.providerId),
520 check(
521 'models_upstream_identity_pair',
522 sql`(${table.upstreamProvider} IS NULL) = (${table.upstreamRawId} IS NULL)
523 AND (${table.upstreamProvider} IS NULL) = (${table.upstreamSource} IS NULL)`,
524 ),
525 check('models_sameAs_not_self', sql`${table.sameAsModelId} != ${table.id}`),
526 check('models_root_not_self', sql`${table.rootModelId} != ${table.id}`),
527 ],
529​
530export const endpoints = sqliteTable(
531 'endpoints',
532 {
533 id: text('id').primaryKey(),
534 providerId: text('provider_id')
535 .notNull()
536 .references(() => providers.id, { onDelete: 'cascade' }),
537 activity: text('activity', { enum: activities }).notNull(),
538 method: text('method').notNull(),
539 path: text('path').notNull(),
540 description: text('description'),
541 /**
542 * Request media type when it is not `application/json` (a file upload
543 * is `multipart/form-data`). Null means JSON, including rows synced
544 * before the column existed.
545 */
546 requestContentType: text('request_content_type'),
547 /**
548 * Success-response media types when they are not a single JSON body.
549 * A stream stays in the list beside JSON. Null means `application/json`.
550 */
551 responseContentTypes: text('response_content_types', {
552 mode: 'json',
553 }).$type<Array<string> | null>(),
554 },
555 (table) => [index('endpoints_providerId_idx').on(table.providerId)],
557​
558export const schemaVersions = sqliteTable(
559 'schema_versions',
560 {
561 id: text('id').primaryKey(),
562 endpointId: text('endpoint_id')
563 .notNull()
564 .references(() => endpoints.id, { onDelete: 'cascade' }),
565 /**
566 * `stream` is the SSE event schema for an operation that also has an
567 * `output` JSON schema. It is not a `GET /v1/schemas` kind.
568 */
569 kind: text('kind', { enum: ['input', 'output', 'stream'] }).notNull(),
570 contentHash: text('content_hash').notNull(),
571 schema: text('schema').notNull(),
572 specRevision: text('spec_revision'),
573 // Provenance (nullable on rows synced before it was recorded): the
574 // upstream document this version was derived from, and the extractor
575 // that derived it. createdAt doubles as the fetched-at timestamp.
576 sourceUrl: text('source_url'),
577 sourceHash: text('source_hash'),
578 extractorVersion: text('extractor_version'),
579 /**
580 * How the content was arrived at — the `Derivation` trust ladder in
581 * `src/server/providers/types.ts`. Nullable on rows synced before it was
582 * recorded. `verifiedAt` is a `YYYY-MM-DD` date and is only meaningful
583 * for `probe-verified`, whose accuracy is a point-in-time claim.
584 */
585 derivation: text('derivation', {
586 enum: ['upstream-spec', 'generated', 'probe-verified', 'docs-derived'],
587 }),
588 verifiedAt: text('verified_at'),
589 createdAt: integer('created_at').notNull(),
590 supersededAt: integer('superseded_at'),
591 },
592 (table) => [
593 index('schema_versions_endpointId_kind_idx').on(
594 table.endpointId,
595 table.kind,
596 ),
597 index('schema_versions_contentHash_idx').on(table.contentHash),
598 ],
600​
601export const changes = sqliteTable(
602 'changes',
603 {
604 id: text('id').primaryKey(),
605 type: text('type', { enum: changeTypes }).notNull(),
606 providerId: text('provider_id')
607 .notNull()
608 .references(() => providers.id, { onDelete: 'cascade' }),
609 subjectId: text('subject_id').notNull(),
610 summary: text('summary').notNull(),
611 payload: text('payload', { mode: 'json' }),
612 createdAt: integer('created_at').notNull(),
613 },
614 (table) => [
615 index('changes_createdAt_idx').on(table.createdAt),
616 index('changes_providerId_idx').on(table.providerId),
617 ],
619​
620export const providersRelations = relations(providers, ({ many }) => ({
621 models: many(models),
622 endpoints: many(endpoints),
623 changes: many(changes),
624}))
625​
626export const modelsRelations = relations(models, ({ one }) => ({
627 provider: one(providers, {
628 fields: [models.providerId],
629 references: [providers.id],
630 }),
631}))
632​
633export const endpointsRelations = relations(endpoints, ({ one, many }) => ({
634 provider: one(providers, {
635 fields: [endpoints.providerId],
636 references: [providers.id],
637 }),
638 schemaVersions: many(schemaVersions),
639}))
640​
641export const schemaVersionsRelations = relations(schemaVersions, ({ one }) => ({
642 endpoint: one(endpoints, {
643 fields: [schemaVersions.endpointId],
644 references: [endpoints.id],
645 }),
646}))
647​
648export const changesRelations = relations(changes, ({ one }) => ({
649 provider: one(providers, {
650 fields: [changes.providerId],
651 references: [providers.id],
652 }),
653}))
654​
655// ---------------------------------------------------------------------------
656// Bookkeeping rows (ingest records, completeness, webhook checkpoint, FAL
657// extract cursor). Not a response cache: public GETs read D1 and the edge.
658// `refreshing` remains from the retired KV freshness layer; nothing writes it.
659// ---------------------------------------------------------------------------
660​
661export const cacheMeta = sqliteTable('cache_meta', {
662 key: text('key').primaryKey(),
663 fetchedAt: integer('fetched_at').notNull(),
664 staleTime: integer('stale_time').notNull(),
665 lastError: text('last_error'),
666 refreshing: integer('refreshing', { mode: 'boolean' })
667 .notNull()
668 .default(false),
669})
670​
671export const subscriptions = sqliteTable(
672 'subscriptions',
673 {
674 id: text('id').primaryKey(),
675 agentId: text('agent_id')
676 .notNull()
677 .references(() => user.id, { onDelete: 'cascade' }),
678 url: text('url').notNull(),
679 secret: text('secret').notNull(),
680 events: text('events', { mode: 'json' }).notNull(),
681 providerFilter: text('provider_filter').references(() => providers.id, {
682 onDelete: 'cascade',
683 }),
684 active: integer('active', { mode: 'boolean' }).notNull().default(true),
685 createdAt: integer('created_at').notNull(),
686 },
687 (table) => [index('subscriptions_agentId_idx').on(table.agentId)],
689​
690export const webhookDeliveries = sqliteTable(
691 'webhook_deliveries',
692 {
693 id: text('id').primaryKey(),
694 subscriptionId: text('subscription_id')
695 .notNull()
696 .references(() => subscriptions.id, { onDelete: 'cascade' }),
697 changeId: text('change_id')
698 .notNull()
699 .references(() => changes.id, { onDelete: 'cascade' }),
700 attempt: integer('attempt').notNull().default(0),
701 nextAttemptAt: integer('next_attempt_at').notNull(),
702 status: text('status', { enum: ['pending', 'ok', 'failed'] })
703 .notNull()
704 .default('pending'),
705 lastResponseCode: integer('last_response_code'),
706 },
707 (table) => [
708 index('webhook_deliveries_status_nextAttemptAt_idx').on(
709 table.status,
710 table.nextAttemptAt,
711 ),
712 index('webhook_deliveries_subscriptionId_idx').on(table.subscriptionId),
713 ],
715​
716export const subscriptionsRelations = relations(
717 subscriptions,
718 ({ one, many }) => ({
719 agent: one(user, {
720 fields: [subscriptions.agentId],
721 references: [user.id],
722 }),
723 deliveries: many(webhookDeliveries),
724 }),
726​
727export const webhookDeliveriesRelations = relations(
728 webhookDeliveries,
729 ({ one }) => ({
730 subscription: one(subscriptions, {
731 fields: [webhookDeliveries.subscriptionId],
732 references: [subscriptions.id],
733 }),
734 change: one(changes, {
735 fields: [webhookDeliveries.changeId],
736 references: [changes.id],
737 }),
738 }),