@elizaos/plugin-sql 1.0.0-beta.6 → 1.0.0-beta.8
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/LICENSE +1 -1
- package/dist/index.js +81 -1
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
package/LICENSE
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
MIT License
|
|
2
2
|
|
|
3
|
-
Copyright (c) 2025 Shaw Walters
|
|
3
|
+
Copyright (c) 2025 Shaw Walters and elizaOS Contributors
|
|
4
4
|
|
|
5
5
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
6
|
of this software and associated documentation files (the "Software"), to deal
|
package/dist/index.js
CHANGED
|
@@ -27,7 +27,8 @@ import {
|
|
|
27
27
|
inArray,
|
|
28
28
|
lte,
|
|
29
29
|
or,
|
|
30
|
-
sql as sql12
|
|
30
|
+
sql as sql12,
|
|
31
|
+
not
|
|
31
32
|
} from "drizzle-orm";
|
|
32
33
|
import { v4 } from "uuid";
|
|
33
34
|
|
|
@@ -569,6 +570,9 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
569
570
|
throw new Error("Agent ID is required for update");
|
|
570
571
|
}
|
|
571
572
|
await this.db.transaction(async (tx) => {
|
|
573
|
+
if (agent.settings) {
|
|
574
|
+
agent.settings = await this.mergeAgentSettings(tx, agentId, agent.settings);
|
|
575
|
+
}
|
|
572
576
|
await tx.update(agentTable).set({
|
|
573
577
|
...agent,
|
|
574
578
|
updatedAt: Date.now()
|
|
@@ -588,6 +592,39 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
588
592
|
}
|
|
589
593
|
});
|
|
590
594
|
}
|
|
595
|
+
/**
|
|
596
|
+
* Merges updated agent settings with existing settings in the database,
|
|
597
|
+
* with special handling for nested objects like secrets.
|
|
598
|
+
* @param tx - The database transaction
|
|
599
|
+
* @param agentId - The ID of the agent
|
|
600
|
+
* @param updatedSettings - The settings object with updates
|
|
601
|
+
* @returns The merged settings object
|
|
602
|
+
* @private
|
|
603
|
+
*/
|
|
604
|
+
async mergeAgentSettings(tx, agentId, updatedSettings) {
|
|
605
|
+
const currentAgent = await tx.select({ settings: agentTable.settings }).from(agentTable).where(eq(agentTable.id, agentId)).limit(1);
|
|
606
|
+
if (currentAgent.length === 0 || !currentAgent[0].settings) {
|
|
607
|
+
return updatedSettings;
|
|
608
|
+
}
|
|
609
|
+
const currentSettings = currentAgent[0].settings;
|
|
610
|
+
if (updatedSettings.secrets) {
|
|
611
|
+
const currentSecrets = currentSettings.secrets || {};
|
|
612
|
+
const updatedSecrets = updatedSettings.secrets;
|
|
613
|
+
const mergedSecrets = { ...currentSecrets };
|
|
614
|
+
for (const [key, value] of Object.entries(updatedSecrets)) {
|
|
615
|
+
if (value === null) {
|
|
616
|
+
delete mergedSecrets[key];
|
|
617
|
+
} else {
|
|
618
|
+
mergedSecrets[key] = value;
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
updatedSettings.secrets = mergedSecrets;
|
|
622
|
+
}
|
|
623
|
+
return {
|
|
624
|
+
...currentSettings,
|
|
625
|
+
...updatedSettings
|
|
626
|
+
};
|
|
627
|
+
}
|
|
591
628
|
/**
|
|
592
629
|
* Asynchronously deletes an agent with the specified UUID and all related entries.
|
|
593
630
|
*
|
|
@@ -597,6 +634,42 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
597
634
|
async deleteAgent(agentId) {
|
|
598
635
|
return this.withDatabase(async () => {
|
|
599
636
|
await this.db.transaction(async (tx) => {
|
|
637
|
+
const entities = await this.db.select({ entityId: entityTable.id }).from(entityTable).where(eq(entityTable.agentId, agentId));
|
|
638
|
+
const entityIds = entities.map((e) => e.entityId);
|
|
639
|
+
let memoryIds = [];
|
|
640
|
+
if (entityIds.length > 0) {
|
|
641
|
+
const entityMemories = await this.db.select({ memoryId: memoryTable.id }).from(memoryTable).where(inArray(memoryTable.entityId, entityIds));
|
|
642
|
+
memoryIds = entityMemories.map((m) => m.memoryId);
|
|
643
|
+
}
|
|
644
|
+
const agentMemories = await this.db.select({ memoryId: memoryTable.id }).from(memoryTable).where(eq(memoryTable.agentId, agentId));
|
|
645
|
+
memoryIds.push(...agentMemories.map((m) => m.memoryId));
|
|
646
|
+
if (memoryIds.length > 0) {
|
|
647
|
+
await tx.delete(embeddingTable).where(inArray(embeddingTable.memoryId, memoryIds));
|
|
648
|
+
await tx.delete(memoryTable).where(inArray(memoryTable.id, memoryIds));
|
|
649
|
+
}
|
|
650
|
+
const rooms = await this.db.select({ roomId: roomTable.id }).from(roomTable).where(eq(roomTable.agentId, agentId));
|
|
651
|
+
const roomIds = rooms.map((r) => r.roomId);
|
|
652
|
+
if (entityIds.length > 0) {
|
|
653
|
+
await tx.delete(logTable).where(inArray(logTable.entityId, entityIds));
|
|
654
|
+
await tx.delete(participantTable).where(inArray(participantTable.entityId, entityIds));
|
|
655
|
+
}
|
|
656
|
+
if (roomIds.length > 0) {
|
|
657
|
+
await tx.delete(logTable).where(inArray(logTable.roomId, roomIds));
|
|
658
|
+
await tx.delete(participantTable).where(inArray(participantTable.roomId, roomIds));
|
|
659
|
+
}
|
|
660
|
+
await tx.delete(participantTable).where(eq(participantTable.agentId, agentId));
|
|
661
|
+
if (roomIds.length > 0) {
|
|
662
|
+
await tx.delete(roomTable).where(inArray(roomTable.id, roomIds));
|
|
663
|
+
}
|
|
664
|
+
await tx.delete(cacheTable).where(eq(cacheTable.agentId, agentId));
|
|
665
|
+
await tx.delete(relationshipTable).where(eq(relationshipTable.agentId, agentId));
|
|
666
|
+
await tx.delete(entityTable).where(eq(entityTable.agentId, agentId));
|
|
667
|
+
const newAgent = await this.db.select({ newAgentId: agentTable.id }).from(agentTable).where(not(eq(agentTable.id, agentId))).limit(1);
|
|
668
|
+
if (newAgent.length > 0) {
|
|
669
|
+
await tx.update(worldTable).set({ agentId: newAgent[0].newAgentId }).where(eq(worldTable.agentId, agentId));
|
|
670
|
+
} else {
|
|
671
|
+
await tx.delete(worldTable).where(eq(worldTable.agentId, agentId));
|
|
672
|
+
}
|
|
600
673
|
await tx.delete(agentTable).where(eq(agentTable.id, agentId));
|
|
601
674
|
});
|
|
602
675
|
return true;
|
|
@@ -710,6 +783,13 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
|
|
|
710
783
|
return this.withDatabase(async () => {
|
|
711
784
|
try {
|
|
712
785
|
return await this.db.transaction(async (tx) => {
|
|
786
|
+
const existingEntity = await this.getEntityById(entity.id);
|
|
787
|
+
if (existingEntity) {
|
|
788
|
+
logger.debug("Entity already exists:", {
|
|
789
|
+
entity
|
|
790
|
+
});
|
|
791
|
+
return true;
|
|
792
|
+
}
|
|
713
793
|
await tx.insert(entityTable).values(entity);
|
|
714
794
|
logger.debug("Entity created successfully:", {
|
|
715
795
|
entity
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/pglite/adapter.ts","../src/base.ts","../src/schema/embedding.ts","../src/schema/memory.ts","../src/schema/agent.ts","../src/schema/types.ts","../src/schema/entity.ts","../src/schema/room.ts","../src/schema/worldTable.ts","../src/schema/cache.ts","../src/schema/component.ts","../src/schema/log.ts","../src/schema/participant.ts","../src/schema/relationship.ts","../src/schema/tasks.ts","../src/pg/adapter.ts"],"sourceRoot":"./","sourcesContent":["import * as os from 'node:os';\nimport type { IDatabaseAdapter, UUID } from '@elizaos/core';\nimport { type IAgentRuntime, type Plugin, logger } from '@elizaos/core';\nimport { PgliteDatabaseAdapter } from './pglite/adapter';\nimport { PGliteClientManager } from './pglite/manager';\nimport { PgDatabaseAdapter } from './pg/adapter';\nimport { PostgresConnectionManager } from './pg/manager';\n\n/**\n * Global Singleton Instances (Package-scoped)\n *\n * These instances are stored globally within the package scope to ensure a single shared instance across multiple adapters within this package.\n * This approach prevents multiple instantiations due to module caching or multiple imports within the same process.\n *\n * IMPORTANT:\n * - Do NOT directly modify these instances outside their intended initialization logic.\n * - These instances are NOT exported and should NOT be accessed outside this package.\n */\nconst GLOBAL_SINGLETONS = Symbol.for('@elizaos/plugin-sql/global-singletons');\n\ninterface GlobalSingletons {\n pgLiteClientManager?: PGliteClientManager;\n postgresConnectionManager?: PostgresConnectionManager;\n}\n\nconst globalSymbols = global as unknown as Record<symbol, GlobalSingletons>;\n\nif (!globalSymbols[GLOBAL_SINGLETONS]) {\n globalSymbols[GLOBAL_SINGLETONS] = {};\n}\n\nconst globalSingletons = globalSymbols[GLOBAL_SINGLETONS];\n\n/**\n * Helper function to expand tilde in paths\n */\nfunction expandTildePath(filepath: string): string {\n if (filepath && typeof filepath === 'string' && filepath.startsWith('~')) {\n return filepath.replace(/^~/, os.homedir());\n }\n return filepath;\n}\n\n/**\n * Creates a database adapter based on the provided configuration.\n * If a postgresUrl is provided in the config, a PgDatabaseAdapter is initialized using the PostgresConnectionManager.\n * If no postgresUrl is provided, a PgliteDatabaseAdapter is initialized using PGliteClientManager with the dataDir from the config.\n *\n * @param {object} config - The configuration object.\n * @param {string} [config.dataDir] - The directory where data is stored. Defaults to \"./elizadb\".\n * @param {string} [config.postgresUrl] - The URL for the PostgreSQL database.\n * @param {UUID} agentId - The unique identifier for the agent.\n * @returns {IDatabaseAdapter} The created database adapter.\n */\nexport function createDatabaseAdapter(\n config: {\n dataDir?: string;\n postgresUrl?: string;\n },\n agentId: UUID\n): IDatabaseAdapter {\n if (config.dataDir) {\n config.dataDir = expandTildePath(config.dataDir);\n }\n\n if (config.postgresUrl) {\n if (!globalSingletons.postgresConnectionManager) {\n globalSingletons.postgresConnectionManager = new PostgresConnectionManager(\n config.postgresUrl\n );\n }\n return new PgDatabaseAdapter(agentId, globalSingletons.postgresConnectionManager);\n }\n\n const dataDir = config.dataDir ?? './elizadb';\n\n if (!globalSingletons.pgLiteClientManager) {\n globalSingletons.pgLiteClientManager = new PGliteClientManager({ dataDir });\n }\n\n return new PgliteDatabaseAdapter(agentId, globalSingletons.pgLiteClientManager);\n}\n\n/**\n * SQL plugin for database adapter using Drizzle ORM\n *\n * @typedef {Object} Plugin\n * @property {string} name - The name of the plugin\n * @property {string} description - The description of the plugin\n * @property {Function} init - The initialization function for the plugin\n * @param {any} _ - Input parameter\n * @param {IAgentRuntime} runtime - The runtime environment for the agent\n */\nconst sqlPlugin: Plugin = {\n name: 'sql',\n description: 'SQL database adapter plugin using Drizzle ORM',\n init: async (_, runtime: IAgentRuntime) => {\n const config = {\n dataDir: runtime.getSetting('PGLITE_DATA_DIR') ?? './pglite',\n postgresUrl: runtime.getSetting('POSTGRES_URL'),\n };\n\n try {\n const db = createDatabaseAdapter(config, runtime.agentId);\n logger.success('Database connection established successfully');\n runtime.registerDatabaseAdapter(db);\n } catch (error) {\n logger.error('Failed to initialize database:', error);\n throw error;\n }\n },\n};\n\nexport default sqlPlugin;\n","import { type UUID, logger } from '@elizaos/core';\nimport { type PgliteDatabase, drizzle } from 'drizzle-orm/pglite';\nimport { BaseDrizzleAdapter } from '../base';\nimport { DIMENSION_MAP, type EmbeddingDimensionColumn } from '../schema/embedding';\nimport type { PGliteClientManager } from './manager';\n\n/**\n * PgliteDatabaseAdapter class represents an adapter for interacting with a PgliteDatabase.\n * Extends BaseDrizzleAdapter<PgliteDatabase>.\n *\n * @constructor\n * @param {UUID} agentId - The ID of the agent.\n * @param {PGliteClientManager} manager - The manager for the PgliteDatabase.\n *\n * @method withDatabase\n * @param {() => Promise<T>} operation - The operation to perform on the database.\n * @return {Promise<T>} - The result of the operation.\n *\n * @method init\n * @return {Promise<void>} - A Promise that resolves when the initialization is complete.\n *\n * @method close\n * @return {void} - A Promise that resolves when the database is closed.\n */\nexport class PgliteDatabaseAdapter extends BaseDrizzleAdapter<PgliteDatabase> {\n private manager: PGliteClientManager;\n protected embeddingDimension: EmbeddingDimensionColumn = DIMENSION_MAP[384];\n\n /**\n * Constructor for creating an instance of a class.\n * @param {UUID} agentId - The unique identifier for the agent.\n * @param {PGliteClientManager} manager - The manager for the PGlite client.\n */\n constructor(agentId: UUID, manager: PGliteClientManager) {\n super(agentId);\n this.manager = manager;\n this.db = drizzle(this.manager.getConnection());\n }\n\n /**\n * Asynchronously runs the provided database operation while checking if the database manager is currently shutting down.\n * If the database manager is shutting down, a warning is logged and null is returned.\n *\n * @param {Function} operation - The database operation to be performed.\n * @returns {Promise<T>} A promise that resolves with the result of the database operation.\n */\n protected async withDatabase<T>(operation: () => Promise<T>): Promise<T> {\n if (this.manager.isShuttingDown()) {\n logger.warn('Database is shutting down');\n return null as unknown as T;\n }\n return operation();\n }\n\n /**\n * Asynchronously initializes the database by running migrations using the manager.\n *\n * @returns {Promise<void>} A Promise that resolves when the database initialization is complete.\n */\n async init(): Promise<void> {\n try {\n await this.manager.runMigrations();\n } catch (error) {\n logger.error('Failed to initialize database:', error);\n throw error;\n }\n }\n\n /**\n * Asynchronously closes the manager.\n */\n async close() {\n await this.manager.close();\n }\n}\n","import {\n type Agent,\n type Component,\n DatabaseAdapter,\n type Entity,\n type Memory,\n type MemoryMetadata,\n type Participant,\n type Relationship,\n type Room,\n type Task,\n type UUID,\n type World,\n type Log,\n logger,\n} from '@elizaos/core';\nimport {\n Column,\n and,\n cosineDistance,\n count,\n desc,\n eq,\n gte,\n inArray,\n lte,\n or,\n sql,\n} from 'drizzle-orm';\nimport { v4 } from 'uuid';\nimport { DIMENSION_MAP, type EmbeddingDimensionColumn } from './schema/embedding';\nimport {\n agentTable,\n cacheTable,\n componentTable,\n embeddingTable,\n entityTable,\n logTable,\n memoryTable,\n participantTable,\n relationshipTable,\n roomTable,\n taskTable,\n worldTable,\n} from './schema/index';\nimport type { DrizzleOperations } from './types';\n\n// Define the metadata type inline since we can't import it\n/**\n * Represents metadata information about memory.\n * @typedef {Object} MemoryMetadata\n * @property {string} type - The type of memory.\n * @property {string} [source] - The source of the memory.\n * @property {UUID} [sourceId] - The ID of the source.\n * @property {string} [scope] - The scope of the memory.\n * @property {number} [timestamp] - The timestamp of the memory.\n * @property {string[]} [tags] - The tags associated with the memory.\n * @property {UUID} [documentId] - The ID of the document associated with the memory.\n * @property {number} [position] - The position of the memory.\n */\n\n/**\n * Abstract class representing a base Drizzle adapter for working with databases.\n * This adapter provides a comprehensive set of methods for interacting with a database\n * using Drizzle ORM. It implements the DatabaseAdapter interface and handles operations\n * for various entity types including agents, entities, components, memories, rooms,\n * participants, relationships, tasks, and more.\n *\n * The adapter includes built-in retry logic for database operations, embedding dimension\n * management, and transaction support. Concrete implementations must provide the\n * withDatabase method to execute operations against their specific database.\n *\n * @template TDatabase - The type of Drizzle operations supported by the adapter.\n */\nexport abstract class BaseDrizzleAdapter<\n TDatabase extends DrizzleOperations,\n> extends DatabaseAdapter<TDatabase> {\n protected readonly maxRetries: number = 3;\n protected readonly baseDelay: number = 1000;\n protected readonly maxDelay: number = 10000;\n protected readonly jitterMax: number = 1000;\n protected embeddingDimension: EmbeddingDimensionColumn = DIMENSION_MAP[384];\n\n protected abstract withDatabase<T>(operation: () => Promise<T>): Promise<T>;\n public abstract init(): Promise<void>;\n public abstract close(): Promise<void>;\n\n protected agentId: UUID;\n\n /**\n * Constructor for creating a new instance of Agent with the specified agentId.\n *\n * @param {UUID} agentId - The unique identifier for the agent.\n */\n constructor(agentId: UUID) {\n super();\n this.agentId = agentId;\n }\n\n /**\n * Executes the given operation with retry logic.\n * @template T\n * @param {() => Promise<T>} operation - The operation to be executed.\n * @returns {Promise<T>} A promise that resolves with the result of the operation.\n */\n protected async withRetry<T>(operation: () => Promise<T>): Promise<T> {\n let lastError: Error = new Error('Unknown error');\n\n for (let attempt = 1; attempt <= this.maxRetries; attempt++) {\n try {\n return await operation();\n } catch (error) {\n lastError = error as Error;\n\n if (attempt < this.maxRetries) {\n const backoffDelay = Math.min(this.baseDelay * 2 ** (attempt - 1), this.maxDelay);\n\n const jitter = Math.random() * this.jitterMax;\n const delay = backoffDelay + jitter;\n\n logger.warn(`Database operation failed (attempt ${attempt}/${this.maxRetries}):`, {\n error: error instanceof Error ? error.message : String(error),\n nextRetryIn: `${(delay / 1000).toFixed(1)}s`,\n });\n\n await new Promise((resolve) => setTimeout(resolve, delay));\n } else {\n logger.error('Max retry attempts reached:', {\n error: error instanceof Error ? error.message : String(error),\n totalAttempts: attempt,\n });\n throw error instanceof Error ? error : new Error(String(error));\n }\n }\n }\n\n throw lastError;\n }\n\n /**\n * Asynchronously ensures that an agent exists by checking if an agent with the same name already exists in the system.\n * If the agent does not exist, it will be created with the provided data.\n *\n * @param {Partial<Agent>} agent - The partial data of the agent to ensure its existence.\n * @returns {Promise<void>} - A promise that resolves when the agent is successfully ensured.\n * @throws {Error} - If the agent name is not provided or if there is an issue creating the agent.\n */\n async ensureAgentExists(agent: Partial<Agent>): Promise<void> {\n if (!agent.name) {\n throw new Error('Agent name is required');\n }\n\n const agents = await this.getAgents();\n const existingAgent = agents.find(\n (a: Partial<Agent & { status: string }>) => a.name === agent.name\n );\n\n if (!existingAgent) {\n await this.createAgent(agent);\n }\n }\n\n /**\n * Asynchronously ensures that the given embedding dimension is valid for the agent.\n *\n * @param {number} dimension - The dimension to ensure for the embedding.\n * @returns {Promise<void>} - Resolves once the embedding dimension is ensured.\n */\n async ensureEmbeddingDimension(dimension: number) {\n const existingMemory = await this.db\n .select({\n embedding: embeddingTable,\n })\n .from(memoryTable)\n .innerJoin(embeddingTable, eq(embeddingTable.memoryId, memoryTable.id))\n .where(eq(memoryTable.agentId, this.agentId))\n .limit(1);\n\n if (existingMemory.length > 0) {\n const usedDimension = Object.entries(DIMENSION_MAP).find(\n ([_, colName]) => existingMemory[0].embedding[colName] !== null\n );\n }\n\n this.embeddingDimension = DIMENSION_MAP[dimension];\n }\n\n /**\n * Asynchronously retrieves an agent by their ID from the database.\n * @param {UUID} agentId - The ID of the agent to retrieve.\n * @returns {Promise<Agent | null>} A promise that resolves to the retrieved agent or null if not found.\n */\n async getAgent(agentId: UUID): Promise<Agent | null> {\n return this.withDatabase(async () => {\n const result = await this.db\n .select()\n .from(agentTable)\n .where(eq(agentTable.id, agentId))\n .limit(1);\n\n if (result.length === 0) return null;\n return result[0];\n });\n }\n\n /**\n * Asynchronously retrieves a list of agents from the database.\n *\n * @returns {Promise<Agent[]>} A Promise that resolves to an array of Agent objects.\n */\n async getAgents(): Promise<Agent[]> {\n return this.withDatabase(async () => {\n const result = await this.db.select().from(agentTable);\n\n return result;\n });\n }\n\n /**\n * Asynchronously creates a new agent record in the database.\n *\n * @param {Partial<Agent>} agent The agent object to be created.\n * @returns {Promise<boolean>} A promise that resolves to a boolean indicating the success of the operation.\n */\n async createAgent(agent: Partial<Agent>): Promise<boolean> {\n return this.withDatabase(async () => {\n try {\n await this.db.transaction(async (tx) => {\n await tx.insert(agentTable).values({\n ...agent,\n });\n });\n\n logger.debug('Agent created successfully:', {\n agentId: agent.id,\n });\n return true;\n } catch (error) {\n logger.error('Error creating agent:', {\n error: error instanceof Error ? error.message : String(error),\n agentId: agent.id,\n agent,\n });\n return false;\n }\n });\n }\n\n /**\n * Updates an agent in the database with the provided agent ID and data.\n * @param {UUID} agentId - The unique identifier of the agent to update.\n * @param {Partial<Agent>} agent - The partial agent object containing the fields to update.\n * @returns {Promise<boolean>} - A boolean indicating if the agent was successfully updated.\n */\n async updateAgent(agentId: UUID, agent: Partial<Agent>): Promise<boolean> {\n return this.withDatabase(async () => {\n try {\n if (!agent.id) {\n throw new Error('Agent ID is required for update');\n }\n\n await this.db.transaction(async (tx) => {\n await tx\n .update(agentTable)\n .set({\n ...agent,\n updatedAt: Date.now(),\n })\n .where(eq(agentTable.id, agentId));\n });\n\n logger.debug('Agent updated successfully:', {\n agentId,\n });\n return true;\n } catch (error) {\n logger.error('Error updating agent:', {\n error: error instanceof Error ? error.message : String(error),\n agentId,\n agent,\n });\n return false;\n }\n });\n }\n\n /**\n * Asynchronously deletes an agent with the specified UUID and all related entries.\n *\n * @param {UUID} agentId - The UUID of the agent to be deleted.\n * @returns {Promise<boolean>} - A boolean indicating if the deletion was successful.\n */\n async deleteAgent(agentId: UUID): Promise<boolean> {\n // casacade delete all related for the agent\n return this.withDatabase(async () => {\n await this.db.transaction(async (tx) => {\n await tx.delete(agentTable).where(eq(agentTable.id, agentId));\n });\n return true;\n });\n }\n\n /**\n * Count all agents in the database\n * Used primarily for maintenance and cleanup operations\n */\n /**\n * Asynchronously counts the number of agents in the database.\n * @returns {Promise<number>} A Promise that resolves to the number of agents in the database.\n */\n async countAgents(): Promise<number> {\n return this.withDatabase(async () => {\n try {\n const result = await this.db.select({ count: count() }).from(agentTable);\n\n return result[0]?.count || 0;\n } catch (error) {\n logger.error('Error counting agents:', {\n error: error instanceof Error ? error.message : String(error),\n });\n return 0;\n }\n });\n }\n\n /**\n * Clean up the agents table by removing all agents\n * This is used during server startup to ensure no orphaned agents exist\n * from previous crashes or improper shutdowns\n */\n async cleanupAgents(): Promise<void> {\n return this.withDatabase(async () => {\n try {\n await this.db.delete(agentTable);\n logger.success('Successfully cleaned up agent table');\n } catch (error) {\n logger.error('Error cleaning up agent table:', {\n error: error instanceof Error ? error.message : String(error),\n });\n throw error;\n }\n });\n }\n\n /**\n * Asynchronously retrieves an entity and its components by entity ID.\n * @param {UUID} entityId - The unique identifier of the entity to retrieve.\n * @returns {Promise<Entity | null>} A Promise that resolves to the entity with its components if found, null otherwise.\n */\n async getEntityById(entityId: UUID): Promise<Entity | null> {\n return this.withDatabase(async () => {\n const result = await this.db\n .select({\n entity: entityTable,\n components: componentTable,\n })\n .from(entityTable)\n .leftJoin(componentTable, eq(componentTable.entityId, entityTable.id))\n .where(and(eq(entityTable.id, entityId), eq(entityTable.agentId, this.agentId)));\n\n if (result.length === 0) return null;\n\n // Group components by entity\n const entity = result[0].entity;\n entity.components = result.filter((row) => row.components).map((row) => row.components);\n\n return entity;\n });\n }\n\n /**\n * Asynchronously retrieves all entities for a given room, optionally including their components.\n * @param {UUID} roomId - The unique identifier of the room to get entities for\n * @param {boolean} [includeComponents] - Whether to include component data for each entity\n * @returns {Promise<Entity[]>} A Promise that resolves to an array of entities in the room\n */\n async getEntitiesForRoom(roomId: UUID, includeComponents?: boolean): Promise<Entity[]> {\n return this.withDatabase(async () => {\n const query = this.db\n .select({\n entity: entityTable,\n ...(includeComponents && { components: componentTable }),\n })\n .from(participantTable)\n .leftJoin(\n entityTable,\n and(eq(participantTable.entityId, entityTable.id), eq(entityTable.agentId, this.agentId))\n );\n\n if (includeComponents) {\n query.leftJoin(componentTable, eq(componentTable.entityId, entityTable.id));\n }\n\n const result = await query.where(eq(participantTable.roomId, roomId));\n\n // Group components by entity if includeComponents is true\n const entitiesByIdMap = new Map<UUID, Entity>();\n\n for (const row of result) {\n if (!row.entity) continue;\n\n const entityId = row.entity.id as UUID;\n if (!entitiesByIdMap.has(entityId)) {\n const entity: Entity = {\n ...row.entity,\n components: includeComponents ? [] : undefined,\n };\n entitiesByIdMap.set(entityId, entity);\n }\n\n if (includeComponents && row.components) {\n const entity = entitiesByIdMap.get(entityId);\n if (entity) {\n if (!entity.components) {\n entity.components = [];\n }\n entity.components.push(row.components);\n }\n }\n }\n\n return Array.from(entitiesByIdMap.values());\n });\n }\n\n /**\n * Asynchronously creates a new entity in the database.\n * @param {Entity} entity - The entity object to be created.\n * @returns {Promise<boolean>} A Promise that resolves to a boolean indicating the success of the operation.\n */\n async createEntity(entity: Entity): Promise<boolean> {\n return this.withDatabase(async () => {\n try {\n return await this.db.transaction(async (tx) => {\n await tx.insert(entityTable).values(entity);\n\n logger.debug('Entity created successfully:', {\n entity,\n });\n\n return true;\n });\n } catch (error) {\n logger.error('Error creating entity:', {\n error: error instanceof Error ? error.message : String(error),\n entityId: entity.id,\n name: entity.metadata?.name,\n });\n // trace the error\n logger.trace(error);\n return false;\n }\n });\n }\n\n /**\n * Asynchronously ensures an entity exists, creating it if it doesn't\n * @param entity The entity to ensure exists\n * @returns Promise resolving to boolean indicating success\n */\n protected async ensureEntityExists(entity: Entity): Promise<boolean> {\n if (!entity.id) {\n logger.error('Entity ID is required for ensureEntityExists');\n return false;\n }\n\n try {\n const existingEntity = await this.getEntityById(entity.id);\n\n if (!existingEntity) {\n return await this.createEntity(entity);\n }\n\n return true;\n } catch (error) {\n logger.error('Error ensuring entity exists:', {\n error: error instanceof Error ? error.message : String(error),\n entityId: entity.id,\n });\n return false;\n }\n }\n\n /**\n * Asynchronously updates an entity in the database.\n * @param {Entity} entity - The entity object to be updated.\n * @returns {Promise<void>} A Promise that resolves when the entity is updated.\n */\n async updateEntity(entity: Entity): Promise<void> {\n return this.withDatabase(async () => {\n await this.db\n .update(entityTable)\n .set(entity)\n .where(and(eq(entityTable.id, entity.id as UUID), eq(entityTable.agentId, entity.agentId)));\n });\n }\n\n async getComponent(\n entityId: UUID,\n type: string,\n worldId?: UUID,\n sourceEntityId?: UUID\n ): Promise<Component | null> {\n return this.withDatabase(async () => {\n const conditions = [eq(componentTable.entityId, entityId), eq(componentTable.type, type)];\n\n if (worldId) {\n conditions.push(eq(componentTable.worldId, worldId));\n }\n\n if (sourceEntityId) {\n conditions.push(eq(componentTable.sourceEntityId, sourceEntityId));\n }\n\n const result = await this.db\n .select()\n .from(componentTable)\n .where(and(...conditions));\n return result.length > 0 ? result[0] : null;\n });\n }\n\n /**\n * Asynchronously retrieves all components for a given entity, optionally filtered by world and source entity.\n * @param {UUID} entityId - The unique identifier of the entity to retrieve components for\n * @param {UUID} [worldId] - Optional world ID to filter components by\n * @param {UUID} [sourceEntityId] - Optional source entity ID to filter components by\n * @returns {Promise<Component[]>} A Promise that resolves to an array of components\n */\n async getComponents(entityId: UUID, worldId?: UUID, sourceEntityId?: UUID): Promise<Component[]> {\n return this.withDatabase(async () => {\n const conditions = [eq(componentTable.entityId, entityId)];\n\n if (worldId) {\n conditions.push(eq(componentTable.worldId, worldId));\n }\n\n if (sourceEntityId) {\n conditions.push(eq(componentTable.sourceEntityId, sourceEntityId));\n }\n\n const result = await this.db\n .select({\n id: componentTable.id,\n entityId: componentTable.entityId,\n type: componentTable.type,\n data: componentTable.data,\n worldId: componentTable.worldId,\n sourceEntityId: componentTable.sourceEntityId,\n createdAt: componentTable.createdAt,\n })\n .from(componentTable)\n .where(and(...conditions));\n return result;\n });\n }\n\n /**\n * Asynchronously creates a new component in the database.\n * @param {Component} component - The component object to be created.\n * @returns {Promise<boolean>} A Promise that resolves to a boolean indicating the success of the operation.\n */\n async createComponent(component: Component): Promise<boolean> {\n return this.withDatabase(async () => {\n await this.db.insert(componentTable).values(component);\n return true;\n });\n }\n\n /**\n * Asynchronously updates an existing component in the database.\n * @param {Component} component - The component object to be updated.\n * @returns {Promise<void>} A Promise that resolves when the component is updated.\n */\n async updateComponent(component: Component): Promise<void> {\n return this.withDatabase(async () => {\n await this.db\n .update(componentTable)\n .set(component)\n .where(eq(componentTable.id, component.id));\n });\n }\n\n /**\n * Asynchronously deletes a component from the database.\n * @param {UUID} componentId - The unique identifier of the component to delete.\n * @returns {Promise<void>} A Promise that resolves when the component is deleted.\n */\n async deleteComponent(componentId: UUID): Promise<void> {\n return this.withDatabase(async () => {\n await this.db.delete(componentTable).where(eq(componentTable.id, componentId));\n });\n }\n\n /**\n * Asynchronously retrieves memories from the database based on the provided parameters.\n * @param {Object} params - The parameters for retrieving memories.\n * @param {UUID} params.roomId - The ID of the room to retrieve memories for.\n * @param {number} [params.count] - The maximum number of memories to retrieve.\n * @param {boolean} [params.unique] - Whether to retrieve unique memories only.\n * @param {string} [params.tableName] - The name of the table to retrieve memories from.\n * @param {number} [params.start] - The start date to retrieve memories from.\n * @param {number} [params.end] - The end date to retrieve memories from.\n * @returns {Promise<Memory[]>} A Promise that resolves to an array of memories.\n */\n async getMemories(params: {\n entityId?: UUID;\n agentId?: UUID;\n roomId?: UUID;\n count?: number;\n unique?: boolean;\n tableName: string;\n start?: number;\n end?: number;\n }): Promise<Memory[]> {\n const { entityId, agentId, roomId, tableName, count, unique, start, end } = params;\n\n if (!tableName) throw new Error('tableName is required');\n if (!roomId && !entityId && !agentId)\n throw new Error('roomId, entityId, or agentId is required');\n\n return this.withDatabase(async () => {\n const conditions = [eq(memoryTable.type, tableName)];\n\n if (start) {\n conditions.push(gte(memoryTable.createdAt, start));\n }\n\n if (entityId) {\n conditions.push(eq(memoryTable.entityId, entityId));\n }\n\n if (roomId) {\n conditions.push(eq(memoryTable.roomId, roomId));\n }\n\n if (end) {\n conditions.push(lte(memoryTable.createdAt, end));\n }\n\n if (unique) {\n conditions.push(eq(memoryTable.unique, true));\n }\n\n if (agentId) {\n conditions.push(eq(memoryTable.agentId, agentId));\n }\n\n const query = this.db\n .select({\n memory: {\n id: memoryTable.id,\n type: memoryTable.type,\n createdAt: memoryTable.createdAt,\n content: memoryTable.content,\n entityId: memoryTable.entityId,\n agentId: memoryTable.agentId,\n roomId: memoryTable.roomId,\n unique: memoryTable.unique,\n metadata: memoryTable.metadata,\n },\n embedding: embeddingTable[this.embeddingDimension],\n })\n .from(memoryTable)\n .leftJoin(embeddingTable, eq(embeddingTable.memoryId, memoryTable.id))\n .where(and(...conditions))\n .orderBy(desc(memoryTable.createdAt));\n\n const rows = params.count ? await query.limit(params.count) : await query;\n\n return rows.map((row) => ({\n id: row.memory.id as UUID,\n type: row.memory.type,\n createdAt: row.memory.createdAt,\n content:\n typeof row.memory.content === 'string'\n ? JSON.parse(row.memory.content)\n : row.memory.content,\n entityId: row.memory.entityId as UUID,\n agentId: row.memory.agentId as UUID,\n roomId: row.memory.roomId as UUID,\n unique: row.memory.unique,\n metadata: row.memory.metadata,\n embedding: row.embedding ? Array.from(row.embedding) : undefined,\n }));\n });\n }\n\n /**\n * Asynchronously retrieves memories from the database based on the provided parameters.\n * @param {Object} params - The parameters for retrieving memories.\n * @param {UUID[]} params.roomIds - The IDs of the rooms to retrieve memories for.\n * @param {string} params.tableName - The name of the table to retrieve memories from.\n * @param {number} [params.limit] - The maximum number of memories to retrieve.\n * @returns {Promise<Memory[]>} A Promise that resolves to an array of memories.\n */\n async getMemoriesByRoomIds(params: {\n roomIds: UUID[];\n tableName: string;\n limit?: number;\n }): Promise<Memory[]> {\n return this.withDatabase(async () => {\n if (params.roomIds.length === 0) return [];\n\n const conditions = [\n eq(memoryTable.type, params.tableName),\n inArray(memoryTable.roomId, params.roomIds),\n ];\n\n conditions.push(eq(memoryTable.agentId, this.agentId));\n\n const query = this.db\n .select({\n id: memoryTable.id,\n type: memoryTable.type,\n createdAt: memoryTable.createdAt,\n content: memoryTable.content,\n entityId: memoryTable.entityId,\n agentId: memoryTable.agentId,\n roomId: memoryTable.roomId,\n unique: memoryTable.unique,\n metadata: memoryTable.metadata,\n })\n .from(memoryTable)\n .where(and(...conditions))\n .orderBy(desc(memoryTable.createdAt));\n\n const rows = params.limit ? await query.limit(params.limit) : await query;\n\n return rows.map((row) => ({\n id: row.id as UUID,\n createdAt: row.createdAt,\n content: typeof row.content === 'string' ? JSON.parse(row.content) : row.content,\n entityId: row.entityId as UUID,\n agentId: row.agentId as UUID,\n roomId: row.roomId as UUID,\n unique: row.unique,\n metadata: row.metadata,\n })) as Memory[];\n });\n }\n\n /**\n * Asynchronously retrieves a memory by its unique identifier.\n * @param {UUID} id - The unique identifier of the memory to retrieve.\n * @returns {Promise<Memory | null>} A Promise that resolves to the memory if found, null otherwise.\n */\n async getMemoryById(id: UUID): Promise<Memory | null> {\n return this.withDatabase(async () => {\n const result = await this.db\n .select({\n memory: memoryTable,\n embedding: embeddingTable[this.embeddingDimension],\n })\n .from(memoryTable)\n .leftJoin(embeddingTable, eq(memoryTable.id, embeddingTable.memoryId))\n .where(eq(memoryTable.id, id))\n .limit(1);\n\n if (result.length === 0) return null;\n\n const row = result[0];\n return {\n id: row.memory.id as UUID,\n createdAt: row.memory.createdAt,\n content:\n typeof row.memory.content === 'string'\n ? JSON.parse(row.memory.content)\n : row.memory.content,\n entityId: row.memory.entityId as UUID,\n agentId: row.memory.agentId as UUID,\n roomId: row.memory.roomId as UUID,\n unique: row.memory.unique,\n embedding: row.embedding ?? undefined,\n };\n });\n }\n\n /**\n * Asynchronously retrieves memories from the database based on the provided parameters.\n * @param {Object} params - The parameters for retrieving memories.\n * @param {UUID[]} params.memoryIds - The IDs of the memories to retrieve.\n * @param {string} [params.tableName] - The name of the table to retrieve memories from.\n * @returns {Promise<Memory[]>} A Promise that resolves to an array of memories.\n */\n async getMemoriesByIds(memoryIds: UUID[], tableName?: string): Promise<Memory[]> {\n return this.withDatabase(async () => {\n if (memoryIds.length === 0) return [];\n\n const conditions = [inArray(memoryTable.id, memoryIds)];\n\n if (tableName) {\n conditions.push(eq(memoryTable.type, tableName));\n }\n\n const rows = await this.db\n .select({\n memory: memoryTable,\n embedding: embeddingTable[this.embeddingDimension],\n })\n .from(memoryTable)\n .leftJoin(embeddingTable, eq(embeddingTable.memoryId, memoryTable.id))\n .where(and(...conditions))\n .orderBy(desc(memoryTable.createdAt));\n\n return rows.map((row) => ({\n id: row.memory.id as UUID,\n createdAt: row.memory.createdAt,\n content:\n typeof row.memory.content === 'string'\n ? JSON.parse(row.memory.content)\n : row.memory.content,\n entityId: row.memory.entityId as UUID,\n agentId: row.memory.agentId as UUID,\n roomId: row.memory.roomId as UUID,\n unique: row.memory.unique,\n metadata: row.memory.metadata,\n embedding: row.embedding ?? undefined,\n }));\n });\n }\n\n /**\n * Asynchronously retrieves cached embeddings from the database based on the provided parameters.\n * @param {Object} opts - The parameters for retrieving cached embeddings.\n * @param {string} opts.query_table_name - The name of the table to retrieve embeddings from.\n * @param {number} opts.query_threshold - The threshold for the levenshtein distance.\n * @param {string} opts.query_input - The input string to search for.\n * @param {string} opts.query_field_name - The name of the field to retrieve embeddings from.\n * @param {string} opts.query_field_sub_name - The name of the sub-field to retrieve embeddings from.\n * @param {number} opts.query_match_count - The maximum number of matches to retrieve.\n * @returns {Promise<{ embedding: number[]; levenshtein_score: number }[]>} A Promise that resolves to an array of cached embeddings.\n */\n async getCachedEmbeddings(opts: {\n query_table_name: string;\n query_threshold: number;\n query_input: string;\n query_field_name: string;\n query_field_sub_name: string;\n query_match_count: number;\n }): Promise<{ embedding: number[]; levenshtein_score: number }[]> {\n return this.withDatabase(async () => {\n try {\n const results = await this.db.execute<{\n embedding: number[];\n levenshtein_score: number;\n }>(sql`\n WITH content_text AS (\n SELECT\n m.id,\n COALESCE(\n m.content->>${opts.query_field_sub_name},\n ''\n ) as content_text\n FROM memories m\n WHERE m.type = ${opts.query_table_name}\n AND m.content->>${opts.query_field_sub_name} IS NOT NULL\n ),\n embedded_text AS (\n SELECT \n ct.content_text,\n COALESCE(\n e.dim_384,\n e.dim_512,\n e.dim_768,\n e.dim_1024,\n e.dim_1536,\n e.dim_3072\n ) as embedding\n FROM content_text ct\n LEFT JOIN embeddings e ON e.memory_id = ct.id\n WHERE e.memory_id IS NOT NULL\n )\n SELECT\n embedding,\n levenshtein(${opts.query_input}, content_text) as levenshtein_score\n FROM embedded_text\n WHERE levenshtein(${opts.query_input}, content_text) <= ${opts.query_threshold}\n ORDER BY levenshtein_score\n LIMIT ${opts.query_match_count}\n `);\n\n return results.rows\n .map((row) => ({\n embedding: Array.isArray(row.embedding)\n ? row.embedding\n : typeof row.embedding === 'string'\n ? JSON.parse(row.embedding)\n : [],\n levenshtein_score: Number(row.levenshtein_score),\n }))\n .filter((row) => Array.isArray(row.embedding));\n } catch (error) {\n logger.error('Error in getCachedEmbeddings:', {\n error: error instanceof Error ? error.message : String(error),\n tableName: opts.query_table_name,\n fieldName: opts.query_field_name,\n });\n if (\n error instanceof Error &&\n error.message === 'levenshtein argument exceeds maximum length of 255 characters'\n ) {\n return [];\n }\n throw error;\n }\n });\n }\n\n /**\n * Asynchronously logs an event in the database.\n * @param {Object} params - The parameters for logging an event.\n * @param {Object} params.body - The body of the event to log.\n * @param {UUID} params.entityId - The ID of the entity associated with the event.\n * @param {UUID} params.roomId - The ID of the room associated with the event.\n * @param {string} params.type - The type of the event to log.\n * @returns {Promise<void>} A Promise that resolves when the event is logged.\n */\n async log(params: {\n body: { [key: string]: unknown };\n entityId: UUID;\n roomId: UUID;\n type: string;\n }): Promise<void> {\n return this.withDatabase(async () => {\n try {\n await this.db.transaction(async (tx) => {\n await tx.insert(logTable).values({\n body: sql`${params.body}::jsonb`,\n entityId: params.entityId,\n roomId: params.roomId,\n type: params.type,\n });\n });\n } catch (error) {\n logger.error('Failed to create log entry:', {\n error: error instanceof Error ? error.message : String(error),\n type: params.type,\n roomId: params.roomId,\n entityId: params.entityId,\n });\n throw error;\n }\n });\n }\n\n /**\n * Asynchronously retrieves logs from the database based on the provided parameters.\n * @param {Object} params - The parameters for retrieving logs.\n * @param {UUID} params.entityId - The ID of the entity associated with the logs.\n * @param {UUID} [params.roomId] - The ID of the room associated with the logs.\n * @param {string} [params.type] - The type of the logs to retrieve.\n * @param {number} [params.count] - The maximum number of logs to retrieve.\n * @param {number} [params.offset] - The offset to retrieve logs from.\n * @returns {Promise<Log[]>} A Promise that resolves to an array of logs.\n */\n async getLogs(params: {\n entityId: UUID;\n roomId?: UUID;\n type?: string;\n count?: number;\n offset?: number;\n }): Promise<Log[]> {\n const { entityId, roomId, type, count, offset } = params;\n return this.withDatabase(async () => {\n const result = await this.db\n .select()\n .from(logTable)\n .where(\n and(\n eq(logTable.entityId, entityId),\n roomId ? eq(logTable.roomId, roomId) : undefined,\n type ? eq(logTable.type, type) : undefined\n )\n )\n .orderBy(desc(logTable.createdAt))\n .limit(count ?? 10)\n .offset(offset ?? 0);\n return result;\n });\n }\n\n /**\n * Asynchronously deletes a log from the database based on the provided parameters.\n * @param {UUID} logId - The ID of the log to delete.\n * @returns {Promise<void>} A Promise that resolves when the log is deleted.\n */\n async deleteLog(logId: UUID): Promise<void> {\n return this.withDatabase(async () => {\n await this.db.delete(logTable).where(eq(logTable.id, logId));\n });\n }\n\n /**\n * Asynchronously searches for memories in the database based on the provided parameters.\n * @param {Object} params - The parameters for searching for memories.\n * @param {string} params.tableName - The name of the table to search for memories in.\n * @param {UUID} params.roomId - The ID of the room to search for memories in.\n * @param {number[]} params.embedding - The embedding to search for.\n * @param {number} [params.match_threshold] - The threshold for the cosine distance.\n * @param {number} [params.count] - The maximum number of memories to retrieve.\n * @param {boolean} [params.unique] - Whether to retrieve unique memories only.\n * @returns {Promise<Memory[]>} A Promise that resolves to an array of memories.\n */\n async searchMemories(params: {\n tableName: string;\n roomId: UUID;\n embedding: number[];\n match_threshold: number;\n count: number;\n unique: boolean;\n }): Promise<Memory[]> {\n return await this.searchMemoriesByEmbedding(params.embedding, {\n match_threshold: params.match_threshold,\n count: params.count,\n roomId: params.roomId,\n unique: params.unique,\n tableName: params.tableName,\n });\n }\n\n /**\n * Asynchronously searches for memories in the database based on the provided parameters.\n * @param {number[]} embedding - The embedding to search for.\n * @param {Object} params - The parameters for searching for memories.\n * @param {number} [params.match_threshold] - The threshold for the cosine distance.\n * @param {number} [params.count] - The maximum number of memories to retrieve.\n * @param {UUID} [params.roomId] - The ID of the room to search for memories in.\n * @param {boolean} [params.unique] - Whether to retrieve unique memories only.\n * @param {string} [params.tableName] - The name of the table to search for memories in.\n * @returns {Promise<Memory[]>} A Promise that resolves to an array of memories.\n */\n async searchMemoriesByEmbedding(\n embedding: number[],\n params: {\n match_threshold?: number;\n count?: number;\n roomId?: UUID;\n unique?: boolean;\n tableName: string;\n }\n ): Promise<Memory[]> {\n return this.withDatabase(async () => {\n const cleanVector = embedding.map((n) => (Number.isFinite(n) ? Number(n.toFixed(6)) : 0));\n\n const similarity = sql<number>`1 - (${cosineDistance(\n embeddingTable[this.embeddingDimension],\n cleanVector\n )})`;\n\n const conditions = [eq(memoryTable.type, params.tableName)];\n\n if (params.unique) {\n conditions.push(eq(memoryTable.unique, true));\n }\n\n conditions.push(eq(memoryTable.agentId, this.agentId));\n\n if (params.roomId) {\n conditions.push(eq(memoryTable.roomId, params.roomId));\n }\n\n if (params.match_threshold) {\n conditions.push(gte(similarity, params.match_threshold));\n }\n\n const results = await this.db\n .select({\n memory: memoryTable,\n similarity,\n embedding: embeddingTable[this.embeddingDimension],\n })\n .from(embeddingTable)\n .innerJoin(memoryTable, eq(memoryTable.id, embeddingTable.memoryId))\n .where(and(...conditions))\n .orderBy(desc(similarity))\n .limit(params.count ?? 10);\n\n return results.map((row) => ({\n id: row.memory.id as UUID,\n type: row.memory.type,\n createdAt: row.memory.createdAt,\n content:\n typeof row.memory.content === 'string'\n ? JSON.parse(row.memory.content)\n : row.memory.content,\n entityId: row.memory.entityId as UUID,\n agentId: row.memory.agentId as UUID,\n roomId: row.memory.roomId as UUID,\n unique: row.memory.unique,\n metadata: row.memory.metadata,\n embedding: row.embedding ?? undefined,\n similarity: row.similarity,\n }));\n });\n }\n\n /**\n * Asynchronously creates a new memory in the database.\n * @param {Memory & { metadata?: MemoryMetadata }} memory - The memory object to create.\n * @param {string} tableName - The name of the table to create the memory in.\n * @returns {Promise<UUID>} A Promise that resolves to the ID of the created memory.\n */\n async createMemory(\n memory: Memory & { metadata?: MemoryMetadata },\n tableName: string\n ): Promise<UUID> {\n logger.debug('DrizzleAdapter createMemory:', {\n memoryId: memory.id,\n embeddingLength: memory.embedding?.length,\n contentLength: memory.content?.text?.length,\n });\n\n let isUnique = true;\n if (memory.embedding && Array.isArray(memory.embedding)) {\n const similarMemories = await this.searchMemoriesByEmbedding(memory.embedding, {\n tableName,\n roomId: memory.roomId,\n match_threshold: 0.95,\n count: 1,\n });\n isUnique = similarMemories.length === 0;\n }\n\n const contentToInsert =\n typeof memory.content === 'string' ? JSON.parse(memory.content) : memory.content;\n\n const memoryId = memory.id ?? (v4() as UUID);\n\n await this.db.transaction(async (tx) => {\n await tx.insert(memoryTable).values([\n {\n id: memoryId,\n type: tableName,\n content: sql`${contentToInsert}::jsonb`,\n metadata: sql`${memory.metadata || {}}::jsonb`,\n entityId: memory.entityId,\n roomId: memory.roomId,\n agentId: memory.agentId,\n unique: memory.unique ?? isUnique,\n createdAt: memory.createdAt,\n },\n ]);\n\n if (memory.embedding && Array.isArray(memory.embedding)) {\n const embeddingValues: Record<string, unknown> = {\n id: v4(),\n memoryId: memoryId,\n createdAt: memory.createdAt,\n };\n\n const cleanVector = memory.embedding.map((n) =>\n Number.isFinite(n) ? Number(n.toFixed(6)) : 0\n );\n\n embeddingValues[this.embeddingDimension] = cleanVector;\n\n await tx.insert(embeddingTable).values([embeddingValues]);\n }\n });\n\n return memoryId;\n }\n\n /**\n * Updates an existing memory in the database.\n * @param memory The memory object with updated content and optional embedding\n * @returns Promise resolving to boolean indicating success\n */\n async updateMemory(\n memory: Partial<Memory> & { id: UUID; metadata?: MemoryMetadata }\n ): Promise<boolean> {\n return this.withDatabase(async () => {\n try {\n logger.debug('Updating memory:', {\n memoryId: memory.id,\n hasEmbedding: !!memory.embedding,\n });\n\n await this.db.transaction(async (tx) => {\n // Update memory content if provided\n if (memory.content) {\n const contentToUpdate =\n typeof memory.content === 'string' ? JSON.parse(memory.content) : memory.content;\n\n await tx\n .update(memoryTable)\n .set({\n content: sql`${contentToUpdate}::jsonb`,\n ...(memory.metadata && { metadata: sql`${memory.metadata}::jsonb` }),\n })\n .where(eq(memoryTable.id, memory.id));\n } else if (memory.metadata) {\n // Update only metadata if content is not provided\n await tx\n .update(memoryTable)\n .set({\n metadata: sql`${memory.metadata}::jsonb`,\n })\n .where(eq(memoryTable.id, memory.id));\n }\n\n // Update embedding if provided\n if (memory.embedding && Array.isArray(memory.embedding)) {\n const cleanVector = memory.embedding.map((n) =>\n Number.isFinite(n) ? Number(n.toFixed(6)) : 0\n );\n\n // Check if embedding exists\n const existingEmbedding = await tx\n .select({ id: embeddingTable.id })\n .from(embeddingTable)\n .where(eq(embeddingTable.memoryId, memory.id))\n .limit(1);\n\n if (existingEmbedding.length > 0) {\n // Update existing embedding\n const updateValues: Record<string, unknown> = {};\n updateValues[this.embeddingDimension] = cleanVector;\n\n await tx\n .update(embeddingTable)\n .set(updateValues)\n .where(eq(embeddingTable.memoryId, memory.id));\n } else {\n // Create new embedding\n const embeddingValues: Record<string, unknown> = {\n id: v4(),\n memoryId: memory.id,\n createdAt: Date.now(),\n };\n embeddingValues[this.embeddingDimension] = cleanVector;\n\n await tx.insert(embeddingTable).values([embeddingValues]);\n }\n }\n });\n\n logger.debug('Memory updated successfully:', {\n memoryId: memory.id,\n });\n return true;\n } catch (error) {\n logger.error('Error updating memory:', {\n error: error instanceof Error ? error.message : String(error),\n memoryId: memory.id,\n });\n return false;\n }\n });\n }\n\n /**\n * Asynchronously deletes a memory from the database based on the provided parameters.\n * @param {UUID} memoryId - The ID of the memory to delete.\n * @returns {Promise<void>} A Promise that resolves when the memory is deleted.\n */\n async deleteMemory(memoryId: UUID): Promise<void> {\n return this.withDatabase(async () => {\n await this.db.transaction(async (tx) => {\n // See if there are any fragments that we need to delete\n await this.deleteMemoryFragments(tx, memoryId);\n\n // Then delete the embedding for the main memory\n await tx.delete(embeddingTable).where(eq(embeddingTable.memoryId, memoryId));\n\n // Finally delete the memory itself\n await tx.delete(memoryTable).where(eq(memoryTable.id, memoryId));\n });\n\n logger.debug('Memory and related fragments removed successfully:', {\n memoryId,\n });\n });\n }\n\n /**\n * Deletes all memory fragments that reference a specific document memory\n * @param tx The database transaction\n * @param documentId The UUID of the document memory whose fragments should be deleted\n * @private\n */\n private async deleteMemoryFragments(tx: DrizzleOperations, documentId: UUID): Promise<void> {\n const fragmentsToDelete = await this.getMemoryFragments(tx, documentId);\n\n if (fragmentsToDelete.length > 0) {\n const fragmentIds = fragmentsToDelete.map((f) => f.id) as UUID[];\n\n // Delete embeddings for fragments\n await tx.delete(embeddingTable).where(inArray(embeddingTable.memoryId, fragmentIds));\n\n // Delete the fragments\n await tx.delete(memoryTable).where(inArray(memoryTable.id, fragmentIds));\n\n logger.debug('Deleted related fragments:', {\n documentId,\n fragmentCount: fragmentsToDelete.length,\n });\n }\n }\n\n /**\n * Retrieves all memory fragments that reference a specific document memory\n * @param tx The database transaction\n * @param documentId The UUID of the document memory whose fragments should be retrieved\n * @returns An array of memory fragments\n * @private\n */\n private async getMemoryFragments(tx: DrizzleOperations, documentId: UUID): Promise<Memory[]> {\n const fragments = await tx\n .select({ id: memoryTable.id })\n .from(memoryTable)\n .where(\n and(\n eq(memoryTable.agentId, this.agentId),\n sql`${memoryTable.metadata}->>'documentId' = ${documentId}`\n )\n );\n\n return fragments;\n }\n\n /**\n * Asynchronously deletes all memories from the database based on the provided parameters.\n * @param {UUID} roomId - The ID of the room to delete memories from.\n * @param {string} tableName - The name of the table to delete memories from.\n * @returns {Promise<void>} A Promise that resolves when the memories are deleted.\n */\n async deleteAllMemories(roomId: UUID, tableName: string): Promise<void> {\n return this.withDatabase(async () => {\n await this.db.transaction(async (tx) => {\n const memoryIds = await tx\n .select({ id: memoryTable.id })\n .from(memoryTable)\n .where(and(eq(memoryTable.roomId, roomId), eq(memoryTable.type, tableName)));\n\n if (memoryIds.length > 0) {\n await tx.delete(embeddingTable).where(\n inArray(\n embeddingTable.memoryId,\n memoryIds.map((m) => m.id)\n )\n );\n\n await tx\n .delete(memoryTable)\n .where(and(eq(memoryTable.roomId, roomId), eq(memoryTable.type, tableName)));\n }\n });\n\n logger.debug('All memories removed successfully:', {\n roomId,\n tableName,\n });\n });\n }\n\n /**\n * Asynchronously counts the number of memories in the database based on the provided parameters.\n * @param {UUID} roomId - The ID of the room to count memories in.\n * @param {boolean} [unique] - Whether to count unique memories only.\n * @param {string} [tableName] - The name of the table to count memories in.\n * @returns {Promise<number>} A Promise that resolves to the number of memories.\n */\n async countMemories(roomId: UUID, unique = true, tableName = ''): Promise<number> {\n if (!tableName) throw new Error('tableName is required');\n\n return this.withDatabase(async () => {\n const conditions = [eq(memoryTable.roomId, roomId), eq(memoryTable.type, tableName)];\n\n if (unique) {\n conditions.push(eq(memoryTable.unique, true));\n }\n\n const result = await this.db\n .select({ count: sql<number>`count(*)` })\n .from(memoryTable)\n .where(and(...conditions));\n\n return Number(result[0]?.count ?? 0);\n });\n }\n\n /**\n * Asynchronously retrieves a room from the database based on the provided parameters.\n * @param {UUID} roomId - The ID of the room to retrieve.\n * @returns {Promise<Room | null>} A Promise that resolves to the room if found, null otherwise.\n */\n async getRoom(roomId: UUID): Promise<Room | null> {\n return this.withDatabase(async () => {\n const result = await this.db\n .select({\n id: roomTable.id,\n channelId: roomTable.channelId,\n agentId: roomTable.agentId,\n serverId: roomTable.serverId,\n worldId: roomTable.worldId,\n type: roomTable.type,\n source: roomTable.source,\n })\n .from(roomTable)\n .where(and(eq(roomTable.id, roomId), eq(roomTable.agentId, this.agentId)))\n .limit(1);\n if (result.length === 0) return null;\n return result[0];\n });\n }\n\n /**\n * Asynchronously retrieves all rooms from the database based on the provided parameters.\n * @param {UUID} worldId - The ID of the world to retrieve rooms from.\n * @returns {Promise<Room[]>} A Promise that resolves to an array of rooms.\n */\n async getRooms(worldId: UUID): Promise<Room[]> {\n return this.withDatabase(async () => {\n const result = await this.db.select().from(roomTable).where(eq(roomTable.worldId, worldId));\n return result;\n });\n }\n\n /**\n * Asynchronously updates a room in the database based on the provided parameters.\n * @param {Room} room - The room object to update.\n * @returns {Promise<void>} A Promise that resolves when the room is updated.\n */\n async updateRoom(room: Room): Promise<void> {\n return this.withDatabase(async () => {\n await this.db\n .update(roomTable)\n .set({ ...room, agentId: this.agentId })\n .where(eq(roomTable.id, room.id));\n });\n }\n\n /**\n * Asynchronously creates a new room in the database based on the provided parameters.\n * @param {Room} room - The room object to create.\n * @returns {Promise<UUID>} A Promise that resolves to the ID of the created room.\n */\n async createRoom({\n id,\n name,\n source,\n type,\n channelId,\n serverId,\n worldId,\n metadata,\n }: Room): Promise<UUID> {\n return this.withDatabase(async () => {\n const newRoomId = id || v4();\n await this.db\n .insert(roomTable)\n .values({\n id: newRoomId,\n name,\n agentId: this.agentId,\n source,\n type,\n channelId,\n serverId,\n worldId,\n metadata,\n })\n .onConflictDoNothing({ target: roomTable.id });\n return newRoomId as UUID;\n });\n }\n\n /**\n * Asynchronously deletes a room from the database based on the provided parameters.\n * @param {UUID} roomId - The ID of the room to delete.\n * @returns {Promise<void>} A Promise that resolves when the room is deleted.\n */\n async deleteRoom(roomId: UUID): Promise<void> {\n if (!roomId) throw new Error('Room ID is required');\n return this.withDatabase(async () => {\n await this.db.transaction(async (tx) => {\n await tx.delete(roomTable).where(eq(roomTable.id, roomId));\n });\n });\n }\n\n /**\n * Asynchronously retrieves all rooms for a participant from the database based on the provided parameters.\n * @param {UUID} entityId - The ID of the entity to retrieve rooms for.\n * @returns {Promise<UUID[]>} A Promise that resolves to an array of room IDs.\n */\n async getRoomsForParticipant(entityId: UUID): Promise<UUID[]> {\n return this.withDatabase(async () => {\n const result = await this.db\n .select({ roomId: participantTable.roomId })\n .from(participantTable)\n .innerJoin(roomTable, eq(participantTable.roomId, roomTable.id))\n .where(and(eq(participantTable.entityId, entityId), eq(roomTable.agentId, this.agentId)));\n\n return result.map((row) => row.roomId as UUID);\n });\n }\n\n /**\n * Asynchronously retrieves all rooms for a list of participants from the database based on the provided parameters.\n * @param {UUID[]} entityIds - The IDs of the entities to retrieve rooms for.\n * @returns {Promise<UUID[]>} A Promise that resolves to an array of room IDs.\n */\n async getRoomsForParticipants(entityIds: UUID[]): Promise<UUID[]> {\n return this.withDatabase(async () => {\n const result = await this.db\n .selectDistinct({ roomId: participantTable.roomId })\n .from(participantTable)\n .innerJoin(roomTable, eq(participantTable.roomId, roomTable.id))\n .where(\n and(inArray(participantTable.entityId, entityIds), eq(roomTable.agentId, this.agentId))\n );\n\n return result.map((row) => row.roomId as UUID);\n });\n }\n\n /**\n * Asynchronously adds a participant to a room in the database based on the provided parameters.\n * @param {UUID} entityId - The ID of the entity to add to the room.\n * @param {UUID} roomId - The ID of the room to add the entity to.\n * @returns {Promise<boolean>} A Promise that resolves to a boolean indicating whether the participant was added successfully.\n */\n async addParticipant(entityId: UUID, roomId: UUID): Promise<boolean> {\n return this.withDatabase(async () => {\n try {\n await this.db\n .insert(participantTable)\n .values({\n entityId,\n roomId,\n agentId: this.agentId,\n })\n .onConflictDoNothing();\n return true;\n } catch (error) {\n logger.error('Error adding participant', {\n error: error instanceof Error ? error.message : String(error),\n entityId,\n roomId,\n agentId: this.agentId,\n });\n return false;\n }\n });\n }\n\n /**\n * Asynchronously removes a participant from a room in the database based on the provided parameters.\n * @param {UUID} entityId - The ID of the entity to remove from the room.\n * @param {UUID} roomId - The ID of the room to remove the entity from.\n * @returns {Promise<boolean>} A Promise that resolves to a boolean indicating whether the participant was removed successfully.\n */\n async removeParticipant(entityId: UUID, roomId: UUID): Promise<boolean> {\n return this.withDatabase(async () => {\n try {\n const result = await this.db.transaction(async (tx) => {\n return await tx\n .delete(participantTable)\n .where(\n and(eq(participantTable.entityId, entityId), eq(participantTable.roomId, roomId))\n )\n .returning();\n });\n\n const removed = result.length > 0;\n logger.debug(`Participant ${removed ? 'removed' : 'not found'}:`, {\n entityId,\n roomId,\n removed,\n });\n\n return removed;\n } catch (error) {\n logger.error('Failed to remove participant:', {\n error: error instanceof Error ? error.message : String(error),\n entityId,\n roomId,\n });\n return false;\n }\n });\n }\n\n /**\n * Asynchronously retrieves all participants for an entity from the database based on the provided parameters.\n * @param {UUID} entityId - The ID of the entity to retrieve participants for.\n * @returns {Promise<Participant[]>} A Promise that resolves to an array of participants.\n */\n async getParticipantsForEntity(entityId: UUID): Promise<Participant[]> {\n return this.withDatabase(async () => {\n const result = await this.db\n .select({\n id: participantTable.id,\n entityId: participantTable.entityId,\n roomId: participantTable.roomId,\n })\n .from(participantTable)\n .where(eq(participantTable.entityId, entityId));\n\n const entity = await this.getEntityById(entityId);\n\n if (!entity) {\n return [];\n }\n\n return result.map((row) => ({\n id: row.id as UUID,\n entity: entity,\n }));\n });\n }\n\n /**\n * Asynchronously retrieves all participants for a room from the database based on the provided parameters.\n * @param {UUID} roomId - The ID of the room to retrieve participants for.\n * @returns {Promise<UUID[]>} A Promise that resolves to an array of entity IDs.\n */\n async getParticipantsForRoom(roomId: UUID): Promise<UUID[]> {\n return this.withDatabase(async () => {\n const result = await this.db\n .select({ entityId: participantTable.entityId })\n .from(participantTable)\n .where(eq(participantTable.roomId, roomId));\n\n return result.map((row) => row.entityId as UUID);\n });\n }\n\n /**\n * Asynchronously retrieves the user state for a participant in a room from the database based on the provided parameters.\n * @param {UUID} roomId - The ID of the room to retrieve the participant's user state for.\n * @param {UUID} entityId - The ID of the entity to retrieve the user state for.\n * @returns {Promise<\"FOLLOWED\" | \"MUTED\" | null>} A Promise that resolves to the participant's user state.\n */\n async getParticipantUserState(\n roomId: UUID,\n entityId: UUID\n ): Promise<'FOLLOWED' | 'MUTED' | null> {\n return this.withDatabase(async () => {\n const result = await this.db\n .select({ roomState: participantTable.roomState })\n .from(participantTable)\n .where(\n and(\n eq(participantTable.roomId, roomId),\n eq(participantTable.entityId, entityId),\n eq(participantTable.agentId, this.agentId)\n )\n )\n .limit(1);\n\n return (result[0]?.roomState as 'FOLLOWED' | 'MUTED' | null) ?? null;\n });\n }\n\n /**\n * Asynchronously sets the user state for a participant in a room in the database based on the provided parameters.\n * @param {UUID} roomId - The ID of the room to set the participant's user state for.\n * @param {UUID} entityId - The ID of the entity to set the user state for.\n * @param {string} state - The state to set the participant's user state to.\n * @returns {Promise<void>} A Promise that resolves when the participant's user state is set.\n */\n async setParticipantUserState(\n roomId: UUID,\n entityId: UUID,\n state: 'FOLLOWED' | 'MUTED' | null\n ): Promise<void> {\n return this.withDatabase(async () => {\n try {\n await this.db.transaction(async (tx) => {\n await tx\n .update(participantTable)\n .set({ roomState: state })\n .where(\n and(\n eq(participantTable.roomId, roomId),\n eq(participantTable.entityId, entityId),\n eq(participantTable.agentId, this.agentId)\n )\n );\n });\n } catch (error) {\n logger.error('Failed to set participant user state:', {\n roomId,\n entityId,\n state,\n error: error instanceof Error ? error.message : String(error),\n });\n throw error;\n }\n });\n }\n\n /**\n * Asynchronously creates a new relationship in the database based on the provided parameters.\n * @param {Object} params - The parameters for creating a new relationship.\n * @param {UUID} params.sourceEntityId - The ID of the source entity.\n * @param {UUID} params.targetEntityId - The ID of the target entity.\n * @param {string[]} [params.tags] - The tags for the relationship.\n * @param {Object} [params.metadata] - The metadata for the relationship.\n * @returns {Promise<boolean>} A Promise that resolves to a boolean indicating whether the relationship was created successfully.\n */\n async createRelationship(params: {\n sourceEntityId: UUID;\n targetEntityId: UUID;\n tags?: string[];\n metadata?: { [key: string]: unknown };\n }): Promise<boolean> {\n return this.withDatabase(async () => {\n const id = v4();\n const saveParams = {\n id,\n sourceEntityId: params.sourceEntityId,\n targetEntityId: params.targetEntityId,\n agentId: this.agentId,\n tags: params.tags || [],\n metadata: params.metadata || {},\n };\n try {\n await this.db.insert(relationshipTable).values(saveParams);\n return true;\n } catch (error) {\n logger.error('Error creating relationship:', {\n error: error instanceof Error ? error.message : String(error),\n saveParams,\n });\n return false;\n }\n });\n }\n\n /**\n * Asynchronously updates an existing relationship in the database based on the provided parameters.\n * @param {Relationship} relationship - The relationship object to update.\n * @returns {Promise<void>} A Promise that resolves when the relationship is updated.\n */\n async updateRelationship(relationship: Relationship): Promise<void> {\n return this.withDatabase(async () => {\n try {\n await this.db\n .update(relationshipTable)\n .set({\n tags: relationship.tags || [],\n metadata: relationship.metadata || {},\n })\n .where(eq(relationshipTable.id, relationship.id));\n } catch (error) {\n logger.error('Error updating relationship:', {\n error: error instanceof Error ? error.message : String(error),\n relationship,\n });\n throw error;\n }\n });\n }\n\n /**\n * Asynchronously retrieves a relationship from the database based on the provided parameters.\n * @param {Object} params - The parameters for retrieving a relationship.\n * @param {UUID} params.sourceEntityId - The ID of the source entity.\n * @param {UUID} params.targetEntityId - The ID of the target entity.\n * @returns {Promise<Relationship | null>} A Promise that resolves to the relationship if found, null otherwise.\n */\n async getRelationship(params: {\n sourceEntityId: UUID;\n targetEntityId: UUID;\n }): Promise<Relationship | null> {\n return this.withDatabase(async () => {\n try {\n const result = await this.db\n .select()\n .from(relationshipTable)\n .where(\n and(\n eq(relationshipTable.sourceEntityId, params.sourceEntityId),\n eq(relationshipTable.targetEntityId, params.targetEntityId),\n eq(relationshipTable.agentId, this.agentId)\n )\n )\n .limit(1);\n\n if (result.length === 0) {\n return null;\n }\n\n return {\n id: result[0].id,\n sourceEntityId: result[0].sourceEntityId,\n targetEntityId: result[0].targetEntityId,\n agentId: result[0].agentId,\n tags: result[0].tags || [],\n metadata: result[0].metadata || {},\n createdAt: result[0].createdAt?.toString(),\n };\n } catch (error) {\n logger.error('Error getting relationship:', {\n error: error instanceof Error ? error.message : String(error),\n params,\n });\n return null;\n }\n });\n }\n\n /**\n * Asynchronously retrieves all relationships from the database based on the provided parameters.\n * @param {Object} params - The parameters for retrieving relationships.\n * @param {UUID} params.entityId - The ID of the entity to retrieve relationships for.\n * @param {string[]} [params.tags] - The tags to filter relationships by.\n * @returns {Promise<Relationship[]>} A Promise that resolves to an array of relationships.\n */\n async getRelationships(params: { entityId: UUID; tags?: string[] }): Promise<Relationship[]> {\n return this.withDatabase(async () => {\n try {\n let query = this.db\n .select()\n .from(relationshipTable)\n .where(\n and(\n or(\n eq(relationshipTable.sourceEntityId, params.entityId),\n eq(relationshipTable.targetEntityId, params.entityId)\n ),\n eq(relationshipTable.agentId, this.agentId)\n )\n );\n\n // Filter by tags if provided\n if (params.tags && params.tags.length > 0) {\n // Filter by tags - find tasks that have ALL of the specified tags\n // Using @> operator which checks if left array contains all elements from right array\n const tagParams = params.tags.map((tag) => `'${tag.replace(/'/g, \"''\")}'`).join(', ');\n query = query.where(\n sql`${relationshipTable.tags} @> ARRAY[${sql.raw(tagParams)}]::text[]`\n );\n }\n\n const results = await query;\n\n return results.map((result) => ({\n id: result.id,\n sourceEntityId: result.sourceEntityId,\n targetEntityId: result.targetEntityId,\n agentId: result.agentId,\n tags: result.tags || [],\n metadata: result.metadata || {},\n createdAt: result.createdAt?.toString(),\n }));\n } catch (error) {\n logger.error('Error getting relationships:', {\n error: error instanceof Error ? error.message : String(error),\n params,\n });\n return [];\n }\n });\n }\n\n /**\n * Asynchronously retrieves a cache value from the database based on the provided key.\n * @param {string} key - The key to retrieve the cache value for.\n * @returns {Promise<T | undefined>} A Promise that resolves to the cache value if found, undefined otherwise.\n */\n async getCache<T>(key: string): Promise<T | undefined> {\n return this.withDatabase(async () => {\n try {\n const result = await this.db\n .select()\n .from(cacheTable)\n .where(and(eq(cacheTable.agentId, this.agentId), eq(cacheTable.key, key)));\n\n return result[0]?.value as T | undefined;\n } catch (error) {\n logger.error('Error fetching cache', {\n error: error instanceof Error ? error.message : String(error),\n key: key,\n agentId: this.agentId,\n });\n return undefined;\n }\n });\n }\n\n /**\n * Asynchronously sets a cache value in the database based on the provided key and value.\n * @param {string} key - The key to set the cache value for.\n * @param {T} value - The value to set in the cache.\n * @returns {Promise<boolean>} A Promise that resolves to a boolean indicating whether the cache value was set successfully.\n */\n async setCache<T>(key: string, value: T): Promise<boolean> {\n return this.withDatabase(async () => {\n try {\n await this.db.transaction(async (tx) => {\n await tx\n .insert(cacheTable)\n .values({\n key: key,\n agentId: this.agentId,\n value: value,\n })\n .onConflictDoUpdate({\n target: [cacheTable.key, cacheTable.agentId],\n set: {\n value: value,\n },\n });\n });\n return true;\n } catch (error) {\n logger.error('Error setting cache', {\n error: error instanceof Error ? error.message : String(error),\n key: key,\n agentId: this.agentId,\n });\n return false;\n }\n });\n }\n\n /**\n * Asynchronously deletes a cache value from the database based on the provided key.\n * @param {string} key - The key to delete the cache value for.\n * @returns {Promise<boolean>} A Promise that resolves to a boolean indicating whether the cache value was deleted successfully.\n */\n async deleteCache(key: string): Promise<boolean> {\n return this.withDatabase(async () => {\n try {\n await this.db.transaction(async (tx) => {\n await tx\n .delete(cacheTable)\n .where(and(eq(cacheTable.agentId, this.agentId), eq(cacheTable.key, key)));\n });\n return true;\n } catch (error) {\n logger.error('Error deleting cache', {\n error: error instanceof Error ? error.message : String(error),\n key: key,\n agentId: this.agentId,\n });\n return false;\n }\n });\n }\n\n /**\n * Asynchronously creates a new world in the database based on the provided parameters.\n * @param {World} world - The world object to create.\n * @returns {Promise<UUID>} A Promise that resolves to the ID of the created world.\n */\n async createWorld(world: World): Promise<UUID> {\n return this.withDatabase(async () => {\n const newWorldId = world.id || v4();\n await this.db.insert(worldTable).values({\n ...world,\n id: newWorldId,\n });\n return newWorldId;\n });\n }\n\n /**\n * Asynchronously retrieves a world from the database based on the provided parameters.\n * @param {UUID} id - The ID of the world to retrieve.\n * @returns {Promise<World | null>} A Promise that resolves to the world if found, null otherwise.\n */\n async getWorld(id: UUID): Promise<World | null> {\n return this.withDatabase(async () => {\n const result = await this.db.select().from(worldTable).where(eq(worldTable.id, id));\n return result[0] as World | null;\n });\n }\n\n /**\n * Asynchronously retrieves all worlds from the database based on the provided parameters.\n * @returns {Promise<World[]>} A Promise that resolves to an array of worlds.\n */\n async getAllWorlds(): Promise<World[]> {\n return this.withDatabase(async () => {\n const result = await this.db\n .select()\n .from(worldTable)\n .where(eq(worldTable.agentId, this.agentId));\n return result as World[];\n });\n }\n\n /**\n * Asynchronously updates an existing world in the database based on the provided parameters.\n * @param {World} world - The world object to update.\n * @returns {Promise<void>} A Promise that resolves when the world is updated.\n */\n async updateWorld(world: World): Promise<void> {\n return this.withDatabase(async () => {\n await this.db.update(worldTable).set(world).where(eq(worldTable.id, world.id));\n });\n }\n\n /**\n * Asynchronously removes a world from the database based on the provided parameters.\n * @param {UUID} id - The ID of the world to remove.\n * @returns {Promise<void>} A Promise that resolves when the world is removed.\n */\n async removeWorld(id: UUID): Promise<void> {\n return this.withDatabase(async () => {\n await this.db.delete(worldTable).where(eq(worldTable.id, id));\n });\n }\n\n /**\n * Asynchronously creates a new task in the database based on the provided parameters.\n * @param {Task} task - The task object to create.\n * @returns {Promise<UUID>} A Promise that resolves to the ID of the created task.\n */\n async createTask(task: Task): Promise<UUID> {\n return this.withRetry(async () => {\n return this.withDatabase(async () => {\n const now = new Date();\n const metadata = task.metadata || {};\n\n const values = {\n id: task.id as UUID,\n name: task.name,\n description: task.description,\n roomId: task.roomId,\n worldId: task.worldId,\n tags: task.tags,\n metadata: metadata,\n createdAt: now,\n updatedAt: now,\n agentId: this.agentId,\n };\n const result = await this.db\n .insert(taskTable)\n .values(values)\n .returning({ id: taskTable.id });\n\n return result[0].id;\n });\n });\n }\n\n /**\n * Asynchronously retrieves tasks based on specified parameters.\n * @param params Object containing optional roomId and tags to filter tasks\n * @returns Promise resolving to an array of Task objects\n */\n async getTasks(params: { roomId?: UUID; tags?: string[] }): Promise<Task[]> {\n return this.withRetry(async () => {\n return this.withDatabase(async () => {\n let query = this.db.select().from(taskTable).where(eq(taskTable.agentId, this.agentId));\n\n // Apply filters if provided\n if (params.roomId) {\n query = query.where(eq(taskTable.roomId, params.roomId));\n }\n\n if (params.tags && params.tags.length > 0) {\n // Filter by tags - find tasks that have ALL of the specified tags\n // Using @> operator which checks if left array contains all elements from right array\n const tagParams = params.tags.map((tag) => `'${tag.replace(/'/g, \"''\")}'`).join(', ');\n query = query.where(sql`${taskTable.tags} @> ARRAY[${sql.raw(tagParams)}]::text[]`);\n }\n\n const result = await query;\n\n return result.map((row) => ({\n id: row.id,\n name: row.name,\n description: row.description,\n roomId: row.roomId,\n worldId: row.worldId,\n tags: row.tags,\n metadata: row.metadata,\n }));\n });\n });\n }\n\n /**\n * Asynchronously retrieves a specific task by its name.\n * @param name The name of the task to retrieve\n * @returns Promise resolving to the Task object if found, null otherwise\n */\n async getTasksByName(name: string): Promise<Task[]> {\n return this.withRetry(async () => {\n return this.withDatabase(async () => {\n const result = await this.db\n .select()\n .from(taskTable)\n .where(and(eq(taskTable.name, name), eq(taskTable.agentId, this.agentId)));\n\n return result.map((row) => ({\n id: row.id,\n name: row.name,\n description: row.description,\n roomId: row.roomId,\n worldId: row.worldId,\n tags: row.tags || [],\n metadata: row.metadata || {},\n }));\n });\n });\n }\n\n /**\n * Asynchronously retrieves a specific task by its ID.\n * @param id The UUID of the task to retrieve\n * @returns Promise resolving to the Task object if found, null otherwise\n */\n async getTask(id: UUID): Promise<Task | null> {\n return this.withRetry(async () => {\n return this.withDatabase(async () => {\n const result = await this.db\n .select()\n .from(taskTable)\n .where(and(eq(taskTable.id, id), eq(taskTable.agentId, this.agentId)))\n .limit(1);\n\n if (result.length === 0) {\n return null;\n }\n\n const row = result[0];\n return {\n id: row.id,\n name: row.name,\n description: row.description,\n roomId: row.roomId,\n worldId: row.worldId,\n tags: row.tags || [],\n metadata: row.metadata || {},\n };\n });\n });\n }\n\n /**\n * Asynchronously updates an existing task in the database.\n * @param id The UUID of the task to update\n * @param task Partial Task object containing the fields to update\n * @returns Promise resolving when the update is complete\n */\n async updateTask(id: UUID, task: Partial<Task>): Promise<void> {\n await this.withRetry(async () => {\n await this.withDatabase(async () => {\n const updateValues: Partial<Task> = {};\n\n // Add fields to update if they exist in the partial task object\n if (task.name !== undefined) updateValues.name = task.name;\n if (task.description !== undefined) updateValues.description = task.description;\n if (task.roomId !== undefined) updateValues.roomId = task.roomId;\n if (task.worldId !== undefined) updateValues.worldId = task.worldId;\n if (task.tags !== undefined) updateValues.tags = task.tags;\n\n task.updatedAt = Date.now();\n\n // Handle metadata updates\n if (task.metadata) {\n // Get current task to merge metadata\n const currentTask = await this.getTask(id);\n if (currentTask) {\n const currentMetadata = currentTask.metadata || {};\n const newMetadata = {\n ...currentMetadata,\n ...task.metadata,\n };\n updateValues.metadata = newMetadata;\n } else {\n updateValues.metadata = {\n ...task.metadata,\n };\n }\n }\n\n await this.db\n .update(taskTable)\n .set(updateValues)\n .where(and(eq(taskTable.id, id), eq(taskTable.agentId, this.agentId)));\n });\n });\n }\n\n /**\n * Asynchronously deletes a task from the database.\n * @param id The UUID of the task to delete\n * @returns Promise resolving when the deletion is complete\n */\n async deleteTask(id: UUID): Promise<void> {\n await this.withRetry(async () => {\n await this.withDatabase(async () => {\n await this.db\n .delete(taskTable)\n .where(and(eq(taskTable.id, id), eq(taskTable.agentId, this.agentId)));\n });\n });\n }\n\n /**\n * Asynchronously retrieves group chat memories from all rooms under a given server.\n * It fetches all room IDs associated with the `serverId`, then retrieves memories\n * from those rooms in descending order (latest to oldest), with an optional count limit.\n *\n * @param {Object} params - Parameters for fetching memories.\n * @param {UUID} params.serverId - The server ID to fetch memories for.\n * @param {number} [params.count] - The maximum number of memories to retrieve.\n * @returns {Promise<Memory[]>} - A promise that resolves to an array of memory objects.\n */\n async getMemoriesByServerId(params: { serverId: UUID; count?: number }): Promise<Memory[]> {\n return this.withDatabase(async () => {\n // Step 1: Fetch all room IDs associated with the given serverId\n const roomIdsResult = await this.db\n .select({ roomId: roomTable.id })\n .from(roomTable)\n .where(eq(roomTable.serverId, params.serverId));\n\n if (roomIdsResult.length === 0) return [];\n\n const roomIds = roomIdsResult.map((row) => row.roomId);\n\n // Step 2: Fetch all memories for these rooms, ordered from latest to oldest\n const query = this.db\n .select({\n memory: memoryTable,\n embedding: embeddingTable[this.embeddingDimension],\n })\n .from(memoryTable)\n .leftJoin(embeddingTable, eq(embeddingTable.memoryId, memoryTable.id))\n .where(inArray(memoryTable.roomId, roomIds))\n .orderBy(desc(memoryTable.createdAt));\n\n // Step 3: Apply the count limit if provided\n const rows = params.count ? await query.limit(params.count) : await query;\n\n return rows.map((row) => ({\n id: row.memory.id as UUID,\n type: row.memory.type,\n createdAt: row.memory.createdAt,\n content:\n typeof row.memory.content === 'string'\n ? JSON.parse(row.memory.content)\n : row.memory.content,\n entityId: row.memory.entityId as UUID,\n agentId: row.memory.agentId as UUID,\n roomId: row.memory.roomId as UUID,\n unique: row.memory.unique,\n embedding: row.embedding ?? undefined,\n }));\n });\n }\n\n /**\n * Asynchronously deletes all rooms associated with a specific serverId.\n * @param {UUID} serverId - The server ID to delete rooms for.\n * @returns {Promise<void>} A Promise that resolves when the rooms are deleted.\n */\n async deleteRoomsByServerId(serverId: UUID): Promise<void> {\n return this.withDatabase(async () => {\n await this.db.transaction(async (tx) => {\n const roomIdsResult = await tx\n .select({ roomId: roomTable.id })\n .from(roomTable)\n .where(eq(roomTable.serverId, serverId));\n\n if (roomIdsResult.length === 0) return;\n\n const roomIds = roomIdsResult.map((row) => row.roomId);\n\n await tx\n .delete(embeddingTable)\n .where(\n inArray(\n embeddingTable.memoryId,\n tx\n .select({ id: memoryTable.id })\n .from(memoryTable)\n .where(inArray(memoryTable.roomId, roomIds))\n )\n );\n await tx.delete(memoryTable).where(inArray(memoryTable.roomId, roomIds));\n\n await tx.delete(participantTable).where(inArray(participantTable.roomId, roomIds));\n\n await tx.delete(logTable).where(inArray(logTable.roomId, roomIds));\n\n await tx.delete(roomTable).where(inArray(roomTable.id, roomIds));\n });\n\n logger.debug('Rooms and related logs deleted successfully for server:', {\n serverId,\n });\n });\n }\n}\n","import { sql } from 'drizzle-orm';\nimport { check, foreignKey, index, pgTable, uuid, vector } from 'drizzle-orm/pg-core';\nimport { memoryTable } from './memory';\nimport { numberTimestamp } from './types';\n\nexport const VECTOR_DIMS = {\n SMALL: 384,\n MEDIUM: 512,\n LARGE: 768,\n XL: 1024,\n XXL: 1536,\n XXXL: 3072,\n} as const;\n\nexport const DIMENSION_MAP = {\n [VECTOR_DIMS.SMALL]: 'dim384',\n [VECTOR_DIMS.MEDIUM]: 'dim512',\n [VECTOR_DIMS.LARGE]: 'dim768',\n [VECTOR_DIMS.XL]: 'dim1024',\n [VECTOR_DIMS.XXL]: 'dim1536',\n [VECTOR_DIMS.XXXL]: 'dim3072',\n} as const;\n\n/**\n * Definition of the embeddings table in the database.\n * Contains columns for ID, Memory ID, Creation Timestamp, and multiple vector dimensions.\n */\nexport const embeddingTable = pgTable(\n 'embeddings',\n {\n id: uuid('id').primaryKey().defaultRandom().notNull(),\n memoryId: uuid('memory_id').references(() => memoryTable.id),\n createdAt: numberTimestamp('created_at')\n .default(sql`now()`)\n .notNull(),\n dim384: vector('dim_384', { dimensions: VECTOR_DIMS.SMALL }),\n dim512: vector('dim_512', { dimensions: VECTOR_DIMS.MEDIUM }),\n dim768: vector('dim_768', { dimensions: VECTOR_DIMS.LARGE }),\n dim1024: vector('dim_1024', { dimensions: VECTOR_DIMS.XL }),\n dim1536: vector('dim_1536', { dimensions: VECTOR_DIMS.XXL }),\n dim3072: vector('dim_3072', { dimensions: VECTOR_DIMS.XXXL }),\n },\n (table) => [\n check('embedding_source_check', sql`\"memory_id\" IS NOT NULL`),\n index('idx_embedding_memory').on(table.memoryId),\n foreignKey({\n name: 'fk_embedding_memory',\n columns: [table.memoryId],\n foreignColumns: [memoryTable.id],\n }).onDelete('cascade'),\n ]\n);\n\n/**\n * Defines the possible values for the Embedding Dimension Column.\n * It can be \"dim384\", \"dim512\", \"dim768\", \"dim1024\", \"dim1536\", or \"dim3072\".\n */\nexport type EmbeddingDimensionColumn =\n | 'dim384'\n | 'dim512'\n | 'dim768'\n | 'dim1024'\n | 'dim1536'\n | 'dim3072';\n\n/**\n * Retrieve the type of a specific column in the EmbeddingTable based on the EmbeddingDimensionColumn key.\n */\nexport type EmbeddingTableColumn = (typeof embeddingTable._.columns)[EmbeddingDimensionColumn];\n","import { relations, sql } from 'drizzle-orm';\nimport {\n boolean,\n check,\n foreignKey,\n index,\n jsonb,\n pgTable,\n text,\n unique,\n uuid,\n vector,\n} from 'drizzle-orm/pg-core';\nimport { agentTable } from './agent';\nimport { embeddingTable } from './embedding';\nimport { entityTable } from './entity';\nimport { roomTable } from './room';\nimport { numberTimestamp } from './types';\n\n/**\n * Definition of the memory table in the database.\n *\n * @param {string} tableName - The name of the table.\n * @param {object} columns - An object containing the column definitions.\n * @param {function} indexes - A function that defines the indexes for the table.\n * @returns {object} - The memory table object.\n */\nexport const memoryTable = pgTable(\n 'memories',\n {\n id: uuid('id').primaryKey().notNull(),\n type: text('type').notNull(),\n createdAt: numberTimestamp('createdAt')\n .default(sql`now()`)\n .notNull(),\n content: jsonb('content').notNull(),\n entityId: uuid('entityId').references(() => entityTable.id, {\n onDelete: 'cascade',\n }),\n agentId: uuid('agentId').references(() => agentTable.id, {\n onDelete: 'cascade',\n }),\n roomId: uuid('roomId').references(() => roomTable.id, {\n onDelete: 'cascade',\n }),\n unique: boolean('unique').default(true).notNull(),\n metadata: jsonb('metadata').default({}).notNull(),\n },\n (table) => [\n index('idx_memories_type_room').on(table.type, table.roomId),\n foreignKey({\n name: 'fk_room',\n columns: [table.roomId],\n foreignColumns: [roomTable.id],\n }).onDelete('cascade'),\n foreignKey({\n name: 'fk_user',\n columns: [table.entityId],\n foreignColumns: [entityTable.id],\n }).onDelete('cascade'),\n foreignKey({\n name: 'fk_agent',\n columns: [table.agentId],\n foreignColumns: [entityTable.id],\n }).onDelete('cascade'),\n index('idx_memories_metadata_type').on(sql`((metadata->>'type'))`),\n index('idx_memories_document_id').on(sql`((metadata->>'documentId'))`),\n index('idx_fragments_order').on(\n sql`((metadata->>'documentId'))`,\n sql`((metadata->>'position'))`\n ),\n check(\n 'fragment_metadata_check',\n sql`\n CASE \n WHEN metadata->>'type' = 'fragment' THEN\n metadata ? 'documentId' AND \n metadata ? 'position'\n ELSE true\n END\n `\n ),\n check(\n 'document_metadata_check',\n sql`\n CASE \n WHEN metadata->>'type' = 'document' THEN\n metadata ? 'timestamp'\n ELSE true\n END\n `\n ),\n ]\n);\n\nexport const memoryRelations = relations(memoryTable, ({ one }) => ({\n embedding: one(embeddingTable),\n}));\n","import type { MessageExample } from '@elizaos/core';\nimport { sql } from 'drizzle-orm';\nimport { boolean, jsonb, pgTable, text, unique, uuid } from 'drizzle-orm/pg-core';\nimport { numberTimestamp } from './types';\n\n/**\n * Represents a table for storing agent data.\n *\n * @type {Table}\n */\nexport const agentTable = pgTable(\n 'agents',\n {\n id: uuid('id').primaryKey().defaultRandom(),\n enabled: boolean('enabled').default(true).notNull(),\n createdAt: numberTimestamp('createdAt')\n .default(sql`now()`)\n .notNull(),\n\n updatedAt: numberTimestamp('updatedAt')\n .default(sql`now()`)\n .notNull(),\n\n // Character\n name: text('name'),\n username: text('username'),\n system: text('system'),\n bio: jsonb('bio').$type<string | string[]>().notNull(),\n messageExamples: jsonb('message_examples')\n .$type<MessageExample[][]>()\n .default(sql`'[]'::jsonb`),\n postExamples: jsonb('post_examples')\n .$type<string[]>()\n .default(sql`'[]'::jsonb`),\n topics: jsonb('topics')\n .$type<string[]>()\n .default(sql`'[]'::jsonb`),\n adjectives: jsonb('adjectives')\n .$type<string[]>()\n .default(sql`'[]'::jsonb`),\n knowledge: jsonb('knowledge')\n .$type<(string | { path: string; shared?: boolean })[]>()\n .default(sql`'[]'::jsonb`),\n plugins: jsonb('plugins')\n .$type<string[]>()\n .default(sql`'[]'::jsonb`),\n settings: jsonb('settings')\n .$type<{\n secrets?: { [key: string]: string | boolean | number };\n [key: string]: unknown;\n }>()\n .default(sql`'{}'::jsonb`),\n style: jsonb('style')\n .$type<{\n all?: string[];\n chat?: string[];\n post?: string[];\n }>()\n .default(sql`'{}'::jsonb`),\n },\n (table) => {\n return {\n nameUnique: unique('name_unique').on(table.name),\n };\n }\n);\n","import { customType } from 'drizzle-orm/pg-core';\n\n/**\n * Represents a custom type for converting a string to a JSONB format and vice versa.\n * @param {Object} options - The options for the custom type.\n * @param {Function} options.dataType - A function that returns the data type as \"jsonb\".\n * @param {Function} options.toDriver - A function that converts a string to a JSON string.\n * @param {Function} options.fromDriver - A function that converts a JSON string back to a string.\n * @returns {Object} - The custom type for string to JSONB conversion.\n */\n\nexport const stringJsonb = customType<{ data: string; driverData: string }>({\n dataType() {\n return 'jsonb';\n },\n toDriver(value: string): string {\n return JSON.stringify(value);\n },\n fromDriver(value: string): string {\n return JSON.stringify(value);\n },\n});\n\n/**\n * Represents a custom type for converting a number to a timestamp string and vice versa.\n * @param {Object} options - The options for the custom type.\n * @param {Function} options.dataType - A function that returns the data type as \"timestamptz\".\n * @param {Function} options.toDriver - A function that converts a number to a timestamp string using the Date object's toISOString method.\n * @param {Function} options.fromDriver - A function that converts a timestamp string to a number using the Date object's getTime method.\n * @returns {Object} - The custom type for number to timestamp conversion.\n */\nexport const numberTimestamp = customType<{ data: number; driverData: string }>({\n dataType() {\n return 'timestamptz';\n },\n toDriver(value: number): string {\n return new Date(value).toISOString();\n },\n fromDriver(value: string): number {\n return new Date(value).getTime();\n },\n});\n","import { sql } from 'drizzle-orm';\nimport { jsonb, pgTable, text, unique, uuid } from 'drizzle-orm/pg-core';\nimport { agentTable } from './agent';\nimport { numberTimestamp } from './types';\n\n/**\n * Represents an entity table in the database.\n * Includes columns for id, agentId, createdAt, names, and metadata.\n */\nexport const entityTable = pgTable(\n 'entities',\n {\n id: uuid('id').notNull().primaryKey(),\n agentId: uuid('agentId')\n .notNull()\n .references(() => agentTable.id, {\n onDelete: 'cascade',\n }),\n createdAt: numberTimestamp('createdAt')\n .default(sql`now()`)\n .notNull(),\n names: text('names')\n .array()\n .default(sql`'{}'::text[]`),\n metadata: jsonb('metadata').default(sql`'{}'::jsonb`),\n },\n (table) => {\n return {\n idAgentIdUnique: unique('id_agent_id_unique').on(table.id, table.agentId),\n };\n }\n);\n","import { sql } from 'drizzle-orm';\nimport { jsonb, pgTable, text, uuid } from 'drizzle-orm/pg-core';\nimport { agentTable } from './agent';\nimport { numberTimestamp } from './types';\nimport { worldTable } from './worldTable';\n\n/**\n * Defines a table schema for 'rooms' in the database.\n *\n * @typedef {object} RoomTable\n * @property {string} id - The unique identifier for the room.\n * @property {string} agentId - The UUID of the agent associated with the room.\n * @property {string} source - The source of the room.\n * @property {string} type - The type of the room.\n * @property {string} serverId - The server ID of the room.\n * @property {string} worldId - The UUID of the world associated with the room.\n * @property {string} name - The name of the room.\n * @property {object} metadata - Additional metadata for the room in JSON format.\n * @property {string} channelId - The channel ID of the room.\n * @property {number} createdAt - The timestamp of when the room was created.\n */\nexport const roomTable = pgTable('rooms', {\n id: uuid('id')\n .notNull()\n .primaryKey()\n .default(sql`gen_random_uuid()`),\n agentId: uuid('agentId').references(() => agentTable.id, {\n onDelete: 'cascade',\n }),\n source: text('source').notNull(),\n type: text('type').notNull(),\n serverId: text('serverId'),\n worldId: uuid('worldId').references(() => worldTable.id, {\n onDelete: 'cascade',\n }),\n name: text('name'),\n metadata: jsonb('metadata'),\n channelId: text('channelId'),\n createdAt: numberTimestamp('createdAt')\n .default(sql`now()`)\n .notNull(),\n});\n","import { sql } from 'drizzle-orm';\nimport { jsonb, pgTable, text, uuid } from 'drizzle-orm/pg-core';\nimport { agentTable } from './agent';\nimport { numberTimestamp } from './types';\n\n/**\n * Represents a table schema for worlds in the database.\n *\n * @type {PgTable}\n */\n\nexport const worldTable = pgTable('worlds', {\n id: uuid('id')\n .notNull()\n .primaryKey()\n .default(sql`gen_random_uuid()`),\n agentId: uuid('agentId')\n .notNull()\n .references(() => agentTable.id, { onDelete: 'cascade' }),\n name: text('name').notNull(),\n metadata: jsonb('metadata'),\n serverId: text('serverId').notNull(),\n createdAt: numberTimestamp('createdAt')\n .default(sql`now()`)\n .notNull(),\n});\n","import { sql } from 'drizzle-orm';\nimport { jsonb, pgTable, text, unique, uuid } from 'drizzle-orm/pg-core';\nimport { agentTable } from './agent';\nimport { numberTimestamp } from './types';\n\n/**\n * Represents a PostgreSQL table for caching data.\n *\n * @type {pgTable}\n */\nexport const cacheTable = pgTable(\n 'cache',\n {\n id: uuid('id')\n .notNull()\n .primaryKey()\n .default(sql`gen_random_uuid()`),\n key: text('key').notNull(),\n agentId: uuid('agentId')\n .notNull()\n .references(() => agentTable.id, { onDelete: 'cascade' }),\n value: jsonb('value').notNull(),\n createdAt: numberTimestamp('createdAt')\n .default(sql`now()`)\n .notNull(),\n expiresAt: numberTimestamp('expiresAt'),\n },\n (table) => [unique('cache_key_agent_unique').on(table.key, table.agentId)]\n);\n","import { sql } from 'drizzle-orm';\nimport { jsonb, pgTable, text, uuid } from 'drizzle-orm/pg-core';\nimport { agentTable } from './agent';\nimport { entityTable } from './entity';\nimport { roomTable } from './room';\nimport { numberTimestamp } from './types';\nimport { worldTable } from './worldTable';\n\n/**\n * Definition of a table representing components in the database.\n *\n * @type {Table}\n */\nexport const componentTable = pgTable('components', {\n id: uuid('id').primaryKey().defaultRandom(),\n entityId: uuid('entityId')\n .notNull()\n .references(() => entityTable.id, { onDelete: 'cascade' }),\n agentId: uuid('agentId')\n .notNull()\n .references(() => agentTable.id, { onDelete: 'cascade' }),\n roomId: uuid('roomId')\n .notNull()\n .references(() => roomTable.id, { onDelete: 'cascade' }),\n worldId: uuid('worldId').references(() => worldTable.id, {\n onDelete: 'cascade',\n }),\n sourceEntityId: uuid('sourceEntityId').references(() => entityTable.id, {\n onDelete: 'cascade',\n }),\n type: text('type').notNull(),\n data: jsonb('data').default(sql`'{}'::jsonb`),\n createdAt: numberTimestamp('createdAt')\n .default(sql`now()`)\n .notNull(),\n});\n","import { sql } from 'drizzle-orm';\nimport { foreignKey, jsonb, pgTable, text, uuid } from 'drizzle-orm/pg-core';\nimport { entityTable } from './entity';\nimport { roomTable } from './room';\nimport { numberTimestamp } from './types';\n\n/**\n * Represents a PostgreSQL table for storing logs.\n *\n * @type {Table}\n */\n\nexport const logTable = pgTable(\n 'logs',\n {\n id: uuid('id').defaultRandom().notNull(),\n createdAt: numberTimestamp('createdAt')\n .default(sql`now()`)\n .notNull(),\n entityId: uuid('entityId')\n .notNull()\n .references(() => entityTable.id),\n body: jsonb('body').notNull(),\n type: text('type').notNull(),\n roomId: uuid('roomId')\n .notNull()\n .references(() => roomTable.id),\n },\n (table) => [\n foreignKey({\n name: 'fk_room',\n columns: [table.roomId],\n foreignColumns: [roomTable.id],\n }).onDelete('cascade'),\n foreignKey({\n name: 'fk_user',\n columns: [table.entityId],\n foreignColumns: [entityTable.id],\n }).onDelete('cascade'),\n ]\n);\n","import { sql } from 'drizzle-orm';\nimport { foreignKey, index, pgTable, text, unique, uuid } from 'drizzle-orm/pg-core';\nimport { agentTable } from './agent';\nimport { entityTable } from './entity';\nimport { roomTable } from './room';\nimport { numberTimestamp } from './types';\n\n/**\n * Defines the schema for the \"participants\" table in the database.\n *\n * @type {import('knex').TableBuilder}\n */\nexport const participantTable = pgTable(\n 'participants',\n {\n id: uuid('id')\n .notNull()\n .primaryKey()\n .default(sql`gen_random_uuid()`),\n createdAt: numberTimestamp('createdAt')\n .default(sql`now()`)\n .notNull(),\n entityId: uuid('entityId').references(() => entityTable.id, {\n onDelete: 'cascade',\n }),\n roomId: uuid('roomId').references(() => roomTable.id, {\n onDelete: 'cascade',\n }),\n agentId: uuid('agentId').references(() => agentTable.id, {\n onDelete: 'cascade',\n }),\n roomState: text('roomState'),\n },\n (table) => [\n // unique(\"participants_user_room_agent_unique\").on(table.entityId, table.roomId, table.agentId),\n index('idx_participants_user').on(table.entityId),\n index('idx_participants_room').on(table.roomId),\n foreignKey({\n name: 'fk_room',\n columns: [table.roomId],\n foreignColumns: [roomTable.id],\n }).onDelete('cascade'),\n foreignKey({\n name: 'fk_user',\n columns: [table.entityId],\n foreignColumns: [entityTable.id],\n }).onDelete('cascade'),\n ]\n);\n","import { sql } from 'drizzle-orm';\nimport { foreignKey, index, jsonb, pgTable, text, unique, uuid } from 'drizzle-orm/pg-core';\nimport { agentTable } from './agent';\nimport { entityTable } from './entity';\nimport { numberTimestamp } from './types';\n\n/**\n * Defines the relationshipTable containing information about relationships between entities and agents.\n * @type {import('knex').TableBuilder}\n */\nexport const relationshipTable = pgTable(\n 'relationships',\n {\n id: uuid('id')\n .notNull()\n .primaryKey()\n .default(sql`gen_random_uuid()`),\n createdAt: numberTimestamp('createdAt')\n .default(sql`now()`)\n .notNull(),\n sourceEntityId: uuid('sourceEntityId')\n .notNull()\n .references(() => entityTable.id, { onDelete: 'cascade' }),\n targetEntityId: uuid('targetEntityId')\n .notNull()\n .references(() => entityTable.id, { onDelete: 'cascade' }),\n agentId: uuid('agentId')\n .notNull()\n .references(() => agentTable.id, { onDelete: 'cascade' }),\n tags: text('tags').array(),\n metadata: jsonb('metadata'),\n },\n (table) => [\n index('idx_relationships_users').on(table.sourceEntityId, table.targetEntityId),\n unique('unique_relationship').on(table.sourceEntityId, table.targetEntityId, table.agentId),\n foreignKey({\n name: 'fk_user_a',\n columns: [table.sourceEntityId],\n foreignColumns: [entityTable.id],\n }).onDelete('cascade'),\n foreignKey({\n name: 'fk_user_b',\n columns: [table.targetEntityId],\n foreignColumns: [entityTable.id],\n }).onDelete('cascade'),\n ]\n);\n","import { jsonb, pgTable, text, timestamp, uuid } from 'drizzle-orm/pg-core';\n\n/**\n * Represents a table schema for tasks in the database.\n *\n * @type {PgTable}\n */\nexport const taskTable = pgTable('tasks', {\n id: uuid('id').primaryKey().defaultRandom(),\n name: text('name').notNull(),\n description: text('description').notNull(),\n roomId: uuid('room_id'),\n worldId: uuid('world_id'),\n agentId: uuid('agent_id').notNull(),\n tags: text('tags').array(),\n metadata: jsonb('metadata'),\n createdAt: timestamp('created_at').defaultNow(),\n updatedAt: timestamp('updated_at').defaultNow(),\n});\n","import { type UUID, logger } from '@elizaos/core';\nimport { type NodePgDatabase, drizzle } from 'drizzle-orm/node-postgres';\nimport { BaseDrizzleAdapter } from '../base';\nimport { DIMENSION_MAP, type EmbeddingDimensionColumn } from '../schema/embedding';\nimport type { PostgresConnectionManager } from './manager';\n\n/**\n * Adapter class for interacting with a PostgreSQL database.\n * Extends BaseDrizzleAdapter<NodePgDatabase>.\n */\nexport class PgDatabaseAdapter extends BaseDrizzleAdapter<NodePgDatabase> {\n protected embeddingDimension: EmbeddingDimensionColumn = DIMENSION_MAP[384];\n\n /**\n * Constructor for creating a new instance of a class.\n * @param {UUID} agentId - The unique identifier for the agent.\n * @param {PostgresConnectionManager} manager - The Postgres connection manager for the instance.\n */\n constructor(\n agentId: UUID,\n private manager: PostgresConnectionManager\n ) {\n super(agentId);\n this.manager = manager;\n }\n\n /**\n * Executes the provided operation with a database connection.\n *\n * @template T\n * @param {() => Promise<T>} operation - The operation to be executed with the database connection.\n * @returns {Promise<T>} A promise that resolves with the result of the operation.\n */\n protected async withDatabase<T>(operation: () => Promise<T>): Promise<T> {\n return await this.withRetry(async () => {\n const client = await this.manager.getClient();\n try {\n const db = drizzle(client);\n this.db = db;\n\n return await operation();\n } finally {\n client.release();\n }\n });\n }\n\n /**\n * Asynchronously initializes the PgDatabaseAdapter by running migrations using the manager.\n * Logs a success message if initialization is successful, otherwise logs an error message.\n *\n * @returns {Promise<void>} A promise that resolves when initialization is complete.\n */\n async init(): Promise<void> {\n try {\n await this.manager.runMigrations();\n logger.debug('PgDatabaseAdapter initialized successfully');\n } catch (error) {\n logger.error('Failed to initialize PgDatabaseAdapter:', error);\n throw error;\n }\n }\n\n /**\n * Asynchronously closes the manager associated with this instance.\n *\n * @returns A Promise that resolves once the manager is closed.\n */\n async close(): Promise<void> {\n await this.manager.close();\n }\n}\n"],"mappings":";;;;;;;AAAA,YAAY,QAAQ;AAEpB,SAA0C,UAAAA,eAAc;;;ACFxD,SAAoB,UAAAC,eAAc;AAClC,SAA8B,eAAe;;;ACD7C;AAAA,EAGE;AAAA,EAWA;AAAA,OACK;AACP;AAAA,EAEE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,OAAAC;AAAA,OACK;AACP,SAAS,UAAU;;;AC7BnB,SAAS,OAAAC,YAAW;AACpB,SAAS,SAAAC,QAAO,cAAAC,aAAY,SAAAC,QAAO,WAAAC,UAAS,QAAAC,OAAM,UAAAC,eAAc;;;ACDhE,SAAS,WAAW,OAAAC,YAAW;AAC/B;AAAA,EACE,WAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,SAAAC;AAAA,EACA,WAAAC;AAAA,EACA,QAAAC;AAAA,EAEA,QAAAC;AAAA,OAEK;;;ACXP,SAAS,WAAW;AACpB,SAAS,SAAS,OAAO,SAAS,MAAM,QAAQ,YAAY;;;ACF5D,SAAS,kBAAkB;AAWpB,IAAM,cAAc,WAAiD;AAAA,EAC1E,WAAW;AACT,WAAO;AAAA,EACT;AAAA,EACA,SAAS,OAAuB;AAC9B,WAAO,KAAK,UAAU,KAAK;AAAA,EAC7B;AAAA,EACA,WAAW,OAAuB;AAChC,WAAO,KAAK,UAAU,KAAK;AAAA,EAC7B;AACF,CAAC;AAUM,IAAM,kBAAkB,WAAiD;AAAA,EAC9E,WAAW;AACT,WAAO;AAAA,EACT;AAAA,EACA,SAAS,OAAuB;AAC9B,WAAO,IAAI,KAAK,KAAK,EAAE,YAAY;AAAA,EACrC;AAAA,EACA,WAAW,OAAuB;AAChC,WAAO,IAAI,KAAK,KAAK,EAAE,QAAQ;AAAA,EACjC;AACF,CAAC;;;AD/BM,IAAM,aAAa;AAAA,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B;AAChF;AA3BgB;AAuChB,IAAM,YAAoB;AAAA,EACxB,MAAM;AAAA,EACN,aAAa;AAAA,EACb,MAAM,8BAAO,GAAG,YAA2B;AACzC,UAAM,SAAS;AAAA,MACb,SAAS,QAAQ,WAAW,iBAAiB,KAAK;AAAA,MAClD,aAAa,QAAQ,WAAW,cAAc;AAAA,IAChD;AAEA,QAAI;AACF,YAAM,KAAK,sBAAsB,QAAQ,QAAQ,OAAO;AACxD,MAAAC,QAAO,QAAQ,8CAA8C;AAC7D,cAAQ,wBAAwB,EAAE;AAAA,IACpC,SAAS,OAAO;AACd,MAAAA,QAAO,MAAM,kCAAkC,KAAK;AACpD,YAAM;AAAA,IACR;AAAA,EACF,GAdM;AAeR;AAEA,IAAO,gBAAQ;","names":["logger","logger","sql","sql","check","foreignKey","index","pgTable","uuid","vector","sql","boolean","jsonb","pgTable","text","uuid","sql","jsonb","pgTable","text","unique","uuid","pgTable","uuid","sql","text","jsonb","unique","sql","jsonb","pgTable","text","uuid","sql","jsonb","pgTable","text","uuid","pgTable","uuid","sql","text","jsonb","pgTable","uuid","sql","text","jsonb","pgTable","uuid","text","sql","jsonb","boolean","pgTable","uuid","sql","vector","check","index","foreignKey","sql","jsonb","pgTable","text","unique","uuid","pgTable","uuid","sql","text","jsonb","unique","sql","jsonb","pgTable","text","uuid","pgTable","uuid","text","jsonb","sql","sql","foreignKey","jsonb","pgTable","text","uuid","pgTable","uuid","sql","jsonb","text","foreignKey","sql","foreignKey","index","pgTable","text","uuid","pgTable","uuid","sql","text","index","foreignKey","sql","foreignKey","index","jsonb","pgTable","text","unique","uuid","pgTable","uuid","sql","text","jsonb","index","unique","foreignKey","jsonb","pgTable","text","uuid","count","unique","sql","logger","logger","drizzle","drizzle","logger","logger"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/pglite/adapter.ts","../src/base.ts","../src/schema/embedding.ts","../src/schema/memory.ts","../src/schema/agent.ts","../src/schema/types.ts","../src/schema/entity.ts","../src/schema/room.ts","../src/schema/worldTable.ts","../src/schema/cache.ts","../src/schema/component.ts","../src/schema/log.ts","../src/schema/participant.ts","../src/schema/relationship.ts","../src/schema/tasks.ts","../src/pg/adapter.ts"],"sourceRoot":"./","sourcesContent":["import * as os from 'node:os';\nimport type { IDatabaseAdapter, UUID } from '@elizaos/core';\nimport { type IAgentRuntime, type Plugin, logger } from '@elizaos/core';\nimport { PgliteDatabaseAdapter } from './pglite/adapter';\nimport { PGliteClientManager } from './pglite/manager';\nimport { PgDatabaseAdapter } from './pg/adapter';\nimport { PostgresConnectionManager } from './pg/manager';\n\n/**\n * Global Singleton Instances (Package-scoped)\n *\n * These instances are stored globally within the package scope to ensure a single shared instance across multiple adapters within this package.\n * This approach prevents multiple instantiations due to module caching or multiple imports within the same process.\n *\n * IMPORTANT:\n * - Do NOT directly modify these instances outside their intended initialization logic.\n * - These instances are NOT exported and should NOT be accessed outside this package.\n */\nconst GLOBAL_SINGLETONS = Symbol.for('@elizaos/plugin-sql/global-singletons');\n\ninterface GlobalSingletons {\n pgLiteClientManager?: PGliteClientManager;\n postgresConnectionManager?: PostgresConnectionManager;\n}\n\nconst globalSymbols = global as unknown as Record<symbol, GlobalSingletons>;\n\nif (!globalSymbols[GLOBAL_SINGLETONS]) {\n globalSymbols[GLOBAL_SINGLETONS] = {};\n}\n\nconst globalSingletons = globalSymbols[GLOBAL_SINGLETONS];\n\n/**\n * Helper function to expand tilde in paths\n */\nfunction expandTildePath(filepath: string): string {\n if (filepath && typeof filepath === 'string' && filepath.startsWith('~')) {\n return filepath.replace(/^~/, os.homedir());\n }\n return filepath;\n}\n\n/**\n * Creates a database adapter based on the provided configuration.\n * If a postgresUrl is provided in the config, a PgDatabaseAdapter is initialized using the PostgresConnectionManager.\n * If no postgresUrl is provided, a PgliteDatabaseAdapter is initialized using PGliteClientManager with the dataDir from the config.\n *\n * @param {object} config - The configuration object.\n * @param {string} [config.dataDir] - The directory where data is stored. Defaults to \"./elizadb\".\n * @param {string} [config.postgresUrl] - The URL for the PostgreSQL database.\n * @param {UUID} agentId - The unique identifier for the agent.\n * @returns {IDatabaseAdapter} The created database adapter.\n */\nexport function createDatabaseAdapter(\n config: {\n dataDir?: string;\n postgresUrl?: string;\n },\n agentId: UUID\n): IDatabaseAdapter {\n if (config.dataDir) {\n config.dataDir = expandTildePath(config.dataDir);\n }\n\n if (config.postgresUrl) {\n if (!globalSingletons.postgresConnectionManager) {\n globalSingletons.postgresConnectionManager = new PostgresConnectionManager(\n config.postgresUrl\n );\n }\n return new PgDatabaseAdapter(agentId, globalSingletons.postgresConnectionManager);\n }\n\n const dataDir = config.dataDir ?? './elizadb';\n\n if (!globalSingletons.pgLiteClientManager) {\n globalSingletons.pgLiteClientManager = new PGliteClientManager({ dataDir });\n }\n\n return new PgliteDatabaseAdapter(agentId, globalSingletons.pgLiteClientManager);\n}\n\n/**\n * SQL plugin for database adapter using Drizzle ORM\n *\n * @typedef {Object} Plugin\n * @property {string} name - The name of the plugin\n * @property {string} description - The description of the plugin\n * @property {Function} init - The initialization function for the plugin\n * @param {any} _ - Input parameter\n * @param {IAgentRuntime} runtime - The runtime environment for the agent\n */\nconst sqlPlugin: Plugin = {\n name: 'sql',\n description: 'SQL database adapter plugin using Drizzle ORM',\n init: async (_, runtime: IAgentRuntime) => {\n const config = {\n dataDir: runtime.getSetting('PGLITE_DATA_DIR') ?? './pglite',\n postgresUrl: runtime.getSetting('POSTGRES_URL'),\n };\n\n try {\n const db = createDatabaseAdapter(config, runtime.agentId);\n logger.success('Database connection established successfully');\n runtime.registerDatabaseAdapter(db);\n } catch (error) {\n logger.error('Failed to initialize database:', error);\n throw error;\n }\n },\n};\n\nexport default sqlPlugin;\n","import { type UUID, logger } from '@elizaos/core';\nimport { type PgliteDatabase, drizzle } from 'drizzle-orm/pglite';\nimport { BaseDrizzleAdapter } from '../base';\nimport { DIMENSION_MAP, type EmbeddingDimensionColumn } from '../schema/embedding';\nimport type { PGliteClientManager } from './manager';\n\n/**\n * PgliteDatabaseAdapter class represents an adapter for interacting with a PgliteDatabase.\n * Extends BaseDrizzleAdapter<PgliteDatabase>.\n *\n * @constructor\n * @param {UUID} agentId - The ID of the agent.\n * @param {PGliteClientManager} manager - The manager for the PgliteDatabase.\n *\n * @method withDatabase\n * @param {() => Promise<T>} operation - The operation to perform on the database.\n * @return {Promise<T>} - The result of the operation.\n *\n * @method init\n * @return {Promise<void>} - A Promise that resolves when the initialization is complete.\n *\n * @method close\n * @return {void} - A Promise that resolves when the database is closed.\n */\nexport class PgliteDatabaseAdapter extends BaseDrizzleAdapter<PgliteDatabase> {\n private manager: PGliteClientManager;\n protected embeddingDimension: EmbeddingDimensionColumn = DIMENSION_MAP[384];\n\n /**\n * Constructor for creating an instance of a class.\n * @param {UUID} agentId - The unique identifier for the agent.\n * @param {PGliteClientManager} manager - The manager for the PGlite client.\n */\n constructor(agentId: UUID, manager: PGliteClientManager) {\n super(agentId);\n this.manager = manager;\n this.db = drizzle(this.manager.getConnection());\n }\n\n /**\n * Asynchronously runs the provided database operation while checking if the database manager is currently shutting down.\n * If the database manager is shutting down, a warning is logged and null is returned.\n *\n * @param {Function} operation - The database operation to be performed.\n * @returns {Promise<T>} A promise that resolves with the result of the database operation.\n */\n protected async withDatabase<T>(operation: () => Promise<T>): Promise<T> {\n if (this.manager.isShuttingDown()) {\n logger.warn('Database is shutting down');\n return null as unknown as T;\n }\n return operation();\n }\n\n /**\n * Asynchronously initializes the database by running migrations using the manager.\n *\n * @returns {Promise<void>} A Promise that resolves when the database initialization is complete.\n */\n async init(): Promise<void> {\n try {\n await this.manager.runMigrations();\n } catch (error) {\n logger.error('Failed to initialize database:', error);\n throw error;\n }\n }\n\n /**\n * Asynchronously closes the manager.\n */\n async close() {\n await this.manager.close();\n }\n}\n","import {\n type Agent,\n type Component,\n DatabaseAdapter,\n type Entity,\n type Memory,\n type MemoryMetadata,\n type Participant,\n type Relationship,\n type Room,\n type Task,\n type UUID,\n type World,\n type Log,\n logger,\n} from '@elizaos/core';\nimport {\n Column,\n and,\n cosineDistance,\n count,\n desc,\n eq,\n gte,\n inArray,\n lte,\n or,\n sql,\n not,\n} from 'drizzle-orm';\nimport { v4 } from 'uuid';\nimport { DIMENSION_MAP, type EmbeddingDimensionColumn } from './schema/embedding';\nimport {\n agentTable,\n cacheTable,\n componentTable,\n embeddingTable,\n entityTable,\n logTable,\n memoryTable,\n participantTable,\n relationshipTable,\n roomTable,\n taskTable,\n worldTable,\n} from './schema/index';\nimport type { DrizzleOperations } from './types';\n\n// Define the metadata type inline since we can't import it\n/**\n * Represents metadata information about memory.\n * @typedef {Object} MemoryMetadata\n * @property {string} type - The type of memory.\n * @property {string} [source] - The source of the memory.\n * @property {UUID} [sourceId] - The ID of the source.\n * @property {string} [scope] - The scope of the memory.\n * @property {number} [timestamp] - The timestamp of the memory.\n * @property {string[]} [tags] - The tags associated with the memory.\n * @property {UUID} [documentId] - The ID of the document associated with the memory.\n * @property {number} [position] - The position of the memory.\n */\n\n/**\n * Abstract class representing a base Drizzle adapter for working with databases.\n * This adapter provides a comprehensive set of methods for interacting with a database\n * using Drizzle ORM. It implements the DatabaseAdapter interface and handles operations\n * for various entity types including agents, entities, components, memories, rooms,\n * participants, relationships, tasks, and more.\n *\n * The adapter includes built-in retry logic for database operations, embedding dimension\n * management, and transaction support. Concrete implementations must provide the\n * withDatabase method to execute operations against their specific database.\n *\n * @template TDatabase - The type of Drizzle operations supported by the adapter.\n */\nexport abstract class BaseDrizzleAdapter<\n TDatabase extends DrizzleOperations,\n> extends DatabaseAdapter<TDatabase> {\n protected readonly maxRetries: number = 3;\n protected readonly baseDelay: number = 1000;\n protected readonly maxDelay: number = 10000;\n protected readonly jitterMax: number = 1000;\n protected embeddingDimension: EmbeddingDimensionColumn = DIMENSION_MAP[384];\n\n protected abstract withDatabase<T>(operation: () => Promise<T>): Promise<T>;\n public abstract init(): Promise<void>;\n public abstract close(): Promise<void>;\n\n protected agentId: UUID;\n\n /**\n * Constructor for creating a new instance of Agent with the specified agentId.\n *\n * @param {UUID} agentId - The unique identifier for the agent.\n */\n constructor(agentId: UUID) {\n super();\n this.agentId = agentId;\n }\n\n /**\n * Executes the given operation with retry logic.\n * @template T\n * @param {() => Promise<T>} operation - The operation to be executed.\n * @returns {Promise<T>} A promise that resolves with the result of the operation.\n */\n protected async withRetry<T>(operation: () => Promise<T>): Promise<T> {\n let lastError: Error = new Error('Unknown error');\n\n for (let attempt = 1; attempt <= this.maxRetries; attempt++) {\n try {\n return await operation();\n } catch (error) {\n lastError = error as Error;\n\n if (attempt < this.maxRetries) {\n const backoffDelay = Math.min(this.baseDelay * 2 ** (attempt - 1), this.maxDelay);\n\n const jitter = Math.random() * this.jitterMax;\n const delay = backoffDelay + jitter;\n\n logger.warn(`Database operation failed (attempt ${attempt}/${this.maxRetries}):`, {\n error: error instanceof Error ? error.message : String(error),\n nextRetryIn: `${(delay / 1000).toFixed(1)}s`,\n });\n\n await new Promise((resolve) => setTimeout(resolve, delay));\n } else {\n logger.error('Max retry attempts reached:', {\n error: error instanceof Error ? error.message : String(error),\n totalAttempts: attempt,\n });\n throw error instanceof Error ? error : new Error(String(error));\n }\n }\n }\n\n throw lastError;\n }\n\n /**\n * Asynchronously ensures that an agent exists by checking if an agent with the same name already exists in the system.\n * If the agent does not exist, it will be created with the provided data.\n *\n * @param {Partial<Agent>} agent - The partial data of the agent to ensure its existence.\n * @returns {Promise<void>} - A promise that resolves when the agent is successfully ensured.\n * @throws {Error} - If the agent name is not provided or if there is an issue creating the agent.\n */\n async ensureAgentExists(agent: Partial<Agent>): Promise<void> {\n if (!agent.name) {\n throw new Error('Agent name is required');\n }\n\n const agents = await this.getAgents();\n const existingAgent = agents.find(\n (a: Partial<Agent & { status: string }>) => a.name === agent.name\n );\n\n if (!existingAgent) {\n await this.createAgent(agent);\n }\n }\n\n /**\n * Asynchronously ensures that the given embedding dimension is valid for the agent.\n *\n * @param {number} dimension - The dimension to ensure for the embedding.\n * @returns {Promise<void>} - Resolves once the embedding dimension is ensured.\n */\n async ensureEmbeddingDimension(dimension: number) {\n const existingMemory = await this.db\n .select({\n embedding: embeddingTable,\n })\n .from(memoryTable)\n .innerJoin(embeddingTable, eq(embeddingTable.memoryId, memoryTable.id))\n .where(eq(memoryTable.agentId, this.agentId))\n .limit(1);\n\n if (existingMemory.length > 0) {\n const usedDimension = Object.entries(DIMENSION_MAP).find(\n ([_, colName]) => existingMemory[0].embedding[colName] !== null\n );\n }\n\n this.embeddingDimension = DIMENSION_MAP[dimension];\n }\n\n /**\n * Asynchronously retrieves an agent by their ID from the database.\n * @param {UUID} agentId - The ID of the agent to retrieve.\n * @returns {Promise<Agent | null>} A promise that resolves to the retrieved agent or null if not found.\n */\n async getAgent(agentId: UUID): Promise<Agent | null> {\n return this.withDatabase(async () => {\n const result = await this.db\n .select()\n .from(agentTable)\n .where(eq(agentTable.id, agentId))\n .limit(1);\n\n if (result.length === 0) return null;\n return result[0];\n });\n }\n\n /**\n * Asynchronously retrieves a list of agents from the database.\n *\n * @returns {Promise<Agent[]>} A Promise that resolves to an array of Agent objects.\n */\n async getAgents(): Promise<Agent[]> {\n return this.withDatabase(async () => {\n const result = await this.db.select().from(agentTable);\n\n return result;\n });\n }\n\n /**\n * Asynchronously creates a new agent record in the database.\n *\n * @param {Partial<Agent>} agent The agent object to be created.\n * @returns {Promise<boolean>} A promise that resolves to a boolean indicating the success of the operation.\n */\n async createAgent(agent: Partial<Agent>): Promise<boolean> {\n return this.withDatabase(async () => {\n try {\n await this.db.transaction(async (tx) => {\n await tx.insert(agentTable).values({\n ...agent,\n });\n });\n\n logger.debug('Agent created successfully:', {\n agentId: agent.id,\n });\n return true;\n } catch (error) {\n logger.error('Error creating agent:', {\n error: error instanceof Error ? error.message : String(error),\n agentId: agent.id,\n agent,\n });\n return false;\n }\n });\n }\n\n /**\n * Updates an agent in the database with the provided agent ID and data.\n * @param {UUID} agentId - The unique identifier of the agent to update.\n * @param {Partial<Agent>} agent - The partial agent object containing the fields to update.\n * @returns {Promise<boolean>} - A boolean indicating if the agent was successfully updated.\n */\n async updateAgent(agentId: UUID, agent: Partial<Agent>): Promise<boolean> {\n return this.withDatabase(async () => {\n try {\n if (!agent.id) {\n throw new Error('Agent ID is required for update');\n }\n\n await this.db.transaction(async (tx) => {\n // Handle settings update if present\n if (agent.settings) {\n agent.settings = await this.mergeAgentSettings(tx, agentId, agent.settings);\n }\n\n await tx\n .update(agentTable)\n .set({\n ...agent,\n updatedAt: Date.now(),\n })\n .where(eq(agentTable.id, agentId));\n });\n\n logger.debug('Agent updated successfully:', {\n agentId,\n });\n return true;\n } catch (error) {\n logger.error('Error updating agent:', {\n error: error instanceof Error ? error.message : String(error),\n agentId,\n agent,\n });\n return false;\n }\n });\n }\n\n /**\n * Merges updated agent settings with existing settings in the database,\n * with special handling for nested objects like secrets.\n * @param tx - The database transaction\n * @param agentId - The ID of the agent\n * @param updatedSettings - The settings object with updates\n * @returns The merged settings object\n * @private\n */\n private async mergeAgentSettings(\n tx: DrizzleOperations,\n agentId: UUID,\n updatedSettings: any\n ): Promise<any> {\n // First get the current agent data\n const currentAgent = await tx\n .select({ settings: agentTable.settings })\n .from(agentTable)\n .where(eq(agentTable.id, agentId))\n .limit(1);\n\n if (currentAgent.length === 0 || !currentAgent[0].settings) {\n return updatedSettings;\n }\n\n const currentSettings = currentAgent[0].settings;\n\n // Handle secrets with special null-values treatment\n if (updatedSettings.secrets) {\n const currentSecrets = currentSettings.secrets || {};\n const updatedSecrets = updatedSettings.secrets;\n\n // Create a new secrets object\n const mergedSecrets = { ...currentSecrets };\n\n // Process the incoming secrets updates\n for (const [key, value] of Object.entries(updatedSecrets)) {\n if (value === null) {\n // If value is null, remove the key\n delete mergedSecrets[key];\n } else {\n // Otherwise, update the value\n mergedSecrets[key] = value;\n }\n }\n\n // Replace the secrets in updatedSettings with our processed version\n updatedSettings.secrets = mergedSecrets;\n }\n\n // Deep merge the settings objects\n return {\n ...currentSettings,\n ...updatedSettings,\n };\n }\n\n /**\n * Asynchronously deletes an agent with the specified UUID and all related entries.\n *\n * @param {UUID} agentId - The UUID of the agent to be deleted.\n * @returns {Promise<boolean>} - A boolean indicating if the deletion was successful.\n */\n async deleteAgent(agentId: UUID): Promise<boolean> {\n return this.withDatabase(async () => {\n await this.db.transaction(async (tx) => {\n const entities = await this.db\n .select({ entityId: entityTable.id })\n .from(entityTable)\n .where(eq(entityTable.agentId, agentId));\n\n const entityIds = entities.map((e) => e.entityId);\n\n let memoryIds: UUID[] = [];\n\n if (entityIds.length > 0) {\n const entityMemories = await this.db\n .select({ memoryId: memoryTable.id })\n .from(memoryTable)\n .where(inArray(memoryTable.entityId, entityIds));\n\n memoryIds = entityMemories.map((m) => m.memoryId);\n }\n\n const agentMemories = await this.db\n .select({ memoryId: memoryTable.id })\n .from(memoryTable)\n .where(eq(memoryTable.agentId, agentId));\n\n memoryIds.push(...agentMemories.map((m) => m.memoryId));\n\n if (memoryIds.length > 0) {\n await tx.delete(embeddingTable).where(inArray(embeddingTable.memoryId, memoryIds));\n\n await tx.delete(memoryTable).where(inArray(memoryTable.id, memoryIds));\n }\n\n const rooms = await this.db\n .select({ roomId: roomTable.id })\n .from(roomTable)\n .where(eq(roomTable.agentId, agentId));\n\n const roomIds = rooms.map((r) => r.roomId);\n\n if (entityIds.length > 0) {\n await tx.delete(logTable).where(inArray(logTable.entityId, entityIds));\n await tx.delete(participantTable).where(inArray(participantTable.entityId, entityIds));\n }\n\n if (roomIds.length > 0) {\n await tx.delete(logTable).where(inArray(logTable.roomId, roomIds));\n await tx.delete(participantTable).where(inArray(participantTable.roomId, roomIds));\n }\n\n await tx.delete(participantTable).where(eq(participantTable.agentId, agentId));\n\n if (roomIds.length > 0) {\n await tx.delete(roomTable).where(inArray(roomTable.id, roomIds));\n }\n\n await tx.delete(cacheTable).where(eq(cacheTable.agentId, agentId));\n\n await tx.delete(relationshipTable).where(eq(relationshipTable.agentId, agentId));\n\n await tx.delete(entityTable).where(eq(entityTable.agentId, agentId));\n\n const newAgent = await this.db\n .select({ newAgentId: agentTable.id })\n .from(agentTable)\n .where(not(eq(agentTable.id, agentId)))\n .limit(1);\n\n if (newAgent.length > 0) {\n await tx\n .update(worldTable)\n .set({ agentId: newAgent[0].newAgentId })\n .where(eq(worldTable.agentId, agentId));\n } else {\n await tx.delete(worldTable).where(eq(worldTable.agentId, agentId));\n }\n\n await tx.delete(agentTable).where(eq(agentTable.id, agentId));\n });\n\n return true;\n });\n }\n\n /**\n * Count all agents in the database\n * Used primarily for maintenance and cleanup operations\n */\n /**\n * Asynchronously counts the number of agents in the database.\n * @returns {Promise<number>} A Promise that resolves to the number of agents in the database.\n */\n async countAgents(): Promise<number> {\n return this.withDatabase(async () => {\n try {\n const result = await this.db.select({ count: count() }).from(agentTable);\n\n return result[0]?.count || 0;\n } catch (error) {\n logger.error('Error counting agents:', {\n error: error instanceof Error ? error.message : String(error),\n });\n return 0;\n }\n });\n }\n\n /**\n * Clean up the agents table by removing all agents\n * This is used during server startup to ensure no orphaned agents exist\n * from previous crashes or improper shutdowns\n */\n async cleanupAgents(): Promise<void> {\n return this.withDatabase(async () => {\n try {\n await this.db.delete(agentTable);\n logger.success('Successfully cleaned up agent table');\n } catch (error) {\n logger.error('Error cleaning up agent table:', {\n error: error instanceof Error ? error.message : String(error),\n });\n throw error;\n }\n });\n }\n\n /**\n * Asynchronously retrieves an entity and its components by entity ID.\n * @param {UUID} entityId - The unique identifier of the entity to retrieve.\n * @returns {Promise<Entity | null>} A Promise that resolves to the entity with its components if found, null otherwise.\n */\n async getEntityById(entityId: UUID): Promise<Entity | null> {\n return this.withDatabase(async () => {\n const result = await this.db\n .select({\n entity: entityTable,\n components: componentTable,\n })\n .from(entityTable)\n .leftJoin(componentTable, eq(componentTable.entityId, entityTable.id))\n .where(and(eq(entityTable.id, entityId), eq(entityTable.agentId, this.agentId)));\n\n if (result.length === 0) return null;\n\n // Group components by entity\n const entity = result[0].entity;\n entity.components = result.filter((row) => row.components).map((row) => row.components);\n\n return entity;\n });\n }\n\n /**\n * Asynchronously retrieves all entities for a given room, optionally including their components.\n * @param {UUID} roomId - The unique identifier of the room to get entities for\n * @param {boolean} [includeComponents] - Whether to include component data for each entity\n * @returns {Promise<Entity[]>} A Promise that resolves to an array of entities in the room\n */\n async getEntitiesForRoom(roomId: UUID, includeComponents?: boolean): Promise<Entity[]> {\n return this.withDatabase(async () => {\n const query = this.db\n .select({\n entity: entityTable,\n ...(includeComponents && { components: componentTable }),\n })\n .from(participantTable)\n .leftJoin(\n entityTable,\n and(eq(participantTable.entityId, entityTable.id), eq(entityTable.agentId, this.agentId))\n );\n\n if (includeComponents) {\n query.leftJoin(componentTable, eq(componentTable.entityId, entityTable.id));\n }\n\n const result = await query.where(eq(participantTable.roomId, roomId));\n\n // Group components by entity if includeComponents is true\n const entitiesByIdMap = new Map<UUID, Entity>();\n\n for (const row of result) {\n if (!row.entity) continue;\n\n const entityId = row.entity.id as UUID;\n if (!entitiesByIdMap.has(entityId)) {\n const entity: Entity = {\n ...row.entity,\n components: includeComponents ? [] : undefined,\n };\n entitiesByIdMap.set(entityId, entity);\n }\n\n if (includeComponents && row.components) {\n const entity = entitiesByIdMap.get(entityId);\n if (entity) {\n if (!entity.components) {\n entity.components = [];\n }\n entity.components.push(row.components);\n }\n }\n }\n\n return Array.from(entitiesByIdMap.values());\n });\n }\n\n /**\n * Asynchronously creates a new entity in the database.\n * @param {Entity} entity - The entity object to be created.\n * @returns {Promise<boolean>} A Promise that resolves to a boolean indicating the success of the operation.\n */\n async createEntity(entity: Entity): Promise<boolean> {\n return this.withDatabase(async () => {\n try {\n return await this.db.transaction(async (tx) => {\n // try get entity by id\n const existingEntity = await this.getEntityById(entity.id as UUID);\n if (existingEntity) {\n logger.debug('Entity already exists:', {\n entity,\n });\n return true;\n }\n\n await tx.insert(entityTable).values(entity);\n\n logger.debug('Entity created successfully:', {\n entity,\n });\n\n return true;\n });\n } catch (error) {\n logger.error('Error creating entity:', {\n error: error instanceof Error ? error.message : String(error),\n entityId: entity.id,\n name: entity.metadata?.name,\n });\n // trace the error\n logger.trace(error);\n return false;\n }\n });\n }\n\n /**\n * Asynchronously ensures an entity exists, creating it if it doesn't\n * @param entity The entity to ensure exists\n * @returns Promise resolving to boolean indicating success\n */\n protected async ensureEntityExists(entity: Entity): Promise<boolean> {\n if (!entity.id) {\n logger.error('Entity ID is required for ensureEntityExists');\n return false;\n }\n\n try {\n const existingEntity = await this.getEntityById(entity.id);\n\n if (!existingEntity) {\n return await this.createEntity(entity);\n }\n\n return true;\n } catch (error) {\n logger.error('Error ensuring entity exists:', {\n error: error instanceof Error ? error.message : String(error),\n entityId: entity.id,\n });\n return false;\n }\n }\n\n /**\n * Asynchronously updates an entity in the database.\n * @param {Entity} entity - The entity object to be updated.\n * @returns {Promise<void>} A Promise that resolves when the entity is updated.\n */\n async updateEntity(entity: Entity): Promise<void> {\n return this.withDatabase(async () => {\n await this.db\n .update(entityTable)\n .set(entity)\n .where(and(eq(entityTable.id, entity.id as UUID), eq(entityTable.agentId, entity.agentId)));\n });\n }\n\n async getComponent(\n entityId: UUID,\n type: string,\n worldId?: UUID,\n sourceEntityId?: UUID\n ): Promise<Component | null> {\n return this.withDatabase(async () => {\n const conditions = [eq(componentTable.entityId, entityId), eq(componentTable.type, type)];\n\n if (worldId) {\n conditions.push(eq(componentTable.worldId, worldId));\n }\n\n if (sourceEntityId) {\n conditions.push(eq(componentTable.sourceEntityId, sourceEntityId));\n }\n\n const result = await this.db\n .select()\n .from(componentTable)\n .where(and(...conditions));\n return result.length > 0 ? result[0] : null;\n });\n }\n\n /**\n * Asynchronously retrieves all components for a given entity, optionally filtered by world and source entity.\n * @param {UUID} entityId - The unique identifier of the entity to retrieve components for\n * @param {UUID} [worldId] - Optional world ID to filter components by\n * @param {UUID} [sourceEntityId] - Optional source entity ID to filter components by\n * @returns {Promise<Component[]>} A Promise that resolves to an array of components\n */\n async getComponents(entityId: UUID, worldId?: UUID, sourceEntityId?: UUID): Promise<Component[]> {\n return this.withDatabase(async () => {\n const conditions = [eq(componentTable.entityId, entityId)];\n\n if (worldId) {\n conditions.push(eq(componentTable.worldId, worldId));\n }\n\n if (sourceEntityId) {\n conditions.push(eq(componentTable.sourceEntityId, sourceEntityId));\n }\n\n const result = await this.db\n .select({\n id: componentTable.id,\n entityId: componentTable.entityId,\n type: componentTable.type,\n data: componentTable.data,\n worldId: componentTable.worldId,\n sourceEntityId: componentTable.sourceEntityId,\n createdAt: componentTable.createdAt,\n })\n .from(componentTable)\n .where(and(...conditions));\n return result;\n });\n }\n\n /**\n * Asynchronously creates a new component in the database.\n * @param {Component} component - The component object to be created.\n * @returns {Promise<boolean>} A Promise that resolves to a boolean indicating the success of the operation.\n */\n async createComponent(component: Component): Promise<boolean> {\n return this.withDatabase(async () => {\n await this.db.insert(componentTable).values(component);\n return true;\n });\n }\n\n /**\n * Asynchronously updates an existing component in the database.\n * @param {Component} component - The component object to be updated.\n * @returns {Promise<void>} A Promise that resolves when the component is updated.\n */\n async updateComponent(component: Component): Promise<void> {\n return this.withDatabase(async () => {\n await this.db\n .update(componentTable)\n .set(component)\n .where(eq(componentTable.id, component.id));\n });\n }\n\n /**\n * Asynchronously deletes a component from the database.\n * @param {UUID} componentId - The unique identifier of the component to delete.\n * @returns {Promise<void>} A Promise that resolves when the component is deleted.\n */\n async deleteComponent(componentId: UUID): Promise<void> {\n return this.withDatabase(async () => {\n await this.db.delete(componentTable).where(eq(componentTable.id, componentId));\n });\n }\n\n /**\n * Asynchronously retrieves memories from the database based on the provided parameters.\n * @param {Object} params - The parameters for retrieving memories.\n * @param {UUID} params.roomId - The ID of the room to retrieve memories for.\n * @param {number} [params.count] - The maximum number of memories to retrieve.\n * @param {boolean} [params.unique] - Whether to retrieve unique memories only.\n * @param {string} [params.tableName] - The name of the table to retrieve memories from.\n * @param {number} [params.start] - The start date to retrieve memories from.\n * @param {number} [params.end] - The end date to retrieve memories from.\n * @returns {Promise<Memory[]>} A Promise that resolves to an array of memories.\n */\n async getMemories(params: {\n entityId?: UUID;\n agentId?: UUID;\n roomId?: UUID;\n count?: number;\n unique?: boolean;\n tableName: string;\n start?: number;\n end?: number;\n }): Promise<Memory[]> {\n const { entityId, agentId, roomId, tableName, count, unique, start, end } = params;\n\n if (!tableName) throw new Error('tableName is required');\n if (!roomId && !entityId && !agentId)\n throw new Error('roomId, entityId, or agentId is required');\n\n return this.withDatabase(async () => {\n const conditions = [eq(memoryTable.type, tableName)];\n\n if (start) {\n conditions.push(gte(memoryTable.createdAt, start));\n }\n\n if (entityId) {\n conditions.push(eq(memoryTable.entityId, entityId));\n }\n\n if (roomId) {\n conditions.push(eq(memoryTable.roomId, roomId));\n }\n\n if (end) {\n conditions.push(lte(memoryTable.createdAt, end));\n }\n\n if (unique) {\n conditions.push(eq(memoryTable.unique, true));\n }\n\n if (agentId) {\n conditions.push(eq(memoryTable.agentId, agentId));\n }\n\n const query = this.db\n .select({\n memory: {\n id: memoryTable.id,\n type: memoryTable.type,\n createdAt: memoryTable.createdAt,\n content: memoryTable.content,\n entityId: memoryTable.entityId,\n agentId: memoryTable.agentId,\n roomId: memoryTable.roomId,\n unique: memoryTable.unique,\n metadata: memoryTable.metadata,\n },\n embedding: embeddingTable[this.embeddingDimension],\n })\n .from(memoryTable)\n .leftJoin(embeddingTable, eq(embeddingTable.memoryId, memoryTable.id))\n .where(and(...conditions))\n .orderBy(desc(memoryTable.createdAt));\n\n const rows = params.count ? await query.limit(params.count) : await query;\n\n return rows.map((row) => ({\n id: row.memory.id as UUID,\n type: row.memory.type,\n createdAt: row.memory.createdAt,\n content:\n typeof row.memory.content === 'string'\n ? JSON.parse(row.memory.content)\n : row.memory.content,\n entityId: row.memory.entityId as UUID,\n agentId: row.memory.agentId as UUID,\n roomId: row.memory.roomId as UUID,\n unique: row.memory.unique,\n metadata: row.memory.metadata,\n embedding: row.embedding ? Array.from(row.embedding) : undefined,\n }));\n });\n }\n\n /**\n * Asynchronously retrieves memories from the database based on the provided parameters.\n * @param {Object} params - The parameters for retrieving memories.\n * @param {UUID[]} params.roomIds - The IDs of the rooms to retrieve memories for.\n * @param {string} params.tableName - The name of the table to retrieve memories from.\n * @param {number} [params.limit] - The maximum number of memories to retrieve.\n * @returns {Promise<Memory[]>} A Promise that resolves to an array of memories.\n */\n async getMemoriesByRoomIds(params: {\n roomIds: UUID[];\n tableName: string;\n limit?: number;\n }): Promise<Memory[]> {\n return this.withDatabase(async () => {\n if (params.roomIds.length === 0) return [];\n\n const conditions = [\n eq(memoryTable.type, params.tableName),\n inArray(memoryTable.roomId, params.roomIds),\n ];\n\n conditions.push(eq(memoryTable.agentId, this.agentId));\n\n const query = this.db\n .select({\n id: memoryTable.id,\n type: memoryTable.type,\n createdAt: memoryTable.createdAt,\n content: memoryTable.content,\n entityId: memoryTable.entityId,\n agentId: memoryTable.agentId,\n roomId: memoryTable.roomId,\n unique: memoryTable.unique,\n metadata: memoryTable.metadata,\n })\n .from(memoryTable)\n .where(and(...conditions))\n .orderBy(desc(memoryTable.createdAt));\n\n const rows = params.limit ? await query.limit(params.limit) : await query;\n\n return rows.map((row) => ({\n id: row.id as UUID,\n createdAt: row.createdAt,\n content: typeof row.content === 'string' ? JSON.parse(row.content) : row.content,\n entityId: row.entityId as UUID,\n agentId: row.agentId as UUID,\n roomId: row.roomId as UUID,\n unique: row.unique,\n metadata: row.metadata,\n })) as Memory[];\n });\n }\n\n /**\n * Asynchronously retrieves a memory by its unique identifier.\n * @param {UUID} id - The unique identifier of the memory to retrieve.\n * @returns {Promise<Memory | null>} A Promise that resolves to the memory if found, null otherwise.\n */\n async getMemoryById(id: UUID): Promise<Memory | null> {\n return this.withDatabase(async () => {\n const result = await this.db\n .select({\n memory: memoryTable,\n embedding: embeddingTable[this.embeddingDimension],\n })\n .from(memoryTable)\n .leftJoin(embeddingTable, eq(memoryTable.id, embeddingTable.memoryId))\n .where(eq(memoryTable.id, id))\n .limit(1);\n\n if (result.length === 0) return null;\n\n const row = result[0];\n return {\n id: row.memory.id as UUID,\n createdAt: row.memory.createdAt,\n content:\n typeof row.memory.content === 'string'\n ? JSON.parse(row.memory.content)\n : row.memory.content,\n entityId: row.memory.entityId as UUID,\n agentId: row.memory.agentId as UUID,\n roomId: row.memory.roomId as UUID,\n unique: row.memory.unique,\n embedding: row.embedding ?? undefined,\n };\n });\n }\n\n /**\n * Asynchronously retrieves memories from the database based on the provided parameters.\n * @param {Object} params - The parameters for retrieving memories.\n * @param {UUID[]} params.memoryIds - The IDs of the memories to retrieve.\n * @param {string} [params.tableName] - The name of the table to retrieve memories from.\n * @returns {Promise<Memory[]>} A Promise that resolves to an array of memories.\n */\n async getMemoriesByIds(memoryIds: UUID[], tableName?: string): Promise<Memory[]> {\n return this.withDatabase(async () => {\n if (memoryIds.length === 0) return [];\n\n const conditions = [inArray(memoryTable.id, memoryIds)];\n\n if (tableName) {\n conditions.push(eq(memoryTable.type, tableName));\n }\n\n const rows = await this.db\n .select({\n memory: memoryTable,\n embedding: embeddingTable[this.embeddingDimension],\n })\n .from(memoryTable)\n .leftJoin(embeddingTable, eq(embeddingTable.memoryId, memoryTable.id))\n .where(and(...conditions))\n .orderBy(desc(memoryTable.createdAt));\n\n return rows.map((row) => ({\n id: row.memory.id as UUID,\n createdAt: row.memory.createdAt,\n content:\n typeof row.memory.content === 'string'\n ? JSON.parse(row.memory.content)\n : row.memory.content,\n entityId: row.memory.entityId as UUID,\n agentId: row.memory.agentId as UUID,\n roomId: row.memory.roomId as UUID,\n unique: row.memory.unique,\n metadata: row.memory.metadata,\n embedding: row.embedding ?? undefined,\n }));\n });\n }\n\n /**\n * Asynchronously retrieves cached embeddings from the database based on the provided parameters.\n * @param {Object} opts - The parameters for retrieving cached embeddings.\n * @param {string} opts.query_table_name - The name of the table to retrieve embeddings from.\n * @param {number} opts.query_threshold - The threshold for the levenshtein distance.\n * @param {string} opts.query_input - The input string to search for.\n * @param {string} opts.query_field_name - The name of the field to retrieve embeddings from.\n * @param {string} opts.query_field_sub_name - The name of the sub-field to retrieve embeddings from.\n * @param {number} opts.query_match_count - The maximum number of matches to retrieve.\n * @returns {Promise<{ embedding: number[]; levenshtein_score: number }[]>} A Promise that resolves to an array of cached embeddings.\n */\n async getCachedEmbeddings(opts: {\n query_table_name: string;\n query_threshold: number;\n query_input: string;\n query_field_name: string;\n query_field_sub_name: string;\n query_match_count: number;\n }): Promise<{ embedding: number[]; levenshtein_score: number }[]> {\n return this.withDatabase(async () => {\n try {\n const results = await this.db.execute<{\n embedding: number[];\n levenshtein_score: number;\n }>(sql`\n WITH content_text AS (\n SELECT\n m.id,\n COALESCE(\n m.content->>${opts.query_field_sub_name},\n ''\n ) as content_text\n FROM memories m\n WHERE m.type = ${opts.query_table_name}\n AND m.content->>${opts.query_field_sub_name} IS NOT NULL\n ),\n embedded_text AS (\n SELECT \n ct.content_text,\n COALESCE(\n e.dim_384,\n e.dim_512,\n e.dim_768,\n e.dim_1024,\n e.dim_1536,\n e.dim_3072\n ) as embedding\n FROM content_text ct\n LEFT JOIN embeddings e ON e.memory_id = ct.id\n WHERE e.memory_id IS NOT NULL\n )\n SELECT\n embedding,\n levenshtein(${opts.query_input}, content_text) as levenshtein_score\n FROM embedded_text\n WHERE levenshtein(${opts.query_input}, content_text) <= ${opts.query_threshold}\n ORDER BY levenshtein_score\n LIMIT ${opts.query_match_count}\n `);\n\n return results.rows\n .map((row) => ({\n embedding: Array.isArray(row.embedding)\n ? row.embedding\n : typeof row.embedding === 'string'\n ? JSON.parse(row.embedding)\n : [],\n levenshtein_score: Number(row.levenshtein_score),\n }))\n .filter((row) => Array.isArray(row.embedding));\n } catch (error) {\n logger.error('Error in getCachedEmbeddings:', {\n error: error instanceof Error ? error.message : String(error),\n tableName: opts.query_table_name,\n fieldName: opts.query_field_name,\n });\n if (\n error instanceof Error &&\n error.message === 'levenshtein argument exceeds maximum length of 255 characters'\n ) {\n return [];\n }\n throw error;\n }\n });\n }\n\n /**\n * Asynchronously logs an event in the database.\n * @param {Object} params - The parameters for logging an event.\n * @param {Object} params.body - The body of the event to log.\n * @param {UUID} params.entityId - The ID of the entity associated with the event.\n * @param {UUID} params.roomId - The ID of the room associated with the event.\n * @param {string} params.type - The type of the event to log.\n * @returns {Promise<void>} A Promise that resolves when the event is logged.\n */\n async log(params: {\n body: { [key: string]: unknown };\n entityId: UUID;\n roomId: UUID;\n type: string;\n }): Promise<void> {\n return this.withDatabase(async () => {\n try {\n await this.db.transaction(async (tx) => {\n await tx.insert(logTable).values({\n body: sql`${params.body}::jsonb`,\n entityId: params.entityId,\n roomId: params.roomId,\n type: params.type,\n });\n });\n } catch (error) {\n logger.error('Failed to create log entry:', {\n error: error instanceof Error ? error.message : String(error),\n type: params.type,\n roomId: params.roomId,\n entityId: params.entityId,\n });\n throw error;\n }\n });\n }\n\n /**\n * Asynchronously retrieves logs from the database based on the provided parameters.\n * @param {Object} params - The parameters for retrieving logs.\n * @param {UUID} params.entityId - The ID of the entity associated with the logs.\n * @param {UUID} [params.roomId] - The ID of the room associated with the logs.\n * @param {string} [params.type] - The type of the logs to retrieve.\n * @param {number} [params.count] - The maximum number of logs to retrieve.\n * @param {number} [params.offset] - The offset to retrieve logs from.\n * @returns {Promise<Log[]>} A Promise that resolves to an array of logs.\n */\n async getLogs(params: {\n entityId: UUID;\n roomId?: UUID;\n type?: string;\n count?: number;\n offset?: number;\n }): Promise<Log[]> {\n const { entityId, roomId, type, count, offset } = params;\n return this.withDatabase(async () => {\n const result = await this.db\n .select()\n .from(logTable)\n .where(\n and(\n eq(logTable.entityId, entityId),\n roomId ? eq(logTable.roomId, roomId) : undefined,\n type ? eq(logTable.type, type) : undefined\n )\n )\n .orderBy(desc(logTable.createdAt))\n .limit(count ?? 10)\n .offset(offset ?? 0);\n return result;\n });\n }\n\n /**\n * Asynchronously deletes a log from the database based on the provided parameters.\n * @param {UUID} logId - The ID of the log to delete.\n * @returns {Promise<void>} A Promise that resolves when the log is deleted.\n */\n async deleteLog(logId: UUID): Promise<void> {\n return this.withDatabase(async () => {\n await this.db.delete(logTable).where(eq(logTable.id, logId));\n });\n }\n\n /**\n * Asynchronously searches for memories in the database based on the provided parameters.\n * @param {Object} params - The parameters for searching for memories.\n * @param {string} params.tableName - The name of the table to search for memories in.\n * @param {UUID} params.roomId - The ID of the room to search for memories in.\n * @param {number[]} params.embedding - The embedding to search for.\n * @param {number} [params.match_threshold] - The threshold for the cosine distance.\n * @param {number} [params.count] - The maximum number of memories to retrieve.\n * @param {boolean} [params.unique] - Whether to retrieve unique memories only.\n * @returns {Promise<Memory[]>} A Promise that resolves to an array of memories.\n */\n async searchMemories(params: {\n tableName: string;\n roomId: UUID;\n embedding: number[];\n match_threshold: number;\n count: number;\n unique: boolean;\n }): Promise<Memory[]> {\n return await this.searchMemoriesByEmbedding(params.embedding, {\n match_threshold: params.match_threshold,\n count: params.count,\n roomId: params.roomId,\n unique: params.unique,\n tableName: params.tableName,\n });\n }\n\n /**\n * Asynchronously searches for memories in the database based on the provided parameters.\n * @param {number[]} embedding - The embedding to search for.\n * @param {Object} params - The parameters for searching for memories.\n * @param {number} [params.match_threshold] - The threshold for the cosine distance.\n * @param {number} [params.count] - The maximum number of memories to retrieve.\n * @param {UUID} [params.roomId] - The ID of the room to search for memories in.\n * @param {boolean} [params.unique] - Whether to retrieve unique memories only.\n * @param {string} [params.tableName] - The name of the table to search for memories in.\n * @returns {Promise<Memory[]>} A Promise that resolves to an array of memories.\n */\n async searchMemoriesByEmbedding(\n embedding: number[],\n params: {\n match_threshold?: number;\n count?: number;\n roomId?: UUID;\n unique?: boolean;\n tableName: string;\n }\n ): Promise<Memory[]> {\n return this.withDatabase(async () => {\n const cleanVector = embedding.map((n) => (Number.isFinite(n) ? Number(n.toFixed(6)) : 0));\n\n const similarity = sql<number>`1 - (${cosineDistance(\n embeddingTable[this.embeddingDimension],\n cleanVector\n )})`;\n\n const conditions = [eq(memoryTable.type, params.tableName)];\n\n if (params.unique) {\n conditions.push(eq(memoryTable.unique, true));\n }\n\n conditions.push(eq(memoryTable.agentId, this.agentId));\n\n if (params.roomId) {\n conditions.push(eq(memoryTable.roomId, params.roomId));\n }\n\n if (params.match_threshold) {\n conditions.push(gte(similarity, params.match_threshold));\n }\n\n const results = await this.db\n .select({\n memory: memoryTable,\n similarity,\n embedding: embeddingTable[this.embeddingDimension],\n })\n .from(embeddingTable)\n .innerJoin(memoryTable, eq(memoryTable.id, embeddingTable.memoryId))\n .where(and(...conditions))\n .orderBy(desc(similarity))\n .limit(params.count ?? 10);\n\n return results.map((row) => ({\n id: row.memory.id as UUID,\n type: row.memory.type,\n createdAt: row.memory.createdAt,\n content:\n typeof row.memory.content === 'string'\n ? JSON.parse(row.memory.content)\n : row.memory.content,\n entityId: row.memory.entityId as UUID,\n agentId: row.memory.agentId as UUID,\n roomId: row.memory.roomId as UUID,\n unique: row.memory.unique,\n metadata: row.memory.metadata,\n embedding: row.embedding ?? undefined,\n similarity: row.similarity,\n }));\n });\n }\n\n /**\n * Asynchronously creates a new memory in the database.\n * @param {Memory & { metadata?: MemoryMetadata }} memory - The memory object to create.\n * @param {string} tableName - The name of the table to create the memory in.\n * @returns {Promise<UUID>} A Promise that resolves to the ID of the created memory.\n */\n async createMemory(\n memory: Memory & { metadata?: MemoryMetadata },\n tableName: string\n ): Promise<UUID> {\n logger.debug('DrizzleAdapter createMemory:', {\n memoryId: memory.id,\n embeddingLength: memory.embedding?.length,\n contentLength: memory.content?.text?.length,\n });\n\n let isUnique = true;\n if (memory.embedding && Array.isArray(memory.embedding)) {\n const similarMemories = await this.searchMemoriesByEmbedding(memory.embedding, {\n tableName,\n roomId: memory.roomId,\n match_threshold: 0.95,\n count: 1,\n });\n isUnique = similarMemories.length === 0;\n }\n\n const contentToInsert =\n typeof memory.content === 'string' ? JSON.parse(memory.content) : memory.content;\n\n const memoryId = memory.id ?? (v4() as UUID);\n\n await this.db.transaction(async (tx) => {\n await tx.insert(memoryTable).values([\n {\n id: memoryId,\n type: tableName,\n content: sql`${contentToInsert}::jsonb`,\n metadata: sql`${memory.metadata || {}}::jsonb`,\n entityId: memory.entityId,\n roomId: memory.roomId,\n agentId: memory.agentId,\n unique: memory.unique ?? isUnique,\n createdAt: memory.createdAt,\n },\n ]);\n\n if (memory.embedding && Array.isArray(memory.embedding)) {\n const embeddingValues: Record<string, unknown> = {\n id: v4(),\n memoryId: memoryId,\n createdAt: memory.createdAt,\n };\n\n const cleanVector = memory.embedding.map((n) =>\n Number.isFinite(n) ? Number(n.toFixed(6)) : 0\n );\n\n embeddingValues[this.embeddingDimension] = cleanVector;\n\n await tx.insert(embeddingTable).values([embeddingValues]);\n }\n });\n\n return memoryId;\n }\n\n /**\n * Updates an existing memory in the database.\n * @param memory The memory object with updated content and optional embedding\n * @returns Promise resolving to boolean indicating success\n */\n async updateMemory(\n memory: Partial<Memory> & { id: UUID; metadata?: MemoryMetadata }\n ): Promise<boolean> {\n return this.withDatabase(async () => {\n try {\n logger.debug('Updating memory:', {\n memoryId: memory.id,\n hasEmbedding: !!memory.embedding,\n });\n\n await this.db.transaction(async (tx) => {\n // Update memory content if provided\n if (memory.content) {\n const contentToUpdate =\n typeof memory.content === 'string' ? JSON.parse(memory.content) : memory.content;\n\n await tx\n .update(memoryTable)\n .set({\n content: sql`${contentToUpdate}::jsonb`,\n ...(memory.metadata && { metadata: sql`${memory.metadata}::jsonb` }),\n })\n .where(eq(memoryTable.id, memory.id));\n } else if (memory.metadata) {\n // Update only metadata if content is not provided\n await tx\n .update(memoryTable)\n .set({\n metadata: sql`${memory.metadata}::jsonb`,\n })\n .where(eq(memoryTable.id, memory.id));\n }\n\n // Update embedding if provided\n if (memory.embedding && Array.isArray(memory.embedding)) {\n const cleanVector = memory.embedding.map((n) =>\n Number.isFinite(n) ? Number(n.toFixed(6)) : 0\n );\n\n // Check if embedding exists\n const existingEmbedding = await tx\n .select({ id: embeddingTable.id })\n .from(embeddingTable)\n .where(eq(embeddingTable.memoryId, memory.id))\n .limit(1);\n\n if (existingEmbedding.length > 0) {\n // Update existing embedding\n const updateValues: Record<string, unknown> = {};\n updateValues[this.embeddingDimension] = cleanVector;\n\n await tx\n .update(embeddingTable)\n .set(updateValues)\n .where(eq(embeddingTable.memoryId, memory.id));\n } else {\n // Create new embedding\n const embeddingValues: Record<string, unknown> = {\n id: v4(),\n memoryId: memory.id,\n createdAt: Date.now(),\n };\n embeddingValues[this.embeddingDimension] = cleanVector;\n\n await tx.insert(embeddingTable).values([embeddingValues]);\n }\n }\n });\n\n logger.debug('Memory updated successfully:', {\n memoryId: memory.id,\n });\n return true;\n } catch (error) {\n logger.error('Error updating memory:', {\n error: error instanceof Error ? error.message : String(error),\n memoryId: memory.id,\n });\n return false;\n }\n });\n }\n\n /**\n * Asynchronously deletes a memory from the database based on the provided parameters.\n * @param {UUID} memoryId - The ID of the memory to delete.\n * @returns {Promise<void>} A Promise that resolves when the memory is deleted.\n */\n async deleteMemory(memoryId: UUID): Promise<void> {\n return this.withDatabase(async () => {\n await this.db.transaction(async (tx) => {\n // See if there are any fragments that we need to delete\n await this.deleteMemoryFragments(tx, memoryId);\n\n // Then delete the embedding for the main memory\n await tx.delete(embeddingTable).where(eq(embeddingTable.memoryId, memoryId));\n\n // Finally delete the memory itself\n await tx.delete(memoryTable).where(eq(memoryTable.id, memoryId));\n });\n\n logger.debug('Memory and related fragments removed successfully:', {\n memoryId,\n });\n });\n }\n\n /**\n * Deletes all memory fragments that reference a specific document memory\n * @param tx The database transaction\n * @param documentId The UUID of the document memory whose fragments should be deleted\n * @private\n */\n private async deleteMemoryFragments(tx: DrizzleOperations, documentId: UUID): Promise<void> {\n const fragmentsToDelete = await this.getMemoryFragments(tx, documentId);\n\n if (fragmentsToDelete.length > 0) {\n const fragmentIds = fragmentsToDelete.map((f) => f.id) as UUID[];\n\n // Delete embeddings for fragments\n await tx.delete(embeddingTable).where(inArray(embeddingTable.memoryId, fragmentIds));\n\n // Delete the fragments\n await tx.delete(memoryTable).where(inArray(memoryTable.id, fragmentIds));\n\n logger.debug('Deleted related fragments:', {\n documentId,\n fragmentCount: fragmentsToDelete.length,\n });\n }\n }\n\n /**\n * Retrieves all memory fragments that reference a specific document memory\n * @param tx The database transaction\n * @param documentId The UUID of the document memory whose fragments should be retrieved\n * @returns An array of memory fragments\n * @private\n */\n private async getMemoryFragments(tx: DrizzleOperations, documentId: UUID): Promise<Memory[]> {\n const fragments = await tx\n .select({ id: memoryTable.id })\n .from(memoryTable)\n .where(\n and(\n eq(memoryTable.agentId, this.agentId),\n sql`${memoryTable.metadata}->>'documentId' = ${documentId}`\n )\n );\n\n return fragments;\n }\n\n /**\n * Asynchronously deletes all memories from the database based on the provided parameters.\n * @param {UUID} roomId - The ID of the room to delete memories from.\n * @param {string} tableName - The name of the table to delete memories from.\n * @returns {Promise<void>} A Promise that resolves when the memories are deleted.\n */\n async deleteAllMemories(roomId: UUID, tableName: string): Promise<void> {\n return this.withDatabase(async () => {\n await this.db.transaction(async (tx) => {\n const memoryIds = await tx\n .select({ id: memoryTable.id })\n .from(memoryTable)\n .where(and(eq(memoryTable.roomId, roomId), eq(memoryTable.type, tableName)));\n\n if (memoryIds.length > 0) {\n await tx.delete(embeddingTable).where(\n inArray(\n embeddingTable.memoryId,\n memoryIds.map((m) => m.id)\n )\n );\n\n await tx\n .delete(memoryTable)\n .where(and(eq(memoryTable.roomId, roomId), eq(memoryTable.type, tableName)));\n }\n });\n\n logger.debug('All memories removed successfully:', {\n roomId,\n tableName,\n });\n });\n }\n\n /**\n * Asynchronously counts the number of memories in the database based on the provided parameters.\n * @param {UUID} roomId - The ID of the room to count memories in.\n * @param {boolean} [unique] - Whether to count unique memories only.\n * @param {string} [tableName] - The name of the table to count memories in.\n * @returns {Promise<number>} A Promise that resolves to the number of memories.\n */\n async countMemories(roomId: UUID, unique = true, tableName = ''): Promise<number> {\n if (!tableName) throw new Error('tableName is required');\n\n return this.withDatabase(async () => {\n const conditions = [eq(memoryTable.roomId, roomId), eq(memoryTable.type, tableName)];\n\n if (unique) {\n conditions.push(eq(memoryTable.unique, true));\n }\n\n const result = await this.db\n .select({ count: sql<number>`count(*)` })\n .from(memoryTable)\n .where(and(...conditions));\n\n return Number(result[0]?.count ?? 0);\n });\n }\n\n /**\n * Asynchronously retrieves a room from the database based on the provided parameters.\n * @param {UUID} roomId - The ID of the room to retrieve.\n * @returns {Promise<Room | null>} A Promise that resolves to the room if found, null otherwise.\n */\n async getRoom(roomId: UUID): Promise<Room | null> {\n return this.withDatabase(async () => {\n const result = await this.db\n .select({\n id: roomTable.id,\n channelId: roomTable.channelId,\n agentId: roomTable.agentId,\n serverId: roomTable.serverId,\n worldId: roomTable.worldId,\n type: roomTable.type,\n source: roomTable.source,\n })\n .from(roomTable)\n .where(and(eq(roomTable.id, roomId), eq(roomTable.agentId, this.agentId)))\n .limit(1);\n if (result.length === 0) return null;\n return result[0];\n });\n }\n\n /**\n * Asynchronously retrieves all rooms from the database based on the provided parameters.\n * @param {UUID} worldId - The ID of the world to retrieve rooms from.\n * @returns {Promise<Room[]>} A Promise that resolves to an array of rooms.\n */\n async getRooms(worldId: UUID): Promise<Room[]> {\n return this.withDatabase(async () => {\n const result = await this.db.select().from(roomTable).where(eq(roomTable.worldId, worldId));\n return result;\n });\n }\n\n /**\n * Asynchronously updates a room in the database based on the provided parameters.\n * @param {Room} room - The room object to update.\n * @returns {Promise<void>} A Promise that resolves when the room is updated.\n */\n async updateRoom(room: Room): Promise<void> {\n return this.withDatabase(async () => {\n await this.db\n .update(roomTable)\n .set({ ...room, agentId: this.agentId })\n .where(eq(roomTable.id, room.id));\n });\n }\n\n /**\n * Asynchronously creates a new room in the database based on the provided parameters.\n * @param {Room} room - The room object to create.\n * @returns {Promise<UUID>} A Promise that resolves to the ID of the created room.\n */\n async createRoom({\n id,\n name,\n source,\n type,\n channelId,\n serverId,\n worldId,\n metadata,\n }: Room): Promise<UUID> {\n return this.withDatabase(async () => {\n const newRoomId = id || v4();\n await this.db\n .insert(roomTable)\n .values({\n id: newRoomId,\n name,\n agentId: this.agentId,\n source,\n type,\n channelId,\n serverId,\n worldId,\n metadata,\n })\n .onConflictDoNothing({ target: roomTable.id });\n return newRoomId as UUID;\n });\n }\n\n /**\n * Asynchronously deletes a room from the database based on the provided parameters.\n * @param {UUID} roomId - The ID of the room to delete.\n * @returns {Promise<void>} A Promise that resolves when the room is deleted.\n */\n async deleteRoom(roomId: UUID): Promise<void> {\n if (!roomId) throw new Error('Room ID is required');\n return this.withDatabase(async () => {\n await this.db.transaction(async (tx) => {\n await tx.delete(roomTable).where(eq(roomTable.id, roomId));\n });\n });\n }\n\n /**\n * Asynchronously retrieves all rooms for a participant from the database based on the provided parameters.\n * @param {UUID} entityId - The ID of the entity to retrieve rooms for.\n * @returns {Promise<UUID[]>} A Promise that resolves to an array of room IDs.\n */\n async getRoomsForParticipant(entityId: UUID): Promise<UUID[]> {\n return this.withDatabase(async () => {\n const result = await this.db\n .select({ roomId: participantTable.roomId })\n .from(participantTable)\n .innerJoin(roomTable, eq(participantTable.roomId, roomTable.id))\n .where(and(eq(participantTable.entityId, entityId), eq(roomTable.agentId, this.agentId)));\n\n return result.map((row) => row.roomId as UUID);\n });\n }\n\n /**\n * Asynchronously retrieves all rooms for a list of participants from the database based on the provided parameters.\n * @param {UUID[]} entityIds - The IDs of the entities to retrieve rooms for.\n * @returns {Promise<UUID[]>} A Promise that resolves to an array of room IDs.\n */\n async getRoomsForParticipants(entityIds: UUID[]): Promise<UUID[]> {\n return this.withDatabase(async () => {\n const result = await this.db\n .selectDistinct({ roomId: participantTable.roomId })\n .from(participantTable)\n .innerJoin(roomTable, eq(participantTable.roomId, roomTable.id))\n .where(\n and(inArray(participantTable.entityId, entityIds), eq(roomTable.agentId, this.agentId))\n );\n\n return result.map((row) => row.roomId as UUID);\n });\n }\n\n /**\n * Asynchronously adds a participant to a room in the database based on the provided parameters.\n * @param {UUID} entityId - The ID of the entity to add to the room.\n * @param {UUID} roomId - The ID of the room to add the entity to.\n * @returns {Promise<boolean>} A Promise that resolves to a boolean indicating whether the participant was added successfully.\n */\n async addParticipant(entityId: UUID, roomId: UUID): Promise<boolean> {\n return this.withDatabase(async () => {\n try {\n await this.db\n .insert(participantTable)\n .values({\n entityId,\n roomId,\n agentId: this.agentId,\n })\n .onConflictDoNothing();\n return true;\n } catch (error) {\n logger.error('Error adding participant', {\n error: error instanceof Error ? error.message : String(error),\n entityId,\n roomId,\n agentId: this.agentId,\n });\n return false;\n }\n });\n }\n\n /**\n * Asynchronously removes a participant from a room in the database based on the provided parameters.\n * @param {UUID} entityId - The ID of the entity to remove from the room.\n * @param {UUID} roomId - The ID of the room to remove the entity from.\n * @returns {Promise<boolean>} A Promise that resolves to a boolean indicating whether the participant was removed successfully.\n */\n async removeParticipant(entityId: UUID, roomId: UUID): Promise<boolean> {\n return this.withDatabase(async () => {\n try {\n const result = await this.db.transaction(async (tx) => {\n return await tx\n .delete(participantTable)\n .where(\n and(eq(participantTable.entityId, entityId), eq(participantTable.roomId, roomId))\n )\n .returning();\n });\n\n const removed = result.length > 0;\n logger.debug(`Participant ${removed ? 'removed' : 'not found'}:`, {\n entityId,\n roomId,\n removed,\n });\n\n return removed;\n } catch (error) {\n logger.error('Failed to remove participant:', {\n error: error instanceof Error ? error.message : String(error),\n entityId,\n roomId,\n });\n return false;\n }\n });\n }\n\n /**\n * Asynchronously retrieves all participants for an entity from the database based on the provided parameters.\n * @param {UUID} entityId - The ID of the entity to retrieve participants for.\n * @returns {Promise<Participant[]>} A Promise that resolves to an array of participants.\n */\n async getParticipantsForEntity(entityId: UUID): Promise<Participant[]> {\n return this.withDatabase(async () => {\n const result = await this.db\n .select({\n id: participantTable.id,\n entityId: participantTable.entityId,\n roomId: participantTable.roomId,\n })\n .from(participantTable)\n .where(eq(participantTable.entityId, entityId));\n\n const entity = await this.getEntityById(entityId);\n\n if (!entity) {\n return [];\n }\n\n return result.map((row) => ({\n id: row.id as UUID,\n entity: entity,\n }));\n });\n }\n\n /**\n * Asynchronously retrieves all participants for a room from the database based on the provided parameters.\n * @param {UUID} roomId - The ID of the room to retrieve participants for.\n * @returns {Promise<UUID[]>} A Promise that resolves to an array of entity IDs.\n */\n async getParticipantsForRoom(roomId: UUID): Promise<UUID[]> {\n return this.withDatabase(async () => {\n const result = await this.db\n .select({ entityId: participantTable.entityId })\n .from(participantTable)\n .where(eq(participantTable.roomId, roomId));\n\n return result.map((row) => row.entityId as UUID);\n });\n }\n\n /**\n * Asynchronously retrieves the user state for a participant in a room from the database based on the provided parameters.\n * @param {UUID} roomId - The ID of the room to retrieve the participant's user state for.\n * @param {UUID} entityId - The ID of the entity to retrieve the user state for.\n * @returns {Promise<\"FOLLOWED\" | \"MUTED\" | null>} A Promise that resolves to the participant's user state.\n */\n async getParticipantUserState(\n roomId: UUID,\n entityId: UUID\n ): Promise<'FOLLOWED' | 'MUTED' | null> {\n return this.withDatabase(async () => {\n const result = await this.db\n .select({ roomState: participantTable.roomState })\n .from(participantTable)\n .where(\n and(\n eq(participantTable.roomId, roomId),\n eq(participantTable.entityId, entityId),\n eq(participantTable.agentId, this.agentId)\n )\n )\n .limit(1);\n\n return (result[0]?.roomState as 'FOLLOWED' | 'MUTED' | null) ?? null;\n });\n }\n\n /**\n * Asynchronously sets the user state for a participant in a room in the database based on the provided parameters.\n * @param {UUID} roomId - The ID of the room to set the participant's user state for.\n * @param {UUID} entityId - The ID of the entity to set the user state for.\n * @param {string} state - The state to set the participant's user state to.\n * @returns {Promise<void>} A Promise that resolves when the participant's user state is set.\n */\n async setParticipantUserState(\n roomId: UUID,\n entityId: UUID,\n state: 'FOLLOWED' | 'MUTED' | null\n ): Promise<void> {\n return this.withDatabase(async () => {\n try {\n await this.db.transaction(async (tx) => {\n await tx\n .update(participantTable)\n .set({ roomState: state })\n .where(\n and(\n eq(participantTable.roomId, roomId),\n eq(participantTable.entityId, entityId),\n eq(participantTable.agentId, this.agentId)\n )\n );\n });\n } catch (error) {\n logger.error('Failed to set participant user state:', {\n roomId,\n entityId,\n state,\n error: error instanceof Error ? error.message : String(error),\n });\n throw error;\n }\n });\n }\n\n /**\n * Asynchronously creates a new relationship in the database based on the provided parameters.\n * @param {Object} params - The parameters for creating a new relationship.\n * @param {UUID} params.sourceEntityId - The ID of the source entity.\n * @param {UUID} params.targetEntityId - The ID of the target entity.\n * @param {string[]} [params.tags] - The tags for the relationship.\n * @param {Object} [params.metadata] - The metadata for the relationship.\n * @returns {Promise<boolean>} A Promise that resolves to a boolean indicating whether the relationship was created successfully.\n */\n async createRelationship(params: {\n sourceEntityId: UUID;\n targetEntityId: UUID;\n tags?: string[];\n metadata?: { [key: string]: unknown };\n }): Promise<boolean> {\n return this.withDatabase(async () => {\n const id = v4();\n const saveParams = {\n id,\n sourceEntityId: params.sourceEntityId,\n targetEntityId: params.targetEntityId,\n agentId: this.agentId,\n tags: params.tags || [],\n metadata: params.metadata || {},\n };\n try {\n await this.db.insert(relationshipTable).values(saveParams);\n return true;\n } catch (error) {\n logger.error('Error creating relationship:', {\n error: error instanceof Error ? error.message : String(error),\n saveParams,\n });\n return false;\n }\n });\n }\n\n /**\n * Asynchronously updates an existing relationship in the database based on the provided parameters.\n * @param {Relationship} relationship - The relationship object to update.\n * @returns {Promise<void>} A Promise that resolves when the relationship is updated.\n */\n async updateRelationship(relationship: Relationship): Promise<void> {\n return this.withDatabase(async () => {\n try {\n await this.db\n .update(relationshipTable)\n .set({\n tags: relationship.tags || [],\n metadata: relationship.metadata || {},\n })\n .where(eq(relationshipTable.id, relationship.id));\n } catch (error) {\n logger.error('Error updating relationship:', {\n error: error instanceof Error ? error.message : String(error),\n relationship,\n });\n throw error;\n }\n });\n }\n\n /**\n * Asynchronously retrieves a relationship from the database based on the provided parameters.\n * @param {Object} params - The parameters for retrieving a relationship.\n * @param {UUID} params.sourceEntityId - The ID of the source entity.\n * @param {UUID} params.targetEntityId - The ID of the target entity.\n * @returns {Promise<Relationship | null>} A Promise that resolves to the relationship if found, null otherwise.\n */\n async getRelationship(params: {\n sourceEntityId: UUID;\n targetEntityId: UUID;\n }): Promise<Relationship | null> {\n return this.withDatabase(async () => {\n try {\n const result = await this.db\n .select()\n .from(relationshipTable)\n .where(\n and(\n eq(relationshipTable.sourceEntityId, params.sourceEntityId),\n eq(relationshipTable.targetEntityId, params.targetEntityId),\n eq(relationshipTable.agentId, this.agentId)\n )\n )\n .limit(1);\n\n if (result.length === 0) {\n return null;\n }\n\n return {\n id: result[0].id,\n sourceEntityId: result[0].sourceEntityId,\n targetEntityId: result[0].targetEntityId,\n agentId: result[0].agentId,\n tags: result[0].tags || [],\n metadata: result[0].metadata || {},\n createdAt: result[0].createdAt?.toString(),\n };\n } catch (error) {\n logger.error('Error getting relationship:', {\n error: error instanceof Error ? error.message : String(error),\n params,\n });\n return null;\n }\n });\n }\n\n /**\n * Asynchronously retrieves all relationships from the database based on the provided parameters.\n * @param {Object} params - The parameters for retrieving relationships.\n * @param {UUID} params.entityId - The ID of the entity to retrieve relationships for.\n * @param {string[]} [params.tags] - The tags to filter relationships by.\n * @returns {Promise<Relationship[]>} A Promise that resolves to an array of relationships.\n */\n async getRelationships(params: { entityId: UUID; tags?: string[] }): Promise<Relationship[]> {\n return this.withDatabase(async () => {\n try {\n let query = this.db\n .select()\n .from(relationshipTable)\n .where(\n and(\n or(\n eq(relationshipTable.sourceEntityId, params.entityId),\n eq(relationshipTable.targetEntityId, params.entityId)\n ),\n eq(relationshipTable.agentId, this.agentId)\n )\n );\n\n // Filter by tags if provided\n if (params.tags && params.tags.length > 0) {\n // Filter by tags - find tasks that have ALL of the specified tags\n // Using @> operator which checks if left array contains all elements from right array\n const tagParams = params.tags.map((tag) => `'${tag.replace(/'/g, \"''\")}'`).join(', ');\n query = query.where(\n sql`${relationshipTable.tags} @> ARRAY[${sql.raw(tagParams)}]::text[]`\n );\n }\n\n const results = await query;\n\n return results.map((result) => ({\n id: result.id,\n sourceEntityId: result.sourceEntityId,\n targetEntityId: result.targetEntityId,\n agentId: result.agentId,\n tags: result.tags || [],\n metadata: result.metadata || {},\n createdAt: result.createdAt?.toString(),\n }));\n } catch (error) {\n logger.error('Error getting relationships:', {\n error: error instanceof Error ? error.message : String(error),\n params,\n });\n return [];\n }\n });\n }\n\n /**\n * Asynchronously retrieves a cache value from the database based on the provided key.\n * @param {string} key - The key to retrieve the cache value for.\n * @returns {Promise<T | undefined>} A Promise that resolves to the cache value if found, undefined otherwise.\n */\n async getCache<T>(key: string): Promise<T | undefined> {\n return this.withDatabase(async () => {\n try {\n const result = await this.db\n .select()\n .from(cacheTable)\n .where(and(eq(cacheTable.agentId, this.agentId), eq(cacheTable.key, key)));\n\n return result[0]?.value as T | undefined;\n } catch (error) {\n logger.error('Error fetching cache', {\n error: error instanceof Error ? error.message : String(error),\n key: key,\n agentId: this.agentId,\n });\n return undefined;\n }\n });\n }\n\n /**\n * Asynchronously sets a cache value in the database based on the provided key and value.\n * @param {string} key - The key to set the cache value for.\n * @param {T} value - The value to set in the cache.\n * @returns {Promise<boolean>} A Promise that resolves to a boolean indicating whether the cache value was set successfully.\n */\n async setCache<T>(key: string, value: T): Promise<boolean> {\n return this.withDatabase(async () => {\n try {\n await this.db.transaction(async (tx) => {\n await tx\n .insert(cacheTable)\n .values({\n key: key,\n agentId: this.agentId,\n value: value,\n })\n .onConflictDoUpdate({\n target: [cacheTable.key, cacheTable.agentId],\n set: {\n value: value,\n },\n });\n });\n return true;\n } catch (error) {\n logger.error('Error setting cache', {\n error: error instanceof Error ? error.message : String(error),\n key: key,\n agentId: this.agentId,\n });\n return false;\n }\n });\n }\n\n /**\n * Asynchronously deletes a cache value from the database based on the provided key.\n * @param {string} key - The key to delete the cache value for.\n * @returns {Promise<boolean>} A Promise that resolves to a boolean indicating whether the cache value was deleted successfully.\n */\n async deleteCache(key: string): Promise<boolean> {\n return this.withDatabase(async () => {\n try {\n await this.db.transaction(async (tx) => {\n await tx\n .delete(cacheTable)\n .where(and(eq(cacheTable.agentId, this.agentId), eq(cacheTable.key, key)));\n });\n return true;\n } catch (error) {\n logger.error('Error deleting cache', {\n error: error instanceof Error ? error.message : String(error),\n key: key,\n agentId: this.agentId,\n });\n return false;\n }\n });\n }\n\n /**\n * Asynchronously creates a new world in the database based on the provided parameters.\n * @param {World} world - The world object to create.\n * @returns {Promise<UUID>} A Promise that resolves to the ID of the created world.\n */\n async createWorld(world: World): Promise<UUID> {\n return this.withDatabase(async () => {\n const newWorldId = world.id || v4();\n await this.db.insert(worldTable).values({\n ...world,\n id: newWorldId,\n });\n return newWorldId;\n });\n }\n\n /**\n * Asynchronously retrieves a world from the database based on the provided parameters.\n * @param {UUID} id - The ID of the world to retrieve.\n * @returns {Promise<World | null>} A Promise that resolves to the world if found, null otherwise.\n */\n async getWorld(id: UUID): Promise<World | null> {\n return this.withDatabase(async () => {\n const result = await this.db.select().from(worldTable).where(eq(worldTable.id, id));\n return result[0] as World | null;\n });\n }\n\n /**\n * Asynchronously retrieves all worlds from the database based on the provided parameters.\n * @returns {Promise<World[]>} A Promise that resolves to an array of worlds.\n */\n async getAllWorlds(): Promise<World[]> {\n return this.withDatabase(async () => {\n const result = await this.db\n .select()\n .from(worldTable)\n .where(eq(worldTable.agentId, this.agentId));\n return result as World[];\n });\n }\n\n /**\n * Asynchronously updates an existing world in the database based on the provided parameters.\n * @param {World} world - The world object to update.\n * @returns {Promise<void>} A Promise that resolves when the world is updated.\n */\n async updateWorld(world: World): Promise<void> {\n return this.withDatabase(async () => {\n await this.db.update(worldTable).set(world).where(eq(worldTable.id, world.id));\n });\n }\n\n /**\n * Asynchronously removes a world from the database based on the provided parameters.\n * @param {UUID} id - The ID of the world to remove.\n * @returns {Promise<void>} A Promise that resolves when the world is removed.\n */\n async removeWorld(id: UUID): Promise<void> {\n return this.withDatabase(async () => {\n await this.db.delete(worldTable).where(eq(worldTable.id, id));\n });\n }\n\n /**\n * Asynchronously creates a new task in the database based on the provided parameters.\n * @param {Task} task - The task object to create.\n * @returns {Promise<UUID>} A Promise that resolves to the ID of the created task.\n */\n async createTask(task: Task): Promise<UUID> {\n return this.withRetry(async () => {\n return this.withDatabase(async () => {\n const now = new Date();\n const metadata = task.metadata || {};\n\n const values = {\n id: task.id as UUID,\n name: task.name,\n description: task.description,\n roomId: task.roomId,\n worldId: task.worldId,\n tags: task.tags,\n metadata: metadata,\n createdAt: now,\n updatedAt: now,\n agentId: this.agentId,\n };\n const result = await this.db\n .insert(taskTable)\n .values(values)\n .returning({ id: taskTable.id });\n\n return result[0].id;\n });\n });\n }\n\n /**\n * Asynchronously retrieves tasks based on specified parameters.\n * @param params Object containing optional roomId and tags to filter tasks\n * @returns Promise resolving to an array of Task objects\n */\n async getTasks(params: { roomId?: UUID; tags?: string[] }): Promise<Task[]> {\n return this.withRetry(async () => {\n return this.withDatabase(async () => {\n let query = this.db.select().from(taskTable).where(eq(taskTable.agentId, this.agentId));\n\n // Apply filters if provided\n if (params.roomId) {\n query = query.where(eq(taskTable.roomId, params.roomId));\n }\n\n if (params.tags && params.tags.length > 0) {\n // Filter by tags - find tasks that have ALL of the specified tags\n // Using @> operator which checks if left array contains all elements from right array\n const tagParams = params.tags.map((tag) => `'${tag.replace(/'/g, \"''\")}'`).join(', ');\n query = query.where(sql`${taskTable.tags} @> ARRAY[${sql.raw(tagParams)}]::text[]`);\n }\n\n const result = await query;\n\n return result.map((row) => ({\n id: row.id,\n name: row.name,\n description: row.description,\n roomId: row.roomId,\n worldId: row.worldId,\n tags: row.tags,\n metadata: row.metadata,\n }));\n });\n });\n }\n\n /**\n * Asynchronously retrieves a specific task by its name.\n * @param name The name of the task to retrieve\n * @returns Promise resolving to the Task object if found, null otherwise\n */\n async getTasksByName(name: string): Promise<Task[]> {\n return this.withRetry(async () => {\n return this.withDatabase(async () => {\n const result = await this.db\n .select()\n .from(taskTable)\n .where(and(eq(taskTable.name, name), eq(taskTable.agentId, this.agentId)));\n\n return result.map((row) => ({\n id: row.id,\n name: row.name,\n description: row.description,\n roomId: row.roomId,\n worldId: row.worldId,\n tags: row.tags || [],\n metadata: row.metadata || {},\n }));\n });\n });\n }\n\n /**\n * Asynchronously retrieves a specific task by its ID.\n * @param id The UUID of the task to retrieve\n * @returns Promise resolving to the Task object if found, null otherwise\n */\n async getTask(id: UUID): Promise<Task | null> {\n return this.withRetry(async () => {\n return this.withDatabase(async () => {\n const result = await this.db\n .select()\n .from(taskTable)\n .where(and(eq(taskTable.id, id), eq(taskTable.agentId, this.agentId)))\n .limit(1);\n\n if (result.length === 0) {\n return null;\n }\n\n const row = result[0];\n return {\n id: row.id,\n name: row.name,\n description: row.description,\n roomId: row.roomId,\n worldId: row.worldId,\n tags: row.tags || [],\n metadata: row.metadata || {},\n };\n });\n });\n }\n\n /**\n * Asynchronously updates an existing task in the database.\n * @param id The UUID of the task to update\n * @param task Partial Task object containing the fields to update\n * @returns Promise resolving when the update is complete\n */\n async updateTask(id: UUID, task: Partial<Task>): Promise<void> {\n await this.withRetry(async () => {\n await this.withDatabase(async () => {\n const updateValues: Partial<Task> = {};\n\n // Add fields to update if they exist in the partial task object\n if (task.name !== undefined) updateValues.name = task.name;\n if (task.description !== undefined) updateValues.description = task.description;\n if (task.roomId !== undefined) updateValues.roomId = task.roomId;\n if (task.worldId !== undefined) updateValues.worldId = task.worldId;\n if (task.tags !== undefined) updateValues.tags = task.tags;\n\n task.updatedAt = Date.now();\n\n // Handle metadata updates\n if (task.metadata) {\n // Get current task to merge metadata\n const currentTask = await this.getTask(id);\n if (currentTask) {\n const currentMetadata = currentTask.metadata || {};\n const newMetadata = {\n ...currentMetadata,\n ...task.metadata,\n };\n updateValues.metadata = newMetadata;\n } else {\n updateValues.metadata = {\n ...task.metadata,\n };\n }\n }\n\n await this.db\n .update(taskTable)\n .set(updateValues)\n .where(and(eq(taskTable.id, id), eq(taskTable.agentId, this.agentId)));\n });\n });\n }\n\n /**\n * Asynchronously deletes a task from the database.\n * @param id The UUID of the task to delete\n * @returns Promise resolving when the deletion is complete\n */\n async deleteTask(id: UUID): Promise<void> {\n await this.withRetry(async () => {\n await this.withDatabase(async () => {\n await this.db\n .delete(taskTable)\n .where(and(eq(taskTable.id, id), eq(taskTable.agentId, this.agentId)));\n });\n });\n }\n\n /**\n * Asynchronously retrieves group chat memories from all rooms under a given server.\n * It fetches all room IDs associated with the `serverId`, then retrieves memories\n * from those rooms in descending order (latest to oldest), with an optional count limit.\n *\n * @param {Object} params - Parameters for fetching memories.\n * @param {UUID} params.serverId - The server ID to fetch memories for.\n * @param {number} [params.count] - The maximum number of memories to retrieve.\n * @returns {Promise<Memory[]>} - A promise that resolves to an array of memory objects.\n */\n async getMemoriesByServerId(params: { serverId: UUID; count?: number }): Promise<Memory[]> {\n return this.withDatabase(async () => {\n // Step 1: Fetch all room IDs associated with the given serverId\n const roomIdsResult = await this.db\n .select({ roomId: roomTable.id })\n .from(roomTable)\n .where(eq(roomTable.serverId, params.serverId));\n\n if (roomIdsResult.length === 0) return [];\n\n const roomIds = roomIdsResult.map((row) => row.roomId);\n\n // Step 2: Fetch all memories for these rooms, ordered from latest to oldest\n const query = this.db\n .select({\n memory: memoryTable,\n embedding: embeddingTable[this.embeddingDimension],\n })\n .from(memoryTable)\n .leftJoin(embeddingTable, eq(embeddingTable.memoryId, memoryTable.id))\n .where(inArray(memoryTable.roomId, roomIds))\n .orderBy(desc(memoryTable.createdAt));\n\n // Step 3: Apply the count limit if provided\n const rows = params.count ? await query.limit(params.count) : await query;\n\n return rows.map((row) => ({\n id: row.memory.id as UUID,\n type: row.memory.type,\n createdAt: row.memory.createdAt,\n content:\n typeof row.memory.content === 'string'\n ? JSON.parse(row.memory.content)\n : row.memory.content,\n entityId: row.memory.entityId as UUID,\n agentId: row.memory.agentId as UUID,\n roomId: row.memory.roomId as UUID,\n unique: row.memory.unique,\n embedding: row.embedding ?? undefined,\n }));\n });\n }\n\n /**\n * Asynchronously deletes all rooms associated with a specific serverId.\n * @param {UUID} serverId - The server ID to delete rooms for.\n * @returns {Promise<void>} A Promise that resolves when the rooms are deleted.\n */\n async deleteRoomsByServerId(serverId: UUID): Promise<void> {\n return this.withDatabase(async () => {\n await this.db.transaction(async (tx) => {\n const roomIdsResult = await tx\n .select({ roomId: roomTable.id })\n .from(roomTable)\n .where(eq(roomTable.serverId, serverId));\n\n if (roomIdsResult.length === 0) return;\n\n const roomIds = roomIdsResult.map((row) => row.roomId);\n\n await tx\n .delete(embeddingTable)\n .where(\n inArray(\n embeddingTable.memoryId,\n tx\n .select({ id: memoryTable.id })\n .from(memoryTable)\n .where(inArray(memoryTable.roomId, roomIds))\n )\n );\n await tx.delete(memoryTable).where(inArray(memoryTable.roomId, roomIds));\n\n await tx.delete(participantTable).where(inArray(participantTable.roomId, roomIds));\n\n await tx.delete(logTable).where(inArray(logTable.roomId, roomIds));\n\n await tx.delete(roomTable).where(inArray(roomTable.id, roomIds));\n });\n\n logger.debug('Rooms and related logs deleted successfully for server:', {\n serverId,\n });\n });\n }\n}\n","import { sql } from 'drizzle-orm';\nimport { check, foreignKey, index, pgTable, uuid, vector } from 'drizzle-orm/pg-core';\nimport { memoryTable } from './memory';\nimport { numberTimestamp } from './types';\n\nexport const VECTOR_DIMS = {\n SMALL: 384,\n MEDIUM: 512,\n LARGE: 768,\n XL: 1024,\n XXL: 1536,\n XXXL: 3072,\n} as const;\n\nexport const DIMENSION_MAP = {\n [VECTOR_DIMS.SMALL]: 'dim384',\n [VECTOR_DIMS.MEDIUM]: 'dim512',\n [VECTOR_DIMS.LARGE]: 'dim768',\n [VECTOR_DIMS.XL]: 'dim1024',\n [VECTOR_DIMS.XXL]: 'dim1536',\n [VECTOR_DIMS.XXXL]: 'dim3072',\n} as const;\n\n/**\n * Definition of the embeddings table in the database.\n * Contains columns for ID, Memory ID, Creation Timestamp, and multiple vector dimensions.\n */\nexport const embeddingTable = pgTable(\n 'embeddings',\n {\n id: uuid('id').primaryKey().defaultRandom().notNull(),\n memoryId: uuid('memory_id').references(() => memoryTable.id),\n createdAt: numberTimestamp('created_at')\n .default(sql`now()`)\n .notNull(),\n dim384: vector('dim_384', { dimensions: VECTOR_DIMS.SMALL }),\n dim512: vector('dim_512', { dimensions: VECTOR_DIMS.MEDIUM }),\n dim768: vector('dim_768', { dimensions: VECTOR_DIMS.LARGE }),\n dim1024: vector('dim_1024', { dimensions: VECTOR_DIMS.XL }),\n dim1536: vector('dim_1536', { dimensions: VECTOR_DIMS.XXL }),\n dim3072: vector('dim_3072', { dimensions: VECTOR_DIMS.XXXL }),\n },\n (table) => [\n check('embedding_source_check', sql`\"memory_id\" IS NOT NULL`),\n index('idx_embedding_memory').on(table.memoryId),\n foreignKey({\n name: 'fk_embedding_memory',\n columns: [table.memoryId],\n foreignColumns: [memoryTable.id],\n }).onDelete('cascade'),\n ]\n);\n\n/**\n * Defines the possible values for the Embedding Dimension Column.\n * It can be \"dim384\", \"dim512\", \"dim768\", \"dim1024\", \"dim1536\", or \"dim3072\".\n */\nexport type EmbeddingDimensionColumn =\n | 'dim384'\n | 'dim512'\n | 'dim768'\n | 'dim1024'\n | 'dim1536'\n | 'dim3072';\n\n/**\n * Retrieve the type of a specific column in the EmbeddingTable based on the EmbeddingDimensionColumn key.\n */\nexport type EmbeddingTableColumn = (typeof embeddingTable._.columns)[EmbeddingDimensionColumn];\n","import { relations, sql } from 'drizzle-orm';\nimport {\n boolean,\n check,\n foreignKey,\n index,\n jsonb,\n pgTable,\n text,\n unique,\n uuid,\n vector,\n} from 'drizzle-orm/pg-core';\nimport { agentTable } from './agent';\nimport { embeddingTable } from './embedding';\nimport { entityTable } from './entity';\nimport { roomTable } from './room';\nimport { numberTimestamp } from './types';\n\n/**\n * Definition of the memory table in the database.\n *\n * @param {string} tableName - The name of the table.\n * @param {object} columns - An object containing the column definitions.\n * @param {function} indexes - A function that defines the indexes for the table.\n * @returns {object} - The memory table object.\n */\nexport const memoryTable = pgTable(\n 'memories',\n {\n id: uuid('id').primaryKey().notNull(),\n type: text('type').notNull(),\n createdAt: numberTimestamp('createdAt')\n .default(sql`now()`)\n .notNull(),\n content: jsonb('content').notNull(),\n entityId: uuid('entityId').references(() => entityTable.id, {\n onDelete: 'cascade',\n }),\n agentId: uuid('agentId').references(() => agentTable.id, {\n onDelete: 'cascade',\n }),\n roomId: uuid('roomId').references(() => roomTable.id, {\n onDelete: 'cascade',\n }),\n unique: boolean('unique').default(true).notNull(),\n metadata: jsonb('metadata').default({}).notNull(),\n },\n (table) => [\n index('idx_memories_type_room').on(table.type, table.roomId),\n foreignKey({\n name: 'fk_room',\n columns: [table.roomId],\n foreignColumns: [roomTable.id],\n }).onDelete('cascade'),\n foreignKey({\n name: 'fk_user',\n columns: [table.entityId],\n foreignColumns: [entityTable.id],\n }).onDelete('cascade'),\n foreignKey({\n name: 'fk_agent',\n columns: [table.agentId],\n foreignColumns: [entityTable.id],\n }).onDelete('cascade'),\n index('idx_memories_metadata_type').on(sql`((metadata->>'type'))`),\n index('idx_memories_document_id').on(sql`((metadata->>'documentId'))`),\n index('idx_fragments_order').on(\n sql`((metadata->>'documentId'))`,\n sql`((metadata->>'position'))`\n ),\n check(\n 'fragment_metadata_check',\n sql`\n CASE \n WHEN metadata->>'type' = 'fragment' THEN\n metadata ? 'documentId' AND \n metadata ? 'position'\n ELSE true\n END\n `\n ),\n check(\n 'document_metadata_check',\n sql`\n CASE \n WHEN metadata->>'type' = 'document' THEN\n metadata ? 'timestamp'\n ELSE true\n END\n `\n ),\n ]\n);\n\nexport const memoryRelations = relations(memoryTable, ({ one }) => ({\n embedding: one(embeddingTable),\n}));\n","import type { MessageExample } from '@elizaos/core';\nimport { sql } from 'drizzle-orm';\nimport { boolean, jsonb, pgTable, text, unique, uuid } from 'drizzle-orm/pg-core';\nimport { numberTimestamp } from './types';\n\n/**\n * Represents a table for storing agent data.\n *\n * @type {Table}\n */\nexport const agentTable = pgTable(\n 'agents',\n {\n id: uuid('id').primaryKey().defaultRandom(),\n enabled: boolean('enabled').default(true).notNull(),\n createdAt: numberTimestamp('createdAt')\n .default(sql`now()`)\n .notNull(),\n\n updatedAt: numberTimestamp('updatedAt')\n .default(sql`now()`)\n .notNull(),\n\n // Character\n name: text('name'),\n username: text('username'),\n system: text('system'),\n bio: jsonb('bio').$type<string | string[]>().notNull(),\n messageExamples: jsonb('message_examples')\n .$type<MessageExample[][]>()\n .default(sql`'[]'::jsonb`),\n postExamples: jsonb('post_examples')\n .$type<string[]>()\n .default(sql`'[]'::jsonb`),\n topics: jsonb('topics')\n .$type<string[]>()\n .default(sql`'[]'::jsonb`),\n adjectives: jsonb('adjectives')\n .$type<string[]>()\n .default(sql`'[]'::jsonb`),\n knowledge: jsonb('knowledge')\n .$type<(string | { path: string; shared?: boolean })[]>()\n .default(sql`'[]'::jsonb`),\n plugins: jsonb('plugins')\n .$type<string[]>()\n .default(sql`'[]'::jsonb`),\n settings: jsonb('settings')\n .$type<{\n secrets?: { [key: string]: string | boolean | number };\n [key: string]: unknown;\n }>()\n .default(sql`'{}'::jsonb`),\n style: jsonb('style')\n .$type<{\n all?: string[];\n chat?: string[];\n post?: string[];\n }>()\n .default(sql`'{}'::jsonb`),\n },\n (table) => {\n return {\n nameUnique: unique('name_unique').on(table.name),\n };\n }\n);\n","import { customType } from 'drizzle-orm/pg-core';\n\n/**\n * Represents a custom type for converting a string to a JSONB format and vice versa.\n * @param {Object} options - The options for the custom type.\n * @param {Function} options.dataType - A function that returns the data type as \"jsonb\".\n * @param {Function} options.toDriver - A function that converts a string to a JSON string.\n * @param {Function} options.fromDriver - A function that converts a JSON string back to a string.\n * @returns {Object} - The custom type for string to JSONB conversion.\n */\n\nexport const stringJsonb = customType<{ data: string; driverData: string }>({\n dataType() {\n return 'jsonb';\n },\n toDriver(value: string): string {\n return JSON.stringify(value);\n },\n fromDriver(value: string): string {\n return JSON.stringify(value);\n },\n});\n\n/**\n * Represents a custom type for converting a number to a timestamp string and vice versa.\n * @param {Object} options - The options for the custom type.\n * @param {Function} options.dataType - A function that returns the data type as \"timestamptz\".\n * @param {Function} options.toDriver - A function that converts a number to a timestamp string using the Date object's toISOString method.\n * @param {Function} options.fromDriver - A function that converts a timestamp string to a number using the Date object's getTime method.\n * @returns {Object} - The custom type for number to timestamp conversion.\n */\nexport const numberTimestamp = customType<{ data: number; driverData: string }>({\n dataType() {\n return 'timestamptz';\n },\n toDriver(value: number): string {\n return new Date(value).toISOString();\n },\n fromDriver(value: string): number {\n return new Date(value).getTime();\n },\n});\n","import { sql } from 'drizzle-orm';\nimport { jsonb, pgTable, text, unique, uuid } from 'drizzle-orm/pg-core';\nimport { agentTable } from './agent';\nimport { numberTimestamp } from './types';\n\n/**\n * Represents an entity table in the database.\n * Includes columns for id, agentId, createdAt, names, and metadata.\n */\nexport const entityTable = pgTable(\n 'entities',\n {\n id: uuid('id').notNull().primaryKey(),\n agentId: uuid('agentId')\n .notNull()\n .references(() => agentTable.id, {\n onDelete: 'cascade',\n }),\n createdAt: numberTimestamp('createdAt')\n .default(sql`now()`)\n .notNull(),\n names: text('names')\n .array()\n .default(sql`'{}'::text[]`),\n metadata: jsonb('metadata').default(sql`'{}'::jsonb`),\n },\n (table) => {\n return {\n idAgentIdUnique: unique('id_agent_id_unique').on(table.id, table.agentId),\n };\n }\n);\n","import { sql } from 'drizzle-orm';\nimport { jsonb, pgTable, text, uuid } from 'drizzle-orm/pg-core';\nimport { agentTable } from './agent';\nimport { numberTimestamp } from './types';\nimport { worldTable } from './worldTable';\n\n/**\n * Defines a table schema for 'rooms' in the database.\n *\n * @typedef {object} RoomTable\n * @property {string} id - The unique identifier for the room.\n * @property {string} agentId - The UUID of the agent associated with the room.\n * @property {string} source - The source of the room.\n * @property {string} type - The type of the room.\n * @property {string} serverId - The server ID of the room.\n * @property {string} worldId - The UUID of the world associated with the room.\n * @property {string} name - The name of the room.\n * @property {object} metadata - Additional metadata for the room in JSON format.\n * @property {string} channelId - The channel ID of the room.\n * @property {number} createdAt - The timestamp of when the room was created.\n */\nexport const roomTable = pgTable('rooms', {\n id: uuid('id')\n .notNull()\n .primaryKey()\n .default(sql`gen_random_uuid()`),\n agentId: uuid('agentId').references(() => agentTable.id, {\n onDelete: 'cascade',\n }),\n source: text('source').notNull(),\n type: text('type').notNull(),\n serverId: text('serverId'),\n worldId: uuid('worldId').references(() => worldTable.id, {\n onDelete: 'cascade',\n }),\n name: text('name'),\n metadata: jsonb('metadata'),\n channelId: text('channelId'),\n createdAt: numberTimestamp('createdAt')\n .default(sql`now()`)\n .notNull(),\n});\n","import { sql } from 'drizzle-orm';\nimport { jsonb, pgTable, text, uuid } from 'drizzle-orm/pg-core';\nimport { agentTable } from './agent';\nimport { numberTimestamp } from './types';\n\n/**\n * Represents a table schema for worlds in the database.\n *\n * @type {PgTable}\n */\n\nexport const worldTable = pgTable('worlds', {\n id: uuid('id')\n .notNull()\n .primaryKey()\n .default(sql`gen_random_uuid()`),\n agentId: uuid('agentId')\n .notNull()\n .references(() => agentTable.id, { onDelete: 'cascade' }),\n name: text('name').notNull(),\n metadata: jsonb('metadata'),\n serverId: text('serverId').notNull(),\n createdAt: numberTimestamp('createdAt')\n .default(sql`now()`)\n .notNull(),\n});\n","import { sql } from 'drizzle-orm';\nimport { jsonb, pgTable, text, unique, uuid } from 'drizzle-orm/pg-core';\nimport { agentTable } from './agent';\nimport { numberTimestamp } from './types';\n\n/**\n * Represents a PostgreSQL table for caching data.\n *\n * @type {pgTable}\n */\nexport const cacheTable = pgTable(\n 'cache',\n {\n id: uuid('id')\n .notNull()\n .primaryKey()\n .default(sql`gen_random_uuid()`),\n key: text('key').notNull(),\n agentId: uuid('agentId')\n .notNull()\n .references(() => agentTable.id, { onDelete: 'cascade' }),\n value: jsonb('value').notNull(),\n createdAt: numberTimestamp('createdAt')\n .default(sql`now()`)\n .notNull(),\n expiresAt: numberTimestamp('expiresAt'),\n },\n (table) => [unique('cache_key_agent_unique').on(table.key, table.agentId)]\n);\n","import { sql } from 'drizzle-orm';\nimport { jsonb, pgTable, text, uuid } from 'drizzle-orm/pg-core';\nimport { agentTable } from './agent';\nimport { entityTable } from './entity';\nimport { roomTable } from './room';\nimport { numberTimestamp } from './types';\nimport { worldTable } from './worldTable';\n\n/**\n * Definition of a table representing components in the database.\n *\n * @type {Table}\n */\nexport const componentTable = pgTable('components', {\n id: uuid('id').primaryKey().defaultRandom(),\n entityId: uuid('entityId')\n .notNull()\n .references(() => entityTable.id, { onDelete: 'cascade' }),\n agentId: uuid('agentId')\n .notNull()\n .references(() => agentTable.id, { onDelete: 'cascade' }),\n roomId: uuid('roomId')\n .notNull()\n .references(() => roomTable.id, { onDelete: 'cascade' }),\n worldId: uuid('worldId').references(() => worldTable.id, {\n onDelete: 'cascade',\n }),\n sourceEntityId: uuid('sourceEntityId').references(() => entityTable.id, {\n onDelete: 'cascade',\n }),\n type: text('type').notNull(),\n data: jsonb('data').default(sql`'{}'::jsonb`),\n createdAt: numberTimestamp('createdAt')\n .default(sql`now()`)\n .notNull(),\n});\n","import { sql } from 'drizzle-orm';\nimport { foreignKey, jsonb, pgTable, text, uuid } from 'drizzle-orm/pg-core';\nimport { entityTable } from './entity';\nimport { roomTable } from './room';\nimport { numberTimestamp } from './types';\n\n/**\n * Represents a PostgreSQL table for storing logs.\n *\n * @type {Table}\n */\n\nexport const logTable = pgTable(\n 'logs',\n {\n id: uuid('id').defaultRandom().notNull(),\n createdAt: numberTimestamp('createdAt')\n .default(sql`now()`)\n .notNull(),\n entityId: uuid('entityId')\n .notNull()\n .references(() => entityTable.id),\n body: jsonb('body').notNull(),\n type: text('type').notNull(),\n roomId: uuid('roomId')\n .notNull()\n .references(() => roomTable.id),\n },\n (table) => [\n foreignKey({\n name: 'fk_room',\n columns: [table.roomId],\n foreignColumns: [roomTable.id],\n }).onDelete('cascade'),\n foreignKey({\n name: 'fk_user',\n columns: [table.entityId],\n foreignColumns: [entityTable.id],\n }).onDelete('cascade'),\n ]\n);\n","import { sql } from 'drizzle-orm';\nimport { foreignKey, index, pgTable, text, unique, uuid } from 'drizzle-orm/pg-core';\nimport { agentTable } from './agent';\nimport { entityTable } from './entity';\nimport { roomTable } from './room';\nimport { numberTimestamp } from './types';\n\n/**\n * Defines the schema for the \"participants\" table in the database.\n *\n * @type {import('knex').TableBuilder}\n */\nexport const participantTable = pgTable(\n 'participants',\n {\n id: uuid('id')\n .notNull()\n .primaryKey()\n .default(sql`gen_random_uuid()`),\n createdAt: numberTimestamp('createdAt')\n .default(sql`now()`)\n .notNull(),\n entityId: uuid('entityId').references(() => entityTable.id, {\n onDelete: 'cascade',\n }),\n roomId: uuid('roomId').references(() => roomTable.id, {\n onDelete: 'cascade',\n }),\n agentId: uuid('agentId').references(() => agentTable.id, {\n onDelete: 'cascade',\n }),\n roomState: text('roomState'),\n },\n (table) => [\n // unique(\"participants_user_room_agent_unique\").on(table.entityId, table.roomId, table.agentId),\n index('idx_participants_user').on(table.entityId),\n index('idx_participants_room').on(table.roomId),\n foreignKey({\n name: 'fk_room',\n columns: [table.roomId],\n foreignColumns: [roomTable.id],\n }).onDelete('cascade'),\n foreignKey({\n name: 'fk_user',\n columns: [table.entityId],\n foreignColumns: [entityTable.id],\n }).onDelete('cascade'),\n ]\n);\n","import { sql } from 'drizzle-orm';\nimport { foreignKey, index, jsonb, pgTable, text, unique, uuid } from 'drizzle-orm/pg-core';\nimport { agentTable } from './agent';\nimport { entityTable } from './entity';\nimport { numberTimestamp } from './types';\n\n/**\n * Defines the relationshipTable containing information about relationships between entities and agents.\n * @type {import('knex').TableBuilder}\n */\nexport const relationshipTable = pgTable(\n 'relationships',\n {\n id: uuid('id')\n .notNull()\n .primaryKey()\n .default(sql`gen_random_uuid()`),\n createdAt: numberTimestamp('createdAt')\n .default(sql`now()`)\n .notNull(),\n sourceEntityId: uuid('sourceEntityId')\n .notNull()\n .references(() => entityTable.id, { onDelete: 'cascade' }),\n targetEntityId: uuid('targetEntityId')\n .notNull()\n .references(() => entityTable.id, { onDelete: 'cascade' }),\n agentId: uuid('agentId')\n .notNull()\n .references(() => agentTable.id, { onDelete: 'cascade' }),\n tags: text('tags').array(),\n metadata: jsonb('metadata'),\n },\n (table) => [\n index('idx_relationships_users').on(table.sourceEntityId, table.targetEntityId),\n unique('unique_relationship').on(table.sourceEntityId, table.targetEntityId, table.agentId),\n foreignKey({\n name: 'fk_user_a',\n columns: [table.sourceEntityId],\n foreignColumns: [entityTable.id],\n }).onDelete('cascade'),\n foreignKey({\n name: 'fk_user_b',\n columns: [table.targetEntityId],\n foreignColumns: [entityTable.id],\n }).onDelete('cascade'),\n ]\n);\n","import { jsonb, pgTable, text, timestamp, uuid } from 'drizzle-orm/pg-core';\n\n/**\n * Represents a table schema for tasks in the database.\n *\n * @type {PgTable}\n */\nexport const taskTable = pgTable('tasks', {\n id: uuid('id').primaryKey().defaultRandom(),\n name: text('name').notNull(),\n description: text('description').notNull(),\n roomId: uuid('room_id'),\n worldId: uuid('world_id'),\n agentId: uuid('agent_id').notNull(),\n tags: text('tags').array(),\n metadata: jsonb('metadata'),\n createdAt: timestamp('created_at').defaultNow(),\n updatedAt: timestamp('updated_at').defaultNow(),\n});\n","import { type UUID, logger } from '@elizaos/core';\nimport { type NodePgDatabase, drizzle } from 'drizzle-orm/node-postgres';\nimport { BaseDrizzleAdapter } from '../base';\nimport { DIMENSION_MAP, type EmbeddingDimensionColumn } from '../schema/embedding';\nimport type { PostgresConnectionManager } from './manager';\n\n/**\n * Adapter class for interacting with a PostgreSQL database.\n * Extends BaseDrizzleAdapter<NodePgDatabase>.\n */\nexport class PgDatabaseAdapter extends BaseDrizzleAdapter<NodePgDatabase> {\n protected embeddingDimension: EmbeddingDimensionColumn = DIMENSION_MAP[384];\n\n /**\n * Constructor for creating a new instance of a class.\n * @param {UUID} agentId - The unique identifier for the agent.\n * @param {PostgresConnectionManager} manager - The Postgres connection manager for the instance.\n */\n constructor(\n agentId: UUID,\n private manager: PostgresConnectionManager\n ) {\n super(agentId);\n this.manager = manager;\n }\n\n /**\n * Executes the provided operation with a database connection.\n *\n * @template T\n * @param {() => Promise<T>} operation - The operation to be executed with the database connection.\n * @returns {Promise<T>} A promise that resolves with the result of the operation.\n */\n protected async withDatabase<T>(operation: () => Promise<T>): Promise<T> {\n return await this.withRetry(async () => {\n const client = await this.manager.getClient();\n try {\n const db = drizzle(client);\n this.db = db;\n\n return await operation();\n } finally {\n client.release();\n }\n });\n }\n\n /**\n * Asynchronously initializes the PgDatabaseAdapter by running migrations using the manager.\n * Logs a success message if initialization is successful, otherwise logs an error message.\n *\n * @returns {Promise<void>} A promise that resolves when initialization is complete.\n */\n async init(): Promise<void> {\n try {\n await this.manager.runMigrations();\n logger.debug('PgDatabaseAdapter initialized successfully');\n } catch (error) {\n logger.error('Failed to initialize PgDatabaseAdapter:', error);\n throw error;\n }\n }\n\n /**\n * Asynchronously closes the manager associated with this instance.\n *\n * @returns A Promise that resolves once the manager is closed.\n */\n async close(): Promise<void> {\n await this.manager.close();\n }\n}\n"],"mappings":";;;;;;;AAAA,YAAY,QAAQ;AAEpB,SAA0C,UAAAA,eAAc;;;ACFxD,SAAoB,UAAAC,eAAc;AAClC,SAA8B,eAAe;;;ACD7C;AAAA,EAGE;AAAA,EAWA;AAAA,OACK;AACP;AAAA,EAEE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,OAAAC;AAAA,EACA;AAAA,OACK;AACP,SAAS,UAAU;;;AC9BnB,SAAS,OAAAC,YAAW;AACpB,SAAS,SAAAC,QAAO,cAAAC,aAAY,SAAAC,QAAO,WAAAC,UAAS,QAAAC,OAAM,UAAAC,eAAc;;;ACDhE,SAAS,WAAW,OAAAC,YAAW;AAC/B;AAAA,EACE,WAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,SAAAC;AAAA,EACA,WAAAC;AAAA,EACA,QAAAC;AAAA,EAEA,QAAAC;AAAA,OAEK;;;ACXP,SAAS,WAAW;AACpB,SAAS,SAAS,OAAO,SAAS,MAAM,QAAQ,YAAY;;;ACF5D,SAAS,kBAAkB;AAWpB,IAAM,cAAc,WAAiD;AAAA,EAC1E,WAAW;AACT,WAAO;AAAA,EACT;AAAA,EACA,SAAS,OAAuB;AAC9B,WAAO,KAAK,UAAU,KAAK;AAAA,EAC7B;AAAA,EACA,WAAW,OAAuB;AAChC,WAAO,KAAK,UAAU,KAAK;AAAA,EAC7B;AACF,CA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zC,UAAM,SAAS;AAAA,MACb,SAAS,QAAQ,WAAW,iBAAiB,KAAK;AAAA,MAClD,aAAa,QAAQ,WAAW,cAAc;AAAA,IAChD;AAEA,QAAI;AACF,YAAM,KAAK,sBAAsB,QAAQ,QAAQ,OAAO;AACxD,MAAAC,QAAO,QAAQ,8CAA8C;AAC7D,cAAQ,wBAAwB,EAAE;AAAA,IACpC,SAAS,OAAO;AACd,MAAAA,QAAO,MAAM,kCAAkC,KAAK;AACpD,YAAM;AAAA,IACR;AAAA,EACF,GAdM;AAeR;AAEA,IAAO,gBAAQ;","names":["logger","logger","sql","sql","check","foreignKey","index","pgTable","uuid","vector","sql","boolean","jsonb","pgTable","text","uuid","sql","jsonb","pgTable","text","unique","uuid","pgTable","uuid","sql","text","jsonb","unique","sql","jsonb","pgTable","text","uuid","sql","jsonb","pgTable","text","uuid","pgTable","uuid","sql","text","jsonb","pgTable","uuid","sql","text","jsonb","pgTable","uuid","text","sql","jsonb","boolean","pgTable","uuid","sql","vector","check","index","foreignKey","sql","jsonb","pgTable","text","unique","uuid","pgTable","uuid","sql","text","jsonb","unique","sql","jsonb","pgTable","text","uuid","pgTable","uuid","text","jsonb","sql","sql","foreignKey","jsonb","pgTable","text","uuid","pgTable","uuid","sql","jsonb","text","foreignKey","sql","foreignKey","index","pgTable","text","uuid","pgTable","uuid","sql","text","index","foreignKey","sql","foreignKey","index","jsonb","pgTable","text","unique","uuid","pgTable","uuid","sql","text","jsonb","index","unique","foreignKey","jsonb","pgTable","text","uuid","count","unique","sql","logger","logger","drizzle","drizzle","logger","logger"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@elizaos/plugin-sql",
|
|
3
|
-
"version": "1.0.0-beta.
|
|
3
|
+
"version": "1.0.0-beta.8",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"module": "dist/index.js",
|
|
@@ -27,7 +27,7 @@
|
|
|
27
27
|
],
|
|
28
28
|
"dependencies": {
|
|
29
29
|
"@electric-sql/pglite": "^0.2.17",
|
|
30
|
-
"@elizaos/core": "^1.0.0-beta.
|
|
30
|
+
"@elizaos/core": "^1.0.0-beta.8",
|
|
31
31
|
"@types/pg": "8.11.10",
|
|
32
32
|
"drizzle-kit": "^0.30.4",
|
|
33
33
|
"drizzle-orm": "^0.39.1",
|
|
@@ -51,5 +51,5 @@
|
|
|
51
51
|
"peerDependencies": {
|
|
52
52
|
"typescript": "5.8.2"
|
|
53
53
|
},
|
|
54
|
-
"gitHead": "
|
|
54
|
+
"gitHead": "a84e25ee21e33387a1303e62a2f95dc670ffddd4"
|
|
55
55
|
}
|