@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.
- package/dist/base.d.ts +1102 -0
- package/dist/browser/index.browser.js +1526 -533
- package/dist/browser/index.browser.js.map +28 -18
- package/dist/browser/index.d.ts +2 -2
- package/dist/cjs/index.d.ts +2 -2
- package/dist/cjs/index.node.cjs +1934 -899
- package/dist/cjs/index.node.cjs.map +29 -15
- package/dist/index.d.ts +4 -2
- package/dist/index.js +2 -0
- package/dist/index.node.d.ts +17 -0
- package/dist/migration-service.d.ts +17 -0
- package/dist/migrations.d.ts +15 -0
- package/dist/node/index.d.ts +2 -2
- package/dist/node/index.node.js +1540 -490
- package/dist/node/index.node.js.map +29 -15
- package/dist/pg/adapter.d.ts +41 -0
- package/dist/pg/manager.d.ts +14 -0
- package/dist/pglite/adapter.d.ts +23 -0
- package/dist/pglite/errors.d.ts +20 -0
- package/dist/pglite/manager.d.ts +25 -0
- package/dist/rls.d.ts +13 -0
- package/dist/runtime-migrator/crypto-utils.d.ts +25 -0
- package/dist/runtime-migrator/drizzle-adapters/database-introspector.d.ts +58 -0
- package/dist/runtime-migrator/drizzle-adapters/diff-calculator.d.ts +77 -0
- package/dist/runtime-migrator/drizzle-adapters/snapshot-generator.d.ts +21 -0
- package/dist/runtime-migrator/drizzle-adapters/sql-generator.d.ts +38 -0
- package/dist/runtime-migrator/extension-manager.d.ts +6 -0
- package/dist/runtime-migrator/index.d.ts +8 -0
- package/dist/runtime-migrator/runtime-migrator.d.ts +95 -0
- package/dist/runtime-migrator/schema-transformer.d.ts +18 -0
- package/dist/runtime-migrator/storage/journal-storage.d.ts +10 -0
- package/dist/runtime-migrator/storage/migration-tracker.d.ts +13 -0
- package/dist/runtime-migrator/storage/snapshot-storage.d.ts +9 -0
- package/dist/runtime-migrator/types.d.ts +157 -0
- package/dist/schema/agent.d.ts +344 -0
- package/dist/schema/approvalRequests.d.ts +277 -0
- package/dist/schema/authAuditEvent.d.ts +153 -0
- package/dist/schema/authBootstrapJti.d.ts +49 -0
- package/dist/schema/authIdentity.d.ts +121 -0
- package/dist/schema/authOwnerBinding.d.ts +168 -0
- package/dist/schema/authOwnerLoginToken.d.ts +122 -0
- package/dist/schema/authSession.d.ts +225 -0
- package/dist/schema/cache.d.ts +97 -0
- package/dist/schema/channel.d.ts +177 -0
- package/dist/schema/channelParticipant.d.ts +41 -0
- package/dist/schema/component.d.ts +163 -0
- package/dist/schema/embedding.d.ts +204 -0
- package/dist/schema/entity.d.ts +125 -0
- package/dist/schema/entityIdentity.d.ts +577 -0
- package/dist/schema/index.d.ts +34 -0
- package/dist/schema/log.d.ts +114 -0
- package/dist/schema/longTermMemories.d.ts +254 -0
- package/dist/schema/memory.d.ts +185 -0
- package/dist/schema/memoryAccessLogs.d.ts +109 -0
- package/dist/schema/message.d.ts +194 -0
- package/dist/schema/messageServer.d.ts +126 -0
- package/dist/schema/messageServerAgent.d.ts +41 -0
- package/dist/schema/pairingAllowlist.d.ts +113 -0
- package/dist/schema/pairingRequest.d.ts +147 -0
- package/dist/schema/participant.d.ts +114 -0
- package/dist/schema/relationship.d.ts +156 -0
- package/dist/schema/room.d.ts +195 -0
- package/dist/schema/server.d.ts +64 -0
- package/dist/schema/sessionSummaries.d.ts +273 -0
- package/dist/schema/tasks.d.ts +225 -0
- package/dist/schema/types.d.ts +68 -0
- package/dist/schema/world.d.ts +114 -0
- package/dist/services/advanced-memory-storage.d.ts +36 -0
- package/dist/types.d.ts +13 -0
- package/dist/utils/string-to-uuid.d.ts +2 -0
- package/dist/utils.d.ts +4 -0
- package/dist/utils.node.d.ts +4 -0
- package/drizzle/index.ts +17 -0
- package/package.json +38 -18
- package/schema/agent.ts +50 -0
- package/schema/approvalRequests.ts +57 -0
- package/schema/authAuditEvent.ts +29 -0
- package/schema/authBootstrapJti.ts +18 -0
- package/schema/authIdentity.ts +35 -0
- package/schema/authOwnerBinding.ts +43 -0
- package/schema/authOwnerLoginToken.ts +50 -0
- package/schema/authSession.ts +44 -0
- package/schema/cache.ts +22 -0
- package/schema/channel.ts +19 -0
- package/schema/channelParticipant.ts +13 -0
- package/schema/component.ts +37 -0
- package/schema/embedding.ts +73 -0
- package/schema/entity.ts +28 -0
- package/schema/entityIdentity.ts +142 -0
- package/schema/index.ts +41 -0
- package/schema/log.ts +38 -0
- package/schema/longTermMemories.ts +27 -0
- package/schema/memory.ts +103 -0
- package/schema/memoryAccessLogs.ts +19 -0
- package/schema/message.ts +24 -0
- package/schema/messageServer.ts +12 -0
- package/schema/messageServerAgent.ts +16 -0
- package/schema/pairingAllowlist.ts +36 -0
- package/schema/pairingRequest.ts +46 -0
- package/schema/participant.ts +43 -0
- package/schema/relationship.ts +50 -0
- package/schema/room.ts +37 -0
- package/schema/server.ts +14 -0
- package/schema/sessionSummaries.ts +27 -0
- package/schema/tasks.ts +24 -0
- package/schema/types.ts +42 -0
- package/schema/world.ts +20 -0
- 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
|
|
45
|
-
import { pgTable as
|
|
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 =
|
|
49
|
-
id:
|
|
50
|
-
createdAt:
|
|
51
|
-
updatedAt:
|
|
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,
|
|
60
|
-
return result.rows[
|
|
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
|
|
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(
|
|
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(
|
|
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(
|
|
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(
|
|
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(
|
|
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(
|
|
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(
|
|
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(
|
|
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(
|
|
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(
|
|
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(
|
|
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(
|
|
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(
|
|
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(
|
|
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(
|
|
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(
|
|
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(
|
|
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(
|
|
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(
|
|
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(
|
|
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(
|
|
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(
|
|
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(
|
|
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(
|
|
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(
|
|
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(
|
|
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(
|
|
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(
|
|
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(
|
|
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(
|
|
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(
|
|
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(
|
|
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(
|
|
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(
|
|
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(
|
|
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(
|
|
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(
|
|
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(
|
|
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(
|
|
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(
|
|
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(
|
|
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
|
|
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(
|
|
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(
|
|
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(
|
|
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(
|
|
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;
|
|
@@ -647,7 +647,7 @@ async function installRLSFunctions(adapter) {
|
|
|
647
647
|
async function applyRLSToNewTables(adapter) {
|
|
648
648
|
const db = getDb(adapter);
|
|
649
649
|
try {
|
|
650
|
-
await db.execute(
|
|
650
|
+
await db.execute(sql26`SELECT apply_rls_to_all_tables()`);
|
|
651
651
|
logger2.info({ src: "plugin:sql" }, "RLS applied to all tables");
|
|
652
652
|
} catch (error) {
|
|
653
653
|
logger2.warn({ src: "plugin:sql", error: String(error) }, "Failed to apply RLS to some tables");
|
|
@@ -656,7 +656,7 @@ async function applyRLSToNewTables(adapter) {
|
|
|
656
656
|
async function installEntityRLS(adapter) {
|
|
657
657
|
const db = getDb(adapter);
|
|
658
658
|
logger2.info("[Entity RLS] Installing entity RLS functions and policies...");
|
|
659
|
-
await db.execute(
|
|
659
|
+
await db.execute(sql26`
|
|
660
660
|
CREATE OR REPLACE FUNCTION current_entity_id()
|
|
661
661
|
RETURNS UUID AS $$
|
|
662
662
|
DECLARE
|
|
@@ -678,7 +678,7 @@ async function installEntityRLS(adapter) {
|
|
|
678
678
|
$$ LANGUAGE plpgsql STABLE;
|
|
679
679
|
`);
|
|
680
680
|
logger2.info("[Entity RLS] Created current_entity_id() function");
|
|
681
|
-
await db.execute(
|
|
681
|
+
await db.execute(sql26`
|
|
682
682
|
CREATE OR REPLACE FUNCTION add_entity_isolation(
|
|
683
683
|
schema_name text,
|
|
684
684
|
table_name text,
|
|
@@ -835,7 +835,7 @@ async function installEntityRLS(adapter) {
|
|
|
835
835
|
$$ LANGUAGE plpgsql;
|
|
836
836
|
`);
|
|
837
837
|
logger2.info("[Entity RLS] Created add_entity_isolation() function");
|
|
838
|
-
await db.execute(
|
|
838
|
+
await db.execute(sql26`
|
|
839
839
|
CREATE OR REPLACE FUNCTION apply_entity_rls_to_all_tables() RETURNS void AS $$
|
|
840
840
|
DECLARE
|
|
841
841
|
tbl record;
|
|
@@ -879,7 +879,7 @@ async function installEntityRLS(adapter) {
|
|
|
879
879
|
async function applyEntityRLSToAllTables(adapter) {
|
|
880
880
|
const db = getDb(adapter);
|
|
881
881
|
try {
|
|
882
|
-
await db.execute(
|
|
882
|
+
await db.execute(sql26`SELECT apply_entity_rls_to_all_tables()`);
|
|
883
883
|
logger2.info("[Entity RLS] Applied entity RLS to all eligible tables");
|
|
884
884
|
} catch (error) {
|
|
885
885
|
logger2.warn("[Entity RLS] Failed to apply entity RLS to some tables:", String(error));
|
|
@@ -913,9 +913,53 @@ function stringToBigInt(str) {
|
|
|
913
913
|
return lockId;
|
|
914
914
|
}
|
|
915
915
|
|
|
916
|
-
// runtime-migrator/
|
|
916
|
+
// runtime-migrator/schema-transformer.ts
|
|
917
917
|
import { logger as logger3 } from "@elizaos/core";
|
|
918
|
-
import {
|
|
918
|
+
import { getTableConfig, pgSchema } from "drizzle-orm/pg-core";
|
|
919
|
+
function deriveSchemaName(pluginName) {
|
|
920
|
+
let schemaName = pluginName.replace(/^@[^/]+\//, "").replace(/^plugin-/, "").toLowerCase();
|
|
921
|
+
schemaName = normalizeSchemaName(schemaName);
|
|
922
|
+
const reserved = ["public", "pg_catalog", "information_schema", "migrations"];
|
|
923
|
+
if (!schemaName || reserved.includes(schemaName)) {
|
|
924
|
+
schemaName = `plugin_${normalizeSchemaName(pluginName.toLowerCase())}`;
|
|
925
|
+
}
|
|
926
|
+
if (!/^[a-z]/.test(schemaName)) {
|
|
927
|
+
schemaName = `p_${schemaName}`;
|
|
928
|
+
}
|
|
929
|
+
if (schemaName.length > 63) {
|
|
930
|
+
schemaName = schemaName.substring(0, 63);
|
|
931
|
+
}
|
|
932
|
+
return schemaName;
|
|
933
|
+
}
|
|
934
|
+
function normalizeSchemaName(input) {
|
|
935
|
+
const chars = [];
|
|
936
|
+
let prevWasUnderscore = false;
|
|
937
|
+
for (let i = 0;i < input.length; i++) {
|
|
938
|
+
const char = input[i];
|
|
939
|
+
if (/[a-z0-9]/.test(char)) {
|
|
940
|
+
chars.push(char);
|
|
941
|
+
prevWasUnderscore = false;
|
|
942
|
+
} else if (!prevWasUnderscore) {
|
|
943
|
+
chars.push("_");
|
|
944
|
+
prevWasUnderscore = true;
|
|
945
|
+
}
|
|
946
|
+
}
|
|
947
|
+
const result = chars.join("");
|
|
948
|
+
let start = 0;
|
|
949
|
+
let end = result.length;
|
|
950
|
+
while (start < end && result[start] === "_") {
|
|
951
|
+
start++;
|
|
952
|
+
}
|
|
953
|
+
while (end > start && result[end - 1] === "_") {
|
|
954
|
+
end--;
|
|
955
|
+
}
|
|
956
|
+
return result.slice(start, end);
|
|
957
|
+
}
|
|
958
|
+
var init_schema_transformer = () => {};
|
|
959
|
+
|
|
960
|
+
// runtime-migrator/drizzle-adapters/database-introspector.ts
|
|
961
|
+
import { logger as logger4 } from "@elizaos/core";
|
|
962
|
+
import { sql as sql27 } from "drizzle-orm";
|
|
919
963
|
function getRows2(result) {
|
|
920
964
|
return result.rows;
|
|
921
965
|
}
|
|
@@ -926,7 +970,7 @@ class DatabaseIntrospector {
|
|
|
926
970
|
this.db = db;
|
|
927
971
|
}
|
|
928
972
|
async introspectSchema(schemaName = "public") {
|
|
929
|
-
|
|
973
|
+
logger4.info({ src: "plugin:sql", schemaName }, "Starting database introspection");
|
|
930
974
|
const tables = {};
|
|
931
975
|
const schemas = {};
|
|
932
976
|
const enums = {};
|
|
@@ -934,7 +978,7 @@ class DatabaseIntrospector {
|
|
|
934
978
|
for (const tableInfo of allTables) {
|
|
935
979
|
const tableName = tableInfo.table_name;
|
|
936
980
|
const tableSchema = tableInfo.table_schema || "public";
|
|
937
|
-
|
|
981
|
+
logger4.debug({ src: "plugin:sql", tableSchema, tableName }, "Introspecting table");
|
|
938
982
|
const columns = await this.getColumns(tableSchema, tableName);
|
|
939
983
|
const columnsObject = {};
|
|
940
984
|
const uniqueConstraintObject = {};
|
|
@@ -1029,7 +1073,7 @@ class DatabaseIntrospector {
|
|
|
1029
1073
|
}
|
|
1030
1074
|
enums[key].values.push(enumInfo.value);
|
|
1031
1075
|
}
|
|
1032
|
-
|
|
1076
|
+
logger4.info({ src: "plugin:sql", tableCount: Object.keys(tables).length }, "Database introspection complete");
|
|
1033
1077
|
return {
|
|
1034
1078
|
version: "7",
|
|
1035
1079
|
dialect: "postgresql",
|
|
@@ -1044,7 +1088,7 @@ class DatabaseIntrospector {
|
|
|
1044
1088
|
};
|
|
1045
1089
|
}
|
|
1046
1090
|
async getTables(schemaName) {
|
|
1047
|
-
const result = await this.db.execute(
|
|
1091
|
+
const result = await this.db.execute(sql27`SELECT
|
|
1048
1092
|
table_schema,
|
|
1049
1093
|
table_name
|
|
1050
1094
|
FROM information_schema.tables
|
|
@@ -1054,7 +1098,7 @@ class DatabaseIntrospector {
|
|
|
1054
1098
|
return getRows2(result);
|
|
1055
1099
|
}
|
|
1056
1100
|
async getColumns(schemaName, tableName) {
|
|
1057
|
-
const result = await this.db.execute(
|
|
1101
|
+
const result = await this.db.execute(sql27`SELECT
|
|
1058
1102
|
a.attname AS column_name,
|
|
1059
1103
|
CASE
|
|
1060
1104
|
WHEN a.attnotnull THEN 'NO'
|
|
@@ -1097,7 +1141,7 @@ class DatabaseIntrospector {
|
|
|
1097
1141
|
return getRows2(result);
|
|
1098
1142
|
}
|
|
1099
1143
|
async getIndexes(schemaName, tableName) {
|
|
1100
|
-
const result = await this.db.execute(
|
|
1144
|
+
const result = await this.db.execute(sql27`SELECT
|
|
1101
1145
|
i.relname AS name,
|
|
1102
1146
|
idx.indisunique AS is_unique,
|
|
1103
1147
|
idx.indisprimary AS is_primary,
|
|
@@ -1121,7 +1165,7 @@ class DatabaseIntrospector {
|
|
|
1121
1165
|
return getRows2(result);
|
|
1122
1166
|
}
|
|
1123
1167
|
async getForeignKeys(schemaName, tableName) {
|
|
1124
|
-
const result = await this.db.execute(
|
|
1168
|
+
const result = await this.db.execute(sql27`SELECT
|
|
1125
1169
|
con.conname AS name,
|
|
1126
1170
|
att.attname AS column_name,
|
|
1127
1171
|
fnsp.nspname AS foreign_table_schema,
|
|
@@ -1156,7 +1200,7 @@ class DatabaseIntrospector {
|
|
|
1156
1200
|
return getRows2(result);
|
|
1157
1201
|
}
|
|
1158
1202
|
async getPrimaryKeys(schemaName, tableName) {
|
|
1159
|
-
const result = await this.db.execute(
|
|
1203
|
+
const result = await this.db.execute(sql27`SELECT
|
|
1160
1204
|
con.conname AS name,
|
|
1161
1205
|
ARRAY(
|
|
1162
1206
|
SELECT a.attname
|
|
@@ -1174,7 +1218,7 @@ class DatabaseIntrospector {
|
|
|
1174
1218
|
return getRows2(result);
|
|
1175
1219
|
}
|
|
1176
1220
|
async getUniqueConstraints(schemaName, tableName) {
|
|
1177
|
-
const result = await this.db.execute(
|
|
1221
|
+
const result = await this.db.execute(sql27`SELECT
|
|
1178
1222
|
con.conname AS name,
|
|
1179
1223
|
ARRAY(
|
|
1180
1224
|
SELECT a.attname
|
|
@@ -1192,7 +1236,7 @@ class DatabaseIntrospector {
|
|
|
1192
1236
|
return getRows2(result);
|
|
1193
1237
|
}
|
|
1194
1238
|
async getCheckConstraints(schemaName, tableName) {
|
|
1195
|
-
const result = await this.db.execute(
|
|
1239
|
+
const result = await this.db.execute(sql27`SELECT
|
|
1196
1240
|
con.conname AS name,
|
|
1197
1241
|
pg_get_constraintdef(con.oid) AS definition
|
|
1198
1242
|
FROM pg_constraint con
|
|
@@ -1204,7 +1248,7 @@ class DatabaseIntrospector {
|
|
|
1204
1248
|
return getRows2(result);
|
|
1205
1249
|
}
|
|
1206
1250
|
async getEnums(schemaName) {
|
|
1207
|
-
const result = await this.db.execute(
|
|
1251
|
+
const result = await this.db.execute(sql27`SELECT
|
|
1208
1252
|
n.nspname AS schema,
|
|
1209
1253
|
t.typname AS name,
|
|
1210
1254
|
e.enumlabel AS value,
|
|
@@ -1235,8 +1279,8 @@ class DatabaseIntrospector {
|
|
|
1235
1279
|
return defaultValue;
|
|
1236
1280
|
}
|
|
1237
1281
|
async hasExistingTables(pluginName) {
|
|
1238
|
-
const schemaName = pluginName === "@elizaos/plugin-sql" ? "public" :
|
|
1239
|
-
const result = await this.db.execute(
|
|
1282
|
+
const schemaName = pluginName === "@elizaos/plugin-sql" ? "public" : deriveSchemaName(pluginName);
|
|
1283
|
+
const result = await this.db.execute(sql27`SELECT COUNT(*) AS count
|
|
1240
1284
|
FROM information_schema.tables
|
|
1241
1285
|
WHERE table_schema = ${schemaName}
|
|
1242
1286
|
AND table_type = 'BASE TABLE'`);
|
|
@@ -1244,11 +1288,10 @@ class DatabaseIntrospector {
|
|
|
1244
1288
|
const count = parseInt(firstRow && firstRow.count || "0", 10);
|
|
1245
1289
|
return count > 0;
|
|
1246
1290
|
}
|
|
1247
|
-
deriveSchemaName(pluginName) {
|
|
1248
|
-
return pluginName.replace("@", "").replace("/", "_").replace(/-/g, "_").toLowerCase();
|
|
1249
|
-
}
|
|
1250
1291
|
}
|
|
1251
|
-
var init_database_introspector = () => {
|
|
1292
|
+
var init_database_introspector = __esm(() => {
|
|
1293
|
+
init_schema_transformer();
|
|
1294
|
+
});
|
|
1252
1295
|
|
|
1253
1296
|
// runtime-migrator/drizzle-adapters/diff-calculator.ts
|
|
1254
1297
|
var exports_diff_calculator = {};
|
|
@@ -1583,7 +1626,7 @@ function hasDiffChanges(diff) {
|
|
|
1583
1626
|
|
|
1584
1627
|
// runtime-migrator/drizzle-adapters/snapshot-generator.ts
|
|
1585
1628
|
import { is, SQL } from "drizzle-orm";
|
|
1586
|
-
import { getTableConfig, PgDialect, PgTable } from "drizzle-orm/pg-core";
|
|
1629
|
+
import { getTableConfig as getTableConfig2, PgDialect, PgTable } from "drizzle-orm/pg-core";
|
|
1587
1630
|
function escapeSingleQuotes(str) {
|
|
1588
1631
|
return str.replace(/'/g, "''");
|
|
1589
1632
|
}
|
|
@@ -1631,7 +1674,7 @@ async function generateSnapshot(schema) {
|
|
|
1631
1674
|
const enums = {};
|
|
1632
1675
|
const pgTables = extractTablesFromSchema(schema);
|
|
1633
1676
|
for (const table of pgTables) {
|
|
1634
|
-
const config =
|
|
1677
|
+
const config = getTableConfig2(table);
|
|
1635
1678
|
const {
|
|
1636
1679
|
name: tableName,
|
|
1637
1680
|
columns,
|
|
@@ -1687,7 +1730,7 @@ async function generateSnapshot(schema) {
|
|
|
1687
1730
|
}
|
|
1688
1731
|
const columnWithConfig = column;
|
|
1689
1732
|
const columnConfig = columnWithConfig.config;
|
|
1690
|
-
if (columnWithConfig.isUnique && columnConfig
|
|
1733
|
+
if (columnWithConfig.isUnique && columnConfig?.uniqueName) {
|
|
1691
1734
|
uniqueConstraintObject[columnConfig.uniqueName] = {
|
|
1692
1735
|
name: columnConfig.uniqueName,
|
|
1693
1736
|
columns: [name],
|
|
@@ -1717,8 +1760,8 @@ async function generateSnapshot(schema) {
|
|
|
1717
1760
|
const reference = fk.reference();
|
|
1718
1761
|
const columnsFrom = reference.columns.map((it) => it.name);
|
|
1719
1762
|
const columnsTo = reference.foreignColumns.map((it) => it.name);
|
|
1720
|
-
const tableTo =
|
|
1721
|
-
const schemaTo =
|
|
1763
|
+
const tableTo = getTableConfig2(reference.foreignTable).name;
|
|
1764
|
+
const schemaTo = getTableConfig2(reference.foreignTable).schema || "public";
|
|
1722
1765
|
const name = fk.getName();
|
|
1723
1766
|
foreignKeysObject[name] = {
|
|
1724
1767
|
name,
|
|
@@ -1809,7 +1852,7 @@ function hasChanges(previousSnapshot, currentSnapshot) {
|
|
|
1809
1852
|
const currHash = hashSnapshot(currentSnapshot);
|
|
1810
1853
|
return prevHash !== currHash;
|
|
1811
1854
|
}
|
|
1812
|
-
var sqlToStr = (
|
|
1855
|
+
var sqlToStr = (sql28, _casing) => {
|
|
1813
1856
|
const config = {
|
|
1814
1857
|
escapeName: () => {
|
|
1815
1858
|
throw new Error("we don't support params for `sql` default values");
|
|
@@ -1822,12 +1865,12 @@ var sqlToStr = (sql22, _casing) => {
|
|
|
1822
1865
|
},
|
|
1823
1866
|
casing: undefined
|
|
1824
1867
|
};
|
|
1825
|
-
return
|
|
1868
|
+
return sql28.toQuery(config).sql;
|
|
1826
1869
|
};
|
|
1827
1870
|
var init_snapshot_generator = () => {};
|
|
1828
1871
|
|
|
1829
1872
|
// runtime-migrator/drizzle-adapters/sql-generator.ts
|
|
1830
|
-
import { logger as
|
|
1873
|
+
import { logger as logger5 } from "@elizaos/core";
|
|
1831
1874
|
function checkForDataLoss(diff) {
|
|
1832
1875
|
const result = {
|
|
1833
1876
|
hasDataLoss: false,
|
|
@@ -1957,7 +2000,7 @@ async function generateMigrationSQL(previousSnapshot, currentSnapshot, diff) {
|
|
|
1957
2000
|
}
|
|
1958
2001
|
const dataLossCheck = checkForDataLoss(diff);
|
|
1959
2002
|
if (dataLossCheck.warnings.length > 0) {
|
|
1960
|
-
|
|
2003
|
+
logger5.warn({ src: "plugin:sql", warnings: dataLossCheck.warnings }, "Schema changes may cause data loss");
|
|
1961
2004
|
}
|
|
1962
2005
|
const schemasToCreate = new Set;
|
|
1963
2006
|
for (const tableName of diff.tables.created) {
|
|
@@ -2012,14 +2055,14 @@ async function generateMigrationSQL(previousSnapshot, currentSnapshot, diff) {
|
|
|
2012
2055
|
const alterStatements = generateAlterColumnSQL(modified.table, modified.column, modified.changes);
|
|
2013
2056
|
statements.push(...alterStatements);
|
|
2014
2057
|
}
|
|
2015
|
-
for (const
|
|
2016
|
-
statements.push(generateDropIndexSQL(
|
|
2058
|
+
for (const index18 of diff.indexes.deleted) {
|
|
2059
|
+
statements.push(generateDropIndexSQL(index18));
|
|
2017
2060
|
}
|
|
2018
2061
|
for (const alteredIndex of diff.indexes.altered) {
|
|
2019
2062
|
statements.push(generateDropIndexSQL(alteredIndex.old));
|
|
2020
2063
|
}
|
|
2021
|
-
for (const
|
|
2022
|
-
statements.push(generateCreateIndexSQL(
|
|
2064
|
+
for (const index18 of diff.indexes.created) {
|
|
2065
|
+
statements.push(generateCreateIndexSQL(index18));
|
|
2023
2066
|
}
|
|
2024
2067
|
for (const alteredIndex of diff.indexes.altered) {
|
|
2025
2068
|
statements.push(generateCreateIndexSQL(alteredIndex.new));
|
|
@@ -2121,18 +2164,18 @@ function generateCreateTableSQL(fullTableName, table) {
|
|
|
2121
2164
|
return { tableSQL, fkSQLs };
|
|
2122
2165
|
}
|
|
2123
2166
|
function generateColumnDefinition(name, def) {
|
|
2124
|
-
let
|
|
2167
|
+
let sql28 = `"${name}" ${def.type}`;
|
|
2125
2168
|
if (def.primaryKey && !def.type.includes("SERIAL")) {
|
|
2126
|
-
|
|
2169
|
+
sql28 += " PRIMARY KEY";
|
|
2127
2170
|
}
|
|
2128
2171
|
if (def.notNull) {
|
|
2129
|
-
|
|
2172
|
+
sql28 += " NOT NULL";
|
|
2130
2173
|
}
|
|
2131
2174
|
if (def.default !== undefined) {
|
|
2132
2175
|
const defaultValue = formatDefaultValue(def.default, def.type);
|
|
2133
|
-
|
|
2176
|
+
sql28 += ` DEFAULT ${defaultValue}`;
|
|
2134
2177
|
}
|
|
2135
|
-
return
|
|
2178
|
+
return sql28;
|
|
2136
2179
|
}
|
|
2137
2180
|
function generateAddColumnSQL(table, column, definition) {
|
|
2138
2181
|
const [schema, tableName] = table.includes(".") ? table.split(".") : ["public", table];
|
|
@@ -2268,28 +2311,28 @@ function formatDefaultValue(value, type) {
|
|
|
2268
2311
|
}
|
|
2269
2312
|
return String(value);
|
|
2270
2313
|
}
|
|
2271
|
-
function generateCreateIndexSQL(
|
|
2272
|
-
const
|
|
2273
|
-
const method =
|
|
2274
|
-
const columns =
|
|
2314
|
+
function generateCreateIndexSQL(index18) {
|
|
2315
|
+
const unique4 = index18.isUnique ? "UNIQUE " : "";
|
|
2316
|
+
const method = index18.method || "btree";
|
|
2317
|
+
const columns = index18.columns.map((c) => {
|
|
2275
2318
|
if (c.isExpression) {
|
|
2276
2319
|
return c.expression;
|
|
2277
2320
|
}
|
|
2278
2321
|
return `"${c.expression}"${c.asc === false ? " DESC" : ""}`;
|
|
2279
2322
|
}).join(", ");
|
|
2280
|
-
const indexName =
|
|
2323
|
+
const indexName = index18.name.includes(".") ? index18.name.split(".")[1] : index18.name;
|
|
2281
2324
|
let tableRef;
|
|
2282
|
-
const indexTable =
|
|
2325
|
+
const indexTable = index18.table;
|
|
2283
2326
|
if (indexTable?.includes(".")) {
|
|
2284
2327
|
const [schema, table] = indexTable.split(".");
|
|
2285
2328
|
tableRef = `"${schema}"."${table}"`;
|
|
2286
2329
|
} else {
|
|
2287
2330
|
tableRef = `"${indexTable || ""}"`;
|
|
2288
2331
|
}
|
|
2289
|
-
return `CREATE ${
|
|
2332
|
+
return `CREATE ${unique4}INDEX IF NOT EXISTS "${indexName}" ON ${tableRef} USING ${method} (${columns});`;
|
|
2290
2333
|
}
|
|
2291
|
-
function generateDropIndexSQL(
|
|
2292
|
-
const indexNameFull = typeof
|
|
2334
|
+
function generateDropIndexSQL(index18) {
|
|
2335
|
+
const indexNameFull = typeof index18 === "string" ? index18 : index18.name;
|
|
2293
2336
|
const indexName = indexNameFull.includes(".") ? indexNameFull.split(".")[1] : indexNameFull;
|
|
2294
2337
|
return `DROP INDEX IF EXISTS "${indexName}";`;
|
|
2295
2338
|
}
|
|
@@ -2305,12 +2348,12 @@ function generateCreateUniqueConstraintSQL(constraint) {
|
|
|
2305
2348
|
const [schema, tableName] = table.includes(".") ? table.split(".") : ["public", table];
|
|
2306
2349
|
const name = constraint.name;
|
|
2307
2350
|
const columns = constraint.columns.map((c) => `"${c}"`).join(", ");
|
|
2308
|
-
let
|
|
2351
|
+
let sql28 = `ALTER TABLE "${schema}"."${tableName}" ADD CONSTRAINT "${name}" UNIQUE`;
|
|
2309
2352
|
if (constraint.nullsNotDistinct) {
|
|
2310
|
-
|
|
2353
|
+
sql28 += ` NULLS NOT DISTINCT`;
|
|
2311
2354
|
}
|
|
2312
|
-
|
|
2313
|
-
return
|
|
2355
|
+
sql28 += ` (${columns});`;
|
|
2356
|
+
return sql28;
|
|
2314
2357
|
}
|
|
2315
2358
|
function generateDropUniqueConstraintSQL(constraint) {
|
|
2316
2359
|
const table = constraint.table || "";
|
|
@@ -2335,14 +2378,14 @@ function buildCreateForeignKeyBodySQL(fk) {
|
|
|
2335
2378
|
const tableFrom = fk.tableFrom;
|
|
2336
2379
|
const columnsFrom = fk.columnsFrom.map((c) => `"${c}"`).join(", ");
|
|
2337
2380
|
const columnsTo = fk.columnsTo.map((c) => `"${c}"`).join(", ");
|
|
2338
|
-
let
|
|
2381
|
+
let sql28 = `ALTER TABLE "${schemaFrom}"."${tableFrom}" ADD CONSTRAINT "${fk.name}" FOREIGN KEY (${columnsFrom}) REFERENCES "${schemaTo}"."${fk.tableTo}" (${columnsTo})`;
|
|
2339
2382
|
if (fk.onDelete) {
|
|
2340
|
-
|
|
2383
|
+
sql28 += ` ON DELETE ${fk.onDelete}`;
|
|
2341
2384
|
}
|
|
2342
2385
|
if (fk.onUpdate) {
|
|
2343
|
-
|
|
2386
|
+
sql28 += ` ON UPDATE ${fk.onUpdate}`;
|
|
2344
2387
|
}
|
|
2345
|
-
return
|
|
2388
|
+
return sql28;
|
|
2346
2389
|
}
|
|
2347
2390
|
function wrapConstraintCreationGuard(constraintName, statement) {
|
|
2348
2391
|
const escapedConstraintName = constraintName.replace(/'/g, "''");
|
|
@@ -2351,8 +2394,8 @@ function wrapConstraintCreationGuard(constraintName, statement) {
|
|
|
2351
2394
|
var init_sql_generator = () => {};
|
|
2352
2395
|
|
|
2353
2396
|
// runtime-migrator/extension-manager.ts
|
|
2354
|
-
import { logger as
|
|
2355
|
-
import { sql as
|
|
2397
|
+
import { logger as logger6 } from "@elizaos/core";
|
|
2398
|
+
import { sql as sql28 } from "drizzle-orm";
|
|
2356
2399
|
|
|
2357
2400
|
class ExtensionManager {
|
|
2358
2401
|
db;
|
|
@@ -2363,66 +2406,22 @@ class ExtensionManager {
|
|
|
2363
2406
|
for (const extension of extensions) {
|
|
2364
2407
|
try {
|
|
2365
2408
|
if (!/^[a-zA-Z0-9_-]+$/.test(extension)) {
|
|
2366
|
-
|
|
2409
|
+
logger6.warn({ src: "plugin:sql", extension }, "Invalid extension name - contains invalid characters");
|
|
2367
2410
|
continue;
|
|
2368
2411
|
}
|
|
2369
|
-
await this.db.execute(
|
|
2370
|
-
|
|
2412
|
+
await this.db.execute(sql28`CREATE EXTENSION IF NOT EXISTS ${sql28.identifier(extension)}`);
|
|
2413
|
+
logger6.debug({ src: "plugin:sql", extension }, "Extension installed");
|
|
2371
2414
|
} catch (error) {
|
|
2372
2415
|
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
2373
|
-
|
|
2416
|
+
logger6.warn({ src: "plugin:sql", extension, error: errorMessage }, "Could not install extension");
|
|
2374
2417
|
}
|
|
2375
2418
|
}
|
|
2376
2419
|
}
|
|
2377
2420
|
}
|
|
2378
2421
|
var init_extension_manager = () => {};
|
|
2379
2422
|
|
|
2380
|
-
// runtime-migrator/schema-transformer.ts
|
|
2381
|
-
import { logger as logger6 } from "@elizaos/core";
|
|
2382
|
-
import { getTableConfig as getTableConfig2, pgSchema } from "drizzle-orm/pg-core";
|
|
2383
|
-
function deriveSchemaName(pluginName) {
|
|
2384
|
-
let schemaName = pluginName.replace(/^@[^/]+\//, "").replace(/^plugin-/, "").toLowerCase();
|
|
2385
|
-
schemaName = normalizeSchemaName(schemaName);
|
|
2386
|
-
const reserved = ["public", "pg_catalog", "information_schema", "migrations"];
|
|
2387
|
-
if (!schemaName || reserved.includes(schemaName)) {
|
|
2388
|
-
schemaName = `plugin_${normalizeSchemaName(pluginName.toLowerCase())}`;
|
|
2389
|
-
}
|
|
2390
|
-
if (!/^[a-z]/.test(schemaName)) {
|
|
2391
|
-
schemaName = `p_${schemaName}`;
|
|
2392
|
-
}
|
|
2393
|
-
if (schemaName.length > 63) {
|
|
2394
|
-
schemaName = schemaName.substring(0, 63);
|
|
2395
|
-
}
|
|
2396
|
-
return schemaName;
|
|
2397
|
-
}
|
|
2398
|
-
function normalizeSchemaName(input) {
|
|
2399
|
-
const chars = [];
|
|
2400
|
-
let prevWasUnderscore = false;
|
|
2401
|
-
for (let i = 0;i < input.length; i++) {
|
|
2402
|
-
const char = input[i];
|
|
2403
|
-
if (/[a-z0-9]/.test(char)) {
|
|
2404
|
-
chars.push(char);
|
|
2405
|
-
prevWasUnderscore = false;
|
|
2406
|
-
} else if (!prevWasUnderscore) {
|
|
2407
|
-
chars.push("_");
|
|
2408
|
-
prevWasUnderscore = true;
|
|
2409
|
-
}
|
|
2410
|
-
}
|
|
2411
|
-
const result = chars.join("");
|
|
2412
|
-
let start = 0;
|
|
2413
|
-
let end = result.length;
|
|
2414
|
-
while (start < end && result[start] === "_") {
|
|
2415
|
-
start++;
|
|
2416
|
-
}
|
|
2417
|
-
while (end > start && result[end - 1] === "_") {
|
|
2418
|
-
end--;
|
|
2419
|
-
}
|
|
2420
|
-
return result.slice(start, end);
|
|
2421
|
-
}
|
|
2422
|
-
var init_schema_transformer = () => {};
|
|
2423
|
-
|
|
2424
2423
|
// runtime-migrator/storage/journal-storage.ts
|
|
2425
|
-
import { sql as
|
|
2424
|
+
import { sql as sql29 } from "drizzle-orm";
|
|
2426
2425
|
|
|
2427
2426
|
class JournalStorage {
|
|
2428
2427
|
db;
|
|
@@ -2430,7 +2429,7 @@ class JournalStorage {
|
|
|
2430
2429
|
this.db = db;
|
|
2431
2430
|
}
|
|
2432
2431
|
async loadJournal(pluginName) {
|
|
2433
|
-
const result = await this.db.execute(
|
|
2432
|
+
const result = await this.db.execute(sql29`SELECT version, dialect, entries
|
|
2434
2433
|
FROM migrations._journal
|
|
2435
2434
|
WHERE plugin_name = ${pluginName}`);
|
|
2436
2435
|
if (result.rows.length === 0) {
|
|
@@ -2447,7 +2446,7 @@ class JournalStorage {
|
|
|
2447
2446
|
};
|
|
2448
2447
|
}
|
|
2449
2448
|
async saveJournal(pluginName, journal) {
|
|
2450
|
-
await this.db.execute(
|
|
2449
|
+
await this.db.execute(sql29`INSERT INTO migrations._journal (plugin_name, version, dialect, entries)
|
|
2451
2450
|
VALUES (${pluginName}, ${journal.version}, ${journal.dialect}, ${JSON.stringify(journal.entries)}::jsonb)
|
|
2452
2451
|
ON CONFLICT (plugin_name)
|
|
2453
2452
|
DO UPDATE SET
|
|
@@ -2489,7 +2488,7 @@ class JournalStorage {
|
|
|
2489
2488
|
var init_journal_storage = () => {};
|
|
2490
2489
|
|
|
2491
2490
|
// runtime-migrator/storage/migration-tracker.ts
|
|
2492
|
-
import { sql as
|
|
2491
|
+
import { sql as sql30 } from "drizzle-orm";
|
|
2493
2492
|
|
|
2494
2493
|
class MigrationTracker {
|
|
2495
2494
|
db;
|
|
@@ -2497,11 +2496,11 @@ class MigrationTracker {
|
|
|
2497
2496
|
this.db = db;
|
|
2498
2497
|
}
|
|
2499
2498
|
async ensureSchema() {
|
|
2500
|
-
await this.db.execute(
|
|
2499
|
+
await this.db.execute(sql30`CREATE SCHEMA IF NOT EXISTS migrations`);
|
|
2501
2500
|
}
|
|
2502
2501
|
async ensureTables() {
|
|
2503
2502
|
await this.ensureSchema();
|
|
2504
|
-
await this.db.execute(
|
|
2503
|
+
await this.db.execute(sql30`
|
|
2505
2504
|
CREATE TABLE IF NOT EXISTS migrations._migrations (
|
|
2506
2505
|
id SERIAL PRIMARY KEY,
|
|
2507
2506
|
plugin_name TEXT NOT NULL,
|
|
@@ -2509,7 +2508,7 @@ class MigrationTracker {
|
|
|
2509
2508
|
created_at BIGINT NOT NULL
|
|
2510
2509
|
)
|
|
2511
2510
|
`);
|
|
2512
|
-
await this.db.execute(
|
|
2511
|
+
await this.db.execute(sql30`
|
|
2513
2512
|
CREATE TABLE IF NOT EXISTS migrations._journal (
|
|
2514
2513
|
plugin_name TEXT PRIMARY KEY,
|
|
2515
2514
|
version TEXT NOT NULL,
|
|
@@ -2517,7 +2516,7 @@ class MigrationTracker {
|
|
|
2517
2516
|
entries JSONB NOT NULL DEFAULT '[]'
|
|
2518
2517
|
)
|
|
2519
2518
|
`);
|
|
2520
|
-
await this.db.execute(
|
|
2519
|
+
await this.db.execute(sql30`
|
|
2521
2520
|
CREATE TABLE IF NOT EXISTS migrations._snapshots (
|
|
2522
2521
|
id SERIAL PRIMARY KEY,
|
|
2523
2522
|
plugin_name TEXT NOT NULL,
|
|
@@ -2529,7 +2528,7 @@ class MigrationTracker {
|
|
|
2529
2528
|
`);
|
|
2530
2529
|
}
|
|
2531
2530
|
async getLastMigration(pluginName) {
|
|
2532
|
-
const result = await this.db.execute(
|
|
2531
|
+
const result = await this.db.execute(sql30`SELECT id, hash, created_at
|
|
2533
2532
|
FROM migrations._migrations
|
|
2534
2533
|
WHERE plugin_name = ${pluginName}
|
|
2535
2534
|
ORDER BY created_at DESC
|
|
@@ -2537,14 +2536,14 @@ class MigrationTracker {
|
|
|
2537
2536
|
return getRow(result) || null;
|
|
2538
2537
|
}
|
|
2539
2538
|
async recordMigration(pluginName, hash, createdAt) {
|
|
2540
|
-
await this.db.execute(
|
|
2539
|
+
await this.db.execute(sql30`INSERT INTO migrations._migrations (plugin_name, hash, created_at)
|
|
2541
2540
|
VALUES (${pluginName}, ${hash}, ${createdAt})`);
|
|
2542
2541
|
}
|
|
2543
2542
|
}
|
|
2544
2543
|
var init_migration_tracker = () => {};
|
|
2545
2544
|
|
|
2546
2545
|
// runtime-migrator/storage/snapshot-storage.ts
|
|
2547
|
-
import { sql as
|
|
2546
|
+
import { sql as sql31 } from "drizzle-orm";
|
|
2548
2547
|
|
|
2549
2548
|
class SnapshotStorage {
|
|
2550
2549
|
db;
|
|
@@ -2552,7 +2551,7 @@ class SnapshotStorage {
|
|
|
2552
2551
|
this.db = db;
|
|
2553
2552
|
}
|
|
2554
2553
|
async saveSnapshot(pluginName, idx, snapshot) {
|
|
2555
|
-
await this.db.execute(
|
|
2554
|
+
await this.db.execute(sql31`INSERT INTO migrations._snapshots (plugin_name, idx, snapshot)
|
|
2556
2555
|
VALUES (${pluginName}, ${idx}, ${JSON.stringify(snapshot)}::jsonb)
|
|
2557
2556
|
ON CONFLICT (plugin_name, idx)
|
|
2558
2557
|
DO UPDATE SET
|
|
@@ -2560,7 +2559,7 @@ class SnapshotStorage {
|
|
|
2560
2559
|
created_at = NOW()`);
|
|
2561
2560
|
}
|
|
2562
2561
|
async loadSnapshot(pluginName, idx) {
|
|
2563
|
-
const result = await this.db.execute(
|
|
2562
|
+
const result = await this.db.execute(sql31`SELECT snapshot
|
|
2564
2563
|
FROM migrations._snapshots
|
|
2565
2564
|
WHERE plugin_name = ${pluginName} AND idx = ${idx}`);
|
|
2566
2565
|
if (result.rows.length === 0) {
|
|
@@ -2569,7 +2568,7 @@ class SnapshotStorage {
|
|
|
2569
2568
|
return result.rows[0].snapshot;
|
|
2570
2569
|
}
|
|
2571
2570
|
async getLatestSnapshot(pluginName) {
|
|
2572
|
-
const result = await this.db.execute(
|
|
2571
|
+
const result = await this.db.execute(sql31`SELECT snapshot
|
|
2573
2572
|
FROM migrations._snapshots
|
|
2574
2573
|
WHERE plugin_name = ${pluginName}
|
|
2575
2574
|
ORDER BY idx DESC
|
|
@@ -2580,7 +2579,7 @@ class SnapshotStorage {
|
|
|
2580
2579
|
return result.rows[0].snapshot;
|
|
2581
2580
|
}
|
|
2582
2581
|
async getAllSnapshots(pluginName) {
|
|
2583
|
-
const result = await this.db.execute(
|
|
2582
|
+
const result = await this.db.execute(sql31`SELECT snapshot
|
|
2584
2583
|
FROM migrations._snapshots
|
|
2585
2584
|
WHERE plugin_name = ${pluginName}
|
|
2586
2585
|
ORDER BY idx ASC`);
|
|
@@ -2591,7 +2590,7 @@ var init_snapshot_storage = () => {};
|
|
|
2591
2590
|
|
|
2592
2591
|
// runtime-migrator/runtime-migrator.ts
|
|
2593
2592
|
import { logger as logger7 } from "@elizaos/core";
|
|
2594
|
-
import { sql as
|
|
2593
|
+
import { sql as sql32 } from "drizzle-orm";
|
|
2595
2594
|
|
|
2596
2595
|
class RuntimeMigrator {
|
|
2597
2596
|
db;
|
|
@@ -2629,7 +2628,7 @@ class RuntimeMigrator {
|
|
|
2629
2628
|
}
|
|
2630
2629
|
for (const schemaName of schemasToCreate) {
|
|
2631
2630
|
logger7.debug({ src: "plugin:sql", schemaName }, "Ensuring schema exists");
|
|
2632
|
-
await this.db.execute(
|
|
2631
|
+
await this.db.execute(sql32.raw(`CREATE SCHEMA IF NOT EXISTS "${schemaName}"`));
|
|
2633
2632
|
}
|
|
2634
2633
|
}
|
|
2635
2634
|
validateSchemaUsage(pluginName, snapshot) {
|
|
@@ -2783,11 +2782,11 @@ class RuntimeMigrator {
|
|
|
2783
2782
|
try {
|
|
2784
2783
|
logger7.debug({ src: "plugin:sql", pluginName }, "Using PostgreSQL advisory locks");
|
|
2785
2784
|
const lockIdStr = lockId.toString();
|
|
2786
|
-
const lockResult = await this.db.execute(
|
|
2785
|
+
const lockResult = await this.db.execute(sql32`SELECT pg_try_advisory_lock(CAST(${lockIdStr} AS bigint)) as acquired`);
|
|
2787
2786
|
lockAcquired = getRow(lockResult)?.acquired === true;
|
|
2788
2787
|
if (!lockAcquired) {
|
|
2789
2788
|
logger7.info({ src: "plugin:sql", pluginName }, "Migration already in progress, waiting for lock");
|
|
2790
|
-
await this.db.execute(
|
|
2789
|
+
await this.db.execute(sql32`SELECT pg_advisory_lock(CAST(${lockIdStr} AS bigint))`);
|
|
2791
2790
|
lockAcquired = true;
|
|
2792
2791
|
logger7.info({ src: "plugin:sql", pluginName }, "Lock acquired");
|
|
2793
2792
|
} else {
|
|
@@ -2918,7 +2917,7 @@ class RuntimeMigrator {
|
|
|
2918
2917
|
if (lockAcquired && isRealPostgres) {
|
|
2919
2918
|
try {
|
|
2920
2919
|
const lockIdStr = lockId.toString();
|
|
2921
|
-
await this.db.execute(
|
|
2920
|
+
await this.db.execute(sql32`SELECT pg_advisory_unlock(CAST(${lockIdStr} AS bigint))`);
|
|
2922
2921
|
logger7.debug({ src: "plugin:sql", pluginName }, "Advisory lock released");
|
|
2923
2922
|
} catch (unlockError) {
|
|
2924
2923
|
logger7.warn({
|
|
@@ -2933,23 +2932,23 @@ class RuntimeMigrator {
|
|
|
2933
2932
|
async executeMigration(pluginName, snapshot, hash, sqlStatements) {
|
|
2934
2933
|
let transactionStarted = false;
|
|
2935
2934
|
try {
|
|
2936
|
-
await this.db.execute(
|
|
2935
|
+
await this.db.execute(sql32`BEGIN`);
|
|
2937
2936
|
transactionStarted = true;
|
|
2938
2937
|
for (const stmt of sqlStatements) {
|
|
2939
2938
|
logger7.debug({ src: "plugin:sql", statement: stmt }, "Executing SQL statement");
|
|
2940
|
-
await this.db.execute(
|
|
2939
|
+
await this.db.execute(sql32.raw(stmt));
|
|
2941
2940
|
}
|
|
2942
2941
|
const idx = await this.journalStorage.getNextIdx(pluginName);
|
|
2943
2942
|
await this.migrationTracker.recordMigration(pluginName, hash, Date.now());
|
|
2944
2943
|
const tag = this.generateMigrationTag(idx, pluginName);
|
|
2945
2944
|
await this.journalStorage.updateJournal(pluginName, idx, tag, true);
|
|
2946
2945
|
await this.snapshotStorage.saveSnapshot(pluginName, idx, snapshot);
|
|
2947
|
-
await this.db.execute(
|
|
2946
|
+
await this.db.execute(sql32`COMMIT`);
|
|
2948
2947
|
logger7.info({ src: "plugin:sql", pluginName, tag }, "Recorded migration");
|
|
2949
2948
|
} catch (error) {
|
|
2950
2949
|
if (transactionStarted) {
|
|
2951
2950
|
try {
|
|
2952
|
-
await this.db.execute(
|
|
2951
|
+
await this.db.execute(sql32`ROLLBACK`);
|
|
2953
2952
|
logger7.error({
|
|
2954
2953
|
src: "plugin:sql",
|
|
2955
2954
|
error: error instanceof Error ? error.message : String(error)
|
|
@@ -2966,8 +2965,8 @@ class RuntimeMigrator {
|
|
|
2966
2965
|
}
|
|
2967
2966
|
generateMigrationTag(idx, pluginName) {
|
|
2968
2967
|
const prefix = idx.toString().padStart(4, "0");
|
|
2969
|
-
const
|
|
2970
|
-
return `${prefix}_${pluginName}_${
|
|
2968
|
+
const timestamp24 = Date.now().toString(36);
|
|
2969
|
+
return `${prefix}_${pluginName}_${timestamp24}`;
|
|
2971
2970
|
}
|
|
2972
2971
|
async getStatus(pluginName) {
|
|
2973
2972
|
const lastMigration = await this.migrationTracker.getLastMigration(pluginName);
|
|
@@ -2982,9 +2981,9 @@ class RuntimeMigrator {
|
|
|
2982
2981
|
}
|
|
2983
2982
|
async reset(pluginName) {
|
|
2984
2983
|
logger7.warn({ src: "plugin:sql", pluginName }, "Resetting migrations");
|
|
2985
|
-
await this.db.execute(
|
|
2986
|
-
await this.db.execute(
|
|
2987
|
-
await this.db.execute(
|
|
2984
|
+
await this.db.execute(sql32`DELETE FROM migrations._migrations WHERE plugin_name = ${pluginName}`);
|
|
2985
|
+
await this.db.execute(sql32`DELETE FROM migrations._journal WHERE plugin_name = ${pluginName}`);
|
|
2986
|
+
await this.db.execute(sql32`DELETE FROM migrations._snapshots WHERE plugin_name = ${pluginName}`);
|
|
2988
2987
|
logger7.warn({ src: "plugin:sql", pluginName }, "Reset complete");
|
|
2989
2988
|
}
|
|
2990
2989
|
async checkMigration(pluginName, schema) {
|
|
@@ -3165,64 +3164,10 @@ import {
|
|
|
3165
3164
|
lt,
|
|
3166
3165
|
lte,
|
|
3167
3166
|
or,
|
|
3168
|
-
sql as
|
|
3167
|
+
sql as sql33
|
|
3169
3168
|
} from "drizzle-orm";
|
|
3170
|
-
// ../../../node_modules/.bun/uuid@13.0.0/node_modules/uuid/dist/native.js
|
|
3171
|
-
var randomUUID = typeof crypto !== "undefined" && crypto.randomUUID && crypto.randomUUID.bind(crypto);
|
|
3172
|
-
var native_default = { randomUUID };
|
|
3173
|
-
|
|
3174
|
-
// ../../../node_modules/.bun/uuid@13.0.0/node_modules/uuid/dist/rng.js
|
|
3175
|
-
var getRandomValues;
|
|
3176
|
-
var rnds8 = new Uint8Array(16);
|
|
3177
|
-
function rng() {
|
|
3178
|
-
if (!getRandomValues) {
|
|
3179
|
-
if (typeof crypto === "undefined" || !crypto.getRandomValues) {
|
|
3180
|
-
throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");
|
|
3181
|
-
}
|
|
3182
|
-
getRandomValues = crypto.getRandomValues.bind(crypto);
|
|
3183
|
-
}
|
|
3184
|
-
return getRandomValues(rnds8);
|
|
3185
|
-
}
|
|
3186
3169
|
|
|
3187
|
-
// ../../../node_modules/.bun/uuid@13.0.0/node_modules/uuid/dist/stringify.js
|
|
3188
|
-
var byteToHex = [];
|
|
3189
|
-
for (let i = 0;i < 256; ++i) {
|
|
3190
|
-
byteToHex.push((i + 256).toString(16).slice(1));
|
|
3191
|
-
}
|
|
3192
|
-
function unsafeStringify(arr, offset = 0) {
|
|
3193
|
-
return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + "-" + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + "-" + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + "-" + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + "-" + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase();
|
|
3194
|
-
}
|
|
3195
|
-
|
|
3196
|
-
// ../../../node_modules/.bun/uuid@13.0.0/node_modules/uuid/dist/v4.js
|
|
3197
|
-
function _v4(options, buf, offset) {
|
|
3198
|
-
options = options || {};
|
|
3199
|
-
const rnds = options.random ?? options.rng?.() ?? rng();
|
|
3200
|
-
if (rnds.length < 16) {
|
|
3201
|
-
throw new Error("Random bytes length must be >= 16");
|
|
3202
|
-
}
|
|
3203
|
-
rnds[6] = rnds[6] & 15 | 64;
|
|
3204
|
-
rnds[8] = rnds[8] & 63 | 128;
|
|
3205
|
-
if (buf) {
|
|
3206
|
-
offset = offset || 0;
|
|
3207
|
-
if (offset < 0 || offset + 16 > buf.length) {
|
|
3208
|
-
throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`);
|
|
3209
|
-
}
|
|
3210
|
-
for (let i = 0;i < 16; ++i) {
|
|
3211
|
-
buf[offset + i] = rnds[i];
|
|
3212
|
-
}
|
|
3213
|
-
return buf;
|
|
3214
|
-
}
|
|
3215
|
-
return unsafeStringify(rnds);
|
|
3216
|
-
}
|
|
3217
|
-
function v4(options, buf, offset) {
|
|
3218
|
-
if (native_default.randomUUID && !buf && !options) {
|
|
3219
|
-
return native_default.randomUUID();
|
|
3220
|
-
}
|
|
3221
|
-
return _v4(options, buf, offset);
|
|
3222
|
-
}
|
|
3223
|
-
var v4_default = v4;
|
|
3224
3170
|
// schema/embedding.ts
|
|
3225
|
-
import { VECTOR_DIMS } from "@elizaos/core";
|
|
3226
3171
|
import { relations, sql as sql5 } from "drizzle-orm";
|
|
3227
3172
|
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";
|
|
3228
3173
|
|
|
@@ -3335,6 +3280,14 @@ var memoryTable = pgTable4("memories", {
|
|
|
3335
3280
|
]);
|
|
3336
3281
|
|
|
3337
3282
|
// schema/embedding.ts
|
|
3283
|
+
var VECTOR_DIMS = {
|
|
3284
|
+
SMALL: 384,
|
|
3285
|
+
MEDIUM: 512,
|
|
3286
|
+
LARGE: 768,
|
|
3287
|
+
XL: 1024,
|
|
3288
|
+
XXL: 1536,
|
|
3289
|
+
XXXL: 3072
|
|
3290
|
+
};
|
|
3338
3291
|
var DIMENSION_MAP = {
|
|
3339
3292
|
[VECTOR_DIMS.SMALL]: "dim384",
|
|
3340
3293
|
[VECTOR_DIMS.MEDIUM]: "dim512",
|
|
@@ -3374,6 +3327,7 @@ var exports_schema = {};
|
|
|
3374
3327
|
__export(exports_schema, {
|
|
3375
3328
|
worldTable: () => worldTable,
|
|
3376
3329
|
taskTable: () => taskTable,
|
|
3330
|
+
sessionSummaries: () => sessionSummaries,
|
|
3377
3331
|
serverTable: () => serverTable,
|
|
3378
3332
|
roomTable: () => roomTable,
|
|
3379
3333
|
relationshipTable: () => relationshipTable,
|
|
@@ -3384,203 +3338,484 @@ __export(exports_schema, {
|
|
|
3384
3338
|
messageServerTable: () => messageServerTable,
|
|
3385
3339
|
messageServerAgentsTable: () => messageServerAgentsTable,
|
|
3386
3340
|
memoryTable: () => memoryTable,
|
|
3341
|
+
memoryAccessLogs: () => memoryAccessLogs,
|
|
3342
|
+
longTermMemories: () => longTermMemories,
|
|
3387
3343
|
logTable: () => logTable,
|
|
3344
|
+
factCandidateTable: () => factCandidateTable,
|
|
3388
3345
|
entityTable: () => entityTable,
|
|
3346
|
+
entityMergeCandidateTable: () => entityMergeCandidateTable,
|
|
3347
|
+
entityIdentityTable: () => entityIdentityTable,
|
|
3389
3348
|
embeddingTable: () => embeddingTable,
|
|
3390
3349
|
componentTable: () => componentTable,
|
|
3391
3350
|
channelTable: () => channelTable,
|
|
3392
3351
|
channelParticipantsTable: () => channelParticipantsTable,
|
|
3393
3352
|
cacheTable: () => cacheTable,
|
|
3353
|
+
authSessionTable: () => authSessionTable,
|
|
3354
|
+
authOwnerLoginTokenTable: () => authOwnerLoginTokenTable,
|
|
3355
|
+
authOwnerBindingTable: () => authOwnerBindingTable,
|
|
3356
|
+
authIdentityTable: () => authIdentityTable,
|
|
3357
|
+
authIdentityCreatedAtDefault: () => authIdentityCreatedAtDefault,
|
|
3358
|
+
authBootstrapJtiSeenTable: () => authBootstrapJtiSeenTable,
|
|
3359
|
+
authAuditEventTable: () => authAuditEventTable,
|
|
3360
|
+
approvalRequestTable: () => approvalRequestTable,
|
|
3394
3361
|
agentTable: () => agentTable
|
|
3395
3362
|
});
|
|
3396
3363
|
|
|
3397
|
-
// schema/
|
|
3364
|
+
// schema/approvalRequests.ts
|
|
3398
3365
|
init_agent();
|
|
3399
3366
|
import { sql as sql6 } from "drizzle-orm";
|
|
3400
|
-
import { jsonb as jsonb5, pgTable as pgTable6,
|
|
3401
|
-
var
|
|
3402
|
-
|
|
3367
|
+
import { index as index3, jsonb as jsonb5, pgTable as pgTable6, text as text5, timestamp as timestamp6, uuid as uuid6 } from "drizzle-orm/pg-core";
|
|
3368
|
+
var approvalRequestTable = pgTable6("approval_requests", {
|
|
3369
|
+
id: uuid6("id").primaryKey().defaultRandom(),
|
|
3370
|
+
state: text5("state").notNull(),
|
|
3371
|
+
requestedBy: text5("requested_by").notNull(),
|
|
3372
|
+
subjectUserId: text5("subject_user_id").notNull(),
|
|
3373
|
+
action: text5("action").notNull(),
|
|
3374
|
+
payload: jsonb5("payload").notNull(),
|
|
3375
|
+
channel: text5("channel").notNull(),
|
|
3376
|
+
reason: text5("reason").notNull(),
|
|
3377
|
+
expiresAt: timestamp6("expires_at", { withTimezone: true }).notNull(),
|
|
3378
|
+
resolvedAt: timestamp6("resolved_at", { withTimezone: true }),
|
|
3379
|
+
resolvedBy: text5("resolved_by"),
|
|
3380
|
+
resolutionReason: text5("resolution_reason"),
|
|
3403
3381
|
agentId: uuid6("agent_id").notNull().references(() => agentTable.id, { onDelete: "cascade" }),
|
|
3404
|
-
value: jsonb5("value").notNull(),
|
|
3405
3382
|
createdAt: timestamp6("created_at", { withTimezone: true }).default(sql6`now()`).notNull(),
|
|
3406
|
-
|
|
3383
|
+
updatedAt: timestamp6("updated_at", { withTimezone: true }).default(sql6`now()`).notNull()
|
|
3384
|
+
}, (table) => [
|
|
3385
|
+
index3("approval_requests_subject_state_idx").on(table.subjectUserId, table.state),
|
|
3386
|
+
index3("approval_requests_agent_state_idx").on(table.agentId, table.state),
|
|
3387
|
+
index3("approval_requests_state_expires_idx").on(table.state, table.expiresAt)
|
|
3388
|
+
]);
|
|
3389
|
+
// schema/authAuditEvent.ts
|
|
3390
|
+
import { bigint, index as index4, jsonb as jsonb6, pgTable as pgTable7, text as text6 } from "drizzle-orm/pg-core";
|
|
3391
|
+
var authAuditEventTable = pgTable7("auth_audit_events", {
|
|
3392
|
+
id: text6("id").primaryKey(),
|
|
3393
|
+
ts: bigint("ts", { mode: "number" }).notNull(),
|
|
3394
|
+
actorIdentityId: text6("actor_identity_id"),
|
|
3395
|
+
ip: text6("ip"),
|
|
3396
|
+
userAgent: text6("user_agent"),
|
|
3397
|
+
action: text6("action").notNull(),
|
|
3398
|
+
outcome: text6("outcome").notNull(),
|
|
3399
|
+
metadata: jsonb6("metadata").$type().notNull()
|
|
3400
|
+
}, (table) => [
|
|
3401
|
+
index4("auth_audit_events_action_idx").on(table.action),
|
|
3402
|
+
index4("auth_audit_events_ts_idx").on(table.ts),
|
|
3403
|
+
index4("auth_audit_events_actor_idx").on(table.actorIdentityId)
|
|
3404
|
+
]);
|
|
3405
|
+
// schema/authBootstrapJti.ts
|
|
3406
|
+
import { bigint as bigint2, index as index5, pgTable as pgTable8, text as text7 } from "drizzle-orm/pg-core";
|
|
3407
|
+
var authBootstrapJtiSeenTable = pgTable8("auth_bootstrap_jti_seen", {
|
|
3408
|
+
jti: text7("jti").primaryKey(),
|
|
3409
|
+
seenAt: bigint2("seen_at", { mode: "number" }).notNull()
|
|
3410
|
+
}, (table) => [index5("auth_bootstrap_jti_seen_at_idx").on(table.seenAt)]);
|
|
3411
|
+
// schema/authIdentity.ts
|
|
3412
|
+
import { sql as sql7 } from "drizzle-orm";
|
|
3413
|
+
import { bigint as bigint3, index as index6, pgTable as pgTable9, text as text8 } from "drizzle-orm/pg-core";
|
|
3414
|
+
var authIdentityTable = pgTable9("auth_identities", {
|
|
3415
|
+
id: text8("id").primaryKey(),
|
|
3416
|
+
kind: text8("kind").notNull(),
|
|
3417
|
+
displayName: text8("display_name").notNull(),
|
|
3418
|
+
createdAt: bigint3("created_at", { mode: "number" }).notNull(),
|
|
3419
|
+
passwordHash: text8("password_hash"),
|
|
3420
|
+
cloudUserId: text8("cloud_user_id")
|
|
3421
|
+
}, (table) => [
|
|
3422
|
+
index6("auth_identities_kind_idx").on(table.kind),
|
|
3423
|
+
index6("auth_identities_cloud_user_idx").on(table.cloudUserId)
|
|
3424
|
+
]);
|
|
3425
|
+
var authIdentityCreatedAtDefault = sql7`(extract(epoch from now()) * 1000)::bigint`;
|
|
3426
|
+
// schema/authOwnerBinding.ts
|
|
3427
|
+
import { bigint as bigint4, foreignKey as foreignKey3, index as index7, pgTable as pgTable10, text as text9, uniqueIndex } from "drizzle-orm/pg-core";
|
|
3428
|
+
var authOwnerBindingTable = pgTable10("auth_owner_bindings", {
|
|
3429
|
+
id: text9("id").primaryKey(),
|
|
3430
|
+
identityId: text9("identity_id").notNull().references(() => authIdentityTable.id, { onDelete: "cascade" }),
|
|
3431
|
+
connector: text9("connector").notNull(),
|
|
3432
|
+
externalId: text9("external_id").notNull(),
|
|
3433
|
+
displayHandle: text9("display_handle").notNull(),
|
|
3434
|
+
instanceId: text9("instance_id").notNull(),
|
|
3435
|
+
verifiedAt: bigint4("verified_at", { mode: "number" }).notNull(),
|
|
3436
|
+
pendingCodeHash: text9("pending_code_hash"),
|
|
3437
|
+
pendingExpiresAt: bigint4("pending_expires_at", { mode: "number" })
|
|
3438
|
+
}, (table) => [
|
|
3439
|
+
index7("auth_owner_bindings_identity_idx").on(table.identityId),
|
|
3440
|
+
index7("auth_owner_bindings_connector_idx").on(table.connector),
|
|
3441
|
+
uniqueIndex("auth_owner_bindings_connector_external_instance_uniq").on(table.connector, table.externalId, table.instanceId),
|
|
3442
|
+
foreignKey3({
|
|
3443
|
+
name: "fk_auth_owner_bindings_identity",
|
|
3444
|
+
columns: [table.identityId],
|
|
3445
|
+
foreignColumns: [authIdentityTable.id]
|
|
3446
|
+
}).onDelete("cascade")
|
|
3447
|
+
]);
|
|
3448
|
+
// schema/authOwnerLoginToken.ts
|
|
3449
|
+
import { bigint as bigint5, foreignKey as foreignKey4, index as index8, pgTable as pgTable11, text as text10 } from "drizzle-orm/pg-core";
|
|
3450
|
+
var authOwnerLoginTokenTable = pgTable11("auth_owner_login_tokens", {
|
|
3451
|
+
tokenHash: text10("token_hash").primaryKey(),
|
|
3452
|
+
identityId: text10("identity_id").notNull().references(() => authIdentityTable.id, { onDelete: "cascade" }),
|
|
3453
|
+
bindingId: text10("binding_id").notNull().references(() => authOwnerBindingTable.id, { onDelete: "cascade" }),
|
|
3454
|
+
issuedAt: bigint5("issued_at", { mode: "number" }).notNull(),
|
|
3455
|
+
expiresAt: bigint5("expires_at", { mode: "number" }).notNull(),
|
|
3456
|
+
consumedAt: bigint5("consumed_at", { mode: "number" })
|
|
3457
|
+
}, (table) => [
|
|
3458
|
+
index8("auth_owner_login_tokens_identity_idx").on(table.identityId),
|
|
3459
|
+
index8("auth_owner_login_tokens_binding_idx").on(table.bindingId),
|
|
3460
|
+
index8("auth_owner_login_tokens_expires_idx").on(table.expiresAt),
|
|
3461
|
+
foreignKey4({
|
|
3462
|
+
name: "fk_auth_owner_login_tokens_identity",
|
|
3463
|
+
columns: [table.identityId],
|
|
3464
|
+
foreignColumns: [authIdentityTable.id]
|
|
3465
|
+
}).onDelete("cascade"),
|
|
3466
|
+
foreignKey4({
|
|
3467
|
+
name: "fk_auth_owner_login_tokens_binding",
|
|
3468
|
+
columns: [table.bindingId],
|
|
3469
|
+
foreignColumns: [authOwnerBindingTable.id]
|
|
3470
|
+
}).onDelete("cascade")
|
|
3471
|
+
]);
|
|
3472
|
+
// schema/authSession.ts
|
|
3473
|
+
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";
|
|
3474
|
+
var authSessionTable = pgTable12("auth_sessions", {
|
|
3475
|
+
id: text11("id").primaryKey(),
|
|
3476
|
+
identityId: text11("identity_id").notNull().references(() => authIdentityTable.id, { onDelete: "cascade" }),
|
|
3477
|
+
kind: text11("kind").notNull(),
|
|
3478
|
+
createdAt: bigint6("created_at", { mode: "number" }).notNull(),
|
|
3479
|
+
lastSeenAt: bigint6("last_seen_at", { mode: "number" }).notNull(),
|
|
3480
|
+
expiresAt: bigint6("expires_at", { mode: "number" }).notNull(),
|
|
3481
|
+
rememberDevice: boolean3("remember_device").notNull().default(false),
|
|
3482
|
+
csrfSecret: text11("csrf_secret").notNull(),
|
|
3483
|
+
ip: text11("ip"),
|
|
3484
|
+
userAgent: text11("user_agent"),
|
|
3485
|
+
scopes: jsonb7("scopes").$type().notNull(),
|
|
3486
|
+
revokedAt: bigint6("revoked_at", { mode: "number" })
|
|
3487
|
+
}, (table) => [
|
|
3488
|
+
index9("auth_sessions_identity_idx").on(table.identityId),
|
|
3489
|
+
index9("auth_sessions_expires_idx").on(table.expiresAt),
|
|
3490
|
+
foreignKey5({
|
|
3491
|
+
name: "fk_auth_sessions_identity",
|
|
3492
|
+
columns: [table.identityId],
|
|
3493
|
+
foreignColumns: [authIdentityTable.id]
|
|
3494
|
+
}).onDelete("cascade")
|
|
3495
|
+
]);
|
|
3496
|
+
// schema/cache.ts
|
|
3497
|
+
init_agent();
|
|
3498
|
+
import { sql as sql8 } from "drizzle-orm";
|
|
3499
|
+
import { jsonb as jsonb8, pgTable as pgTable13, primaryKey, text as text12, timestamp as timestamp7, uuid as uuid7 } from "drizzle-orm/pg-core";
|
|
3500
|
+
var cacheTable = pgTable13("cache", {
|
|
3501
|
+
key: text12("key").notNull(),
|
|
3502
|
+
agentId: uuid7("agent_id").notNull().references(() => agentTable.id, { onDelete: "cascade" }),
|
|
3503
|
+
value: jsonb8("value").notNull(),
|
|
3504
|
+
createdAt: timestamp7("created_at", { withTimezone: true }).default(sql8`now()`).notNull(),
|
|
3505
|
+
expiresAt: timestamp7("expires_at", { withTimezone: true })
|
|
3407
3506
|
}, (table) => [primaryKey({ columns: [table.key, table.agentId] })]);
|
|
3408
3507
|
// schema/channel.ts
|
|
3409
|
-
import { sql as
|
|
3410
|
-
import { jsonb as
|
|
3508
|
+
import { sql as sql10 } from "drizzle-orm";
|
|
3509
|
+
import { jsonb as jsonb10, pgTable as pgTable15, text as text14, timestamp as timestamp9, uuid as uuid9 } from "drizzle-orm/pg-core";
|
|
3411
3510
|
|
|
3412
3511
|
// schema/messageServer.ts
|
|
3413
|
-
import { sql as
|
|
3414
|
-
import { jsonb as
|
|
3415
|
-
var messageServerTable =
|
|
3416
|
-
id:
|
|
3417
|
-
name:
|
|
3418
|
-
sourceType:
|
|
3419
|
-
sourceId:
|
|
3420
|
-
metadata:
|
|
3421
|
-
createdAt:
|
|
3422
|
-
updatedAt:
|
|
3512
|
+
import { sql as sql9 } from "drizzle-orm";
|
|
3513
|
+
import { jsonb as jsonb9, pgTable as pgTable14, text as text13, timestamp as timestamp8, uuid as uuid8 } from "drizzle-orm/pg-core";
|
|
3514
|
+
var messageServerTable = pgTable14("message_servers", {
|
|
3515
|
+
id: uuid8("id").primaryKey(),
|
|
3516
|
+
name: text13("name").notNull(),
|
|
3517
|
+
sourceType: text13("source_type").notNull(),
|
|
3518
|
+
sourceId: text13("source_id"),
|
|
3519
|
+
metadata: jsonb9("metadata"),
|
|
3520
|
+
createdAt: timestamp8("created_at", { mode: "date" }).default(sql9`CURRENT_TIMESTAMP`).notNull(),
|
|
3521
|
+
updatedAt: timestamp8("updated_at", { mode: "date" }).default(sql9`CURRENT_TIMESTAMP`).notNull()
|
|
3423
3522
|
});
|
|
3424
3523
|
|
|
3425
3524
|
// schema/channel.ts
|
|
3426
|
-
var channelTable =
|
|
3427
|
-
id:
|
|
3428
|
-
messageServerId:
|
|
3429
|
-
name:
|
|
3430
|
-
type:
|
|
3431
|
-
sourceType:
|
|
3432
|
-
sourceId:
|
|
3433
|
-
topic:
|
|
3434
|
-
metadata:
|
|
3435
|
-
createdAt:
|
|
3436
|
-
updatedAt:
|
|
3525
|
+
var channelTable = pgTable15("channels", {
|
|
3526
|
+
id: text14("id").primaryKey(),
|
|
3527
|
+
messageServerId: uuid9("message_server_id").notNull().references(() => messageServerTable.id, { onDelete: "cascade" }),
|
|
3528
|
+
name: text14("name").notNull(),
|
|
3529
|
+
type: text14("type").notNull(),
|
|
3530
|
+
sourceType: text14("source_type"),
|
|
3531
|
+
sourceId: text14("source_id"),
|
|
3532
|
+
topic: text14("topic"),
|
|
3533
|
+
metadata: jsonb10("metadata"),
|
|
3534
|
+
createdAt: timestamp9("created_at", { mode: "date" }).default(sql10`CURRENT_TIMESTAMP`).notNull(),
|
|
3535
|
+
updatedAt: timestamp9("updated_at", { mode: "date" }).default(sql10`CURRENT_TIMESTAMP`).notNull()
|
|
3437
3536
|
});
|
|
3438
3537
|
// schema/channelParticipant.ts
|
|
3439
|
-
import { pgTable as
|
|
3440
|
-
var channelParticipantsTable =
|
|
3441
|
-
channelId:
|
|
3442
|
-
entityId:
|
|
3538
|
+
import { pgTable as pgTable16, primaryKey as primaryKey2, text as text15 } from "drizzle-orm/pg-core";
|
|
3539
|
+
var channelParticipantsTable = pgTable16("channel_participants", {
|
|
3540
|
+
channelId: text15("channel_id").notNull().references(() => channelTable.id, { onDelete: "cascade" }),
|
|
3541
|
+
entityId: text15("entity_id").notNull()
|
|
3443
3542
|
}, (table) => [primaryKey2({ columns: [table.channelId, table.entityId] })]);
|
|
3444
3543
|
// schema/component.ts
|
|
3445
3544
|
init_agent();
|
|
3446
|
-
import { sql as
|
|
3447
|
-
import { jsonb as
|
|
3545
|
+
import { sql as sql12 } from "drizzle-orm";
|
|
3546
|
+
import { jsonb as jsonb12, pgTable as pgTable18, text as text17, timestamp as timestamp11, uuid as uuid11 } from "drizzle-orm/pg-core";
|
|
3448
3547
|
|
|
3449
3548
|
// schema/world.ts
|
|
3450
3549
|
init_agent();
|
|
3451
|
-
import { sql as
|
|
3452
|
-
import { jsonb as
|
|
3453
|
-
var worldTable =
|
|
3454
|
-
id:
|
|
3455
|
-
agentId:
|
|
3456
|
-
name:
|
|
3457
|
-
metadata:
|
|
3458
|
-
messageServerId:
|
|
3459
|
-
createdAt:
|
|
3550
|
+
import { sql as sql11 } from "drizzle-orm";
|
|
3551
|
+
import { jsonb as jsonb11, pgTable as pgTable17, text as text16, timestamp as timestamp10, uuid as uuid10 } from "drizzle-orm/pg-core";
|
|
3552
|
+
var worldTable = pgTable17("worlds", {
|
|
3553
|
+
id: uuid10("id").notNull().primaryKey().default(sql11`gen_random_uuid()`),
|
|
3554
|
+
agentId: uuid10("agent_id").notNull().references(() => agentTable.id, { onDelete: "cascade" }),
|
|
3555
|
+
name: text16("name").notNull(),
|
|
3556
|
+
metadata: jsonb11("metadata"),
|
|
3557
|
+
messageServerId: uuid10("message_server_id"),
|
|
3558
|
+
createdAt: timestamp10("created_at").default(sql11`now()`).notNull()
|
|
3460
3559
|
});
|
|
3461
3560
|
|
|
3462
3561
|
// schema/component.ts
|
|
3463
|
-
var componentTable =
|
|
3464
|
-
id:
|
|
3465
|
-
entityId:
|
|
3466
|
-
agentId:
|
|
3467
|
-
roomId:
|
|
3468
|
-
worldId:
|
|
3562
|
+
var componentTable = pgTable18("components", {
|
|
3563
|
+
id: uuid11("id").primaryKey().default(sql12`gen_random_uuid()`).notNull(),
|
|
3564
|
+
entityId: uuid11("entity_id").references(() => entityTable.id, { onDelete: "cascade" }).notNull(),
|
|
3565
|
+
agentId: uuid11("agent_id").references(() => agentTable.id, { onDelete: "cascade" }).notNull(),
|
|
3566
|
+
roomId: uuid11("room_id").references(() => roomTable.id, { onDelete: "cascade" }).notNull(),
|
|
3567
|
+
worldId: uuid11("world_id").references(() => worldTable.id, {
|
|
3469
3568
|
onDelete: "cascade"
|
|
3470
3569
|
}),
|
|
3471
|
-
sourceEntityId:
|
|
3570
|
+
sourceEntityId: uuid11("source_entity_id").references(() => entityTable.id, {
|
|
3472
3571
|
onDelete: "cascade"
|
|
3473
3572
|
}),
|
|
3474
|
-
type:
|
|
3475
|
-
data:
|
|
3476
|
-
createdAt:
|
|
3573
|
+
type: text17("type").notNull(),
|
|
3574
|
+
data: jsonb12("data").default(sql12`'{}'::jsonb`),
|
|
3575
|
+
createdAt: timestamp11("created_at").default(sql12`now()`).notNull()
|
|
3477
3576
|
});
|
|
3577
|
+
// schema/entityIdentity.ts
|
|
3578
|
+
init_agent();
|
|
3579
|
+
import { sql as sql13 } from "drizzle-orm";
|
|
3580
|
+
import {
|
|
3581
|
+
boolean as boolean4,
|
|
3582
|
+
foreignKey as foreignKey6,
|
|
3583
|
+
index as index10,
|
|
3584
|
+
jsonb as jsonb13,
|
|
3585
|
+
pgTable as pgTable19,
|
|
3586
|
+
real,
|
|
3587
|
+
text as text18,
|
|
3588
|
+
timestamp as timestamp12,
|
|
3589
|
+
unique as unique2,
|
|
3590
|
+
uuid as uuid12
|
|
3591
|
+
} from "drizzle-orm/pg-core";
|
|
3592
|
+
var entityIdentityTable = pgTable19("entity_identities", {
|
|
3593
|
+
id: uuid12("id").notNull().primaryKey().default(sql13`gen_random_uuid()`),
|
|
3594
|
+
entityId: uuid12("entity_id").notNull().references(() => entityTable.id, { onDelete: "cascade" }),
|
|
3595
|
+
agentId: uuid12("agent_id").notNull().references(() => agentTable.id, { onDelete: "cascade" }),
|
|
3596
|
+
platform: text18("platform").notNull(),
|
|
3597
|
+
handle: text18("handle").notNull(),
|
|
3598
|
+
verified: boolean4("verified").notNull().default(false),
|
|
3599
|
+
confidence: real("confidence").notNull().default(0),
|
|
3600
|
+
source: text18("source"),
|
|
3601
|
+
firstSeen: timestamp12("first_seen", { withTimezone: true }).notNull().default(sql13`now()`),
|
|
3602
|
+
lastSeen: timestamp12("last_seen", { withTimezone: true }).notNull().default(sql13`now()`),
|
|
3603
|
+
evidenceMessageIds: jsonb13("evidence_message_ids").$type(),
|
|
3604
|
+
createdAt: timestamp12("created_at", { withTimezone: true }).notNull().default(sql13`now()`)
|
|
3605
|
+
}, (table) => [
|
|
3606
|
+
index10("idx_entity_identities_entity").on(table.entityId),
|
|
3607
|
+
index10("idx_entity_identities_platform_handle").on(table.platform, table.handle),
|
|
3608
|
+
unique2("unique_entity_identity").on(table.entityId, table.platform, table.handle, table.agentId),
|
|
3609
|
+
foreignKey6({
|
|
3610
|
+
name: "fk_entity_identities_entity",
|
|
3611
|
+
columns: [table.entityId],
|
|
3612
|
+
foreignColumns: [entityTable.id]
|
|
3613
|
+
}).onDelete("cascade"),
|
|
3614
|
+
foreignKey6({
|
|
3615
|
+
name: "fk_entity_identities_agent",
|
|
3616
|
+
columns: [table.agentId],
|
|
3617
|
+
foreignColumns: [agentTable.id]
|
|
3618
|
+
}).onDelete("cascade")
|
|
3619
|
+
]);
|
|
3620
|
+
var entityMergeCandidateTable = pgTable19("entity_merge_candidates", {
|
|
3621
|
+
id: uuid12("id").notNull().primaryKey().default(sql13`gen_random_uuid()`),
|
|
3622
|
+
agentId: uuid12("agent_id").notNull().references(() => agentTable.id, { onDelete: "cascade" }),
|
|
3623
|
+
entityA: uuid12("entity_a").notNull().references(() => entityTable.id, { onDelete: "cascade" }),
|
|
3624
|
+
entityB: uuid12("entity_b").notNull().references(() => entityTable.id, { onDelete: "cascade" }),
|
|
3625
|
+
confidence: real("confidence").notNull().default(0),
|
|
3626
|
+
evidence: jsonb13("evidence"),
|
|
3627
|
+
status: text18("status").notNull().default("pending"),
|
|
3628
|
+
proposedAt: timestamp12("proposed_at", { withTimezone: true }).notNull().default(sql13`now()`),
|
|
3629
|
+
resolvedAt: timestamp12("resolved_at", { withTimezone: true })
|
|
3630
|
+
}, (table) => [
|
|
3631
|
+
index10("idx_entity_merge_candidates_status").on(table.status),
|
|
3632
|
+
index10("idx_entity_merge_candidates_pair").on(table.entityA, table.entityB),
|
|
3633
|
+
foreignKey6({
|
|
3634
|
+
name: "fk_entity_merge_candidates_a",
|
|
3635
|
+
columns: [table.entityA],
|
|
3636
|
+
foreignColumns: [entityTable.id]
|
|
3637
|
+
}).onDelete("cascade"),
|
|
3638
|
+
foreignKey6({
|
|
3639
|
+
name: "fk_entity_merge_candidates_b",
|
|
3640
|
+
columns: [table.entityB],
|
|
3641
|
+
foreignColumns: [entityTable.id]
|
|
3642
|
+
}).onDelete("cascade"),
|
|
3643
|
+
foreignKey6({
|
|
3644
|
+
name: "fk_entity_merge_candidates_agent",
|
|
3645
|
+
columns: [table.agentId],
|
|
3646
|
+
foreignColumns: [agentTable.id]
|
|
3647
|
+
}).onDelete("cascade")
|
|
3648
|
+
]);
|
|
3649
|
+
var factCandidateTable = pgTable19("fact_candidates", {
|
|
3650
|
+
id: uuid12("id").notNull().primaryKey().default(sql13`gen_random_uuid()`),
|
|
3651
|
+
agentId: uuid12("agent_id").notNull().references(() => agentTable.id, { onDelete: "cascade" }),
|
|
3652
|
+
entityId: uuid12("entity_id").notNull().references(() => entityTable.id, { onDelete: "cascade" }),
|
|
3653
|
+
kind: text18("kind").notNull(),
|
|
3654
|
+
existingFactId: uuid12("existing_fact_id"),
|
|
3655
|
+
proposedText: text18("proposed_text").notNull(),
|
|
3656
|
+
confidence: real("confidence").notNull().default(0),
|
|
3657
|
+
evidence: jsonb13("evidence"),
|
|
3658
|
+
status: text18("status").notNull().default("pending"),
|
|
3659
|
+
proposedAt: timestamp12("proposed_at", { withTimezone: true }).notNull().default(sql13`now()`),
|
|
3660
|
+
resolvedAt: timestamp12("resolved_at", { withTimezone: true })
|
|
3661
|
+
}, (table) => [
|
|
3662
|
+
index10("idx_fact_candidates_status").on(table.status),
|
|
3663
|
+
index10("idx_fact_candidates_entity").on(table.entityId),
|
|
3664
|
+
foreignKey6({
|
|
3665
|
+
name: "fk_fact_candidates_entity",
|
|
3666
|
+
columns: [table.entityId],
|
|
3667
|
+
foreignColumns: [entityTable.id]
|
|
3668
|
+
}).onDelete("cascade"),
|
|
3669
|
+
foreignKey6({
|
|
3670
|
+
name: "fk_fact_candidates_agent",
|
|
3671
|
+
columns: [table.agentId],
|
|
3672
|
+
foreignColumns: [agentTable.id]
|
|
3673
|
+
}).onDelete("cascade")
|
|
3674
|
+
]);
|
|
3478
3675
|
// schema/log.ts
|
|
3479
|
-
import { sql as
|
|
3480
|
-
import { foreignKey as
|
|
3481
|
-
var logTable =
|
|
3482
|
-
id:
|
|
3483
|
-
createdAt:
|
|
3484
|
-
entityId:
|
|
3485
|
-
body:
|
|
3486
|
-
type:
|
|
3487
|
-
roomId:
|
|
3676
|
+
import { sql as sql14 } from "drizzle-orm";
|
|
3677
|
+
import { foreignKey as foreignKey7, jsonb as jsonb14, pgTable as pgTable20, text as text19, timestamp as timestamp13, uuid as uuid13 } from "drizzle-orm/pg-core";
|
|
3678
|
+
var logTable = pgTable20("logs", {
|
|
3679
|
+
id: uuid13("id").defaultRandom().notNull(),
|
|
3680
|
+
createdAt: timestamp13("created_at", { withTimezone: true }).default(sql14`now()`).notNull(),
|
|
3681
|
+
entityId: uuid13("entity_id").notNull().references(() => entityTable.id, { onDelete: "cascade" }),
|
|
3682
|
+
body: jsonb14("body").notNull(),
|
|
3683
|
+
type: text19("type").notNull(),
|
|
3684
|
+
roomId: uuid13("room_id").notNull().references(() => roomTable.id, { onDelete: "cascade" })
|
|
3488
3685
|
}, (table) => [
|
|
3489
|
-
|
|
3686
|
+
foreignKey7({
|
|
3490
3687
|
name: "fk_room",
|
|
3491
3688
|
columns: [table.roomId],
|
|
3492
3689
|
foreignColumns: [roomTable.id]
|
|
3493
3690
|
}).onDelete("cascade"),
|
|
3494
|
-
|
|
3691
|
+
foreignKey7({
|
|
3495
3692
|
name: "fk_user",
|
|
3496
3693
|
columns: [table.entityId],
|
|
3497
3694
|
foreignColumns: [entityTable.id]
|
|
3498
3695
|
}).onDelete("cascade")
|
|
3499
3696
|
]);
|
|
3697
|
+
// schema/longTermMemories.ts
|
|
3698
|
+
import { sql as sql15 } from "drizzle-orm";
|
|
3699
|
+
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";
|
|
3700
|
+
var longTermMemories = pgTable21("long_term_memories", {
|
|
3701
|
+
id: uuid14("id").primaryKey().notNull(),
|
|
3702
|
+
agentId: uuid14("agent_id").notNull(),
|
|
3703
|
+
entityId: uuid14("entity_id").notNull(),
|
|
3704
|
+
category: text20("category").notNull(),
|
|
3705
|
+
content: text20("content").notNull(),
|
|
3706
|
+
metadata: jsonb15("metadata"),
|
|
3707
|
+
embedding: real2("embedding").array(),
|
|
3708
|
+
confidence: real2("confidence").default(1),
|
|
3709
|
+
source: text20("source"),
|
|
3710
|
+
createdAt: timestamp14("created_at").default(sql15`now()`).notNull(),
|
|
3711
|
+
updatedAt: timestamp14("updated_at").default(sql15`now()`).notNull(),
|
|
3712
|
+
lastAccessedAt: timestamp14("last_accessed_at"),
|
|
3713
|
+
accessCount: integer("access_count").default(0)
|
|
3714
|
+
}, (table) => [
|
|
3715
|
+
index11("long_term_memories_agent_entity_idx").on(table.agentId, table.entityId),
|
|
3716
|
+
index11("long_term_memories_category_idx").on(table.category),
|
|
3717
|
+
index11("long_term_memories_confidence_idx").on(table.confidence),
|
|
3718
|
+
index11("long_term_memories_created_at_idx").on(table.createdAt)
|
|
3719
|
+
]);
|
|
3720
|
+
// schema/memoryAccessLogs.ts
|
|
3721
|
+
import { sql as sql16 } from "drizzle-orm";
|
|
3722
|
+
import { index as index12, pgTable as pgTable22, text as text21, timestamp as timestamp15, uuid as uuid15 } from "drizzle-orm/pg-core";
|
|
3723
|
+
var memoryAccessLogs = pgTable22("memory_access_logs", {
|
|
3724
|
+
id: uuid15("id").primaryKey().notNull(),
|
|
3725
|
+
memoryId: uuid15("memory_id").notNull(),
|
|
3726
|
+
memoryType: text21("memory_type").notNull(),
|
|
3727
|
+
agentId: uuid15("agent_id").notNull(),
|
|
3728
|
+
accessType: text21("access_type").notNull(),
|
|
3729
|
+
accessedAt: timestamp15("accessed_at").default(sql16`now()`).notNull()
|
|
3730
|
+
}, (table) => [
|
|
3731
|
+
index12("memory_access_logs_memory_id_idx").on(table.memoryId),
|
|
3732
|
+
index12("memory_access_logs_agent_id_idx").on(table.agentId),
|
|
3733
|
+
index12("memory_access_logs_accessed_at_idx").on(table.accessedAt)
|
|
3734
|
+
]);
|
|
3500
3735
|
// schema/message.ts
|
|
3501
|
-
import { sql as
|
|
3502
|
-
import { jsonb as
|
|
3503
|
-
var messageTable =
|
|
3504
|
-
id:
|
|
3505
|
-
channelId:
|
|
3506
|
-
authorId:
|
|
3507
|
-
content:
|
|
3508
|
-
rawMessage:
|
|
3509
|
-
inReplyToRootMessageId:
|
|
3736
|
+
import { sql as sql17 } from "drizzle-orm";
|
|
3737
|
+
import { jsonb as jsonb16, pgTable as pgTable23, text as text22, timestamp as timestamp16 } from "drizzle-orm/pg-core";
|
|
3738
|
+
var messageTable = pgTable23("central_messages", {
|
|
3739
|
+
id: text22("id").primaryKey(),
|
|
3740
|
+
channelId: text22("channel_id").notNull().references(() => channelTable.id, { onDelete: "cascade" }),
|
|
3741
|
+
authorId: text22("author_id").notNull(),
|
|
3742
|
+
content: text22("content").notNull(),
|
|
3743
|
+
rawMessage: jsonb16("raw_message"),
|
|
3744
|
+
inReplyToRootMessageId: text22("in_reply_to_root_message_id").references(() => messageTable.id, {
|
|
3510
3745
|
onDelete: "set null"
|
|
3511
3746
|
}),
|
|
3512
|
-
sourceType:
|
|
3513
|
-
sourceId:
|
|
3514
|
-
metadata:
|
|
3515
|
-
createdAt:
|
|
3516
|
-
updatedAt:
|
|
3747
|
+
sourceType: text22("source_type"),
|
|
3748
|
+
sourceId: text22("source_id"),
|
|
3749
|
+
metadata: jsonb16("metadata"),
|
|
3750
|
+
createdAt: timestamp16("created_at", { mode: "date" }).default(sql17`CURRENT_TIMESTAMP`).notNull(),
|
|
3751
|
+
updatedAt: timestamp16("updated_at", { mode: "date" }).default(sql17`CURRENT_TIMESTAMP`).notNull()
|
|
3517
3752
|
});
|
|
3518
3753
|
// schema/messageServerAgent.ts
|
|
3519
3754
|
init_agent();
|
|
3520
|
-
import { pgTable as
|
|
3521
|
-
var messageServerAgentsTable =
|
|
3522
|
-
messageServerId:
|
|
3523
|
-
agentId:
|
|
3755
|
+
import { pgTable as pgTable24, primaryKey as primaryKey3, uuid as uuid16 } from "drizzle-orm/pg-core";
|
|
3756
|
+
var messageServerAgentsTable = pgTable24("message_server_agents", {
|
|
3757
|
+
messageServerId: uuid16("message_server_id").notNull().references(() => messageServerTable.id, { onDelete: "cascade" }),
|
|
3758
|
+
agentId: uuid16("agent_id").notNull().references(() => agentTable.id, { onDelete: "cascade" })
|
|
3524
3759
|
}, (table) => [primaryKey3({ columns: [table.messageServerId, table.agentId] })]);
|
|
3525
3760
|
// schema/pairingAllowlist.ts
|
|
3526
3761
|
init_agent();
|
|
3527
|
-
import { sql as
|
|
3528
|
-
import { index as
|
|
3529
|
-
var pairingAllowlistTable =
|
|
3530
|
-
id:
|
|
3531
|
-
channel:
|
|
3532
|
-
senderId:
|
|
3533
|
-
createdAt:
|
|
3534
|
-
metadata:
|
|
3535
|
-
agentId:
|
|
3762
|
+
import { sql as sql18 } from "drizzle-orm";
|
|
3763
|
+
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";
|
|
3764
|
+
var pairingAllowlistTable = pgTable25("pairing_allowlist", {
|
|
3765
|
+
id: uuid17("id").primaryKey().defaultRandom(),
|
|
3766
|
+
channel: text23("channel").notNull(),
|
|
3767
|
+
senderId: text23("sender_id").notNull(),
|
|
3768
|
+
createdAt: timestamp17("created_at", { withTimezone: true }).default(sql18`now()`).notNull(),
|
|
3769
|
+
metadata: jsonb17("metadata").default(sql18`'{}'::jsonb`),
|
|
3770
|
+
agentId: uuid17("agent_id").notNull().references(() => agentTable.id, { onDelete: "cascade" })
|
|
3536
3771
|
}, (table) => [
|
|
3537
|
-
|
|
3538
|
-
|
|
3772
|
+
index13("pairing_allowlist_channel_agent_idx").on(table.channel, table.agentId),
|
|
3773
|
+
uniqueIndex2("pairing_allowlist_sender_channel_agent_idx").on(table.senderId, table.channel, table.agentId)
|
|
3539
3774
|
]);
|
|
3540
3775
|
// schema/pairingRequest.ts
|
|
3541
3776
|
init_agent();
|
|
3542
|
-
import { sql as
|
|
3543
|
-
import { index as
|
|
3544
|
-
var pairingRequestTable =
|
|
3545
|
-
id:
|
|
3546
|
-
channel:
|
|
3547
|
-
senderId:
|
|
3548
|
-
code:
|
|
3549
|
-
createdAt:
|
|
3550
|
-
lastSeenAt:
|
|
3551
|
-
metadata:
|
|
3552
|
-
agentId:
|
|
3777
|
+
import { sql as sql19 } from "drizzle-orm";
|
|
3778
|
+
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";
|
|
3779
|
+
var pairingRequestTable = pgTable26("pairing_requests", {
|
|
3780
|
+
id: uuid18("id").primaryKey().defaultRandom(),
|
|
3781
|
+
channel: text24("channel").notNull(),
|
|
3782
|
+
senderId: text24("sender_id").notNull(),
|
|
3783
|
+
code: text24("code").notNull(),
|
|
3784
|
+
createdAt: timestamp18("created_at", { withTimezone: true }).default(sql19`now()`).notNull(),
|
|
3785
|
+
lastSeenAt: timestamp18("last_seen_at", { withTimezone: true }).default(sql19`now()`).notNull(),
|
|
3786
|
+
metadata: jsonb18("metadata").default(sql19`'{}'::jsonb`),
|
|
3787
|
+
agentId: uuid18("agent_id").notNull().references(() => agentTable.id, { onDelete: "cascade" })
|
|
3553
3788
|
}, (table) => [
|
|
3554
|
-
|
|
3555
|
-
|
|
3556
|
-
|
|
3789
|
+
index14("pairing_requests_channel_agent_idx").on(table.channel, table.agentId),
|
|
3790
|
+
uniqueIndex3("pairing_requests_code_channel_agent_idx").on(table.code, table.channel, table.agentId),
|
|
3791
|
+
uniqueIndex3("pairing_requests_sender_channel_agent_idx").on(table.senderId, table.channel, table.agentId)
|
|
3557
3792
|
]);
|
|
3558
3793
|
// schema/participant.ts
|
|
3559
3794
|
init_agent();
|
|
3560
|
-
import { sql as
|
|
3561
|
-
import { foreignKey as
|
|
3562
|
-
var participantTable =
|
|
3563
|
-
id:
|
|
3564
|
-
createdAt:
|
|
3565
|
-
entityId:
|
|
3795
|
+
import { sql as sql20 } from "drizzle-orm";
|
|
3796
|
+
import { foreignKey as foreignKey8, index as index15, pgTable as pgTable27, text as text25, timestamp as timestamp19, uuid as uuid19 } from "drizzle-orm/pg-core";
|
|
3797
|
+
var participantTable = pgTable27("participants", {
|
|
3798
|
+
id: uuid19("id").notNull().primaryKey().default(sql20`gen_random_uuid()`),
|
|
3799
|
+
createdAt: timestamp19("created_at", { withTimezone: true }).default(sql20`now()`).notNull(),
|
|
3800
|
+
entityId: uuid19("entity_id").references(() => entityTable.id, {
|
|
3566
3801
|
onDelete: "cascade"
|
|
3567
3802
|
}),
|
|
3568
|
-
roomId:
|
|
3803
|
+
roomId: uuid19("room_id").references(() => roomTable.id, {
|
|
3569
3804
|
onDelete: "cascade"
|
|
3570
3805
|
}),
|
|
3571
|
-
agentId:
|
|
3806
|
+
agentId: uuid19("agent_id").references(() => agentTable.id, {
|
|
3572
3807
|
onDelete: "cascade"
|
|
3573
3808
|
}),
|
|
3574
|
-
roomState:
|
|
3809
|
+
roomState: text25("room_state")
|
|
3575
3810
|
}, (table) => [
|
|
3576
|
-
|
|
3577
|
-
|
|
3578
|
-
|
|
3811
|
+
index15("idx_participants_user").on(table.entityId),
|
|
3812
|
+
index15("idx_participants_room").on(table.roomId),
|
|
3813
|
+
foreignKey8({
|
|
3579
3814
|
name: "fk_room",
|
|
3580
3815
|
columns: [table.roomId],
|
|
3581
3816
|
foreignColumns: [roomTable.id]
|
|
3582
3817
|
}).onDelete("cascade"),
|
|
3583
|
-
|
|
3818
|
+
foreignKey8({
|
|
3584
3819
|
name: "fk_user",
|
|
3585
3820
|
columns: [table.entityId],
|
|
3586
3821
|
foreignColumns: [entityTable.id]
|
|
@@ -3588,34 +3823,34 @@ var participantTable = pgTable17("participants", {
|
|
|
3588
3823
|
]);
|
|
3589
3824
|
// schema/relationship.ts
|
|
3590
3825
|
init_agent();
|
|
3591
|
-
import { sql as
|
|
3826
|
+
import { sql as sql21 } from "drizzle-orm";
|
|
3592
3827
|
import {
|
|
3593
|
-
foreignKey as
|
|
3594
|
-
index as
|
|
3595
|
-
jsonb as
|
|
3596
|
-
pgTable as
|
|
3597
|
-
text as
|
|
3598
|
-
timestamp as
|
|
3599
|
-
unique as
|
|
3600
|
-
uuid as
|
|
3828
|
+
foreignKey as foreignKey9,
|
|
3829
|
+
index as index16,
|
|
3830
|
+
jsonb as jsonb19,
|
|
3831
|
+
pgTable as pgTable28,
|
|
3832
|
+
text as text26,
|
|
3833
|
+
timestamp as timestamp20,
|
|
3834
|
+
unique as unique3,
|
|
3835
|
+
uuid as uuid20
|
|
3601
3836
|
} from "drizzle-orm/pg-core";
|
|
3602
|
-
var relationshipTable =
|
|
3603
|
-
id:
|
|
3604
|
-
createdAt:
|
|
3605
|
-
sourceEntityId:
|
|
3606
|
-
targetEntityId:
|
|
3607
|
-
agentId:
|
|
3608
|
-
tags:
|
|
3609
|
-
metadata:
|
|
3837
|
+
var relationshipTable = pgTable28("relationships", {
|
|
3838
|
+
id: uuid20("id").notNull().primaryKey().default(sql21`gen_random_uuid()`),
|
|
3839
|
+
createdAt: timestamp20("created_at", { withTimezone: true }).default(sql21`now()`).notNull(),
|
|
3840
|
+
sourceEntityId: uuid20("source_entity_id").notNull().references(() => entityTable.id, { onDelete: "cascade" }),
|
|
3841
|
+
targetEntityId: uuid20("target_entity_id").notNull().references(() => entityTable.id, { onDelete: "cascade" }),
|
|
3842
|
+
agentId: uuid20("agent_id").notNull().references(() => agentTable.id, { onDelete: "cascade" }),
|
|
3843
|
+
tags: text26("tags").array(),
|
|
3844
|
+
metadata: jsonb19("metadata")
|
|
3610
3845
|
}, (table) => [
|
|
3611
|
-
|
|
3612
|
-
|
|
3613
|
-
|
|
3846
|
+
index16("idx_relationships_users").on(table.sourceEntityId, table.targetEntityId),
|
|
3847
|
+
unique3("unique_relationship").on(table.sourceEntityId, table.targetEntityId, table.agentId),
|
|
3848
|
+
foreignKey9({
|
|
3614
3849
|
name: "fk_user_a",
|
|
3615
3850
|
columns: [table.sourceEntityId],
|
|
3616
3851
|
foreignColumns: [entityTable.id]
|
|
3617
3852
|
}).onDelete("cascade"),
|
|
3618
|
-
|
|
3853
|
+
foreignKey9({
|
|
3619
3854
|
name: "fk_user_b",
|
|
3620
3855
|
columns: [table.targetEntityId],
|
|
3621
3856
|
foreignColumns: [entityTable.id]
|
|
@@ -3625,24 +3860,58 @@ var relationshipTable = pgTable18("relationships", {
|
|
|
3625
3860
|
// schema/index.ts
|
|
3626
3861
|
init_server();
|
|
3627
3862
|
|
|
3863
|
+
// schema/sessionSummaries.ts
|
|
3864
|
+
import { sql as sql23 } from "drizzle-orm";
|
|
3865
|
+
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";
|
|
3866
|
+
var sessionSummaries = pgTable30("session_summaries", {
|
|
3867
|
+
id: uuid22("id").primaryKey().notNull(),
|
|
3868
|
+
agentId: uuid22("agent_id").notNull(),
|
|
3869
|
+
roomId: uuid22("room_id").notNull(),
|
|
3870
|
+
entityId: uuid22("entity_id"),
|
|
3871
|
+
summary: text27("summary").notNull(),
|
|
3872
|
+
messageCount: integer2("message_count").notNull(),
|
|
3873
|
+
lastMessageOffset: integer2("last_message_offset").default(0).notNull(),
|
|
3874
|
+
startTime: timestamp22("start_time").notNull(),
|
|
3875
|
+
endTime: timestamp22("end_time").notNull(),
|
|
3876
|
+
topics: jsonb20("topics").$type(),
|
|
3877
|
+
metadata: jsonb20("metadata"),
|
|
3878
|
+
embedding: real3("embedding").array(),
|
|
3879
|
+
createdAt: timestamp22("created_at").default(sql23`now()`).notNull(),
|
|
3880
|
+
updatedAt: timestamp22("updated_at").default(sql23`now()`).notNull()
|
|
3881
|
+
}, (table) => [
|
|
3882
|
+
index17("session_summaries_agent_room_idx").on(table.agentId, table.roomId),
|
|
3883
|
+
index17("session_summaries_entity_idx").on(table.entityId),
|
|
3884
|
+
index17("session_summaries_start_time_idx").on(table.startTime)
|
|
3885
|
+
]);
|
|
3628
3886
|
// schema/tasks.ts
|
|
3629
3887
|
init_agent();
|
|
3630
|
-
import { sql as
|
|
3631
|
-
import { jsonb as
|
|
3632
|
-
var taskTable =
|
|
3633
|
-
id:
|
|
3634
|
-
name:
|
|
3635
|
-
description:
|
|
3636
|
-
roomId:
|
|
3637
|
-
worldId:
|
|
3638
|
-
entityId:
|
|
3639
|
-
agentId:
|
|
3640
|
-
tags:
|
|
3641
|
-
metadata:
|
|
3642
|
-
createdAt:
|
|
3643
|
-
updatedAt:
|
|
3888
|
+
import { sql as sql24 } from "drizzle-orm";
|
|
3889
|
+
import { jsonb as jsonb21, pgTable as pgTable31, text as text28, timestamp as timestamp23, uuid as uuid23 } from "drizzle-orm/pg-core";
|
|
3890
|
+
var taskTable = pgTable31("tasks", {
|
|
3891
|
+
id: uuid23("id").primaryKey().defaultRandom(),
|
|
3892
|
+
name: text28("name").notNull(),
|
|
3893
|
+
description: text28("description"),
|
|
3894
|
+
roomId: uuid23("room_id"),
|
|
3895
|
+
worldId: uuid23("world_id"),
|
|
3896
|
+
entityId: uuid23("entity_id"),
|
|
3897
|
+
agentId: uuid23("agent_id").notNull().references(() => agentTable.id, { onDelete: "cascade" }),
|
|
3898
|
+
tags: text28("tags").array().default(sql24`'{}'::text[]`),
|
|
3899
|
+
metadata: jsonb21("metadata").default(sql24`'{}'::jsonb`),
|
|
3900
|
+
createdAt: timestamp23("created_at", { withTimezone: true }).defaultNow(),
|
|
3901
|
+
updatedAt: timestamp23("updated_at", { withTimezone: true }).defaultNow()
|
|
3644
3902
|
});
|
|
3645
3903
|
// base.ts
|
|
3904
|
+
function asRawMessage(value) {
|
|
3905
|
+
if (value && typeof value === "object" && !Array.isArray(value)) {
|
|
3906
|
+
return value;
|
|
3907
|
+
}
|
|
3908
|
+
return;
|
|
3909
|
+
}
|
|
3910
|
+
function asMetadata(value) {
|
|
3911
|
+
return value ?? undefined;
|
|
3912
|
+
}
|
|
3913
|
+
var v4 = () => crypto.randomUUID();
|
|
3914
|
+
|
|
3646
3915
|
class BaseDrizzleAdapter extends DatabaseAdapter {
|
|
3647
3916
|
maxRetries = 3;
|
|
3648
3917
|
baseDelay = 1000;
|
|
@@ -3687,8 +3956,11 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
|
|
|
3687
3956
|
if (names instanceof Set) {
|
|
3688
3957
|
return Array.from(names).map(String);
|
|
3689
3958
|
}
|
|
3690
|
-
if (typeof names === "object"
|
|
3691
|
-
|
|
3959
|
+
if (typeof names === "object") {
|
|
3960
|
+
const iterableNames = names;
|
|
3961
|
+
if (typeof iterableNames[Symbol.iterator] === "function") {
|
|
3962
|
+
return Array.from(names).map(String);
|
|
3963
|
+
}
|
|
3692
3964
|
}
|
|
3693
3965
|
return [String(names)];
|
|
3694
3966
|
}
|
|
@@ -3698,7 +3970,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
|
|
|
3698
3970
|
normalizeWorldData(world) {
|
|
3699
3971
|
const worldData = {
|
|
3700
3972
|
agentId: this.agentId,
|
|
3701
|
-
id: world.id ||
|
|
3973
|
+
id: world.id || v4(),
|
|
3702
3974
|
name: world.name || "",
|
|
3703
3975
|
metadata: world.metadata || {}
|
|
3704
3976
|
};
|
|
@@ -3759,13 +4031,12 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
|
|
|
3759
4031
|
}
|
|
3760
4032
|
const resolvedDimension = DIMENSION_MAP[dimension];
|
|
3761
4033
|
if (!resolvedDimension) {
|
|
3762
|
-
const fallbackDimension = this.embeddingDimension ?? DIMENSION_MAP[384];
|
|
3763
|
-
this.embeddingDimension = fallbackDimension;
|
|
3764
4034
|
logger9.warn({
|
|
3765
4035
|
src: "plugin:sql",
|
|
4036
|
+
agentId: this.agentId,
|
|
3766
4037
|
requestedDimension: dimension,
|
|
3767
|
-
fallbackDimension
|
|
3768
|
-
}, "Unsupported embedding dimension requested; keeping
|
|
4038
|
+
fallbackDimension: this.embeddingDimension
|
|
4039
|
+
}, "Unsupported embedding dimension requested; keeping current embedding column");
|
|
3769
4040
|
return;
|
|
3770
4041
|
}
|
|
3771
4042
|
this.embeddingDimension = resolvedDimension;
|
|
@@ -4112,15 +4383,17 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
|
|
|
4112
4383
|
return await this.db.transaction(async (tx) => {
|
|
4113
4384
|
const normalizedEntities = entities.map((entity) => {
|
|
4114
4385
|
const { names, metadata, ...normalizedEntity } = entity;
|
|
4386
|
+
const id = entity.id || v4();
|
|
4115
4387
|
return {
|
|
4116
4388
|
...normalizedEntity,
|
|
4389
|
+
id,
|
|
4117
4390
|
agentId: this.agentId,
|
|
4118
4391
|
names: this.normalizeEntityNames(names),
|
|
4119
4392
|
metadata: metadata || {}
|
|
4120
4393
|
};
|
|
4121
4394
|
});
|
|
4122
4395
|
await tx.insert(entityTable).values(normalizedEntities);
|
|
4123
|
-
return
|
|
4396
|
+
return normalizedEntities.map((entity) => entity.id);
|
|
4124
4397
|
});
|
|
4125
4398
|
} catch (error) {
|
|
4126
4399
|
logger9.error({
|
|
@@ -4128,7 +4401,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
|
|
|
4128
4401
|
entityId: entities[0]?.id,
|
|
4129
4402
|
error: error instanceof Error ? error.message : String(error)
|
|
4130
4403
|
}, "Failed to create entities");
|
|
4131
|
-
return
|
|
4404
|
+
return [];
|
|
4132
4405
|
}
|
|
4133
4406
|
});
|
|
4134
4407
|
}
|
|
@@ -4139,8 +4412,8 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
|
|
|
4139
4412
|
}
|
|
4140
4413
|
try {
|
|
4141
4414
|
const existingEntities = await this.getEntitiesByIds([entity.id]);
|
|
4142
|
-
if (!existingEntities
|
|
4143
|
-
return await this.createEntities([entity]);
|
|
4415
|
+
if (!existingEntities?.length) {
|
|
4416
|
+
return (await this.createEntities([entity])).length > 0;
|
|
4144
4417
|
}
|
|
4145
4418
|
return true;
|
|
4146
4419
|
} catch (error) {
|
|
@@ -4177,11 +4450,11 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
|
|
|
4177
4450
|
async getEntitiesByNames(params) {
|
|
4178
4451
|
return this.withDatabase(async () => {
|
|
4179
4452
|
const { names, agentId } = params;
|
|
4180
|
-
const nameConditions = names.map((name) =>
|
|
4181
|
-
const query =
|
|
4453
|
+
const nameConditions = names.map((name) => sql33`${name} = ANY(${entityTable.names})`);
|
|
4454
|
+
const query = sql33`
|
|
4182
4455
|
SELECT * FROM ${entityTable}
|
|
4183
4456
|
WHERE ${entityTable.agentId} = ${agentId}
|
|
4184
|
-
AND (${
|
|
4457
|
+
AND (${sql33.join(nameConditions, sql33` OR `)})
|
|
4185
4458
|
`;
|
|
4186
4459
|
const result = await this.db.execute(query);
|
|
4187
4460
|
return result.rows.map((row) => ({
|
|
@@ -4204,7 +4477,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
|
|
|
4204
4477
|
metadata: row.metadata || {}
|
|
4205
4478
|
}));
|
|
4206
4479
|
}
|
|
4207
|
-
const searchQuery =
|
|
4480
|
+
const searchQuery = sql33`
|
|
4208
4481
|
SELECT * FROM ${entityTable}
|
|
4209
4482
|
WHERE ${entityTable.agentId} = ${agentId}
|
|
4210
4483
|
AND EXISTS (
|
|
@@ -4312,9 +4585,8 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
|
|
|
4312
4585
|
});
|
|
4313
4586
|
}
|
|
4314
4587
|
async getMemories(params) {
|
|
4315
|
-
const { entityId, agentId, roomId, worldId,
|
|
4316
|
-
|
|
4317
|
-
throw new Error("tableName is required");
|
|
4588
|
+
const { entityId, agentId, roomId, worldId, unique: unique4, start, end, offset } = params;
|
|
4589
|
+
const tableName = params.tableName ?? "messages";
|
|
4318
4590
|
if (offset !== undefined && offset < 0) {
|
|
4319
4591
|
throw new Error("offset must be a non-negative number");
|
|
4320
4592
|
}
|
|
@@ -4332,7 +4604,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
|
|
|
4332
4604
|
if (end !== undefined) {
|
|
4333
4605
|
conditions.push(lte(memoryTable.createdAt, new Date(end)));
|
|
4334
4606
|
}
|
|
4335
|
-
if (
|
|
4607
|
+
if (unique4) {
|
|
4336
4608
|
conditions.push(eq2(memoryTable.unique, true));
|
|
4337
4609
|
}
|
|
4338
4610
|
if (agentId) {
|
|
@@ -4460,7 +4732,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
|
|
|
4460
4732
|
async getCachedEmbeddings(opts) {
|
|
4461
4733
|
return this.withDatabase(async () => {
|
|
4462
4734
|
try {
|
|
4463
|
-
const results = await this.db.execute(
|
|
4735
|
+
const results = await this.db.execute(sql33`
|
|
4464
4736
|
WITH content_text AS (
|
|
4465
4737
|
SELECT
|
|
4466
4738
|
m.id,
|
|
@@ -4489,9 +4761,9 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
|
|
|
4489
4761
|
)
|
|
4490
4762
|
SELECT
|
|
4491
4763
|
embedding,
|
|
4492
|
-
levenshtein(${opts.query_input}, content_text) as levenshtein_score
|
|
4764
|
+
levenshtein(CAST(${opts.query_input} AS text), content_text) as levenshtein_score
|
|
4493
4765
|
FROM embedded_text
|
|
4494
|
-
WHERE levenshtein(${opts.query_input}, content_text) <= ${opts.query_threshold}
|
|
4766
|
+
WHERE levenshtein(CAST(${opts.query_input} AS text), content_text) <= ${opts.query_threshold}
|
|
4495
4767
|
ORDER BY levenshtein_score
|
|
4496
4768
|
LIMIT ${opts.query_match_count}
|
|
4497
4769
|
`);
|
|
@@ -4520,7 +4792,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
|
|
|
4520
4792
|
const jsonString = JSON.stringify(sanitizedBody);
|
|
4521
4793
|
await this.withEntityContext(params.entityId, async (tx) => {
|
|
4522
4794
|
await tx.insert(logTable).values({
|
|
4523
|
-
body:
|
|
4795
|
+
body: sql33`${jsonString}::jsonb`,
|
|
4524
4796
|
entityId: params.entityId,
|
|
4525
4797
|
roomId: params.roomId,
|
|
4526
4798
|
type: params.type
|
|
@@ -4534,7 +4806,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
|
|
|
4534
4806
|
entityId: params.entityId,
|
|
4535
4807
|
error: error instanceof Error ? error.message : String(error)
|
|
4536
4808
|
}, "Failed to create log entry");
|
|
4537
|
-
|
|
4809
|
+
return;
|
|
4538
4810
|
}
|
|
4539
4811
|
});
|
|
4540
4812
|
}
|
|
@@ -4594,7 +4866,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
|
|
|
4594
4866
|
const runMap = new Map;
|
|
4595
4867
|
const conditions = [
|
|
4596
4868
|
eq2(logTable.type, "run_event"),
|
|
4597
|
-
|
|
4869
|
+
sql33`${logTable.body} ? 'runId'`,
|
|
4598
4870
|
eq2(roomTable.agentId, this.agentId)
|
|
4599
4871
|
];
|
|
4600
4872
|
if (params.roomId) {
|
|
@@ -4609,9 +4881,9 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
|
|
|
4609
4881
|
const whereClause = and(...conditions);
|
|
4610
4882
|
const eventLimit = Math.max(limit * 20, 200);
|
|
4611
4883
|
const runEventRows = await tx.select({
|
|
4612
|
-
runId:
|
|
4613
|
-
status:
|
|
4614
|
-
messageId:
|
|
4884
|
+
runId: sql33`(${logTable.body} ->> 'runId')`,
|
|
4885
|
+
status: sql33`(${logTable.body} ->> 'status')`,
|
|
4886
|
+
messageId: sql33`(${logTable.body} ->> 'messageId')`,
|
|
4615
4887
|
rawBody: logTable.body,
|
|
4616
4888
|
createdAt: logTable.createdAt,
|
|
4617
4889
|
roomId: logTable.roomId,
|
|
@@ -4658,18 +4930,18 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
|
|
|
4658
4930
|
}
|
|
4659
4931
|
}
|
|
4660
4932
|
const createdAt = row.createdAt instanceof Date ? row.createdAt : new Date(row.createdAt);
|
|
4661
|
-
const
|
|
4933
|
+
const timestamp24 = createdAt.getTime();
|
|
4662
4934
|
const bodyStatus = body?.status;
|
|
4663
4935
|
const eventStatus = row.status ?? bodyStatus;
|
|
4664
4936
|
if (eventStatus === "started") {
|
|
4665
4937
|
const currentStartedAt = summary.startedAt === null ? null : typeof summary.startedAt === "bigint" ? Number(summary.startedAt) : summary.startedAt;
|
|
4666
|
-
summary.startedAt = currentStartedAt === null ?
|
|
4938
|
+
summary.startedAt = currentStartedAt === null ? timestamp24 : Math.min(currentStartedAt, timestamp24);
|
|
4667
4939
|
} else if (eventStatus === "completed" || eventStatus === "timeout" || eventStatus === "error") {
|
|
4668
4940
|
summary.status = eventStatus;
|
|
4669
|
-
summary.endedAt =
|
|
4941
|
+
summary.endedAt = timestamp24;
|
|
4670
4942
|
if (summary.startedAt !== null) {
|
|
4671
4943
|
const startedAtNum = typeof summary.startedAt === "bigint" ? Number(summary.startedAt) : summary.startedAt;
|
|
4672
|
-
summary.durationMs = Math.max(
|
|
4944
|
+
summary.durationMs = Math.max(timestamp24 - startedAtNum, 0);
|
|
4673
4945
|
}
|
|
4674
4946
|
}
|
|
4675
4947
|
runMap.set(runId, summary);
|
|
@@ -4697,8 +4969,8 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
|
|
|
4697
4969
|
}
|
|
4698
4970
|
const runIds = limitedRuns.map((run) => run.runId).filter(Boolean);
|
|
4699
4971
|
if (runIds.length > 0) {
|
|
4700
|
-
const runIdArray =
|
|
4701
|
-
const actionSummary = await this.db.execute(
|
|
4972
|
+
const runIdArray = sql33`array[${sql33.join(runIds.map((id) => sql33`${id}`), sql33`, `)}]::text[]`;
|
|
4973
|
+
const actionSummary = await this.db.execute(sql33`
|
|
4702
4974
|
SELECT
|
|
4703
4975
|
body->>'runId' as "runId",
|
|
4704
4976
|
COUNT(*)::int as "actions",
|
|
@@ -4718,7 +4990,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
|
|
|
4718
4990
|
counts.errors += Number(row.errors ?? 0);
|
|
4719
4991
|
counts.modelCalls += Number(row.modelCalls ?? 0);
|
|
4720
4992
|
}
|
|
4721
|
-
const evaluatorSummary = await this.db.execute(
|
|
4993
|
+
const evaluatorSummary = await this.db.execute(sql33`
|
|
4722
4994
|
SELECT
|
|
4723
4995
|
body->>'runId' as "runId",
|
|
4724
4996
|
COUNT(*)::int as "evaluators"
|
|
@@ -4734,7 +5006,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
|
|
|
4734
5006
|
continue;
|
|
4735
5007
|
counts.evaluators += Number(row.evaluators ?? 0);
|
|
4736
5008
|
}
|
|
4737
|
-
const genericSummary = await this.db.execute(
|
|
5009
|
+
const genericSummary = await this.db.execute(sql33`
|
|
4738
5010
|
SELECT
|
|
4739
5011
|
body->>'runId' as "runId",
|
|
4740
5012
|
COUNT(*) FILTER (WHERE type LIKE 'useModel:%')::int as "modelLogs",
|
|
@@ -4782,13 +5054,13 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
|
|
|
4782
5054
|
worldId: params.worldId,
|
|
4783
5055
|
entityId: params.entityId,
|
|
4784
5056
|
unique: params.unique,
|
|
4785
|
-
tableName: params.tableName
|
|
5057
|
+
tableName: params.tableName ?? "messages"
|
|
4786
5058
|
});
|
|
4787
5059
|
}
|
|
4788
5060
|
async searchMemoriesByEmbedding(embedding, params) {
|
|
4789
5061
|
return this.withDatabase(async () => {
|
|
4790
5062
|
const cleanVector = embedding.map((n) => Number.isFinite(n) ? Number(n.toFixed(6)) : 0);
|
|
4791
|
-
const similarity =
|
|
5063
|
+
const similarity = sql33`1 - (${cosineDistance(embeddingTable[this.embeddingDimension], cleanVector)})`;
|
|
4792
5064
|
const conditions = [eq2(memoryTable.type, params.tableName)];
|
|
4793
5065
|
if (params.unique) {
|
|
4794
5066
|
conditions.push(eq2(memoryTable.unique, true));
|
|
@@ -4828,7 +5100,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
|
|
|
4828
5100
|
});
|
|
4829
5101
|
}
|
|
4830
5102
|
async createMemory(memory, tableName) {
|
|
4831
|
-
const memoryId = memory.id ??
|
|
5103
|
+
const memoryId = memory.id ?? v4();
|
|
4832
5104
|
const existing = await this.getMemoryById(memoryId);
|
|
4833
5105
|
if (existing) {
|
|
4834
5106
|
return memoryId;
|
|
@@ -4854,8 +5126,8 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
|
|
|
4854
5126
|
{
|
|
4855
5127
|
id: memoryId,
|
|
4856
5128
|
type: tableName,
|
|
4857
|
-
content:
|
|
4858
|
-
metadata:
|
|
5129
|
+
content: sql33`${contentToInsert}::jsonb`,
|
|
5130
|
+
metadata: sql33`${metadataToInsert}::jsonb`,
|
|
4859
5131
|
entityId: memory.entityId,
|
|
4860
5132
|
roomId: memory.roomId,
|
|
4861
5133
|
worldId: memory.worldId,
|
|
@@ -4866,7 +5138,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
|
|
|
4866
5138
|
]);
|
|
4867
5139
|
if (memory.embedding && Array.isArray(memory.embedding)) {
|
|
4868
5140
|
const embeddingValues = {
|
|
4869
|
-
id:
|
|
5141
|
+
id: v4(),
|
|
4870
5142
|
memoryId,
|
|
4871
5143
|
createdAt: memory.createdAt !== undefined ? new Date(memory.createdAt) : new Date
|
|
4872
5144
|
};
|
|
@@ -4885,15 +5157,15 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
|
|
|
4885
5157
|
const contentToUpdate = typeof memory.content === "string" ? memory.content : JSON.stringify(memory.content ?? {});
|
|
4886
5158
|
const metadataToUpdate = typeof memory.metadata === "string" ? memory.metadata : JSON.stringify(memory.metadata ?? {});
|
|
4887
5159
|
await tx.update(memoryTable).set({
|
|
4888
|
-
content:
|
|
5160
|
+
content: sql33`${contentToUpdate}::jsonb`,
|
|
4889
5161
|
...memory.metadata && {
|
|
4890
|
-
metadata:
|
|
5162
|
+
metadata: sql33`${metadataToUpdate}::jsonb`
|
|
4891
5163
|
}
|
|
4892
5164
|
}).where(eq2(memoryTable.id, memory.id));
|
|
4893
5165
|
} else if (memory.metadata) {
|
|
4894
5166
|
const metadataToUpdate = typeof memory.metadata === "string" ? memory.metadata : JSON.stringify(memory.metadata ?? {});
|
|
4895
5167
|
await tx.update(memoryTable).set({
|
|
4896
|
-
metadata:
|
|
5168
|
+
metadata: sql33`${metadataToUpdate}::jsonb`
|
|
4897
5169
|
}).where(eq2(memoryTable.id, memory.id));
|
|
4898
5170
|
}
|
|
4899
5171
|
if (memory.embedding && Array.isArray(memory.embedding)) {
|
|
@@ -4905,7 +5177,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
|
|
|
4905
5177
|
await tx.update(embeddingTable).set(updateValues).where(eq2(embeddingTable.memoryId, memory.id));
|
|
4906
5178
|
} else {
|
|
4907
5179
|
const embeddingValues = {
|
|
4908
|
-
id:
|
|
5180
|
+
id: v4(),
|
|
4909
5181
|
memoryId: memory.id
|
|
4910
5182
|
};
|
|
4911
5183
|
embeddingValues[this.embeddingDimension] = cleanVector;
|
|
@@ -4960,15 +5232,19 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
|
|
|
4960
5232
|
}
|
|
4961
5233
|
}
|
|
4962
5234
|
async getMemoryFragments(tx, documentId) {
|
|
4963
|
-
const fragments = await tx.select({ id: memoryTable.id }).from(memoryTable).where(and(eq2(memoryTable.agentId, this.agentId),
|
|
5235
|
+
const fragments = await tx.select({ id: memoryTable.id }).from(memoryTable).where(and(eq2(memoryTable.agentId, this.agentId), sql33`${memoryTable.metadata}->>'documentId' = ${documentId}`));
|
|
4964
5236
|
return fragments.map((f) => ({ id: f.id }));
|
|
4965
5237
|
}
|
|
4966
|
-
async deleteAllMemories(
|
|
5238
|
+
async deleteAllMemories(roomIdsOrRoomId, tableName) {
|
|
4967
5239
|
return this.withDatabase(async () => {
|
|
5240
|
+
const roomIds = Array.isArray(roomIdsOrRoomId) ? roomIdsOrRoomId : [roomIdsOrRoomId];
|
|
5241
|
+
if (roomIds.length === 0) {
|
|
5242
|
+
return;
|
|
5243
|
+
}
|
|
4968
5244
|
await this.db.transaction(async (tx) => {
|
|
4969
|
-
const rows = await tx.select({ id: memoryTable.id }).from(memoryTable).where(and(
|
|
5245
|
+
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)));
|
|
4970
5246
|
const ids = rows.map((r) => r.id);
|
|
4971
|
-
logger9.debug({ src: "plugin:sql",
|
|
5247
|
+
logger9.debug({ src: "plugin:sql", roomIds, tableName, memoryCount: ids.length }, "Deleting all memories");
|
|
4972
5248
|
if (ids.length === 0) {
|
|
4973
5249
|
return;
|
|
4974
5250
|
}
|
|
@@ -4976,19 +5252,36 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
|
|
|
4976
5252
|
await this.deleteMemoryFragments(tx, memoryId);
|
|
4977
5253
|
await tx.delete(embeddingTable).where(eq2(embeddingTable.memoryId, memoryId));
|
|
4978
5254
|
}));
|
|
4979
|
-
await tx.delete(memoryTable).where(and(
|
|
5255
|
+
await tx.delete(memoryTable).where(and(inArray(memoryTable.roomId, roomIds), eq2(memoryTable.type, tableName), eq2(memoryTable.agentId, this.agentId)));
|
|
4980
5256
|
});
|
|
4981
5257
|
});
|
|
4982
5258
|
}
|
|
4983
|
-
async countMemories(
|
|
4984
|
-
|
|
4985
|
-
|
|
5259
|
+
async countMemories(paramsOrRoomId, unique4 = true, tableName) {
|
|
5260
|
+
const params = typeof paramsOrRoomId === "string" ? {
|
|
5261
|
+
roomIds: [paramsOrRoomId],
|
|
5262
|
+
unique: unique4,
|
|
5263
|
+
tableName: tableName ?? "messages"
|
|
5264
|
+
} : {
|
|
5265
|
+
...paramsOrRoomId,
|
|
5266
|
+
tableName: paramsOrRoomId.tableName ?? "messages",
|
|
5267
|
+
unique: paramsOrRoomId.unique ?? false
|
|
5268
|
+
};
|
|
4986
5269
|
return this.withDatabase(async () => {
|
|
4987
|
-
const
|
|
4988
|
-
|
|
5270
|
+
const tableName2 = params.tableName ?? "messages";
|
|
5271
|
+
const conditions = [eq2(memoryTable.type, tableName2)];
|
|
5272
|
+
if (params.roomIds && params.roomIds.length > 0) {
|
|
5273
|
+
conditions.push(inArray(memoryTable.roomId, params.roomIds));
|
|
5274
|
+
}
|
|
5275
|
+
if (params.entityId) {
|
|
5276
|
+
conditions.push(eq2(memoryTable.entityId, params.entityId));
|
|
5277
|
+
}
|
|
5278
|
+
if (params.agentId) {
|
|
5279
|
+
conditions.push(eq2(memoryTable.agentId, params.agentId));
|
|
5280
|
+
}
|
|
5281
|
+
if (params.unique) {
|
|
4989
5282
|
conditions.push(eq2(memoryTable.unique, true));
|
|
4990
5283
|
}
|
|
4991
|
-
const result = await this.db.select({ count:
|
|
5284
|
+
const result = await this.db.select({ count: sql33`count(*)` }).from(memoryTable).where(and(...conditions));
|
|
4992
5285
|
const result0 = result[0];
|
|
4993
5286
|
return Number(result0?.count ?? 0);
|
|
4994
5287
|
});
|
|
@@ -5049,7 +5342,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
|
|
|
5049
5342
|
const roomsWithIds = rooms.map((room) => ({
|
|
5050
5343
|
...room,
|
|
5051
5344
|
agentId: this.agentId,
|
|
5052
|
-
id: room.id ||
|
|
5345
|
+
id: room.id || v4()
|
|
5053
5346
|
}));
|
|
5054
5347
|
const insertedRooms = await this.db.insert(roomTable).values(roomsWithIds).onConflictDoNothing().returning();
|
|
5055
5348
|
const insertedIds = insertedRooms.map((r) => r.id);
|
|
@@ -5153,7 +5446,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
|
|
|
5153
5446
|
roomId: participantTable.roomId
|
|
5154
5447
|
}).from(participantTable).where(eq2(participantTable.entityId, entityId));
|
|
5155
5448
|
const entities = await this.getEntitiesByIds([entityId]);
|
|
5156
|
-
if (!entities
|
|
5449
|
+
if (!entities?.length) {
|
|
5157
5450
|
return [];
|
|
5158
5451
|
}
|
|
5159
5452
|
return result.map((row) => ({
|
|
@@ -5201,7 +5494,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
|
|
|
5201
5494
|
}
|
|
5202
5495
|
async createRelationship(params) {
|
|
5203
5496
|
return this.withDatabase(async () => {
|
|
5204
|
-
const id =
|
|
5497
|
+
const id = v4();
|
|
5205
5498
|
const saveParams = {
|
|
5206
5499
|
id,
|
|
5207
5500
|
sourceEntityId: params.sourceEntityId,
|
|
@@ -5268,22 +5561,22 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
|
|
|
5268
5561
|
if (entityIds.length === 0) {
|
|
5269
5562
|
return [];
|
|
5270
5563
|
}
|
|
5271
|
-
const entityFilter =
|
|
5272
|
-
let query =
|
|
5564
|
+
const entityFilter = sql33.join(entityIds.map((id) => sql33`(${relationshipTable.sourceEntityId} = ${id} OR ${relationshipTable.targetEntityId} = ${id})`), sql33` OR `);
|
|
5565
|
+
let query = sql33`
|
|
5273
5566
|
SELECT * FROM ${relationshipTable}
|
|
5274
5567
|
WHERE (${entityFilter})
|
|
5275
5568
|
`;
|
|
5276
5569
|
if (tags && tags.length > 0) {
|
|
5277
|
-
query =
|
|
5570
|
+
query = sql33`
|
|
5278
5571
|
${query}
|
|
5279
|
-
AND ${relationshipTable.tags} && CAST(ARRAY[${
|
|
5572
|
+
AND ${relationshipTable.tags} && CAST(ARRAY[${sql33.join(tags, sql33`, `)}] AS text[])
|
|
5280
5573
|
`;
|
|
5281
5574
|
}
|
|
5282
5575
|
if (typeof limit === "number") {
|
|
5283
|
-
query =
|
|
5576
|
+
query = sql33`${query} LIMIT ${limit}`;
|
|
5284
5577
|
}
|
|
5285
5578
|
if (typeof offset === "number" && offset > 0) {
|
|
5286
|
-
query =
|
|
5579
|
+
query = sql33`${query} OFFSET ${offset}`;
|
|
5287
5580
|
}
|
|
5288
5581
|
const result = await this.db.execute(query);
|
|
5289
5582
|
return result.rows.map((relationship) => ({
|
|
@@ -5401,7 +5694,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
|
|
|
5401
5694
|
const now = new Date;
|
|
5402
5695
|
const metadata = task.metadata || {};
|
|
5403
5696
|
const values = {
|
|
5404
|
-
id: task.id,
|
|
5697
|
+
...task.id ? { id: task.id } : {},
|
|
5405
5698
|
name: task.name,
|
|
5406
5699
|
description: task.description,
|
|
5407
5700
|
roomId: task.roomId,
|
|
@@ -5421,7 +5714,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
|
|
|
5421
5714
|
return this.withRetry(async () => {
|
|
5422
5715
|
return this.withDatabase(async () => {
|
|
5423
5716
|
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 ? [
|
|
5424
|
-
|
|
5717
|
+
sql33`${taskTable.tags} @> ARRAY[${sql33.join(params.tags.map((t) => sql33`${t}`), sql33`, `)}]::text[]`
|
|
5425
5718
|
] : []));
|
|
5426
5719
|
return result.map((row) => ({
|
|
5427
5720
|
id: row.id,
|
|
@@ -5551,7 +5844,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
|
|
|
5551
5844
|
}
|
|
5552
5845
|
async createMessageServer(data) {
|
|
5553
5846
|
return this.withDatabase(async () => {
|
|
5554
|
-
const newId = data.id ||
|
|
5847
|
+
const newId = data.id || v4();
|
|
5555
5848
|
const now = new Date;
|
|
5556
5849
|
const serverToInsert = {
|
|
5557
5850
|
id: newId,
|
|
@@ -5611,7 +5904,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
|
|
|
5611
5904
|
}
|
|
5612
5905
|
async getMessageServerByRlsServerId(rlsServerId) {
|
|
5613
5906
|
return this.withDatabase(async () => {
|
|
5614
|
-
const results = await this.db.execute(
|
|
5907
|
+
const results = await this.db.execute(sql33`
|
|
5615
5908
|
SELECT id, name, source_type, source_id, metadata, created_at, updated_at
|
|
5616
5909
|
FROM message_servers
|
|
5617
5910
|
WHERE server_id = ${rlsServerId}
|
|
@@ -5631,7 +5924,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
|
|
|
5631
5924
|
}
|
|
5632
5925
|
async createChannel(data, participantIds) {
|
|
5633
5926
|
return this.withDatabase(async () => {
|
|
5634
|
-
const newId = data.id ||
|
|
5927
|
+
const newId = data.id || v4();
|
|
5635
5928
|
const now = new Date;
|
|
5636
5929
|
const channelToInsert = {
|
|
5637
5930
|
id: newId,
|
|
@@ -5694,7 +5987,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
|
|
|
5694
5987
|
}
|
|
5695
5988
|
async createMessage(data) {
|
|
5696
5989
|
return this.withDatabase(async () => {
|
|
5697
|
-
const newId = data.messageId ||
|
|
5990
|
+
const newId = data.messageId || v4();
|
|
5698
5991
|
const now = new Date;
|
|
5699
5992
|
const messageToInsert = {
|
|
5700
5993
|
id: newId,
|
|
@@ -5724,7 +6017,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
|
|
|
5724
6017
|
channelId: row.channelId,
|
|
5725
6018
|
authorId: row.authorId,
|
|
5726
6019
|
content: row.content,
|
|
5727
|
-
rawMessage: row.rawMessage
|
|
6020
|
+
rawMessage: asRawMessage(row.rawMessage),
|
|
5728
6021
|
sourceType: row.sourceType || undefined,
|
|
5729
6022
|
sourceId: row.sourceId || undefined,
|
|
5730
6023
|
metadata: row.metadata || undefined,
|
|
@@ -5769,10 +6062,10 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
|
|
|
5769
6062
|
channelId: r.channelId,
|
|
5770
6063
|
authorId: r.authorId,
|
|
5771
6064
|
content: r.content,
|
|
5772
|
-
rawMessage: r.rawMessage
|
|
6065
|
+
rawMessage: asRawMessage(r.rawMessage),
|
|
5773
6066
|
sourceType: r.sourceType || undefined,
|
|
5774
6067
|
sourceId: r.sourceId || undefined,
|
|
5775
|
-
metadata: r.metadata
|
|
6068
|
+
metadata: asMetadata(r.metadata),
|
|
5776
6069
|
inReplyToRootMessageId: r.inReplyToRootMessageId,
|
|
5777
6070
|
createdAt: r.createdAt,
|
|
5778
6071
|
updatedAt: r.updatedAt
|
|
@@ -5890,24 +6183,33 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
|
|
|
5890
6183
|
}, ids);
|
|
5891
6184
|
});
|
|
5892
6185
|
}
|
|
5893
|
-
async getPairingRequests(
|
|
6186
|
+
async getPairingRequests(queries) {
|
|
5894
6187
|
return this.withDatabase(async () => {
|
|
5895
|
-
|
|
5896
|
-
|
|
5897
|
-
|
|
5898
|
-
|
|
5899
|
-
|
|
5900
|
-
|
|
5901
|
-
|
|
5902
|
-
|
|
5903
|
-
|
|
5904
|
-
|
|
6188
|
+
if (queries.length === 0) {
|
|
6189
|
+
return [];
|
|
6190
|
+
}
|
|
6191
|
+
return Promise.all(queries.map(async ({ channel, agentId }) => {
|
|
6192
|
+
const results = await this.db.select().from(pairingRequestTable).where(and(eq2(pairingRequestTable.channel, channel), eq2(pairingRequestTable.agentId, agentId))).orderBy(pairingRequestTable.createdAt);
|
|
6193
|
+
return {
|
|
6194
|
+
channel,
|
|
6195
|
+
agentId,
|
|
6196
|
+
requests: results.map((row) => ({
|
|
6197
|
+
id: row.id,
|
|
6198
|
+
channel: row.channel,
|
|
6199
|
+
senderId: row.senderId,
|
|
6200
|
+
code: row.code,
|
|
6201
|
+
createdAt: row.createdAt,
|
|
6202
|
+
lastSeenAt: row.lastSeenAt,
|
|
6203
|
+
metadata: row.metadata || undefined,
|
|
6204
|
+
agentId: row.agentId
|
|
6205
|
+
}))
|
|
6206
|
+
};
|
|
5905
6207
|
}));
|
|
5906
6208
|
});
|
|
5907
6209
|
}
|
|
5908
6210
|
async createPairingRequest(request) {
|
|
5909
6211
|
return this.withDatabase(async () => {
|
|
5910
|
-
const id = request.id ||
|
|
6212
|
+
const id = request.id || v4();
|
|
5911
6213
|
await this.db.insert(pairingRequestTable).values({
|
|
5912
6214
|
id,
|
|
5913
6215
|
channel: request.channel,
|
|
@@ -5949,7 +6251,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
|
|
|
5949
6251
|
}
|
|
5950
6252
|
async createPairingAllowlistEntry(entry) {
|
|
5951
6253
|
return this.withDatabase(async () => {
|
|
5952
|
-
const id = entry.id ||
|
|
6254
|
+
const id = entry.id || v4();
|
|
5953
6255
|
await this.db.insert(pairingAllowlistTable).values({
|
|
5954
6256
|
id,
|
|
5955
6257
|
channel: entry.channel,
|
|
@@ -5968,7 +6270,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
|
|
|
5968
6270
|
}
|
|
5969
6271
|
async isReady() {
|
|
5970
6272
|
try {
|
|
5971
|
-
await this.db.execute(
|
|
6273
|
+
await this.db.execute(sql33`SELECT 1`);
|
|
5972
6274
|
return true;
|
|
5973
6275
|
} catch {
|
|
5974
6276
|
return false;
|
|
@@ -6071,8 +6373,12 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
|
|
|
6071
6373
|
async patchComponents(_updates, _options) {}
|
|
6072
6374
|
async upsertEntities(entities) {
|
|
6073
6375
|
for (const entity of entities) {
|
|
6376
|
+
if (!entity.id) {
|
|
6377
|
+
await this.createEntities([entity]);
|
|
6378
|
+
continue;
|
|
6379
|
+
}
|
|
6074
6380
|
const existing = await this.getEntitiesByIds([entity.id]);
|
|
6075
|
-
if (existing
|
|
6381
|
+
if (existing.length > 0) {
|
|
6076
6382
|
await this.updateEntity(entity);
|
|
6077
6383
|
} else {
|
|
6078
6384
|
await this.createEntities([entity]);
|
|
@@ -6089,11 +6395,17 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
|
|
|
6089
6395
|
if (params.agentId) {
|
|
6090
6396
|
conditions.push(eq2(entityTable.agentId, params.agentId));
|
|
6091
6397
|
}
|
|
6092
|
-
if (params.componentType) {
|
|
6093
|
-
const
|
|
6398
|
+
if (params.componentType || params.worldId) {
|
|
6399
|
+
const subConditions = [sql33`${componentTable.entityId} = ${entityTable.id}`];
|
|
6400
|
+
if (params.componentType) {
|
|
6401
|
+
subConditions.push(sql33`${componentTable.type} = ${params.componentType}`);
|
|
6402
|
+
}
|
|
6403
|
+
if (params.worldId) {
|
|
6404
|
+
subConditions.push(sql33`${componentTable.worldId} = ${params.worldId}`);
|
|
6405
|
+
}
|
|
6406
|
+
const subquery = sql33`EXISTS (
|
|
6094
6407
|
SELECT 1 FROM ${componentTable}
|
|
6095
|
-
WHERE ${
|
|
6096
|
-
AND ${componentTable.type} = ${params.componentType}
|
|
6408
|
+
WHERE ${sql33.join(subConditions, sql33` AND `)}
|
|
6097
6409
|
)`;
|
|
6098
6410
|
conditions.push(subquery);
|
|
6099
6411
|
}
|
|
@@ -6105,13 +6417,27 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
|
|
|
6105
6417
|
query = query.offset(params.offset);
|
|
6106
6418
|
}
|
|
6107
6419
|
const result = await query;
|
|
6108
|
-
|
|
6420
|
+
const entities = result.map((row) => ({
|
|
6109
6421
|
...row,
|
|
6110
6422
|
id: row.id,
|
|
6111
6423
|
agentId: row.agentId,
|
|
6112
6424
|
names: row.names || [],
|
|
6113
6425
|
metadata: row.metadata || {}
|
|
6114
6426
|
}));
|
|
6427
|
+
if (params.includeAllComponents && entities.length > 0) {
|
|
6428
|
+
const entityIds = entities.flatMap((entity) => entity.id ? [entity.id] : []);
|
|
6429
|
+
const components = await this.getComponentsForEntities(entityIds, params.worldId);
|
|
6430
|
+
const componentsByEntity = new Map;
|
|
6431
|
+
for (const comp of components) {
|
|
6432
|
+
const list = componentsByEntity.get(comp.entityId) ?? [];
|
|
6433
|
+
list.push(comp);
|
|
6434
|
+
componentsByEntity.set(comp.entityId, list);
|
|
6435
|
+
}
|
|
6436
|
+
for (const entity of entities) {
|
|
6437
|
+
entity.components = entity.id ? componentsByEntity.get(entity.id) ?? [] : [];
|
|
6438
|
+
}
|
|
6439
|
+
}
|
|
6440
|
+
return entities;
|
|
6115
6441
|
});
|
|
6116
6442
|
}
|
|
6117
6443
|
async updateEntities(entities) {
|
|
@@ -6176,8 +6502,8 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
|
|
|
6176
6502
|
}
|
|
6177
6503
|
async createMemories(memories) {
|
|
6178
6504
|
const ids = [];
|
|
6179
|
-
for (const { memory, tableName, unique:
|
|
6180
|
-
const memoryWithUnique =
|
|
6505
|
+
for (const { memory, tableName, unique: unique4 } of memories) {
|
|
6506
|
+
const memoryWithUnique = unique4 !== undefined ? { ...memory, unique: unique4 } : memory;
|
|
6181
6507
|
const id = await this.createMemory(memoryWithUnique, tableName);
|
|
6182
6508
|
ids.push(id);
|
|
6183
6509
|
}
|
|
@@ -6367,7 +6693,7 @@ class BaseDrizzleAdapter extends DatabaseAdapter {
|
|
|
6367
6693
|
async createRelationships(relationships) {
|
|
6368
6694
|
const ids = [];
|
|
6369
6695
|
for (const rel of relationships) {
|
|
6370
|
-
const id =
|
|
6696
|
+
const id = v4();
|
|
6371
6697
|
const success = await this.createRelationship(rel);
|
|
6372
6698
|
if (success)
|
|
6373
6699
|
ids.push(id);
|
|
@@ -6515,7 +6841,8 @@ class PgliteDatabaseAdapter extends BaseDrizzleAdapter {
|
|
|
6515
6841
|
constructor(agentId, manager) {
|
|
6516
6842
|
super(agentId);
|
|
6517
6843
|
this.manager = manager;
|
|
6518
|
-
|
|
6844
|
+
const drizzleAny = drizzle;
|
|
6845
|
+
this.db = drizzleAny(this.manager.getConnection());
|
|
6519
6846
|
}
|
|
6520
6847
|
async withEntityContext(_entityId, callback) {
|
|
6521
6848
|
return this.db.transaction(callback);
|
|
@@ -6550,7 +6877,14 @@ class PgliteDatabaseAdapter extends BaseDrizzleAdapter {
|
|
|
6550
6877
|
async withDatabase(operation) {
|
|
6551
6878
|
if (this.manager.isShuttingDown()) {
|
|
6552
6879
|
const error = new Error("Database is shutting down - operation rejected");
|
|
6553
|
-
logger10.
|
|
6880
|
+
logger10.info({ src: "plugin:sql", error: error.message }, "Database operation rejected during shutdown");
|
|
6881
|
+
throw error;
|
|
6882
|
+
}
|
|
6883
|
+
const managerWithInit = this.manager;
|
|
6884
|
+
await managerWithInit.initialize?.();
|
|
6885
|
+
if (this.manager.isShuttingDown()) {
|
|
6886
|
+
const error = new Error("Database is shutting down - operation rejected");
|
|
6887
|
+
logger10.info({ src: "plugin:sql", error: error.message }, "Database operation rejected during shutdown");
|
|
6554
6888
|
throw error;
|
|
6555
6889
|
}
|
|
6556
6890
|
return operation();
|
|
@@ -6561,7 +6895,8 @@ class PgliteDatabaseAdapter extends BaseDrizzleAdapter {
|
|
|
6561
6895
|
logger10.debug({ src: "plugin:sql" }, "PGliteDatabaseAdapter initialized");
|
|
6562
6896
|
}
|
|
6563
6897
|
async isReady() {
|
|
6564
|
-
|
|
6898
|
+
const managerWithState = this.manager;
|
|
6899
|
+
return !this.manager.isShuttingDown() && managerWithState.isInitialized?.() === true;
|
|
6565
6900
|
}
|
|
6566
6901
|
async close() {
|
|
6567
6902
|
await this.manager.close();
|
|
@@ -6577,12 +6912,60 @@ class PgliteDatabaseAdapter extends BaseDrizzleAdapter {
|
|
|
6577
6912
|
}
|
|
6578
6913
|
|
|
6579
6914
|
// pglite/manager.ts
|
|
6580
|
-
var {existsSync,
|
|
6915
|
+
var {existsSync, readFileSync, unlinkSync} = (() => ({}));
|
|
6581
6916
|
import { PGlite } from "@electric-sql/pglite";
|
|
6582
6917
|
import { fuzzystrmatch } from "@electric-sql/pglite/contrib/fuzzystrmatch";
|
|
6583
6918
|
import { vector as vector2 } from "@electric-sql/pglite/vector";
|
|
6584
6919
|
import { logger as logger11 } from "@elizaos/core";
|
|
6585
6920
|
|
|
6921
|
+
// pglite/errors.ts
|
|
6922
|
+
var PGLITE_ERROR_CODES = {
|
|
6923
|
+
ACTIVE_LOCK: "ELIZA_PGLITE_DATA_DIR_IN_USE",
|
|
6924
|
+
CORRUPT_DATA: "ELIZA_PGLITE_CORRUPT_DATA",
|
|
6925
|
+
MANUAL_RESET_REQUIRED: "ELIZA_PGLITE_MANUAL_RESET_REQUIRED"
|
|
6926
|
+
};
|
|
6927
|
+
|
|
6928
|
+
class PgliteInitError extends Error {
|
|
6929
|
+
code;
|
|
6930
|
+
dataDir;
|
|
6931
|
+
constructor(code, message, options) {
|
|
6932
|
+
super(message, { cause: options?.cause });
|
|
6933
|
+
this.name = "PgliteInitError";
|
|
6934
|
+
this.code = code;
|
|
6935
|
+
this.dataDir = options?.dataDir;
|
|
6936
|
+
}
|
|
6937
|
+
}
|
|
6938
|
+
function createPgliteInitError(code, message, options) {
|
|
6939
|
+
return new PgliteInitError(code, message, options);
|
|
6940
|
+
}
|
|
6941
|
+
function getPgliteErrorCode(err) {
|
|
6942
|
+
const seen = new Set;
|
|
6943
|
+
let current = err;
|
|
6944
|
+
while (current && !seen.has(current)) {
|
|
6945
|
+
seen.add(current);
|
|
6946
|
+
if (typeof current === "object" && current !== null && "code" in current && typeof current.code === "string") {
|
|
6947
|
+
const code = current.code;
|
|
6948
|
+
if (code === PGLITE_ERROR_CODES.ACTIVE_LOCK || code === PGLITE_ERROR_CODES.CORRUPT_DATA || code === PGLITE_ERROR_CODES.MANUAL_RESET_REQUIRED) {
|
|
6949
|
+
return code;
|
|
6950
|
+
}
|
|
6951
|
+
}
|
|
6952
|
+
if (current instanceof Error) {
|
|
6953
|
+
current = current.cause;
|
|
6954
|
+
continue;
|
|
6955
|
+
}
|
|
6956
|
+
if (typeof current === "object" && current !== null && "cause" in current) {
|
|
6957
|
+
current = current.cause;
|
|
6958
|
+
continue;
|
|
6959
|
+
}
|
|
6960
|
+
break;
|
|
6961
|
+
}
|
|
6962
|
+
return null;
|
|
6963
|
+
}
|
|
6964
|
+
function isFatalPgliteErrorCode(code) {
|
|
6965
|
+
return code === PGLITE_ERROR_CODES.ACTIVE_LOCK || code === PGLITE_ERROR_CODES.CORRUPT_DATA || code === PGLITE_ERROR_CODES.MANUAL_RESET_REQUIRED;
|
|
6966
|
+
}
|
|
6967
|
+
|
|
6968
|
+
// pglite/manager.ts
|
|
6586
6969
|
class PGliteClientManager {
|
|
6587
6970
|
client;
|
|
6588
6971
|
options;
|
|
@@ -6600,6 +6983,9 @@ class PGliteClientManager {
|
|
|
6600
6983
|
isShuttingDown() {
|
|
6601
6984
|
return this.shuttingDown;
|
|
6602
6985
|
}
|
|
6986
|
+
isInitialized() {
|
|
6987
|
+
return this.initialized;
|
|
6988
|
+
}
|
|
6603
6989
|
async initialize() {
|
|
6604
6990
|
if (this.initialized) {
|
|
6605
6991
|
return;
|
|
@@ -6653,44 +7039,608 @@ class PGliteClientManager {
|
|
|
6653
7039
|
}
|
|
6654
7040
|
return String(error);
|
|
6655
7041
|
}
|
|
7042
|
+
reconcilePglitePidFile(dataDir) {
|
|
7043
|
+
const pidPath = `${dataDir}/postmaster.pid`;
|
|
7044
|
+
if (!existsSync(pidPath)) {
|
|
7045
|
+
return "missing";
|
|
7046
|
+
}
|
|
7047
|
+
try {
|
|
7048
|
+
const content = readFileSync(pidPath, "utf-8");
|
|
7049
|
+
const firstLine = content.split(`
|
|
7050
|
+
`)[0]?.trim();
|
|
7051
|
+
const pid = parseInt(firstLine, 10);
|
|
7052
|
+
if (Number.isNaN(pid) || pid <= 0) {
|
|
7053
|
+
unlinkSync(pidPath);
|
|
7054
|
+
logger11.info({ src: "plugin:sql", dataDir, pidPath }, "Removed malformed PGlite postmaster.pid");
|
|
7055
|
+
return "cleared-malformed";
|
|
7056
|
+
}
|
|
7057
|
+
try {
|
|
7058
|
+
process.kill(pid, 0);
|
|
7059
|
+
logger11.warn({ src: "plugin:sql", dataDir, pid }, "PGlite data dir is already in use by another process");
|
|
7060
|
+
return "active";
|
|
7061
|
+
} catch (killErr) {
|
|
7062
|
+
const code = killErr.code;
|
|
7063
|
+
if (code === "ESRCH") {
|
|
7064
|
+
unlinkSync(pidPath);
|
|
7065
|
+
logger11.info({ src: "plugin:sql", dataDir, pid }, "Removed stale PGlite postmaster.pid");
|
|
7066
|
+
return "cleared-stale";
|
|
7067
|
+
}
|
|
7068
|
+
logger11.warn({ src: "plugin:sql", dataDir, pid, code }, "Cannot confirm PGlite postmaster.pid ownership");
|
|
7069
|
+
return "active-unconfirmed";
|
|
7070
|
+
}
|
|
7071
|
+
} catch (err) {
|
|
7072
|
+
logger11.warn({
|
|
7073
|
+
src: "plugin:sql",
|
|
7074
|
+
dataDir,
|
|
7075
|
+
error: this.getErrorText(err)
|
|
7076
|
+
}, "Failed to inspect PGlite postmaster.pid");
|
|
7077
|
+
return "check-failed";
|
|
7078
|
+
}
|
|
7079
|
+
}
|
|
7080
|
+
createActiveLockError(dataDir, cause) {
|
|
7081
|
+
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 });
|
|
7082
|
+
}
|
|
7083
|
+
createManualResetRequiredError(dataDir, cause) {
|
|
7084
|
+
const errorText = this.getErrorText(cause);
|
|
7085
|
+
const corruptCause = createPgliteInitError(PGLITE_ERROR_CODES.CORRUPT_DATA, `PGlite data dir at ${dataDir} appears corrupt or unreadable: ${errorText}`, { cause, dataDir });
|
|
7086
|
+
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 });
|
|
7087
|
+
}
|
|
7088
|
+
async queryMigrationsSchema() {
|
|
7089
|
+
await this.client.query("CREATE SCHEMA IF NOT EXISTS migrations");
|
|
7090
|
+
this.initialized = true;
|
|
7091
|
+
}
|
|
6656
7092
|
async initializeInternal() {
|
|
6657
7093
|
try {
|
|
6658
|
-
await this.
|
|
6659
|
-
this.initialized = true;
|
|
7094
|
+
await this.queryMigrationsSchema();
|
|
6660
7095
|
return;
|
|
6661
7096
|
} catch (initialError) {
|
|
6662
7097
|
const dataDir = this.getDataDir();
|
|
6663
7098
|
if (!this.isFileBackedDataDir(dataDir)) {
|
|
6664
7099
|
throw initialError;
|
|
6665
7100
|
}
|
|
6666
|
-
const
|
|
6667
|
-
|
|
6668
|
-
|
|
6669
|
-
src: "plugin:sql",
|
|
6670
|
-
dataDir,
|
|
6671
|
-
backupDir,
|
|
6672
|
-
error: errorText
|
|
6673
|
-
}, "PGlite initialization failed; attempting recovery with a clean data directory");
|
|
6674
|
-
try {
|
|
6675
|
-
await this.client.close();
|
|
6676
|
-
} catch {}
|
|
6677
|
-
if (existsSync(dataDir)) {
|
|
6678
|
-
renameSync(dataDir, backupDir);
|
|
7101
|
+
const pidStatus = this.reconcilePglitePidFile(dataDir);
|
|
7102
|
+
if (pidStatus === "active" || pidStatus === "active-unconfirmed" || pidStatus === "check-failed") {
|
|
7103
|
+
throw this.createActiveLockError(dataDir, initialError);
|
|
6679
7104
|
}
|
|
6680
|
-
|
|
6681
|
-
this.client = this.createClient(this.options);
|
|
6682
|
-
try {
|
|
6683
|
-
await this.client.query("CREATE SCHEMA IF NOT EXISTS migrations");
|
|
6684
|
-
this.initialized = true;
|
|
7105
|
+
if (pidStatus === "cleared-stale" || pidStatus === "cleared-malformed") {
|
|
6685
7106
|
logger11.warn({
|
|
6686
7107
|
src: "plugin:sql",
|
|
6687
7108
|
dataDir,
|
|
6688
|
-
|
|
6689
|
-
}, "
|
|
6690
|
-
|
|
6691
|
-
|
|
7109
|
+
error: this.getErrorText(initialError)
|
|
7110
|
+
}, "Retrying PGlite initialization after clearing postmaster.pid");
|
|
7111
|
+
try {
|
|
7112
|
+
await this.client.close();
|
|
7113
|
+
} catch {}
|
|
7114
|
+
this.client = this.createClient(this.options);
|
|
7115
|
+
try {
|
|
7116
|
+
await this.queryMigrationsSchema();
|
|
7117
|
+
return;
|
|
7118
|
+
} catch (retryError) {
|
|
7119
|
+
logger11.error({
|
|
7120
|
+
src: "plugin:sql",
|
|
7121
|
+
dataDir,
|
|
7122
|
+
error: this.getErrorText(retryError)
|
|
7123
|
+
}, "PGlite initialization still failed after clearing postmaster.pid");
|
|
7124
|
+
throw this.createManualResetRequiredError(dataDir, retryError);
|
|
7125
|
+
}
|
|
7126
|
+
}
|
|
7127
|
+
logger11.error({
|
|
7128
|
+
src: "plugin:sql",
|
|
7129
|
+
dataDir,
|
|
7130
|
+
error: this.getErrorText(initialError)
|
|
7131
|
+
}, "PGlite initialization failed; manual reset required");
|
|
7132
|
+
throw this.createManualResetRequiredError(dataDir, initialError);
|
|
7133
|
+
}
|
|
7134
|
+
}
|
|
7135
|
+
}
|
|
7136
|
+
|
|
7137
|
+
// services/advanced-memory-storage.ts
|
|
7138
|
+
import {
|
|
7139
|
+
ChannelType as ChannelType2,
|
|
7140
|
+
Service
|
|
7141
|
+
} from "@elizaos/core";
|
|
7142
|
+
|
|
7143
|
+
// utils/string-to-uuid.ts
|
|
7144
|
+
var UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
7145
|
+
function hashSegment(input, seed) {
|
|
7146
|
+
let hash = seed >>> 0;
|
|
7147
|
+
for (let index18 = 0;index18 < input.length; index18 += 1) {
|
|
7148
|
+
hash ^= input.charCodeAt(index18);
|
|
7149
|
+
hash = Math.imul(hash, 16777619);
|
|
7150
|
+
}
|
|
7151
|
+
return hash >>> 0;
|
|
7152
|
+
}
|
|
7153
|
+
function stringToUuid(target) {
|
|
7154
|
+
const value = typeof target === "number" ? target.toString() : target;
|
|
7155
|
+
if (typeof value !== "string") {
|
|
7156
|
+
throw new TypeError("Value must be string");
|
|
7157
|
+
}
|
|
7158
|
+
if (UUID_PATTERN.test(value)) {
|
|
7159
|
+
return value;
|
|
7160
|
+
}
|
|
7161
|
+
const input = encodeURIComponent(value);
|
|
7162
|
+
const hex = [
|
|
7163
|
+
hashSegment(input, 2166136261),
|
|
7164
|
+
hashSegment(input, 2654435761),
|
|
7165
|
+
hashSegment(input, 2246822507),
|
|
7166
|
+
hashSegment(input, 3266489909)
|
|
7167
|
+
].map((part) => part.toString(16).padStart(8, "0")).join("").slice(0, 32).split("");
|
|
7168
|
+
hex[12] = "0";
|
|
7169
|
+
hex[16] = (Number.parseInt(hex[16] ?? "0", 16) & 3 | 8).toString(16);
|
|
7170
|
+
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("")}`;
|
|
7171
|
+
}
|
|
7172
|
+
|
|
7173
|
+
// services/advanced-memory-storage.ts
|
|
7174
|
+
var ENTITY_RESOLUTION_SERVICE = "entity_resolution";
|
|
7175
|
+
var LONG_TERM_MEMORY_TABLE = "long_term_memories";
|
|
7176
|
+
var SESSION_SUMMARY_TABLE = "session_summaries";
|
|
7177
|
+
var ADVANCED_MEMORY_SOURCE = "advanced-memory";
|
|
7178
|
+
function isRecord(value) {
|
|
7179
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
7180
|
+
}
|
|
7181
|
+
function asRecord(value) {
|
|
7182
|
+
return isRecord(value) ? value : null;
|
|
7183
|
+
}
|
|
7184
|
+
function toJsonValue(value) {
|
|
7185
|
+
if (value === null)
|
|
7186
|
+
return null;
|
|
7187
|
+
if (typeof value === "string") {
|
|
7188
|
+
return value;
|
|
7189
|
+
}
|
|
7190
|
+
if (typeof value === "number") {
|
|
7191
|
+
return value;
|
|
7192
|
+
}
|
|
7193
|
+
if (typeof value === "boolean") {
|
|
7194
|
+
return value;
|
|
7195
|
+
}
|
|
7196
|
+
if (Array.isArray(value)) {
|
|
7197
|
+
return value.map((entry) => toJsonValue(entry)).filter((entry) => entry !== undefined);
|
|
7198
|
+
}
|
|
7199
|
+
if (isRecord(value)) {
|
|
7200
|
+
const entries = Object.entries(value).map(([key, entry]) => {
|
|
7201
|
+
const jsonValue = toJsonValue(entry);
|
|
7202
|
+
return jsonValue === undefined ? null : [key, jsonValue];
|
|
7203
|
+
}).filter((entry) => entry !== null);
|
|
7204
|
+
return Object.fromEntries(entries);
|
|
7205
|
+
}
|
|
7206
|
+
return;
|
|
7207
|
+
}
|
|
7208
|
+
function toJsonRecord(value) {
|
|
7209
|
+
const jsonValue = toJsonValue(value);
|
|
7210
|
+
return isRecord(jsonValue) ? jsonValue : undefined;
|
|
7211
|
+
}
|
|
7212
|
+
function buildCustomMemoryMetadata(params) {
|
|
7213
|
+
const metadata = {
|
|
7214
|
+
...params.existing ?? {},
|
|
7215
|
+
type: "custom",
|
|
7216
|
+
scope: params.scope,
|
|
7217
|
+
timestamp: params.timestamp,
|
|
7218
|
+
advancedMemory: params.advancedMemory
|
|
7219
|
+
};
|
|
7220
|
+
if (params.source) {
|
|
7221
|
+
metadata.source = params.source;
|
|
7222
|
+
}
|
|
7223
|
+
return metadata;
|
|
7224
|
+
}
|
|
7225
|
+
function asString(value) {
|
|
7226
|
+
return typeof value === "string" && value.trim().length > 0 ? value.trim() : undefined;
|
|
7227
|
+
}
|
|
7228
|
+
function asNumber(value) {
|
|
7229
|
+
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
|
7230
|
+
}
|
|
7231
|
+
function asStringArray(value) {
|
|
7232
|
+
if (!Array.isArray(value))
|
|
7233
|
+
return;
|
|
7234
|
+
const values = value.filter((entry) => typeof entry === "string");
|
|
7235
|
+
return values.length > 0 ? values : undefined;
|
|
7236
|
+
}
|
|
7237
|
+
function toDate(value, fallback) {
|
|
7238
|
+
if (value instanceof Date && Number.isFinite(value.getTime())) {
|
|
7239
|
+
return value;
|
|
7240
|
+
}
|
|
7241
|
+
if (typeof value === "number" && Number.isFinite(value)) {
|
|
7242
|
+
const parsed = new Date(value);
|
|
7243
|
+
if (Number.isFinite(parsed.getTime()))
|
|
7244
|
+
return parsed;
|
|
7245
|
+
}
|
|
7246
|
+
if (typeof value === "string" && value.trim().length > 0) {
|
|
7247
|
+
const parsed = new Date(value);
|
|
7248
|
+
if (Number.isFinite(parsed.getTime()))
|
|
7249
|
+
return parsed;
|
|
7250
|
+
}
|
|
7251
|
+
return fallback ?? new Date;
|
|
7252
|
+
}
|
|
7253
|
+
function getMemoryText(memory) {
|
|
7254
|
+
return typeof memory.content?.text === "string" ? memory.content.text : "";
|
|
7255
|
+
}
|
|
7256
|
+
function getAdvancedMemoryEnvelope(memory) {
|
|
7257
|
+
const metadata = asRecord(memory.metadata);
|
|
7258
|
+
const advancedMemory = asRecord(metadata?.advancedMemory);
|
|
7259
|
+
if (!advancedMemory) {
|
|
7260
|
+
return null;
|
|
7261
|
+
}
|
|
7262
|
+
const kind = asString(advancedMemory.kind);
|
|
7263
|
+
if (kind !== "long_term_memory" && kind !== "session_summary") {
|
|
7264
|
+
return null;
|
|
7265
|
+
}
|
|
7266
|
+
return {
|
|
7267
|
+
kind,
|
|
7268
|
+
originalEntityId: asString(advancedMemory.originalEntityId),
|
|
7269
|
+
anchorEntityId: asString(advancedMemory.anchorEntityId),
|
|
7270
|
+
category: asString(advancedMemory.category),
|
|
7271
|
+
confidence: asNumber(advancedMemory.confidence),
|
|
7272
|
+
source: asString(advancedMemory.source),
|
|
7273
|
+
semanticMetadata: toJsonRecord(advancedMemory.semanticMetadata),
|
|
7274
|
+
messageCount: asNumber(advancedMemory.messageCount),
|
|
7275
|
+
lastMessageOffset: asNumber(advancedMemory.lastMessageOffset),
|
|
7276
|
+
startTime: asString(advancedMemory.startTime),
|
|
7277
|
+
endTime: asString(advancedMemory.endTime),
|
|
7278
|
+
topics: asStringArray(advancedMemory.topics),
|
|
7279
|
+
summaryMetadata: toJsonRecord(advancedMemory.summaryMetadata),
|
|
7280
|
+
updatedAt: asString(advancedMemory.updatedAt),
|
|
7281
|
+
lastAccessedAt: asString(advancedMemory.lastAccessedAt),
|
|
7282
|
+
accessCount: asNumber(advancedMemory.accessCount)
|
|
7283
|
+
};
|
|
7284
|
+
}
|
|
7285
|
+
|
|
7286
|
+
class AdvancedMemoryStorageService extends Service {
|
|
7287
|
+
static serviceType = "memoryStorage";
|
|
7288
|
+
capabilityDescription = "Persistent advanced-memory storage backed by SQL memory tables";
|
|
7289
|
+
static async start(runtime) {
|
|
7290
|
+
const service = new AdvancedMemoryStorageService;
|
|
7291
|
+
await service.initialize(runtime);
|
|
7292
|
+
return service;
|
|
7293
|
+
}
|
|
7294
|
+
async initialize(runtime) {
|
|
7295
|
+
this.runtime = runtime;
|
|
7296
|
+
}
|
|
7297
|
+
async stop() {}
|
|
7298
|
+
getMemoryWorldId() {
|
|
7299
|
+
return stringToUuid(`advanced-memory:world:${this.runtime.agentId}`);
|
|
7300
|
+
}
|
|
7301
|
+
getLongTermRoomId(entityId) {
|
|
7302
|
+
return stringToUuid(`advanced-memory:long-term:${this.runtime.agentId}:${entityId}`);
|
|
7303
|
+
}
|
|
7304
|
+
async ensureMemoryWorld() {
|
|
7305
|
+
const worldId = this.getMemoryWorldId();
|
|
7306
|
+
const world = {
|
|
7307
|
+
id: worldId,
|
|
7308
|
+
agentId: this.runtime.agentId,
|
|
7309
|
+
name: "Advanced Memory",
|
|
7310
|
+
metadata: {
|
|
7311
|
+
purpose: ADVANCED_MEMORY_SOURCE
|
|
7312
|
+
},
|
|
7313
|
+
createdAt: new Date
|
|
7314
|
+
};
|
|
7315
|
+
await this.runtime.ensureWorldExists(world);
|
|
7316
|
+
return worldId;
|
|
7317
|
+
}
|
|
7318
|
+
async ensureLongTermRoom(entityId, worldId) {
|
|
7319
|
+
const roomId = this.getLongTermRoomId(entityId);
|
|
7320
|
+
const room = {
|
|
7321
|
+
id: roomId,
|
|
7322
|
+
agentId: this.runtime.agentId,
|
|
7323
|
+
worldId,
|
|
7324
|
+
source: ADVANCED_MEMORY_SOURCE,
|
|
7325
|
+
type: ChannelType2.SELF,
|
|
7326
|
+
name: `Advanced Memory ${entityId.slice(0, 8)}`,
|
|
7327
|
+
metadata: {
|
|
7328
|
+
purpose: "long_term_memory",
|
|
7329
|
+
entityId
|
|
7330
|
+
},
|
|
7331
|
+
createdAt: new Date
|
|
7332
|
+
};
|
|
7333
|
+
await this.runtime.ensureRoomExists(room);
|
|
7334
|
+
return roomId;
|
|
7335
|
+
}
|
|
7336
|
+
async getEntityResolutionService() {
|
|
7337
|
+
const existing = this.runtime.getService(ENTITY_RESOLUTION_SERVICE);
|
|
7338
|
+
if (existing) {
|
|
7339
|
+
return existing;
|
|
7340
|
+
}
|
|
7341
|
+
if (!this.runtime.hasService(ENTITY_RESOLUTION_SERVICE)) {
|
|
7342
|
+
return null;
|
|
7343
|
+
}
|
|
7344
|
+
try {
|
|
7345
|
+
return await this.runtime.getServiceLoadPromise(ENTITY_RESOLUTION_SERVICE);
|
|
7346
|
+
} catch {
|
|
7347
|
+
return null;
|
|
7348
|
+
}
|
|
7349
|
+
}
|
|
7350
|
+
async getIdentityGroup(entityId) {
|
|
7351
|
+
const resolution = await this.getEntityResolutionService();
|
|
7352
|
+
if (!resolution) {
|
|
7353
|
+
return new Set([entityId]);
|
|
7354
|
+
}
|
|
7355
|
+
const group = new Set([entityId]);
|
|
7356
|
+
const queue = [entityId];
|
|
7357
|
+
while (queue.length > 0) {
|
|
7358
|
+
const current = queue.shift();
|
|
7359
|
+
const links = await resolution.getConfirmedLinks(current);
|
|
7360
|
+
for (const link of links) {
|
|
7361
|
+
const other = link.entityA === current ? link.entityB : link.entityA;
|
|
7362
|
+
if (!group.has(other)) {
|
|
7363
|
+
group.add(other);
|
|
7364
|
+
queue.push(other);
|
|
7365
|
+
}
|
|
7366
|
+
}
|
|
7367
|
+
}
|
|
7368
|
+
return group;
|
|
7369
|
+
}
|
|
7370
|
+
async getAnchorEntityId(entityId) {
|
|
7371
|
+
const group = await this.getIdentityGroup(entityId);
|
|
7372
|
+
return Array.from(group).sort()[0];
|
|
7373
|
+
}
|
|
7374
|
+
parseLongTermMemory(memory) {
|
|
7375
|
+
const envelope = getAdvancedMemoryEnvelope(memory);
|
|
7376
|
+
if (!envelope || envelope.kind !== "long_term_memory" || !memory.id || !memory.agentId) {
|
|
7377
|
+
return null;
|
|
7378
|
+
}
|
|
7379
|
+
return {
|
|
7380
|
+
id: memory.id,
|
|
7381
|
+
agentId: memory.agentId,
|
|
7382
|
+
entityId: envelope.originalEntityId ?? envelope.anchorEntityId ?? memory.entityId,
|
|
7383
|
+
category: envelope.category ?? "semantic",
|
|
7384
|
+
content: getMemoryText(memory),
|
|
7385
|
+
metadata: envelope.semanticMetadata,
|
|
7386
|
+
embedding: Array.isArray(memory.embedding) ? memory.embedding : undefined,
|
|
7387
|
+
confidence: envelope.confidence,
|
|
7388
|
+
source: envelope.source,
|
|
7389
|
+
createdAt: toDate(memory.createdAt),
|
|
7390
|
+
updatedAt: toDate(envelope.updatedAt, toDate(memory.createdAt)),
|
|
7391
|
+
lastAccessedAt: envelope.lastAccessedAt ? toDate(envelope.lastAccessedAt) : undefined,
|
|
7392
|
+
accessCount: envelope.accessCount ?? 0
|
|
7393
|
+
};
|
|
7394
|
+
}
|
|
7395
|
+
parseSessionSummary(memory) {
|
|
7396
|
+
const envelope = getAdvancedMemoryEnvelope(memory);
|
|
7397
|
+
if (!envelope || envelope.kind !== "session_summary" || !memory.id || !memory.agentId || !memory.roomId) {
|
|
7398
|
+
return null;
|
|
7399
|
+
}
|
|
7400
|
+
return {
|
|
7401
|
+
id: memory.id,
|
|
7402
|
+
agentId: memory.agentId,
|
|
7403
|
+
roomId: memory.roomId,
|
|
7404
|
+
entityId: envelope.originalEntityId ?? memory.entityId,
|
|
7405
|
+
summary: getMemoryText(memory),
|
|
7406
|
+
messageCount: envelope.messageCount ?? 0,
|
|
7407
|
+
lastMessageOffset: envelope.lastMessageOffset ?? 0,
|
|
7408
|
+
startTime: toDate(envelope.startTime, toDate(memory.createdAt)),
|
|
7409
|
+
endTime: toDate(envelope.endTime, toDate(memory.createdAt)),
|
|
7410
|
+
topics: envelope.topics,
|
|
7411
|
+
metadata: envelope.summaryMetadata,
|
|
7412
|
+
embedding: Array.isArray(memory.embedding) ? memory.embedding : undefined,
|
|
7413
|
+
createdAt: toDate(memory.createdAt),
|
|
7414
|
+
updatedAt: toDate(envelope.updatedAt, toDate(memory.createdAt))
|
|
7415
|
+
};
|
|
7416
|
+
}
|
|
7417
|
+
sortLongTermMemories(memories) {
|
|
7418
|
+
return [...memories].sort((left, right) => {
|
|
7419
|
+
const leftUpdated = left.updatedAt.getTime();
|
|
7420
|
+
const rightUpdated = right.updatedAt.getTime();
|
|
7421
|
+
if (rightUpdated !== leftUpdated) {
|
|
7422
|
+
return rightUpdated - leftUpdated;
|
|
6692
7423
|
}
|
|
7424
|
+
const leftConfidence = left.confidence ?? 0;
|
|
7425
|
+
const rightConfidence = right.confidence ?? 0;
|
|
7426
|
+
if (rightConfidence !== leftConfidence) {
|
|
7427
|
+
return rightConfidence - leftConfidence;
|
|
7428
|
+
}
|
|
7429
|
+
return right.createdAt.getTime() - left.createdAt.getTime();
|
|
7430
|
+
});
|
|
7431
|
+
}
|
|
7432
|
+
sortSessionSummaries(summaries) {
|
|
7433
|
+
return [...summaries].sort((left, right) => {
|
|
7434
|
+
const leftUpdated = left.updatedAt.getTime();
|
|
7435
|
+
const rightUpdated = right.updatedAt.getTime();
|
|
7436
|
+
if (rightUpdated !== leftUpdated) {
|
|
7437
|
+
return rightUpdated - leftUpdated;
|
|
7438
|
+
}
|
|
7439
|
+
return right.createdAt.getTime() - left.createdAt.getTime();
|
|
7440
|
+
});
|
|
7441
|
+
}
|
|
7442
|
+
async storeLongTermMemory(memory) {
|
|
7443
|
+
const now = new Date;
|
|
7444
|
+
const anchorEntityId = await this.getAnchorEntityId(memory.entityId);
|
|
7445
|
+
const worldId = await this.ensureMemoryWorld();
|
|
7446
|
+
const roomId = await this.ensureLongTermRoom(anchorEntityId, worldId);
|
|
7447
|
+
const advancedMemory = toJsonRecord({
|
|
7448
|
+
kind: "long_term_memory",
|
|
7449
|
+
originalEntityId: memory.entityId,
|
|
7450
|
+
anchorEntityId,
|
|
7451
|
+
category: memory.category,
|
|
7452
|
+
confidence: memory.confidence,
|
|
7453
|
+
source: memory.source,
|
|
7454
|
+
semanticMetadata: memory.metadata,
|
|
7455
|
+
updatedAt: now.toISOString(),
|
|
7456
|
+
accessCount: 0
|
|
7457
|
+
});
|
|
7458
|
+
if (!advancedMemory) {
|
|
7459
|
+
throw new Error("Long-term memory metadata is not JSON-serializable");
|
|
7460
|
+
}
|
|
7461
|
+
const id = await this.runtime.createMemory({
|
|
7462
|
+
agentId: this.runtime.agentId,
|
|
7463
|
+
entityId: anchorEntityId,
|
|
7464
|
+
roomId,
|
|
7465
|
+
worldId,
|
|
7466
|
+
content: { text: memory.content },
|
|
7467
|
+
metadata: buildCustomMemoryMetadata({
|
|
7468
|
+
scope: "shared",
|
|
7469
|
+
timestamp: now.getTime(),
|
|
7470
|
+
source: memory.source,
|
|
7471
|
+
advancedMemory
|
|
7472
|
+
}),
|
|
7473
|
+
embedding: memory.embedding,
|
|
7474
|
+
createdAt: now.getTime(),
|
|
7475
|
+
unique: false
|
|
7476
|
+
}, LONG_TERM_MEMORY_TABLE, false);
|
|
7477
|
+
const stored = await this.runtime.getMemoryById(id);
|
|
7478
|
+
const parsed = stored ? this.parseLongTermMemory(stored) : null;
|
|
7479
|
+
if (!parsed) {
|
|
7480
|
+
throw new Error("Failed to persist long-term memory");
|
|
7481
|
+
}
|
|
7482
|
+
return parsed;
|
|
7483
|
+
}
|
|
7484
|
+
async getLongTermMemories(agentId, entityId, opts) {
|
|
7485
|
+
const group = await this.getIdentityGroup(entityId);
|
|
7486
|
+
const roomIds = Array.from(group).map((memberEntityId) => this.getLongTermRoomId(memberEntityId));
|
|
7487
|
+
if (roomIds.length === 0) {
|
|
7488
|
+
return [];
|
|
7489
|
+
}
|
|
7490
|
+
const memories = await this.runtime.getMemoriesByRoomIds({
|
|
7491
|
+
tableName: LONG_TERM_MEMORY_TABLE,
|
|
7492
|
+
roomIds,
|
|
7493
|
+
limit: Math.max((opts?.limit ?? 20) * roomIds.length * 4, 80)
|
|
7494
|
+
});
|
|
7495
|
+
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);
|
|
7496
|
+
return this.sortLongTermMemories(filtered).slice(0, opts?.limit ?? 20);
|
|
7497
|
+
}
|
|
7498
|
+
async updateLongTermMemory(id, agentId, entityId, updates) {
|
|
7499
|
+
const existing = await this.runtime.getMemoryById(id);
|
|
7500
|
+
const parsed = existing ? this.parseLongTermMemory(existing) : null;
|
|
7501
|
+
if (!existing || !parsed || existing.agentId !== agentId) {
|
|
7502
|
+
throw new Error(`Long-term memory ${id} not found`);
|
|
7503
|
+
}
|
|
7504
|
+
const allowedGroup = await this.getIdentityGroup(entityId);
|
|
7505
|
+
if (!allowedGroup.has(parsed.entityId)) {
|
|
7506
|
+
throw new Error(`Long-term memory ${id} does not belong to entity ${entityId}`);
|
|
7507
|
+
}
|
|
7508
|
+
const currentEnvelope = getAdvancedMemoryEnvelope(existing);
|
|
7509
|
+
const updatedAt = new Date;
|
|
7510
|
+
const advancedMemory = toJsonRecord({
|
|
7511
|
+
...currentEnvelope ?? {},
|
|
7512
|
+
kind: "long_term_memory",
|
|
7513
|
+
originalEntityId: currentEnvelope?.originalEntityId ?? entityId,
|
|
7514
|
+
anchorEntityId: parsed.entityId,
|
|
7515
|
+
category: updates.category ?? parsed.category,
|
|
7516
|
+
confidence: updates.confidence ?? parsed.confidence,
|
|
7517
|
+
source: updates.source ?? parsed.source,
|
|
7518
|
+
semanticMetadata: updates.metadata ?? parsed.metadata,
|
|
7519
|
+
updatedAt: updatedAt.toISOString(),
|
|
7520
|
+
lastAccessedAt: updates.lastAccessedAt?.toISOString(),
|
|
7521
|
+
accessCount: updates.accessCount ?? parsed.accessCount ?? 0
|
|
7522
|
+
});
|
|
7523
|
+
if (!advancedMemory) {
|
|
7524
|
+
throw new Error("Updated long-term memory metadata is not JSON-serializable");
|
|
6693
7525
|
}
|
|
7526
|
+
await this.runtime.updateMemory({
|
|
7527
|
+
id,
|
|
7528
|
+
content: {
|
|
7529
|
+
text: updates.content ?? parsed.content
|
|
7530
|
+
},
|
|
7531
|
+
metadata: buildCustomMemoryMetadata({
|
|
7532
|
+
existing: asRecord(existing.metadata),
|
|
7533
|
+
scope: "shared",
|
|
7534
|
+
timestamp: updatedAt.getTime(),
|
|
7535
|
+
source: updates.source ?? parsed.source,
|
|
7536
|
+
advancedMemory
|
|
7537
|
+
}),
|
|
7538
|
+
...updates.embedding ? { embedding: updates.embedding } : {}
|
|
7539
|
+
});
|
|
7540
|
+
}
|
|
7541
|
+
async deleteLongTermMemory(id, agentId, entityId) {
|
|
7542
|
+
const existing = await this.runtime.getMemoryById(id);
|
|
7543
|
+
const parsed = existing ? this.parseLongTermMemory(existing) : null;
|
|
7544
|
+
if (!existing || !parsed || existing.agentId !== agentId) {
|
|
7545
|
+
throw new Error(`Long-term memory ${id} not found`);
|
|
7546
|
+
}
|
|
7547
|
+
const allowedGroup = await this.getIdentityGroup(entityId);
|
|
7548
|
+
if (!allowedGroup.has(parsed.entityId)) {
|
|
7549
|
+
throw new Error(`Long-term memory ${id} does not belong to entity ${entityId}`);
|
|
7550
|
+
}
|
|
7551
|
+
await this.runtime.deleteMemory(id);
|
|
7552
|
+
}
|
|
7553
|
+
async storeSessionSummary(summary) {
|
|
7554
|
+
const now = new Date;
|
|
7555
|
+
const advancedMemory = toJsonRecord({
|
|
7556
|
+
kind: "session_summary",
|
|
7557
|
+
originalEntityId: summary.entityId,
|
|
7558
|
+
messageCount: summary.messageCount,
|
|
7559
|
+
lastMessageOffset: summary.lastMessageOffset,
|
|
7560
|
+
startTime: summary.startTime.toISOString(),
|
|
7561
|
+
endTime: summary.endTime.toISOString(),
|
|
7562
|
+
topics: summary.topics,
|
|
7563
|
+
summaryMetadata: summary.metadata,
|
|
7564
|
+
updatedAt: now.toISOString()
|
|
7565
|
+
});
|
|
7566
|
+
if (!advancedMemory) {
|
|
7567
|
+
throw new Error("Session summary metadata is not JSON-serializable");
|
|
7568
|
+
}
|
|
7569
|
+
const id = await this.runtime.createMemory({
|
|
7570
|
+
agentId: this.runtime.agentId,
|
|
7571
|
+
entityId: summary.entityId ?? this.runtime.agentId,
|
|
7572
|
+
roomId: summary.roomId,
|
|
7573
|
+
worldId: this.getMemoryWorldId(),
|
|
7574
|
+
content: { text: summary.summary },
|
|
7575
|
+
metadata: buildCustomMemoryMetadata({
|
|
7576
|
+
scope: "room",
|
|
7577
|
+
timestamp: now.getTime(),
|
|
7578
|
+
advancedMemory
|
|
7579
|
+
}),
|
|
7580
|
+
embedding: summary.embedding,
|
|
7581
|
+
createdAt: now.getTime(),
|
|
7582
|
+
unique: false
|
|
7583
|
+
}, SESSION_SUMMARY_TABLE, false);
|
|
7584
|
+
const stored = await this.runtime.getMemoryById(id);
|
|
7585
|
+
const parsed = stored ? this.parseSessionSummary(stored) : null;
|
|
7586
|
+
if (!parsed) {
|
|
7587
|
+
throw new Error("Failed to persist session summary");
|
|
7588
|
+
}
|
|
7589
|
+
return parsed;
|
|
7590
|
+
}
|
|
7591
|
+
async getCurrentSessionSummary(agentId, roomId) {
|
|
7592
|
+
const summaries = await this.getSessionSummaries(agentId, roomId, 1);
|
|
7593
|
+
return summaries[0] ?? null;
|
|
7594
|
+
}
|
|
7595
|
+
async updateSessionSummary(id, agentId, roomId, updates) {
|
|
7596
|
+
const existing = await this.runtime.getMemoryById(id);
|
|
7597
|
+
const parsed = existing ? this.parseSessionSummary(existing) : null;
|
|
7598
|
+
if (!existing || !parsed || existing.agentId !== agentId || existing.roomId !== roomId) {
|
|
7599
|
+
throw new Error(`Session summary ${id} not found`);
|
|
7600
|
+
}
|
|
7601
|
+
const currentEnvelope = getAdvancedMemoryEnvelope(existing);
|
|
7602
|
+
const updatedAt = new Date;
|
|
7603
|
+
const advancedMemory = toJsonRecord({
|
|
7604
|
+
...currentEnvelope ?? {},
|
|
7605
|
+
kind: "session_summary",
|
|
7606
|
+
originalEntityId: currentEnvelope?.originalEntityId ?? parsed.entityId,
|
|
7607
|
+
messageCount: updates.messageCount ?? parsed.messageCount,
|
|
7608
|
+
lastMessageOffset: updates.lastMessageOffset ?? parsed.lastMessageOffset,
|
|
7609
|
+
startTime: (updates.startTime ?? parsed.startTime).toISOString(),
|
|
7610
|
+
endTime: (updates.endTime ?? parsed.endTime).toISOString(),
|
|
7611
|
+
topics: updates.topics ?? parsed.topics,
|
|
7612
|
+
summaryMetadata: updates.metadata ?? parsed.metadata,
|
|
7613
|
+
updatedAt: updatedAt.toISOString()
|
|
7614
|
+
});
|
|
7615
|
+
if (!advancedMemory) {
|
|
7616
|
+
throw new Error("Updated session summary metadata is not JSON-serializable");
|
|
7617
|
+
}
|
|
7618
|
+
await this.runtime.updateMemory({
|
|
7619
|
+
id,
|
|
7620
|
+
content: {
|
|
7621
|
+
text: updates.summary ?? parsed.summary
|
|
7622
|
+
},
|
|
7623
|
+
metadata: buildCustomMemoryMetadata({
|
|
7624
|
+
existing: asRecord(existing.metadata),
|
|
7625
|
+
scope: "room",
|
|
7626
|
+
timestamp: updatedAt.getTime(),
|
|
7627
|
+
advancedMemory
|
|
7628
|
+
}),
|
|
7629
|
+
...updates.embedding ? { embedding: updates.embedding } : {}
|
|
7630
|
+
});
|
|
7631
|
+
}
|
|
7632
|
+
async getSessionSummaries(agentId, roomId, limit = 5) {
|
|
7633
|
+
if (limit <= 0) {
|
|
7634
|
+
return [];
|
|
7635
|
+
}
|
|
7636
|
+
const memories = await this.runtime.getMemories({
|
|
7637
|
+
agentId,
|
|
7638
|
+
roomId,
|
|
7639
|
+
tableName: SESSION_SUMMARY_TABLE,
|
|
7640
|
+
count: Math.max(limit * 4, 20),
|
|
7641
|
+
unique: false
|
|
7642
|
+
});
|
|
7643
|
+
return this.sortSessionSummaries(memories.map((memory) => this.parseSessionSummary(memory)).filter((memory) => memory !== null)).slice(0, limit);
|
|
6694
7644
|
}
|
|
6695
7645
|
}
|
|
6696
7646
|
|
|
@@ -6713,7 +7663,9 @@ var plugin = {
|
|
|
6713
7663
|
description: "A plugin for SQL database access (PGlite WASM in browser).",
|
|
6714
7664
|
priority: 0,
|
|
6715
7665
|
schema: exports_schema,
|
|
7666
|
+
services: [AdvancedMemoryStorageService],
|
|
6716
7667
|
init: async (_config, runtime) => {
|
|
7668
|
+
const runtimeWithAdapter = runtime;
|
|
6717
7669
|
logger12.info({ src: "plugin:sql" }, "plugin-sql (browser) init starting");
|
|
6718
7670
|
try {
|
|
6719
7671
|
const isReady = await runtime.isReady();
|
|
@@ -6723,17 +7675,58 @@ var plugin = {
|
|
|
6723
7675
|
}
|
|
6724
7676
|
} catch (_error) {}
|
|
6725
7677
|
const dbAdapter = createDatabaseAdapter({}, runtime.agentId);
|
|
6726
|
-
|
|
7678
|
+
runtimeWithAdapter.registerDatabaseAdapter(dbAdapter);
|
|
7679
|
+
await dbAdapter.initialize();
|
|
6727
7680
|
logger12.info({ src: "plugin:sql" }, "Browser database adapter (PGlite) created and registered");
|
|
6728
7681
|
}
|
|
6729
7682
|
};
|
|
6730
7683
|
var index_browser_default = plugin;
|
|
6731
7684
|
export {
|
|
7685
|
+
worldTable,
|
|
7686
|
+
taskTable,
|
|
7687
|
+
sessionSummaries,
|
|
7688
|
+
serverTable,
|
|
7689
|
+
roomTable,
|
|
7690
|
+
relationshipTable,
|
|
6732
7691
|
plugin,
|
|
7692
|
+
participantTable,
|
|
7693
|
+
pairingRequestTable,
|
|
7694
|
+
pairingAllowlistTable,
|
|
7695
|
+
messageTable,
|
|
7696
|
+
messageServerTable,
|
|
7697
|
+
messageServerAgentsTable,
|
|
7698
|
+
memoryTable,
|
|
7699
|
+
memoryAccessLogs,
|
|
7700
|
+
longTermMemories,
|
|
7701
|
+
logTable,
|
|
7702
|
+
isFatalPgliteErrorCode,
|
|
7703
|
+
getPgliteErrorCode,
|
|
7704
|
+
factCandidateTable,
|
|
7705
|
+
entityTable,
|
|
7706
|
+
entityMergeCandidateTable,
|
|
7707
|
+
entityIdentityTable,
|
|
7708
|
+
embeddingTable,
|
|
6733
7709
|
index_browser_default as default,
|
|
7710
|
+
createPgliteInitError,
|
|
6734
7711
|
createDatabaseAdapter,
|
|
6735
|
-
|
|
7712
|
+
componentTable,
|
|
7713
|
+
channelTable,
|
|
7714
|
+
channelParticipantsTable,
|
|
7715
|
+
cacheTable,
|
|
7716
|
+
authSessionTable,
|
|
7717
|
+
authOwnerLoginTokenTable,
|
|
7718
|
+
authOwnerBindingTable,
|
|
7719
|
+
authIdentityTable,
|
|
7720
|
+
authIdentityCreatedAtDefault,
|
|
7721
|
+
authBootstrapJtiSeenTable,
|
|
7722
|
+
authAuditEventTable,
|
|
7723
|
+
approvalRequestTable,
|
|
7724
|
+
agentTable,
|
|
7725
|
+
PgliteInitError,
|
|
7726
|
+
PGLITE_ERROR_CODES,
|
|
7727
|
+
DatabaseMigrationService,
|
|
7728
|
+
AdvancedMemoryStorageService
|
|
6736
7729
|
};
|
|
6737
7730
|
|
|
6738
|
-
//# debugId=
|
|
7731
|
+
//# debugId=AE7EA444AC00D2E764756E2164756E21
|
|
6739
7732
|
//# sourceMappingURL=index.browser.js.map
|