@elizaos/plugin-sql 1.0.0-alpha.4 → 1.0.0-alpha.41

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/index.js CHANGED
@@ -1,6 +1,13 @@
1
+ import {
2
+ PGliteClientManager,
3
+ PostgresConnectionManager,
4
+ __name
5
+ } from "./chunk-UX7XPDSU.js";
6
+
1
7
  // src/index.ts
8
+ import * as os from "node:os";
2
9
  import {
3
- logger as logger6
10
+ logger as logger4
4
11
  } from "@elizaos/core";
5
12
 
6
13
  // src/pg-lite/adapter.ts
@@ -22,20 +29,43 @@ import {
22
29
  inArray,
23
30
  lte,
24
31
  or,
25
- sql as sql13
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
- index as index2,
35
- foreignKey as foreignKey2,
36
- check as check2
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
+ jsonb,
64
+ pgTable,
65
+ text,
66
+ unique,
67
+ uuid
37
68
  } from "drizzle-orm/pg-core";
38
- import { sql as sql6 } from "drizzle-orm";
39
69
 
40
70
  // src/schema/types.ts
41
71
  import { customType } from "drizzle-orm/pg-core";
@@ -64,40 +94,13 @@ var numberTimestamp = customType(
64
94
  }
65
95
  );
66
96
 
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
97
  // 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
98
  var agentTable = pgTable(
95
99
  "agents",
96
100
  {
97
101
  id: uuid("id").primaryKey().defaultRandom(),
98
102
  createdAt: numberTimestamp("createdAt").default(sql`now()`).notNull(),
99
103
  updatedAt: numberTimestamp("updatedAt").default(sql`now()`).notNull(),
100
- enabled: boolean("enabled").default(true).notNull(),
101
104
  // Character
102
105
  name: text("name"),
103
106
  username: text("username"),
@@ -120,6 +123,8 @@ var agentTable = pgTable(
120
123
  );
121
124
 
122
125
  // src/schema/entity.ts
126
+ import { sql as sql2 } from "drizzle-orm";
127
+ import { jsonb as jsonb2, pgTable as pgTable2, text as text2, unique as unique2, uuid as uuid2 } from "drizzle-orm/pg-core";
123
128
  var entityTable = pgTable2(
124
129
  "entities",
125
130
  {
@@ -143,8 +148,8 @@ import { sql as sql4 } from "drizzle-orm";
143
148
  import { jsonb as jsonb4, pgTable as pgTable4, text as text4, uuid as uuid4 } from "drizzle-orm/pg-core";
144
149
 
145
150
  // src/schema/worldTable.ts
146
- import { jsonb as jsonb3, pgTable as pgTable3, text as text3, uuid as uuid3 } from "drizzle-orm/pg-core";
147
151
  import { sql as sql3 } from "drizzle-orm";
152
+ import { jsonb as jsonb3, pgTable as pgTable3, text as text3, uuid as uuid3 } from "drizzle-orm/pg-core";
148
153
  var worldTable = pgTable3("worlds", {
149
154
  id: uuid3("id").notNull().primaryKey().default(sql3`gen_random_uuid()`),
150
155
  agentId: uuid3("agentId").notNull().references(() => agentTable.id, { onDelete: "cascade" }),
@@ -300,8 +305,8 @@ var cacheTable = pgTable7(
300
305
  );
301
306
 
302
307
  // src/schema/component.ts
303
- import { pgTable as pgTable8, uuid as uuid8, jsonb as jsonb7, text as text7 } from "drizzle-orm/pg-core";
304
308
  import { sql as sql8 } from "drizzle-orm";
309
+ import { jsonb as jsonb7, pgTable as pgTable8, text as text7, uuid as uuid8 } from "drizzle-orm/pg-core";
305
310
  var componentTable = pgTable8("components", {
306
311
  id: uuid8("id").primaryKey().defaultRandom(),
307
312
  entityId: uuid8("entityId").notNull().references(() => entityTable.id, { onDelete: "cascade" }),
@@ -318,27 +323,18 @@ var componentTable = pgTable8("components", {
318
323
  createdAt: numberTimestamp("createdAt").default(sql8`now()`).notNull()
319
324
  });
320
325
 
321
- // src/schema/goal.ts
322
- import { pgTable as pgTable9, uuid as uuid9, text as text8, jsonb as jsonb8, foreignKey as foreignKey3 } from "drizzle-orm/pg-core";
326
+ // src/schema/log.ts
323
327
  import { sql as sql9 } from "drizzle-orm";
324
- var goalTable = pgTable9(
325
- "goals",
328
+ import { foreignKey as foreignKey3, jsonb as jsonb8, pgTable as pgTable9, text as text8, uuid as uuid9 } from "drizzle-orm/pg-core";
329
+ var logTable = pgTable9(
330
+ "logs",
326
331
  {
327
- id: uuid9("id").notNull().primaryKey().default(sql9`gen_random_uuid()`),
332
+ id: uuid9("id").defaultRandom().notNull(),
328
333
  createdAt: numberTimestamp("createdAt").default(sql9`now()`).notNull(),
329
- entityId: uuid9("entityId").references(() => entityTable.id, {
330
- onDelete: "cascade"
331
- }),
332
- agentId: uuid9("agentId").references(() => agentTable.id, {
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()
334
+ entityId: uuid9("entityId").notNull().references(() => entityTable.id),
335
+ body: jsonb8("body").notNull(),
336
+ type: text8("type").notNull(),
337
+ roomId: uuid9("roomId").notNull().references(() => roomTable.id)
342
338
  },
343
339
  (table) => [
344
340
  foreignKey3({
@@ -354,68 +350,41 @@ var goalTable = pgTable9(
354
350
  ]
355
351
  );
356
352
 
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
353
  // src/schema/participant.ts
354
+ import { sql as sql10 } from "drizzle-orm";
385
355
  import {
386
- pgTable as pgTable11,
387
- uuid as uuid11,
388
- text as text10,
356
+ foreignKey as foreignKey4,
389
357
  index as index3,
390
- foreignKey as foreignKey5
358
+ pgTable as pgTable10,
359
+ text as text9,
360
+ uuid as uuid10
391
361
  } from "drizzle-orm/pg-core";
392
- import { sql as sql11 } from "drizzle-orm";
393
- var participantTable = pgTable11(
362
+ var participantTable = pgTable10(
394
363
  "participants",
395
364
  {
396
- id: uuid11("id").notNull().primaryKey().default(sql11`gen_random_uuid()`),
397
- createdAt: numberTimestamp("createdAt").default(sql11`now()`).notNull(),
398
- entityId: uuid11("entityId").references(() => entityTable.id, {
365
+ id: uuid10("id").notNull().primaryKey().default(sql10`gen_random_uuid()`),
366
+ createdAt: numberTimestamp("createdAt").default(sql10`now()`).notNull(),
367
+ entityId: uuid10("entityId").references(() => entityTable.id, {
399
368
  onDelete: "cascade"
400
369
  }),
401
- roomId: uuid11("roomId").references(() => roomTable.id, {
370
+ roomId: uuid10("roomId").references(() => roomTable.id, {
402
371
  onDelete: "cascade"
403
372
  }),
404
- agentId: uuid11("agentId").references(() => agentTable.id, {
373
+ agentId: uuid10("agentId").references(() => agentTable.id, {
405
374
  onDelete: "cascade"
406
375
  }),
407
- roomState: text10("roomState")
376
+ roomState: text9("roomState")
408
377
  },
409
378
  (table) => [
410
379
  // unique("participants_user_room_agent_unique").on(table.entityId, table.roomId, table.agentId),
411
380
  index3("idx_participants_user").on(table.entityId),
412
381
  index3("idx_participants_room").on(table.roomId),
413
- foreignKey5({
382
+ foreignKey4({
414
383
  name: "fk_room",
415
384
  columns: [table.roomId],
416
385
  foreignColumns: [roomTable.id]
417
386
  }).onDelete("cascade"),
418
- foreignKey5({
387
+ foreignKey4({
419
388
  name: "fk_user",
420
389
  columns: [table.entityId],
421
390
  foreignColumns: [entityTable.id]
@@ -424,26 +393,26 @@ var participantTable = pgTable11(
424
393
  );
425
394
 
426
395
  // src/schema/relationship.ts
427
- import { sql as sql12 } from "drizzle-orm";
396
+ import { sql as sql11 } from "drizzle-orm";
428
397
  import {
429
- foreignKey as foreignKey6,
398
+ foreignKey as foreignKey5,
430
399
  index as index4,
431
- jsonb as jsonb10,
432
- pgTable as pgTable12,
433
- text as text11,
400
+ jsonb as jsonb9,
401
+ pgTable as pgTable11,
402
+ text as text10,
434
403
  unique as unique6,
435
- uuid as uuid12
404
+ uuid as uuid11
436
405
  } from "drizzle-orm/pg-core";
437
- var relationshipTable = pgTable12(
406
+ var relationshipTable = pgTable11(
438
407
  "relationships",
439
408
  {
440
- id: uuid12("id").notNull().primaryKey().default(sql12`gen_random_uuid()`),
441
- createdAt: numberTimestamp("createdAt").default(sql12`now()`).notNull(),
442
- sourceEntityId: uuid12("sourceEntityId").notNull().references(() => entityTable.id, { onDelete: "cascade" }),
443
- targetEntityId: uuid12("targetEntityId").notNull().references(() => entityTable.id, { onDelete: "cascade" }),
444
- agentId: uuid12("agentId").notNull().references(() => agentTable.id, { onDelete: "cascade" }),
445
- tags: text11("tags").array(),
446
- metadata: jsonb10("metadata")
409
+ id: uuid11("id").notNull().primaryKey().default(sql11`gen_random_uuid()`),
410
+ createdAt: numberTimestamp("createdAt").default(sql11`now()`).notNull(),
411
+ sourceEntityId: uuid11("sourceEntityId").notNull().references(() => entityTable.id, { onDelete: "cascade" }),
412
+ targetEntityId: uuid11("targetEntityId").notNull().references(() => entityTable.id, { onDelete: "cascade" }),
413
+ agentId: uuid11("agentId").notNull().references(() => agentTable.id, { onDelete: "cascade" }),
414
+ tags: text10("tags").array(),
415
+ metadata: jsonb9("metadata")
447
416
  },
448
417
  (table) => [
449
418
  index4("idx_relationships_users").on(
@@ -455,12 +424,12 @@ var relationshipTable = pgTable12(
455
424
  table.targetEntityId,
456
425
  table.agentId
457
426
  ),
458
- foreignKey6({
427
+ foreignKey5({
459
428
  name: "fk_user_a",
460
429
  columns: [table.sourceEntityId],
461
430
  foreignColumns: [entityTable.id]
462
431
  }).onDelete("cascade"),
463
- foreignKey6({
432
+ foreignKey5({
464
433
  name: "fk_user_b",
465
434
  columns: [table.targetEntityId],
466
435
  foreignColumns: [entityTable.id]
@@ -469,32 +438,46 @@ var relationshipTable = pgTable12(
469
438
  );
470
439
 
471
440
  // src/schema/tasks.ts
472
- import { jsonb as jsonb11, pgTable as pgTable13, text as text12, timestamp, uuid as uuid13 } from "drizzle-orm/pg-core";
473
- var taskTable = pgTable13("tasks", {
474
- id: uuid13("id").primaryKey().defaultRandom(),
475
- name: text12("name").notNull(),
476
- description: text12("description").notNull(),
477
- roomId: uuid13("room_id"),
478
- worldId: uuid13("world_id"),
479
- agentId: uuid13("agent_id").notNull(),
480
- tags: text12("tags").array(),
481
- metadata: jsonb11("metadata"),
441
+ import { jsonb as jsonb10, pgTable as pgTable12, text as text11, timestamp, uuid as uuid12 } from "drizzle-orm/pg-core";
442
+ var taskTable = pgTable12("tasks", {
443
+ id: uuid12("id").primaryKey().defaultRandom(),
444
+ name: text11("name").notNull(),
445
+ description: text11("description").notNull(),
446
+ roomId: uuid12("room_id"),
447
+ worldId: uuid12("world_id"),
448
+ agentId: uuid12("agent_id").notNull(),
449
+ tags: text11("tags").array(),
450
+ metadata: jsonb10("metadata"),
482
451
  createdAt: timestamp("created_at").defaultNow(),
483
452
  updatedAt: timestamp("updated_at").defaultNow()
484
453
  });
485
454
 
486
455
  // src/base.ts
487
456
  var BaseDrizzleAdapter = class extends DatabaseAdapter {
457
+ static {
458
+ __name(this, "BaseDrizzleAdapter");
459
+ }
488
460
  maxRetries = 3;
489
461
  baseDelay = 1e3;
490
462
  maxDelay = 1e4;
491
463
  jitterMax = 1e3;
492
464
  embeddingDimension = DIMENSION_MAP[384];
493
465
  agentId;
466
+ /**
467
+ * Constructor for creating a new instance of Agent with the specified agentId.
468
+ *
469
+ * @param {UUID} agentId - The unique identifier for the agent.
470
+ */
494
471
  constructor(agentId) {
495
472
  super();
496
473
  this.agentId = agentId;
497
474
  }
475
+ /**
476
+ * Executes the given operation with retry logic.
477
+ * @template T
478
+ * @param {() => Promise<T>} operation - The operation to be executed.
479
+ * @returns {Promise<T>} A promise that resolves with the result of the operation.
480
+ */
498
481
  async withRetry(operation) {
499
482
  let lastError = new Error("Unknown error");
500
483
  for (let attempt = 1; attempt <= this.maxRetries; attempt++) {
@@ -516,7 +499,6 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
516
499
  nextRetryIn: `${(delay / 1e3).toFixed(1)}s`
517
500
  }
518
501
  );
519
- console.trace("****** Database operation failure source");
520
502
  await new Promise((resolve) => setTimeout(resolve, delay));
521
503
  } else {
522
504
  logger.error("Max retry attempts reached:", {
@@ -529,6 +511,14 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
529
511
  }
530
512
  throw lastError;
531
513
  }
514
+ /**
515
+ * Ensure that an agent exists by checking if an agent with the same name already exists in the system.
516
+ * If the agent does not exist, it will be created with the provided data.
517
+ *
518
+ * @param {Partial<Agent>} agent - The partial data of the agent to ensure its existence.
519
+ * @returns {Promise<void>} - A promise that resolves when the agent is successfully ensured.
520
+ * @throws {Error} - If the agent name is not provided or if there is an issue creating the agent.
521
+ */
532
522
  async ensureAgentExists(agent) {
533
523
  if (!agent.name) {
534
524
  throw new Error("Agent name is required");
@@ -541,6 +531,12 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
541
531
  await this.createAgent(agent);
542
532
  }
543
533
  }
534
+ /**
535
+ * Ensure that the given embedding dimension is valid for the agent.
536
+ *
537
+ * @param {number} dimension - The dimension to ensure for the embedding.
538
+ * @returns {Promise<void>} - Resolves once the embedding dimension is ensured.
539
+ */
544
540
  async ensureEmbeddingDimension(dimension) {
545
541
  const existingMemory = await this.db.select({
546
542
  embedding: embeddingTable
@@ -549,12 +545,14 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
549
545
  const usedDimension = Object.entries(DIMENSION_MAP).find(
550
546
  ([_, colName]) => existingMemory[0].embedding[colName] !== null
551
547
  );
552
- if (usedDimension && usedDimension[1] !== DIMENSION_MAP[dimension]) {
553
- throw new Error("Cannot change embedding dimension for agent");
554
- }
555
548
  }
556
549
  this.embeddingDimension = DIMENSION_MAP[dimension];
557
550
  }
551
+ /**
552
+ * Asynchronously retrieves an agent by their ID from the database.
553
+ * @param {UUID} agentId - The ID of the agent to retrieve.
554
+ * @returns {Promise<Agent | null>} A promise that resolves to the retrieved agent or null if not found.
555
+ */
558
556
  async getAgent(agentId) {
559
557
  return this.withDatabase(async () => {
560
558
  const result = await this.db.select().from(agentTable).where(eq(agentTable.id, agentId)).limit(1);
@@ -562,12 +560,23 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
562
560
  return result[0];
563
561
  });
564
562
  }
563
+ /**
564
+ * Asynchronously retrieves a list of agents from the database.
565
+ *
566
+ * @returns {Promise<Agent[]>} A Promise that resolves to an array of Agent objects.
567
+ */
565
568
  async getAgents() {
566
569
  return this.withDatabase(async () => {
567
570
  const result = await this.db.select().from(agentTable);
568
571
  return result;
569
572
  });
570
573
  }
574
+ /**
575
+ * Asynchronously creates a new agent record in the database.
576
+ *
577
+ * @param {Partial<Agent>} agent The agent object to be created.
578
+ * @returns {Promise<boolean>} A promise that resolves to a boolean indicating the success of the operation.
579
+ */
571
580
  async createAgent(agent) {
572
581
  return this.withDatabase(async () => {
573
582
  try {
@@ -590,6 +599,12 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
590
599
  }
591
600
  });
592
601
  }
602
+ /**
603
+ * Updates an agent in the database with the provided agent ID and data.
604
+ * @param {UUID} agentId - The unique identifier of the agent to update.
605
+ * @param {Partial<Agent>} agent - The partial agent object containing the fields to update.
606
+ * @returns {Promise<boolean>} - A boolean indicating if the agent was successfully updated.
607
+ */
593
608
  async updateAgent(agentId, agent) {
594
609
  return this.withDatabase(async () => {
595
610
  try {
@@ -616,6 +631,12 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
616
631
  }
617
632
  });
618
633
  }
634
+ /**
635
+ * Asynchronously deletes an agent with the specified UUID and all related entries.
636
+ *
637
+ * @param {UUID} agentId - The UUID of the agent to be deleted.
638
+ * @returns {Promise<boolean>} - A boolean indicating if the deletion was successful.
639
+ */
619
640
  async deleteAgent(agentId) {
620
641
  return this.withDatabase(async () => {
621
642
  await this.db.transaction(async (tx) => {
@@ -628,6 +649,10 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
628
649
  * Count all agents in the database
629
650
  * Used primarily for maintenance and cleanup operations
630
651
  */
652
+ /**
653
+ * Asynchronously counts the number of agents in the database.
654
+ * @returns {Promise<number>} A Promise that resolves to the number of agents in the database.
655
+ */
631
656
  async countAgents() {
632
657
  return this.withDatabase(async () => {
633
658
  try {
@@ -730,11 +755,12 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
730
755
  return true;
731
756
  });
732
757
  } catch (error) {
733
- logger.error("Error creating account:", {
758
+ logger.error("Error creating entity:", {
734
759
  error: error instanceof Error ? error.message : String(error),
735
760
  entityId: entity.id,
736
761
  name: entity.metadata?.name
737
762
  });
763
+ console.trace(error);
738
764
  return false;
739
765
  }
740
766
  });
@@ -947,7 +973,7 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
947
973
  async getCachedEmbeddings(opts) {
948
974
  return this.withDatabase(async () => {
949
975
  try {
950
- const results = await this.db.execute(sql13`
976
+ const results = await this.db.execute(sql12`
951
977
  WITH content_text AS (
952
978
  SELECT
953
979
  m.id,
@@ -1004,7 +1030,7 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1004
1030
  try {
1005
1031
  await this.db.transaction(async (tx) => {
1006
1032
  await tx.insert(logTable).values({
1007
- body: sql13`${params.body}::jsonb`,
1033
+ body: sql12`${params.body}::jsonb`,
1008
1034
  entityId: params.entityId,
1009
1035
  roomId: params.roomId,
1010
1036
  type: params.type
@@ -1030,30 +1056,12 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1030
1056
  tableName: params.tableName
1031
1057
  });
1032
1058
  }
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
1059
  async searchMemoriesByEmbedding(embedding, params) {
1052
1060
  return this.withDatabase(async () => {
1053
1061
  const cleanVector = embedding.map(
1054
1062
  (n) => Number.isFinite(n) ? Number(n.toFixed(6)) : 0
1055
1063
  );
1056
- const similarity = sql13`1 - (${cosineDistance(
1064
+ const similarity = sql12`1 - (${cosineDistance(
1057
1065
  embeddingTable[this.embeddingDimension],
1058
1066
  cleanVector
1059
1067
  )})`;
@@ -1113,8 +1121,8 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1113
1121
  {
1114
1122
  id: memoryId,
1115
1123
  type: tableName,
1116
- content: sql13`${contentToInsert}::jsonb`,
1117
- metadata: sql13`${memory.metadata || {}}::jsonb`,
1124
+ content: sql12`${contentToInsert}::jsonb`,
1125
+ metadata: sql12`${memory.metadata || {}}::jsonb`,
1118
1126
  entityId: memory.entityId,
1119
1127
  roomId: memory.roomId,
1120
1128
  agentId: memory.agentId,
@@ -1191,103 +1199,10 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1191
1199
  if (unique7) {
1192
1200
  conditions.push(eq(memoryTable.unique, true));
1193
1201
  }
1194
- const result = await this.db.select({ count: sql13`count(*)` }).from(memoryTable).where(and(...conditions));
1202
+ const result = await this.db.select({ count: sql12`count(*)` }).from(memoryTable).where(and(...conditions));
1195
1203
  return Number(result[0]?.count ?? 0);
1196
1204
  });
1197
1205
  }
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
1206
  async getRoom(roomId) {
1292
1207
  return this.withDatabase(async () => {
1293
1208
  const result = await this.db.select({
@@ -1566,7 +1481,9 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1566
1481
  if (params.tags && params.tags.length > 0) {
1567
1482
  const tagParams = params.tags.map((tag) => `'${tag.replace(/'/g, "''")}'`).join(", ");
1568
1483
  query = query.where(
1569
- sql13`${relationshipTable.tags} @> ARRAY[${sql13.raw(tagParams)}]::text[]`
1484
+ sql12`${relationshipTable.tags} @> ARRAY[${sql12.raw(
1485
+ tagParams
1486
+ )}]::text[]`
1570
1487
  );
1571
1488
  }
1572
1489
  const results = await query;
@@ -1727,7 +1644,7 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1727
1644
  if (params.tags && params.tags.length > 0) {
1728
1645
  const tagParams = params.tags.map((tag) => `'${tag.replace(/'/g, "''")}'`).join(", ");
1729
1646
  query = query.where(
1730
- sql13`${taskTable.tags} @> ARRAY[${sql13.raw(tagParams)}]::text[]`
1647
+ sql12`${taskTable.tags} @> ARRAY[${sql12.raw(tagParams)}]::text[]`
1731
1648
  );
1732
1649
  }
1733
1650
  const result = await query;
@@ -1847,13 +1764,28 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1847
1764
 
1848
1765
  // src/pg-lite/adapter.ts
1849
1766
  var PgliteDatabaseAdapter = class extends BaseDrizzleAdapter {
1767
+ static {
1768
+ __name(this, "PgliteDatabaseAdapter");
1769
+ }
1850
1770
  manager;
1851
1771
  embeddingDimension = DIMENSION_MAP[384];
1772
+ /**
1773
+ * Constructor for creating an instance of a class.
1774
+ * @param {UUID} agentId - The unique identifier for the agent.
1775
+ * @param {PGliteClientManager} manager - The manager for the PGlite client.
1776
+ */
1852
1777
  constructor(agentId, manager) {
1853
1778
  super(agentId);
1854
1779
  this.manager = manager;
1855
1780
  this.db = drizzle(this.manager.getConnection());
1856
1781
  }
1782
+ /**
1783
+ * Asynchronously runs the provided database operation while checking if the database manager is currently shutting down.
1784
+ * If the database manager is shutting down, a warning is logged and null is returned.
1785
+ *
1786
+ * @param {Function} operation - The database operation to be performed.
1787
+ * @returns {Promise<T>} A promise that resolves with the result of the database operation.
1788
+ */
1857
1789
  async withDatabase(operation) {
1858
1790
  if (this.manager.isShuttingDown()) {
1859
1791
  logger2.warn("Database is shutting down");
@@ -1861,6 +1793,11 @@ var PgliteDatabaseAdapter = class extends BaseDrizzleAdapter {
1861
1793
  }
1862
1794
  return operation();
1863
1795
  }
1796
+ /**
1797
+ * Asynchronously initializes the database by running migrations using the manager.
1798
+ *
1799
+ * @returns {Promise<void>} A Promise that resolves when the database initialization is complete.
1800
+ */
1864
1801
  async init() {
1865
1802
  try {
1866
1803
  await this.manager.runMigrations();
@@ -1869,123 +1806,44 @@ var PgliteDatabaseAdapter = class extends BaseDrizzleAdapter {
1869
1806
  throw error;
1870
1807
  }
1871
1808
  }
1809
+ /**
1810
+ * Asynchronously closes the manager.
1811
+ */
1872
1812
  async close() {
1873
1813
  await this.manager.close();
1874
1814
  }
1875
1815
  };
1876
1816
 
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
1817
  // src/pg/adapter.ts
1975
- import { logger as logger4 } from "@elizaos/core";
1976
- import { drizzle as drizzle3 } from "drizzle-orm/node-postgres";
1818
+ import { logger as logger3 } from "@elizaos/core";
1819
+ import { drizzle as drizzle2 } from "drizzle-orm/node-postgres";
1977
1820
  var PgDatabaseAdapter = class extends BaseDrizzleAdapter {
1821
+ /**
1822
+ * Constructor for creating a new instance of a class.
1823
+ * @param {UUID} agentId - The unique identifier for the agent.
1824
+ * @param {PostgresConnectionManager} manager - The Postgres connection manager for the instance.
1825
+ */
1978
1826
  constructor(agentId, manager) {
1979
1827
  super(agentId);
1980
1828
  this.manager = manager;
1981
1829
  this.manager = manager;
1982
1830
  }
1831
+ static {
1832
+ __name(this, "PgDatabaseAdapter");
1833
+ }
1983
1834
  embeddingDimension = DIMENSION_MAP[384];
1835
+ /**
1836
+ * Executes the provided operation with a database connection.
1837
+ *
1838
+ * @template T
1839
+ * @param {() => Promise<T>} operation - The operation to be executed with the database connection.
1840
+ * @returns {Promise<T>} A promise that resolves with the result of the operation.
1841
+ */
1984
1842
  async withDatabase(operation) {
1985
1843
  return await this.withRetry(async () => {
1986
1844
  const client = await this.manager.getClient();
1987
1845
  try {
1988
- const db = drizzle3(client);
1846
+ const db = drizzle2(client);
1989
1847
  this.db = db;
1990
1848
  return await operation();
1991
1849
  } finally {
@@ -1993,157 +1851,52 @@ var PgDatabaseAdapter = class extends BaseDrizzleAdapter {
1993
1851
  }
1994
1852
  });
1995
1853
  }
1854
+ /**
1855
+ * Asynchronously initializes the PgDatabaseAdapter by running migrations using the manager.
1856
+ * Logs a success message if initialization is successful, otherwise logs an error message.
1857
+ *
1858
+ * @returns {Promise<void>} A promise that resolves when initialization is complete.
1859
+ */
1996
1860
  async init() {
1997
1861
  try {
1998
1862
  await this.manager.runMigrations();
1999
- logger4.info("PgDatabaseAdapter initialized successfully");
1863
+ logger3.info("PgDatabaseAdapter initialized successfully");
2000
1864
  } catch (error) {
2001
- logger4.error("Failed to initialize PgDatabaseAdapter:", error);
1865
+ logger3.error("Failed to initialize PgDatabaseAdapter:", error);
2002
1866
  throw error;
2003
1867
  }
2004
1868
  }
1869
+ /**
1870
+ * Asynchronously closes the manager associated with this instance.
1871
+ *
1872
+ * @returns A Promise that resolves once the manager is closed.
1873
+ */
2005
1874
  async close() {
2006
1875
  await this.manager.close();
2007
1876
  }
2008
1877
  };
2009
1878
 
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
1879
  // src/index.ts
2142
1880
  var pgLiteClientManager;
1881
+ var postgresConnectionManager;
1882
+ function expandTildePath(filepath) {
1883
+ if (filepath && typeof filepath === "string" && filepath.startsWith("~")) {
1884
+ return filepath.replace(/^~/, os.homedir());
1885
+ }
1886
+ return filepath;
1887
+ }
1888
+ __name(expandTildePath, "expandTildePath");
2143
1889
  function createDatabaseAdapter(config, agentId) {
1890
+ if (config.dataDir) {
1891
+ config.dataDir = expandTildePath(config.dataDir);
1892
+ }
2144
1893
  if (config.postgresUrl) {
2145
- const manager = new PostgresConnectionManager(config.postgresUrl);
2146
- return new PgDatabaseAdapter(agentId, manager);
1894
+ if (!postgresConnectionManager) {
1895
+ postgresConnectionManager = new PostgresConnectionManager(
1896
+ config.postgresUrl
1897
+ );
1898
+ }
1899
+ return new PgDatabaseAdapter(agentId, postgresConnectionManager);
2147
1900
  }
2148
1901
  const dataDir = config.dataDir ?? "./elizadb";
2149
1902
  if (!pgLiteClientManager) {
@@ -2151,23 +1904,24 @@ function createDatabaseAdapter(config, agentId) {
2151
1904
  }
2152
1905
  return new PgliteDatabaseAdapter(agentId, pgLiteClientManager);
2153
1906
  }
1907
+ __name(createDatabaseAdapter, "createDatabaseAdapter");
2154
1908
  var drizzlePlugin = {
2155
1909
  name: "drizzle",
2156
1910
  description: "Database adapter plugin using Drizzle ORM",
2157
- init: async (_, runtime) => {
1911
+ init: /* @__PURE__ */ __name(async (_, runtime) => {
2158
1912
  const config = {
2159
1913
  dataDir: runtime.getSetting("PGLITE_DATA_DIR") ?? "./pglite",
2160
1914
  postgresUrl: runtime.getSetting("POSTGRES_URL")
2161
1915
  };
2162
1916
  try {
2163
1917
  const db = createDatabaseAdapter(config, runtime.agentId);
2164
- logger6.success("Database connection established successfully");
1918
+ logger4.success("Database connection established successfully");
2165
1919
  runtime.registerDatabaseAdapter(db);
2166
1920
  } catch (error) {
2167
- logger6.error("Failed to initialize database:", error);
1921
+ logger4.error("Failed to initialize database:", error);
2168
1922
  throw error;
2169
1923
  }
2170
- }
1924
+ }, "init")
2171
1925
  };
2172
1926
  var index_default = drizzlePlugin;
2173
1927
  export {