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