@elizaos/plugin-sql 1.0.0-beta.48 → 1.0.0-beta.49

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
@@ -18,19 +18,7 @@ import {
18
18
  logger,
19
19
  stringToUuid
20
20
  } from "@elizaos/core";
21
- import {
22
- and,
23
- cosineDistance,
24
- count,
25
- desc,
26
- eq,
27
- gte,
28
- inArray,
29
- lte,
30
- or,
31
- sql as sql12,
32
- not
33
- } from "drizzle-orm";
21
+ import { and, cosineDistance, count, desc, eq, gte, inArray, lte, or, sql as sql12, not } from "drizzle-orm";
34
22
  import { v4 } from "uuid";
35
23
 
36
24
  // src/schema/embedding.ts
@@ -89,18 +77,18 @@ var agentTable = pgTable(
89
77
  createdAt: numberTimestamp("createdAt").default(sql`now()`).notNull(),
90
78
  updatedAt: numberTimestamp("updatedAt").default(sql`now()`).notNull(),
91
79
  // Character
92
- name: text("name"),
80
+ name: text("name").notNull(),
93
81
  username: text("username"),
94
- system: text("system"),
82
+ system: text("system").notNull(),
95
83
  bio: jsonb("bio").$type().notNull(),
96
- messageExamples: jsonb("message_examples").$type().default(sql`'[]'::jsonb`),
97
- postExamples: jsonb("post_examples").$type().default(sql`'[]'::jsonb`),
98
- topics: jsonb("topics").$type().default(sql`'[]'::jsonb`),
99
- adjectives: jsonb("adjectives").$type().default(sql`'[]'::jsonb`),
100
- knowledge: jsonb("knowledge").$type().default(sql`'[]'::jsonb`),
101
- plugins: jsonb("plugins").$type().default(sql`'[]'::jsonb`),
102
- settings: jsonb("settings").$type().default(sql`'{}'::jsonb`),
103
- style: jsonb("style").$type().default(sql`'{}'::jsonb`)
84
+ messageExamples: jsonb("message_examples").$type().default(sql`'[]'::jsonb`).notNull(),
85
+ postExamples: jsonb("post_examples").$type().default(sql`'[]'::jsonb`).notNull(),
86
+ topics: jsonb("topics").$type().default(sql`'[]'::jsonb`).notNull(),
87
+ adjectives: jsonb("adjectives").$type().default(sql`'[]'::jsonb`).notNull(),
88
+ knowledge: jsonb("knowledge").$type().default(sql`'[]'::jsonb`).notNull(),
89
+ plugins: jsonb("plugins").$type().default(sql`'[]'::jsonb`).notNull(),
90
+ settings: jsonb("settings").$type().default(sql`'{}'::jsonb`).notNull(),
91
+ style: jsonb("style").$type().default(sql`'{}'::jsonb`).notNull()
104
92
  },
105
93
  (table) => {
106
94
  return {
@@ -120,8 +108,8 @@ var entityTable = pgTable2(
120
108
  onDelete: "cascade"
121
109
  }),
122
110
  createdAt: numberTimestamp("createdAt").default(sql2`now()`).notNull(),
123
- names: text2("names").array().default(sql2`'{}'::text[]`),
124
- metadata: jsonb2("metadata").default(sql2`'{}'::jsonb`)
111
+ names: text2("names").array().default(sql2`'{}'::text[]`).notNull(),
112
+ metadata: jsonb2("metadata").default(sql2`'{}'::jsonb`).notNull()
125
113
  },
126
114
  (table) => {
127
115
  return {
@@ -322,7 +310,7 @@ var logTable = pgTable9(
322
310
  entityId: uuid9("entityId").notNull().references(() => entityTable.id),
323
311
  body: jsonb8("body").notNull(),
324
312
  type: text8("type").notNull(),
325
- roomId: uuid9("roomId").notNull().references(() => roomTable.id)
313
+ roomId: uuid9("roomId").notNull().references(() => roomTable.id, { onDelete: "cascade" })
326
314
  },
327
315
  (table) => [
328
316
  foreignKey3({
@@ -485,15 +473,17 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
485
473
  throw new Error("Agent name is required");
486
474
  }
487
475
  const agents = await this.getAgents();
488
- const existingAgent = agents.find(
489
- (a) => a.name === agent.name
490
- );
491
- if (existingAgent) {
476
+ const existingAgentId = agents.find((a) => a.name === agent.name)?.id;
477
+ if (existingAgentId) {
478
+ const existingAgent = await this.getAgent(existingAgentId);
492
479
  return existingAgent;
493
480
  }
494
- agent.id = stringToUuid(agent.name ?? v4());
495
- await this.createAgent(agent);
496
- return agent;
481
+ const newAgent = {
482
+ ...agent,
483
+ id: stringToUuid(agent.name)
484
+ };
485
+ await this.createAgent(newAgent);
486
+ return newAgent;
497
487
  }
498
488
  /**
499
489
  * Asynchronously ensures that the given embedding dimension is valid for the agent.
@@ -519,20 +509,31 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
519
509
  */
520
510
  async getAgent(agentId) {
521
511
  return this.withDatabase(async () => {
522
- const result = await this.db.select().from(agentTable).where(eq(agentTable.id, agentId)).limit(1);
523
- if (result.length === 0) return null;
524
- return result[0];
512
+ const rows = await this.db.select().from(agentTable).where(eq(agentTable.id, agentId)).limit(1);
513
+ if (rows.length === 0) return null;
514
+ const row = rows[0];
515
+ return {
516
+ ...row,
517
+ id: row.id
518
+ };
525
519
  });
526
520
  }
527
521
  /**
528
522
  * Asynchronously retrieves a list of agents from the database.
529
523
  *
530
- * @returns {Promise<Agent[]>} A Promise that resolves to an array of Agent objects.
524
+ * @returns {Promise<Partial<Agent>[]>} A Promise that resolves to an array of Agent objects.
531
525
  */
532
526
  async getAgents() {
533
527
  return this.withDatabase(async () => {
534
- const result = await this.db.select().from(agentTable);
535
- return result;
528
+ const rows = await this.db.select({
529
+ id: agentTable.id,
530
+ name: agentTable.name,
531
+ bio: agentTable.bio
532
+ }).from(agentTable);
533
+ return rows.map((row) => ({
534
+ ...row,
535
+ id: row.id
536
+ }));
536
537
  });
537
538
  }
538
539
  /**
@@ -849,11 +850,17 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
849
850
  const result = await this.db.select({
850
851
  entity: entityTable,
851
852
  components: componentTable
852
- }).from(entityTable).leftJoin(componentTable, eq(componentTable.entityId, entityTable.id)).where(eq(entityTable.id, entityId));
853
+ }).from(entityTable).leftJoin(componentTable, eq(componentTable.entityId, entityTable.id)).where(eq(entityTable.id, entityId)).limit(1);
853
854
  if (result.length === 0) return null;
854
855
  const entity = result[0].entity;
855
- entity.components = result.filter((row) => row.components).map((row) => row.components);
856
- return entity;
856
+ const components = result.map((r) => r.components).filter((c) => c !== null);
857
+ return {
858
+ ...entity,
859
+ id: entity.id,
860
+ agentId: entity.agentId,
861
+ metadata: entity.metadata,
862
+ components
863
+ };
857
864
  });
858
865
  }
859
866
  /**
@@ -882,6 +889,9 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
882
889
  if (!entitiesByIdMap.has(entityId)) {
883
890
  const entity = {
884
891
  ...row.entity,
892
+ id: stringToUuid(entityId),
893
+ agentId: stringToUuid(row.entity.agentId),
894
+ metadata: row.entity.metadata,
885
895
  components: includeComponents ? [] : void 0
886
896
  };
887
897
  entitiesByIdMap.set(entityId, entity);
@@ -969,7 +979,18 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
969
979
  conditions.push(eq(componentTable.sourceEntityId, sourceEntityId));
970
980
  }
971
981
  const result = await this.db.select().from(componentTable).where(and(...conditions));
972
- return result.length > 0 ? result[0] : null;
982
+ if (result.length === 0) return null;
983
+ const component = result[0];
984
+ return {
985
+ ...component,
986
+ id: component.id,
987
+ entityId: component.entityId,
988
+ agentId: component.agentId,
989
+ roomId: component.roomId,
990
+ worldId: component.worldId ?? "",
991
+ sourceEntityId: component.sourceEntityId ?? "",
992
+ data: component.data
993
+ };
973
994
  });
974
995
  }
975
996
  /**
@@ -994,10 +1015,23 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
994
1015
  type: componentTable.type,
995
1016
  data: componentTable.data,
996
1017
  worldId: componentTable.worldId,
1018
+ agentId: componentTable.agentId,
1019
+ roomId: componentTable.roomId,
997
1020
  sourceEntityId: componentTable.sourceEntityId,
998
1021
  createdAt: componentTable.createdAt
999
1022
  }).from(componentTable).where(and(...conditions));
1000
- return result;
1023
+ if (result.length === 0) return [];
1024
+ const components = result.map((component) => ({
1025
+ ...component,
1026
+ id: component.id,
1027
+ entityId: component.entityId,
1028
+ agentId: component.agentId,
1029
+ roomId: component.roomId,
1030
+ worldId: component.worldId ?? "",
1031
+ sourceEntityId: component.sourceEntityId ?? "",
1032
+ data: component.data
1033
+ }));
1034
+ return components;
1001
1035
  });
1002
1036
  }
1003
1037
  /**
@@ -1220,7 +1254,7 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1220
1254
  AND m.content->>${opts.query_field_sub_name} IS NOT NULL
1221
1255
  ),
1222
1256
  embedded_text AS (
1223
- SELECT
1257
+ SELECT
1224
1258
  ct.content_text,
1225
1259
  COALESCE(
1226
1260
  e.dim_384,
@@ -1310,7 +1344,16 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1310
1344
  type ? eq(logTable.type, type) : void 0
1311
1345
  )
1312
1346
  ).orderBy(desc(logTable.createdAt)).limit(count2 ?? 10).offset(offset ?? 0);
1313
- return result;
1347
+ const logs = result.map((log) => ({
1348
+ ...log,
1349
+ id: log.id,
1350
+ entityId: log.entityId,
1351
+ roomId: log.roomId,
1352
+ body: log.body,
1353
+ createdAt: new Date(log.createdAt)
1354
+ }));
1355
+ if (logs.length === 0) return [];
1356
+ return logs;
1314
1357
  });
1315
1358
  }
1316
1359
  /**
@@ -1579,7 +1622,7 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1579
1622
  sql12`${memoryTable.metadata}->>'documentId' = ${documentId}`
1580
1623
  )
1581
1624
  );
1582
- return fragments;
1625
+ return fragments.map((f) => ({ id: f.id }));
1583
1626
  }
1584
1627
  /**
1585
1628
  * Asynchronously deletes all memories from the database based on the provided parameters.
@@ -1590,21 +1633,21 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1590
1633
  async deleteAllMemories(roomId, tableName) {
1591
1634
  return this.withDatabase(async () => {
1592
1635
  await this.db.transaction(async (tx) => {
1593
- const memoryIds = await tx.select({ id: memoryTable.id }).from(memoryTable).where(and(eq(memoryTable.roomId, roomId), eq(memoryTable.type, tableName)));
1594
- if (memoryIds.length > 0) {
1595
- await tx.delete(embeddingTable).where(
1596
- inArray(
1597
- embeddingTable.memoryId,
1598
- memoryIds.map((m) => m.id)
1599
- )
1600
- );
1601
- await tx.delete(memoryTable).where(and(eq(memoryTable.roomId, roomId), eq(memoryTable.type, tableName)));
1636
+ const rows = await tx.select({ id: memoryTable.id }).from(memoryTable).where(and(eq(memoryTable.roomId, roomId), eq(memoryTable.type, tableName)));
1637
+ const ids = rows.map((r) => r.id);
1638
+ logger.debug("[deleteAllMemories] memory IDs to delete:", { roomId, tableName, ids });
1639
+ if (ids.length === 0) {
1640
+ return;
1602
1641
  }
1642
+ await Promise.all(
1643
+ ids.map(async (memoryId) => {
1644
+ await this.deleteMemoryFragments(tx, memoryId);
1645
+ await tx.delete(embeddingTable).where(eq(embeddingTable.memoryId, memoryId));
1646
+ })
1647
+ );
1648
+ await tx.delete(memoryTable).where(and(eq(memoryTable.roomId, roomId), eq(memoryTable.type, tableName)));
1603
1649
  });
1604
- logger.debug("All memories removed successfully:", {
1605
- roomId,
1606
- tableName
1607
- });
1650
+ logger.debug("All memories removed successfully:", { roomId, tableName });
1608
1651
  });
1609
1652
  }
1610
1653
  /**
@@ -1642,7 +1685,16 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1642
1685
  source: roomTable.source
1643
1686
  }).from(roomTable).where(and(eq(roomTable.id, roomId), eq(roomTable.agentId, this.agentId))).limit(1);
1644
1687
  if (result.length === 0) return null;
1645
- return result[0];
1688
+ const room = result[0];
1689
+ return {
1690
+ ...room,
1691
+ id: room.id,
1692
+ agentId: room.agentId,
1693
+ serverId: room.serverId,
1694
+ worldId: room.worldId,
1695
+ channelId: room.channelId,
1696
+ type: room.type
1697
+ };
1646
1698
  });
1647
1699
  }
1648
1700
  /**
@@ -1653,7 +1705,19 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1653
1705
  async getRooms(worldId) {
1654
1706
  return this.withDatabase(async () => {
1655
1707
  const result = await this.db.select().from(roomTable).where(eq(roomTable.worldId, worldId));
1656
- return result;
1708
+ const rooms = result.map((room) => ({
1709
+ ...room,
1710
+ id: room.id,
1711
+ name: room.name ?? void 0,
1712
+ agentId: room.agentId,
1713
+ serverId: room.serverId,
1714
+ worldId: room.worldId,
1715
+ channelId: room.channelId,
1716
+ type: room.type,
1717
+ metadata: room.metadata
1718
+ }));
1719
+ if (rooms.length === 0) return [];
1720
+ return rooms;
1657
1721
  });
1658
1722
  }
1659
1723
  /**
@@ -1973,39 +2037,28 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
1973
2037
  */
1974
2038
  async getRelationships(params) {
1975
2039
  return this.withDatabase(async () => {
1976
- try {
1977
- let query = this.db.select().from(relationshipTable).where(
1978
- and(
1979
- or(
1980
- eq(relationshipTable.sourceEntityId, params.entityId),
1981
- eq(relationshipTable.targetEntityId, params.entityId)
1982
- ),
1983
- eq(relationshipTable.agentId, this.agentId)
1984
- )
1985
- );
1986
- if (params.tags && params.tags.length > 0) {
1987
- const tagParams = params.tags.map((tag) => `'${tag.replace(/'/g, "''")}'`).join(", ");
1988
- query = query.where(
1989
- sql12`${relationshipTable.tags} @> ARRAY[${sql12.raw(tagParams)}]::text[]`
1990
- );
1991
- }
1992
- const results = await query;
1993
- return results.map((result) => ({
1994
- id: result.id,
1995
- sourceEntityId: result.sourceEntityId,
1996
- targetEntityId: result.targetEntityId,
1997
- agentId: result.agentId,
1998
- tags: result.tags || [],
1999
- metadata: result.metadata || {},
2000
- createdAt: result.createdAt?.toString()
2001
- }));
2002
- } catch (error) {
2003
- logger.error("Error getting relationships:", {
2004
- error: error instanceof Error ? error.message : String(error),
2005
- params
2006
- });
2007
- return [];
2008
- }
2040
+ const conditions = [
2041
+ or(
2042
+ eq(relationshipTable.sourceEntityId, params.entityId),
2043
+ eq(relationshipTable.targetEntityId, params.entityId)
2044
+ ),
2045
+ eq(relationshipTable.agentId, this.agentId),
2046
+ ...params.tags && params.tags.length > 0 ? [
2047
+ sql12`${relationshipTable.tags} @> ARRAY[${sql12.raw(
2048
+ params.tags.map((tag) => `'${tag.replace(/'/g, "''")}'`).join(", ")
2049
+ )}]::text[]`
2050
+ ] : []
2051
+ ];
2052
+ const results = await this.db.select().from(relationshipTable).where(and(...conditions));
2053
+ return results.map((row) => ({
2054
+ id: row.id,
2055
+ sourceEntityId: row.sourceEntityId,
2056
+ targetEntityId: row.targetEntityId,
2057
+ agentId: row.agentId,
2058
+ tags: row.tags || [],
2059
+ metadata: row.metadata || {},
2060
+ createdAt: row.createdAt?.toString()
2061
+ }));
2009
2062
  });
2010
2063
  }
2011
2064
  /**
@@ -2092,7 +2145,8 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
2092
2145
  const newWorldId = world.id || v4();
2093
2146
  await this.db.insert(worldTable).values({
2094
2147
  ...world,
2095
- id: newWorldId
2148
+ id: newWorldId,
2149
+ name: world.name || ""
2096
2150
  });
2097
2151
  return newWorldId;
2098
2152
  });
@@ -2160,7 +2214,7 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
2160
2214
  updatedAt: now,
2161
2215
  agentId: this.agentId
2162
2216
  };
2163
- const result = await this.db.insert(taskTable).values(values).returning({ id: taskTable.id });
2217
+ const result = await this.db.insert(taskTable).values(values).returning();
2164
2218
  return result[0].id;
2165
2219
  });
2166
2220
  });
@@ -2173,22 +2227,24 @@ var BaseDrizzleAdapter = class extends DatabaseAdapter {
2173
2227
  async getTasks(params) {
2174
2228
  return this.withRetry(async () => {
2175
2229
  return this.withDatabase(async () => {
2176
- let query = this.db.select().from(taskTable).where(eq(taskTable.agentId, this.agentId));
2177
- if (params.roomId) {
2178
- query = query.where(eq(taskTable.roomId, params.roomId));
2179
- }
2180
- if (params.tags && params.tags.length > 0) {
2181
- const tagParams = params.tags.map((tag) => `'${tag.replace(/'/g, "''")}'`).join(", ");
2182
- query = query.where(sql12`${taskTable.tags} @> ARRAY[${sql12.raw(tagParams)}]::text[]`);
2183
- }
2184
- const result = await query;
2230
+ const result = await this.db.select().from(taskTable).where(
2231
+ and(
2232
+ eq(taskTable.agentId, this.agentId),
2233
+ ...params.roomId ? [eq(taskTable.roomId, params.roomId)] : [],
2234
+ ...params.tags && params.tags.length > 0 ? [
2235
+ sql12`${taskTable.tags} @> ARRAY[${sql12.raw(
2236
+ params.tags.map((t) => `'${t.replace(/'/g, "''")}'`).join(", ")
2237
+ )}]::text[]`
2238
+ ] : []
2239
+ )
2240
+ );
2185
2241
  return result.map((row) => ({
2186
2242
  id: row.id,
2187
2243
  name: row.name,
2188
2244
  description: row.description,
2189
2245
  roomId: row.roomId,
2190
2246
  worldId: row.worldId,
2191
- tags: row.tags,
2247
+ tags: row.tags || [],
2192
2248
  metadata: row.metadata
2193
2249
  }));
2194
2250
  });