import { sql } from "drizzle-orm"; import { boolean, customType, index, integer, jsonb, pgTable, smallint, text, timestamp, unique, uniqueIndex, uuid, } from "drizzle-orm/pg-core"; // Migration 0929: event sources, deliveries, normalized events and the event // triggers of automations (scheduled tasks). Foreign keys to accounts, // workspaces and scheduled tasks live in the migration. const bytea = customType<{ data: Uint8Array; driverData: Uint8Array }>({ dataType() { return "bytea"; }, }); export const eventSources = pgTable( "event_sources", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id").notNull(), workspaceId: uuid("workspace_id").notNull(), kind: text("kind").notNull(), adapter: text("adapter"), // Migration 0987: how a custom webhook reads its app's deliveries. webhookFormat: jsonb("webhook_format"), name: text("name").notNull(), ownerSubjectId: text("owner_subject_id"), visibility: text("visibility").notNull().default("private"), status: text("status").notNull().default("active"), statusReason: text("status_reason"), // Migration 0960: the reason as a code clients word, and what the app said. statusReasonCode: text("status_reason_code"), statusReasonDetail: text("status_reason_detail"), secretEncrypted: text("secret_encrypted"), // Migration 1128: 'api' once an API caller set or received the signing // secret, or named a workspace MCP source's URL (`BillingOrigin`); its // deliveries are then API use. Never turned back; null means only the // app has held it. secretBillingOrigin: text("secret_billing_origin"), externalKey: text("external_key"), mcpServerId: text("mcp_server_id"), // Migration 1103: a workspace MCP source listens to this URL, signed in // by the workspace credential provider; null for a connector source. mcpServerUrl: text("mcp_server_url"), connectionId: uuid("connection_id"), lastDeliveryAt: timestamp("last_delivery_at", { withTimezone: true }), createdBySubjectId: text("created_by_subject_id").notNull(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ workspaceId: uniqueIndex("event_sources_workspace_id_uq").on(table.workspaceId, table.id), }), ); /** * Credential-free routing from a webhook URL (its random route id) or a GitHub * App installation to a source. No tenant RLS: intake finds the workspace * here. So it holds no provider identity: a GitHub route's external key is a * keyed hash of the installation (githubInstallationRouteKey). */ export const eventIngressRoutes = pgTable( "event_ingress_routes", { routeId: uuid("route_id").primaryKey().defaultRandom(), accountId: uuid("account_id").notNull(), workspaceId: uuid("workspace_id").notNull(), sourceId: uuid("source_id") .notNull() .references(() => eventSources.id, { onDelete: "cascade" }), kind: text("kind").notNull(), externalKey: text("external_key"), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ source: index("event_ingress_routes_source_idx").on(table.sourceId), external: index("event_ingress_routes_external_idx") .on(table.kind, table.externalKey) .where(sql`${table.externalKey} is not null`), }), ); export const eventDeliveries = pgTable( "event_deliveries", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id").notNull(), workspaceId: uuid("workspace_id").notNull(), sourceId: uuid("source_id") .notNull() .references(() => eventSources.id, { onDelete: "cascade" }), receivedAt: timestamp("received_at", { withTimezone: true }).notNull().defaultNow(), status: text("status").notNull(), reason: text("reason"), dedupeKey: text("dedupe_key").notNull(), body: bytea("body"), bodyBytes: integer("body_bytes").notNull(), bodySha256: text("body_sha256").notNull(), headers: jsonb("headers").$type>().notNull().default({}), eventCount: integer("event_count").notNull().default(0), duplicateCount: integer("duplicate_count").notNull().default(0), lastDuplicateAt: timestamp("last_duplicate_at", { withTimezone: true }), replayOfDeliveryId: uuid("replay_of_delivery_id"), // Migration 0932: the MCP subscription stream a delivery arrived on. streamKey: text("stream_key").notNull().default(""), }, (table) => ({ dedupe: uniqueIndex("event_deliveries_dedupe_uq") .on(table.sourceId, table.dedupeKey) .where(sql`${table.replayOfDeliveryId} is null`), sourceReceived: index("event_deliveries_source_received_idx").on( table.workspaceId, table.sourceId, table.receivedAt, table.id, ), }), ); export const inboundEvents = pgTable( "inbound_events", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id").notNull(), workspaceId: uuid("workspace_id").notNull(), sourceId: uuid("source_id") .notNull() .references(() => eventSources.id, { onDelete: "cascade" }), deliveryId: uuid("delivery_id").references(() => eventDeliveries.id, { onDelete: "set null", }), externalId: text("external_id"), streamKey: text("stream_key").notNull().default(""), type: text("type").notNull(), occurredAt: timestamp("occurred_at", { withTimezone: true }).notNull(), receivedAt: timestamp("received_at", { withTimezone: true }).notNull().defaultNow(), subject: text("subject"), summary: text("summary").notNull(), url: text("url"), actorKind: text("actor_kind").notNull().default("unknown"), actorName: text("actor_name"), data: jsonb("data").$type>().notNull().default({}), dataTruncated: boolean("data_truncated").notNull().default(false), gapBefore: boolean("gap_before").notNull().default(false), // Migration 1105: 0, or the chain depth of the automation run that caused it. chainDepth: smallint("chain_depth").notNull().default(0), }, (table) => ({ external: uniqueIndex("inbound_events_external_uq") .on(table.sourceId, table.streamKey, table.externalId) .where(sql`${table.externalId} is not null`), sourceReceived: index("inbound_events_source_received_idx").on( table.workspaceId, table.sourceId, table.receivedAt, table.id, ), }), ); export const eventTriggers = pgTable( "event_triggers", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id").notNull(), workspaceId: uuid("workspace_id").notNull(), taskId: uuid("task_id").notNull(), sourceId: uuid("source_id") .notNull() .references(() => eventSources.id, { onDelete: "cascade" }), position: smallint("position").notNull(), eventTypes: text("event_types").array().notNull(), conditions: jsonb("conditions").$type().notNull().default([]), includeOwnEvents: boolean("include_own_events").notNull().default(false), arguments: jsonb("arguments").$type | null>(), // Migration 0932: the MCP subscription stream the trigger listens on. streamKey: text("stream_key").notNull().default(""), status: text("status").notNull().default("active"), statusReason: text("status_reason"), // Migration 0960: the reason as a code clients word, and what the app said. statusReasonCode: text("status_reason_code"), statusReasonDetail: text("status_reason_detail"), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ position: unique("event_triggers_position_uq").on(table.taskId, table.position), }), ); export const scheduledTaskEventSettings = pgTable("scheduled_task_event_settings", { taskId: uuid("task_id").primaryKey(), accountId: uuid("account_id").notNull(), workspaceId: uuid("workspace_id").notNull(), maxRunsPerHour: integer("max_runs_per_hour").notNull().default(30), once: boolean("once").notNull().default(false), completedAt: timestamp("completed_at", { withTimezone: true }), armedAt: timestamp("armed_at", { withTimezone: true }).notNull().defaultNow(), dispatchDueAt: timestamp("dispatch_due_at", { withTimezone: true }), throttledSince: timestamp("throttled_since", { withTimezone: true }), throttleNotified: boolean("throttle_notified").notNull().default(false), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }); // Migration 1105: what happens in Opengeni itself (chats finishing, failing, // waiting; usage thresholds), written by database triggers and kept 24 hours // for the "This workspace" feed. Row security decides who sees each fact. export const workspaceActivityEvents = pgTable( "workspace_activity_events", { workspaceId: uuid("workspace_id").notNull(), id: uuid("id").notNull(), accountId: uuid("account_id").notNull(), type: text("type").notNull(), occurredAt: timestamp("occurred_at", { withTimezone: true }).notNull(), sessionId: uuid("session_id"), turnId: uuid("turn_id"), subjectId: text("subject_id"), automationId: uuid("automation_id"), automationRunId: uuid("automation_run_id"), chainDepth: smallint("chain_depth").notNull().default(0), data: jsonb("data").$type>().notNull().default({}), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ feed: index("workspace_activity_events_feed_idx").on( table.workspaceId, table.createdAt, table.id, ), }), ); export const scheduledTaskEventOccurrences = pgTable("scheduled_task_event_occurrences", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id").notNull(), workspaceId: uuid("workspace_id").notNull(), taskId: uuid("task_id").notNull(), triggerIds: uuid("trigger_ids").array().notNull(), eventCount: integer("event_count").notNull(), eventIds: uuid("event_ids").array().notNull(), events: jsonb("events").$type().notNull(), gapBefore: boolean("gap_before").notNull().default(false), status: text("status").notNull().default("pending"), startAttempts: integer("start_attempts").notNull().default(0), lastError: text("last_error"), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), startedAt: timestamp("started_at", { withTimezone: true }), }); export const scheduledTaskEventInbox = pgTable( "scheduled_task_event_inbox", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id").notNull(), workspaceId: uuid("workspace_id").notNull(), taskId: uuid("task_id").notNull(), eventId: uuid("event_id") .notNull() .references(() => inboundEvents.id, { onDelete: "cascade" }), triggerIds: uuid("trigger_ids").array().notNull(), occurredAt: timestamp("occurred_at", { withTimezone: true }).notNull(), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), status: text("status").notNull().default("pending"), occurrenceId: uuid("occurrence_id").references(() => scheduledTaskEventOccurrences.id, { onDelete: "set null", }), }, (table) => ({ event: unique("scheduled_task_event_inbox_event_uq").on(table.taskId, table.eventId), }), ); // Migration 0932: one MCP Events subscription per (source, event name, // canonical arguments) that runnable automations want. export const mcpEventSubscriptions = pgTable( "mcp_event_subscriptions", { id: uuid("id").primaryKey().defaultRandom(), accountId: uuid("account_id").notNull(), workspaceId: uuid("workspace_id").notNull(), sourceId: uuid("source_id") .notNull() .references(() => eventSources.id, { onDelete: "cascade" }), streamKey: text("stream_key").notNull(), eventName: text("event_name").notNull(), arguments: jsonb("arguments").$type>().notNull().default({}), mode: text("mode"), // Migration 1296: why the subscription polls, and since when. pollReason: text("poll_reason"), pollReasonAt: timestamp("poll_reason_at", { withTimezone: true }), cursor: text("cursor"), gapPending: boolean("gap_pending").notNull().default(false), routeId: uuid("route_id"), secretEncrypted: text("secret_encrypted"), serverSubscriptionId: text("server_subscription_id"), refreshBefore: timestamp("refresh_before", { withTimezone: true }), nextActionAt: timestamp("next_action_at", { withTimezone: true }).notNull().defaultNow(), leaseUntil: timestamp("lease_until", { withTimezone: true }), failures: integer("failures").notNull().default(0), failingSince: timestamp("failing_since", { withTimezone: true }), lastError: text("last_error"), lastSuccessAt: timestamp("last_success_at", { withTimezone: true }), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => ({ stream: unique("mcp_event_subscriptions_stream_uq").on(table.sourceId, table.streamKey), route: uniqueIndex("mcp_event_subscriptions_route_id_key").on(table.routeId), }), ); // Migration 0935: the reading position of a source whose events Opengeni // reads from the app's change history (Gmail), one per source. export const eventSourceFeeds = pgTable("event_source_feeds", { sourceId: uuid("source_id").primaryKey(), accountId: uuid("account_id").notNull(), workspaceId: uuid("workspace_id").notNull(), cursor: text("cursor"), gapPending: boolean("gap_pending").notNull().default(false), nextActionAt: timestamp("next_action_at", { withTimezone: true }).notNull().defaultNow(), leaseUntil: timestamp("lease_until", { withTimezone: true }), failures: integer("failures").notNull().default(0), failingSince: timestamp("failing_since", { withTimezone: true }), lastError: text("last_error"), lastSuccessAt: timestamp("last_success_at", { withTimezone: true }), createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(), });