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 provider's own statement of its upstream model (issue #199); it
443 // can precede the target row's arrival. The namespace resolves through
444 // providers / provider_model_namespaces.
445 upstreamProvider: text('upstream_provider'),
446 upstreamRawId: text('upstream_raw_id'),
447 upstreamSource: text('upstream_source', { mode: 'json' }),
448 // Resolved link, written only by reconcileSameAs; never the row's facts.
449 sameAsModelId: text('same_as_model_id').references(
450 (): AnySQLiteColumn => models.id,
451 { onDelete: 'set null' },
452 ),
453 // Per-field provenance for catalog facts (issue #53). JSON ModelFactSources.
454 factSources: text('fact_sources', { mode: 'json' }),
455 // Generation route decided from listing data the read path cannot see
456 // (Gemini's supportedGenerationMethods → :predict vs :generateContent).
457 // Null → config binds at read time; Gemini still reads leftover
458 // methods from capabilities until the poller rewrites the row.
459 schemaEndpointId: text('schema_endpoint_id'),
460 // The provider's own stated release/created date; null when it reports
461 // none. `firstSeenAt` below folds the same date in and cannot say which.
462 releasedAt: integer('released_at'),
463 // `YYYY-MM` or `YYYY-MM-DD`, as precise as the provider states it.
464 knowledgeCutoff: text('knowledge_cutoff'),
465 // Stated by the provider itself, never inferred; null = unstated.
466 openWeights: integer('open_weights', { mode: 'boolean' }),
467 weightsUrl: text('weights_url'),
468 // True when this id's own source states it trains on request data.
469 // Null when that source says it does not, or does not mention the id.
470 trainsOnRequestData: integer('trains_on_request_data', { mode: 'boolean' }),
471 // Upstream release date when the provider reports one (backdated by the
472 // poller, issue #1); otherwise when our poller first observed the model.
473 firstSeenAt: integer('first_seen_at').notNull(),
474 lastSeenAt: integer('last_seen_at').notNull(),
475 deprecatedAt: integer('deprecated_at'),
476 // The provider's deprecations page entry (issue #410), as it states it.
477 // Set means deprecatedAt is set too; null = the page names no such row
478 // or this provider has no page we read.
479 deprecation: text('deprecation', {
480 mode: 'json',
481 }).$type<ModelDeprecation | null>(),
482 },
483 (table) => [
484 index('models_providerId_idx').on(table.providerId),
485 index('models_activity_idx').on(table.activity),
486 index('models_sameAsModelId_idx').on(table.sameAsModelId),
487 check(
488 'models_upstream_identity_pair',
489 sql`(${table.upstreamProvider} IS NULL) = (${table.upstreamRawId} IS NULL)
490 AND (${table.upstreamProvider} IS NULL) = (${table.upstreamSource} IS NULL)`,
491 ),
492 check('models_sameAs_not_self', sql`${table.sameAsModelId} != ${table.id}`),
493 ],
494)
495
496export const endpoints = sqliteTable(
497 'endpoints',
498 {
499 id: text('id').primaryKey(),
500 providerId: text('provider_id')
501 .notNull()
502 .references(() => providers.id, { onDelete: 'cascade' }),
503 activity: text('activity', { enum: activities }).notNull(),
504 method: text('method').notNull(),
505 path: text('path').notNull(),
506 description: text('description'),
507 /**
508 * Request media type when it is not `application/json` (a file upload
509 * is `multipart/form-data`). Null means JSON, including rows synced
510 * before the column existed.
511 */
512 requestContentType: text('request_content_type'),
513 /**
514 * Success-response media types when they are not a single JSON body.
515 * A stream stays in the list beside JSON. Null means `application/json`.
516 */
517 responseContentTypes: text('response_content_types', {
518 mode: 'json',
519 }).$type<Array<string> | null>(),
520 },
521 (table) => [index('endpoints_providerId_idx').on(table.providerId)],
522)
523
524export const schemaVersions = sqliteTable(
525 'schema_versions',
526 {
527 id: text('id').primaryKey(),
528 endpointId: text('endpoint_id')
529 .notNull()
530 .references(() => endpoints.id, { onDelete: 'cascade' }),
531 /**
532 * `stream` is the SSE event schema for an operation that also has an
533 * `output` JSON schema. It is not a `GET /v1/schemas` kind.
534 */
535 kind: text('kind', { enum: ['input', 'output', 'stream'] }).notNull(),
536 contentHash: text('content_hash').notNull(),
537 schema: text('schema').notNull(),
538 specRevision: text('spec_revision'),
539 // Provenance (nullable on rows synced before it was recorded): the
540 // upstream document this version was derived from, and the extractor
541 // that derived it. createdAt doubles as the fetched-at timestamp.
542 sourceUrl: text('source_url'),
543 sourceHash: text('source_hash'),
544 extractorVersion: text('extractor_version'),
545 /**
546 * How the content was arrived at — the `Derivation` trust ladder in
547 * `src/server/providers/types.ts`. Nullable on rows synced before it was
548 * recorded. `verifiedAt` is a `YYYY-MM-DD` date and is only meaningful
549 * for `probe-verified`, whose accuracy is a point-in-time claim.
550 */
551 derivation: text('derivation', {
552 enum: ['upstream-spec', 'generated', 'probe-verified', 'docs-derived'],
553 }),
554 verifiedAt: text('verified_at'),
555 createdAt: integer('created_at').notNull(),
556 supersededAt: integer('superseded_at'),
557 },
558 (table) => [
559 index('schema_versions_endpointId_kind_idx').on(
560 table.endpointId,
561 table.kind,
562 ),
563 index('schema_versions_contentHash_idx').on(table.contentHash),
564 ],
565)
566
567export const changes = sqliteTable(
568 'changes',
569 {
570 id: text('id').primaryKey(),
571 type: text('type', { enum: changeTypes }).notNull(),
572 providerId: text('provider_id')
573 .notNull()
574 .references(() => providers.id, { onDelete: 'cascade' }),
575 subjectId: text('subject_id').notNull(),
576 summary: text('summary').notNull(),
577 payload: text('payload', { mode: 'json' }),
578 createdAt: integer('created_at').notNull(),
579 },
580 (table) => [
581 index('changes_createdAt_idx').on(table.createdAt),
582 index('changes_providerId_idx').on(table.providerId),
583 ],
584)
585
586export const providersRelations = relations(providers, ({ many }) => ({
587 models: many(models),
588 endpoints: many(endpoints),
589 changes: many(changes),
590}))
591
592export const modelsRelations = relations(models, ({ one }) => ({
593 provider: one(providers, {
594 fields: [models.providerId],
595 references: [providers.id],
596 }),
597}))
598
599export const endpointsRelations = relations(endpoints, ({ one, many }) => ({
600 provider: one(providers, {
601 fields: [endpoints.providerId],
602 references: [providers.id],
603 }),
604 schemaVersions: many(schemaVersions),
605}))
606
607export const schemaVersionsRelations = relations(schemaVersions, ({ one }) => ({
608 endpoint: one(endpoints, {
609 fields: [schemaVersions.endpointId],
610 references: [endpoints.id],
611 }),
612}))
613
614export const changesRelations = relations(changes, ({ one }) => ({
615 provider: one(providers, {
616 fields: [changes.providerId],
617 references: [providers.id],
618 }),
619}))
620
621// ---------------------------------------------------------------------------
622// Bookkeeping rows (ingest records, completeness, webhook checkpoint, FAL
623// extract cursor). Not a response cache: public GETs read D1 and the edge.
624// `refreshing` remains from the retired KV freshness layer; nothing writes it.
625// ---------------------------------------------------------------------------
626
627export const cacheMeta = sqliteTable('cache_meta', {
628 key: text('key').primaryKey(),
629 fetchedAt: integer('fetched_at').notNull(),
630 staleTime: integer('stale_time').notNull(),
631 lastError: text('last_error'),
632 refreshing: integer('refreshing', { mode: 'boolean' })
633 .notNull()
634 .default(false),
635})
636
637export const subscriptions = sqliteTable(
638 'subscriptions',
639 {
640 id: text('id').primaryKey(),
641 agentId: text('agent_id')
642 .notNull()
643 .references(() => user.id, { onDelete: 'cascade' }),
644 url: text('url').notNull(),
645 secret: text('secret').notNull(),
646 events: text('events', { mode: 'json' }).notNull(),
647 providerFilter: text('provider_filter').references(() => providers.id, {
648 onDelete: 'cascade',
649 }),
650 active: integer('active', { mode: 'boolean' }).notNull().default(true),
651 createdAt: integer('created_at').notNull(),
652 },
653 (table) => [index('subscriptions_agentId_idx').on(table.agentId)],
654)
655
656export const webhookDeliveries = sqliteTable(
657 'webhook_deliveries',
658 {
659 id: text('id').primaryKey(),
660 subscriptionId: text('subscription_id')
661 .notNull()
662 .references(() => subscriptions.id, { onDelete: 'cascade' }),
663 changeId: text('change_id')
664 .notNull()
665 .references(() => changes.id, { onDelete: 'cascade' }),
666 attempt: integer('attempt').notNull().default(0),
667 nextAttemptAt: integer('next_attempt_at').notNull(),
668 status: text('status', { enum: ['pending', 'ok', 'failed'] })
669 .notNull()
670 .default('pending'),
671 lastResponseCode: integer('last_response_code'),
672 },
673 (table) => [
674 index('webhook_deliveries_status_nextAttemptAt_idx').on(
675 table.status,
676 table.nextAttemptAt,
677 ),
678 index('webhook_deliveries_subscriptionId_idx').on(table.subscriptionId),
679 ],
680)
681
682export const subscriptionsRelations = relations(
683 subscriptions,
684 ({ one, many }) => ({
685 agent: one(user, {
686 fields: [subscriptions.agentId],
687 references: [user.id],
688 }),
689 deliveries: many(webhookDeliveries),
690 }),
691)
692
693export const webhookDeliveriesRelations = relations(
694 webhookDeliveries,
695 ({ one }) => ({
696 subscription: one(subscriptions, {
697 fields: [webhookDeliveries.subscriptionId],
698 references: [subscriptions.id],
699 }),
700 change: one(changes, {
701 fields: [webhookDeliveries.changeId],
702 references: [changes.id],
703 }),
704 }),
705)