@elizaos/plugin-sql 1.0.0-alpha.7 → 1.0.0-beta.0

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,15 +1,16 @@
1
1
  import {
2
2
  PGliteClientManager,
3
- PostgresConnectionManager,
3
+ PostgresConnectionManager
4
+ } from "./chunk-PSEXCDLP.js";
5
+ import {
4
6
  __name
5
- } from "./chunk-LLEN3JTK.js";
7
+ } from "./chunk-I3JSTNED.js";
6
8
 
7
9
  // src/index.ts
8
- import {
9
- logger as logger4
10
- } from "@elizaos/core";
10
+ import * as os from "node:os";
11
+ import { logger as logger4 } from "@elizaos/core";
11
12
 
12
- // src/pg-lite/adapter.ts
13
+ // src/pglite/adapter.ts
13
14
  import { logger as logger2 } from "@elizaos/core";
14
15
  import { drizzle } from "drizzle-orm/pglite";
15
16
 
@@ -28,20 +29,13 @@ import {
28
29
  inArray,
29
30
  lte,
30
31
  or,
31
- sql as sql13
32
+ sql as sql12
32
33
  } from "drizzle-orm";
33
34
  import { v4 } from "uuid";
34
35
 
35
36
  // src/schema/embedding.ts
36
37
  import { sql as sql6 } from "drizzle-orm";
37
- import {
38
- check as check2,
39
- foreignKey as foreignKey2,
40
- index as index2,
41
- pgTable as pgTable6,
42
- uuid as uuid6,
43
- vector as vector2
44
- } from "drizzle-orm/pg-core";
38
+ import { check as check2, foreignKey as foreignKey2, index as index2, pgTable as pgTable6, uuid as uuid6, vector as vector2 } from "drizzle-orm/pg-core";
45
39
 
46
40
  // src/schema/memory.ts
47
41
  import { relations, sql as sql5 } from "drizzle-orm";
@@ -58,14 +52,7 @@ import {
58
52
 
59
53
  // src/schema/agent.ts
60
54
  import { sql } from "drizzle-orm";
61
- import {
62
- boolean,
63
- jsonb,
64
- pgTable,
65
- text,
66
- unique,
67
- uuid
68
- } from "drizzle-orm/pg-core";
55
+ import { boolean, jsonb, pgTable, text, unique, uuid } from "drizzle-orm/pg-core";
69
56
 
70
57
  // src/schema/types.ts
71
58
  import { customType } from "drizzle-orm/pg-core";
@@ -80,28 +67,26 @@ var stringJsonb = customType({
80
67
  return JSON.stringify(value);
81
68
  }
82
69
  });
83
- var numberTimestamp = customType(
84
- {
85
- dataType() {
86
- return "timestamptz";
87
- },
88
- toDriver(value) {
89
- return new Date(value).toISOString();
90
- },
91
- fromDriver(value) {
92
- return new Date(value).getTime();
93
- }
70
+ var numberTimestamp = customType({
71
+ dataType() {
72
+ return "timestamptz";
73
+ },
74
+ toDriver(value) {
75
+ return new Date(value).toISOString();
76
+ },
77
+ fromDriver(value) {
78
+ return new Date(value).getTime();
94
79
  }
95
- );
80
+ });
96
81
 
97
82
  // src/schema/agent.ts
98
83
  var agentTable = pgTable(
99
84
  "agents",
100
85
  {
101
86
  id: uuid("id").primaryKey().defaultRandom(),
87
+ enabled: boolean("enabled").default(true).notNull(),
102
88
  createdAt: numberTimestamp("createdAt").default(sql`now()`).notNull(),
103
89
  updatedAt: numberTimestamp("updatedAt").default(sql`now()`).notNull(),
104
- enabled: boolean("enabled").default(true).notNull(),
105
90
  // Character
106
91
  name: text("name"),
107
92
  username: text("username"),
@@ -324,27 +309,18 @@ var componentTable = pgTable8("components", {
324
309
  createdAt: numberTimestamp("createdAt").default(sql8`now()`).notNull()
325
310
  });
326
311
 
327
- // src/schema/goal.ts
312
+ // src/schema/log.ts
328
313
  import { sql as sql9 } from "drizzle-orm";
329
314
  import { foreignKey as foreignKey3, jsonb as jsonb8, pgTable as pgTable9, text as text8, uuid as uuid9 } from "drizzle-orm/pg-core";
330
- var goalTable = pgTable9(
331
- "goals",
315
+ var logTable = pgTable9(
316
+ "logs",
332
317
  {
333
- id: uuid9("id").notNull().primaryKey().default(sql9`gen_random_uuid()`),
318
+ id: uuid9("id").defaultRandom().notNull(),
334
319
  createdAt: numberTimestamp("createdAt").default(sql9`now()`).notNull(),
335
- entityId: uuid9("entityId").references(() => entityTable.id, {
336
- onDelete: "cascade"
337
- }),
338
- agentId: uuid9("agentId").references(() => agentTable.id, {
339
- onDelete: "cascade"
340
- }),
341
- name: text8("name"),
342
- status: text8("status"),
343
- description: text8("description"),
344
- roomId: uuid9("roomId").references(() => roomTable.id, {
345
- onDelete: "cascade"
346
- }),
347
- objectives: jsonb8("objectives").default("[]").notNull()
320
+ entityId: uuid9("entityId").notNull().references(() => entityTable.id),
321
+ body: jsonb8("body").notNull(),
322
+ type: text8("type").notNull(),
323
+ roomId: uuid9("roomId").notNull().references(() => roomTable.id)
348
324
  },
349
325
  (table) => [
350
326
  foreignKey3({
@@ -360,68 +336,35 @@ var goalTable = pgTable9(
360
336
  ]
361
337
  );
362
338
 
363
- // src/schema/log.ts
364
- import { sql as sql10 } from "drizzle-orm";
365
- import { foreignKey as foreignKey4, jsonb as jsonb9, pgTable as pgTable10, text as text9, uuid as uuid10 } from "drizzle-orm/pg-core";
366
- var logTable = pgTable10(
367
- "logs",
368
- {
369
- id: uuid10("id").defaultRandom().notNull(),
370
- createdAt: numberTimestamp("createdAt").default(sql10`now()`).notNull(),
371
- entityId: uuid10("entityId").notNull().references(() => entityTable.id),
372
- body: jsonb9("body").notNull(),
373
- type: text9("type").notNull(),
374
- roomId: uuid10("roomId").notNull().references(() => roomTable.id)
375
- },
376
- (table) => [
377
- foreignKey4({
378
- name: "fk_room",
379
- columns: [table.roomId],
380
- foreignColumns: [roomTable.id]
381
- }).onDelete("cascade"),
382
- foreignKey4({
383
- name: "fk_user",
384
- columns: [table.entityId],
385
- foreignColumns: [entityTable.id]
386
- }).onDelete("cascade")
387
- ]
388
- );
389
-
390
339
  // src/schema/participant.ts
391
- import { sql as sql11 } from "drizzle-orm";
392
- import {
393
- foreignKey as foreignKey5,
394
- index as index3,
395
- pgTable as pgTable11,
396
- text as text10,
397
- uuid as uuid11
398
- } from "drizzle-orm/pg-core";
399
- var participantTable = pgTable11(
340
+ import { sql as sql10 } from "drizzle-orm";
341
+ import { foreignKey as foreignKey4, index as index3, pgTable as pgTable10, text as text9, uuid as uuid10 } from "drizzle-orm/pg-core";
342
+ var participantTable = pgTable10(
400
343
  "participants",
401
344
  {
402
- id: uuid11("id").notNull().primaryKey().default(sql11`gen_random_uuid()`),
403
- createdAt: numberTimestamp("createdAt").default(sql11`now()`).notNull(),
404
- entityId: uuid11("entityId").references(() => entityTable.id, {
345
+ id: uuid10("id").notNull().primaryKey().default(sql10`gen_random_uuid()`),
346
+ createdAt: numberTimestamp("createdAt").default(sql10`now()`).notNull(),
347
+ entityId: uuid10("entityId").references(() => entityTable.id, {
405
348
  onDelete: "cascade"
406
349
  }),
407
- roomId: uuid11("roomId").references(() => roomTable.id, {
350
+ roomId: uuid10("roomId").references(() => roomTable.id, {
408
351
  onDelete: "cascade"
409
352
  }),
410
- agentId: uuid11("agentId").references(() => agentTable.id, {
353
+ agentId: uuid10("agentId").references(() => agentTable.id, {
411
354
  onDelete: "cascade"
412
355
  }),
413
- roomState: text10("roomState")
356
+ roomState: text9("roomState")
414
357
  },
415
358
  (table) => [
416
359
  // unique("participants_user_room_agent_unique").on(table.entityId, table.roomId, table.agentId),
417
360
  index3("idx_participants_user").on(table.entityId),
418
361
  index3("idx_participants_room").on(table.roomId),
419
- foreignKey5({
362
+ foreignKey4({
420
363
  name: "fk_room",
421
364
  columns: [table.roomId],
422
365
  foreignColumns: [roomTable.id]
423
366
  }).onDelete("cascade"),
424
- foreignKey5({
367
+ foreignKey4({
425
368
  name: "fk_user",
426
369
  columns: [table.entityId],
427
370
  foreignColumns: [entityTable.id]
@@ -430,43 +373,28 @@ var participantTable = pgTable11(
430
373
  );
431
374
 
432
375
  // src/schema/relationship.ts
433
- import { sql as sql12 } from "drizzle-orm";
434
- import {
435
- foreignKey as foreignKey6,
436
- index as index4,
437
- jsonb as jsonb10,
438
- pgTable as pgTable12,
439
- text as text11,
440
- unique as unique6,
441
- uuid as uuid12
442
- } from "drizzle-orm/pg-core";
443
- var relationshipTable = pgTable12(
376
+ import { sql as sql11 } from "drizzle-orm";
377
+ import { foreignKey as foreignKey5, index as index4, jsonb as jsonb9, pgTable as pgTable11, text as text10, unique as unique6, uuid as uuid11 } from "drizzle-orm/pg-core";
378
+ var relationshipTable = pgTable11(
444
379
  "relationships",
445
380
  {
446
- id: uuid12("id").notNull().primaryKey().default(sql12`gen_random_uuid()`),
447
- createdAt: numberTimestamp("createdAt").default(sql12`now()`).notNull(),
448
- sourceEntityId: uuid12("sourceEntityId").notNull().references(() => entityTable.id, { onDelete: "cascade" }),
449
- targetEntityId: uuid12("targetEntityId").notNull().references(() => entityTable.id, { onDelete: "cascade" }),
450
- agentId: uuid12("agentId").notNull().references(() => agentTable.id, { onDelete: "cascade" }),
451
- tags: text11("tags").array(),
452
- metadata: jsonb10("metadata")
381
+ id: uuid11("id").notNull().primaryKey().default(sql11`gen_random_uuid()`),
382
+ createdAt: numberTimestamp("createdAt").default(sql11`now()`).notNull(),
383
+ sourceEntityId: uuid11("sourceEntityId").notNull().references(() => entityTable.id, { onDelete: "cascade" }),
384
+ targetEntityId: uuid11("targetEntityId").notNull().references(() => entityTable.id, { onDelete: "cascade" }),
385
+ agentId: uuid11("agentId").notNull().references(() => agentTable.id, { onDelete: "cascade" }),
386
+ tags: text10("tags").array(),
387
+ metadata: jsonb9("metadata")
453
388
  },
454
389
  (table) => [
455
- index4("idx_relationships_users").on(
456
- table.sourceEntityId,
457
- table.targetEntityId
458
- ),
459
- unique6("unique_relationship").on(
460
- table.sourceEntityId,
461
- table.targetEntityId,
462
- table.agentId
463
- ),
464
- foreignKey6({
390
+ index4("idx_relationships_users").on(table.sourceEntityId, table.targetEntityId),
391
+ unique6("unique_relationship").on(table.sourceEntityId, table.targetEntityId, table.agentId),
392
+ foreignKey5({
465
393
  name: "fk_user_a",
466
394
  columns: [table.sourceEntityId],
467
395
  foreignColumns: [entityTable.id]
468
396
  }).onDelete("cascade"),
469
- foreignKey6({
397
+ foreignKey5({
470
398
  name: "fk_user_b",
471
399
  columns: [table.targetEntityId],
472
400
  foreignColumns: [entityTable.id]
@@ -475,16 +403,16 @@ var relationshipTable = pgTable12(
475
403
  );
476
404
 
477
405
  // src/schema/tasks.ts
478
- import { jsonb as jsonb11, pgTable as pgTable13, text as text12, timestamp, uuid as uuid13 } from "drizzle-orm/pg-core";
479
- var taskTable = pgTable13("tasks", {
480
- id: uuid13("id").primaryKey().defaultRandom(),
481
- name: text12("name").notNull(),
482
- description: text12("description").notNull(),
483
- roomId: uuid13("room_id"),
484
- worldId: uuid13("world_id"),
485
- agentId: uuid13("agent_id").notNull(),
486
- tags: text12("tags").array(),
487
- metadata: jsonb11("metadata"),
406
+ import { jsonb as jsonb10, pgTable as pgTable12, text as text11, timestamp, uuid as uuid12 } from "drizzle-orm/pg-core";
407
+ var taskTable = pgTable12("tasks", {
408
+ id: uuid12("id").primaryKey().defaultRandom(),
409
+ name: text11("name").notNull(),
410
+ description: text11("description").notNull(),
411
+ roomId: uuid12("room_id"),
412
+ worldId: uuid12("world_id"),
413
+ agentId: uuid12("agent_id").notNull(),
414
+ tags: text11("tags").array(),
415
+ metadata: jsonb10("metadata"),
488
416
  createdAt: timestamp("created_at").defaultNow(),
489
417
  updatedAt: timestamp("updated_at").defaultNow()
490
418
  });
@@ -523,20 +451,13 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
523
451
  } catch (error) {
524
452
  lastError = error;
525
453
  if (attempt < this.maxRetries) {
526
- const backoffDelay = Math.min(
527
- this.baseDelay * 2 ** (attempt - 1),
528
- this.maxDelay
529
- );
454
+ const backoffDelay = Math.min(this.baseDelay * 2 ** (attempt - 1), this.maxDelay);
530
455
  const jitter = Math.random() * this.jitterMax;
531
456
  const delay = backoffDelay + jitter;
532
- logger.warn(
533
- `Database operation failed (attempt ${attempt}/${this.maxRetries}):`,
534
- {
535
- error: error instanceof Error ? error.message : String(error),
536
- nextRetryIn: `${(delay / 1e3).toFixed(1)}s`
537
- }
538
- );
539
- console.trace("****** Database operation failure source");
457
+ logger.warn(`Database operation failed (attempt ${attempt}/${this.maxRetries}):`, {
458
+ error: error instanceof Error ? error.message : String(error),
459
+ nextRetryIn: `${(delay / 1e3).toFixed(1)}s`
460
+ });
540
461
  await new Promise((resolve) => setTimeout(resolve, delay));
541
462
  } else {
542
463
  logger.error("Max retry attempts reached:", {
@@ -550,7 +471,7 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
550
471
  throw lastError;
551
472
  }
552
473
  /**
553
- * Ensure that an agent exists by checking if an agent with the same name already exists in the system.
474
+ * Asynchronously ensures that an agent exists by checking if an agent with the same name already exists in the system.
554
475
  * If the agent does not exist, it will be created with the provided data.
555
476
  *
556
477
  * @param {Partial<Agent>} agent - The partial data of the agent to ensure its existence.
@@ -570,7 +491,7 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
570
491
  }
571
492
  }
572
493
  /**
573
- * Ensure that the given embedding dimension is valid for the agent.
494
+ * Asynchronously ensures that the given embedding dimension is valid for the agent.
574
495
  *
575
496
  * @param {number} dimension - The dimension to ensure for the embedding.
576
497
  * @returns {Promise<void>} - Resolves once the embedding dimension is ensured.
@@ -583,9 +504,6 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
583
504
  const usedDimension = Object.entries(DIMENSION_MAP).find(
584
505
  ([_, colName]) => existingMemory[0].embedding[colName] !== null
585
506
  );
586
- if (usedDimension && usedDimension[1] !== DIMENSION_MAP[dimension]) {
587
- throw new Error("Cannot change embedding dimension for agent");
588
- }
589
507
  }
590
508
  this.embeddingDimension = DIMENSION_MAP[dimension];
591
509
  }
@@ -725,23 +643,29 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
725
643
  }
726
644
  });
727
645
  }
646
+ /**
647
+ * Asynchronously retrieves an entity and its components by entity ID.
648
+ * @param {UUID} entityId - The unique identifier of the entity to retrieve.
649
+ * @returns {Promise<Entity | null>} A Promise that resolves to the entity with its components if found, null otherwise.
650
+ */
728
651
  async getEntityById(entityId) {
729
652
  return this.withDatabase(async () => {
730
653
  const result = await this.db.select({
731
654
  entity: entityTable,
732
655
  components: componentTable
733
- }).from(entityTable).leftJoin(componentTable, eq(componentTable.entityId, entityTable.id)).where(
734
- and(
735
- eq(entityTable.id, entityId),
736
- eq(entityTable.agentId, this.agentId)
737
- )
738
- );
656
+ }).from(entityTable).leftJoin(componentTable, eq(componentTable.entityId, entityTable.id)).where(and(eq(entityTable.id, entityId), eq(entityTable.agentId, this.agentId)));
739
657
  if (result.length === 0) return null;
740
658
  const entity = result[0].entity;
741
659
  entity.components = result.filter((row) => row.components).map((row) => row.components);
742
660
  return entity;
743
661
  });
744
662
  }
663
+ /**
664
+ * Asynchronously retrieves all entities for a given room, optionally including their components.
665
+ * @param {UUID} roomId - The unique identifier of the room to get entities for
666
+ * @param {boolean} [includeComponents] - Whether to include component data for each entity
667
+ * @returns {Promise<Entity[]>} A Promise that resolves to an array of entities in the room
668
+ */
745
669
  async getEntitiesForRoom(roomId, includeComponents) {
746
670
  return this.withDatabase(async () => {
747
671
  const query = this.db.select({
@@ -749,16 +673,10 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
749
673
  ...includeComponents && { components: componentTable }
750
674
  }).from(participantTable).leftJoin(
751
675
  entityTable,
752
- and(
753
- eq(participantTable.entityId, entityTable.id),
754
- eq(entityTable.agentId, this.agentId)
755
- )
676
+ and(eq(participantTable.entityId, entityTable.id), eq(entityTable.agentId, this.agentId))
756
677
  );
757
678
  if (includeComponents) {
758
- query.leftJoin(
759
- componentTable,
760
- eq(componentTable.entityId, entityTable.id)
761
- );
679
+ query.leftJoin(componentTable, eq(componentTable.entityId, entityTable.id));
762
680
  }
763
681
  const result = await query.where(eq(participantTable.roomId, roomId));
764
682
  const entitiesByIdMap = /* @__PURE__ */ new Map();
@@ -785,6 +703,11 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
785
703
  return Array.from(entitiesByIdMap.values());
786
704
  });
787
705
  }
706
+ /**
707
+ * Asynchronously creates a new entity in the database.
708
+ * @param {Entity} entity - The entity object to be created.
709
+ * @returns {Promise<boolean>} A Promise that resolves to a boolean indicating the success of the operation.
710
+ */
788
711
  async createEntity(entity) {
789
712
  return this.withDatabase(async () => {
790
713
  try {
@@ -801,13 +724,13 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
801
724
  entityId: entity.id,
802
725
  name: entity.metadata?.name
803
726
  });
804
- console.trace(error);
727
+ logger.trace(error);
805
728
  return false;
806
729
  }
807
730
  });
808
731
  }
809
732
  /**
810
- * Ensures an entity exists, creating it if it doesn't
733
+ * Asynchronously ensures an entity exists, creating it if it doesn't
811
734
  * @param entity The entity to ensure exists
812
735
  * @returns Promise resolving to boolean indicating success
813
736
  */
@@ -830,22 +753,19 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
830
753
  return false;
831
754
  }
832
755
  }
756
+ /**
757
+ * Asynchronously updates an entity in the database.
758
+ * @param {Entity} entity - The entity object to be updated.
759
+ * @returns {Promise<void>} A Promise that resolves when the entity is updated.
760
+ */
833
761
  async updateEntity(entity) {
834
762
  return this.withDatabase(async () => {
835
- await this.db.update(entityTable).set(entity).where(
836
- and(
837
- eq(entityTable.id, entity.id),
838
- eq(entityTable.agentId, entity.agentId)
839
- )
840
- );
763
+ await this.db.update(entityTable).set(entity).where(and(eq(entityTable.id, entity.id), eq(entityTable.agentId, entity.agentId)));
841
764
  });
842
765
  }
843
766
  async getComponent(entityId, type, worldId, sourceEntityId) {
844
767
  return this.withDatabase(async () => {
845
- const conditions = [
846
- eq(componentTable.entityId, entityId),
847
- eq(componentTable.type, type)
848
- ];
768
+ const conditions = [eq(componentTable.entityId, entityId), eq(componentTable.type, type)];
849
769
  if (worldId) {
850
770
  conditions.push(eq(componentTable.worldId, worldId));
851
771
  }
@@ -856,6 +776,13 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
856
776
  return result.length > 0 ? result[0] : null;
857
777
  });
858
778
  }
779
+ /**
780
+ * Asynchronously retrieves all components for a given entity, optionally filtered by world and source entity.
781
+ * @param {UUID} entityId - The unique identifier of the entity to retrieve components for
782
+ * @param {UUID} [worldId] - Optional world ID to filter components by
783
+ * @param {UUID} [sourceEntityId] - Optional source entity ID to filter components by
784
+ * @returns {Promise<Component[]>} A Promise that resolves to an array of components
785
+ */
859
786
  async getComponents(entityId, worldId, sourceEntityId) {
860
787
  return this.withDatabase(async () => {
861
788
  const conditions = [eq(componentTable.entityId, entityId)];
@@ -877,40 +804,73 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
877
804
  return result;
878
805
  });
879
806
  }
807
+ /**
808
+ * Asynchronously creates a new component in the database.
809
+ * @param {Component} component - The component object to be created.
810
+ * @returns {Promise<boolean>} A Promise that resolves to a boolean indicating the success of the operation.
811
+ */
880
812
  async createComponent(component) {
881
813
  return this.withDatabase(async () => {
882
814
  await this.db.insert(componentTable).values(component);
883
815
  return true;
884
816
  });
885
817
  }
818
+ /**
819
+ * Asynchronously updates an existing component in the database.
820
+ * @param {Component} component - The component object to be updated.
821
+ * @returns {Promise<void>} A Promise that resolves when the component is updated.
822
+ */
886
823
  async updateComponent(component) {
887
824
  return this.withDatabase(async () => {
888
825
  await this.db.update(componentTable).set(component).where(eq(componentTable.id, component.id));
889
826
  });
890
827
  }
828
+ /**
829
+ * Asynchronously deletes a component from the database.
830
+ * @param {UUID} componentId - The unique identifier of the component to delete.
831
+ * @returns {Promise<void>} A Promise that resolves when the component is deleted.
832
+ */
891
833
  async deleteComponent(componentId) {
892
834
  return this.withDatabase(async () => {
893
835
  await this.db.delete(componentTable).where(eq(componentTable.id, componentId));
894
836
  });
895
837
  }
838
+ /**
839
+ * Asynchronously retrieves memories from the database based on the provided parameters.
840
+ * @param {Object} params - The parameters for retrieving memories.
841
+ * @param {UUID} params.roomId - The ID of the room to retrieve memories for.
842
+ * @param {number} [params.count] - The maximum number of memories to retrieve.
843
+ * @param {boolean} [params.unique] - Whether to retrieve unique memories only.
844
+ * @param {string} [params.tableName] - The name of the table to retrieve memories from.
845
+ * @param {number} [params.start] - The start date to retrieve memories from.
846
+ * @param {number} [params.end] - The end date to retrieve memories from.
847
+ * @returns {Promise<Memory[]>} A Promise that resolves to an array of memories.
848
+ */
896
849
  async getMemories(params) {
897
- if (!params.tableName) throw new Error("tableName is required");
898
- if (!params.roomId) throw new Error("roomId is required");
850
+ const { entityId, agentId, roomId, tableName, count: count2, unique: unique7, start, end } = params;
851
+ if (!tableName) throw new Error("tableName is required");
852
+ if (!roomId && !entityId && !agentId)
853
+ throw new Error("roomId, entityId, or agentId is required");
899
854
  return this.withDatabase(async () => {
900
- const conditions = [
901
- eq(memoryTable.type, params.tableName),
902
- eq(memoryTable.roomId, params.roomId)
903
- ];
904
- if (params.start) {
905
- conditions.push(gte(memoryTable.createdAt, params.start));
855
+ const conditions = [eq(memoryTable.type, tableName)];
856
+ if (start) {
857
+ conditions.push(gte(memoryTable.createdAt, start));
906
858
  }
907
- if (params.end) {
908
- conditions.push(lte(memoryTable.createdAt, params.end));
859
+ if (entityId) {
860
+ conditions.push(eq(memoryTable.entityId, entityId));
909
861
  }
910
- if (params.unique) {
862
+ if (roomId) {
863
+ conditions.push(eq(memoryTable.roomId, roomId));
864
+ }
865
+ if (end) {
866
+ conditions.push(lte(memoryTable.createdAt, end));
867
+ }
868
+ if (unique7) {
911
869
  conditions.push(eq(memoryTable.unique, true));
912
870
  }
913
- conditions.push(eq(memoryTable.agentId, this.agentId));
871
+ if (agentId) {
872
+ conditions.push(eq(memoryTable.agentId, agentId));
873
+ }
914
874
  const query = this.db.select({
915
875
  memory: {
916
876
  id: memoryTable.id,
@@ -920,7 +880,8 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
920
880
  entityId: memoryTable.entityId,
921
881
  agentId: memoryTable.agentId,
922
882
  roomId: memoryTable.roomId,
923
- unique: memoryTable.unique
883
+ unique: memoryTable.unique,
884
+ metadata: memoryTable.metadata
924
885
  },
925
886
  embedding: embeddingTable[this.embeddingDimension]
926
887
  }).from(memoryTable).leftJoin(embeddingTable, eq(embeddingTable.memoryId, memoryTable.id)).where(and(...conditions)).orderBy(desc(memoryTable.createdAt));
@@ -934,10 +895,19 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
934
895
  agentId: row.memory.agentId,
935
896
  roomId: row.memory.roomId,
936
897
  unique: row.memory.unique,
898
+ metadata: row.memory.metadata,
937
899
  embedding: row.embedding ? Array.from(row.embedding) : void 0
938
900
  }));
939
901
  });
940
902
  }
903
+ /**
904
+ * Asynchronously retrieves memories from the database based on the provided parameters.
905
+ * @param {Object} params - The parameters for retrieving memories.
906
+ * @param {UUID[]} params.roomIds - The IDs of the rooms to retrieve memories for.
907
+ * @param {string} params.tableName - The name of the table to retrieve memories from.
908
+ * @param {number} [params.limit] - The maximum number of memories to retrieve.
909
+ * @returns {Promise<Memory[]>} A Promise that resolves to an array of memories.
910
+ */
941
911
  async getMemoriesByRoomIds(params) {
942
912
  return this.withDatabase(async () => {
943
913
  if (params.roomIds.length === 0) return [];
@@ -954,7 +924,8 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
954
924
  entityId: memoryTable.entityId,
955
925
  agentId: memoryTable.agentId,
956
926
  roomId: memoryTable.roomId,
957
- unique: memoryTable.unique
927
+ unique: memoryTable.unique,
928
+ metadata: memoryTable.metadata
958
929
  }).from(memoryTable).where(and(...conditions)).orderBy(desc(memoryTable.createdAt));
959
930
  const rows = params.limit ? await query.limit(params.limit) : await query;
960
931
  return rows.map((row) => ({
@@ -964,10 +935,16 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
964
935
  entityId: row.entityId,
965
936
  agentId: row.agentId,
966
937
  roomId: row.roomId,
967
- unique: row.unique
938
+ unique: row.unique,
939
+ metadata: row.metadata
968
940
  }));
969
941
  });
970
942
  }
943
+ /**
944
+ * Asynchronously retrieves a memory by its unique identifier.
945
+ * @param {UUID} id - The unique identifier of the memory to retrieve.
946
+ * @returns {Promise<Memory | null>} A Promise that resolves to the memory if found, null otherwise.
947
+ */
971
948
  async getMemoryById(id) {
972
949
  return this.withDatabase(async () => {
973
950
  const result = await this.db.select({
@@ -988,6 +965,13 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
988
965
  };
989
966
  });
990
967
  }
968
+ /**
969
+ * Asynchronously retrieves memories from the database based on the provided parameters.
970
+ * @param {Object} params - The parameters for retrieving memories.
971
+ * @param {UUID[]} params.memoryIds - The IDs of the memories to retrieve.
972
+ * @param {string} [params.tableName] - The name of the table to retrieve memories from.
973
+ * @returns {Promise<Memory[]>} A Promise that resolves to an array of memories.
974
+ */
991
975
  async getMemoriesByIds(memoryIds, tableName) {
992
976
  return this.withDatabase(async () => {
993
977
  if (memoryIds.length === 0) return [];
@@ -1007,14 +991,26 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1007
991
  agentId: row.memory.agentId,
1008
992
  roomId: row.memory.roomId,
1009
993
  unique: row.memory.unique,
994
+ metadata: row.memory.metadata,
1010
995
  embedding: row.embedding ?? void 0
1011
996
  }));
1012
997
  });
1013
998
  }
999
+ /**
1000
+ * Asynchronously retrieves cached embeddings from the database based on the provided parameters.
1001
+ * @param {Object} opts - The parameters for retrieving cached embeddings.
1002
+ * @param {string} opts.query_table_name - The name of the table to retrieve embeddings from.
1003
+ * @param {number} opts.query_threshold - The threshold for the levenshtein distance.
1004
+ * @param {string} opts.query_input - The input string to search for.
1005
+ * @param {string} opts.query_field_name - The name of the field to retrieve embeddings from.
1006
+ * @param {string} opts.query_field_sub_name - The name of the sub-field to retrieve embeddings from.
1007
+ * @param {number} opts.query_match_count - The maximum number of matches to retrieve.
1008
+ * @returns {Promise<{ embedding: number[]; levenshtein_score: number }[]>} A Promise that resolves to an array of cached embeddings.
1009
+ */
1014
1010
  async getCachedEmbeddings(opts) {
1015
1011
  return this.withDatabase(async () => {
1016
1012
  try {
1017
- const results = await this.db.execute(sql13`
1013
+ const results = await this.db.execute(sql12`
1018
1014
  WITH content_text AS (
1019
1015
  SELECT
1020
1016
  m.id,
@@ -1066,12 +1062,21 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1066
1062
  }
1067
1063
  });
1068
1064
  }
1065
+ /**
1066
+ * Asynchronously logs an event in the database.
1067
+ * @param {Object} params - The parameters for logging an event.
1068
+ * @param {Object} params.body - The body of the event to log.
1069
+ * @param {UUID} params.entityId - The ID of the entity associated with the event.
1070
+ * @param {UUID} params.roomId - The ID of the room associated with the event.
1071
+ * @param {string} params.type - The type of the event to log.
1072
+ * @returns {Promise<void>} A Promise that resolves when the event is logged.
1073
+ */
1069
1074
  async log(params) {
1070
1075
  return this.withDatabase(async () => {
1071
1076
  try {
1072
1077
  await this.db.transaction(async (tx) => {
1073
1078
  await tx.insert(logTable).values({
1074
- body: sql13`${params.body}::jsonb`,
1079
+ body: sql12`${params.body}::jsonb`,
1075
1080
  entityId: params.entityId,
1076
1081
  roomId: params.roomId,
1077
1082
  type: params.type
@@ -1088,6 +1093,50 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1088
1093
  }
1089
1094
  });
1090
1095
  }
1096
+ /**
1097
+ * Asynchronously retrieves logs from the database based on the provided parameters.
1098
+ * @param {Object} params - The parameters for retrieving logs.
1099
+ * @param {UUID} params.entityId - The ID of the entity associated with the logs.
1100
+ * @param {UUID} [params.roomId] - The ID of the room associated with the logs.
1101
+ * @param {string} [params.type] - The type of the logs to retrieve.
1102
+ * @param {number} [params.count] - The maximum number of logs to retrieve.
1103
+ * @param {number} [params.offset] - The offset to retrieve logs from.
1104
+ * @returns {Promise<Log[]>} A Promise that resolves to an array of logs.
1105
+ */
1106
+ async getLogs(params) {
1107
+ const { entityId, roomId, type, count: count2, offset } = params;
1108
+ return this.withDatabase(async () => {
1109
+ const result = await this.db.select().from(logTable).where(
1110
+ and(
1111
+ eq(logTable.entityId, entityId),
1112
+ roomId ? eq(logTable.roomId, roomId) : void 0,
1113
+ type ? eq(logTable.type, type) : void 0
1114
+ )
1115
+ ).orderBy(desc(logTable.createdAt)).limit(count2 ?? 10).offset(offset ?? 0);
1116
+ return result;
1117
+ });
1118
+ }
1119
+ /**
1120
+ * Asynchronously deletes a log from the database based on the provided parameters.
1121
+ * @param {UUID} logId - The ID of the log to delete.
1122
+ * @returns {Promise<void>} A Promise that resolves when the log is deleted.
1123
+ */
1124
+ async deleteLog(logId) {
1125
+ return this.withDatabase(async () => {
1126
+ await this.db.delete(logTable).where(eq(logTable.id, logId));
1127
+ });
1128
+ }
1129
+ /**
1130
+ * Asynchronously searches for memories in the database based on the provided parameters.
1131
+ * @param {Object} params - The parameters for searching for memories.
1132
+ * @param {string} params.tableName - The name of the table to search for memories in.
1133
+ * @param {UUID} params.roomId - The ID of the room to search for memories in.
1134
+ * @param {number[]} params.embedding - The embedding to search for.
1135
+ * @param {number} [params.match_threshold] - The threshold for the cosine distance.
1136
+ * @param {number} [params.count] - The maximum number of memories to retrieve.
1137
+ * @param {boolean} [params.unique] - Whether to retrieve unique memories only.
1138
+ * @returns {Promise<Memory[]>} A Promise that resolves to an array of memories.
1139
+ */
1091
1140
  async searchMemories(params) {
1092
1141
  return await this.searchMemoriesByEmbedding(params.embedding, {
1093
1142
  match_threshold: params.match_threshold,
@@ -1097,30 +1146,21 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1097
1146
  tableName: params.tableName
1098
1147
  });
1099
1148
  }
1100
- async updateGoalStatus(params) {
1101
- return this.withDatabase(async () => {
1102
- try {
1103
- await this.db.transaction(async (tx) => {
1104
- await tx.update(goalTable).set({
1105
- status: params.status
1106
- }).where(eq(goalTable.id, params.goalId));
1107
- });
1108
- } catch (error) {
1109
- logger.error("Failed to update goal status:", {
1110
- goalId: params.goalId,
1111
- status: params.status,
1112
- error: error instanceof Error ? error.message : String(error)
1113
- });
1114
- throw error;
1115
- }
1116
- });
1117
- }
1149
+ /**
1150
+ * Asynchronously searches for memories in the database based on the provided parameters.
1151
+ * @param {number[]} embedding - The embedding to search for.
1152
+ * @param {Object} params - The parameters for searching for memories.
1153
+ * @param {number} [params.match_threshold] - The threshold for the cosine distance.
1154
+ * @param {number} [params.count] - The maximum number of memories to retrieve.
1155
+ * @param {UUID} [params.roomId] - The ID of the room to search for memories in.
1156
+ * @param {boolean} [params.unique] - Whether to retrieve unique memories only.
1157
+ * @param {string} [params.tableName] - The name of the table to search for memories in.
1158
+ * @returns {Promise<Memory[]>} A Promise that resolves to an array of memories.
1159
+ */
1118
1160
  async searchMemoriesByEmbedding(embedding, params) {
1119
1161
  return this.withDatabase(async () => {
1120
- const cleanVector = embedding.map(
1121
- (n) => Number.isFinite(n) ? Number(n.toFixed(6)) : 0
1122
- );
1123
- const similarity = sql13`1 - (${cosineDistance(
1162
+ const cleanVector = embedding.map((n) => Number.isFinite(n) ? Number(n.toFixed(6)) : 0);
1163
+ const similarity = sql12`1 - (${cosineDistance(
1124
1164
  embeddingTable[this.embeddingDimension],
1125
1165
  cleanVector
1126
1166
  )})`;
@@ -1149,11 +1189,18 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1149
1189
  agentId: row.memory.agentId,
1150
1190
  roomId: row.memory.roomId,
1151
1191
  unique: row.memory.unique,
1192
+ metadata: row.memory.metadata,
1152
1193
  embedding: row.embedding ?? void 0,
1153
1194
  similarity: row.similarity
1154
1195
  }));
1155
1196
  });
1156
1197
  }
1198
+ /**
1199
+ * Asynchronously creates a new memory in the database.
1200
+ * @param {Memory & { metadata?: MemoryMetadata }} memory - The memory object to create.
1201
+ * @param {string} tableName - The name of the table to create the memory in.
1202
+ * @returns {Promise<UUID>} A Promise that resolves to the ID of the created memory.
1203
+ */
1157
1204
  async createMemory(memory, tableName) {
1158
1205
  logger.debug("DrizzleAdapter createMemory:", {
1159
1206
  memoryId: memory.id,
@@ -1162,15 +1209,12 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1162
1209
  });
1163
1210
  let isUnique = true;
1164
1211
  if (memory.embedding && Array.isArray(memory.embedding)) {
1165
- const similarMemories = await this.searchMemoriesByEmbedding(
1166
- memory.embedding,
1167
- {
1168
- tableName,
1169
- roomId: memory.roomId,
1170
- match_threshold: 0.95,
1171
- count: 1
1172
- }
1173
- );
1212
+ const similarMemories = await this.searchMemoriesByEmbedding(memory.embedding, {
1213
+ tableName,
1214
+ roomId: memory.roomId,
1215
+ match_threshold: 0.95,
1216
+ count: 1
1217
+ });
1174
1218
  isUnique = similarMemories.length === 0;
1175
1219
  }
1176
1220
  const contentToInsert = typeof memory.content === "string" ? JSON.parse(memory.content) : memory.content;
@@ -1180,8 +1224,8 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1180
1224
  {
1181
1225
  id: memoryId,
1182
1226
  type: tableName,
1183
- content: sql13`${contentToInsert}::jsonb`,
1184
- metadata: sql13`${memory.metadata || {}}::jsonb`,
1227
+ content: sql12`${contentToInsert}::jsonb`,
1228
+ metadata: sql12`${memory.metadata || {}}::jsonb`,
1185
1229
  entityId: memory.entityId,
1186
1230
  roomId: memory.roomId,
1187
1231
  agentId: memory.agentId,
@@ -1204,29 +1248,124 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1204
1248
  });
1205
1249
  return memoryId;
1206
1250
  }
1207
- async removeMemory(memoryId, tableName) {
1251
+ /**
1252
+ * Updates an existing memory in the database.
1253
+ * @param memory The memory object with updated content and optional embedding
1254
+ * @returns Promise resolving to boolean indicating success
1255
+ */
1256
+ async updateMemory(memory) {
1257
+ return this.withDatabase(async () => {
1258
+ try {
1259
+ logger.debug("Updating memory:", {
1260
+ memoryId: memory.id,
1261
+ hasEmbedding: !!memory.embedding
1262
+ });
1263
+ await this.db.transaction(async (tx) => {
1264
+ if (memory.content) {
1265
+ const contentToUpdate = typeof memory.content === "string" ? JSON.parse(memory.content) : memory.content;
1266
+ await tx.update(memoryTable).set({
1267
+ content: sql12`${contentToUpdate}::jsonb`,
1268
+ ...memory.metadata && { metadata: sql12`${memory.metadata}::jsonb` }
1269
+ }).where(eq(memoryTable.id, memory.id));
1270
+ } else if (memory.metadata) {
1271
+ await tx.update(memoryTable).set({
1272
+ metadata: sql12`${memory.metadata}::jsonb`
1273
+ }).where(eq(memoryTable.id, memory.id));
1274
+ }
1275
+ if (memory.embedding && Array.isArray(memory.embedding)) {
1276
+ const cleanVector = memory.embedding.map(
1277
+ (n) => Number.isFinite(n) ? Number(n.toFixed(6)) : 0
1278
+ );
1279
+ const existingEmbedding = await tx.select({ id: embeddingTable.id }).from(embeddingTable).where(eq(embeddingTable.memoryId, memory.id)).limit(1);
1280
+ if (existingEmbedding.length > 0) {
1281
+ const updateValues = {};
1282
+ updateValues[this.embeddingDimension] = cleanVector;
1283
+ await tx.update(embeddingTable).set(updateValues).where(eq(embeddingTable.memoryId, memory.id));
1284
+ } else {
1285
+ const embeddingValues = {
1286
+ id: v4(),
1287
+ memoryId: memory.id,
1288
+ createdAt: Date.now()
1289
+ };
1290
+ embeddingValues[this.embeddingDimension] = cleanVector;
1291
+ await tx.insert(embeddingTable).values([embeddingValues]);
1292
+ }
1293
+ }
1294
+ });
1295
+ logger.debug("Memory updated successfully:", {
1296
+ memoryId: memory.id
1297
+ });
1298
+ return true;
1299
+ } catch (error) {
1300
+ logger.error("Error updating memory:", {
1301
+ error: error instanceof Error ? error.message : String(error),
1302
+ memoryId: memory.id
1303
+ });
1304
+ return false;
1305
+ }
1306
+ });
1307
+ }
1308
+ /**
1309
+ * Asynchronously deletes a memory from the database based on the provided parameters.
1310
+ * @param {UUID} memoryId - The ID of the memory to delete.
1311
+ * @returns {Promise<void>} A Promise that resolves when the memory is deleted.
1312
+ */
1313
+ async deleteMemory(memoryId) {
1208
1314
  return this.withDatabase(async () => {
1209
1315
  await this.db.transaction(async (tx) => {
1316
+ await this.deleteMemoryFragments(tx, memoryId);
1210
1317
  await tx.delete(embeddingTable).where(eq(embeddingTable.memoryId, memoryId));
1211
- await tx.delete(memoryTable).where(
1212
- and(eq(memoryTable.id, memoryId), eq(memoryTable.type, tableName))
1213
- );
1318
+ await tx.delete(memoryTable).where(eq(memoryTable.id, memoryId));
1214
1319
  });
1215
- logger.debug("Memory removed successfully:", {
1216
- memoryId,
1217
- tableName
1320
+ logger.debug("Memory and related fragments removed successfully:", {
1321
+ memoryId
1218
1322
  });
1219
1323
  });
1220
1324
  }
1221
- async removeAllMemories(roomId, tableName) {
1325
+ /**
1326
+ * Deletes all memory fragments that reference a specific document memory
1327
+ * @param tx The database transaction
1328
+ * @param documentId The UUID of the document memory whose fragments should be deleted
1329
+ * @private
1330
+ */
1331
+ async deleteMemoryFragments(tx, documentId) {
1332
+ const fragmentsToDelete = await this.getMemoryFragments(tx, documentId);
1333
+ if (fragmentsToDelete.length > 0) {
1334
+ const fragmentIds = fragmentsToDelete.map((f) => f.id);
1335
+ await tx.delete(embeddingTable).where(inArray(embeddingTable.memoryId, fragmentIds));
1336
+ await tx.delete(memoryTable).where(inArray(memoryTable.id, fragmentIds));
1337
+ logger.debug("Deleted related fragments:", {
1338
+ documentId,
1339
+ fragmentCount: fragmentsToDelete.length
1340
+ });
1341
+ }
1342
+ }
1343
+ /**
1344
+ * Retrieves all memory fragments that reference a specific document memory
1345
+ * @param tx The database transaction
1346
+ * @param documentId The UUID of the document memory whose fragments should be retrieved
1347
+ * @returns An array of memory fragments
1348
+ * @private
1349
+ */
1350
+ async getMemoryFragments(tx, documentId) {
1351
+ const fragments = await tx.select({ id: memoryTable.id }).from(memoryTable).where(
1352
+ and(
1353
+ eq(memoryTable.agentId, this.agentId),
1354
+ sql12`${memoryTable.metadata}->>'documentId' = ${documentId}`
1355
+ )
1356
+ );
1357
+ return fragments;
1358
+ }
1359
+ /**
1360
+ * Asynchronously deletes all memories from the database based on the provided parameters.
1361
+ * @param {UUID} roomId - The ID of the room to delete memories from.
1362
+ * @param {string} tableName - The name of the table to delete memories from.
1363
+ * @returns {Promise<void>} A Promise that resolves when the memories are deleted.
1364
+ */
1365
+ async deleteAllMemories(roomId, tableName) {
1222
1366
  return this.withDatabase(async () => {
1223
1367
  await this.db.transaction(async (tx) => {
1224
- const memoryIds = await tx.select({ id: memoryTable.id }).from(memoryTable).where(
1225
- and(
1226
- eq(memoryTable.roomId, roomId),
1227
- eq(memoryTable.type, tableName)
1228
- )
1229
- );
1368
+ const memoryIds = await tx.select({ id: memoryTable.id }).from(memoryTable).where(and(eq(memoryTable.roomId, roomId), eq(memoryTable.type, tableName)));
1230
1369
  if (memoryIds.length > 0) {
1231
1370
  await tx.delete(embeddingTable).where(
1232
1371
  inArray(
@@ -1234,12 +1373,7 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1234
1373
  memoryIds.map((m) => m.id)
1235
1374
  )
1236
1375
  );
1237
- await tx.delete(memoryTable).where(
1238
- and(
1239
- eq(memoryTable.roomId, roomId),
1240
- eq(memoryTable.type, tableName)
1241
- )
1242
- );
1376
+ await tx.delete(memoryTable).where(and(eq(memoryTable.roomId, roomId), eq(memoryTable.type, tableName)));
1243
1377
  }
1244
1378
  });
1245
1379
  logger.debug("All memories removed successfully:", {
@@ -1248,113 +1382,29 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1248
1382
  });
1249
1383
  });
1250
1384
  }
1385
+ /**
1386
+ * Asynchronously counts the number of memories in the database based on the provided parameters.
1387
+ * @param {UUID} roomId - The ID of the room to count memories in.
1388
+ * @param {boolean} [unique] - Whether to count unique memories only.
1389
+ * @param {string} [tableName] - The name of the table to count memories in.
1390
+ * @returns {Promise<number>} A Promise that resolves to the number of memories.
1391
+ */
1251
1392
  async countMemories(roomId, unique7 = true, tableName = "") {
1252
1393
  if (!tableName) throw new Error("tableName is required");
1253
1394
  return this.withDatabase(async () => {
1254
- const conditions = [
1255
- eq(memoryTable.roomId, roomId),
1256
- eq(memoryTable.type, tableName)
1257
- ];
1395
+ const conditions = [eq(memoryTable.roomId, roomId), eq(memoryTable.type, tableName)];
1258
1396
  if (unique7) {
1259
1397
  conditions.push(eq(memoryTable.unique, true));
1260
1398
  }
1261
- const result = await this.db.select({ count: sql13`count(*)` }).from(memoryTable).where(and(...conditions));
1399
+ const result = await this.db.select({ count: sql12`count(*)` }).from(memoryTable).where(and(...conditions));
1262
1400
  return Number(result[0]?.count ?? 0);
1263
1401
  });
1264
1402
  }
1265
- async getGoals(params) {
1266
- return this.withDatabase(async () => {
1267
- const conditions = [eq(goalTable.roomId, params.roomId)];
1268
- if (params.entityId) {
1269
- conditions.push(eq(goalTable.entityId, params.entityId));
1270
- }
1271
- if (params.onlyInProgress) {
1272
- conditions.push(eq(goalTable.status, "IN_PROGRESS"));
1273
- }
1274
- const query = this.db.select().from(goalTable).where(and(...conditions)).orderBy(desc(goalTable.createdAt));
1275
- const result = await (params.count ? query.limit(params.count) : query);
1276
- return result.map((row) => ({
1277
- id: row.id,
1278
- roomId: row.roomId,
1279
- entityId: row.entityId,
1280
- name: row.name ?? "",
1281
- status: row.status ?? "NOT_STARTED",
1282
- description: row.description ?? "",
1283
- objectives: row.objectives,
1284
- createdAt: row.createdAt
1285
- }));
1286
- });
1287
- }
1288
- async updateGoal(goal) {
1289
- return this.withDatabase(async () => {
1290
- try {
1291
- await this.db.transaction(async (tx) => {
1292
- await tx.update(goalTable).set({
1293
- name: goal.name,
1294
- status: goal.status,
1295
- objectives: goal.objectives
1296
- }).where(eq(goalTable.id, goal.id));
1297
- });
1298
- } catch (error) {
1299
- logger.error("Failed to update goal:", {
1300
- error: error instanceof Error ? error.message : String(error),
1301
- goalId: goal.id,
1302
- status: goal.status
1303
- });
1304
- throw error;
1305
- }
1306
- });
1307
- }
1308
- async createGoal(goal) {
1309
- return this.withDatabase(async () => {
1310
- try {
1311
- await this.db.transaction(async (tx) => {
1312
- await tx.insert(goalTable).values({
1313
- id: goal.id ?? v4(),
1314
- roomId: goal.roomId,
1315
- entityId: goal.entityId,
1316
- name: goal.name,
1317
- status: goal.status,
1318
- objectives: sql13`${goal.objectives}::jsonb`
1319
- });
1320
- });
1321
- } catch (error) {
1322
- logger.error("Failed to update goal:", {
1323
- goalId: goal.id,
1324
- error: error instanceof Error ? error.message : String(error),
1325
- status: goal.status
1326
- });
1327
- throw error;
1328
- }
1329
- });
1330
- }
1331
- async removeGoal(goalId) {
1332
- if (!goalId) throw new Error("Goal ID is required");
1333
- return this.withDatabase(async () => {
1334
- try {
1335
- await this.db.transaction(async (tx) => {
1336
- await tx.delete(goalTable).where(eq(goalTable.id, goalId));
1337
- });
1338
- logger.debug("Goal removal attempt:", {
1339
- goalId,
1340
- removed: true
1341
- });
1342
- } catch (error) {
1343
- logger.error("Failed to remove goal:", {
1344
- error: error instanceof Error ? error.message : String(error),
1345
- goalId
1346
- });
1347
- throw error;
1348
- }
1349
- });
1350
- }
1351
- async removeAllGoals(roomId) {
1352
- return this.withDatabase(async () => {
1353
- await this.db.transaction(async (tx) => {
1354
- await tx.delete(goalTable).where(eq(goalTable.roomId, roomId));
1355
- });
1356
- });
1357
- }
1403
+ /**
1404
+ * Asynchronously retrieves a room from the database based on the provided parameters.
1405
+ * @param {UUID} roomId - The ID of the room to retrieve.
1406
+ * @returns {Promise<Room | null>} A Promise that resolves to the room if found, null otherwise.
1407
+ */
1358
1408
  async getRoom(roomId) {
1359
1409
  return this.withDatabase(async () => {
1360
1410
  const result = await this.db.select({
@@ -1365,33 +1415,38 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1365
1415
  worldId: roomTable.worldId,
1366
1416
  type: roomTable.type,
1367
1417
  source: roomTable.source
1368
- }).from(roomTable).where(
1369
- and(eq(roomTable.id, roomId), eq(roomTable.agentId, this.agentId))
1370
- ).limit(1);
1418
+ }).from(roomTable).where(and(eq(roomTable.id, roomId), eq(roomTable.agentId, this.agentId))).limit(1);
1371
1419
  if (result.length === 0) return null;
1372
1420
  return result[0];
1373
1421
  });
1374
1422
  }
1423
+ /**
1424
+ * Asynchronously retrieves all rooms from the database based on the provided parameters.
1425
+ * @param {UUID} worldId - The ID of the world to retrieve rooms from.
1426
+ * @returns {Promise<Room[]>} A Promise that resolves to an array of rooms.
1427
+ */
1375
1428
  async getRooms(worldId) {
1376
1429
  return this.withDatabase(async () => {
1377
1430
  const result = await this.db.select().from(roomTable).where(eq(roomTable.worldId, worldId));
1378
1431
  return result;
1379
1432
  });
1380
1433
  }
1434
+ /**
1435
+ * Asynchronously updates a room in the database based on the provided parameters.
1436
+ * @param {Room} room - The room object to update.
1437
+ * @returns {Promise<void>} A Promise that resolves when the room is updated.
1438
+ */
1381
1439
  async updateRoom(room) {
1382
1440
  return this.withDatabase(async () => {
1383
1441
  await this.db.update(roomTable).set({ ...room, agentId: this.agentId }).where(eq(roomTable.id, room.id));
1384
1442
  });
1385
1443
  }
1386
- async createRoom({
1387
- id,
1388
- name,
1389
- source,
1390
- type,
1391
- channelId,
1392
- serverId,
1393
- worldId
1394
- }) {
1444
+ /**
1445
+ * Asynchronously creates a new room in the database based on the provided parameters.
1446
+ * @param {Room} room - The room object to create.
1447
+ * @returns {Promise<UUID>} A Promise that resolves to the ID of the created room.
1448
+ */
1449
+ async createRoom({ id, name, source, type, channelId, serverId, worldId }) {
1395
1450
  return this.withDatabase(async () => {
1396
1451
  const newRoomId = id || v4();
1397
1452
  await this.db.insert(roomTable).values({
@@ -1407,6 +1462,11 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1407
1462
  return newRoomId;
1408
1463
  });
1409
1464
  }
1465
+ /**
1466
+ * Asynchronously deletes a room from the database based on the provided parameters.
1467
+ * @param {UUID} roomId - The ID of the room to delete.
1468
+ * @returns {Promise<void>} A Promise that resolves when the room is deleted.
1469
+ */
1410
1470
  async deleteRoom(roomId) {
1411
1471
  if (!roomId) throw new Error("Room ID is required");
1412
1472
  return this.withDatabase(async () => {
@@ -1415,28 +1475,36 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1415
1475
  });
1416
1476
  });
1417
1477
  }
1478
+ /**
1479
+ * Asynchronously retrieves all rooms for a participant from the database based on the provided parameters.
1480
+ * @param {UUID} entityId - The ID of the entity to retrieve rooms for.
1481
+ * @returns {Promise<UUID[]>} A Promise that resolves to an array of room IDs.
1482
+ */
1418
1483
  async getRoomsForParticipant(entityId) {
1419
1484
  return this.withDatabase(async () => {
1420
- const result = await this.db.select({ roomId: participantTable.roomId }).from(participantTable).innerJoin(roomTable, eq(participantTable.roomId, roomTable.id)).where(
1421
- and(
1422
- eq(participantTable.entityId, entityId),
1423
- eq(roomTable.agentId, this.agentId)
1424
- )
1425
- );
1485
+ const result = await this.db.select({ roomId: participantTable.roomId }).from(participantTable).innerJoin(roomTable, eq(participantTable.roomId, roomTable.id)).where(and(eq(participantTable.entityId, entityId), eq(roomTable.agentId, this.agentId)));
1426
1486
  return result.map((row) => row.roomId);
1427
1487
  });
1428
1488
  }
1489
+ /**
1490
+ * Asynchronously retrieves all rooms for a list of participants from the database based on the provided parameters.
1491
+ * @param {UUID[]} entityIds - The IDs of the entities to retrieve rooms for.
1492
+ * @returns {Promise<UUID[]>} A Promise that resolves to an array of room IDs.
1493
+ */
1429
1494
  async getRoomsForParticipants(entityIds) {
1430
1495
  return this.withDatabase(async () => {
1431
1496
  const result = await this.db.selectDistinct({ roomId: participantTable.roomId }).from(participantTable).innerJoin(roomTable, eq(participantTable.roomId, roomTable.id)).where(
1432
- and(
1433
- inArray(participantTable.entityId, entityIds),
1434
- eq(roomTable.agentId, this.agentId)
1435
- )
1497
+ and(inArray(participantTable.entityId, entityIds), eq(roomTable.agentId, this.agentId))
1436
1498
  );
1437
1499
  return result.map((row) => row.roomId);
1438
1500
  });
1439
1501
  }
1502
+ /**
1503
+ * Asynchronously adds a participant to a room in the database based on the provided parameters.
1504
+ * @param {UUID} entityId - The ID of the entity to add to the room.
1505
+ * @param {UUID} roomId - The ID of the room to add the entity to.
1506
+ * @returns {Promise<boolean>} A Promise that resolves to a boolean indicating whether the participant was added successfully.
1507
+ */
1440
1508
  async addParticipant(entityId, roomId) {
1441
1509
  return this.withDatabase(async () => {
1442
1510
  try {
@@ -1457,15 +1525,18 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1457
1525
  }
1458
1526
  });
1459
1527
  }
1528
+ /**
1529
+ * Asynchronously removes a participant from a room in the database based on the provided parameters.
1530
+ * @param {UUID} entityId - The ID of the entity to remove from the room.
1531
+ * @param {UUID} roomId - The ID of the room to remove the entity from.
1532
+ * @returns {Promise<boolean>} A Promise that resolves to a boolean indicating whether the participant was removed successfully.
1533
+ */
1460
1534
  async removeParticipant(entityId, roomId) {
1461
1535
  return this.withDatabase(async () => {
1462
1536
  try {
1463
1537
  const result = await this.db.transaction(async (tx) => {
1464
1538
  return await tx.delete(participantTable).where(
1465
- and(
1466
- eq(participantTable.entityId, entityId),
1467
- eq(participantTable.roomId, roomId)
1468
- )
1539
+ and(eq(participantTable.entityId, entityId), eq(participantTable.roomId, roomId))
1469
1540
  ).returning();
1470
1541
  });
1471
1542
  const removed = result.length > 0;
@@ -1485,6 +1556,11 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1485
1556
  }
1486
1557
  });
1487
1558
  }
1559
+ /**
1560
+ * Asynchronously retrieves all participants for an entity from the database based on the provided parameters.
1561
+ * @param {UUID} entityId - The ID of the entity to retrieve participants for.
1562
+ * @returns {Promise<Participant[]>} A Promise that resolves to an array of participants.
1563
+ */
1488
1564
  async getParticipantsForEntity(entityId) {
1489
1565
  return this.withDatabase(async () => {
1490
1566
  const result = await this.db.select({
@@ -1502,17 +1578,25 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1502
1578
  }));
1503
1579
  });
1504
1580
  }
1581
+ /**
1582
+ * Asynchronously retrieves all participants for a room from the database based on the provided parameters.
1583
+ * @param {UUID} roomId - The ID of the room to retrieve participants for.
1584
+ * @returns {Promise<UUID[]>} A Promise that resolves to an array of entity IDs.
1585
+ */
1505
1586
  async getParticipantsForRoom(roomId) {
1506
1587
  return this.withDatabase(async () => {
1507
1588
  const result = await this.db.select({ entityId: participantTable.entityId }).from(participantTable).where(
1508
- and(
1509
- eq(participantTable.roomId, roomId),
1510
- eq(participantTable.agentId, this.agentId)
1511
- )
1589
+ and(eq(participantTable.roomId, roomId), eq(participantTable.agentId, this.agentId))
1512
1590
  );
1513
1591
  return result.map((row) => row.entityId);
1514
1592
  });
1515
1593
  }
1594
+ /**
1595
+ * Asynchronously retrieves the user state for a participant in a room from the database based on the provided parameters.
1596
+ * @param {UUID} roomId - The ID of the room to retrieve the participant's user state for.
1597
+ * @param {UUID} entityId - The ID of the entity to retrieve the user state for.
1598
+ * @returns {Promise<"FOLLOWED" | "MUTED" | null>} A Promise that resolves to the participant's user state.
1599
+ */
1516
1600
  async getParticipantUserState(roomId, entityId) {
1517
1601
  return this.withDatabase(async () => {
1518
1602
  const result = await this.db.select({ roomState: participantTable.roomState }).from(participantTable).where(
@@ -1525,6 +1609,13 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1525
1609
  return result[0]?.roomState ?? null;
1526
1610
  });
1527
1611
  }
1612
+ /**
1613
+ * Asynchronously sets the user state for a participant in a room in the database based on the provided parameters.
1614
+ * @param {UUID} roomId - The ID of the room to set the participant's user state for.
1615
+ * @param {UUID} entityId - The ID of the entity to set the user state for.
1616
+ * @param {string} state - The state to set the participant's user state to.
1617
+ * @returns {Promise<void>} A Promise that resolves when the participant's user state is set.
1618
+ */
1528
1619
  async setParticipantUserState(roomId, entityId, state) {
1529
1620
  return this.withDatabase(async () => {
1530
1621
  try {
@@ -1548,6 +1639,15 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1548
1639
  }
1549
1640
  });
1550
1641
  }
1642
+ /**
1643
+ * Asynchronously creates a new relationship in the database based on the provided parameters.
1644
+ * @param {Object} params - The parameters for creating a new relationship.
1645
+ * @param {UUID} params.sourceEntityId - The ID of the source entity.
1646
+ * @param {UUID} params.targetEntityId - The ID of the target entity.
1647
+ * @param {string[]} [params.tags] - The tags for the relationship.
1648
+ * @param {Object} [params.metadata] - The metadata for the relationship.
1649
+ * @returns {Promise<boolean>} A Promise that resolves to a boolean indicating whether the relationship was created successfully.
1650
+ */
1551
1651
  async createRelationship(params) {
1552
1652
  return this.withDatabase(async () => {
1553
1653
  const id = v4();
@@ -1571,6 +1671,11 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1571
1671
  }
1572
1672
  });
1573
1673
  }
1674
+ /**
1675
+ * Asynchronously updates an existing relationship in the database based on the provided parameters.
1676
+ * @param {Relationship} relationship - The relationship object to update.
1677
+ * @returns {Promise<void>} A Promise that resolves when the relationship is updated.
1678
+ */
1574
1679
  async updateRelationship(relationship) {
1575
1680
  return this.withDatabase(async () => {
1576
1681
  try {
@@ -1587,6 +1692,13 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1587
1692
  }
1588
1693
  });
1589
1694
  }
1695
+ /**
1696
+ * Asynchronously retrieves a relationship from the database based on the provided parameters.
1697
+ * @param {Object} params - The parameters for retrieving a relationship.
1698
+ * @param {UUID} params.sourceEntityId - The ID of the source entity.
1699
+ * @param {UUID} params.targetEntityId - The ID of the target entity.
1700
+ * @returns {Promise<Relationship | null>} A Promise that resolves to the relationship if found, null otherwise.
1701
+ */
1590
1702
  async getRelationship(params) {
1591
1703
  return this.withDatabase(async () => {
1592
1704
  try {
@@ -1618,6 +1730,13 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1618
1730
  }
1619
1731
  });
1620
1732
  }
1733
+ /**
1734
+ * Asynchronously retrieves all relationships from the database based on the provided parameters.
1735
+ * @param {Object} params - The parameters for retrieving relationships.
1736
+ * @param {UUID} params.entityId - The ID of the entity to retrieve relationships for.
1737
+ * @param {string[]} [params.tags] - The tags to filter relationships by.
1738
+ * @returns {Promise<Relationship[]>} A Promise that resolves to an array of relationships.
1739
+ */
1621
1740
  async getRelationships(params) {
1622
1741
  return this.withDatabase(async () => {
1623
1742
  try {
@@ -1633,9 +1752,7 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1633
1752
  if (params.tags && params.tags.length > 0) {
1634
1753
  const tagParams = params.tags.map((tag) => `'${tag.replace(/'/g, "''")}'`).join(", ");
1635
1754
  query = query.where(
1636
- sql13`${relationshipTable.tags} @> ARRAY[${sql13.raw(
1637
- tagParams
1638
- )}]::text[]`
1755
+ sql12`${relationshipTable.tags} @> ARRAY[${sql12.raw(tagParams)}]::text[]`
1639
1756
  );
1640
1757
  }
1641
1758
  const results = await query;
@@ -1657,12 +1774,15 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1657
1774
  }
1658
1775
  });
1659
1776
  }
1777
+ /**
1778
+ * Asynchronously retrieves a cache value from the database based on the provided key.
1779
+ * @param {string} key - The key to retrieve the cache value for.
1780
+ * @returns {Promise<T | undefined>} A Promise that resolves to the cache value if found, undefined otherwise.
1781
+ */
1660
1782
  async getCache(key) {
1661
1783
  return this.withDatabase(async () => {
1662
1784
  try {
1663
- const result = await this.db.select().from(cacheTable).where(
1664
- and(eq(cacheTable.agentId, this.agentId), eq(cacheTable.key, key))
1665
- );
1785
+ const result = await this.db.select().from(cacheTable).where(and(eq(cacheTable.agentId, this.agentId), eq(cacheTable.key, key)));
1666
1786
  return result[0]?.value;
1667
1787
  } catch (error) {
1668
1788
  logger.error("Error fetching cache", {
@@ -1674,6 +1794,12 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1674
1794
  }
1675
1795
  });
1676
1796
  }
1797
+ /**
1798
+ * Asynchronously sets a cache value in the database based on the provided key and value.
1799
+ * @param {string} key - The key to set the cache value for.
1800
+ * @param {T} value - The value to set in the cache.
1801
+ * @returns {Promise<boolean>} A Promise that resolves to a boolean indicating whether the cache value was set successfully.
1802
+ */
1677
1803
  async setCache(key, value) {
1678
1804
  return this.withDatabase(async () => {
1679
1805
  try {
@@ -1700,16 +1826,16 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1700
1826
  }
1701
1827
  });
1702
1828
  }
1829
+ /**
1830
+ * Asynchronously deletes a cache value from the database based on the provided key.
1831
+ * @param {string} key - The key to delete the cache value for.
1832
+ * @returns {Promise<boolean>} A Promise that resolves to a boolean indicating whether the cache value was deleted successfully.
1833
+ */
1703
1834
  async deleteCache(key) {
1704
1835
  return this.withDatabase(async () => {
1705
1836
  try {
1706
1837
  await this.db.transaction(async (tx) => {
1707
- await tx.delete(cacheTable).where(
1708
- and(
1709
- eq(cacheTable.agentId, this.agentId),
1710
- eq(cacheTable.key, key)
1711
- )
1712
- );
1838
+ await tx.delete(cacheTable).where(and(eq(cacheTable.agentId, this.agentId), eq(cacheTable.key, key)));
1713
1839
  });
1714
1840
  return true;
1715
1841
  } catch (error) {
@@ -1722,6 +1848,11 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1722
1848
  }
1723
1849
  });
1724
1850
  }
1851
+ /**
1852
+ * Asynchronously creates a new world in the database based on the provided parameters.
1853
+ * @param {World} world - The world object to create.
1854
+ * @returns {Promise<UUID>} A Promise that resolves to the ID of the created world.
1855
+ */
1725
1856
  async createWorld(world) {
1726
1857
  return this.withDatabase(async () => {
1727
1858
  const newWorldId = world.id || v4();
@@ -1732,32 +1863,51 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1732
1863
  return newWorldId;
1733
1864
  });
1734
1865
  }
1866
+ /**
1867
+ * Asynchronously retrieves a world from the database based on the provided parameters.
1868
+ * @param {UUID} id - The ID of the world to retrieve.
1869
+ * @returns {Promise<World | null>} A Promise that resolves to the world if found, null otherwise.
1870
+ */
1735
1871
  async getWorld(id) {
1736
1872
  return this.withDatabase(async () => {
1737
1873
  const result = await this.db.select().from(worldTable).where(eq(worldTable.id, id));
1738
1874
  return result[0];
1739
1875
  });
1740
1876
  }
1877
+ /**
1878
+ * Asynchronously retrieves all worlds from the database based on the provided parameters.
1879
+ * @returns {Promise<World[]>} A Promise that resolves to an array of worlds.
1880
+ */
1741
1881
  async getAllWorlds() {
1742
1882
  return this.withDatabase(async () => {
1743
1883
  const result = await this.db.select().from(worldTable).where(eq(worldTable.agentId, this.agentId));
1744
1884
  return result;
1745
1885
  });
1746
1886
  }
1887
+ /**
1888
+ * Asynchronously updates an existing world in the database based on the provided parameters.
1889
+ * @param {World} world - The world object to update.
1890
+ * @returns {Promise<void>} A Promise that resolves when the world is updated.
1891
+ */
1747
1892
  async updateWorld(world) {
1748
1893
  return this.withDatabase(async () => {
1749
1894
  await this.db.update(worldTable).set(world).where(eq(worldTable.id, world.id));
1750
1895
  });
1751
1896
  }
1897
+ /**
1898
+ * Asynchronously removes a world from the database based on the provided parameters.
1899
+ * @param {UUID} id - The ID of the world to remove.
1900
+ * @returns {Promise<void>} A Promise that resolves when the world is removed.
1901
+ */
1752
1902
  async removeWorld(id) {
1753
1903
  return this.withDatabase(async () => {
1754
1904
  await this.db.delete(worldTable).where(eq(worldTable.id, id));
1755
1905
  });
1756
1906
  }
1757
1907
  /**
1758
- * Creates a new task in the database.
1759
- * @param task The task object to create
1760
- * @returns Promise resolving to the UUID of the created task
1908
+ * Asynchronously creates a new task in the database based on the provided parameters.
1909
+ * @param {Task} task - The task object to create.
1910
+ * @returns {Promise<UUID>} A Promise that resolves to the ID of the created task.
1761
1911
  */
1762
1912
  async createTask(task) {
1763
1913
  return this.withRetry(async () => {
@@ -1782,7 +1932,7 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1782
1932
  });
1783
1933
  }
1784
1934
  /**
1785
- * Retrieves tasks based on specified parameters.
1935
+ * Asynchronously retrieves tasks based on specified parameters.
1786
1936
  * @param params Object containing optional roomId and tags to filter tasks
1787
1937
  * @returns Promise resolving to an array of Task objects
1788
1938
  */
@@ -1795,9 +1945,7 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1795
1945
  }
1796
1946
  if (params.tags && params.tags.length > 0) {
1797
1947
  const tagParams = params.tags.map((tag) => `'${tag.replace(/'/g, "''")}'`).join(", ");
1798
- query = query.where(
1799
- sql13`${taskTable.tags} @> ARRAY[${sql13.raw(tagParams)}]::text[]`
1800
- );
1948
+ query = query.where(sql12`${taskTable.tags} @> ARRAY[${sql12.raw(tagParams)}]::text[]`);
1801
1949
  }
1802
1950
  const result = await query;
1803
1951
  return result.map((row) => ({
@@ -1813,16 +1961,14 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1813
1961
  });
1814
1962
  }
1815
1963
  /**
1816
- * Retrieves a specific task by its name.
1964
+ * Asynchronously retrieves a specific task by its name.
1817
1965
  * @param name The name of the task to retrieve
1818
1966
  * @returns Promise resolving to the Task object if found, null otherwise
1819
1967
  */
1820
1968
  async getTasksByName(name) {
1821
1969
  return this.withRetry(async () => {
1822
1970
  return this.withDatabase(async () => {
1823
- const result = await this.db.select().from(taskTable).where(
1824
- and(eq(taskTable.name, name), eq(taskTable.agentId, this.agentId))
1825
- );
1971
+ const result = await this.db.select().from(taskTable).where(and(eq(taskTable.name, name), eq(taskTable.agentId, this.agentId)));
1826
1972
  return result.map((row) => ({
1827
1973
  id: row.id,
1828
1974
  name: row.name,
@@ -1836,7 +1982,7 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1836
1982
  });
1837
1983
  }
1838
1984
  /**
1839
- * Retrieves a specific task by its ID.
1985
+ * Asynchronously retrieves a specific task by its ID.
1840
1986
  * @param id The UUID of the task to retrieve
1841
1987
  * @returns Promise resolving to the Task object if found, null otherwise
1842
1988
  */
@@ -1861,7 +2007,7 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1861
2007
  });
1862
2008
  }
1863
2009
  /**
1864
- * Updates an existing task in the database.
2010
+ * Asynchronously updates an existing task in the database.
1865
2011
  * @param id The UUID of the task to update
1866
2012
  * @param task Partial Task object containing the fields to update
1867
2013
  * @returns Promise resolving when the update is complete
@@ -1871,8 +2017,7 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1871
2017
  await this.withDatabase(async () => {
1872
2018
  const updateValues = {};
1873
2019
  if (task.name !== void 0) updateValues.name = task.name;
1874
- if (task.description !== void 0)
1875
- updateValues.description = task.description;
2020
+ if (task.description !== void 0) updateValues.description = task.description;
1876
2021
  if (task.roomId !== void 0) updateValues.roomId = task.roomId;
1877
2022
  if (task.worldId !== void 0) updateValues.worldId = task.worldId;
1878
2023
  if (task.tags !== void 0) updateValues.tags = task.tags;
@@ -1892,29 +2037,25 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1892
2037
  };
1893
2038
  }
1894
2039
  }
1895
- await this.db.update(taskTable).set(updateValues).where(
1896
- and(eq(taskTable.id, id), eq(taskTable.agentId, this.agentId))
1897
- );
2040
+ await this.db.update(taskTable).set(updateValues).where(and(eq(taskTable.id, id), eq(taskTable.agentId, this.agentId)));
1898
2041
  });
1899
2042
  });
1900
2043
  }
1901
2044
  /**
1902
- * Deletes a task from the database.
2045
+ * Asynchronously deletes a task from the database.
1903
2046
  * @param id The UUID of the task to delete
1904
2047
  * @returns Promise resolving when the deletion is complete
1905
2048
  */
1906
2049
  async deleteTask(id) {
1907
2050
  await this.withRetry(async () => {
1908
2051
  await this.withDatabase(async () => {
1909
- await this.db.delete(taskTable).where(
1910
- and(eq(taskTable.id, id), eq(taskTable.agentId, this.agentId))
1911
- );
2052
+ await this.db.delete(taskTable).where(and(eq(taskTable.id, id), eq(taskTable.agentId, this.agentId)));
1912
2053
  });
1913
2054
  });
1914
2055
  }
1915
2056
  };
1916
2057
 
1917
- // src/pg-lite/adapter.ts
2058
+ // src/pglite/adapter.ts
1918
2059
  var PgliteDatabaseAdapter = class extends BaseDrizzleAdapter {
1919
2060
  static {
1920
2061
  __name(this, "PgliteDatabaseAdapter");
@@ -2012,7 +2153,7 @@ var PgDatabaseAdapter = class extends BaseDrizzleAdapter {
2012
2153
  async init() {
2013
2154
  try {
2014
2155
  await this.manager.runMigrations();
2015
- logger3.info("PgDatabaseAdapter initialized successfully");
2156
+ logger3.debug("PgDatabaseAdapter initialized successfully");
2016
2157
  } catch (error) {
2017
2158
  logger3.error("Failed to initialize PgDatabaseAdapter:", error);
2018
2159
  throw error;
@@ -2029,30 +2170,45 @@ var PgDatabaseAdapter = class extends BaseDrizzleAdapter {
2029
2170
  };
2030
2171
 
2031
2172
  // src/index.ts
2032
- var pgLiteClientManager;
2033
- var postgresConnectionManager;
2173
+ import { Pool } from "pg";
2174
+ var GLOBAL_SINGLETONS = Symbol.for("@elizaos/plugin-sql/global-singletons");
2175
+ var globalSymbols = global;
2176
+ if (!globalSymbols[GLOBAL_SINGLETONS]) {
2177
+ globalSymbols[GLOBAL_SINGLETONS] = {};
2178
+ }
2179
+ var globalSingletons = globalSymbols[GLOBAL_SINGLETONS];
2180
+ function expandTildePath(filepath) {
2181
+ if (filepath && typeof filepath === "string" && filepath.startsWith("~")) {
2182
+ return filepath.replace(/^~/, os.homedir());
2183
+ }
2184
+ return filepath;
2185
+ }
2186
+ __name(expandTildePath, "expandTildePath");
2034
2187
  function createDatabaseAdapter(config, agentId) {
2035
- console.log("*** postgresUrl", config.postgresUrl);
2188
+ if (config.dataDir) {
2189
+ config.dataDir = expandTildePath(config.dataDir);
2190
+ }
2036
2191
  if (config.postgresUrl) {
2037
- if (!postgresConnectionManager) {
2038
- postgresConnectionManager = new PostgresConnectionManager(
2192
+ const pool = new Pool({ connectionString: config.postgresUrl });
2193
+ if (!globalSingletons.postgresConnectionManager) {
2194
+ globalSingletons.postgresConnectionManager = new PostgresConnectionManager(
2195
+ pool,
2039
2196
  config.postgresUrl
2040
2197
  );
2041
2198
  }
2042
- return new PgDatabaseAdapter(agentId, postgresConnectionManager);
2199
+ return new PgDatabaseAdapter(agentId, globalSingletons.postgresConnectionManager);
2043
2200
  }
2044
2201
  const dataDir = config.dataDir ?? "./elizadb";
2045
- if (!pgLiteClientManager) {
2046
- pgLiteClientManager = new PGliteClientManager({ dataDir });
2202
+ if (!globalSingletons.pgLiteClientManager) {
2203
+ globalSingletons.pgLiteClientManager = new PGliteClientManager({ dataDir });
2047
2204
  }
2048
- return new PgliteDatabaseAdapter(agentId, pgLiteClientManager);
2205
+ return new PgliteDatabaseAdapter(agentId, globalSingletons.pgLiteClientManager);
2049
2206
  }
2050
2207
  __name(createDatabaseAdapter, "createDatabaseAdapter");
2051
- var drizzlePlugin = {
2052
- name: "drizzle",
2053
- description: "Database adapter plugin using Drizzle ORM",
2208
+ var sqlPlugin = {
2209
+ name: "sql",
2210
+ description: "SQL database adapter plugin using Drizzle ORM",
2054
2211
  init: /* @__PURE__ */ __name(async (_, runtime) => {
2055
- console.log("*** drizzlePlugin init");
2056
2212
  const config = {
2057
2213
  dataDir: runtime.getSetting("PGLITE_DATA_DIR") ?? "./pglite",
2058
2214
  postgresUrl: runtime.getSetting("POSTGRES_URL")
@@ -2067,7 +2223,7 @@ var drizzlePlugin = {
2067
2223
  }
2068
2224
  }, "init")
2069
2225
  };
2070
- var index_default = drizzlePlugin;
2226
+ var index_default = sqlPlugin;
2071
2227
  export {
2072
2228
  createDatabaseAdapter,
2073
2229
  index_default as default