@elizaos/plugin-sql 1.0.0-alpha.2 → 1.0.0-alpha.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,6 +1,13 @@
1
+ import {
2
+ PGliteClientManager,
3
+ PostgresConnectionManager,
4
+ __name
5
+ } from "./chunk-LLEN3JTK.js";
6
+
1
7
  // src/index.ts
8
+ import * as os from "node:os";
2
9
  import {
3
- logger as logger6
10
+ logger as logger4
4
11
  } from "@elizaos/core";
5
12
 
6
13
  // src/pg-lite/adapter.ts
@@ -27,15 +34,39 @@ import {
27
34
  import { v4 } from "uuid";
28
35
 
29
36
  // src/schema/embedding.ts
37
+ import { sql as sql6 } from "drizzle-orm";
30
38
  import {
39
+ check as check2,
40
+ foreignKey as foreignKey2,
41
+ index as index2,
31
42
  pgTable as pgTable6,
32
43
  uuid as uuid6,
33
- vector as vector2,
34
- index as index2,
35
- foreignKey as foreignKey2,
36
- check as check2
44
+ vector as vector2
45
+ } from "drizzle-orm/pg-core";
46
+
47
+ // src/schema/memory.ts
48
+ import { relations, sql as sql5 } from "drizzle-orm";
49
+ import {
50
+ boolean as boolean2,
51
+ check,
52
+ foreignKey,
53
+ index,
54
+ jsonb as jsonb5,
55
+ pgTable as pgTable5,
56
+ text as text5,
57
+ uuid as uuid5
58
+ } from "drizzle-orm/pg-core";
59
+
60
+ // src/schema/agent.ts
61
+ import { sql } from "drizzle-orm";
62
+ import {
63
+ boolean,
64
+ jsonb,
65
+ pgTable,
66
+ text,
67
+ unique,
68
+ uuid
37
69
  } from "drizzle-orm/pg-core";
38
- import { sql as sql6 } from "drizzle-orm";
39
70
 
40
71
  // src/schema/types.ts
41
72
  import { customType } from "drizzle-orm/pg-core";
@@ -64,33 +95,7 @@ var numberTimestamp = customType(
64
95
  }
65
96
  );
66
97
 
67
- // src/schema/memory.ts
68
- import {
69
- pgTable as pgTable5,
70
- uuid as uuid5,
71
- text as text5,
72
- jsonb as jsonb5,
73
- index,
74
- boolean as boolean2,
75
- foreignKey,
76
- check
77
- } from "drizzle-orm/pg-core";
78
- import { relations, sql as sql5 } from "drizzle-orm";
79
-
80
- // src/schema/entity.ts
81
- import { sql as sql2 } from "drizzle-orm";
82
- import { jsonb as jsonb2, pgTable as pgTable2, text as text2, unique as unique2, uuid as uuid2 } from "drizzle-orm/pg-core";
83
-
84
98
  // src/schema/agent.ts
85
- import {
86
- boolean,
87
- jsonb,
88
- pgTable,
89
- text,
90
- uuid,
91
- unique
92
- } from "drizzle-orm/pg-core";
93
- import { sql } from "drizzle-orm";
94
99
  var agentTable = pgTable(
95
100
  "agents",
96
101
  {
@@ -120,6 +125,8 @@ var agentTable = pgTable(
120
125
  );
121
126
 
122
127
  // src/schema/entity.ts
128
+ import { sql as sql2 } from "drizzle-orm";
129
+ import { jsonb as jsonb2, pgTable as pgTable2, text as text2, unique as unique2, uuid as uuid2 } from "drizzle-orm/pg-core";
123
130
  var entityTable = pgTable2(
124
131
  "entities",
125
132
  {
@@ -143,8 +150,8 @@ import { sql as sql4 } from "drizzle-orm";
143
150
  import { jsonb as jsonb4, pgTable as pgTable4, text as text4, uuid as uuid4 } from "drizzle-orm/pg-core";
144
151
 
145
152
  // src/schema/worldTable.ts
146
- import { jsonb as jsonb3, pgTable as pgTable3, text as text3, uuid as uuid3 } from "drizzle-orm/pg-core";
147
153
  import { sql as sql3 } from "drizzle-orm";
154
+ import { jsonb as jsonb3, pgTable as pgTable3, text as text3, uuid as uuid3 } from "drizzle-orm/pg-core";
148
155
  var worldTable = pgTable3("worlds", {
149
156
  id: uuid3("id").notNull().primaryKey().default(sql3`gen_random_uuid()`),
150
157
  agentId: uuid3("agentId").notNull().references(() => agentTable.id, { onDelete: "cascade" }),
@@ -300,8 +307,8 @@ var cacheTable = pgTable7(
300
307
  );
301
308
 
302
309
  // src/schema/component.ts
303
- import { pgTable as pgTable8, uuid as uuid8, jsonb as jsonb7, text as text7 } from "drizzle-orm/pg-core";
304
310
  import { sql as sql8 } from "drizzle-orm";
311
+ import { jsonb as jsonb7, pgTable as pgTable8, text as text7, uuid as uuid8 } from "drizzle-orm/pg-core";
305
312
  var componentTable = pgTable8("components", {
306
313
  id: uuid8("id").primaryKey().defaultRandom(),
307
314
  entityId: uuid8("entityId").notNull().references(() => entityTable.id, { onDelete: "cascade" }),
@@ -319,8 +326,8 @@ var componentTable = pgTable8("components", {
319
326
  });
320
327
 
321
328
  // src/schema/goal.ts
322
- import { pgTable as pgTable9, uuid as uuid9, text as text8, jsonb as jsonb8, foreignKey as foreignKey3 } from "drizzle-orm/pg-core";
323
329
  import { sql as sql9 } from "drizzle-orm";
330
+ import { foreignKey as foreignKey3, jsonb as jsonb8, pgTable as pgTable9, text as text8, uuid as uuid9 } from "drizzle-orm/pg-core";
324
331
  var goalTable = pgTable9(
325
332
  "goals",
326
333
  {
@@ -355,8 +362,8 @@ var goalTable = pgTable9(
355
362
  );
356
363
 
357
364
  // src/schema/log.ts
358
- import { pgTable as pgTable10, uuid as uuid10, text as text9, jsonb as jsonb9, foreignKey as foreignKey4 } from "drizzle-orm/pg-core";
359
365
  import { sql as sql10 } from "drizzle-orm";
366
+ import { foreignKey as foreignKey4, jsonb as jsonb9, pgTable as pgTable10, text as text9, uuid as uuid10 } from "drizzle-orm/pg-core";
360
367
  var logTable = pgTable10(
361
368
  "logs",
362
369
  {
@@ -382,14 +389,14 @@ var logTable = pgTable10(
382
389
  );
383
390
 
384
391
  // src/schema/participant.ts
392
+ import { sql as sql11 } from "drizzle-orm";
385
393
  import {
394
+ foreignKey as foreignKey5,
395
+ index as index3,
386
396
  pgTable as pgTable11,
387
- uuid as uuid11,
388
397
  text as text10,
389
- index as index3,
390
- foreignKey as foreignKey5
398
+ uuid as uuid11
391
399
  } from "drizzle-orm/pg-core";
392
- import { sql as sql11 } from "drizzle-orm";
393
400
  var participantTable = pgTable11(
394
401
  "participants",
395
402
  {
@@ -485,16 +492,30 @@ var taskTable = pgTable13("tasks", {
485
492
 
486
493
  // src/base.ts
487
494
  var BaseDrizzleAdapter = class extends DatabaseAdapter {
495
+ static {
496
+ __name(this, "BaseDrizzleAdapter");
497
+ }
488
498
  maxRetries = 3;
489
499
  baseDelay = 1e3;
490
500
  maxDelay = 1e4;
491
501
  jitterMax = 1e3;
492
502
  embeddingDimension = DIMENSION_MAP[384];
493
503
  agentId;
504
+ /**
505
+ * Constructor for creating a new instance of Agent with the specified agentId.
506
+ *
507
+ * @param {UUID} agentId - The unique identifier for the agent.
508
+ */
494
509
  constructor(agentId) {
495
510
  super();
496
511
  this.agentId = agentId;
497
512
  }
513
+ /**
514
+ * Executes the given operation with retry logic.
515
+ * @template T
516
+ * @param {() => Promise<T>} operation - The operation to be executed.
517
+ * @returns {Promise<T>} A promise that resolves with the result of the operation.
518
+ */
498
519
  async withRetry(operation) {
499
520
  let lastError = new Error("Unknown error");
500
521
  for (let attempt = 1; attempt <= this.maxRetries; attempt++) {
@@ -516,7 +537,6 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
516
537
  nextRetryIn: `${(delay / 1e3).toFixed(1)}s`
517
538
  }
518
539
  );
519
- console.trace("****** Database operation failure source");
520
540
  await new Promise((resolve) => setTimeout(resolve, delay));
521
541
  } else {
522
542
  logger.error("Max retry attempts reached:", {
@@ -529,6 +549,14 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
529
549
  }
530
550
  throw lastError;
531
551
  }
552
+ /**
553
+ * Ensure that an agent exists by checking if an agent with the same name already exists in the system.
554
+ * If the agent does not exist, it will be created with the provided data.
555
+ *
556
+ * @param {Partial<Agent>} agent - The partial data of the agent to ensure its existence.
557
+ * @returns {Promise<void>} - A promise that resolves when the agent is successfully ensured.
558
+ * @throws {Error} - If the agent name is not provided or if there is an issue creating the agent.
559
+ */
532
560
  async ensureAgentExists(agent) {
533
561
  if (!agent.name) {
534
562
  throw new Error("Agent name is required");
@@ -541,6 +569,12 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
541
569
  await this.createAgent(agent);
542
570
  }
543
571
  }
572
+ /**
573
+ * Ensure that the given embedding dimension is valid for the agent.
574
+ *
575
+ * @param {number} dimension - The dimension to ensure for the embedding.
576
+ * @returns {Promise<void>} - Resolves once the embedding dimension is ensured.
577
+ */
544
578
  async ensureEmbeddingDimension(dimension) {
545
579
  const existingMemory = await this.db.select({
546
580
  embedding: embeddingTable
@@ -555,6 +589,11 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
555
589
  }
556
590
  this.embeddingDimension = DIMENSION_MAP[dimension];
557
591
  }
592
+ /**
593
+ * Asynchronously retrieves an agent by their ID from the database.
594
+ * @param {UUID} agentId - The ID of the agent to retrieve.
595
+ * @returns {Promise<Agent | null>} A promise that resolves to the retrieved agent or null if not found.
596
+ */
558
597
  async getAgent(agentId) {
559
598
  return this.withDatabase(async () => {
560
599
  const result = await this.db.select().from(agentTable).where(eq(agentTable.id, agentId)).limit(1);
@@ -562,12 +601,23 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
562
601
  return result[0];
563
602
  });
564
603
  }
604
+ /**
605
+ * Asynchronously retrieves a list of agents from the database.
606
+ *
607
+ * @returns {Promise<Agent[]>} A Promise that resolves to an array of Agent objects.
608
+ */
565
609
  async getAgents() {
566
610
  return this.withDatabase(async () => {
567
611
  const result = await this.db.select().from(agentTable);
568
612
  return result;
569
613
  });
570
614
  }
615
+ /**
616
+ * Asynchronously creates a new agent record in the database.
617
+ *
618
+ * @param {Partial<Agent>} agent The agent object to be created.
619
+ * @returns {Promise<boolean>} A promise that resolves to a boolean indicating the success of the operation.
620
+ */
571
621
  async createAgent(agent) {
572
622
  return this.withDatabase(async () => {
573
623
  try {
@@ -590,6 +640,12 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
590
640
  }
591
641
  });
592
642
  }
643
+ /**
644
+ * Updates an agent in the database with the provided agent ID and data.
645
+ * @param {UUID} agentId - The unique identifier of the agent to update.
646
+ * @param {Partial<Agent>} agent - The partial agent object containing the fields to update.
647
+ * @returns {Promise<boolean>} - A boolean indicating if the agent was successfully updated.
648
+ */
593
649
  async updateAgent(agentId, agent) {
594
650
  return this.withDatabase(async () => {
595
651
  try {
@@ -616,6 +672,12 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
616
672
  }
617
673
  });
618
674
  }
675
+ /**
676
+ * Asynchronously deletes an agent with the specified UUID and all related entries.
677
+ *
678
+ * @param {UUID} agentId - The UUID of the agent to be deleted.
679
+ * @returns {Promise<boolean>} - A boolean indicating if the deletion was successful.
680
+ */
619
681
  async deleteAgent(agentId) {
620
682
  return this.withDatabase(async () => {
621
683
  await this.db.transaction(async (tx) => {
@@ -628,6 +690,10 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
628
690
  * Count all agents in the database
629
691
  * Used primarily for maintenance and cleanup operations
630
692
  */
693
+ /**
694
+ * Asynchronously counts the number of agents in the database.
695
+ * @returns {Promise<number>} A Promise that resolves to the number of agents in the database.
696
+ */
631
697
  async countAgents() {
632
698
  return this.withDatabase(async () => {
633
699
  try {
@@ -730,11 +796,12 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
730
796
  return true;
731
797
  });
732
798
  } catch (error) {
733
- logger.error("Error creating account:", {
799
+ logger.error("Error creating entity:", {
734
800
  error: error instanceof Error ? error.message : String(error),
735
801
  entityId: entity.id,
736
802
  name: entity.metadata?.name
737
803
  });
804
+ console.trace(error);
738
805
  return false;
739
806
  }
740
807
  });
@@ -1566,7 +1633,9 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1566
1633
  if (params.tags && params.tags.length > 0) {
1567
1634
  const tagParams = params.tags.map((tag) => `'${tag.replace(/'/g, "''")}'`).join(", ");
1568
1635
  query = query.where(
1569
- sql13`${relationshipTable.tags} @> ARRAY[${sql13.raw(tagParams)}]::text[]`
1636
+ sql13`${relationshipTable.tags} @> ARRAY[${sql13.raw(
1637
+ tagParams
1638
+ )}]::text[]`
1570
1639
  );
1571
1640
  }
1572
1641
  const results = await query;
@@ -1847,13 +1916,28 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1847
1916
 
1848
1917
  // src/pg-lite/adapter.ts
1849
1918
  var PgliteDatabaseAdapter = class extends BaseDrizzleAdapter {
1919
+ static {
1920
+ __name(this, "PgliteDatabaseAdapter");
1921
+ }
1850
1922
  manager;
1851
1923
  embeddingDimension = DIMENSION_MAP[384];
1924
+ /**
1925
+ * Constructor for creating an instance of a class.
1926
+ * @param {UUID} agentId - The unique identifier for the agent.
1927
+ * @param {PGliteClientManager} manager - The manager for the PGlite client.
1928
+ */
1852
1929
  constructor(agentId, manager) {
1853
1930
  super(agentId);
1854
1931
  this.manager = manager;
1855
1932
  this.db = drizzle(this.manager.getConnection());
1856
1933
  }
1934
+ /**
1935
+ * Asynchronously runs the provided database operation while checking if the database manager is currently shutting down.
1936
+ * If the database manager is shutting down, a warning is logged and null is returned.
1937
+ *
1938
+ * @param {Function} operation - The database operation to be performed.
1939
+ * @returns {Promise<T>} A promise that resolves with the result of the database operation.
1940
+ */
1857
1941
  async withDatabase(operation) {
1858
1942
  if (this.manager.isShuttingDown()) {
1859
1943
  logger2.warn("Database is shutting down");
@@ -1861,6 +1945,11 @@ var PgliteDatabaseAdapter = class extends BaseDrizzleAdapter {
1861
1945
  }
1862
1946
  return operation();
1863
1947
  }
1948
+ /**
1949
+ * Asynchronously initializes the database by running migrations using the manager.
1950
+ *
1951
+ * @returns {Promise<void>} A Promise that resolves when the database initialization is complete.
1952
+ */
1864
1953
  async init() {
1865
1954
  try {
1866
1955
  await this.manager.runMigrations();
@@ -1869,123 +1958,44 @@ var PgliteDatabaseAdapter = class extends BaseDrizzleAdapter {
1869
1958
  throw error;
1870
1959
  }
1871
1960
  }
1961
+ /**
1962
+ * Asynchronously closes the manager.
1963
+ */
1872
1964
  async close() {
1873
1965
  await this.manager.close();
1874
1966
  }
1875
1967
  };
1876
1968
 
1877
- // src/pg-lite/manager.ts
1878
- import { PGlite } from "@electric-sql/pglite";
1879
- import { vector as vector3 } from "@electric-sql/pglite/vector";
1880
- import { fuzzystrmatch } from "@electric-sql/pglite/contrib/fuzzystrmatch";
1881
- import { logger as logger3 } from "@elizaos/core";
1882
- import { migrate } from "drizzle-orm/pglite/migrator";
1883
- import { fileURLToPath } from "node:url";
1884
- import path from "node:path";
1885
- import { drizzle as drizzle2 } from "drizzle-orm/pglite";
1886
- var __filename = fileURLToPath(import.meta.url);
1887
- var __dirname = path.dirname(__filename);
1888
- var PGliteClientManager = class {
1889
- client;
1890
- shuttingDown = false;
1891
- shutdownTimeout = 800;
1892
- constructor(options) {
1893
- this.client = new PGlite({
1894
- ...options,
1895
- extensions: {
1896
- vector: vector3,
1897
- fuzzystrmatch
1898
- }
1899
- });
1900
- this.setupShutdownHandlers();
1901
- }
1902
- getConnection() {
1903
- if (this.shuttingDown) {
1904
- throw new Error("Client manager is shutting down");
1905
- }
1906
- return this.client;
1907
- }
1908
- async gracefulShutdown() {
1909
- if (this.shuttingDown) {
1910
- return;
1911
- }
1912
- this.shuttingDown = true;
1913
- logger3.info("Starting graceful shutdown of PGlite client...");
1914
- const timeout = setTimeout(() => {
1915
- logger3.warn(
1916
- "Shutdown timeout reached, forcing database connection closure..."
1917
- );
1918
- this.client.close().finally(() => {
1919
- process.exit(1);
1920
- });
1921
- }, this.shutdownTimeout);
1922
- try {
1923
- await new Promise((resolve) => setTimeout(resolve, this.shutdownTimeout));
1924
- await this.client.close();
1925
- clearTimeout(timeout);
1926
- logger3.info("PGlite client shutdown completed successfully");
1927
- process.exit(0);
1928
- } catch (error) {
1929
- logger3.error("Error during graceful shutdown:", error);
1930
- process.exit(1);
1931
- }
1932
- }
1933
- setupShutdownHandlers() {
1934
- process.on("SIGINT", async () => {
1935
- await this.gracefulShutdown();
1936
- });
1937
- process.on("SIGTERM", async () => {
1938
- await this.gracefulShutdown();
1939
- });
1940
- process.on("beforeExit", async () => {
1941
- await this.gracefulShutdown();
1942
- });
1943
- }
1944
- async initialize() {
1945
- try {
1946
- await this.client.waitReady;
1947
- logger3.info("PGlite client initialized successfully");
1948
- } catch (error) {
1949
- logger3.error("Failed to initialize PGlite client:", error);
1950
- throw error;
1951
- }
1952
- }
1953
- async close() {
1954
- if (!this.shuttingDown) {
1955
- await this.gracefulShutdown();
1956
- }
1957
- }
1958
- isShuttingDown() {
1959
- return this.shuttingDown;
1960
- }
1961
- async runMigrations() {
1962
- try {
1963
- const db = drizzle2(this.client);
1964
- await migrate(db, {
1965
- migrationsFolder: path.resolve(__dirname, "../drizzle/migrations")
1966
- });
1967
- logger3.info("Migrations completed successfully!");
1968
- } catch (error) {
1969
- logger3.error("Failed to run database migrations:", error);
1970
- }
1971
- }
1972
- };
1973
-
1974
1969
  // src/pg/adapter.ts
1975
- import { logger as logger4 } from "@elizaos/core";
1976
- import { drizzle as drizzle3 } from "drizzle-orm/node-postgres";
1970
+ import { logger as logger3 } from "@elizaos/core";
1971
+ import { drizzle as drizzle2 } from "drizzle-orm/node-postgres";
1977
1972
  var PgDatabaseAdapter = class extends BaseDrizzleAdapter {
1973
+ /**
1974
+ * Constructor for creating a new instance of a class.
1975
+ * @param {UUID} agentId - The unique identifier for the agent.
1976
+ * @param {PostgresConnectionManager} manager - The Postgres connection manager for the instance.
1977
+ */
1978
1978
  constructor(agentId, manager) {
1979
1979
  super(agentId);
1980
1980
  this.manager = manager;
1981
1981
  this.manager = manager;
1982
1982
  }
1983
+ static {
1984
+ __name(this, "PgDatabaseAdapter");
1985
+ }
1983
1986
  embeddingDimension = DIMENSION_MAP[384];
1987
+ /**
1988
+ * Executes the provided operation with a database connection.
1989
+ *
1990
+ * @template T
1991
+ * @param {() => Promise<T>} operation - The operation to be executed with the database connection.
1992
+ * @returns {Promise<T>} A promise that resolves with the result of the operation.
1993
+ */
1984
1994
  async withDatabase(operation) {
1985
1995
  return await this.withRetry(async () => {
1986
1996
  const client = await this.manager.getClient();
1987
1997
  try {
1988
- const db = drizzle3(client);
1998
+ const db = drizzle2(client);
1989
1999
  this.db = db;
1990
2000
  return await operation();
1991
2001
  } finally {
@@ -1993,181 +2003,77 @@ var PgDatabaseAdapter = class extends BaseDrizzleAdapter {
1993
2003
  }
1994
2004
  });
1995
2005
  }
2006
+ /**
2007
+ * Asynchronously initializes the PgDatabaseAdapter by running migrations using the manager.
2008
+ * Logs a success message if initialization is successful, otherwise logs an error message.
2009
+ *
2010
+ * @returns {Promise<void>} A promise that resolves when initialization is complete.
2011
+ */
1996
2012
  async init() {
1997
2013
  try {
1998
2014
  await this.manager.runMigrations();
1999
- logger4.info("PgDatabaseAdapter initialized successfully");
2015
+ logger3.info("PgDatabaseAdapter initialized successfully");
2000
2016
  } catch (error) {
2001
- logger4.error("Failed to initialize PgDatabaseAdapter:", error);
2017
+ logger3.error("Failed to initialize PgDatabaseAdapter:", error);
2002
2018
  throw error;
2003
2019
  }
2004
2020
  }
2021
+ /**
2022
+ * Asynchronously closes the manager associated with this instance.
2023
+ *
2024
+ * @returns A Promise that resolves once the manager is closed.
2025
+ */
2005
2026
  async close() {
2006
2027
  await this.manager.close();
2007
2028
  }
2008
2029
  };
2009
2030
 
2010
- // src/pg/manager.ts
2011
- import pkg from "pg";
2012
- import { logger as logger5 } from "@elizaos/core";
2013
- import { migrate as migrate2 } from "drizzle-orm/node-postgres/migrator";
2014
- import { fileURLToPath as fileURLToPath2 } from "node:url";
2015
- import path2 from "node:path";
2016
- import { drizzle as drizzle4 } from "drizzle-orm/node-postgres";
2017
- var { Pool } = pkg;
2018
- var __filename2 = fileURLToPath2(import.meta.url);
2019
- var __dirname2 = path2.dirname(__filename2);
2020
- var PostgresConnectionManager = class {
2021
- pool;
2022
- isShuttingDown = false;
2023
- connectionTimeout = 5e3;
2024
- constructor(connectionString) {
2025
- const defaultConfig = {
2026
- max: 20,
2027
- idleTimeoutMillis: 3e4,
2028
- connectionTimeoutMillis: this.connectionTimeout
2029
- };
2030
- this.pool = new Pool({
2031
- ...defaultConfig,
2032
- connectionString
2033
- });
2034
- this.pool.on("error", (err) => {
2035
- logger5.error("Unexpected pool error", err);
2036
- this.handlePoolError(err);
2037
- });
2038
- this.setupPoolErrorHandling();
2039
- this.testConnection();
2040
- }
2041
- async handlePoolError(error) {
2042
- logger5.error("Pool error occurred, attempting to reconnect", {
2043
- error: error.message
2044
- });
2045
- try {
2046
- await this.pool.end();
2047
- this.pool = new Pool({
2048
- ...this.pool.options,
2049
- connectionTimeoutMillis: this.connectionTimeout
2050
- });
2051
- await this.testConnection();
2052
- logger5.success("Pool reconnection successful");
2053
- } catch (reconnectError) {
2054
- logger5.error("Failed to reconnect pool", {
2055
- error: reconnectError instanceof Error ? reconnectError.message : String(reconnectError)
2056
- });
2057
- throw reconnectError;
2058
- }
2059
- }
2060
- async testConnection() {
2061
- let client;
2062
- try {
2063
- client = await this.pool.connect();
2064
- const result = await client.query("SELECT NOW()");
2065
- logger5.success("Database connection test successful:", result.rows[0]);
2066
- return true;
2067
- } catch (error) {
2068
- logger5.error("Database connection test failed:", error);
2069
- throw new Error(
2070
- `Failed to connect to database: ${error.message}`
2071
- );
2072
- } finally {
2073
- if (client) client.release();
2074
- }
2075
- }
2076
- setupPoolErrorHandling() {
2077
- process.on("SIGINT", async () => {
2078
- await this.cleanup();
2079
- process.exit(0);
2080
- });
2081
- process.on("SIGTERM", async () => {
2082
- await this.cleanup();
2083
- process.exit(0);
2084
- });
2085
- process.on("beforeExit", async () => {
2086
- await this.cleanup();
2087
- });
2088
- }
2089
- getConnection() {
2090
- if (this.isShuttingDown) {
2091
- throw new Error("Connection manager is shutting down");
2092
- }
2093
- try {
2094
- return this.pool;
2095
- } catch (error) {
2096
- logger5.error("Failed to get connection from pool:", error);
2097
- throw error;
2098
- }
2099
- }
2100
- async getClient() {
2101
- try {
2102
- return await this.pool.connect();
2103
- } catch (error) {
2104
- logger5.error("Failed to acquire a database client:", error);
2105
- throw error;
2106
- }
2107
- }
2108
- async initialize() {
2109
- try {
2110
- await this.testConnection();
2111
- logger5.info("PostgreSQL connection manager initialized successfully");
2112
- } catch (error) {
2113
- logger5.error("Failed to initialize connection manager:", error);
2114
- throw error;
2115
- }
2116
- }
2117
- async close() {
2118
- await this.cleanup();
2119
- }
2120
- async cleanup() {
2121
- try {
2122
- await this.pool.end();
2123
- logger5.info("Database pool closed");
2124
- } catch (error) {
2125
- logger5.error("Error closing database pool:", error);
2126
- }
2127
- }
2128
- async runMigrations() {
2129
- try {
2130
- const db = drizzle4(this.pool);
2131
- await migrate2(db, {
2132
- migrationsFolder: path2.resolve(__dirname2, "../drizzle/migrations")
2133
- });
2134
- logger5.info("Migrations completed successfully!");
2135
- } catch (error) {
2136
- logger5.error("Failed to run database migrations:", error);
2137
- }
2138
- }
2139
- };
2140
-
2141
2031
  // src/index.ts
2142
2032
  var pgLiteClientManager;
2033
+ var postgresConnectionManager;
2034
+ function expandTildePath(filepath) {
2035
+ if (filepath && typeof filepath === "string" && filepath.startsWith("~")) {
2036
+ return filepath.replace(/^~/, os.homedir());
2037
+ }
2038
+ return filepath;
2039
+ }
2040
+ __name(expandTildePath, "expandTildePath");
2143
2041
  function createDatabaseAdapter(config, agentId) {
2042
+ if (config.dataDir) {
2043
+ config.dataDir = expandTildePath(config.dataDir);
2044
+ }
2144
2045
  if (config.postgresUrl) {
2145
- const manager = new PostgresConnectionManager(config.postgresUrl);
2146
- return new PgDatabaseAdapter(agentId, manager);
2046
+ if (!postgresConnectionManager) {
2047
+ postgresConnectionManager = new PostgresConnectionManager(
2048
+ config.postgresUrl
2049
+ );
2050
+ }
2051
+ return new PgDatabaseAdapter(agentId, postgresConnectionManager);
2147
2052
  }
2148
- const dataDir = config.dataDir ?? "../../pgLite";
2053
+ const dataDir = config.dataDir ?? "./elizadb";
2149
2054
  if (!pgLiteClientManager) {
2150
2055
  pgLiteClientManager = new PGliteClientManager({ dataDir });
2151
2056
  }
2152
2057
  return new PgliteDatabaseAdapter(agentId, pgLiteClientManager);
2153
2058
  }
2059
+ __name(createDatabaseAdapter, "createDatabaseAdapter");
2154
2060
  var drizzlePlugin = {
2155
2061
  name: "drizzle",
2156
2062
  description: "Database adapter plugin using Drizzle ORM",
2157
- init: async (_, runtime) => {
2063
+ init: /* @__PURE__ */ __name(async (_, runtime) => {
2158
2064
  const config = {
2159
- dataDir: runtime.getSetting("PGLITE_DATA_DIR"),
2065
+ dataDir: runtime.getSetting("PGLITE_DATA_DIR") ?? "./pglite",
2160
2066
  postgresUrl: runtime.getSetting("POSTGRES_URL")
2161
2067
  };
2162
2068
  try {
2163
2069
  const db = createDatabaseAdapter(config, runtime.agentId);
2164
- logger6.success("Database connection established successfully");
2070
+ logger4.success("Database connection established successfully");
2165
2071
  runtime.registerDatabaseAdapter(db);
2166
2072
  } catch (error) {
2167
- logger6.error("Failed to initialize database:", error);
2073
+ logger4.error("Failed to initialize database:", error);
2168
2074
  throw error;
2169
2075
  }
2170
- }
2076
+ }, "init")
2171
2077
  };
2172
2078
  var index_default = drizzlePlugin;
2173
2079
  export {