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

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