@elizaos/plugin-sql 2.0.0-alpha.19 → 2.0.0-alpha.20

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.
Files changed (108) hide show
  1. package/dist/base.d.ts +1102 -0
  2. package/dist/browser/index.browser.js +1526 -533
  3. package/dist/browser/index.browser.js.map +28 -18
  4. package/dist/browser/index.d.ts +2 -2
  5. package/dist/cjs/index.d.ts +2 -2
  6. package/dist/cjs/index.node.cjs +1934 -899
  7. package/dist/cjs/index.node.cjs.map +29 -15
  8. package/dist/index.d.ts +4 -2
  9. package/dist/index.js +2 -0
  10. package/dist/index.node.d.ts +17 -0
  11. package/dist/migration-service.d.ts +17 -0
  12. package/dist/migrations.d.ts +15 -0
  13. package/dist/node/index.d.ts +2 -2
  14. package/dist/node/index.node.js +1540 -490
  15. package/dist/node/index.node.js.map +29 -15
  16. package/dist/pg/adapter.d.ts +41 -0
  17. package/dist/pg/manager.d.ts +14 -0
  18. package/dist/pglite/adapter.d.ts +23 -0
  19. package/dist/pglite/errors.d.ts +20 -0
  20. package/dist/pglite/manager.d.ts +25 -0
  21. package/dist/rls.d.ts +13 -0
  22. package/dist/runtime-migrator/crypto-utils.d.ts +25 -0
  23. package/dist/runtime-migrator/drizzle-adapters/database-introspector.d.ts +58 -0
  24. package/dist/runtime-migrator/drizzle-adapters/diff-calculator.d.ts +77 -0
  25. package/dist/runtime-migrator/drizzle-adapters/snapshot-generator.d.ts +21 -0
  26. package/dist/runtime-migrator/drizzle-adapters/sql-generator.d.ts +38 -0
  27. package/dist/runtime-migrator/extension-manager.d.ts +6 -0
  28. package/dist/runtime-migrator/index.d.ts +8 -0
  29. package/dist/runtime-migrator/runtime-migrator.d.ts +95 -0
  30. package/dist/runtime-migrator/schema-transformer.d.ts +18 -0
  31. package/dist/runtime-migrator/storage/journal-storage.d.ts +10 -0
  32. package/dist/runtime-migrator/storage/migration-tracker.d.ts +13 -0
  33. package/dist/runtime-migrator/storage/snapshot-storage.d.ts +9 -0
  34. package/dist/runtime-migrator/types.d.ts +157 -0
  35. package/dist/schema/agent.d.ts +344 -0
  36. package/dist/schema/approvalRequests.d.ts +277 -0
  37. package/dist/schema/authAuditEvent.d.ts +153 -0
  38. package/dist/schema/authBootstrapJti.d.ts +49 -0
  39. package/dist/schema/authIdentity.d.ts +121 -0
  40. package/dist/schema/authOwnerBinding.d.ts +168 -0
  41. package/dist/schema/authOwnerLoginToken.d.ts +122 -0
  42. package/dist/schema/authSession.d.ts +225 -0
  43. package/dist/schema/cache.d.ts +97 -0
  44. package/dist/schema/channel.d.ts +177 -0
  45. package/dist/schema/channelParticipant.d.ts +41 -0
  46. package/dist/schema/component.d.ts +163 -0
  47. package/dist/schema/embedding.d.ts +204 -0
  48. package/dist/schema/entity.d.ts +125 -0
  49. package/dist/schema/entityIdentity.d.ts +577 -0
  50. package/dist/schema/index.d.ts +34 -0
  51. package/dist/schema/log.d.ts +114 -0
  52. package/dist/schema/longTermMemories.d.ts +254 -0
  53. package/dist/schema/memory.d.ts +185 -0
  54. package/dist/schema/memoryAccessLogs.d.ts +109 -0
  55. package/dist/schema/message.d.ts +194 -0
  56. package/dist/schema/messageServer.d.ts +126 -0
  57. package/dist/schema/messageServerAgent.d.ts +41 -0
  58. package/dist/schema/pairingAllowlist.d.ts +113 -0
  59. package/dist/schema/pairingRequest.d.ts +147 -0
  60. package/dist/schema/participant.d.ts +114 -0
  61. package/dist/schema/relationship.d.ts +156 -0
  62. package/dist/schema/room.d.ts +195 -0
  63. package/dist/schema/server.d.ts +64 -0
  64. package/dist/schema/sessionSummaries.d.ts +273 -0
  65. package/dist/schema/tasks.d.ts +225 -0
  66. package/dist/schema/types.d.ts +68 -0
  67. package/dist/schema/world.d.ts +114 -0
  68. package/dist/services/advanced-memory-storage.d.ts +36 -0
  69. package/dist/types.d.ts +13 -0
  70. package/dist/utils/string-to-uuid.d.ts +2 -0
  71. package/dist/utils.d.ts +4 -0
  72. package/dist/utils.node.d.ts +4 -0
  73. package/drizzle/index.ts +17 -0
  74. package/package.json +38 -18
  75. package/schema/agent.ts +50 -0
  76. package/schema/approvalRequests.ts +57 -0
  77. package/schema/authAuditEvent.ts +29 -0
  78. package/schema/authBootstrapJti.ts +18 -0
  79. package/schema/authIdentity.ts +35 -0
  80. package/schema/authOwnerBinding.ts +43 -0
  81. package/schema/authOwnerLoginToken.ts +50 -0
  82. package/schema/authSession.ts +44 -0
  83. package/schema/cache.ts +22 -0
  84. package/schema/channel.ts +19 -0
  85. package/schema/channelParticipant.ts +13 -0
  86. package/schema/component.ts +37 -0
  87. package/schema/embedding.ts +73 -0
  88. package/schema/entity.ts +28 -0
  89. package/schema/entityIdentity.ts +142 -0
  90. package/schema/index.ts +41 -0
  91. package/schema/log.ts +38 -0
  92. package/schema/longTermMemories.ts +27 -0
  93. package/schema/memory.ts +103 -0
  94. package/schema/memoryAccessLogs.ts +19 -0
  95. package/schema/message.ts +24 -0
  96. package/schema/messageServer.ts +12 -0
  97. package/schema/messageServerAgent.ts +16 -0
  98. package/schema/pairingAllowlist.ts +36 -0
  99. package/schema/pairingRequest.ts +46 -0
  100. package/schema/participant.ts +43 -0
  101. package/schema/relationship.ts +50 -0
  102. package/schema/room.ts +37 -0
  103. package/schema/server.ts +14 -0
  104. package/schema/sessionSummaries.ts +27 -0
  105. package/schema/tasks.ts +24 -0
  106. package/schema/types.ts +42 -0
  107. package/schema/world.ts +20 -0
  108. package/types.ts +19 -0
@@ -41,14 +41,14 @@ var init_agent = __esm(() => {
41
41
  });
42
42
 
43
43
  // schema/server.ts
44
- import { sql as sql17 } from "drizzle-orm";
45
- import { pgTable as pgTable19, timestamp as timestamp17, uuid as uuid17 } from "drizzle-orm/pg-core";
44
+ import { sql as sql22 } from "drizzle-orm";
45
+ import { pgTable as pgTable29, timestamp as timestamp21, uuid as uuid21 } from "drizzle-orm/pg-core";
46
46
  var serverTable;
47
47
  var init_server = __esm(() => {
48
- serverTable = pgTable19("servers", {
49
- id: uuid17("id").primaryKey(),
50
- createdAt: timestamp17("created_at", { withTimezone: true }).default(sql17`now()`).notNull(),
51
- updatedAt: timestamp17("updated_at", { withTimezone: true }).default(sql17`now()`).notNull()
48
+ serverTable = pgTable29("servers", {
49
+ id: uuid21("id").primaryKey(),
50
+ createdAt: timestamp21("created_at", { withTimezone: true }).default(sql22`now()`).notNull(),
51
+ updatedAt: timestamp21("updated_at", { withTimezone: true }).default(sql22`now()`).notNull()
52
52
  });
53
53
  });
54
54
 
@@ -56,27 +56,27 @@ var init_server = __esm(() => {
56
56
  function getDb(adapter) {
57
57
  return adapter.db;
58
58
  }
59
- function getRow(result, index7 = 0) {
60
- return result.rows[index7];
59
+ function getRow(result, index18 = 0) {
60
+ return result.rows[index18];
61
61
  }
62
62
 
63
63
  // migrations.ts
64
64
  import { logger } from "@elizaos/core";
65
- import { sql as sql19 } from "drizzle-orm";
65
+ import { sql as sql25 } from "drizzle-orm";
66
66
  function getRows(result) {
67
67
  return result.rows;
68
68
  }
69
69
  async function migrateToEntityRLS(adapter) {
70
70
  const db = getDb(adapter);
71
71
  try {
72
- await db.execute(sql19`SELECT 1 FROM pg_tables LIMIT 1`);
72
+ await db.execute(sql25`SELECT 1 FROM pg_tables LIMIT 1`);
73
73
  } catch {
74
74
  logger.debug("[Migration] ⊘ Not PostgreSQL, skipping PostgreSQL-specific migrations");
75
75
  return;
76
76
  }
77
77
  let schemaAlreadyMigrated = false;
78
78
  try {
79
- const migrationCheck = await db.execute(sql19`
79
+ const migrationCheck = await db.execute(sql25`
80
80
  SELECT column_name FROM information_schema.columns
81
81
  WHERE table_schema = 'public'
82
82
  AND table_name = 'rooms'
@@ -98,7 +98,7 @@ async function migrateToEntityRLS(adapter) {
98
98
  }
99
99
  logger.debug("[Migration] → Schema migrated but RLS disabled, cleaning up...");
100
100
  try {
101
- const tablesWithRls = await db.execute(sql19`
101
+ const tablesWithRls = await db.execute(sql25`
102
102
  SELECT c.relname as tablename
103
103
  FROM pg_class c
104
104
  JOIN pg_namespace n ON n.oid = c.relnamespace
@@ -111,7 +111,7 @@ async function migrateToEntityRLS(adapter) {
111
111
  for (const row of tablesWithRls.rows) {
112
112
  const tableName = row.tablename;
113
113
  try {
114
- await db.execute(sql19.raw(`ALTER TABLE "${tableName}" DISABLE ROW LEVEL SECURITY`));
114
+ await db.execute(sql25.raw(`ALTER TABLE "${tableName}" DISABLE ROW LEVEL SECURITY`));
115
115
  } catch {}
116
116
  }
117
117
  logger.debug(`[Migration] ✓ RLS cleanup completed (${tablesWithRls.rows.length} tables)`);
@@ -127,14 +127,14 @@ async function migrateToEntityRLS(adapter) {
127
127
  try {
128
128
  logger.debug("[Migration] → Clearing RuntimeMigrator snapshot cache...");
129
129
  try {
130
- await db.execute(sql19`DELETE FROM migrations._snapshots WHERE plugin_name = '@elizaos/plugin-sql'`);
130
+ await db.execute(sql25`DELETE FROM migrations._snapshots WHERE plugin_name = '@elizaos/plugin-sql'`);
131
131
  logger.debug("[Migration] ✓ Snapshot cache cleared");
132
132
  } catch (_error) {
133
133
  logger.debug("[Migration] ⊘ No snapshot cache to clear (migrations schema not yet created)");
134
134
  }
135
135
  logger.debug("[Migration] → Checking for Row Level Security to disable...");
136
136
  try {
137
- const tablesWithRls = await db.execute(sql19`
137
+ const tablesWithRls = await db.execute(sql25`
138
138
  SELECT c.relname as tablename
139
139
  FROM pg_class c
140
140
  JOIN pg_namespace n ON n.oid = c.relnamespace
@@ -147,7 +147,7 @@ async function migrateToEntityRLS(adapter) {
147
147
  for (const row of tablesWithRls.rows) {
148
148
  const tableName = row.tablename;
149
149
  try {
150
- await db.execute(sql19.raw(`ALTER TABLE "${tableName}" DISABLE ROW LEVEL SECURITY`));
150
+ await db.execute(sql25.raw(`ALTER TABLE "${tableName}" DISABLE ROW LEVEL SECURITY`));
151
151
  logger.debug(`[Migration] ✓ Disabled RLS on ${tableName}`);
152
152
  } catch (_error) {
153
153
  logger.debug(`[Migration] ⊘ Could not disable RLS on ${tableName}`);
@@ -163,7 +163,7 @@ async function migrateToEntityRLS(adapter) {
163
163
  const tablesToMigrate = ["channels", "worlds", "rooms"];
164
164
  for (const tableName of tablesToMigrate) {
165
165
  try {
166
- const columnsResult = await db.execute(sql19`
166
+ const columnsResult = await db.execute(sql25`
167
167
  SELECT column_name, data_type, is_nullable
168
168
  FROM information_schema.columns
169
169
  WHERE table_schema = 'public'
@@ -179,19 +179,19 @@ async function migrateToEntityRLS(adapter) {
179
179
  const oldColumnName = serverIdSnake ? "server_id" : "serverId";
180
180
  if (serverId && !messageServerId) {
181
181
  logger.debug(`[Migration] → Renaming ${tableName}.${oldColumnName} to message_server_id...`);
182
- await db.execute(sql19.raw(`ALTER TABLE "${tableName}" RENAME COLUMN "${oldColumnName}" TO "message_server_id"`));
182
+ await db.execute(sql25.raw(`ALTER TABLE "${tableName}" RENAME COLUMN "${oldColumnName}" TO "message_server_id"`));
183
183
  logger.debug(`[Migration] ✓ Renamed ${tableName}.${oldColumnName} → message_server_id`);
184
184
  if (serverId.data_type === "text") {
185
185
  try {
186
186
  logger.debug(`[Migration] → Dropping DEFAULT constraint on ${tableName}.message_server_id...`);
187
- await db.execute(sql19.raw(`ALTER TABLE "${tableName}" ALTER COLUMN "message_server_id" DROP DEFAULT`));
187
+ await db.execute(sql25.raw(`ALTER TABLE "${tableName}" ALTER COLUMN "message_server_id" DROP DEFAULT`));
188
188
  logger.debug(`[Migration] ✓ Dropped DEFAULT constraint`);
189
189
  } catch {
190
190
  logger.debug(`[Migration] ⊘ No DEFAULT constraint to drop on ${tableName}.message_server_id`);
191
191
  }
192
192
  try {
193
193
  logger.debug(`[Migration] → Converting ${tableName}.message_server_id from text to uuid...`);
194
- await db.execute(sql19.raw(`
194
+ await db.execute(sql25.raw(`
195
195
  ALTER TABLE "${tableName}"
196
196
  ALTER COLUMN "message_server_id" TYPE uuid
197
197
  USING CASE
@@ -208,29 +208,29 @@ async function migrateToEntityRLS(adapter) {
208
208
  }
209
209
  }
210
210
  if (tableName === "channels") {
211
- const nullCountResult = await db.execute(sql19.raw(`SELECT COUNT(*) as count FROM "${tableName}" WHERE "message_server_id" IS NULL`));
211
+ const nullCountResult = await db.execute(sql25.raw(`SELECT COUNT(*) as count FROM "${tableName}" WHERE "message_server_id" IS NULL`));
212
212
  const nullCount = nullCountResult.rows?.[0]?.count;
213
213
  if (nullCount && parseInt(nullCount, 10) > 0) {
214
214
  logger.warn(`[Migration] ⚠️ ${tableName} has ${nullCount} rows with NULL message_server_id - these will be deleted`);
215
- await db.execute(sql19.raw(`DELETE FROM "${tableName}" WHERE "message_server_id" IS NULL`));
215
+ await db.execute(sql25.raw(`DELETE FROM "${tableName}" WHERE "message_server_id" IS NULL`));
216
216
  logger.debug(`[Migration] ✓ Deleted ${nullCount} rows with NULL message_server_id from ${tableName}`);
217
217
  }
218
218
  logger.debug(`[Migration] → Making ${tableName}.message_server_id NOT NULL...`);
219
- await db.execute(sql19.raw(`ALTER TABLE "${tableName}" ALTER COLUMN "message_server_id" SET NOT NULL`));
219
+ await db.execute(sql25.raw(`ALTER TABLE "${tableName}" ALTER COLUMN "message_server_id" SET NOT NULL`));
220
220
  logger.debug(`[Migration] ✓ Set ${tableName}.message_server_id NOT NULL`);
221
221
  }
222
222
  } else if (serverId && messageServerId) {
223
223
  logger.debug(`[Migration] → ${tableName} has both columns, dropping ${oldColumnName}...`);
224
- await db.execute(sql19.raw(`ALTER TABLE "${tableName}" DROP COLUMN "${oldColumnName}" CASCADE`));
224
+ await db.execute(sql25.raw(`ALTER TABLE "${tableName}" DROP COLUMN "${oldColumnName}" CASCADE`));
225
225
  logger.debug(`[Migration] ✓ Dropped ${tableName}.${oldColumnName}`);
226
226
  } else if (!serverId && messageServerId) {
227
227
  if (messageServerId.data_type === "text") {
228
228
  logger.debug(`[Migration] → ${tableName}.message_server_id exists but is TEXT, needs UUID conversion...`);
229
229
  logger.debug(`[Migration] → Dropping DEFAULT constraint on ${tableName}.message_server_id...`);
230
- await db.execute(sql19.raw(`ALTER TABLE "${tableName}" ALTER COLUMN "message_server_id" DROP DEFAULT`));
230
+ await db.execute(sql25.raw(`ALTER TABLE "${tableName}" ALTER COLUMN "message_server_id" DROP DEFAULT`));
231
231
  logger.debug(`[Migration] ✓ Dropped DEFAULT constraint`);
232
232
  logger.debug(`[Migration] → Converting ${tableName}.message_server_id from text to uuid (generating UUIDs from text)...`);
233
- await db.execute(sql19.raw(`
233
+ await db.execute(sql25.raw(`
234
234
  ALTER TABLE "${tableName}"
235
235
  ALTER COLUMN "message_server_id" TYPE uuid
236
236
  USING CASE
@@ -252,7 +252,7 @@ async function migrateToEntityRLS(adapter) {
252
252
  }
253
253
  logger.debug("[Migration] → Dropping all remaining RLS-managed server_id columns...");
254
254
  try {
255
- const serverIdColumnsResult = await db.execute(sql19`
255
+ const serverIdColumnsResult = await db.execute(sql25`
256
256
  SELECT table_name
257
257
  FROM information_schema.columns
258
258
  WHERE table_schema = 'public'
@@ -274,7 +274,7 @@ async function migrateToEntityRLS(adapter) {
274
274
  for (const row of tablesToClean) {
275
275
  const tableName = row.table_name;
276
276
  try {
277
- await db.execute(sql19.raw(`ALTER TABLE "${tableName}" DROP COLUMN IF EXISTS server_id CASCADE`));
277
+ await db.execute(sql25.raw(`ALTER TABLE "${tableName}" DROP COLUMN IF EXISTS server_id CASCADE`));
278
278
  logger.debug(`[Migration] ✓ Dropped server_id from ${tableName}`);
279
279
  } catch (_error) {
280
280
  logger.debug(`[Migration] ⊘ Could not drop server_id from ${tableName}`);
@@ -285,7 +285,7 @@ async function migrateToEntityRLS(adapter) {
285
285
  }
286
286
  logger.debug("[Migration] → Checking agents.owner_id → server_id rename...");
287
287
  try {
288
- const agentsColumnsResult = await db.execute(sql19`
288
+ const agentsColumnsResult = await db.execute(sql25`
289
289
  SELECT column_name
290
290
  FROM information_schema.columns
291
291
  WHERE table_schema = 'public'
@@ -298,11 +298,11 @@ async function migrateToEntityRLS(adapter) {
298
298
  const hasServerId = agentsColumns.some((c) => c.column_name === "server_id");
299
299
  if (hasOwnerId && !hasServerId) {
300
300
  logger.debug("[Migration] → Renaming agents.owner_id to server_id...");
301
- await db.execute(sql19.raw(`ALTER TABLE "agents" RENAME COLUMN "owner_id" TO "server_id"`));
301
+ await db.execute(sql25.raw(`ALTER TABLE "agents" RENAME COLUMN "owner_id" TO "server_id"`));
302
302
  logger.debug("[Migration] ✓ Renamed agents.owner_id → server_id");
303
303
  } else if (hasOwnerId && hasServerId) {
304
304
  logger.debug("[Migration] → Both owner_id and server_id exist, dropping owner_id...");
305
- await db.execute(sql19.raw(`ALTER TABLE "agents" DROP COLUMN "owner_id" CASCADE`));
305
+ await db.execute(sql25.raw(`ALTER TABLE "agents" DROP COLUMN "owner_id" CASCADE`));
306
306
  logger.debug("[Migration] ✓ Dropped agents.owner_id");
307
307
  } else {
308
308
  logger.debug("[Migration] ⊘ agents table already has server_id (or no owner_id), skipping");
@@ -312,7 +312,7 @@ async function migrateToEntityRLS(adapter) {
312
312
  }
313
313
  logger.debug("[Migration] → Checking for owners → servers data migration...");
314
314
  try {
315
- const ownersTableResult = await db.execute(sql19`
315
+ const ownersTableResult = await db.execute(sql25`
316
316
  SELECT table_name
317
317
  FROM information_schema.tables
318
318
  WHERE table_schema = 'public'
@@ -320,7 +320,7 @@ async function migrateToEntityRLS(adapter) {
320
320
  `);
321
321
  if (ownersTableResult.rows && ownersTableResult.rows.length > 0) {
322
322
  logger.debug("[Migration] → Ensuring servers table exists...");
323
- await db.execute(sql19.raw(`
323
+ await db.execute(sql25.raw(`
324
324
  CREATE TABLE IF NOT EXISTS "servers" (
325
325
  "id" uuid PRIMARY KEY,
326
326
  "created_at" timestamp with time zone DEFAULT now() NOT NULL,
@@ -328,7 +328,7 @@ async function migrateToEntityRLS(adapter) {
328
328
  )
329
329
  `));
330
330
  logger.debug("[Migration] → Migrating owners data to servers...");
331
- await db.execute(sql19.raw(`
331
+ await db.execute(sql25.raw(`
332
332
  INSERT INTO "servers" ("id", "created_at", "updated_at")
333
333
  SELECT "id", COALESCE("created_at", now()), COALESCE("updated_at", now())
334
334
  FROM "owners"
@@ -336,7 +336,7 @@ async function migrateToEntityRLS(adapter) {
336
336
  `));
337
337
  logger.debug("[Migration] ✓ Migrated owners data to servers");
338
338
  logger.debug("[Migration] → Dropping obsolete owners table...");
339
- await db.execute(sql19.raw(`DROP TABLE IF EXISTS "owners" CASCADE`));
339
+ await db.execute(sql25.raw(`DROP TABLE IF EXISTS "owners" CASCADE`));
340
340
  logger.debug("[Migration] ✓ Dropped obsolete owners table");
341
341
  } else {
342
342
  logger.debug("[Migration] ⊘ owners table not found, skipping");
@@ -346,7 +346,7 @@ async function migrateToEntityRLS(adapter) {
346
346
  }
347
347
  logger.debug("[Migration] → Checking server_agents table rename...");
348
348
  try {
349
- const tablesResult = await db.execute(sql19`
349
+ const tablesResult = await db.execute(sql25`
350
350
  SELECT table_name
351
351
  FROM information_schema.tables
352
352
  WHERE table_schema = 'public'
@@ -358,16 +358,16 @@ async function migrateToEntityRLS(adapter) {
358
358
  const hasMessageServerAgents = tables.some((t) => t.table_name === "message_server_agents");
359
359
  if (hasServerAgents && !hasMessageServerAgents) {
360
360
  logger.debug("[Migration] → Renaming server_agents to message_server_agents...");
361
- await db.execute(sql19.raw(`ALTER TABLE "server_agents" RENAME TO "message_server_agents"`));
361
+ await db.execute(sql25.raw(`ALTER TABLE "server_agents" RENAME TO "message_server_agents"`));
362
362
  logger.debug("[Migration] ✓ Renamed server_agents → message_server_agents");
363
363
  logger.debug("[Migration] → Renaming message_server_agents.server_id to message_server_id...");
364
- await db.execute(sql19.raw(`ALTER TABLE "message_server_agents" RENAME COLUMN "server_id" TO "message_server_id"`));
364
+ await db.execute(sql25.raw(`ALTER TABLE "message_server_agents" RENAME COLUMN "server_id" TO "message_server_id"`));
365
365
  logger.debug("[Migration] ✓ Renamed message_server_agents.server_id → message_server_id");
366
366
  } else if (!hasServerAgents && !hasMessageServerAgents) {
367
367
  logger.debug("[Migration] ⊘ No server_agents table to migrate");
368
368
  } else if (hasMessageServerAgents) {
369
369
  logger.debug("[Migration] → Checking message_server_agents columns...");
370
- const columnsResult = await db.execute(sql19`
370
+ const columnsResult = await db.execute(sql25`
371
371
  SELECT column_name
372
372
  FROM information_schema.columns
373
373
  WHERE table_schema = 'public'
@@ -380,11 +380,11 @@ async function migrateToEntityRLS(adapter) {
380
380
  const hasMessageServerId = columns.some((c) => c.column_name === "message_server_id");
381
381
  if (hasServerId && !hasMessageServerId) {
382
382
  logger.debug("[Migration] → Renaming message_server_agents.server_id to message_server_id...");
383
- await db.execute(sql19.raw(`ALTER TABLE "message_server_agents" RENAME COLUMN "server_id" TO "message_server_id"`));
383
+ await db.execute(sql25.raw(`ALTER TABLE "message_server_agents" RENAME COLUMN "server_id" TO "message_server_id"`));
384
384
  logger.debug("[Migration] ✓ Renamed message_server_agents.server_id → message_server_id");
385
385
  } else if (!hasServerId && !hasMessageServerId) {
386
386
  logger.debug("[Migration] → message_server_agents exists without required columns, truncating...");
387
- await db.execute(sql19`TRUNCATE TABLE message_server_agents CASCADE`);
387
+ await db.execute(sql25`TRUNCATE TABLE message_server_agents CASCADE`);
388
388
  logger.debug("[Migration] ✓ Truncated message_server_agents");
389
389
  } else {
390
390
  logger.debug("[Migration] ⊘ message_server_agents already has correct schema");
@@ -395,7 +395,7 @@ async function migrateToEntityRLS(adapter) {
395
395
  }
396
396
  logger.debug("[Migration] → Checking channel_participants table...");
397
397
  try {
398
- const columnsResult = await db.execute(sql19`
398
+ const columnsResult = await db.execute(sql25`
399
399
  SELECT column_name
400
400
  FROM information_schema.columns
401
401
  WHERE table_schema = 'public'
@@ -410,11 +410,11 @@ async function migrateToEntityRLS(adapter) {
410
410
  const hasEntityId = columns.some((c) => c.column_name === "entity_id");
411
411
  if (hasUserId && !hasEntityId) {
412
412
  logger.debug("[Migration] → Renaming channel_participants.user_id to entity_id...");
413
- await db.execute(sql19.raw(`ALTER TABLE "channel_participants" RENAME COLUMN "user_id" TO "entity_id"`));
413
+ await db.execute(sql25.raw(`ALTER TABLE "channel_participants" RENAME COLUMN "user_id" TO "entity_id"`));
414
414
  logger.debug("[Migration] ✓ Renamed channel_participants.user_id → entity_id");
415
415
  } else if (!hasUserId && !hasEntityId) {
416
416
  logger.debug("[Migration] → channel_participants exists without entity_id or user_id, truncating...");
417
- await db.execute(sql19`TRUNCATE TABLE channel_participants CASCADE`);
417
+ await db.execute(sql25`TRUNCATE TABLE channel_participants CASCADE`);
418
418
  logger.debug("[Migration] ✓ Truncated channel_participants");
419
419
  } else {
420
420
  logger.debug("[Migration] ⊘ channel_participants already has entity_id column");
@@ -424,7 +424,7 @@ async function migrateToEntityRLS(adapter) {
424
424
  }
425
425
  logger.debug("[Migration] → Discovering and dropping all regular indexes...");
426
426
  try {
427
- const indexesResult = await db.execute(sql19`
427
+ const indexesResult = await db.execute(sql25`
428
428
  SELECT i.relname AS index_name
429
429
  FROM pg_index idx
430
430
  JOIN pg_class i ON i.oid = idx.indexrelid
@@ -441,7 +441,7 @@ async function migrateToEntityRLS(adapter) {
441
441
  for (const row of indexesToDrop) {
442
442
  const indexName = row.index_name;
443
443
  try {
444
- await db.execute(sql19.raw(`DROP INDEX IF EXISTS "${indexName}"`));
444
+ await db.execute(sql25.raw(`DROP INDEX IF EXISTS "${indexName}"`));
445
445
  logger.debug(`[Migration] ✓ Dropped index ${indexName}`);
446
446
  } catch (_error) {
447
447
  logger.debug(`[Migration] ⊘ Could not drop index ${indexName}`);
@@ -506,14 +506,14 @@ async function migrateToEntityRLS(adapter) {
506
506
  ];
507
507
  for (const rename of columnRenames) {
508
508
  try {
509
- const tableExistsResult = await db.execute(sql19`
509
+ const tableExistsResult = await db.execute(sql25`
510
510
  SELECT 1 FROM information_schema.tables
511
511
  WHERE table_schema = 'public' AND table_name = ${rename.table}
512
512
  `);
513
513
  if (!tableExistsResult.rows || tableExistsResult.rows.length === 0) {
514
514
  continue;
515
515
  }
516
- const columnsResult = await db.execute(sql19`
516
+ const columnsResult = await db.execute(sql25`
517
517
  SELECT column_name
518
518
  FROM information_schema.columns
519
519
  WHERE table_schema = 'public'
@@ -526,11 +526,11 @@ async function migrateToEntityRLS(adapter) {
526
526
  const hasNewColumn = columns.some((c) => c.column_name === rename.to);
527
527
  if (hasOldColumn && !hasNewColumn) {
528
528
  logger.debug(`[Migration] → Renaming ${rename.table}.${rename.from} to ${rename.to}...`);
529
- await db.execute(sql19.raw(`ALTER TABLE "${rename.table}" RENAME COLUMN "${rename.from}" TO "${rename.to}"`));
529
+ await db.execute(sql25.raw(`ALTER TABLE "${rename.table}" RENAME COLUMN "${rename.from}" TO "${rename.to}"`));
530
530
  logger.debug(`[Migration] ✓ Renamed ${rename.table}.${rename.from} → ${rename.to}`);
531
531
  } else if (hasOldColumn && hasNewColumn) {
532
532
  logger.debug(`[Migration] → Both columns exist, dropping ${rename.table}.${rename.from}...`);
533
- await db.execute(sql19.raw(`ALTER TABLE "${rename.table}" DROP COLUMN "${rename.from}" CASCADE`));
533
+ await db.execute(sql25.raw(`ALTER TABLE "${rename.table}" DROP COLUMN "${rename.from}" CASCADE`));
534
534
  logger.debug(`[Migration] ✓ Dropped ${rename.table}.${rename.from}`);
535
535
  }
536
536
  } catch (error) {
@@ -548,17 +548,17 @@ var init_migrations = () => {};
548
548
 
549
549
  // rls.ts
550
550
  import { logger as logger2, validateUuid } from "@elizaos/core";
551
- import { eq, sql as sql20 } from "drizzle-orm";
551
+ import { eq, sql as sql26 } from "drizzle-orm";
552
552
  async function installRLSFunctions(adapter) {
553
553
  const db = getDb(adapter);
554
- await db.execute(sql20`
554
+ await db.execute(sql26`
555
555
  CREATE TABLE IF NOT EXISTS servers (
556
556
  id UUID PRIMARY KEY,
557
557
  created_at TIMESTAMPTZ DEFAULT NOW() NOT NULL,
558
558
  updated_at TIMESTAMPTZ DEFAULT NOW() NOT NULL
559
559
  )
560
560
  `);
561
- await db.execute(sql20`
561
+ await db.execute(sql26`
562
562
  CREATE OR REPLACE FUNCTION current_server_id() RETURNS UUID AS $$
563
563
  DECLARE
564
564
  app_name TEXT;
@@ -573,7 +573,7 @@ async function installRLSFunctions(adapter) {
573
573
  END;
574
574
  $$ LANGUAGE plpgsql STABLE;
575
575
  `);
576
- await db.execute(sql20`
576
+ await db.execute(sql26`
577
577
  CREATE OR REPLACE FUNCTION add_server_isolation(
578
578
  schema_name text,
579
579
  table_name text
@@ -617,7 +617,7 @@ async function installRLSFunctions(adapter) {
617
617
  END;
618
618
  $$ LANGUAGE plpgsql;
619
619
  `);
620
- await db.execute(sql20`
620
+ await db.execute(sql26`
621
621
  CREATE OR REPLACE FUNCTION apply_rls_to_all_tables() RETURNS void AS $$
622
622
  DECLARE
623
623
  tbl record;
@@ -690,7 +690,7 @@ async function assignAgentToServer(adapter, agentId, serverId) {
690
690
  async function applyRLSToNewTables(adapter) {
691
691
  const db = getDb(adapter);
692
692
  try {
693
- await db.execute(sql20`SELECT apply_rls_to_all_tables()`);
693
+ await db.execute(sql26`SELECT apply_rls_to_all_tables()`);
694
694
  logger2.info({ src: "plugin:sql" }, "RLS applied to all tables");
695
695
  } catch (error) {
696
696
  logger2.warn({ src: "plugin:sql", error: String(error) }, "Failed to apply RLS to some tables");
@@ -699,7 +699,7 @@ async function applyRLSToNewTables(adapter) {
699
699
  async function uninstallRLS(adapter) {
700
700
  const db = getDb(adapter);
701
701
  try {
702
- const checkResult = await db.execute(sql20`
702
+ const checkResult = await db.execute(sql26`
703
703
  SELECT EXISTS (
704
704
  SELECT FROM pg_tables
705
705
  WHERE schemaname = 'public' AND tablename = 'servers'
@@ -716,7 +716,7 @@ async function uninstallRLS(adapter) {
716
716
  } catch (_entityRlsError) {
717
717
  logger2.debug({ src: "plugin:sql" }, "Entity RLS cleanup skipped (not installed or already cleaned)");
718
718
  }
719
- await db.execute(sql20`
719
+ await db.execute(sql26`
720
720
  CREATE OR REPLACE FUNCTION _temp_disable_rls_on_table(
721
721
  p_schema_name text,
722
722
  p_table_name text
@@ -740,7 +740,7 @@ async function uninstallRLS(adapter) {
740
740
  END;
741
741
  $$ LANGUAGE plpgsql;
742
742
  `);
743
- const tablesResult = await db.execute(sql20`
743
+ const tablesResult = await db.execute(sql26`
744
744
  SELECT schemaname, tablename
745
745
  FROM pg_tables
746
746
  WHERE schemaname = 'public'
@@ -750,19 +750,19 @@ async function uninstallRLS(adapter) {
750
750
  const schemaName = row.schemaname;
751
751
  const tableName = row.tablename;
752
752
  try {
753
- await db.execute(sql20`SELECT _temp_disable_rls_on_table(${schemaName}, ${tableName})`);
753
+ await db.execute(sql26`SELECT _temp_disable_rls_on_table(${schemaName}, ${tableName})`);
754
754
  logger2.debug({ src: "plugin:sql", schemaName, tableName }, "Disabled RLS on table");
755
755
  } catch (error) {
756
756
  logger2.warn({ src: "plugin:sql", schemaName, tableName, error: String(error) }, "Failed to disable RLS on table");
757
757
  }
758
758
  }
759
- await db.execute(sql20`DROP FUNCTION IF EXISTS _temp_disable_rls_on_table(text, text)`);
759
+ await db.execute(sql26`DROP FUNCTION IF EXISTS _temp_disable_rls_on_table(text, text)`);
760
760
  logger2.info({ src: "plugin:sql" }, "Keeping server_id values intact (prevents data theft on re-enable)");
761
761
  logger2.info({ src: "plugin:sql" }, "Clearing servers table...");
762
- await db.execute(sql20`TRUNCATE TABLE servers`);
763
- await db.execute(sql20`DROP FUNCTION IF EXISTS apply_rls_to_all_tables() CASCADE`);
764
- await db.execute(sql20`DROP FUNCTION IF EXISTS add_server_isolation(text, text) CASCADE`);
765
- await db.execute(sql20`DROP FUNCTION IF EXISTS current_server_id() CASCADE`);
762
+ await db.execute(sql26`TRUNCATE TABLE servers`);
763
+ await db.execute(sql26`DROP FUNCTION IF EXISTS apply_rls_to_all_tables() CASCADE`);
764
+ await db.execute(sql26`DROP FUNCTION IF EXISTS add_server_isolation(text, text) CASCADE`);
765
+ await db.execute(sql26`DROP FUNCTION IF EXISTS current_server_id() CASCADE`);
766
766
  logger2.info({ src: "plugin:sql" }, "Dropped all RLS functions");
767
767
  logger2.info({ src: "plugin:sql" }, "RLS disabled successfully (server_id columns preserved)");
768
768
  } catch (error) {
@@ -773,7 +773,7 @@ async function uninstallRLS(adapter) {
773
773
  async function installEntityRLS(adapter) {
774
774
  const db = getDb(adapter);
775
775
  logger2.info("[Entity RLS] Installing entity RLS functions and policies...");
776
- await db.execute(sql20`
776
+ await db.execute(sql26`
777
777
  CREATE OR REPLACE FUNCTION current_entity_id()
778
778
  RETURNS UUID AS $$
779
779
  DECLARE
@@ -795,7 +795,7 @@ async function installEntityRLS(adapter) {
795
795
  $$ LANGUAGE plpgsql STABLE;
796
796
  `);
797
797
  logger2.info("[Entity RLS] Created current_entity_id() function");
798
- await db.execute(sql20`
798
+ await db.execute(sql26`
799
799
  CREATE OR REPLACE FUNCTION add_entity_isolation(
800
800
  schema_name text,
801
801
  table_name text,
@@ -952,7 +952,7 @@ async function installEntityRLS(adapter) {
952
952
  $$ LANGUAGE plpgsql;
953
953
  `);
954
954
  logger2.info("[Entity RLS] Created add_entity_isolation() function");
955
- await db.execute(sql20`
955
+ await db.execute(sql26`
956
956
  CREATE OR REPLACE FUNCTION apply_entity_rls_to_all_tables() RETURNS void AS $$
957
957
  DECLARE
958
958
  tbl record;
@@ -996,7 +996,7 @@ async function installEntityRLS(adapter) {
996
996
  async function applyEntityRLSToAllTables(adapter) {
997
997
  const db = getDb(adapter);
998
998
  try {
999
- await db.execute(sql20`SELECT apply_entity_rls_to_all_tables()`);
999
+ await db.execute(sql26`SELECT apply_entity_rls_to_all_tables()`);
1000
1000
  logger2.info("[Entity RLS] Applied entity RLS to all eligible tables");
1001
1001
  } catch (error) {
1002
1002
  logger2.warn("[Entity RLS] Failed to apply entity RLS to some tables:", String(error));
@@ -1006,7 +1006,7 @@ async function uninstallEntityRLS(adapter) {
1006
1006
  const db = getDb(adapter);
1007
1007
  logger2.info("[Entity RLS] Removing entity RLS policies and functions...");
1008
1008
  try {
1009
- const tablesResult = await db.execute(sql20`
1009
+ const tablesResult = await db.execute(sql26`
1010
1010
  SELECT schemaname, tablename
1011
1011
  FROM pg_tables
1012
1012
  WHERE schemaname = 'public'
@@ -1016,15 +1016,15 @@ async function uninstallEntityRLS(adapter) {
1016
1016
  const schemaName = row.schemaname;
1017
1017
  const tableName = row.tablename;
1018
1018
  try {
1019
- await db.execute(sql20.raw(`DROP POLICY IF EXISTS entity_isolation_policy ON "${schemaName}"."${tableName}"`));
1019
+ await db.execute(sql26.raw(`DROP POLICY IF EXISTS entity_isolation_policy ON "${schemaName}"."${tableName}"`));
1020
1020
  logger2.debug(`[Entity RLS] Dropped entity_isolation_policy from ${schemaName}.${tableName}`);
1021
1021
  } catch (_error) {
1022
1022
  logger2.debug(`[Entity RLS] No entity policy on ${schemaName}.${tableName}`);
1023
1023
  }
1024
1024
  }
1025
- await db.execute(sql20`DROP FUNCTION IF EXISTS apply_entity_rls_to_all_tables() CASCADE`);
1026
- await db.execute(sql20`DROP FUNCTION IF EXISTS add_entity_isolation(text, text) CASCADE`);
1027
- await db.execute(sql20`DROP FUNCTION IF EXISTS current_entity_id() CASCADE`);
1025
+ await db.execute(sql26`DROP FUNCTION IF EXISTS apply_entity_rls_to_all_tables() CASCADE`);
1026
+ await db.execute(sql26`DROP FUNCTION IF EXISTS add_entity_isolation(text, text) CASCADE`);
1027
+ await db.execute(sql26`DROP FUNCTION IF EXISTS current_entity_id() CASCADE`);
1028
1028
  logger2.info("[Entity RLS] Entity RLS functions and policies removed successfully");
1029
1029
  } catch (error) {
1030
1030
  logger2.error("[Entity RLS] Failed to remove entity RLS:", String(error));
@@ -1062,9 +1062,53 @@ function stringToBigInt(str) {
1062
1062
  return lockId;
1063
1063
  }
1064
1064
 
1065
- // runtime-migrator/drizzle-adapters/database-introspector.ts
1065
+ // runtime-migrator/schema-transformer.ts
1066
1066
  import { logger as logger3 } from "@elizaos/core";
1067
- import { sql as sql21 } from "drizzle-orm";
1067
+ import { getTableConfig, pgSchema } from "drizzle-orm/pg-core";
1068
+ function deriveSchemaName(pluginName) {
1069
+ let schemaName = pluginName.replace(/^@[^/]+\//, "").replace(/^plugin-/, "").toLowerCase();
1070
+ schemaName = normalizeSchemaName(schemaName);
1071
+ const reserved = ["public", "pg_catalog", "information_schema", "migrations"];
1072
+ if (!schemaName || reserved.includes(schemaName)) {
1073
+ schemaName = `plugin_${normalizeSchemaName(pluginName.toLowerCase())}`;
1074
+ }
1075
+ if (!/^[a-z]/.test(schemaName)) {
1076
+ schemaName = `p_${schemaName}`;
1077
+ }
1078
+ if (schemaName.length > 63) {
1079
+ schemaName = schemaName.substring(0, 63);
1080
+ }
1081
+ return schemaName;
1082
+ }
1083
+ function normalizeSchemaName(input) {
1084
+ const chars = [];
1085
+ let prevWasUnderscore = false;
1086
+ for (let i = 0;i < input.length; i++) {
1087
+ const char = input[i];
1088
+ if (/[a-z0-9]/.test(char)) {
1089
+ chars.push(char);
1090
+ prevWasUnderscore = false;
1091
+ } else if (!prevWasUnderscore) {
1092
+ chars.push("_");
1093
+ prevWasUnderscore = true;
1094
+ }
1095
+ }
1096
+ const result = chars.join("");
1097
+ let start = 0;
1098
+ let end = result.length;
1099
+ while (start < end && result[start] === "_") {
1100
+ start++;
1101
+ }
1102
+ while (end > start && result[end - 1] === "_") {
1103
+ end--;
1104
+ }
1105
+ return result.slice(start, end);
1106
+ }
1107
+ var init_schema_transformer = () => {};
1108
+
1109
+ // runtime-migrator/drizzle-adapters/database-introspector.ts
1110
+ import { logger as logger4 } from "@elizaos/core";
1111
+ import { sql as sql27 } from "drizzle-orm";
1068
1112
  function getRows2(result) {
1069
1113
  return result.rows;
1070
1114
  }
@@ -1075,7 +1119,7 @@ class DatabaseIntrospector {
1075
1119
  this.db = db;
1076
1120
  }
1077
1121
  async introspectSchema(schemaName = "public") {
1078
- logger3.info({ src: "plugin:sql", schemaName }, "Starting database introspection");
1122
+ logger4.info({ src: "plugin:sql", schemaName }, "Starting database introspection");
1079
1123
  const tables = {};
1080
1124
  const schemas = {};
1081
1125
  const enums = {};
@@ -1083,7 +1127,7 @@ class DatabaseIntrospector {
1083
1127
  for (const tableInfo of allTables) {
1084
1128
  const tableName = tableInfo.table_name;
1085
1129
  const tableSchema = tableInfo.table_schema || "public";
1086
- logger3.debug({ src: "plugin:sql", tableSchema, tableName }, "Introspecting table");
1130
+ logger4.debug({ src: "plugin:sql", tableSchema, tableName }, "Introspecting table");
1087
1131
  const columns = await this.getColumns(tableSchema, tableName);
1088
1132
  const columnsObject = {};
1089
1133
  const uniqueConstraintObject = {};
@@ -1178,7 +1222,7 @@ class DatabaseIntrospector {
1178
1222
  }
1179
1223
  enums[key].values.push(enumInfo.value);
1180
1224
  }
1181
- logger3.info({ src: "plugin:sql", tableCount: Object.keys(tables).length }, "Database introspection complete");
1225
+ logger4.info({ src: "plugin:sql", tableCount: Object.keys(tables).length }, "Database introspection complete");
1182
1226
  return {
1183
1227
  version: "7",
1184
1228
  dialect: "postgresql",
@@ -1193,7 +1237,7 @@ class DatabaseIntrospector {
1193
1237
  };
1194
1238
  }
1195
1239
  async getTables(schemaName) {
1196
- const result = await this.db.execute(sql21`SELECT
1240
+ const result = await this.db.execute(sql27`SELECT
1197
1241
  table_schema,
1198
1242
  table_name
1199
1243
  FROM information_schema.tables
@@ -1203,7 +1247,7 @@ class DatabaseIntrospector {
1203
1247
  return getRows2(result);
1204
1248
  }
1205
1249
  async getColumns(schemaName, tableName) {
1206
- const result = await this.db.execute(sql21`SELECT
1250
+ const result = await this.db.execute(sql27`SELECT
1207
1251
  a.attname AS column_name,
1208
1252
  CASE
1209
1253
  WHEN a.attnotnull THEN 'NO'
@@ -1246,7 +1290,7 @@ class DatabaseIntrospector {
1246
1290
  return getRows2(result);
1247
1291
  }
1248
1292
  async getIndexes(schemaName, tableName) {
1249
- const result = await this.db.execute(sql21`SELECT
1293
+ const result = await this.db.execute(sql27`SELECT
1250
1294
  i.relname AS name,
1251
1295
  idx.indisunique AS is_unique,
1252
1296
  idx.indisprimary AS is_primary,
@@ -1270,7 +1314,7 @@ class DatabaseIntrospector {
1270
1314
  return getRows2(result);
1271
1315
  }
1272
1316
  async getForeignKeys(schemaName, tableName) {
1273
- const result = await this.db.execute(sql21`SELECT
1317
+ const result = await this.db.execute(sql27`SELECT
1274
1318
  con.conname AS name,
1275
1319
  att.attname AS column_name,
1276
1320
  fnsp.nspname AS foreign_table_schema,
@@ -1305,7 +1349,7 @@ class DatabaseIntrospector {
1305
1349
  return getRows2(result);
1306
1350
  }
1307
1351
  async getPrimaryKeys(schemaName, tableName) {
1308
- const result = await this.db.execute(sql21`SELECT
1352
+ const result = await this.db.execute(sql27`SELECT
1309
1353
  con.conname AS name,
1310
1354
  ARRAY(
1311
1355
  SELECT a.attname
@@ -1323,7 +1367,7 @@ class DatabaseIntrospector {
1323
1367
  return getRows2(result);
1324
1368
  }
1325
1369
  async getUniqueConstraints(schemaName, tableName) {
1326
- const result = await this.db.execute(sql21`SELECT
1370
+ const result = await this.db.execute(sql27`SELECT
1327
1371
  con.conname AS name,
1328
1372
  ARRAY(
1329
1373
  SELECT a.attname
@@ -1341,7 +1385,7 @@ class DatabaseIntrospector {
1341
1385
  return getRows2(result);
1342
1386
  }
1343
1387
  async getCheckConstraints(schemaName, tableName) {
1344
- const result = await this.db.execute(sql21`SELECT
1388
+ const result = await this.db.execute(sql27`SELECT
1345
1389
  con.conname AS name,
1346
1390
  pg_get_constraintdef(con.oid) AS definition
1347
1391
  FROM pg_constraint con
@@ -1353,7 +1397,7 @@ class DatabaseIntrospector {
1353
1397
  return getRows2(result);
1354
1398
  }
1355
1399
  async getEnums(schemaName) {
1356
- const result = await this.db.execute(sql21`SELECT
1400
+ const result = await this.db.execute(sql27`SELECT
1357
1401
  n.nspname AS schema,
1358
1402
  t.typname AS name,
1359
1403
  e.enumlabel AS value,
@@ -1384,8 +1428,8 @@ class DatabaseIntrospector {
1384
1428
  return defaultValue;
1385
1429
  }
1386
1430
  async hasExistingTables(pluginName) {
1387
- const schemaName = pluginName === "@elizaos/plugin-sql" ? "public" : this.deriveSchemaName(pluginName);
1388
- const result = await this.db.execute(sql21`SELECT COUNT(*) AS count
1431
+ const schemaName = pluginName === "@elizaos/plugin-sql" ? "public" : deriveSchemaName(pluginName);
1432
+ const result = await this.db.execute(sql27`SELECT COUNT(*) AS count
1389
1433
  FROM information_schema.tables
1390
1434
  WHERE table_schema = ${schemaName}
1391
1435
  AND table_type = 'BASE TABLE'`);
@@ -1393,11 +1437,10 @@ class DatabaseIntrospector {
1393
1437
  const count = parseInt(firstRow && firstRow.count || "0", 10);
1394
1438
  return count > 0;
1395
1439
  }
1396
- deriveSchemaName(pluginName) {
1397
- return pluginName.replace("@", "").replace("/", "_").replace(/-/g, "_").toLowerCase();
1398
- }
1399
1440
  }
1400
- var init_database_introspector = () => {};
1441
+ var init_database_introspector = __esm(() => {
1442
+ init_schema_transformer();
1443
+ });
1401
1444
 
1402
1445
  // runtime-migrator/drizzle-adapters/diff-calculator.ts
1403
1446
  var exports_diff_calculator = {};
@@ -1732,7 +1775,7 @@ function hasDiffChanges(diff) {
1732
1775
 
1733
1776
  // runtime-migrator/drizzle-adapters/snapshot-generator.ts
1734
1777
  import { is, SQL } from "drizzle-orm";
1735
- import { getTableConfig, PgDialect, PgTable } from "drizzle-orm/pg-core";
1778
+ import { getTableConfig as getTableConfig2, PgDialect, PgTable } from "drizzle-orm/pg-core";
1736
1779
  function escapeSingleQuotes(str) {
1737
1780
  return str.replace(/'/g, "''");
1738
1781
  }
@@ -1780,7 +1823,7 @@ async function generateSnapshot(schema) {
1780
1823
  const enums = {};
1781
1824
  const pgTables = extractTablesFromSchema(schema);
1782
1825
  for (const table of pgTables) {
1783
- const config = getTableConfig(table);
1826
+ const config = getTableConfig2(table);
1784
1827
  const {
1785
1828
  name: tableName,
1786
1829
  columns,
@@ -1836,7 +1879,7 @@ async function generateSnapshot(schema) {
1836
1879
  }
1837
1880
  const columnWithConfig = column;
1838
1881
  const columnConfig = columnWithConfig.config;
1839
- if (columnWithConfig.isUnique && columnConfig && columnConfig.uniqueName) {
1882
+ if (columnWithConfig.isUnique && columnConfig?.uniqueName) {
1840
1883
  uniqueConstraintObject[columnConfig.uniqueName] = {
1841
1884
  name: columnConfig.uniqueName,
1842
1885
  columns: [name],
@@ -1866,8 +1909,8 @@ async function generateSnapshot(schema) {
1866
1909
  const reference = fk.reference();
1867
1910
  const columnsFrom = reference.columns.map((it) => it.name);
1868
1911
  const columnsTo = reference.foreignColumns.map((it) => it.name);
1869
- const tableTo = getTableConfig(reference.foreignTable).name;
1870
- const schemaTo = getTableConfig(reference.foreignTable).schema || "public";
1912
+ const tableTo = getTableConfig2(reference.foreignTable).name;
1913
+ const schemaTo = getTableConfig2(reference.foreignTable).schema || "public";
1871
1914
  const name = fk.getName();
1872
1915
  foreignKeysObject[name] = {
1873
1916
  name,
@@ -1958,7 +2001,7 @@ function hasChanges(previousSnapshot, currentSnapshot) {
1958
2001
  const currHash = hashSnapshot(currentSnapshot);
1959
2002
  return prevHash !== currHash;
1960
2003
  }
1961
- var sqlToStr = (sql22, _casing) => {
2004
+ var sqlToStr = (sql28, _casing) => {
1962
2005
  const config = {
1963
2006
  escapeName: () => {
1964
2007
  throw new Error("we don't support params for `sql` default values");
@@ -1971,12 +2014,12 @@ var sqlToStr = (sql22, _casing) => {
1971
2014
  },
1972
2015
  casing: undefined
1973
2016
  };
1974
- return sql22.toQuery(config).sql;
2017
+ return sql28.toQuery(config).sql;
1975
2018
  };
1976
2019
  var init_snapshot_generator = () => {};
1977
2020
 
1978
2021
  // runtime-migrator/drizzle-adapters/sql-generator.ts
1979
- import { logger as logger4 } from "@elizaos/core";
2022
+ import { logger as logger5 } from "@elizaos/core";
1980
2023
  function checkForDataLoss(diff) {
1981
2024
  const result = {
1982
2025
  hasDataLoss: false,
@@ -2106,7 +2149,7 @@ async function generateMigrationSQL(previousSnapshot, currentSnapshot, diff) {
2106
2149
  }
2107
2150
  const dataLossCheck = checkForDataLoss(diff);
2108
2151
  if (dataLossCheck.warnings.length > 0) {
2109
- logger4.warn({ src: "plugin:sql", warnings: dataLossCheck.warnings }, "Schema changes may cause data loss");
2152
+ logger5.warn({ src: "plugin:sql", warnings: dataLossCheck.warnings }, "Schema changes may cause data loss");
2110
2153
  }
2111
2154
  const schemasToCreate = new Set;
2112
2155
  for (const tableName of diff.tables.created) {
@@ -2161,14 +2204,14 @@ async function generateMigrationSQL(previousSnapshot, currentSnapshot, diff) {
2161
2204
  const alterStatements = generateAlterColumnSQL(modified.table, modified.column, modified.changes);
2162
2205
  statements.push(...alterStatements);
2163
2206
  }
2164
- for (const index7 of diff.indexes.deleted) {
2165
- statements.push(generateDropIndexSQL(index7));
2207
+ for (const index18 of diff.indexes.deleted) {
2208
+ statements.push(generateDropIndexSQL(index18));
2166
2209
  }
2167
2210
  for (const alteredIndex of diff.indexes.altered) {
2168
2211
  statements.push(generateDropIndexSQL(alteredIndex.old));
2169
2212
  }
2170
- for (const index7 of diff.indexes.created) {
2171
- statements.push(generateCreateIndexSQL(index7));
2213
+ for (const index18 of diff.indexes.created) {
2214
+ statements.push(generateCreateIndexSQL(index18));
2172
2215
  }
2173
2216
  for (const alteredIndex of diff.indexes.altered) {
2174
2217
  statements.push(generateCreateIndexSQL(alteredIndex.new));
@@ -2270,18 +2313,18 @@ function generateCreateTableSQL(fullTableName, table) {
2270
2313
  return { tableSQL, fkSQLs };
2271
2314
  }
2272
2315
  function generateColumnDefinition(name, def) {
2273
- let sql22 = `"${name}" ${def.type}`;
2316
+ let sql28 = `"${name}" ${def.type}`;
2274
2317
  if (def.primaryKey && !def.type.includes("SERIAL")) {
2275
- sql22 += " PRIMARY KEY";
2318
+ sql28 += " PRIMARY KEY";
2276
2319
  }
2277
2320
  if (def.notNull) {
2278
- sql22 += " NOT NULL";
2321
+ sql28 += " NOT NULL";
2279
2322
  }
2280
2323
  if (def.default !== undefined) {
2281
2324
  const defaultValue = formatDefaultValue(def.default, def.type);
2282
- sql22 += ` DEFAULT ${defaultValue}`;
2325
+ sql28 += ` DEFAULT ${defaultValue}`;
2283
2326
  }
2284
- return sql22;
2327
+ return sql28;
2285
2328
  }
2286
2329
  function generateAddColumnSQL(table, column, definition) {
2287
2330
  const [schema, tableName] = table.includes(".") ? table.split(".") : ["public", table];
@@ -2417,28 +2460,28 @@ function formatDefaultValue(value, type) {
2417
2460
  }
2418
2461
  return String(value);
2419
2462
  }
2420
- function generateCreateIndexSQL(index7) {
2421
- const unique3 = index7.isUnique ? "UNIQUE " : "";
2422
- const method = index7.method || "btree";
2423
- const columns = index7.columns.map((c) => {
2463
+ function generateCreateIndexSQL(index18) {
2464
+ const unique4 = index18.isUnique ? "UNIQUE " : "";
2465
+ const method = index18.method || "btree";
2466
+ const columns = index18.columns.map((c) => {
2424
2467
  if (c.isExpression) {
2425
2468
  return c.expression;
2426
2469
  }
2427
2470
  return `"${c.expression}"${c.asc === false ? " DESC" : ""}`;
2428
2471
  }).join(", ");
2429
- const indexName = index7.name.includes(".") ? index7.name.split(".")[1] : index7.name;
2472
+ const indexName = index18.name.includes(".") ? index18.name.split(".")[1] : index18.name;
2430
2473
  let tableRef;
2431
- const indexTable = index7.table;
2474
+ const indexTable = index18.table;
2432
2475
  if (indexTable?.includes(".")) {
2433
2476
  const [schema, table] = indexTable.split(".");
2434
2477
  tableRef = `"${schema}"."${table}"`;
2435
2478
  } else {
2436
2479
  tableRef = `"${indexTable || ""}"`;
2437
2480
  }
2438
- return `CREATE ${unique3}INDEX "${indexName}" ON ${tableRef} USING ${method} (${columns});`;
2481
+ return `CREATE ${unique4}INDEX IF NOT EXISTS "${indexName}" ON ${tableRef} USING ${method} (${columns});`;
2439
2482
  }
2440
- function generateDropIndexSQL(index7) {
2441
- const indexNameFull = typeof index7 === "string" ? index7 : index7.name;
2483
+ function generateDropIndexSQL(index18) {
2484
+ const indexNameFull = typeof index18 === "string" ? index18 : index18.name;
2442
2485
  const indexName = indexNameFull.includes(".") ? indexNameFull.split(".")[1] : indexNameFull;
2443
2486
  return `DROP INDEX IF EXISTS "${indexName}";`;
2444
2487
  }
@@ -2454,12 +2497,12 @@ function generateCreateUniqueConstraintSQL(constraint) {
2454
2497
  const [schema, tableName] = table.includes(".") ? table.split(".") : ["public", table];
2455
2498
  const name = constraint.name;
2456
2499
  const columns = constraint.columns.map((c) => `"${c}"`).join(", ");
2457
- let sql22 = `ALTER TABLE "${schema}"."${tableName}" ADD CONSTRAINT "${name}" UNIQUE`;
2500
+ let sql28 = `ALTER TABLE "${schema}"."${tableName}" ADD CONSTRAINT "${name}" UNIQUE`;
2458
2501
  if (constraint.nullsNotDistinct) {
2459
- sql22 += ` NULLS NOT DISTINCT`;
2502
+ sql28 += ` NULLS NOT DISTINCT`;
2460
2503
  }
2461
- sql22 += ` (${columns});`;
2462
- return sql22;
2504
+ sql28 += ` (${columns});`;
2505
+ return sql28;
2463
2506
  }
2464
2507
  function generateDropUniqueConstraintSQL(constraint) {
2465
2508
  const table = constraint.table || "";
@@ -2484,14 +2527,14 @@ function buildCreateForeignKeyBodySQL(fk) {
2484
2527
  const tableFrom = fk.tableFrom;
2485
2528
  const columnsFrom = fk.columnsFrom.map((c) => `"${c}"`).join(", ");
2486
2529
  const columnsTo = fk.columnsTo.map((c) => `"${c}"`).join(", ");
2487
- let sql22 = `ALTER TABLE "${schemaFrom}"."${tableFrom}" ADD CONSTRAINT "${fk.name}" FOREIGN KEY (${columnsFrom}) REFERENCES "${schemaTo}"."${fk.tableTo}" (${columnsTo})`;
2530
+ let sql28 = `ALTER TABLE "${schemaFrom}"."${tableFrom}" ADD CONSTRAINT "${fk.name}" FOREIGN KEY (${columnsFrom}) REFERENCES "${schemaTo}"."${fk.tableTo}" (${columnsTo})`;
2488
2531
  if (fk.onDelete) {
2489
- sql22 += ` ON DELETE ${fk.onDelete}`;
2532
+ sql28 += ` ON DELETE ${fk.onDelete}`;
2490
2533
  }
2491
2534
  if (fk.onUpdate) {
2492
- sql22 += ` ON UPDATE ${fk.onUpdate}`;
2535
+ sql28 += ` ON UPDATE ${fk.onUpdate}`;
2493
2536
  }
2494
- return sql22;
2537
+ return sql28;
2495
2538
  }
2496
2539
  function wrapConstraintCreationGuard(constraintName, statement) {
2497
2540
  const escapedConstraintName = constraintName.replace(/'/g, "''");
@@ -2500,8 +2543,8 @@ function wrapConstraintCreationGuard(constraintName, statement) {
2500
2543
  var init_sql_generator = () => {};
2501
2544
 
2502
2545
  // runtime-migrator/extension-manager.ts
2503
- import { logger as logger5 } from "@elizaos/core";
2504
- import { sql as sql22 } from "drizzle-orm";
2546
+ import { logger as logger6 } from "@elizaos/core";
2547
+ import { sql as sql28 } from "drizzle-orm";
2505
2548
 
2506
2549
  class ExtensionManager {
2507
2550
  db;
@@ -2512,66 +2555,22 @@ class ExtensionManager {
2512
2555
  for (const extension of extensions) {
2513
2556
  try {
2514
2557
  if (!/^[a-zA-Z0-9_-]+$/.test(extension)) {
2515
- logger5.warn({ src: "plugin:sql", extension }, "Invalid extension name - contains invalid characters");
2558
+ logger6.warn({ src: "plugin:sql", extension }, "Invalid extension name - contains invalid characters");
2516
2559
  continue;
2517
2560
  }
2518
- await this.db.execute(sql22`CREATE EXTENSION IF NOT EXISTS ${sql22.identifier(extension)}`);
2519
- logger5.debug({ src: "plugin:sql", extension }, "Extension installed");
2561
+ await this.db.execute(sql28`CREATE EXTENSION IF NOT EXISTS ${sql28.identifier(extension)}`);
2562
+ logger6.debug({ src: "plugin:sql", extension }, "Extension installed");
2520
2563
  } catch (error) {
2521
2564
  const errorMessage = error instanceof Error ? error.message : String(error);
2522
- logger5.warn({ src: "plugin:sql", extension, error: errorMessage }, "Could not install extension");
2565
+ logger6.warn({ src: "plugin:sql", extension, error: errorMessage }, "Could not install extension");
2523
2566
  }
2524
2567
  }
2525
2568
  }
2526
2569
  }
2527
2570
  var init_extension_manager = () => {};
2528
2571
 
2529
- // runtime-migrator/schema-transformer.ts
2530
- import { logger as logger6 } from "@elizaos/core";
2531
- import { getTableConfig as getTableConfig2, pgSchema } from "drizzle-orm/pg-core";
2532
- function deriveSchemaName(pluginName) {
2533
- let schemaName = pluginName.replace(/^@[^/]+\//, "").replace(/^plugin-/, "").toLowerCase();
2534
- schemaName = normalizeSchemaName(schemaName);
2535
- const reserved = ["public", "pg_catalog", "information_schema", "migrations"];
2536
- if (!schemaName || reserved.includes(schemaName)) {
2537
- schemaName = `plugin_${normalizeSchemaName(pluginName.toLowerCase())}`;
2538
- }
2539
- if (!/^[a-z]/.test(schemaName)) {
2540
- schemaName = `p_${schemaName}`;
2541
- }
2542
- if (schemaName.length > 63) {
2543
- schemaName = schemaName.substring(0, 63);
2544
- }
2545
- return schemaName;
2546
- }
2547
- function normalizeSchemaName(input) {
2548
- const chars = [];
2549
- let prevWasUnderscore = false;
2550
- for (let i = 0;i < input.length; i++) {
2551
- const char = input[i];
2552
- if (/[a-z0-9]/.test(char)) {
2553
- chars.push(char);
2554
- prevWasUnderscore = false;
2555
- } else if (!prevWasUnderscore) {
2556
- chars.push("_");
2557
- prevWasUnderscore = true;
2558
- }
2559
- }
2560
- const result = chars.join("");
2561
- let start = 0;
2562
- let end = result.length;
2563
- while (start < end && result[start] === "_") {
2564
- start++;
2565
- }
2566
- while (end > start && result[end - 1] === "_") {
2567
- end--;
2568
- }
2569
- return result.slice(start, end);
2570
- }
2571
- var init_schema_transformer = () => {};
2572
-
2573
2572
  // runtime-migrator/storage/journal-storage.ts
2574
- import { sql as sql23 } from "drizzle-orm";
2573
+ import { sql as sql29 } from "drizzle-orm";
2575
2574
 
2576
2575
  class JournalStorage {
2577
2576
  db;
@@ -2579,7 +2578,7 @@ class JournalStorage {
2579
2578
  this.db = db;
2580
2579
  }
2581
2580
  async loadJournal(pluginName) {
2582
- const result = await this.db.execute(sql23`SELECT version, dialect, entries
2581
+ const result = await this.db.execute(sql29`SELECT version, dialect, entries
2583
2582
  FROM migrations._journal
2584
2583
  WHERE plugin_name = ${pluginName}`);
2585
2584
  if (result.rows.length === 0) {
@@ -2596,7 +2595,7 @@ class JournalStorage {
2596
2595
  };
2597
2596
  }
2598
2597
  async saveJournal(pluginName, journal) {
2599
- await this.db.execute(sql23`INSERT INTO migrations._journal (plugin_name, version, dialect, entries)
2598
+ await this.db.execute(sql29`INSERT INTO migrations._journal (plugin_name, version, dialect, entries)
2600
2599
  VALUES (${pluginName}, ${journal.version}, ${journal.dialect}, ${JSON.stringify(journal.entries)}::jsonb)
2601
2600
  ON CONFLICT (plugin_name)
2602
2601
  DO UPDATE SET
@@ -2638,7 +2637,7 @@ class JournalStorage {
2638
2637
  var init_journal_storage = () => {};
2639
2638
 
2640
2639
  // runtime-migrator/storage/migration-tracker.ts
2641
- import { sql as sql24 } from "drizzle-orm";
2640
+ import { sql as sql30 } from "drizzle-orm";
2642
2641
 
2643
2642
  class MigrationTracker {
2644
2643
  db;
@@ -2646,11 +2645,11 @@ class MigrationTracker {
2646
2645
  this.db = db;
2647
2646
  }
2648
2647
  async ensureSchema() {
2649
- await this.db.execute(sql24`CREATE SCHEMA IF NOT EXISTS migrations`);
2648
+ await this.db.execute(sql30`CREATE SCHEMA IF NOT EXISTS migrations`);
2650
2649
  }
2651
2650
  async ensureTables() {
2652
2651
  await this.ensureSchema();
2653
- await this.db.execute(sql24`
2652
+ await this.db.execute(sql30`
2654
2653
  CREATE TABLE IF NOT EXISTS migrations._migrations (
2655
2654
  id SERIAL PRIMARY KEY,
2656
2655
  plugin_name TEXT NOT NULL,
@@ -2658,7 +2657,7 @@ class MigrationTracker {
2658
2657
  created_at BIGINT NOT NULL
2659
2658
  )
2660
2659
  `);
2661
- await this.db.execute(sql24`
2660
+ await this.db.execute(sql30`
2662
2661
  CREATE TABLE IF NOT EXISTS migrations._journal (
2663
2662
  plugin_name TEXT PRIMARY KEY,
2664
2663
  version TEXT NOT NULL,
@@ -2666,7 +2665,7 @@ class MigrationTracker {
2666
2665
  entries JSONB NOT NULL DEFAULT '[]'
2667
2666
  )
2668
2667
  `);
2669
- await this.db.execute(sql24`
2668
+ await this.db.execute(sql30`
2670
2669
  CREATE TABLE IF NOT EXISTS migrations._snapshots (
2671
2670
  id SERIAL PRIMARY KEY,
2672
2671
  plugin_name TEXT NOT NULL,
@@ -2678,7 +2677,7 @@ class MigrationTracker {
2678
2677
  `);
2679
2678
  }
2680
2679
  async getLastMigration(pluginName) {
2681
- const result = await this.db.execute(sql24`SELECT id, hash, created_at
2680
+ const result = await this.db.execute(sql30`SELECT id, hash, created_at
2682
2681
  FROM migrations._migrations
2683
2682
  WHERE plugin_name = ${pluginName}
2684
2683
  ORDER BY created_at DESC
@@ -2686,14 +2685,14 @@ class MigrationTracker {
2686
2685
  return getRow(result) || null;
2687
2686
  }
2688
2687
  async recordMigration(pluginName, hash, createdAt) {
2689
- await this.db.execute(sql24`INSERT INTO migrations._migrations (plugin_name, hash, created_at)
2688
+ await this.db.execute(sql30`INSERT INTO migrations._migrations (plugin_name, hash, created_at)
2690
2689
  VALUES (${pluginName}, ${hash}, ${createdAt})`);
2691
2690
  }
2692
2691
  }
2693
2692
  var init_migration_tracker = () => {};
2694
2693
 
2695
2694
  // runtime-migrator/storage/snapshot-storage.ts
2696
- import { sql as sql25 } from "drizzle-orm";
2695
+ import { sql as sql31 } from "drizzle-orm";
2697
2696
 
2698
2697
  class SnapshotStorage {
2699
2698
  db;
@@ -2701,7 +2700,7 @@ class SnapshotStorage {
2701
2700
  this.db = db;
2702
2701
  }
2703
2702
  async saveSnapshot(pluginName, idx, snapshot) {
2704
- await this.db.execute(sql25`INSERT INTO migrations._snapshots (plugin_name, idx, snapshot)
2703
+ await this.db.execute(sql31`INSERT INTO migrations._snapshots (plugin_name, idx, snapshot)
2705
2704
  VALUES (${pluginName}, ${idx}, ${JSON.stringify(snapshot)}::jsonb)
2706
2705
  ON CONFLICT (plugin_name, idx)
2707
2706
  DO UPDATE SET
@@ -2709,7 +2708,7 @@ class SnapshotStorage {
2709
2708
  created_at = NOW()`);
2710
2709
  }
2711
2710
  async loadSnapshot(pluginName, idx) {
2712
- const result = await this.db.execute(sql25`SELECT snapshot
2711
+ const result = await this.db.execute(sql31`SELECT snapshot
2713
2712
  FROM migrations._snapshots
2714
2713
  WHERE plugin_name = ${pluginName} AND idx = ${idx}`);
2715
2714
  if (result.rows.length === 0) {
@@ -2718,7 +2717,7 @@ class SnapshotStorage {
2718
2717
  return result.rows[0].snapshot;
2719
2718
  }
2720
2719
  async getLatestSnapshot(pluginName) {
2721
- const result = await this.db.execute(sql25`SELECT snapshot
2720
+ const result = await this.db.execute(sql31`SELECT snapshot
2722
2721
  FROM migrations._snapshots
2723
2722
  WHERE plugin_name = ${pluginName}
2724
2723
  ORDER BY idx DESC
@@ -2729,7 +2728,7 @@ class SnapshotStorage {
2729
2728
  return result.rows[0].snapshot;
2730
2729
  }
2731
2730
  async getAllSnapshots(pluginName) {
2732
- const result = await this.db.execute(sql25`SELECT snapshot
2731
+ const result = await this.db.execute(sql31`SELECT snapshot
2733
2732
  FROM migrations._snapshots
2734
2733
  WHERE plugin_name = ${pluginName}
2735
2734
  ORDER BY idx ASC`);
@@ -2740,7 +2739,7 @@ var init_snapshot_storage = () => {};
2740
2739
 
2741
2740
  // runtime-migrator/runtime-migrator.ts
2742
2741
  import { logger as logger7 } from "@elizaos/core";
2743
- import { sql as sql26 } from "drizzle-orm";
2742
+ import { sql as sql32 } from "drizzle-orm";
2744
2743
 
2745
2744
  class RuntimeMigrator {
2746
2745
  db;
@@ -2778,7 +2777,7 @@ class RuntimeMigrator {
2778
2777
  }
2779
2778
  for (const schemaName of schemasToCreate) {
2780
2779
  logger7.debug({ src: "plugin:sql", schemaName }, "Ensuring schema exists");
2781
- await this.db.execute(sql26.raw(`CREATE SCHEMA IF NOT EXISTS "${schemaName}"`));
2780
+ await this.db.execute(sql32.raw(`CREATE SCHEMA IF NOT EXISTS "${schemaName}"`));
2782
2781
  }
2783
2782
  }
2784
2783
  validateSchemaUsage(pluginName, snapshot) {
@@ -2932,11 +2931,11 @@ class RuntimeMigrator {
2932
2931
  try {
2933
2932
  logger7.debug({ src: "plugin:sql", pluginName }, "Using PostgreSQL advisory locks");
2934
2933
  const lockIdStr = lockId.toString();
2935
- const lockResult = await this.db.execute(sql26`SELECT pg_try_advisory_lock(CAST(${lockIdStr} AS bigint)) as acquired`);
2934
+ const lockResult = await this.db.execute(sql32`SELECT pg_try_advisory_lock(CAST(${lockIdStr} AS bigint)) as acquired`);
2936
2935
  lockAcquired = getRow(lockResult)?.acquired === true;
2937
2936
  if (!lockAcquired) {
2938
2937
  logger7.info({ src: "plugin:sql", pluginName }, "Migration already in progress, waiting for lock");
2939
- await this.db.execute(sql26`SELECT pg_advisory_lock(CAST(${lockIdStr} AS bigint))`);
2938
+ await this.db.execute(sql32`SELECT pg_advisory_lock(CAST(${lockIdStr} AS bigint))`);
2940
2939
  lockAcquired = true;
2941
2940
  logger7.info({ src: "plugin:sql", pluginName }, "Lock acquired");
2942
2941
  } else {
@@ -3067,7 +3066,7 @@ class RuntimeMigrator {
3067
3066
  if (lockAcquired && isRealPostgres) {
3068
3067
  try {
3069
3068
  const lockIdStr = lockId.toString();
3070
- await this.db.execute(sql26`SELECT pg_advisory_unlock(CAST(${lockIdStr} AS bigint))`);
3069
+ await this.db.execute(sql32`SELECT pg_advisory_unlock(CAST(${lockIdStr} AS bigint))`);
3071
3070
  logger7.debug({ src: "plugin:sql", pluginName }, "Advisory lock released");
3072
3071
  } catch (unlockError) {
3073
3072
  logger7.warn({
@@ -3082,23 +3081,23 @@ class RuntimeMigrator {
3082
3081
  async executeMigration(pluginName, snapshot, hash, sqlStatements) {
3083
3082
  let transactionStarted = false;
3084
3083
  try {
3085
- await this.db.execute(sql26`BEGIN`);
3084
+ await this.db.execute(sql32`BEGIN`);
3086
3085
  transactionStarted = true;
3087
3086
  for (const stmt of sqlStatements) {
3088
3087
  logger7.debug({ src: "plugin:sql", statement: stmt }, "Executing SQL statement");
3089
- await this.db.execute(sql26.raw(stmt));
3088
+ await this.db.execute(sql32.raw(stmt));
3090
3089
  }
3091
3090
  const idx = await this.journalStorage.getNextIdx(pluginName);
3092
3091
  await this.migrationTracker.recordMigration(pluginName, hash, Date.now());
3093
3092
  const tag = this.generateMigrationTag(idx, pluginName);
3094
3093
  await this.journalStorage.updateJournal(pluginName, idx, tag, true);
3095
3094
  await this.snapshotStorage.saveSnapshot(pluginName, idx, snapshot);
3096
- await this.db.execute(sql26`COMMIT`);
3095
+ await this.db.execute(sql32`COMMIT`);
3097
3096
  logger7.info({ src: "plugin:sql", pluginName, tag }, "Recorded migration");
3098
3097
  } catch (error) {
3099
3098
  if (transactionStarted) {
3100
3099
  try {
3101
- await this.db.execute(sql26`ROLLBACK`);
3100
+ await this.db.execute(sql32`ROLLBACK`);
3102
3101
  logger7.error({
3103
3102
  src: "plugin:sql",
3104
3103
  error: error instanceof Error ? error.message : String(error)
@@ -3115,8 +3114,8 @@ class RuntimeMigrator {
3115
3114
  }
3116
3115
  generateMigrationTag(idx, pluginName) {
3117
3116
  const prefix = idx.toString().padStart(4, "0");
3118
- const timestamp19 = Date.now().toString(36);
3119
- return `${prefix}_${pluginName}_${timestamp19}`;
3117
+ const timestamp24 = Date.now().toString(36);
3118
+ return `${prefix}_${pluginName}_${timestamp24}`;
3120
3119
  }
3121
3120
  async getStatus(pluginName) {
3122
3121
  const lastMigration = await this.migrationTracker.getLastMigration(pluginName);
@@ -3131,9 +3130,9 @@ class RuntimeMigrator {
3131
3130
  }
3132
3131
  async reset(pluginName) {
3133
3132
  logger7.warn({ src: "plugin:sql", pluginName }, "Resetting migrations");
3134
- await this.db.execute(sql26`DELETE FROM migrations._migrations WHERE plugin_name = ${pluginName}`);
3135
- await this.db.execute(sql26`DELETE FROM migrations._journal WHERE plugin_name = ${pluginName}`);
3136
- await this.db.execute(sql26`DELETE FROM migrations._snapshots WHERE plugin_name = ${pluginName}`);
3133
+ await this.db.execute(sql32`DELETE FROM migrations._migrations WHERE plugin_name = ${pluginName}`);
3134
+ await this.db.execute(sql32`DELETE FROM migrations._journal WHERE plugin_name = ${pluginName}`);
3135
+ await this.db.execute(sql32`DELETE FROM migrations._snapshots WHERE plugin_name = ${pluginName}`);
3137
3136
  logger7.warn({ src: "plugin:sql", pluginName }, "Reset complete");
3138
3137
  }
3139
3138
  async checkMigration(pluginName, schema) {
@@ -3289,8 +3288,8 @@ var init_migration_service = __esm(() => {
3289
3288
  });
3290
3289
 
3291
3290
  // index.ts
3292
- import { mkdirSync as mkdirSync2 } from "node:fs";
3293
- import { logger as logger14, stringToUuid } from "@elizaos/core";
3291
+ import { mkdirSync } from "node:fs";
3292
+ import { logger as logger14 } from "@elizaos/core";
3294
3293
 
3295
3294
  // pg/adapter.ts
3296
3295
  import {
@@ -3314,12 +3313,10 @@ import {
3314
3313
  lt,
3315
3314
  lte,
3316
3315
  or,
3317
- sql as sql27
3316
+ sql as sql33
3318
3317
  } from "drizzle-orm";
3319
- import { v4 } from "uuid";
3320
3318
 
3321
3319
  // schema/embedding.ts
3322
- import { VECTOR_DIMS } from "@elizaos/core";
3323
3320
  import { relations, sql as sql5 } from "drizzle-orm";
3324
3321
  import { check as check2, foreignKey as foreignKey2, index as index2, pgTable as pgTable5, timestamp as timestamp5, uuid as uuid5, vector } from "drizzle-orm/pg-core";
3325
3322
 
@@ -3432,6 +3429,14 @@ var memoryTable = pgTable4("memories", {
3432
3429
  ]);
3433
3430
 
3434
3431
  // schema/embedding.ts
3432
+ var VECTOR_DIMS = {
3433
+ SMALL: 384,
3434
+ MEDIUM: 512,
3435
+ LARGE: 768,
3436
+ XL: 1024,
3437
+ XXL: 1536,
3438
+ XXXL: 3072
3439
+ };
3435
3440
  var DIMENSION_MAP = {
3436
3441
  [VECTOR_DIMS.SMALL]: "dim384",
3437
3442
  [VECTOR_DIMS.MEDIUM]: "dim512",
@@ -3471,6 +3476,7 @@ var exports_schema = {};
3471
3476
  __export(exports_schema, {
3472
3477
  worldTable: () => worldTable,
3473
3478
  taskTable: () => taskTable,
3479
+ sessionSummaries: () => sessionSummaries,
3474
3480
  serverTable: () => serverTable,
3475
3481
  roomTable: () => roomTable,
3476
3482
  relationshipTable: () => relationshipTable,
@@ -3481,203 +3487,484 @@ __export(exports_schema, {
3481
3487
  messageServerTable: () => messageServerTable,
3482
3488
  messageServerAgentsTable: () => messageServerAgentsTable,
3483
3489
  memoryTable: () => memoryTable,
3490
+ memoryAccessLogs: () => memoryAccessLogs,
3491
+ longTermMemories: () => longTermMemories,
3484
3492
  logTable: () => logTable,
3493
+ factCandidateTable: () => factCandidateTable,
3485
3494
  entityTable: () => entityTable,
3495
+ entityMergeCandidateTable: () => entityMergeCandidateTable,
3496
+ entityIdentityTable: () => entityIdentityTable,
3486
3497
  embeddingTable: () => embeddingTable,
3487
3498
  componentTable: () => componentTable,
3488
3499
  channelTable: () => channelTable,
3489
3500
  channelParticipantsTable: () => channelParticipantsTable,
3490
3501
  cacheTable: () => cacheTable,
3502
+ authSessionTable: () => authSessionTable,
3503
+ authOwnerLoginTokenTable: () => authOwnerLoginTokenTable,
3504
+ authOwnerBindingTable: () => authOwnerBindingTable,
3505
+ authIdentityTable: () => authIdentityTable,
3506
+ authIdentityCreatedAtDefault: () => authIdentityCreatedAtDefault,
3507
+ authBootstrapJtiSeenTable: () => authBootstrapJtiSeenTable,
3508
+ authAuditEventTable: () => authAuditEventTable,
3509
+ approvalRequestTable: () => approvalRequestTable,
3491
3510
  agentTable: () => agentTable
3492
3511
  });
3493
3512
 
3494
- // schema/cache.ts
3513
+ // schema/approvalRequests.ts
3495
3514
  init_agent();
3496
3515
  import { sql as sql6 } from "drizzle-orm";
3497
- import { jsonb as jsonb5, pgTable as pgTable6, primaryKey, text as text5, timestamp as timestamp6, uuid as uuid6 } from "drizzle-orm/pg-core";
3498
- var cacheTable = pgTable6("cache", {
3499
- key: text5("key").notNull(),
3516
+ import { index as index3, jsonb as jsonb5, pgTable as pgTable6, text as text5, timestamp as timestamp6, uuid as uuid6 } from "drizzle-orm/pg-core";
3517
+ var approvalRequestTable = pgTable6("approval_requests", {
3518
+ id: uuid6("id").primaryKey().defaultRandom(),
3519
+ state: text5("state").notNull(),
3520
+ requestedBy: text5("requested_by").notNull(),
3521
+ subjectUserId: text5("subject_user_id").notNull(),
3522
+ action: text5("action").notNull(),
3523
+ payload: jsonb5("payload").notNull(),
3524
+ channel: text5("channel").notNull(),
3525
+ reason: text5("reason").notNull(),
3526
+ expiresAt: timestamp6("expires_at", { withTimezone: true }).notNull(),
3527
+ resolvedAt: timestamp6("resolved_at", { withTimezone: true }),
3528
+ resolvedBy: text5("resolved_by"),
3529
+ resolutionReason: text5("resolution_reason"),
3500
3530
  agentId: uuid6("agent_id").notNull().references(() => agentTable.id, { onDelete: "cascade" }),
3501
- value: jsonb5("value").notNull(),
3502
3531
  createdAt: timestamp6("created_at", { withTimezone: true }).default(sql6`now()`).notNull(),
3503
- expiresAt: timestamp6("expires_at", { withTimezone: true })
3532
+ updatedAt: timestamp6("updated_at", { withTimezone: true }).default(sql6`now()`).notNull()
3533
+ }, (table) => [
3534
+ index3("approval_requests_subject_state_idx").on(table.subjectUserId, table.state),
3535
+ index3("approval_requests_agent_state_idx").on(table.agentId, table.state),
3536
+ index3("approval_requests_state_expires_idx").on(table.state, table.expiresAt)
3537
+ ]);
3538
+ // schema/authAuditEvent.ts
3539
+ import { bigint, index as index4, jsonb as jsonb6, pgTable as pgTable7, text as text6 } from "drizzle-orm/pg-core";
3540
+ var authAuditEventTable = pgTable7("auth_audit_events", {
3541
+ id: text6("id").primaryKey(),
3542
+ ts: bigint("ts", { mode: "number" }).notNull(),
3543
+ actorIdentityId: text6("actor_identity_id"),
3544
+ ip: text6("ip"),
3545
+ userAgent: text6("user_agent"),
3546
+ action: text6("action").notNull(),
3547
+ outcome: text6("outcome").notNull(),
3548
+ metadata: jsonb6("metadata").$type().notNull()
3549
+ }, (table) => [
3550
+ index4("auth_audit_events_action_idx").on(table.action),
3551
+ index4("auth_audit_events_ts_idx").on(table.ts),
3552
+ index4("auth_audit_events_actor_idx").on(table.actorIdentityId)
3553
+ ]);
3554
+ // schema/authBootstrapJti.ts
3555
+ import { bigint as bigint2, index as index5, pgTable as pgTable8, text as text7 } from "drizzle-orm/pg-core";
3556
+ var authBootstrapJtiSeenTable = pgTable8("auth_bootstrap_jti_seen", {
3557
+ jti: text7("jti").primaryKey(),
3558
+ seenAt: bigint2("seen_at", { mode: "number" }).notNull()
3559
+ }, (table) => [index5("auth_bootstrap_jti_seen_at_idx").on(table.seenAt)]);
3560
+ // schema/authIdentity.ts
3561
+ import { sql as sql7 } from "drizzle-orm";
3562
+ import { bigint as bigint3, index as index6, pgTable as pgTable9, text as text8 } from "drizzle-orm/pg-core";
3563
+ var authIdentityTable = pgTable9("auth_identities", {
3564
+ id: text8("id").primaryKey(),
3565
+ kind: text8("kind").notNull(),
3566
+ displayName: text8("display_name").notNull(),
3567
+ createdAt: bigint3("created_at", { mode: "number" }).notNull(),
3568
+ passwordHash: text8("password_hash"),
3569
+ cloudUserId: text8("cloud_user_id")
3570
+ }, (table) => [
3571
+ index6("auth_identities_kind_idx").on(table.kind),
3572
+ index6("auth_identities_cloud_user_idx").on(table.cloudUserId)
3573
+ ]);
3574
+ var authIdentityCreatedAtDefault = sql7`(extract(epoch from now()) * 1000)::bigint`;
3575
+ // schema/authOwnerBinding.ts
3576
+ import { bigint as bigint4, foreignKey as foreignKey3, index as index7, pgTable as pgTable10, text as text9, uniqueIndex } from "drizzle-orm/pg-core";
3577
+ var authOwnerBindingTable = pgTable10("auth_owner_bindings", {
3578
+ id: text9("id").primaryKey(),
3579
+ identityId: text9("identity_id").notNull().references(() => authIdentityTable.id, { onDelete: "cascade" }),
3580
+ connector: text9("connector").notNull(),
3581
+ externalId: text9("external_id").notNull(),
3582
+ displayHandle: text9("display_handle").notNull(),
3583
+ instanceId: text9("instance_id").notNull(),
3584
+ verifiedAt: bigint4("verified_at", { mode: "number" }).notNull(),
3585
+ pendingCodeHash: text9("pending_code_hash"),
3586
+ pendingExpiresAt: bigint4("pending_expires_at", { mode: "number" })
3587
+ }, (table) => [
3588
+ index7("auth_owner_bindings_identity_idx").on(table.identityId),
3589
+ index7("auth_owner_bindings_connector_idx").on(table.connector),
3590
+ uniqueIndex("auth_owner_bindings_connector_external_instance_uniq").on(table.connector, table.externalId, table.instanceId),
3591
+ foreignKey3({
3592
+ name: "fk_auth_owner_bindings_identity",
3593
+ columns: [table.identityId],
3594
+ foreignColumns: [authIdentityTable.id]
3595
+ }).onDelete("cascade")
3596
+ ]);
3597
+ // schema/authOwnerLoginToken.ts
3598
+ import { bigint as bigint5, foreignKey as foreignKey4, index as index8, pgTable as pgTable11, text as text10 } from "drizzle-orm/pg-core";
3599
+ var authOwnerLoginTokenTable = pgTable11("auth_owner_login_tokens", {
3600
+ tokenHash: text10("token_hash").primaryKey(),
3601
+ identityId: text10("identity_id").notNull().references(() => authIdentityTable.id, { onDelete: "cascade" }),
3602
+ bindingId: text10("binding_id").notNull().references(() => authOwnerBindingTable.id, { onDelete: "cascade" }),
3603
+ issuedAt: bigint5("issued_at", { mode: "number" }).notNull(),
3604
+ expiresAt: bigint5("expires_at", { mode: "number" }).notNull(),
3605
+ consumedAt: bigint5("consumed_at", { mode: "number" })
3606
+ }, (table) => [
3607
+ index8("auth_owner_login_tokens_identity_idx").on(table.identityId),
3608
+ index8("auth_owner_login_tokens_binding_idx").on(table.bindingId),
3609
+ index8("auth_owner_login_tokens_expires_idx").on(table.expiresAt),
3610
+ foreignKey4({
3611
+ name: "fk_auth_owner_login_tokens_identity",
3612
+ columns: [table.identityId],
3613
+ foreignColumns: [authIdentityTable.id]
3614
+ }).onDelete("cascade"),
3615
+ foreignKey4({
3616
+ name: "fk_auth_owner_login_tokens_binding",
3617
+ columns: [table.bindingId],
3618
+ foreignColumns: [authOwnerBindingTable.id]
3619
+ }).onDelete("cascade")
3620
+ ]);
3621
+ // schema/authSession.ts
3622
+ import { bigint as bigint6, boolean as boolean3, foreignKey as foreignKey5, index as index9, jsonb as jsonb7, pgTable as pgTable12, text as text11 } from "drizzle-orm/pg-core";
3623
+ var authSessionTable = pgTable12("auth_sessions", {
3624
+ id: text11("id").primaryKey(),
3625
+ identityId: text11("identity_id").notNull().references(() => authIdentityTable.id, { onDelete: "cascade" }),
3626
+ kind: text11("kind").notNull(),
3627
+ createdAt: bigint6("created_at", { mode: "number" }).notNull(),
3628
+ lastSeenAt: bigint6("last_seen_at", { mode: "number" }).notNull(),
3629
+ expiresAt: bigint6("expires_at", { mode: "number" }).notNull(),
3630
+ rememberDevice: boolean3("remember_device").notNull().default(false),
3631
+ csrfSecret: text11("csrf_secret").notNull(),
3632
+ ip: text11("ip"),
3633
+ userAgent: text11("user_agent"),
3634
+ scopes: jsonb7("scopes").$type().notNull(),
3635
+ revokedAt: bigint6("revoked_at", { mode: "number" })
3636
+ }, (table) => [
3637
+ index9("auth_sessions_identity_idx").on(table.identityId),
3638
+ index9("auth_sessions_expires_idx").on(table.expiresAt),
3639
+ foreignKey5({
3640
+ name: "fk_auth_sessions_identity",
3641
+ columns: [table.identityId],
3642
+ foreignColumns: [authIdentityTable.id]
3643
+ }).onDelete("cascade")
3644
+ ]);
3645
+ // schema/cache.ts
3646
+ init_agent();
3647
+ import { sql as sql8 } from "drizzle-orm";
3648
+ import { jsonb as jsonb8, pgTable as pgTable13, primaryKey, text as text12, timestamp as timestamp7, uuid as uuid7 } from "drizzle-orm/pg-core";
3649
+ var cacheTable = pgTable13("cache", {
3650
+ key: text12("key").notNull(),
3651
+ agentId: uuid7("agent_id").notNull().references(() => agentTable.id, { onDelete: "cascade" }),
3652
+ value: jsonb8("value").notNull(),
3653
+ createdAt: timestamp7("created_at", { withTimezone: true }).default(sql8`now()`).notNull(),
3654
+ expiresAt: timestamp7("expires_at", { withTimezone: true })
3504
3655
  }, (table) => [primaryKey({ columns: [table.key, table.agentId] })]);
3505
3656
  // schema/channel.ts
3506
- import { sql as sql8 } from "drizzle-orm";
3507
- import { jsonb as jsonb7, pgTable as pgTable8, text as text7, timestamp as timestamp8, uuid as uuid8 } from "drizzle-orm/pg-core";
3657
+ import { sql as sql10 } from "drizzle-orm";
3658
+ import { jsonb as jsonb10, pgTable as pgTable15, text as text14, timestamp as timestamp9, uuid as uuid9 } from "drizzle-orm/pg-core";
3508
3659
 
3509
3660
  // schema/messageServer.ts
3510
- import { sql as sql7 } from "drizzle-orm";
3511
- import { jsonb as jsonb6, pgTable as pgTable7, text as text6, timestamp as timestamp7, uuid as uuid7 } from "drizzle-orm/pg-core";
3512
- var messageServerTable = pgTable7("message_servers", {
3513
- id: uuid7("id").primaryKey(),
3514
- name: text6("name").notNull(),
3515
- sourceType: text6("source_type").notNull(),
3516
- sourceId: text6("source_id"),
3517
- metadata: jsonb6("metadata"),
3518
- createdAt: timestamp7("created_at", { mode: "date" }).default(sql7`CURRENT_TIMESTAMP`).notNull(),
3519
- updatedAt: timestamp7("updated_at", { mode: "date" }).default(sql7`CURRENT_TIMESTAMP`).notNull()
3661
+ import { sql as sql9 } from "drizzle-orm";
3662
+ import { jsonb as jsonb9, pgTable as pgTable14, text as text13, timestamp as timestamp8, uuid as uuid8 } from "drizzle-orm/pg-core";
3663
+ var messageServerTable = pgTable14("message_servers", {
3664
+ id: uuid8("id").primaryKey(),
3665
+ name: text13("name").notNull(),
3666
+ sourceType: text13("source_type").notNull(),
3667
+ sourceId: text13("source_id"),
3668
+ metadata: jsonb9("metadata"),
3669
+ createdAt: timestamp8("created_at", { mode: "date" }).default(sql9`CURRENT_TIMESTAMP`).notNull(),
3670
+ updatedAt: timestamp8("updated_at", { mode: "date" }).default(sql9`CURRENT_TIMESTAMP`).notNull()
3520
3671
  });
3521
3672
 
3522
3673
  // schema/channel.ts
3523
- var channelTable = pgTable8("channels", {
3524
- id: text7("id").primaryKey(),
3525
- messageServerId: uuid8("message_server_id").notNull().references(() => messageServerTable.id, { onDelete: "cascade" }),
3526
- name: text7("name").notNull(),
3527
- type: text7("type").notNull(),
3528
- sourceType: text7("source_type"),
3529
- sourceId: text7("source_id"),
3530
- topic: text7("topic"),
3531
- metadata: jsonb7("metadata"),
3532
- createdAt: timestamp8("created_at", { mode: "date" }).default(sql8`CURRENT_TIMESTAMP`).notNull(),
3533
- updatedAt: timestamp8("updated_at", { mode: "date" }).default(sql8`CURRENT_TIMESTAMP`).notNull()
3674
+ var channelTable = pgTable15("channels", {
3675
+ id: text14("id").primaryKey(),
3676
+ messageServerId: uuid9("message_server_id").notNull().references(() => messageServerTable.id, { onDelete: "cascade" }),
3677
+ name: text14("name").notNull(),
3678
+ type: text14("type").notNull(),
3679
+ sourceType: text14("source_type"),
3680
+ sourceId: text14("source_id"),
3681
+ topic: text14("topic"),
3682
+ metadata: jsonb10("metadata"),
3683
+ createdAt: timestamp9("created_at", { mode: "date" }).default(sql10`CURRENT_TIMESTAMP`).notNull(),
3684
+ updatedAt: timestamp9("updated_at", { mode: "date" }).default(sql10`CURRENT_TIMESTAMP`).notNull()
3534
3685
  });
3535
3686
  // schema/channelParticipant.ts
3536
- import { pgTable as pgTable9, primaryKey as primaryKey2, text as text8 } from "drizzle-orm/pg-core";
3537
- var channelParticipantsTable = pgTable9("channel_participants", {
3538
- channelId: text8("channel_id").notNull().references(() => channelTable.id, { onDelete: "cascade" }),
3539
- entityId: text8("entity_id").notNull()
3687
+ import { pgTable as pgTable16, primaryKey as primaryKey2, text as text15 } from "drizzle-orm/pg-core";
3688
+ var channelParticipantsTable = pgTable16("channel_participants", {
3689
+ channelId: text15("channel_id").notNull().references(() => channelTable.id, { onDelete: "cascade" }),
3690
+ entityId: text15("entity_id").notNull()
3540
3691
  }, (table) => [primaryKey2({ columns: [table.channelId, table.entityId] })]);
3541
3692
  // schema/component.ts
3542
3693
  init_agent();
3543
- import { sql as sql10 } from "drizzle-orm";
3544
- import { jsonb as jsonb9, pgTable as pgTable11, text as text10, timestamp as timestamp10, uuid as uuid10 } from "drizzle-orm/pg-core";
3694
+ import { sql as sql12 } from "drizzle-orm";
3695
+ import { jsonb as jsonb12, pgTable as pgTable18, text as text17, timestamp as timestamp11, uuid as uuid11 } from "drizzle-orm/pg-core";
3545
3696
 
3546
3697
  // schema/world.ts
3547
3698
  init_agent();
3548
- import { sql as sql9 } from "drizzle-orm";
3549
- import { jsonb as jsonb8, pgTable as pgTable10, text as text9, timestamp as timestamp9, uuid as uuid9 } from "drizzle-orm/pg-core";
3550
- var worldTable = pgTable10("worlds", {
3551
- id: uuid9("id").notNull().primaryKey().default(sql9`gen_random_uuid()`),
3552
- agentId: uuid9("agent_id").notNull().references(() => agentTable.id, { onDelete: "cascade" }),
3553
- name: text9("name").notNull(),
3554
- metadata: jsonb8("metadata"),
3555
- messageServerId: uuid9("message_server_id"),
3556
- createdAt: timestamp9("created_at").default(sql9`now()`).notNull()
3699
+ import { sql as sql11 } from "drizzle-orm";
3700
+ import { jsonb as jsonb11, pgTable as pgTable17, text as text16, timestamp as timestamp10, uuid as uuid10 } from "drizzle-orm/pg-core";
3701
+ var worldTable = pgTable17("worlds", {
3702
+ id: uuid10("id").notNull().primaryKey().default(sql11`gen_random_uuid()`),
3703
+ agentId: uuid10("agent_id").notNull().references(() => agentTable.id, { onDelete: "cascade" }),
3704
+ name: text16("name").notNull(),
3705
+ metadata: jsonb11("metadata"),
3706
+ messageServerId: uuid10("message_server_id"),
3707
+ createdAt: timestamp10("created_at").default(sql11`now()`).notNull()
3557
3708
  });
3558
3709
 
3559
3710
  // schema/component.ts
3560
- var componentTable = pgTable11("components", {
3561
- id: uuid10("id").primaryKey().default(sql10`gen_random_uuid()`).notNull(),
3562
- entityId: uuid10("entity_id").references(() => entityTable.id, { onDelete: "cascade" }).notNull(),
3563
- agentId: uuid10("agent_id").references(() => agentTable.id, { onDelete: "cascade" }).notNull(),
3564
- roomId: uuid10("room_id").references(() => roomTable.id, { onDelete: "cascade" }).notNull(),
3565
- worldId: uuid10("world_id").references(() => worldTable.id, {
3711
+ var componentTable = pgTable18("components", {
3712
+ id: uuid11("id").primaryKey().default(sql12`gen_random_uuid()`).notNull(),
3713
+ entityId: uuid11("entity_id").references(() => entityTable.id, { onDelete: "cascade" }).notNull(),
3714
+ agentId: uuid11("agent_id").references(() => agentTable.id, { onDelete: "cascade" }).notNull(),
3715
+ roomId: uuid11("room_id").references(() => roomTable.id, { onDelete: "cascade" }).notNull(),
3716
+ worldId: uuid11("world_id").references(() => worldTable.id, {
3566
3717
  onDelete: "cascade"
3567
3718
  }),
3568
- sourceEntityId: uuid10("source_entity_id").references(() => entityTable.id, {
3719
+ sourceEntityId: uuid11("source_entity_id").references(() => entityTable.id, {
3569
3720
  onDelete: "cascade"
3570
3721
  }),
3571
- type: text10("type").notNull(),
3572
- data: jsonb9("data").default(sql10`'{}'::jsonb`),
3573
- createdAt: timestamp10("created_at").default(sql10`now()`).notNull()
3722
+ type: text17("type").notNull(),
3723
+ data: jsonb12("data").default(sql12`'{}'::jsonb`),
3724
+ createdAt: timestamp11("created_at").default(sql12`now()`).notNull()
3574
3725
  });
3726
+ // schema/entityIdentity.ts
3727
+ init_agent();
3728
+ import { sql as sql13 } from "drizzle-orm";
3729
+ import {
3730
+ boolean as boolean4,
3731
+ foreignKey as foreignKey6,
3732
+ index as index10,
3733
+ jsonb as jsonb13,
3734
+ pgTable as pgTable19,
3735
+ real,
3736
+ text as text18,
3737
+ timestamp as timestamp12,
3738
+ unique as unique2,
3739
+ uuid as uuid12
3740
+ } from "drizzle-orm/pg-core";
3741
+ var entityIdentityTable = pgTable19("entity_identities", {
3742
+ id: uuid12("id").notNull().primaryKey().default(sql13`gen_random_uuid()`),
3743
+ entityId: uuid12("entity_id").notNull().references(() => entityTable.id, { onDelete: "cascade" }),
3744
+ agentId: uuid12("agent_id").notNull().references(() => agentTable.id, { onDelete: "cascade" }),
3745
+ platform: text18("platform").notNull(),
3746
+ handle: text18("handle").notNull(),
3747
+ verified: boolean4("verified").notNull().default(false),
3748
+ confidence: real("confidence").notNull().default(0),
3749
+ source: text18("source"),
3750
+ firstSeen: timestamp12("first_seen", { withTimezone: true }).notNull().default(sql13`now()`),
3751
+ lastSeen: timestamp12("last_seen", { withTimezone: true }).notNull().default(sql13`now()`),
3752
+ evidenceMessageIds: jsonb13("evidence_message_ids").$type(),
3753
+ createdAt: timestamp12("created_at", { withTimezone: true }).notNull().default(sql13`now()`)
3754
+ }, (table) => [
3755
+ index10("idx_entity_identities_entity").on(table.entityId),
3756
+ index10("idx_entity_identities_platform_handle").on(table.platform, table.handle),
3757
+ unique2("unique_entity_identity").on(table.entityId, table.platform, table.handle, table.agentId),
3758
+ foreignKey6({
3759
+ name: "fk_entity_identities_entity",
3760
+ columns: [table.entityId],
3761
+ foreignColumns: [entityTable.id]
3762
+ }).onDelete("cascade"),
3763
+ foreignKey6({
3764
+ name: "fk_entity_identities_agent",
3765
+ columns: [table.agentId],
3766
+ foreignColumns: [agentTable.id]
3767
+ }).onDelete("cascade")
3768
+ ]);
3769
+ var entityMergeCandidateTable = pgTable19("entity_merge_candidates", {
3770
+ id: uuid12("id").notNull().primaryKey().default(sql13`gen_random_uuid()`),
3771
+ agentId: uuid12("agent_id").notNull().references(() => agentTable.id, { onDelete: "cascade" }),
3772
+ entityA: uuid12("entity_a").notNull().references(() => entityTable.id, { onDelete: "cascade" }),
3773
+ entityB: uuid12("entity_b").notNull().references(() => entityTable.id, { onDelete: "cascade" }),
3774
+ confidence: real("confidence").notNull().default(0),
3775
+ evidence: jsonb13("evidence"),
3776
+ status: text18("status").notNull().default("pending"),
3777
+ proposedAt: timestamp12("proposed_at", { withTimezone: true }).notNull().default(sql13`now()`),
3778
+ resolvedAt: timestamp12("resolved_at", { withTimezone: true })
3779
+ }, (table) => [
3780
+ index10("idx_entity_merge_candidates_status").on(table.status),
3781
+ index10("idx_entity_merge_candidates_pair").on(table.entityA, table.entityB),
3782
+ foreignKey6({
3783
+ name: "fk_entity_merge_candidates_a",
3784
+ columns: [table.entityA],
3785
+ foreignColumns: [entityTable.id]
3786
+ }).onDelete("cascade"),
3787
+ foreignKey6({
3788
+ name: "fk_entity_merge_candidates_b",
3789
+ columns: [table.entityB],
3790
+ foreignColumns: [entityTable.id]
3791
+ }).onDelete("cascade"),
3792
+ foreignKey6({
3793
+ name: "fk_entity_merge_candidates_agent",
3794
+ columns: [table.agentId],
3795
+ foreignColumns: [agentTable.id]
3796
+ }).onDelete("cascade")
3797
+ ]);
3798
+ var factCandidateTable = pgTable19("fact_candidates", {
3799
+ id: uuid12("id").notNull().primaryKey().default(sql13`gen_random_uuid()`),
3800
+ agentId: uuid12("agent_id").notNull().references(() => agentTable.id, { onDelete: "cascade" }),
3801
+ entityId: uuid12("entity_id").notNull().references(() => entityTable.id, { onDelete: "cascade" }),
3802
+ kind: text18("kind").notNull(),
3803
+ existingFactId: uuid12("existing_fact_id"),
3804
+ proposedText: text18("proposed_text").notNull(),
3805
+ confidence: real("confidence").notNull().default(0),
3806
+ evidence: jsonb13("evidence"),
3807
+ status: text18("status").notNull().default("pending"),
3808
+ proposedAt: timestamp12("proposed_at", { withTimezone: true }).notNull().default(sql13`now()`),
3809
+ resolvedAt: timestamp12("resolved_at", { withTimezone: true })
3810
+ }, (table) => [
3811
+ index10("idx_fact_candidates_status").on(table.status),
3812
+ index10("idx_fact_candidates_entity").on(table.entityId),
3813
+ foreignKey6({
3814
+ name: "fk_fact_candidates_entity",
3815
+ columns: [table.entityId],
3816
+ foreignColumns: [entityTable.id]
3817
+ }).onDelete("cascade"),
3818
+ foreignKey6({
3819
+ name: "fk_fact_candidates_agent",
3820
+ columns: [table.agentId],
3821
+ foreignColumns: [agentTable.id]
3822
+ }).onDelete("cascade")
3823
+ ]);
3575
3824
  // schema/log.ts
3576
- import { sql as sql11 } from "drizzle-orm";
3577
- import { foreignKey as foreignKey3, jsonb as jsonb10, pgTable as pgTable12, text as text11, timestamp as timestamp11, uuid as uuid11 } from "drizzle-orm/pg-core";
3578
- var logTable = pgTable12("logs", {
3579
- id: uuid11("id").defaultRandom().notNull(),
3580
- createdAt: timestamp11("created_at", { withTimezone: true }).default(sql11`now()`).notNull(),
3581
- entityId: uuid11("entity_id").notNull().references(() => entityTable.id, { onDelete: "cascade" }),
3582
- body: jsonb10("body").notNull(),
3583
- type: text11("type").notNull(),
3584
- roomId: uuid11("room_id").notNull().references(() => roomTable.id, { onDelete: "cascade" })
3825
+ import { sql as sql14 } from "drizzle-orm";
3826
+ import { foreignKey as foreignKey7, jsonb as jsonb14, pgTable as pgTable20, text as text19, timestamp as timestamp13, uuid as uuid13 } from "drizzle-orm/pg-core";
3827
+ var logTable = pgTable20("logs", {
3828
+ id: uuid13("id").defaultRandom().notNull(),
3829
+ createdAt: timestamp13("created_at", { withTimezone: true }).default(sql14`now()`).notNull(),
3830
+ entityId: uuid13("entity_id").notNull().references(() => entityTable.id, { onDelete: "cascade" }),
3831
+ body: jsonb14("body").notNull(),
3832
+ type: text19("type").notNull(),
3833
+ roomId: uuid13("room_id").notNull().references(() => roomTable.id, { onDelete: "cascade" })
3585
3834
  }, (table) => [
3586
- foreignKey3({
3835
+ foreignKey7({
3587
3836
  name: "fk_room",
3588
3837
  columns: [table.roomId],
3589
3838
  foreignColumns: [roomTable.id]
3590
3839
  }).onDelete("cascade"),
3591
- foreignKey3({
3840
+ foreignKey7({
3592
3841
  name: "fk_user",
3593
3842
  columns: [table.entityId],
3594
3843
  foreignColumns: [entityTable.id]
3595
3844
  }).onDelete("cascade")
3596
3845
  ]);
3846
+ // schema/longTermMemories.ts
3847
+ import { sql as sql15 } from "drizzle-orm";
3848
+ import { index as index11, integer, jsonb as jsonb15, pgTable as pgTable21, real as real2, text as text20, timestamp as timestamp14, uuid as uuid14 } from "drizzle-orm/pg-core";
3849
+ var longTermMemories = pgTable21("long_term_memories", {
3850
+ id: uuid14("id").primaryKey().notNull(),
3851
+ agentId: uuid14("agent_id").notNull(),
3852
+ entityId: uuid14("entity_id").notNull(),
3853
+ category: text20("category").notNull(),
3854
+ content: text20("content").notNull(),
3855
+ metadata: jsonb15("metadata"),
3856
+ embedding: real2("embedding").array(),
3857
+ confidence: real2("confidence").default(1),
3858
+ source: text20("source"),
3859
+ createdAt: timestamp14("created_at").default(sql15`now()`).notNull(),
3860
+ updatedAt: timestamp14("updated_at").default(sql15`now()`).notNull(),
3861
+ lastAccessedAt: timestamp14("last_accessed_at"),
3862
+ accessCount: integer("access_count").default(0)
3863
+ }, (table) => [
3864
+ index11("long_term_memories_agent_entity_idx").on(table.agentId, table.entityId),
3865
+ index11("long_term_memories_category_idx").on(table.category),
3866
+ index11("long_term_memories_confidence_idx").on(table.confidence),
3867
+ index11("long_term_memories_created_at_idx").on(table.createdAt)
3868
+ ]);
3869
+ // schema/memoryAccessLogs.ts
3870
+ import { sql as sql16 } from "drizzle-orm";
3871
+ import { index as index12, pgTable as pgTable22, text as text21, timestamp as timestamp15, uuid as uuid15 } from "drizzle-orm/pg-core";
3872
+ var memoryAccessLogs = pgTable22("memory_access_logs", {
3873
+ id: uuid15("id").primaryKey().notNull(),
3874
+ memoryId: uuid15("memory_id").notNull(),
3875
+ memoryType: text21("memory_type").notNull(),
3876
+ agentId: uuid15("agent_id").notNull(),
3877
+ accessType: text21("access_type").notNull(),
3878
+ accessedAt: timestamp15("accessed_at").default(sql16`now()`).notNull()
3879
+ }, (table) => [
3880
+ index12("memory_access_logs_memory_id_idx").on(table.memoryId),
3881
+ index12("memory_access_logs_agent_id_idx").on(table.agentId),
3882
+ index12("memory_access_logs_accessed_at_idx").on(table.accessedAt)
3883
+ ]);
3597
3884
  // schema/message.ts
3598
- import { sql as sql12 } from "drizzle-orm";
3599
- import { jsonb as jsonb11, pgTable as pgTable13, text as text12, timestamp as timestamp12 } from "drizzle-orm/pg-core";
3600
- var messageTable = pgTable13("central_messages", {
3601
- id: text12("id").primaryKey(),
3602
- channelId: text12("channel_id").notNull().references(() => channelTable.id, { onDelete: "cascade" }),
3603
- authorId: text12("author_id").notNull(),
3604
- content: text12("content").notNull(),
3605
- rawMessage: jsonb11("raw_message"),
3606
- inReplyToRootMessageId: text12("in_reply_to_root_message_id").references(() => messageTable.id, {
3885
+ import { sql as sql17 } from "drizzle-orm";
3886
+ import { jsonb as jsonb16, pgTable as pgTable23, text as text22, timestamp as timestamp16 } from "drizzle-orm/pg-core";
3887
+ var messageTable = pgTable23("central_messages", {
3888
+ id: text22("id").primaryKey(),
3889
+ channelId: text22("channel_id").notNull().references(() => channelTable.id, { onDelete: "cascade" }),
3890
+ authorId: text22("author_id").notNull(),
3891
+ content: text22("content").notNull(),
3892
+ rawMessage: jsonb16("raw_message"),
3893
+ inReplyToRootMessageId: text22("in_reply_to_root_message_id").references(() => messageTable.id, {
3607
3894
  onDelete: "set null"
3608
3895
  }),
3609
- sourceType: text12("source_type"),
3610
- sourceId: text12("source_id"),
3611
- metadata: jsonb11("metadata"),
3612
- createdAt: timestamp12("created_at", { mode: "date" }).default(sql12`CURRENT_TIMESTAMP`).notNull(),
3613
- updatedAt: timestamp12("updated_at", { mode: "date" }).default(sql12`CURRENT_TIMESTAMP`).notNull()
3896
+ sourceType: text22("source_type"),
3897
+ sourceId: text22("source_id"),
3898
+ metadata: jsonb16("metadata"),
3899
+ createdAt: timestamp16("created_at", { mode: "date" }).default(sql17`CURRENT_TIMESTAMP`).notNull(),
3900
+ updatedAt: timestamp16("updated_at", { mode: "date" }).default(sql17`CURRENT_TIMESTAMP`).notNull()
3614
3901
  });
3615
3902
  // schema/messageServerAgent.ts
3616
3903
  init_agent();
3617
- import { pgTable as pgTable14, primaryKey as primaryKey3, uuid as uuid12 } from "drizzle-orm/pg-core";
3618
- var messageServerAgentsTable = pgTable14("message_server_agents", {
3619
- messageServerId: uuid12("message_server_id").notNull().references(() => messageServerTable.id, { onDelete: "cascade" }),
3620
- agentId: uuid12("agent_id").notNull().references(() => agentTable.id, { onDelete: "cascade" })
3904
+ import { pgTable as pgTable24, primaryKey as primaryKey3, uuid as uuid16 } from "drizzle-orm/pg-core";
3905
+ var messageServerAgentsTable = pgTable24("message_server_agents", {
3906
+ messageServerId: uuid16("message_server_id").notNull().references(() => messageServerTable.id, { onDelete: "cascade" }),
3907
+ agentId: uuid16("agent_id").notNull().references(() => agentTable.id, { onDelete: "cascade" })
3621
3908
  }, (table) => [primaryKey3({ columns: [table.messageServerId, table.agentId] })]);
3622
3909
  // schema/pairingAllowlist.ts
3623
3910
  init_agent();
3624
- import { sql as sql13 } from "drizzle-orm";
3625
- import { index as index3, jsonb as jsonb12, pgTable as pgTable15, text as text13, timestamp as timestamp13, uniqueIndex, uuid as uuid13 } from "drizzle-orm/pg-core";
3626
- var pairingAllowlistTable = pgTable15("pairing_allowlist", {
3627
- id: uuid13("id").primaryKey().defaultRandom(),
3628
- channel: text13("channel").notNull(),
3629
- senderId: text13("sender_id").notNull(),
3630
- createdAt: timestamp13("created_at", { withTimezone: true }).default(sql13`now()`).notNull(),
3631
- metadata: jsonb12("metadata").default(sql13`'{}'::jsonb`),
3632
- agentId: uuid13("agent_id").notNull().references(() => agentTable.id, { onDelete: "cascade" })
3911
+ import { sql as sql18 } from "drizzle-orm";
3912
+ import { index as index13, jsonb as jsonb17, pgTable as pgTable25, text as text23, timestamp as timestamp17, uniqueIndex as uniqueIndex2, uuid as uuid17 } from "drizzle-orm/pg-core";
3913
+ var pairingAllowlistTable = pgTable25("pairing_allowlist", {
3914
+ id: uuid17("id").primaryKey().defaultRandom(),
3915
+ channel: text23("channel").notNull(),
3916
+ senderId: text23("sender_id").notNull(),
3917
+ createdAt: timestamp17("created_at", { withTimezone: true }).default(sql18`now()`).notNull(),
3918
+ metadata: jsonb17("metadata").default(sql18`'{}'::jsonb`),
3919
+ agentId: uuid17("agent_id").notNull().references(() => agentTable.id, { onDelete: "cascade" })
3633
3920
  }, (table) => [
3634
- index3("pairing_allowlist_channel_agent_idx").on(table.channel, table.agentId),
3635
- uniqueIndex("pairing_allowlist_sender_channel_agent_idx").on(table.senderId, table.channel, table.agentId)
3921
+ index13("pairing_allowlist_channel_agent_idx").on(table.channel, table.agentId),
3922
+ uniqueIndex2("pairing_allowlist_sender_channel_agent_idx").on(table.senderId, table.channel, table.agentId)
3636
3923
  ]);
3637
3924
  // schema/pairingRequest.ts
3638
3925
  init_agent();
3639
- import { sql as sql14 } from "drizzle-orm";
3640
- import { index as index4, jsonb as jsonb13, pgTable as pgTable16, text as text14, timestamp as timestamp14, uniqueIndex as uniqueIndex2, uuid as uuid14 } from "drizzle-orm/pg-core";
3641
- var pairingRequestTable = pgTable16("pairing_requests", {
3642
- id: uuid14("id").primaryKey().defaultRandom(),
3643
- channel: text14("channel").notNull(),
3644
- senderId: text14("sender_id").notNull(),
3645
- code: text14("code").notNull(),
3646
- createdAt: timestamp14("created_at", { withTimezone: true }).default(sql14`now()`).notNull(),
3647
- lastSeenAt: timestamp14("last_seen_at", { withTimezone: true }).default(sql14`now()`).notNull(),
3648
- metadata: jsonb13("metadata").default(sql14`'{}'::jsonb`),
3649
- agentId: uuid14("agent_id").notNull().references(() => agentTable.id, { onDelete: "cascade" })
3926
+ import { sql as sql19 } from "drizzle-orm";
3927
+ import { index as index14, jsonb as jsonb18, pgTable as pgTable26, text as text24, timestamp as timestamp18, uniqueIndex as uniqueIndex3, uuid as uuid18 } from "drizzle-orm/pg-core";
3928
+ var pairingRequestTable = pgTable26("pairing_requests", {
3929
+ id: uuid18("id").primaryKey().defaultRandom(),
3930
+ channel: text24("channel").notNull(),
3931
+ senderId: text24("sender_id").notNull(),
3932
+ code: text24("code").notNull(),
3933
+ createdAt: timestamp18("created_at", { withTimezone: true }).default(sql19`now()`).notNull(),
3934
+ lastSeenAt: timestamp18("last_seen_at", { withTimezone: true }).default(sql19`now()`).notNull(),
3935
+ metadata: jsonb18("metadata").default(sql19`'{}'::jsonb`),
3936
+ agentId: uuid18("agent_id").notNull().references(() => agentTable.id, { onDelete: "cascade" })
3650
3937
  }, (table) => [
3651
- index4("pairing_requests_channel_agent_idx").on(table.channel, table.agentId),
3652
- uniqueIndex2("pairing_requests_code_channel_agent_idx").on(table.code, table.channel, table.agentId),
3653
- uniqueIndex2("pairing_requests_sender_channel_agent_idx").on(table.senderId, table.channel, table.agentId)
3938
+ index14("pairing_requests_channel_agent_idx").on(table.channel, table.agentId),
3939
+ uniqueIndex3("pairing_requests_code_channel_agent_idx").on(table.code, table.channel, table.agentId),
3940
+ uniqueIndex3("pairing_requests_sender_channel_agent_idx").on(table.senderId, table.channel, table.agentId)
3654
3941
  ]);
3655
3942
  // schema/participant.ts
3656
3943
  init_agent();
3657
- import { sql as sql15 } from "drizzle-orm";
3658
- import { foreignKey as foreignKey4, index as index5, pgTable as pgTable17, text as text15, timestamp as timestamp15, uuid as uuid15 } from "drizzle-orm/pg-core";
3659
- var participantTable = pgTable17("participants", {
3660
- id: uuid15("id").notNull().primaryKey().default(sql15`gen_random_uuid()`),
3661
- createdAt: timestamp15("created_at", { withTimezone: true }).default(sql15`now()`).notNull(),
3662
- entityId: uuid15("entity_id").references(() => entityTable.id, {
3944
+ import { sql as sql20 } from "drizzle-orm";
3945
+ import { foreignKey as foreignKey8, index as index15, pgTable as pgTable27, text as text25, timestamp as timestamp19, uuid as uuid19 } from "drizzle-orm/pg-core";
3946
+ var participantTable = pgTable27("participants", {
3947
+ id: uuid19("id").notNull().primaryKey().default(sql20`gen_random_uuid()`),
3948
+ createdAt: timestamp19("created_at", { withTimezone: true }).default(sql20`now()`).notNull(),
3949
+ entityId: uuid19("entity_id").references(() => entityTable.id, {
3663
3950
  onDelete: "cascade"
3664
3951
  }),
3665
- roomId: uuid15("room_id").references(() => roomTable.id, {
3952
+ roomId: uuid19("room_id").references(() => roomTable.id, {
3666
3953
  onDelete: "cascade"
3667
3954
  }),
3668
- agentId: uuid15("agent_id").references(() => agentTable.id, {
3955
+ agentId: uuid19("agent_id").references(() => agentTable.id, {
3669
3956
  onDelete: "cascade"
3670
3957
  }),
3671
- roomState: text15("room_state")
3958
+ roomState: text25("room_state")
3672
3959
  }, (table) => [
3673
- index5("idx_participants_user").on(table.entityId),
3674
- index5("idx_participants_room").on(table.roomId),
3675
- foreignKey4({
3960
+ index15("idx_participants_user").on(table.entityId),
3961
+ index15("idx_participants_room").on(table.roomId),
3962
+ foreignKey8({
3676
3963
  name: "fk_room",
3677
3964
  columns: [table.roomId],
3678
3965
  foreignColumns: [roomTable.id]
3679
3966
  }).onDelete("cascade"),
3680
- foreignKey4({
3967
+ foreignKey8({
3681
3968
  name: "fk_user",
3682
3969
  columns: [table.entityId],
3683
3970
  foreignColumns: [entityTable.id]
@@ -3685,34 +3972,34 @@ var participantTable = pgTable17("participants", {
3685
3972
  ]);
3686
3973
  // schema/relationship.ts
3687
3974
  init_agent();
3688
- import { sql as sql16 } from "drizzle-orm";
3975
+ import { sql as sql21 } from "drizzle-orm";
3689
3976
  import {
3690
- foreignKey as foreignKey5,
3691
- index as index6,
3692
- jsonb as jsonb14,
3693
- pgTable as pgTable18,
3694
- text as text16,
3695
- timestamp as timestamp16,
3696
- unique as unique2,
3697
- uuid as uuid16
3977
+ foreignKey as foreignKey9,
3978
+ index as index16,
3979
+ jsonb as jsonb19,
3980
+ pgTable as pgTable28,
3981
+ text as text26,
3982
+ timestamp as timestamp20,
3983
+ unique as unique3,
3984
+ uuid as uuid20
3698
3985
  } from "drizzle-orm/pg-core";
3699
- var relationshipTable = pgTable18("relationships", {
3700
- id: uuid16("id").notNull().primaryKey().default(sql16`gen_random_uuid()`),
3701
- createdAt: timestamp16("created_at", { withTimezone: true }).default(sql16`now()`).notNull(),
3702
- sourceEntityId: uuid16("source_entity_id").notNull().references(() => entityTable.id, { onDelete: "cascade" }),
3703
- targetEntityId: uuid16("target_entity_id").notNull().references(() => entityTable.id, { onDelete: "cascade" }),
3704
- agentId: uuid16("agent_id").notNull().references(() => agentTable.id, { onDelete: "cascade" }),
3705
- tags: text16("tags").array(),
3706
- metadata: jsonb14("metadata")
3986
+ var relationshipTable = pgTable28("relationships", {
3987
+ id: uuid20("id").notNull().primaryKey().default(sql21`gen_random_uuid()`),
3988
+ createdAt: timestamp20("created_at", { withTimezone: true }).default(sql21`now()`).notNull(),
3989
+ sourceEntityId: uuid20("source_entity_id").notNull().references(() => entityTable.id, { onDelete: "cascade" }),
3990
+ targetEntityId: uuid20("target_entity_id").notNull().references(() => entityTable.id, { onDelete: "cascade" }),
3991
+ agentId: uuid20("agent_id").notNull().references(() => agentTable.id, { onDelete: "cascade" }),
3992
+ tags: text26("tags").array(),
3993
+ metadata: jsonb19("metadata")
3707
3994
  }, (table) => [
3708
- index6("idx_relationships_users").on(table.sourceEntityId, table.targetEntityId),
3709
- unique2("unique_relationship").on(table.sourceEntityId, table.targetEntityId, table.agentId),
3710
- foreignKey5({
3995
+ index16("idx_relationships_users").on(table.sourceEntityId, table.targetEntityId),
3996
+ unique3("unique_relationship").on(table.sourceEntityId, table.targetEntityId, table.agentId),
3997
+ foreignKey9({
3711
3998
  name: "fk_user_a",
3712
3999
  columns: [table.sourceEntityId],
3713
4000
  foreignColumns: [entityTable.id]
3714
4001
  }).onDelete("cascade"),
3715
- foreignKey5({
4002
+ foreignKey9({
3716
4003
  name: "fk_user_b",
3717
4004
  columns: [table.targetEntityId],
3718
4005
  foreignColumns: [entityTable.id]
@@ -3722,24 +4009,58 @@ var relationshipTable = pgTable18("relationships", {
3722
4009
  // schema/index.ts
3723
4010
  init_server();
3724
4011
 
4012
+ // schema/sessionSummaries.ts
4013
+ import { sql as sql23 } from "drizzle-orm";
4014
+ import { index as index17, integer as integer2, jsonb as jsonb20, pgTable as pgTable30, real as real3, text as text27, timestamp as timestamp22, uuid as uuid22 } from "drizzle-orm/pg-core";
4015
+ var sessionSummaries = pgTable30("session_summaries", {
4016
+ id: uuid22("id").primaryKey().notNull(),
4017
+ agentId: uuid22("agent_id").notNull(),
4018
+ roomId: uuid22("room_id").notNull(),
4019
+ entityId: uuid22("entity_id"),
4020
+ summary: text27("summary").notNull(),
4021
+ messageCount: integer2("message_count").notNull(),
4022
+ lastMessageOffset: integer2("last_message_offset").default(0).notNull(),
4023
+ startTime: timestamp22("start_time").notNull(),
4024
+ endTime: timestamp22("end_time").notNull(),
4025
+ topics: jsonb20("topics").$type(),
4026
+ metadata: jsonb20("metadata"),
4027
+ embedding: real3("embedding").array(),
4028
+ createdAt: timestamp22("created_at").default(sql23`now()`).notNull(),
4029
+ updatedAt: timestamp22("updated_at").default(sql23`now()`).notNull()
4030
+ }, (table) => [
4031
+ index17("session_summaries_agent_room_idx").on(table.agentId, table.roomId),
4032
+ index17("session_summaries_entity_idx").on(table.entityId),
4033
+ index17("session_summaries_start_time_idx").on(table.startTime)
4034
+ ]);
3725
4035
  // schema/tasks.ts
3726
4036
  init_agent();
3727
- import { sql as sql18 } from "drizzle-orm";
3728
- import { jsonb as jsonb15, pgTable as pgTable20, text as text17, timestamp as timestamp18, uuid as uuid18 } from "drizzle-orm/pg-core";
3729
- var taskTable = pgTable20("tasks", {
3730
- id: uuid18("id").primaryKey().defaultRandom(),
3731
- name: text17("name").notNull(),
3732
- description: text17("description"),
3733
- roomId: uuid18("room_id"),
3734
- worldId: uuid18("world_id"),
3735
- entityId: uuid18("entity_id"),
3736
- agentId: uuid18("agent_id").notNull().references(() => agentTable.id, { onDelete: "cascade" }),
3737
- tags: text17("tags").array().default(sql18`'{}'::text[]`),
3738
- metadata: jsonb15("metadata").default(sql18`'{}'::jsonb`),
3739
- createdAt: timestamp18("created_at", { withTimezone: true }).defaultNow(),
3740
- updatedAt: timestamp18("updated_at", { withTimezone: true }).defaultNow()
4037
+ import { sql as sql24 } from "drizzle-orm";
4038
+ import { jsonb as jsonb21, pgTable as pgTable31, text as text28, timestamp as timestamp23, uuid as uuid23 } from "drizzle-orm/pg-core";
4039
+ var taskTable = pgTable31("tasks", {
4040
+ id: uuid23("id").primaryKey().defaultRandom(),
4041
+ name: text28("name").notNull(),
4042
+ description: text28("description"),
4043
+ roomId: uuid23("room_id"),
4044
+ worldId: uuid23("world_id"),
4045
+ entityId: uuid23("entity_id"),
4046
+ agentId: uuid23("agent_id").notNull().references(() => agentTable.id, { onDelete: "cascade" }),
4047
+ tags: text28("tags").array().default(sql24`'{}'::text[]`),
4048
+ metadata: jsonb21("metadata").default(sql24`'{}'::jsonb`),
4049
+ createdAt: timestamp23("created_at", { withTimezone: true }).defaultNow(),
4050
+ updatedAt: timestamp23("updated_at", { withTimezone: true }).defaultNow()
3741
4051
  });
3742
4052
  // base.ts
4053
+ function asRawMessage(value) {
4054
+ if (value && typeof value === "object" && !Array.isArray(value)) {
4055
+ return value;
4056
+ }
4057
+ return;
4058
+ }
4059
+ function asMetadata(value) {
4060
+ return value ?? undefined;
4061
+ }
4062
+ var v4 = () => crypto.randomUUID();
4063
+
3743
4064
  class BaseDrizzleAdapter extends DatabaseAdapter {
3744
4065
  maxRetries = 3;
3745
4066
  baseDelay = 1000;
@@ -3784,8 +4105,11 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
3784
4105
  if (names instanceof Set) {
3785
4106
  return Array.from(names).map(String);
3786
4107
  }
3787
- if (typeof names === "object" && typeof names[Symbol.iterator] === "function") {
3788
- return Array.from(names).map(String);
4108
+ if (typeof names === "object") {
4109
+ const iterableNames = names;
4110
+ if (typeof iterableNames[Symbol.iterator] === "function") {
4111
+ return Array.from(names).map(String);
4112
+ }
3789
4113
  }
3790
4114
  return [String(names)];
3791
4115
  }
@@ -3856,13 +4180,12 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
3856
4180
  }
3857
4181
  const resolvedDimension = DIMENSION_MAP[dimension];
3858
4182
  if (!resolvedDimension) {
3859
- const fallbackDimension = this.embeddingDimension ?? DIMENSION_MAP[384];
3860
- this.embeddingDimension = fallbackDimension;
3861
4183
  logger9.warn({
3862
4184
  src: "plugin:sql",
4185
+ agentId: this.agentId,
3863
4186
  requestedDimension: dimension,
3864
- fallbackDimension
3865
- }, "Unsupported embedding dimension requested; keeping fallback embedding column");
4187
+ fallbackDimension: this.embeddingDimension
4188
+ }, "Unsupported embedding dimension requested; keeping current embedding column");
3866
4189
  return;
3867
4190
  }
3868
4191
  this.embeddingDimension = resolvedDimension;
@@ -4209,15 +4532,17 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
4209
4532
  return await this.db.transaction(async (tx) => {
4210
4533
  const normalizedEntities = entities.map((entity) => {
4211
4534
  const { names, metadata, ...normalizedEntity } = entity;
4535
+ const id = entity.id || v4();
4212
4536
  return {
4213
4537
  ...normalizedEntity,
4538
+ id,
4214
4539
  agentId: this.agentId,
4215
4540
  names: this.normalizeEntityNames(names),
4216
4541
  metadata: metadata || {}
4217
4542
  };
4218
4543
  });
4219
4544
  await tx.insert(entityTable).values(normalizedEntities);
4220
- return true;
4545
+ return normalizedEntities.map((entity) => entity.id);
4221
4546
  });
4222
4547
  } catch (error) {
4223
4548
  logger9.error({
@@ -4225,7 +4550,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
4225
4550
  entityId: entities[0]?.id,
4226
4551
  error: error instanceof Error ? error.message : String(error)
4227
4552
  }, "Failed to create entities");
4228
- return false;
4553
+ return [];
4229
4554
  }
4230
4555
  });
4231
4556
  }
@@ -4236,8 +4561,8 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
4236
4561
  }
4237
4562
  try {
4238
4563
  const existingEntities = await this.getEntitiesByIds([entity.id]);
4239
- if (!existingEntities || !existingEntities.length) {
4240
- return await this.createEntities([entity]);
4564
+ if (!existingEntities?.length) {
4565
+ return (await this.createEntities([entity])).length > 0;
4241
4566
  }
4242
4567
  return true;
4243
4568
  } catch (error) {
@@ -4274,11 +4599,11 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
4274
4599
  async getEntitiesByNames(params) {
4275
4600
  return this.withDatabase(async () => {
4276
4601
  const { names, agentId } = params;
4277
- const nameConditions = names.map((name) => sql27`${name} = ANY(${entityTable.names})`);
4278
- const query = sql27`
4602
+ const nameConditions = names.map((name) => sql33`${name} = ANY(${entityTable.names})`);
4603
+ const query = sql33`
4279
4604
  SELECT * FROM ${entityTable}
4280
4605
  WHERE ${entityTable.agentId} = ${agentId}
4281
- AND (${sql27.join(nameConditions, sql27` OR `)})
4606
+ AND (${sql33.join(nameConditions, sql33` OR `)})
4282
4607
  `;
4283
4608
  const result = await this.db.execute(query);
4284
4609
  return result.rows.map((row) => ({
@@ -4301,7 +4626,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
4301
4626
  metadata: row.metadata || {}
4302
4627
  }));
4303
4628
  }
4304
- const searchQuery = sql27`
4629
+ const searchQuery = sql33`
4305
4630
  SELECT * FROM ${entityTable}
4306
4631
  WHERE ${entityTable.agentId} = ${agentId}
4307
4632
  AND EXISTS (
@@ -4409,9 +4734,8 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
4409
4734
  });
4410
4735
  }
4411
4736
  async getMemories(params) {
4412
- const { entityId, agentId, roomId, worldId, tableName, unique: unique3, start, end, offset } = params;
4413
- if (!tableName)
4414
- throw new Error("tableName is required");
4737
+ const { entityId, agentId, roomId, worldId, unique: unique4, start, end, offset } = params;
4738
+ const tableName = params.tableName ?? "messages";
4415
4739
  if (offset !== undefined && offset < 0) {
4416
4740
  throw new Error("offset must be a non-negative number");
4417
4741
  }
@@ -4429,7 +4753,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
4429
4753
  if (end !== undefined) {
4430
4754
  conditions.push(lte(memoryTable.createdAt, new Date(end)));
4431
4755
  }
4432
- if (unique3) {
4756
+ if (unique4) {
4433
4757
  conditions.push(eq2(memoryTable.unique, true));
4434
4758
  }
4435
4759
  if (agentId) {
@@ -4557,7 +4881,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
4557
4881
  async getCachedEmbeddings(opts) {
4558
4882
  return this.withDatabase(async () => {
4559
4883
  try {
4560
- const results = await this.db.execute(sql27`
4884
+ const results = await this.db.execute(sql33`
4561
4885
  WITH content_text AS (
4562
4886
  SELECT
4563
4887
  m.id,
@@ -4586,9 +4910,9 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
4586
4910
  )
4587
4911
  SELECT
4588
4912
  embedding,
4589
- levenshtein(${opts.query_input}, content_text) as levenshtein_score
4913
+ levenshtein(CAST(${opts.query_input} AS text), content_text) as levenshtein_score
4590
4914
  FROM embedded_text
4591
- WHERE levenshtein(${opts.query_input}, content_text) <= ${opts.query_threshold}
4915
+ WHERE levenshtein(CAST(${opts.query_input} AS text), content_text) <= ${opts.query_threshold}
4592
4916
  ORDER BY levenshtein_score
4593
4917
  LIMIT ${opts.query_match_count}
4594
4918
  `);
@@ -4617,7 +4941,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
4617
4941
  const jsonString = JSON.stringify(sanitizedBody);
4618
4942
  await this.withEntityContext(params.entityId, async (tx) => {
4619
4943
  await tx.insert(logTable).values({
4620
- body: sql27`${jsonString}::jsonb`,
4944
+ body: sql33`${jsonString}::jsonb`,
4621
4945
  entityId: params.entityId,
4622
4946
  roomId: params.roomId,
4623
4947
  type: params.type
@@ -4631,7 +4955,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
4631
4955
  entityId: params.entityId,
4632
4956
  error: error instanceof Error ? error.message : String(error)
4633
4957
  }, "Failed to create log entry");
4634
- throw error;
4958
+ return;
4635
4959
  }
4636
4960
  });
4637
4961
  }
@@ -4691,7 +5015,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
4691
5015
  const runMap = new Map;
4692
5016
  const conditions = [
4693
5017
  eq2(logTable.type, "run_event"),
4694
- sql27`${logTable.body} ? 'runId'`,
5018
+ sql33`${logTable.body} ? 'runId'`,
4695
5019
  eq2(roomTable.agentId, this.agentId)
4696
5020
  ];
4697
5021
  if (params.roomId) {
@@ -4706,9 +5030,9 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
4706
5030
  const whereClause = and(...conditions);
4707
5031
  const eventLimit = Math.max(limit * 20, 200);
4708
5032
  const runEventRows = await tx.select({
4709
- runId: sql27`(${logTable.body} ->> 'runId')`,
4710
- status: sql27`(${logTable.body} ->> 'status')`,
4711
- messageId: sql27`(${logTable.body} ->> 'messageId')`,
5033
+ runId: sql33`(${logTable.body} ->> 'runId')`,
5034
+ status: sql33`(${logTable.body} ->> 'status')`,
5035
+ messageId: sql33`(${logTable.body} ->> 'messageId')`,
4712
5036
  rawBody: logTable.body,
4713
5037
  createdAt: logTable.createdAt,
4714
5038
  roomId: logTable.roomId,
@@ -4755,18 +5079,18 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
4755
5079
  }
4756
5080
  }
4757
5081
  const createdAt = row.createdAt instanceof Date ? row.createdAt : new Date(row.createdAt);
4758
- const timestamp19 = createdAt.getTime();
5082
+ const timestamp24 = createdAt.getTime();
4759
5083
  const bodyStatus = body?.status;
4760
5084
  const eventStatus = row.status ?? bodyStatus;
4761
5085
  if (eventStatus === "started") {
4762
5086
  const currentStartedAt = summary.startedAt === null ? null : typeof summary.startedAt === "bigint" ? Number(summary.startedAt) : summary.startedAt;
4763
- summary.startedAt = currentStartedAt === null ? timestamp19 : Math.min(currentStartedAt, timestamp19);
5087
+ summary.startedAt = currentStartedAt === null ? timestamp24 : Math.min(currentStartedAt, timestamp24);
4764
5088
  } else if (eventStatus === "completed" || eventStatus === "timeout" || eventStatus === "error") {
4765
5089
  summary.status = eventStatus;
4766
- summary.endedAt = timestamp19;
5090
+ summary.endedAt = timestamp24;
4767
5091
  if (summary.startedAt !== null) {
4768
5092
  const startedAtNum = typeof summary.startedAt === "bigint" ? Number(summary.startedAt) : summary.startedAt;
4769
- summary.durationMs = Math.max(timestamp19 - startedAtNum, 0);
5093
+ summary.durationMs = Math.max(timestamp24 - startedAtNum, 0);
4770
5094
  }
4771
5095
  }
4772
5096
  runMap.set(runId, summary);
@@ -4794,8 +5118,8 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
4794
5118
  }
4795
5119
  const runIds = limitedRuns.map((run) => run.runId).filter(Boolean);
4796
5120
  if (runIds.length > 0) {
4797
- const runIdArray = sql27`array[${sql27.join(runIds.map((id) => sql27`${id}`), sql27`, `)}]::text[]`;
4798
- const actionSummary = await this.db.execute(sql27`
5121
+ const runIdArray = sql33`array[${sql33.join(runIds.map((id) => sql33`${id}`), sql33`, `)}]::text[]`;
5122
+ const actionSummary = await this.db.execute(sql33`
4799
5123
  SELECT
4800
5124
  body->>'runId' as "runId",
4801
5125
  COUNT(*)::int as "actions",
@@ -4815,7 +5139,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
4815
5139
  counts.errors += Number(row.errors ?? 0);
4816
5140
  counts.modelCalls += Number(row.modelCalls ?? 0);
4817
5141
  }
4818
- const evaluatorSummary = await this.db.execute(sql27`
5142
+ const evaluatorSummary = await this.db.execute(sql33`
4819
5143
  SELECT
4820
5144
  body->>'runId' as "runId",
4821
5145
  COUNT(*)::int as "evaluators"
@@ -4831,7 +5155,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
4831
5155
  continue;
4832
5156
  counts.evaluators += Number(row.evaluators ?? 0);
4833
5157
  }
4834
- const genericSummary = await this.db.execute(sql27`
5158
+ const genericSummary = await this.db.execute(sql33`
4835
5159
  SELECT
4836
5160
  body->>'runId' as "runId",
4837
5161
  COUNT(*) FILTER (WHERE type LIKE 'useModel:%')::int as "modelLogs",
@@ -4879,13 +5203,13 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
4879
5203
  worldId: params.worldId,
4880
5204
  entityId: params.entityId,
4881
5205
  unique: params.unique,
4882
- tableName: params.tableName
5206
+ tableName: params.tableName ?? "messages"
4883
5207
  });
4884
5208
  }
4885
5209
  async searchMemoriesByEmbedding(embedding, params) {
4886
5210
  return this.withDatabase(async () => {
4887
5211
  const cleanVector = embedding.map((n) => Number.isFinite(n) ? Number(n.toFixed(6)) : 0);
4888
- const similarity = sql27`1 - (${cosineDistance(embeddingTable[this.embeddingDimension], cleanVector)})`;
5212
+ const similarity = sql33`1 - (${cosineDistance(embeddingTable[this.embeddingDimension], cleanVector)})`;
4889
5213
  const conditions = [eq2(memoryTable.type, params.tableName)];
4890
5214
  if (params.unique) {
4891
5215
  conditions.push(eq2(memoryTable.unique, true));
@@ -4951,8 +5275,8 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
4951
5275
  {
4952
5276
  id: memoryId,
4953
5277
  type: tableName,
4954
- content: sql27`${contentToInsert}::jsonb`,
4955
- metadata: sql27`${metadataToInsert}::jsonb`,
5278
+ content: sql33`${contentToInsert}::jsonb`,
5279
+ metadata: sql33`${metadataToInsert}::jsonb`,
4956
5280
  entityId: memory.entityId,
4957
5281
  roomId: memory.roomId,
4958
5282
  worldId: memory.worldId,
@@ -4982,15 +5306,15 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
4982
5306
  const contentToUpdate = typeof memory.content === "string" ? memory.content : JSON.stringify(memory.content ?? {});
4983
5307
  const metadataToUpdate = typeof memory.metadata === "string" ? memory.metadata : JSON.stringify(memory.metadata ?? {});
4984
5308
  await tx.update(memoryTable).set({
4985
- content: sql27`${contentToUpdate}::jsonb`,
5309
+ content: sql33`${contentToUpdate}::jsonb`,
4986
5310
  ...memory.metadata && {
4987
- metadata: sql27`${metadataToUpdate}::jsonb`
5311
+ metadata: sql33`${metadataToUpdate}::jsonb`
4988
5312
  }
4989
5313
  }).where(eq2(memoryTable.id, memory.id));
4990
5314
  } else if (memory.metadata) {
4991
5315
  const metadataToUpdate = typeof memory.metadata === "string" ? memory.metadata : JSON.stringify(memory.metadata ?? {});
4992
5316
  await tx.update(memoryTable).set({
4993
- metadata: sql27`${metadataToUpdate}::jsonb`
5317
+ metadata: sql33`${metadataToUpdate}::jsonb`
4994
5318
  }).where(eq2(memoryTable.id, memory.id));
4995
5319
  }
4996
5320
  if (memory.embedding && Array.isArray(memory.embedding)) {
@@ -5057,15 +5381,19 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
5057
5381
  }
5058
5382
  }
5059
5383
  async getMemoryFragments(tx, documentId) {
5060
- const fragments = await tx.select({ id: memoryTable.id }).from(memoryTable).where(and(eq2(memoryTable.agentId, this.agentId), sql27`${memoryTable.metadata}->>'documentId' = ${documentId}`));
5384
+ const fragments = await tx.select({ id: memoryTable.id }).from(memoryTable).where(and(eq2(memoryTable.agentId, this.agentId), sql33`${memoryTable.metadata}->>'documentId' = ${documentId}`));
5061
5385
  return fragments.map((f) => ({ id: f.id }));
5062
5386
  }
5063
- async deleteAllMemories(roomId, tableName) {
5387
+ async deleteAllMemories(roomIdsOrRoomId, tableName) {
5064
5388
  return this.withDatabase(async () => {
5389
+ const roomIds = Array.isArray(roomIdsOrRoomId) ? roomIdsOrRoomId : [roomIdsOrRoomId];
5390
+ if (roomIds.length === 0) {
5391
+ return;
5392
+ }
5065
5393
  await this.db.transaction(async (tx) => {
5066
- const rows = await tx.select({ id: memoryTable.id }).from(memoryTable).where(and(eq2(memoryTable.roomId, roomId), eq2(memoryTable.type, tableName)));
5394
+ const rows = await tx.select({ id: memoryTable.id }).from(memoryTable).where(and(inArray(memoryTable.roomId, roomIds), eq2(memoryTable.type, tableName), eq2(memoryTable.agentId, this.agentId)));
5067
5395
  const ids = rows.map((r) => r.id);
5068
- logger9.debug({ src: "plugin:sql", roomId, tableName, memoryCount: ids.length }, "Deleting all memories");
5396
+ logger9.debug({ src: "plugin:sql", roomIds, tableName, memoryCount: ids.length }, "Deleting all memories");
5069
5397
  if (ids.length === 0) {
5070
5398
  return;
5071
5399
  }
@@ -5073,19 +5401,36 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
5073
5401
  await this.deleteMemoryFragments(tx, memoryId);
5074
5402
  await tx.delete(embeddingTable).where(eq2(embeddingTable.memoryId, memoryId));
5075
5403
  }));
5076
- await tx.delete(memoryTable).where(and(eq2(memoryTable.roomId, roomId), eq2(memoryTable.type, tableName)));
5404
+ await tx.delete(memoryTable).where(and(inArray(memoryTable.roomId, roomIds), eq2(memoryTable.type, tableName), eq2(memoryTable.agentId, this.agentId)));
5077
5405
  });
5078
5406
  });
5079
5407
  }
5080
- async countMemories(roomId, unique3 = true, tableName = "") {
5081
- if (!tableName)
5082
- throw new Error("tableName is required");
5408
+ async countMemories(paramsOrRoomId, unique4 = true, tableName) {
5409
+ const params = typeof paramsOrRoomId === "string" ? {
5410
+ roomIds: [paramsOrRoomId],
5411
+ unique: unique4,
5412
+ tableName: tableName ?? "messages"
5413
+ } : {
5414
+ ...paramsOrRoomId,
5415
+ tableName: paramsOrRoomId.tableName ?? "messages",
5416
+ unique: paramsOrRoomId.unique ?? false
5417
+ };
5083
5418
  return this.withDatabase(async () => {
5084
- const conditions = [eq2(memoryTable.roomId, roomId), eq2(memoryTable.type, tableName)];
5085
- if (unique3) {
5419
+ const tableName2 = params.tableName ?? "messages";
5420
+ const conditions = [eq2(memoryTable.type, tableName2)];
5421
+ if (params.roomIds && params.roomIds.length > 0) {
5422
+ conditions.push(inArray(memoryTable.roomId, params.roomIds));
5423
+ }
5424
+ if (params.entityId) {
5425
+ conditions.push(eq2(memoryTable.entityId, params.entityId));
5426
+ }
5427
+ if (params.agentId) {
5428
+ conditions.push(eq2(memoryTable.agentId, params.agentId));
5429
+ }
5430
+ if (params.unique) {
5086
5431
  conditions.push(eq2(memoryTable.unique, true));
5087
5432
  }
5088
- const result = await this.db.select({ count: sql27`count(*)` }).from(memoryTable).where(and(...conditions));
5433
+ const result = await this.db.select({ count: sql33`count(*)` }).from(memoryTable).where(and(...conditions));
5089
5434
  const result0 = result[0];
5090
5435
  return Number(result0?.count ?? 0);
5091
5436
  });
@@ -5250,7 +5595,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
5250
5595
  roomId: participantTable.roomId
5251
5596
  }).from(participantTable).where(eq2(participantTable.entityId, entityId));
5252
5597
  const entities = await this.getEntitiesByIds([entityId]);
5253
- if (!entities || !entities.length) {
5598
+ if (!entities?.length) {
5254
5599
  return [];
5255
5600
  }
5256
5601
  return result.map((row) => ({
@@ -5365,22 +5710,22 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
5365
5710
  if (entityIds.length === 0) {
5366
5711
  return [];
5367
5712
  }
5368
- const entityFilter = sql27.join(entityIds.map((id) => sql27`(${relationshipTable.sourceEntityId} = ${id} OR ${relationshipTable.targetEntityId} = ${id})`), sql27` OR `);
5369
- let query = sql27`
5713
+ const entityFilter = sql33.join(entityIds.map((id) => sql33`(${relationshipTable.sourceEntityId} = ${id} OR ${relationshipTable.targetEntityId} = ${id})`), sql33` OR `);
5714
+ let query = sql33`
5370
5715
  SELECT * FROM ${relationshipTable}
5371
5716
  WHERE (${entityFilter})
5372
5717
  `;
5373
5718
  if (tags && tags.length > 0) {
5374
- query = sql27`
5719
+ query = sql33`
5375
5720
  ${query}
5376
- AND ${relationshipTable.tags} && CAST(ARRAY[${sql27.join(tags, sql27`, `)}] AS text[])
5721
+ AND ${relationshipTable.tags} && CAST(ARRAY[${sql33.join(tags, sql33`, `)}] AS text[])
5377
5722
  `;
5378
5723
  }
5379
5724
  if (typeof limit === "number") {
5380
- query = sql27`${query} LIMIT ${limit}`;
5725
+ query = sql33`${query} LIMIT ${limit}`;
5381
5726
  }
5382
5727
  if (typeof offset === "number" && offset > 0) {
5383
- query = sql27`${query} OFFSET ${offset}`;
5728
+ query = sql33`${query} OFFSET ${offset}`;
5384
5729
  }
5385
5730
  const result = await this.db.execute(query);
5386
5731
  return result.rows.map((relationship) => ({
@@ -5498,7 +5843,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
5498
5843
  const now = new Date;
5499
5844
  const metadata = task.metadata || {};
5500
5845
  const values = {
5501
- id: task.id,
5846
+ ...task.id ? { id: task.id } : {},
5502
5847
  name: task.name,
5503
5848
  description: task.description,
5504
5849
  roomId: task.roomId,
@@ -5518,7 +5863,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
5518
5863
  return this.withRetry(async () => {
5519
5864
  return this.withDatabase(async () => {
5520
5865
  const result = await this.db.select().from(taskTable).where(and(eq2(taskTable.agentId, this.agentId), ...params.roomId ? [eq2(taskTable.roomId, params.roomId)] : [], ...params.tags && params.tags.length > 0 ? [
5521
- sql27`${taskTable.tags} @> ARRAY[${sql27.join(params.tags.map((t) => sql27`${t}`), sql27`, `)}]::text[]`
5866
+ sql33`${taskTable.tags} @> ARRAY[${sql33.join(params.tags.map((t) => sql33`${t}`), sql33`, `)}]::text[]`
5522
5867
  ] : []));
5523
5868
  return result.map((row) => ({
5524
5869
  id: row.id,
@@ -5708,7 +6053,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
5708
6053
  }
5709
6054
  async getMessageServerByRlsServerId(rlsServerId) {
5710
6055
  return this.withDatabase(async () => {
5711
- const results = await this.db.execute(sql27`
6056
+ const results = await this.db.execute(sql33`
5712
6057
  SELECT id, name, source_type, source_id, metadata, created_at, updated_at
5713
6058
  FROM message_servers
5714
6059
  WHERE server_id = ${rlsServerId}
@@ -5821,7 +6166,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
5821
6166
  channelId: row.channelId,
5822
6167
  authorId: row.authorId,
5823
6168
  content: row.content,
5824
- rawMessage: row.rawMessage || undefined,
6169
+ rawMessage: asRawMessage(row.rawMessage),
5825
6170
  sourceType: row.sourceType || undefined,
5826
6171
  sourceId: row.sourceId || undefined,
5827
6172
  metadata: row.metadata || undefined,
@@ -5866,10 +6211,10 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
5866
6211
  channelId: r.channelId,
5867
6212
  authorId: r.authorId,
5868
6213
  content: r.content,
5869
- rawMessage: r.rawMessage || undefined,
6214
+ rawMessage: asRawMessage(r.rawMessage),
5870
6215
  sourceType: r.sourceType || undefined,
5871
6216
  sourceId: r.sourceId || undefined,
5872
- metadata: r.metadata || undefined,
6217
+ metadata: asMetadata(r.metadata),
5873
6218
  inReplyToRootMessageId: r.inReplyToRootMessageId,
5874
6219
  createdAt: r.createdAt,
5875
6220
  updatedAt: r.updatedAt
@@ -5987,18 +6332,27 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
5987
6332
  }, ids);
5988
6333
  });
5989
6334
  }
5990
- async getPairingRequests(channel, agentId) {
6335
+ async getPairingRequests(queries) {
5991
6336
  return this.withDatabase(async () => {
5992
- const results = await this.db.select().from(pairingRequestTable).where(and(eq2(pairingRequestTable.channel, channel), eq2(pairingRequestTable.agentId, agentId))).orderBy(pairingRequestTable.createdAt);
5993
- return results.map((row) => ({
5994
- id: row.id,
5995
- channel: row.channel,
5996
- senderId: row.senderId,
5997
- code: row.code,
5998
- createdAt: row.createdAt,
5999
- lastSeenAt: row.lastSeenAt,
6000
- metadata: row.metadata || undefined,
6001
- agentId: row.agentId
6337
+ if (queries.length === 0) {
6338
+ return [];
6339
+ }
6340
+ return Promise.all(queries.map(async ({ channel, agentId }) => {
6341
+ const results = await this.db.select().from(pairingRequestTable).where(and(eq2(pairingRequestTable.channel, channel), eq2(pairingRequestTable.agentId, agentId))).orderBy(pairingRequestTable.createdAt);
6342
+ return {
6343
+ channel,
6344
+ agentId,
6345
+ requests: results.map((row) => ({
6346
+ id: row.id,
6347
+ channel: row.channel,
6348
+ senderId: row.senderId,
6349
+ code: row.code,
6350
+ createdAt: row.createdAt,
6351
+ lastSeenAt: row.lastSeenAt,
6352
+ metadata: row.metadata || undefined,
6353
+ agentId: row.agentId
6354
+ }))
6355
+ };
6002
6356
  }));
6003
6357
  });
6004
6358
  }
@@ -6065,7 +6419,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
6065
6419
  }
6066
6420
  async isReady() {
6067
6421
  try {
6068
- await this.db.execute(sql27`SELECT 1`);
6422
+ await this.db.execute(sql33`SELECT 1`);
6069
6423
  return true;
6070
6424
  } catch {
6071
6425
  return false;
@@ -6168,8 +6522,12 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
6168
6522
  async patchComponents(_updates, _options) {}
6169
6523
  async upsertEntities(entities) {
6170
6524
  for (const entity of entities) {
6525
+ if (!entity.id) {
6526
+ await this.createEntities([entity]);
6527
+ continue;
6528
+ }
6171
6529
  const existing = await this.getEntitiesByIds([entity.id]);
6172
- if (existing && existing.length > 0) {
6530
+ if (existing.length > 0) {
6173
6531
  await this.updateEntity(entity);
6174
6532
  } else {
6175
6533
  await this.createEntities([entity]);
@@ -6186,11 +6544,17 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
6186
6544
  if (params.agentId) {
6187
6545
  conditions.push(eq2(entityTable.agentId, params.agentId));
6188
6546
  }
6189
- if (params.componentType) {
6190
- const subquery = sql27`EXISTS (
6547
+ if (params.componentType || params.worldId) {
6548
+ const subConditions = [sql33`${componentTable.entityId} = ${entityTable.id}`];
6549
+ if (params.componentType) {
6550
+ subConditions.push(sql33`${componentTable.type} = ${params.componentType}`);
6551
+ }
6552
+ if (params.worldId) {
6553
+ subConditions.push(sql33`${componentTable.worldId} = ${params.worldId}`);
6554
+ }
6555
+ const subquery = sql33`EXISTS (
6191
6556
  SELECT 1 FROM ${componentTable}
6192
- WHERE ${componentTable.entityId} = ${entityTable.id}
6193
- AND ${componentTable.type} = ${params.componentType}
6557
+ WHERE ${sql33.join(subConditions, sql33` AND `)}
6194
6558
  )`;
6195
6559
  conditions.push(subquery);
6196
6560
  }
@@ -6202,13 +6566,27 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
6202
6566
  query = query.offset(params.offset);
6203
6567
  }
6204
6568
  const result = await query;
6205
- return result.map((row) => ({
6569
+ const entities = result.map((row) => ({
6206
6570
  ...row,
6207
6571
  id: row.id,
6208
6572
  agentId: row.agentId,
6209
6573
  names: row.names || [],
6210
6574
  metadata: row.metadata || {}
6211
6575
  }));
6576
+ if (params.includeAllComponents && entities.length > 0) {
6577
+ const entityIds = entities.flatMap((entity) => entity.id ? [entity.id] : []);
6578
+ const components = await this.getComponentsForEntities(entityIds, params.worldId);
6579
+ const componentsByEntity = new Map;
6580
+ for (const comp of components) {
6581
+ const list = componentsByEntity.get(comp.entityId) ?? [];
6582
+ list.push(comp);
6583
+ componentsByEntity.set(comp.entityId, list);
6584
+ }
6585
+ for (const entity of entities) {
6586
+ entity.components = entity.id ? componentsByEntity.get(entity.id) ?? [] : [];
6587
+ }
6588
+ }
6589
+ return entities;
6212
6590
  });
6213
6591
  }
6214
6592
  async updateEntities(entities) {
@@ -6273,8 +6651,8 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
6273
6651
  }
6274
6652
  async createMemories(memories) {
6275
6653
  const ids = [];
6276
- for (const { memory, tableName, unique: unique3 } of memories) {
6277
- const memoryWithUnique = unique3 !== undefined ? { ...memory, unique: unique3 } : memory;
6654
+ for (const { memory, tableName, unique: unique4 } of memories) {
6655
+ const memoryWithUnique = unique4 !== undefined ? { ...memory, unique: unique4 } : memory;
6278
6656
  const id = await this.createMemory(memoryWithUnique, tableName);
6279
6657
  ids.push(id);
6280
6658
  }
@@ -6716,7 +7094,7 @@ class PgDatabaseAdapter extends BaseDrizzleAdapter {
6716
7094
 
6717
7095
  // pg/manager.ts
6718
7096
  import { logger as logger11, validateUuid as validateUuid2 } from "@elizaos/core";
6719
- import { sql as sql28 } from "drizzle-orm";
7097
+ import { sql as sql34 } from "drizzle-orm";
6720
7098
  import { drizzle } from "drizzle-orm/node-postgres";
6721
7099
  import { Pool } from "pg";
6722
7100
 
@@ -6778,7 +7156,7 @@ class PostgresConnectionManager {
6778
7156
  throw new Error(`Invalid UUID format for entity context: ${entityId}`);
6779
7157
  }
6780
7158
  try {
6781
- await tx.execute(sql28.raw(`SET LOCAL app.entity_id = '${entityId}'`));
7159
+ await tx.execute(sql34.raw(`SET LOCAL app.entity_id = '${entityId}'`));
6782
7160
  logger11.debug(`[Entity Context] Set app.entity_id = ${entityId}`);
6783
7161
  } catch (error) {
6784
7162
  const errorMessage = error instanceof Error ? error.message : String(error);
@@ -6805,7 +7183,8 @@ class PgliteDatabaseAdapter extends BaseDrizzleAdapter {
6805
7183
  constructor(agentId, manager) {
6806
7184
  super(agentId);
6807
7185
  this.manager = manager;
6808
- this.db = drizzle2(this.manager.getConnection());
7186
+ const drizzleAny = drizzle2;
7187
+ this.db = drizzleAny(this.manager.getConnection());
6809
7188
  }
6810
7189
  async withEntityContext(_entityId, callback) {
6811
7190
  return this.db.transaction(callback);
@@ -6840,7 +7219,14 @@ class PgliteDatabaseAdapter extends BaseDrizzleAdapter {
6840
7219
  async withDatabase(operation) {
6841
7220
  if (this.manager.isShuttingDown()) {
6842
7221
  const error = new Error("Database is shutting down - operation rejected");
6843
- logger12.warn({ src: "plugin:sql", error: error.message }, "Database operation rejected during shutdown");
7222
+ logger12.info({ src: "plugin:sql", error: error.message }, "Database operation rejected during shutdown");
7223
+ throw error;
7224
+ }
7225
+ const managerWithInit = this.manager;
7226
+ await managerWithInit.initialize?.();
7227
+ if (this.manager.isShuttingDown()) {
7228
+ const error = new Error("Database is shutting down - operation rejected");
7229
+ logger12.info({ src: "plugin:sql", error: error.message }, "Database operation rejected during shutdown");
6844
7230
  throw error;
6845
7231
  }
6846
7232
  return operation();
@@ -6851,7 +7237,8 @@ class PgliteDatabaseAdapter extends BaseDrizzleAdapter {
6851
7237
  logger12.debug({ src: "plugin:sql" }, "PGliteDatabaseAdapter initialized");
6852
7238
  }
6853
7239
  async isReady() {
6854
- return !this.manager.isShuttingDown();
7240
+ const managerWithState = this.manager;
7241
+ return !this.manager.isShuttingDown() && managerWithState.isInitialized?.() === true;
6855
7242
  }
6856
7243
  async close() {
6857
7244
  await this.manager.close();
@@ -6867,12 +7254,60 @@ class PgliteDatabaseAdapter extends BaseDrizzleAdapter {
6867
7254
  }
6868
7255
 
6869
7256
  // pglite/manager.ts
6870
- import { existsSync, mkdirSync, renameSync } from "node:fs";
7257
+ import { existsSync, readFileSync, unlinkSync } from "node:fs";
6871
7258
  import { PGlite } from "@electric-sql/pglite";
6872
7259
  import { fuzzystrmatch } from "@electric-sql/pglite/contrib/fuzzystrmatch";
6873
7260
  import { vector as vector2 } from "@electric-sql/pglite/vector";
6874
7261
  import { logger as logger13 } from "@elizaos/core";
6875
7262
 
7263
+ // pglite/errors.ts
7264
+ var PGLITE_ERROR_CODES = {
7265
+ ACTIVE_LOCK: "ELIZA_PGLITE_DATA_DIR_IN_USE",
7266
+ CORRUPT_DATA: "ELIZA_PGLITE_CORRUPT_DATA",
7267
+ MANUAL_RESET_REQUIRED: "ELIZA_PGLITE_MANUAL_RESET_REQUIRED"
7268
+ };
7269
+
7270
+ class PgliteInitError extends Error {
7271
+ code;
7272
+ dataDir;
7273
+ constructor(code, message, options) {
7274
+ super(message, { cause: options?.cause });
7275
+ this.name = "PgliteInitError";
7276
+ this.code = code;
7277
+ this.dataDir = options?.dataDir;
7278
+ }
7279
+ }
7280
+ function createPgliteInitError(code, message, options) {
7281
+ return new PgliteInitError(code, message, options);
7282
+ }
7283
+ function getPgliteErrorCode(err) {
7284
+ const seen = new Set;
7285
+ let current = err;
7286
+ while (current && !seen.has(current)) {
7287
+ seen.add(current);
7288
+ if (typeof current === "object" && current !== null && "code" in current && typeof current.code === "string") {
7289
+ const code = current.code;
7290
+ if (code === PGLITE_ERROR_CODES.ACTIVE_LOCK || code === PGLITE_ERROR_CODES.CORRUPT_DATA || code === PGLITE_ERROR_CODES.MANUAL_RESET_REQUIRED) {
7291
+ return code;
7292
+ }
7293
+ }
7294
+ if (current instanceof Error) {
7295
+ current = current.cause;
7296
+ continue;
7297
+ }
7298
+ if (typeof current === "object" && current !== null && "cause" in current) {
7299
+ current = current.cause;
7300
+ continue;
7301
+ }
7302
+ break;
7303
+ }
7304
+ return null;
7305
+ }
7306
+ function isFatalPgliteErrorCode(code) {
7307
+ return code === PGLITE_ERROR_CODES.ACTIVE_LOCK || code === PGLITE_ERROR_CODES.CORRUPT_DATA || code === PGLITE_ERROR_CODES.MANUAL_RESET_REQUIRED;
7308
+ }
7309
+
7310
+ // pglite/manager.ts
6876
7311
  class PGliteClientManager {
6877
7312
  client;
6878
7313
  options;
@@ -6890,6 +7325,9 @@ class PGliteClientManager {
6890
7325
  isShuttingDown() {
6891
7326
  return this.shuttingDown;
6892
7327
  }
7328
+ isInitialized() {
7329
+ return this.initialized;
7330
+ }
6893
7331
  async initialize() {
6894
7332
  if (this.initialized) {
6895
7333
  return;
@@ -6943,44 +7381,608 @@ class PGliteClientManager {
6943
7381
  }
6944
7382
  return String(error);
6945
7383
  }
7384
+ reconcilePglitePidFile(dataDir) {
7385
+ const pidPath = `${dataDir}/postmaster.pid`;
7386
+ if (!existsSync(pidPath)) {
7387
+ return "missing";
7388
+ }
7389
+ try {
7390
+ const content = readFileSync(pidPath, "utf-8");
7391
+ const firstLine = content.split(`
7392
+ `)[0]?.trim();
7393
+ const pid = parseInt(firstLine, 10);
7394
+ if (Number.isNaN(pid) || pid <= 0) {
7395
+ unlinkSync(pidPath);
7396
+ logger13.info({ src: "plugin:sql", dataDir, pidPath }, "Removed malformed PGlite postmaster.pid");
7397
+ return "cleared-malformed";
7398
+ }
7399
+ try {
7400
+ process.kill(pid, 0);
7401
+ logger13.warn({ src: "plugin:sql", dataDir, pid }, "PGlite data dir is already in use by another process");
7402
+ return "active";
7403
+ } catch (killErr) {
7404
+ const code = killErr.code;
7405
+ if (code === "ESRCH") {
7406
+ unlinkSync(pidPath);
7407
+ logger13.info({ src: "plugin:sql", dataDir, pid }, "Removed stale PGlite postmaster.pid");
7408
+ return "cleared-stale";
7409
+ }
7410
+ logger13.warn({ src: "plugin:sql", dataDir, pid, code }, "Cannot confirm PGlite postmaster.pid ownership");
7411
+ return "active-unconfirmed";
7412
+ }
7413
+ } catch (err) {
7414
+ logger13.warn({
7415
+ src: "plugin:sql",
7416
+ dataDir,
7417
+ error: this.getErrorText(err)
7418
+ }, "Failed to inspect PGlite postmaster.pid");
7419
+ return "check-failed";
7420
+ }
7421
+ }
7422
+ createActiveLockError(dataDir, cause) {
7423
+ return createPgliteInitError(PGLITE_ERROR_CODES.ACTIVE_LOCK, `PGlite data dir is already in use at ${dataDir}. Close the other Eliza process, or point PGLITE_DATA_DIR at a different directory before retrying.`, { cause, dataDir });
7424
+ }
7425
+ createManualResetRequiredError(dataDir, cause) {
7426
+ const errorText = this.getErrorText(cause);
7427
+ const corruptCause = createPgliteInitError(PGLITE_ERROR_CODES.CORRUPT_DATA, `PGlite data dir at ${dataDir} appears corrupt or unreadable: ${errorText}`, { cause, dataDir });
7428
+ return createPgliteInitError(PGLITE_ERROR_CODES.MANUAL_RESET_REQUIRED, `PGlite initialization failed for ${dataDir}: ${errorText}. Stop Eliza, then rename or delete only this directory before retrying: ${dataDir}`, { cause: corruptCause, dataDir });
7429
+ }
7430
+ async queryMigrationsSchema() {
7431
+ await this.client.query("CREATE SCHEMA IF NOT EXISTS migrations");
7432
+ this.initialized = true;
7433
+ }
6946
7434
  async initializeInternal() {
6947
7435
  try {
6948
- await this.client.query("CREATE SCHEMA IF NOT EXISTS migrations");
6949
- this.initialized = true;
7436
+ await this.queryMigrationsSchema();
6950
7437
  return;
6951
7438
  } catch (initialError) {
6952
7439
  const dataDir = this.getDataDir();
6953
7440
  if (!this.isFileBackedDataDir(dataDir)) {
6954
7441
  throw initialError;
6955
7442
  }
6956
- const errorText = this.getErrorText(initialError);
6957
- const backupDir = `${dataDir}.corrupt-${Date.now()}`;
6958
- logger13.error({
6959
- src: "plugin:sql",
6960
- dataDir,
6961
- backupDir,
6962
- error: errorText
6963
- }, "PGlite initialization failed; attempting recovery with a clean data directory");
6964
- try {
6965
- await this.client.close();
6966
- } catch {}
6967
- if (existsSync(dataDir)) {
6968
- renameSync(dataDir, backupDir);
7443
+ const pidStatus = this.reconcilePglitePidFile(dataDir);
7444
+ if (pidStatus === "active" || pidStatus === "active-unconfirmed" || pidStatus === "check-failed") {
7445
+ throw this.createActiveLockError(dataDir, initialError);
6969
7446
  }
6970
- mkdirSync(dataDir, { recursive: true });
6971
- this.client = this.createClient(this.options);
6972
- try {
6973
- await this.client.query("CREATE SCHEMA IF NOT EXISTS migrations");
6974
- this.initialized = true;
7447
+ if (pidStatus === "cleared-stale" || pidStatus === "cleared-malformed") {
6975
7448
  logger13.warn({
6976
7449
  src: "plugin:sql",
6977
7450
  dataDir,
6978
- backupDir
6979
- }, "Recovered from corrupted PGlite database directory");
6980
- } catch (recoveryError) {
6981
- throw new Error(`PGlite recovery failed for ${dataDir}: ${this.getErrorText(recoveryError)}`);
7451
+ error: this.getErrorText(initialError)
7452
+ }, "Retrying PGlite initialization after clearing postmaster.pid");
7453
+ try {
7454
+ await this.client.close();
7455
+ } catch {}
7456
+ this.client = this.createClient(this.options);
7457
+ try {
7458
+ await this.queryMigrationsSchema();
7459
+ return;
7460
+ } catch (retryError) {
7461
+ logger13.error({
7462
+ src: "plugin:sql",
7463
+ dataDir,
7464
+ error: this.getErrorText(retryError)
7465
+ }, "PGlite initialization still failed after clearing postmaster.pid");
7466
+ throw this.createManualResetRequiredError(dataDir, retryError);
7467
+ }
7468
+ }
7469
+ logger13.error({
7470
+ src: "plugin:sql",
7471
+ dataDir,
7472
+ error: this.getErrorText(initialError)
7473
+ }, "PGlite initialization failed; manual reset required");
7474
+ throw this.createManualResetRequiredError(dataDir, initialError);
7475
+ }
7476
+ }
7477
+ }
7478
+
7479
+ // services/advanced-memory-storage.ts
7480
+ import {
7481
+ ChannelType as ChannelType2,
7482
+ Service
7483
+ } from "@elizaos/core";
7484
+
7485
+ // utils/string-to-uuid.ts
7486
+ var UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
7487
+ function hashSegment(input, seed) {
7488
+ let hash = seed >>> 0;
7489
+ for (let index18 = 0;index18 < input.length; index18 += 1) {
7490
+ hash ^= input.charCodeAt(index18);
7491
+ hash = Math.imul(hash, 16777619);
7492
+ }
7493
+ return hash >>> 0;
7494
+ }
7495
+ function stringToUuid(target) {
7496
+ const value = typeof target === "number" ? target.toString() : target;
7497
+ if (typeof value !== "string") {
7498
+ throw new TypeError("Value must be string");
7499
+ }
7500
+ if (UUID_PATTERN.test(value)) {
7501
+ return value;
7502
+ }
7503
+ const input = encodeURIComponent(value);
7504
+ const hex = [
7505
+ hashSegment(input, 2166136261),
7506
+ hashSegment(input, 2654435761),
7507
+ hashSegment(input, 2246822507),
7508
+ hashSegment(input, 3266489909)
7509
+ ].map((part) => part.toString(16).padStart(8, "0")).join("").slice(0, 32).split("");
7510
+ hex[12] = "0";
7511
+ hex[16] = (Number.parseInt(hex[16] ?? "0", 16) & 3 | 8).toString(16);
7512
+ return `${hex.slice(0, 8).join("")}-${hex.slice(8, 12).join("")}-${hex.slice(12, 16).join("")}-${hex.slice(16, 20).join("")}-${hex.slice(20, 32).join("")}`;
7513
+ }
7514
+
7515
+ // services/advanced-memory-storage.ts
7516
+ var ENTITY_RESOLUTION_SERVICE = "entity_resolution";
7517
+ var LONG_TERM_MEMORY_TABLE = "long_term_memories";
7518
+ var SESSION_SUMMARY_TABLE = "session_summaries";
7519
+ var ADVANCED_MEMORY_SOURCE = "advanced-memory";
7520
+ function isRecord(value) {
7521
+ return typeof value === "object" && value !== null && !Array.isArray(value);
7522
+ }
7523
+ function asRecord(value) {
7524
+ return isRecord(value) ? value : null;
7525
+ }
7526
+ function toJsonValue(value) {
7527
+ if (value === null)
7528
+ return null;
7529
+ if (typeof value === "string") {
7530
+ return value;
7531
+ }
7532
+ if (typeof value === "number") {
7533
+ return value;
7534
+ }
7535
+ if (typeof value === "boolean") {
7536
+ return value;
7537
+ }
7538
+ if (Array.isArray(value)) {
7539
+ return value.map((entry) => toJsonValue(entry)).filter((entry) => entry !== undefined);
7540
+ }
7541
+ if (isRecord(value)) {
7542
+ const entries = Object.entries(value).map(([key, entry]) => {
7543
+ const jsonValue = toJsonValue(entry);
7544
+ return jsonValue === undefined ? null : [key, jsonValue];
7545
+ }).filter((entry) => entry !== null);
7546
+ return Object.fromEntries(entries);
7547
+ }
7548
+ return;
7549
+ }
7550
+ function toJsonRecord(value) {
7551
+ const jsonValue = toJsonValue(value);
7552
+ return isRecord(jsonValue) ? jsonValue : undefined;
7553
+ }
7554
+ function buildCustomMemoryMetadata(params) {
7555
+ const metadata = {
7556
+ ...params.existing ?? {},
7557
+ type: "custom",
7558
+ scope: params.scope,
7559
+ timestamp: params.timestamp,
7560
+ advancedMemory: params.advancedMemory
7561
+ };
7562
+ if (params.source) {
7563
+ metadata.source = params.source;
7564
+ }
7565
+ return metadata;
7566
+ }
7567
+ function asString(value) {
7568
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : undefined;
7569
+ }
7570
+ function asNumber(value) {
7571
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
7572
+ }
7573
+ function asStringArray(value) {
7574
+ if (!Array.isArray(value))
7575
+ return;
7576
+ const values = value.filter((entry) => typeof entry === "string");
7577
+ return values.length > 0 ? values : undefined;
7578
+ }
7579
+ function toDate(value, fallback) {
7580
+ if (value instanceof Date && Number.isFinite(value.getTime())) {
7581
+ return value;
7582
+ }
7583
+ if (typeof value === "number" && Number.isFinite(value)) {
7584
+ const parsed = new Date(value);
7585
+ if (Number.isFinite(parsed.getTime()))
7586
+ return parsed;
7587
+ }
7588
+ if (typeof value === "string" && value.trim().length > 0) {
7589
+ const parsed = new Date(value);
7590
+ if (Number.isFinite(parsed.getTime()))
7591
+ return parsed;
7592
+ }
7593
+ return fallback ?? new Date;
7594
+ }
7595
+ function getMemoryText(memory) {
7596
+ return typeof memory.content?.text === "string" ? memory.content.text : "";
7597
+ }
7598
+ function getAdvancedMemoryEnvelope(memory) {
7599
+ const metadata = asRecord(memory.metadata);
7600
+ const advancedMemory = asRecord(metadata?.advancedMemory);
7601
+ if (!advancedMemory) {
7602
+ return null;
7603
+ }
7604
+ const kind = asString(advancedMemory.kind);
7605
+ if (kind !== "long_term_memory" && kind !== "session_summary") {
7606
+ return null;
7607
+ }
7608
+ return {
7609
+ kind,
7610
+ originalEntityId: asString(advancedMemory.originalEntityId),
7611
+ anchorEntityId: asString(advancedMemory.anchorEntityId),
7612
+ category: asString(advancedMemory.category),
7613
+ confidence: asNumber(advancedMemory.confidence),
7614
+ source: asString(advancedMemory.source),
7615
+ semanticMetadata: toJsonRecord(advancedMemory.semanticMetadata),
7616
+ messageCount: asNumber(advancedMemory.messageCount),
7617
+ lastMessageOffset: asNumber(advancedMemory.lastMessageOffset),
7618
+ startTime: asString(advancedMemory.startTime),
7619
+ endTime: asString(advancedMemory.endTime),
7620
+ topics: asStringArray(advancedMemory.topics),
7621
+ summaryMetadata: toJsonRecord(advancedMemory.summaryMetadata),
7622
+ updatedAt: asString(advancedMemory.updatedAt),
7623
+ lastAccessedAt: asString(advancedMemory.lastAccessedAt),
7624
+ accessCount: asNumber(advancedMemory.accessCount)
7625
+ };
7626
+ }
7627
+
7628
+ class AdvancedMemoryStorageService extends Service {
7629
+ static serviceType = "memoryStorage";
7630
+ capabilityDescription = "Persistent advanced-memory storage backed by SQL memory tables";
7631
+ static async start(runtime) {
7632
+ const service = new AdvancedMemoryStorageService;
7633
+ await service.initialize(runtime);
7634
+ return service;
7635
+ }
7636
+ async initialize(runtime) {
7637
+ this.runtime = runtime;
7638
+ }
7639
+ async stop() {}
7640
+ getMemoryWorldId() {
7641
+ return stringToUuid(`advanced-memory:world:${this.runtime.agentId}`);
7642
+ }
7643
+ getLongTermRoomId(entityId) {
7644
+ return stringToUuid(`advanced-memory:long-term:${this.runtime.agentId}:${entityId}`);
7645
+ }
7646
+ async ensureMemoryWorld() {
7647
+ const worldId = this.getMemoryWorldId();
7648
+ const world = {
7649
+ id: worldId,
7650
+ agentId: this.runtime.agentId,
7651
+ name: "Advanced Memory",
7652
+ metadata: {
7653
+ purpose: ADVANCED_MEMORY_SOURCE
7654
+ },
7655
+ createdAt: new Date
7656
+ };
7657
+ await this.runtime.ensureWorldExists(world);
7658
+ return worldId;
7659
+ }
7660
+ async ensureLongTermRoom(entityId, worldId) {
7661
+ const roomId = this.getLongTermRoomId(entityId);
7662
+ const room = {
7663
+ id: roomId,
7664
+ agentId: this.runtime.agentId,
7665
+ worldId,
7666
+ source: ADVANCED_MEMORY_SOURCE,
7667
+ type: ChannelType2.SELF,
7668
+ name: `Advanced Memory ${entityId.slice(0, 8)}`,
7669
+ metadata: {
7670
+ purpose: "long_term_memory",
7671
+ entityId
7672
+ },
7673
+ createdAt: new Date
7674
+ };
7675
+ await this.runtime.ensureRoomExists(room);
7676
+ return roomId;
7677
+ }
7678
+ async getEntityResolutionService() {
7679
+ const existing = this.runtime.getService(ENTITY_RESOLUTION_SERVICE);
7680
+ if (existing) {
7681
+ return existing;
7682
+ }
7683
+ if (!this.runtime.hasService(ENTITY_RESOLUTION_SERVICE)) {
7684
+ return null;
7685
+ }
7686
+ try {
7687
+ return await this.runtime.getServiceLoadPromise(ENTITY_RESOLUTION_SERVICE);
7688
+ } catch {
7689
+ return null;
7690
+ }
7691
+ }
7692
+ async getIdentityGroup(entityId) {
7693
+ const resolution = await this.getEntityResolutionService();
7694
+ if (!resolution) {
7695
+ return new Set([entityId]);
7696
+ }
7697
+ const group = new Set([entityId]);
7698
+ const queue = [entityId];
7699
+ while (queue.length > 0) {
7700
+ const current = queue.shift();
7701
+ const links = await resolution.getConfirmedLinks(current);
7702
+ for (const link of links) {
7703
+ const other = link.entityA === current ? link.entityB : link.entityA;
7704
+ if (!group.has(other)) {
7705
+ group.add(other);
7706
+ queue.push(other);
7707
+ }
6982
7708
  }
6983
7709
  }
7710
+ return group;
7711
+ }
7712
+ async getAnchorEntityId(entityId) {
7713
+ const group = await this.getIdentityGroup(entityId);
7714
+ return Array.from(group).sort()[0];
7715
+ }
7716
+ parseLongTermMemory(memory) {
7717
+ const envelope = getAdvancedMemoryEnvelope(memory);
7718
+ if (!envelope || envelope.kind !== "long_term_memory" || !memory.id || !memory.agentId) {
7719
+ return null;
7720
+ }
7721
+ return {
7722
+ id: memory.id,
7723
+ agentId: memory.agentId,
7724
+ entityId: envelope.originalEntityId ?? envelope.anchorEntityId ?? memory.entityId,
7725
+ category: envelope.category ?? "semantic",
7726
+ content: getMemoryText(memory),
7727
+ metadata: envelope.semanticMetadata,
7728
+ embedding: Array.isArray(memory.embedding) ? memory.embedding : undefined,
7729
+ confidence: envelope.confidence,
7730
+ source: envelope.source,
7731
+ createdAt: toDate(memory.createdAt),
7732
+ updatedAt: toDate(envelope.updatedAt, toDate(memory.createdAt)),
7733
+ lastAccessedAt: envelope.lastAccessedAt ? toDate(envelope.lastAccessedAt) : undefined,
7734
+ accessCount: envelope.accessCount ?? 0
7735
+ };
7736
+ }
7737
+ parseSessionSummary(memory) {
7738
+ const envelope = getAdvancedMemoryEnvelope(memory);
7739
+ if (!envelope || envelope.kind !== "session_summary" || !memory.id || !memory.agentId || !memory.roomId) {
7740
+ return null;
7741
+ }
7742
+ return {
7743
+ id: memory.id,
7744
+ agentId: memory.agentId,
7745
+ roomId: memory.roomId,
7746
+ entityId: envelope.originalEntityId ?? memory.entityId,
7747
+ summary: getMemoryText(memory),
7748
+ messageCount: envelope.messageCount ?? 0,
7749
+ lastMessageOffset: envelope.lastMessageOffset ?? 0,
7750
+ startTime: toDate(envelope.startTime, toDate(memory.createdAt)),
7751
+ endTime: toDate(envelope.endTime, toDate(memory.createdAt)),
7752
+ topics: envelope.topics,
7753
+ metadata: envelope.summaryMetadata,
7754
+ embedding: Array.isArray(memory.embedding) ? memory.embedding : undefined,
7755
+ createdAt: toDate(memory.createdAt),
7756
+ updatedAt: toDate(envelope.updatedAt, toDate(memory.createdAt))
7757
+ };
7758
+ }
7759
+ sortLongTermMemories(memories) {
7760
+ return [...memories].sort((left, right) => {
7761
+ const leftUpdated = left.updatedAt.getTime();
7762
+ const rightUpdated = right.updatedAt.getTime();
7763
+ if (rightUpdated !== leftUpdated) {
7764
+ return rightUpdated - leftUpdated;
7765
+ }
7766
+ const leftConfidence = left.confidence ?? 0;
7767
+ const rightConfidence = right.confidence ?? 0;
7768
+ if (rightConfidence !== leftConfidence) {
7769
+ return rightConfidence - leftConfidence;
7770
+ }
7771
+ return right.createdAt.getTime() - left.createdAt.getTime();
7772
+ });
7773
+ }
7774
+ sortSessionSummaries(summaries) {
7775
+ return [...summaries].sort((left, right) => {
7776
+ const leftUpdated = left.updatedAt.getTime();
7777
+ const rightUpdated = right.updatedAt.getTime();
7778
+ if (rightUpdated !== leftUpdated) {
7779
+ return rightUpdated - leftUpdated;
7780
+ }
7781
+ return right.createdAt.getTime() - left.createdAt.getTime();
7782
+ });
7783
+ }
7784
+ async storeLongTermMemory(memory) {
7785
+ const now = new Date;
7786
+ const anchorEntityId = await this.getAnchorEntityId(memory.entityId);
7787
+ const worldId = await this.ensureMemoryWorld();
7788
+ const roomId = await this.ensureLongTermRoom(anchorEntityId, worldId);
7789
+ const advancedMemory = toJsonRecord({
7790
+ kind: "long_term_memory",
7791
+ originalEntityId: memory.entityId,
7792
+ anchorEntityId,
7793
+ category: memory.category,
7794
+ confidence: memory.confidence,
7795
+ source: memory.source,
7796
+ semanticMetadata: memory.metadata,
7797
+ updatedAt: now.toISOString(),
7798
+ accessCount: 0
7799
+ });
7800
+ if (!advancedMemory) {
7801
+ throw new Error("Long-term memory metadata is not JSON-serializable");
7802
+ }
7803
+ const id = await this.runtime.createMemory({
7804
+ agentId: this.runtime.agentId,
7805
+ entityId: anchorEntityId,
7806
+ roomId,
7807
+ worldId,
7808
+ content: { text: memory.content },
7809
+ metadata: buildCustomMemoryMetadata({
7810
+ scope: "shared",
7811
+ timestamp: now.getTime(),
7812
+ source: memory.source,
7813
+ advancedMemory
7814
+ }),
7815
+ embedding: memory.embedding,
7816
+ createdAt: now.getTime(),
7817
+ unique: false
7818
+ }, LONG_TERM_MEMORY_TABLE, false);
7819
+ const stored = await this.runtime.getMemoryById(id);
7820
+ const parsed = stored ? this.parseLongTermMemory(stored) : null;
7821
+ if (!parsed) {
7822
+ throw new Error("Failed to persist long-term memory");
7823
+ }
7824
+ return parsed;
7825
+ }
7826
+ async getLongTermMemories(agentId, entityId, opts) {
7827
+ const group = await this.getIdentityGroup(entityId);
7828
+ const roomIds = Array.from(group).map((memberEntityId) => this.getLongTermRoomId(memberEntityId));
7829
+ if (roomIds.length === 0) {
7830
+ return [];
7831
+ }
7832
+ const memories = await this.runtime.getMemoriesByRoomIds({
7833
+ tableName: LONG_TERM_MEMORY_TABLE,
7834
+ roomIds,
7835
+ limit: Math.max((opts?.limit ?? 20) * roomIds.length * 4, 80)
7836
+ });
7837
+ const filtered = memories.filter((memory) => memory.agentId === agentId).map((memory) => this.parseLongTermMemory(memory)).filter((memory) => memory !== null).filter((memory) => opts?.category ? memory.category === opts.category : true);
7838
+ return this.sortLongTermMemories(filtered).slice(0, opts?.limit ?? 20);
7839
+ }
7840
+ async updateLongTermMemory(id, agentId, entityId, updates) {
7841
+ const existing = await this.runtime.getMemoryById(id);
7842
+ const parsed = existing ? this.parseLongTermMemory(existing) : null;
7843
+ if (!existing || !parsed || existing.agentId !== agentId) {
7844
+ throw new Error(`Long-term memory ${id} not found`);
7845
+ }
7846
+ const allowedGroup = await this.getIdentityGroup(entityId);
7847
+ if (!allowedGroup.has(parsed.entityId)) {
7848
+ throw new Error(`Long-term memory ${id} does not belong to entity ${entityId}`);
7849
+ }
7850
+ const currentEnvelope = getAdvancedMemoryEnvelope(existing);
7851
+ const updatedAt = new Date;
7852
+ const advancedMemory = toJsonRecord({
7853
+ ...currentEnvelope ?? {},
7854
+ kind: "long_term_memory",
7855
+ originalEntityId: currentEnvelope?.originalEntityId ?? entityId,
7856
+ anchorEntityId: parsed.entityId,
7857
+ category: updates.category ?? parsed.category,
7858
+ confidence: updates.confidence ?? parsed.confidence,
7859
+ source: updates.source ?? parsed.source,
7860
+ semanticMetadata: updates.metadata ?? parsed.metadata,
7861
+ updatedAt: updatedAt.toISOString(),
7862
+ lastAccessedAt: updates.lastAccessedAt?.toISOString(),
7863
+ accessCount: updates.accessCount ?? parsed.accessCount ?? 0
7864
+ });
7865
+ if (!advancedMemory) {
7866
+ throw new Error("Updated long-term memory metadata is not JSON-serializable");
7867
+ }
7868
+ await this.runtime.updateMemory({
7869
+ id,
7870
+ content: {
7871
+ text: updates.content ?? parsed.content
7872
+ },
7873
+ metadata: buildCustomMemoryMetadata({
7874
+ existing: asRecord(existing.metadata),
7875
+ scope: "shared",
7876
+ timestamp: updatedAt.getTime(),
7877
+ source: updates.source ?? parsed.source,
7878
+ advancedMemory
7879
+ }),
7880
+ ...updates.embedding ? { embedding: updates.embedding } : {}
7881
+ });
7882
+ }
7883
+ async deleteLongTermMemory(id, agentId, entityId) {
7884
+ const existing = await this.runtime.getMemoryById(id);
7885
+ const parsed = existing ? this.parseLongTermMemory(existing) : null;
7886
+ if (!existing || !parsed || existing.agentId !== agentId) {
7887
+ throw new Error(`Long-term memory ${id} not found`);
7888
+ }
7889
+ const allowedGroup = await this.getIdentityGroup(entityId);
7890
+ if (!allowedGroup.has(parsed.entityId)) {
7891
+ throw new Error(`Long-term memory ${id} does not belong to entity ${entityId}`);
7892
+ }
7893
+ await this.runtime.deleteMemory(id);
7894
+ }
7895
+ async storeSessionSummary(summary) {
7896
+ const now = new Date;
7897
+ const advancedMemory = toJsonRecord({
7898
+ kind: "session_summary",
7899
+ originalEntityId: summary.entityId,
7900
+ messageCount: summary.messageCount,
7901
+ lastMessageOffset: summary.lastMessageOffset,
7902
+ startTime: summary.startTime.toISOString(),
7903
+ endTime: summary.endTime.toISOString(),
7904
+ topics: summary.topics,
7905
+ summaryMetadata: summary.metadata,
7906
+ updatedAt: now.toISOString()
7907
+ });
7908
+ if (!advancedMemory) {
7909
+ throw new Error("Session summary metadata is not JSON-serializable");
7910
+ }
7911
+ const id = await this.runtime.createMemory({
7912
+ agentId: this.runtime.agentId,
7913
+ entityId: summary.entityId ?? this.runtime.agentId,
7914
+ roomId: summary.roomId,
7915
+ worldId: this.getMemoryWorldId(),
7916
+ content: { text: summary.summary },
7917
+ metadata: buildCustomMemoryMetadata({
7918
+ scope: "room",
7919
+ timestamp: now.getTime(),
7920
+ advancedMemory
7921
+ }),
7922
+ embedding: summary.embedding,
7923
+ createdAt: now.getTime(),
7924
+ unique: false
7925
+ }, SESSION_SUMMARY_TABLE, false);
7926
+ const stored = await this.runtime.getMemoryById(id);
7927
+ const parsed = stored ? this.parseSessionSummary(stored) : null;
7928
+ if (!parsed) {
7929
+ throw new Error("Failed to persist session summary");
7930
+ }
7931
+ return parsed;
7932
+ }
7933
+ async getCurrentSessionSummary(agentId, roomId) {
7934
+ const summaries = await this.getSessionSummaries(agentId, roomId, 1);
7935
+ return summaries[0] ?? null;
7936
+ }
7937
+ async updateSessionSummary(id, agentId, roomId, updates) {
7938
+ const existing = await this.runtime.getMemoryById(id);
7939
+ const parsed = existing ? this.parseSessionSummary(existing) : null;
7940
+ if (!existing || !parsed || existing.agentId !== agentId || existing.roomId !== roomId) {
7941
+ throw new Error(`Session summary ${id} not found`);
7942
+ }
7943
+ const currentEnvelope = getAdvancedMemoryEnvelope(existing);
7944
+ const updatedAt = new Date;
7945
+ const advancedMemory = toJsonRecord({
7946
+ ...currentEnvelope ?? {},
7947
+ kind: "session_summary",
7948
+ originalEntityId: currentEnvelope?.originalEntityId ?? parsed.entityId,
7949
+ messageCount: updates.messageCount ?? parsed.messageCount,
7950
+ lastMessageOffset: updates.lastMessageOffset ?? parsed.lastMessageOffset,
7951
+ startTime: (updates.startTime ?? parsed.startTime).toISOString(),
7952
+ endTime: (updates.endTime ?? parsed.endTime).toISOString(),
7953
+ topics: updates.topics ?? parsed.topics,
7954
+ summaryMetadata: updates.metadata ?? parsed.metadata,
7955
+ updatedAt: updatedAt.toISOString()
7956
+ });
7957
+ if (!advancedMemory) {
7958
+ throw new Error("Updated session summary metadata is not JSON-serializable");
7959
+ }
7960
+ await this.runtime.updateMemory({
7961
+ id,
7962
+ content: {
7963
+ text: updates.summary ?? parsed.summary
7964
+ },
7965
+ metadata: buildCustomMemoryMetadata({
7966
+ existing: asRecord(existing.metadata),
7967
+ scope: "room",
7968
+ timestamp: updatedAt.getTime(),
7969
+ advancedMemory
7970
+ }),
7971
+ ...updates.embedding ? { embedding: updates.embedding } : {}
7972
+ });
7973
+ }
7974
+ async getSessionSummaries(agentId, roomId, limit = 5) {
7975
+ if (limit <= 0) {
7976
+ return [];
7977
+ }
7978
+ const memories = await this.runtime.getMemories({
7979
+ agentId,
7980
+ roomId,
7981
+ tableName: SESSION_SUMMARY_TABLE,
7982
+ count: Math.max(limit * 4, 20),
7983
+ unique: false
7984
+ });
7985
+ return this.sortSessionSummaries(memories.map((memory) => this.parseSessionSummary(memory)).filter((memory) => memory !== null)).slice(0, limit);
6984
7986
  }
6985
7987
  }
6986
7988
 
@@ -7065,21 +8067,26 @@ function createDatabaseAdapter(config, agentId) {
7065
8067
  }
7066
8068
  const dataDir = resolvePgliteDir(config.dataDir);
7067
8069
  if (dataDir && !dataDir.includes("://")) {
7068
- mkdirSync2(dataDir, { recursive: true });
8070
+ mkdirSync(dataDir, { recursive: true });
7069
8071
  }
7070
8072
  if (!shouldReusePgliteManager(globalSingletons.pgLiteClientManager)) {
7071
8073
  globalSingletons.pgLiteClientManager = new PGliteClientManager({ dataDir });
7072
8074
  }
7073
- return new PgliteDatabaseAdapter(agentId, globalSingletons.pgLiteClientManager);
8075
+ const manager = globalSingletons.pgLiteClientManager;
8076
+ if (!manager) {
8077
+ throw new Error("[plugin-sql] pgLiteClientManager not initialized before adapter creation");
8078
+ }
8079
+ return new PgliteDatabaseAdapter(agentId, manager);
7074
8080
  }
7075
8081
  var plugin = {
7076
8082
  name: "@elizaos/plugin-sql",
7077
8083
  description: "A plugin for SQL database access with dynamic schema migrations",
7078
8084
  priority: 0,
7079
8085
  schema: exports_schema,
8086
+ services: [AdvancedMemoryStorageService],
7080
8087
  init: async (_, runtime) => {
7081
- runtime.logger.info({ src: "plugin:sql", agentId: runtime.agentId }, "plugin-sql init starting");
7082
8088
  const runtimeWithAdapter = runtime;
8089
+ runtime.logger.info({ src: "plugin:sql", agentId: runtime.agentId }, "plugin-sql init starting");
7083
8090
  const adapterRegistered = typeof runtimeWithAdapter.hasDatabaseAdapter === "function" ? runtimeWithAdapter.hasDatabaseAdapter() : (() => {
7084
8091
  try {
7085
8092
  const existing = runtimeWithAdapter.getDatabaseAdapter?.() ?? runtimeWithAdapter.databaseAdapter ?? runtimeWithAdapter.adapter;
@@ -7099,24 +8106,67 @@ var plugin = {
7099
8106
  dataDir: typeof dataDir === "string" ? dataDir : undefined,
7100
8107
  postgresUrl: typeof postgresUrl === "string" ? postgresUrl : undefined
7101
8108
  }, runtime.agentId);
7102
- runtime.registerDatabaseAdapter(dbAdapter);
8109
+ runtimeWithAdapter.registerDatabaseAdapter(dbAdapter);
8110
+ await dbAdapter.initialize();
7103
8111
  runtime.logger.info({ src: "plugin:sql", agentId: runtime.agentId }, "Database adapter created and registered");
7104
8112
  }
7105
8113
  };
7106
8114
  var typescript_default = plugin;
7107
8115
  export {
8116
+ worldTable,
7108
8117
  uninstallRLS,
8118
+ taskTable,
7109
8119
  setServerContext,
8120
+ sessionSummaries,
8121
+ serverTable,
7110
8122
  exports_schema as schema,
8123
+ roomTable,
8124
+ relationshipTable,
7111
8125
  plugin,
8126
+ participantTable,
8127
+ pairingRequestTable,
8128
+ pairingAllowlistTable,
8129
+ messageTable,
8130
+ messageServerTable,
8131
+ messageServerAgentsTable,
8132
+ memoryTable,
8133
+ memoryAccessLogs,
8134
+ longTermMemories,
8135
+ logTable,
8136
+ isFatalPgliteErrorCode,
7112
8137
  installRLSFunctions,
8138
+ getRow,
8139
+ getPgliteErrorCode,
7113
8140
  getOrCreateRlsServer,
8141
+ getDb,
8142
+ factCandidateTable,
8143
+ entityTable,
8144
+ entityMergeCandidateTable,
8145
+ entityIdentityTable,
8146
+ embeddingTable,
7114
8147
  typescript_default as default,
8148
+ createPgliteInitError,
7115
8149
  createDatabaseAdapter,
8150
+ componentTable,
8151
+ channelTable,
8152
+ channelParticipantsTable,
8153
+ cacheTable,
8154
+ authSessionTable,
8155
+ authOwnerLoginTokenTable,
8156
+ authOwnerBindingTable,
8157
+ authIdentityTable,
8158
+ authIdentityCreatedAtDefault,
8159
+ authBootstrapJtiSeenTable,
8160
+ authAuditEventTable,
7116
8161
  assignAgentToServer,
8162
+ approvalRequestTable,
7117
8163
  applyRLSToNewTables,
7118
- DatabaseMigrationService
8164
+ agentTable,
8165
+ PgliteInitError,
8166
+ PGLITE_ERROR_CODES,
8167
+ DatabaseMigrationService,
8168
+ AdvancedMemoryStorageService
7119
8169
  };
7120
8170
 
7121
- //# debugId=606A9AD08C7E6C2364756E2164756E21
8171
+ //# debugId=064AB64C70B2F55A64756E2164756E21
7122
8172
  //# sourceMappingURL=index.node.js.map