@elizaos/plugin-sql 1.0.0-alpha.2 → 1.0.0-alpha.21
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/README.md +4 -20
- package/dist/chunk-2FOOMI3E.js +372 -0
- package/dist/chunk-2FOOMI3E.js.map +1 -0
- package/dist/index.js +241 -485
- package/dist/index.js.map +1 -1
- package/dist/migrate.js +53 -0
- package/dist/migrate.js.map +1 -0
- package/package.json +9 -7
- package/dist/index.d.ts +0 -9
package/dist/index.js
CHANGED
|
@@ -1,6 +1,13 @@
|
|
|
1
|
+
import {
|
|
2
|
+
PGliteClientManager,
|
|
3
|
+
PostgresConnectionManager,
|
|
4
|
+
__name
|
|
5
|
+
} from "./chunk-2FOOMI3E.js";
|
|
6
|
+
|
|
1
7
|
// src/index.ts
|
|
8
|
+
import * as os from "node:os";
|
|
2
9
|
import {
|
|
3
|
-
logger as
|
|
10
|
+
logger as logger4
|
|
4
11
|
} from "@elizaos/core";
|
|
5
12
|
|
|
6
13
|
// src/pg-lite/adapter.ts
|
|
@@ -22,20 +29,44 @@ import {
|
|
|
22
29
|
inArray,
|
|
23
30
|
lte,
|
|
24
31
|
or,
|
|
25
|
-
sql as
|
|
32
|
+
sql as sql12
|
|
26
33
|
} from "drizzle-orm";
|
|
27
34
|
import { v4 } from "uuid";
|
|
28
35
|
|
|
29
36
|
// src/schema/embedding.ts
|
|
37
|
+
import { sql as sql6 } from "drizzle-orm";
|
|
30
38
|
import {
|
|
39
|
+
check as check2,
|
|
40
|
+
foreignKey as foreignKey2,
|
|
41
|
+
index as index2,
|
|
31
42
|
pgTable as pgTable6,
|
|
32
43
|
uuid as uuid6,
|
|
33
|
-
vector as vector2
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
44
|
+
vector as vector2
|
|
45
|
+
} from "drizzle-orm/pg-core";
|
|
46
|
+
|
|
47
|
+
// src/schema/memory.ts
|
|
48
|
+
import { relations, sql as sql5 } from "drizzle-orm";
|
|
49
|
+
import {
|
|
50
|
+
boolean as boolean2,
|
|
51
|
+
check,
|
|
52
|
+
foreignKey,
|
|
53
|
+
index,
|
|
54
|
+
jsonb as jsonb5,
|
|
55
|
+
pgTable as pgTable5,
|
|
56
|
+
text as text5,
|
|
57
|
+
uuid as uuid5
|
|
58
|
+
} from "drizzle-orm/pg-core";
|
|
59
|
+
|
|
60
|
+
// src/schema/agent.ts
|
|
61
|
+
import { sql } from "drizzle-orm";
|
|
62
|
+
import {
|
|
63
|
+
boolean,
|
|
64
|
+
jsonb,
|
|
65
|
+
pgTable,
|
|
66
|
+
text,
|
|
67
|
+
unique,
|
|
68
|
+
uuid
|
|
37
69
|
} from "drizzle-orm/pg-core";
|
|
38
|
-
import { sql as sql6 } from "drizzle-orm";
|
|
39
70
|
|
|
40
71
|
// src/schema/types.ts
|
|
41
72
|
import { customType } from "drizzle-orm/pg-core";
|
|
@@ -64,33 +95,7 @@ var numberTimestamp = customType(
|
|
|
64
95
|
}
|
|
65
96
|
);
|
|
66
97
|
|
|
67
|
-
// src/schema/memory.ts
|
|
68
|
-
import {
|
|
69
|
-
pgTable as pgTable5,
|
|
70
|
-
uuid as uuid5,
|
|
71
|
-
text as text5,
|
|
72
|
-
jsonb as jsonb5,
|
|
73
|
-
index,
|
|
74
|
-
boolean as boolean2,
|
|
75
|
-
foreignKey,
|
|
76
|
-
check
|
|
77
|
-
} from "drizzle-orm/pg-core";
|
|
78
|
-
import { relations, sql as sql5 } from "drizzle-orm";
|
|
79
|
-
|
|
80
|
-
// src/schema/entity.ts
|
|
81
|
-
import { sql as sql2 } from "drizzle-orm";
|
|
82
|
-
import { jsonb as jsonb2, pgTable as pgTable2, text as text2, unique as unique2, uuid as uuid2 } from "drizzle-orm/pg-core";
|
|
83
|
-
|
|
84
98
|
// src/schema/agent.ts
|
|
85
|
-
import {
|
|
86
|
-
boolean,
|
|
87
|
-
jsonb,
|
|
88
|
-
pgTable,
|
|
89
|
-
text,
|
|
90
|
-
uuid,
|
|
91
|
-
unique
|
|
92
|
-
} from "drizzle-orm/pg-core";
|
|
93
|
-
import { sql } from "drizzle-orm";
|
|
94
99
|
var agentTable = pgTable(
|
|
95
100
|
"agents",
|
|
96
101
|
{
|
|
@@ -120,6 +125,8 @@ var agentTable = pgTable(
|
|
|
120
125
|
);
|
|
121
126
|
|
|
122
127
|
// src/schema/entity.ts
|
|
128
|
+
import { sql as sql2 } from "drizzle-orm";
|
|
129
|
+
import { jsonb as jsonb2, pgTable as pgTable2, text as text2, unique as unique2, uuid as uuid2 } from "drizzle-orm/pg-core";
|
|
123
130
|
var entityTable = pgTable2(
|
|
124
131
|
"entities",
|
|
125
132
|
{
|
|
@@ -143,8 +150,8 @@ import { sql as sql4 } from "drizzle-orm";
|
|
|
143
150
|
import { jsonb as jsonb4, pgTable as pgTable4, text as text4, uuid as uuid4 } from "drizzle-orm/pg-core";
|
|
144
151
|
|
|
145
152
|
// src/schema/worldTable.ts
|
|
146
|
-
import { jsonb as jsonb3, pgTable as pgTable3, text as text3, uuid as uuid3 } from "drizzle-orm/pg-core";
|
|
147
153
|
import { sql as sql3 } from "drizzle-orm";
|
|
154
|
+
import { jsonb as jsonb3, pgTable as pgTable3, text as text3, uuid as uuid3 } from "drizzle-orm/pg-core";
|
|
148
155
|
var worldTable = pgTable3("worlds", {
|
|
149
156
|
id: uuid3("id").notNull().primaryKey().default(sql3`gen_random_uuid()`),
|
|
150
157
|
agentId: uuid3("agentId").notNull().references(() => agentTable.id, { onDelete: "cascade" }),
|
|
@@ -300,8 +307,8 @@ var cacheTable = pgTable7(
|
|
|
300
307
|
);
|
|
301
308
|
|
|
302
309
|
// src/schema/component.ts
|
|
303
|
-
import { pgTable as pgTable8, uuid as uuid8, jsonb as jsonb7, text as text7 } from "drizzle-orm/pg-core";
|
|
304
310
|
import { sql as sql8 } from "drizzle-orm";
|
|
311
|
+
import { jsonb as jsonb7, pgTable as pgTable8, text as text7, uuid as uuid8 } from "drizzle-orm/pg-core";
|
|
305
312
|
var componentTable = pgTable8("components", {
|
|
306
313
|
id: uuid8("id").primaryKey().defaultRandom(),
|
|
307
314
|
entityId: uuid8("entityId").notNull().references(() => entityTable.id, { onDelete: "cascade" }),
|
|
@@ -318,27 +325,18 @@ var componentTable = pgTable8("components", {
|
|
|
318
325
|
createdAt: numberTimestamp("createdAt").default(sql8`now()`).notNull()
|
|
319
326
|
});
|
|
320
327
|
|
|
321
|
-
// src/schema/
|
|
322
|
-
import { pgTable as pgTable9, uuid as uuid9, text as text8, jsonb as jsonb8, foreignKey as foreignKey3 } from "drizzle-orm/pg-core";
|
|
328
|
+
// src/schema/log.ts
|
|
323
329
|
import { sql as sql9 } from "drizzle-orm";
|
|
324
|
-
|
|
325
|
-
|
|
330
|
+
import { foreignKey as foreignKey3, jsonb as jsonb8, pgTable as pgTable9, text as text8, uuid as uuid9 } from "drizzle-orm/pg-core";
|
|
331
|
+
var logTable = pgTable9(
|
|
332
|
+
"logs",
|
|
326
333
|
{
|
|
327
|
-
id: uuid9("id").
|
|
334
|
+
id: uuid9("id").defaultRandom().notNull(),
|
|
328
335
|
createdAt: numberTimestamp("createdAt").default(sql9`now()`).notNull(),
|
|
329
|
-
entityId: uuid9("entityId").references(() => entityTable.id,
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
onDelete: "cascade"
|
|
334
|
-
}),
|
|
335
|
-
name: text8("name"),
|
|
336
|
-
status: text8("status"),
|
|
337
|
-
description: text8("description"),
|
|
338
|
-
roomId: uuid9("roomId").references(() => roomTable.id, {
|
|
339
|
-
onDelete: "cascade"
|
|
340
|
-
}),
|
|
341
|
-
objectives: jsonb8("objectives").default("[]").notNull()
|
|
336
|
+
entityId: uuid9("entityId").notNull().references(() => entityTable.id),
|
|
337
|
+
body: jsonb8("body").notNull(),
|
|
338
|
+
type: text8("type").notNull(),
|
|
339
|
+
roomId: uuid9("roomId").notNull().references(() => roomTable.id)
|
|
342
340
|
},
|
|
343
341
|
(table) => [
|
|
344
342
|
foreignKey3({
|
|
@@ -354,68 +352,41 @@ var goalTable = pgTable9(
|
|
|
354
352
|
]
|
|
355
353
|
);
|
|
356
354
|
|
|
357
|
-
// src/schema/log.ts
|
|
358
|
-
import { pgTable as pgTable10, uuid as uuid10, text as text9, jsonb as jsonb9, foreignKey as foreignKey4 } from "drizzle-orm/pg-core";
|
|
359
|
-
import { sql as sql10 } from "drizzle-orm";
|
|
360
|
-
var logTable = pgTable10(
|
|
361
|
-
"logs",
|
|
362
|
-
{
|
|
363
|
-
id: uuid10("id").defaultRandom().notNull(),
|
|
364
|
-
createdAt: numberTimestamp("createdAt").default(sql10`now()`).notNull(),
|
|
365
|
-
entityId: uuid10("entityId").notNull().references(() => entityTable.id),
|
|
366
|
-
body: jsonb9("body").notNull(),
|
|
367
|
-
type: text9("type").notNull(),
|
|
368
|
-
roomId: uuid10("roomId").notNull().references(() => roomTable.id)
|
|
369
|
-
},
|
|
370
|
-
(table) => [
|
|
371
|
-
foreignKey4({
|
|
372
|
-
name: "fk_room",
|
|
373
|
-
columns: [table.roomId],
|
|
374
|
-
foreignColumns: [roomTable.id]
|
|
375
|
-
}).onDelete("cascade"),
|
|
376
|
-
foreignKey4({
|
|
377
|
-
name: "fk_user",
|
|
378
|
-
columns: [table.entityId],
|
|
379
|
-
foreignColumns: [entityTable.id]
|
|
380
|
-
}).onDelete("cascade")
|
|
381
|
-
]
|
|
382
|
-
);
|
|
383
|
-
|
|
384
355
|
// src/schema/participant.ts
|
|
356
|
+
import { sql as sql10 } from "drizzle-orm";
|
|
385
357
|
import {
|
|
386
|
-
|
|
387
|
-
uuid as uuid11,
|
|
388
|
-
text as text10,
|
|
358
|
+
foreignKey as foreignKey4,
|
|
389
359
|
index as index3,
|
|
390
|
-
|
|
360
|
+
pgTable as pgTable10,
|
|
361
|
+
text as text9,
|
|
362
|
+
uuid as uuid10
|
|
391
363
|
} from "drizzle-orm/pg-core";
|
|
392
|
-
|
|
393
|
-
var participantTable = pgTable11(
|
|
364
|
+
var participantTable = pgTable10(
|
|
394
365
|
"participants",
|
|
395
366
|
{
|
|
396
|
-
id:
|
|
397
|
-
createdAt: numberTimestamp("createdAt").default(
|
|
398
|
-
entityId:
|
|
367
|
+
id: uuid10("id").notNull().primaryKey().default(sql10`gen_random_uuid()`),
|
|
368
|
+
createdAt: numberTimestamp("createdAt").default(sql10`now()`).notNull(),
|
|
369
|
+
entityId: uuid10("entityId").references(() => entityTable.id, {
|
|
399
370
|
onDelete: "cascade"
|
|
400
371
|
}),
|
|
401
|
-
roomId:
|
|
372
|
+
roomId: uuid10("roomId").references(() => roomTable.id, {
|
|
402
373
|
onDelete: "cascade"
|
|
403
374
|
}),
|
|
404
|
-
agentId:
|
|
375
|
+
agentId: uuid10("agentId").references(() => agentTable.id, {
|
|
405
376
|
onDelete: "cascade"
|
|
406
377
|
}),
|
|
407
|
-
roomState:
|
|
378
|
+
roomState: text9("roomState")
|
|
408
379
|
},
|
|
409
380
|
(table) => [
|
|
410
381
|
// unique("participants_user_room_agent_unique").on(table.entityId, table.roomId, table.agentId),
|
|
411
382
|
index3("idx_participants_user").on(table.entityId),
|
|
412
383
|
index3("idx_participants_room").on(table.roomId),
|
|
413
|
-
|
|
384
|
+
foreignKey4({
|
|
414
385
|
name: "fk_room",
|
|
415
386
|
columns: [table.roomId],
|
|
416
387
|
foreignColumns: [roomTable.id]
|
|
417
388
|
}).onDelete("cascade"),
|
|
418
|
-
|
|
389
|
+
foreignKey4({
|
|
419
390
|
name: "fk_user",
|
|
420
391
|
columns: [table.entityId],
|
|
421
392
|
foreignColumns: [entityTable.id]
|
|
@@ -424,26 +395,26 @@ var participantTable = pgTable11(
|
|
|
424
395
|
);
|
|
425
396
|
|
|
426
397
|
// src/schema/relationship.ts
|
|
427
|
-
import { sql as
|
|
398
|
+
import { sql as sql11 } from "drizzle-orm";
|
|
428
399
|
import {
|
|
429
|
-
foreignKey as
|
|
400
|
+
foreignKey as foreignKey5,
|
|
430
401
|
index as index4,
|
|
431
|
-
jsonb as
|
|
432
|
-
pgTable as
|
|
433
|
-
text as
|
|
402
|
+
jsonb as jsonb9,
|
|
403
|
+
pgTable as pgTable11,
|
|
404
|
+
text as text10,
|
|
434
405
|
unique as unique6,
|
|
435
|
-
uuid as
|
|
406
|
+
uuid as uuid11
|
|
436
407
|
} from "drizzle-orm/pg-core";
|
|
437
|
-
var relationshipTable =
|
|
408
|
+
var relationshipTable = pgTable11(
|
|
438
409
|
"relationships",
|
|
439
410
|
{
|
|
440
|
-
id:
|
|
441
|
-
createdAt: numberTimestamp("createdAt").default(
|
|
442
|
-
sourceEntityId:
|
|
443
|
-
targetEntityId:
|
|
444
|
-
agentId:
|
|
445
|
-
tags:
|
|
446
|
-
metadata:
|
|
411
|
+
id: uuid11("id").notNull().primaryKey().default(sql11`gen_random_uuid()`),
|
|
412
|
+
createdAt: numberTimestamp("createdAt").default(sql11`now()`).notNull(),
|
|
413
|
+
sourceEntityId: uuid11("sourceEntityId").notNull().references(() => entityTable.id, { onDelete: "cascade" }),
|
|
414
|
+
targetEntityId: uuid11("targetEntityId").notNull().references(() => entityTable.id, { onDelete: "cascade" }),
|
|
415
|
+
agentId: uuid11("agentId").notNull().references(() => agentTable.id, { onDelete: "cascade" }),
|
|
416
|
+
tags: text10("tags").array(),
|
|
417
|
+
metadata: jsonb9("metadata")
|
|
447
418
|
},
|
|
448
419
|
(table) => [
|
|
449
420
|
index4("idx_relationships_users").on(
|
|
@@ -455,12 +426,12 @@ var relationshipTable = pgTable12(
|
|
|
455
426
|
table.targetEntityId,
|
|
456
427
|
table.agentId
|
|
457
428
|
),
|
|
458
|
-
|
|
429
|
+
foreignKey5({
|
|
459
430
|
name: "fk_user_a",
|
|
460
431
|
columns: [table.sourceEntityId],
|
|
461
432
|
foreignColumns: [entityTable.id]
|
|
462
433
|
}).onDelete("cascade"),
|
|
463
|
-
|
|
434
|
+
foreignKey5({
|
|
464
435
|
name: "fk_user_b",
|
|
465
436
|
columns: [table.targetEntityId],
|
|
466
437
|
foreignColumns: [entityTable.id]
|
|
@@ -469,32 +440,46 @@ var relationshipTable = pgTable12(
|
|
|
469
440
|
);
|
|
470
441
|
|
|
471
442
|
// src/schema/tasks.ts
|
|
472
|
-
import { jsonb as
|
|
473
|
-
var taskTable =
|
|
474
|
-
id:
|
|
475
|
-
name:
|
|
476
|
-
description:
|
|
477
|
-
roomId:
|
|
478
|
-
worldId:
|
|
479
|
-
agentId:
|
|
480
|
-
tags:
|
|
481
|
-
metadata:
|
|
443
|
+
import { jsonb as jsonb10, pgTable as pgTable12, text as text11, timestamp, uuid as uuid12 } from "drizzle-orm/pg-core";
|
|
444
|
+
var taskTable = pgTable12("tasks", {
|
|
445
|
+
id: uuid12("id").primaryKey().defaultRandom(),
|
|
446
|
+
name: text11("name").notNull(),
|
|
447
|
+
description: text11("description").notNull(),
|
|
448
|
+
roomId: uuid12("room_id"),
|
|
449
|
+
worldId: uuid12("world_id"),
|
|
450
|
+
agentId: uuid12("agent_id").notNull(),
|
|
451
|
+
tags: text11("tags").array(),
|
|
452
|
+
metadata: jsonb10("metadata"),
|
|
482
453
|
createdAt: timestamp("created_at").defaultNow(),
|
|
483
454
|
updatedAt: timestamp("updated_at").defaultNow()
|
|
484
455
|
});
|
|
485
456
|
|
|
486
457
|
// src/base.ts
|
|
487
458
|
var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
459
|
+
static {
|
|
460
|
+
__name(this, "BaseDrizzleAdapter");
|
|
461
|
+
}
|
|
488
462
|
maxRetries = 3;
|
|
489
463
|
baseDelay = 1e3;
|
|
490
464
|
maxDelay = 1e4;
|
|
491
465
|
jitterMax = 1e3;
|
|
492
466
|
embeddingDimension = DIMENSION_MAP[384];
|
|
493
467
|
agentId;
|
|
468
|
+
/**
|
|
469
|
+
* Constructor for creating a new instance of Agent with the specified agentId.
|
|
470
|
+
*
|
|
471
|
+
* @param {UUID} agentId - The unique identifier for the agent.
|
|
472
|
+
*/
|
|
494
473
|
constructor(agentId) {
|
|
495
474
|
super();
|
|
496
475
|
this.agentId = agentId;
|
|
497
476
|
}
|
|
477
|
+
/**
|
|
478
|
+
* Executes the given operation with retry logic.
|
|
479
|
+
* @template T
|
|
480
|
+
* @param {() => Promise<T>} operation - The operation to be executed.
|
|
481
|
+
* @returns {Promise<T>} A promise that resolves with the result of the operation.
|
|
482
|
+
*/
|
|
498
483
|
async withRetry(operation) {
|
|
499
484
|
let lastError = new Error("Unknown error");
|
|
500
485
|
for (let attempt = 1; attempt <= this.maxRetries; attempt++) {
|
|
@@ -516,7 +501,6 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
516
501
|
nextRetryIn: `${(delay / 1e3).toFixed(1)}s`
|
|
517
502
|
}
|
|
518
503
|
);
|
|
519
|
-
console.trace("****** Database operation failure source");
|
|
520
504
|
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
521
505
|
} else {
|
|
522
506
|
logger.error("Max retry attempts reached:", {
|
|
@@ -529,6 +513,14 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
529
513
|
}
|
|
530
514
|
throw lastError;
|
|
531
515
|
}
|
|
516
|
+
/**
|
|
517
|
+
* Ensure that an agent exists by checking if an agent with the same name already exists in the system.
|
|
518
|
+
* If the agent does not exist, it will be created with the provided data.
|
|
519
|
+
*
|
|
520
|
+
* @param {Partial<Agent>} agent - The partial data of the agent to ensure its existence.
|
|
521
|
+
* @returns {Promise<void>} - A promise that resolves when the agent is successfully ensured.
|
|
522
|
+
* @throws {Error} - If the agent name is not provided or if there is an issue creating the agent.
|
|
523
|
+
*/
|
|
532
524
|
async ensureAgentExists(agent) {
|
|
533
525
|
if (!agent.name) {
|
|
534
526
|
throw new Error("Agent name is required");
|
|
@@ -541,6 +533,12 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
541
533
|
await this.createAgent(agent);
|
|
542
534
|
}
|
|
543
535
|
}
|
|
536
|
+
/**
|
|
537
|
+
* Ensure that the given embedding dimension is valid for the agent.
|
|
538
|
+
*
|
|
539
|
+
* @param {number} dimension - The dimension to ensure for the embedding.
|
|
540
|
+
* @returns {Promise<void>} - Resolves once the embedding dimension is ensured.
|
|
541
|
+
*/
|
|
544
542
|
async ensureEmbeddingDimension(dimension) {
|
|
545
543
|
const existingMemory = await this.db.select({
|
|
546
544
|
embedding: embeddingTable
|
|
@@ -549,12 +547,14 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
549
547
|
const usedDimension = Object.entries(DIMENSION_MAP).find(
|
|
550
548
|
([_, colName]) => existingMemory[0].embedding[colName] !== null
|
|
551
549
|
);
|
|
552
|
-
if (usedDimension && usedDimension[1] !== DIMENSION_MAP[dimension]) {
|
|
553
|
-
throw new Error("Cannot change embedding dimension for agent");
|
|
554
|
-
}
|
|
555
550
|
}
|
|
556
551
|
this.embeddingDimension = DIMENSION_MAP[dimension];
|
|
557
552
|
}
|
|
553
|
+
/**
|
|
554
|
+
* Asynchronously retrieves an agent by their ID from the database.
|
|
555
|
+
* @param {UUID} agentId - The ID of the agent to retrieve.
|
|
556
|
+
* @returns {Promise<Agent | null>} A promise that resolves to the retrieved agent or null if not found.
|
|
557
|
+
*/
|
|
558
558
|
async getAgent(agentId) {
|
|
559
559
|
return this.withDatabase(async () => {
|
|
560
560
|
const result = await this.db.select().from(agentTable).where(eq(agentTable.id, agentId)).limit(1);
|
|
@@ -562,12 +562,23 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
562
562
|
return result[0];
|
|
563
563
|
});
|
|
564
564
|
}
|
|
565
|
+
/**
|
|
566
|
+
* Asynchronously retrieves a list of agents from the database.
|
|
567
|
+
*
|
|
568
|
+
* @returns {Promise<Agent[]>} A Promise that resolves to an array of Agent objects.
|
|
569
|
+
*/
|
|
565
570
|
async getAgents() {
|
|
566
571
|
return this.withDatabase(async () => {
|
|
567
572
|
const result = await this.db.select().from(agentTable);
|
|
568
573
|
return result;
|
|
569
574
|
});
|
|
570
575
|
}
|
|
576
|
+
/**
|
|
577
|
+
* Asynchronously creates a new agent record in the database.
|
|
578
|
+
*
|
|
579
|
+
* @param {Partial<Agent>} agent The agent object to be created.
|
|
580
|
+
* @returns {Promise<boolean>} A promise that resolves to a boolean indicating the success of the operation.
|
|
581
|
+
*/
|
|
571
582
|
async createAgent(agent) {
|
|
572
583
|
return this.withDatabase(async () => {
|
|
573
584
|
try {
|
|
@@ -590,6 +601,12 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
590
601
|
}
|
|
591
602
|
});
|
|
592
603
|
}
|
|
604
|
+
/**
|
|
605
|
+
* Updates an agent in the database with the provided agent ID and data.
|
|
606
|
+
* @param {UUID} agentId - The unique identifier of the agent to update.
|
|
607
|
+
* @param {Partial<Agent>} agent - The partial agent object containing the fields to update.
|
|
608
|
+
* @returns {Promise<boolean>} - A boolean indicating if the agent was successfully updated.
|
|
609
|
+
*/
|
|
593
610
|
async updateAgent(agentId, agent) {
|
|
594
611
|
return this.withDatabase(async () => {
|
|
595
612
|
try {
|
|
@@ -616,6 +633,12 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
616
633
|
}
|
|
617
634
|
});
|
|
618
635
|
}
|
|
636
|
+
/**
|
|
637
|
+
* Asynchronously deletes an agent with the specified UUID and all related entries.
|
|
638
|
+
*
|
|
639
|
+
* @param {UUID} agentId - The UUID of the agent to be deleted.
|
|
640
|
+
* @returns {Promise<boolean>} - A boolean indicating if the deletion was successful.
|
|
641
|
+
*/
|
|
619
642
|
async deleteAgent(agentId) {
|
|
620
643
|
return this.withDatabase(async () => {
|
|
621
644
|
await this.db.transaction(async (tx) => {
|
|
@@ -628,6 +651,10 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
628
651
|
* Count all agents in the database
|
|
629
652
|
* Used primarily for maintenance and cleanup operations
|
|
630
653
|
*/
|
|
654
|
+
/**
|
|
655
|
+
* Asynchronously counts the number of agents in the database.
|
|
656
|
+
* @returns {Promise<number>} A Promise that resolves to the number of agents in the database.
|
|
657
|
+
*/
|
|
631
658
|
async countAgents() {
|
|
632
659
|
return this.withDatabase(async () => {
|
|
633
660
|
try {
|
|
@@ -730,11 +757,12 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
730
757
|
return true;
|
|
731
758
|
});
|
|
732
759
|
} catch (error) {
|
|
733
|
-
logger.error("Error creating
|
|
760
|
+
logger.error("Error creating entity:", {
|
|
734
761
|
error: error instanceof Error ? error.message : String(error),
|
|
735
762
|
entityId: entity.id,
|
|
736
763
|
name: entity.metadata?.name
|
|
737
764
|
});
|
|
765
|
+
console.trace(error);
|
|
738
766
|
return false;
|
|
739
767
|
}
|
|
740
768
|
});
|
|
@@ -947,7 +975,7 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
947
975
|
async getCachedEmbeddings(opts) {
|
|
948
976
|
return this.withDatabase(async () => {
|
|
949
977
|
try {
|
|
950
|
-
const results = await this.db.execute(
|
|
978
|
+
const results = await this.db.execute(sql12`
|
|
951
979
|
WITH content_text AS (
|
|
952
980
|
SELECT
|
|
953
981
|
m.id,
|
|
@@ -1004,7 +1032,7 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
1004
1032
|
try {
|
|
1005
1033
|
await this.db.transaction(async (tx) => {
|
|
1006
1034
|
await tx.insert(logTable).values({
|
|
1007
|
-
body:
|
|
1035
|
+
body: sql12`${params.body}::jsonb`,
|
|
1008
1036
|
entityId: params.entityId,
|
|
1009
1037
|
roomId: params.roomId,
|
|
1010
1038
|
type: params.type
|
|
@@ -1030,30 +1058,12 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
1030
1058
|
tableName: params.tableName
|
|
1031
1059
|
});
|
|
1032
1060
|
}
|
|
1033
|
-
async updateGoalStatus(params) {
|
|
1034
|
-
return this.withDatabase(async () => {
|
|
1035
|
-
try {
|
|
1036
|
-
await this.db.transaction(async (tx) => {
|
|
1037
|
-
await tx.update(goalTable).set({
|
|
1038
|
-
status: params.status
|
|
1039
|
-
}).where(eq(goalTable.id, params.goalId));
|
|
1040
|
-
});
|
|
1041
|
-
} catch (error) {
|
|
1042
|
-
logger.error("Failed to update goal status:", {
|
|
1043
|
-
goalId: params.goalId,
|
|
1044
|
-
status: params.status,
|
|
1045
|
-
error: error instanceof Error ? error.message : String(error)
|
|
1046
|
-
});
|
|
1047
|
-
throw error;
|
|
1048
|
-
}
|
|
1049
|
-
});
|
|
1050
|
-
}
|
|
1051
1061
|
async searchMemoriesByEmbedding(embedding, params) {
|
|
1052
1062
|
return this.withDatabase(async () => {
|
|
1053
1063
|
const cleanVector = embedding.map(
|
|
1054
1064
|
(n) => Number.isFinite(n) ? Number(n.toFixed(6)) : 0
|
|
1055
1065
|
);
|
|
1056
|
-
const similarity =
|
|
1066
|
+
const similarity = sql12`1 - (${cosineDistance(
|
|
1057
1067
|
embeddingTable[this.embeddingDimension],
|
|
1058
1068
|
cleanVector
|
|
1059
1069
|
)})`;
|
|
@@ -1113,8 +1123,8 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
1113
1123
|
{
|
|
1114
1124
|
id: memoryId,
|
|
1115
1125
|
type: tableName,
|
|
1116
|
-
content:
|
|
1117
|
-
metadata:
|
|
1126
|
+
content: sql12`${contentToInsert}::jsonb`,
|
|
1127
|
+
metadata: sql12`${memory.metadata || {}}::jsonb`,
|
|
1118
1128
|
entityId: memory.entityId,
|
|
1119
1129
|
roomId: memory.roomId,
|
|
1120
1130
|
agentId: memory.agentId,
|
|
@@ -1191,103 +1201,10 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
1191
1201
|
if (unique7) {
|
|
1192
1202
|
conditions.push(eq(memoryTable.unique, true));
|
|
1193
1203
|
}
|
|
1194
|
-
const result = await this.db.select({ count:
|
|
1204
|
+
const result = await this.db.select({ count: sql12`count(*)` }).from(memoryTable).where(and(...conditions));
|
|
1195
1205
|
return Number(result[0]?.count ?? 0);
|
|
1196
1206
|
});
|
|
1197
1207
|
}
|
|
1198
|
-
async getGoals(params) {
|
|
1199
|
-
return this.withDatabase(async () => {
|
|
1200
|
-
const conditions = [eq(goalTable.roomId, params.roomId)];
|
|
1201
|
-
if (params.entityId) {
|
|
1202
|
-
conditions.push(eq(goalTable.entityId, params.entityId));
|
|
1203
|
-
}
|
|
1204
|
-
if (params.onlyInProgress) {
|
|
1205
|
-
conditions.push(eq(goalTable.status, "IN_PROGRESS"));
|
|
1206
|
-
}
|
|
1207
|
-
const query = this.db.select().from(goalTable).where(and(...conditions)).orderBy(desc(goalTable.createdAt));
|
|
1208
|
-
const result = await (params.count ? query.limit(params.count) : query);
|
|
1209
|
-
return result.map((row) => ({
|
|
1210
|
-
id: row.id,
|
|
1211
|
-
roomId: row.roomId,
|
|
1212
|
-
entityId: row.entityId,
|
|
1213
|
-
name: row.name ?? "",
|
|
1214
|
-
status: row.status ?? "NOT_STARTED",
|
|
1215
|
-
description: row.description ?? "",
|
|
1216
|
-
objectives: row.objectives,
|
|
1217
|
-
createdAt: row.createdAt
|
|
1218
|
-
}));
|
|
1219
|
-
});
|
|
1220
|
-
}
|
|
1221
|
-
async updateGoal(goal) {
|
|
1222
|
-
return this.withDatabase(async () => {
|
|
1223
|
-
try {
|
|
1224
|
-
await this.db.transaction(async (tx) => {
|
|
1225
|
-
await tx.update(goalTable).set({
|
|
1226
|
-
name: goal.name,
|
|
1227
|
-
status: goal.status,
|
|
1228
|
-
objectives: goal.objectives
|
|
1229
|
-
}).where(eq(goalTable.id, goal.id));
|
|
1230
|
-
});
|
|
1231
|
-
} catch (error) {
|
|
1232
|
-
logger.error("Failed to update goal:", {
|
|
1233
|
-
error: error instanceof Error ? error.message : String(error),
|
|
1234
|
-
goalId: goal.id,
|
|
1235
|
-
status: goal.status
|
|
1236
|
-
});
|
|
1237
|
-
throw error;
|
|
1238
|
-
}
|
|
1239
|
-
});
|
|
1240
|
-
}
|
|
1241
|
-
async createGoal(goal) {
|
|
1242
|
-
return this.withDatabase(async () => {
|
|
1243
|
-
try {
|
|
1244
|
-
await this.db.transaction(async (tx) => {
|
|
1245
|
-
await tx.insert(goalTable).values({
|
|
1246
|
-
id: goal.id ?? v4(),
|
|
1247
|
-
roomId: goal.roomId,
|
|
1248
|
-
entityId: goal.entityId,
|
|
1249
|
-
name: goal.name,
|
|
1250
|
-
status: goal.status,
|
|
1251
|
-
objectives: sql13`${goal.objectives}::jsonb`
|
|
1252
|
-
});
|
|
1253
|
-
});
|
|
1254
|
-
} catch (error) {
|
|
1255
|
-
logger.error("Failed to update goal:", {
|
|
1256
|
-
goalId: goal.id,
|
|
1257
|
-
error: error instanceof Error ? error.message : String(error),
|
|
1258
|
-
status: goal.status
|
|
1259
|
-
});
|
|
1260
|
-
throw error;
|
|
1261
|
-
}
|
|
1262
|
-
});
|
|
1263
|
-
}
|
|
1264
|
-
async removeGoal(goalId) {
|
|
1265
|
-
if (!goalId) throw new Error("Goal ID is required");
|
|
1266
|
-
return this.withDatabase(async () => {
|
|
1267
|
-
try {
|
|
1268
|
-
await this.db.transaction(async (tx) => {
|
|
1269
|
-
await tx.delete(goalTable).where(eq(goalTable.id, goalId));
|
|
1270
|
-
});
|
|
1271
|
-
logger.debug("Goal removal attempt:", {
|
|
1272
|
-
goalId,
|
|
1273
|
-
removed: true
|
|
1274
|
-
});
|
|
1275
|
-
} catch (error) {
|
|
1276
|
-
logger.error("Failed to remove goal:", {
|
|
1277
|
-
error: error instanceof Error ? error.message : String(error),
|
|
1278
|
-
goalId
|
|
1279
|
-
});
|
|
1280
|
-
throw error;
|
|
1281
|
-
}
|
|
1282
|
-
});
|
|
1283
|
-
}
|
|
1284
|
-
async removeAllGoals(roomId) {
|
|
1285
|
-
return this.withDatabase(async () => {
|
|
1286
|
-
await this.db.transaction(async (tx) => {
|
|
1287
|
-
await tx.delete(goalTable).where(eq(goalTable.roomId, roomId));
|
|
1288
|
-
});
|
|
1289
|
-
});
|
|
1290
|
-
}
|
|
1291
1208
|
async getRoom(roomId) {
|
|
1292
1209
|
return this.withDatabase(async () => {
|
|
1293
1210
|
const result = await this.db.select({
|
|
@@ -1566,7 +1483,9 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
1566
1483
|
if (params.tags && params.tags.length > 0) {
|
|
1567
1484
|
const tagParams = params.tags.map((tag) => `'${tag.replace(/'/g, "''")}'`).join(", ");
|
|
1568
1485
|
query = query.where(
|
|
1569
|
-
|
|
1486
|
+
sql12`${relationshipTable.tags} @> ARRAY[${sql12.raw(
|
|
1487
|
+
tagParams
|
|
1488
|
+
)}]::text[]`
|
|
1570
1489
|
);
|
|
1571
1490
|
}
|
|
1572
1491
|
const results = await query;
|
|
@@ -1727,7 +1646,7 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
1727
1646
|
if (params.tags && params.tags.length > 0) {
|
|
1728
1647
|
const tagParams = params.tags.map((tag) => `'${tag.replace(/'/g, "''")}'`).join(", ");
|
|
1729
1648
|
query = query.where(
|
|
1730
|
-
|
|
1649
|
+
sql12`${taskTable.tags} @> ARRAY[${sql12.raw(tagParams)}]::text[]`
|
|
1731
1650
|
);
|
|
1732
1651
|
}
|
|
1733
1652
|
const result = await query;
|
|
@@ -1847,13 +1766,28 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
1847
1766
|
|
|
1848
1767
|
// src/pg-lite/adapter.ts
|
|
1849
1768
|
var PgliteDatabaseAdapter = class extends BaseDrizzleAdapter {
|
|
1769
|
+
static {
|
|
1770
|
+
__name(this, "PgliteDatabaseAdapter");
|
|
1771
|
+
}
|
|
1850
1772
|
manager;
|
|
1851
1773
|
embeddingDimension = DIMENSION_MAP[384];
|
|
1774
|
+
/**
|
|
1775
|
+
* Constructor for creating an instance of a class.
|
|
1776
|
+
* @param {UUID} agentId - The unique identifier for the agent.
|
|
1777
|
+
* @param {PGliteClientManager} manager - The manager for the PGlite client.
|
|
1778
|
+
*/
|
|
1852
1779
|
constructor(agentId, manager) {
|
|
1853
1780
|
super(agentId);
|
|
1854
1781
|
this.manager = manager;
|
|
1855
1782
|
this.db = drizzle(this.manager.getConnection());
|
|
1856
1783
|
}
|
|
1784
|
+
/**
|
|
1785
|
+
* Asynchronously runs the provided database operation while checking if the database manager is currently shutting down.
|
|
1786
|
+
* If the database manager is shutting down, a warning is logged and null is returned.
|
|
1787
|
+
*
|
|
1788
|
+
* @param {Function} operation - The database operation to be performed.
|
|
1789
|
+
* @returns {Promise<T>} A promise that resolves with the result of the database operation.
|
|
1790
|
+
*/
|
|
1857
1791
|
async withDatabase(operation) {
|
|
1858
1792
|
if (this.manager.isShuttingDown()) {
|
|
1859
1793
|
logger2.warn("Database is shutting down");
|
|
@@ -1861,6 +1795,11 @@ var PgliteDatabaseAdapter = class extends BaseDrizzleAdapter {
|
|
|
1861
1795
|
}
|
|
1862
1796
|
return operation();
|
|
1863
1797
|
}
|
|
1798
|
+
/**
|
|
1799
|
+
* Asynchronously initializes the database by running migrations using the manager.
|
|
1800
|
+
*
|
|
1801
|
+
* @returns {Promise<void>} A Promise that resolves when the database initialization is complete.
|
|
1802
|
+
*/
|
|
1864
1803
|
async init() {
|
|
1865
1804
|
try {
|
|
1866
1805
|
await this.manager.runMigrations();
|
|
@@ -1869,123 +1808,44 @@ var PgliteDatabaseAdapter = class extends BaseDrizzleAdapter {
|
|
|
1869
1808
|
throw error;
|
|
1870
1809
|
}
|
|
1871
1810
|
}
|
|
1811
|
+
/**
|
|
1812
|
+
* Asynchronously closes the manager.
|
|
1813
|
+
*/
|
|
1872
1814
|
async close() {
|
|
1873
1815
|
await this.manager.close();
|
|
1874
1816
|
}
|
|
1875
1817
|
};
|
|
1876
1818
|
|
|
1877
|
-
// src/pg-lite/manager.ts
|
|
1878
|
-
import { PGlite } from "@electric-sql/pglite";
|
|
1879
|
-
import { vector as vector3 } from "@electric-sql/pglite/vector";
|
|
1880
|
-
import { fuzzystrmatch } from "@electric-sql/pglite/contrib/fuzzystrmatch";
|
|
1881
|
-
import { logger as logger3 } from "@elizaos/core";
|
|
1882
|
-
import { migrate } from "drizzle-orm/pglite/migrator";
|
|
1883
|
-
import { fileURLToPath } from "node:url";
|
|
1884
|
-
import path from "node:path";
|
|
1885
|
-
import { drizzle as drizzle2 } from "drizzle-orm/pglite";
|
|
1886
|
-
var __filename = fileURLToPath(import.meta.url);
|
|
1887
|
-
var __dirname = path.dirname(__filename);
|
|
1888
|
-
var PGliteClientManager = class {
|
|
1889
|
-
client;
|
|
1890
|
-
shuttingDown = false;
|
|
1891
|
-
shutdownTimeout = 800;
|
|
1892
|
-
constructor(options) {
|
|
1893
|
-
this.client = new PGlite({
|
|
1894
|
-
...options,
|
|
1895
|
-
extensions: {
|
|
1896
|
-
vector: vector3,
|
|
1897
|
-
fuzzystrmatch
|
|
1898
|
-
}
|
|
1899
|
-
});
|
|
1900
|
-
this.setupShutdownHandlers();
|
|
1901
|
-
}
|
|
1902
|
-
getConnection() {
|
|
1903
|
-
if (this.shuttingDown) {
|
|
1904
|
-
throw new Error("Client manager is shutting down");
|
|
1905
|
-
}
|
|
1906
|
-
return this.client;
|
|
1907
|
-
}
|
|
1908
|
-
async gracefulShutdown() {
|
|
1909
|
-
if (this.shuttingDown) {
|
|
1910
|
-
return;
|
|
1911
|
-
}
|
|
1912
|
-
this.shuttingDown = true;
|
|
1913
|
-
logger3.info("Starting graceful shutdown of PGlite client...");
|
|
1914
|
-
const timeout = setTimeout(() => {
|
|
1915
|
-
logger3.warn(
|
|
1916
|
-
"Shutdown timeout reached, forcing database connection closure..."
|
|
1917
|
-
);
|
|
1918
|
-
this.client.close().finally(() => {
|
|
1919
|
-
process.exit(1);
|
|
1920
|
-
});
|
|
1921
|
-
}, this.shutdownTimeout);
|
|
1922
|
-
try {
|
|
1923
|
-
await new Promise((resolve) => setTimeout(resolve, this.shutdownTimeout));
|
|
1924
|
-
await this.client.close();
|
|
1925
|
-
clearTimeout(timeout);
|
|
1926
|
-
logger3.info("PGlite client shutdown completed successfully");
|
|
1927
|
-
process.exit(0);
|
|
1928
|
-
} catch (error) {
|
|
1929
|
-
logger3.error("Error during graceful shutdown:", error);
|
|
1930
|
-
process.exit(1);
|
|
1931
|
-
}
|
|
1932
|
-
}
|
|
1933
|
-
setupShutdownHandlers() {
|
|
1934
|
-
process.on("SIGINT", async () => {
|
|
1935
|
-
await this.gracefulShutdown();
|
|
1936
|
-
});
|
|
1937
|
-
process.on("SIGTERM", async () => {
|
|
1938
|
-
await this.gracefulShutdown();
|
|
1939
|
-
});
|
|
1940
|
-
process.on("beforeExit", async () => {
|
|
1941
|
-
await this.gracefulShutdown();
|
|
1942
|
-
});
|
|
1943
|
-
}
|
|
1944
|
-
async initialize() {
|
|
1945
|
-
try {
|
|
1946
|
-
await this.client.waitReady;
|
|
1947
|
-
logger3.info("PGlite client initialized successfully");
|
|
1948
|
-
} catch (error) {
|
|
1949
|
-
logger3.error("Failed to initialize PGlite client:", error);
|
|
1950
|
-
throw error;
|
|
1951
|
-
}
|
|
1952
|
-
}
|
|
1953
|
-
async close() {
|
|
1954
|
-
if (!this.shuttingDown) {
|
|
1955
|
-
await this.gracefulShutdown();
|
|
1956
|
-
}
|
|
1957
|
-
}
|
|
1958
|
-
isShuttingDown() {
|
|
1959
|
-
return this.shuttingDown;
|
|
1960
|
-
}
|
|
1961
|
-
async runMigrations() {
|
|
1962
|
-
try {
|
|
1963
|
-
const db = drizzle2(this.client);
|
|
1964
|
-
await migrate(db, {
|
|
1965
|
-
migrationsFolder: path.resolve(__dirname, "../drizzle/migrations")
|
|
1966
|
-
});
|
|
1967
|
-
logger3.info("Migrations completed successfully!");
|
|
1968
|
-
} catch (error) {
|
|
1969
|
-
logger3.error("Failed to run database migrations:", error);
|
|
1970
|
-
}
|
|
1971
|
-
}
|
|
1972
|
-
};
|
|
1973
|
-
|
|
1974
1819
|
// src/pg/adapter.ts
|
|
1975
|
-
import { logger as
|
|
1976
|
-
import { drizzle as
|
|
1820
|
+
import { logger as logger3 } from "@elizaos/core";
|
|
1821
|
+
import { drizzle as drizzle2 } from "drizzle-orm/node-postgres";
|
|
1977
1822
|
var PgDatabaseAdapter = class extends BaseDrizzleAdapter {
|
|
1823
|
+
/**
|
|
1824
|
+
* Constructor for creating a new instance of a class.
|
|
1825
|
+
* @param {UUID} agentId - The unique identifier for the agent.
|
|
1826
|
+
* @param {PostgresConnectionManager} manager - The Postgres connection manager for the instance.
|
|
1827
|
+
*/
|
|
1978
1828
|
constructor(agentId, manager) {
|
|
1979
1829
|
super(agentId);
|
|
1980
1830
|
this.manager = manager;
|
|
1981
1831
|
this.manager = manager;
|
|
1982
1832
|
}
|
|
1833
|
+
static {
|
|
1834
|
+
__name(this, "PgDatabaseAdapter");
|
|
1835
|
+
}
|
|
1983
1836
|
embeddingDimension = DIMENSION_MAP[384];
|
|
1837
|
+
/**
|
|
1838
|
+
* Executes the provided operation with a database connection.
|
|
1839
|
+
*
|
|
1840
|
+
* @template T
|
|
1841
|
+
* @param {() => Promise<T>} operation - The operation to be executed with the database connection.
|
|
1842
|
+
* @returns {Promise<T>} A promise that resolves with the result of the operation.
|
|
1843
|
+
*/
|
|
1984
1844
|
async withDatabase(operation) {
|
|
1985
1845
|
return await this.withRetry(async () => {
|
|
1986
1846
|
const client = await this.manager.getClient();
|
|
1987
1847
|
try {
|
|
1988
|
-
const db =
|
|
1848
|
+
const db = drizzle2(client);
|
|
1989
1849
|
this.db = db;
|
|
1990
1850
|
return await operation();
|
|
1991
1851
|
} finally {
|
|
@@ -1993,181 +1853,77 @@ var PgDatabaseAdapter = class extends BaseDrizzleAdapter {
|
|
|
1993
1853
|
}
|
|
1994
1854
|
});
|
|
1995
1855
|
}
|
|
1856
|
+
/**
|
|
1857
|
+
* Asynchronously initializes the PgDatabaseAdapter by running migrations using the manager.
|
|
1858
|
+
* Logs a success message if initialization is successful, otherwise logs an error message.
|
|
1859
|
+
*
|
|
1860
|
+
* @returns {Promise<void>} A promise that resolves when initialization is complete.
|
|
1861
|
+
*/
|
|
1996
1862
|
async init() {
|
|
1997
1863
|
try {
|
|
1998
1864
|
await this.manager.runMigrations();
|
|
1999
|
-
|
|
1865
|
+
logger3.info("PgDatabaseAdapter initialized successfully");
|
|
2000
1866
|
} catch (error) {
|
|
2001
|
-
|
|
1867
|
+
logger3.error("Failed to initialize PgDatabaseAdapter:", error);
|
|
2002
1868
|
throw error;
|
|
2003
1869
|
}
|
|
2004
1870
|
}
|
|
1871
|
+
/**
|
|
1872
|
+
* Asynchronously closes the manager associated with this instance.
|
|
1873
|
+
*
|
|
1874
|
+
* @returns A Promise that resolves once the manager is closed.
|
|
1875
|
+
*/
|
|
2005
1876
|
async close() {
|
|
2006
1877
|
await this.manager.close();
|
|
2007
1878
|
}
|
|
2008
1879
|
};
|
|
2009
1880
|
|
|
2010
|
-
// src/pg/manager.ts
|
|
2011
|
-
import pkg from "pg";
|
|
2012
|
-
import { logger as logger5 } from "@elizaos/core";
|
|
2013
|
-
import { migrate as migrate2 } from "drizzle-orm/node-postgres/migrator";
|
|
2014
|
-
import { fileURLToPath as fileURLToPath2 } from "node:url";
|
|
2015
|
-
import path2 from "node:path";
|
|
2016
|
-
import { drizzle as drizzle4 } from "drizzle-orm/node-postgres";
|
|
2017
|
-
var { Pool } = pkg;
|
|
2018
|
-
var __filename2 = fileURLToPath2(import.meta.url);
|
|
2019
|
-
var __dirname2 = path2.dirname(__filename2);
|
|
2020
|
-
var PostgresConnectionManager = class {
|
|
2021
|
-
pool;
|
|
2022
|
-
isShuttingDown = false;
|
|
2023
|
-
connectionTimeout = 5e3;
|
|
2024
|
-
constructor(connectionString) {
|
|
2025
|
-
const defaultConfig = {
|
|
2026
|
-
max: 20,
|
|
2027
|
-
idleTimeoutMillis: 3e4,
|
|
2028
|
-
connectionTimeoutMillis: this.connectionTimeout
|
|
2029
|
-
};
|
|
2030
|
-
this.pool = new Pool({
|
|
2031
|
-
...defaultConfig,
|
|
2032
|
-
connectionString
|
|
2033
|
-
});
|
|
2034
|
-
this.pool.on("error", (err) => {
|
|
2035
|
-
logger5.error("Unexpected pool error", err);
|
|
2036
|
-
this.handlePoolError(err);
|
|
2037
|
-
});
|
|
2038
|
-
this.setupPoolErrorHandling();
|
|
2039
|
-
this.testConnection();
|
|
2040
|
-
}
|
|
2041
|
-
async handlePoolError(error) {
|
|
2042
|
-
logger5.error("Pool error occurred, attempting to reconnect", {
|
|
2043
|
-
error: error.message
|
|
2044
|
-
});
|
|
2045
|
-
try {
|
|
2046
|
-
await this.pool.end();
|
|
2047
|
-
this.pool = new Pool({
|
|
2048
|
-
...this.pool.options,
|
|
2049
|
-
connectionTimeoutMillis: this.connectionTimeout
|
|
2050
|
-
});
|
|
2051
|
-
await this.testConnection();
|
|
2052
|
-
logger5.success("Pool reconnection successful");
|
|
2053
|
-
} catch (reconnectError) {
|
|
2054
|
-
logger5.error("Failed to reconnect pool", {
|
|
2055
|
-
error: reconnectError instanceof Error ? reconnectError.message : String(reconnectError)
|
|
2056
|
-
});
|
|
2057
|
-
throw reconnectError;
|
|
2058
|
-
}
|
|
2059
|
-
}
|
|
2060
|
-
async testConnection() {
|
|
2061
|
-
let client;
|
|
2062
|
-
try {
|
|
2063
|
-
client = await this.pool.connect();
|
|
2064
|
-
const result = await client.query("SELECT NOW()");
|
|
2065
|
-
logger5.success("Database connection test successful:", result.rows[0]);
|
|
2066
|
-
return true;
|
|
2067
|
-
} catch (error) {
|
|
2068
|
-
logger5.error("Database connection test failed:", error);
|
|
2069
|
-
throw new Error(
|
|
2070
|
-
`Failed to connect to database: ${error.message}`
|
|
2071
|
-
);
|
|
2072
|
-
} finally {
|
|
2073
|
-
if (client) client.release();
|
|
2074
|
-
}
|
|
2075
|
-
}
|
|
2076
|
-
setupPoolErrorHandling() {
|
|
2077
|
-
process.on("SIGINT", async () => {
|
|
2078
|
-
await this.cleanup();
|
|
2079
|
-
process.exit(0);
|
|
2080
|
-
});
|
|
2081
|
-
process.on("SIGTERM", async () => {
|
|
2082
|
-
await this.cleanup();
|
|
2083
|
-
process.exit(0);
|
|
2084
|
-
});
|
|
2085
|
-
process.on("beforeExit", async () => {
|
|
2086
|
-
await this.cleanup();
|
|
2087
|
-
});
|
|
2088
|
-
}
|
|
2089
|
-
getConnection() {
|
|
2090
|
-
if (this.isShuttingDown) {
|
|
2091
|
-
throw new Error("Connection manager is shutting down");
|
|
2092
|
-
}
|
|
2093
|
-
try {
|
|
2094
|
-
return this.pool;
|
|
2095
|
-
} catch (error) {
|
|
2096
|
-
logger5.error("Failed to get connection from pool:", error);
|
|
2097
|
-
throw error;
|
|
2098
|
-
}
|
|
2099
|
-
}
|
|
2100
|
-
async getClient() {
|
|
2101
|
-
try {
|
|
2102
|
-
return await this.pool.connect();
|
|
2103
|
-
} catch (error) {
|
|
2104
|
-
logger5.error("Failed to acquire a database client:", error);
|
|
2105
|
-
throw error;
|
|
2106
|
-
}
|
|
2107
|
-
}
|
|
2108
|
-
async initialize() {
|
|
2109
|
-
try {
|
|
2110
|
-
await this.testConnection();
|
|
2111
|
-
logger5.info("PostgreSQL connection manager initialized successfully");
|
|
2112
|
-
} catch (error) {
|
|
2113
|
-
logger5.error("Failed to initialize connection manager:", error);
|
|
2114
|
-
throw error;
|
|
2115
|
-
}
|
|
2116
|
-
}
|
|
2117
|
-
async close() {
|
|
2118
|
-
await this.cleanup();
|
|
2119
|
-
}
|
|
2120
|
-
async cleanup() {
|
|
2121
|
-
try {
|
|
2122
|
-
await this.pool.end();
|
|
2123
|
-
logger5.info("Database pool closed");
|
|
2124
|
-
} catch (error) {
|
|
2125
|
-
logger5.error("Error closing database pool:", error);
|
|
2126
|
-
}
|
|
2127
|
-
}
|
|
2128
|
-
async runMigrations() {
|
|
2129
|
-
try {
|
|
2130
|
-
const db = drizzle4(this.pool);
|
|
2131
|
-
await migrate2(db, {
|
|
2132
|
-
migrationsFolder: path2.resolve(__dirname2, "../drizzle/migrations")
|
|
2133
|
-
});
|
|
2134
|
-
logger5.info("Migrations completed successfully!");
|
|
2135
|
-
} catch (error) {
|
|
2136
|
-
logger5.error("Failed to run database migrations:", error);
|
|
2137
|
-
}
|
|
2138
|
-
}
|
|
2139
|
-
};
|
|
2140
|
-
|
|
2141
1881
|
// src/index.ts
|
|
2142
1882
|
var pgLiteClientManager;
|
|
1883
|
+
var postgresConnectionManager;
|
|
1884
|
+
function expandTildePath(filepath) {
|
|
1885
|
+
if (filepath && typeof filepath === "string" && filepath.startsWith("~")) {
|
|
1886
|
+
return filepath.replace(/^~/, os.homedir());
|
|
1887
|
+
}
|
|
1888
|
+
return filepath;
|
|
1889
|
+
}
|
|
1890
|
+
__name(expandTildePath, "expandTildePath");
|
|
2143
1891
|
function createDatabaseAdapter(config, agentId) {
|
|
1892
|
+
if (config.dataDir) {
|
|
1893
|
+
config.dataDir = expandTildePath(config.dataDir);
|
|
1894
|
+
}
|
|
2144
1895
|
if (config.postgresUrl) {
|
|
2145
|
-
|
|
2146
|
-
|
|
1896
|
+
if (!postgresConnectionManager) {
|
|
1897
|
+
postgresConnectionManager = new PostgresConnectionManager(
|
|
1898
|
+
config.postgresUrl
|
|
1899
|
+
);
|
|
1900
|
+
}
|
|
1901
|
+
return new PgDatabaseAdapter(agentId, postgresConnectionManager);
|
|
2147
1902
|
}
|
|
2148
|
-
const dataDir = config.dataDir ?? "
|
|
1903
|
+
const dataDir = config.dataDir ?? "./elizadb";
|
|
2149
1904
|
if (!pgLiteClientManager) {
|
|
2150
1905
|
pgLiteClientManager = new PGliteClientManager({ dataDir });
|
|
2151
1906
|
}
|
|
2152
1907
|
return new PgliteDatabaseAdapter(agentId, pgLiteClientManager);
|
|
2153
1908
|
}
|
|
1909
|
+
__name(createDatabaseAdapter, "createDatabaseAdapter");
|
|
2154
1910
|
var drizzlePlugin = {
|
|
2155
1911
|
name: "drizzle",
|
|
2156
1912
|
description: "Database adapter plugin using Drizzle ORM",
|
|
2157
|
-
init: async (_, runtime) => {
|
|
1913
|
+
init: /* @__PURE__ */ __name(async (_, runtime) => {
|
|
2158
1914
|
const config = {
|
|
2159
|
-
dataDir: runtime.getSetting("PGLITE_DATA_DIR"),
|
|
1915
|
+
dataDir: runtime.getSetting("PGLITE_DATA_DIR") ?? "./pglite",
|
|
2160
1916
|
postgresUrl: runtime.getSetting("POSTGRES_URL")
|
|
2161
1917
|
};
|
|
2162
1918
|
try {
|
|
2163
1919
|
const db = createDatabaseAdapter(config, runtime.agentId);
|
|
2164
|
-
|
|
1920
|
+
logger4.success("Database connection established successfully");
|
|
2165
1921
|
runtime.registerDatabaseAdapter(db);
|
|
2166
1922
|
} catch (error) {
|
|
2167
|
-
|
|
1923
|
+
logger4.error("Failed to initialize database:", error);
|
|
2168
1924
|
throw error;
|
|
2169
1925
|
}
|
|
2170
|
-
}
|
|
1926
|
+
}, "init")
|
|
2171
1927
|
};
|
|
2172
1928
|
var index_default = drizzlePlugin;
|
|
2173
1929
|
export {
|