@elizaos/plugin-sql 2.0.0-alpha.11 → 2.0.0-alpha.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,16 +1,16 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../../schema/agent.ts", "../../schema/server.ts", "../../types.ts", "../../migrations.ts", "../../rls.ts", "../../runtime-migrator/drizzle-adapters/diff-calculator.ts", "../../runtime-migrator/crypto-utils.ts", "../../runtime-migrator/drizzle-adapters/snapshot-generator.ts", "../../runtime-migrator/drizzle-adapters/sql-generator.ts", "../../runtime-migrator/drizzle-adapters/database-introspector.ts", "../../runtime-migrator/extension-manager.ts", "../../runtime-migrator/schema-transformer.ts", "../../runtime-migrator/storage/journal-storage.ts", "../../runtime-migrator/storage/migration-tracker.ts", "../../runtime-migrator/storage/snapshot-storage.ts", "../../runtime-migrator/runtime-migrator.ts", "../../runtime-migrator/index.ts", "../../migration-service.ts", "../../index.browser.ts", "../../pglite/adapter.ts", "../../base.ts", "../../node_modules/uuid/dist/stringify.js", "../../node_modules/uuid/dist/rng.js", "../../node_modules/uuid/dist/native.js", "../../node_modules/uuid/dist/v4.js", "../../schema/embedding.ts", "../../schema/memory.ts", "../../schema/entity.ts", "../../schema/room.ts", "../../schema/index.ts", "../../schema/cache.ts", "../../schema/channel.ts", "../../schema/messageServer.ts", "../../schema/channelParticipant.ts", "../../schema/component.ts", "../../schema/world.ts", "../../schema/log.ts", "../../schema/message.ts", "../../schema/messageServerAgent.ts", "../../schema/pairingAllowlist.ts", "../../schema/pairingRequest.ts", "../../schema/participant.ts", "../../schema/relationship.ts", "../../schema/tasks.ts", "../../pglite/manager.ts"],
3
+ "sources": ["../../schema/agent.ts", "../../schema/server.ts", "../../types.ts", "../../migrations.ts", "../../rls.ts", "../../runtime-migrator/drizzle-adapters/diff-calculator.ts", "../../runtime-migrator/crypto-utils.ts", "../../runtime-migrator/drizzle-adapters/snapshot-generator.ts", "../../runtime-migrator/drizzle-adapters/sql-generator.ts", "../../runtime-migrator/drizzle-adapters/database-introspector.ts", "../../runtime-migrator/extension-manager.ts", "../../runtime-migrator/schema-transformer.ts", "../../runtime-migrator/storage/journal-storage.ts", "../../runtime-migrator/storage/migration-tracker.ts", "../../runtime-migrator/storage/snapshot-storage.ts", "../../runtime-migrator/runtime-migrator.ts", "../../runtime-migrator/index.ts", "../../migration-service.ts", "../../index.browser.ts", "../../pglite/adapter.ts", "../../base.ts", "../../../../../node_modules/.pnpm/uuid@13.0.0/node_modules/uuid/dist/stringify.js", "../../../../../node_modules/.pnpm/uuid@13.0.0/node_modules/uuid/dist/rng.js", "../../../../../node_modules/.pnpm/uuid@13.0.0/node_modules/uuid/dist/native.js", "../../../../../node_modules/.pnpm/uuid@13.0.0/node_modules/uuid/dist/v4.js", "../../schema/embedding.ts", "../../schema/memory.ts", "../../schema/entity.ts", "../../schema/room.ts", "../../schema/index.ts", "../../schema/cache.ts", "../../schema/channel.ts", "../../schema/messageServer.ts", "../../schema/channelParticipant.ts", "../../schema/component.ts", "../../schema/world.ts", "../../schema/log.ts", "../../schema/message.ts", "../../schema/messageServerAgent.ts", "../../schema/pairingAllowlist.ts", "../../schema/pairingRequest.ts", "../../schema/participant.ts", "../../schema/relationship.ts", "../../schema/tasks.ts", "../../pglite/manager.ts"],
4
4
  "sourcesContent": [
5
5
  "import type { MessageExample } from \"@elizaos/core\";\nimport { sql } from \"drizzle-orm\";\nimport { boolean, jsonb, pgTable, text, timestamp, uuid } from \"drizzle-orm/pg-core\";\n\n/**\n * Represents a table for storing agent data.\n *\n * @type {Table}\n */\nexport const agentTable = pgTable(\"agents\", {\n id: uuid(\"id\").primaryKey().defaultRandom(),\n enabled: boolean(\"enabled\").default(true).notNull(),\n server_id: uuid(\"server_id\"),\n createdAt: timestamp(\"created_at\", { withTimezone: true }).default(sql`now()`).notNull(),\n\n updatedAt: timestamp(\"updated_at\", { withTimezone: true }).default(sql`now()`).notNull(),\n\n // Character\n name: text(\"name\").notNull(),\n username: text(\"username\"),\n system: text(\"system\").default(\"\"),\n bio: jsonb(\"bio\").$type<string | string[]>().default(sql`'[]'::jsonb`),\n messageExamples: jsonb(\"message_examples\")\n .$type<MessageExample[][]>()\n .default(sql`'[]'::jsonb`)\n .notNull(),\n postExamples: jsonb(\"post_examples\").$type<string[]>().default(sql`'[]'::jsonb`).notNull(),\n topics: jsonb(\"topics\").$type<string[]>().default(sql`'[]'::jsonb`).notNull(),\n adjectives: jsonb(\"adjectives\").$type<string[]>().default(sql`'[]'::jsonb`).notNull(),\n knowledge: jsonb(\"knowledge\")\n .$type<(string | { path: string; shared?: boolean })[]>()\n .default(sql`'[]'::jsonb`)\n .notNull(),\n plugins: jsonb(\"plugins\").$type<string[]>().default(sql`'[]'::jsonb`).notNull(),\n settings: jsonb(\"settings\")\n .$type<{\n secrets?: { [key: string]: string | boolean | number };\n [key: string]: string | boolean | number | Record<string, unknown> | undefined;\n }>()\n .default(sql`'{}'::jsonb`)\n .notNull(),\n style: jsonb(\"style\")\n .$type<{\n all?: string[];\n chat?: string[];\n post?: string[];\n }>()\n .default(sql`'{}'::jsonb`)\n .notNull(),\n});\n",
6
6
  "import { sql } from \"drizzle-orm\";\nimport { pgTable, timestamp, uuid } from \"drizzle-orm/pg-core\";\n\n/**\n * Represents a table for storing server data for RLS multi-tenant isolation.\n * Each server represents one elizaOS instance in a multi-tenant deployment.\n *\n * @type {Table}\n */\nexport const serverTable = pgTable(\"servers\", {\n id: uuid(\"id\").primaryKey(),\n createdAt: timestamp(\"created_at\", { withTimezone: true }).default(sql`now()`).notNull(),\n updatedAt: timestamp(\"updated_at\", { withTimezone: true }).default(sql`now()`).notNull(),\n});\n",
7
7
  "import type { IDatabaseAdapter } from \"@elizaos/core\";\nimport type { NodePgDatabase } from \"drizzle-orm/node-postgres\";\nimport type { PgliteDatabase } from \"drizzle-orm/pglite\";\n\nexport type DrizzleDatabase = NodePgDatabase | PgliteDatabase;\n\nexport interface IDatabaseClientManager<T> {\n initialize(): Promise<void>;\n getConnection(): T;\n close(): Promise<void>;\n}\n\nexport function getDb(adapter: IDatabaseAdapter): DrizzleDatabase {\n return adapter.db as DrizzleDatabase;\n}\n\nexport function getRow<T>(result: { rows: unknown[] }, index = 0): T | undefined {\n return result.rows[index] as T | undefined;\n}\n",
8
- "import { type IDatabaseAdapter, logger } from \"@elizaos/core\";\nimport { sql } from \"drizzle-orm\";\nimport { getDb } from \"./types\";\n\n// Column info row for schema introspection queries\ninterface ColumnInfoRow {\n column_name: string;\n data_type: string;\n}\n\n// Table info row for schema introspection queries\ninterface TableInfoRow {\n table_name: string;\n}\n\n/**\n * Type-safe extraction of rows from SQL query results.\n */\nfunction getRows<T>(result: { rows: unknown[] }): T[] {\n return result.rows as T[];\n}\n\n/**\n * TEMPORARY MIGRATION: pre-1.6.5 → 1.6.5+ schema migration\n *\n * This migration runs automatically on startup and is idempotent.\n * It handles the migration from Owner RLS to Server RLS + Entity RLS, including:\n * - Disabling old RLS policies temporarily\n * - Renaming server_id → message_server_id in channels, worlds, rooms\n * - Converting TEXT → UUID where needed\n * - Dropping old server_id columns for RLS\n * - Cleaning up indexes\n *\n * @param adapter - Database adapter\n */\nexport async function migrateToEntityRLS(adapter: IDatabaseAdapter): Promise<void> {\n const db = getDb(adapter);\n\n // Detect database type - skip PostgreSQL-specific migrations for SQLite\n try {\n await db.execute(sql`SELECT 1 FROM pg_tables LIMIT 1`);\n } catch {\n // Not PostgreSQL (likely SQLite)\n logger.debug(\"[Migration] ⊘ Not PostgreSQL, skipping PostgreSQL-specific migrations\");\n return;\n }\n\n // Check if schema migration has already been completed\n // We use the presence of snake_case columns as a marker\n let schemaAlreadyMigrated = false;\n try {\n const migrationCheck = await db.execute(sql`\n SELECT column_name FROM information_schema.columns\n WHERE table_schema = 'public'\n AND table_name = 'rooms'\n AND column_name = 'agent_id'\n `);\n\n if (migrationCheck.rows && migrationCheck.rows.length > 0) {\n // Migration already completed - rooms.agent_id exists (snake_case)\n schemaAlreadyMigrated = true;\n logger.debug(\"[Migration] ⊘ Schema already migrated (snake_case columns exist)\");\n }\n } catch {\n // Table might not exist yet, continue with migration\n logger.debug(\"[Migration] → rooms table not found, will be created by RuntimeMigrator\");\n return; // Let RuntimeMigrator create fresh tables\n }\n\n // If schema is already migrated, check if we need to clean up RLS\n // Only disable RLS if ENABLE_DATA_ISOLATION is NOT true (user disabled isolation)\n // If ENABLE_DATA_ISOLATION=true, keep RLS as-is - migration-service.ts will ensure proper config\n if (schemaAlreadyMigrated) {\n const dataIsolationEnabled = process.env.ENABLE_DATA_ISOLATION === \"true\";\n\n if (dataIsolationEnabled) {\n // RLS should stay enabled - no need to disable/re-enable cycle\n // migration-service.ts ensures RLS is properly configured via idempotent calls\n logger.debug(\"[Migration] ⊘ Schema already migrated, RLS enabled - nothing to do\");\n return;\n }\n\n // User disabled data isolation - clean up RLS if it was previously enabled\n logger.debug(\"[Migration] → Schema migrated but RLS disabled, cleaning up...\");\n\n try {\n const tablesWithRls = await db.execute(sql`\n SELECT c.relname as tablename\n FROM pg_class c\n JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE n.nspname = 'public'\n AND c.relkind = 'r'\n AND c.relrowsecurity = true\n ORDER BY c.relname\n `);\n\n if (tablesWithRls.rows && tablesWithRls.rows.length > 0) {\n for (const row of tablesWithRls.rows) {\n const tableName = row.tablename as string;\n try {\n await db.execute(sql.raw(`ALTER TABLE \"${tableName}\" DISABLE ROW LEVEL SECURITY`));\n } catch {\n // Ignore errors\n }\n }\n logger.debug(`[Migration] ✓ RLS cleanup completed (${tablesWithRls.rows.length} tables)`);\n } else {\n logger.debug(\"[Migration] ⊘ No tables with RLS to clean up\");\n }\n } catch {\n logger.debug(\"[Migration] ⊘ Could not perform RLS cleanup\");\n }\n\n return;\n }\n\n logger.info(\"[Migration] Starting pre-1.6.5 → 1.6.5+ schema migration...\");\n\n try {\n // Clear RuntimeMigrator snapshot cache to force fresh introspection\n // This ensures the snapshot matches the current database state after our migrations\n logger.debug(\"[Migration] → Clearing RuntimeMigrator snapshot cache...\");\n try {\n await db.execute(\n sql`DELETE FROM migrations._snapshots WHERE plugin_name = '@elizaos/plugin-sql'`\n );\n logger.debug(\"[Migration] ✓ Snapshot cache cleared\");\n } catch (_error) {\n // If migrations schema doesn't exist yet, that's fine - no cache to clear\n logger.debug(\"[Migration] ⊘ No snapshot cache to clear (migrations schema not yet created)\");\n }\n\n // Disable RLS only on tables that have it enabled\n // RLS will be re-implemented properly later\n logger.debug(\"[Migration] → Checking for Row Level Security to disable...\");\n try {\n const tablesWithRls = await db.execute(sql`\n SELECT c.relname as tablename\n FROM pg_class c\n JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE n.nspname = 'public'\n AND c.relkind = 'r'\n AND c.relrowsecurity = true\n ORDER BY c.relname\n `);\n\n if (tablesWithRls.rows && tablesWithRls.rows.length > 0) {\n for (const row of tablesWithRls.rows) {\n const tableName = row.tablename as string;\n try {\n await db.execute(sql.raw(`ALTER TABLE \"${tableName}\" DISABLE ROW LEVEL SECURITY`));\n logger.debug(`[Migration] ✓ Disabled RLS on ${tableName}`);\n } catch (_error) {\n logger.debug(`[Migration] ⊘ Could not disable RLS on ${tableName}`);\n }\n }\n } else {\n logger.debug(\"[Migration] ⊘ No tables with RLS enabled\");\n }\n } catch (_error) {\n logger.debug(\"[Migration] ⊘ Could not check RLS (may not have permissions)\");\n }\n\n // Special handling for tables where serverId/server_id needs to become message_server_id\n // v1.6.4 had: rooms.serverId (TEXT camelCase), worlds.serverId (TEXT camelCase), channels.server_id (UUID)\n // Current: message_server_id (UUID) in all tables\n //\n // STRATEGY: Rename serverId/server_id to message_server_id preserving data\n logger.debug(\"[Migration] → Handling serverId/server_id → message_server_id migrations...\");\n\n const tablesToMigrate = [\"channels\", \"worlds\", \"rooms\"];\n\n for (const tableName of tablesToMigrate) {\n try {\n // Check for both camelCase (serverId) and snake_case (server_id) columns\n const columnsResult = await db.execute(sql`\n SELECT column_name, data_type, is_nullable\n FROM information_schema.columns\n WHERE table_schema = 'public'\n AND table_name = ${tableName}\n AND column_name IN ('server_id', 'serverId', 'message_server_id')\n ORDER BY column_name\n `);\n\n const columns = getRows<ColumnInfoRow>(columnsResult);\n const serverIdSnake = columns.find((c) => c.column_name === \"server_id\");\n const serverIdCamel = columns.find((c) => c.column_name === \"serverId\");\n const messageServerId = columns.find((c) => c.column_name === \"message_server_id\");\n\n // Use whichever old column exists (prefer snake_case for channels)\n const serverId = serverIdSnake || serverIdCamel;\n const oldColumnName = serverIdSnake ? \"server_id\" : \"serverId\";\n\n if (serverId && !messageServerId) {\n // Old column exists → rename it to message_server_id\n logger.debug(\n `[Migration] → Renaming ${tableName}.${oldColumnName} to message_server_id...`\n );\n await db.execute(\n sql.raw(\n `ALTER TABLE \"${tableName}\" RENAME COLUMN \"${oldColumnName}\" TO \"message_server_id\"`\n )\n );\n logger.debug(`[Migration] ✓ Renamed ${tableName}.${oldColumnName} → message_server_id`);\n\n // If the column was text, try to convert to UUID (if data is UUID-compatible)\n if (serverId.data_type === \"text\") {\n // CRITICAL: Drop DEFAULT constraint before type conversion\n // This prevents \"default for column cannot be cast automatically\" errors\n // Wrap in separate try-catch to ensure we continue even if no default exists\n try {\n logger.debug(\n `[Migration] → Dropping DEFAULT constraint on ${tableName}.message_server_id...`\n );\n await db.execute(\n sql.raw(`ALTER TABLE \"${tableName}\" ALTER COLUMN \"message_server_id\" DROP DEFAULT`)\n );\n logger.debug(`[Migration] ✓ Dropped DEFAULT constraint`);\n } catch {\n logger.debug(\n `[Migration] ⊘ No DEFAULT constraint to drop on ${tableName}.message_server_id`\n );\n }\n\n try {\n logger.debug(\n `[Migration] → Converting ${tableName}.message_server_id from text to uuid...`\n );\n // Use robust conversion: valid UUIDs are cast directly, others get md5 hash\n // This handles: empty strings, non-UUID text, uppercase UUIDs, NULL values\n await db.execute(\n sql.raw(`\n ALTER TABLE \"${tableName}\"\n ALTER COLUMN \"message_server_id\" TYPE uuid\n USING CASE\n WHEN \"message_server_id\" IS NULL THEN NULL\n WHEN \"message_server_id\" = '' THEN NULL\n WHEN \"message_server_id\" ~ '^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$'\n THEN \"message_server_id\"::uuid\n ELSE md5(\"message_server_id\")::uuid\n END\n `)\n );\n logger.debug(`[Migration] ✓ Converted ${tableName}.message_server_id to uuid`);\n } catch (convertError) {\n logger.warn(\n `[Migration] ⚠️ Could not convert ${tableName}.message_server_id to uuid: ${convertError}`\n );\n }\n }\n\n // If the column should be NOT NULL but has NULLs, we need to handle that\n // For channels, it's NOT NULL in the new schema\n if (tableName === \"channels\") {\n const nullCountResult = await db.execute(\n sql.raw(\n `SELECT COUNT(*) as count FROM \"${tableName}\" WHERE \"message_server_id\" IS NULL`\n )\n );\n const nullCount = nullCountResult.rows?.[0]?.count as string | undefined;\n if (nullCount && parseInt(nullCount, 10) > 0) {\n logger.warn(\n `[Migration] ⚠️ ${tableName} has ${nullCount} rows with NULL message_server_id - these will be deleted`\n );\n await db.execute(\n sql.raw(`DELETE FROM \"${tableName}\" WHERE \"message_server_id\" IS NULL`)\n );\n logger.debug(\n `[Migration] ✓ Deleted ${nullCount} rows with NULL message_server_id from ${tableName}`\n );\n }\n\n // Make it NOT NULL\n logger.debug(`[Migration] → Making ${tableName}.message_server_id NOT NULL...`);\n await db.execute(\n sql.raw(`ALTER TABLE \"${tableName}\" ALTER COLUMN \"message_server_id\" SET NOT NULL`)\n );\n logger.debug(`[Migration] ✓ Set ${tableName}.message_server_id NOT NULL`);\n }\n } else if (serverId && messageServerId) {\n // Both exist → just drop the old column\n logger.debug(`[Migration] → ${tableName} has both columns, dropping ${oldColumnName}...`);\n await db.execute(\n sql.raw(`ALTER TABLE \"${tableName}\" DROP COLUMN \"${oldColumnName}\" CASCADE`)\n );\n logger.debug(`[Migration] ✓ Dropped ${tableName}.${oldColumnName}`);\n } else if (!serverId && messageServerId) {\n // Only message_server_id exists - check if it needs type conversion from TEXT to UUID\n // This handles idempotency when migration partially ran before rollback\n if (messageServerId.data_type === \"text\") {\n logger.debug(\n `[Migration] → ${tableName}.message_server_id exists but is TEXT, needs UUID conversion...`\n );\n\n // CRITICAL: Drop DEFAULT constraint before type conversion\n // This prevents \"default for column cannot be cast automatically\" errors\n logger.debug(\n `[Migration] → Dropping DEFAULT constraint on ${tableName}.message_server_id...`\n );\n await db.execute(\n sql.raw(`ALTER TABLE \"${tableName}\" ALTER COLUMN \"message_server_id\" DROP DEFAULT`)\n );\n logger.debug(`[Migration] ✓ Dropped DEFAULT constraint`);\n\n // Convert TEXT to UUID using MD5 hash for non-UUID text values\n // This creates deterministic UUIDs from text values, preserving data\n logger.debug(\n `[Migration] → Converting ${tableName}.message_server_id from text to uuid (generating UUIDs from text)...`\n );\n await db.execute(\n sql.raw(`\n ALTER TABLE \"${tableName}\"\n ALTER COLUMN \"message_server_id\" TYPE uuid\n USING CASE\n WHEN \"message_server_id\" ~ '^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$'\n THEN \"message_server_id\"::uuid\n ELSE md5(\"message_server_id\")::uuid\n END\n `)\n );\n logger.debug(`[Migration] ✓ Converted ${tableName}.message_server_id to uuid`);\n } else {\n logger.debug(`[Migration] ⊘ ${tableName}.message_server_id already UUID, skipping`);\n }\n } else {\n logger.debug(`[Migration] ⊘ ${tableName} already migrated, skipping`);\n }\n } catch (error) {\n logger.warn(`[Migration] ⚠️ Error migrating ${tableName}.server_id: ${error}`);\n }\n }\n\n // Drop ALL remaining server_id columns (will be re-added by RLS after migrations)\n // This prevents RuntimeMigrator from seeing them and trying to drop them\n // EXCEPT for tables where server_id is part of the schema (like agents, server_agents)\n logger.debug(\"[Migration] → Dropping all remaining RLS-managed server_id columns...\");\n try {\n const serverIdColumnsResult = await db.execute(sql`\n SELECT table_name\n FROM information_schema.columns\n WHERE table_schema = 'public'\n AND column_name = 'server_id'\n AND table_name NOT IN (\n 'servers', -- server_id is the primary key\n 'agents', -- server_id is in the schema (for RLS)\n 'channels', -- already handled above\n 'worlds', -- already handled above\n 'rooms', -- already handled above\n 'server_agents', -- server_id is part of composite key\n 'drizzle_migrations',\n '__drizzle_migrations'\n )\n ORDER BY table_name\n `);\n\n const tablesToClean = serverIdColumnsResult.rows || [];\n logger.debug(`[Migration] → Found ${tablesToClean.length} tables with server_id columns`);\n\n for (const row of tablesToClean) {\n const tableName = row.table_name as string;\n try {\n await db.execute(\n sql.raw(`ALTER TABLE \"${tableName}\" DROP COLUMN IF EXISTS server_id CASCADE`)\n );\n logger.debug(`[Migration] ✓ Dropped server_id from ${tableName}`);\n } catch (_error) {\n logger.debug(`[Migration] ⊘ Could not drop server_id from ${tableName}`);\n }\n }\n } catch (_error) {\n logger.debug(\"[Migration] ⊘ Could not drop server_id columns (may not have permissions)\");\n }\n\n // Special handling for agents table: rename owner_id → server_id\n // v1.6.4 had owner_id, v1.6.5 changed it to server_id\n logger.debug(\"[Migration] → Checking agents.owner_id → server_id rename...\");\n try {\n const agentsColumnsResult = await db.execute(sql`\n SELECT column_name\n FROM information_schema.columns\n WHERE table_schema = 'public'\n AND table_name = 'agents'\n AND column_name IN ('owner_id', 'server_id')\n ORDER BY column_name\n `);\n\n const agentsColumns = getRows<ColumnInfoRow>(agentsColumnsResult);\n const hasOwnerId = agentsColumns.some((c) => c.column_name === \"owner_id\");\n const hasServerId = agentsColumns.some((c) => c.column_name === \"server_id\");\n\n if (hasOwnerId && !hasServerId) {\n // Rename owner_id → server_id\n logger.debug(\"[Migration] → Renaming agents.owner_id to server_id...\");\n await db.execute(sql.raw(`ALTER TABLE \"agents\" RENAME COLUMN \"owner_id\" TO \"server_id\"`));\n logger.debug(\"[Migration] ✓ Renamed agents.owner_id → server_id\");\n } else if (hasOwnerId && hasServerId) {\n // Both exist - drop owner_id (data should be in server_id)\n logger.debug(\"[Migration] → Both owner_id and server_id exist, dropping owner_id...\");\n await db.execute(sql.raw(`ALTER TABLE \"agents\" DROP COLUMN \"owner_id\" CASCADE`));\n logger.debug(\"[Migration] ✓ Dropped agents.owner_id\");\n } else {\n logger.debug(\"[Migration] ⊘ agents table already has server_id (or no owner_id), skipping\");\n }\n } catch (_error) {\n logger.debug(\"[Migration] ⊘ Could not check/migrate agents.owner_id\");\n }\n\n // Migrate data from obsolete 'owners' table to 'servers' (if owners exists)\n // v1.6.4 used owners table, v1.6.5+ uses servers table\n logger.debug(\"[Migration] → Checking for owners → servers data migration...\");\n try {\n const ownersTableResult = await db.execute(sql`\n SELECT table_name\n FROM information_schema.tables\n WHERE table_schema = 'public'\n AND table_name = 'owners'\n `);\n\n if (ownersTableResult.rows && ownersTableResult.rows.length > 0) {\n // First, ensure servers table exists\n logger.debug(\"[Migration] → Ensuring servers table exists...\");\n await db.execute(\n sql.raw(`\n CREATE TABLE IF NOT EXISTS \"servers\" (\n \"id\" uuid PRIMARY KEY,\n \"created_at\" timestamp with time zone DEFAULT now() NOT NULL,\n \"updated_at\" timestamp with time zone DEFAULT now() NOT NULL\n )\n `)\n );\n\n // Migrate data from owners to servers (if any)\n logger.debug(\"[Migration] → Migrating owners data to servers...\");\n await db.execute(\n sql.raw(`\n INSERT INTO \"servers\" (\"id\", \"created_at\", \"updated_at\")\n SELECT \"id\", COALESCE(\"created_at\", now()), COALESCE(\"updated_at\", now())\n FROM \"owners\"\n ON CONFLICT (\"id\") DO NOTHING\n `)\n );\n logger.debug(\"[Migration] ✓ Migrated owners data to servers\");\n\n // Now safe to drop owners table\n logger.debug(\"[Migration] → Dropping obsolete owners table...\");\n await db.execute(sql.raw(`DROP TABLE IF EXISTS \"owners\" CASCADE`));\n logger.debug(\"[Migration] ✓ Dropped obsolete owners table\");\n } else {\n logger.debug(\"[Migration] ⊘ owners table not found, skipping\");\n }\n } catch (error) {\n logger.warn(`[Migration] ⚠️ Could not migrate owners → servers: ${error}`);\n }\n\n // Special handling for server_agents → message_server_agents rename\n // This aligns with the server_id → message_server_id naming convention\n logger.debug(\"[Migration] → Checking server_agents table rename...\");\n try {\n const tablesResult = await db.execute(sql`\n SELECT table_name\n FROM information_schema.tables\n WHERE table_schema = 'public'\n AND table_name IN ('server_agents', 'message_server_agents')\n ORDER BY table_name\n `);\n\n const tables = getRows<TableInfoRow>(tablesResult);\n const hasServerAgents = tables.some((t) => t.table_name === \"server_agents\");\n const hasMessageServerAgents = tables.some((t) => t.table_name === \"message_server_agents\");\n\n if (hasServerAgents && !hasMessageServerAgents) {\n // Rename server_agents → message_server_agents\n logger.debug(\"[Migration] → Renaming server_agents to message_server_agents...\");\n await db.execute(sql.raw(`ALTER TABLE \"server_agents\" RENAME TO \"message_server_agents\"`));\n logger.debug(\"[Migration] ✓ Renamed server_agents → message_server_agents\");\n\n // Now rename server_id column → message_server_id\n logger.debug(\n \"[Migration] → Renaming message_server_agents.server_id to message_server_id...\"\n );\n await db.execute(\n sql.raw(\n `ALTER TABLE \"message_server_agents\" RENAME COLUMN \"server_id\" TO \"message_server_id\"`\n )\n );\n logger.debug(\"[Migration] ✓ Renamed message_server_agents.server_id → message_server_id\");\n } else if (!hasServerAgents && !hasMessageServerAgents) {\n // Neither table exists - RuntimeMigrator will create message_server_agents\n logger.debug(\"[Migration] ⊘ No server_agents table to migrate\");\n } else if (hasMessageServerAgents) {\n // Check if it has the columns and rename if needed\n logger.debug(\"[Migration] → Checking message_server_agents columns...\");\n const columnsResult = await db.execute(sql`\n SELECT column_name\n FROM information_schema.columns\n WHERE table_schema = 'public'\n AND table_name = 'message_server_agents'\n AND column_name IN ('server_id', 'message_server_id')\n ORDER BY column_name\n `);\n\n const columns = getRows<ColumnInfoRow>(columnsResult);\n const hasServerId = columns.some((c) => c.column_name === \"server_id\");\n const hasMessageServerId = columns.some((c) => c.column_name === \"message_server_id\");\n\n if (hasServerId && !hasMessageServerId) {\n // Rename server_id → message_server_id\n logger.debug(\n \"[Migration] → Renaming message_server_agents.server_id to message_server_id...\"\n );\n await db.execute(\n sql.raw(\n `ALTER TABLE \"message_server_agents\" RENAME COLUMN \"server_id\" TO \"message_server_id\"`\n )\n );\n logger.debug(\"[Migration] ✓ Renamed message_server_agents.server_id → message_server_id\");\n } else if (!hasServerId && !hasMessageServerId) {\n // Table exists but doesn't have either column - truncate it\n logger.debug(\n \"[Migration] → message_server_agents exists without required columns, truncating...\"\n );\n await db.execute(sql`TRUNCATE TABLE message_server_agents CASCADE`);\n logger.debug(\"[Migration] ✓ Truncated message_server_agents\");\n } else {\n logger.debug(\"[Migration] ⊘ message_server_agents already has correct schema\");\n }\n }\n } catch (_error) {\n logger.debug(\"[Migration] ⊘ Could not check/migrate server_agents table\");\n }\n\n // Special handling for channel_participants: rename userId → entityId\n // This handles the migration from the old userId column to the new entityId column\n logger.debug(\"[Migration] → Checking channel_participants table...\");\n try {\n const columnsResult = await db.execute(sql`\n SELECT column_name\n FROM information_schema.columns\n WHERE table_schema = 'public'\n AND table_name = 'channel_participants'\n AND column_name IN ('user_id', 'entity_id')\n ORDER BY column_name\n `);\n\n const columns = getRows<ColumnInfoRow>({ rows: columnsResult.rows || [] });\n const hasUserId = columns.some((c) => c.column_name === \"user_id\");\n const hasEntityId = columns.some((c) => c.column_name === \"entity_id\");\n\n if (hasUserId && !hasEntityId) {\n // Rename user_id → entity_id\n logger.debug(\"[Migration] → Renaming channel_participants.user_id to entity_id...\");\n await db.execute(\n sql.raw(`ALTER TABLE \"channel_participants\" RENAME COLUMN \"user_id\" TO \"entity_id\"`)\n );\n logger.debug(\"[Migration] ✓ Renamed channel_participants.user_id → entity_id\");\n } else if (!hasUserId && !hasEntityId) {\n // Table exists but has neither column - truncate it so RuntimeMigrator can add entity_id\n logger.debug(\n \"[Migration] → channel_participants exists without entity_id or user_id, truncating...\"\n );\n await db.execute(sql`TRUNCATE TABLE channel_participants CASCADE`);\n logger.debug(\"[Migration] ✓ Truncated channel_participants\");\n } else {\n logger.debug(\"[Migration] ⊘ channel_participants already has entity_id column\");\n }\n } catch (_error) {\n logger.debug(\"[Migration] ⊘ Could not check/migrate channel_participants\");\n }\n\n // Drop ALL regular indexes (not PK or unique constraints) to avoid conflicts\n // The RuntimeMigrator will recreate them based on the schema\n logger.debug(\"[Migration] → Discovering and dropping all regular indexes...\");\n try {\n const indexesResult = await db.execute(sql`\n SELECT i.relname AS index_name\n FROM pg_index idx\n JOIN pg_class i ON i.oid = idx.indexrelid\n JOIN pg_class c ON c.oid = idx.indrelid\n JOIN pg_namespace n ON n.oid = c.relnamespace\n LEFT JOIN pg_constraint con ON con.conindid = idx.indexrelid\n WHERE n.nspname = 'public'\n AND NOT idx.indisprimary -- Not a primary key\n AND con.contype IS NULL -- Not a constraint (unique, etc)\n ORDER BY i.relname\n `);\n\n const indexesToDrop = indexesResult.rows || [];\n logger.debug(`[Migration] → Found ${indexesToDrop.length} indexes to drop`);\n\n for (const row of indexesToDrop) {\n const indexName = row.index_name as string;\n try {\n await db.execute(sql.raw(`DROP INDEX IF EXISTS \"${indexName}\"`));\n logger.debug(`[Migration] ✓ Dropped index ${indexName}`);\n } catch (_error) {\n logger.debug(`[Migration] ⊘ Could not drop index ${indexName}`);\n }\n }\n } catch (_error) {\n logger.debug(\"[Migration] ⊘ Could not drop indexes (may not have permissions)\");\n }\n\n // =========================================================================\n // SMOOTH MIGRATION: camelCase → snake_case column renames\n // This ensures a non-destructive transition from v1.6.4 to v1.6.5+\n // All data is preserved through RENAME COLUMN operations\n // This section can be removed once all deployments have been migrated\n // =========================================================================\n logger.debug(\"[Migration] → Starting camelCase → snake_case column renames...\");\n\n const columnRenames = [\n // rooms table\n { table: \"rooms\", from: \"agentId\", to: \"agent_id\" },\n { table: \"rooms\", from: \"worldId\", to: \"world_id\" },\n { table: \"rooms\", from: \"channelId\", to: \"channel_id\" },\n { table: \"rooms\", from: \"createdAt\", to: \"created_at\" },\n\n // worlds table\n { table: \"worlds\", from: \"agentId\", to: \"agent_id\" },\n { table: \"worlds\", from: \"createdAt\", to: \"created_at\" },\n\n // memories table\n { table: \"memories\", from: \"createdAt\", to: \"created_at\" },\n { table: \"memories\", from: \"entityId\", to: \"entity_id\" },\n { table: \"memories\", from: \"agentId\", to: \"agent_id\" },\n { table: \"memories\", from: \"roomId\", to: \"room_id\" },\n { table: \"memories\", from: \"worldId\", to: \"world_id\" },\n\n // components table\n { table: \"components\", from: \"entityId\", to: \"entity_id\" },\n { table: \"components\", from: \"agentId\", to: \"agent_id\" },\n { table: \"components\", from: \"roomId\", to: \"room_id\" },\n { table: \"components\", from: \"worldId\", to: \"world_id\" },\n { table: \"components\", from: \"sourceEntityId\", to: \"source_entity_id\" },\n { table: \"components\", from: \"createdAt\", to: \"created_at\" },\n\n // participants table\n { table: \"participants\", from: \"entityId\", to: \"entity_id\" },\n { table: \"participants\", from: \"roomId\", to: \"room_id\" },\n { table: \"participants\", from: \"agentId\", to: \"agent_id\" },\n { table: \"participants\", from: \"roomState\", to: \"room_state\" },\n { table: \"participants\", from: \"createdAt\", to: \"created_at\" },\n\n // relationships table\n {\n table: \"relationships\",\n from: \"sourceEntityId\",\n to: \"source_entity_id\",\n },\n {\n table: \"relationships\",\n from: \"targetEntityId\",\n to: \"target_entity_id\",\n },\n { table: \"relationships\", from: \"agentId\", to: \"agent_id\" },\n { table: \"relationships\", from: \"createdAt\", to: \"created_at\" },\n\n // logs table\n { table: \"logs\", from: \"entityId\", to: \"entity_id\" },\n { table: \"logs\", from: \"roomId\", to: \"room_id\" },\n { table: \"logs\", from: \"createdAt\", to: \"created_at\" },\n\n // tasks table\n { table: \"tasks\", from: \"roomId\", to: \"room_id\" },\n { table: \"tasks\", from: \"worldId\", to: \"world_id\" },\n { table: \"tasks\", from: \"entityId\", to: \"entity_id\" },\n { table: \"tasks\", from: \"createdAt\", to: \"created_at\" },\n { table: \"tasks\", from: \"updatedAt\", to: \"updated_at\" },\n\n // agents table\n { table: \"agents\", from: \"createdAt\", to: \"created_at\" },\n { table: \"agents\", from: \"updatedAt\", to: \"updated_at\" },\n\n // entities table\n { table: \"entities\", from: \"agentId\", to: \"agent_id\" },\n { table: \"entities\", from: \"createdAt\", to: \"created_at\" },\n\n // embeddings table\n { table: \"embeddings\", from: \"memoryId\", to: \"memory_id\" },\n { table: \"embeddings\", from: \"createdAt\", to: \"created_at\" },\n\n // cache table\n { table: \"cache\", from: \"agentId\", to: \"agent_id\" },\n { table: \"cache\", from: \"createdAt\", to: \"created_at\" },\n { table: \"cache\", from: \"expiresAt\", to: \"expires_at\" },\n ];\n\n for (const rename of columnRenames) {\n try {\n // Check if table exists first\n const tableExistsResult = await db.execute(sql`\n SELECT 1 FROM information_schema.tables\n WHERE table_schema = 'public' AND table_name = ${rename.table}\n `);\n\n if (!tableExistsResult.rows || tableExistsResult.rows.length === 0) {\n // Table doesn't exist yet, skip\n continue;\n }\n\n // Check which columns exist\n const columnsResult = await db.execute(sql`\n SELECT column_name\n FROM information_schema.columns\n WHERE table_schema = 'public'\n AND table_name = ${rename.table}\n AND column_name IN (${rename.from}, ${rename.to})\n ORDER BY column_name\n `);\n\n const columns = getRows<ColumnInfoRow>(columnsResult);\n const hasOldColumn = columns.some((c) => c.column_name === rename.from);\n const hasNewColumn = columns.some((c) => c.column_name === rename.to);\n\n if (hasOldColumn && !hasNewColumn) {\n // Old column exists, new doesn't → RENAME (preserves data!)\n logger.debug(`[Migration] → Renaming ${rename.table}.${rename.from} to ${rename.to}...`);\n await db.execute(\n sql.raw(\n `ALTER TABLE \"${rename.table}\" RENAME COLUMN \"${rename.from}\" TO \"${rename.to}\"`\n )\n );\n logger.debug(`[Migration] ✓ Renamed ${rename.table}.${rename.from} → ${rename.to}`);\n } else if (hasOldColumn && hasNewColumn) {\n // Both exist → drop old (data should be in new already)\n logger.debug(\n `[Migration] → Both columns exist, dropping ${rename.table}.${rename.from}...`\n );\n await db.execute(\n sql.raw(`ALTER TABLE \"${rename.table}\" DROP COLUMN \"${rename.from}\" CASCADE`)\n );\n logger.debug(`[Migration] ✓ Dropped ${rename.table}.${rename.from}`);\n }\n // If only new column exists or neither exists, nothing to do\n } catch (error) {\n // Log but continue - table might not exist yet or column might already be renamed\n logger.debug(`[Migration] ⊘ Could not process ${rename.table}.${rename.from}: ${error}`);\n }\n }\n\n logger.debug(\"[Migration] ✓ Completed camelCase → snake_case column renames\");\n\n logger.info(\"[Migration] ✓ Migration complete - pre-1.6.5 → 1.6.5+ schema migration finished\");\n } catch (error) {\n // Re-throw errors to prevent RuntimeMigrator from running on broken state\n logger.error(\"[Migration] Migration failed:\", String(error));\n throw error;\n }\n}\n",
8
+ "import { type IDatabaseAdapter, logger } from \"@elizaos/core\";\nimport { sql } from \"drizzle-orm\";\nimport { getDb } from \"./types\";\n\n// Column info row for schema introspection queries\ninterface ColumnInfoRow {\n column_name: string;\n data_type: string;\n}\n\n// Table info row for schema introspection queries\ninterface TableInfoRow {\n table_name: string;\n}\n\n/**\n * Type-safe extraction of rows from SQL query results.\n */\nfunction getRows<T>(result: { rows: unknown[] }): T[] {\n return result.rows as T[];\n}\n\n/**\n * TEMPORARY MIGRATION: pre-1.6.5 → 1.6.5+ schema migration\n *\n * This migration runs automatically on startup and is idempotent.\n * It handles the migration from Owner RLS to Server RLS + Entity RLS, including:\n * - Disabling old RLS policies temporarily\n * - Renaming server_id → message_server_id in channels, worlds, rooms\n * - Converting TEXT → UUID where needed\n * - Dropping old server_id columns for RLS\n * - Cleaning up indexes\n *\n * @param adapter - Database adapter\n */\nexport async function migrateToEntityRLS(adapter: IDatabaseAdapter): Promise<void> {\n const db = getDb(adapter);\n\n // Detect database type - skip PostgreSQL-specific migrations for SQLite\n try {\n await db.execute(sql`SELECT 1 FROM pg_tables LIMIT 1`);\n } catch {\n // Not PostgreSQL (likely SQLite)\n logger.debug(\"[Migration] ⊘ Not PostgreSQL, skipping PostgreSQL-specific migrations\");\n return;\n }\n\n // Check if schema migration has already been completed\n // We use the presence of snake_case columns as a marker\n let schemaAlreadyMigrated = false;\n try {\n const migrationCheck = await db.execute(sql`\n SELECT column_name FROM information_schema.columns\n WHERE table_schema = 'public'\n AND table_name = 'rooms'\n AND column_name = 'agent_id'\n `);\n\n if (migrationCheck.rows && migrationCheck.rows.length > 0) {\n // Migration already completed - rooms.agent_id exists (snake_case)\n schemaAlreadyMigrated = true;\n logger.debug(\"[Migration] ⊘ Schema already migrated (snake_case columns exist)\");\n }\n } catch {\n // Table might not exist yet, continue with migration\n logger.debug(\"[Migration] → rooms table not found, will be created by RuntimeMigrator\");\n return; // Let RuntimeMigrator create fresh tables\n }\n\n // If schema is already migrated, check if we need to clean up RLS\n // Only disable RLS if ENABLE_DATA_ISOLATION is NOT true (user disabled isolation)\n // If ENABLE_DATA_ISOLATION=true, keep RLS as-is - migration-service.ts will ensure proper config\n if (schemaAlreadyMigrated) {\n const dataIsolationEnabled = process.env.ENABLE_DATA_ISOLATION === \"true\";\n\n if (dataIsolationEnabled) {\n // RLS should stay enabled - no need to disable/re-enable cycle\n // migration-service.ts ensures RLS is properly configured via idempotent calls\n logger.debug(\"[Migration] ⊘ Schema already migrated, RLS enabled - nothing to do\");\n return;\n }\n\n // User disabled data isolation - clean up RLS if it was previously enabled\n logger.debug(\"[Migration] → Schema migrated but RLS disabled, cleaning up...\");\n\n try {\n const tablesWithRls = await db.execute(sql`\n SELECT c.relname as tablename\n FROM pg_class c\n JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE n.nspname = 'public'\n AND c.relkind = 'r'\n AND c.relrowsecurity = true\n ORDER BY c.relname\n `);\n\n if (tablesWithRls.rows && tablesWithRls.rows.length > 0) {\n for (const row of tablesWithRls.rows) {\n const tableName = row.tablename as string;\n try {\n await db.execute(sql.raw(`ALTER TABLE \"${tableName}\" DISABLE ROW LEVEL SECURITY`));\n } catch {\n // Ignore errors\n }\n }\n logger.debug(`[Migration] ✓ RLS cleanup completed (${tablesWithRls.rows.length} tables)`);\n } else {\n logger.debug(\"[Migration] ⊘ No tables with RLS to clean up\");\n }\n } catch {\n logger.debug(\"[Migration] ⊘ Could not perform RLS cleanup\");\n }\n\n return;\n }\n\n logger.info(\"[Migration] Starting pre-1.6.5 → 1.6.5+ schema migration...\");\n\n try {\n // Clear RuntimeMigrator snapshot cache to force fresh introspection\n // This ensures the snapshot matches the current database state after our migrations\n logger.debug(\"[Migration] → Clearing RuntimeMigrator snapshot cache...\");\n try {\n await db.execute(\n sql`DELETE FROM migrations._snapshots WHERE plugin_name = '@elizaos/plugin-sql'`\n );\n logger.debug(\"[Migration] ✓ Snapshot cache cleared\");\n } catch (_error) {\n // If migrations schema doesn't exist yet, that's fine - no cache to clear\n logger.debug(\"[Migration] ⊘ No snapshot cache to clear (migrations schema not yet created)\");\n }\n\n // Disable RLS only on tables that have it enabled\n // RLS will be re-implemented properly later\n logger.debug(\"[Migration] → Checking for Row Level Security to disable...\");\n try {\n const tablesWithRls = await db.execute(sql`\n SELECT c.relname as tablename\n FROM pg_class c\n JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE n.nspname = 'public'\n AND c.relkind = 'r'\n AND c.relrowsecurity = true\n ORDER BY c.relname\n `);\n\n if (tablesWithRls.rows && tablesWithRls.rows.length > 0) {\n for (const row of tablesWithRls.rows) {\n const tableName = row.tablename as string;\n try {\n await db.execute(sql.raw(`ALTER TABLE \"${tableName}\" DISABLE ROW LEVEL SECURITY`));\n logger.debug(`[Migration] ✓ Disabled RLS on ${tableName}`);\n } catch (_error) {\n logger.debug(`[Migration] ⊘ Could not disable RLS on ${tableName}`);\n }\n }\n } else {\n logger.debug(\"[Migration] ⊘ No tables with RLS enabled\");\n }\n } catch (_error) {\n logger.debug(\"[Migration] ⊘ Could not check RLS (may not have permissions)\");\n }\n\n // Special handling for tables where serverId/server_id needs to become message_server_id\n // v1.6.4 had: rooms.serverId (TEXT camelCase), worlds.serverId (TEXT camelCase), channels.server_id (UUID)\n // Current: message_server_id (UUID) in all tables\n //\n // STRATEGY: Rename serverId/server_id to message_server_id preserving data\n logger.debug(\"[Migration] → Handling serverId/server_id → message_server_id migrations...\");\n\n const tablesToMigrate = [\"channels\", \"worlds\", \"rooms\"];\n\n for (const tableName of tablesToMigrate) {\n try {\n // Check for both camelCase (serverId) and snake_case (server_id) columns\n const columnsResult = await db.execute(sql`\n SELECT column_name, data_type, is_nullable\n FROM information_schema.columns\n WHERE table_schema = 'public'\n AND table_name = ${tableName}\n AND column_name IN ('server_id', 'serverId', 'message_server_id')\n ORDER BY column_name\n `);\n\n const columns = getRows<ColumnInfoRow>(columnsResult);\n const serverIdSnake = columns.find((c) => c.column_name === \"server_id\");\n const serverIdCamel = columns.find((c) => c.column_name === \"serverId\");\n const messageServerId = columns.find((c) => c.column_name === \"message_server_id\");\n\n // Use whichever old column exists (prefer snake_case for channels)\n const serverId = serverIdSnake || serverIdCamel;\n const oldColumnName = serverIdSnake ? \"server_id\" : \"serverId\";\n\n if (serverId && !messageServerId) {\n // Old column exists → rename it to message_server_id\n logger.debug(\n `[Migration] → Renaming ${tableName}.${oldColumnName} to message_server_id...`\n );\n await db.execute(\n sql.raw(\n `ALTER TABLE \"${tableName}\" RENAME COLUMN \"${oldColumnName}\" TO \"message_server_id\"`\n )\n );\n logger.debug(`[Migration] ✓ Renamed ${tableName}.${oldColumnName} → message_server_id`);\n\n // If the column was text, try to convert to UUID (if data is UUID-compatible)\n if (serverId.data_type === \"text\") {\n // CRITICAL: Drop DEFAULT constraint before type conversion\n // This prevents \"default for column cannot be cast automatically\" errors\n // Wrap in separate try-catch to ensure we continue even if no default exists\n try {\n logger.debug(\n `[Migration] → Dropping DEFAULT constraint on ${tableName}.message_server_id...`\n );\n await db.execute(\n sql.raw(`ALTER TABLE \"${tableName}\" ALTER COLUMN \"message_server_id\" DROP DEFAULT`)\n );\n logger.debug(`[Migration] ✓ Dropped DEFAULT constraint`);\n } catch {\n logger.debug(\n `[Migration] ⊘ No DEFAULT constraint to drop on ${tableName}.message_server_id`\n );\n }\n\n try {\n logger.debug(\n `[Migration] → Converting ${tableName}.message_server_id from text to uuid...`\n );\n // Use robust conversion: valid UUIDs are cast directly, others get md5 hash\n // This handles: empty strings, non-UUID text, uppercase UUIDs, NULL values\n await db.execute(\n sql.raw(`\n ALTER TABLE \"${tableName}\"\n ALTER COLUMN \"message_server_id\" TYPE uuid\n USING CASE\n WHEN \"message_server_id\" IS NULL THEN NULL\n WHEN \"message_server_id\" = '' THEN NULL\n WHEN \"message_server_id\" ~ '^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$'\n THEN \"message_server_id\"::uuid\n ELSE md5(\"message_server_id\")::uuid\n END\n `)\n );\n logger.debug(`[Migration] ✓ Converted ${tableName}.message_server_id to uuid`);\n } catch (convertError) {\n logger.warn(\n `[Migration] ⚠️ Could not convert ${tableName}.message_server_id to uuid: ${convertError}`\n );\n }\n }\n\n // If the column should be NOT NULL but has NULLs, we need to handle that\n // For channels, it's NOT NULL in the new schema\n if (tableName === \"channels\") {\n const nullCountResult = await db.execute(\n sql.raw(\n `SELECT COUNT(*) as count FROM \"${tableName}\" WHERE \"message_server_id\" IS NULL`\n )\n );\n const nullCount = nullCountResult.rows?.[0]?.count as string | undefined;\n if (nullCount && parseInt(nullCount, 10) > 0) {\n logger.warn(\n `[Migration] ⚠️ ${tableName} has ${nullCount} rows with NULL message_server_id - these will be deleted`\n );\n await db.execute(\n sql.raw(`DELETE FROM \"${tableName}\" WHERE \"message_server_id\" IS NULL`)\n );\n logger.debug(\n `[Migration] ✓ Deleted ${nullCount} rows with NULL message_server_id from ${tableName}`\n );\n }\n\n // Make it NOT NULL\n logger.debug(`[Migration] → Making ${tableName}.message_server_id NOT NULL...`);\n await db.execute(\n sql.raw(`ALTER TABLE \"${tableName}\" ALTER COLUMN \"message_server_id\" SET NOT NULL`)\n );\n logger.debug(`[Migration] ✓ Set ${tableName}.message_server_id NOT NULL`);\n }\n } else if (serverId && messageServerId) {\n // Both exist → just drop the old column\n logger.debug(`[Migration] → ${tableName} has both columns, dropping ${oldColumnName}...`);\n await db.execute(\n sql.raw(`ALTER TABLE \"${tableName}\" DROP COLUMN \"${oldColumnName}\" CASCADE`)\n );\n logger.debug(`[Migration] ✓ Dropped ${tableName}.${oldColumnName}`);\n } else if (!serverId && messageServerId) {\n // Only message_server_id exists - check if it needs type conversion from TEXT to UUID\n // This handles idempotency when migration partially ran before rollback\n if (messageServerId.data_type === \"text\") {\n logger.debug(\n `[Migration] → ${tableName}.message_server_id exists but is TEXT, needs UUID conversion...`\n );\n\n // CRITICAL: Drop DEFAULT constraint before type conversion\n // This prevents \"default for column cannot be cast automatically\" errors\n logger.debug(\n `[Migration] → Dropping DEFAULT constraint on ${tableName}.message_server_id...`\n );\n await db.execute(\n sql.raw(`ALTER TABLE \"${tableName}\" ALTER COLUMN \"message_server_id\" DROP DEFAULT`)\n );\n logger.debug(`[Migration] ✓ Dropped DEFAULT constraint`);\n\n // Convert TEXT to UUID using MD5 hash for non-UUID text values\n // This creates deterministic UUIDs from text values, preserving data\n logger.debug(\n `[Migration] → Converting ${tableName}.message_server_id from text to uuid (generating UUIDs from text)...`\n );\n await db.execute(\n sql.raw(`\n ALTER TABLE \"${tableName}\"\n ALTER COLUMN \"message_server_id\" TYPE uuid\n USING CASE\n WHEN \"message_server_id\" ~ '^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$'\n THEN \"message_server_id\"::uuid\n ELSE md5(\"message_server_id\")::uuid\n END\n `)\n );\n logger.debug(`[Migration] ✓ Converted ${tableName}.message_server_id to uuid`);\n } else {\n logger.debug(`[Migration] ⊘ ${tableName}.message_server_id already UUID, skipping`);\n }\n } else {\n logger.debug(`[Migration] ⊘ ${tableName} already migrated, skipping`);\n }\n } catch (error) {\n logger.warn(`[Migration] ⚠️ Error migrating ${tableName}.server_id: ${error}`);\n }\n }\n\n // Drop ALL remaining server_id columns (will be re-added by RLS after migrations)\n // This prevents RuntimeMigrator from seeing them and trying to drop them\n // EXCEPT for tables where server_id is part of the schema (like agents, server_agents)\n logger.debug(\"[Migration] → Dropping all remaining RLS-managed server_id columns...\");\n try {\n const serverIdColumnsResult = await db.execute(sql`\n SELECT table_name\n FROM information_schema.columns\n WHERE table_schema = 'public'\n AND column_name = 'server_id'\n AND table_name NOT IN (\n 'servers', -- server_id is the primary key\n 'agents', -- server_id is in the schema (for RLS)\n 'channels', -- already handled above\n 'worlds', -- already handled above\n 'rooms', -- already handled above\n 'server_agents', -- server_id is part of composite key\n 'drizzle_migrations',\n '__drizzle_migrations'\n )\n ORDER BY table_name\n `);\n\n const tablesToClean = serverIdColumnsResult.rows || [];\n logger.debug(`[Migration] → Found ${tablesToClean.length} tables with server_id columns`);\n\n for (const row of tablesToClean) {\n const tableName = row.table_name as string;\n try {\n await db.execute(\n sql.raw(`ALTER TABLE \"${tableName}\" DROP COLUMN IF EXISTS server_id CASCADE`)\n );\n logger.debug(`[Migration] ✓ Dropped server_id from ${tableName}`);\n } catch (_error) {\n logger.debug(`[Migration] ⊘ Could not drop server_id from ${tableName}`);\n }\n }\n } catch (_error) {\n logger.debug(\"[Migration] ⊘ Could not drop server_id columns (may not have permissions)\");\n }\n\n // Special handling for agents table: rename owner_id → server_id\n // v1.6.4 had owner_id, v1.6.5 changed it to server_id\n logger.debug(\"[Migration] → Checking agents.owner_id → server_id rename...\");\n try {\n const agentsColumnsResult = await db.execute(sql`\n SELECT column_name\n FROM information_schema.columns\n WHERE table_schema = 'public'\n AND table_name = 'agents'\n AND column_name IN ('owner_id', 'server_id')\n ORDER BY column_name\n `);\n\n const agentsColumns = getRows<ColumnInfoRow>(agentsColumnsResult);\n const hasOwnerId = agentsColumns.some((c) => c.column_name === \"owner_id\");\n const hasServerId = agentsColumns.some((c) => c.column_name === \"server_id\");\n\n if (hasOwnerId && !hasServerId) {\n // Rename owner_id → server_id\n logger.debug(\"[Migration] → Renaming agents.owner_id to server_id...\");\n await db.execute(sql.raw(`ALTER TABLE \"agents\" RENAME COLUMN \"owner_id\" TO \"server_id\"`));\n logger.debug(\"[Migration] ✓ Renamed agents.owner_id → server_id\");\n } else if (hasOwnerId && hasServerId) {\n // Both exist - drop owner_id (data should be in server_id)\n logger.debug(\"[Migration] → Both owner_id and server_id exist, dropping owner_id...\");\n await db.execute(sql.raw(`ALTER TABLE \"agents\" DROP COLUMN \"owner_id\" CASCADE`));\n logger.debug(\"[Migration] ✓ Dropped agents.owner_id\");\n } else {\n logger.debug(\"[Migration] ⊘ agents table already has server_id (or no owner_id), skipping\");\n }\n } catch (_error) {\n logger.debug(\"[Migration] ⊘ Could not check/migrate agents.owner_id\");\n }\n\n // Migrate data from obsolete 'owners' table to 'servers' (if owners exists)\n // v1.6.4 used owners table, v1.6.5+ uses servers table\n logger.debug(\"[Migration] → Checking for owners → servers data migration...\");\n try {\n const ownersTableResult = await db.execute(sql`\n SELECT table_name\n FROM information_schema.tables\n WHERE table_schema = 'public'\n AND table_name = 'owners'\n `);\n\n if (ownersTableResult.rows && ownersTableResult.rows.length > 0) {\n // First, ensure servers table exists\n logger.debug(\"[Migration] → Ensuring servers table exists...\");\n await db.execute(\n sql.raw(`\n CREATE TABLE IF NOT EXISTS \"servers\" (\n \"id\" uuid PRIMARY KEY,\n \"created_at\" timestamp with time zone DEFAULT now() NOT NULL,\n \"updated_at\" timestamp with time zone DEFAULT now() NOT NULL\n )\n `)\n );\n\n // Migrate data from owners to servers (if any)\n logger.debug(\"[Migration] → Migrating owners data to servers...\");\n await db.execute(\n sql.raw(`\n INSERT INTO \"servers\" (\"id\", \"created_at\", \"updated_at\")\n SELECT \"id\", COALESCE(\"created_at\", now()), COALESCE(\"updated_at\", now())\n FROM \"owners\"\n ON CONFLICT (\"id\") DO NOTHING\n `)\n );\n logger.debug(\"[Migration] ✓ Migrated owners data to servers\");\n\n // Now safe to drop owners table\n logger.debug(\"[Migration] → Dropping obsolete owners table...\");\n await db.execute(sql.raw(`DROP TABLE IF EXISTS \"owners\" CASCADE`));\n logger.debug(\"[Migration] ✓ Dropped obsolete owners table\");\n } else {\n logger.debug(\"[Migration] ⊘ owners table not found, skipping\");\n }\n } catch (error) {\n logger.warn(`[Migration] ⚠️ Could not migrate owners → servers: ${error}`);\n }\n\n // Special handling for server_agents → message_server_agents rename\n // This aligns with the server_id → message_server_id naming convention\n logger.debug(\"[Migration] → Checking server_agents table rename...\");\n try {\n const tablesResult = await db.execute(sql`\n SELECT table_name\n FROM information_schema.tables\n WHERE table_schema = 'public'\n AND table_name IN ('server_agents', 'message_server_agents')\n ORDER BY table_name\n `);\n\n const tables = getRows<TableInfoRow>(tablesResult);\n const hasServerAgents = tables.some((t) => t.table_name === \"server_agents\");\n const hasMessageServerAgents = tables.some((t) => t.table_name === \"message_server_agents\");\n\n if (hasServerAgents && !hasMessageServerAgents) {\n // Rename server_agents → message_server_agents\n logger.debug(\"[Migration] → Renaming server_agents to message_server_agents...\");\n await db.execute(sql.raw(`ALTER TABLE \"server_agents\" RENAME TO \"message_server_agents\"`));\n logger.debug(\"[Migration] ✓ Renamed server_agents → message_server_agents\");\n\n // Now rename server_id column → message_server_id\n logger.debug(\n \"[Migration] → Renaming message_server_agents.server_id to message_server_id...\"\n );\n await db.execute(\n sql.raw(\n `ALTER TABLE \"message_server_agents\" RENAME COLUMN \"server_id\" TO \"message_server_id\"`\n )\n );\n logger.debug(\"[Migration] ✓ Renamed message_server_agents.server_id → message_server_id\");\n } else if (!hasServerAgents && !hasMessageServerAgents) {\n // Neither table exists - RuntimeMigrator will create message_server_agents\n logger.debug(\"[Migration] ⊘ No server_agents table to migrate\");\n } else if (hasMessageServerAgents) {\n // Check if it has the columns and rename if needed\n logger.debug(\"[Migration] → Checking message_server_agents columns...\");\n const columnsResult = await db.execute(sql`\n SELECT column_name\n FROM information_schema.columns\n WHERE table_schema = 'public'\n AND table_name = 'message_server_agents'\n AND column_name IN ('server_id', 'message_server_id')\n ORDER BY column_name\n `);\n\n const columns = getRows<ColumnInfoRow>(columnsResult);\n const hasServerId = columns.some((c) => c.column_name === \"server_id\");\n const hasMessageServerId = columns.some((c) => c.column_name === \"message_server_id\");\n\n if (hasServerId && !hasMessageServerId) {\n // Rename server_id → message_server_id\n logger.debug(\n \"[Migration] → Renaming message_server_agents.server_id to message_server_id...\"\n );\n await db.execute(\n sql.raw(\n `ALTER TABLE \"message_server_agents\" RENAME COLUMN \"server_id\" TO \"message_server_id\"`\n )\n );\n logger.debug(\"[Migration] ✓ Renamed message_server_agents.server_id → message_server_id\");\n } else if (!hasServerId && !hasMessageServerId) {\n // Table exists but doesn't have either column - truncate it\n logger.debug(\n \"[Migration] → message_server_agents exists without required columns, truncating...\"\n );\n await db.execute(sql`TRUNCATE TABLE message_server_agents CASCADE`);\n logger.debug(\"[Migration] ✓ Truncated message_server_agents\");\n } else {\n logger.debug(\"[Migration] ⊘ message_server_agents already has correct schema\");\n }\n }\n } catch (_error) {\n logger.debug(\"[Migration] ⊘ Could not check/migrate server_agents table\");\n }\n\n // Special handling for channel_participants: rename userId → entityId\n // This handles the migration from the old userId column to the new entityId column\n logger.debug(\"[Migration] → Checking channel_participants table...\");\n try {\n const columnsResult = await db.execute(sql`\n SELECT column_name\n FROM information_schema.columns\n WHERE table_schema = 'public'\n AND table_name = 'channel_participants'\n AND column_name IN ('user_id', 'entity_id')\n ORDER BY column_name\n `);\n\n const columns = getRows<ColumnInfoRow>({\n rows: columnsResult.rows || [],\n });\n const hasUserId = columns.some((c) => c.column_name === \"user_id\");\n const hasEntityId = columns.some((c) => c.column_name === \"entity_id\");\n\n if (hasUserId && !hasEntityId) {\n // Rename user_id → entity_id\n logger.debug(\"[Migration] → Renaming channel_participants.user_id to entity_id...\");\n await db.execute(\n sql.raw(`ALTER TABLE \"channel_participants\" RENAME COLUMN \"user_id\" TO \"entity_id\"`)\n );\n logger.debug(\"[Migration] ✓ Renamed channel_participants.user_id → entity_id\");\n } else if (!hasUserId && !hasEntityId) {\n // Table exists but has neither column - truncate it so RuntimeMigrator can add entity_id\n logger.debug(\n \"[Migration] → channel_participants exists without entity_id or user_id, truncating...\"\n );\n await db.execute(sql`TRUNCATE TABLE channel_participants CASCADE`);\n logger.debug(\"[Migration] ✓ Truncated channel_participants\");\n } else {\n logger.debug(\"[Migration] ⊘ channel_participants already has entity_id column\");\n }\n } catch (_error) {\n logger.debug(\"[Migration] ⊘ Could not check/migrate channel_participants\");\n }\n\n // Drop ALL regular indexes (not PK or unique constraints) to avoid conflicts\n // The RuntimeMigrator will recreate them based on the schema\n logger.debug(\"[Migration] → Discovering and dropping all regular indexes...\");\n try {\n const indexesResult = await db.execute(sql`\n SELECT i.relname AS index_name\n FROM pg_index idx\n JOIN pg_class i ON i.oid = idx.indexrelid\n JOIN pg_class c ON c.oid = idx.indrelid\n JOIN pg_namespace n ON n.oid = c.relnamespace\n LEFT JOIN pg_constraint con ON con.conindid = idx.indexrelid\n WHERE n.nspname = 'public'\n AND NOT idx.indisprimary -- Not a primary key\n AND con.contype IS NULL -- Not a constraint (unique, etc)\n ORDER BY i.relname\n `);\n\n const indexesToDrop = indexesResult.rows || [];\n logger.debug(`[Migration] → Found ${indexesToDrop.length} indexes to drop`);\n\n for (const row of indexesToDrop) {\n const indexName = row.index_name as string;\n try {\n await db.execute(sql.raw(`DROP INDEX IF EXISTS \"${indexName}\"`));\n logger.debug(`[Migration] ✓ Dropped index ${indexName}`);\n } catch (_error) {\n logger.debug(`[Migration] ⊘ Could not drop index ${indexName}`);\n }\n }\n } catch (_error) {\n logger.debug(\"[Migration] ⊘ Could not drop indexes (may not have permissions)\");\n }\n\n // =========================================================================\n // SMOOTH MIGRATION: camelCase → snake_case column renames\n // This ensures a non-destructive transition from v1.6.4 to v1.6.5+\n // All data is preserved through RENAME COLUMN operations\n // This section can be removed once all deployments have been migrated\n // =========================================================================\n logger.debug(\"[Migration] → Starting camelCase → snake_case column renames...\");\n\n const columnRenames = [\n // rooms table\n { table: \"rooms\", from: \"agentId\", to: \"agent_id\" },\n { table: \"rooms\", from: \"worldId\", to: \"world_id\" },\n { table: \"rooms\", from: \"channelId\", to: \"channel_id\" },\n { table: \"rooms\", from: \"createdAt\", to: \"created_at\" },\n\n // worlds table\n { table: \"worlds\", from: \"agentId\", to: \"agent_id\" },\n { table: \"worlds\", from: \"createdAt\", to: \"created_at\" },\n\n // memories table\n { table: \"memories\", from: \"createdAt\", to: \"created_at\" },\n { table: \"memories\", from: \"entityId\", to: \"entity_id\" },\n { table: \"memories\", from: \"agentId\", to: \"agent_id\" },\n { table: \"memories\", from: \"roomId\", to: \"room_id\" },\n { table: \"memories\", from: \"worldId\", to: \"world_id\" },\n\n // components table\n { table: \"components\", from: \"entityId\", to: \"entity_id\" },\n { table: \"components\", from: \"agentId\", to: \"agent_id\" },\n { table: \"components\", from: \"roomId\", to: \"room_id\" },\n { table: \"components\", from: \"worldId\", to: \"world_id\" },\n { table: \"components\", from: \"sourceEntityId\", to: \"source_entity_id\" },\n { table: \"components\", from: \"createdAt\", to: \"created_at\" },\n\n // participants table\n { table: \"participants\", from: \"entityId\", to: \"entity_id\" },\n { table: \"participants\", from: \"roomId\", to: \"room_id\" },\n { table: \"participants\", from: \"agentId\", to: \"agent_id\" },\n { table: \"participants\", from: \"roomState\", to: \"room_state\" },\n { table: \"participants\", from: \"createdAt\", to: \"created_at\" },\n\n // relationships table\n {\n table: \"relationships\",\n from: \"sourceEntityId\",\n to: \"source_entity_id\",\n },\n {\n table: \"relationships\",\n from: \"targetEntityId\",\n to: \"target_entity_id\",\n },\n { table: \"relationships\", from: \"agentId\", to: \"agent_id\" },\n { table: \"relationships\", from: \"createdAt\", to: \"created_at\" },\n\n // logs table\n { table: \"logs\", from: \"entityId\", to: \"entity_id\" },\n { table: \"logs\", from: \"roomId\", to: \"room_id\" },\n { table: \"logs\", from: \"createdAt\", to: \"created_at\" },\n\n // tasks table\n { table: \"tasks\", from: \"roomId\", to: \"room_id\" },\n { table: \"tasks\", from: \"worldId\", to: \"world_id\" },\n { table: \"tasks\", from: \"entityId\", to: \"entity_id\" },\n { table: \"tasks\", from: \"createdAt\", to: \"created_at\" },\n { table: \"tasks\", from: \"updatedAt\", to: \"updated_at\" },\n\n // agents table\n { table: \"agents\", from: \"createdAt\", to: \"created_at\" },\n { table: \"agents\", from: \"updatedAt\", to: \"updated_at\" },\n\n // entities table\n { table: \"entities\", from: \"agentId\", to: \"agent_id\" },\n { table: \"entities\", from: \"createdAt\", to: \"created_at\" },\n\n // embeddings table\n { table: \"embeddings\", from: \"memoryId\", to: \"memory_id\" },\n { table: \"embeddings\", from: \"createdAt\", to: \"created_at\" },\n\n // cache table\n { table: \"cache\", from: \"agentId\", to: \"agent_id\" },\n { table: \"cache\", from: \"createdAt\", to: \"created_at\" },\n { table: \"cache\", from: \"expiresAt\", to: \"expires_at\" },\n ];\n\n for (const rename of columnRenames) {\n try {\n // Check if table exists first\n const tableExistsResult = await db.execute(sql`\n SELECT 1 FROM information_schema.tables\n WHERE table_schema = 'public' AND table_name = ${rename.table}\n `);\n\n if (!tableExistsResult.rows || tableExistsResult.rows.length === 0) {\n // Table doesn't exist yet, skip\n continue;\n }\n\n // Check which columns exist\n const columnsResult = await db.execute(sql`\n SELECT column_name\n FROM information_schema.columns\n WHERE table_schema = 'public'\n AND table_name = ${rename.table}\n AND column_name IN (${rename.from}, ${rename.to})\n ORDER BY column_name\n `);\n\n const columns = getRows<ColumnInfoRow>(columnsResult);\n const hasOldColumn = columns.some((c) => c.column_name === rename.from);\n const hasNewColumn = columns.some((c) => c.column_name === rename.to);\n\n if (hasOldColumn && !hasNewColumn) {\n // Old column exists, new doesn't → RENAME (preserves data!)\n logger.debug(`[Migration] → Renaming ${rename.table}.${rename.from} to ${rename.to}...`);\n await db.execute(\n sql.raw(\n `ALTER TABLE \"${rename.table}\" RENAME COLUMN \"${rename.from}\" TO \"${rename.to}\"`\n )\n );\n logger.debug(`[Migration] ✓ Renamed ${rename.table}.${rename.from} → ${rename.to}`);\n } else if (hasOldColumn && hasNewColumn) {\n // Both exist → drop old (data should be in new already)\n logger.debug(\n `[Migration] → Both columns exist, dropping ${rename.table}.${rename.from}...`\n );\n await db.execute(\n sql.raw(`ALTER TABLE \"${rename.table}\" DROP COLUMN \"${rename.from}\" CASCADE`)\n );\n logger.debug(`[Migration] ✓ Dropped ${rename.table}.${rename.from}`);\n }\n // If only new column exists or neither exists, nothing to do\n } catch (error) {\n // Log but continue - table might not exist yet or column might already be renamed\n logger.debug(`[Migration] ⊘ Could not process ${rename.table}.${rename.from}: ${error}`);\n }\n }\n\n logger.debug(\"[Migration] ✓ Completed camelCase → snake_case column renames\");\n\n logger.info(\"[Migration] ✓ Migration complete - pre-1.6.5 → 1.6.5+ schema migration finished\");\n } catch (error) {\n // Re-throw errors to prevent RuntimeMigrator from running on broken state\n logger.error(\"[Migration] Migration failed:\", String(error));\n throw error;\n }\n}\n",
9
9
  "import { type IDatabaseAdapter, logger, validateUuid } from \"@elizaos/core\";\nimport { eq, sql } from \"drizzle-orm\";\nimport { agentTable } from \"./schema/agent\";\nimport { serverTable } from \"./schema/server\";\nimport { getDb } from \"./types\";\n\nexport async function installRLSFunctions(adapter: IDatabaseAdapter): Promise<void> {\n const db = getDb(adapter);\n\n await db.execute(sql`\n CREATE TABLE IF NOT EXISTS servers (\n id UUID PRIMARY KEY,\n created_at TIMESTAMPTZ DEFAULT NOW() NOT NULL,\n updated_at TIMESTAMPTZ DEFAULT NOW() NOT NULL\n )\n `);\n\n await db.execute(sql`\n CREATE OR REPLACE FUNCTION current_server_id() RETURNS UUID AS $$\n DECLARE\n app_name TEXT;\n BEGIN\n app_name := NULLIF(current_setting('application_name', TRUE), '');\n\n BEGIN\n RETURN app_name::UUID;\n EXCEPTION WHEN OTHERS THEN\n RETURN NULL;\n END;\n END;\n $$ LANGUAGE plpgsql STABLE;\n `);\n\n await db.execute(sql`\n CREATE OR REPLACE FUNCTION add_server_isolation(\n schema_name text,\n table_name text\n ) RETURNS void AS $$\n DECLARE\n full_table_name text;\n column_exists boolean;\n orphaned_count bigint;\n BEGIN\n full_table_name := schema_name || '.' || table_name;\n\n SELECT EXISTS (\n SELECT 1 FROM information_schema.columns\n WHERE information_schema.columns.table_schema = schema_name\n AND information_schema.columns.table_name = add_server_isolation.table_name\n AND information_schema.columns.column_name = 'server_id'\n ) INTO column_exists;\n\n IF NOT column_exists THEN\n EXECUTE format('ALTER TABLE %I.%I ADD COLUMN server_id UUID DEFAULT current_server_id()', schema_name, table_name);\n EXECUTE format('UPDATE %I.%I SET server_id = current_server_id() WHERE server_id IS NULL', schema_name, table_name);\n ELSE\n EXECUTE format('ALTER TABLE %I.%I ALTER COLUMN server_id SET DEFAULT current_server_id()', schema_name, table_name);\n EXECUTE format('SELECT COUNT(*) FROM %I.%I WHERE server_id IS NULL', schema_name, table_name) INTO orphaned_count;\n\n IF orphaned_count > 0 THEN\n RAISE NOTICE 'Backfilling % rows with NULL server_id in %.%', orphaned_count, schema_name, table_name;\n EXECUTE format('UPDATE %I.%I SET server_id = current_server_id() WHERE server_id IS NULL', schema_name, table_name);\n END IF;\n END IF;\n\n EXECUTE format('CREATE INDEX IF NOT EXISTS idx_%I_server_id ON %I.%I(server_id)', table_name, schema_name, table_name);\n EXECUTE format('ALTER TABLE %I.%I ENABLE ROW LEVEL SECURITY', schema_name, table_name);\n EXECUTE format('ALTER TABLE %I.%I FORCE ROW LEVEL SECURITY', schema_name, table_name);\n EXECUTE format('DROP POLICY IF EXISTS server_isolation_policy ON %I.%I', schema_name, table_name);\n EXECUTE format('\n CREATE POLICY server_isolation_policy ON %I.%I\n USING (server_id = current_server_id())\n WITH CHECK (server_id = current_server_id())\n ', schema_name, table_name);\n END;\n $$ LANGUAGE plpgsql;\n `);\n\n await db.execute(sql`\n CREATE OR REPLACE FUNCTION apply_rls_to_all_tables() RETURNS void AS $$\n DECLARE\n tbl record;\n BEGIN\n FOR tbl IN\n SELECT schemaname, tablename\n FROM pg_tables\n WHERE schemaname = 'public'\n AND tablename NOT IN (\n 'servers',\n 'drizzle_migrations',\n '__drizzle_migrations'\n )\n LOOP\n BEGIN\n PERFORM add_server_isolation(tbl.schemaname, tbl.tablename);\n EXCEPTION WHEN OTHERS THEN\n RAISE WARNING 'Failed to apply RLS to %.%: %', tbl.schemaname, tbl.tablename, SQLERRM;\n END;\n END LOOP;\n END;\n $$ LANGUAGE plpgsql;\n `);\n\n logger.info({ src: \"plugin:sql\" }, \"RLS PostgreSQL functions installed\");\n await installEntityRLS(adapter);\n}\n\nexport async function getOrCreateRlsServer(\n adapter: IDatabaseAdapter,\n serverId: string\n): Promise<string> {\n const db = getDb(adapter);\n\n // Use Drizzle's insert with onConflictDoNothing\n await db\n .insert(serverTable)\n .values({\n id: serverId,\n })\n .onConflictDoNothing();\n\n logger.info({ src: \"plugin:sql\", serverId: serverId.slice(0, 8) }, \"RLS server registered\");\n return serverId;\n}\n\nexport async function setServerContext(adapter: IDatabaseAdapter, serverId: string): Promise<void> {\n if (!validateUuid(serverId)) {\n throw new Error(`Invalid server ID format: ${serverId}. Must be a valid UUID.`);\n }\n\n const db = getDb(adapter);\n const servers = await db.select().from(serverTable).where(eq(serverTable.id, serverId));\n\n if (servers.length === 0) {\n throw new Error(`Server ${serverId} does not exist`);\n }\n\n logger.info({ src: \"plugin:sql\", serverId: serverId.slice(0, 8) }, \"RLS context configured\");\n}\n\nexport async function assignAgentToServer(\n adapter: IDatabaseAdapter,\n agentId: string,\n serverId: string\n): Promise<void> {\n if (!agentId || !serverId) {\n logger.warn(\n `[Data Isolation] Cannot assign agent to server: invalid agentId (${agentId}) or serverId (${serverId})`\n );\n return;\n }\n\n const db = getDb(adapter);\n\n // Check if agent exists using Drizzle\n const agents = await db.select().from(agentTable).where(eq(agentTable.id, agentId));\n\n if (agents.length > 0) {\n const agent = agents[0];\n const currentServerId = agent.server_id;\n\n if (currentServerId === serverId) {\n logger.debug(\n { src: \"plugin:sql\", agentName: agent.name },\n \"Agent already assigned to correct server\"\n );\n } else {\n // Update agent server using Drizzle\n await db.update(agentTable).set({ server_id: serverId }).where(eq(agentTable.id, agentId));\n\n if (currentServerId === null) {\n logger.info({ src: \"plugin:sql\", agentName: agent.name }, \"Agent assigned to server\");\n } else {\n logger.warn({ src: \"plugin:sql\", agentName: agent.name }, \"Agent server changed\");\n }\n }\n } else {\n logger.debug({ src: \"plugin:sql\", agentId }, \"Agent does not exist yet\");\n }\n}\n\n/**\n * Apply RLS to all tables by calling PostgreSQL function\n */\nexport async function applyRLSToNewTables(adapter: IDatabaseAdapter): Promise<void> {\n const db = getDb(adapter);\n\n try {\n await db.execute(sql`SELECT apply_rls_to_all_tables()`);\n logger.info({ src: \"plugin:sql\" }, \"RLS applied to all tables\");\n } catch (error) {\n logger.warn({ src: \"plugin:sql\", error: String(error) }, \"Failed to apply RLS to some tables\");\n }\n}\n\nexport async function uninstallRLS(adapter: IDatabaseAdapter): Promise<void> {\n const db = getDb(adapter);\n\n try {\n const checkResult = await db.execute(sql`\n SELECT EXISTS (\n SELECT FROM pg_tables\n WHERE schemaname = 'public' AND tablename = 'servers'\n ) as rls_enabled\n `);\n\n const rlsEnabled = checkResult.rows?.[0]?.rls_enabled;\n\n if (!rlsEnabled) {\n logger.debug({ src: \"plugin:sql\" }, \"RLS not installed, skipping cleanup\");\n return;\n }\n\n logger.info(\n { src: \"plugin:sql\" },\n \"Disabling RLS globally (keeping server_id columns for schema compatibility)...\"\n );\n\n try {\n await uninstallEntityRLS(adapter);\n } catch (_entityRlsError) {\n logger.debug(\n { src: \"plugin:sql\" },\n \"Entity RLS cleanup skipped (not installed or already cleaned)\"\n );\n }\n\n await db.execute(sql`\n CREATE OR REPLACE FUNCTION _temp_disable_rls_on_table(\n p_schema_name text,\n p_table_name text\n ) RETURNS void AS $$\n DECLARE\n policy_rec record;\n BEGIN\n -- Drop all policies on this table\n FOR policy_rec IN\n SELECT policyname\n FROM pg_policies\n WHERE schemaname = p_schema_name AND tablename = p_table_name\n LOOP\n EXECUTE format('DROP POLICY IF EXISTS %I ON %I.%I',\n policy_rec.policyname, p_schema_name, p_table_name);\n END LOOP;\n\n -- Disable RLS\n EXECUTE format('ALTER TABLE %I.%I NO FORCE ROW LEVEL SECURITY', p_schema_name, p_table_name);\n EXECUTE format('ALTER TABLE %I.%I DISABLE ROW LEVEL SECURITY', p_schema_name, p_table_name);\n END;\n $$ LANGUAGE plpgsql;\n `);\n\n const tablesResult = await db.execute(sql`\n SELECT schemaname, tablename\n FROM pg_tables\n WHERE schemaname = 'public'\n AND tablename NOT IN ('drizzle_migrations', '__drizzle_migrations')\n `);\n\n for (const row of tablesResult.rows || []) {\n const schemaName = row.schemaname;\n const tableName = row.tablename;\n\n try {\n await db.execute(sql`SELECT _temp_disable_rls_on_table(${schemaName}, ${tableName})`);\n logger.debug({ src: \"plugin:sql\", schemaName, tableName }, \"Disabled RLS on table\");\n } catch (error) {\n logger.warn(\n { src: \"plugin:sql\", schemaName, tableName, error: String(error) },\n \"Failed to disable RLS on table\"\n );\n }\n }\n\n await db.execute(sql`DROP FUNCTION IF EXISTS _temp_disable_rls_on_table(text, text)`);\n\n logger.info(\n { src: \"plugin:sql\" },\n \"Keeping server_id values intact (prevents data theft on re-enable)\"\n );\n\n logger.info({ src: \"plugin:sql\" }, \"Clearing servers table...\");\n await db.execute(sql`TRUNCATE TABLE servers`);\n\n await db.execute(sql`DROP FUNCTION IF EXISTS apply_rls_to_all_tables() CASCADE`);\n await db.execute(sql`DROP FUNCTION IF EXISTS add_server_isolation(text, text) CASCADE`);\n await db.execute(sql`DROP FUNCTION IF EXISTS current_server_id() CASCADE`);\n logger.info({ src: \"plugin:sql\" }, \"Dropped all RLS functions\");\n\n logger.info({ src: \"plugin:sql\" }, \"RLS disabled successfully (server_id columns preserved)\");\n } catch (error) {\n logger.error({ src: \"plugin:sql\", error: String(error) }, \"Failed to disable RLS\");\n throw error;\n }\n}\n\nexport async function installEntityRLS(adapter: IDatabaseAdapter): Promise<void> {\n const db = getDb(adapter);\n\n logger.info(\"[Entity RLS] Installing entity RLS functions and policies...\");\n\n await db.execute(sql`\n CREATE OR REPLACE FUNCTION current_entity_id()\n RETURNS UUID AS $$\n DECLARE\n entity_id_text TEXT;\n BEGIN\n -- Read from transaction-local variable\n entity_id_text := NULLIF(current_setting('app.entity_id', TRUE), '');\n\n IF entity_id_text IS NULL OR entity_id_text = '' THEN\n RETURN NULL;\n END IF;\n\n BEGIN\n RETURN entity_id_text::UUID;\n EXCEPTION WHEN OTHERS THEN\n RETURN NULL;\n END;\n END;\n $$ LANGUAGE plpgsql STABLE;\n `);\n\n logger.info(\"[Entity RLS] Created current_entity_id() function\");\n\n // 2. Create add_entity_isolation() function - applies entity RLS to a single table\n await db.execute(sql`\n CREATE OR REPLACE FUNCTION add_entity_isolation(\n schema_name text,\n table_name text,\n require_entity boolean DEFAULT false\n ) RETURNS void AS $$\n DECLARE\n full_table_name text;\n has_entity_id boolean;\n has_author_id boolean;\n has_channel_id boolean;\n has_room_id boolean;\n entity_column_name text;\n room_column_name text;\n BEGIN\n full_table_name := schema_name || '.' || table_name;\n\n SELECT EXISTS (\n SELECT 1 FROM information_schema.columns\n WHERE information_schema.columns.table_schema = schema_name\n AND information_schema.columns.table_name = add_entity_isolation.table_name\n AND information_schema.columns.column_name = 'entity_id'\n ) INTO has_entity_id;\n\n SELECT EXISTS (\n SELECT 1 FROM information_schema.columns\n WHERE information_schema.columns.table_schema = schema_name\n AND information_schema.columns.table_name = add_entity_isolation.table_name\n AND information_schema.columns.column_name = 'author_id'\n ) INTO has_author_id;\n\n SELECT EXISTS (\n SELECT 1 FROM information_schema.columns\n WHERE information_schema.columns.table_schema = schema_name\n AND information_schema.columns.table_name = add_entity_isolation.table_name\n AND information_schema.columns.column_name = 'room_id'\n ) INTO has_room_id;\n\n IF NOT (has_entity_id OR has_author_id OR has_room_id) THEN\n RAISE NOTICE '[Entity RLS] Skipping %.%: no entity columns found', schema_name, table_name;\n RETURN;\n END IF;\n\n IF table_name = 'participants' AND has_entity_id THEN\n entity_column_name := 'entity_id';\n room_column_name := NULL;\n ELSIF has_room_id THEN\n room_column_name := 'room_id';\n entity_column_name := NULL;\n ELSIF has_entity_id THEN\n entity_column_name := 'entity_id';\n room_column_name := NULL;\n ELSIF has_author_id THEN\n entity_column_name := 'author_id';\n room_column_name := NULL;\n ELSE\n entity_column_name := NULL;\n room_column_name := NULL;\n END IF;\n\n EXECUTE format('ALTER TABLE %I.%I ENABLE ROW LEVEL SECURITY', schema_name, table_name);\n EXECUTE format('ALTER TABLE %I.%I FORCE ROW LEVEL SECURITY', schema_name, table_name);\n EXECUTE format('DROP POLICY IF EXISTS entity_isolation_policy ON %I.%I', schema_name, table_name);\n\n IF room_column_name IS NOT NULL THEN\n IF require_entity THEN\n EXECUTE format('\n CREATE POLICY entity_isolation_policy ON %I.%I\n AS RESTRICTIVE\n USING (\n current_entity_id() IS NOT NULL\n AND %I IN (\n SELECT room_id\n FROM participants\n WHERE entity_id = current_entity_id()\n )\n )\n WITH CHECK (\n current_entity_id() IS NOT NULL\n AND %I IN (\n SELECT room_id\n FROM participants\n WHERE entity_id = current_entity_id()\n )\n )\n ', schema_name, table_name, room_column_name, room_column_name);\n RAISE NOTICE '[Entity RLS] Applied STRICT RESTRICTIVE to %.% (via % → participants.room_id, entity REQUIRED)', schema_name, table_name, room_column_name;\n ELSE\n EXECUTE format('\n CREATE POLICY entity_isolation_policy ON %I.%I\n AS RESTRICTIVE\n USING (\n current_entity_id() IS NULL\n OR %I IN (\n SELECT room_id\n FROM participants\n WHERE entity_id = current_entity_id()\n )\n )\n WITH CHECK (\n current_entity_id() IS NULL\n OR %I IN (\n SELECT room_id\n FROM participants\n WHERE entity_id = current_entity_id()\n )\n )\n ', schema_name, table_name, room_column_name, room_column_name);\n RAISE NOTICE '[Entity RLS] Applied PERMISSIVE RESTRICTIVE to %.% (via % → participants.room_id, NULL allowed)', schema_name, table_name, room_column_name;\n END IF;\n\n ELSIF entity_column_name IS NOT NULL THEN\n IF require_entity THEN\n EXECUTE format('\n CREATE POLICY entity_isolation_policy ON %I.%I\n AS RESTRICTIVE\n USING (\n current_entity_id() IS NOT NULL\n AND %I = current_entity_id()\n )\n WITH CHECK (\n current_entity_id() IS NOT NULL\n AND %I = current_entity_id()\n )\n ', schema_name, table_name, entity_column_name, entity_column_name);\n RAISE NOTICE '[Entity RLS] Applied STRICT RESTRICTIVE to %.% (direct column: %, entity REQUIRED)', schema_name, table_name, entity_column_name;\n ELSE\n -- PERMISSIVE MODE: NULL entity_id allows system/admin access\n EXECUTE format('\n CREATE POLICY entity_isolation_policy ON %I.%I\n AS RESTRICTIVE\n USING (\n current_entity_id() IS NULL\n OR %I = current_entity_id()\n )\n WITH CHECK (\n current_entity_id() IS NULL\n OR %I = current_entity_id()\n )\n ', schema_name, table_name, entity_column_name, entity_column_name);\n RAISE NOTICE '[Entity RLS] Applied PERMISSIVE RESTRICTIVE to %.% (direct column: %, NULL allowed)', schema_name, table_name, entity_column_name;\n END IF;\n END IF;\n\n IF room_column_name IS NOT NULL THEN\n EXECUTE format('CREATE INDEX IF NOT EXISTS idx_%I_room ON %I.%I(%I)',\n table_name, schema_name, table_name, room_column_name);\n END IF;\n\n IF entity_column_name IS NOT NULL THEN\n EXECUTE format('CREATE INDEX IF NOT EXISTS idx_%I_entity ON %I.%I(%I)',\n table_name, schema_name, table_name, entity_column_name);\n END IF;\n END;\n $$ LANGUAGE plpgsql;\n `);\n\n logger.info(\"[Entity RLS] Created add_entity_isolation() function\");\n\n await db.execute(sql`\n CREATE OR REPLACE FUNCTION apply_entity_rls_to_all_tables() RETURNS void AS $$\n DECLARE\n tbl record;\n require_entity_for_table boolean;\n BEGIN\n FOR tbl IN\n SELECT schemaname, tablename\n FROM pg_tables\n WHERE schemaname = 'public'\n AND tablename NOT IN (\n 'servers', -- Server RLS table\n 'users', -- Authentication table (no entity isolation needed)\n 'entity_mappings', -- Mapping table (no entity isolation needed)\n 'drizzle_migrations', -- Migration tracking\n '__drizzle_migrations' -- Migration tracking\n )\n LOOP\n BEGIN\n -- Apply STRICT mode (require_entity=true) to sensitive user-facing tables\n -- These tables MUST have entity context set to access data\n -- STRICT tables: memories, logs, components, tasks (user data requiring isolation)\n -- NOTE: Excluded tables:\n -- - 'participants': Adding participants is a privileged operation during initialization\n IF tbl.tablename IN ('memories', 'logs', 'components', 'tasks') THEN\n require_entity_for_table := true;\n ELSE\n require_entity_for_table := false;\n END IF;\n\n PERFORM add_entity_isolation(tbl.schemaname, tbl.tablename, require_entity_for_table);\n EXCEPTION WHEN OTHERS THEN\n RAISE WARNING '[Entity RLS] Failed to apply to %.%: %', tbl.schemaname, tbl.tablename, SQLERRM;\n END;\n END LOOP;\n END;\n $$ LANGUAGE plpgsql;\n `);\n\n logger.info(\"[Entity RLS] Created apply_entity_rls_to_all_tables() function\");\n\n logger.info(\"[Entity RLS] Entity RLS functions installed successfully\");\n}\n\nexport async function applyEntityRLSToAllTables(adapter: IDatabaseAdapter): Promise<void> {\n const db = getDb(adapter);\n\n try {\n await db.execute(sql`SELECT apply_entity_rls_to_all_tables()`);\n logger.info(\"[Entity RLS] Applied entity RLS to all eligible tables\");\n } catch (error) {\n logger.warn(\"[Entity RLS] Failed to apply entity RLS to some tables:\", String(error));\n }\n}\n\nexport async function uninstallEntityRLS(adapter: IDatabaseAdapter): Promise<void> {\n const db = getDb(adapter);\n\n logger.info(\"[Entity RLS] Removing entity RLS policies and functions...\");\n\n try {\n const tablesResult = await db.execute(sql`\n SELECT schemaname, tablename\n FROM pg_tables\n WHERE schemaname = 'public'\n AND tablename NOT IN ('drizzle_migrations', '__drizzle_migrations')\n `);\n\n for (const row of tablesResult.rows || []) {\n const schemaName = row.schemaname;\n const tableName = row.tablename;\n\n try {\n await db.execute(\n sql.raw(`DROP POLICY IF EXISTS entity_isolation_policy ON \"${schemaName}\".\"${tableName}\"`)\n );\n logger.debug(\n `[Entity RLS] Dropped entity_isolation_policy from ${schemaName}.${tableName}`\n );\n } catch (_error) {\n logger.debug(`[Entity RLS] No entity policy on ${schemaName}.${tableName}`);\n }\n }\n\n await db.execute(sql`DROP FUNCTION IF EXISTS apply_entity_rls_to_all_tables() CASCADE`);\n await db.execute(sql`DROP FUNCTION IF EXISTS add_entity_isolation(text, text) CASCADE`);\n await db.execute(sql`DROP FUNCTION IF EXISTS current_entity_id() CASCADE`);\n\n logger.info(\"[Entity RLS] Entity RLS functions and policies removed successfully\");\n } catch (error) {\n logger.error(\"[Entity RLS] Failed to remove entity RLS:\", String(error));\n throw error;\n }\n}\n",
10
10
  "import type {\n IndexColumn,\n SchemaCheckConstraint,\n SchemaColumn,\n SchemaForeignKey,\n SchemaIndex,\n SchemaSnapshot,\n SchemaUniqueConstraint,\n} from \"../types\";\n\n/**\n * Normalize SQL types for comparison\n * Handles equivalent type variations between introspected DB and schema definitions\n */\nfunction normalizeType(type: string | undefined): string {\n if (!type) return \"\";\n\n const normalized = type.toLowerCase().trim();\n\n // Handle timestamp variations\n if (normalized === \"timestamp without time zone\" || normalized === \"timestamp with time zone\") {\n return \"timestamp\";\n }\n\n // Handle serial vs integer with identity\n // serial is essentially integer with auto-increment\n if (normalized === \"serial\") {\n return \"integer\";\n }\n if (normalized === \"bigserial\") {\n return \"bigint\";\n }\n if (normalized === \"smallserial\") {\n return \"smallint\";\n }\n\n // Handle numeric/decimal equivalence\n if (normalized.startsWith(\"numeric\") || normalized.startsWith(\"decimal\")) {\n // Extract precision and scale if present\n const match = normalized.match(/\\((\\d+)(?:,\\s*(\\d+))?\\)/);\n if (match) {\n return `numeric(${match[1]}${match[2] ? `,${match[2]}` : \"\"})`;\n }\n return \"numeric\";\n }\n\n // Handle varchar/character varying\n if (normalized.startsWith(\"character varying\")) {\n return normalized.replace(\"character varying\", \"varchar\");\n }\n\n // Handle text array variations\n if (normalized === \"text[]\" || normalized === \"_text\") {\n return \"text[]\";\n }\n\n return normalized;\n}\n\n/**\n * Helper function to compare two index definitions\n * Returns true if indexes are different and need to be recreated\n */\nfunction isIndexChanged(prevIndex: SchemaIndex, currIndex: SchemaIndex): boolean {\n // Compare basic properties\n if (prevIndex.isUnique !== currIndex.isUnique) return true;\n if (prevIndex.method !== currIndex.method) return true;\n if (prevIndex.where !== currIndex.where) return true;\n if (prevIndex.concurrently !== currIndex.concurrently) return true;\n\n // Compare columns array - must be same columns in same order\n const prevColumns = prevIndex.columns || [];\n const currColumns = currIndex.columns || [];\n\n if (prevColumns.length !== currColumns.length) return true;\n\n for (let i = 0; i < prevColumns.length; i++) {\n const prevCol = prevColumns[i] as string | IndexColumn;\n const currCol = currColumns[i] as string | IndexColumn;\n\n // Handle both string columns and expression columns\n if (typeof prevCol === \"string\" && typeof currCol === \"string\") {\n if (prevCol !== currCol) return true;\n } else if (typeof prevCol === \"object\" && typeof currCol === \"object\") {\n // Compare expression columns\n if (prevCol.expression !== currCol.expression) return true;\n if (prevCol.isExpression !== currCol.isExpression) return true;\n if (prevCol.asc !== currCol.asc) return true;\n if (prevCol.nulls !== currCol.nulls) return true;\n } else {\n // Type mismatch (one is string, other is object)\n return true;\n }\n }\n\n return false;\n}\n\n// Column changes interface\nexport interface ColumnChanges {\n typeChanged?: boolean;\n prevType?: string;\n newType?: string;\n nullabilityChanged?: boolean;\n wasNullable?: boolean;\n isNullable?: boolean;\n defaultChanged?: boolean;\n prevDefault?: string | number | boolean;\n newDefault?: string | number | boolean;\n from?: SchemaColumn;\n to?: SchemaColumn;\n}\n\n// Table changes interface\nexport interface TableChanges {\n columnsAdded: string[];\n columnsDeleted: string[];\n columnsModified: string[];\n}\n\nexport interface SchemaDiff {\n tables: {\n created: string[];\n deleted: string[];\n modified: Array<{\n name: string;\n changes: TableChanges;\n }>;\n };\n columns: {\n added: Array<{\n table: string;\n column: string;\n definition: SchemaColumn;\n }>;\n deleted: Array<{\n table: string;\n column: string;\n }>;\n modified: Array<{\n table: string;\n column: string;\n changes: ColumnChanges;\n }>;\n };\n indexes: {\n created: SchemaIndex[];\n deleted: SchemaIndex[];\n altered: Array<{\n // Indexes with same name but different definition\n old: SchemaIndex;\n new: SchemaIndex;\n }>;\n };\n foreignKeys: {\n created: SchemaForeignKey[];\n deleted: SchemaForeignKey[];\n altered: Array<{\n // FKs with modified CASCADE behavior\n old: SchemaForeignKey;\n new: SchemaForeignKey;\n }>;\n };\n uniqueConstraints: {\n created: SchemaUniqueConstraint[];\n deleted: SchemaUniqueConstraint[];\n };\n checkConstraints: {\n created: SchemaCheckConstraint[];\n deleted: SchemaCheckConstraint[];\n };\n}\n\n/**\n * Calculate the difference between two snapshots\n */\nexport async function calculateDiff(\n previousSnapshot: SchemaSnapshot | null,\n currentSnapshot: SchemaSnapshot\n): Promise<SchemaDiff> {\n const diff: SchemaDiff = {\n tables: {\n created: [],\n deleted: [],\n modified: [],\n },\n columns: {\n added: [],\n deleted: [],\n modified: [],\n },\n indexes: {\n created: [],\n deleted: [],\n altered: [],\n },\n foreignKeys: {\n created: [],\n deleted: [],\n altered: [],\n },\n uniqueConstraints: {\n created: [],\n deleted: [],\n },\n checkConstraints: {\n created: [],\n deleted: [],\n },\n };\n\n // If no previous snapshot, all tables are new\n if (!previousSnapshot) {\n diff.tables.created = Object.keys(currentSnapshot.tables);\n\n // Also track indexes and foreign keys from new tables\n for (const tableName in currentSnapshot.tables) {\n const table = currentSnapshot.tables[tableName];\n\n // Add indexes\n if (table.indexes) {\n for (const indexName in table.indexes) {\n diff.indexes.created.push({\n ...table.indexes[indexName],\n table: tableName,\n } as SchemaIndex & { table: string });\n }\n }\n\n // Add foreign keys\n if (table.foreignKeys) {\n for (const fkName in table.foreignKeys) {\n diff.foreignKeys.created.push(table.foreignKeys[fkName]);\n }\n }\n }\n\n return diff;\n }\n\n const prevTables = previousSnapshot.tables || {};\n const currTables = currentSnapshot.tables || {};\n\n // Find created tables\n for (const tableName in currTables) {\n if (!(tableName in prevTables)) {\n diff.tables.created.push(tableName);\n\n const table = currTables[tableName];\n\n // Add indexes for new table\n if (table.indexes) {\n for (const indexName in table.indexes) {\n diff.indexes.created.push({\n ...table.indexes[indexName],\n table: tableName,\n } as SchemaIndex & { table: string });\n }\n }\n\n // Add unique constraints for new table\n if (table.uniqueConstraints) {\n for (const uqName in table.uniqueConstraints) {\n diff.uniqueConstraints.created.push({\n ...table.uniqueConstraints[uqName],\n table: tableName,\n } as SchemaUniqueConstraint & { table: string });\n }\n }\n\n // Add check constraints for new table\n if (table.checkConstraints) {\n for (const checkName in table.checkConstraints) {\n diff.checkConstraints.created.push({\n ...table.checkConstraints[checkName],\n table: tableName,\n } as SchemaCheckConstraint & { table: string });\n }\n }\n\n // Add foreign keys for new table\n if (table.foreignKeys) {\n for (const fkName in table.foreignKeys) {\n diff.foreignKeys.created.push(table.foreignKeys[fkName]);\n }\n }\n }\n }\n\n // Find deleted tables\n for (const tableName in prevTables) {\n if (!(tableName in currTables)) {\n diff.tables.deleted.push(tableName);\n }\n }\n\n // Find modified tables (check columns, indexes, foreign keys)\n for (const tableName in currTables) {\n if (tableName in prevTables) {\n const prevTable = prevTables[tableName];\n const currTable = currTables[tableName];\n\n // Early check: if the table schemas are identical, skip it entirely\n // This prevents false positives when other tables are modified\n const prevTableJson = JSON.stringify({\n columns: prevTable.columns || {},\n indexes: prevTable.indexes || {},\n foreignKeys: prevTable.foreignKeys || {},\n uniqueConstraints: prevTable.uniqueConstraints || {},\n checkConstraints: prevTable.checkConstraints || {},\n });\n\n const currTableJson = JSON.stringify({\n columns: currTable.columns || {},\n indexes: currTable.indexes || {},\n foreignKeys: currTable.foreignKeys || {},\n uniqueConstraints: currTable.uniqueConstraints || {},\n checkConstraints: currTable.checkConstraints || {},\n });\n\n // If tables are identical, skip all processing for this table\n if (prevTableJson === currTableJson) {\n continue;\n }\n\n // Compare columns\n const prevColumns = prevTable.columns || {};\n const currColumns = currTable.columns || {};\n\n // Find added columns\n for (const colName in currColumns) {\n if (!(colName in prevColumns)) {\n diff.columns.added.push({\n table: tableName,\n column: colName,\n definition: currColumns[colName],\n });\n }\n }\n\n // Find deleted columns\n for (const colName in prevColumns) {\n if (!(colName in currColumns)) {\n diff.columns.deleted.push({\n table: tableName,\n column: colName,\n });\n }\n }\n\n // Find modified columns\n for (const colName in currColumns) {\n if (colName in prevColumns) {\n const prevCol = prevColumns[colName];\n const currCol = currColumns[colName];\n\n // Check for changes in column properties\n // Use normalized type comparison\n const typeChanged = normalizeType(prevCol.type) !== normalizeType(currCol.type);\n const hasChanges =\n typeChanged ||\n prevCol.notNull !== currCol.notNull ||\n prevCol.default !== currCol.default ||\n prevCol.primaryKey !== currCol.primaryKey;\n\n if (hasChanges) {\n diff.columns.modified.push({\n table: tableName,\n column: colName,\n changes: {\n from: prevCol,\n to: currCol,\n },\n });\n }\n }\n }\n\n // Compare indexes\n const prevIndexes = prevTable.indexes || {};\n const currIndexes = currTable.indexes || {};\n\n // Find new, deleted, and altered indexes\n for (const indexName in currIndexes) {\n if (!(indexName in prevIndexes)) {\n // New index\n diff.indexes.created.push({\n ...currIndexes[indexName],\n table: tableName,\n } as SchemaIndex & { table: string });\n } else {\n // Check if index definition changed\n const prevIndex = prevIndexes[indexName];\n const currIndex = currIndexes[indexName];\n\n // Deep comparison of index properties\n const indexChanged = isIndexChanged(prevIndex, currIndex);\n\n if (indexChanged) {\n // Index definition changed - need to drop and recreate\n diff.indexes.altered.push({\n old: {\n ...prevIndex,\n table: tableName,\n name: indexName,\n } as SchemaIndex & { table: string },\n new: {\n ...currIndex,\n table: tableName,\n name: indexName,\n } as SchemaIndex & { table: string },\n });\n }\n }\n }\n\n // Find deleted indexes (not altered)\n for (const indexName in prevIndexes) {\n if (!(indexName in currIndexes)) {\n diff.indexes.deleted.push({\n ...prevIndexes[indexName],\n table: tableName,\n } as SchemaIndex & { table: string });\n }\n }\n\n // Compare unique constraints\n const prevUniqueConstraints = prevTable.uniqueConstraints || {};\n const currUniqueConstraints = currTable.uniqueConstraints || {};\n\n // Find new unique constraints\n for (const uqName in currUniqueConstraints) {\n if (!(uqName in prevUniqueConstraints)) {\n diff.uniqueConstraints.created.push({\n ...currUniqueConstraints[uqName],\n table: tableName,\n } as SchemaUniqueConstraint & { table: string });\n }\n }\n\n // Find deleted unique constraints\n for (const uqName in prevUniqueConstraints) {\n if (!(uqName in currUniqueConstraints)) {\n diff.uniqueConstraints.deleted.push({\n ...prevUniqueConstraints[uqName],\n table: tableName,\n } as SchemaUniqueConstraint & { table: string });\n }\n }\n\n // Compare check constraints\n const prevCheckConstraints = prevTable.checkConstraints || {};\n const currCheckConstraints = currTable.checkConstraints || {};\n\n // Find new check constraints\n for (const checkName in currCheckConstraints) {\n if (!(checkName in prevCheckConstraints)) {\n diff.checkConstraints.created.push({\n ...currCheckConstraints[checkName],\n table: tableName,\n } as SchemaCheckConstraint & { table: string });\n }\n }\n\n // Find deleted check constraints\n for (const checkName in prevCheckConstraints) {\n if (!(checkName in currCheckConstraints)) {\n diff.checkConstraints.deleted.push({\n ...prevCheckConstraints[checkName],\n table: tableName,\n } as SchemaCheckConstraint & { table: string });\n }\n }\n\n // Compare foreign keys\n const prevFKs = prevTable.foreignKeys || {};\n const currFKs = currTable.foreignKeys || {};\n\n // Find new, deleted, and altered foreign keys\n for (const fkName in currFKs) {\n if (!(fkName in prevFKs)) {\n // New FK\n diff.foreignKeys.created.push(currFKs[fkName]);\n } else {\n // Check if FK definition changed (CASCADE behavior, etc.)\n const prevFK = prevFKs[fkName];\n const currFK = currFKs[fkName];\n\n // Compare FK properties\n const prevOnDelete = prevFK.onDelete || \"no action\";\n const currOnDelete = currFK.onDelete || \"no action\";\n const prevOnUpdate = prevFK.onUpdate || \"no action\";\n const currOnUpdate = currFK.onUpdate || \"no action\";\n\n if (prevOnDelete !== currOnDelete || prevOnUpdate !== currOnUpdate) {\n // FK CASCADE behavior changed - need to drop and recreate\n diff.foreignKeys.altered.push({\n old: prevFK,\n new: currFK,\n });\n }\n }\n }\n\n // Find deleted foreign keys (not altered)\n for (const fkName in prevFKs) {\n if (!(fkName in currFKs)) {\n const prevFK = prevFKs[fkName];\n diff.foreignKeys.deleted.push({\n ...prevFK,\n tableFrom: tableName,\n } as SchemaForeignKey);\n }\n }\n }\n }\n\n return diff;\n}\n\n/**\n * Check if a diff has any changes\n */\nexport function hasDiffChanges(diff: SchemaDiff): boolean {\n return (\n diff.tables.created.length > 0 ||\n diff.tables.deleted.length > 0 ||\n diff.tables.modified.length > 0 ||\n diff.columns.added.length > 0 ||\n diff.columns.deleted.length > 0 ||\n diff.columns.modified.length > 0 ||\n diff.indexes.created.length > 0 ||\n diff.indexes.deleted.length > 0 ||\n diff.indexes.altered.length > 0 ||\n diff.foreignKeys.created.length > 0 ||\n diff.foreignKeys.deleted.length > 0 ||\n diff.foreignKeys.altered.length > 0 ||\n diff.uniqueConstraints.created.length > 0 ||\n diff.uniqueConstraints.deleted.length > 0 ||\n diff.checkConstraints.created.length > 0 ||\n diff.checkConstraints.deleted.length > 0\n );\n}\n",
11
11
  "/**\n * Browser-compatible crypto utilities\n * Uses the Web Crypto API which is available in both browsers and Node.js\n */\n\n/**\n * Simple synchronous hash function for change detection\n * This is NOT cryptographic - it's just for comparing snapshots\n * Uses djb2 hash algorithm for speed and simplicity\n */\nexport function simpleHash(str: string): string {\n let hash = 5381;\n for (let i = 0; i < str.length; i++) {\n hash = (hash * 33) ^ str.charCodeAt(i);\n }\n // Convert to unsigned 32-bit integer and then to hex\n return (hash >>> 0).toString(16).padStart(8, \"0\");\n}\n\n/**\n * Create a longer hash by combining multiple passes\n * This provides better distribution for larger inputs\n */\nexport function extendedHash(str: string): string {\n // Run multiple passes with different seeds for better distribution\n const h1 = hashWithSeed(str, 5381);\n const h2 = hashWithSeed(str, 7919);\n const h3 = hashWithSeed(str, 104729);\n const h4 = hashWithSeed(str, 224737);\n\n return h1 + h2 + h3 + h4;\n}\n\nfunction hashWithSeed(str: string, seed: number): string {\n let hash = seed;\n for (let i = 0; i < str.length; i++) {\n hash = (hash * 33) ^ str.charCodeAt(i);\n }\n return (hash >>> 0).toString(16).padStart(8, \"0\");\n}\n\n/**\n * Convert string to Uint8Array\n */\nfunction stringToBytes(str: string): Uint8Array {\n const encoder = new TextEncoder();\n return encoder.encode(str);\n}\n\n/**\n * Convert ArrayBuffer to hex string\n */\nfunction bufferToHex(buffer: ArrayBuffer): string {\n const bytes = new Uint8Array(buffer);\n let hex = \"\";\n for (let i = 0; i < bytes.length; i++) {\n hex += bytes[i].toString(16).padStart(2, \"0\");\n }\n return hex;\n}\n\n/**\n * Async SHA-256 hash using Web Crypto API\n * Works in both browsers and Node.js (v15+)\n */\nexport async function sha256Async(data: string): Promise<string> {\n const bytes = stringToBytes(data);\n // Cast to ArrayBuffer to satisfy TypeScript's strict BufferSource typing\n const hashBuffer = await crypto.subtle.digest(\"SHA-256\", bytes.buffer as ArrayBuffer);\n return bufferToHex(hashBuffer);\n}\n\n/**\n * Generate a stable bigint from a string for advisory lock IDs\n * Uses a simple hash that produces consistent results across runs\n */\nexport function stringToBigInt(str: string): bigint {\n // Use extended hash for better uniqueness\n const hash = extendedHash(str);\n\n // Convert first 16 hex chars (64 bits) to bigint\n let lockId = BigInt(`0x${hash.slice(0, 16)}`);\n\n // Ensure the value fits in PostgreSQL's positive bigint range\n // Use a mask to keep only 63 bits (ensures positive in signed 64-bit)\n const mask63Bits = 0x7fffffffffffffffn;\n lockId = lockId & mask63Bits;\n\n // Ensure non-zero\n if (lockId === 0n) {\n lockId = 1n;\n }\n\n return lockId;\n}\n",
12
12
  "import { is, SQL } from \"drizzle-orm\";\nimport { getTableConfig, type PgColumn, PgDialect, PgTable } from \"drizzle-orm/pg-core\";\nimport { extendedHash } from \"../crypto-utils\";\nimport type {\n IndexColumn,\n SchemaCheckConstraint,\n SchemaColumn,\n SchemaEnum,\n SchemaForeignKey,\n SchemaIndex,\n SchemaPrimaryKey,\n SchemaSnapshot,\n SchemaTable,\n SchemaUniqueConstraint,\n} from \"../types\";\n\n// Drizzle schema type - an object mapping table names to PgTable instances\ntype DrizzleSchema = Record<string, unknown>;\n\n// Array element type for building SQL arrays\ntype ArrayElement = number | bigint | boolean | string | Date | object | ArrayElement[];\n\n/**\n * Internal Drizzle types for working with SQL expressions and indexes.\n * These types aren't exported from drizzle-orm but are needed for snapshot generation.\n *\n * Note: Drizzle's SQL.toQuery() accepts a config object with specific properties.\n * Since these are internal to Drizzle, we define compatible types here.\n */\ninterface SqlToQueryConfig {\n escapeName: () => never;\n escapeParam: () => never;\n escapeString: () => never;\n casing?: undefined; // We don't use casing transformation\n}\n\n/**\n * Internal Drizzle column config interface.\n * PgColumn has internal properties not exposed in the public type definition.\n */\ninterface DrizzleColumnWithConfig {\n name: string;\n notNull: boolean;\n primary: boolean;\n getSQLType: () => string;\n default?: unknown;\n isUnique?: boolean;\n config?: {\n uniqueName?: string;\n uniqueType?: string;\n };\n}\n\n/**\n * Utility functions from Drizzle's code\n */\nfunction escapeSingleQuotes(str: string): string {\n return str.replace(/'/g, \"''\");\n}\n\nfunction isPgArrayType(sqlType: string): boolean {\n return sqlType.match(/.*\\[\\d*\\].*|.*\\[\\].*/g) !== null;\n}\n\nfunction buildArrayString(array: ArrayElement[], sqlType: string): string {\n sqlType = sqlType.split(\"[\")[0];\n const values = array\n .map((value) => {\n if (typeof value === \"number\" || typeof value === \"bigint\") {\n return value.toString();\n } else if (typeof value === \"boolean\") {\n return value ? \"true\" : \"false\";\n } else if (Array.isArray(value)) {\n return buildArrayString(value, sqlType);\n } else if (value instanceof Date) {\n if (sqlType === \"date\") {\n return `\"${value.toISOString().split(\"T\")[0]}\"`;\n } else if (sqlType === \"timestamp\") {\n return `\"${value.toISOString().replace(\"T\", \" \").slice(0, 23)}\"`;\n } else {\n return `\"${value.toISOString()}\"`;\n }\n } else if (typeof value === \"object\") {\n return `\"${JSON.stringify(value).replaceAll('\"', '\\\\\"')}\"`;\n }\n\n return `\"${value}\"`;\n })\n .join(\",\");\n\n return `{${values}}`;\n}\n\n/**\n * Convert a Drizzle SQL expression to a string.\n * This is used for extracting default values from column definitions.\n *\n * Note: We use a type assertion here because SQL.toQuery() expects internal\n * Drizzle types that aren't publicly exported. Our config is compatible\n * at runtime but TypeScript can't verify this.\n */\nconst sqlToStr = (sql: SQL, _casing: string | undefined) => {\n const config: SqlToQueryConfig = {\n escapeName: () => {\n throw new Error(\"we don't support params for `sql` default values\");\n },\n escapeParam: () => {\n throw new Error(\"we don't support params for `sql` default values\");\n },\n escapeString: () => {\n throw new Error(\"we don't support params for `sql` default values\");\n },\n casing: undefined, // We don't use casing transformation in this context\n };\n // Type assertion needed: SQL.toQuery expects internal Drizzle types\n type ToQueryParam = Parameters<SQL[\"toQuery\"]>[0];\n return sql.toQuery(config as ToQueryParam).sql;\n};\n\n/**\n * Extract Drizzle tables from a schema object\n */\nfunction extractTablesFromSchema(schema: DrizzleSchema): PgTable[] {\n const tables: PgTable[] = [];\n\n // Iterate through all exports in the schema\n const exports = Object.values(schema);\n exports.forEach((t: unknown) => {\n // Check if it's a PgTable using Drizzle's is() function\n if (is(t, PgTable)) {\n tables.push(t);\n }\n });\n\n return tables;\n}\n\n/**\n * Generate a snapshot from a Drizzle schema\n * This is a port of Drizzle's pgSerializer.generatePgSnapshot\n */\nexport async function generateSnapshot(schema: DrizzleSchema): Promise<SchemaSnapshot> {\n const dialect = new PgDialect({ casing: undefined });\n const tables: Record<string, SchemaTable> = {};\n const schemas: Record<string, string> = {};\n const enums: Record<string, SchemaEnum> = {};\n\n // Extract tables from schema\n const pgTables = extractTablesFromSchema(schema);\n\n // Process each table\n for (const table of pgTables) {\n const config = getTableConfig(table);\n const {\n name: tableName,\n columns,\n indexes,\n foreignKeys,\n schema: tableSchema,\n primaryKeys,\n uniqueConstraints,\n checks,\n } = config;\n\n const columnsObject: Record<string, SchemaColumn> = {};\n const indexesObject: Record<string, SchemaIndex> = {};\n const foreignKeysObject: Record<string, SchemaForeignKey> = {};\n const primaryKeysObject: Record<string, SchemaPrimaryKey> = {};\n const uniqueConstraintObject: Record<string, SchemaUniqueConstraint> = {};\n const checksObject: Record<string, SchemaCheckConstraint> = {};\n\n // Process columns - EXACT copy of Drizzle's logic\n columns.forEach((column: PgColumn) => {\n const name = column.name;\n const notNull = column.notNull;\n const primaryKey = column.primary;\n const sqlType = column.getSQLType();\n const sqlTypeLowered = sqlType.toLowerCase();\n\n const columnToSet: SchemaColumn = {\n name,\n type: sqlType,\n primaryKey,\n notNull,\n };\n\n // Handle defaults - EXACT copy from Drizzle's pgSerializer.ts lines 247-273\n if (column.default !== undefined) {\n if (is(column.default, SQL)) {\n columnToSet.default = sqlToStr(column.default, undefined);\n } else {\n if (typeof column.default === \"string\") {\n columnToSet.default = `'${escapeSingleQuotes(column.default)}'`;\n } else {\n if (sqlTypeLowered === \"jsonb\" || sqlTypeLowered === \"json\") {\n columnToSet.default = `'${JSON.stringify(column.default)}'::${sqlTypeLowered}`;\n } else if (column.default instanceof Date) {\n if (sqlTypeLowered === \"date\") {\n columnToSet.default = `'${column.default.toISOString().split(\"T\")[0]}'`;\n } else if (sqlTypeLowered === \"timestamp\") {\n columnToSet.default = `'${column.default.toISOString().replace(\"T\", \" \").slice(0, 23)}'`;\n } else {\n columnToSet.default = `'${column.default.toISOString()}'`;\n }\n } else if (isPgArrayType(sqlTypeLowered) && Array.isArray(column.default)) {\n columnToSet.default = `'${buildArrayString(column.default as ArrayElement[], sqlTypeLowered)}'`;\n } else {\n // Should do for all types\n // columnToSet.default = `'${column.default}'::${sqlTypeLowered}`;\n columnToSet.default = column.default as string | number | boolean;\n }\n }\n }\n }\n\n // Handle column-level unique constraints\n // IMPORTANT: Check isUnique, not just uniqueName presence!\n // Drizzle sets uniqueName for all columns but only unique ones should have constraints\n // Type assertion: accessing internal Drizzle column properties not in public types\n const columnWithConfig = column as unknown as DrizzleColumnWithConfig;\n const columnConfig = columnWithConfig.config;\n if (columnWithConfig.isUnique && columnConfig && columnConfig.uniqueName) {\n uniqueConstraintObject[columnConfig.uniqueName] = {\n name: columnConfig.uniqueName,\n columns: [name],\n nullsNotDistinct: columnConfig.uniqueType === \"not distinct\",\n };\n }\n\n columnsObject[name] = columnToSet;\n });\n\n // Drizzle primary key interface\n interface DrizzlePrimaryKey {\n columns: Array<{ name: string }>;\n getName: () => string;\n }\n\n // Process primary keys\n primaryKeys.forEach((pk: DrizzlePrimaryKey) => {\n const columnNames = pk.columns.map((c) => c.name);\n const name = pk.getName();\n\n primaryKeysObject[name] = {\n name,\n columns: columnNames,\n };\n });\n\n // Drizzle unique constraint interface\n interface DrizzleUniqueConstraint {\n columns: Array<{ name: string }>;\n name?: string;\n nullsNotDistinct?: boolean;\n }\n\n // Process unique constraints\n uniqueConstraints?.forEach((unq: DrizzleUniqueConstraint) => {\n const columnNames = unq.columns.map((c) => c.name);\n const name = unq.name || `${tableName}_${columnNames.join(\"_\")}_unique`;\n\n uniqueConstraintObject[name] = {\n name,\n columns: columnNames,\n nullsNotDistinct: unq.nullsNotDistinct,\n };\n });\n\n // Drizzle foreign key interfaces\n interface DrizzleForeignKeyReference {\n columns: Array<{ name: string }>;\n foreignColumns: Array<{ name: string }>;\n foreignTable: PgTable;\n }\n\n interface DrizzleForeignKey {\n reference: () => DrizzleForeignKeyReference;\n getName: () => string;\n onDelete?: string;\n onUpdate?: string;\n }\n\n // Process foreign keys - includes both explicit foreignKeys and inline references\n // Drizzle's getTableConfig automatically collects inline .references() into foreignKeys\n foreignKeys.forEach((fk: DrizzleForeignKey) => {\n const reference = fk.reference();\n const columnsFrom = reference.columns.map((it) => it.name);\n const columnsTo = reference.foreignColumns.map((it) => it.name);\n const tableTo = getTableConfig(reference.foreignTable).name;\n const schemaTo = getTableConfig(reference.foreignTable).schema || \"public\";\n\n const name = fk.getName();\n\n foreignKeysObject[name] = {\n name,\n tableFrom: tableName,\n schemaFrom: tableSchema, // Add source table schema\n tableTo,\n schemaTo,\n columnsFrom,\n columnsTo,\n onDelete: fk.onDelete || \"no action\",\n onUpdate: fk.onUpdate || \"no action\",\n };\n });\n\n // Drizzle index interfaces\n interface DrizzleIndexConfig {\n order?: string;\n nulls?: string;\n }\n\n interface DrizzleIndexColumn {\n name: string;\n indexConfig?: DrizzleIndexConfig;\n }\n\n interface DrizzleIndex {\n config: {\n columns: Array<DrizzleIndexColumn | SQL>;\n name?: string;\n unique?: boolean;\n method?: string;\n };\n }\n\n // Process indexes\n // Drizzle's getTableConfig returns indexes with internal types not exported from the package\n (indexes as DrizzleIndex[]).forEach((idx: DrizzleIndex) => {\n const indexCols = idx.config.columns;\n const indexColumns: IndexColumn[] = indexCols.map((col) => {\n if (is(col, SQL)) {\n return {\n expression: dialect.sqlToQuery(col).sql,\n isExpression: true,\n };\n } else {\n const indexCol: IndexColumn = {\n expression: col.name,\n isExpression: false,\n asc: col.indexConfig && col.indexConfig.order === \"asc\",\n };\n // Only add nulls if explicitly specified in the config\n if (col.indexConfig?.nulls) {\n indexCol.nulls = col.indexConfig.nulls;\n }\n return indexCol;\n }\n });\n\n const name =\n idx.config.name || `${tableName}_${indexColumns.map((c) => c.expression).join(\"_\")}_index`;\n\n indexesObject[name] = {\n name,\n columns: indexColumns,\n isUnique: idx.config.unique || false,\n method: idx.config.method || \"btree\",\n };\n });\n\n // Drizzle check constraint interface\n interface DrizzleCheck {\n name: string;\n value: SQL;\n }\n\n // Process check constraints\n if (checks) {\n checks.forEach((check: DrizzleCheck) => {\n const checkName = check.name;\n checksObject[checkName] = {\n name: checkName,\n value: dialect.sqlToQuery(check.value).sql,\n };\n });\n }\n\n // Build the table object\n tables[`${tableSchema || \"public\"}.${tableName}`] = {\n name: tableName,\n schema: tableSchema || \"public\",\n columns: columnsObject,\n indexes: indexesObject,\n foreignKeys: foreignKeysObject,\n compositePrimaryKeys: primaryKeysObject,\n uniqueConstraints: uniqueConstraintObject,\n checkConstraints: checksObject,\n };\n\n // Track schemas\n if (tableSchema && tableSchema !== \"public\") {\n schemas[tableSchema] = tableSchema;\n }\n }\n\n // Create snapshot in Drizzle's format\n const snapshot: SchemaSnapshot = {\n version: \"7\",\n dialect: \"postgresql\",\n tables,\n schemas,\n enums,\n _meta: {\n schemas: {},\n tables: {},\n columns: {},\n },\n };\n\n return snapshot;\n}\n\n/**\n * Calculate hash of a snapshot for change detection\n * Uses a browser-compatible hash function\n */\nexport function hashSnapshot(snapshot: SchemaSnapshot): string {\n const content = JSON.stringify(snapshot);\n return extendedHash(content);\n}\n\n/**\n * Create an empty snapshot for initial migration\n */\nexport function createEmptySnapshot(): SchemaSnapshot {\n return {\n version: \"7\",\n dialect: \"postgresql\",\n tables: {},\n schemas: {},\n enums: {},\n _meta: {\n schemas: {},\n tables: {},\n columns: {},\n },\n };\n}\n\n/**\n * Compare two snapshots and detect if there are changes\n */\nexport function hasChanges(\n previousSnapshot: SchemaSnapshot | null,\n currentSnapshot: SchemaSnapshot\n): boolean {\n // If no previous snapshot, there are definitely changes\n if (!previousSnapshot) {\n return Object.keys(currentSnapshot.tables).length > 0;\n }\n\n // Simple comparison for now - in production, use deep comparison\n const prevHash = hashSnapshot(previousSnapshot);\n const currHash = hashSnapshot(currentSnapshot);\n\n return prevHash !== currHash;\n}\n",
13
- "import { logger } from \"@elizaos/core\";\nimport type {\n SchemaCheckConstraint,\n SchemaColumn,\n SchemaForeignKey,\n SchemaIndex,\n SchemaPrimaryKey,\n SchemaSnapshot,\n SchemaTable,\n SchemaUniqueConstraint,\n} from \"../types\";\nimport type { SchemaDiff } from \"./diff-calculator\";\n\n/**\n * Data loss detection result\n * Based on Drizzle's pgPushUtils approach\n */\nexport interface DataLossCheck {\n hasDataLoss: boolean;\n tablesToRemove: string[];\n columnsToRemove: string[];\n tablesToTruncate: string[];\n typeChanges: Array<{\n table: string;\n column: string;\n from: string;\n to: string;\n }>;\n warnings: string[];\n requiresConfirmation: boolean;\n}\n\n/**\n * Check for potential data loss in schema changes\n * Based on Drizzle's pgSuggestions function\n */\nexport function checkForDataLoss(diff: SchemaDiff): DataLossCheck {\n const result: DataLossCheck = {\n hasDataLoss: false,\n tablesToRemove: [],\n columnsToRemove: [],\n tablesToTruncate: [],\n typeChanges: [],\n warnings: [],\n requiresConfirmation: false,\n };\n\n // Check for table deletions\n if (diff.tables.deleted.length > 0) {\n result.hasDataLoss = true;\n result.requiresConfirmation = true;\n result.tablesToRemove = [...diff.tables.deleted];\n for (const table of diff.tables.deleted) {\n result.warnings.push(`Table \"${table}\" will be dropped with all its data`);\n }\n }\n\n // Check for column deletions\n if (diff.columns.deleted.length > 0) {\n result.hasDataLoss = true;\n result.requiresConfirmation = true;\n for (const col of diff.columns.deleted) {\n result.columnsToRemove.push(`${col.table}.${col.column}`);\n result.warnings.push(`Column \"${col.column}\" in table \"${col.table}\" will be dropped`);\n }\n }\n\n // Check for column type changes that might cause data loss\n for (const modified of diff.columns.modified) {\n const from = modified.changes.from;\n const to = modified.changes.to;\n\n if (!from || !to) continue;\n\n // Check if type change is destructive\n if (from.type !== to.type) {\n const isDestructive = checkIfTypeChangeIsDestructive(from.type, to.type);\n\n if (isDestructive) {\n result.hasDataLoss = true;\n result.requiresConfirmation = true;\n result.typeChanges.push({\n table: modified.table,\n column: modified.column,\n from: from.type,\n to: to.type,\n });\n result.tablesToTruncate.push(modified.table);\n result.warnings.push(\n `Column \"${modified.column}\" in table \"${modified.table}\" changes type from \"${from.type}\" to \"${to.type}\". ` +\n `This may require truncating the table to avoid data conversion errors.`\n );\n }\n }\n\n // Check for adding NOT NULL without default to existing column\n if (!from.notNull && to.notNull && !to.default) {\n result.hasDataLoss = true;\n result.requiresConfirmation = true;\n result.warnings.push(\n `Column \"${modified.column}\" in table \"${modified.table}\" is becoming NOT NULL without a default value. ` +\n `This will fail if the table contains NULL values.`\n );\n }\n }\n\n // Check for adding NOT NULL columns without defaults\n for (const added of diff.columns.added) {\n if (added.definition.notNull && !added.definition.default) {\n // This is only a problem if the table already has data\n // We'll flag it as a potential issue\n result.warnings.push(\n `Column \"${added.column}\" is being added to table \"${added.table}\" as NOT NULL without a default value. ` +\n `This will fail if the table contains data.`\n );\n // Don't set requiresConfirmation here - it's only a warning\n }\n }\n\n return result;\n}\n\n/**\n * Normalize SQL types for comparison\n * Handles equivalent type variations between introspected DB and schema definitions\n */\nfunction normalizeType(type: string | undefined): string {\n if (!type) return \"\";\n\n const normalized = type.toLowerCase().trim();\n\n // Handle timestamp variations - all are equivalent\n if (\n normalized === \"timestamp without time zone\" ||\n normalized === \"timestamp with time zone\" ||\n normalized === \"timestamptz\"\n ) {\n return \"timestamp\";\n }\n\n // Handle serial vs integer with identity\n // serial is essentially integer with auto-increment\n if (normalized === \"serial\") {\n return \"integer\";\n }\n if (normalized === \"bigserial\") {\n return \"bigint\";\n }\n if (normalized === \"smallserial\") {\n return \"smallint\";\n }\n\n // Handle numeric/decimal equivalence\n if (normalized.startsWith(\"numeric\") || normalized.startsWith(\"decimal\")) {\n // Extract precision and scale if present\n const match = normalized.match(/\\((\\d+)(?:,\\s*(\\d+))?\\)/);\n if (match) {\n return `numeric(${match[1]}${match[2] ? `,${match[2]}` : \"\"})`;\n }\n return \"numeric\";\n }\n\n // Handle varchar/character varying\n if (normalized.startsWith(\"character varying\")) {\n return normalized.replace(\"character varying\", \"varchar\");\n }\n\n // Handle text array variations\n if (normalized === \"text[]\" || normalized === \"_text\") {\n return \"text[]\";\n }\n\n return normalized;\n}\n\n/**\n * Check if a type change is destructive\n * Based on PostgreSQL's type casting rules\n */\nfunction checkIfTypeChangeIsDestructive(fromType: string, toType: string): boolean {\n // First normalize the types to handle equivalent variations\n const normalizedFrom = normalizeType(fromType);\n const normalizedTo = normalizeType(toType);\n\n // If normalized types match, it's not destructive\n if (normalizedFrom === normalizedTo) {\n return false;\n }\n\n // Safe conversions (PostgreSQL) - based on Drizzle's logic\n const safeConversions: Record<string, string[]> = {\n smallint: [\"integer\", \"bigint\", \"numeric\", \"real\", \"double precision\"],\n integer: [\"bigint\", \"numeric\", \"real\", \"double precision\"],\n bigint: [\"numeric\"],\n real: [\"double precision\"],\n varchar: [\"text\"],\n char: [\"varchar\", \"text\"],\n citext: [\"text\"],\n text: [\"citext\"],\n // UUID to text is safe\n uuid: [\"text\", \"varchar\"],\n // Timestamp variations are generally safe (now handled by normalization)\n timestamp: [\"timestamp\"], // Simplified since normalization handles variations\n // Date/time conversions\n date: [\"timestamp\"],\n time: [\"timetz\"],\n };\n\n const fromBase = normalizedFrom.split(\"(\")[0];\n const toBase = normalizedTo.split(\"(\")[0];\n\n // Same type is always safe\n if (fromBase === toBase) {\n return false;\n }\n\n // Check if it's a safe conversion\n const safeTo = safeConversions[fromBase];\n if (safeTo?.includes(toBase)) {\n return false;\n }\n\n // All other conversions are considered potentially destructive\n return true;\n}\n\n/**\n * Generate SQL statements from a schema diff\n * This follows Drizzle's approach: create all tables first, then add foreign keys\n */\nexport async function generateMigrationSQL(\n previousSnapshot: SchemaSnapshot | null,\n currentSnapshot: SchemaSnapshot,\n diff?: SchemaDiff\n): Promise<string[]> {\n const statements: string[] = [];\n\n // If no diff provided, calculate it\n if (!diff) {\n const { calculateDiff } = await import(\"./diff-calculator\");\n diff = await calculateDiff(previousSnapshot, currentSnapshot);\n }\n\n // Check for data loss\n const dataLossCheck = checkForDataLoss(diff);\n\n // Log warnings if any\n if (dataLossCheck.warnings.length > 0) {\n logger.warn(\n { src: \"plugin:sql\", warnings: dataLossCheck.warnings },\n \"Schema changes may cause data loss\"\n );\n }\n\n // Phase 1: Collect unique schemas and create them first\n const schemasToCreate = new Set<string>();\n for (const tableName of diff.tables.created) {\n const table = currentSnapshot.tables[tableName];\n if (table) {\n const schema = table.schema || \"public\";\n if (schema !== \"public\") {\n schemasToCreate.add(schema);\n }\n }\n }\n\n // Create schemas first (following drizzle-kit pattern)\n for (const schema of schemasToCreate) {\n statements.push(`CREATE SCHEMA IF NOT EXISTS \"${schema}\";`);\n }\n\n // Phase 2: Generate CREATE TABLE statements for new tables (WITHOUT foreign keys)\n const createTableStatements: string[] = [];\n const foreignKeyStatements: string[] = [];\n\n for (const tableName of diff.tables.created) {\n const table = currentSnapshot.tables[tableName];\n if (table) {\n const { tableSQL, fkSQLs } = generateCreateTableSQL(tableName, table);\n createTableStatements.push(tableSQL);\n foreignKeyStatements.push(...fkSQLs);\n }\n }\n\n // Add all CREATE TABLE statements\n statements.push(...createTableStatements);\n\n // Phase 3: Add all foreign keys AFTER tables are created\n // Deduplicate foreign key statements to avoid duplicate constraints\n const uniqueFKs = new Set<string>();\n const dedupedFKStatements: string[] = [];\n\n for (const fkSQL of foreignKeyStatements) {\n // Extract constraint name to check for duplicates\n const match = fkSQL.match(/ADD CONSTRAINT \"([^\"]+)\"/);\n if (match) {\n const constraintName = match[1];\n if (!uniqueFKs.has(constraintName)) {\n uniqueFKs.add(constraintName);\n dedupedFKStatements.push(fkSQL);\n }\n } else {\n dedupedFKStatements.push(fkSQL);\n }\n }\n\n statements.push(...dedupedFKStatements);\n\n // Phase 4: Handle table modifications\n\n // Generate DROP TABLE statements for deleted tables\n for (const tableName of diff.tables.deleted) {\n const [schema, name] = tableName.includes(\".\") ? tableName.split(\".\") : [\"public\", tableName];\n statements.push(`DROP TABLE IF EXISTS \"${schema}\".\"${name}\" CASCADE;`);\n }\n\n // Generate ALTER TABLE statements for column changes\n // Handle column additions\n for (const added of diff.columns.added) {\n statements.push(generateAddColumnSQL(added.table, added.column, added.definition));\n }\n\n // Handle column deletions\n for (const deleted of diff.columns.deleted) {\n statements.push(generateDropColumnSQL(deleted.table, deleted.column));\n }\n\n // Handle column modifications\n for (const modified of diff.columns.modified) {\n const alterStatements = generateAlterColumnSQL(\n modified.table,\n modified.column,\n modified.changes\n );\n statements.push(...alterStatements);\n }\n\n // Generate DROP INDEX statements (including altered ones - drop old version)\n for (const index of diff.indexes.deleted) {\n statements.push(generateDropIndexSQL(index));\n }\n\n // Drop old version of altered indexes\n for (const alteredIndex of diff.indexes.altered) {\n statements.push(generateDropIndexSQL(alteredIndex.old));\n }\n\n // Generate CREATE INDEX statements (including altered ones - create new version)\n for (const index of diff.indexes.created) {\n statements.push(generateCreateIndexSQL(index));\n }\n\n // Create new version of altered indexes\n for (const alteredIndex of diff.indexes.altered) {\n statements.push(generateCreateIndexSQL(alteredIndex.new));\n }\n\n // Generate CREATE UNIQUE CONSTRAINT statements\n for (const constraint of diff.uniqueConstraints.created) {\n // Skip if it's part of a new table (already handled)\n const isNewTable = diff.tables.created.some((tableName) => {\n const [schema, table] = tableName.includes(\".\")\n ? tableName.split(\".\")\n : [\"public\", tableName];\n const constraintTable =\n (constraint as SchemaUniqueConstraint & { table?: string }).table || \"\";\n const [constraintSchema, constraintTableName] = constraintTable.includes(\".\")\n ? constraintTable.split(\".\")\n : [\"public\", constraintTable];\n return table === constraintTableName && schema === constraintSchema;\n });\n\n if (!isNewTable) {\n statements.push(generateCreateUniqueConstraintSQL(constraint));\n }\n }\n\n // Generate DROP UNIQUE CONSTRAINT statements\n for (const constraint of diff.uniqueConstraints.deleted) {\n statements.push(generateDropUniqueConstraintSQL(constraint));\n }\n\n // Generate CREATE CHECK CONSTRAINT statements\n for (const constraint of diff.checkConstraints.created) {\n // Skip if it's part of a new table (already handled)\n const isNewTable = diff.tables.created.some((tableName) => {\n const [schema, table] = tableName.includes(\".\")\n ? tableName.split(\".\")\n : [\"public\", tableName];\n const constraintTable =\n (constraint as SchemaCheckConstraint & { table?: string }).table || \"\";\n const [constraintSchema, constraintTableName] = constraintTable.includes(\".\")\n ? constraintTable.split(\".\")\n : [\"public\", constraintTable];\n return table === constraintTableName && schema === constraintSchema;\n });\n\n if (!isNewTable) {\n statements.push(generateCreateCheckConstraintSQL(constraint));\n }\n }\n\n // Generate DROP CHECK CONSTRAINT statements\n for (const constraint of diff.checkConstraints.deleted) {\n statements.push(generateDropCheckConstraintSQL(constraint));\n }\n\n // Handle foreign key deletions first (including altered ones)\n for (const fk of diff.foreignKeys.deleted) {\n statements.push(generateDropForeignKeySQL(fk));\n }\n\n // Drop old version of altered foreign keys\n for (const alteredFK of diff.foreignKeys.altered) {\n statements.push(generateDropForeignKeySQL(alteredFK.old));\n }\n\n // Handle foreign key creations (for existing tables)\n for (const fk of diff.foreignKeys.created) {\n // Only add if it's not part of a new table (those were handled above)\n // Check both with and without schema prefix\n const tableFrom = fk.tableFrom || \"\";\n const schemaFrom = fk.schemaFrom || \"public\";\n\n const isNewTable = diff.tables.created.some((tableName) => {\n // Compare table names, handling schema prefixes\n const [createdSchema, createdTable] = tableName.includes(\".\")\n ? tableName.split(\".\")\n : [\"public\", tableName];\n\n // Compare using the actual schema and table from the FK\n return createdTable === tableFrom && createdSchema === schemaFrom;\n });\n\n if (!isNewTable) {\n statements.push(generateCreateForeignKeySQL(fk));\n }\n }\n\n // Create new version of altered foreign keys\n for (const alteredFK of diff.foreignKeys.altered) {\n statements.push(generateCreateForeignKeySQL(alteredFK.new));\n }\n\n return statements;\n}\n\n/**\n * Generate CREATE TABLE SQL (following Drizzle's pattern)\n * Returns the table creation SQL and separate foreign key SQLs\n */\nfunction generateCreateTableSQL(\n fullTableName: string,\n table: SchemaTable\n): { tableSQL: string; fkSQLs: string[] } {\n const [schema, tableName] = fullTableName.includes(\".\")\n ? fullTableName.split(\".\")\n : [\"public\", fullTableName];\n const columns: string[] = [];\n const fkSQLs: string[] = [];\n\n // Add columns\n for (const [colName, colDef] of Object.entries(table.columns || {})) {\n columns.push(generateColumnDefinition(colName, colDef));\n }\n\n // Add composite primary keys if exists\n const primaryKeys = table.compositePrimaryKeys || {};\n for (const [pkName, pkDef] of Object.entries(primaryKeys)) {\n const pk = pkDef as SchemaPrimaryKey;\n if (pk.columns && pk.columns.length > 0) {\n columns.push(\n `CONSTRAINT \"${pkName}\" PRIMARY KEY (${pk.columns.map((c) => `\"${c}\"`).join(\", \")})`\n );\n }\n }\n\n // Add unique constraints\n const uniqueConstraints = table.uniqueConstraints || {};\n for (const [uqName, uqDef] of Object.entries(uniqueConstraints)) {\n const uq = uqDef as SchemaUniqueConstraint;\n if (uq.columns && uq.columns.length > 0) {\n const uniqueDef = uq.nullsNotDistinct\n ? `CONSTRAINT \"${uqName}\" UNIQUE NULLS NOT DISTINCT (${uq.columns.map((c) => `\"${c}\"`).join(\", \")})`\n : `CONSTRAINT \"${uqName}\" UNIQUE (${uq.columns.map((c) => `\"${c}\"`).join(\", \")})`;\n columns.push(uniqueDef);\n }\n }\n\n // Add check constraints\n const checkConstraints = table.checkConstraints || {};\n for (const [checkName, checkDef] of Object.entries(checkConstraints)) {\n const check = checkDef as SchemaCheckConstraint;\n if (check.value) {\n columns.push(`CONSTRAINT \"${checkName}\" CHECK (${check.value})`);\n }\n }\n\n // Following drizzle-kit pattern: don't create schema here, it's handled separately\n const tableSQL = `CREATE TABLE IF NOT EXISTS \"${schema}\".\"${tableName}\" (\\n ${columns.join(\",\\n \")}\\n);`;\n\n // Collect foreign keys to be added AFTER all tables are created\n const foreignKeys = table.foreignKeys || {};\n for (const [fkName, fkDef] of Object.entries(foreignKeys)) {\n const fk = fkDef as SchemaForeignKey;\n const fkSQL = `ALTER TABLE \"${schema}\".\"${tableName}\" ADD CONSTRAINT \"${fkName}\" FOREIGN KEY (${fk.columnsFrom.map((c) => `\"${c}\"`).join(\", \")}) REFERENCES \"${fk.schemaTo || \"public\"}\".\"${fk.tableTo}\" (${fk.columnsTo.map((c) => `\"${c}\"`).join(\", \")})${fk.onDelete ? ` ON DELETE ${fk.onDelete}` : \"\"}${fk.onUpdate ? ` ON UPDATE ${fk.onUpdate}` : \"\"};`;\n fkSQLs.push(fkSQL);\n }\n\n return { tableSQL, fkSQLs };\n}\n\n/**\n * Generate column definition (following Drizzle's pattern)\n */\nfunction generateColumnDefinition(name: string, def: SchemaColumn): string {\n let sql = `\"${name}\" ${def.type}`;\n\n // Handle primary key that's not part of composite\n if (def.primaryKey && !def.type.includes(\"SERIAL\")) {\n sql += \" PRIMARY KEY\";\n }\n\n // Add NOT NULL constraint\n if (def.notNull) {\n sql += \" NOT NULL\";\n }\n\n // Add DEFAULT value - properly formatted\n if (def.default !== undefined) {\n const defaultValue = formatDefaultValue(def.default, def.type);\n sql += ` DEFAULT ${defaultValue}`;\n }\n\n return sql;\n}\n\n/**\n * Generate ALTER TABLE ADD COLUMN SQL\n * Based on Drizzle's PgAlterTableAddColumnConvertor\n */\nfunction generateAddColumnSQL(table: string, column: string, definition: SchemaColumn): string {\n const [schema, tableName] = table.includes(\".\") ? table.split(\".\") : [\"public\", table];\n const tableNameWithSchema = `\"${schema}\".\"${tableName}\"`;\n\n // Build column definition parts in the correct order (like Drizzle)\n const parts: string[] = [`\"${column}\"`];\n\n // Type\n parts.push(definition.type);\n\n // Primary key\n if (definition.primaryKey) {\n parts.push(\"PRIMARY KEY\");\n }\n\n // Default value - needs proper formatting based on type\n if (definition.default !== undefined) {\n const defaultValue = formatDefaultValue(definition.default, definition.type);\n if (defaultValue) {\n parts.push(`DEFAULT ${defaultValue}`);\n }\n }\n\n // Generated columns\n const definitionWithGenerated = definition as SchemaColumn & { generated?: string };\n if (definitionWithGenerated.generated) {\n parts.push(`GENERATED ALWAYS AS (${definitionWithGenerated.generated}) STORED`);\n }\n\n // NOT NULL constraint - comes after DEFAULT\n if (definition.notNull) {\n parts.push(\"NOT NULL\");\n }\n\n return `ALTER TABLE ${tableNameWithSchema} ADD COLUMN ${parts.join(\" \")};`;\n}\n\n/**\n * Generate ALTER TABLE DROP COLUMN SQL\n * Based on Drizzle's approach with CASCADE\n */\nfunction generateDropColumnSQL(table: string, column: string): string {\n const [schema, tableName] = table.includes(\".\") ? table.split(\".\") : [\"public\", table];\n const tableNameWithSchema = `\"${schema}\".\"${tableName}\"`;\n // Use CASCADE to handle dependent objects\n return `ALTER TABLE ${tableNameWithSchema} DROP COLUMN \"${column}\" CASCADE;`;\n}\n\n// Column change tracking interface\ninterface ColumnChangeInfo {\n from?: SchemaColumn;\n to?: SchemaColumn;\n}\n\n/**\n * Generate ALTER TABLE ALTER COLUMN SQL\n * Based on Drizzle's approach with proper type casting and handling\n */\nfunction generateAlterColumnSQL(\n table: string,\n column: string,\n changes: ColumnChangeInfo\n): string[] {\n const [schema, tableName] = table.includes(\".\") ? table.split(\".\") : [\"public\", table];\n const tableNameWithSchema = `\"${schema}\".\"${tableName}\"`;\n const statements: string[] = [];\n\n // Handle type changes - need to handle enums and complex types\n const changesTo = changes.to;\n const changesFrom = changes.from;\n const changesToType = changesTo?.type;\n const changesFromType = changesFrom?.type;\n if (changesToType !== changesFromType) {\n const newType = changesToType || \"TEXT\";\n\n // Check if we need a USING clause for type conversion\n const needsUsing = checkIfNeedsUsingClause(changesFromType || \"\", newType);\n\n if (needsUsing) {\n // For complex type changes, use USING clause like Drizzle\n statements.push(\n `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN \"${column}\" TYPE ${newType} USING \"${column}\"::text::${newType};`\n );\n } else {\n statements.push(\n `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN \"${column}\" SET DATA TYPE ${newType};`\n );\n }\n }\n\n // Handle NOT NULL changes\n const changesToNotNull = changesTo?.notNull;\n const changesFromNotNull = changesFrom?.notNull;\n if (changesToNotNull !== changesFromNotNull) {\n if (changesToNotNull) {\n // When adding NOT NULL, might need to set defaults for existing NULL values\n statements.push(`ALTER TABLE ${tableNameWithSchema} ALTER COLUMN \"${column}\" SET NOT NULL;`);\n } else {\n statements.push(`ALTER TABLE ${tableNameWithSchema} ALTER COLUMN \"${column}\" DROP NOT NULL;`);\n }\n }\n\n // Handle default value changes\n const changesToDefault = changesTo?.default;\n const changesFromDefault = changesFrom?.default;\n if (changesToDefault !== changesFromDefault) {\n if (changesToDefault !== undefined) {\n const defaultValue = formatDefaultValue(changesToDefault, changesToType || \"\");\n statements.push(\n `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN \"${column}\" SET DEFAULT ${defaultValue};`\n );\n } else {\n statements.push(`ALTER TABLE ${tableNameWithSchema} ALTER COLUMN \"${column}\" DROP DEFAULT;`);\n }\n }\n\n return statements;\n}\n\n/**\n * Check if a type change needs a USING clause\n * Based on Drizzle's type conversion logic\n */\nfunction checkIfNeedsUsingClause(fromType: string, toType: string): boolean {\n if (!fromType || !toType) return false;\n\n // Enum changes always need USING\n if (fromType.includes(\"enum\") || toType.includes(\"enum\")) {\n return true;\n }\n\n const fromBase = fromType.split(\"(\")[0].toLowerCase();\n const toBase = toType.split(\"(\")[0].toLowerCase();\n\n // Text/varchar to JSONB always needs USING\n if (\n (fromBase === \"text\" || fromBase === \"varchar\" || fromBase === \"character varying\") &&\n (toBase === \"jsonb\" || toBase === \"json\")\n ) {\n return true;\n }\n\n // Some specific type conversions need USING\n const needsUsingPairs = [\n [\"integer\", \"boolean\"],\n [\"boolean\", \"integer\"],\n [\"text\", \"integer\"],\n [\"text\", \"numeric\"],\n [\"text\", \"boolean\"],\n [\"text\", \"uuid\"],\n [\"text\", \"jsonb\"],\n [\"text\", \"json\"],\n [\"varchar\", \"integer\"],\n [\"varchar\", \"numeric\"],\n [\"varchar\", \"boolean\"],\n [\"varchar\", \"uuid\"],\n [\"varchar\", \"jsonb\"],\n [\"varchar\", \"json\"],\n [\"character varying\", \"jsonb\"],\n [\"character varying\", \"json\"],\n // Add more as needed based on PostgreSQL casting rules\n ];\n\n for (const [from, to] of needsUsingPairs) {\n if ((fromBase === from && toBase === to) || (fromBase === to && toBase === from)) {\n return true;\n }\n }\n\n return false;\n}\n\n// Default value type - can be string, number, boolean, or null\ntype DefaultValue = string | number | boolean | null | undefined;\n\n/**\n * Format a default value for SQL\n * Based on Drizzle's default value formatting\n */\nfunction formatDefaultValue(value: DefaultValue, type: string): string {\n // Handle NULL\n if (value === null || value === \"NULL\") {\n return \"NULL\";\n }\n\n // Handle boolean\n if (type && (type.toLowerCase().includes(\"boolean\") || type.toLowerCase() === \"bool\")) {\n if (value === true || value === \"true\" || value === \"t\" || value === 1) {\n return \"true\";\n }\n if (value === false || value === \"false\" || value === \"f\" || value === 0) {\n return \"false\";\n }\n }\n\n // Handle numeric types\n if (type?.match(/^(integer|bigint|smallint|numeric|decimal|real|double)/i)) {\n return String(value);\n }\n\n // Handle SQL expressions and pre-formatted defaults\n if (typeof value === \"string\") {\n // Already formatted with type cast (e.g., '[]'::jsonb, '{}'::jsonb)\n // These come from the snapshot and are already properly formatted\n if (value.includes(\"::\")) {\n return value;\n }\n\n // Already quoted string literals (from snapshot)\n // These start and end with single quotes\n if (value.startsWith(\"'\") && value.endsWith(\"'\")) {\n return value;\n }\n\n // SQL functions like now(), gen_random_uuid(), etc.\n if (value.match(/^\\w+\\(\\)/i) || (value.includes(\"(\") && value.includes(\")\"))) {\n return value;\n }\n\n // SQL expressions starting with CURRENT_\n if (value.toUpperCase().startsWith(\"CURRENT_\")) {\n return value;\n }\n\n // Otherwise, it's an unquoted string literal - wrap and escape\n return `'${value.replace(/'/g, \"''\")}'`;\n }\n\n // Default: return as-is\n return String(value);\n}\n\n// Extended index interface with table reference\ninterface SchemaIndexWithTableRef {\n name: string;\n columns: Array<{ expression: string; isExpression: boolean; asc?: boolean; nulls?: string }>;\n isUnique: boolean;\n method?: string;\n where?: string;\n concurrently?: boolean;\n table?: string;\n}\n\n/**\n * Generate CREATE INDEX SQL\n */\nfunction generateCreateIndexSQL(index: SchemaIndexWithTableRef): string {\n const unique = index.isUnique ? \"UNIQUE \" : \"\";\n const method = index.method || \"btree\";\n const columns = index.columns\n .map((c) => {\n if (c.isExpression) {\n return c.expression;\n }\n // Only add DESC if explicitly set to false, no NULLS clause by default\n return `\"${c.expression}\"${c.asc === false ? \" DESC\" : \"\"}`;\n })\n .join(\", \");\n\n // Extract index name and table with proper schema handling\n const indexName = index.name.includes(\".\") ? index.name.split(\".\")[1] : index.name;\n\n // Keep the full table name with schema if present\n let tableRef: string;\n const indexTable = index.table;\n if (indexTable?.includes(\".\")) {\n const [schema, table] = indexTable.split(\".\");\n tableRef = `\"${schema}\".\"${table}\"`;\n } else {\n tableRef = `\"${indexTable || \"\"}\"`;\n }\n\n // Include schema in table reference for correct index creation\n return `CREATE ${unique}INDEX \"${indexName}\" ON ${tableRef} USING ${method} (${columns});`;\n}\n\n/**\n * Generate DROP INDEX SQL\n */\nfunction generateDropIndexSQL(index: SchemaIndex | string): string {\n // Extract just the index name without schema\n const indexNameFull = typeof index === \"string\" ? index : index.name;\n const indexName = indexNameFull.includes(\".\") ? indexNameFull.split(\".\")[1] : indexNameFull;\n // Match Drizzle's format - no schema qualification\n return `DROP INDEX IF EXISTS \"${indexName}\";`;\n}\n\n/**\n * Generate CREATE FOREIGN KEY SQL (for existing tables)\n */\nfunction generateCreateForeignKeySQL(fk: SchemaForeignKey): string {\n const schemaFrom = fk.schemaFrom || \"public\";\n const schemaTo = fk.schemaTo || \"public\";\n const tableFrom = fk.tableFrom;\n const columnsFrom = fk.columnsFrom.map((c: string) => `\"${c}\"`).join(\", \");\n const columnsTo = fk.columnsTo.map((c: string) => `\"${c}\"`).join(\", \");\n\n let sql = `ALTER TABLE \"${schemaFrom}\".\"${tableFrom}\" ADD CONSTRAINT \"${fk.name}\" FOREIGN KEY (${columnsFrom}) REFERENCES \"${schemaTo}\".\"${fk.tableTo}\" (${columnsTo})`;\n\n if (fk.onDelete) {\n sql += ` ON DELETE ${fk.onDelete}`;\n }\n\n if (fk.onUpdate) {\n sql += ` ON UPDATE ${fk.onUpdate}`;\n }\n\n return `${sql};`;\n}\n\n/**\n * Generate DROP FOREIGN KEY SQL\n */\nfunction generateDropForeignKeySQL(fk: SchemaForeignKey): string {\n const [schema, tableName] = fk.tableFrom\n ? fk.tableFrom.includes(\".\")\n ? fk.tableFrom.split(\".\")\n : [\"public\", fk.tableFrom]\n : [\"public\", \"\"];\n return `ALTER TABLE \"${schema}\".\"${tableName}\" DROP CONSTRAINT \"${fk.name}\";`;\n}\n\n/**\n * Generate SQL for renaming a table\n */\nexport function generateRenameTableSQL(oldName: string, newName: string): string {\n const [oldSchema, oldTable] = oldName.includes(\".\") ? oldName.split(\".\") : [\"public\", oldName];\n const [, newTable] = newName.includes(\".\") ? newName.split(\".\") : [\"public\", newName];\n return `ALTER TABLE \"${oldSchema}\".\"${oldTable}\" RENAME TO \"${newTable}\";`;\n}\n\n/**\n * Generate SQL for renaming a column\n */\nexport function generateRenameColumnSQL(table: string, oldName: string, newName: string): string {\n const [schema, tableName] = table.includes(\".\") ? table.split(\".\") : [\"public\", table];\n return `ALTER TABLE \"${schema}\".\"${tableName}\" RENAME COLUMN \"${oldName}\" TO \"${newName}\";`;\n}\n\n// Extended constraint interfaces with table reference\ninterface UniqueConstraintWithTable extends SchemaUniqueConstraint {\n table?: string;\n}\n\ninterface CheckConstraintWithTable extends SchemaCheckConstraint {\n table?: string;\n}\n\n/**\n * Generate CREATE UNIQUE CONSTRAINT SQL\n */\nfunction generateCreateUniqueConstraintSQL(constraint: UniqueConstraintWithTable): string {\n const table = constraint.table || \"\";\n const [schema, tableName] = table.includes(\".\") ? table.split(\".\") : [\"public\", table];\n\n const name = constraint.name;\n const columns = constraint.columns.map((c) => `\"${c}\"`).join(\", \");\n\n let sql = `ALTER TABLE \"${schema}\".\"${tableName}\" ADD CONSTRAINT \"${name}\" UNIQUE`;\n\n // Handle NULLS NOT DISTINCT if specified (PostgreSQL 15+)\n if (constraint.nullsNotDistinct) {\n sql += ` NULLS NOT DISTINCT`;\n }\n\n sql += ` (${columns});`;\n\n return sql;\n}\n\n/**\n * Generate DROP UNIQUE CONSTRAINT SQL\n */\nfunction generateDropUniqueConstraintSQL(constraint: UniqueConstraintWithTable): string {\n const table = constraint.table || \"\";\n const [schema, tableName] = table.includes(\".\") ? table.split(\".\") : [\"public\", table];\n\n return `ALTER TABLE \"${schema}\".\"${tableName}\" DROP CONSTRAINT \"${constraint.name}\";`;\n}\n\n/**\n * Generate CREATE CHECK CONSTRAINT SQL\n */\nfunction generateCreateCheckConstraintSQL(constraint: CheckConstraintWithTable): string {\n const table = constraint.table || \"\";\n const [schema, tableName] = table.includes(\".\") ? table.split(\".\") : [\"public\", table];\n\n const name = constraint.name;\n const value = constraint.value;\n\n return `ALTER TABLE \"${schema}\".\"${tableName}\" ADD CONSTRAINT \"${name}\" CHECK (${value});`;\n}\n\n/**\n * Generate DROP CHECK CONSTRAINT SQL\n */\nfunction generateDropCheckConstraintSQL(constraint: CheckConstraintWithTable): string {\n const table = constraint.table || \"\";\n const [schema, tableName] = table.includes(\".\") ? table.split(\".\") : [\"public\", table];\n\n return `ALTER TABLE \"${schema}\".\"${tableName}\" DROP CONSTRAINT \"${constraint.name}\";`;\n}\n",
13
+ "import { logger } from \"@elizaos/core\";\nimport type {\n SchemaCheckConstraint,\n SchemaColumn,\n SchemaForeignKey,\n SchemaIndex,\n SchemaPrimaryKey,\n SchemaSnapshot,\n SchemaTable,\n SchemaUniqueConstraint,\n} from \"../types\";\nimport type { SchemaDiff } from \"./diff-calculator\";\n\n/**\n * Data loss detection result\n * Based on Drizzle's pgPushUtils approach\n */\nexport interface DataLossCheck {\n hasDataLoss: boolean;\n tablesToRemove: string[];\n columnsToRemove: string[];\n tablesToTruncate: string[];\n typeChanges: Array<{\n table: string;\n column: string;\n from: string;\n to: string;\n }>;\n warnings: string[];\n requiresConfirmation: boolean;\n}\n\n/**\n * Check for potential data loss in schema changes\n * Based on Drizzle's pgSuggestions function\n */\nexport function checkForDataLoss(diff: SchemaDiff): DataLossCheck {\n const result: DataLossCheck = {\n hasDataLoss: false,\n tablesToRemove: [],\n columnsToRemove: [],\n tablesToTruncate: [],\n typeChanges: [],\n warnings: [],\n requiresConfirmation: false,\n };\n\n // Check for table deletions\n if (diff.tables.deleted.length > 0) {\n result.hasDataLoss = true;\n result.requiresConfirmation = true;\n result.tablesToRemove = [...diff.tables.deleted];\n for (const table of diff.tables.deleted) {\n result.warnings.push(`Table \"${table}\" will be dropped with all its data`);\n }\n }\n\n // Check for column deletions\n if (diff.columns.deleted.length > 0) {\n result.hasDataLoss = true;\n result.requiresConfirmation = true;\n for (const col of diff.columns.deleted) {\n result.columnsToRemove.push(`${col.table}.${col.column}`);\n result.warnings.push(`Column \"${col.column}\" in table \"${col.table}\" will be dropped`);\n }\n }\n\n // Check for column type changes that might cause data loss\n for (const modified of diff.columns.modified) {\n const from = modified.changes.from;\n const to = modified.changes.to;\n\n if (!from || !to) continue;\n\n // Check if type change is destructive\n if (from.type !== to.type) {\n const isDestructive = checkIfTypeChangeIsDestructive(from.type, to.type);\n\n if (isDestructive) {\n result.hasDataLoss = true;\n result.requiresConfirmation = true;\n result.typeChanges.push({\n table: modified.table,\n column: modified.column,\n from: from.type,\n to: to.type,\n });\n result.tablesToTruncate.push(modified.table);\n result.warnings.push(\n `Column \"${modified.column}\" in table \"${modified.table}\" changes type from \"${from.type}\" to \"${to.type}\". ` +\n `This may require truncating the table to avoid data conversion errors.`\n );\n }\n }\n\n // Check for adding NOT NULL without default to existing column\n if (!from.notNull && to.notNull && !to.default) {\n result.hasDataLoss = true;\n result.requiresConfirmation = true;\n result.warnings.push(\n `Column \"${modified.column}\" in table \"${modified.table}\" is becoming NOT NULL without a default value. ` +\n `This will fail if the table contains NULL values.`\n );\n }\n }\n\n // Check for adding NOT NULL columns without defaults\n for (const added of diff.columns.added) {\n if (added.definition.notNull && !added.definition.default) {\n // This is only a problem if the table already has data\n // We'll flag it as a potential issue\n result.warnings.push(\n `Column \"${added.column}\" is being added to table \"${added.table}\" as NOT NULL without a default value. ` +\n `This will fail if the table contains data.`\n );\n // Don't set requiresConfirmation here - it's only a warning\n }\n }\n\n return result;\n}\n\n/**\n * Normalize SQL types for comparison\n * Handles equivalent type variations between introspected DB and schema definitions\n */\nfunction normalizeType(type: string | undefined): string {\n if (!type) return \"\";\n\n const normalized = type.toLowerCase().trim();\n\n // Handle timestamp variations - all are equivalent\n if (\n normalized === \"timestamp without time zone\" ||\n normalized === \"timestamp with time zone\" ||\n normalized === \"timestamptz\"\n ) {\n return \"timestamp\";\n }\n\n // Handle serial vs integer with identity\n // serial is essentially integer with auto-increment\n if (normalized === \"serial\") {\n return \"integer\";\n }\n if (normalized === \"bigserial\") {\n return \"bigint\";\n }\n if (normalized === \"smallserial\") {\n return \"smallint\";\n }\n\n // Handle numeric/decimal equivalence\n if (normalized.startsWith(\"numeric\") || normalized.startsWith(\"decimal\")) {\n // Extract precision and scale if present\n const match = normalized.match(/\\((\\d+)(?:,\\s*(\\d+))?\\)/);\n if (match) {\n return `numeric(${match[1]}${match[2] ? `,${match[2]}` : \"\"})`;\n }\n return \"numeric\";\n }\n\n // Handle varchar/character varying\n if (normalized.startsWith(\"character varying\")) {\n return normalized.replace(\"character varying\", \"varchar\");\n }\n\n // Handle text array variations\n if (normalized === \"text[]\" || normalized === \"_text\") {\n return \"text[]\";\n }\n\n return normalized;\n}\n\n/**\n * Check if a type change is destructive\n * Based on PostgreSQL's type casting rules\n */\nfunction checkIfTypeChangeIsDestructive(fromType: string, toType: string): boolean {\n // First normalize the types to handle equivalent variations\n const normalizedFrom = normalizeType(fromType);\n const normalizedTo = normalizeType(toType);\n\n // If normalized types match, it's not destructive\n if (normalizedFrom === normalizedTo) {\n return false;\n }\n\n // Safe conversions (PostgreSQL) - based on Drizzle's logic\n const safeConversions: Record<string, string[]> = {\n smallint: [\"integer\", \"bigint\", \"numeric\", \"real\", \"double precision\"],\n integer: [\"bigint\", \"numeric\", \"real\", \"double precision\"],\n bigint: [\"numeric\"],\n real: [\"double precision\"],\n varchar: [\"text\"],\n char: [\"varchar\", \"text\"],\n citext: [\"text\"],\n text: [\"citext\"],\n // UUID to text is safe\n uuid: [\"text\", \"varchar\"],\n // Timestamp variations are generally safe (now handled by normalization)\n timestamp: [\"timestamp\"], // Simplified since normalization handles variations\n // Date/time conversions\n date: [\"timestamp\"],\n time: [\"timetz\"],\n };\n\n const fromBase = normalizedFrom.split(\"(\")[0];\n const toBase = normalizedTo.split(\"(\")[0];\n\n // Same type is always safe\n if (fromBase === toBase) {\n return false;\n }\n\n // Check if it's a safe conversion\n const safeTo = safeConversions[fromBase];\n if (safeTo?.includes(toBase)) {\n return false;\n }\n\n // All other conversions are considered potentially destructive\n return true;\n}\n\n/**\n * Generate SQL statements from a schema diff\n * This follows Drizzle's approach: create all tables first, then add foreign keys\n */\nexport async function generateMigrationSQL(\n previousSnapshot: SchemaSnapshot | null,\n currentSnapshot: SchemaSnapshot,\n diff?: SchemaDiff\n): Promise<string[]> {\n const statements: string[] = [];\n\n // If no diff provided, calculate it\n if (!diff) {\n const { calculateDiff } = await import(\"./diff-calculator\");\n diff = await calculateDiff(previousSnapshot, currentSnapshot);\n }\n\n // Check for data loss\n const dataLossCheck = checkForDataLoss(diff);\n\n // Log warnings if any\n if (dataLossCheck.warnings.length > 0) {\n logger.warn(\n { src: \"plugin:sql\", warnings: dataLossCheck.warnings },\n \"Schema changes may cause data loss\"\n );\n }\n\n // Phase 1: Collect unique schemas and create them first\n const schemasToCreate = new Set<string>();\n for (const tableName of diff.tables.created) {\n const table = currentSnapshot.tables[tableName];\n if (table) {\n const schema = table.schema || \"public\";\n if (schema !== \"public\") {\n schemasToCreate.add(schema);\n }\n }\n }\n\n // Create schemas first (following drizzle-kit pattern)\n for (const schema of schemasToCreate) {\n statements.push(`CREATE SCHEMA IF NOT EXISTS \"${schema}\";`);\n }\n\n // Phase 2: Generate CREATE TABLE statements for new tables (WITHOUT foreign keys)\n const createTableStatements: string[] = [];\n const foreignKeyStatements: string[] = [];\n\n for (const tableName of diff.tables.created) {\n const table = currentSnapshot.tables[tableName];\n if (table) {\n const { tableSQL, fkSQLs } = generateCreateTableSQL(tableName, table);\n createTableStatements.push(tableSQL);\n foreignKeyStatements.push(...fkSQLs);\n }\n }\n\n // Add all CREATE TABLE statements\n statements.push(...createTableStatements);\n\n // Phase 3: Add all foreign keys AFTER tables are created\n // Deduplicate foreign key statements to avoid duplicate constraints\n const uniqueFKs = new Set<string>();\n const dedupedFKStatements: string[] = [];\n\n for (const fkSQL of foreignKeyStatements) {\n // Extract constraint name to check for duplicates\n const match = fkSQL.match(/ADD CONSTRAINT \"([^\"]+)\"/);\n if (match) {\n const constraintName = match[1];\n if (!uniqueFKs.has(constraintName)) {\n uniqueFKs.add(constraintName);\n dedupedFKStatements.push(fkSQL);\n }\n } else {\n dedupedFKStatements.push(fkSQL);\n }\n }\n\n statements.push(...dedupedFKStatements);\n\n // Phase 4: Handle table modifications\n\n // Generate DROP TABLE statements for deleted tables\n for (const tableName of diff.tables.deleted) {\n const [schema, name] = tableName.includes(\".\") ? tableName.split(\".\") : [\"public\", tableName];\n statements.push(`DROP TABLE IF EXISTS \"${schema}\".\"${name}\" CASCADE;`);\n }\n\n // Generate ALTER TABLE statements for column changes\n // Handle column additions\n for (const added of diff.columns.added) {\n statements.push(generateAddColumnSQL(added.table, added.column, added.definition));\n }\n\n // Handle column deletions\n for (const deleted of diff.columns.deleted) {\n statements.push(generateDropColumnSQL(deleted.table, deleted.column));\n }\n\n // Handle column modifications\n for (const modified of diff.columns.modified) {\n const alterStatements = generateAlterColumnSQL(\n modified.table,\n modified.column,\n modified.changes\n );\n statements.push(...alterStatements);\n }\n\n // Generate DROP INDEX statements (including altered ones - drop old version)\n for (const index of diff.indexes.deleted) {\n statements.push(generateDropIndexSQL(index));\n }\n\n // Drop old version of altered indexes\n for (const alteredIndex of diff.indexes.altered) {\n statements.push(generateDropIndexSQL(alteredIndex.old));\n }\n\n // Generate CREATE INDEX statements (including altered ones - create new version)\n for (const index of diff.indexes.created) {\n statements.push(generateCreateIndexSQL(index));\n }\n\n // Create new version of altered indexes\n for (const alteredIndex of diff.indexes.altered) {\n statements.push(generateCreateIndexSQL(alteredIndex.new));\n }\n\n // Generate CREATE UNIQUE CONSTRAINT statements\n for (const constraint of diff.uniqueConstraints.created) {\n // Skip if it's part of a new table (already handled)\n const isNewTable = diff.tables.created.some((tableName) => {\n const [schema, table] = tableName.includes(\".\")\n ? tableName.split(\".\")\n : [\"public\", tableName];\n const constraintTable =\n (constraint as SchemaUniqueConstraint & { table?: string }).table || \"\";\n const [constraintSchema, constraintTableName] = constraintTable.includes(\".\")\n ? constraintTable.split(\".\")\n : [\"public\", constraintTable];\n return table === constraintTableName && schema === constraintSchema;\n });\n\n if (!isNewTable) {\n statements.push(generateCreateUniqueConstraintSQL(constraint));\n }\n }\n\n // Generate DROP UNIQUE CONSTRAINT statements\n for (const constraint of diff.uniqueConstraints.deleted) {\n statements.push(generateDropUniqueConstraintSQL(constraint));\n }\n\n // Generate CREATE CHECK CONSTRAINT statements\n for (const constraint of diff.checkConstraints.created) {\n // Skip if it's part of a new table (already handled)\n const isNewTable = diff.tables.created.some((tableName) => {\n const [schema, table] = tableName.includes(\".\")\n ? tableName.split(\".\")\n : [\"public\", tableName];\n const constraintTable =\n (constraint as SchemaCheckConstraint & { table?: string }).table || \"\";\n const [constraintSchema, constraintTableName] = constraintTable.includes(\".\")\n ? constraintTable.split(\".\")\n : [\"public\", constraintTable];\n return table === constraintTableName && schema === constraintSchema;\n });\n\n if (!isNewTable) {\n statements.push(generateCreateCheckConstraintSQL(constraint));\n }\n }\n\n // Generate DROP CHECK CONSTRAINT statements\n for (const constraint of diff.checkConstraints.deleted) {\n statements.push(generateDropCheckConstraintSQL(constraint));\n }\n\n // Handle foreign key deletions first (including altered ones)\n for (const fk of diff.foreignKeys.deleted) {\n statements.push(generateDropForeignKeySQL(fk));\n }\n\n // Drop old version of altered foreign keys\n for (const alteredFK of diff.foreignKeys.altered) {\n statements.push(generateDropForeignKeySQL(alteredFK.old));\n }\n\n // Handle foreign key creations (for existing tables)\n for (const fk of diff.foreignKeys.created) {\n // Only add if it's not part of a new table (those were handled above)\n // Check both with and without schema prefix\n const tableFrom = fk.tableFrom || \"\";\n const schemaFrom = fk.schemaFrom || \"public\";\n\n const isNewTable = diff.tables.created.some((tableName) => {\n // Compare table names, handling schema prefixes\n const [createdSchema, createdTable] = tableName.includes(\".\")\n ? tableName.split(\".\")\n : [\"public\", tableName];\n\n // Compare using the actual schema and table from the FK\n return createdTable === tableFrom && createdSchema === schemaFrom;\n });\n\n if (!isNewTable) {\n statements.push(generateCreateForeignKeySQL(fk));\n }\n }\n\n // Create new version of altered foreign keys\n for (const alteredFK of diff.foreignKeys.altered) {\n statements.push(generateCreateForeignKeySQL(alteredFK.new));\n }\n\n return statements;\n}\n\n/**\n * Generate CREATE TABLE SQL (following Drizzle's pattern)\n * Returns the table creation SQL and separate foreign key SQLs\n */\nfunction generateCreateTableSQL(\n fullTableName: string,\n table: SchemaTable\n): { tableSQL: string; fkSQLs: string[] } {\n const [schema, tableName] = fullTableName.includes(\".\")\n ? fullTableName.split(\".\")\n : [\"public\", fullTableName];\n const columns: string[] = [];\n const fkSQLs: string[] = [];\n\n // Add columns\n for (const [colName, colDef] of Object.entries(table.columns || {})) {\n columns.push(generateColumnDefinition(colName, colDef));\n }\n\n // Add composite primary keys if exists\n const primaryKeys = table.compositePrimaryKeys || {};\n for (const [pkName, pkDef] of Object.entries(primaryKeys)) {\n const pk = pkDef as SchemaPrimaryKey;\n if (pk.columns && pk.columns.length > 0) {\n columns.push(\n `CONSTRAINT \"${pkName}\" PRIMARY KEY (${pk.columns.map((c) => `\"${c}\"`).join(\", \")})`\n );\n }\n }\n\n // Add unique constraints\n const uniqueConstraints = table.uniqueConstraints || {};\n for (const [uqName, uqDef] of Object.entries(uniqueConstraints)) {\n const uq = uqDef as SchemaUniqueConstraint;\n if (uq.columns && uq.columns.length > 0) {\n const uniqueDef = uq.nullsNotDistinct\n ? `CONSTRAINT \"${uqName}\" UNIQUE NULLS NOT DISTINCT (${uq.columns.map((c) => `\"${c}\"`).join(\", \")})`\n : `CONSTRAINT \"${uqName}\" UNIQUE (${uq.columns.map((c) => `\"${c}\"`).join(\", \")})`;\n columns.push(uniqueDef);\n }\n }\n\n // Add check constraints\n const checkConstraints = table.checkConstraints || {};\n for (const [checkName, checkDef] of Object.entries(checkConstraints)) {\n const check = checkDef as SchemaCheckConstraint;\n if (check.value) {\n columns.push(`CONSTRAINT \"${checkName}\" CHECK (${check.value})`);\n }\n }\n\n // Following drizzle-kit pattern: don't create schema here, it's handled separately\n const tableSQL = `CREATE TABLE IF NOT EXISTS \"${schema}\".\"${tableName}\" (\\n ${columns.join(\",\\n \")}\\n);`;\n\n // Collect foreign keys to be added AFTER all tables are created\n const foreignKeys = table.foreignKeys || {};\n for (const [fkName, fkDef] of Object.entries(foreignKeys)) {\n const fk = fkDef as SchemaForeignKey;\n const fkSQL = `ALTER TABLE \"${schema}\".\"${tableName}\" ADD CONSTRAINT \"${fkName}\" FOREIGN KEY (${fk.columnsFrom.map((c) => `\"${c}\"`).join(\", \")}) REFERENCES \"${fk.schemaTo || \"public\"}\".\"${fk.tableTo}\" (${fk.columnsTo.map((c) => `\"${c}\"`).join(\", \")})${fk.onDelete ? ` ON DELETE ${fk.onDelete}` : \"\"}${fk.onUpdate ? ` ON UPDATE ${fk.onUpdate}` : \"\"};`;\n fkSQLs.push(fkSQL);\n }\n\n return { tableSQL, fkSQLs };\n}\n\n/**\n * Generate column definition (following Drizzle's pattern)\n */\nfunction generateColumnDefinition(name: string, def: SchemaColumn): string {\n let sql = `\"${name}\" ${def.type}`;\n\n // Handle primary key that's not part of composite\n if (def.primaryKey && !def.type.includes(\"SERIAL\")) {\n sql += \" PRIMARY KEY\";\n }\n\n // Add NOT NULL constraint\n if (def.notNull) {\n sql += \" NOT NULL\";\n }\n\n // Add DEFAULT value - properly formatted\n if (def.default !== undefined) {\n const defaultValue = formatDefaultValue(def.default, def.type);\n sql += ` DEFAULT ${defaultValue}`;\n }\n\n return sql;\n}\n\n/**\n * Generate ALTER TABLE ADD COLUMN SQL\n * Based on Drizzle's PgAlterTableAddColumnConvertor\n */\nfunction generateAddColumnSQL(table: string, column: string, definition: SchemaColumn): string {\n const [schema, tableName] = table.includes(\".\") ? table.split(\".\") : [\"public\", table];\n const tableNameWithSchema = `\"${schema}\".\"${tableName}\"`;\n\n // Build column definition parts in the correct order (like Drizzle)\n const parts: string[] = [`\"${column}\"`];\n\n // Type\n parts.push(definition.type);\n\n // Primary key\n if (definition.primaryKey) {\n parts.push(\"PRIMARY KEY\");\n }\n\n // Default value - needs proper formatting based on type\n if (definition.default !== undefined) {\n const defaultValue = formatDefaultValue(definition.default, definition.type);\n if (defaultValue) {\n parts.push(`DEFAULT ${defaultValue}`);\n }\n }\n\n // Generated columns\n const definitionWithGenerated = definition as SchemaColumn & {\n generated?: string;\n };\n if (definitionWithGenerated.generated) {\n parts.push(`GENERATED ALWAYS AS (${definitionWithGenerated.generated}) STORED`);\n }\n\n // NOT NULL constraint - comes after DEFAULT\n if (definition.notNull) {\n parts.push(\"NOT NULL\");\n }\n\n return `ALTER TABLE ${tableNameWithSchema} ADD COLUMN ${parts.join(\" \")};`;\n}\n\n/**\n * Generate ALTER TABLE DROP COLUMN SQL\n * Based on Drizzle's approach with CASCADE\n */\nfunction generateDropColumnSQL(table: string, column: string): string {\n const [schema, tableName] = table.includes(\".\") ? table.split(\".\") : [\"public\", table];\n const tableNameWithSchema = `\"${schema}\".\"${tableName}\"`;\n // Use CASCADE to handle dependent objects\n return `ALTER TABLE ${tableNameWithSchema} DROP COLUMN \"${column}\" CASCADE;`;\n}\n\n// Column change tracking interface\ninterface ColumnChangeInfo {\n from?: SchemaColumn;\n to?: SchemaColumn;\n}\n\n/**\n * Generate ALTER TABLE ALTER COLUMN SQL\n * Based on Drizzle's approach with proper type casting and handling\n */\nfunction generateAlterColumnSQL(\n table: string,\n column: string,\n changes: ColumnChangeInfo\n): string[] {\n const [schema, tableName] = table.includes(\".\") ? table.split(\".\") : [\"public\", table];\n const tableNameWithSchema = `\"${schema}\".\"${tableName}\"`;\n const statements: string[] = [];\n\n // Handle type changes - need to handle enums and complex types\n const changesTo = changes.to;\n const changesFrom = changes.from;\n const changesToType = changesTo?.type;\n const changesFromType = changesFrom?.type;\n if (changesToType !== changesFromType) {\n const newType = changesToType || \"TEXT\";\n\n // Check if we need a USING clause for type conversion\n const needsUsing = checkIfNeedsUsingClause(changesFromType || \"\", newType);\n\n if (needsUsing) {\n // For complex type changes, use USING clause like Drizzle\n statements.push(\n `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN \"${column}\" TYPE ${newType} USING \"${column}\"::text::${newType};`\n );\n } else {\n statements.push(\n `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN \"${column}\" SET DATA TYPE ${newType};`\n );\n }\n }\n\n // Handle NOT NULL changes\n const changesToNotNull = changesTo?.notNull;\n const changesFromNotNull = changesFrom?.notNull;\n if (changesToNotNull !== changesFromNotNull) {\n if (changesToNotNull) {\n // When adding NOT NULL, might need to set defaults for existing NULL values\n statements.push(`ALTER TABLE ${tableNameWithSchema} ALTER COLUMN \"${column}\" SET NOT NULL;`);\n } else {\n statements.push(`ALTER TABLE ${tableNameWithSchema} ALTER COLUMN \"${column}\" DROP NOT NULL;`);\n }\n }\n\n // Handle default value changes\n const changesToDefault = changesTo?.default;\n const changesFromDefault = changesFrom?.default;\n if (changesToDefault !== changesFromDefault) {\n if (changesToDefault !== undefined) {\n const defaultValue = formatDefaultValue(changesToDefault, changesToType || \"\");\n statements.push(\n `ALTER TABLE ${tableNameWithSchema} ALTER COLUMN \"${column}\" SET DEFAULT ${defaultValue};`\n );\n } else {\n statements.push(`ALTER TABLE ${tableNameWithSchema} ALTER COLUMN \"${column}\" DROP DEFAULT;`);\n }\n }\n\n return statements;\n}\n\n/**\n * Check if a type change needs a USING clause\n * Based on Drizzle's type conversion logic\n */\nfunction checkIfNeedsUsingClause(fromType: string, toType: string): boolean {\n if (!fromType || !toType) return false;\n\n // Enum changes always need USING\n if (fromType.includes(\"enum\") || toType.includes(\"enum\")) {\n return true;\n }\n\n const fromBase = fromType.split(\"(\")[0].toLowerCase();\n const toBase = toType.split(\"(\")[0].toLowerCase();\n\n // Text/varchar to JSONB always needs USING\n if (\n (fromBase === \"text\" || fromBase === \"varchar\" || fromBase === \"character varying\") &&\n (toBase === \"jsonb\" || toBase === \"json\")\n ) {\n return true;\n }\n\n // Some specific type conversions need USING\n const needsUsingPairs = [\n [\"integer\", \"boolean\"],\n [\"boolean\", \"integer\"],\n [\"text\", \"integer\"],\n [\"text\", \"numeric\"],\n [\"text\", \"boolean\"],\n [\"text\", \"uuid\"],\n [\"text\", \"jsonb\"],\n [\"text\", \"json\"],\n [\"varchar\", \"integer\"],\n [\"varchar\", \"numeric\"],\n [\"varchar\", \"boolean\"],\n [\"varchar\", \"uuid\"],\n [\"varchar\", \"jsonb\"],\n [\"varchar\", \"json\"],\n [\"character varying\", \"jsonb\"],\n [\"character varying\", \"json\"],\n // Add more as needed based on PostgreSQL casting rules\n ];\n\n for (const [from, to] of needsUsingPairs) {\n if ((fromBase === from && toBase === to) || (fromBase === to && toBase === from)) {\n return true;\n }\n }\n\n return false;\n}\n\n// Default value type - can be string, number, boolean, or null\ntype DefaultValue = string | number | boolean | null | undefined;\n\n/**\n * Format a default value for SQL\n * Based on Drizzle's default value formatting\n */\nfunction formatDefaultValue(value: DefaultValue, type: string): string {\n // Handle NULL\n if (value === null || value === \"NULL\") {\n return \"NULL\";\n }\n\n // Handle boolean\n if (type && (type.toLowerCase().includes(\"boolean\") || type.toLowerCase() === \"bool\")) {\n if (value === true || value === \"true\" || value === \"t\" || value === 1) {\n return \"true\";\n }\n if (value === false || value === \"false\" || value === \"f\" || value === 0) {\n return \"false\";\n }\n }\n\n // Handle numeric types\n if (type?.match(/^(integer|bigint|smallint|numeric|decimal|real|double)/i)) {\n return String(value);\n }\n\n // Handle SQL expressions and pre-formatted defaults\n if (typeof value === \"string\") {\n // Already formatted with type cast (e.g., '[]'::jsonb, '{}'::jsonb)\n // These come from the snapshot and are already properly formatted\n if (value.includes(\"::\")) {\n return value;\n }\n\n // Already quoted string literals (from snapshot)\n // These start and end with single quotes\n if (value.startsWith(\"'\") && value.endsWith(\"'\")) {\n return value;\n }\n\n // SQL functions like now(), gen_random_uuid(), etc.\n if (value.match(/^\\w+\\(\\)/i) || (value.includes(\"(\") && value.includes(\")\"))) {\n return value;\n }\n\n // SQL expressions starting with CURRENT_\n if (value.toUpperCase().startsWith(\"CURRENT_\")) {\n return value;\n }\n\n // Otherwise, it's an unquoted string literal - wrap and escape\n return `'${value.replace(/'/g, \"''\")}'`;\n }\n\n // Default: return as-is\n return String(value);\n}\n\n// Extended index interface with table reference\ninterface SchemaIndexWithTableRef {\n name: string;\n columns: Array<{\n expression: string;\n isExpression: boolean;\n asc?: boolean;\n nulls?: string;\n }>;\n isUnique: boolean;\n method?: string;\n where?: string;\n concurrently?: boolean;\n table?: string;\n}\n\n/**\n * Generate CREATE INDEX SQL\n */\nfunction generateCreateIndexSQL(index: SchemaIndexWithTableRef): string {\n const unique = index.isUnique ? \"UNIQUE \" : \"\";\n const method = index.method || \"btree\";\n const columns = index.columns\n .map((c) => {\n if (c.isExpression) {\n return c.expression;\n }\n // Only add DESC if explicitly set to false, no NULLS clause by default\n return `\"${c.expression}\"${c.asc === false ? \" DESC\" : \"\"}`;\n })\n .join(\", \");\n\n // Extract index name and table with proper schema handling\n const indexName = index.name.includes(\".\") ? index.name.split(\".\")[1] : index.name;\n\n // Keep the full table name with schema if present\n let tableRef: string;\n const indexTable = index.table;\n if (indexTable?.includes(\".\")) {\n const [schema, table] = indexTable.split(\".\");\n tableRef = `\"${schema}\".\"${table}\"`;\n } else {\n tableRef = `\"${indexTable || \"\"}\"`;\n }\n\n // Include schema in table reference for correct index creation\n return `CREATE ${unique}INDEX \"${indexName}\" ON ${tableRef} USING ${method} (${columns});`;\n}\n\n/**\n * Generate DROP INDEX SQL\n */\nfunction generateDropIndexSQL(index: SchemaIndex | string): string {\n // Extract just the index name without schema\n const indexNameFull = typeof index === \"string\" ? index : index.name;\n const indexName = indexNameFull.includes(\".\") ? indexNameFull.split(\".\")[1] : indexNameFull;\n // Match Drizzle's format - no schema qualification\n return `DROP INDEX IF EXISTS \"${indexName}\";`;\n}\n\n/**\n * Generate CREATE FOREIGN KEY SQL (for existing tables)\n */\nfunction generateCreateForeignKeySQL(fk: SchemaForeignKey): string {\n const schemaFrom = fk.schemaFrom || \"public\";\n const schemaTo = fk.schemaTo || \"public\";\n const tableFrom = fk.tableFrom;\n const columnsFrom = fk.columnsFrom.map((c: string) => `\"${c}\"`).join(\", \");\n const columnsTo = fk.columnsTo.map((c: string) => `\"${c}\"`).join(\", \");\n\n let sql = `ALTER TABLE \"${schemaFrom}\".\"${tableFrom}\" ADD CONSTRAINT \"${fk.name}\" FOREIGN KEY (${columnsFrom}) REFERENCES \"${schemaTo}\".\"${fk.tableTo}\" (${columnsTo})`;\n\n if (fk.onDelete) {\n sql += ` ON DELETE ${fk.onDelete}`;\n }\n\n if (fk.onUpdate) {\n sql += ` ON UPDATE ${fk.onUpdate}`;\n }\n\n return `${sql};`;\n}\n\n/**\n * Generate DROP FOREIGN KEY SQL\n */\nfunction generateDropForeignKeySQL(fk: SchemaForeignKey): string {\n const [schema, tableName] = fk.tableFrom\n ? fk.tableFrom.includes(\".\")\n ? fk.tableFrom.split(\".\")\n : [\"public\", fk.tableFrom]\n : [\"public\", \"\"];\n return `ALTER TABLE \"${schema}\".\"${tableName}\" DROP CONSTRAINT \"${fk.name}\";`;\n}\n\n/**\n * Generate SQL for renaming a table\n */\nexport function generateRenameTableSQL(oldName: string, newName: string): string {\n const [oldSchema, oldTable] = oldName.includes(\".\") ? oldName.split(\".\") : [\"public\", oldName];\n const [, newTable] = newName.includes(\".\") ? newName.split(\".\") : [\"public\", newName];\n return `ALTER TABLE \"${oldSchema}\".\"${oldTable}\" RENAME TO \"${newTable}\";`;\n}\n\n/**\n * Generate SQL for renaming a column\n */\nexport function generateRenameColumnSQL(table: string, oldName: string, newName: string): string {\n const [schema, tableName] = table.includes(\".\") ? table.split(\".\") : [\"public\", table];\n return `ALTER TABLE \"${schema}\".\"${tableName}\" RENAME COLUMN \"${oldName}\" TO \"${newName}\";`;\n}\n\n// Extended constraint interfaces with table reference\ninterface UniqueConstraintWithTable extends SchemaUniqueConstraint {\n table?: string;\n}\n\ninterface CheckConstraintWithTable extends SchemaCheckConstraint {\n table?: string;\n}\n\n/**\n * Generate CREATE UNIQUE CONSTRAINT SQL\n */\nfunction generateCreateUniqueConstraintSQL(constraint: UniqueConstraintWithTable): string {\n const table = constraint.table || \"\";\n const [schema, tableName] = table.includes(\".\") ? table.split(\".\") : [\"public\", table];\n\n const name = constraint.name;\n const columns = constraint.columns.map((c) => `\"${c}\"`).join(\", \");\n\n let sql = `ALTER TABLE \"${schema}\".\"${tableName}\" ADD CONSTRAINT \"${name}\" UNIQUE`;\n\n // Handle NULLS NOT DISTINCT if specified (PostgreSQL 15+)\n if (constraint.nullsNotDistinct) {\n sql += ` NULLS NOT DISTINCT`;\n }\n\n sql += ` (${columns});`;\n\n return sql;\n}\n\n/**\n * Generate DROP UNIQUE CONSTRAINT SQL\n */\nfunction generateDropUniqueConstraintSQL(constraint: UniqueConstraintWithTable): string {\n const table = constraint.table || \"\";\n const [schema, tableName] = table.includes(\".\") ? table.split(\".\") : [\"public\", table];\n\n return `ALTER TABLE \"${schema}\".\"${tableName}\" DROP CONSTRAINT \"${constraint.name}\";`;\n}\n\n/**\n * Generate CREATE CHECK CONSTRAINT SQL\n */\nfunction generateCreateCheckConstraintSQL(constraint: CheckConstraintWithTable): string {\n const table = constraint.table || \"\";\n const [schema, tableName] = table.includes(\".\") ? table.split(\".\") : [\"public\", table];\n\n const name = constraint.name;\n const value = constraint.value;\n\n return `ALTER TABLE \"${schema}\".\"${tableName}\" ADD CONSTRAINT \"${name}\" CHECK (${value});`;\n}\n\n/**\n * Generate DROP CHECK CONSTRAINT SQL\n */\nfunction generateDropCheckConstraintSQL(constraint: CheckConstraintWithTable): string {\n const table = constraint.table || \"\";\n const [schema, tableName] = table.includes(\".\") ? table.split(\".\") : [\"public\", table];\n\n return `ALTER TABLE \"${schema}\".\"${tableName}\" DROP CONSTRAINT \"${constraint.name}\";`;\n}\n",
14
14
  "import { logger } from \"@elizaos/core\";\nimport { sql } from \"drizzle-orm\";\nimport type {\n CheckConstraintInfoRow,\n ColumnInfoRow,\n DrizzleDB,\n EnumInfoRow,\n ForeignKeyInfoRow,\n IndexInfoRow,\n PrimaryKeyInfoRow,\n SchemaCheckConstraint,\n SchemaColumn,\n SchemaEnum,\n SchemaForeignKey,\n SchemaIndex,\n SchemaPrimaryKey,\n SchemaSnapshot,\n SchemaTable,\n SchemaUniqueConstraint,\n TableInfoRow,\n UniqueConstraintInfoRow,\n} from \"../types\";\n\n/**\n * Type-safe extraction of rows from SQL query results.\n * Raw SQL queries in Drizzle return untyped rows - this helper provides type safety.\n */\nfunction getRows<T>(result: { rows: unknown[] }): T[] {\n return result.rows as T[];\n}\n\n/**\n * Introspect the current database state and generate a snapshot\n * This is used when no previous snapshot exists for a plugin\n * to capture the existing database state before migrations\n */\nexport class DatabaseIntrospector {\n constructor(private db: DrizzleDB) {}\n\n /**\n * Introspect all tables in the database and generate a snapshot\n * @param schemaName - Schema to introspect (default: 'public')\n * @returns Schema snapshot of current database state\n */\n async introspectSchema(schemaName: string = \"public\"): Promise<SchemaSnapshot> {\n logger.info({ src: \"plugin:sql\", schemaName }, \"Starting database introspection\");\n\n const tables: Record<string, SchemaTable> = {};\n const schemas: Record<string, string> = {};\n const enums: Record<string, SchemaEnum> = {};\n\n // Get all tables in the schema\n const allTables = await this.getTables(schemaName);\n\n for (const tableInfo of allTables) {\n const tableName = tableInfo.table_name;\n const tableSchema = tableInfo.table_schema || \"public\";\n\n logger.debug({ src: \"plugin:sql\", tableSchema, tableName }, \"Introspecting table\");\n\n // Get columns for this table\n const columns = await this.getColumns(tableSchema, tableName);\n const columnsObject: Record<string, SchemaColumn> = {};\n const uniqueConstraintObject: Record<string, SchemaUniqueConstraint> = {};\n\n for (const col of columns) {\n columnsObject[col.column_name] = {\n name: col.column_name,\n type: col.data_type,\n primaryKey: col.is_primary || false,\n notNull: col.is_nullable === \"NO\",\n default: col.column_default\n ? this.parseDefault(col.column_default, col.data_type)\n : undefined,\n };\n }\n\n // Get indexes\n const indexes = await this.getIndexes(tableSchema, tableName);\n const indexesObject: Record<string, SchemaIndex> = {};\n\n for (const idx of indexes) {\n if (!idx.is_primary && !idx.is_unique_constraint) {\n // Skip primary keys and unique constraints\n // Also skip indexes with no columns (partial indexes, expression indexes, etc.)\n if (idx.columns && Array.isArray(idx.columns) && idx.columns.length > 0) {\n indexesObject[idx.name] = {\n name: idx.name,\n columns: idx.columns.map((col) => ({\n expression: col,\n isExpression: false,\n })),\n isUnique: idx.is_unique,\n method: idx.method || \"btree\",\n };\n }\n }\n }\n\n // Get foreign keys\n const foreignKeys = await this.getForeignKeys(tableSchema, tableName);\n const foreignKeysObject: Record<string, SchemaForeignKey> = {};\n\n for (const fk of foreignKeys) {\n foreignKeysObject[fk.name] = {\n name: fk.name,\n tableFrom: tableName,\n schemaFrom: tableSchema,\n tableTo: fk.foreign_table_name,\n schemaTo: fk.foreign_table_schema || \"public\",\n columnsFrom: [fk.column_name],\n columnsTo: [fk.foreign_column_name],\n onDelete: fk.delete_rule?.toLowerCase() || \"no action\",\n onUpdate: fk.update_rule?.toLowerCase() || \"no action\",\n };\n }\n\n // Get primary keys\n const primaryKeys = await this.getPrimaryKeys(tableSchema, tableName);\n const primaryKeysObject: Record<string, SchemaPrimaryKey> = {};\n\n for (const pk of primaryKeys) {\n primaryKeysObject[pk.name] = {\n name: pk.name,\n columns: pk.columns,\n };\n }\n\n // Get unique constraints\n const uniqueConstraints = await this.getUniqueConstraints(tableSchema, tableName);\n\n for (const unq of uniqueConstraints) {\n uniqueConstraintObject[unq.name] = {\n name: unq.name,\n columns: unq.columns,\n nullsNotDistinct: false, // Default value\n };\n }\n\n // Get check constraints\n const checkConstraints = await this.getCheckConstraints(tableSchema, tableName);\n const checksObject: Record<string, SchemaCheckConstraint> = {};\n\n for (const check of checkConstraints) {\n checksObject[check.name] = {\n name: check.name,\n value: check.definition,\n };\n }\n\n // Build the table object\n tables[`${tableSchema}.${tableName}`] = {\n name: tableName,\n schema: tableSchema,\n columns: columnsObject,\n indexes: indexesObject,\n foreignKeys: foreignKeysObject,\n compositePrimaryKeys: primaryKeysObject,\n uniqueConstraints: uniqueConstraintObject,\n checkConstraints: checksObject,\n };\n\n // Track schemas\n if (tableSchema && tableSchema !== \"public\") {\n schemas[tableSchema] = tableSchema;\n }\n }\n\n // Get enums if any\n const enumsResult = await this.getEnums(schemaName);\n for (const enumInfo of enumsResult) {\n const key = `${enumInfo.schema}.${enumInfo.name}`;\n if (!enums[key]) {\n enums[key] = {\n name: enumInfo.name,\n schema: enumInfo.schema,\n values: [],\n };\n }\n enums[key].values.push(enumInfo.value);\n }\n\n logger.info(\n { src: \"plugin:sql\", tableCount: Object.keys(tables).length },\n \"Database introspection complete\"\n );\n\n return {\n version: \"7\",\n dialect: \"postgresql\",\n tables,\n schemas,\n enums,\n _meta: {\n schemas: {},\n tables: {},\n columns: {},\n },\n };\n }\n\n /**\n * Get all tables in a schema\n */\n private async getTables(schemaName: string): Promise<TableInfoRow[]> {\n const result = await this.db.execute(\n sql`SELECT \n table_schema,\n table_name\n FROM information_schema.tables\n WHERE table_schema = ${schemaName}\n AND table_type = 'BASE TABLE'\n ORDER BY table_name`\n );\n return getRows<TableInfoRow>(result);\n }\n\n /**\n * Get columns for a table\n */\n private async getColumns(schemaName: string, tableName: string): Promise<ColumnInfoRow[]> {\n const result = await this.db.execute(\n sql`SELECT \n a.attname AS column_name,\n CASE \n WHEN a.attnotnull THEN 'NO'\n ELSE 'YES'\n END AS is_nullable,\n CASE \n WHEN a.atttypid = ANY ('{int,int8,int2}'::regtype[]) \n AND EXISTS (\n SELECT FROM pg_attrdef ad\n WHERE ad.adrelid = a.attrelid \n AND ad.adnum = a.attnum \n AND pg_get_expr(ad.adbin, ad.adrelid) = 'nextval(''' \n || pg_get_serial_sequence(a.attrelid::regclass::text, a.attname)::regclass || '''::regclass)'\n )\n THEN CASE a.atttypid\n WHEN 'int'::regtype THEN 'serial'\n WHEN 'int8'::regtype THEN 'bigserial'\n WHEN 'int2'::regtype THEN 'smallserial'\n END\n ELSE format_type(a.atttypid, a.atttypmod)\n END AS data_type,\n pg_get_expr(ad.adbin, ad.adrelid) AS column_default,\n CASE \n WHEN con.contype = 'p' THEN true\n ELSE false\n END AS is_primary\n FROM pg_attribute a\n JOIN pg_class cls ON cls.oid = a.attrelid\n JOIN pg_namespace ns ON ns.oid = cls.relnamespace\n LEFT JOIN pg_attrdef ad ON ad.adrelid = a.attrelid AND ad.adnum = a.attnum\n LEFT JOIN pg_constraint con ON con.conrelid = a.attrelid \n AND a.attnum = ANY(con.conkey) \n AND con.contype = 'p'\n WHERE \n a.attnum > 0\n AND NOT a.attisdropped\n AND ns.nspname = ${schemaName}\n AND cls.relname = ${tableName}\n ORDER BY a.attnum`\n );\n return getRows<ColumnInfoRow>(result);\n }\n\n /**\n * Get indexes for a table\n */\n private async getIndexes(schemaName: string, tableName: string): Promise<IndexInfoRow[]> {\n const result = await this.db.execute(\n sql`SELECT \n i.relname AS name,\n idx.indisunique AS is_unique,\n idx.indisprimary AS is_primary,\n con.contype = 'u' AS is_unique_constraint,\n ARRAY(\n SELECT a.attname\n FROM pg_attribute a\n WHERE a.attrelid = idx.indrelid\n AND a.attnum = ANY(idx.indkey::int[])\n ORDER BY a.attnum\n ) AS columns,\n am.amname AS method\n FROM pg_index idx\n JOIN pg_class i ON i.oid = idx.indexrelid\n JOIN pg_class c ON c.oid = idx.indrelid\n JOIN pg_namespace n ON n.oid = c.relnamespace\n JOIN pg_am am ON am.oid = i.relam\n LEFT JOIN pg_constraint con ON con.conindid = idx.indexrelid\n WHERE n.nspname = ${schemaName}\n AND c.relname = ${tableName}`\n );\n return getRows<IndexInfoRow>(result);\n }\n\n /**\n * Get foreign keys for a table\n */\n private async getForeignKeys(\n schemaName: string,\n tableName: string\n ): Promise<ForeignKeyInfoRow[]> {\n const result = await this.db.execute(\n sql`SELECT\n con.conname AS name,\n att.attname AS column_name,\n fnsp.nspname AS foreign_table_schema,\n frel.relname AS foreign_table_name,\n fatt.attname AS foreign_column_name,\n CASE con.confupdtype\n WHEN 'a' THEN 'NO ACTION'\n WHEN 'r' THEN 'RESTRICT'\n WHEN 'n' THEN 'SET NULL'\n WHEN 'c' THEN 'CASCADE'\n WHEN 'd' THEN 'SET DEFAULT'\n END AS update_rule,\n CASE con.confdeltype\n WHEN 'a' THEN 'NO ACTION'\n WHEN 'r' THEN 'RESTRICT'\n WHEN 'n' THEN 'SET NULL'\n WHEN 'c' THEN 'CASCADE'\n WHEN 'd' THEN 'SET DEFAULT'\n END AS delete_rule\n FROM pg_catalog.pg_constraint con\n JOIN pg_catalog.pg_class rel ON rel.oid = con.conrelid\n JOIN pg_catalog.pg_namespace nsp ON nsp.oid = con.connamespace\n LEFT JOIN pg_catalog.pg_attribute att ON att.attnum = ANY (con.conkey)\n AND att.attrelid = con.conrelid\n LEFT JOIN pg_catalog.pg_class frel ON frel.oid = con.confrelid\n LEFT JOIN pg_catalog.pg_namespace fnsp ON fnsp.oid = frel.relnamespace\n LEFT JOIN pg_catalog.pg_attribute fatt ON fatt.attnum = ANY (con.confkey)\n AND fatt.attrelid = con.confrelid\n WHERE con.contype = 'f'\n AND nsp.nspname = ${schemaName}\n AND rel.relname = ${tableName}`\n );\n return getRows<ForeignKeyInfoRow>(result);\n }\n\n /**\n * Get primary keys for a table\n */\n private async getPrimaryKeys(\n schemaName: string,\n tableName: string\n ): Promise<PrimaryKeyInfoRow[]> {\n const result = await this.db.execute(\n sql`SELECT \n con.conname AS name,\n ARRAY(\n SELECT a.attname\n FROM pg_attribute a\n WHERE a.attrelid = con.conrelid\n AND a.attnum = ANY(con.conkey)\n ORDER BY a.attnum\n ) AS columns\n FROM pg_constraint con\n JOIN pg_class rel ON rel.oid = con.conrelid\n JOIN pg_namespace nsp ON nsp.oid = con.connamespace\n WHERE con.contype = 'p'\n AND nsp.nspname = ${schemaName}\n AND rel.relname = ${tableName}`\n );\n return getRows<PrimaryKeyInfoRow>(result);\n }\n\n /**\n * Get unique constraints for a table\n */\n private async getUniqueConstraints(\n schemaName: string,\n tableName: string\n ): Promise<UniqueConstraintInfoRow[]> {\n const result = await this.db.execute(\n sql`SELECT \n con.conname AS name,\n ARRAY(\n SELECT a.attname\n FROM pg_attribute a\n WHERE a.attrelid = con.conrelid\n AND a.attnum = ANY(con.conkey)\n ORDER BY a.attnum\n ) AS columns\n FROM pg_constraint con\n JOIN pg_class rel ON rel.oid = con.conrelid\n JOIN pg_namespace nsp ON nsp.oid = con.connamespace\n WHERE con.contype = 'u'\n AND nsp.nspname = ${schemaName}\n AND rel.relname = ${tableName}`\n );\n return getRows<UniqueConstraintInfoRow>(result);\n }\n\n /**\n * Get check constraints for a table\n */\n private async getCheckConstraints(\n schemaName: string,\n tableName: string\n ): Promise<CheckConstraintInfoRow[]> {\n const result = await this.db.execute(\n sql`SELECT \n con.conname AS name,\n pg_get_constraintdef(con.oid) AS definition\n FROM pg_constraint con\n JOIN pg_class rel ON rel.oid = con.conrelid\n JOIN pg_namespace nsp ON nsp.oid = con.connamespace\n WHERE con.contype = 'c'\n AND nsp.nspname = ${schemaName}\n AND rel.relname = ${tableName}`\n );\n return getRows<CheckConstraintInfoRow>(result);\n }\n\n /**\n * Get enums in a schema\n */\n private async getEnums(schemaName: string): Promise<EnumInfoRow[]> {\n const result = await this.db.execute(\n sql`SELECT \n n.nspname AS schema,\n t.typname AS name,\n e.enumlabel AS value,\n e.enumsortorder AS sort_order\n FROM pg_type t\n JOIN pg_enum e ON t.oid = e.enumtypid\n JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace\n WHERE n.nspname = ${schemaName}\n ORDER BY schema, name, sort_order`\n );\n return getRows<EnumInfoRow>(result);\n }\n\n /**\n * Parse default value for a column\n */\n private parseDefault(defaultValue: string, dataType: string): string | undefined {\n if (!defaultValue) return undefined;\n\n // Remove the type cast if present (e.g., \"'value'::text\" -> \"'value'\")\n const match = defaultValue.match(/^'(.*)'::/);\n if (match) {\n return `'${match[1]}'`;\n }\n\n // Handle nextval for sequences\n if (defaultValue.includes(\"nextval(\")) {\n return undefined; // Serial types handle this automatically\n }\n\n // Handle boolean defaults\n if (dataType === \"boolean\") {\n if (defaultValue === \"true\") return \"true\";\n if (defaultValue === \"false\") return \"false\";\n }\n\n // Return as-is for other cases\n return defaultValue;\n }\n\n /**\n * Check if tables exist for a plugin by checking if any tables exist in its schema\n * @param pluginName - Name of the plugin\n * @returns True if tables exist, false otherwise\n */\n async hasExistingTables(pluginName: string): Promise<boolean> {\n const schemaName =\n pluginName === \"@elizaos/plugin-sql\" ? \"public\" : this.deriveSchemaName(pluginName);\n\n const result = await this.db.execute(\n sql`SELECT COUNT(*) AS count\n FROM information_schema.tables\n WHERE table_schema = ${schemaName}\n AND table_type = 'BASE TABLE'`\n );\n\n const firstRow = result.rows?.[0];\n const count = parseInt((firstRow && (firstRow.count as string)) || \"0\", 10);\n return count > 0;\n }\n\n /**\n * Derive schema name from plugin name\n */\n private deriveSchemaName(pluginName: string): string {\n // Same logic as in schema-transformer.ts\n return pluginName.replace(\"@\", \"\").replace(\"/\", \"_\").replace(/-/g, \"_\").toLowerCase();\n }\n}\n",
15
15
  "import { logger } from \"@elizaos/core\";\nimport { sql } from \"drizzle-orm\";\nimport type { DrizzleDB } from \"./types\";\n\nexport class ExtensionManager {\n constructor(private db: DrizzleDB) {}\n\n async installRequiredExtensions(extensions: string[]): Promise<void> {\n for (const extension of extensions) {\n try {\n // Validate extension name to prevent SQL injection\n // Extension names should only contain alphanumeric characters, underscores, and hyphens\n if (!/^[a-zA-Z0-9_-]+$/.test(extension)) {\n logger.warn(\n { src: \"plugin:sql\", extension },\n \"Invalid extension name - contains invalid characters\"\n );\n continue;\n }\n\n // Use sql.identifier for safe escaping of SQL identifiers\n await this.db.execute(sql`CREATE EXTENSION IF NOT EXISTS ${sql.identifier(extension)}`);\n logger.debug({ src: \"plugin:sql\", extension }, \"Extension installed\");\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n logger.warn(\n { src: \"plugin:sql\", extension, error: errorMessage },\n \"Could not install extension\"\n );\n // Some extensions might not be available or already installed\n // This shouldn't stop the migration process\n }\n }\n }\n}\n",
16
16
  "import { logger } from \"@elizaos/core\";\nimport { getTableConfig, type PgTable, pgSchema } from \"drizzle-orm/pg-core\";\n\n// Drizzle schema type - an object mapping names to tables or other schema objects\ntype DrizzleSchema = Record<string, unknown>;\n\n// pgSchema object interface\ninterface PgSchemaObject {\n _schema: string;\n table: (...args: unknown[]) => unknown;\n}\n\n/**\n * Transform a plugin's schema to use the appropriate namespace\n *\n * @elizaos/plugin-sql uses 'public' schema (no transformation)\n * Other plugins get their tables wrapped in a namespaced schema\n */\nexport function transformPluginSchema(pluginName: string, schema: DrizzleSchema): DrizzleSchema {\n // Core plugin uses public schema - no transformation needed\n if (pluginName === \"@elizaos/plugin-sql\") {\n return schema;\n }\n\n // Derive schema name from plugin name\n const schemaName = deriveSchemaName(pluginName);\n\n // If schema is already using pgSchema, return as-is\n if (isAlreadyNamespaced(schema, schemaName)) {\n logger.debug(\n { src: \"plugin:sql\", pluginName, schemaName },\n \"Plugin already uses expected schema\"\n );\n return schema;\n }\n\n logger.info({ src: \"plugin:sql\", pluginName, schemaName }, \"Transforming plugin to use schema\");\n\n // Transform the schema object\n const transformed: DrizzleSchema = {};\n\n for (const [key, value] of Object.entries(schema)) {\n if (isPgTable(value)) {\n // Get the table configuration\n const config = getTableConfig(value as PgTable);\n\n // If the table doesn't have a schema or is in public, warn about it\n if (!config.schema || config.schema === \"public\") {\n // Can't easily transform existing tables to different schema\n // (would require reconstructing all column definitions, constraints, etc.)\n logger.warn(\n {\n src: \"plugin:sql\",\n tableName: config.name,\n pluginName,\n expectedSchema: schemaName,\n },\n \"Table should use pgSchema for proper isolation - manual migration may be required\"\n );\n transformed[key] = value;\n } else {\n // Table already has a schema, keep it as-is\n transformed[key] = value;\n }\n } else if (typeof value === \"object\" && value !== null) {\n // Check if this is a schema object (created with pgSchema)\n const obj = value as PgSchemaObject;\n if (obj._schema && obj.table) {\n // This is already a pgSchema object, keep it\n transformed[key] = value;\n } else {\n // Regular object, keep as-is\n transformed[key] = value;\n }\n } else {\n // Not a table, keep as-is\n transformed[key] = value;\n }\n }\n\n return transformed;\n}\n\n/**\n * Derive a valid PostgreSQL schema name from a plugin name\n */\nexport function deriveSchemaName(pluginName: string): string {\n // Remove common prefixes and convert to lowercase with underscores\n let schemaName = pluginName\n .replace(/^@[^/]+\\//, \"\") // Remove npm scope like @elizaos/\n .replace(/^plugin-/, \"\") // Remove plugin- prefix\n .toLowerCase();\n\n // Replace non-alphanumeric characters with underscores (avoid polynomial regex)\n schemaName = normalizeSchemaName(schemaName);\n\n // Ensure schema name is valid (not empty, not a reserved word)\n const reserved = [\"public\", \"pg_catalog\", \"information_schema\", \"migrations\"];\n if (!schemaName || reserved.includes(schemaName)) {\n // Fallback to using the full plugin name with safe characters\n schemaName = `plugin_${normalizeSchemaName(pluginName.toLowerCase())}`;\n }\n\n // Ensure it starts with a letter (PostgreSQL requirement)\n if (!/^[a-z]/.test(schemaName)) {\n schemaName = `p_${schemaName}`;\n }\n\n // Truncate if too long (PostgreSQL identifier limit is 63 chars)\n if (schemaName.length > 63) {\n schemaName = schemaName.substring(0, 63);\n }\n\n return schemaName;\n}\n\n/**\n * Normalize a string to be a valid PostgreSQL identifier\n * Avoids polynomial regex by using string manipulation instead\n */\nfunction normalizeSchemaName(input: string): string {\n const chars: string[] = [];\n let prevWasUnderscore = false;\n\n for (let i = 0; i < input.length; i++) {\n const char = input[i];\n\n if (/[a-z0-9]/.test(char)) {\n chars.push(char);\n prevWasUnderscore = false;\n } else if (!prevWasUnderscore) {\n // Only add underscore if previous char wasn't already an underscore\n chars.push(\"_\");\n prevWasUnderscore = true;\n }\n // Skip consecutive non-alphanumeric characters\n }\n\n // Remove leading and trailing underscores\n const result = chars.join(\"\");\n\n // Trim underscores from start and end efficiently\n let start = 0;\n let end = result.length;\n\n while (start < end && result[start] === \"_\") {\n start++;\n }\n\n while (end > start && result[end - 1] === \"_\") {\n end--;\n }\n\n return result.slice(start, end);\n}\n\n/**\n * Check if a value is a PgTable\n */\nfunction isPgTable(value: unknown): value is PgTable {\n if (!value || typeof value !== \"object\") {\n return false;\n }\n\n // Check for table-like properties\n // This is a heuristic since we can't use instanceof across module boundaries\n try {\n const config = getTableConfig(value as PgTable);\n return config && typeof config.name === \"string\";\n } catch {\n return false;\n }\n}\n\n/**\n * Check if a schema is already properly namespaced\n */\nfunction isAlreadyNamespaced(schema: DrizzleSchema, expectedSchemaName: string): boolean {\n for (const value of Object.values(schema)) {\n if (isPgTable(value)) {\n try {\n const config = getTableConfig(value);\n if (config.schema === expectedSchemaName) {\n return true;\n }\n } catch {\n // Not a table, continue\n }\n }\n }\n return false;\n}\n\n/**\n * Create a namespaced schema helper for plugins\n * This is what plugins should ideally use to define their tables\n */\nexport function createPluginSchema(pluginName: string) {\n const schemaName = deriveSchemaName(pluginName);\n return pgSchema(schemaName);\n}\n",
@@ -22,7 +22,7 @@
22
22
  "import { type IDatabaseAdapter, logger, type Plugin } from \"@elizaos/core\";\nimport { migrateToEntityRLS } from \"./migrations\";\nimport { applyEntityRLSToAllTables, applyRLSToNewTables, installRLSFunctions } from \"./rls\";\nimport { RuntimeMigrator } from \"./runtime-migrator\";\nimport type { DrizzleDatabase } from \"./types\";\n\nexport class DatabaseMigrationService {\n private db: DrizzleDatabase | null = null;\n private registeredSchemas = new Map<string, Record<string, unknown>>();\n private migrator: RuntimeMigrator | null = null;\n\n async initializeWithDatabase(db: DrizzleDatabase): Promise<void> {\n this.db = db;\n\n interface AdapterWrapper extends IDatabaseAdapter {\n db: DrizzleDatabase;\n }\n const adapterWrapper: AdapterWrapper = { db } as AdapterWrapper;\n await migrateToEntityRLS(adapterWrapper);\n\n this.migrator = new RuntimeMigrator(db);\n await this.migrator.initialize();\n logger.info({ src: \"plugin:sql\" }, \"DatabaseMigrationService initialized\");\n }\n\n discoverAndRegisterPluginSchemas(plugins: Plugin[]): void {\n for (const plugin of plugins) {\n type PluginWithSchema = Plugin & {\n schema?: Record<string, unknown>;\n };\n const pluginWithSchema = plugin as PluginWithSchema;\n if (pluginWithSchema.schema) {\n this.registeredSchemas.set(plugin.name, pluginWithSchema.schema);\n }\n }\n logger.info(\n {\n src: \"plugin:sql\",\n schemasDiscovered: this.registeredSchemas.size,\n totalPlugins: plugins.length,\n },\n \"Plugin schemas discovered\"\n );\n }\n\n registerSchema(pluginName: string, schema: Record<string, unknown>): void {\n this.registeredSchemas.set(pluginName, schema);\n logger.debug({ src: \"plugin:sql\", pluginName }, \"Schema registered\");\n }\n\n async runAllPluginMigrations(options?: {\n verbose?: boolean;\n force?: boolean;\n dryRun?: boolean;\n }): Promise<void> {\n if (!this.db || !this.migrator) {\n throw new Error(\"Database or migrator not initialized in DatabaseMigrationService\");\n }\n\n const isProduction = process.env.NODE_ENV === \"production\";\n\n const migrationOptions = {\n verbose: options?.verbose ?? !isProduction,\n force: options?.force ?? false,\n dryRun: options?.dryRun ?? false,\n };\n\n logger.info(\n {\n src: \"plugin:sql\",\n environment: isProduction ? \"PRODUCTION\" : \"DEVELOPMENT\",\n pluginCount: this.registeredSchemas.size,\n dryRun: migrationOptions.dryRun,\n },\n \"Starting migrations\"\n );\n\n let successCount = 0;\n let failureCount = 0;\n const errors: Array<{ pluginName: string; error: Error }> = [];\n\n for (const [pluginName, schema] of this.registeredSchemas) {\n try {\n await this.migrator.migrate(pluginName, schema, migrationOptions);\n successCount++;\n logger.info({ src: \"plugin:sql\", pluginName }, \"Migration completed\");\n } catch (error) {\n failureCount++;\n const errorMessage = (error as Error).message;\n\n errors.push({ pluginName, error: error as Error });\n\n if (errorMessage.includes(\"Destructive migration blocked\")) {\n logger.error(\n { src: \"plugin:sql\", pluginName },\n \"Migration blocked - destructive changes detected. Set ELIZA_ALLOW_DESTRUCTIVE_MIGRATIONS=true or use force option\"\n );\n } else {\n logger.error({ src: \"plugin:sql\", pluginName, error: errorMessage }, \"Migration failed\");\n }\n }\n }\n\n if (failureCount === 0) {\n logger.info({ src: \"plugin:sql\", successCount }, \"All migrations completed successfully\");\n\n const dataIsolationEnabled = process.env.ENABLE_DATA_ISOLATION === \"true\";\n\n if (dataIsolationEnabled) {\n try {\n logger.info({ src: \"plugin:sql\" }, \"Re-applying Row Level Security...\");\n interface AdapterWrapper extends IDatabaseAdapter {\n db: DrizzleDatabase;\n }\n const adapterWrapper: AdapterWrapper = {\n db: this.db,\n } as AdapterWrapper;\n await installRLSFunctions(adapterWrapper);\n await applyRLSToNewTables(adapterWrapper);\n await applyEntityRLSToAllTables(adapterWrapper);\n logger.info({ src: \"plugin:sql\" }, \"RLS re-applied successfully\");\n } catch (rlsError) {\n const errorMsg = rlsError instanceof Error ? rlsError.message : String(rlsError);\n logger.warn(\n { src: \"plugin:sql\", error: errorMsg },\n \"Failed to re-apply RLS (this is OK if server_id columns are not yet in schemas)\"\n );\n }\n } else {\n logger.info(\n { src: \"plugin:sql\" },\n \"Skipping RLS re-application (ENABLE_DATA_ISOLATION is not true)\"\n );\n }\n } else {\n logger.error({ src: \"plugin:sql\", failureCount, successCount }, \"Some migrations failed\");\n\n const errorSummary = errors.map((e) => `${e.pluginName}: ${e.error.message}`).join(\"\\n \");\n throw new Error(`${failureCount} migration(s) failed:\\n ${errorSummary}`);\n }\n }\n\n getMigrator(): RuntimeMigrator | null {\n return this.migrator;\n }\n}\n",
23
23
  "import {\n type IAgentRuntime,\n type IDatabaseAdapter,\n logger,\n type Plugin,\n type UUID,\n} from \"@elizaos/core\";\nimport { PgliteDatabaseAdapter } from \"./pglite/adapter\";\nimport { PGliteClientManager } from \"./pglite/manager\";\nimport * as schema from \"./schema\";\n\nconst GLOBAL_SINGLETONS = Symbol.for(\"@elizaos/plugin-sql/global-singletons\");\n\ninterface GlobalSingletons {\n pgLiteClientManager?: PGliteClientManager;\n}\n\nconst globalSymbols = globalThis as typeof globalThis & Record<symbol, GlobalSingletons>;\nif (!globalSymbols[GLOBAL_SINGLETONS]) {\n globalSymbols[GLOBAL_SINGLETONS] = {};\n}\nconst globalSingletons = globalSymbols[GLOBAL_SINGLETONS];\n\nexport function createDatabaseAdapter(\n _config: { dataDir?: string },\n agentId: UUID\n): IDatabaseAdapter {\n if (!globalSingletons.pgLiteClientManager) {\n globalSingletons.pgLiteClientManager = new PGliteClientManager({});\n }\n return new PgliteDatabaseAdapter(agentId, globalSingletons.pgLiteClientManager);\n}\n\nexport const plugin: Plugin = {\n name: \"@elizaos/plugin-sql\",\n description: \"A plugin for SQL database access (PGlite WASM in browser).\",\n priority: 0,\n schema: schema,\n init: async (_config, runtime: IAgentRuntime) => {\n logger.info({ src: \"plugin:sql\" }, \"plugin-sql (browser) init starting\");\n\n try {\n const isReady = await runtime.isReady();\n if (isReady) {\n logger.info(\n { src: \"plugin:sql\" },\n \"Database adapter already registered, skipping creation\"\n );\n return;\n }\n } catch (_error) {}\n\n const dbAdapter = createDatabaseAdapter({}, runtime.agentId);\n runtime.registerDatabaseAdapter(dbAdapter);\n logger.info({ src: \"plugin:sql\" }, \"Browser database adapter (PGlite) created and registered\");\n },\n};\n\nexport default plugin;\n\nexport { DatabaseMigrationService } from \"./migration-service\";\n",
24
24
  "import { type Agent, type Entity, logger, type Memory, type UUID } from \"@elizaos/core\";\nimport { drizzle, type PgliteDatabase } from \"drizzle-orm/pglite\";\nimport { BaseDrizzleAdapter } from \"../base\";\nimport { DIMENSION_MAP, type EmbeddingDimensionColumn } from \"../schema/embedding\";\nimport type { PGliteClientManager } from \"./manager\";\n\nexport class PgliteDatabaseAdapter extends BaseDrizzleAdapter {\n private manager: PGliteClientManager;\n protected embeddingDimension: EmbeddingDimensionColumn = DIMENSION_MAP[384];\n\n constructor(agentId: UUID, manager: PGliteClientManager) {\n super(agentId);\n this.manager = manager;\n this.db = drizzle(this.manager.getConnection());\n }\n\n public async withEntityContext<T>(\n _entityId: UUID | null,\n callback: (tx: PgliteDatabase) => Promise<T>\n ): Promise<T> {\n return this.db.transaction(callback);\n }\n\n async getEntityByIds(entityIds: UUID[]): Promise<Entity[] | null> {\n return this.getEntitiesByIds(entityIds);\n }\n\n async getMemoriesByServerId(_params: { serverId: UUID; count?: number }): Promise<Memory[]> {\n logger.warn({ src: \"plugin:sql\" }, \"getMemoriesByServerId called but not implemented\");\n return [];\n }\n\n async ensureAgentExists(agent: Partial<Agent>): Promise<Agent> {\n const existingAgent = await this.getAgent(this.agentId);\n if (existingAgent) {\n return existingAgent;\n }\n\n const newAgent: Agent = {\n id: this.agentId,\n name: agent.name || \"Unknown Agent\",\n username: agent.username,\n bio: (Array.isArray(agent.bio)\n ? agent.bio\n : agent.bio\n ? [agent.bio]\n : [\"An AI agent\"]) as string[],\n createdAt: agent.createdAt || Date.now(),\n updatedAt: agent.updatedAt || Date.now(),\n };\n\n await this.createAgent(newAgent);\n const createdAgent = await this.getAgent(this.agentId);\n if (!createdAgent) {\n throw new Error(\"Failed to create agent\");\n }\n return createdAgent;\n }\n\n protected async withDatabase<T>(operation: () => Promise<T>): Promise<T> {\n if (this.manager.isShuttingDown()) {\n const error = new Error(\"Database is shutting down - operation rejected\");\n logger.warn(\n { src: \"plugin:sql\", error: error.message },\n \"Database operation rejected during shutdown\"\n );\n throw error;\n }\n return operation();\n }\n\n async init(): Promise<void> {\n const managerWithInit = this.manager as PGliteClientManager & {\n initialize?: () => Promise<void>;\n };\n await managerWithInit.initialize?.();\n logger.debug({ src: \"plugin:sql\" }, \"PGliteDatabaseAdapter initialized\");\n }\n\n async isReady(): Promise<boolean> {\n return !this.manager.isShuttingDown();\n }\n\n async close() {\n await this.manager.close();\n }\n\n async getConnection(): Promise<PgliteDatabase> {\n const managerWithInit = this.manager as PGliteClientManager & {\n initialize?: () => Promise<void>;\n };\n await managerWithInit.initialize?.();\n return this.db as PgliteDatabase;\n }\n\n getRawConnection() {\n return this.manager.getConnection();\n }\n}\n",
25
- "import {\n type Agent,\n type AgentRunCounts,\n type AgentRunSummary,\n type AgentRunSummaryResult,\n ChannelType,\n type Component,\n DatabaseAdapter,\n type Entity,\n type Log,\n type LogBody,\n logger,\n type Memory,\n type MemoryMetadata,\n type Metadata,\n type PairingAllowlistEntry,\n type PairingChannel,\n type PairingRequest,\n type Participant,\n type Relationship,\n type Room,\n type RunStatus,\n type Task,\n type TaskMetadata,\n type UUID,\n type World,\n} from \"@elizaos/core\";\n\n// JSON-serializable value type for metadata\ntype JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };\n\nimport {\n and,\n cosineDistance,\n count,\n desc,\n eq,\n gte,\n inArray,\n lt,\n lte,\n or,\n type SQL,\n sql,\n} from \"drizzle-orm\";\nimport { v4 } from \"uuid\";\nimport type { DatabaseMigrationService } from \"./migration-service\";\nimport { DIMENSION_MAP, type EmbeddingDimensionColumn } from \"./schema/embedding\";\nimport {\n agentTable,\n cacheTable,\n channelParticipantsTable,\n channelTable,\n componentTable,\n embeddingTable,\n entityTable,\n logTable,\n memoryTable,\n messageServerAgentsTable,\n messageServerTable,\n messageTable,\n pairingAllowlistTable,\n pairingRequestTable,\n participantTable,\n relationshipTable,\n roomTable,\n taskTable,\n worldTable,\n} from \"./schema/index\";\nimport type { DrizzleDatabase } from \"./types\";\n\nexport abstract class BaseDrizzleAdapter extends DatabaseAdapter<DrizzleDatabase> {\n protected readonly maxRetries: number = 3;\n protected readonly baseDelay: number = 1000;\n protected readonly maxDelay: number = 10000;\n protected readonly jitterMax: number = 1000;\n protected embeddingDimension: EmbeddingDimensionColumn = DIMENSION_MAP[384];\n protected migrationService?: DatabaseMigrationService;\n\n protected abstract withDatabase<T>(operation: () => Promise<T>): Promise<T>;\n\n public abstract withEntityContext<T>(\n entityId: UUID | null,\n callback: (tx: DrizzleDatabase) => Promise<T>\n ): Promise<T>;\n\n public abstract init(): Promise<void>;\n public abstract close(): Promise<void>;\n\n public async initialize(): Promise<void> {\n await this.init();\n }\n\n public async runPluginMigrations(\n plugins: Array<{ name: string; schema?: Record<string, unknown> }>,\n options?: {\n verbose?: boolean;\n force?: boolean;\n dryRun?: boolean;\n }\n ): Promise<void> {\n if (!this.migrationService) {\n const { DatabaseMigrationService } = await import(\"./migration-service\");\n this.migrationService = new DatabaseMigrationService();\n await this.migrationService.initializeWithDatabase(this.db as DrizzleDatabase);\n }\n\n for (const plugin of plugins) {\n if (plugin.schema) {\n this.migrationService.registerSchema(plugin.name, plugin.schema);\n }\n }\n\n await this.migrationService.runAllPluginMigrations(options);\n }\n\n public getDatabase(): unknown {\n return this.db;\n }\n\n protected agentId: UUID;\n\n constructor(agentId: UUID) {\n super();\n this.agentId = agentId;\n }\n\n private normalizeEntityNames(names: unknown): string[] {\n if (names == null) {\n return [];\n }\n\n if (typeof names === \"string\") {\n return [names];\n }\n\n if (Array.isArray(names)) {\n return names.map(String);\n }\n\n if (names instanceof Set) {\n return Array.from(names).map(String);\n }\n\n if (typeof names === \"object\" && typeof names[Symbol.iterator] === \"function\") {\n return Array.from(names as Iterable<unknown>).map(String);\n }\n\n return [String(names)];\n }\n\n /**\n * Executes the given operation with retry logic.\n * @template T\n * @param {() => Promise<T>} operation - The operation to be executed.\n * @returns {Promise<T>} A promise that resolves with the result of the operation.\n */\n protected async withRetry<T>(operation: () => Promise<T>): Promise<T> {\n let lastError: Error = new Error(\"Unknown error\");\n\n for (let attempt = 1; attempt <= this.maxRetries; attempt++) {\n try {\n return await operation();\n } catch (error) {\n lastError = error as Error;\n\n if (attempt < this.maxRetries) {\n const backoffDelay = Math.min(this.baseDelay * 2 ** (attempt - 1), this.maxDelay);\n\n const jitter = Math.random() * this.jitterMax;\n const delay = backoffDelay + jitter;\n\n logger.warn(\n {\n src: \"plugin:sql\",\n attempt,\n maxRetries: this.maxRetries,\n error: error instanceof Error ? error.message : String(error),\n },\n \"Database operation failed, retrying\"\n );\n\n await new Promise((resolve) => setTimeout(resolve, delay));\n } else {\n logger.error(\n {\n src: \"plugin:sql\",\n totalAttempts: attempt,\n error: error instanceof Error ? error.message : String(error),\n },\n \"Max retry attempts reached\"\n );\n throw error instanceof Error ? error : new Error(String(error));\n }\n }\n }\n\n throw lastError;\n }\n\n /**\n * Asynchronously ensures that the given embedding dimension is valid for the agent.\n *\n * @param {number} dimension - The dimension to ensure for the embedding.\n * @returns {Promise<void>} - Resolves once the embedding dimension is ensured.\n */\n async ensureEmbeddingDimension(dimension: number) {\n return this.withDatabase(async () => {\n const existingMemory = await this.db\n .select()\n .from(memoryTable)\n .innerJoin(embeddingTable, eq(embeddingTable.memoryId, memoryTable.id))\n .where(eq(memoryTable.agentId, this.agentId))\n .limit(1);\n\n if (existingMemory.length > 0) {\n // The join result includes both memoryTable and embeddingTable columns\n // Access embedding columns directly from the joined result\n interface JoinedMemoryResult {\n memories: typeof memoryTable.$inferSelect;\n embeddings: typeof embeddingTable.$inferSelect;\n }\n const joinedResult = existingMemory[0] as JoinedMemoryResult;\n Object.entries(DIMENSION_MAP).find(([_, colName]) => {\n const embeddingCol = colName as keyof typeof embeddingTable.$inferSelect;\n return joinedResult.embeddings[embeddingCol] !== null;\n });\n // We don't actually need to use usedDimension for now, but it's good to know it's there.\n }\n\n this.embeddingDimension = DIMENSION_MAP[dimension as keyof typeof DIMENSION_MAP];\n });\n }\n\n /**\n * Asynchronously retrieves an agent by their ID from the database.\n * @param {UUID} agentId - The ID of the agent to retrieve.\n * @returns {Promise<Agent | null>} A promise that resolves to the retrieved agent or null if not found.\n */\n async getAgent(agentId: UUID): Promise<Agent | null> {\n return this.withDatabase(async () => {\n const rows = await this.db\n .select()\n .from(agentTable)\n .where(eq(agentTable.id, agentId))\n .limit(1);\n\n if (rows.length === 0) return null;\n\n const row = rows[0];\n const bioValue = !row.bio ? \"\" : Array.isArray(row.bio) ? row.bio : row.bio;\n return {\n ...row,\n username: row.username || \"\",\n id: row.id as UUID,\n system: !row.system ? undefined : row.system,\n bio: bioValue as string | string[],\n createdAt: row.createdAt.getTime(),\n updatedAt: row.updatedAt.getTime(),\n } as unknown as Agent;\n });\n }\n\n /**\n * Asynchronously retrieves a list of agents from the database.\n *\n * @returns {Promise<Partial<Agent>[]>} A Promise that resolves to an array of Agent objects.\n */\n async getAgents(): Promise<Partial<Agent>[]> {\n const result = await this.withDatabase(async () => {\n const rows = await this.db\n .select({\n id: agentTable.id,\n name: agentTable.name,\n bio: agentTable.bio,\n })\n .from(agentTable);\n return rows.map(\n (row) =>\n ({\n ...row,\n id: row.id as UUID,\n bio: (row.bio === null ? \"\" : Array.isArray(row.bio) ? row.bio : row.bio) as\n | string\n | string[],\n }) as Partial<Agent>\n );\n });\n // Guard against null return\n return result || [];\n }\n /**\n * Asynchronously creates a new agent record in the database.\n *\n * @param {Partial<Agent>} agent The agent object to be created.\n * @returns {Promise<boolean>} A promise that resolves to a boolean indicating the success of the operation.\n */\n async createAgent(agent: Agent): Promise<boolean> {\n return this.withDatabase(async () => {\n try {\n // Check for existing agent with the same ID only (names can be duplicated)\n if (agent.id) {\n const existing = await this.db\n .select({ id: agentTable.id })\n .from(agentTable)\n .where(eq(agentTable.id, agent.id))\n .limit(1);\n\n if (existing.length > 0) {\n logger.warn(\n { src: \"plugin:sql\", agentId: agent.id },\n \"Attempted to create agent with duplicate ID\"\n );\n return false;\n }\n }\n\n await this.db.transaction(async (tx) => {\n const agentData = {\n ...agent,\n createdAt: new Date(\n typeof agent.createdAt === \"bigint\"\n ? Number(agent.createdAt)\n : agent.createdAt || Date.now()\n ),\n updatedAt: new Date(\n typeof agent.updatedAt === \"bigint\"\n ? Number(agent.updatedAt)\n : agent.updatedAt || Date.now()\n ),\n };\n await tx\n .insert(agentTable)\n .values(agentData as unknown as typeof agentTable.$inferInsert);\n });\n\n return true;\n } catch (error) {\n logger.error(\n {\n src: \"plugin:sql\",\n agentId: agent.id,\n error: error instanceof Error ? error.message : String(error),\n },\n \"Failed to create agent\"\n );\n return false;\n }\n });\n }\n\n /**\n * Updates an agent in the database with the provided agent ID and data.\n * @param {UUID} agentId - The unique identifier of the agent to update.\n * @param {Partial<Agent>} agent - The partial agent object containing the fields to update.\n * @returns {Promise<boolean>} - A boolean indicating if the agent was successfully updated.\n */\n async updateAgent(agentId: UUID, agent: Partial<Agent>): Promise<boolean> {\n return this.withDatabase(async () => {\n try {\n if (!agentId) {\n throw new Error(\"Agent ID is required for update\");\n }\n\n await this.db.transaction(async (tx) => {\n // Handle settings update if present\n if (agent?.settings) {\n agent.settings = await this.mergeAgentSettings(tx, agentId, agent.settings);\n }\n\n // Convert numeric timestamps to Date objects for database storage\n // The Agent interface uses numbers, but the database schema expects Date objects\n const updateData: Record<string, unknown> = { ...agent };\n\n if (updateData.createdAt) {\n if (typeof updateData.createdAt === \"number\") {\n updateData.createdAt = new Date(updateData.createdAt);\n } else {\n delete updateData.createdAt; // Don't update createdAt if it's not a valid timestamp\n }\n }\n if (updateData.updatedAt) {\n if (typeof updateData.updatedAt === \"number\") {\n updateData.updatedAt = new Date(updateData.updatedAt);\n } else {\n updateData.updatedAt = new Date(); // Use current time if invalid\n }\n } else {\n updateData.updatedAt = new Date(); // Always set updatedAt to current time\n }\n\n await tx.update(agentTable).set(updateData).where(eq(agentTable.id, agentId));\n });\n\n return true;\n } catch (error) {\n logger.error(\n {\n src: \"plugin:sql\",\n agentId,\n error: error instanceof Error ? error.message : String(error),\n },\n \"Failed to update agent\"\n );\n return false;\n }\n });\n }\n\n /**\n * Merges updated agent settings with existing settings in the database,\n * with special handling for nested objects like secrets.\n * @param tx - The database transaction\n * @param agentId - The ID of the agent\n * @param updatedSettings - The settings object with updates\n * @returns The merged settings object\n * @private\n */\n private async mergeAgentSettings<T extends Record<string, unknown>>(\n tx: DrizzleDatabase,\n agentId: UUID,\n updatedSettings: T\n ): Promise<T> {\n // First get the current agent data\n const currentAgent = await tx\n .select({ settings: agentTable.settings })\n .from(agentTable)\n .where(eq(agentTable.id, agentId))\n .limit(1);\n\n const currentSettings =\n currentAgent.length > 0 && currentAgent[0].settings ? currentAgent[0].settings : {};\n\n const deepMerge = (\n target: Record<string, unknown> | unknown,\n source: Record<string, unknown>\n ): Record<string, unknown> | undefined => {\n // If source is explicitly null, it means the intention is to set this entire branch to null (or delete if top-level handled by caller).\n // For recursive calls, if a sub-object in source is null, it effectively means \"remove this sub-object from target\".\n // However, our primary deletion signal is a *property value* being null within an object.\n if (source === null) {\n // If the entire source for a given key is null, we treat it as \"delete this key from target\"\n // by returning undefined, which the caller can use to delete the key.\n return undefined;\n }\n\n // If source is an array or a primitive, it replaces the target value.\n if (Array.isArray(source) || typeof source !== \"object\") {\n return source;\n }\n\n // Initialize output. If target is not an object, start with an empty one to merge source into.\n const output =\n typeof target === \"object\" && target !== null && !Array.isArray(target)\n ? { ...target }\n : {};\n\n for (const key of Object.keys(source)) {\n // Iterate over source keys\n const sourceValue = source[key];\n\n if (sourceValue === null) {\n // If a value in source is null, delete the corresponding key from output.\n delete output[key];\n } else if (typeof sourceValue === \"object\" && !Array.isArray(sourceValue)) {\n // If value is an object, recurse.\n const nestedMergeResult = deepMerge(output[key], sourceValue as Record<string, unknown>);\n if (nestedMergeResult === undefined) {\n // If recursive merge resulted in undefined (meaning the nested object should be deleted)\n delete output[key];\n } else {\n output[key] = nestedMergeResult;\n }\n } else {\n // Primitive or array value from source, assign it.\n output[key] = sourceValue;\n }\n }\n\n // After processing all keys from source, check if output became empty.\n // An object is empty if all its keys were deleted or resulted in undefined.\n // This is a more direct check than iterating 'output' after building it.\n if (Object.keys(output).length === 0) {\n // If the source itself was not an explicitly empty object,\n // and the merge resulted in an empty object, signal deletion.\n if (!(typeof source === \"object\" && source !== null && Object.keys(source).length === 0)) {\n return undefined; // Signal to delete this (parent) key if it became empty.\n }\n }\n\n return output;\n }; // End of deepMerge\n\n const finalSettings = deepMerge(currentSettings, updatedSettings);\n // If the entire settings object becomes undefined (e.g. all keys removed),\n // return an empty object instead of undefined/null to keep the settings field present.\n return (finalSettings ?? {}) as T;\n }\n\n /**\n * Asynchronously deletes an agent with the specified UUID and all related entries.\n *\n * @param {UUID} agentId - The UUID of the agent to be deleted.\n * @returns {Promise<boolean>} - A boolean indicating if the deletion was successful.\n */\n async deleteAgent(agentId: UUID): Promise<boolean> {\n return this.withDatabase(async () => {\n try {\n // Simply delete the agent - all related data will be cascade deleted\n const result = await this.db\n .delete(agentTable)\n .where(eq(agentTable.id, agentId))\n .returning();\n\n if (result.length === 0) {\n logger.warn({ src: \"plugin:sql\", agentId }, \"Agent not found for deletion\");\n return false;\n }\n\n return true;\n } catch (error) {\n logger.error(\n {\n src: \"plugin:sql\",\n agentId,\n error: error instanceof Error ? error.message : String(error),\n },\n \"Failed to delete agent\"\n );\n throw error;\n }\n });\n }\n\n /**\n * Count all agents in the database\n * Used primarily for maintenance and cleanup operations\n */\n /**\n * Asynchronously counts the number of agents in the database.\n * @returns {Promise<number>} A Promise that resolves to the number of agents in the database.\n */\n async countAgents(): Promise<number> {\n return this.withDatabase(async () => {\n try {\n const result = await this.db.select({ count: count() }).from(agentTable);\n\n const result0 = result[0];\n return result0?.count || 0;\n } catch (error) {\n logger.error(\n {\n src: \"plugin:sql\",\n error: error instanceof Error ? error.message : String(error),\n },\n \"Failed to count agents\"\n );\n return 0;\n }\n });\n }\n\n /**\n * Clean up the agents table by removing all agents\n * This is used during server startup to ensure no orphaned agents exist\n * from previous crashes or improper shutdowns\n */\n async cleanupAgents(): Promise<void> {\n return this.withDatabase(async () => {\n try {\n await this.db.delete(agentTable);\n } catch (error) {\n logger.error(\n {\n src: \"plugin:sql\",\n error: error instanceof Error ? error.message : String(error),\n },\n \"Failed to clean up agent table\"\n );\n throw error;\n }\n });\n }\n\n /**\n * Asynchronously retrieves an entity and its components by entity IDs.\n * @param {UUID[]} entityIds - The unique identifiers of the entities to retrieve.\n * @returns {Promise<Entity[] | null>} A Promise that resolves to the entity with its components if found, null otherwise.\n */\n async getEntitiesByIds(entityIds: UUID[]): Promise<Entity[] | null> {\n return this.withDatabase(async () => {\n const result = await this.db\n .select({\n entity: entityTable,\n components: componentTable,\n })\n .from(entityTable)\n .leftJoin(componentTable, eq(componentTable.entityId, entityTable.id))\n .where(inArray(entityTable.id, entityIds));\n\n if (result.length === 0) return [];\n\n // Group components by entity\n const entities: Record<UUID, Entity> = {};\n const entityComponents: Record<UUID, Entity[\"components\"]> = {};\n for (const e of result) {\n const key = e.entity.id;\n entities[key] = e.entity;\n if (entityComponents[key] === undefined) entityComponents[key] = [];\n if (e.components) {\n // Handle both single component and array of components\n const componentsArray = Array.isArray(e.components) ? e.components : [e.components];\n entityComponents[key] = [...entityComponents[key], ...componentsArray];\n }\n }\n for (const k of Object.keys(entityComponents)) {\n entities[k].components = entityComponents[k];\n }\n\n return Object.values(entities);\n });\n }\n\n /**\n * Asynchronously retrieves all entities for a given room, optionally including their components.\n * @param {UUID} roomId - The unique identifier of the room to get entities for\n * @param {boolean} [includeComponents] - Whether to include component data for each entity\n * @returns {Promise<Entity[]>} A Promise that resolves to an array of entities in the room\n */\n async getEntitiesForRoom(roomId: UUID, includeComponents?: boolean): Promise<Entity[]> {\n return this.withDatabase(async () => {\n const query = this.db\n .select({\n entity: entityTable,\n ...(includeComponents && { components: componentTable }),\n })\n .from(participantTable)\n .leftJoin(\n entityTable,\n and(eq(participantTable.entityId, entityTable.id), eq(entityTable.agentId, this.agentId))\n );\n\n if (includeComponents) {\n query.leftJoin(componentTable, eq(componentTable.entityId, entityTable.id));\n }\n\n const result = await query.where(eq(participantTable.roomId, roomId));\n\n // Group components by entity if includeComponents is true\n const entitiesByIdMap = new Map<UUID, Entity>();\n\n for (const row of result) {\n if (!row.entity) continue;\n\n const entityId = row.entity.id as UUID;\n if (!entitiesByIdMap.has(entityId)) {\n const entity: Entity = {\n ...row.entity,\n id: entityId,\n agentId: row.entity.agentId as UUID,\n metadata: (row.entity.metadata || {}) as Metadata,\n components: includeComponents ? [] : undefined,\n };\n entitiesByIdMap.set(entityId, entity);\n }\n\n if (includeComponents && row.components) {\n const entity = entitiesByIdMap.get(entityId);\n if (entity) {\n if (!entity.components) {\n entity.components = [];\n }\n entity.components.push(row.components);\n }\n }\n }\n\n return Array.from(entitiesByIdMap.values());\n });\n }\n\n /**\n * Asynchronously creates new entities in the database.\n * @param {Entity[]} entities - The entity objects to be created.\n * @returns {Promise<boolean>} A Promise that resolves to a boolean indicating the success of the operation.\n */\n async createEntities(entities: Entity[]): Promise<boolean> {\n return this.withDatabase(async () => {\n try {\n return await this.db.transaction(async (tx) => {\n // Normalize entity data to ensure names is a proper array\n const normalizedEntities = entities.map((entity) => ({\n ...entity,\n names: this.normalizeEntityNames(entity.names),\n metadata: entity.metadata || {},\n }));\n\n await tx.insert(entityTable).values(normalizedEntities);\n\n return true;\n });\n } catch (error) {\n logger.error(\n {\n src: \"plugin:sql\",\n entityId: entities[0]?.id,\n error: error instanceof Error ? error.message : String(error),\n },\n \"Failed to create entities\"\n );\n return false;\n }\n });\n }\n\n /**\n * Asynchronously ensures an entity exists, creating it if it doesn't\n * @param entity The entity to ensure exists\n * @returns Promise resolving to boolean indicating success\n */\n protected async ensureEntityExists(entity: Entity): Promise<boolean> {\n if (!entity.id) {\n logger.error({ src: \"plugin:sql\" }, \"Entity ID is required for ensureEntityExists\");\n return false;\n }\n\n try {\n const existingEntities = await this.getEntitiesByIds([entity.id]);\n\n if (!existingEntities || !existingEntities.length) {\n return await this.createEntities([entity]);\n }\n\n return true;\n } catch (error) {\n logger.error(\n {\n src: \"plugin:sql\",\n entityId: entity.id,\n error: error instanceof Error ? error.message : String(error),\n },\n \"Failed to ensure entity exists\"\n );\n return false;\n }\n }\n\n /**\n * Asynchronously updates an entity in the database.\n * @param {Entity} entity - The entity object to be updated.\n * @returns {Promise<void>} A Promise that resolves when the entity is updated.\n */\n async updateEntity(entity: Entity): Promise<void> {\n if (!entity.id) {\n throw new Error(\"Entity ID is required for update\");\n }\n return this.withDatabase(async () => {\n // Normalize entity data to ensure names is a proper array\n const normalizedEntity = {\n ...entity,\n names: this.normalizeEntityNames(entity.names),\n metadata: entity.metadata || {},\n };\n\n await this.db\n .update(entityTable)\n .set(normalizedEntity)\n .where(eq(entityTable.id, entity.id as string));\n });\n }\n\n /**\n * Asynchronously deletes an entity from the database based on the provided ID.\n * @param {UUID} entityId - The ID of the entity to delete.\n * @returns {Promise<void>} A Promise that resolves when the entity is deleted.\n */\n async deleteEntity(entityId: UUID): Promise<void> {\n return this.withDatabase(async () => {\n await this.db.transaction(async (tx) => {\n // Delete related components first\n await tx\n .delete(componentTable)\n .where(\n or(eq(componentTable.entityId, entityId), eq(componentTable.sourceEntityId, entityId))\n );\n\n // Delete the entity\n await tx.delete(entityTable).where(eq(entityTable.id, entityId));\n });\n });\n }\n\n /**\n * Asynchronously retrieves entities by their names and agentId.\n * @param {Object} params - The parameters for retrieving entities.\n * @param {string[]} params.names - The names to search for.\n * @param {UUID} params.agentId - The agent ID to filter by.\n * @returns {Promise<Entity[]>} A Promise that resolves to an array of entities.\n */\n async getEntitiesByNames(params: { names: string[]; agentId: UUID }): Promise<Entity[]> {\n return this.withDatabase(async () => {\n const { names, agentId } = params;\n\n // Build a condition to match any of the names\n const nameConditions = names.map((name) => sql`${name} = ANY(${entityTable.names})`);\n\n const query = sql`\n SELECT * FROM ${entityTable}\n WHERE ${entityTable.agentId} = ${agentId}\n AND (${sql.join(nameConditions, sql` OR `)})\n `;\n\n const result = await this.db.execute(query);\n\n return result.rows.map((row: Record<string, unknown>) => ({\n id: row.id as UUID,\n agentId: row.agentId as UUID,\n names: (row.names || []) as string[],\n metadata: (row.metadata || {}) as Metadata,\n }));\n });\n }\n\n /**\n * Asynchronously searches for entities by name with fuzzy matching.\n * @param {Object} params - The parameters for searching entities.\n * @param {string} params.query - The search query.\n * @param {UUID} params.agentId - The agent ID to filter by.\n * @param {number} params.limit - The maximum number of results to return.\n * @returns {Promise<Entity[]>} A Promise that resolves to an array of entities.\n */\n async searchEntitiesByName(params: {\n query: string;\n agentId: UUID;\n limit?: number;\n }): Promise<Entity[]> {\n return this.withDatabase(async () => {\n const { query, agentId, limit = 10 } = params;\n\n // If query is empty, return all entities up to limit\n if (!query || query.trim() === \"\") {\n const result = await this.db\n .select()\n .from(entityTable)\n .where(eq(entityTable.agentId, agentId))\n .limit(limit);\n\n return result.map((row: Record<string, unknown>) => ({\n id: row.id as UUID,\n agentId: row.agentId as UUID,\n names: (row.names || []) as string[],\n metadata: (row.metadata || {}) as Metadata,\n }));\n }\n\n // Otherwise, search for entities with names containing the query (case-insensitive)\n const searchQuery = sql`\n SELECT * FROM ${entityTable}\n WHERE ${entityTable.agentId} = ${agentId}\n AND EXISTS (\n SELECT 1 FROM unnest(${entityTable.names}) AS name\n WHERE LOWER(name) LIKE LOWER(${`%${query}%`})\n )\n LIMIT ${limit}\n `;\n\n const result = await this.db.execute(searchQuery);\n\n return result.rows.map((row: Record<string, unknown>) => ({\n id: row.id as UUID,\n agentId: row.agentId as UUID,\n names: (row.names || []) as string[],\n metadata: (row.metadata || {}) as Metadata,\n }));\n });\n }\n\n async getComponent(\n entityId: UUID,\n type: string,\n worldId?: UUID,\n sourceEntityId?: UUID\n ): Promise<Component | null> {\n return this.withDatabase(async () => {\n const conditions = [eq(componentTable.entityId, entityId), eq(componentTable.type, type)];\n\n if (worldId) {\n conditions.push(eq(componentTable.worldId, worldId));\n }\n\n if (sourceEntityId) {\n conditions.push(eq(componentTable.sourceEntityId, sourceEntityId));\n }\n\n const result = await this.db\n .select()\n .from(componentTable)\n .where(and(...conditions));\n\n if (result.length === 0) return null;\n\n const component = result[0];\n\n return {\n ...component,\n id: component.id as UUID,\n entityId: component.entityId as UUID,\n agentId: component.agentId as UUID,\n roomId: component.roomId as UUID,\n worldId: (component.worldId ?? \"\") as UUID,\n sourceEntityId: (component.sourceEntityId ?? \"\") as UUID,\n data: component.data as Metadata,\n createdAt: component.createdAt.getTime(),\n };\n });\n }\n\n /**\n * Asynchronously retrieves all components for a given entity, optionally filtered by world and source entity.\n * @param {UUID} entityId - The unique identifier of the entity to retrieve components for\n * @param {UUID} [worldId] - Optional world ID to filter components by\n * @param {UUID} [sourceEntityId] - Optional source entity ID to filter components by\n * @returns {Promise<Component[]>} A Promise that resolves to an array of components\n */\n async getComponents(entityId: UUID, worldId?: UUID, sourceEntityId?: UUID): Promise<Component[]> {\n return this.withDatabase(async () => {\n const conditions = [eq(componentTable.entityId, entityId)];\n\n if (worldId) {\n conditions.push(eq(componentTable.worldId, worldId));\n }\n\n if (sourceEntityId) {\n conditions.push(eq(componentTable.sourceEntityId, sourceEntityId));\n }\n\n const result = await this.db\n .select({\n id: componentTable.id,\n entityId: componentTable.entityId,\n type: componentTable.type,\n data: componentTable.data,\n worldId: componentTable.worldId,\n agentId: componentTable.agentId,\n roomId: componentTable.roomId,\n sourceEntityId: componentTable.sourceEntityId,\n createdAt: componentTable.createdAt,\n })\n .from(componentTable)\n .where(and(...conditions));\n\n if (result.length === 0) return [];\n\n const components = result.map((component) => ({\n ...component,\n id: component.id as UUID,\n entityId: component.entityId as UUID,\n agentId: component.agentId as UUID,\n roomId: component.roomId as UUID,\n worldId: (component.worldId ?? \"\") as UUID,\n sourceEntityId: (component.sourceEntityId ?? \"\") as UUID,\n data: component.data as Metadata,\n createdAt: component.createdAt.getTime(),\n }));\n\n return components;\n });\n }\n\n /**\n * Asynchronously creates a new component in the database.\n * @param {Component} component - The component object to be created.\n * @returns {Promise<boolean>} A Promise that resolves to a boolean indicating the success of the operation.\n */\n async createComponent(component: Component): Promise<boolean> {\n return this.withDatabase(async () => {\n await this.db.insert(componentTable).values({\n ...component,\n createdAt: new Date(),\n });\n return true;\n });\n }\n\n /**\n * Asynchronously updates an existing component in the database.\n * @param {Component} component - The component object to be updated.\n * @returns {Promise<void>} A Promise that resolves when the component is updated.\n */\n async updateComponent(component: Component): Promise<void> {\n return this.withDatabase(async () => {\n try {\n // Convert createdAt from number to Date for database compatibility\n const { createdAt, ...rest } = component;\n await this.db\n .update(componentTable)\n .set({\n ...rest,\n createdAt: new Date(createdAt),\n })\n .where(eq(componentTable.id, component.id));\n } catch (e) {\n console.error(\"updateComponent error\", e);\n }\n });\n }\n\n /**\n * Asynchronously deletes a component from the database.\n * @param {UUID} componentId - The unique identifier of the component to delete.\n * @returns {Promise<void>} A Promise that resolves when the component is deleted.\n */\n async deleteComponent(componentId: UUID): Promise<void> {\n return this.withDatabase(async () => {\n await this.db.delete(componentTable).where(eq(componentTable.id, componentId));\n });\n }\n\n /**\n * Asynchronously retrieves memories from the database based on the provided parameters.\n * @param {Object} params - The parameters for retrieving memories.\n * @param {UUID} params.roomId - The ID of the room to retrieve memories for.\n * @param {number} [params.count] - The maximum number of memories to retrieve.\n * @param {number} [params.offset] - The offset for pagination.\n * @param {boolean} [params.unique] - Whether to retrieve unique memories only.\n * @param {string} [params.tableName] - The name of the table to retrieve memories from.\n * @param {number} [params.start] - The start date to retrieve memories from.\n * @param {number} [params.end] - The end date to retrieve memories from.\n * @returns {Promise<Memory[]>} A Promise that resolves to an array of memories.\n */\n async getMemories(params: {\n entityId?: UUID;\n agentId?: UUID;\n count?: number;\n offset?: number;\n unique?: boolean;\n tableName: string;\n start?: number;\n end?: number;\n roomId?: UUID;\n worldId?: UUID;\n }): Promise<Memory[]> {\n const { entityId, agentId, roomId, worldId, tableName, unique, start, end, offset } = params;\n\n if (!tableName) throw new Error(\"tableName is required\");\n if (offset !== undefined && offset < 0) {\n throw new Error(\"offset must be a non-negative number\");\n }\n\n return this.withEntityContext(entityId ?? null, async (tx) => {\n const conditions = [eq(memoryTable.type, tableName)];\n\n if (start) {\n conditions.push(gte(memoryTable.createdAt, new Date(start)));\n }\n\n // RLS handles access control - no explicit entityId filter needed\n\n if (roomId) {\n conditions.push(eq(memoryTable.roomId, roomId));\n }\n\n // Add worldId condition\n if (worldId) {\n conditions.push(eq(memoryTable.worldId, worldId));\n }\n\n if (end) {\n conditions.push(lte(memoryTable.createdAt, new Date(end)));\n }\n\n if (unique) {\n conditions.push(eq(memoryTable.unique, true));\n }\n\n if (agentId) {\n conditions.push(eq(memoryTable.agentId, agentId));\n }\n\n const baseQuery = tx\n .select({\n memory: {\n id: memoryTable.id,\n type: memoryTable.type,\n createdAt: memoryTable.createdAt,\n content: memoryTable.content,\n entityId: memoryTable.entityId,\n agentId: memoryTable.agentId,\n roomId: memoryTable.roomId,\n unique: memoryTable.unique,\n metadata: memoryTable.metadata,\n },\n embedding: embeddingTable[this.embeddingDimension],\n })\n .from(memoryTable)\n .leftJoin(embeddingTable, eq(embeddingTable.memoryId, memoryTable.id))\n .where(and(...conditions))\n .orderBy(desc(memoryTable.createdAt));\n\n // Apply limit and offset for pagination\n // Build query conditionally to maintain proper types\n const rows = await (async () => {\n if (params.count && offset !== undefined && offset > 0) {\n return baseQuery.limit(params.count).offset(offset);\n } else if (params.count) {\n return baseQuery.limit(params.count);\n } else if (offset !== undefined && offset > 0) {\n return baseQuery.offset(offset);\n } else {\n return baseQuery;\n }\n })();\n\n return rows.map((row) => ({\n id: row.memory.id as UUID,\n type: row.memory.type,\n createdAt: row.memory.createdAt.getTime(),\n content:\n typeof row.memory.content === \"string\"\n ? JSON.parse(row.memory.content)\n : row.memory.content,\n entityId: row.memory.entityId as UUID,\n agentId: row.memory.agentId as UUID,\n roomId: row.memory.roomId as UUID,\n unique: row.memory.unique,\n metadata: row.memory.metadata as MemoryMetadata,\n embedding: row.embedding ? Array.from(row.embedding) : undefined,\n }));\n });\n }\n\n /**\n * Asynchronously retrieves memories from the database based on the provided parameters.\n * @param {Object} params - The parameters for retrieving memories.\n * @param {UUID[]} params.roomIds - The IDs of the rooms to retrieve memories for.\n * @param {string} params.tableName - The name of the table to retrieve memories from.\n * @param {number} [params.limit] - The maximum number of memories to retrieve.\n * @returns {Promise<Memory[]>} A Promise that resolves to an array of memories.\n */\n async getMemoriesByRoomIds(params: {\n roomIds: UUID[];\n tableName: string;\n limit?: number;\n }): Promise<Memory[]> {\n return this.withDatabase(async () => {\n if (params.roomIds.length === 0) return [];\n\n const conditions = [\n eq(memoryTable.type, params.tableName),\n inArray(memoryTable.roomId, params.roomIds),\n ];\n\n conditions.push(eq(memoryTable.agentId, this.agentId));\n\n const query = this.db\n .select({\n id: memoryTable.id,\n type: memoryTable.type,\n createdAt: memoryTable.createdAt,\n content: memoryTable.content,\n entityId: memoryTable.entityId,\n agentId: memoryTable.agentId,\n roomId: memoryTable.roomId,\n unique: memoryTable.unique,\n metadata: memoryTable.metadata,\n })\n .from(memoryTable)\n .where(and(...conditions))\n .orderBy(desc(memoryTable.createdAt));\n\n const rows = params.limit ? await query.limit(params.limit) : await query;\n\n return rows.map((row) => ({\n id: row.id as UUID,\n createdAt: row.createdAt.getTime(),\n content: typeof row.content === \"string\" ? JSON.parse(row.content) : row.content,\n entityId: row.entityId as UUID,\n agentId: row.agentId as UUID,\n roomId: row.roomId as UUID,\n unique: row.unique,\n metadata: row.metadata,\n })) as Memory[];\n });\n }\n\n /**\n * Asynchronously retrieves a memory by its unique identifier.\n * @param {UUID} id - The unique identifier of the memory to retrieve.\n * @returns {Promise<Memory | null>} A Promise that resolves to the memory if found, null otherwise.\n */\n async getMemoryById(id: UUID): Promise<Memory | null> {\n return this.withDatabase(async () => {\n const result = await this.db\n .select({\n memory: memoryTable,\n embedding: embeddingTable[this.embeddingDimension],\n })\n .from(memoryTable)\n .leftJoin(embeddingTable, eq(memoryTable.id, embeddingTable.memoryId))\n .where(eq(memoryTable.id, id))\n .limit(1);\n\n if (result.length === 0) return null;\n\n const row = result[0];\n return {\n id: row.memory.id as UUID,\n createdAt: row.memory.createdAt.getTime(),\n content:\n typeof row.memory.content === \"string\"\n ? JSON.parse(row.memory.content)\n : row.memory.content,\n entityId: row.memory.entityId as UUID,\n agentId: row.memory.agentId as UUID,\n roomId: row.memory.roomId as UUID,\n unique: row.memory.unique,\n metadata: row.memory.metadata as MemoryMetadata,\n embedding: row.embedding ?? undefined,\n };\n });\n }\n\n /**\n * Asynchronously retrieves memories from the database based on the provided parameters.\n * @param {Object} params - The parameters for retrieving memories.\n * @param {UUID[]} params.memoryIds - The IDs of the memories to retrieve.\n * @param {string} [params.tableName] - The name of the table to retrieve memories from.\n * @returns {Promise<Memory[]>} A Promise that resolves to an array of memories.\n */\n async getMemoriesByIds(memoryIds: UUID[], tableName?: string): Promise<Memory[]> {\n return this.withDatabase(async () => {\n if (memoryIds.length === 0) return [];\n\n const conditions = [inArray(memoryTable.id, memoryIds)];\n\n if (tableName) {\n conditions.push(eq(memoryTable.type, tableName));\n }\n\n const rows = await this.db\n .select({\n memory: memoryTable,\n embedding: embeddingTable[this.embeddingDimension],\n })\n .from(memoryTable)\n .leftJoin(embeddingTable, eq(embeddingTable.memoryId, memoryTable.id))\n .where(and(...conditions))\n .orderBy(desc(memoryTable.createdAt));\n\n return rows.map((row) => ({\n id: row.memory.id as UUID,\n createdAt: row.memory.createdAt.getTime(),\n content:\n typeof row.memory.content === \"string\"\n ? JSON.parse(row.memory.content)\n : row.memory.content,\n entityId: row.memory.entityId as UUID,\n agentId: row.memory.agentId as UUID,\n roomId: row.memory.roomId as UUID,\n unique: row.memory.unique,\n metadata: row.memory.metadata as MemoryMetadata,\n embedding: row.embedding ?? undefined,\n }));\n });\n }\n\n /**\n * Asynchronously retrieves cached embeddings from the database based on the provided parameters.\n * @param {Object} opts - The parameters for retrieving cached embeddings.\n * @param {string} opts.query_table_name - The name of the table to retrieve embeddings from.\n * @param {number} opts.query_threshold - The threshold for the levenshtein distance.\n * @param {string} opts.query_input - The input string to search for.\n * @param {string} opts.query_field_name - The name of the field to retrieve embeddings from.\n * @param {string} opts.query_field_sub_name - The name of the sub-field to retrieve embeddings from.\n * @param {number} opts.query_match_count - The maximum number of matches to retrieve.\n * @returns {Promise<{ embedding: number[]; levenshtein_score: number }[]>} A Promise that resolves to an array of cached embeddings.\n */\n async getCachedEmbeddings(opts: {\n query_table_name: string;\n query_threshold: number;\n query_input: string;\n query_field_name: string;\n query_field_sub_name: string;\n query_match_count: number;\n }): Promise<{ embedding: number[]; levenshtein_score: number }[]> {\n return this.withDatabase(async () => {\n try {\n // Drizzle database has execute method for raw SQL\n interface DrizzleDatabaseWithExecute {\n execute: (query: ReturnType<typeof sql>) => Promise<{ rows: Record<string, unknown>[] }>;\n }\n const results = await (this.db as DrizzleDatabaseWithExecute).execute(sql`\n WITH content_text AS (\n SELECT\n m.id,\n COALESCE(\n m.content->>${opts.query_field_sub_name},\n ''\n ) as content_text\n FROM memories m\n WHERE m.type = ${opts.query_table_name}\n AND m.content->>${opts.query_field_sub_name} IS NOT NULL\n ),\n embedded_text AS (\n SELECT\n ct.content_text,\n COALESCE(\n e.dim_384,\n e.dim_512,\n e.dim_768,\n e.dim_1024,\n e.dim_1536,\n e.dim_3072\n ) as embedding\n FROM content_text ct\n LEFT JOIN embeddings e ON e.memory_id = ct.id\n WHERE e.memory_id IS NOT NULL\n )\n SELECT\n embedding,\n levenshtein(${opts.query_input}, content_text) as levenshtein_score\n FROM embedded_text\n WHERE levenshtein(${opts.query_input}, content_text) <= ${opts.query_threshold}\n ORDER BY levenshtein_score\n LIMIT ${opts.query_match_count}\n `);\n\n return results.rows\n .map((row) => ({\n embedding: Array.isArray(row.embedding)\n ? row.embedding\n : typeof row.embedding === \"string\"\n ? JSON.parse(row.embedding)\n : [],\n levenshtein_score: Number(row.levenshtein_score),\n }))\n .filter((row) => Array.isArray(row.embedding));\n } catch (error) {\n logger.error(\n {\n src: \"plugin:sql\",\n tableName: opts.query_table_name,\n fieldName: opts.query_field_name,\n error: error instanceof Error ? error.message : String(error),\n },\n \"Failed to get cached embeddings\"\n );\n if (\n error instanceof Error &&\n error.message === \"levenshtein argument exceeds maximum length of 255 characters\"\n ) {\n return [];\n }\n throw error;\n }\n });\n }\n\n /**\n * Asynchronously logs an event in the database.\n * @param {Object} params - The parameters for logging an event.\n * @param {Object} params.body - The body of the event to log.\n * @param {UUID} params.entityId - The ID of the entity associated with the event.\n * @param {UUID} params.roomId - The ID of the room associated with the event.\n * @param {string} params.type - The type of the event to log.\n * @returns {Promise<void>} A Promise that resolves when the event is logged.\n */\n async log(params: {\n body: { [key: string]: unknown };\n entityId: UUID;\n roomId: UUID;\n type: string;\n }): Promise<void> {\n return this.withDatabase(async () => {\n try {\n // Sanitize JSON body to prevent Unicode escape sequence errors\n const sanitizedBody = this.sanitizeJsonObject(params.body);\n\n // Serialize to JSON string first for an additional layer of protection\n // This ensures any problematic characters are properly escaped during JSON serialization\n const jsonString = JSON.stringify(sanitizedBody);\n\n // Use withEntityContext to set Entity RLS context before inserting\n // This ensures the log entry passes STRICT Entity RLS policy\n await this.withEntityContext(params.entityId, async (tx) => {\n await tx.insert(logTable).values({\n body: sql`${jsonString}::jsonb`,\n entityId: params.entityId,\n roomId: params.roomId,\n type: params.type,\n });\n });\n } catch (error) {\n logger.error(\n {\n src: \"plugin:sql\",\n type: params.type,\n roomId: params.roomId,\n entityId: params.entityId,\n error: error instanceof Error ? error.message : String(error),\n },\n \"Failed to create log entry\"\n );\n throw error;\n }\n });\n }\n\n /**\n * Sanitizes a JSON object by replacing problematic Unicode escape sequences\n * that could cause errors during JSON serialization/storage\n *\n * @param value - The value to sanitize\n * @returns The sanitized value\n */\n private sanitizeJsonObject(value: unknown, seen: WeakSet<object> = new WeakSet()): unknown {\n if (value === null || value === undefined) {\n return value;\n }\n\n if (typeof value === \"string\") {\n // Handle multiple cases that can cause PostgreSQL/PgLite JSON parsing errors:\n // 1. Remove null bytes (U+0000) which are not allowed in PostgreSQL text fields\n // 2. Escape single backslashes that might be interpreted as escape sequences\n // 3. Fix broken Unicode escape sequences (\\u not followed by 4 hex digits)\n const nullChar = String.fromCharCode(0);\n const nullCharRegex = new RegExp(nullChar, \"g\");\n return value\n .replace(nullCharRegex, \"\") // Remove null bytes\n .replace(/\\\\(?![\"\\\\/bfnrtu])/g, \"\\\\\\\\\") // Escape single backslashes not part of valid escape sequences\n .replace(/\\\\u(?![0-9a-fA-F]{4})/g, \"\\\\\\\\u\"); // Fix malformed Unicode escape sequences\n }\n\n if (typeof value === \"object\") {\n if (seen.has(value as object)) {\n return null;\n } else {\n seen.add(value as object);\n }\n\n if (Array.isArray(value)) {\n return value.map((item) => this.sanitizeJsonObject(item, seen));\n } else {\n const result: Record<string, unknown> = {};\n const nullChar = String.fromCharCode(0);\n const nullCharRegex = new RegExp(nullChar, \"g\");\n for (const [key, val] of Object.entries(value)) {\n // Also sanitize object keys\n const sanitizedKey =\n typeof key === \"string\"\n ? key.replace(nullCharRegex, \"\").replace(/\\\\u(?![0-9a-fA-F]{4})/g, \"\\\\\\\\u\")\n : key;\n result[sanitizedKey] = this.sanitizeJsonObject(val, seen);\n }\n return result;\n }\n }\n\n return value;\n }\n\n /**\n * Asynchronously retrieves logs from the database based on the provided parameters.\n * @param {Object} params - The parameters for retrieving logs.\n * @param {UUID} params.entityId - The ID of the entity associated with the logs.\n * @param {UUID} [params.roomId] - The ID of the room associated with the logs.\n * @param {string} [params.type] - The type of the logs to retrieve.\n * @param {number} [params.count] - The maximum number of logs to retrieve.\n * @param {number} [params.offset] - The offset to retrieve logs from.\n * @returns {Promise<Log[]>} A Promise that resolves to an array of logs.\n */\n async getLogs(params: {\n entityId?: UUID;\n roomId?: UUID;\n type?: string;\n count?: number;\n offset?: number;\n }): Promise<Log[]> {\n const { entityId, roomId, type, count, offset } = params;\n\n // Use withEntityContext for RLS only when entityId is provided\n // Without entityId, bypass RLS to see all logs (for non-RLS mode)\n return this.withEntityContext(entityId ?? null, async (tx) => {\n const result = await tx\n .select()\n .from(logTable)\n .where(\n and(\n roomId ? eq(logTable.roomId, roomId) : undefined,\n type ? eq(logTable.type, type) : undefined\n )\n )\n .orderBy(desc(logTable.createdAt))\n .limit(count ?? 10)\n .offset(offset ?? 0);\n\n const logs = result.map((log) => ({\n ...log,\n id: log.id as UUID,\n entityId: log.entityId as UUID,\n roomId: log.roomId as UUID,\n type: log.type as string,\n body: log.body as LogBody,\n createdAt: new Date(log.createdAt as string | number | Date),\n }));\n\n if (logs.length === 0) return [];\n\n return logs;\n });\n }\n\n async getAgentRunSummaries(\n params: {\n limit?: number;\n roomId?: UUID;\n status?: RunStatus | \"all\";\n from?: number;\n to?: number;\n entityId?: UUID;\n } = {}\n ): Promise<AgentRunSummaryResult> {\n const limit = Math.min(Math.max(params.limit ?? 20, 1), 100);\n const fromDate = typeof params.from === \"number\" ? new Date(params.from) : undefined;\n const toDate = typeof params.to === \"number\" ? new Date(params.to) : undefined;\n\n // Use withEntityContext for RLS when entityId is provided\n return this.withEntityContext(params.entityId ?? null, async (tx) => {\n const runMap = new Map<string, AgentRunSummary>();\n\n const conditions: SQL<unknown>[] = [\n eq(logTable.type, \"run_event\"),\n sql`${logTable.body} ? 'runId'`,\n eq(roomTable.agentId, this.agentId),\n ];\n\n if (params.roomId) {\n conditions.push(eq(logTable.roomId, params.roomId));\n }\n if (fromDate) {\n conditions.push(gte(logTable.createdAt, fromDate));\n }\n if (toDate) {\n conditions.push(lte(logTable.createdAt, toDate));\n }\n\n const whereClause = and(...conditions);\n\n const eventLimit = Math.max(limit * 20, 200);\n\n const runEventRows = await tx\n .select({\n runId: sql<string>`(${logTable.body} ->> 'runId')`,\n status: sql<string | null>`(${logTable.body} ->> 'status')`,\n messageId: sql<string | null>`(${logTable.body} ->> 'messageId')`,\n rawBody: logTable.body,\n createdAt: logTable.createdAt,\n roomId: logTable.roomId,\n entityId: logTable.entityId,\n })\n .from(logTable)\n .innerJoin(roomTable, eq(roomTable.id, logTable.roomId))\n .where(whereClause)\n .orderBy(desc(logTable.createdAt))\n .limit(eventLimit);\n\n for (const row of runEventRows) {\n const runId = row.runId;\n if (!runId) continue;\n\n const summary: AgentRunSummary = runMap.get(runId) ?? {\n runId,\n status: \"started\",\n startedAt: null,\n endedAt: null,\n durationMs: null,\n messageId: undefined,\n roomId: undefined,\n entityId: undefined,\n metadata: {},\n };\n\n if (!summary.messageId && row.messageId) {\n summary.messageId = row.messageId as UUID;\n }\n if (!summary.roomId && row.roomId) {\n summary.roomId = row.roomId as UUID;\n }\n if (!summary.entityId && row.entityId) {\n summary.entityId = row.entityId as UUID;\n }\n\n const body = row.rawBody as Record<string, unknown> | undefined;\n if (body && typeof body === \"object\") {\n if (!summary.roomId && typeof body.roomId === \"string\") {\n summary.roomId = body.roomId as UUID;\n }\n if (!summary.entityId && typeof body.entityId === \"string\") {\n summary.entityId = body.entityId as UUID;\n }\n if (!summary.messageId && typeof body.messageId === \"string\") {\n summary.messageId = body.messageId as UUID;\n }\n if (!summary.metadata || Object.keys(summary.metadata).length === 0) {\n const metadata = (body.metadata as Record<string, unknown> | undefined) ?? undefined;\n summary.metadata = metadata ? ({ ...metadata } as Record<string, JsonValue>) : {};\n }\n }\n\n const createdAt = row.createdAt instanceof Date ? row.createdAt : new Date(row.createdAt);\n const timestamp = createdAt.getTime();\n const bodyStatus = body?.status;\n const eventStatus =\n (row.status as RunStatus | undefined) ?? (bodyStatus as RunStatus | undefined);\n\n if (eventStatus === \"started\") {\n const currentStartedAt =\n summary.startedAt === null\n ? null\n : typeof summary.startedAt === \"bigint\"\n ? Number(summary.startedAt)\n : summary.startedAt;\n summary.startedAt =\n currentStartedAt === null ? timestamp : Math.min(currentStartedAt, timestamp);\n } else if (\n eventStatus === \"completed\" ||\n eventStatus === \"timeout\" ||\n eventStatus === \"error\"\n ) {\n summary.status = eventStatus;\n summary.endedAt = timestamp;\n if (summary.startedAt !== null) {\n const startedAtNum =\n typeof summary.startedAt === \"bigint\" ? Number(summary.startedAt) : summary.startedAt;\n summary.durationMs = Math.max(timestamp - startedAtNum, 0);\n }\n }\n\n runMap.set(runId, summary);\n }\n\n let runs = Array.from(runMap.values());\n if (params.status && params.status !== \"all\") {\n runs = runs.filter((run) => run.status === params.status);\n }\n\n runs.sort((a, b) => {\n const aStarted =\n a.startedAt === null\n ? 0\n : typeof a.startedAt === \"bigint\"\n ? Number(a.startedAt)\n : a.startedAt;\n const bStarted =\n b.startedAt === null\n ? 0\n : typeof b.startedAt === \"bigint\"\n ? Number(b.startedAt)\n : b.startedAt;\n return bStarted - aStarted;\n });\n\n const total = runs.length;\n const limitedRuns = runs.slice(0, limit);\n const hasMore = total > limit;\n\n const runCounts = new Map<string, AgentRunCounts>();\n for (const run of limitedRuns) {\n runCounts.set(run.runId, {\n actions: 0,\n modelCalls: 0,\n errors: 0,\n evaluators: 0,\n });\n }\n\n const runIds = limitedRuns.map((run) => run.runId).filter(Boolean);\n\n if (runIds.length > 0) {\n const runIdArray = sql`array[${sql.join(\n runIds.map((id) => sql`${id}`),\n sql`, `\n )}]::text[]`;\n\n const actionSummary = await this.db.execute(sql`\n SELECT\n body->>'runId' as \"runId\",\n COUNT(*)::int as \"actions\",\n SUM(CASE WHEN COALESCE(body->'result'->>'success', 'true') = 'false' THEN 1 ELSE 0 END)::int as \"errors\",\n SUM(COALESCE((body->>'promptCount')::int, 0))::int as \"modelCalls\"\n FROM ${logTable}\n WHERE type = 'action'\n AND body->>'runId' = ANY(${runIdArray})\n GROUP BY body->>'runId'\n `);\n\n const actionRows = (actionSummary.rows ?? []) as Array<{\n runId: string;\n actions: number | string;\n errors: number | string;\n modelCalls: number | string;\n }>;\n\n for (const row of actionRows) {\n const counts = runCounts.get(row.runId);\n if (!counts) continue;\n counts.actions += Number(row.actions ?? 0);\n counts.errors += Number(row.errors ?? 0);\n counts.modelCalls += Number(row.modelCalls ?? 0);\n }\n\n const evaluatorSummary = await this.db.execute(sql`\n SELECT\n body->>'runId' as \"runId\",\n COUNT(*)::int as \"evaluators\"\n FROM ${logTable}\n WHERE type = 'evaluator'\n AND body->>'runId' = ANY(${runIdArray})\n GROUP BY body->>'runId'\n `);\n\n const evaluatorRows = (evaluatorSummary.rows ?? []) as Array<{\n runId: string;\n evaluators: number | string;\n }>;\n\n for (const row of evaluatorRows) {\n const counts = runCounts.get(row.runId);\n if (!counts) continue;\n counts.evaluators += Number(row.evaluators ?? 0);\n }\n\n const genericSummary = await this.db.execute(sql`\n SELECT\n body->>'runId' as \"runId\",\n COUNT(*) FILTER (WHERE type LIKE 'useModel:%')::int as \"modelLogs\",\n COUNT(*) FILTER (WHERE type = 'embedding_event' AND body->>'status' = 'failed')::int as \"embeddingErrors\"\n FROM ${logTable}\n WHERE (type LIKE 'useModel:%' OR type = 'embedding_event')\n AND body->>'runId' = ANY(${runIdArray})\n GROUP BY body->>'runId'\n `);\n\n const genericRows = (genericSummary.rows ?? []) as Array<{\n runId: string;\n modelLogs: number | string;\n embeddingErrors: number | string;\n }>;\n\n for (const row of genericRows) {\n const counts = runCounts.get(row.runId);\n if (!counts) continue;\n counts.modelCalls += Number(row.modelLogs ?? 0);\n counts.errors += Number(row.embeddingErrors ?? 0);\n }\n }\n\n for (const run of limitedRuns) {\n const counts = runCounts.get(run.runId) ?? {\n actions: 0,\n modelCalls: 0,\n errors: 0,\n evaluators: 0,\n };\n // Cast through unknown to bridge the core type (without $typeName) to proto type (with $typeName)\n run.counts = counts as unknown as typeof run.counts;\n }\n\n return {\n runs: limitedRuns as unknown as import(\"@elizaos/core\").AgentRunSummary[],\n total,\n hasMore,\n } as AgentRunSummaryResult;\n });\n }\n\n /**\n * Asynchronously deletes a log from the database based on the provided parameters.\n * @param {UUID} logId - The ID of the log to delete.\n * @returns {Promise<void>} A Promise that resolves when the log is deleted.\n */\n async deleteLog(logId: UUID): Promise<void> {\n return this.withDatabase(async () => {\n await this.db.delete(logTable).where(eq(logTable.id, logId));\n });\n }\n\n /**\n * Asynchronously searches for memories in the database based on the provided parameters.\n * @param {Object} params - The parameters for searching for memories.\n * @param {string} params.tableName - The name of the table to search for memories in.\n * @param {number[]} params.embedding - The embedding to search for.\n * @param {number} [params.match_threshold] - The threshold for the cosine distance.\n * @param {number} [params.count] - The maximum number of memories to retrieve.\n * @param {boolean} [params.unique] - Whether to retrieve unique memories only.\n * @param {string} [params.query] - Optional query string for potential reranking.\n * @param {UUID} [params.roomId] - Optional room ID to filter by.\n * @param {UUID} [params.worldId] - Optional world ID to filter by.\n * @param {UUID} [params.entityId] - Optional entity ID to filter by.\n * @returns {Promise<Memory[]>} A Promise that resolves to an array of memories.\n */\n async searchMemories(params: {\n tableName: string;\n embedding: number[];\n match_threshold?: number;\n count?: number;\n unique?: boolean;\n query?: string;\n roomId?: UUID;\n worldId?: UUID;\n entityId?: UUID;\n }): Promise<Memory[]> {\n return await this.searchMemoriesByEmbedding(params.embedding, {\n match_threshold: params.match_threshold,\n count: params.count,\n // Pass direct scope fields down\n roomId: params.roomId,\n worldId: params.worldId,\n entityId: params.entityId,\n unique: params.unique,\n tableName: params.tableName,\n });\n }\n\n /**\n * Asynchronously searches for memories in the database based on the provided parameters.\n * @param {number[]} embedding - The embedding to search for.\n * @param {Object} params - The parameters for searching for memories.\n * @param {number} [params.match_threshold] - The threshold for the cosine distance.\n * @param {number} [params.count] - The maximum number of memories to retrieve.\n * @param {UUID} [params.roomId] - Optional room ID to filter by.\n * @param {UUID} [params.worldId] - Optional world ID to filter by.\n * @param {UUID} [params.entityId] - Optional entity ID to filter by.\n * @param {boolean} [params.unique] - Whether to retrieve unique memories only.\n * @param {string} [params.tableName] - The name of the table to search for memories in.\n * @returns {Promise<Memory[]>} A Promise that resolves to an array of memories.\n */\n async searchMemoriesByEmbedding(\n embedding: number[],\n params: {\n match_threshold?: number;\n count?: number;\n roomId?: UUID;\n worldId?: UUID;\n entityId?: UUID;\n unique?: boolean;\n tableName: string;\n }\n ): Promise<Memory[]> {\n return this.withDatabase(async () => {\n const cleanVector = embedding.map((n) => (Number.isFinite(n) ? Number(n.toFixed(6)) : 0));\n\n const similarity = sql<number>`1 - (${cosineDistance(\n embeddingTable[this.embeddingDimension],\n cleanVector\n )})`;\n\n const conditions = [eq(memoryTable.type, params.tableName)];\n\n if (params.unique) {\n conditions.push(eq(memoryTable.unique, true));\n }\n\n conditions.push(eq(memoryTable.agentId, this.agentId));\n\n // Add filters based on direct params\n if (params.roomId) {\n conditions.push(eq(memoryTable.roomId, params.roomId));\n }\n if (params.worldId) {\n conditions.push(eq(memoryTable.worldId, params.worldId));\n }\n if (params.entityId) {\n conditions.push(eq(memoryTable.entityId, params.entityId));\n }\n\n if (params.match_threshold) {\n conditions.push(gte(similarity, params.match_threshold));\n }\n\n const results = await this.db\n .select({\n memory: memoryTable,\n similarity,\n embedding: embeddingTable[this.embeddingDimension],\n })\n .from(embeddingTable)\n .innerJoin(memoryTable, eq(memoryTable.id, embeddingTable.memoryId))\n .where(and(...conditions))\n .orderBy(desc(similarity))\n .limit(params.count ?? 10);\n\n return results.map((row) => ({\n id: row.memory.id as UUID,\n type: row.memory.type,\n createdAt: row.memory.createdAt.getTime(),\n content:\n typeof row.memory.content === \"string\"\n ? JSON.parse(row.memory.content)\n : row.memory.content,\n entityId: row.memory.entityId as UUID,\n agentId: row.memory.agentId as UUID,\n roomId: row.memory.roomId as UUID,\n worldId: row.memory.worldId as UUID | undefined, // Include worldId\n unique: row.memory.unique,\n metadata: row.memory.metadata as MemoryMetadata,\n embedding: row.embedding ?? undefined,\n similarity: row.similarity,\n }));\n });\n }\n\n /**\n * Asynchronously creates a new memory in the database.\n * @param {Memory & { metadata?: MemoryMetadata }} memory - The memory object to create.\n * @param {string} tableName - The name of the table to create the memory in.\n * @returns {Promise<UUID>} A Promise that resolves to the ID of the created memory.\n */\n async createMemory(\n memory: Memory & { metadata?: MemoryMetadata },\n tableName: string\n ): Promise<UUID> {\n const memoryId = memory.id ?? (v4() as UUID);\n\n const existing = await this.getMemoryById(memoryId);\n if (existing) {\n return memoryId;\n }\n\n // only do costly check if we need to\n if (memory.unique === undefined) {\n memory.unique = true; // set default\n if (memory.embedding && Array.isArray(memory.embedding)) {\n const similarMemories = await this.searchMemoriesByEmbedding(memory.embedding, {\n tableName,\n // Use the scope fields from the memory object for similarity check\n roomId: memory.roomId,\n worldId: memory.worldId,\n entityId: memory.entityId,\n match_threshold: 0.95,\n count: 1,\n });\n memory.unique = similarMemories.length === 0;\n }\n }\n\n // Ensure we always pass a JSON string to the SQL placeholder – if we pass an\n // object directly PG sees `[object Object]` and fails the `::jsonb` cast.\n const contentToInsert =\n typeof memory.content === \"string\" ? memory.content : JSON.stringify(memory.content ?? {});\n\n const metadataToInsert =\n typeof memory.metadata === \"string\" ? memory.metadata : JSON.stringify(memory.metadata ?? {});\n\n // Use withEntityContext to set Entity RLS context if needed\n // This delegates to the concrete adapter implementation (PostgreSQL or PGLite)\n await this.withEntityContext(memory.entityId, async (tx) => {\n await tx.insert(memoryTable).values([\n {\n id: memoryId,\n type: tableName,\n content: sql`${contentToInsert}::jsonb`,\n metadata: sql`${metadataToInsert}::jsonb`,\n entityId: memory.entityId,\n roomId: memory.roomId,\n worldId: memory.worldId, // Include worldId\n agentId: memory.agentId || this.agentId,\n unique: memory.unique,\n createdAt: memory.createdAt ? new Date(memory.createdAt) : new Date(),\n },\n ]);\n\n if (memory.embedding && Array.isArray(memory.embedding)) {\n const embeddingValues: Record<string, unknown> = {\n id: v4(),\n memoryId: memoryId,\n createdAt: memory.createdAt ? new Date(memory.createdAt) : new Date(),\n };\n\n const cleanVector = memory.embedding.map((n) =>\n Number.isFinite(n) ? Number(n.toFixed(6)) : 0\n );\n\n embeddingValues[this.embeddingDimension] = cleanVector;\n\n await tx.insert(embeddingTable).values([embeddingValues]);\n }\n });\n\n return memoryId;\n }\n\n /**\n * Updates an existing memory in the database.\n * @param memory The memory object with updated content and optional embedding\n * @returns Promise resolving to boolean indicating success\n */\n async updateMemory(\n memory: Partial<Memory> & { id: UUID; metadata?: MemoryMetadata }\n ): Promise<boolean> {\n return this.withDatabase(async () => {\n try {\n await this.db.transaction(async (tx) => {\n // Update memory content if provided\n if (memory.content) {\n const contentToUpdate =\n typeof memory.content === \"string\"\n ? memory.content\n : JSON.stringify(memory.content ?? {});\n\n const metadataToUpdate =\n typeof memory.metadata === \"string\"\n ? memory.metadata\n : JSON.stringify(memory.metadata ?? {});\n\n await tx\n .update(memoryTable)\n .set({\n content: sql`${contentToUpdate}::jsonb`,\n ...(memory.metadata && {\n metadata: sql`${metadataToUpdate}::jsonb`,\n }),\n })\n .where(eq(memoryTable.id, memory.id));\n } else if (memory.metadata) {\n // Update only metadata if content is not provided\n const metadataToUpdate =\n typeof memory.metadata === \"string\"\n ? memory.metadata\n : JSON.stringify(memory.metadata ?? {});\n\n await tx\n .update(memoryTable)\n .set({\n metadata: sql`${metadataToUpdate}::jsonb`,\n })\n .where(eq(memoryTable.id, memory.id));\n }\n\n // Update embedding if provided\n if (memory.embedding && Array.isArray(memory.embedding)) {\n const cleanVector = memory.embedding.map((n) =>\n Number.isFinite(n) ? Number(n.toFixed(6)) : 0\n );\n\n // Check if embedding exists\n const existingEmbedding = await tx\n .select({ id: embeddingTable.id })\n .from(embeddingTable)\n .where(eq(embeddingTable.memoryId, memory.id))\n .limit(1);\n\n if (existingEmbedding.length > 0) {\n // Update existing embedding\n const updateValues: Record<string, unknown> = {};\n updateValues[this.embeddingDimension] = cleanVector;\n\n await tx\n .update(embeddingTable)\n .set(updateValues)\n .where(eq(embeddingTable.memoryId, memory.id));\n } else {\n // Create new embedding\n const embeddingValues: Record<string, unknown> = {\n id: v4(),\n memoryId: memory.id,\n };\n embeddingValues[this.embeddingDimension] = cleanVector;\n\n await tx.insert(embeddingTable).values([embeddingValues]);\n }\n }\n });\n\n return true;\n } catch (error) {\n logger.error(\n {\n src: \"plugin:sql\",\n memoryId: memory.id,\n error: error instanceof Error ? error.message : String(error),\n },\n \"Failed to update memory\"\n );\n return false;\n }\n });\n }\n\n /**\n * Asynchronously deletes a memory from the database based on the provided parameters.\n * @param {UUID} memoryId - The ID of the memory to delete.\n * @returns {Promise<void>} A Promise that resolves when the memory is deleted.\n */\n async deleteMemory(memoryId: UUID): Promise<void> {\n return this.withDatabase(async () => {\n await this.db.transaction(async (tx) => {\n // See if there are any fragments that we need to delete\n await this.deleteMemoryFragments(tx, memoryId);\n\n // Then delete the embedding for the main memory\n await tx.delete(embeddingTable).where(eq(embeddingTable.memoryId, memoryId));\n\n // Finally delete the memory itself\n await tx.delete(memoryTable).where(eq(memoryTable.id, memoryId));\n });\n });\n }\n\n /**\n * Asynchronously deletes multiple memories from the database in a single batch operation.\n * @param {UUID[]} memoryIds - An array of UUIDs of the memories to delete.\n * @returns {Promise<void>} A Promise that resolves when all memories are deleted.\n */\n async deleteManyMemories(memoryIds: UUID[]): Promise<void> {\n if (memoryIds.length === 0) {\n return;\n }\n\n return this.withDatabase(async () => {\n await this.db.transaction(async (tx) => {\n // Process in smaller batches to avoid query size limits\n const BATCH_SIZE = 100;\n for (let i = 0; i < memoryIds.length; i += BATCH_SIZE) {\n const batch = memoryIds.slice(i, i + BATCH_SIZE);\n\n // Delete any fragments for document memories in this batch\n await Promise.all(\n batch.map(async (memoryId) => {\n await this.deleteMemoryFragments(tx, memoryId);\n })\n );\n\n // Delete embeddings for the batch\n await tx.delete(embeddingTable).where(inArray(embeddingTable.memoryId, batch));\n\n // Delete the memories themselves\n await tx.delete(memoryTable).where(inArray(memoryTable.id, batch));\n }\n });\n });\n }\n\n /**\n * Deletes all memory fragments that reference a specific document memory\n * @param tx The database transaction\n * @param documentId The UUID of the document memory whose fragments should be deleted\n * @private\n */\n private async deleteMemoryFragments(tx: DrizzleDatabase, documentId: UUID): Promise<void> {\n const fragmentsToDelete = await this.getMemoryFragments(tx, documentId);\n\n if (fragmentsToDelete.length > 0) {\n const fragmentIds = fragmentsToDelete.map((f) => f.id) as UUID[];\n\n // Delete embeddings for fragments\n await tx.delete(embeddingTable).where(inArray(embeddingTable.memoryId, fragmentIds));\n\n // Delete the fragments\n await tx.delete(memoryTable).where(inArray(memoryTable.id, fragmentIds));\n }\n }\n\n /**\n * Retrieves all memory fragments that reference a specific document memory\n * @param tx The database transaction\n * @param documentId The UUID of the document memory whose fragments should be retrieved\n * @returns An array of memory fragments\n * @private\n */\n private async getMemoryFragments(tx: DrizzleDatabase, documentId: UUID): Promise<{ id: UUID }[]> {\n const fragments = await tx\n .select({ id: memoryTable.id })\n .from(memoryTable)\n .where(\n and(\n eq(memoryTable.agentId, this.agentId),\n sql`${memoryTable.metadata}->>'documentId' = ${documentId}`\n )\n );\n\n return fragments.map((f) => ({ id: f.id as UUID }));\n }\n\n /**\n * Asynchronously deletes all memories from the database based on the provided parameters.\n * @param {UUID} roomId - The ID of the room to delete memories from.\n * @param {string} tableName - The name of the table to delete memories from.\n * @returns {Promise<void>} A Promise that resolves when the memories are deleted.\n */\n async deleteAllMemories(roomId: UUID, tableName: string): Promise<void> {\n return this.withDatabase(async () => {\n await this.db.transaction(async (tx) => {\n // 1) fetch all memory IDs for this room + table\n const rows = await tx\n .select({ id: memoryTable.id })\n .from(memoryTable)\n .where(and(eq(memoryTable.roomId, roomId), eq(memoryTable.type, tableName)));\n\n const ids = rows.map((r) => r.id);\n logger.debug(\n { src: \"plugin:sql\", roomId, tableName, memoryCount: ids.length },\n \"Deleting all memories\"\n );\n\n if (ids.length === 0) {\n return;\n }\n\n // 2) delete any fragments for \"document\" memories & their embeddings\n await Promise.all(\n ids.map(async (memoryId) => {\n await this.deleteMemoryFragments(tx, memoryId);\n await tx.delete(embeddingTable).where(eq(embeddingTable.memoryId, memoryId));\n })\n );\n\n // 3) delete the memories themselves\n await tx\n .delete(memoryTable)\n .where(and(eq(memoryTable.roomId, roomId), eq(memoryTable.type, tableName)));\n });\n });\n }\n\n /**\n * Asynchronously counts the number of memories in the database based on the provided parameters.\n * @param {UUID} roomId - The ID of the room to count memories in.\n * @param {boolean} [unique] - Whether to count unique memories only.\n * @param {string} [tableName] - The name of the table to count memories in.\n * @returns {Promise<number>} A Promise that resolves to the number of memories.\n */\n async countMemories(roomId: UUID, unique = true, tableName = \"\"): Promise<number> {\n if (!tableName) throw new Error(\"tableName is required\");\n\n return this.withDatabase(async () => {\n const conditions = [eq(memoryTable.roomId, roomId), eq(memoryTable.type, tableName)];\n\n if (unique) {\n conditions.push(eq(memoryTable.unique, true));\n }\n\n const result = await this.db\n .select({ count: sql<number>`count(*)` })\n .from(memoryTable)\n .where(and(...conditions));\n\n const result0 = result[0];\n return Number(result0?.count ?? 0);\n });\n }\n\n /**\n * Asynchronously retrieves rooms from the database based on the provided parameters.\n * @param {UUID[]} roomIds - The IDs of the rooms to retrieve.\n * @returns {Promise<Room[] | null>} A Promise that resolves to the rooms if found, null otherwise.\n */\n async getRoomsByIds(roomIds: UUID[]): Promise<Room[] | null> {\n return this.withDatabase(async () => {\n const result = await this.db\n .select({\n id: roomTable.id,\n name: roomTable.name, // Added name\n channelId: roomTable.channelId,\n agentId: roomTable.agentId,\n messageServerId: roomTable.messageServerId,\n worldId: roomTable.worldId,\n type: roomTable.type,\n source: roomTable.source,\n metadata: roomTable.metadata, // Added metadata\n })\n .from(roomTable)\n .where(and(inArray(roomTable.id, roomIds), eq(roomTable.agentId, this.agentId)));\n\n // Map the result to properly typed Room objects\n const rooms = result.map((room) => ({\n ...room,\n id: room.id as UUID,\n name: room.name ?? undefined,\n agentId: room.agentId as UUID,\n messageServerId: room.messageServerId as UUID,\n serverId: room.messageServerId as UUID, // Backward compatibility alias\n worldId: room.worldId as UUID,\n channelId: room.channelId as UUID,\n type: room.type as ChannelType,\n metadata: room.metadata as Metadata,\n }));\n\n return rooms;\n });\n }\n\n /**\n * Asynchronously retrieves all rooms from the database based on the provided parameters.\n * @param {UUID} worldId - The ID of the world to retrieve rooms from.\n * @returns {Promise<Room[]>} A Promise that resolves to an array of rooms.\n */\n async getRoomsByWorld(worldId: UUID): Promise<Room[]> {\n return this.withDatabase(async () => {\n const result = await this.db.select().from(roomTable).where(eq(roomTable.worldId, worldId));\n const rooms = result.map((room) => ({\n ...room,\n id: room.id as UUID,\n name: room.name ?? undefined,\n agentId: room.agentId as UUID,\n messageServerId: room.messageServerId as UUID,\n serverId: room.messageServerId as UUID, // Backward compatibility alias\n worldId: room.worldId as UUID,\n channelId: room.channelId as UUID,\n type: room.type as ChannelType,\n metadata: room.metadata as Metadata,\n }));\n return rooms;\n });\n }\n\n /**\n * Asynchronously updates a room in the database based on the provided parameters.\n * @param {Room} room - The room object to update.\n * @returns {Promise<void>} A Promise that resolves when the room is updated.\n */\n async updateRoom(room: Room): Promise<void> {\n return this.withDatabase(async () => {\n await this.db\n .update(roomTable)\n .set({ ...room, agentId: this.agentId })\n .where(eq(roomTable.id, room.id));\n });\n }\n\n /**\n * Asynchronously creates a new room in the database based on the provided parameters.\n * @param {Room} room - The room object to create.\n * @returns {Promise<UUID>} A Promise that resolves to the ID of the created room.\n */\n async createRooms(rooms: Room[]): Promise<UUID[]> {\n return this.withDatabase(async () => {\n const roomsWithIds = rooms.map((room) => ({\n ...room,\n agentId: this.agentId,\n id: room.id || v4(), // ensure each room has a unique ID\n }));\n\n const insertedRooms = await this.db\n .insert(roomTable)\n .values(roomsWithIds)\n .onConflictDoNothing()\n .returning();\n const insertedIds = insertedRooms.map((r) => r.id as UUID);\n return insertedIds;\n });\n }\n\n /**\n * Asynchronously deletes a room from the database based on the provided parameters.\n * @param {UUID} roomId - The ID of the room to delete.\n * @returns {Promise<void>} A Promise that resolves when the room is deleted.\n */\n async deleteRoom(roomId: UUID): Promise<void> {\n if (!roomId) throw new Error(\"Room ID is required\");\n return this.withDatabase(async () => {\n await this.db.transaction(async (tx) => {\n await tx.delete(roomTable).where(eq(roomTable.id, roomId));\n });\n });\n }\n\n /**\n * Asynchronously retrieves all rooms for a participant from the database based on the provided parameters.\n * @param {UUID} entityId - The ID of the entity to retrieve rooms for.\n * @returns {Promise<UUID[]>} A Promise that resolves to an array of room IDs.\n */\n async getRoomsForParticipant(entityId: UUID): Promise<UUID[]> {\n return this.withDatabase(async () => {\n const result = await this.db\n .select({ roomId: participantTable.roomId })\n .from(participantTable)\n .innerJoin(roomTable, eq(participantTable.roomId, roomTable.id))\n .where(and(eq(participantTable.entityId, entityId), eq(roomTable.agentId, this.agentId)));\n\n return result.map((row) => row.roomId as UUID);\n });\n }\n\n /**\n * Asynchronously retrieves all rooms for a list of participants from the database based on the provided parameters.\n * @param {UUID[]} entityIds - The IDs of the entities to retrieve rooms for.\n * @returns {Promise<UUID[]>} A Promise that resolves to an array of room IDs.\n */\n async getRoomsForParticipants(entityIds: UUID[]): Promise<UUID[]> {\n return this.withDatabase(async () => {\n const result = await this.db\n .selectDistinct({ roomId: participantTable.roomId })\n .from(participantTable)\n .innerJoin(roomTable, eq(participantTable.roomId, roomTable.id))\n .where(\n and(inArray(participantTable.entityId, entityIds), eq(roomTable.agentId, this.agentId))\n );\n\n return result.map((row) => row.roomId as UUID);\n });\n }\n\n /**\n * Asynchronously adds a participant to a room in the database based on the provided parameters.\n * @param {UUID} entityId - The ID of the entity to add to the room.\n * @param {UUID} roomId - The ID of the room to add the entity to.\n * @returns {Promise<boolean>} A Promise that resolves to a boolean indicating whether the participant was added successfully.\n */\n async addParticipant(entityId: UUID, roomId: UUID): Promise<boolean> {\n return this.withDatabase(async () => {\n try {\n await this.db\n .insert(participantTable)\n .values({\n entityId,\n roomId,\n agentId: this.agentId,\n })\n .onConflictDoNothing();\n return true;\n } catch (error) {\n logger.error(\n {\n src: \"plugin:sql\",\n entityId,\n roomId,\n agentId: this.agentId,\n error: error instanceof Error ? error.message : String(error),\n },\n \"Failed to add participant to room\"\n );\n return false;\n }\n });\n }\n\n async addParticipantsRoom(entityIds: UUID[], roomId: UUID): Promise<boolean> {\n return this.withDatabase(async () => {\n try {\n const values = entityIds.map((id) => ({\n entityId: id,\n roomId,\n agentId: this.agentId,\n }));\n await this.db.insert(participantTable).values(values).onConflictDoNothing().execute();\n return true;\n } catch (error) {\n logger.error(\n {\n src: \"plugin:sql\",\n roomId,\n agentId: this.agentId,\n error: error instanceof Error ? error.message : String(error),\n },\n \"Failed to add participants to room\"\n );\n return false;\n }\n });\n }\n\n /**\n * Asynchronously removes a participant from a room in the database based on the provided parameters.\n * @param {UUID} entityId - The ID of the entity to remove from the room.\n * @param {UUID} roomId - The ID of the room to remove the entity from.\n * @returns {Promise<boolean>} A Promise that resolves to a boolean indicating whether the participant was removed successfully.\n */\n async removeParticipant(entityId: UUID, roomId: UUID): Promise<boolean> {\n return this.withDatabase(async () => {\n try {\n const result = await this.db.transaction(async (tx) => {\n return await tx\n .delete(participantTable)\n .where(\n and(eq(participantTable.entityId, entityId), eq(participantTable.roomId, roomId))\n )\n .returning();\n });\n\n const removed = result.length > 0;\n return removed;\n } catch (error) {\n logger.error(\n {\n src: \"plugin:sql\",\n entityId,\n roomId,\n error: error instanceof Error ? error.message : String(error),\n },\n \"Failed to remove participant from room\"\n );\n return false;\n }\n });\n }\n\n /**\n * Asynchronously retrieves all participants for an entity from the database based on the provided parameters.\n * @param {UUID} entityId - The ID of the entity to retrieve participants for.\n * @returns {Promise<Participant[]>} A Promise that resolves to an array of participants.\n */\n async getParticipantsForEntity(entityId: UUID): Promise<Participant[]> {\n return this.withDatabase(async () => {\n const result = await this.db\n .select({\n id: participantTable.id,\n entityId: participantTable.entityId,\n roomId: participantTable.roomId,\n })\n .from(participantTable)\n .where(eq(participantTable.entityId, entityId));\n\n const entities = await this.getEntitiesByIds([entityId]);\n\n if (!entities || !entities.length) {\n return [];\n }\n\n return result.map((row) => ({\n id: row.id as UUID,\n entity: entities[0],\n }));\n });\n }\n\n /**\n * Asynchronously retrieves all participants for a room from the database based on the provided parameters.\n * @param {UUID} roomId - The ID of the room to retrieve participants for.\n * @returns {Promise<UUID[]>} A Promise that resolves to an array of entity IDs.\n */\n async getParticipantsForRoom(roomId: UUID): Promise<UUID[]> {\n return this.withDatabase(async () => {\n const result = await this.db\n .select({ entityId: participantTable.entityId })\n .from(participantTable)\n .where(eq(participantTable.roomId, roomId));\n\n return result.map((row) => row.entityId as UUID);\n });\n }\n\n /**\n * Check if an entity is a participant in a specific room/channel.\n * More efficient than getParticipantsForRoom when only checking membership.\n * @param {UUID} roomId - The ID of the room to check.\n * @param {UUID} entityId - The ID of the entity to check.\n * @returns {Promise<boolean>} A Promise that resolves to true if entity is a participant.\n */\n async isRoomParticipant(roomId: UUID, entityId: UUID): Promise<boolean> {\n return this.withDatabase(async () => {\n const result = await this.db\n .select()\n .from(participantTable)\n .where(and(eq(participantTable.roomId, roomId), eq(participantTable.entityId, entityId)))\n .limit(1);\n\n return result.length > 0;\n });\n }\n\n /**\n * Asynchronously retrieves the user state for a participant in a room from the database based on the provided parameters.\n * @param {UUID} roomId - The ID of the room to retrieve the participant's user state for.\n * @param {UUID} entityId - The ID of the entity to retrieve the user state for.\n * @returns {Promise<\"FOLLOWED\" | \"MUTED\" | null>} A Promise that resolves to the participant's user state.\n */\n async getParticipantUserState(\n roomId: UUID,\n entityId: UUID\n ): Promise<\"FOLLOWED\" | \"MUTED\" | null> {\n return this.withDatabase(async () => {\n const result = await this.db\n .select({ roomState: participantTable.roomState })\n .from(participantTable)\n .where(\n and(\n eq(participantTable.roomId, roomId),\n eq(participantTable.entityId, entityId),\n eq(participantTable.agentId, this.agentId)\n )\n )\n .limit(1);\n\n const result0 = result[0];\n return (result0?.roomState as \"FOLLOWED\" | \"MUTED\" | null) ?? null;\n });\n }\n\n /**\n * Asynchronously sets the user state for a participant in a room in the database based on the provided parameters.\n * @param {UUID} roomId - The ID of the room to set the participant's user state for.\n * @param {UUID} entityId - The ID of the entity to set the user state for.\n * @param {string} state - The state to set the participant's user state to.\n * @returns {Promise<void>} A Promise that resolves when the participant's user state is set.\n */\n async setParticipantUserState(\n roomId: UUID,\n entityId: UUID,\n state: \"FOLLOWED\" | \"MUTED\" | null\n ): Promise<void> {\n return this.withDatabase(async () => {\n try {\n await this.db.transaction(async (tx) => {\n await tx\n .update(participantTable)\n .set({ roomState: state })\n .where(\n and(\n eq(participantTable.roomId, roomId),\n eq(participantTable.entityId, entityId),\n eq(participantTable.agentId, this.agentId)\n )\n );\n });\n } catch (error) {\n logger.error(\n {\n src: \"plugin:sql\",\n roomId,\n entityId,\n state,\n error: error instanceof Error ? error.message : String(error),\n },\n \"Failed to set participant follow state\"\n );\n throw error;\n }\n });\n }\n\n /**\n * Asynchronously creates a new relationship in the database based on the provided parameters.\n * @param {Object} params - The parameters for creating a new relationship.\n * @param {UUID} params.sourceEntityId - The ID of the source entity.\n * @param {UUID} params.targetEntityId - The ID of the target entity.\n * @param {string[]} [params.tags] - The tags for the relationship.\n * @param {Object} [params.metadata] - The metadata for the relationship.\n * @returns {Promise<boolean>} A Promise that resolves to a boolean indicating whether the relationship was created successfully.\n */\n async createRelationship(params: {\n sourceEntityId: UUID;\n targetEntityId: UUID;\n tags?: string[];\n metadata?: { [key: string]: unknown };\n }): Promise<boolean> {\n return this.withDatabase(async () => {\n const id = v4();\n const saveParams = {\n id,\n sourceEntityId: params.sourceEntityId,\n targetEntityId: params.targetEntityId,\n agentId: this.agentId,\n tags: params.tags || [],\n metadata: params.metadata || {},\n };\n try {\n await this.db.insert(relationshipTable).values(saveParams);\n return true;\n } catch (error) {\n logger.error(\n {\n src: \"plugin:sql\",\n agentId: this.agentId,\n error: error instanceof Error ? error.message : String(error),\n saveParams,\n },\n \"Error creating relationship\"\n );\n return false;\n }\n });\n }\n\n /**\n * Asynchronously updates an existing relationship in the database based on the provided parameters.\n * @param {Relationship} relationship - The relationship object to update.\n * @returns {Promise<void>} A Promise that resolves when the relationship is updated.\n */\n async updateRelationship(relationship: Relationship): Promise<void> {\n return this.withDatabase(async () => {\n try {\n await this.db\n .update(relationshipTable)\n .set({\n tags: relationship.tags || [],\n metadata: relationship.metadata || {},\n })\n .where(eq(relationshipTable.id, relationship.id));\n } catch (error) {\n logger.error(\n {\n src: \"plugin:sql\",\n agentId: this.agentId,\n error: error instanceof Error ? error.message : String(error),\n relationshipId: relationship.id,\n },\n \"Error updating relationship\"\n );\n throw error;\n }\n });\n }\n\n /**\n * Asynchronously retrieves a relationship from the database based on the provided parameters.\n * @param {Object} params - The parameters for retrieving a relationship.\n * @param {UUID} params.sourceEntityId - The ID of the source entity.\n * @param {UUID} params.targetEntityId - The ID of the target entity.\n * @returns {Promise<Relationship | null>} A Promise that resolves to the relationship if found, null otherwise.\n */\n async getRelationship(params: {\n sourceEntityId: UUID;\n targetEntityId: UUID;\n }): Promise<Relationship | null> {\n return this.withDatabase(async () => {\n const { sourceEntityId, targetEntityId } = params;\n const result = await this.db\n .select()\n .from(relationshipTable)\n .where(\n and(\n eq(relationshipTable.sourceEntityId, sourceEntityId),\n eq(relationshipTable.targetEntityId, targetEntityId)\n )\n );\n if (result.length === 0) return null;\n const relationship = result[0];\n return {\n ...relationship,\n id: relationship.id as UUID,\n sourceEntityId: relationship.sourceEntityId as UUID,\n targetEntityId: relationship.targetEntityId as UUID,\n agentId: relationship.agentId as UUID,\n tags: (relationship.tags ?? []) as string[],\n metadata: (relationship.metadata ?? {}) as Metadata,\n createdAt: relationship.createdAt.toISOString(),\n };\n });\n }\n\n /**\n * Asynchronously retrieves relationships from the database based on the provided parameters.\n * @param {Object} params - The parameters for retrieving relationships.\n * @param {UUID} params.entityId - The ID of the entity to retrieve relationships for.\n * @param {string[]} [params.tags] - The tags to filter relationships by.\n * @returns {Promise<Relationship[]>} A Promise that resolves to an array of relationships.\n */\n async getRelationships(params: { entityId: UUID; tags?: string[] }): Promise<Relationship[]> {\n return this.withDatabase(async () => {\n const { entityId, tags } = params;\n\n let query: SQL;\n\n if (tags && tags.length > 0) {\n query = sql`\n SELECT * FROM ${relationshipTable}\n WHERE (${relationshipTable.sourceEntityId} = ${entityId} OR ${relationshipTable.targetEntityId} = ${entityId})\n AND ${relationshipTable.tags} && CAST(ARRAY[${sql.join(tags, sql`, `)}] AS text[])\n `;\n } else {\n query = sql`\n SELECT * FROM ${relationshipTable}\n WHERE ${relationshipTable.sourceEntityId} = ${entityId} OR ${relationshipTable.targetEntityId} = ${entityId}\n `;\n }\n\n const result = await this.db.execute(query);\n\n return result.rows.map((relationship: Record<string, unknown>) => ({\n ...relationship,\n id: relationship.id as UUID,\n sourceEntityId: (relationship.source_entity_id || relationship.sourceEntityId) as UUID,\n targetEntityId: (relationship.target_entity_id || relationship.targetEntityId) as UUID,\n agentId: (relationship.agent_id || relationship.agentId) as UUID,\n tags: (relationship.tags ?? []) as string[],\n metadata: (relationship.metadata ?? {}) as Metadata,\n createdAt:\n relationship.created_at || relationship.createdAt\n ? (relationship.created_at || relationship.createdAt) instanceof Date\n ? ((relationship.created_at || relationship.createdAt) as Date).toISOString()\n : new Date(\n (relationship.created_at as string) || (relationship.createdAt as string)\n ).toISOString()\n : new Date().toISOString(),\n }));\n });\n }\n\n /**\n * Asynchronously retrieves a cache value from the database based on the provided key.\n * @param {string} key - The key to retrieve the cache value for.\n * @returns {Promise<T | undefined>} A Promise that resolves to the cache value if found, undefined otherwise.\n */\n async getCache<T>(key: string): Promise<T | undefined> {\n return this.withDatabase(async () => {\n try {\n const result = await this.db\n .select({ value: cacheTable.value })\n .from(cacheTable)\n .where(and(eq(cacheTable.agentId, this.agentId), eq(cacheTable.key, key)))\n .limit(1);\n\n if (result && result.length > 0 && result[0]) {\n return result[0].value as T | undefined;\n }\n\n return undefined;\n } catch (error) {\n logger.error(\n {\n src: \"plugin:sql\",\n agentId: this.agentId,\n error: error instanceof Error ? error.message : String(error),\n key,\n },\n \"Error fetching cache\"\n );\n return undefined;\n }\n });\n }\n\n /**\n * Asynchronously sets a cache value in the database based on the provided key and value.\n * @param {string} key - The key to set the cache value for.\n * @param {T} value - The value to set in the cache.\n * @returns {Promise<boolean>} A Promise that resolves to a boolean indicating whether the cache value was set successfully.\n */\n async setCache<T>(key: string, value: T): Promise<boolean> {\n return this.withDatabase(async () => {\n try {\n await this.db\n .insert(cacheTable)\n .values({\n key: key,\n agentId: this.agentId,\n value: value,\n })\n .onConflictDoUpdate({\n target: [cacheTable.key, cacheTable.agentId],\n set: {\n value: value,\n },\n });\n\n return true;\n } catch (error) {\n logger.error(\n {\n src: \"plugin:sql\",\n agentId: this.agentId,\n error: error instanceof Error ? error.message : String(error),\n key,\n },\n \"Error setting cache\"\n );\n return false;\n }\n });\n }\n\n /**\n * Asynchronously deletes a cache value from the database based on the provided key.\n * @param {string} key - The key to delete the cache value for.\n * @returns {Promise<boolean>} A Promise that resolves to a boolean indicating whether the cache value was deleted successfully.\n */\n async deleteCache(key: string): Promise<boolean> {\n return this.withDatabase(async () => {\n try {\n await this.db.transaction(async (tx) => {\n await tx\n .delete(cacheTable)\n .where(and(eq(cacheTable.agentId, this.agentId), eq(cacheTable.key, key)));\n });\n return true;\n } catch (error) {\n logger.error(\n {\n src: \"plugin:sql\",\n agentId: this.agentId,\n error: error instanceof Error ? error.message : String(error),\n key,\n },\n \"Error deleting cache\"\n );\n return false;\n }\n });\n }\n\n /**\n * Asynchronously creates a new world in the database based on the provided parameters.\n * @param {World} world - The world object to create.\n * @returns {Promise<UUID>} A Promise that resolves to the ID of the created world.\n */\n async createWorld(world: World): Promise<UUID> {\n return this.withDatabase(async () => {\n const newWorldId = world.id || (v4() as UUID);\n await this.db.insert(worldTable).values({\n ...world,\n id: newWorldId,\n name: world.name || \"\",\n });\n return newWorldId;\n });\n }\n\n /**\n * Asynchronously retrieves a world from the database based on the provided parameters.\n * @param {UUID} id - The ID of the world to retrieve.\n * @returns {Promise<World | null>} A Promise that resolves to the world if found, null otherwise.\n */\n async getWorld(id: UUID): Promise<World | null> {\n return this.withDatabase(async () => {\n const result = await this.db.select().from(worldTable).where(eq(worldTable.id, id));\n return result.length > 0 ? (result[0] as World) : null;\n });\n }\n\n /**\n * Asynchronously retrieves all worlds from the database based on the provided parameters.\n * @returns {Promise<World[]>} A Promise that resolves to an array of worlds.\n */\n async getAllWorlds(): Promise<World[]> {\n return this.withDatabase(async () => {\n const result = await this.db\n .select()\n .from(worldTable)\n .where(eq(worldTable.agentId, this.agentId));\n return result as World[];\n });\n }\n\n /**\n * Asynchronously updates an existing world in the database based on the provided parameters.\n * @param {World} world - The world object to update.\n * @returns {Promise<void>} A Promise that resolves when the world is updated.\n */\n async updateWorld(world: World): Promise<void> {\n return this.withDatabase(async () => {\n await this.db.update(worldTable).set(world).where(eq(worldTable.id, world.id));\n });\n }\n\n /**\n * Asynchronously removes a world from the database based on the provided parameters.\n * @param {UUID} id - The ID of the world to remove.\n * @returns {Promise<void>} A Promise that resolves when the world is removed.\n */\n async removeWorld(id: UUID): Promise<void> {\n return this.withDatabase(async () => {\n await this.db.delete(worldTable).where(eq(worldTable.id, id));\n });\n }\n\n /**\n * Asynchronously creates a new task in the database based on the provided parameters.\n * @param {Task} task - The task object to create.\n * @returns {Promise<UUID>} A Promise that resolves to the ID of the created task.\n */\n async createTask(task: Task): Promise<UUID> {\n // Default worldId to agentId for agent-internal tasks\n if (!task.worldId) {\n task = { ...task, worldId: this.agentId as UUID };\n }\n return this.withRetry(async () => {\n return this.withDatabase(async () => {\n const now = new Date();\n const metadata = task.metadata || {};\n\n const values = {\n id: task.id as UUID,\n name: task.name,\n description: task.description,\n roomId: task.roomId as UUID,\n worldId: task.worldId as UUID,\n tags: task.tags,\n metadata: metadata,\n createdAt: now,\n updatedAt: now,\n agentId: this.agentId as UUID,\n };\n\n const result = await this.db.insert(taskTable).values(values).returning();\n\n return result[0].id as UUID;\n });\n });\n }\n\n /**\n * Asynchronously retrieves tasks based on specified parameters.\n * @param params Object containing optional roomId, tags, and entityId to filter tasks\n * @returns Promise resolving to an array of Task objects\n */\n async getTasks(params: {\n roomId?: UUID;\n tags?: string[];\n entityId?: UUID; // Added entityId parameter\n }): Promise<Task[]> {\n return this.withRetry(async () => {\n return this.withDatabase(async () => {\n const result = await this.db\n .select()\n .from(taskTable)\n .where(\n and(\n eq(taskTable.agentId, this.agentId),\n ...(params.roomId ? [eq(taskTable.roomId, params.roomId)] : []),\n ...(params.tags && params.tags.length > 0\n ? [\n sql`${taskTable.tags} @> ARRAY[${sql.join(\n params.tags.map((t) => sql`${t}`),\n sql`, `\n )}]::text[]`,\n ]\n : [])\n )\n );\n\n return result.map((row) => ({\n id: row.id as UUID,\n name: row.name,\n description: row.description ?? \"\",\n roomId: row.roomId as UUID,\n worldId: row.worldId as UUID,\n tags: row.tags || [],\n metadata: row.metadata as TaskMetadata,\n }));\n });\n });\n }\n\n /**\n * Asynchronously retrieves a specific task by its name.\n * @param name The name of the task to retrieve\n * @returns Promise resolving to the Task object if found, null otherwise\n */\n async getTasksByName(name: string): Promise<Task[]> {\n return this.withRetry(async () => {\n return this.withDatabase(async () => {\n const result = await this.db\n .select()\n .from(taskTable)\n .where(and(eq(taskTable.name, name), eq(taskTable.agentId, this.agentId)));\n\n return result.map((row) => ({\n id: row.id as UUID,\n name: row.name,\n description: row.description ?? \"\",\n roomId: row.roomId as UUID,\n worldId: row.worldId as UUID,\n tags: row.tags || [],\n metadata: (row.metadata || {}) as TaskMetadata,\n }));\n });\n });\n }\n\n /**\n * Asynchronously retrieves a specific task by its ID.\n * @param id The UUID of the task to retrieve\n * @returns Promise resolving to the Task object if found, null otherwise\n */\n async getTask(id: UUID): Promise<Task | null> {\n return this.withRetry(async () => {\n return this.withDatabase(async () => {\n const result = await this.db\n .select()\n .from(taskTable)\n .where(and(eq(taskTable.id, id), eq(taskTable.agentId, this.agentId)))\n .limit(1);\n\n if (result.length === 0) {\n return null;\n }\n\n const row = result[0];\n return {\n id: row.id as UUID,\n name: row.name,\n description: row.description ?? \"\",\n roomId: row.roomId as UUID,\n worldId: row.worldId as UUID,\n tags: row.tags || [],\n metadata: (row.metadata || {}) as TaskMetadata,\n };\n });\n });\n }\n\n /**\n * Asynchronously updates an existing task in the database.\n * @param id The UUID of the task to update\n * @param task Partial Task object containing the fields to update\n * @returns Promise resolving when the update is complete\n */\n async updateTask(id: UUID, task: Partial<Task>): Promise<void> {\n await this.withRetry(async () => {\n await this.withDatabase(async () => {\n const updateValues: Partial<typeof taskTable.$inferInsert> = {};\n\n // Add fields to update if they exist in the partial task object\n if (task.name !== undefined) updateValues.name = task.name;\n if (task.description !== undefined) updateValues.description = task.description;\n if (task.roomId !== undefined) updateValues.roomId = task.roomId;\n if (task.worldId !== undefined) updateValues.worldId = task.worldId;\n if (task.tags !== undefined) updateValues.tags = task.tags;\n if (task.metadata !== undefined)\n updateValues.metadata = task.metadata as typeof taskTable.$inferInsert.metadata;\n // Handle createdAt if present in the task object (using type assertion for compatibility)\n const taskWithCreatedAt = task as { createdAt?: number | bigint | null };\n if (taskWithCreatedAt.createdAt !== undefined && taskWithCreatedAt.createdAt !== null) {\n const createdAtValue = taskWithCreatedAt.createdAt;\n updateValues.createdAt = new Date(\n typeof createdAtValue === \"bigint\" ? Number(createdAtValue) : createdAtValue\n );\n }\n\n // Always update the updatedAt timestamp as a Date (schema uses Date, not number)\n const dbUpdateValues: Partial<typeof taskTable.$inferInsert> = {\n ...updateValues,\n updatedAt: new Date(),\n };\n\n // Handle metadata updates - just set it directly without merging\n if (task.metadata !== undefined) {\n dbUpdateValues.metadata = task.metadata;\n }\n\n await this.db\n .update(taskTable)\n // createdAt is hella borked, number / Date\n .set(dbUpdateValues)\n .where(and(eq(taskTable.id, id), eq(taskTable.agentId, this.agentId)));\n });\n });\n }\n\n /**\n * Asynchronously deletes a task from the database.\n * @param id The UUID of the task to delete\n * @returns Promise resolving when the deletion is complete\n */\n async deleteTask(id: UUID): Promise<void> {\n return this.withDatabase(async () => {\n await this.db.delete(taskTable).where(eq(taskTable.id, id));\n });\n }\n\n async getMemoriesByWorldId(params: {\n worldId: UUID;\n count?: number;\n tableName?: string;\n }): Promise<Memory[]> {\n return this.withDatabase(async () => {\n // First, get all rooms for the given worldId\n const rooms = await this.db\n .select({ id: roomTable.id })\n .from(roomTable)\n .where(and(eq(roomTable.worldId, params.worldId), eq(roomTable.agentId, this.agentId)));\n\n if (rooms.length === 0) {\n return [];\n }\n\n const roomIds = rooms.map((room) => room.id as UUID);\n\n const memories = await this.getMemoriesByRoomIds({\n roomIds,\n tableName: params.tableName || \"messages\",\n limit: params.count,\n });\n\n return memories;\n });\n }\n\n async deleteRoomsByWorldId(worldId: UUID): Promise<void> {\n return this.withDatabase(async () => {\n const rooms = await this.db\n .select({ id: roomTable.id })\n .from(roomTable)\n .where(and(eq(roomTable.worldId, worldId), eq(roomTable.agentId, this.agentId)));\n\n if (rooms.length === 0) {\n return;\n }\n\n const roomIds = rooms.map((room) => room.id as UUID);\n\n if (roomIds.length > 0) {\n await this.db.delete(logTable).where(inArray(logTable.roomId, roomIds));\n await this.db.delete(participantTable).where(inArray(participantTable.roomId, roomIds));\n\n const memoriesInRooms = await this.db\n .select({ id: memoryTable.id })\n .from(memoryTable)\n .where(inArray(memoryTable.roomId, roomIds));\n const memoryIdsInRooms = memoriesInRooms.map((m) => m.id as UUID);\n\n if (memoryIdsInRooms.length > 0) {\n await this.db\n .delete(embeddingTable)\n .where(inArray(embeddingTable.memoryId, memoryIdsInRooms));\n await this.db.delete(memoryTable).where(inArray(memoryTable.id, memoryIdsInRooms));\n }\n\n await this.db.delete(roomTable).where(inArray(roomTable.id, roomIds));\n\n logger.debug(\n {\n src: \"plugin:sql\",\n worldId,\n roomsDeleted: roomIds.length,\n memoriesDeleted: memoryIdsInRooms.length,\n },\n \"World cleanup completed\"\n );\n }\n });\n }\n\n // Message Server Database Operations\n\n /**\n * Creates a new message server in the central database\n */\n async createMessageServer(data: {\n id?: UUID; // Allow passing a specific ID\n name: string;\n sourceType: string;\n sourceId?: string;\n metadata?: Metadata;\n }): Promise<{\n id: UUID;\n name: string;\n sourceType: string;\n sourceId?: string;\n metadata?: Metadata;\n createdAt: Date;\n updatedAt: Date;\n }> {\n return this.withDatabase(async () => {\n const newId = data.id || (v4() as UUID);\n const now = new Date();\n const serverToInsert = {\n id: newId,\n name: data.name,\n sourceType: data.sourceType,\n sourceId: data.sourceId,\n metadata: data.metadata,\n createdAt: now,\n updatedAt: now,\n };\n\n await this.db.insert(messageServerTable).values(serverToInsert).onConflictDoNothing(); // In case the ID already exists\n\n // If server already existed, fetch it\n if (data.id) {\n const existing = await this.db\n .select()\n .from(messageServerTable)\n .where(eq(messageServerTable.id, data.id))\n .limit(1);\n if (existing.length > 0) {\n return {\n id: existing[0].id as UUID,\n name: existing[0].name,\n sourceType: existing[0].sourceType,\n sourceId: existing[0].sourceId || undefined,\n metadata: (existing[0].metadata || undefined) as Metadata | undefined,\n createdAt: existing[0].createdAt,\n updatedAt: existing[0].updatedAt,\n };\n }\n }\n\n return serverToInsert;\n });\n }\n\n /**\n * Gets all message servers\n */\n async getMessageServers(): Promise<\n Array<{\n id: UUID;\n name: string;\n sourceType: string;\n sourceId?: string;\n metadata?: Metadata;\n createdAt: Date;\n updatedAt: Date;\n }>\n > {\n const result = await this.withDatabase(async () => {\n const results = await this.db.select().from(messageServerTable);\n return results.map((r) => ({\n id: r.id as UUID,\n name: r.name,\n sourceType: r.sourceType,\n sourceId: r.sourceId || undefined,\n metadata: (r.metadata || undefined) as Metadata | undefined,\n createdAt: r.createdAt,\n updatedAt: r.updatedAt,\n }));\n });\n // Guard against null return\n return result || [];\n }\n\n /**\n * Gets a message server by ID\n */\n async getMessageServerById(serverId: UUID): Promise<{\n id: UUID;\n name: string;\n sourceType: string;\n sourceId?: string;\n metadata?: Metadata;\n createdAt: Date;\n updatedAt: Date;\n } | null> {\n return this.withDatabase(async () => {\n const results = await this.db\n .select()\n .from(messageServerTable)\n .where(eq(messageServerTable.id, serverId))\n .limit(1);\n return results.length > 0\n ? {\n id: results[0].id as UUID,\n name: results[0].name,\n sourceType: results[0].sourceType,\n sourceId: results[0].sourceId || undefined,\n metadata: (results[0].metadata || undefined) as Metadata | undefined,\n createdAt: results[0].createdAt,\n updatedAt: results[0].updatedAt,\n }\n : null;\n });\n }\n\n /**\n * Gets a message server by RLS server_id.\n * The server_id column is added dynamically when RLS is enabled.\n */\n async getMessageServerByRlsServerId(rlsServerId: UUID): Promise<{\n id: UUID;\n name: string;\n sourceType: string;\n sourceId?: string;\n metadata?: Metadata;\n createdAt: Date;\n updatedAt: Date;\n } | null> {\n return this.withDatabase(async () => {\n // Use raw SQL since server_id column is dynamically added by RLS and not in Drizzle schema\n const results = await this.db.execute(sql`\n SELECT id, name, source_type, source_id, metadata, created_at, updated_at\n FROM message_servers\n WHERE server_id = ${rlsServerId}\n LIMIT 1\n `);\n\n const rows = results.rows || results;\n return (rows as Record<string, unknown>[]).length > 0\n ? {\n id: (rows as Record<string, unknown>[])[0].id as UUID,\n name: (rows as Record<string, unknown>[])[0].name as string,\n sourceType: (rows as Record<string, unknown>[])[0].source_type as string,\n sourceId: ((rows as Record<string, unknown>[])[0].source_id || undefined) as\n | string\n | undefined,\n metadata: ((rows as Record<string, unknown>[])[0].metadata || undefined) as\n | Metadata\n | undefined,\n createdAt: new Date((rows as Record<string, unknown>[])[0].created_at as string),\n updatedAt: new Date((rows as Record<string, unknown>[])[0].updated_at as string),\n }\n : null;\n });\n }\n\n /**\n * Creates a new channel\n */\n async createChannel(\n data: {\n id?: UUID; // Allow passing a specific ID\n messageServerId: UUID;\n name: string;\n type: string;\n sourceType?: string;\n sourceId?: string;\n topic?: string;\n metadata?: Metadata;\n },\n participantIds?: UUID[]\n ): Promise<{\n id: UUID;\n messageServerId: UUID;\n name: string;\n type: string;\n sourceType?: string;\n sourceId?: string;\n topic?: string;\n metadata?: Metadata;\n createdAt: Date;\n updatedAt: Date;\n }> {\n return this.withDatabase(async () => {\n const newId = data.id || (v4() as UUID);\n const now = new Date();\n const channelToInsert = {\n id: newId,\n messageServerId: data.messageServerId,\n name: data.name,\n type: data.type,\n sourceType: data.sourceType,\n sourceId: data.sourceId,\n topic: data.topic,\n metadata: data.metadata,\n createdAt: now,\n updatedAt: now,\n };\n\n await this.db.transaction(async (tx) => {\n await tx.insert(channelTable).values(channelToInsert);\n\n if (participantIds && participantIds.length > 0) {\n const participantValues = participantIds.map((entityId) => ({\n channelId: newId,\n entityId: entityId,\n }));\n await tx.insert(channelParticipantsTable).values(participantValues).onConflictDoNothing();\n }\n });\n\n return channelToInsert;\n });\n }\n\n /**\n * Gets channels for a message server\n */\n async getChannelsForMessageServer(messageServerId: UUID): Promise<\n Array<{\n id: UUID;\n messageServerId: UUID;\n name: string;\n type: string;\n sourceType?: string;\n sourceId?: string;\n topic?: string;\n metadata?: Metadata;\n createdAt: Date;\n updatedAt: Date;\n }>\n > {\n return this.withDatabase(async () => {\n const results = await this.db\n .select()\n .from(channelTable)\n .where(eq(channelTable.messageServerId, messageServerId));\n return results.map((r) => ({\n id: r.id as UUID,\n messageServerId: r.messageServerId as UUID,\n name: r.name,\n type: r.type,\n sourceType: r.sourceType || undefined,\n sourceId: r.sourceId || undefined,\n topic: r.topic || undefined,\n metadata: (r.metadata || undefined) as Metadata | undefined,\n createdAt: r.createdAt,\n updatedAt: r.updatedAt,\n }));\n });\n }\n\n /**\n * Gets channel details\n */\n async getChannelDetails(channelId: UUID): Promise<{\n id: UUID;\n messageServerId: UUID;\n name: string;\n type: string;\n sourceType?: string;\n sourceId?: string;\n topic?: string;\n metadata?: Metadata;\n createdAt: Date;\n updatedAt: Date;\n } | null> {\n return this.withDatabase(async () => {\n const results = await this.db\n .select()\n .from(channelTable)\n .where(eq(channelTable.id, channelId))\n .limit(1);\n return results.length > 0\n ? {\n id: results[0].id as UUID,\n messageServerId: results[0].messageServerId as UUID,\n name: results[0].name,\n type: results[0].type,\n sourceType: results[0].sourceType || undefined,\n sourceId: results[0].sourceId || undefined,\n topic: results[0].topic || undefined,\n metadata: (results[0].metadata || undefined) as Metadata | undefined,\n createdAt: results[0].createdAt,\n updatedAt: results[0].updatedAt,\n }\n : null;\n });\n }\n\n /**\n * Creates a message\n */\n async createMessage(data: {\n channelId: UUID;\n authorId: UUID;\n content: string;\n rawMessage?: Record<string, unknown>;\n sourceType?: string;\n sourceId?: string;\n metadata?: Metadata;\n inReplyToRootMessageId?: UUID;\n messageId?: UUID;\n }): Promise<{\n id: UUID;\n channelId: UUID;\n authorId: UUID;\n content: string;\n rawMessage?: Record<string, unknown>;\n sourceType?: string;\n sourceId?: string;\n metadata?: Metadata;\n inReplyToRootMessageId?: UUID;\n createdAt: Date;\n updatedAt: Date;\n }> {\n return this.withDatabase(async () => {\n const newId = data.messageId || (v4() as UUID);\n const now = new Date();\n const messageToInsert = {\n id: newId,\n channelId: data.channelId,\n authorId: data.authorId,\n content: data.content,\n rawMessage: data.rawMessage,\n sourceType: data.sourceType,\n sourceId: data.sourceId,\n metadata: data.metadata,\n inReplyToRootMessageId: data.inReplyToRootMessageId,\n createdAt: now,\n updatedAt: now,\n };\n\n await this.db.insert(messageTable).values(messageToInsert);\n return messageToInsert;\n });\n }\n\n async getMessageById(id: UUID): Promise<{\n id: UUID;\n channelId: UUID;\n authorId: UUID;\n content: string;\n rawMessage?: Record<string, unknown>;\n sourceType?: string;\n sourceId?: string;\n metadata?: Metadata;\n inReplyToRootMessageId?: UUID;\n createdAt: Date;\n updatedAt: Date;\n } | null> {\n return this.withDatabase(async () => {\n const rows = await this.db\n .select()\n .from(messageTable)\n .where(eq(messageTable.id, id))\n .limit(1);\n if (!rows || rows.length === 0) return null;\n const row = rows[0];\n return {\n id: row.id as UUID,\n channelId: row.channelId as UUID,\n authorId: row.authorId as UUID,\n content: row.content,\n rawMessage: row.rawMessage || undefined,\n sourceType: row.sourceType || undefined,\n sourceId: row.sourceId || undefined,\n metadata: (row.metadata || undefined) as Metadata | undefined,\n inReplyToRootMessageId: (row.inReplyToRootMessageId || undefined) as UUID | undefined,\n createdAt: row.createdAt,\n updatedAt: row.updatedAt,\n };\n });\n }\n\n async updateMessage(\n id: UUID,\n patch: {\n content?: string;\n rawMessage?: Record<string, unknown>;\n sourceType?: string;\n sourceId?: string;\n metadata?: Metadata;\n inReplyToRootMessageId?: UUID;\n }\n ): Promise<{\n id: UUID;\n channelId: UUID;\n authorId: UUID;\n content: string;\n rawMessage?: Record<string, unknown>;\n sourceType?: string;\n sourceId?: string;\n metadata?: Metadata;\n inReplyToRootMessageId?: UUID;\n createdAt: Date;\n updatedAt: Date;\n } | null> {\n return this.withDatabase(async () => {\n const existing = await this.getMessageById(id);\n if (!existing) return null;\n\n const updatedAt = new Date();\n const next = {\n content: patch.content ?? existing.content,\n rawMessage: patch.rawMessage ?? existing.rawMessage,\n sourceType: patch.sourceType ?? existing.sourceType,\n sourceId: patch.sourceId ?? existing.sourceId,\n metadata: patch.metadata ?? existing.metadata,\n inReplyToRootMessageId: patch.inReplyToRootMessageId ?? existing.inReplyToRootMessageId,\n updatedAt,\n };\n\n await this.db.update(messageTable).set(next).where(eq(messageTable.id, id));\n\n // Return merged object\n return {\n ...existing,\n ...next,\n };\n });\n }\n\n /**\n * Gets messages for a channel\n */\n async getMessagesForChannel(\n channelId: UUID,\n limit: number = 50,\n beforeTimestamp?: Date\n ): Promise<\n Array<{\n id: UUID;\n channelId: UUID;\n authorId: UUID;\n content: string;\n rawMessage?: Record<string, unknown>;\n sourceType?: string;\n sourceId?: string;\n metadata?: Metadata;\n inReplyToRootMessageId?: UUID;\n createdAt: Date;\n updatedAt: Date;\n }>\n > {\n return this.withDatabase(async () => {\n const conditions = [eq(messageTable.channelId, channelId)];\n if (beforeTimestamp) {\n conditions.push(lt(messageTable.createdAt, beforeTimestamp));\n }\n\n const query = this.db\n .select()\n .from(messageTable)\n .where(and(...conditions))\n .orderBy(desc(messageTable.createdAt))\n .limit(limit);\n\n const results = await query;\n return results.map((r) => ({\n id: r.id as UUID,\n channelId: r.channelId as UUID,\n authorId: r.authorId as UUID,\n content: r.content,\n rawMessage: r.rawMessage || undefined,\n sourceType: r.sourceType || undefined,\n sourceId: r.sourceId || undefined,\n metadata: r.metadata || undefined,\n inReplyToRootMessageId: r.inReplyToRootMessageId as UUID | undefined,\n createdAt: r.createdAt,\n updatedAt: r.updatedAt,\n }));\n });\n }\n\n /**\n * Deletes a message\n */\n async deleteMessage(messageId: UUID): Promise<void> {\n return this.withDatabase(async () => {\n await this.db.delete(messageTable).where(eq(messageTable.id, messageId));\n });\n }\n\n /**\n * Updates a channel\n */\n async updateChannel(\n channelId: UUID,\n updates: {\n name?: string;\n participantCentralUserIds?: UUID[];\n metadata?: Metadata;\n }\n ): Promise<{\n id: UUID;\n messageServerId: UUID;\n name: string;\n type: string;\n sourceType?: string;\n sourceId?: string;\n topic?: string;\n metadata?: Metadata;\n createdAt: Date;\n updatedAt: Date;\n }> {\n return this.withDatabase(async () => {\n const now = new Date();\n\n await this.db.transaction(async (tx) => {\n // Update channel details\n const updateData: Record<string, unknown> = { updatedAt: now };\n if (updates.name !== undefined) updateData.name = updates.name;\n if (updates.metadata !== undefined) updateData.metadata = updates.metadata;\n\n await tx.update(channelTable).set(updateData).where(eq(channelTable.id, channelId));\n\n // Update participants if provided\n if (updates.participantCentralUserIds !== undefined) {\n // Remove existing participants\n await tx\n .delete(channelParticipantsTable)\n .where(eq(channelParticipantsTable.channelId, channelId));\n\n // Add new participants\n if (updates.participantCentralUserIds.length > 0) {\n const participantValues = updates.participantCentralUserIds.map((entityId) => ({\n channelId: channelId,\n entityId: entityId,\n }));\n await tx\n .insert(channelParticipantsTable)\n .values(participantValues)\n .onConflictDoNothing();\n }\n }\n });\n\n // Return updated channel details\n const updatedChannel = await this.getChannelDetails(channelId);\n if (!updatedChannel) {\n throw new Error(`Channel ${channelId} not found after update`);\n }\n return updatedChannel;\n });\n }\n\n /**\n * Deletes a channel and all its associated data\n */\n async deleteChannel(channelId: UUID): Promise<void> {\n return this.withDatabase(async () => {\n await this.db.transaction(async (tx) => {\n // Delete all messages in the channel (cascade delete will handle this, but explicit is better)\n await tx.delete(messageTable).where(eq(messageTable.channelId, channelId));\n\n // Delete all participants (cascade delete will handle this, but explicit is better)\n await tx\n .delete(channelParticipantsTable)\n .where(eq(channelParticipantsTable.channelId, channelId));\n\n // Delete the channel itself\n await tx.delete(channelTable).where(eq(channelTable.id, channelId));\n });\n });\n }\n\n /**\n * Adds participants to a channel\n */\n async addChannelParticipants(channelId: UUID, entityIds: UUID[]): Promise<void> {\n return this.withDatabase(async () => {\n if (!entityIds || entityIds.length === 0) return;\n\n const participantValues = entityIds.map((entityId) => ({\n channelId: channelId,\n entityId: entityId,\n }));\n\n await this.db\n .insert(channelParticipantsTable)\n .values(participantValues)\n .onConflictDoNothing();\n });\n }\n\n /**\n * Gets participants for a channel\n */\n async getChannelParticipants(channelId: UUID): Promise<UUID[]> {\n return this.withDatabase(async () => {\n const results = await this.db\n .select({ entityId: channelParticipantsTable.entityId })\n .from(channelParticipantsTable)\n .where(eq(channelParticipantsTable.channelId, channelId));\n\n return results.map((r) => r.entityId as UUID);\n });\n }\n\n /**\n * Check if an entity is a participant in a specific messaging channel.\n * @param {UUID} channelId - The ID of the channel to check.\n * @param {UUID} entityId - The ID of the entity to check.\n * @returns {Promise<boolean>} A Promise that resolves to true if entity is a participant.\n */\n async isChannelParticipant(channelId: UUID, entityId: UUID): Promise<boolean> {\n return this.withDatabase(async () => {\n const result = await this.db\n .select()\n .from(channelParticipantsTable)\n .where(\n and(\n eq(channelParticipantsTable.channelId, channelId),\n eq(channelParticipantsTable.entityId, entityId)\n )\n )\n .limit(1);\n\n return result.length > 0;\n });\n }\n\n /**\n * Adds an agent to a message server (Discord/Telegram server)\n */\n async addAgentToMessageServer(messageServerId: UUID, agentId: UUID): Promise<void> {\n return this.withDatabase(async () => {\n await this.db\n .insert(messageServerAgentsTable)\n .values({\n messageServerId,\n agentId,\n })\n .onConflictDoNothing();\n });\n }\n\n /**\n * Gets agents for a message server (Discord/Telegram server)\n */\n async getAgentsForMessageServer(messageServerId: UUID): Promise<UUID[]> {\n return this.withDatabase(async () => {\n const results = await this.db\n .select({ agentId: messageServerAgentsTable.agentId })\n .from(messageServerAgentsTable)\n .where(eq(messageServerAgentsTable.messageServerId, messageServerId));\n\n return results.map((r) => r.agentId as UUID);\n });\n }\n\n /**\n * Removes an agent from a message server (Discord/Telegram server)\n */\n async removeAgentFromMessageServer(messageServerId: UUID, agentId: UUID): Promise<void> {\n return this.withDatabase(async () => {\n await this.db\n .delete(messageServerAgentsTable)\n .where(\n and(\n eq(messageServerAgentsTable.messageServerId, messageServerId),\n eq(messageServerAgentsTable.agentId, agentId)\n )\n );\n });\n }\n\n /**\n * Finds or creates a DM channel between two users\n */\n async findOrCreateDmChannel(\n user1Id: UUID,\n user2Id: UUID,\n messageServerId: UUID\n ): Promise<{\n id: UUID;\n messageServerId: UUID;\n name: string;\n type: string;\n sourceType?: string;\n sourceId?: string;\n topic?: string;\n metadata?: Metadata;\n createdAt: Date;\n updatedAt: Date;\n }> {\n return this.withDatabase(async () => {\n const ids = [user1Id, user2Id].sort();\n const dmChannelName = `DM-${ids[0]}-${ids[1]}`;\n\n const existingChannels = await this.db\n .select()\n .from(channelTable)\n .where(\n and(\n eq(channelTable.type, ChannelType.DM),\n eq(channelTable.name, dmChannelName),\n eq(channelTable.messageServerId, messageServerId)\n )\n )\n .limit(1);\n\n if (existingChannels.length > 0) {\n return {\n id: existingChannels[0].id as UUID,\n messageServerId: existingChannels[0].messageServerId as UUID,\n name: existingChannels[0].name,\n type: existingChannels[0].type,\n sourceType: existingChannels[0].sourceType || undefined,\n sourceId: existingChannels[0].sourceId || undefined,\n topic: existingChannels[0].topic || undefined,\n metadata: (existingChannels[0].metadata || undefined) as Metadata | undefined,\n createdAt: existingChannels[0].createdAt,\n updatedAt: existingChannels[0].updatedAt,\n };\n }\n\n // Create new DM channel\n return this.createChannel(\n {\n messageServerId,\n name: dmChannelName,\n type: ChannelType.DM,\n metadata: { user1: ids[0], user2: ids[1] },\n },\n ids\n );\n });\n }\n\n // ===============================\n // Pairing Methods\n // ===============================\n\n /**\n * Get all pending pairing requests for a channel and agent.\n */\n async getPairingRequests(channel: PairingChannel, agentId: UUID): Promise<PairingRequest[]> {\n return this.withDatabase(async () => {\n const results = await this.db\n .select()\n .from(pairingRequestTable)\n .where(\n and(eq(pairingRequestTable.channel, channel), eq(pairingRequestTable.agentId, agentId))\n )\n .orderBy(pairingRequestTable.createdAt);\n\n return results.map((row) => ({\n id: row.id as UUID,\n channel: row.channel as PairingChannel,\n senderId: row.senderId,\n code: row.code,\n createdAt: row.createdAt,\n lastSeenAt: row.lastSeenAt,\n metadata: (row.metadata as Record<string, string>) || undefined,\n agentId: row.agentId as UUID,\n }));\n });\n }\n\n /**\n * Create a new pairing request.\n */\n async createPairingRequest(request: PairingRequest): Promise<UUID> {\n return this.withDatabase(async () => {\n const id = request.id || (v4() as UUID);\n await this.db.insert(pairingRequestTable).values({\n id,\n channel: request.channel,\n senderId: request.senderId,\n code: request.code,\n createdAt: request.createdAt,\n lastSeenAt: request.lastSeenAt,\n metadata: request.metadata || {},\n agentId: request.agentId,\n });\n return id;\n });\n }\n\n /**\n * Update an existing pairing request.\n */\n async updatePairingRequest(request: PairingRequest): Promise<void> {\n return this.withDatabase(async () => {\n await this.db\n .update(pairingRequestTable)\n .set({\n lastSeenAt: request.lastSeenAt,\n metadata: request.metadata || {},\n })\n .where(eq(pairingRequestTable.id, request.id));\n });\n }\n\n /**\n * Delete a pairing request by ID.\n */\n async deletePairingRequest(id: UUID): Promise<void> {\n return this.withDatabase(async () => {\n await this.db.delete(pairingRequestTable).where(eq(pairingRequestTable.id, id));\n });\n }\n\n /**\n * Get the allowlist for a channel and agent.\n */\n async getPairingAllowlist(\n channel: PairingChannel,\n agentId: UUID\n ): Promise<PairingAllowlistEntry[]> {\n return this.withDatabase(async () => {\n const results = await this.db\n .select()\n .from(pairingAllowlistTable)\n .where(\n and(\n eq(pairingAllowlistTable.channel, channel),\n eq(pairingAllowlistTable.agentId, agentId)\n )\n )\n .orderBy(pairingAllowlistTable.createdAt);\n\n return results.map((row) => ({\n id: row.id as UUID,\n channel: row.channel as PairingChannel,\n senderId: row.senderId,\n createdAt: row.createdAt,\n metadata: (row.metadata as Record<string, string>) || undefined,\n agentId: row.agentId as UUID,\n }));\n });\n }\n\n /**\n * Create a new allowlist entry.\n */\n async createPairingAllowlistEntry(entry: PairingAllowlistEntry): Promise<UUID> {\n return this.withDatabase(async () => {\n const id = entry.id || (v4() as UUID);\n await this.db\n .insert(pairingAllowlistTable)\n .values({\n id,\n channel: entry.channel,\n senderId: entry.senderId,\n createdAt: entry.createdAt,\n metadata: entry.metadata || {},\n agentId: entry.agentId,\n })\n .onConflictDoNothing();\n return id;\n });\n }\n\n /**\n * Delete an allowlist entry by ID.\n */\n async deletePairingAllowlistEntry(id: UUID): Promise<void> {\n return this.withDatabase(async () => {\n await this.db.delete(pairingAllowlistTable).where(eq(pairingAllowlistTable.id, id));\n });\n }\n}\n\n// Import tables at the end to avoid circular dependencies\n",
25
+ "import {\n type Agent,\n type AgentRunCounts,\n type AgentRunSummary,\n type AgentRunSummaryResult,\n ChannelType,\n type Component,\n DatabaseAdapter,\n type Entity,\n type Log,\n type LogBody,\n logger,\n type Memory,\n type MemoryMetadata,\n type Metadata,\n type PairingAllowlistEntry,\n type PairingChannel,\n type PairingRequest,\n type Participant,\n type Relationship,\n type Room,\n type RunStatus,\n type Task,\n type TaskMetadata,\n type UUID,\n type World,\n} from \"@elizaos/core\";\n\n// JSON-serializable value type for metadata\ntype JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };\n\nimport {\n and,\n cosineDistance,\n count,\n desc,\n eq,\n gte,\n inArray,\n lt,\n lte,\n or,\n type SQL,\n sql,\n} from \"drizzle-orm\";\nimport { v4 } from \"uuid\";\nimport type { DatabaseMigrationService } from \"./migration-service\";\nimport { DIMENSION_MAP, type EmbeddingDimensionColumn } from \"./schema/embedding\";\nimport {\n agentTable,\n cacheTable,\n channelParticipantsTable,\n channelTable,\n componentTable,\n embeddingTable,\n entityTable,\n logTable,\n memoryTable,\n messageServerAgentsTable,\n messageServerTable,\n messageTable,\n pairingAllowlistTable,\n pairingRequestTable,\n participantTable,\n relationshipTable,\n roomTable,\n taskTable,\n worldTable,\n} from \"./schema/index\";\nimport type { DrizzleDatabase } from \"./types\";\n\nexport abstract class BaseDrizzleAdapter extends DatabaseAdapter<DrizzleDatabase> {\n protected readonly maxRetries: number = 3;\n protected readonly baseDelay: number = 1000;\n protected readonly maxDelay: number = 10000;\n protected readonly jitterMax: number = 1000;\n protected embeddingDimension: EmbeddingDimensionColumn = DIMENSION_MAP[384];\n protected migrationService?: DatabaseMigrationService;\n\n protected abstract withDatabase<T>(operation: () => Promise<T>): Promise<T>;\n\n public abstract withEntityContext<T>(\n entityId: UUID | null,\n callback: (tx: DrizzleDatabase) => Promise<T>\n ): Promise<T>;\n\n public abstract init(): Promise<void>;\n public abstract close(): Promise<void>;\n\n public async initialize(): Promise<void> {\n await this.init();\n }\n\n public async runPluginMigrations(\n plugins: Array<{ name: string; schema?: Record<string, unknown> }>,\n options?: {\n verbose?: boolean;\n force?: boolean;\n dryRun?: boolean;\n }\n ): Promise<void> {\n if (!this.migrationService) {\n const { DatabaseMigrationService } = await import(\"./migration-service\");\n this.migrationService = new DatabaseMigrationService();\n await this.migrationService.initializeWithDatabase(this.db as DrizzleDatabase);\n }\n\n for (const plugin of plugins) {\n if (plugin.schema) {\n this.migrationService.registerSchema(plugin.name, plugin.schema);\n }\n }\n\n await this.migrationService.runAllPluginMigrations(options);\n }\n\n public getDatabase(): unknown {\n return this.db;\n }\n\n protected agentId: UUID;\n\n constructor(agentId: UUID) {\n super();\n this.agentId = agentId;\n }\n\n private normalizeEntityNames(names: unknown): string[] {\n if (names == null) {\n return [];\n }\n\n if (typeof names === \"string\") {\n return [names];\n }\n\n if (Array.isArray(names)) {\n return names.map(String);\n }\n\n if (names instanceof Set) {\n return Array.from(names).map(String);\n }\n\n if (typeof names === \"object\" && typeof names[Symbol.iterator] === \"function\") {\n return Array.from(names as Iterable<unknown>).map(String);\n }\n\n return [String(names)];\n }\n\n private isValidUUID(value: string): boolean {\n return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value);\n }\n\n private normalizeWorldData(\n world: Partial<World> & { serverId?: UUID | null }\n ): typeof worldTable.$inferInsert {\n const worldData: typeof worldTable.$inferInsert = {\n agentId: this.agentId,\n id: (world.id || v4()) as UUID,\n name: world.name || \"\",\n metadata: world.metadata || {},\n };\n\n const serverId = world.serverId ?? world.messageServerId;\n if (typeof serverId === \"string\" && this.isValidUUID(serverId)) {\n worldData.messageServerId = serverId;\n } else if (serverId) {\n logger.warn(\n { src: \"plugin:sql\", agentId: this.agentId, serverId },\n \"Ignoring non-UUID message/server identifier for world\"\n );\n }\n\n return worldData;\n }\n\n private mapWorldResult(world: unknown): World {\n const mappedWorld = world as Record<string, unknown>;\n return {\n ...mappedWorld,\n serverId: (mappedWorld.messageServerId || mappedWorld.serverId) as UUID,\n } as unknown as World;\n }\n\n /**\n * Executes the given operation with retry logic.\n * @template T\n * @param {() => Promise<T>} operation - The operation to be executed.\n * @returns {Promise<T>} A promise that resolves with the result of the operation.\n */\n protected async withRetry<T>(operation: () => Promise<T>): Promise<T> {\n let lastError: Error = new Error(\"Unknown error\");\n\n for (let attempt = 1; attempt <= this.maxRetries; attempt++) {\n try {\n return await operation();\n } catch (error) {\n lastError = error as Error;\n\n if (attempt < this.maxRetries) {\n const backoffDelay = Math.min(this.baseDelay * 2 ** (attempt - 1), this.maxDelay);\n\n const jitter = Math.random() * this.jitterMax;\n const delay = backoffDelay + jitter;\n\n logger.warn(\n {\n src: \"plugin:sql\",\n attempt,\n maxRetries: this.maxRetries,\n error: error instanceof Error ? error.message : String(error),\n },\n \"Database operation failed, retrying\"\n );\n\n await new Promise((resolve) => setTimeout(resolve, delay));\n } else {\n logger.error(\n {\n src: \"plugin:sql\",\n totalAttempts: attempt,\n error: error instanceof Error ? error.message : String(error),\n },\n \"Max retry attempts reached\"\n );\n throw error instanceof Error ? error : new Error(String(error));\n }\n }\n }\n\n throw lastError;\n }\n\n /**\n * Asynchronously ensures that the given embedding dimension is valid for the agent.\n *\n * @param {number} dimension - The dimension to ensure for the embedding.\n * @returns {Promise<void>} - Resolves once the embedding dimension is ensured.\n */\n async ensureEmbeddingDimension(dimension: number) {\n return this.withDatabase(async () => {\n const existingMemory = await this.db\n .select()\n .from(memoryTable)\n .innerJoin(embeddingTable, eq(embeddingTable.memoryId, memoryTable.id))\n .where(eq(memoryTable.agentId, this.agentId))\n .limit(1);\n\n if (existingMemory.length > 0) {\n // The join result includes both memoryTable and embeddingTable columns\n // Access embedding columns directly from the joined result\n interface JoinedMemoryResult {\n memories: typeof memoryTable.$inferSelect;\n embeddings: typeof embeddingTable.$inferSelect;\n }\n const joinedResult = existingMemory[0] as JoinedMemoryResult;\n Object.entries(DIMENSION_MAP).find(([_, colName]) => {\n const embeddingCol = colName as keyof typeof embeddingTable.$inferSelect;\n return joinedResult.embeddings[embeddingCol] !== null;\n });\n // We don't actually need to use usedDimension for now, but it's good to know it's there.\n }\n\n const resolvedDimension = DIMENSION_MAP[dimension as keyof typeof DIMENSION_MAP];\n if (!resolvedDimension) {\n const fallbackDimension = this.embeddingDimension ?? DIMENSION_MAP[384];\n this.embeddingDimension = fallbackDimension;\n logger.warn(\n {\n src: \"plugin:sql\",\n requestedDimension: dimension,\n fallbackDimension,\n },\n \"Unsupported embedding dimension requested; keeping fallback embedding column\"\n );\n return;\n }\n\n this.embeddingDimension = resolvedDimension;\n });\n }\n\n /**\n * Asynchronously retrieves an agent by their ID from the database.\n * @param {UUID} agentId - The ID of the agent to retrieve.\n * @returns {Promise<Agent | null>} A promise that resolves to the retrieved agent or null if not found.\n */\n async getAgent(agentId: UUID): Promise<Agent | null> {\n return this.withDatabase(async () => {\n const rows = await this.db\n .select()\n .from(agentTable)\n .where(eq(agentTable.id, agentId))\n .limit(1);\n\n if (rows.length === 0) return null;\n\n const row = rows[0];\n const bioValue = !row.bio ? \"\" : Array.isArray(row.bio) ? row.bio : row.bio;\n return {\n ...row,\n username: row.username || \"\",\n id: row.id as UUID,\n system: !row.system ? undefined : row.system,\n bio: bioValue as string | string[],\n createdAt: row.createdAt.getTime(),\n updatedAt: row.updatedAt.getTime(),\n } as unknown as Agent;\n });\n }\n\n /**\n * Asynchronously retrieves a list of agents from the database.\n *\n * @returns {Promise<Partial<Agent>[]>} A Promise that resolves to an array of Agent objects.\n */\n async getAgents(): Promise<Partial<Agent>[]> {\n const result = await this.withDatabase(async () => {\n const rows = await this.db\n .select({\n id: agentTable.id,\n name: agentTable.name,\n bio: agentTable.bio,\n })\n .from(agentTable);\n return rows.map(\n (row) =>\n ({\n ...row,\n id: row.id as UUID,\n bio: (row.bio === null ? \"\" : Array.isArray(row.bio) ? row.bio : row.bio) as\n | string\n | string[],\n }) as Partial<Agent>\n );\n });\n // Guard against null return\n return result || [];\n }\n /**\n * Asynchronously creates a new agent record in the database.\n *\n * @param {Partial<Agent>} agent The agent object to be created.\n * @returns {Promise<boolean>} A promise that resolves to a boolean indicating the success of the operation.\n */\n async createAgent(agent: Agent): Promise<boolean> {\n const _isDuplicateKeyError = (error: unknown): boolean => {\n if (!error || typeof error !== \"object\") return false;\n\n const maybeError = error as { code?: unknown; message?: unknown };\n if (maybeError.code === \"23505\") return true;\n\n if (typeof maybeError.message === \"string\") {\n return /duplicate key|already exists/i.test(maybeError.message);\n }\n\n return false;\n };\n\n return this.withDatabase(async () => {\n try {\n // Check for existing agent with the same ID only (names can be duplicated)\n if (agent.id) {\n const existing = await this.db\n .select({ id: agentTable.id })\n .from(agentTable)\n .where(eq(agentTable.id, agent.id))\n .limit(1);\n\n if (existing.length > 0) {\n logger.warn(\n { src: \"plugin:sql\", agentId: agent.id },\n \"Attempted to create agent with duplicate ID\"\n );\n return false;\n }\n }\n\n await this.db.transaction(async (tx) => {\n const agentData = {\n ...agent,\n createdAt: new Date(\n typeof agent.createdAt === \"bigint\"\n ? Number(agent.createdAt)\n : agent.createdAt || Date.now()\n ),\n updatedAt: new Date(\n typeof agent.updatedAt === \"bigint\"\n ? Number(agent.updatedAt)\n : agent.updatedAt || Date.now()\n ),\n };\n const sanitizedAgentData = Object.fromEntries(\n Object.entries(agentData).filter(([, value]) => value !== undefined)\n ) as typeof agentData;\n\n await tx\n .insert(agentTable)\n .values(sanitizedAgentData as unknown as typeof agentTable.$inferInsert);\n });\n\n return true;\n } catch (error) {\n if (_isDuplicateKeyError(error)) {\n logger.warn(\n { src: \"plugin:sql\", agentId: agent.id },\n \"Attempted to create agent with duplicate ID\"\n );\n return false;\n }\n\n logger.error(\n {\n src: \"plugin:sql\",\n agentId: agent.id,\n error: error instanceof Error ? error.message : String(error),\n },\n \"Failed to create agent\"\n );\n throw error;\n }\n });\n }\n\n /**\n * Updates an agent in the database with the provided agent ID and data.\n * @param {UUID} agentId - The unique identifier of the agent to update.\n * @param {Partial<Agent>} agent - The partial agent object containing the fields to update.\n * @returns {Promise<boolean>} - A boolean indicating if the agent was successfully updated.\n */\n async updateAgent(agentId: UUID, agent: Partial<Agent>): Promise<boolean> {\n return this.withDatabase(async () => {\n try {\n if (!agentId) {\n throw new Error(\"Agent ID is required for update\");\n }\n\n await this.db.transaction(async (tx) => {\n // Handle settings update if present\n if (agent?.settings) {\n agent.settings = await this.mergeAgentSettings(tx, agentId, agent.settings);\n }\n\n // Convert numeric timestamps to Date objects for database storage\n // The Agent interface uses numbers, but the database schema expects Date objects\n const updateData: Record<string, unknown> = { ...agent };\n\n if (updateData.createdAt) {\n if (typeof updateData.createdAt === \"number\") {\n updateData.createdAt = new Date(updateData.createdAt);\n } else {\n delete updateData.createdAt; // Don't update createdAt if it's not a valid timestamp\n }\n }\n if (updateData.updatedAt) {\n if (typeof updateData.updatedAt === \"number\") {\n updateData.updatedAt = new Date(updateData.updatedAt);\n } else {\n updateData.updatedAt = new Date(); // Use current time if invalid\n }\n } else {\n updateData.updatedAt = new Date(); // Always set updatedAt to current time\n }\n\n await tx.update(agentTable).set(updateData).where(eq(agentTable.id, agentId));\n });\n\n return true;\n } catch (error) {\n logger.error(\n {\n src: \"plugin:sql\",\n agentId,\n error: error instanceof Error ? error.message : String(error),\n },\n \"Failed to update agent\"\n );\n return false;\n }\n });\n }\n\n /**\n * Merges updated agent settings with existing settings in the database,\n * with special handling for nested objects like secrets.\n * @param tx - The database transaction\n * @param agentId - The ID of the agent\n * @param updatedSettings - The settings object with updates\n * @returns The merged settings object\n * @private\n */\n private async mergeAgentSettings<T extends Record<string, unknown>>(\n tx: DrizzleDatabase,\n agentId: UUID,\n updatedSettings: T\n ): Promise<T> {\n // First get the current agent data\n const currentAgent = await tx\n .select({ settings: agentTable.settings })\n .from(agentTable)\n .where(eq(agentTable.id, agentId))\n .limit(1);\n\n const currentSettings =\n currentAgent.length > 0 && currentAgent[0].settings ? currentAgent[0].settings : {};\n\n const deepMerge = (\n target: Record<string, unknown> | unknown,\n source: Record<string, unknown>\n ): Record<string, unknown> | undefined => {\n // If source is explicitly null, it means the intention is to set this entire branch to null (or delete if top-level handled by caller).\n // For recursive calls, if a sub-object in source is null, it effectively means \"remove this sub-object from target\".\n // However, our primary deletion signal is a *property value* being null within an object.\n if (source === null) {\n // If the entire source for a given key is null, we treat it as \"delete this key from target\"\n // by returning undefined, which the caller can use to delete the key.\n return undefined;\n }\n\n // If source is an array or a primitive, it replaces the target value.\n if (Array.isArray(source) || typeof source !== \"object\") {\n return source;\n }\n\n // Initialize output. If target is not an object, start with an empty one to merge source into.\n const output =\n typeof target === \"object\" && target !== null && !Array.isArray(target)\n ? { ...target }\n : {};\n\n for (const key of Object.keys(source)) {\n // Iterate over source keys\n const sourceValue = source[key];\n\n if (sourceValue === null) {\n // If a value in source is null, delete the corresponding key from output.\n delete output[key];\n } else if (typeof sourceValue === \"object\" && !Array.isArray(sourceValue)) {\n // If value is an object, recurse.\n const nestedMergeResult = deepMerge(output[key], sourceValue as Record<string, unknown>);\n if (nestedMergeResult === undefined) {\n // If recursive merge resulted in undefined (meaning the nested object should be deleted)\n delete output[key];\n } else {\n output[key] = nestedMergeResult;\n }\n } else {\n // Primitive or array value from source, assign it.\n output[key] = sourceValue;\n }\n }\n\n // After processing all keys from source, check if output became empty.\n // An object is empty if all its keys were deleted or resulted in undefined.\n // This is a more direct check than iterating 'output' after building it.\n if (Object.keys(output).length === 0) {\n // If the source itself was not an explicitly empty object,\n // and the merge resulted in an empty object, signal deletion.\n if (!(typeof source === \"object\" && source !== null && Object.keys(source).length === 0)) {\n return undefined; // Signal to delete this (parent) key if it became empty.\n }\n }\n\n return output;\n }; // End of deepMerge\n\n const finalSettings = deepMerge(currentSettings, updatedSettings);\n // If the entire settings object becomes undefined (e.g. all keys removed),\n // return an empty object instead of undefined/null to keep the settings field present.\n return (finalSettings ?? {}) as T;\n }\n\n /**\n * Asynchronously deletes an agent with the specified UUID and all related entries.\n *\n * @param {UUID} agentId - The UUID of the agent to be deleted.\n * @returns {Promise<boolean>} - A boolean indicating if the deletion was successful.\n */\n async deleteAgent(agentId: UUID): Promise<boolean> {\n return this.withDatabase(async () => {\n try {\n // Simply delete the agent - all related data will be cascade deleted\n const result = await this.db\n .delete(agentTable)\n .where(eq(agentTable.id, agentId))\n .returning();\n\n if (result.length === 0) {\n logger.warn({ src: \"plugin:sql\", agentId }, \"Agent not found for deletion\");\n return false;\n }\n\n return true;\n } catch (error) {\n logger.error(\n {\n src: \"plugin:sql\",\n agentId,\n error: error instanceof Error ? error.message : String(error),\n },\n \"Failed to delete agent\"\n );\n throw error;\n }\n });\n }\n\n /**\n * Count all agents in the database\n * Used primarily for maintenance and cleanup operations\n */\n /**\n * Asynchronously counts the number of agents in the database.\n * @returns {Promise<number>} A Promise that resolves to the number of agents in the database.\n */\n async countAgents(): Promise<number> {\n return this.withDatabase(async () => {\n try {\n const result = await this.db.select({ count: count() }).from(agentTable);\n\n const result0 = result[0];\n return result0?.count || 0;\n } catch (error) {\n logger.error(\n {\n src: \"plugin:sql\",\n error: error instanceof Error ? error.message : String(error),\n },\n \"Failed to count agents\"\n );\n return 0;\n }\n });\n }\n\n /**\n * Clean up the agents table by removing all agents\n * This is used during server startup to ensure no orphaned agents exist\n * from previous crashes or improper shutdowns\n */\n async cleanupAgents(): Promise<void> {\n return this.withDatabase(async () => {\n try {\n await this.db.delete(agentTable);\n } catch (error) {\n logger.error(\n {\n src: \"plugin:sql\",\n error: error instanceof Error ? error.message : String(error),\n },\n \"Failed to clean up agent table\"\n );\n throw error;\n }\n });\n }\n\n /**\n * Asynchronously retrieves an entity and its components by entity IDs.\n * @param {UUID[]} entityIds - The unique identifiers of the entities to retrieve.\n * @returns {Promise<Entity[] | null>} A Promise that resolves to the entity with its components if found, null otherwise.\n */\n async getEntitiesByIds(entityIds: UUID[]): Promise<Entity[] | null> {\n return this.withDatabase(async () => {\n const result = await this.db\n .select({\n entity: entityTable,\n components: componentTable,\n })\n .from(entityTable)\n .leftJoin(componentTable, eq(componentTable.entityId, entityTable.id))\n .where(inArray(entityTable.id, entityIds));\n\n if (result.length === 0) return [];\n\n // Group components by entity\n const entities: Record<UUID, Entity> = {};\n const entityComponents: Record<UUID, Entity[\"components\"]> = {};\n for (const e of result) {\n const key = e.entity.id;\n entities[key] = e.entity;\n if (entityComponents[key] === undefined) entityComponents[key] = [];\n if (e.components) {\n // Handle both single component and array of components\n const componentsArray = Array.isArray(e.components) ? e.components : [e.components];\n entityComponents[key] = [...entityComponents[key], ...componentsArray];\n }\n }\n for (const k of Object.keys(entityComponents)) {\n entities[k].components = entityComponents[k];\n }\n\n return Object.values(entities);\n });\n }\n\n /**\n * Asynchronously retrieves all entities for a given room, optionally including their components.\n * @param {UUID} roomId - The unique identifier of the room to get entities for\n * @param {boolean} [includeComponents] - Whether to include component data for each entity\n * @returns {Promise<Entity[]>} A Promise that resolves to an array of entities in the room\n */\n async getEntitiesForRoom(roomId: UUID, includeComponents?: boolean): Promise<Entity[]> {\n return this.withDatabase(async () => {\n const query = this.db\n .select({\n entity: entityTable,\n ...(includeComponents && { components: componentTable }),\n })\n .from(participantTable)\n .leftJoin(\n entityTable,\n and(eq(participantTable.entityId, entityTable.id), eq(entityTable.agentId, this.agentId))\n );\n\n if (includeComponents) {\n query.leftJoin(componentTable, eq(componentTable.entityId, entityTable.id));\n }\n\n const result = await query.where(eq(participantTable.roomId, roomId));\n\n // Group components by entity if includeComponents is true\n const entitiesByIdMap = new Map<UUID, Entity>();\n\n for (const row of result) {\n if (!row.entity) continue;\n\n const entityId = row.entity.id as UUID;\n if (!entitiesByIdMap.has(entityId)) {\n const entity: Entity = {\n ...row.entity,\n id: entityId,\n agentId: row.entity.agentId as UUID,\n metadata: (row.entity.metadata || {}) as Metadata,\n components: includeComponents ? [] : undefined,\n };\n entitiesByIdMap.set(entityId, entity);\n }\n\n if (includeComponents && row.components) {\n const entity = entitiesByIdMap.get(entityId);\n if (entity) {\n if (!entity.components) {\n entity.components = [];\n }\n entity.components.push(row.components);\n }\n }\n }\n\n return Array.from(entitiesByIdMap.values());\n });\n }\n\n /**\n * Asynchronously creates new entities in the database.\n * @param {Entity[]} entities - The entity objects to be created.\n * @returns {Promise<boolean>} A Promise that resolves to a boolean indicating the success of the operation.\n */\n async createEntities(entities: Entity[]): Promise<boolean> {\n return this.withDatabase(async () => {\n try {\n return await this.db.transaction(async (tx) => {\n // Normalize entity data to ensure names is a proper array\n const normalizedEntities = entities.map((entity) => {\n const { names, metadata, ...normalizedEntity } = entity as Entity & {\n names?: unknown;\n metadata?: Metadata;\n };\n\n return {\n ...normalizedEntity,\n agentId: this.agentId,\n names: this.normalizeEntityNames(names),\n metadata: metadata || {},\n };\n });\n\n await tx.insert(entityTable).values(normalizedEntities);\n\n return true;\n });\n } catch (error) {\n logger.error(\n {\n src: \"plugin:sql\",\n entityId: entities[0]?.id,\n error: error instanceof Error ? error.message : String(error),\n },\n \"Failed to create entities\"\n );\n return false;\n }\n });\n }\n\n /**\n * Asynchronously ensures an entity exists, creating it if it doesn't\n * @param entity The entity to ensure exists\n * @returns Promise resolving to boolean indicating success\n */\n protected async ensureEntityExists(entity: Entity): Promise<boolean> {\n if (!entity.id) {\n logger.error({ src: \"plugin:sql\" }, \"Entity ID is required for ensureEntityExists\");\n return false;\n }\n\n try {\n const existingEntities = await this.getEntitiesByIds([entity.id]);\n\n if (!existingEntities || !existingEntities.length) {\n return await this.createEntities([entity]);\n }\n\n return true;\n } catch (error) {\n logger.error(\n {\n src: \"plugin:sql\",\n entityId: entity.id,\n error: error instanceof Error ? error.message : String(error),\n },\n \"Failed to ensure entity exists\"\n );\n return false;\n }\n }\n\n /**\n * Asynchronously updates an entity in the database.\n * @param {Entity} entity - The entity object to be updated.\n * @returns {Promise<void>} A Promise that resolves when the entity is updated.\n */\n async updateEntity(entity: Entity): Promise<void> {\n if (!entity.id) {\n throw new Error(\"Entity ID is required for update\");\n }\n return this.withDatabase(async () => {\n // Normalize entity data to ensure names is a proper array\n const normalizedEntity = {\n ...entity,\n agentId: this.agentId,\n names: this.normalizeEntityNames(entity.names),\n metadata: entity.metadata || {},\n };\n\n await this.db\n .update(entityTable)\n .set(normalizedEntity)\n .where(eq(entityTable.id, entity.id as string));\n });\n }\n\n /**\n * Asynchronously deletes an entity from the database based on the provided ID.\n * @param {UUID} entityId - The ID of the entity to delete.\n * @returns {Promise<void>} A Promise that resolves when the entity is deleted.\n */\n async deleteEntity(entityId: UUID): Promise<void> {\n return this.withDatabase(async () => {\n await this.db.transaction(async (tx) => {\n // Delete related components first\n await tx\n .delete(componentTable)\n .where(\n or(eq(componentTable.entityId, entityId), eq(componentTable.sourceEntityId, entityId))\n );\n\n // Delete the entity\n await tx.delete(entityTable).where(eq(entityTable.id, entityId));\n });\n });\n }\n\n /**\n * Asynchronously retrieves entities by their names and agentId.\n * @param {Object} params - The parameters for retrieving entities.\n * @param {string[]} params.names - The names to search for.\n * @param {UUID} params.agentId - The agent ID to filter by.\n * @returns {Promise<Entity[]>} A Promise that resolves to an array of entities.\n */\n async getEntitiesByNames(params: { names: string[]; agentId: UUID }): Promise<Entity[]> {\n return this.withDatabase(async () => {\n const { names, agentId } = params;\n\n // Build a condition to match any of the names\n const nameConditions = names.map((name) => sql`${name} = ANY(${entityTable.names})`);\n\n const query = sql`\n SELECT * FROM ${entityTable}\n WHERE ${entityTable.agentId} = ${agentId}\n AND (${sql.join(nameConditions, sql` OR `)})\n `;\n\n const result = await this.db.execute(query);\n\n return result.rows.map((row: Record<string, unknown>) => ({\n id: row.id as UUID,\n agentId: row.agentId as UUID,\n names: (row.names || []) as string[],\n metadata: (row.metadata || {}) as Metadata,\n }));\n });\n }\n\n /**\n * Asynchronously searches for entities by name with fuzzy matching.\n * @param {Object} params - The parameters for searching entities.\n * @param {string} params.query - The search query.\n * @param {UUID} params.agentId - The agent ID to filter by.\n * @param {number} params.limit - The maximum number of results to return.\n * @returns {Promise<Entity[]>} A Promise that resolves to an array of entities.\n */\n async searchEntitiesByName(params: {\n query: string;\n agentId: UUID;\n limit?: number;\n }): Promise<Entity[]> {\n return this.withDatabase(async () => {\n const { query, agentId, limit = 10 } = params;\n\n // If query is empty, return all entities up to limit\n if (!query || query.trim() === \"\") {\n const result = await this.db\n .select()\n .from(entityTable)\n .where(eq(entityTable.agentId, agentId))\n .limit(limit);\n\n return result.map((row: Record<string, unknown>) => ({\n id: row.id as UUID,\n agentId: row.agentId as UUID,\n names: (row.names || []) as string[],\n metadata: (row.metadata || {}) as Metadata,\n }));\n }\n\n // Otherwise, search for entities with names containing the query (case-insensitive)\n const searchQuery = sql`\n SELECT * FROM ${entityTable}\n WHERE ${entityTable.agentId} = ${agentId}\n AND EXISTS (\n SELECT 1 FROM unnest(${entityTable.names}) AS name\n WHERE LOWER(name) LIKE LOWER(${`%${query}%`})\n )\n LIMIT ${limit}\n `;\n\n const result = await this.db.execute(searchQuery);\n\n return result.rows.map((row: Record<string, unknown>) => ({\n id: row.id as UUID,\n agentId: row.agentId as UUID,\n names: (row.names || []) as string[],\n metadata: (row.metadata || {}) as Metadata,\n }));\n });\n }\n\n async getComponent(\n entityId: UUID,\n type: string,\n worldId?: UUID,\n sourceEntityId?: UUID\n ): Promise<Component | null> {\n return this.withDatabase(async () => {\n const conditions = [eq(componentTable.entityId, entityId), eq(componentTable.type, type)];\n\n if (worldId) {\n conditions.push(eq(componentTable.worldId, worldId));\n }\n\n if (sourceEntityId) {\n conditions.push(eq(componentTable.sourceEntityId, sourceEntityId));\n }\n\n const result = await this.db\n .select()\n .from(componentTable)\n .where(and(...conditions));\n\n if (result.length === 0) return null;\n\n const component = result[0];\n\n return {\n ...component,\n id: component.id as UUID,\n entityId: component.entityId as UUID,\n agentId: component.agentId as UUID,\n roomId: component.roomId as UUID,\n worldId: (component.worldId ?? \"\") as UUID,\n sourceEntityId: (component.sourceEntityId ?? \"\") as UUID,\n data: component.data as Metadata,\n createdAt: component.createdAt.getTime(),\n };\n });\n }\n\n /**\n * Asynchronously retrieves all components for a given entity, optionally filtered by world and source entity.\n * @param {UUID} entityId - The unique identifier of the entity to retrieve components for\n * @param {UUID} [worldId] - Optional world ID to filter components by\n * @param {UUID} [sourceEntityId] - Optional source entity ID to filter components by\n * @returns {Promise<Component[]>} A Promise that resolves to an array of components\n */\n async getComponents(entityId: UUID, worldId?: UUID, sourceEntityId?: UUID): Promise<Component[]> {\n return this.withDatabase(async () => {\n const conditions = [eq(componentTable.entityId, entityId)];\n\n if (worldId) {\n conditions.push(eq(componentTable.worldId, worldId));\n }\n\n if (sourceEntityId) {\n conditions.push(eq(componentTable.sourceEntityId, sourceEntityId));\n }\n\n const result = await this.db\n .select({\n id: componentTable.id,\n entityId: componentTable.entityId,\n type: componentTable.type,\n data: componentTable.data,\n worldId: componentTable.worldId,\n agentId: componentTable.agentId,\n roomId: componentTable.roomId,\n sourceEntityId: componentTable.sourceEntityId,\n createdAt: componentTable.createdAt,\n })\n .from(componentTable)\n .where(and(...conditions));\n\n if (result.length === 0) return [];\n\n const components = result.map((component) => ({\n ...component,\n id: component.id as UUID,\n entityId: component.entityId as UUID,\n agentId: component.agentId as UUID,\n roomId: component.roomId as UUID,\n worldId: (component.worldId ?? \"\") as UUID,\n sourceEntityId: (component.sourceEntityId ?? \"\") as UUID,\n data: component.data as Metadata,\n createdAt: component.createdAt.getTime(),\n }));\n\n return components;\n });\n }\n\n /**\n * Asynchronously creates a new component in the database.\n * @param {Component} component - The component object to be created.\n * @returns {Promise<boolean>} A Promise that resolves to a boolean indicating the success of the operation.\n */\n async createComponent(component: Component): Promise<boolean> {\n return this.withDatabase(async () => {\n await this.db.insert(componentTable).values({\n ...component,\n createdAt: new Date(),\n });\n return true;\n });\n }\n\n /**\n * Asynchronously updates an existing component in the database.\n * @param {Component} component - The component object to be updated.\n * @returns {Promise<void>} A Promise that resolves when the component is updated.\n */\n async updateComponent(component: Component): Promise<void> {\n return this.withDatabase(async () => {\n try {\n // Convert createdAt from number to Date for database compatibility\n const { createdAt, ...rest } = component;\n await this.db\n .update(componentTable)\n .set({\n ...rest,\n createdAt: new Date(createdAt),\n })\n .where(eq(componentTable.id, component.id));\n } catch (e) {\n console.error(\"updateComponent error\", e);\n }\n });\n }\n\n /**\n * Asynchronously deletes a component from the database.\n * @param {UUID} componentId - The unique identifier of the component to delete.\n * @returns {Promise<void>} A Promise that resolves when the component is deleted.\n */\n async deleteComponent(componentId: UUID): Promise<void> {\n return this.withDatabase(async () => {\n await this.db.delete(componentTable).where(eq(componentTable.id, componentId));\n });\n }\n\n /**\n * Asynchronously retrieves memories from the database based on the provided parameters.\n * @param {Object} params - The parameters for retrieving memories.\n * @param {UUID} params.roomId - The ID of the room to retrieve memories for.\n * @param {number} [params.count] - The maximum number of memories to retrieve.\n * @param {number} [params.offset] - The offset for pagination.\n * @param {boolean} [params.unique] - Whether to retrieve unique memories only.\n * @param {string} [params.tableName] - The name of the table to retrieve memories from.\n * @param {number} [params.start] - The start date to retrieve memories from.\n * @param {number} [params.end] - The end date to retrieve memories from.\n * @returns {Promise<Memory[]>} A Promise that resolves to an array of memories.\n */\n async getMemories(params: {\n entityId?: UUID;\n agentId?: UUID;\n count?: number;\n offset?: number;\n unique?: boolean;\n tableName: string;\n start?: number;\n end?: number;\n roomId?: UUID;\n worldId?: UUID;\n }): Promise<Memory[]> {\n const { entityId, agentId, roomId, worldId, tableName, unique, start, end, offset } = params;\n\n if (!tableName) throw new Error(\"tableName is required\");\n if (offset !== undefined && offset < 0) {\n throw new Error(\"offset must be a non-negative number\");\n }\n\n return this.withEntityContext(entityId ?? null, async (tx) => {\n const conditions = [eq(memoryTable.type, tableName)];\n\n if (start !== undefined) {\n conditions.push(gte(memoryTable.createdAt, new Date(start)));\n }\n\n // RLS handles access control - no explicit entityId filter needed\n\n if (roomId) {\n conditions.push(eq(memoryTable.roomId, roomId));\n }\n\n // Add worldId condition\n if (worldId) {\n conditions.push(eq(memoryTable.worldId, worldId));\n }\n\n if (end !== undefined) {\n conditions.push(lte(memoryTable.createdAt, new Date(end)));\n }\n\n if (unique) {\n conditions.push(eq(memoryTable.unique, true));\n }\n\n if (agentId) {\n conditions.push(eq(memoryTable.agentId, agentId));\n }\n\n const baseQuery = tx\n .select({\n memory: {\n id: memoryTable.id,\n type: memoryTable.type,\n createdAt: memoryTable.createdAt,\n content: memoryTable.content,\n entityId: memoryTable.entityId,\n agentId: memoryTable.agentId,\n roomId: memoryTable.roomId,\n unique: memoryTable.unique,\n metadata: memoryTable.metadata,\n },\n embedding: embeddingTable[this.embeddingDimension],\n })\n .from(memoryTable)\n .leftJoin(embeddingTable, eq(embeddingTable.memoryId, memoryTable.id))\n .where(and(...conditions))\n .orderBy(desc(memoryTable.createdAt), desc(memoryTable.id));\n\n // Apply limit and offset for pagination\n // Build query conditionally to maintain proper types\n const rows = await (async () => {\n if (params.count && offset !== undefined && offset > 0) {\n return baseQuery.limit(params.count).offset(offset);\n } else if (params.count) {\n return baseQuery.limit(params.count);\n } else if (offset !== undefined && offset > 0) {\n return baseQuery.offset(offset);\n } else {\n return baseQuery;\n }\n })();\n\n return rows.map((row) => ({\n id: row.memory.id as UUID,\n type: row.memory.type,\n createdAt: row.memory.createdAt.getTime(),\n content:\n typeof row.memory.content === \"string\"\n ? JSON.parse(row.memory.content)\n : row.memory.content,\n entityId: row.memory.entityId as UUID,\n agentId: row.memory.agentId as UUID,\n roomId: row.memory.roomId as UUID,\n unique: row.memory.unique,\n metadata: row.memory.metadata as MemoryMetadata,\n embedding: row.embedding ? Array.from(row.embedding) : undefined,\n }));\n });\n }\n\n /**\n * Asynchronously retrieves memories from the database based on the provided parameters.\n * @param {Object} params - The parameters for retrieving memories.\n * @param {UUID[]} params.roomIds - The IDs of the rooms to retrieve memories for.\n * @param {string} params.tableName - The name of the table to retrieve memories from.\n * @param {number} [params.limit] - The maximum number of memories to retrieve.\n * @returns {Promise<Memory[]>} A Promise that resolves to an array of memories.\n */\n async getMemoriesByRoomIds(params: {\n roomIds: UUID[];\n tableName: string;\n limit?: number;\n }): Promise<Memory[]> {\n return this.withDatabase(async () => {\n if (params.roomIds.length === 0) return [];\n\n const conditions = [\n eq(memoryTable.type, params.tableName),\n inArray(memoryTable.roomId, params.roomIds),\n ];\n\n conditions.push(eq(memoryTable.agentId, this.agentId));\n\n const query = this.db\n .select({\n id: memoryTable.id,\n type: memoryTable.type,\n createdAt: memoryTable.createdAt,\n content: memoryTable.content,\n entityId: memoryTable.entityId,\n agentId: memoryTable.agentId,\n roomId: memoryTable.roomId,\n unique: memoryTable.unique,\n metadata: memoryTable.metadata,\n })\n .from(memoryTable)\n .where(and(...conditions))\n .orderBy(desc(memoryTable.createdAt));\n\n const rows = params.limit ? await query.limit(params.limit) : await query;\n\n return rows.map((row) => ({\n id: row.id as UUID,\n createdAt: row.createdAt.getTime(),\n content: typeof row.content === \"string\" ? JSON.parse(row.content) : row.content,\n entityId: row.entityId as UUID,\n agentId: row.agentId as UUID,\n roomId: row.roomId as UUID,\n unique: row.unique,\n metadata: row.metadata,\n })) as Memory[];\n });\n }\n\n /**\n * Asynchronously retrieves a memory by its unique identifier.\n * @param {UUID} id - The unique identifier of the memory to retrieve.\n * @returns {Promise<Memory | null>} A Promise that resolves to the memory if found, null otherwise.\n */\n async getMemoryById(id: UUID): Promise<Memory | null> {\n return this.withDatabase(async () => {\n const result = await this.db\n .select({\n memory: memoryTable,\n embedding: embeddingTable[this.embeddingDimension],\n })\n .from(memoryTable)\n .leftJoin(embeddingTable, eq(memoryTable.id, embeddingTable.memoryId))\n .where(eq(memoryTable.id, id))\n .limit(1);\n\n if (result.length === 0) return null;\n\n const row = result[0];\n return {\n id: row.memory.id as UUID,\n createdAt: row.memory.createdAt.getTime(),\n content:\n typeof row.memory.content === \"string\"\n ? JSON.parse(row.memory.content)\n : row.memory.content,\n entityId: row.memory.entityId as UUID,\n agentId: row.memory.agentId as UUID,\n roomId: row.memory.roomId as UUID,\n unique: row.memory.unique,\n metadata: row.memory.metadata as MemoryMetadata,\n embedding: row.embedding ?? undefined,\n };\n });\n }\n\n /**\n * Asynchronously retrieves memories from the database based on the provided parameters.\n * @param {Object} params - The parameters for retrieving memories.\n * @param {UUID[]} params.memoryIds - The IDs of the memories to retrieve.\n * @param {string} [params.tableName] - The name of the table to retrieve memories from.\n * @returns {Promise<Memory[]>} A Promise that resolves to an array of memories.\n */\n async getMemoriesByIds(memoryIds: UUID[], tableName?: string): Promise<Memory[]> {\n return this.withDatabase(async () => {\n if (memoryIds.length === 0) return [];\n\n const conditions = [inArray(memoryTable.id, memoryIds)];\n\n if (tableName) {\n conditions.push(eq(memoryTable.type, tableName));\n }\n\n const rows = await this.db\n .select({\n memory: memoryTable,\n embedding: embeddingTable[this.embeddingDimension],\n })\n .from(memoryTable)\n .leftJoin(embeddingTable, eq(embeddingTable.memoryId, memoryTable.id))\n .where(and(...conditions))\n .orderBy(desc(memoryTable.createdAt));\n\n return rows.map((row) => ({\n id: row.memory.id as UUID,\n createdAt: row.memory.createdAt.getTime(),\n content:\n typeof row.memory.content === \"string\"\n ? JSON.parse(row.memory.content)\n : row.memory.content,\n entityId: row.memory.entityId as UUID,\n agentId: row.memory.agentId as UUID,\n roomId: row.memory.roomId as UUID,\n unique: row.memory.unique,\n metadata: row.memory.metadata as MemoryMetadata,\n embedding: row.embedding ?? undefined,\n }));\n });\n }\n\n /**\n * Asynchronously retrieves cached embeddings from the database based on the provided parameters.\n * @param {Object} opts - The parameters for retrieving cached embeddings.\n * @param {string} opts.query_table_name - The name of the table to retrieve embeddings from.\n * @param {number} opts.query_threshold - The threshold for the levenshtein distance.\n * @param {string} opts.query_input - The input string to search for.\n * @param {string} opts.query_field_name - The name of the field to retrieve embeddings from.\n * @param {string} opts.query_field_sub_name - The name of the sub-field to retrieve embeddings from.\n * @param {number} opts.query_match_count - The maximum number of matches to retrieve.\n * @returns {Promise<{ embedding: number[]; levenshtein_score: number }[]>} A Promise that resolves to an array of cached embeddings.\n */\n async getCachedEmbeddings(opts: {\n query_table_name: string;\n query_threshold: number;\n query_input: string;\n query_field_name: string;\n query_field_sub_name: string;\n query_match_count: number;\n }): Promise<{ embedding: number[]; levenshtein_score: number }[]> {\n return this.withDatabase(async () => {\n try {\n // Drizzle database has execute method for raw SQL\n interface DrizzleDatabaseWithExecute {\n execute: (query: ReturnType<typeof sql>) => Promise<{ rows: Record<string, unknown>[] }>;\n }\n const results = await (this.db as DrizzleDatabaseWithExecute).execute(sql`\n WITH content_text AS (\n SELECT\n m.id,\n COALESCE(\n m.content->>${opts.query_field_sub_name},\n ''\n ) as content_text\n FROM memories m\n WHERE m.type = ${opts.query_table_name}\n AND m.content->>${opts.query_field_sub_name} IS NOT NULL\n ),\n embedded_text AS (\n SELECT\n ct.content_text,\n COALESCE(\n e.dim_384,\n e.dim_512,\n e.dim_768,\n e.dim_1024,\n e.dim_1536,\n e.dim_3072\n ) as embedding\n FROM content_text ct\n LEFT JOIN embeddings e ON e.memory_id = ct.id\n WHERE e.memory_id IS NOT NULL\n )\n SELECT\n embedding,\n levenshtein(${opts.query_input}, content_text) as levenshtein_score\n FROM embedded_text\n WHERE levenshtein(${opts.query_input}, content_text) <= ${opts.query_threshold}\n ORDER BY levenshtein_score\n LIMIT ${opts.query_match_count}\n `);\n\n return results.rows\n .map((row) => ({\n embedding: Array.isArray(row.embedding)\n ? row.embedding\n : typeof row.embedding === \"string\"\n ? JSON.parse(row.embedding)\n : [],\n levenshtein_score: Number(row.levenshtein_score),\n }))\n .filter((row) => Array.isArray(row.embedding));\n } catch (error) {\n logger.error(\n {\n src: \"plugin:sql\",\n tableName: opts.query_table_name,\n fieldName: opts.query_field_name,\n error: error instanceof Error ? error.message : String(error),\n },\n \"Failed to get cached embeddings\"\n );\n if (\n error instanceof Error &&\n error.message === \"levenshtein argument exceeds maximum length of 255 characters\"\n ) {\n return [];\n }\n throw error;\n }\n });\n }\n\n /**\n * Asynchronously logs an event in the database.\n * @param {Object} params - The parameters for logging an event.\n * @param {Object} params.body - The body of the event to log.\n * @param {UUID} params.entityId - The ID of the entity associated with the event.\n * @param {UUID} params.roomId - The ID of the room associated with the event.\n * @param {string} params.type - The type of the event to log.\n * @returns {Promise<void>} A Promise that resolves when the event is logged.\n */\n async log(params: {\n body: { [key: string]: unknown };\n entityId: UUID;\n roomId: UUID;\n type: string;\n }): Promise<void> {\n return this.withDatabase(async () => {\n try {\n // Sanitize JSON body to prevent Unicode escape sequence errors\n const sanitizedBody = this.sanitizeJsonObject(params.body);\n\n // Serialize to JSON string first for an additional layer of protection\n // This ensures any problematic characters are properly escaped during JSON serialization\n const jsonString = JSON.stringify(sanitizedBody);\n\n // Use withEntityContext to set Entity RLS context before inserting\n // This ensures the log entry passes STRICT Entity RLS policy\n await this.withEntityContext(params.entityId, async (tx) => {\n await tx.insert(logTable).values({\n body: sql`${jsonString}::jsonb`,\n entityId: params.entityId,\n roomId: params.roomId,\n type: params.type,\n });\n });\n } catch (error) {\n logger.error(\n {\n src: \"plugin:sql\",\n type: params.type,\n roomId: params.roomId,\n entityId: params.entityId,\n error: error instanceof Error ? error.message : String(error),\n },\n \"Failed to create log entry\"\n );\n throw error;\n }\n });\n }\n\n /**\n * Sanitizes a JSON object by replacing problematic Unicode escape sequences\n * that could cause errors during JSON serialization/storage\n *\n * @param value - The value to sanitize\n * @returns The sanitized value\n */\n private sanitizeJsonObject(value: unknown, seen: WeakSet<object> = new WeakSet()): unknown {\n if (value === null || value === undefined) {\n return value;\n }\n\n if (typeof value === \"string\") {\n // Handle multiple cases that can cause PostgreSQL/PgLite JSON parsing errors:\n // 1. Remove null bytes (U+0000) which are not allowed in PostgreSQL text fields\n // 2. Escape single backslashes that might be interpreted as escape sequences\n // 3. Fix broken Unicode escape sequences (\\u not followed by 4 hex digits)\n const nullChar = String.fromCharCode(0);\n const nullCharRegex = new RegExp(nullChar, \"g\");\n return value\n .replace(nullCharRegex, \"\") // Remove null bytes\n .replace(/\\\\(?![\"\\\\/bfnrtu])/g, \"\\\\\\\\\") // Escape single backslashes not part of valid escape sequences\n .replace(/\\\\u(?![0-9a-fA-F]{4})/g, \"\\\\\\\\u\"); // Fix malformed Unicode escape sequences\n }\n\n if (typeof value === \"object\") {\n if (seen.has(value as object)) {\n return null;\n } else {\n seen.add(value as object);\n }\n\n if (Array.isArray(value)) {\n return value.map((item) => this.sanitizeJsonObject(item, seen));\n } else {\n const result: Record<string, unknown> = {};\n const nullChar = String.fromCharCode(0);\n const nullCharRegex = new RegExp(nullChar, \"g\");\n for (const [key, val] of Object.entries(value)) {\n // Also sanitize object keys\n const sanitizedKey =\n typeof key === \"string\"\n ? key.replace(nullCharRegex, \"\").replace(/\\\\u(?![0-9a-fA-F]{4})/g, \"\\\\\\\\u\")\n : key;\n result[sanitizedKey] = this.sanitizeJsonObject(val, seen);\n }\n return result;\n }\n }\n\n return value;\n }\n\n /**\n * Asynchronously retrieves logs from the database based on the provided parameters.\n * @param {Object} params - The parameters for retrieving logs.\n * @param {UUID} params.entityId - The ID of the entity associated with the logs.\n * @param {UUID} [params.roomId] - The ID of the room associated with the logs.\n * @param {string} [params.type] - The type of the logs to retrieve.\n * @param {number} [params.count] - The maximum number of logs to retrieve.\n * @param {number} [params.offset] - The offset to retrieve logs from.\n * @returns {Promise<Log[]>} A Promise that resolves to an array of logs.\n */\n async getLogs(params: {\n entityId?: UUID;\n roomId?: UUID;\n type?: string;\n count?: number;\n offset?: number;\n }): Promise<Log[]> {\n const { entityId, roomId, type, count, offset } = params;\n\n // Use withEntityContext for RLS only when entityId is provided\n // Without entityId, bypass RLS to see all logs (for non-RLS mode)\n return this.withEntityContext(entityId ?? null, async (tx) => {\n const result = await tx\n .select()\n .from(logTable)\n .where(\n and(\n roomId ? eq(logTable.roomId, roomId) : undefined,\n type ? eq(logTable.type, type) : undefined\n )\n )\n .orderBy(desc(logTable.createdAt))\n .limit(count ?? 10)\n .offset(offset ?? 0);\n\n const logs = result.map((log) => ({\n ...log,\n id: log.id as UUID,\n entityId: log.entityId as UUID,\n roomId: log.roomId as UUID,\n type: log.type as string,\n body: log.body as LogBody,\n createdAt: new Date(log.createdAt as string | number | Date),\n }));\n\n if (logs.length === 0) return [];\n\n return logs;\n });\n }\n\n async getAgentRunSummaries(\n params: {\n limit?: number;\n roomId?: UUID;\n status?: RunStatus | \"all\";\n from?: number;\n to?: number;\n entityId?: UUID;\n } = {}\n ): Promise<AgentRunSummaryResult> {\n const limit = Math.min(Math.max(params.limit ?? 20, 1), 100);\n const fromDate = typeof params.from === \"number\" ? new Date(params.from) : undefined;\n const toDate = typeof params.to === \"number\" ? new Date(params.to) : undefined;\n\n // Use withEntityContext for RLS when entityId is provided\n return this.withEntityContext(params.entityId ?? null, async (tx) => {\n const runMap = new Map<string, AgentRunSummary>();\n\n const conditions: SQL<unknown>[] = [\n eq(logTable.type, \"run_event\"),\n sql`${logTable.body} ? 'runId'`,\n eq(roomTable.agentId, this.agentId),\n ];\n\n if (params.roomId) {\n conditions.push(eq(logTable.roomId, params.roomId));\n }\n if (fromDate) {\n conditions.push(gte(logTable.createdAt, fromDate));\n }\n if (toDate) {\n conditions.push(lte(logTable.createdAt, toDate));\n }\n\n const whereClause = and(...conditions);\n\n const eventLimit = Math.max(limit * 20, 200);\n\n const runEventRows = await tx\n .select({\n runId: sql<string>`(${logTable.body} ->> 'runId')`,\n status: sql<string | null>`(${logTable.body} ->> 'status')`,\n messageId: sql<string | null>`(${logTable.body} ->> 'messageId')`,\n rawBody: logTable.body,\n createdAt: logTable.createdAt,\n roomId: logTable.roomId,\n entityId: logTable.entityId,\n })\n .from(logTable)\n .innerJoin(roomTable, eq(roomTable.id, logTable.roomId))\n .where(whereClause)\n .orderBy(desc(logTable.createdAt))\n .limit(eventLimit);\n\n for (const row of runEventRows) {\n const runId = row.runId;\n if (!runId) continue;\n\n const summary: AgentRunSummary = runMap.get(runId) ?? {\n runId,\n status: \"started\",\n startedAt: null,\n endedAt: null,\n durationMs: null,\n messageId: undefined,\n roomId: undefined,\n entityId: undefined,\n metadata: {},\n };\n\n if (!summary.messageId && row.messageId) {\n summary.messageId = row.messageId as UUID;\n }\n if (!summary.roomId && row.roomId) {\n summary.roomId = row.roomId as UUID;\n }\n if (!summary.entityId && row.entityId) {\n summary.entityId = row.entityId as UUID;\n }\n\n const body = row.rawBody as Record<string, unknown> | undefined;\n if (body && typeof body === \"object\") {\n if (!summary.roomId && typeof body.roomId === \"string\") {\n summary.roomId = body.roomId as UUID;\n }\n if (!summary.entityId && typeof body.entityId === \"string\") {\n summary.entityId = body.entityId as UUID;\n }\n if (!summary.messageId && typeof body.messageId === \"string\") {\n summary.messageId = body.messageId as UUID;\n }\n if (!summary.metadata || Object.keys(summary.metadata).length === 0) {\n const metadata = (body.metadata as Record<string, unknown> | undefined) ?? undefined;\n summary.metadata = metadata ? ({ ...metadata } as Record<string, JsonValue>) : {};\n }\n }\n\n const createdAt = row.createdAt instanceof Date ? row.createdAt : new Date(row.createdAt);\n const timestamp = createdAt.getTime();\n const bodyStatus = body?.status;\n const eventStatus =\n (row.status as RunStatus | undefined) ?? (bodyStatus as RunStatus | undefined);\n\n if (eventStatus === \"started\") {\n const currentStartedAt =\n summary.startedAt === null\n ? null\n : typeof summary.startedAt === \"bigint\"\n ? Number(summary.startedAt)\n : summary.startedAt;\n summary.startedAt =\n currentStartedAt === null ? timestamp : Math.min(currentStartedAt, timestamp);\n } else if (\n eventStatus === \"completed\" ||\n eventStatus === \"timeout\" ||\n eventStatus === \"error\"\n ) {\n summary.status = eventStatus;\n summary.endedAt = timestamp;\n if (summary.startedAt !== null) {\n const startedAtNum =\n typeof summary.startedAt === \"bigint\" ? Number(summary.startedAt) : summary.startedAt;\n summary.durationMs = Math.max(timestamp - startedAtNum, 0);\n }\n }\n\n runMap.set(runId, summary);\n }\n\n let runs = Array.from(runMap.values());\n if (params.status && params.status !== \"all\") {\n runs = runs.filter((run) => run.status === params.status);\n }\n\n runs.sort((a, b) => {\n const aStarted =\n a.startedAt === null\n ? 0\n : typeof a.startedAt === \"bigint\"\n ? Number(a.startedAt)\n : a.startedAt;\n const bStarted =\n b.startedAt === null\n ? 0\n : typeof b.startedAt === \"bigint\"\n ? Number(b.startedAt)\n : b.startedAt;\n return bStarted - aStarted;\n });\n\n const total = runs.length;\n const limitedRuns = runs.slice(0, limit);\n const hasMore = total > limit;\n\n const runCounts = new Map<string, AgentRunCounts>();\n for (const run of limitedRuns) {\n runCounts.set(run.runId, {\n actions: 0,\n modelCalls: 0,\n errors: 0,\n evaluators: 0,\n });\n }\n\n const runIds = limitedRuns.map((run) => run.runId).filter(Boolean);\n\n if (runIds.length > 0) {\n const runIdArray = sql`array[${sql.join(\n runIds.map((id) => sql`${id}`),\n sql`, `\n )}]::text[]`;\n\n const actionSummary = await this.db.execute(sql`\n SELECT\n body->>'runId' as \"runId\",\n COUNT(*)::int as \"actions\",\n SUM(CASE WHEN COALESCE(body->'result'->>'success', 'true') = 'false' THEN 1 ELSE 0 END)::int as \"errors\",\n SUM(COALESCE((body->>'promptCount')::int, 0))::int as \"modelCalls\"\n FROM ${logTable}\n WHERE type = 'action'\n AND body->>'runId' = ANY(${runIdArray})\n GROUP BY body->>'runId'\n `);\n\n const actionRows = (actionSummary.rows ?? []) as Array<{\n runId: string;\n actions: number | string;\n errors: number | string;\n modelCalls: number | string;\n }>;\n\n for (const row of actionRows) {\n const counts = runCounts.get(row.runId);\n if (!counts) continue;\n counts.actions += Number(row.actions ?? 0);\n counts.errors += Number(row.errors ?? 0);\n counts.modelCalls += Number(row.modelCalls ?? 0);\n }\n\n const evaluatorSummary = await this.db.execute(sql`\n SELECT\n body->>'runId' as \"runId\",\n COUNT(*)::int as \"evaluators\"\n FROM ${logTable}\n WHERE type = 'evaluator'\n AND body->>'runId' = ANY(${runIdArray})\n GROUP BY body->>'runId'\n `);\n\n const evaluatorRows = (evaluatorSummary.rows ?? []) as Array<{\n runId: string;\n evaluators: number | string;\n }>;\n\n for (const row of evaluatorRows) {\n const counts = runCounts.get(row.runId);\n if (!counts) continue;\n counts.evaluators += Number(row.evaluators ?? 0);\n }\n\n const genericSummary = await this.db.execute(sql`\n SELECT\n body->>'runId' as \"runId\",\n COUNT(*) FILTER (WHERE type LIKE 'useModel:%')::int as \"modelLogs\",\n COUNT(*) FILTER (WHERE type = 'embedding_event' AND body->>'status' = 'failed')::int as \"embeddingErrors\"\n FROM ${logTable}\n WHERE (type LIKE 'useModel:%' OR type = 'embedding_event')\n AND body->>'runId' = ANY(${runIdArray})\n GROUP BY body->>'runId'\n `);\n\n const genericRows = (genericSummary.rows ?? []) as Array<{\n runId: string;\n modelLogs: number | string;\n embeddingErrors: number | string;\n }>;\n\n for (const row of genericRows) {\n const counts = runCounts.get(row.runId);\n if (!counts) continue;\n counts.modelCalls += Number(row.modelLogs ?? 0);\n counts.errors += Number(row.embeddingErrors ?? 0);\n }\n }\n\n for (const run of limitedRuns) {\n const counts = runCounts.get(run.runId) ?? {\n actions: 0,\n modelCalls: 0,\n errors: 0,\n evaluators: 0,\n };\n // Cast through unknown to bridge the core type (without $typeName) to proto type (with $typeName)\n run.counts = counts as unknown as typeof run.counts;\n }\n\n return {\n runs: limitedRuns as unknown as import(\"@elizaos/core\").AgentRunSummary[],\n total,\n hasMore,\n } as AgentRunSummaryResult;\n });\n }\n\n /**\n * Asynchronously deletes a log from the database based on the provided parameters.\n * @param {UUID} logId - The ID of the log to delete.\n * @returns {Promise<void>} A Promise that resolves when the log is deleted.\n */\n async deleteLog(logId: UUID): Promise<void> {\n return this.withDatabase(async () => {\n await this.db.delete(logTable).where(eq(logTable.id, logId));\n });\n }\n\n /**\n * Asynchronously searches for memories in the database based on the provided parameters.\n * @param {Object} params - The parameters for searching for memories.\n * @param {string} params.tableName - The name of the table to search for memories in.\n * @param {number[]} params.embedding - The embedding to search for.\n * @param {number} [params.match_threshold] - The threshold for the cosine distance.\n * @param {number} [params.count] - The maximum number of memories to retrieve.\n * @param {boolean} [params.unique] - Whether to retrieve unique memories only.\n * @param {string} [params.query] - Optional query string for potential reranking.\n * @param {UUID} [params.roomId] - Optional room ID to filter by.\n * @param {UUID} [params.worldId] - Optional world ID to filter by.\n * @param {UUID} [params.entityId] - Optional entity ID to filter by.\n * @returns {Promise<Memory[]>} A Promise that resolves to an array of memories.\n */\n async searchMemories(params: {\n tableName: string;\n embedding: number[];\n match_threshold?: number;\n count?: number;\n unique?: boolean;\n query?: string;\n roomId?: UUID;\n worldId?: UUID;\n entityId?: UUID;\n }): Promise<Memory[]> {\n return await this.searchMemoriesByEmbedding(params.embedding, {\n match_threshold: params.match_threshold,\n count: params.count,\n // Pass direct scope fields down\n roomId: params.roomId,\n worldId: params.worldId,\n entityId: params.entityId,\n unique: params.unique,\n tableName: params.tableName,\n });\n }\n\n /**\n * Asynchronously searches for memories in the database based on the provided parameters.\n * @param {number[]} embedding - The embedding to search for.\n * @param {Object} params - The parameters for searching for memories.\n * @param {number} [params.match_threshold] - The threshold for the cosine distance.\n * @param {number} [params.count] - The maximum number of memories to retrieve.\n * @param {UUID} [params.roomId] - Optional room ID to filter by.\n * @param {UUID} [params.worldId] - Optional world ID to filter by.\n * @param {UUID} [params.entityId] - Optional entity ID to filter by.\n * @param {boolean} [params.unique] - Whether to retrieve unique memories only.\n * @param {string} [params.tableName] - The name of the table to search for memories in.\n * @returns {Promise<Memory[]>} A Promise that resolves to an array of memories.\n */\n async searchMemoriesByEmbedding(\n embedding: number[],\n params: {\n match_threshold?: number;\n count?: number;\n roomId?: UUID;\n worldId?: UUID;\n entityId?: UUID;\n unique?: boolean;\n tableName: string;\n }\n ): Promise<Memory[]> {\n return this.withDatabase(async () => {\n const cleanVector = embedding.map((n) => (Number.isFinite(n) ? Number(n.toFixed(6)) : 0));\n\n const similarity = sql<number>`1 - (${cosineDistance(\n embeddingTable[this.embeddingDimension],\n cleanVector\n )})`;\n\n const conditions = [eq(memoryTable.type, params.tableName)];\n\n if (params.unique) {\n conditions.push(eq(memoryTable.unique, true));\n }\n\n conditions.push(eq(memoryTable.agentId, this.agentId));\n\n // Add filters based on direct params\n if (params.roomId) {\n conditions.push(eq(memoryTable.roomId, params.roomId));\n }\n if (params.worldId) {\n conditions.push(eq(memoryTable.worldId, params.worldId));\n }\n if (params.entityId) {\n conditions.push(eq(memoryTable.entityId, params.entityId));\n }\n\n if (params.match_threshold) {\n conditions.push(gte(similarity, params.match_threshold));\n }\n\n const results = await this.db\n .select({\n memory: memoryTable,\n similarity,\n embedding: embeddingTable[this.embeddingDimension],\n })\n .from(embeddingTable)\n .innerJoin(memoryTable, eq(memoryTable.id, embeddingTable.memoryId))\n .where(and(...conditions))\n .orderBy(desc(similarity))\n .limit(params.count ?? 10);\n\n return results.map((row) => ({\n id: row.memory.id as UUID,\n type: row.memory.type,\n createdAt: row.memory.createdAt.getTime(),\n content:\n typeof row.memory.content === \"string\"\n ? JSON.parse(row.memory.content)\n : row.memory.content,\n entityId: row.memory.entityId as UUID,\n agentId: row.memory.agentId as UUID,\n roomId: row.memory.roomId as UUID,\n worldId: row.memory.worldId as UUID | undefined, // Include worldId\n unique: row.memory.unique,\n metadata: row.memory.metadata as MemoryMetadata,\n embedding: row.embedding ?? undefined,\n similarity: row.similarity,\n }));\n });\n }\n\n /**\n * Asynchronously creates a new memory in the database.\n * @param {Memory & { metadata?: MemoryMetadata }} memory - The memory object to create.\n * @param {string} tableName - The name of the table to create the memory in.\n * @returns {Promise<UUID>} A Promise that resolves to the ID of the created memory.\n */\n async createMemory(\n memory: Memory & { metadata?: MemoryMetadata },\n tableName: string\n ): Promise<UUID> {\n const memoryId = memory.id ?? (v4() as UUID);\n\n const existing = await this.getMemoryById(memoryId);\n if (existing) {\n return memoryId;\n }\n\n // only do costly check if we need to\n if (memory.unique === undefined) {\n memory.unique = true; // set default\n if (memory.embedding && Array.isArray(memory.embedding)) {\n const similarMemories = await this.searchMemoriesByEmbedding(memory.embedding, {\n tableName,\n // Use the scope fields from the memory object for similarity check\n roomId: memory.roomId,\n worldId: memory.worldId,\n entityId: memory.entityId,\n match_threshold: 0.95,\n count: 1,\n });\n memory.unique = similarMemories.length === 0;\n }\n }\n\n // Ensure we always pass a JSON string to the SQL placeholder – if we pass an\n // object directly PG sees `[object Object]` and fails the `::jsonb` cast.\n const contentToInsert =\n typeof memory.content === \"string\" ? memory.content : JSON.stringify(memory.content ?? {});\n\n const metadataToInsert =\n typeof memory.metadata === \"string\" ? memory.metadata : JSON.stringify(memory.metadata ?? {});\n\n // Use withEntityContext to set Entity RLS context if needed\n // This delegates to the concrete adapter implementation (PostgreSQL or PGLite)\n await this.withEntityContext(memory.entityId, async (tx) => {\n await tx.insert(memoryTable).values([\n {\n id: memoryId,\n type: tableName,\n content: sql`${contentToInsert}::jsonb`,\n metadata: sql`${metadataToInsert}::jsonb`,\n entityId: memory.entityId,\n roomId: memory.roomId,\n worldId: memory.worldId, // Include worldId\n agentId: memory.agentId || this.agentId,\n unique: memory.unique,\n createdAt:\n memory.createdAt !== undefined\n ? new Date(memory.createdAt)\n : new Date(),\n },\n ]);\n\n if (memory.embedding && Array.isArray(memory.embedding)) {\n const embeddingValues: Record<string, unknown> = {\n id: v4(),\n memoryId: memoryId,\n createdAt:\n memory.createdAt !== undefined\n ? new Date(memory.createdAt)\n : new Date(),\n };\n\n const cleanVector = memory.embedding.map((n) =>\n Number.isFinite(n) ? Number(n.toFixed(6)) : 0\n );\n\n embeddingValues[this.embeddingDimension] = cleanVector;\n\n await tx.insert(embeddingTable).values([embeddingValues]);\n }\n });\n\n return memoryId;\n }\n\n /**\n * Updates an existing memory in the database.\n * @param memory The memory object with updated content and optional embedding\n * @returns Promise resolving to boolean indicating success\n */\n async updateMemory(\n memory: Partial<Memory> & { id: UUID; metadata?: MemoryMetadata }\n ): Promise<boolean> {\n return this.withDatabase(async () => {\n try {\n await this.db.transaction(async (tx) => {\n // Update memory content if provided\n if (memory.content) {\n const contentToUpdate =\n typeof memory.content === \"string\"\n ? memory.content\n : JSON.stringify(memory.content ?? {});\n\n const metadataToUpdate =\n typeof memory.metadata === \"string\"\n ? memory.metadata\n : JSON.stringify(memory.metadata ?? {});\n\n await tx\n .update(memoryTable)\n .set({\n content: sql`${contentToUpdate}::jsonb`,\n ...(memory.metadata && {\n metadata: sql`${metadataToUpdate}::jsonb`,\n }),\n })\n .where(eq(memoryTable.id, memory.id));\n } else if (memory.metadata) {\n // Update only metadata if content is not provided\n const metadataToUpdate =\n typeof memory.metadata === \"string\"\n ? memory.metadata\n : JSON.stringify(memory.metadata ?? {});\n\n await tx\n .update(memoryTable)\n .set({\n metadata: sql`${metadataToUpdate}::jsonb`,\n })\n .where(eq(memoryTable.id, memory.id));\n }\n\n // Update embedding if provided\n if (memory.embedding && Array.isArray(memory.embedding)) {\n const cleanVector = memory.embedding.map((n) =>\n Number.isFinite(n) ? Number(n.toFixed(6)) : 0\n );\n\n // Check if embedding exists\n const existingEmbedding = await tx\n .select({ id: embeddingTable.id })\n .from(embeddingTable)\n .where(eq(embeddingTable.memoryId, memory.id))\n .limit(1);\n\n if (existingEmbedding.length > 0) {\n // Update existing embedding\n const updateValues: Record<string, unknown> = {};\n updateValues[this.embeddingDimension] = cleanVector;\n\n await tx\n .update(embeddingTable)\n .set(updateValues)\n .where(eq(embeddingTable.memoryId, memory.id));\n } else {\n // Create new embedding\n const embeddingValues: Record<string, unknown> = {\n id: v4(),\n memoryId: memory.id,\n };\n embeddingValues[this.embeddingDimension] = cleanVector;\n\n await tx.insert(embeddingTable).values([embeddingValues]);\n }\n }\n });\n\n return true;\n } catch (error) {\n logger.error(\n {\n src: \"plugin:sql\",\n memoryId: memory.id,\n error: error instanceof Error ? error.message : String(error),\n },\n \"Failed to update memory\"\n );\n return false;\n }\n });\n }\n\n /**\n * Asynchronously deletes a memory from the database based on the provided parameters.\n * @param {UUID} memoryId - The ID of the memory to delete.\n * @returns {Promise<void>} A Promise that resolves when the memory is deleted.\n */\n async deleteMemory(memoryId: UUID): Promise<void> {\n return this.withDatabase(async () => {\n await this.db.transaction(async (tx) => {\n // See if there are any fragments that we need to delete\n await this.deleteMemoryFragments(tx, memoryId);\n\n // Then delete the embedding for the main memory\n await tx.delete(embeddingTable).where(eq(embeddingTable.memoryId, memoryId));\n\n // Finally delete the memory itself\n await tx.delete(memoryTable).where(eq(memoryTable.id, memoryId));\n });\n });\n }\n\n /**\n * Asynchronously deletes multiple memories from the database in a single batch operation.\n * @param {UUID[]} memoryIds - An array of UUIDs of the memories to delete.\n * @returns {Promise<void>} A Promise that resolves when all memories are deleted.\n */\n async deleteManyMemories(memoryIds: UUID[]): Promise<void> {\n if (memoryIds.length === 0) {\n return;\n }\n\n return this.withDatabase(async () => {\n await this.db.transaction(async (tx) => {\n // Process in smaller batches to avoid query size limits\n const BATCH_SIZE = 100;\n for (let i = 0; i < memoryIds.length; i += BATCH_SIZE) {\n const batch = memoryIds.slice(i, i + BATCH_SIZE);\n\n // Delete any fragments for document memories in this batch\n await Promise.all(\n batch.map(async (memoryId) => {\n await this.deleteMemoryFragments(tx, memoryId);\n })\n );\n\n // Delete embeddings for the batch\n await tx.delete(embeddingTable).where(inArray(embeddingTable.memoryId, batch));\n\n // Delete the memories themselves\n await tx.delete(memoryTable).where(inArray(memoryTable.id, batch));\n }\n });\n });\n }\n\n /**\n * Deletes all memory fragments that reference a specific document memory\n * @param tx The database transaction\n * @param documentId The UUID of the document memory whose fragments should be deleted\n * @private\n */\n private async deleteMemoryFragments(tx: DrizzleDatabase, documentId: UUID): Promise<void> {\n const fragmentsToDelete = await this.getMemoryFragments(tx, documentId);\n\n if (fragmentsToDelete.length > 0) {\n const fragmentIds = fragmentsToDelete.map((f) => f.id) as UUID[];\n\n // Delete embeddings for fragments\n await tx.delete(embeddingTable).where(inArray(embeddingTable.memoryId, fragmentIds));\n\n // Delete the fragments\n await tx.delete(memoryTable).where(inArray(memoryTable.id, fragmentIds));\n }\n }\n\n /**\n * Retrieves all memory fragments that reference a specific document memory\n * @param tx The database transaction\n * @param documentId The UUID of the document memory whose fragments should be retrieved\n * @returns An array of memory fragments\n * @private\n */\n private async getMemoryFragments(tx: DrizzleDatabase, documentId: UUID): Promise<{ id: UUID }[]> {\n const fragments = await tx\n .select({ id: memoryTable.id })\n .from(memoryTable)\n .where(\n and(\n eq(memoryTable.agentId, this.agentId),\n sql`${memoryTable.metadata}->>'documentId' = ${documentId}`\n )\n );\n\n return fragments.map((f) => ({ id: f.id as UUID }));\n }\n\n /**\n * Asynchronously deletes all memories from the database based on the provided parameters.\n * @param {UUID} roomId - The ID of the room to delete memories from.\n * @param {string} tableName - The name of the table to delete memories from.\n * @returns {Promise<void>} A Promise that resolves when the memories are deleted.\n */\n async deleteAllMemories(roomId: UUID, tableName: string): Promise<void> {\n return this.withDatabase(async () => {\n await this.db.transaction(async (tx) => {\n // 1) fetch all memory IDs for this room + table\n const rows = await tx\n .select({ id: memoryTable.id })\n .from(memoryTable)\n .where(and(eq(memoryTable.roomId, roomId), eq(memoryTable.type, tableName)));\n\n const ids = rows.map((r) => r.id);\n logger.debug(\n { src: \"plugin:sql\", roomId, tableName, memoryCount: ids.length },\n \"Deleting all memories\"\n );\n\n if (ids.length === 0) {\n return;\n }\n\n // 2) delete any fragments for \"document\" memories & their embeddings\n await Promise.all(\n ids.map(async (memoryId) => {\n await this.deleteMemoryFragments(tx, memoryId);\n await tx.delete(embeddingTable).where(eq(embeddingTable.memoryId, memoryId));\n })\n );\n\n // 3) delete the memories themselves\n await tx\n .delete(memoryTable)\n .where(and(eq(memoryTable.roomId, roomId), eq(memoryTable.type, tableName)));\n });\n });\n }\n\n /**\n * Asynchronously counts the number of memories in the database based on the provided parameters.\n * @param {UUID} roomId - The ID of the room to count memories in.\n * @param {boolean} [unique] - Whether to count unique memories only.\n * @param {string} [tableName] - The name of the table to count memories in.\n * @returns {Promise<number>} A Promise that resolves to the number of memories.\n */\n async countMemories(roomId: UUID, unique = true, tableName = \"\"): Promise<number> {\n if (!tableName) throw new Error(\"tableName is required\");\n\n return this.withDatabase(async () => {\n const conditions = [eq(memoryTable.roomId, roomId), eq(memoryTable.type, tableName)];\n\n if (unique) {\n conditions.push(eq(memoryTable.unique, true));\n }\n\n const result = await this.db\n .select({ count: sql<number>`count(*)` })\n .from(memoryTable)\n .where(and(...conditions));\n\n const result0 = result[0];\n return Number(result0?.count ?? 0);\n });\n }\n\n /**\n * Asynchronously retrieves rooms from the database based on the provided parameters.\n * @param {UUID[]} roomIds - The IDs of the rooms to retrieve.\n * @returns {Promise<Room[] | null>} A Promise that resolves to the rooms if found, null otherwise.\n */\n async getRoomsByIds(roomIds: UUID[]): Promise<Room[] | null> {\n return this.withDatabase(async () => {\n const result = await this.db\n .select({\n id: roomTable.id,\n name: roomTable.name, // Added name\n channelId: roomTable.channelId,\n agentId: roomTable.agentId,\n messageServerId: roomTable.messageServerId,\n worldId: roomTable.worldId,\n type: roomTable.type,\n source: roomTable.source,\n metadata: roomTable.metadata, // Added metadata\n })\n .from(roomTable)\n .where(and(inArray(roomTable.id, roomIds), eq(roomTable.agentId, this.agentId)));\n\n // Map the result to properly typed Room objects\n const rooms = result.map((room) => ({\n ...room,\n id: room.id as UUID,\n name: room.name ?? undefined,\n agentId: room.agentId as UUID,\n messageServerId: room.messageServerId as UUID,\n serverId: room.messageServerId as UUID, // Backward compatibility alias\n worldId: room.worldId as UUID,\n channelId: room.channelId as UUID,\n type: room.type as ChannelType,\n metadata: room.metadata as Metadata,\n }));\n\n return rooms;\n });\n }\n\n /**\n * Asynchronously retrieves all rooms from the database based on the provided parameters.\n * @param {UUID} worldId - The ID of the world to retrieve rooms from.\n * @returns {Promise<Room[]>} A Promise that resolves to an array of rooms.\n */\n async getRoomsByWorld(worldId: UUID): Promise<Room[]> {\n return this.withDatabase(async () => {\n const result = await this.db.select().from(roomTable).where(eq(roomTable.worldId, worldId));\n const rooms = result.map((room) => ({\n ...room,\n id: room.id as UUID,\n name: room.name ?? undefined,\n agentId: room.agentId as UUID,\n messageServerId: room.messageServerId as UUID,\n serverId: room.messageServerId as UUID, // Backward compatibility alias\n worldId: room.worldId as UUID,\n channelId: room.channelId as UUID,\n type: room.type as ChannelType,\n metadata: room.metadata as Metadata,\n }));\n return rooms;\n });\n }\n\n /**\n * Asynchronously updates a room in the database based on the provided parameters.\n * @param {Room} room - The room object to update.\n * @returns {Promise<void>} A Promise that resolves when the room is updated.\n */\n async updateRoom(room: Room): Promise<void> {\n return this.withDatabase(async () => {\n await this.db\n .update(roomTable)\n .set({ ...room, agentId: this.agentId })\n .where(eq(roomTable.id, room.id));\n });\n }\n\n /**\n * Asynchronously creates a new room in the database based on the provided parameters.\n * @param {Room} room - The room object to create.\n * @returns {Promise<UUID>} A Promise that resolves to the ID of the created room.\n */\n async createRooms(rooms: Room[]): Promise<UUID[]> {\n return this.withDatabase(async () => {\n const roomsWithIds = rooms.map((room) => ({\n ...room,\n agentId: this.agentId,\n id: room.id || v4(), // ensure each room has a unique ID\n }));\n\n const insertedRooms = await this.db\n .insert(roomTable)\n .values(roomsWithIds)\n .onConflictDoNothing()\n .returning();\n const insertedIds = insertedRooms.map((r) => r.id as UUID);\n return insertedIds;\n });\n }\n\n /**\n * Asynchronously deletes a room from the database based on the provided parameters.\n * @param {UUID} roomId - The ID of the room to delete.\n * @returns {Promise<void>} A Promise that resolves when the room is deleted.\n */\n async deleteRoom(roomId: UUID): Promise<void> {\n if (!roomId) throw new Error(\"Room ID is required\");\n return this.withDatabase(async () => {\n await this.db.transaction(async (tx) => {\n await tx.delete(roomTable).where(eq(roomTable.id, roomId));\n });\n });\n }\n\n /**\n * Asynchronously retrieves all rooms for a participant from the database based on the provided parameters.\n * @param {UUID} entityId - The ID of the entity to retrieve rooms for.\n * @returns {Promise<UUID[]>} A Promise that resolves to an array of room IDs.\n */\n async getRoomsForParticipant(entityId: UUID): Promise<UUID[]> {\n return this.withDatabase(async () => {\n const result = await this.db\n .select({ roomId: participantTable.roomId })\n .from(participantTable)\n .innerJoin(roomTable, eq(participantTable.roomId, roomTable.id))\n .where(and(eq(participantTable.entityId, entityId), eq(roomTable.agentId, this.agentId)));\n\n return result.map((row) => row.roomId as UUID);\n });\n }\n\n /**\n * Asynchronously retrieves all rooms for a list of participants from the database based on the provided parameters.\n * @param {UUID[]} entityIds - The IDs of the entities to retrieve rooms for.\n * @returns {Promise<UUID[]>} A Promise that resolves to an array of room IDs.\n */\n async getRoomsForParticipants(entityIds: UUID[]): Promise<UUID[]> {\n return this.withDatabase(async () => {\n const result = await this.db\n .selectDistinct({ roomId: participantTable.roomId })\n .from(participantTable)\n .innerJoin(roomTable, eq(participantTable.roomId, roomTable.id))\n .where(\n and(inArray(participantTable.entityId, entityIds), eq(roomTable.agentId, this.agentId))\n );\n\n return result.map((row) => row.roomId as UUID);\n });\n }\n\n /**\n * Asynchronously adds a participant to a room in the database based on the provided parameters.\n * @param {UUID} entityId - The ID of the entity to add to the room.\n * @param {UUID} roomId - The ID of the room to add the entity to.\n * @returns {Promise<boolean>} A Promise that resolves to a boolean indicating whether the participant was added successfully.\n */\n async addParticipant(entityId: UUID, roomId: UUID): Promise<boolean> {\n return this.withDatabase(async () => {\n try {\n await this.db\n .insert(participantTable)\n .values({\n entityId,\n roomId,\n agentId: this.agentId,\n })\n .onConflictDoNothing();\n return true;\n } catch (error) {\n logger.error(\n {\n src: \"plugin:sql\",\n entityId,\n roomId,\n agentId: this.agentId,\n error: error instanceof Error ? error.message : String(error),\n },\n \"Failed to add participant to room\"\n );\n return false;\n }\n });\n }\n\n async addParticipantsRoom(entityIds: UUID[], roomId: UUID): Promise<boolean> {\n return this.withDatabase(async () => {\n try {\n const values = entityIds.map((id) => ({\n entityId: id,\n roomId,\n agentId: this.agentId,\n }));\n await this.db.insert(participantTable).values(values).onConflictDoNothing().execute();\n return true;\n } catch (error) {\n logger.error(\n {\n src: \"plugin:sql\",\n roomId,\n agentId: this.agentId,\n error: error instanceof Error ? error.message : String(error),\n },\n \"Failed to add participants to room\"\n );\n return false;\n }\n });\n }\n\n /**\n * Asynchronously removes a participant from a room in the database based on the provided parameters.\n * @param {UUID} entityId - The ID of the entity to remove from the room.\n * @param {UUID} roomId - The ID of the room to remove the entity from.\n * @returns {Promise<boolean>} A Promise that resolves to a boolean indicating whether the participant was removed successfully.\n */\n async removeParticipant(entityId: UUID, roomId: UUID): Promise<boolean> {\n return this.withDatabase(async () => {\n try {\n const result = await this.db.transaction(async (tx) => {\n return await tx\n .delete(participantTable)\n .where(\n and(eq(participantTable.entityId, entityId), eq(participantTable.roomId, roomId))\n )\n .returning();\n });\n\n const removed = result.length > 0;\n return removed;\n } catch (error) {\n logger.error(\n {\n src: \"plugin:sql\",\n entityId,\n roomId,\n error: error instanceof Error ? error.message : String(error),\n },\n \"Failed to remove participant from room\"\n );\n return false;\n }\n });\n }\n\n /**\n * Asynchronously retrieves all participants for an entity from the database based on the provided parameters.\n * @param {UUID} entityId - The ID of the entity to retrieve participants for.\n * @returns {Promise<Participant[]>} A Promise that resolves to an array of participants.\n */\n async getParticipantsForEntity(entityId: UUID): Promise<Participant[]> {\n return this.withDatabase(async () => {\n const result = await this.db\n .select({\n id: participantTable.id,\n entityId: participantTable.entityId,\n roomId: participantTable.roomId,\n })\n .from(participantTable)\n .where(eq(participantTable.entityId, entityId));\n\n const entities = await this.getEntitiesByIds([entityId]);\n\n if (!entities || !entities.length) {\n return [];\n }\n\n return result.map((row) => ({\n id: row.id as UUID,\n entity: entities[0],\n }));\n });\n }\n\n /**\n * Asynchronously retrieves all participants for a room from the database based on the provided parameters.\n * @param {UUID} roomId - The ID of the room to retrieve participants for.\n * @returns {Promise<UUID[]>} A Promise that resolves to an array of entity IDs.\n */\n async getParticipantsForRoom(roomId: UUID): Promise<UUID[]> {\n return this.withDatabase(async () => {\n const result = await this.db\n .select({ entityId: participantTable.entityId })\n .from(participantTable)\n .where(eq(participantTable.roomId, roomId));\n\n return result.map((row) => row.entityId as UUID);\n });\n }\n\n /**\n * Check if an entity is a participant in a specific room/channel.\n * More efficient than getParticipantsForRoom when only checking membership.\n * @param {UUID} roomId - The ID of the room to check.\n * @param {UUID} entityId - The ID of the entity to check.\n * @returns {Promise<boolean>} A Promise that resolves to true if entity is a participant.\n */\n async isRoomParticipant(roomId: UUID, entityId: UUID): Promise<boolean> {\n return this.withDatabase(async () => {\n const result = await this.db\n .select()\n .from(participantTable)\n .where(and(eq(participantTable.roomId, roomId), eq(participantTable.entityId, entityId)))\n .limit(1);\n\n return result.length > 0;\n });\n }\n\n /**\n * Asynchronously retrieves the user state for a participant in a room from the database based on the provided parameters.\n * @param {UUID} roomId - The ID of the room to retrieve the participant's user state for.\n * @param {UUID} entityId - The ID of the entity to retrieve the user state for.\n * @returns {Promise<\"FOLLOWED\" | \"MUTED\" | null>} A Promise that resolves to the participant's user state.\n */\n async getParticipantUserState(\n roomId: UUID,\n entityId: UUID\n ): Promise<\"FOLLOWED\" | \"MUTED\" | null> {\n return this.withDatabase(async () => {\n const result = await this.db\n .select({ roomState: participantTable.roomState })\n .from(participantTable)\n .where(\n and(\n eq(participantTable.roomId, roomId),\n eq(participantTable.entityId, entityId),\n eq(participantTable.agentId, this.agentId)\n )\n )\n .limit(1);\n\n const result0 = result[0];\n return (result0?.roomState as \"FOLLOWED\" | \"MUTED\" | null) ?? null;\n });\n }\n\n /**\n * Asynchronously sets the user state for a participant in a room in the database based on the provided parameters.\n * @param {UUID} roomId - The ID of the room to set the participant's user state for.\n * @param {UUID} entityId - The ID of the entity to set the user state for.\n * @param {string} state - The state to set the participant's user state to.\n * @returns {Promise<void>} A Promise that resolves when the participant's user state is set.\n */\n async setParticipantUserState(\n roomId: UUID,\n entityId: UUID,\n state: \"FOLLOWED\" | \"MUTED\" | null\n ): Promise<void> {\n return this.withDatabase(async () => {\n try {\n await this.db.transaction(async (tx) => {\n await tx\n .update(participantTable)\n .set({ roomState: state })\n .where(\n and(\n eq(participantTable.roomId, roomId),\n eq(participantTable.entityId, entityId),\n eq(participantTable.agentId, this.agentId)\n )\n );\n });\n } catch (error) {\n logger.error(\n {\n src: \"plugin:sql\",\n roomId,\n entityId,\n state,\n error: error instanceof Error ? error.message : String(error),\n },\n \"Failed to set participant follow state\"\n );\n throw error;\n }\n });\n }\n\n /**\n * Asynchronously creates a new relationship in the database based on the provided parameters.\n * @param {Object} params - The parameters for creating a new relationship.\n * @param {UUID} params.sourceEntityId - The ID of the source entity.\n * @param {UUID} params.targetEntityId - The ID of the target entity.\n * @param {string[]} [params.tags] - The tags for the relationship.\n * @param {Object} [params.metadata] - The metadata for the relationship.\n * @returns {Promise<boolean>} A Promise that resolves to a boolean indicating whether the relationship was created successfully.\n */\n async createRelationship(params: {\n sourceEntityId: UUID;\n targetEntityId: UUID;\n tags?: string[];\n metadata?: { [key: string]: unknown };\n }): Promise<boolean> {\n return this.withDatabase(async () => {\n const id = v4();\n const saveParams = {\n id,\n sourceEntityId: params.sourceEntityId,\n targetEntityId: params.targetEntityId,\n agentId: this.agentId,\n tags: params.tags || [],\n metadata: params.metadata || {},\n };\n try {\n await this.db.insert(relationshipTable).values(saveParams);\n return true;\n } catch (error) {\n logger.error(\n {\n src: \"plugin:sql\",\n agentId: this.agentId,\n error: error instanceof Error ? error.message : String(error),\n saveParams,\n },\n \"Error creating relationship\"\n );\n return false;\n }\n });\n }\n\n /**\n * Asynchronously updates an existing relationship in the database based on the provided parameters.\n * @param {Relationship} relationship - The relationship object to update.\n * @returns {Promise<void>} A Promise that resolves when the relationship is updated.\n */\n async updateRelationship(relationship: Relationship): Promise<void> {\n return this.withDatabase(async () => {\n try {\n await this.db\n .update(relationshipTable)\n .set({\n tags: relationship.tags || [],\n metadata: relationship.metadata || {},\n })\n .where(eq(relationshipTable.id, relationship.id));\n } catch (error) {\n logger.error(\n {\n src: \"plugin:sql\",\n agentId: this.agentId,\n error: error instanceof Error ? error.message : String(error),\n relationshipId: relationship.id,\n },\n \"Error updating relationship\"\n );\n throw error;\n }\n });\n }\n\n /**\n * Asynchronously retrieves a relationship from the database based on the provided parameters.\n * @param {Object} params - The parameters for retrieving a relationship.\n * @param {UUID} params.sourceEntityId - The ID of the source entity.\n * @param {UUID} params.targetEntityId - The ID of the target entity.\n * @returns {Promise<Relationship | null>} A Promise that resolves to the relationship if found, null otherwise.\n */\n async getRelationship(params: {\n sourceEntityId: UUID;\n targetEntityId: UUID;\n }): Promise<Relationship | null> {\n return this.withDatabase(async () => {\n const { sourceEntityId, targetEntityId } = params;\n const result = await this.db\n .select()\n .from(relationshipTable)\n .where(\n and(\n eq(relationshipTable.sourceEntityId, sourceEntityId),\n eq(relationshipTable.targetEntityId, targetEntityId)\n )\n );\n if (result.length === 0) return null;\n const relationship = result[0];\n return {\n ...relationship,\n id: relationship.id as UUID,\n sourceEntityId: relationship.sourceEntityId as UUID,\n targetEntityId: relationship.targetEntityId as UUID,\n agentId: relationship.agentId as UUID,\n tags: (relationship.tags ?? []) as string[],\n metadata: (relationship.metadata ?? {}) as Metadata,\n createdAt: relationship.createdAt.toISOString(),\n };\n });\n }\n\n /**\n * Asynchronously retrieves relationships from the database based on the provided parameters.\n * @param {Object} params - The parameters for retrieving relationships.\n * @param {UUID} params.entityId - The ID of the entity to retrieve relationships for.\n * @param {string[]} [params.tags] - The tags to filter relationships by.\n * @returns {Promise<Relationship[]>} A Promise that resolves to an array of relationships.\n */\n async getRelationships(params: { entityId: UUID; tags?: string[] }): Promise<Relationship[]> {\n return this.withDatabase(async () => {\n const { entityId, tags } = params;\n\n let query: SQL;\n\n if (tags && tags.length > 0) {\n query = sql`\n SELECT * FROM ${relationshipTable}\n WHERE (${relationshipTable.sourceEntityId} = ${entityId} OR ${relationshipTable.targetEntityId} = ${entityId})\n AND ${relationshipTable.tags} && CAST(ARRAY[${sql.join(tags, sql`, `)}] AS text[])\n `;\n } else {\n query = sql`\n SELECT * FROM ${relationshipTable}\n WHERE ${relationshipTable.sourceEntityId} = ${entityId} OR ${relationshipTable.targetEntityId} = ${entityId}\n `;\n }\n\n const result = await this.db.execute(query);\n\n return result.rows.map((relationship: Record<string, unknown>) => ({\n ...relationship,\n id: relationship.id as UUID,\n sourceEntityId: (relationship.source_entity_id || relationship.sourceEntityId) as UUID,\n targetEntityId: (relationship.target_entity_id || relationship.targetEntityId) as UUID,\n agentId: (relationship.agent_id || relationship.agentId) as UUID,\n tags: (relationship.tags ?? []) as string[],\n metadata: (relationship.metadata ?? {}) as Metadata,\n createdAt:\n relationship.created_at || relationship.createdAt\n ? (relationship.created_at || relationship.createdAt) instanceof Date\n ? ((relationship.created_at || relationship.createdAt) as Date).toISOString()\n : new Date(\n (relationship.created_at as string) || (relationship.createdAt as string)\n ).toISOString()\n : new Date().toISOString(),\n }));\n });\n }\n\n /**\n * Asynchronously retrieves a cache value from the database based on the provided key.\n * @param {string} key - The key to retrieve the cache value for.\n * @returns {Promise<T | undefined>} A Promise that resolves to the cache value if found, undefined otherwise.\n */\n async getCache<T>(key: string): Promise<T | undefined> {\n return this.withDatabase(async () => {\n try {\n const result = await this.db\n .select({ value: cacheTable.value })\n .from(cacheTable)\n .where(and(eq(cacheTable.agentId, this.agentId), eq(cacheTable.key, key)))\n .limit(1);\n\n if (result && result.length > 0 && result[0]) {\n return result[0].value as T | undefined;\n }\n\n return undefined;\n } catch (error) {\n logger.error(\n {\n src: \"plugin:sql\",\n agentId: this.agentId,\n error: error instanceof Error ? error.message : String(error),\n key,\n },\n \"Error fetching cache\"\n );\n return undefined;\n }\n });\n }\n\n /**\n * Asynchronously sets a cache value in the database based on the provided key and value.\n * @param {string} key - The key to set the cache value for.\n * @param {T} value - The value to set in the cache.\n * @returns {Promise<boolean>} A Promise that resolves to a boolean indicating whether the cache value was set successfully.\n */\n async setCache<T>(key: string, value: T): Promise<boolean> {\n return this.withDatabase(async () => {\n try {\n await this.db\n .insert(cacheTable)\n .values({\n key: key,\n agentId: this.agentId,\n value: value,\n })\n .onConflictDoUpdate({\n target: [cacheTable.key, cacheTable.agentId],\n set: {\n value: value,\n },\n });\n\n return true;\n } catch (error) {\n logger.error(\n {\n src: \"plugin:sql\",\n agentId: this.agentId,\n error: error instanceof Error ? error.message : String(error),\n key,\n },\n \"Error setting cache\"\n );\n return false;\n }\n });\n }\n\n /**\n * Asynchronously deletes a cache value from the database based on the provided key.\n * @param {string} key - The key to delete the cache value for.\n * @returns {Promise<boolean>} A Promise that resolves to a boolean indicating whether the cache value was deleted successfully.\n */\n async deleteCache(key: string): Promise<boolean> {\n return this.withDatabase(async () => {\n try {\n await this.db.transaction(async (tx) => {\n await tx\n .delete(cacheTable)\n .where(and(eq(cacheTable.agentId, this.agentId), eq(cacheTable.key, key)));\n });\n return true;\n } catch (error) {\n logger.error(\n {\n src: \"plugin:sql\",\n agentId: this.agentId,\n error: error instanceof Error ? error.message : String(error),\n key,\n },\n \"Error deleting cache\"\n );\n return false;\n }\n });\n }\n\n /**\n * Asynchronously creates a new world in the database based on the provided parameters.\n * @param {World} world - The world object to create.\n * @returns {Promise<UUID>} A Promise that resolves to the ID of the created world.\n */\n async createWorld(world: World): Promise<UUID> {\n return this.withDatabase(async () => {\n const normalizedWorld = this.normalizeWorldData(world);\n const newWorldId = normalizedWorld.id as UUID;\n\n await this.db.insert(worldTable).values(normalizedWorld);\n return newWorldId;\n });\n }\n\n /**\n * Asynchronously retrieves a world from the database based on the provided parameters.\n * @param {UUID} id - The ID of the world to retrieve.\n * @returns {Promise<World | null>} A Promise that resolves to the world if found, null otherwise.\n */\n async getWorld(id: UUID): Promise<World | null> {\n return this.withDatabase(async () => {\n const result = await this.db.select().from(worldTable).where(eq(worldTable.id, id));\n return result.length > 0 ? this.mapWorldResult(result[0]) : null;\n });\n }\n\n /**\n * Asynchronously retrieves all worlds from the database based on the provided parameters.\n * @returns {Promise<World[]>} A Promise that resolves to an array of worlds.\n */\n async getAllWorlds(): Promise<World[]> {\n return this.withDatabase(async () => {\n const result = await this.db\n .select()\n .from(worldTable)\n .where(eq(worldTable.agentId, this.agentId));\n return result.map((world) => this.mapWorldResult(world));\n });\n }\n\n /**\n * Asynchronously updates an existing world in the database based on the provided parameters.\n * @param {World} world - The world object to update.\n * @returns {Promise<void>} A Promise that resolves when the world is updated.\n */\n async updateWorld(world: World): Promise<void> {\n return this.withDatabase(async () => {\n const normalizedWorld = this.normalizeWorldData(world);\n delete normalizedWorld.id;\n await this.db\n .update(worldTable)\n .set(normalizedWorld)\n .where(and(eq(worldTable.id, world.id), eq(worldTable.agentId, this.agentId)));\n });\n }\n\n /**\n * Asynchronously removes a world from the database based on the provided parameters.\n * @param {UUID} id - The ID of the world to remove.\n * @returns {Promise<void>} A Promise that resolves when the world is removed.\n */\n async removeWorld(id: UUID): Promise<void> {\n return this.withDatabase(async () => {\n await this.db.delete(worldTable).where(eq(worldTable.id, id));\n });\n }\n\n /**\n * Asynchronously creates a new task in the database based on the provided parameters.\n * @param {Task} task - The task object to create.\n * @returns {Promise<UUID>} A Promise that resolves to the ID of the created task.\n */\n async createTask(task: Task): Promise<UUID> {\n // Default worldId to agentId for agent-internal tasks\n if (!task.worldId) {\n task = { ...task, worldId: this.agentId as UUID };\n }\n return this.withRetry(async () => {\n return this.withDatabase(async () => {\n const now = new Date();\n const metadata = task.metadata || {};\n\n const values = {\n id: task.id as UUID,\n name: task.name,\n description: task.description,\n roomId: task.roomId as UUID,\n worldId: task.worldId as UUID,\n tags: task.tags,\n metadata: metadata,\n createdAt: now,\n updatedAt: now,\n agentId: this.agentId as UUID,\n };\n\n const result = await this.db.insert(taskTable).values(values).returning();\n\n return result[0].id as UUID;\n });\n });\n }\n\n /**\n * Asynchronously retrieves tasks based on specified parameters.\n * @param params Object containing optional roomId, tags, and entityId to filter tasks\n * @returns Promise resolving to an array of Task objects\n */\n async getTasks(params: {\n roomId?: UUID;\n tags?: string[];\n entityId?: UUID; // Added entityId parameter\n }): Promise<Task[]> {\n return this.withRetry(async () => {\n return this.withDatabase(async () => {\n const result = await this.db\n .select()\n .from(taskTable)\n .where(\n and(\n eq(taskTable.agentId, this.agentId),\n ...(params.roomId ? [eq(taskTable.roomId, params.roomId)] : []),\n ...(params.tags && params.tags.length > 0\n ? [\n sql`${taskTable.tags} @> ARRAY[${sql.join(\n params.tags.map((t) => sql`${t}`),\n sql`, `\n )}]::text[]`,\n ]\n : [])\n )\n );\n\n return result.map((row) => ({\n id: row.id as UUID,\n name: row.name,\n description: row.description ?? \"\",\n roomId: row.roomId as UUID,\n worldId: row.worldId as UUID,\n tags: row.tags || [],\n metadata: row.metadata as TaskMetadata,\n }));\n });\n });\n }\n\n /**\n * Asynchronously retrieves a specific task by its name.\n * @param name The name of the task to retrieve\n * @returns Promise resolving to the Task object if found, null otherwise\n */\n async getTasksByName(name: string): Promise<Task[]> {\n return this.withRetry(async () => {\n return this.withDatabase(async () => {\n const result = await this.db\n .select()\n .from(taskTable)\n .where(and(eq(taskTable.name, name), eq(taskTable.agentId, this.agentId)));\n\n return result.map((row) => ({\n id: row.id as UUID,\n name: row.name,\n description: row.description ?? \"\",\n roomId: row.roomId as UUID,\n worldId: row.worldId as UUID,\n tags: row.tags || [],\n metadata: (row.metadata || {}) as TaskMetadata,\n }));\n });\n });\n }\n\n /**\n * Asynchronously retrieves a specific task by its ID.\n * @param id The UUID of the task to retrieve\n * @returns Promise resolving to the Task object if found, null otherwise\n */\n async getTask(id: UUID): Promise<Task | null> {\n return this.withRetry(async () => {\n return this.withDatabase(async () => {\n const result = await this.db\n .select()\n .from(taskTable)\n .where(and(eq(taskTable.id, id), eq(taskTable.agentId, this.agentId)))\n .limit(1);\n\n if (result.length === 0) {\n return null;\n }\n\n const row = result[0];\n return {\n id: row.id as UUID,\n name: row.name,\n description: row.description ?? \"\",\n roomId: row.roomId as UUID,\n worldId: row.worldId as UUID,\n tags: row.tags || [],\n metadata: (row.metadata || {}) as TaskMetadata,\n };\n });\n });\n }\n\n /**\n * Asynchronously updates an existing task in the database.\n * @param id The UUID of the task to update\n * @param task Partial Task object containing the fields to update\n * @returns Promise resolving when the update is complete\n */\n async updateTask(id: UUID, task: Partial<Task>): Promise<void> {\n await this.withRetry(async () => {\n await this.withDatabase(async () => {\n const updateValues: Partial<typeof taskTable.$inferInsert> = {};\n\n // Add fields to update if they exist in the partial task object\n if (task.name !== undefined) updateValues.name = task.name;\n if (task.description !== undefined) updateValues.description = task.description;\n if (task.roomId !== undefined) updateValues.roomId = task.roomId;\n if (task.worldId !== undefined) updateValues.worldId = task.worldId;\n if (task.tags !== undefined) updateValues.tags = task.tags;\n if (task.metadata !== undefined)\n updateValues.metadata = task.metadata as typeof taskTable.$inferInsert.metadata;\n // Handle createdAt if present in the task object (using type assertion for compatibility)\n const taskWithCreatedAt = task as {\n createdAt?: number | bigint | null;\n };\n if (taskWithCreatedAt.createdAt !== undefined && taskWithCreatedAt.createdAt !== null) {\n const createdAtValue = taskWithCreatedAt.createdAt;\n updateValues.createdAt = new Date(\n typeof createdAtValue === \"bigint\" ? Number(createdAtValue) : createdAtValue\n );\n }\n\n // Always update the updatedAt timestamp as a Date (schema uses Date, not number)\n const dbUpdateValues: Partial<typeof taskTable.$inferInsert> = {\n ...updateValues,\n updatedAt: new Date(),\n };\n\n // Handle metadata updates - just set it directly without merging\n if (task.metadata !== undefined) {\n dbUpdateValues.metadata = task.metadata;\n }\n\n await this.db\n .update(taskTable)\n // createdAt is hella borked, number / Date\n .set(dbUpdateValues)\n .where(and(eq(taskTable.id, id), eq(taskTable.agentId, this.agentId)));\n });\n });\n }\n\n /**\n * Asynchronously deletes a task from the database.\n * @param id The UUID of the task to delete\n * @returns Promise resolving when the deletion is complete\n */\n async deleteTask(id: UUID): Promise<void> {\n return this.withDatabase(async () => {\n await this.db.delete(taskTable).where(eq(taskTable.id, id));\n });\n }\n\n async getMemoriesByWorldId(params: {\n worldId: UUID;\n count?: number;\n tableName?: string;\n }): Promise<Memory[]> {\n return this.withDatabase(async () => {\n // First, get all rooms for the given worldId\n const rooms = await this.db\n .select({ id: roomTable.id })\n .from(roomTable)\n .where(and(eq(roomTable.worldId, params.worldId), eq(roomTable.agentId, this.agentId)));\n\n if (rooms.length === 0) {\n return [];\n }\n\n const roomIds = rooms.map((room) => room.id as UUID);\n\n const memories = await this.getMemoriesByRoomIds({\n roomIds,\n tableName: params.tableName || \"messages\",\n limit: params.count,\n });\n\n return memories;\n });\n }\n\n async deleteRoomsByWorldId(worldId: UUID): Promise<void> {\n return this.withDatabase(async () => {\n const rooms = await this.db\n .select({ id: roomTable.id })\n .from(roomTable)\n .where(and(eq(roomTable.worldId, worldId), eq(roomTable.agentId, this.agentId)));\n\n if (rooms.length === 0) {\n return;\n }\n\n const roomIds = rooms.map((room) => room.id as UUID);\n\n if (roomIds.length > 0) {\n await this.db.delete(logTable).where(inArray(logTable.roomId, roomIds));\n await this.db.delete(participantTable).where(inArray(participantTable.roomId, roomIds));\n\n const memoriesInRooms = await this.db\n .select({ id: memoryTable.id })\n .from(memoryTable)\n .where(inArray(memoryTable.roomId, roomIds));\n const memoryIdsInRooms = memoriesInRooms.map((m) => m.id as UUID);\n\n if (memoryIdsInRooms.length > 0) {\n await this.db\n .delete(embeddingTable)\n .where(inArray(embeddingTable.memoryId, memoryIdsInRooms));\n await this.db.delete(memoryTable).where(inArray(memoryTable.id, memoryIdsInRooms));\n }\n\n await this.db.delete(roomTable).where(inArray(roomTable.id, roomIds));\n\n logger.debug(\n {\n src: \"plugin:sql\",\n worldId,\n roomsDeleted: roomIds.length,\n memoriesDeleted: memoryIdsInRooms.length,\n },\n \"World cleanup completed\"\n );\n }\n });\n }\n\n // Message Server Database Operations\n\n /**\n * Creates a new message server in the central database\n */\n async createMessageServer(data: {\n id?: UUID; // Allow passing a specific ID\n name: string;\n sourceType: string;\n sourceId?: string;\n metadata?: Metadata;\n }): Promise<{\n id: UUID;\n name: string;\n sourceType: string;\n sourceId?: string;\n metadata?: Metadata;\n createdAt: Date;\n updatedAt: Date;\n }> {\n return this.withDatabase(async () => {\n const newId = data.id || (v4() as UUID);\n const now = new Date();\n const serverToInsert = {\n id: newId,\n name: data.name,\n sourceType: data.sourceType,\n sourceId: data.sourceId,\n metadata: data.metadata,\n createdAt: now,\n updatedAt: now,\n };\n\n await this.db.insert(messageServerTable).values(serverToInsert).onConflictDoNothing(); // In case the ID already exists\n\n // If server already existed, fetch it\n if (data.id) {\n const existing = await this.db\n .select()\n .from(messageServerTable)\n .where(eq(messageServerTable.id, data.id))\n .limit(1);\n if (existing.length > 0) {\n return {\n id: existing[0].id as UUID,\n name: existing[0].name,\n sourceType: existing[0].sourceType,\n sourceId: existing[0].sourceId || undefined,\n metadata: (existing[0].metadata || undefined) as Metadata | undefined,\n createdAt: existing[0].createdAt,\n updatedAt: existing[0].updatedAt,\n };\n }\n }\n\n return serverToInsert;\n });\n }\n\n /**\n * Gets all message servers\n */\n async getMessageServers(): Promise<\n Array<{\n id: UUID;\n name: string;\n sourceType: string;\n sourceId?: string;\n metadata?: Metadata;\n createdAt: Date;\n updatedAt: Date;\n }>\n > {\n const result = await this.withDatabase(async () => {\n const results = await this.db.select().from(messageServerTable);\n return results.map((r) => ({\n id: r.id as UUID,\n name: r.name,\n sourceType: r.sourceType,\n sourceId: r.sourceId || undefined,\n metadata: (r.metadata || undefined) as Metadata | undefined,\n createdAt: r.createdAt,\n updatedAt: r.updatedAt,\n }));\n });\n // Guard against null return\n return result || [];\n }\n\n /**\n * Gets a message server by ID\n */\n async getMessageServerById(serverId: UUID): Promise<{\n id: UUID;\n name: string;\n sourceType: string;\n sourceId?: string;\n metadata?: Metadata;\n createdAt: Date;\n updatedAt: Date;\n } | null> {\n return this.withDatabase(async () => {\n const results = await this.db\n .select()\n .from(messageServerTable)\n .where(eq(messageServerTable.id, serverId))\n .limit(1);\n return results.length > 0\n ? {\n id: results[0].id as UUID,\n name: results[0].name,\n sourceType: results[0].sourceType,\n sourceId: results[0].sourceId || undefined,\n metadata: (results[0].metadata || undefined) as Metadata | undefined,\n createdAt: results[0].createdAt,\n updatedAt: results[0].updatedAt,\n }\n : null;\n });\n }\n\n /**\n * Gets a message server by RLS server_id.\n * The server_id column is added dynamically when RLS is enabled.\n */\n async getMessageServerByRlsServerId(rlsServerId: UUID): Promise<{\n id: UUID;\n name: string;\n sourceType: string;\n sourceId?: string;\n metadata?: Metadata;\n createdAt: Date;\n updatedAt: Date;\n } | null> {\n return this.withDatabase(async () => {\n // Use raw SQL since server_id column is dynamically added by RLS and not in Drizzle schema\n const results = await this.db.execute(sql`\n SELECT id, name, source_type, source_id, metadata, created_at, updated_at\n FROM message_servers\n WHERE server_id = ${rlsServerId}\n LIMIT 1\n `);\n\n const rows = results.rows || results;\n return (rows as Record<string, unknown>[]).length > 0\n ? {\n id: (rows as Record<string, unknown>[])[0].id as UUID,\n name: (rows as Record<string, unknown>[])[0].name as string,\n sourceType: (rows as Record<string, unknown>[])[0].source_type as string,\n sourceId: ((rows as Record<string, unknown>[])[0].source_id || undefined) as\n | string\n | undefined,\n metadata: ((rows as Record<string, unknown>[])[0].metadata || undefined) as\n | Metadata\n | undefined,\n createdAt: new Date((rows as Record<string, unknown>[])[0].created_at as string),\n updatedAt: new Date((rows as Record<string, unknown>[])[0].updated_at as string),\n }\n : null;\n });\n }\n\n /**\n * Creates a new channel\n */\n async createChannel(\n data: {\n id?: UUID; // Allow passing a specific ID\n messageServerId: UUID;\n name: string;\n type: string;\n sourceType?: string;\n sourceId?: string;\n topic?: string;\n metadata?: Metadata;\n },\n participantIds?: UUID[]\n ): Promise<{\n id: UUID;\n messageServerId: UUID;\n name: string;\n type: string;\n sourceType?: string;\n sourceId?: string;\n topic?: string;\n metadata?: Metadata;\n createdAt: Date;\n updatedAt: Date;\n }> {\n return this.withDatabase(async () => {\n const newId = data.id || (v4() as UUID);\n const now = new Date();\n const channelToInsert = {\n id: newId,\n messageServerId: data.messageServerId,\n name: data.name,\n type: data.type,\n sourceType: data.sourceType,\n sourceId: data.sourceId,\n topic: data.topic,\n metadata: data.metadata,\n createdAt: now,\n updatedAt: now,\n };\n\n await this.db.transaction(async (tx) => {\n await tx.insert(channelTable).values(channelToInsert);\n\n if (participantIds && participantIds.length > 0) {\n const participantValues = participantIds.map((entityId) => ({\n channelId: newId,\n entityId: entityId,\n }));\n await tx.insert(channelParticipantsTable).values(participantValues).onConflictDoNothing();\n }\n });\n\n return channelToInsert;\n });\n }\n\n /**\n * Gets channels for a message server\n */\n async getChannelsForMessageServer(messageServerId: UUID): Promise<\n Array<{\n id: UUID;\n messageServerId: UUID;\n name: string;\n type: string;\n sourceType?: string;\n sourceId?: string;\n topic?: string;\n metadata?: Metadata;\n createdAt: Date;\n updatedAt: Date;\n }>\n > {\n return this.withDatabase(async () => {\n const results = await this.db\n .select()\n .from(channelTable)\n .where(eq(channelTable.messageServerId, messageServerId));\n return results.map((r) => ({\n id: r.id as UUID,\n messageServerId: r.messageServerId as UUID,\n name: r.name,\n type: r.type,\n sourceType: r.sourceType || undefined,\n sourceId: r.sourceId || undefined,\n topic: r.topic || undefined,\n metadata: (r.metadata || undefined) as Metadata | undefined,\n createdAt: r.createdAt,\n updatedAt: r.updatedAt,\n }));\n });\n }\n\n /**\n * Gets channel details\n */\n async getChannelDetails(channelId: UUID): Promise<{\n id: UUID;\n messageServerId: UUID;\n name: string;\n type: string;\n sourceType?: string;\n sourceId?: string;\n topic?: string;\n metadata?: Metadata;\n createdAt: Date;\n updatedAt: Date;\n } | null> {\n return this.withDatabase(async () => {\n const results = await this.db\n .select()\n .from(channelTable)\n .where(eq(channelTable.id, channelId))\n .limit(1);\n return results.length > 0\n ? {\n id: results[0].id as UUID,\n messageServerId: results[0].messageServerId as UUID,\n name: results[0].name,\n type: results[0].type,\n sourceType: results[0].sourceType || undefined,\n sourceId: results[0].sourceId || undefined,\n topic: results[0].topic || undefined,\n metadata: (results[0].metadata || undefined) as Metadata | undefined,\n createdAt: results[0].createdAt,\n updatedAt: results[0].updatedAt,\n }\n : null;\n });\n }\n\n /**\n * Creates a message\n */\n async createMessage(data: {\n channelId: UUID;\n authorId: UUID;\n content: string;\n rawMessage?: Record<string, unknown>;\n sourceType?: string;\n sourceId?: string;\n metadata?: Metadata;\n inReplyToRootMessageId?: UUID;\n messageId?: UUID;\n }): Promise<{\n id: UUID;\n channelId: UUID;\n authorId: UUID;\n content: string;\n rawMessage?: Record<string, unknown>;\n sourceType?: string;\n sourceId?: string;\n metadata?: Metadata;\n inReplyToRootMessageId?: UUID;\n createdAt: Date;\n updatedAt: Date;\n }> {\n return this.withDatabase(async () => {\n const newId = data.messageId || (v4() as UUID);\n const now = new Date();\n const messageToInsert = {\n id: newId,\n channelId: data.channelId,\n authorId: data.authorId,\n content: data.content,\n rawMessage: data.rawMessage,\n sourceType: data.sourceType,\n sourceId: data.sourceId,\n metadata: data.metadata,\n inReplyToRootMessageId: data.inReplyToRootMessageId,\n createdAt: now,\n updatedAt: now,\n };\n\n await this.db.insert(messageTable).values(messageToInsert);\n return messageToInsert;\n });\n }\n\n async getMessageById(id: UUID): Promise<{\n id: UUID;\n channelId: UUID;\n authorId: UUID;\n content: string;\n rawMessage?: Record<string, unknown>;\n sourceType?: string;\n sourceId?: string;\n metadata?: Metadata;\n inReplyToRootMessageId?: UUID;\n createdAt: Date;\n updatedAt: Date;\n } | null> {\n return this.withDatabase(async () => {\n const rows = await this.db\n .select()\n .from(messageTable)\n .where(eq(messageTable.id, id))\n .limit(1);\n if (!rows || rows.length === 0) return null;\n const row = rows[0];\n return {\n id: row.id as UUID,\n channelId: row.channelId as UUID,\n authorId: row.authorId as UUID,\n content: row.content,\n rawMessage: row.rawMessage || undefined,\n sourceType: row.sourceType || undefined,\n sourceId: row.sourceId || undefined,\n metadata: (row.metadata || undefined) as Metadata | undefined,\n inReplyToRootMessageId: (row.inReplyToRootMessageId || undefined) as UUID | undefined,\n createdAt: row.createdAt,\n updatedAt: row.updatedAt,\n };\n });\n }\n\n async updateMessage(\n id: UUID,\n patch: {\n content?: string;\n rawMessage?: Record<string, unknown>;\n sourceType?: string;\n sourceId?: string;\n metadata?: Metadata;\n inReplyToRootMessageId?: UUID;\n }\n ): Promise<{\n id: UUID;\n channelId: UUID;\n authorId: UUID;\n content: string;\n rawMessage?: Record<string, unknown>;\n sourceType?: string;\n sourceId?: string;\n metadata?: Metadata;\n inReplyToRootMessageId?: UUID;\n createdAt: Date;\n updatedAt: Date;\n } | null> {\n return this.withDatabase(async () => {\n const existing = await this.getMessageById(id);\n if (!existing) return null;\n\n const updatedAt = new Date();\n const next = {\n content: patch.content ?? existing.content,\n rawMessage: patch.rawMessage ?? existing.rawMessage,\n sourceType: patch.sourceType ?? existing.sourceType,\n sourceId: patch.sourceId ?? existing.sourceId,\n metadata: patch.metadata ?? existing.metadata,\n inReplyToRootMessageId: patch.inReplyToRootMessageId ?? existing.inReplyToRootMessageId,\n updatedAt,\n };\n\n await this.db.update(messageTable).set(next).where(eq(messageTable.id, id));\n\n // Return merged object\n return {\n ...existing,\n ...next,\n };\n });\n }\n\n /**\n * Gets messages for a channel\n */\n async getMessagesForChannel(\n channelId: UUID,\n limit: number = 50,\n beforeTimestamp?: Date\n ): Promise<\n Array<{\n id: UUID;\n channelId: UUID;\n authorId: UUID;\n content: string;\n rawMessage?: Record<string, unknown>;\n sourceType?: string;\n sourceId?: string;\n metadata?: Metadata;\n inReplyToRootMessageId?: UUID;\n createdAt: Date;\n updatedAt: Date;\n }>\n > {\n return this.withDatabase(async () => {\n const conditions = [eq(messageTable.channelId, channelId)];\n if (beforeTimestamp) {\n conditions.push(lt(messageTable.createdAt, beforeTimestamp));\n }\n\n const query = this.db\n .select()\n .from(messageTable)\n .where(and(...conditions))\n .orderBy(desc(messageTable.createdAt))\n .limit(limit);\n\n const results = await query;\n return results.map((r) => ({\n id: r.id as UUID,\n channelId: r.channelId as UUID,\n authorId: r.authorId as UUID,\n content: r.content,\n rawMessage: r.rawMessage || undefined,\n sourceType: r.sourceType || undefined,\n sourceId: r.sourceId || undefined,\n metadata: r.metadata || undefined,\n inReplyToRootMessageId: r.inReplyToRootMessageId as UUID | undefined,\n createdAt: r.createdAt,\n updatedAt: r.updatedAt,\n }));\n });\n }\n\n /**\n * Deletes a message\n */\n async deleteMessage(messageId: UUID): Promise<void> {\n return this.withDatabase(async () => {\n await this.db.delete(messageTable).where(eq(messageTable.id, messageId));\n });\n }\n\n /**\n * Updates a channel\n */\n async updateChannel(\n channelId: UUID,\n updates: {\n name?: string;\n participantCentralUserIds?: UUID[];\n metadata?: Metadata;\n }\n ): Promise<{\n id: UUID;\n messageServerId: UUID;\n name: string;\n type: string;\n sourceType?: string;\n sourceId?: string;\n topic?: string;\n metadata?: Metadata;\n createdAt: Date;\n updatedAt: Date;\n }> {\n return this.withDatabase(async () => {\n const now = new Date();\n\n await this.db.transaction(async (tx) => {\n // Update channel details\n const updateData: Record<string, unknown> = { updatedAt: now };\n if (updates.name !== undefined) updateData.name = updates.name;\n if (updates.metadata !== undefined) updateData.metadata = updates.metadata;\n\n await tx.update(channelTable).set(updateData).where(eq(channelTable.id, channelId));\n\n // Update participants if provided\n if (updates.participantCentralUserIds !== undefined) {\n // Remove existing participants\n await tx\n .delete(channelParticipantsTable)\n .where(eq(channelParticipantsTable.channelId, channelId));\n\n // Add new participants\n if (updates.participantCentralUserIds.length > 0) {\n const participantValues = updates.participantCentralUserIds.map((entityId) => ({\n channelId: channelId,\n entityId: entityId,\n }));\n await tx\n .insert(channelParticipantsTable)\n .values(participantValues)\n .onConflictDoNothing();\n }\n }\n });\n\n // Return updated channel details\n const updatedChannel = await this.getChannelDetails(channelId);\n if (!updatedChannel) {\n throw new Error(`Channel ${channelId} not found after update`);\n }\n return updatedChannel;\n });\n }\n\n /**\n * Deletes a channel and all its associated data\n */\n async deleteChannel(channelId: UUID): Promise<void> {\n return this.withDatabase(async () => {\n await this.db.transaction(async (tx) => {\n // Delete all messages in the channel (cascade delete will handle this, but explicit is better)\n await tx.delete(messageTable).where(eq(messageTable.channelId, channelId));\n\n // Delete all participants (cascade delete will handle this, but explicit is better)\n await tx\n .delete(channelParticipantsTable)\n .where(eq(channelParticipantsTable.channelId, channelId));\n\n // Delete the channel itself\n await tx.delete(channelTable).where(eq(channelTable.id, channelId));\n });\n });\n }\n\n /**\n * Adds participants to a channel\n */\n async addChannelParticipants(channelId: UUID, entityIds: UUID[]): Promise<void> {\n return this.withDatabase(async () => {\n if (!entityIds || entityIds.length === 0) return;\n\n const participantValues = entityIds.map((entityId) => ({\n channelId: channelId,\n entityId: entityId,\n }));\n\n await this.db\n .insert(channelParticipantsTable)\n .values(participantValues)\n .onConflictDoNothing();\n });\n }\n\n /**\n * Gets participants for a channel\n */\n async getChannelParticipants(channelId: UUID): Promise<UUID[]> {\n return this.withDatabase(async () => {\n const results = await this.db\n .select({ entityId: channelParticipantsTable.entityId })\n .from(channelParticipantsTable)\n .where(eq(channelParticipantsTable.channelId, channelId));\n\n return results.map((r) => r.entityId as UUID);\n });\n }\n\n /**\n * Check if an entity is a participant in a specific messaging channel.\n * @param {UUID} channelId - The ID of the channel to check.\n * @param {UUID} entityId - The ID of the entity to check.\n * @returns {Promise<boolean>} A Promise that resolves to true if entity is a participant.\n */\n async isChannelParticipant(channelId: UUID, entityId: UUID): Promise<boolean> {\n return this.withDatabase(async () => {\n const result = await this.db\n .select()\n .from(channelParticipantsTable)\n .where(\n and(\n eq(channelParticipantsTable.channelId, channelId),\n eq(channelParticipantsTable.entityId, entityId)\n )\n )\n .limit(1);\n\n return result.length > 0;\n });\n }\n\n /**\n * Adds an agent to a message server (Discord/Telegram server)\n */\n async addAgentToMessageServer(messageServerId: UUID, agentId: UUID): Promise<void> {\n return this.withDatabase(async () => {\n await this.db\n .insert(messageServerAgentsTable)\n .values({\n messageServerId,\n agentId,\n })\n .onConflictDoNothing();\n });\n }\n\n /**\n * Gets agents for a message server (Discord/Telegram server)\n */\n async getAgentsForMessageServer(messageServerId: UUID): Promise<UUID[]> {\n return this.withDatabase(async () => {\n const results = await this.db\n .select({ agentId: messageServerAgentsTable.agentId })\n .from(messageServerAgentsTable)\n .where(eq(messageServerAgentsTable.messageServerId, messageServerId));\n\n return results.map((r) => r.agentId as UUID);\n });\n }\n\n /**\n * Removes an agent from a message server (Discord/Telegram server)\n */\n async removeAgentFromMessageServer(messageServerId: UUID, agentId: UUID): Promise<void> {\n return this.withDatabase(async () => {\n await this.db\n .delete(messageServerAgentsTable)\n .where(\n and(\n eq(messageServerAgentsTable.messageServerId, messageServerId),\n eq(messageServerAgentsTable.agentId, agentId)\n )\n );\n });\n }\n\n /**\n * Finds or creates a DM channel between two users\n */\n async findOrCreateDmChannel(\n user1Id: UUID,\n user2Id: UUID,\n messageServerId: UUID\n ): Promise<{\n id: UUID;\n messageServerId: UUID;\n name: string;\n type: string;\n sourceType?: string;\n sourceId?: string;\n topic?: string;\n metadata?: Metadata;\n createdAt: Date;\n updatedAt: Date;\n }> {\n return this.withDatabase(async () => {\n const ids = [user1Id, user2Id].sort();\n const dmChannelName = `DM-${ids[0]}-${ids[1]}`;\n\n const existingChannels = await this.db\n .select()\n .from(channelTable)\n .where(\n and(\n eq(channelTable.type, ChannelType.DM),\n eq(channelTable.name, dmChannelName),\n eq(channelTable.messageServerId, messageServerId)\n )\n )\n .limit(1);\n\n if (existingChannels.length > 0) {\n return {\n id: existingChannels[0].id as UUID,\n messageServerId: existingChannels[0].messageServerId as UUID,\n name: existingChannels[0].name,\n type: existingChannels[0].type,\n sourceType: existingChannels[0].sourceType || undefined,\n sourceId: existingChannels[0].sourceId || undefined,\n topic: existingChannels[0].topic || undefined,\n metadata: (existingChannels[0].metadata || undefined) as Metadata | undefined,\n createdAt: existingChannels[0].createdAt,\n updatedAt: existingChannels[0].updatedAt,\n };\n }\n\n // Create new DM channel\n return this.createChannel(\n {\n messageServerId,\n name: dmChannelName,\n type: ChannelType.DM,\n metadata: { user1: ids[0], user2: ids[1] },\n },\n ids\n );\n });\n }\n\n // ===============================\n // Pairing Methods\n // ===============================\n\n /**\n * Get all pending pairing requests for a channel and agent.\n */\n async getPairingRequests(channel: PairingChannel, agentId: UUID): Promise<PairingRequest[]> {\n return this.withDatabase(async () => {\n const results = await this.db\n .select()\n .from(pairingRequestTable)\n .where(\n and(eq(pairingRequestTable.channel, channel), eq(pairingRequestTable.agentId, agentId))\n )\n .orderBy(pairingRequestTable.createdAt);\n\n return results.map((row) => ({\n id: row.id as UUID,\n channel: row.channel as PairingChannel,\n senderId: row.senderId,\n code: row.code,\n createdAt: row.createdAt,\n lastSeenAt: row.lastSeenAt,\n metadata: (row.metadata as Record<string, string>) || undefined,\n agentId: row.agentId as UUID,\n }));\n });\n }\n\n /**\n * Create a new pairing request.\n */\n async createPairingRequest(request: PairingRequest): Promise<UUID> {\n return this.withDatabase(async () => {\n const id = request.id || (v4() as UUID);\n await this.db.insert(pairingRequestTable).values({\n id,\n channel: request.channel,\n senderId: request.senderId,\n code: request.code,\n createdAt: request.createdAt,\n lastSeenAt: request.lastSeenAt,\n metadata: request.metadata || {},\n agentId: request.agentId,\n });\n return id;\n });\n }\n\n /**\n * Update an existing pairing request.\n */\n async updatePairingRequest(request: PairingRequest): Promise<void> {\n return this.withDatabase(async () => {\n await this.db\n .update(pairingRequestTable)\n .set({\n lastSeenAt: request.lastSeenAt,\n metadata: request.metadata || {},\n })\n .where(eq(pairingRequestTable.id, request.id));\n });\n }\n\n /**\n * Delete a pairing request by ID.\n */\n async deletePairingRequest(id: UUID): Promise<void> {\n return this.withDatabase(async () => {\n await this.db.delete(pairingRequestTable).where(eq(pairingRequestTable.id, id));\n });\n }\n\n /**\n * Get the allowlist for a channel and agent.\n */\n async getPairingAllowlist(\n channel: PairingChannel,\n agentId: UUID\n ): Promise<PairingAllowlistEntry[]> {\n return this.withDatabase(async () => {\n const results = await this.db\n .select()\n .from(pairingAllowlistTable)\n .where(\n and(\n eq(pairingAllowlistTable.channel, channel),\n eq(pairingAllowlistTable.agentId, agentId)\n )\n )\n .orderBy(pairingAllowlistTable.createdAt);\n\n return results.map((row) => ({\n id: row.id as UUID,\n channel: row.channel as PairingChannel,\n senderId: row.senderId,\n createdAt: row.createdAt,\n metadata: (row.metadata as Record<string, string>) || undefined,\n agentId: row.agentId as UUID,\n }));\n });\n }\n\n /**\n * Create a new allowlist entry.\n */\n async createPairingAllowlistEntry(entry: PairingAllowlistEntry): Promise<UUID> {\n return this.withDatabase(async () => {\n const id = entry.id || (v4() as UUID);\n await this.db\n .insert(pairingAllowlistTable)\n .values({\n id,\n channel: entry.channel,\n senderId: entry.senderId,\n createdAt: entry.createdAt,\n metadata: entry.metadata || {},\n agentId: entry.agentId,\n })\n .onConflictDoNothing();\n return id;\n });\n }\n\n /**\n * Delete an allowlist entry by ID.\n */\n async deletePairingAllowlistEntry(id: UUID): Promise<void> {\n return this.withDatabase(async () => {\n await this.db.delete(pairingAllowlistTable).where(eq(pairingAllowlistTable.id, id));\n });\n }\n}\n\n// Import tables at the end to avoid circular dependencies\n",
26
26
  "import validate from './validate.js';\nconst byteToHex = [];\nfor (let i = 0; i < 256; ++i) {\n byteToHex.push((i + 0x100).toString(16).slice(1));\n}\nexport function unsafeStringify(arr, offset = 0) {\n return (byteToHex[arr[offset + 0]] +\n byteToHex[arr[offset + 1]] +\n byteToHex[arr[offset + 2]] +\n byteToHex[arr[offset + 3]] +\n '-' +\n byteToHex[arr[offset + 4]] +\n byteToHex[arr[offset + 5]] +\n '-' +\n byteToHex[arr[offset + 6]] +\n byteToHex[arr[offset + 7]] +\n '-' +\n byteToHex[arr[offset + 8]] +\n byteToHex[arr[offset + 9]] +\n '-' +\n byteToHex[arr[offset + 10]] +\n byteToHex[arr[offset + 11]] +\n byteToHex[arr[offset + 12]] +\n byteToHex[arr[offset + 13]] +\n byteToHex[arr[offset + 14]] +\n byteToHex[arr[offset + 15]]).toLowerCase();\n}\nfunction stringify(arr, offset = 0) {\n const uuid = unsafeStringify(arr, offset);\n if (!validate(uuid)) {\n throw TypeError('Stringified UUID is invalid');\n }\n return uuid;\n}\nexport default stringify;\n",
27
27
  "let getRandomValues;\nconst rnds8 = new Uint8Array(16);\nexport default function rng() {\n if (!getRandomValues) {\n if (typeof crypto === 'undefined' || !crypto.getRandomValues) {\n throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');\n }\n getRandomValues = crypto.getRandomValues.bind(crypto);\n }\n return getRandomValues(rnds8);\n}\n",
28
28
  "const randomUUID = typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID.bind(crypto);\nexport default { randomUUID };\n",
@@ -48,7 +48,7 @@
48
48
  "import { sql } from \"drizzle-orm\";\nimport { jsonb, pgTable, text, timestamp, uuid } from \"drizzle-orm/pg-core\";\nimport { agentTable } from \"./agent\";\n\n/**\n * Represents a table schema for tasks in the database.\n *\n * @type {PgTable}\n */\nexport const taskTable = pgTable(\"tasks\", {\n id: uuid(\"id\").primaryKey().defaultRandom(),\n name: text(\"name\").notNull(),\n description: text(\"description\"),\n roomId: uuid(\"room_id\"),\n worldId: uuid(\"world_id\"),\n entityId: uuid(\"entity_id\"),\n agentId: uuid(\"agent_id\")\n .notNull()\n .references(() => agentTable.id, { onDelete: \"cascade\" }),\n tags: text(\"tags\").array().default(sql`'{}'::text[]`),\n metadata: jsonb(\"metadata\").default(sql`'{}'::jsonb`),\n createdAt: timestamp(\"created_at\", { withTimezone: true }).defaultNow(),\n updatedAt: timestamp(\"updated_at\", { withTimezone: true }).defaultNow(),\n});\n",
49
49
  "import { existsSync, mkdirSync, renameSync } from \"node:fs\";\nimport { PGlite, type PGliteOptions } from \"@electric-sql/pglite\";\nimport { fuzzystrmatch } from \"@electric-sql/pglite/contrib/fuzzystrmatch\";\nimport { vector } from \"@electric-sql/pglite/vector\";\nimport { logger } from \"@elizaos/core\";\nimport type { IDatabaseClientManager } from \"../types\";\n\nexport class PGliteClientManager implements IDatabaseClientManager<PGlite> {\n private client: PGlite;\n private options: PGliteOptions;\n private shuttingDown = false;\n private initialized = false;\n private initializePromise: Promise<void> | null = null;\n\n constructor(options: PGliteOptions) {\n this.options = options;\n this.client = this.createClient(options);\n this.setupShutdownHandlers();\n }\n\n public getConnection(): PGlite {\n return this.client;\n }\n\n public isShuttingDown(): boolean {\n return this.shuttingDown;\n }\n\n public async initialize(): Promise<void> {\n if (this.initialized) {\n return;\n }\n\n if (!this.initializePromise) {\n this.initializePromise = this.initializeInternal().finally(() => {\n this.initializePromise = null;\n });\n }\n\n await this.initializePromise;\n }\n\n public async close(): Promise<void> {\n this.shuttingDown = true;\n if (this.client) {\n try {\n await this.client.close();\n } catch {}\n }\n }\n\n private setupShutdownHandlers() {}\n\n private createClient(options: PGliteOptions): PGlite {\n return new PGlite({\n ...options,\n extensions: {\n ...(options.extensions ?? {}),\n vector,\n fuzzystrmatch,\n },\n });\n }\n\n private getDataDir(): string | null {\n const optionsWithDataDir = this.options as PGliteOptions & {\n dataDir?: unknown;\n dataPath?: unknown;\n };\n\n const dataDir = optionsWithDataDir.dataDir ?? optionsWithDataDir.dataPath;\n return typeof dataDir === \"string\" ? dataDir : null;\n }\n\n private isFileBackedDataDir(dataDir: string | null): dataDir is string {\n if (!dataDir) {\n return false;\n }\n\n if (dataDir.includes(\"://\")) {\n return false;\n }\n\n if (dataDir === \":memory:\") {\n return false;\n }\n\n return true;\n }\n\n private getErrorText(error: unknown): string {\n if (error instanceof Error) {\n return error.message;\n }\n return String(error);\n }\n\n private async initializeInternal(): Promise<void> {\n try {\n await this.client.query(\"CREATE SCHEMA IF NOT EXISTS migrations\");\n this.initialized = true;\n return;\n } catch (initialError) {\n const dataDir = this.getDataDir();\n if (!this.isFileBackedDataDir(dataDir)) {\n throw initialError;\n }\n\n const errorText = this.getErrorText(initialError);\n const backupDir = `${dataDir}.corrupt-${Date.now()}`;\n\n logger.error(\n {\n src: \"plugin:sql\",\n dataDir,\n backupDir,\n error: errorText,\n },\n \"PGlite initialization failed; attempting recovery with a clean data directory\"\n );\n\n try {\n await this.client.close();\n } catch {}\n\n if (existsSync(dataDir)) {\n renameSync(dataDir, backupDir);\n }\n mkdirSync(dataDir, { recursive: true });\n\n this.client = this.createClient(this.options);\n\n try {\n await this.client.query(\"CREATE SCHEMA IF NOT EXISTS migrations\");\n this.initialized = true;\n logger.warn(\n {\n src: \"plugin:sql\",\n dataDir,\n backupDir,\n },\n \"Recovered from corrupted PGlite database directory\"\n );\n } catch (recoveryError) {\n throw new Error(\n `PGlite recovery failed for ${dataDir}: ${this.getErrorText(recoveryError)}`\n );\n }\n }\n }\n}\n"
50
50
  ],
51
- "mappings": ";;;;;;;;;;;;;AACA;AACA;AAAA,IAOa;AAAA;AAAA,eAAa,QAAQ,UAAU;AAAA,IAC1C,IAAI,KAAK,IAAI,EAAE,WAAW,EAAE,cAAc;AAAA,IAC1C,SAAS,QAAQ,SAAS,EAAE,QAAQ,IAAI,EAAE,QAAQ;AAAA,IAClD,WAAW,KAAK,WAAW;AAAA,IAC3B,WAAW,UAAU,cAAc,EAAE,cAAc,KAAK,CAAC,EAAE,QAAQ,UAAU,EAAE,QAAQ;AAAA,IAEvF,WAAW,UAAU,cAAc,EAAE,cAAc,KAAK,CAAC,EAAE,QAAQ,UAAU,EAAE,QAAQ;AAAA,IAGvF,MAAM,KAAK,MAAM,EAAE,QAAQ;AAAA,IAC3B,UAAU,KAAK,UAAU;AAAA,IACzB,QAAQ,KAAK,QAAQ,EAAE,QAAQ,EAAE;AAAA,IACjC,KAAK,MAAM,KAAK,EAAE,MAAyB,EAAE,QAAQ,gBAAgB;AAAA,IACrE,iBAAiB,MAAM,kBAAkB,EACtC,MAA0B,EAC1B,QAAQ,gBAAgB,EACxB,QAAQ;AAAA,IACX,cAAc,MAAM,eAAe,EAAE,MAAgB,EAAE,QAAQ,gBAAgB,EAAE,QAAQ;AAAA,IACzF,QAAQ,MAAM,QAAQ,EAAE,MAAgB,EAAE,QAAQ,gBAAgB,EAAE,QAAQ;AAAA,IAC5E,YAAY,MAAM,YAAY,EAAE,M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