@elizaos/plugin-sql 1.0.0-beta.8 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,11 +1,11 @@
1
1
  import {
2
2
  PGliteClientManager,
3
3
  PostgresConnectionManager,
4
- __name
5
- } from "./chunk-ROCRMD5N.js";
4
+ __name,
5
+ resolvePgliteDir
6
+ } from "./chunk-QOV7MUNF.js";
6
7
 
7
8
  // src/index.ts
8
- import * as os from "node:os";
9
9
  import { logger as logger4 } from "@elizaos/core";
10
10
 
11
11
  // src/pglite/adapter.ts
@@ -17,36 +17,25 @@ import {
17
17
  DatabaseAdapter,
18
18
  logger
19
19
  } from "@elizaos/core";
20
- import {
21
- and,
22
- cosineDistance,
23
- count,
24
- desc,
25
- eq,
26
- gte,
27
- inArray,
28
- lte,
29
- or,
30
- sql as sql12,
31
- not
32
- } from "drizzle-orm";
20
+ import { and, cosineDistance, count, desc, eq, gte, inArray, lte, or, sql as sql13 } from "drizzle-orm";
33
21
  import { v4 } from "uuid";
34
22
 
35
23
  // src/schema/embedding.ts
36
- import { sql as sql6 } from "drizzle-orm";
37
- import { check as check2, foreignKey as foreignKey2, index as index2, pgTable as pgTable6, uuid as uuid6, vector as vector2 } from "drizzle-orm/pg-core";
24
+ import { sql as sql5 } from "drizzle-orm";
25
+ import { check as check2, foreignKey as foreignKey2, index as index2, pgTable as pgTable5, uuid as uuid5, vector as vector2 } from "drizzle-orm/pg-core";
26
+ import { VECTOR_DIMS } from "@elizaos/core";
38
27
 
39
28
  // src/schema/memory.ts
40
- import { relations, sql as sql5 } from "drizzle-orm";
29
+ import { relations, sql as sql4 } from "drizzle-orm";
41
30
  import {
42
31
  boolean as boolean2,
43
32
  check,
44
33
  foreignKey,
45
34
  index,
46
- jsonb as jsonb5,
47
- pgTable as pgTable5,
48
- text as text5,
49
- uuid as uuid5
35
+ jsonb as jsonb4,
36
+ pgTable as pgTable4,
37
+ text as text4,
38
+ uuid as uuid4
50
39
  } from "drizzle-orm/pg-core";
51
40
 
52
41
  // src/schema/agent.ts
@@ -87,18 +76,18 @@ var agentTable = pgTable(
87
76
  createdAt: numberTimestamp("createdAt").default(sql`now()`).notNull(),
88
77
  updatedAt: numberTimestamp("updatedAt").default(sql`now()`).notNull(),
89
78
  // Character
90
- name: text("name"),
79
+ name: text("name").notNull(),
91
80
  username: text("username"),
92
- system: text("system"),
93
- bio: jsonb("bio").$type().notNull(),
94
- messageExamples: jsonb("message_examples").$type().default(sql`'[]'::jsonb`),
95
- postExamples: jsonb("post_examples").$type().default(sql`'[]'::jsonb`),
96
- topics: jsonb("topics").$type().default(sql`'[]'::jsonb`),
97
- adjectives: jsonb("adjectives").$type().default(sql`'[]'::jsonb`),
98
- knowledge: jsonb("knowledge").$type().default(sql`'[]'::jsonb`),
99
- plugins: jsonb("plugins").$type().default(sql`'[]'::jsonb`),
100
- settings: jsonb("settings").$type().default(sql`'{}'::jsonb`),
101
- style: jsonb("style").$type().default(sql`'{}'::jsonb`)
81
+ system: text("system").default(""),
82
+ bio: jsonb("bio").$type().default(sql`'[]'::jsonb`),
83
+ messageExamples: jsonb("message_examples").$type().default(sql`'[]'::jsonb`).notNull(),
84
+ postExamples: jsonb("post_examples").$type().default(sql`'[]'::jsonb`).notNull(),
85
+ topics: jsonb("topics").$type().default(sql`'[]'::jsonb`).notNull(),
86
+ adjectives: jsonb("adjectives").$type().default(sql`'[]'::jsonb`).notNull(),
87
+ knowledge: jsonb("knowledge").$type().default(sql`'[]'::jsonb`).notNull(),
88
+ plugins: jsonb("plugins").$type().default(sql`'[]'::jsonb`).notNull(),
89
+ settings: jsonb("settings").$type().default(sql`'{}'::jsonb`).notNull(),
90
+ style: jsonb("style").$type().default(sql`'{}'::jsonb`).notNull()
102
91
  },
103
92
  (table) => {
104
93
  return {
@@ -118,8 +107,8 @@ var entityTable = pgTable2(
118
107
  onDelete: "cascade"
119
108
  }),
120
109
  createdAt: numberTimestamp("createdAt").default(sql2`now()`).notNull(),
121
- names: text2("names").array().default(sql2`'{}'::text[]`),
122
- metadata: jsonb2("metadata").default(sql2`'{}'::jsonb`)
110
+ names: text2("names").array().default(sql2`'{}'::text[]`).notNull(),
111
+ metadata: jsonb2("metadata").default(sql2`'{}'::jsonb`).notNull()
123
112
  },
124
113
  (table) => {
125
114
  return {
@@ -129,61 +118,54 @@ var entityTable = pgTable2(
129
118
  );
130
119
 
131
120
  // src/schema/room.ts
132
- import { sql as sql4 } from "drizzle-orm";
133
- import { jsonb as jsonb4, pgTable as pgTable4, text as text4, uuid as uuid4 } from "drizzle-orm/pg-core";
134
-
135
- // src/schema/worldTable.ts
136
121
  import { sql as sql3 } from "drizzle-orm";
137
122
  import { jsonb as jsonb3, pgTable as pgTable3, text as text3, uuid as uuid3 } from "drizzle-orm/pg-core";
138
- var worldTable = pgTable3("worlds", {
123
+ var roomTable = pgTable3("rooms", {
139
124
  id: uuid3("id").notNull().primaryKey().default(sql3`gen_random_uuid()`),
140
- agentId: uuid3("agentId").notNull().references(() => agentTable.id, { onDelete: "cascade" }),
141
- name: text3("name").notNull(),
142
- metadata: jsonb3("metadata"),
143
- serverId: text3("serverId").notNull(),
144
- createdAt: numberTimestamp("createdAt").default(sql3`now()`).notNull()
145
- });
146
-
147
- // src/schema/room.ts
148
- var roomTable = pgTable4("rooms", {
149
- id: uuid4("id").notNull().primaryKey().default(sql4`gen_random_uuid()`),
150
- agentId: uuid4("agentId").references(() => agentTable.id, {
151
- onDelete: "cascade"
152
- }),
153
- source: text4("source").notNull(),
154
- type: text4("type").notNull(),
155
- serverId: text4("serverId"),
156
- worldId: uuid4("worldId").references(() => worldTable.id, {
125
+ agentId: uuid3("agentId").references(() => agentTable.id, {
157
126
  onDelete: "cascade"
158
127
  }),
159
- name: text4("name"),
160
- metadata: jsonb4("metadata"),
161
- channelId: text4("channelId"),
162
- createdAt: numberTimestamp("createdAt").default(sql4`now()`).notNull()
128
+ source: text3("source").notNull(),
129
+ type: text3("type").notNull(),
130
+ serverId: text3("serverId"),
131
+ worldId: uuid3("worldId"),
132
+ // no guarantee that world exists, it is optional for now
133
+ // .references(() => worldTable.id, {
134
+ // onDelete: 'cascade',
135
+ // }),
136
+ name: text3("name"),
137
+ metadata: jsonb3("metadata"),
138
+ channelId: text3("channelId"),
139
+ createdAt: numberTimestamp("createdAt").default(sql3`now()`).notNull()
163
140
  });
164
141
 
165
142
  // src/schema/memory.ts
166
- var memoryTable = pgTable5(
143
+ var memoryTable = pgTable4(
167
144
  "memories",
168
145
  {
169
- id: uuid5("id").primaryKey().notNull(),
170
- type: text5("type").notNull(),
171
- createdAt: numberTimestamp("createdAt").default(sql5`now()`).notNull(),
172
- content: jsonb5("content").notNull(),
173
- entityId: uuid5("entityId").references(() => entityTable.id, {
146
+ id: uuid4("id").primaryKey().notNull(),
147
+ type: text4("type").notNull(),
148
+ createdAt: numberTimestamp("createdAt").default(sql4`now()`).notNull(),
149
+ content: jsonb4("content").notNull(),
150
+ entityId: uuid4("entityId").references(() => entityTable.id, {
174
151
  onDelete: "cascade"
175
152
  }),
176
- agentId: uuid5("agentId").references(() => agentTable.id, {
153
+ agentId: uuid4("agentId").references(() => agentTable.id, {
177
154
  onDelete: "cascade"
178
- }),
179
- roomId: uuid5("roomId").references(() => roomTable.id, {
155
+ }).notNull(),
156
+ roomId: uuid4("roomId").references(() => roomTable.id, {
180
157
  onDelete: "cascade"
181
158
  }),
159
+ worldId: uuid4("worldId"),
160
+ // .references(() => worldTable.id, {
161
+ // onDelete: 'set null',
162
+ // }),
182
163
  unique: boolean2("unique").default(true).notNull(),
183
- metadata: jsonb5("metadata").default({}).notNull()
164
+ metadata: jsonb4("metadata").default({}).notNull()
184
165
  },
185
166
  (table) => [
186
167
  index("idx_memories_type_room").on(table.type, table.roomId),
168
+ index("idx_memories_world_id").on(table.worldId),
187
169
  foreignKey({
188
170
  name: "fk_room",
189
171
  columns: [table.roomId],
@@ -197,17 +179,22 @@ var memoryTable = pgTable5(
197
179
  foreignKey({
198
180
  name: "fk_agent",
199
181
  columns: [table.agentId],
200
- foreignColumns: [entityTable.id]
182
+ foreignColumns: [agentTable.id]
201
183
  }).onDelete("cascade"),
202
- index("idx_memories_metadata_type").on(sql5`((metadata->>'type'))`),
203
- index("idx_memories_document_id").on(sql5`((metadata->>'documentId'))`),
184
+ // foreignKey({
185
+ // name: 'fk_world',
186
+ // columns: [table.worldId],
187
+ // foreignColumns: [worldTable.id],
188
+ // }).onDelete('set null'),
189
+ index("idx_memories_metadata_type").on(sql4`((metadata->>'type'))`),
190
+ index("idx_memories_document_id").on(sql4`((metadata->>'documentId'))`),
204
191
  index("idx_fragments_order").on(
205
- sql5`((metadata->>'documentId'))`,
206
- sql5`((metadata->>'position'))`
192
+ sql4`((metadata->>'documentId'))`,
193
+ sql4`((metadata->>'position'))`
207
194
  ),
208
195
  check(
209
196
  "fragment_metadata_check",
210
- sql5`
197
+ sql4`
211
198
  CASE
212
199
  WHEN metadata->>'type' = 'fragment' THEN
213
200
  metadata ? 'documentId' AND
@@ -218,7 +205,7 @@ var memoryTable = pgTable5(
218
205
  ),
219
206
  check(
220
207
  "document_metadata_check",
221
- sql5`
208
+ sql4`
222
209
  CASE
223
210
  WHEN metadata->>'type' = 'document' THEN
224
211
  metadata ? 'timestamp'
@@ -233,14 +220,6 @@ var memoryRelations = relations(memoryTable, ({ one }) => ({
233
220
  }));
234
221
 
235
222
  // src/schema/embedding.ts
236
- var VECTOR_DIMS = {
237
- SMALL: 384,
238
- MEDIUM: 512,
239
- LARGE: 768,
240
- XL: 1024,
241
- XXL: 1536,
242
- XXXL: 3072
243
- };
244
223
  var DIMENSION_MAP = {
245
224
  [VECTOR_DIMS.SMALL]: "dim384",
246
225
  [VECTOR_DIMS.MEDIUM]: "dim512",
@@ -249,12 +228,12 @@ var DIMENSION_MAP = {
249
228
  [VECTOR_DIMS.XXL]: "dim1536",
250
229
  [VECTOR_DIMS.XXXL]: "dim3072"
251
230
  };
252
- var embeddingTable = pgTable6(
231
+ var embeddingTable = pgTable5(
253
232
  "embeddings",
254
233
  {
255
- id: uuid6("id").primaryKey().defaultRandom().notNull(),
256
- memoryId: uuid6("memory_id").references(() => memoryTable.id),
257
- createdAt: numberTimestamp("created_at").default(sql6`now()`).notNull(),
234
+ id: uuid5("id").primaryKey().defaultRandom().notNull(),
235
+ memoryId: uuid5("memory_id").references(() => memoryTable.id),
236
+ createdAt: numberTimestamp("created_at").default(sql5`now()`).notNull(),
258
237
  dim384: vector2("dim_384", { dimensions: VECTOR_DIMS.SMALL }),
259
238
  dim512: vector2("dim_512", { dimensions: VECTOR_DIMS.MEDIUM }),
260
239
  dim768: vector2("dim_768", { dimensions: VECTOR_DIMS.LARGE }),
@@ -263,7 +242,7 @@ var embeddingTable = pgTable6(
263
242
  dim3072: vector2("dim_3072", { dimensions: VECTOR_DIMS.XXXL })
264
243
  },
265
244
  (table) => [
266
- check2("embedding_source_check", sql6`"memory_id" IS NOT NULL`),
245
+ check2("embedding_source_check", sql5`"memory_id" IS NOT NULL`),
267
246
  index2("idx_embedding_memory").on(table.memoryId),
268
247
  foreignKey2({
269
248
  name: "fk_embedding_memory",
@@ -274,16 +253,16 @@ var embeddingTable = pgTable6(
274
253
  );
275
254
 
276
255
  // src/schema/cache.ts
277
- import { sql as sql7 } from "drizzle-orm";
278
- import { jsonb as jsonb6, pgTable as pgTable7, text as text6, unique as unique4, uuid as uuid7 } from "drizzle-orm/pg-core";
279
- var cacheTable = pgTable7(
256
+ import { sql as sql6 } from "drizzle-orm";
257
+ import { jsonb as jsonb5, pgTable as pgTable6, text as text5, unique as unique4, uuid as uuid6 } from "drizzle-orm/pg-core";
258
+ var cacheTable = pgTable6(
280
259
  "cache",
281
260
  {
282
- id: uuid7("id").notNull().primaryKey().default(sql7`gen_random_uuid()`),
283
- key: text6("key").notNull(),
284
- agentId: uuid7("agentId").notNull().references(() => agentTable.id, { onDelete: "cascade" }),
285
- value: jsonb6("value").notNull(),
286
- createdAt: numberTimestamp("createdAt").default(sql7`now()`).notNull(),
261
+ id: uuid6("id").notNull().primaryKey().default(sql6`gen_random_uuid()`),
262
+ key: text5("key").notNull(),
263
+ agentId: uuid6("agentId").notNull().references(() => agentTable.id, { onDelete: "cascade" }),
264
+ value: jsonb5("value").notNull(),
265
+ createdAt: numberTimestamp("createdAt").default(sql6`now()`).notNull(),
287
266
  expiresAt: numberTimestamp("expiresAt")
288
267
  },
289
268
  (table) => [unique4("cache_key_agent_unique").on(table.key, table.agentId)]
@@ -292,6 +271,20 @@ var cacheTable = pgTable7(
292
271
  // src/schema/component.ts
293
272
  import { sql as sql8 } from "drizzle-orm";
294
273
  import { jsonb as jsonb7, pgTable as pgTable8, text as text7, uuid as uuid8 } from "drizzle-orm/pg-core";
274
+
275
+ // src/schema/world.ts
276
+ import { sql as sql7 } from "drizzle-orm";
277
+ import { jsonb as jsonb6, pgTable as pgTable7, text as text6, uuid as uuid7 } from "drizzle-orm/pg-core";
278
+ var worldTable = pgTable7("worlds", {
279
+ id: uuid7("id").notNull().primaryKey().default(sql7`gen_random_uuid()`),
280
+ agentId: uuid7("agentId").notNull().references(() => agentTable.id, { onDelete: "cascade" }),
281
+ name: text6("name").notNull(),
282
+ metadata: jsonb6("metadata"),
283
+ serverId: text6("serverId").notNull(),
284
+ createdAt: numberTimestamp("createdAt").default(sql7`now()`).notNull()
285
+ });
286
+
287
+ // src/schema/component.ts
295
288
  var componentTable = pgTable8("components", {
296
289
  id: uuid8("id").primaryKey().defaultRandom(),
297
290
  entityId: uuid8("entityId").notNull().references(() => entityTable.id, { onDelete: "cascade" }),
@@ -319,7 +312,7 @@ var logTable = pgTable9(
319
312
  entityId: uuid9("entityId").notNull().references(() => entityTable.id),
320
313
  body: jsonb8("body").notNull(),
321
314
  type: text8("type").notNull(),
322
- roomId: uuid9("roomId").notNull().references(() => roomTable.id)
315
+ roomId: uuid9("roomId").notNull().references(() => roomTable.id, { onDelete: "cascade" })
323
316
  },
324
317
  (table) => [
325
318
  foreignKey3({
@@ -403,17 +396,19 @@ var relationshipTable = pgTable11(
403
396
 
404
397
  // src/schema/tasks.ts
405
398
  import { jsonb as jsonb10, pgTable as pgTable12, text as text11, timestamp, uuid as uuid12 } from "drizzle-orm/pg-core";
399
+ import { sql as sql12 } from "drizzle-orm";
406
400
  var taskTable = pgTable12("tasks", {
407
401
  id: uuid12("id").primaryKey().defaultRandom(),
408
402
  name: text11("name").notNull(),
409
- description: text11("description").notNull(),
410
- roomId: uuid12("room_id"),
411
- worldId: uuid12("world_id"),
403
+ description: text11("description"),
404
+ roomId: uuid12("roomId"),
405
+ worldId: uuid12("worldId"),
406
+ entityId: uuid12("entityId"),
412
407
  agentId: uuid12("agent_id").notNull(),
413
- tags: text11("tags").array(),
414
- metadata: jsonb10("metadata"),
415
- createdAt: timestamp("created_at").defaultNow(),
416
- updatedAt: timestamp("updated_at").defaultNow()
408
+ tags: text11("tags").array().default(sql12`'{}'::text[]`),
409
+ metadata: jsonb10("metadata").default(sql12`'{}'::jsonb`),
410
+ createdAt: timestamp("created_at", { withTimezone: true }).defaultNow(),
411
+ updatedAt: timestamp("updated_at", { withTimezone: true }).defaultNow()
417
412
  });
418
413
 
419
414
  // src/base.ts
@@ -469,26 +464,6 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
469
464
  }
470
465
  throw lastError;
471
466
  }
472
- /**
473
- * Asynchronously ensures that an agent exists by checking if an agent with the same name already exists in the system.
474
- * If the agent does not exist, it will be created with the provided data.
475
- *
476
- * @param {Partial<Agent>} agent - The partial data of the agent to ensure its existence.
477
- * @returns {Promise<void>} - A promise that resolves when the agent is successfully ensured.
478
- * @throws {Error} - If the agent name is not provided or if there is an issue creating the agent.
479
- */
480
- async ensureAgentExists(agent) {
481
- if (!agent.name) {
482
- throw new Error("Agent name is required");
483
- }
484
- const agents = await this.getAgents();
485
- const existingAgent = agents.find(
486
- (a) => a.name === agent.name
487
- );
488
- if (!existingAgent) {
489
- await this.createAgent(agent);
490
- }
491
- }
492
467
  /**
493
468
  * Asynchronously ensures that the given embedding dimension is valid for the agent.
494
469
  *
@@ -496,15 +471,17 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
496
471
  * @returns {Promise<void>} - Resolves once the embedding dimension is ensured.
497
472
  */
498
473
  async ensureEmbeddingDimension(dimension) {
499
- const existingMemory = await this.db.select({
500
- embedding: embeddingTable
501
- }).from(memoryTable).innerJoin(embeddingTable, eq(embeddingTable.memoryId, memoryTable.id)).where(eq(memoryTable.agentId, this.agentId)).limit(1);
502
- if (existingMemory.length > 0) {
503
- const usedDimension = Object.entries(DIMENSION_MAP).find(
504
- ([_, colName]) => existingMemory[0].embedding[colName] !== null
505
- );
506
- }
507
- this.embeddingDimension = DIMENSION_MAP[dimension];
474
+ return this.withDatabase(async () => {
475
+ const existingMemory = await this.db.select({
476
+ embedding: embeddingTable
477
+ }).from(memoryTable).innerJoin(embeddingTable, eq(embeddingTable.memoryId, memoryTable.id)).where(eq(memoryTable.agentId, this.agentId)).limit(1);
478
+ if (existingMemory.length > 0) {
479
+ const usedDimension = Object.entries(DIMENSION_MAP).find(
480
+ ([_, colName]) => existingMemory[0].embedding[colName] !== null
481
+ );
482
+ }
483
+ this.embeddingDimension = DIMENSION_MAP[dimension];
484
+ });
508
485
  }
509
486
  /**
510
487
  * Asynchronously retrieves an agent by their ID from the database.
@@ -513,20 +490,35 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
513
490
  */
514
491
  async getAgent(agentId) {
515
492
  return this.withDatabase(async () => {
516
- const result = await this.db.select().from(agentTable).where(eq(agentTable.id, agentId)).limit(1);
517
- if (result.length === 0) return null;
518
- return result[0];
493
+ const rows = await this.db.select().from(agentTable).where(eq(agentTable.id, agentId)).limit(1);
494
+ if (rows.length === 0) return null;
495
+ const row = rows[0];
496
+ return {
497
+ ...row,
498
+ username: row.username || "",
499
+ id: row.id,
500
+ system: !row.system ? void 0 : row.system,
501
+ bio: !row.bio ? "" : row.bio
502
+ };
519
503
  });
520
504
  }
521
505
  /**
522
506
  * Asynchronously retrieves a list of agents from the database.
523
507
  *
524
- * @returns {Promise<Agent[]>} A Promise that resolves to an array of Agent objects.
508
+ * @returns {Promise<Partial<Agent>[]>} A Promise that resolves to an array of Agent objects.
525
509
  */
526
510
  async getAgents() {
527
511
  return this.withDatabase(async () => {
528
- const result = await this.db.select().from(agentTable);
529
- return result;
512
+ const rows = await this.db.select({
513
+ id: agentTable.id,
514
+ name: agentTable.name,
515
+ bio: agentTable.bio
516
+ }).from(agentTable);
517
+ return rows.map((row) => ({
518
+ ...row,
519
+ id: row.id,
520
+ bio: row.bio === null ? "" : row.bio
521
+ }));
530
522
  });
531
523
  }
532
524
  /**
@@ -566,11 +558,11 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
566
558
  async updateAgent(agentId, agent) {
567
559
  return this.withDatabase(async () => {
568
560
  try {
569
- if (!agent.id) {
561
+ if (!agentId) {
570
562
  throw new Error("Agent ID is required for update");
571
563
  }
572
564
  await this.db.transaction(async (tx) => {
573
- if (agent.settings) {
565
+ if (agent?.settings) {
574
566
  agent.settings = await this.mergeAgentSettings(tx, agentId, agent.settings);
575
567
  }
576
568
  await tx.update(agentTable).set({
@@ -603,27 +595,42 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
603
595
  */
604
596
  async mergeAgentSettings(tx, agentId, updatedSettings) {
605
597
  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];
598
+ const currentSettings = currentAgent.length > 0 && currentAgent[0].settings ? currentAgent[0].settings : {};
599
+ const deepMerge = /* @__PURE__ */ __name((target, source) => {
600
+ if (source === null) {
601
+ return void 0;
602
+ }
603
+ if (Array.isArray(source) || typeof source !== "object") {
604
+ return source;
605
+ }
606
+ const output = typeof target === "object" && target !== null && !Array.isArray(target) ? { ...target } : {};
607
+ let isEmpty = true;
608
+ for (const key of Object.keys(source)) {
609
+ const sourceValue = source[key];
610
+ if (sourceValue === null) {
611
+ delete output[key];
612
+ } else if (typeof sourceValue === "object" && !Array.isArray(sourceValue)) {
613
+ const nestedMergeResult = deepMerge(output[key], sourceValue);
614
+ if (nestedMergeResult === void 0) {
615
+ delete output[key];
616
+ } else {
617
+ output[key] = nestedMergeResult;
618
+ isEmpty = false;
619
+ }
617
620
  } else {
618
- mergedSecrets[key] = value;
621
+ output[key] = sourceValue;
622
+ isEmpty = false;
619
623
  }
620
624
  }
621
- updatedSettings.secrets = mergedSecrets;
622
- }
623
- return {
624
- ...currentSettings,
625
- ...updatedSettings
626
- };
625
+ if (Object.keys(output).length === 0) {
626
+ if (!(typeof source === "object" && source !== null && Object.keys(source).length === 0)) {
627
+ return void 0;
628
+ }
629
+ }
630
+ return output;
631
+ }, "deepMerge");
632
+ const finalSettings = deepMerge(currentSettings, updatedSettings);
633
+ return finalSettings === void 0 ? {} : finalSettings;
627
634
  }
628
635
  /**
629
636
  * Asynchronously deletes an agent with the specified UUID and all related entries.
@@ -632,47 +639,161 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
632
639
  * @returns {Promise<boolean>} - A boolean indicating if the deletion was successful.
633
640
  */
634
641
  async deleteAgent(agentId) {
642
+ logger.debug(`[DB] Starting deletion of agent with ID: ${agentId}`);
635
643
  return this.withDatabase(async () => {
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));
644
+ try {
645
+ logger.debug(`[DB] Beginning database transaction for deleting agent: ${agentId}`);
646
+ const deletePromise = new Promise((resolve, reject) => {
647
+ const timeoutId = setTimeout(() => {
648
+ logger.error(`[DB] Transaction timeout reached for agent deletion: ${agentId}`);
649
+ reject(new Error("Database transaction timeout"));
650
+ }, 3e4);
651
+ this.db.transaction(async (tx) => {
652
+ try {
653
+ logger.debug(`[DB] Fetching entities for agent: ${agentId}`);
654
+ const entities = await tx.select({ entityId: entityTable.id }).from(entityTable).where(eq(entityTable.agentId, agentId));
655
+ const entityIds = entities.map((e) => e.entityId);
656
+ logger.debug(
657
+ `[DB] Found ${entityIds.length} entities to delete for agent ${agentId}`
658
+ );
659
+ logger.debug(`[DB] Fetching rooms for agent: ${agentId}`);
660
+ const rooms = await tx.select({ roomId: roomTable.id }).from(roomTable).where(eq(roomTable.agentId, agentId));
661
+ const roomIds = rooms.map((r) => r.roomId);
662
+ logger.debug(`[DB] Found ${roomIds.length} rooms for agent ${agentId}`);
663
+ logger.debug(
664
+ `[DB] Explicitly deleting ALL logs with matching entityIds and roomIds`
665
+ );
666
+ if (entityIds.length > 0) {
667
+ logger.debug(`[DB] Deleting logs for ${entityIds.length} entities (first batch)`);
668
+ const BATCH_SIZE = 50;
669
+ for (let i = 0; i < entityIds.length; i += BATCH_SIZE) {
670
+ const batch = entityIds.slice(i, i + BATCH_SIZE);
671
+ logger.debug(
672
+ `[DB] Processing entity logs batch ${i / BATCH_SIZE + 1} with ${batch.length} entities`
673
+ );
674
+ await tx.delete(logTable).where(inArray(logTable.entityId, batch));
675
+ }
676
+ logger.debug(`[DB] Entity logs deletion completed successfully`);
677
+ }
678
+ if (roomIds.length > 0) {
679
+ logger.debug(`[DB] Deleting logs for ${roomIds.length} rooms (first batch)`);
680
+ const BATCH_SIZE = 50;
681
+ for (let i = 0; i < roomIds.length; i += BATCH_SIZE) {
682
+ const batch = roomIds.slice(i, i + BATCH_SIZE);
683
+ logger.debug(
684
+ `[DB] Processing room logs batch ${i / BATCH_SIZE + 1} with ${batch.length} rooms`
685
+ );
686
+ await tx.delete(logTable).where(inArray(logTable.roomId, batch));
687
+ }
688
+ logger.debug(`[DB] Room logs deletion completed successfully`);
689
+ }
690
+ let memoryIds = [];
691
+ if (entityIds.length > 0) {
692
+ logger.debug(`[DB] Finding memories belonging to entities`);
693
+ const memories = await tx.select({ id: memoryTable.id }).from(memoryTable).where(inArray(memoryTable.entityId, entityIds));
694
+ memoryIds = memories.map((m) => m.id);
695
+ logger.debug(`[DB] Found ${memoryIds.length} memories belonging to entities`);
696
+ }
697
+ logger.debug(`[DB] Finding memories belonging to agent directly`);
698
+ const agentMemories = await tx.select({ id: memoryTable.id }).from(memoryTable).where(eq(memoryTable.agentId, agentId));
699
+ memoryIds = [...memoryIds, ...agentMemories.map((m) => m.id)];
700
+ logger.debug(`[DB] Found total of ${memoryIds.length} memories to delete`);
701
+ if (roomIds.length > 0) {
702
+ logger.debug(`[DB] Finding memories belonging to rooms`);
703
+ const roomMemories = await tx.select({ id: memoryTable.id }).from(memoryTable).where(inArray(memoryTable.roomId, roomIds));
704
+ memoryIds = [...memoryIds, ...roomMemories.map((m) => m.id)];
705
+ logger.debug(`[DB] Updated total to ${memoryIds.length} memories to delete`);
706
+ }
707
+ if (memoryIds.length > 0) {
708
+ logger.debug(`[DB] Deleting embeddings for ${memoryIds.length} memories`);
709
+ const BATCH_SIZE = 100;
710
+ for (let i = 0; i < memoryIds.length; i += BATCH_SIZE) {
711
+ const batch = memoryIds.slice(i, i + BATCH_SIZE);
712
+ await tx.delete(embeddingTable).where(inArray(embeddingTable.memoryId, batch));
713
+ }
714
+ logger.debug(`[DB] Embeddings deleted successfully`);
715
+ }
716
+ if (memoryIds.length > 0) {
717
+ logger.debug(`[DB] Deleting ${memoryIds.length} memories`);
718
+ const BATCH_SIZE = 100;
719
+ for (let i = 0; i < memoryIds.length; i += BATCH_SIZE) {
720
+ const batch = memoryIds.slice(i, i + BATCH_SIZE);
721
+ await tx.delete(memoryTable).where(inArray(memoryTable.id, batch));
722
+ }
723
+ logger.debug(`[DB] Memories deleted successfully`);
724
+ }
725
+ if (entityIds.length > 0) {
726
+ logger.debug(`[DB] Deleting components for entities`);
727
+ await tx.delete(componentTable).where(inArray(componentTable.entityId, entityIds));
728
+ logger.debug(`[DB] Components deleted successfully`);
729
+ }
730
+ if (entityIds.length > 0) {
731
+ logger.debug(`[DB] Deleting source entity references in components`);
732
+ await tx.delete(componentTable).where(inArray(componentTable.sourceEntityId, entityIds));
733
+ logger.debug(`[DB] Source entity references deleted successfully`);
734
+ }
735
+ if (roomIds.length > 0) {
736
+ logger.debug(`[DB] Deleting participations for rooms`);
737
+ await tx.delete(participantTable).where(inArray(participantTable.roomId, roomIds));
738
+ logger.debug(`[DB] Participations deleted for rooms`);
739
+ }
740
+ logger.debug(`[DB] Deleting agent participations`);
741
+ await tx.delete(participantTable).where(eq(participantTable.agentId, agentId));
742
+ logger.debug(`[DB] Agent participations deleted`);
743
+ if (roomIds.length > 0) {
744
+ logger.debug(`[DB] Deleting rooms`);
745
+ await tx.delete(roomTable).where(inArray(roomTable.id, roomIds));
746
+ logger.debug(`[DB] Rooms deleted successfully`);
747
+ }
748
+ logger.debug(`[DB] Deleting cache entries`);
749
+ await tx.delete(cacheTable).where(eq(cacheTable.agentId, agentId));
750
+ logger.debug(`[DB] Cache entries deleted successfully`);
751
+ logger.debug(`[DB] Deleting relationships`);
752
+ if (entityIds.length > 0) {
753
+ await tx.delete(relationshipTable).where(inArray(relationshipTable.sourceEntityId, entityIds));
754
+ await tx.delete(relationshipTable).where(inArray(relationshipTable.targetEntityId, entityIds));
755
+ }
756
+ await tx.delete(relationshipTable).where(eq(relationshipTable.agentId, agentId));
757
+ logger.debug(`[DB] Relationships deleted successfully`);
758
+ if (entityIds.length > 0) {
759
+ logger.debug(`[DB] Deleting entities`);
760
+ await tx.delete(entityTable).where(eq(entityTable.agentId, agentId));
761
+ logger.debug(`[DB] Entities deleted successfully`);
762
+ }
763
+ logger.debug(`[DB] Checking for world references`);
764
+ const worlds = await tx.select({ id: worldTable.id }).from(worldTable).where(eq(worldTable.agentId, agentId));
765
+ if (worlds.length > 0) {
766
+ const worldIds = worlds.map((w) => w.id);
767
+ logger.debug(`[DB] Found ${worldIds.length} worlds to delete`);
768
+ await tx.delete(worldTable).where(inArray(worldTable.id, worldIds));
769
+ logger.debug(`[DB] Worlds deleted successfully`);
770
+ } else {
771
+ logger.debug(`[DB] No worlds found for this agent`);
772
+ }
773
+ logger.debug(`[DB] Deleting agent ${agentId}`);
774
+ await tx.delete(agentTable).where(eq(agentTable.id, agentId));
775
+ logger.debug(`[DB] Agent deleted successfully`);
776
+ resolve(true);
777
+ } catch (error) {
778
+ logger.error(`[DB] Error in transaction:`, error);
779
+ reject(error);
780
+ }
781
+ }).catch((transactionError) => {
782
+ clearTimeout(timeoutId);
783
+ reject(transactionError);
784
+ });
785
+ });
786
+ await deletePromise;
787
+ logger.success(`[DB] Agent ${agentId} successfully deleted`);
788
+ return true;
789
+ } catch (error) {
790
+ logger.error(`[DB] Error in database transaction for agent deletion ${agentId}:`, error);
791
+ if (error instanceof Error) {
792
+ logger.error(`[DB] Error name: ${error.name}, message: ${error.message}`);
793
+ logger.error(`[DB] Error stack: ${error.stack}`);
672
794
  }
673
- await tx.delete(agentTable).where(eq(agentTable.id, agentId));
674
- });
675
- return true;
795
+ throw error;
796
+ }
676
797
  });
677
798
  }
678
799
  /**
@@ -715,20 +836,32 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
715
836
  });
716
837
  }
717
838
  /**
718
- * Asynchronously retrieves an entity and its components by entity ID.
719
- * @param {UUID} entityId - The unique identifier of the entity to retrieve.
720
- * @returns {Promise<Entity | null>} A Promise that resolves to the entity with its components if found, null otherwise.
839
+ * Asynchronously retrieves an entity and its components by entity IDs.
840
+ * @param {UUID[]} entityIds - The unique identifiers of the entities to retrieve.
841
+ * @returns {Promise<Entity[] | null>} A Promise that resolves to the entity with its components if found, null otherwise.
721
842
  */
722
- async getEntityById(entityId) {
843
+ async getEntityByIds(entityIds) {
723
844
  return this.withDatabase(async () => {
724
845
  const result = await this.db.select({
725
846
  entity: entityTable,
726
847
  components: componentTable
727
- }).from(entityTable).leftJoin(componentTable, eq(componentTable.entityId, entityTable.id)).where(and(eq(entityTable.id, entityId), eq(entityTable.agentId, this.agentId)));
848
+ }).from(entityTable).leftJoin(componentTable, eq(componentTable.entityId, entityTable.id)).where(inArray(entityTable.id, entityIds));
728
849
  if (result.length === 0) return null;
729
- const entity = result[0].entity;
730
- entity.components = result.filter((row) => row.components).map((row) => row.components);
731
- return entity;
850
+ const entities = {};
851
+ const entityComponents = {};
852
+ for (const e of result) {
853
+ const key = e.entity.id;
854
+ entities[key] = e.entity;
855
+ if (entityComponents[key] === void 0) entityComponents[key] = [];
856
+ if (e.components) {
857
+ const componentsArray = Array.isArray(e.components) ? e.components : [e.components];
858
+ entityComponents[key] = [...entityComponents[key], ...componentsArray];
859
+ }
860
+ }
861
+ for (const k of Object.keys(entityComponents)) {
862
+ entities[k].components = entityComponents[k];
863
+ }
864
+ return Object.values(entities);
732
865
  });
733
866
  }
734
867
  /**
@@ -757,6 +890,9 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
757
890
  if (!entitiesByIdMap.has(entityId)) {
758
891
  const entity = {
759
892
  ...row.entity,
893
+ id: entityId,
894
+ agentId: row.entity.agentId,
895
+ metadata: row.entity.metadata,
760
896
  components: includeComponents ? [] : void 0
761
897
  };
762
898
  entitiesByIdMap.set(entityId, entity);
@@ -775,32 +911,23 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
775
911
  });
776
912
  }
777
913
  /**
778
- * Asynchronously creates a new entity in the database.
779
- * @param {Entity} entity - The entity object to be created.
914
+ * Asynchronously creates new entities in the database.
915
+ * @param {Entity[]} entities - The entity objects to be created.
780
916
  * @returns {Promise<boolean>} A Promise that resolves to a boolean indicating the success of the operation.
781
917
  */
782
- async createEntity(entity) {
918
+ async createEntities(entities) {
783
919
  return this.withDatabase(async () => {
784
920
  try {
785
921
  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
- }
793
- await tx.insert(entityTable).values(entity);
794
- logger.debug("Entity created successfully:", {
795
- entity
796
- });
922
+ await tx.insert(entityTable).values(entities);
923
+ logger.debug(entities.length, "Entities created successfully");
797
924
  return true;
798
925
  });
799
926
  } catch (error) {
800
927
  logger.error("Error creating entity:", {
801
928
  error: error instanceof Error ? error.message : String(error),
802
- entityId: entity.id,
803
- name: entity.metadata?.name
929
+ entityId: entities[0].id,
930
+ name: entities[0].metadata?.name
804
931
  });
805
932
  logger.trace(error);
806
933
  return false;
@@ -818,9 +945,9 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
818
945
  return false;
819
946
  }
820
947
  try {
821
- const existingEntity = await this.getEntityById(entity.id);
822
- if (!existingEntity) {
823
- return await this.createEntity(entity);
948
+ const existingEntities = await this.getEntityByIds([entity.id]);
949
+ if (!existingEntities || !existingEntities.length) {
950
+ return await this.createEntities([entity]);
824
951
  }
825
952
  return true;
826
953
  } catch (error) {
@@ -851,7 +978,18 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
851
978
  conditions.push(eq(componentTable.sourceEntityId, sourceEntityId));
852
979
  }
853
980
  const result = await this.db.select().from(componentTable).where(and(...conditions));
854
- return result.length > 0 ? result[0] : null;
981
+ if (result.length === 0) return null;
982
+ const component = result[0];
983
+ return {
984
+ ...component,
985
+ id: component.id,
986
+ entityId: component.entityId,
987
+ agentId: component.agentId,
988
+ roomId: component.roomId,
989
+ worldId: component.worldId ?? "",
990
+ sourceEntityId: component.sourceEntityId ?? "",
991
+ data: component.data
992
+ };
855
993
  });
856
994
  }
857
995
  /**
@@ -876,10 +1014,23 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
876
1014
  type: componentTable.type,
877
1015
  data: componentTable.data,
878
1016
  worldId: componentTable.worldId,
1017
+ agentId: componentTable.agentId,
1018
+ roomId: componentTable.roomId,
879
1019
  sourceEntityId: componentTable.sourceEntityId,
880
1020
  createdAt: componentTable.createdAt
881
1021
  }).from(componentTable).where(and(...conditions));
882
- return result;
1022
+ if (result.length === 0) return [];
1023
+ const components = result.map((component) => ({
1024
+ ...component,
1025
+ id: component.id,
1026
+ entityId: component.entityId,
1027
+ agentId: component.agentId,
1028
+ roomId: component.roomId,
1029
+ worldId: component.worldId ?? "",
1030
+ sourceEntityId: component.sourceEntityId ?? "",
1031
+ data: component.data
1032
+ }));
1033
+ return components;
883
1034
  });
884
1035
  }
885
1036
  /**
@@ -925,10 +1076,8 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
925
1076
  * @returns {Promise<Memory[]>} A Promise that resolves to an array of memories.
926
1077
  */
927
1078
  async getMemories(params) {
928
- const { entityId, agentId, roomId, tableName, count: count2, unique: unique7, start, end } = params;
1079
+ const { entityId, agentId, roomId, worldId, tableName, count: count2, unique: unique7, start, end } = params;
929
1080
  if (!tableName) throw new Error("tableName is required");
930
- if (!roomId && !entityId && !agentId)
931
- throw new Error("roomId, entityId, or agentId is required");
932
1081
  return this.withDatabase(async () => {
933
1082
  const conditions = [eq(memoryTable.type, tableName)];
934
1083
  if (start) {
@@ -940,6 +1089,9 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
940
1089
  if (roomId) {
941
1090
  conditions.push(eq(memoryTable.roomId, roomId));
942
1091
  }
1092
+ if (worldId) {
1093
+ conditions.push(eq(memoryTable.worldId, worldId));
1094
+ }
943
1095
  if (end) {
944
1096
  conditions.push(lte(memoryTable.createdAt, end));
945
1097
  }
@@ -1039,6 +1191,7 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1039
1191
  agentId: row.memory.agentId,
1040
1192
  roomId: row.memory.roomId,
1041
1193
  unique: row.memory.unique,
1194
+ metadata: row.memory.metadata,
1042
1195
  embedding: row.embedding ?? void 0
1043
1196
  };
1044
1197
  });
@@ -1088,7 +1241,7 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1088
1241
  async getCachedEmbeddings(opts) {
1089
1242
  return this.withDatabase(async () => {
1090
1243
  try {
1091
- const results = await this.db.execute(sql12`
1244
+ const results = await this.db.execute(sql13`
1092
1245
  WITH content_text AS (
1093
1246
  SELECT
1094
1247
  m.id,
@@ -1101,7 +1254,7 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1101
1254
  AND m.content->>${opts.query_field_sub_name} IS NOT NULL
1102
1255
  ),
1103
1256
  embedded_text AS (
1104
- SELECT
1257
+ SELECT
1105
1258
  ct.content_text,
1106
1259
  COALESCE(
1107
1260
  e.dim_384,
@@ -1152,9 +1305,11 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1152
1305
  async log(params) {
1153
1306
  return this.withDatabase(async () => {
1154
1307
  try {
1308
+ const sanitizedBody = this.sanitizeJsonObject(params.body);
1309
+ const jsonString = JSON.stringify(sanitizedBody);
1155
1310
  await this.db.transaction(async (tx) => {
1156
1311
  await tx.insert(logTable).values({
1157
- body: sql12`${params.body}::jsonb`,
1312
+ body: sql13`${jsonString}::jsonb`,
1158
1313
  entityId: params.entityId,
1159
1314
  roomId: params.roomId,
1160
1315
  type: params.type
@@ -1171,6 +1326,34 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1171
1326
  }
1172
1327
  });
1173
1328
  }
1329
+ /**
1330
+ * Sanitizes a JSON object by replacing problematic Unicode escape sequences
1331
+ * that could cause errors during JSON serialization/storage
1332
+ *
1333
+ * @param value - The value to sanitize
1334
+ * @returns The sanitized value
1335
+ */
1336
+ sanitizeJsonObject(value) {
1337
+ if (value === null || value === void 0) {
1338
+ return value;
1339
+ }
1340
+ if (typeof value === "string") {
1341
+ return value.replace(/\u0000/g, "").replace(/\\(?!["\\/bfnrtu])/g, "\\\\").replace(/\\u(?![0-9a-fA-F]{4})/g, "\\\\u");
1342
+ }
1343
+ if (typeof value === "object") {
1344
+ if (Array.isArray(value)) {
1345
+ return value.map((item) => this.sanitizeJsonObject(item));
1346
+ } else {
1347
+ const result = {};
1348
+ for (const [key, val] of Object.entries(value)) {
1349
+ const sanitizedKey = typeof key === "string" ? key.replace(/\u0000/g, "").replace(/\\u(?![0-9a-fA-F]{4})/g, "\\\\u") : key;
1350
+ result[sanitizedKey] = this.sanitizeJsonObject(val);
1351
+ }
1352
+ return result;
1353
+ }
1354
+ }
1355
+ return value;
1356
+ }
1174
1357
  /**
1175
1358
  * Asynchronously retrieves logs from the database based on the provided parameters.
1176
1359
  * @param {Object} params - The parameters for retrieving logs.
@@ -1191,7 +1374,16 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1191
1374
  type ? eq(logTable.type, type) : void 0
1192
1375
  )
1193
1376
  ).orderBy(desc(logTable.createdAt)).limit(count2 ?? 10).offset(offset ?? 0);
1194
- return result;
1377
+ const logs = result.map((log) => ({
1378
+ ...log,
1379
+ id: log.id,
1380
+ entityId: log.entityId,
1381
+ roomId: log.roomId,
1382
+ body: log.body,
1383
+ createdAt: new Date(log.createdAt)
1384
+ }));
1385
+ if (logs.length === 0) return [];
1386
+ return logs;
1195
1387
  });
1196
1388
  }
1197
1389
  /**
@@ -1208,18 +1400,24 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1208
1400
  * Asynchronously searches for memories in the database based on the provided parameters.
1209
1401
  * @param {Object} params - The parameters for searching for memories.
1210
1402
  * @param {string} params.tableName - The name of the table to search for memories in.
1211
- * @param {UUID} params.roomId - The ID of the room to search for memories in.
1212
1403
  * @param {number[]} params.embedding - The embedding to search for.
1213
1404
  * @param {number} [params.match_threshold] - The threshold for the cosine distance.
1214
1405
  * @param {number} [params.count] - The maximum number of memories to retrieve.
1215
1406
  * @param {boolean} [params.unique] - Whether to retrieve unique memories only.
1407
+ * @param {string} [params.query] - Optional query string for potential reranking.
1408
+ * @param {UUID} [params.roomId] - Optional room ID to filter by.
1409
+ * @param {UUID} [params.worldId] - Optional world ID to filter by.
1410
+ * @param {UUID} [params.entityId] - Optional entity ID to filter by.
1216
1411
  * @returns {Promise<Memory[]>} A Promise that resolves to an array of memories.
1217
1412
  */
1218
1413
  async searchMemories(params) {
1219
1414
  return await this.searchMemoriesByEmbedding(params.embedding, {
1220
1415
  match_threshold: params.match_threshold,
1221
1416
  count: params.count,
1417
+ // Pass direct scope fields down
1222
1418
  roomId: params.roomId,
1419
+ worldId: params.worldId,
1420
+ entityId: params.entityId,
1223
1421
  unique: params.unique,
1224
1422
  tableName: params.tableName
1225
1423
  });
@@ -1230,7 +1428,9 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1230
1428
  * @param {Object} params - The parameters for searching for memories.
1231
1429
  * @param {number} [params.match_threshold] - The threshold for the cosine distance.
1232
1430
  * @param {number} [params.count] - The maximum number of memories to retrieve.
1233
- * @param {UUID} [params.roomId] - The ID of the room to search for memories in.
1431
+ * @param {UUID} [params.roomId] - Optional room ID to filter by.
1432
+ * @param {UUID} [params.worldId] - Optional world ID to filter by.
1433
+ * @param {UUID} [params.entityId] - Optional entity ID to filter by.
1234
1434
  * @param {boolean} [params.unique] - Whether to retrieve unique memories only.
1235
1435
  * @param {string} [params.tableName] - The name of the table to search for memories in.
1236
1436
  * @returns {Promise<Memory[]>} A Promise that resolves to an array of memories.
@@ -1238,7 +1438,7 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1238
1438
  async searchMemoriesByEmbedding(embedding, params) {
1239
1439
  return this.withDatabase(async () => {
1240
1440
  const cleanVector = embedding.map((n) => Number.isFinite(n) ? Number(n.toFixed(6)) : 0);
1241
- const similarity = sql12`1 - (${cosineDistance(
1441
+ const similarity = sql13`1 - (${cosineDistance(
1242
1442
  embeddingTable[this.embeddingDimension],
1243
1443
  cleanVector
1244
1444
  )})`;
@@ -1250,6 +1450,12 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1250
1450
  if (params.roomId) {
1251
1451
  conditions.push(eq(memoryTable.roomId, params.roomId));
1252
1452
  }
1453
+ if (params.worldId) {
1454
+ conditions.push(eq(memoryTable.worldId, params.worldId));
1455
+ }
1456
+ if (params.entityId) {
1457
+ conditions.push(eq(memoryTable.entityId, params.entityId));
1458
+ }
1253
1459
  if (params.match_threshold) {
1254
1460
  conditions.push(gte(similarity, params.match_threshold));
1255
1461
  }
@@ -1266,6 +1472,8 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1266
1472
  entityId: row.memory.entityId,
1267
1473
  agentId: row.memory.agentId,
1268
1474
  roomId: row.memory.roomId,
1475
+ worldId: row.memory.worldId,
1476
+ // Include worldId
1269
1477
  unique: row.memory.unique,
1270
1478
  metadata: row.memory.metadata,
1271
1479
  embedding: row.embedding ?? void 0,
@@ -1285,28 +1493,40 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1285
1493
  embeddingLength: memory.embedding?.length,
1286
1494
  contentLength: memory.content?.text?.length
1287
1495
  });
1496
+ const memoryId = memory.id ?? v4();
1497
+ const existing = await this.getMemoryById(memoryId);
1498
+ if (existing) {
1499
+ logger.debug("Memory already exists, skipping creation:", {
1500
+ memoryId
1501
+ });
1502
+ return memoryId;
1503
+ }
1288
1504
  let isUnique = true;
1289
1505
  if (memory.embedding && Array.isArray(memory.embedding)) {
1290
1506
  const similarMemories = await this.searchMemoriesByEmbedding(memory.embedding, {
1291
1507
  tableName,
1508
+ // Use the scope fields from the memory object for similarity check
1292
1509
  roomId: memory.roomId,
1510
+ worldId: memory.worldId,
1511
+ entityId: memory.entityId,
1293
1512
  match_threshold: 0.95,
1294
1513
  count: 1
1295
1514
  });
1296
1515
  isUnique = similarMemories.length === 0;
1297
1516
  }
1298
1517
  const contentToInsert = typeof memory.content === "string" ? JSON.parse(memory.content) : memory.content;
1299
- const memoryId = memory.id ?? v4();
1300
1518
  await this.db.transaction(async (tx) => {
1301
1519
  await tx.insert(memoryTable).values([
1302
1520
  {
1303
1521
  id: memoryId,
1304
1522
  type: tableName,
1305
- content: sql12`${contentToInsert}::jsonb`,
1306
- metadata: sql12`${memory.metadata || {}}::jsonb`,
1523
+ content: sql13`${contentToInsert}::jsonb`,
1524
+ metadata: sql13`${memory.metadata || {}}::jsonb`,
1307
1525
  entityId: memory.entityId,
1308
1526
  roomId: memory.roomId,
1309
- agentId: memory.agentId,
1527
+ worldId: memory.worldId,
1528
+ // Include worldId
1529
+ agentId: this.agentId,
1310
1530
  unique: memory.unique ?? isUnique,
1311
1531
  createdAt: memory.createdAt
1312
1532
  }
@@ -1342,12 +1562,12 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1342
1562
  if (memory.content) {
1343
1563
  const contentToUpdate = typeof memory.content === "string" ? JSON.parse(memory.content) : memory.content;
1344
1564
  await tx.update(memoryTable).set({
1345
- content: sql12`${contentToUpdate}::jsonb`,
1346
- ...memory.metadata && { metadata: sql12`${memory.metadata}::jsonb` }
1565
+ content: sql13`${contentToUpdate}::jsonb`,
1566
+ ...memory.metadata && { metadata: sql13`${memory.metadata}::jsonb` }
1347
1567
  }).where(eq(memoryTable.id, memory.id));
1348
1568
  } else if (memory.metadata) {
1349
1569
  await tx.update(memoryTable).set({
1350
- metadata: sql12`${memory.metadata}::jsonb`
1570
+ metadata: sql13`${memory.metadata}::jsonb`
1351
1571
  }).where(eq(memoryTable.id, memory.id));
1352
1572
  }
1353
1573
  if (memory.embedding && Array.isArray(memory.embedding)) {
@@ -1429,10 +1649,10 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1429
1649
  const fragments = await tx.select({ id: memoryTable.id }).from(memoryTable).where(
1430
1650
  and(
1431
1651
  eq(memoryTable.agentId, this.agentId),
1432
- sql12`${memoryTable.metadata}->>'documentId' = ${documentId}`
1652
+ sql13`${memoryTable.metadata}->>'documentId' = ${documentId}`
1433
1653
  )
1434
1654
  );
1435
- return fragments;
1655
+ return fragments.map((f) => ({ id: f.id }));
1436
1656
  }
1437
1657
  /**
1438
1658
  * Asynchronously deletes all memories from the database based on the provided parameters.
@@ -1443,21 +1663,21 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1443
1663
  async deleteAllMemories(roomId, tableName) {
1444
1664
  return this.withDatabase(async () => {
1445
1665
  await this.db.transaction(async (tx) => {
1446
- const memoryIds = await tx.select({ id: memoryTable.id }).from(memoryTable).where(and(eq(memoryTable.roomId, roomId), eq(memoryTable.type, tableName)));
1447
- if (memoryIds.length > 0) {
1448
- await tx.delete(embeddingTable).where(
1449
- inArray(
1450
- embeddingTable.memoryId,
1451
- memoryIds.map((m) => m.id)
1452
- )
1453
- );
1454
- await tx.delete(memoryTable).where(and(eq(memoryTable.roomId, roomId), eq(memoryTable.type, tableName)));
1666
+ const rows = await tx.select({ id: memoryTable.id }).from(memoryTable).where(and(eq(memoryTable.roomId, roomId), eq(memoryTable.type, tableName)));
1667
+ const ids = rows.map((r) => r.id);
1668
+ logger.debug("[deleteAllMemories] memory IDs to delete:", { roomId, tableName, ids });
1669
+ if (ids.length === 0) {
1670
+ return;
1455
1671
  }
1672
+ await Promise.all(
1673
+ ids.map(async (memoryId) => {
1674
+ await this.deleteMemoryFragments(tx, memoryId);
1675
+ await tx.delete(embeddingTable).where(eq(embeddingTable.memoryId, memoryId));
1676
+ })
1677
+ );
1678
+ await tx.delete(memoryTable).where(and(eq(memoryTable.roomId, roomId), eq(memoryTable.type, tableName)));
1456
1679
  });
1457
- logger.debug("All memories removed successfully:", {
1458
- roomId,
1459
- tableName
1460
- });
1680
+ logger.debug("All memories removed successfully:", { roomId, tableName });
1461
1681
  });
1462
1682
  }
1463
1683
  /**
@@ -1474,28 +1694,42 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1474
1694
  if (unique7) {
1475
1695
  conditions.push(eq(memoryTable.unique, true));
1476
1696
  }
1477
- const result = await this.db.select({ count: sql12`count(*)` }).from(memoryTable).where(and(...conditions));
1697
+ const result = await this.db.select({ count: sql13`count(*)` }).from(memoryTable).where(and(...conditions));
1478
1698
  return Number(result[0]?.count ?? 0);
1479
1699
  });
1480
1700
  }
1481
1701
  /**
1482
- * Asynchronously retrieves a room from the database based on the provided parameters.
1483
- * @param {UUID} roomId - The ID of the room to retrieve.
1484
- * @returns {Promise<Room | null>} A Promise that resolves to the room if found, null otherwise.
1702
+ * Asynchronously retrieves rooms from the database based on the provided parameters.
1703
+ * @param {UUID[]} roomIds - The IDs of the rooms to retrieve.
1704
+ * @returns {Promise<Room[] | null>} A Promise that resolves to the rooms if found, null otherwise.
1485
1705
  */
1486
- async getRoom(roomId) {
1706
+ async getRoomsByIds(roomIds) {
1487
1707
  return this.withDatabase(async () => {
1488
1708
  const result = await this.db.select({
1489
1709
  id: roomTable.id,
1710
+ name: roomTable.name,
1711
+ // Added name
1490
1712
  channelId: roomTable.channelId,
1491
1713
  agentId: roomTable.agentId,
1492
1714
  serverId: roomTable.serverId,
1493
1715
  worldId: roomTable.worldId,
1494
1716
  type: roomTable.type,
1495
- source: roomTable.source
1496
- }).from(roomTable).where(and(eq(roomTable.id, roomId), eq(roomTable.agentId, this.agentId))).limit(1);
1497
- if (result.length === 0) return null;
1498
- return result[0];
1717
+ source: roomTable.source,
1718
+ metadata: roomTable.metadata
1719
+ // Added metadata
1720
+ }).from(roomTable).where(and(inArray(roomTable.id, roomIds), eq(roomTable.agentId, this.agentId)));
1721
+ const rooms = result.map((room) => ({
1722
+ ...room,
1723
+ id: room.id,
1724
+ name: room.name ?? void 0,
1725
+ agentId: room.agentId,
1726
+ serverId: room.serverId,
1727
+ worldId: room.worldId,
1728
+ channelId: room.channelId,
1729
+ type: room.type,
1730
+ metadata: room.metadata
1731
+ }));
1732
+ return rooms;
1499
1733
  });
1500
1734
  }
1501
1735
  /**
@@ -1503,10 +1737,21 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1503
1737
  * @param {UUID} worldId - The ID of the world to retrieve rooms from.
1504
1738
  * @returns {Promise<Room[]>} A Promise that resolves to an array of rooms.
1505
1739
  */
1506
- async getRooms(worldId) {
1740
+ async getRoomsByWorld(worldId) {
1507
1741
  return this.withDatabase(async () => {
1508
1742
  const result = await this.db.select().from(roomTable).where(eq(roomTable.worldId, worldId));
1509
- return result;
1743
+ const rooms = result.map((room) => ({
1744
+ ...room,
1745
+ id: room.id,
1746
+ name: room.name ?? void 0,
1747
+ agentId: room.agentId,
1748
+ serverId: room.serverId,
1749
+ worldId: room.worldId,
1750
+ channelId: room.channelId,
1751
+ type: room.type,
1752
+ metadata: room.metadata
1753
+ }));
1754
+ return rooms;
1510
1755
  });
1511
1756
  }
1512
1757
  /**
@@ -1524,30 +1769,17 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1524
1769
  * @param {Room} room - The room object to create.
1525
1770
  * @returns {Promise<UUID>} A Promise that resolves to the ID of the created room.
1526
1771
  */
1527
- async createRoom({
1528
- id,
1529
- name,
1530
- source,
1531
- type,
1532
- channelId,
1533
- serverId,
1534
- worldId,
1535
- metadata
1536
- }) {
1772
+ async createRooms(rooms) {
1537
1773
  return this.withDatabase(async () => {
1538
- const newRoomId = id || v4();
1539
- await this.db.insert(roomTable).values({
1540
- id: newRoomId,
1541
- name,
1774
+ const roomsWithIds = rooms.map((room) => ({
1775
+ ...room,
1542
1776
  agentId: this.agentId,
1543
- source,
1544
- type,
1545
- channelId,
1546
- serverId,
1547
- worldId,
1548
- metadata
1549
- }).onConflictDoNothing({ target: roomTable.id });
1550
- return newRoomId;
1777
+ id: room.id || v4()
1778
+ // ensure each room has a unique ID
1779
+ }));
1780
+ const insertedRooms = await this.db.insert(roomTable).values(roomsWithIds).onConflictDoNothing().returning();
1781
+ const insertedIds = insertedRooms.map((r) => r.id);
1782
+ return insertedIds;
1551
1783
  });
1552
1784
  }
1553
1785
  /**
@@ -1569,6 +1801,7 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1569
1801
  * @returns {Promise<UUID[]>} A Promise that resolves to an array of room IDs.
1570
1802
  */
1571
1803
  async getRoomsForParticipant(entityId) {
1804
+ console.log("getRoomsForParticipant", entityId);
1572
1805
  return this.withDatabase(async () => {
1573
1806
  const result = await this.db.select({ roomId: participantTable.roomId }).from(participantTable).innerJoin(roomTable, eq(participantTable.roomId, roomTable.id)).where(and(eq(participantTable.entityId, entityId), eq(roomTable.agentId, this.agentId)));
1574
1807
  return result.map((row) => row.roomId);
@@ -1613,6 +1846,28 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1613
1846
  }
1614
1847
  });
1615
1848
  }
1849
+ async addParticipantsRoom(entityIds, roomId) {
1850
+ return this.withDatabase(async () => {
1851
+ try {
1852
+ const values = entityIds.map((id) => ({
1853
+ entityId: id,
1854
+ roomId,
1855
+ agentId: this.agentId
1856
+ }));
1857
+ await this.db.insert(participantTable).values(values).onConflictDoNothing().execute();
1858
+ logger.debug(entityIds.length, "Entities linked successfully");
1859
+ return true;
1860
+ } catch (error) {
1861
+ logger.error("Error adding participants", {
1862
+ error: error instanceof Error ? error.message : String(error),
1863
+ entityIdSample: entityIds[0],
1864
+ roomId,
1865
+ agentId: this.agentId
1866
+ });
1867
+ return false;
1868
+ }
1869
+ });
1870
+ }
1616
1871
  /**
1617
1872
  * Asynchronously removes a participant from a room in the database based on the provided parameters.
1618
1873
  * @param {UUID} entityId - The ID of the entity to remove from the room.
@@ -1656,13 +1911,13 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1656
1911
  entityId: participantTable.entityId,
1657
1912
  roomId: participantTable.roomId
1658
1913
  }).from(participantTable).where(eq(participantTable.entityId, entityId));
1659
- const entity = await this.getEntityById(entityId);
1660
- if (!entity) {
1914
+ const entities = await this.getEntityByIds([entityId]);
1915
+ if (!entities || !entities.length) {
1661
1916
  return [];
1662
1917
  }
1663
1918
  return result.map((row) => ({
1664
1919
  id: row.id,
1665
- entity
1920
+ entity: entities[0]
1666
1921
  }));
1667
1922
  });
1668
1923
  }
@@ -1825,39 +2080,28 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1825
2080
  */
1826
2081
  async getRelationships(params) {
1827
2082
  return this.withDatabase(async () => {
1828
- try {
1829
- let query = this.db.select().from(relationshipTable).where(
1830
- and(
1831
- or(
1832
- eq(relationshipTable.sourceEntityId, params.entityId),
1833
- eq(relationshipTable.targetEntityId, params.entityId)
1834
- ),
1835
- eq(relationshipTable.agentId, this.agentId)
1836
- )
1837
- );
1838
- if (params.tags && params.tags.length > 0) {
1839
- const tagParams = params.tags.map((tag) => `'${tag.replace(/'/g, "''")}'`).join(", ");
1840
- query = query.where(
1841
- sql12`${relationshipTable.tags} @> ARRAY[${sql12.raw(tagParams)}]::text[]`
1842
- );
1843
- }
1844
- const results = await query;
1845
- return results.map((result) => ({
1846
- id: result.id,
1847
- sourceEntityId: result.sourceEntityId,
1848
- targetEntityId: result.targetEntityId,
1849
- agentId: result.agentId,
1850
- tags: result.tags || [],
1851
- metadata: result.metadata || {},
1852
- createdAt: result.createdAt?.toString()
1853
- }));
1854
- } catch (error) {
1855
- logger.error("Error getting relationships:", {
1856
- error: error instanceof Error ? error.message : String(error),
1857
- params
1858
- });
1859
- return [];
1860
- }
2083
+ const conditions = [
2084
+ or(
2085
+ eq(relationshipTable.sourceEntityId, params.entityId),
2086
+ eq(relationshipTable.targetEntityId, params.entityId)
2087
+ ),
2088
+ eq(relationshipTable.agentId, this.agentId),
2089
+ ...params.tags && params.tags.length > 0 ? [
2090
+ sql13`${relationshipTable.tags} @> ARRAY[${sql13.raw(
2091
+ params.tags.map((tag) => `'${tag.replace(/'/g, "''")}'`).join(", ")
2092
+ )}]::text[]`
2093
+ ] : []
2094
+ ];
2095
+ const results = await this.db.select().from(relationshipTable).where(and(...conditions));
2096
+ return results.map((row) => ({
2097
+ id: row.id,
2098
+ sourceEntityId: row.sourceEntityId,
2099
+ targetEntityId: row.targetEntityId,
2100
+ agentId: row.agentId,
2101
+ tags: row.tags || [],
2102
+ metadata: row.metadata || {},
2103
+ createdAt: row.createdAt?.toString()
2104
+ }));
1861
2105
  });
1862
2106
  }
1863
2107
  /**
@@ -1944,7 +2188,8 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1944
2188
  const newWorldId = world.id || v4();
1945
2189
  await this.db.insert(worldTable).values({
1946
2190
  ...world,
1947
- id: newWorldId
2191
+ id: newWorldId,
2192
+ name: world.name || ""
1948
2193
  });
1949
2194
  return newWorldId;
1950
2195
  });
@@ -1996,6 +2241,9 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1996
2241
  * @returns {Promise<UUID>} A Promise that resolves to the ID of the created task.
1997
2242
  */
1998
2243
  async createTask(task) {
2244
+ if (!task.worldId) {
2245
+ throw new Error("worldId is required");
2246
+ }
1999
2247
  return this.withRetry(async () => {
2000
2248
  return this.withDatabase(async () => {
2001
2249
  const now = /* @__PURE__ */ new Date();
@@ -2012,35 +2260,37 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
2012
2260
  updatedAt: now,
2013
2261
  agentId: this.agentId
2014
2262
  };
2015
- const result = await this.db.insert(taskTable).values(values).returning({ id: taskTable.id });
2263
+ const result = await this.db.insert(taskTable).values(values).returning();
2016
2264
  return result[0].id;
2017
2265
  });
2018
2266
  });
2019
2267
  }
2020
2268
  /**
2021
2269
  * Asynchronously retrieves tasks based on specified parameters.
2022
- * @param params Object containing optional roomId and tags to filter tasks
2270
+ * @param params Object containing optional roomId, tags, and entityId to filter tasks
2023
2271
  * @returns Promise resolving to an array of Task objects
2024
2272
  */
2025
2273
  async getTasks(params) {
2026
2274
  return this.withRetry(async () => {
2027
2275
  return this.withDatabase(async () => {
2028
- let query = this.db.select().from(taskTable).where(eq(taskTable.agentId, this.agentId));
2029
- if (params.roomId) {
2030
- query = query.where(eq(taskTable.roomId, params.roomId));
2031
- }
2032
- if (params.tags && params.tags.length > 0) {
2033
- const tagParams = params.tags.map((tag) => `'${tag.replace(/'/g, "''")}'`).join(", ");
2034
- query = query.where(sql12`${taskTable.tags} @> ARRAY[${sql12.raw(tagParams)}]::text[]`);
2035
- }
2036
- const result = await query;
2276
+ const result = await this.db.select().from(taskTable).where(
2277
+ and(
2278
+ eq(taskTable.agentId, this.agentId),
2279
+ ...params.roomId ? [eq(taskTable.roomId, params.roomId)] : [],
2280
+ ...params.tags && params.tags.length > 0 ? [
2281
+ sql13`${taskTable.tags} @> ARRAY[${sql13.raw(
2282
+ params.tags.map((t) => `'${t.replace(/'/g, "''")}'`).join(", ")
2283
+ )}]::text[]`
2284
+ ] : []
2285
+ )
2286
+ );
2037
2287
  return result.map((row) => ({
2038
2288
  id: row.id,
2039
2289
  name: row.name,
2040
- description: row.description,
2290
+ description: row.description ?? "",
2041
2291
  roomId: row.roomId,
2042
2292
  worldId: row.worldId,
2043
- tags: row.tags,
2293
+ tags: row.tags || [],
2044
2294
  metadata: row.metadata
2045
2295
  }));
2046
2296
  });
@@ -2058,7 +2308,7 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
2058
2308
  return result.map((row) => ({
2059
2309
  id: row.id,
2060
2310
  name: row.name,
2061
- description: row.description,
2311
+ description: row.description ?? "",
2062
2312
  roomId: row.roomId,
2063
2313
  worldId: row.worldId,
2064
2314
  tags: row.tags || [],
@@ -2083,7 +2333,7 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
2083
2333
  return {
2084
2334
  id: row.id,
2085
2335
  name: row.name,
2086
- description: row.description,
2336
+ description: row.description ?? "",
2087
2337
  roomId: row.roomId,
2088
2338
  worldId: row.worldId,
2089
2339
  tags: row.tags || [],
@@ -2133,70 +2383,53 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
2133
2383
  * @returns Promise resolving when the deletion is complete
2134
2384
  */
2135
2385
  async deleteTask(id) {
2136
- await this.withRetry(async () => {
2137
- await this.withDatabase(async () => {
2138
- await this.db.delete(taskTable).where(and(eq(taskTable.id, id), eq(taskTable.agentId, this.agentId)));
2139
- });
2386
+ return this.withDatabase(async () => {
2387
+ await this.db.delete(taskTable).where(eq(taskTable.id, id));
2140
2388
  });
2141
2389
  }
2142
- /**
2143
- * Asynchronously retrieves group chat memories from all rooms under a given server.
2144
- * It fetches all room IDs associated with the `serverId`, then retrieves memories
2145
- * from those rooms in descending order (latest to oldest), with an optional count limit.
2146
- *
2147
- * @param {Object} params - Parameters for fetching memories.
2148
- * @param {UUID} params.serverId - The server ID to fetch memories for.
2149
- * @param {number} [params.count] - The maximum number of memories to retrieve.
2150
- * @returns {Promise<Memory[]>} - A promise that resolves to an array of memory objects.
2151
- */
2152
- async getMemoriesByServerId(params) {
2390
+ async getMemoriesByWorldId(params) {
2153
2391
  return this.withDatabase(async () => {
2154
- const roomIdsResult = await this.db.select({ roomId: roomTable.id }).from(roomTable).where(eq(roomTable.serverId, params.serverId));
2155
- if (roomIdsResult.length === 0) return [];
2156
- const roomIds = roomIdsResult.map((row) => row.roomId);
2157
- const query = this.db.select({
2158
- memory: memoryTable,
2159
- embedding: embeddingTable[this.embeddingDimension]
2160
- }).from(memoryTable).leftJoin(embeddingTable, eq(embeddingTable.memoryId, memoryTable.id)).where(inArray(memoryTable.roomId, roomIds)).orderBy(desc(memoryTable.createdAt));
2161
- const rows = params.count ? await query.limit(params.count) : await query;
2162
- return rows.map((row) => ({
2163
- id: row.memory.id,
2164
- type: row.memory.type,
2165
- createdAt: row.memory.createdAt,
2166
- content: typeof row.memory.content === "string" ? JSON.parse(row.memory.content) : row.memory.content,
2167
- entityId: row.memory.entityId,
2168
- agentId: row.memory.agentId,
2169
- roomId: row.memory.roomId,
2170
- unique: row.memory.unique,
2171
- embedding: row.embedding ?? void 0
2172
- }));
2392
+ const rooms = await this.db.select({ id: roomTable.id }).from(roomTable).where(and(eq(roomTable.worldId, params.worldId), eq(roomTable.agentId, this.agentId)));
2393
+ if (rooms.length === 0) {
2394
+ return [];
2395
+ }
2396
+ const roomIds = rooms.map((room) => room.id);
2397
+ const memories = await this.getMemoriesByRoomIds({
2398
+ roomIds,
2399
+ tableName: params.tableName || "messages",
2400
+ limit: params.count
2401
+ });
2402
+ return memories;
2173
2403
  });
2174
2404
  }
2175
- /**
2176
- * Asynchronously deletes all rooms associated with a specific serverId.
2177
- * @param {UUID} serverId - The server ID to delete rooms for.
2178
- * @returns {Promise<void>} A Promise that resolves when the rooms are deleted.
2179
- */
2180
- async deleteRoomsByServerId(serverId) {
2405
+ async deleteRoomsByWorldId(worldId) {
2181
2406
  return this.withDatabase(async () => {
2182
- await this.db.transaction(async (tx) => {
2183
- const roomIdsResult = await tx.select({ roomId: roomTable.id }).from(roomTable).where(eq(roomTable.serverId, serverId));
2184
- if (roomIdsResult.length === 0) return;
2185
- const roomIds = roomIdsResult.map((row) => row.roomId);
2186
- await tx.delete(embeddingTable).where(
2187
- inArray(
2188
- embeddingTable.memoryId,
2189
- tx.select({ id: memoryTable.id }).from(memoryTable).where(inArray(memoryTable.roomId, roomIds))
2190
- )
2407
+ const rooms = await this.db.select({ id: roomTable.id }).from(roomTable).where(and(eq(roomTable.worldId, worldId), eq(roomTable.agentId, this.agentId)));
2408
+ if (rooms.length === 0) {
2409
+ logger.debug(
2410
+ `No rooms found for worldId ${worldId} and agentId ${this.agentId} to delete.`
2191
2411
  );
2192
- await tx.delete(memoryTable).where(inArray(memoryTable.roomId, roomIds));
2193
- await tx.delete(participantTable).where(inArray(participantTable.roomId, roomIds));
2194
- await tx.delete(logTable).where(inArray(logTable.roomId, roomIds));
2195
- await tx.delete(roomTable).where(inArray(roomTable.id, roomIds));
2196
- });
2197
- logger.debug("Rooms and related logs deleted successfully for server:", {
2198
- serverId
2199
- });
2412
+ return;
2413
+ }
2414
+ const roomIds = rooms.map((room) => room.id);
2415
+ if (roomIds.length > 0) {
2416
+ await this.db.delete(logTable).where(inArray(logTable.roomId, roomIds));
2417
+ logger.debug(`Deleted logs for ${roomIds.length} rooms in world ${worldId}.`);
2418
+ await this.db.delete(participantTable).where(inArray(participantTable.roomId, roomIds));
2419
+ logger.debug(`Deleted participants for ${roomIds.length} rooms in world ${worldId}.`);
2420
+ const memoriesInRooms = await this.db.select({ id: memoryTable.id }).from(memoryTable).where(inArray(memoryTable.roomId, roomIds));
2421
+ const memoryIdsInRooms = memoriesInRooms.map((m) => m.id);
2422
+ if (memoryIdsInRooms.length > 0) {
2423
+ await this.db.delete(embeddingTable).where(inArray(embeddingTable.memoryId, memoryIdsInRooms));
2424
+ logger.debug(
2425
+ `Deleted embeddings for ${memoryIdsInRooms.length} memories in world ${worldId}.`
2426
+ );
2427
+ await this.db.delete(memoryTable).where(inArray(memoryTable.id, memoryIdsInRooms));
2428
+ logger.debug(`Deleted ${memoryIdsInRooms.length} memories in world ${worldId}.`);
2429
+ }
2430
+ await this.db.delete(roomTable).where(inArray(roomTable.id, roomIds));
2431
+ logger.debug(`Deleted ${roomIds.length} rooms for worldId ${worldId}.`);
2432
+ }
2200
2433
  });
2201
2434
  }
2202
2435
  };
@@ -2251,6 +2484,14 @@ var PgliteDatabaseAdapter = class extends BaseDrizzleAdapter {
2251
2484
  async close() {
2252
2485
  await this.manager.close();
2253
2486
  }
2487
+ /**
2488
+ * Asynchronously retrieves the connection from the manager.
2489
+ *
2490
+ * @returns {Promise<PGlite>} A Promise that resolves with the connection.
2491
+ */
2492
+ async getConnection() {
2493
+ return this.manager.getConnection();
2494
+ }
2254
2495
  };
2255
2496
 
2256
2497
  // src/pg/adapter.ts
@@ -2313,6 +2554,14 @@ var PgDatabaseAdapter = class extends BaseDrizzleAdapter {
2313
2554
  async close() {
2314
2555
  await this.manager.close();
2315
2556
  }
2557
+ /**
2558
+ * Asynchronously retrieves the connection from the manager.
2559
+ *
2560
+ * @returns {Promise<PgPool>} A Promise that resolves with the connection.
2561
+ */
2562
+ async getConnection() {
2563
+ return this.manager.getConnection();
2564
+ }
2316
2565
  };
2317
2566
 
2318
2567
  // src/index.ts
@@ -2322,17 +2571,8 @@ if (!globalSymbols[GLOBAL_SINGLETONS]) {
2322
2571
  globalSymbols[GLOBAL_SINGLETONS] = {};
2323
2572
  }
2324
2573
  var globalSingletons = globalSymbols[GLOBAL_SINGLETONS];
2325
- function expandTildePath(filepath) {
2326
- if (filepath && typeof filepath === "string" && filepath.startsWith("~")) {
2327
- return filepath.replace(/^~/, os.homedir());
2328
- }
2329
- return filepath;
2330
- }
2331
- __name(expandTildePath, "expandTildePath");
2332
2574
  function createDatabaseAdapter(config, agentId) {
2333
- if (config.dataDir) {
2334
- config.dataDir = expandTildePath(config.dataDir);
2335
- }
2575
+ const dataDir = resolvePgliteDir(config.dataDir);
2336
2576
  if (config.postgresUrl) {
2337
2577
  if (!globalSingletons.postgresConnectionManager) {
2338
2578
  globalSingletons.postgresConnectionManager = new PostgresConnectionManager(
@@ -2341,7 +2581,6 @@ function createDatabaseAdapter(config, agentId) {
2341
2581
  }
2342
2582
  return new PgDatabaseAdapter(agentId, globalSingletons.postgresConnectionManager);
2343
2583
  }
2344
- const dataDir = config.dataDir ?? "./elizadb";
2345
2584
  if (!globalSingletons.pgLiteClientManager) {
2346
2585
  globalSingletons.pgLiteClientManager = new PGliteClientManager({ dataDir });
2347
2586
  }
@@ -2353,7 +2592,7 @@ var sqlPlugin = {
2353
2592
  description: "SQL database adapter plugin using Drizzle ORM",
2354
2593
  init: /* @__PURE__ */ __name(async (_, runtime) => {
2355
2594
  const config = {
2356
- dataDir: runtime.getSetting("PGLITE_DATA_DIR") ?? "./pglite",
2595
+ dataDir: resolvePgliteDir(runtime.getSetting("PGLITE_DATA_DIR")),
2357
2596
  postgresUrl: runtime.getSetting("POSTGRES_URL")
2358
2597
  };
2359
2598
  try {