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