@elizaos/plugin-inmemorydb 2.0.3-beta.6 → 2.0.3-beta.7

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.
@@ -0,0 +1,1536 @@
1
+ // index.ts
2
+ import {
3
+ logger as logger2
4
+ } from "@elizaos/core";
5
+
6
+ // adapter.ts
7
+ import { randomUUID } from "node:crypto";
8
+ import {
9
+ DatabaseAdapter,
10
+ logger
11
+ } from "@elizaos/core";
12
+
13
+ // hnsw.ts
14
+ function cosineDistance(a, b) {
15
+ if (a.length !== b.length) {
16
+ throw new Error(`Vector dimension mismatch: ${a.length} vs ${b.length}`);
17
+ }
18
+ let dotProduct = 0;
19
+ let normA = 0;
20
+ let normB = 0;
21
+ for (let i = 0;i < a.length; i++) {
22
+ const aValue = a[i] ?? 0;
23
+ const bValue = b[i] ?? 0;
24
+ dotProduct += aValue * bValue;
25
+ normA += aValue * aValue;
26
+ normB += bValue * bValue;
27
+ }
28
+ const magnitude = Math.sqrt(normA) * Math.sqrt(normB);
29
+ if (magnitude === 0)
30
+ return 1;
31
+ return 1 - dotProduct / magnitude;
32
+ }
33
+
34
+ class EphemeralHNSW {
35
+ nodes = new Map;
36
+ entryPoint = null;
37
+ maxLevel = 0;
38
+ dimension = 0;
39
+ config;
40
+ constructor() {
41
+ this.config = {
42
+ M: 16,
43
+ efConstruction: 200,
44
+ efSearch: 50,
45
+ mL: 1 / Math.log(16)
46
+ };
47
+ }
48
+ async init(dimension) {
49
+ this.dimension = dimension;
50
+ }
51
+ getRandomLevel() {
52
+ let level = 0;
53
+ while (Math.random() < Math.exp(-level * this.config.mL) && level < 16) {
54
+ level++;
55
+ }
56
+ return level;
57
+ }
58
+ async add(id, vector) {
59
+ if (vector.length !== this.dimension) {
60
+ throw new Error(`Vector dimension mismatch: expected ${this.dimension}, got ${vector.length}`);
61
+ }
62
+ const existing = this.nodes.get(id);
63
+ if (existing) {
64
+ existing.vector = vector;
65
+ return;
66
+ }
67
+ const level = this.getRandomLevel();
68
+ const newNode = {
69
+ id,
70
+ vector,
71
+ level,
72
+ neighbors: new Map
73
+ };
74
+ for (let l = 0;l <= level; l++) {
75
+ newNode.neighbors.set(l, new Set);
76
+ }
77
+ if (this.entryPoint === null) {
78
+ this.entryPoint = id;
79
+ this.maxLevel = level;
80
+ this.nodes.set(id, newNode);
81
+ return;
82
+ }
83
+ let currentNode = this.entryPoint;
84
+ for (let l = this.maxLevel;l > level; l--) {
85
+ currentNode = this.searchLayer(vector, currentNode, 1, l)[0]?.id ?? currentNode;
86
+ }
87
+ for (let l = Math.min(level, this.maxLevel);l >= 0; l--) {
88
+ const neighbors = this.searchLayer(vector, currentNode, this.config.efConstruction, l);
89
+ const M = this.config.M;
90
+ const selectedNeighbors = neighbors.slice(0, M);
91
+ for (const neighbor of selectedNeighbors) {
92
+ const neighborSet = newNode.neighbors.get(l);
93
+ if (neighborSet) {
94
+ neighborSet.add(neighbor.id);
95
+ }
96
+ const neighborNode = this.nodes.get(neighbor.id);
97
+ if (neighborNode) {
98
+ let neighborSet2 = neighborNode.neighbors.get(l);
99
+ if (!neighborSet2) {
100
+ neighborSet2 = new Set;
101
+ neighborNode.neighbors.set(l, neighborSet2);
102
+ }
103
+ neighborSet2.add(id);
104
+ if (neighborSet2.size > M) {
105
+ const toKeep = this.selectBestNeighbors(neighborNode.vector, neighborSet2, M);
106
+ neighborNode.neighbors.set(l, new Set(toKeep.map((n) => n.id)));
107
+ }
108
+ }
109
+ }
110
+ if (neighbors.length > 0) {
111
+ const closestNeighbor = neighbors[0];
112
+ if (closestNeighbor) {
113
+ currentNode = closestNeighbor.id;
114
+ }
115
+ }
116
+ }
117
+ this.nodes.set(id, newNode);
118
+ if (level > this.maxLevel) {
119
+ this.maxLevel = level;
120
+ this.entryPoint = id;
121
+ }
122
+ }
123
+ searchLayer(query, entryId, ef, level) {
124
+ const visited = new Set([entryId]);
125
+ const entryNode = this.nodes.get(entryId);
126
+ if (!entryNode)
127
+ return [];
128
+ const entryDist = cosineDistance(query, entryNode.vector);
129
+ const candidates = [
130
+ { id: entryId, distance: entryDist }
131
+ ];
132
+ const results = [{ id: entryId, distance: entryDist }];
133
+ while (candidates.length > 0) {
134
+ candidates.sort((a, b) => a.distance - b.distance);
135
+ const current = candidates.shift();
136
+ if (!current)
137
+ break;
138
+ results.sort((a, b) => b.distance - a.distance);
139
+ const furthestResult = results[0];
140
+ if (!furthestResult)
141
+ break;
142
+ if (current.distance > furthestResult.distance) {
143
+ break;
144
+ }
145
+ const currentNode = this.nodes.get(current.id);
146
+ if (!currentNode)
147
+ continue;
148
+ const neighbors = currentNode.neighbors.get(level);
149
+ if (!neighbors)
150
+ continue;
151
+ for (const neighborId of neighbors) {
152
+ if (visited.has(neighborId))
153
+ continue;
154
+ visited.add(neighborId);
155
+ const neighborNode = this.nodes.get(neighborId);
156
+ if (!neighborNode)
157
+ continue;
158
+ const dist = cosineDistance(query, neighborNode.vector);
159
+ if (results.length < ef || dist < furthestResult.distance) {
160
+ candidates.push({ id: neighborId, distance: dist });
161
+ results.push({ id: neighborId, distance: dist });
162
+ if (results.length > ef) {
163
+ results.sort((a, b) => b.distance - a.distance);
164
+ results.pop();
165
+ }
166
+ }
167
+ }
168
+ }
169
+ results.sort((a, b) => a.distance - b.distance);
170
+ return results;
171
+ }
172
+ selectBestNeighbors(nodeVector, neighborIds, M) {
173
+ const neighbors = [];
174
+ for (const id of neighborIds) {
175
+ const node = this.nodes.get(id);
176
+ if (node) {
177
+ neighbors.push({
178
+ id,
179
+ distance: cosineDistance(nodeVector, node.vector)
180
+ });
181
+ }
182
+ }
183
+ neighbors.sort((a, b) => a.distance - b.distance);
184
+ return neighbors.slice(0, M);
185
+ }
186
+ async remove(id) {
187
+ const node = this.nodes.get(id);
188
+ if (!node)
189
+ return;
190
+ for (const [level, neighbors] of node.neighbors) {
191
+ for (const neighborId of neighbors) {
192
+ const neighborNode = this.nodes.get(neighborId);
193
+ if (neighborNode) {
194
+ neighborNode.neighbors.get(level)?.delete(id);
195
+ }
196
+ }
197
+ }
198
+ this.nodes.delete(id);
199
+ if (this.entryPoint === id) {
200
+ if (this.nodes.size === 0) {
201
+ this.entryPoint = null;
202
+ this.maxLevel = 0;
203
+ } else {
204
+ let maxLevel = 0;
205
+ let newEntry = null;
206
+ for (const [nodeId, n] of this.nodes) {
207
+ if (n.level >= maxLevel) {
208
+ maxLevel = n.level;
209
+ newEntry = nodeId;
210
+ }
211
+ }
212
+ this.entryPoint = newEntry;
213
+ this.maxLevel = maxLevel;
214
+ }
215
+ }
216
+ }
217
+ async search(query, k, threshold = 0.5) {
218
+ if (this.entryPoint === null || this.nodes.size === 0) {
219
+ return [];
220
+ }
221
+ if (query.length !== this.dimension) {
222
+ throw new Error(`Query dimension mismatch: expected ${this.dimension}, got ${query.length}`);
223
+ }
224
+ let currentNode = this.entryPoint;
225
+ for (let l = this.maxLevel;l > 0; l--) {
226
+ const closest = this.searchLayer(query, currentNode, 1, l);
227
+ const closestNode = closest[0];
228
+ if (closestNode) {
229
+ currentNode = closestNode.id;
230
+ }
231
+ }
232
+ const results = this.searchLayer(query, currentNode, Math.max(k, this.config.efSearch), 0);
233
+ return results.slice(0, k).filter((r) => 1 - r.distance >= threshold).map((r) => ({
234
+ id: r.id,
235
+ distance: r.distance,
236
+ similarity: 1 - r.distance
237
+ }));
238
+ }
239
+ async clear() {
240
+ this.nodes.clear();
241
+ this.entryPoint = null;
242
+ this.maxLevel = 0;
243
+ }
244
+ size() {
245
+ return this.nodes.size;
246
+ }
247
+ }
248
+
249
+ // types.ts
250
+ var COLLECTIONS = {
251
+ AGENTS: "agents",
252
+ ENTITIES: "entities",
253
+ MEMORIES: "memories",
254
+ ROOMS: "rooms",
255
+ WORLDS: "worlds",
256
+ COMPONENTS: "components",
257
+ RELATIONSHIPS: "relationships",
258
+ PARTICIPANTS: "participants",
259
+ TASKS: "tasks",
260
+ CACHE: "cache",
261
+ LOGS: "logs",
262
+ EMBEDDINGS: "embeddings",
263
+ PAIRING_REQUESTS: "pairing_requests",
264
+ PAIRING_ALLOWLIST: "pairing_allowlist"
265
+ };
266
+
267
+ // adapter.ts
268
+ function toMemory(stored) {
269
+ return {
270
+ id: stored.id,
271
+ entityId: stored.entityId,
272
+ agentId: stored.agentId,
273
+ createdAt: stored.createdAt,
274
+ content: stored.content,
275
+ embedding: stored.embedding,
276
+ roomId: stored.roomId,
277
+ worldId: stored.worldId,
278
+ unique: stored.unique,
279
+ similarity: stored.similarity,
280
+ metadata: stored.metadata
281
+ };
282
+ }
283
+ function relationshipFromStored(r, fallbackAgentId) {
284
+ return {
285
+ id: r.id,
286
+ sourceEntityId: r.sourceEntityId,
287
+ targetEntityId: r.targetEntityId,
288
+ agentId: r.agentId ?? fallbackAgentId,
289
+ tags: r.tags ?? [],
290
+ metadata: r.metadata ?? {},
291
+ createdAt: r.createdAt
292
+ };
293
+ }
294
+ function applyPatchOp(target, op) {
295
+ if (!op.path)
296
+ return;
297
+ const parts = op.path.split(".");
298
+ const last = parts.pop();
299
+ if (last === undefined)
300
+ return;
301
+ let parent = target;
302
+ for (const segment of parts) {
303
+ const next = parent[segment];
304
+ if (next === null || typeof next !== "object") {
305
+ const created = {};
306
+ parent[segment] = created;
307
+ parent = created;
308
+ } else {
309
+ parent = next;
310
+ }
311
+ }
312
+ switch (op.op) {
313
+ case "set":
314
+ parent[last] = op.value;
315
+ break;
316
+ case "remove":
317
+ delete parent[last];
318
+ break;
319
+ case "push": {
320
+ const existing = parent[last];
321
+ if (Array.isArray(existing)) {
322
+ existing.push(op.value);
323
+ } else {
324
+ parent[last] = [op.value];
325
+ }
326
+ break;
327
+ }
328
+ case "increment": {
329
+ const existing = parent[last];
330
+ const delta = typeof op.value === "number" ? op.value : 1;
331
+ parent[last] = typeof existing === "number" ? existing + delta : delta;
332
+ break;
333
+ }
334
+ }
335
+ }
336
+ function levenshtein(a, b) {
337
+ if (a === b)
338
+ return 0;
339
+ if (a.length === 0)
340
+ return b.length;
341
+ if (b.length === 0)
342
+ return a.length;
343
+ const prev = new Array(b.length + 1);
344
+ const curr = new Array(b.length + 1);
345
+ for (let j = 0;j <= b.length; j++)
346
+ prev[j] = j;
347
+ for (let i = 1;i <= a.length; i++) {
348
+ curr[0] = i;
349
+ for (let j = 1;j <= b.length; j++) {
350
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
351
+ curr[j] = Math.min(curr[j - 1] + 1, prev[j] + 1, prev[j - 1] + cost);
352
+ }
353
+ for (let j = 0;j <= b.length; j++)
354
+ prev[j] = curr[j];
355
+ }
356
+ return curr[b.length];
357
+ }
358
+
359
+ class InMemoryDatabaseAdapter extends DatabaseAdapter {
360
+ storage;
361
+ vectorIndex;
362
+ embeddingDimension = 384;
363
+ ready = false;
364
+ agentId;
365
+ constructor(storage, agentId) {
366
+ super();
367
+ this.storage = storage;
368
+ this.agentId = agentId;
369
+ this.db = storage;
370
+ this.vectorIndex = new EphemeralHNSW;
371
+ }
372
+ async initialize(_config) {
373
+ await this.storage.init();
374
+ await this.vectorIndex.init(this.embeddingDimension);
375
+ this.ready = true;
376
+ logger.info({ src: "plugin:inmemorydb" }, "In-memory database initialized");
377
+ }
378
+ async init() {
379
+ await this.initialize();
380
+ }
381
+ async runPluginMigrations(_plugins, _options) {
382
+ logger.debug({ src: "plugin:inmemorydb" }, "Plugin migrations not needed for in-memory storage");
383
+ }
384
+ async isReady() {
385
+ return this.ready && await this.storage.isReady();
386
+ }
387
+ async close() {
388
+ await this.vectorIndex.clear();
389
+ await this.storage.close();
390
+ this.ready = false;
391
+ logger.info({ src: "plugin:inmemorydb" }, "In-memory database closed");
392
+ }
393
+ async getConnection() {
394
+ return this.storage;
395
+ }
396
+ async transaction(callback, _options) {
397
+ return callback(this);
398
+ }
399
+ async ensureEmbeddingDimension(dimension) {
400
+ if (this.embeddingDimension !== dimension) {
401
+ this.embeddingDimension = dimension;
402
+ await this.vectorIndex.init(dimension);
403
+ }
404
+ }
405
+ async createEntities(entities) {
406
+ const ids = [];
407
+ for (const entity of entities) {
408
+ const id = entity.id ?? randomUUID();
409
+ await this.storage.set(COLLECTIONS.ENTITIES, id, { ...entity, id });
410
+ ids.push(id);
411
+ }
412
+ return ids;
413
+ }
414
+ async upsertEntities(entities) {
415
+ for (const entity of entities) {
416
+ if (!entity.id)
417
+ continue;
418
+ const existing = await this.storage.get(COLLECTIONS.ENTITIES, entity.id);
419
+ await this.storage.set(COLLECTIONS.ENTITIES, entity.id, {
420
+ ...existing ?? {},
421
+ ...entity
422
+ });
423
+ }
424
+ }
425
+ async getEntitiesByIds(entityIds) {
426
+ const entities = [];
427
+ for (const id of entityIds) {
428
+ const entity = await this.storage.get(COLLECTIONS.ENTITIES, id);
429
+ if (entity)
430
+ entities.push(entity);
431
+ }
432
+ return entities;
433
+ }
434
+ async updateEntities(entities) {
435
+ for (const entity of entities) {
436
+ if (!entity.id)
437
+ continue;
438
+ const existing = await this.storage.get(COLLECTIONS.ENTITIES, entity.id);
439
+ if (!existing)
440
+ continue;
441
+ await this.storage.set(COLLECTIONS.ENTITIES, entity.id, {
442
+ ...existing,
443
+ ...entity
444
+ });
445
+ }
446
+ }
447
+ async deleteEntities(entityIds) {
448
+ for (const id of entityIds) {
449
+ await this.storage.delete(COLLECTIONS.ENTITIES, id);
450
+ }
451
+ }
452
+ async getEntitiesForRooms(roomIds, includeComponents = false) {
453
+ const result = [];
454
+ for (const roomId of roomIds) {
455
+ const participants = await this.storage.getWhere(COLLECTIONS.PARTICIPANTS, (p) => p.roomId === roomId);
456
+ const entityIds = [...new Set(participants.map((p) => p.entityId))];
457
+ const entities = await this.getEntitiesByIds(entityIds);
458
+ if (includeComponents) {
459
+ for (const entity of entities) {
460
+ if (!entity.id)
461
+ continue;
462
+ const components = await this.getComponentsForEntities([entity.id]);
463
+ entity.components = components;
464
+ }
465
+ }
466
+ result.push({ roomId, entities });
467
+ }
468
+ return result;
469
+ }
470
+ async getEntitiesByNames(params) {
471
+ if (params.names.length === 0)
472
+ return [];
473
+ const set = new Set(params.names);
474
+ return this.storage.getWhere(COLLECTIONS.ENTITIES, (e) => {
475
+ const names = e.names ?? [];
476
+ return names.some((name) => set.has(name));
477
+ });
478
+ }
479
+ async searchEntitiesByName(params) {
480
+ const q = params.query.toLowerCase();
481
+ const matches = await this.storage.getWhere(COLLECTIONS.ENTITIES, (e) => {
482
+ const names = e.names ?? [];
483
+ return names.some((name) => name.toLowerCase().includes(q));
484
+ });
485
+ return params.limit ? matches.slice(0, params.limit) : matches;
486
+ }
487
+ async queryEntities(params) {
488
+ let entityIds;
489
+ if (params.entityIds && params.entityIds.length > 0) {
490
+ entityIds = params.entityIds;
491
+ } else {
492
+ const allComponents = await this.storage.getWhere(COLLECTIONS.COMPONENTS, (c) => {
493
+ if (params.componentType && c.type !== params.componentType)
494
+ return false;
495
+ if (params.worldId && c.worldId !== params.worldId)
496
+ return false;
497
+ if (params.componentDataFilter) {
498
+ const data = c.data;
499
+ if (!data || typeof data !== "object")
500
+ return false;
501
+ for (const [k, v] of Object.entries(params.componentDataFilter)) {
502
+ if (data[k] !== v)
503
+ return false;
504
+ }
505
+ }
506
+ return true;
507
+ });
508
+ entityIds = [...new Set(allComponents.map((c) => c.entityId))];
509
+ }
510
+ const offset = params.offset ?? 0;
511
+ const limit = params.limit;
512
+ const sliced = limit !== undefined ? entityIds.slice(offset, offset + limit) : entityIds.slice(offset);
513
+ const entities = await this.getEntitiesByIds(sliced);
514
+ if (params.includeAllComponents) {
515
+ for (const entity of entities) {
516
+ if (!entity.id)
517
+ continue;
518
+ const components = await this.getComponentsForEntities([entity.id]);
519
+ entity.components = components;
520
+ }
521
+ }
522
+ return entities;
523
+ }
524
+ async createComponents(components) {
525
+ const ids = [];
526
+ for (const component of components) {
527
+ const id = component.id;
528
+ await this.storage.set(COLLECTIONS.COMPONENTS, id, { ...component, id });
529
+ ids.push(id);
530
+ }
531
+ return ids;
532
+ }
533
+ async getComponentsByIds(componentIds) {
534
+ const components = [];
535
+ for (const id of componentIds) {
536
+ const c = await this.storage.get(COLLECTIONS.COMPONENTS, id);
537
+ if (c)
538
+ components.push(c);
539
+ }
540
+ return components;
541
+ }
542
+ async updateComponents(components) {
543
+ for (const component of components) {
544
+ if (!component.id)
545
+ continue;
546
+ const existing = await this.storage.get(COLLECTIONS.COMPONENTS, component.id);
547
+ if (!existing)
548
+ continue;
549
+ await this.storage.set(COLLECTIONS.COMPONENTS, component.id, {
550
+ ...existing,
551
+ ...component
552
+ });
553
+ }
554
+ }
555
+ async deleteComponents(componentIds) {
556
+ for (const id of componentIds) {
557
+ await this.storage.delete(COLLECTIONS.COMPONENTS, id);
558
+ }
559
+ }
560
+ async upsertComponents(components, _options) {
561
+ for (const component of components) {
562
+ const naturalKey = await this.storage.getWhere(COLLECTIONS.COMPONENTS, (c) => c.entityId === component.entityId && c.type === component.type && c.worldId === component.worldId && c.sourceEntityId === component.sourceEntityId);
563
+ const existing = naturalKey[0];
564
+ if (existing) {
565
+ await this.storage.set(COLLECTIONS.COMPONENTS, existing.id, {
566
+ ...existing,
567
+ ...component,
568
+ id: existing.id
569
+ });
570
+ } else {
571
+ const id = component.id;
572
+ await this.storage.set(COLLECTIONS.COMPONENTS, id, {
573
+ ...component,
574
+ id
575
+ });
576
+ }
577
+ }
578
+ }
579
+ async patchComponents(updates, _options) {
580
+ for (const update of updates) {
581
+ const component = await this.storage.get(COLLECTIONS.COMPONENTS, update.componentId);
582
+ if (!component)
583
+ continue;
584
+ const data = { ...component.data ?? {} };
585
+ for (const op of update.ops) {
586
+ applyPatchOp(data, op);
587
+ }
588
+ component.data = data;
589
+ await this.storage.set(COLLECTIONS.COMPONENTS, update.componentId, component);
590
+ }
591
+ }
592
+ async getComponentsByNaturalKeys(keys) {
593
+ const result = [];
594
+ for (const key of keys) {
595
+ const matches = await this.storage.getWhere(COLLECTIONS.COMPONENTS, (c) => c.entityId === key.entityId && c.type === key.type && c.worldId === (key.worldId ?? null) && c.sourceEntityId === (key.sourceEntityId ?? null));
596
+ result.push(matches[0] ?? null);
597
+ }
598
+ return result;
599
+ }
600
+ async getComponentsForEntities(entityIds, worldId, sourceEntityId) {
601
+ if (entityIds.length === 0)
602
+ return [];
603
+ const idSet = new Set(entityIds);
604
+ return this.storage.getWhere(COLLECTIONS.COMPONENTS, (c) => {
605
+ if (!idSet.has(c.entityId))
606
+ return false;
607
+ if (worldId !== undefined && c.worldId !== worldId)
608
+ return false;
609
+ if (sourceEntityId !== undefined && c.sourceEntityId !== sourceEntityId)
610
+ return false;
611
+ return true;
612
+ });
613
+ }
614
+ async getMemories(params) {
615
+ let memories = await this.storage.getWhere(COLLECTIONS.MEMORIES, (m) => {
616
+ if (params.entityId && m.entityId !== params.entityId)
617
+ return false;
618
+ if (params.agentId && m.agentId !== params.agentId)
619
+ return false;
620
+ if (params.roomId && m.roomId !== params.roomId)
621
+ return false;
622
+ if (params.worldId && m.worldId !== params.worldId)
623
+ return false;
624
+ if (params.tableName && m.metadata?.type !== params.tableName)
625
+ return false;
626
+ if (params.start && m.createdAt && m.createdAt < params.start)
627
+ return false;
628
+ if (params.end && m.createdAt && m.createdAt > params.end)
629
+ return false;
630
+ if (params.unique && !m.unique)
631
+ return false;
632
+ if (params.metadata) {
633
+ const md = m.metadata ?? {};
634
+ for (const [k, v] of Object.entries(params.metadata)) {
635
+ if (md[k] !== v)
636
+ return false;
637
+ }
638
+ }
639
+ return true;
640
+ });
641
+ memories.sort((a, b) => (b.createdAt ?? 0) - (a.createdAt ?? 0));
642
+ const offset = params.offset ?? 0;
643
+ const limit = params.limit ?? params.count;
644
+ if (offset > 0)
645
+ memories = memories.slice(offset);
646
+ if (limit !== undefined)
647
+ memories = memories.slice(0, limit);
648
+ return memories.map(toMemory);
649
+ }
650
+ async getMemoriesByRoomIds(params) {
651
+ if (params.roomIds.length === 0)
652
+ return [];
653
+ const roomSet = new Set(params.roomIds);
654
+ const memories = await this.storage.getWhere(COLLECTIONS.MEMORIES, (m) => roomSet.has(m.roomId) && (params.tableName ? m.metadata?.type === params.tableName : true));
655
+ memories.sort((a, b) => (b.createdAt ?? 0) - (a.createdAt ?? 0));
656
+ const sliced = params.limit ? memories.slice(0, params.limit) : memories;
657
+ return sliced.map(toMemory);
658
+ }
659
+ async getMemoriesByIds(memoryIds, tableName) {
660
+ const memories = [];
661
+ for (const id of memoryIds) {
662
+ const m = await this.storage.get(COLLECTIONS.MEMORIES, id);
663
+ if (!m)
664
+ continue;
665
+ if (tableName && m.metadata?.type !== tableName)
666
+ continue;
667
+ memories.push(toMemory(m));
668
+ }
669
+ return memories;
670
+ }
671
+ async getCachedEmbeddings(params) {
672
+ const memories = await this.storage.getWhere(COLLECTIONS.MEMORIES, (m) => m.metadata?.type === params.query_table_name && !!m.embedding);
673
+ const results = [];
674
+ for (const memory of memories) {
675
+ if (!memory.embedding)
676
+ continue;
677
+ const record = memory;
678
+ const fieldValue = record[params.query_field_name];
679
+ const text = String(fieldValue ?? "");
680
+ const score = levenshtein(params.query_input, text);
681
+ if (score <= params.query_threshold) {
682
+ results.push({ embedding: memory.embedding, levenshtein_score: score });
683
+ }
684
+ }
685
+ results.sort((a, b) => a.levenshtein_score - b.levenshtein_score);
686
+ return results.slice(0, params.query_match_count);
687
+ }
688
+ async searchMemories(params) {
689
+ const threshold = params.match_threshold ?? 0.5;
690
+ const limit = params.limit ?? 10;
691
+ const results = await this.vectorIndex.search(params.embedding, limit * 2, threshold);
692
+ const memories = [];
693
+ for (const result of results) {
694
+ const memory = await this.storage.get(COLLECTIONS.MEMORIES, result.id);
695
+ if (!memory)
696
+ continue;
697
+ if (params.tableName && memory.metadata?.type !== params.tableName)
698
+ continue;
699
+ if (params.roomId && memory.roomId !== params.roomId)
700
+ continue;
701
+ if (params.worldId && memory.worldId !== params.worldId)
702
+ continue;
703
+ if (params.entityId && memory.entityId !== params.entityId)
704
+ continue;
705
+ if (params.unique && !memory.unique)
706
+ continue;
707
+ memories.push({ ...toMemory(memory), similarity: result.similarity });
708
+ }
709
+ return memories.slice(0, limit);
710
+ }
711
+ async createMemories(memories) {
712
+ const ids = [];
713
+ for (const { memory, tableName, unique = false } of memories) {
714
+ const id = memory.id ?? randomUUID();
715
+ const stored = {
716
+ ...memory,
717
+ id,
718
+ agentId: memory.agentId ?? this.agentId,
719
+ unique: unique || memory.unique,
720
+ createdAt: memory.createdAt ?? Date.now(),
721
+ metadata: {
722
+ ...memory.metadata ?? {},
723
+ type: tableName
724
+ }
725
+ };
726
+ await this.storage.set(COLLECTIONS.MEMORIES, id, stored);
727
+ if (memory.embedding && memory.embedding.length > 0) {
728
+ await this.vectorIndex.add(id, memory.embedding);
729
+ }
730
+ ids.push(id);
731
+ }
732
+ return ids;
733
+ }
734
+ async updateMemories(memories) {
735
+ for (const memory of memories) {
736
+ const existing = await this.storage.get(COLLECTIONS.MEMORIES, memory.id);
737
+ if (!existing)
738
+ continue;
739
+ const updated = {
740
+ ...existing,
741
+ ...memory,
742
+ metadata: {
743
+ ...existing.metadata ?? {},
744
+ ...memory.metadata ?? {}
745
+ }
746
+ };
747
+ await this.storage.set(COLLECTIONS.MEMORIES, memory.id, updated);
748
+ if (memory.embedding && memory.embedding.length > 0) {
749
+ await this.vectorIndex.add(memory.id, memory.embedding);
750
+ }
751
+ }
752
+ }
753
+ async upsertMemories(memories, _options) {
754
+ for (const { memory, tableName } of memories) {
755
+ if (!memory.id) {
756
+ await this.createMemories([{ memory, tableName }]);
757
+ continue;
758
+ }
759
+ const existing = await this.storage.get(COLLECTIONS.MEMORIES, memory.id);
760
+ const stored = {
761
+ ...existing ?? {},
762
+ ...memory,
763
+ agentId: memory.agentId ?? existing?.agentId ?? this.agentId,
764
+ createdAt: memory.createdAt ?? existing?.createdAt ?? Date.now(),
765
+ metadata: {
766
+ ...existing?.metadata ?? {},
767
+ ...memory.metadata ?? {},
768
+ type: tableName
769
+ }
770
+ };
771
+ await this.storage.set(COLLECTIONS.MEMORIES, memory.id, stored);
772
+ if (memory.embedding && memory.embedding.length > 0) {
773
+ await this.vectorIndex.add(memory.id, memory.embedding);
774
+ }
775
+ }
776
+ }
777
+ async deleteMemories(memoryIds) {
778
+ for (const id of memoryIds) {
779
+ await this.storage.delete(COLLECTIONS.MEMORIES, id);
780
+ await this.vectorIndex.remove(id);
781
+ }
782
+ }
783
+ async deleteAllMemories(roomIds, tableName) {
784
+ if (roomIds.length === 0)
785
+ return;
786
+ const roomSet = new Set(roomIds);
787
+ const memories = await this.storage.getWhere(COLLECTIONS.MEMORIES, (m) => roomSet.has(m.roomId) && (tableName ? m.metadata?.type === tableName : true));
788
+ const ids = memories.map((m) => m.id).filter((id) => id !== undefined);
789
+ await this.deleteMemories(ids);
790
+ }
791
+ async countMemories(params) {
792
+ const roomSet = params.roomIds ? new Set(params.roomIds) : null;
793
+ return this.storage.count(COLLECTIONS.MEMORIES, (m) => {
794
+ if (roomSet && !roomSet.has(m.roomId))
795
+ return false;
796
+ if (params.unique && !m.unique)
797
+ return false;
798
+ if (params.tableName && m.metadata?.type !== params.tableName)
799
+ return false;
800
+ if (params.entityId && m.entityId !== params.entityId)
801
+ return false;
802
+ if (params.agentId && m.agentId !== params.agentId)
803
+ return false;
804
+ if (params.metadata) {
805
+ const md = m.metadata ?? {};
806
+ for (const [k, v] of Object.entries(params.metadata)) {
807
+ if (md[k] !== v)
808
+ return false;
809
+ }
810
+ }
811
+ return true;
812
+ });
813
+ }
814
+ async getMemoriesByWorldId(params) {
815
+ const worldSet = params.worldIds ? new Set(params.worldIds) : null;
816
+ const memories = await this.storage.getWhere(COLLECTIONS.MEMORIES, (m) => (!worldSet || (m.worldId ? worldSet.has(m.worldId) : false)) && (params.tableName ? m.metadata?.type === params.tableName : true));
817
+ memories.sort((a, b) => (b.createdAt ?? 0) - (a.createdAt ?? 0));
818
+ const sliced = params.limit ? memories.slice(0, params.limit) : memories;
819
+ return sliced.map(toMemory);
820
+ }
821
+ async getLogs(params) {
822
+ let logs = await this.storage.getWhere(COLLECTIONS.LOGS, (l) => {
823
+ if (params.entityId && l.entityId !== params.entityId)
824
+ return false;
825
+ if (params.roomId && l.roomId !== params.roomId)
826
+ return false;
827
+ if (params.type && l.type !== params.type)
828
+ return false;
829
+ return true;
830
+ });
831
+ logs.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
832
+ const offset = params.offset ?? 0;
833
+ if (offset > 0)
834
+ logs = logs.slice(offset);
835
+ if (params.limit !== undefined)
836
+ logs = logs.slice(0, params.limit);
837
+ return logs;
838
+ }
839
+ async createLogs(params) {
840
+ for (const entry of params) {
841
+ const id = randomUUID();
842
+ const log = {
843
+ id,
844
+ entityId: entry.entityId,
845
+ roomId: entry.roomId,
846
+ body: entry.body,
847
+ type: entry.type,
848
+ createdAt: new Date
849
+ };
850
+ await this.storage.set(COLLECTIONS.LOGS, id, log);
851
+ }
852
+ }
853
+ async getLogsByIds(logIds) {
854
+ const logs = [];
855
+ for (const id of logIds) {
856
+ const log = await this.storage.get(COLLECTIONS.LOGS, id);
857
+ if (log)
858
+ logs.push(log);
859
+ }
860
+ return logs;
861
+ }
862
+ async updateLogs(logs) {
863
+ for (const { id, updates } of logs) {
864
+ const existing = await this.storage.get(COLLECTIONS.LOGS, id);
865
+ if (!existing)
866
+ continue;
867
+ await this.storage.set(COLLECTIONS.LOGS, id, { ...existing, ...updates });
868
+ }
869
+ }
870
+ async deleteLogs(logIds) {
871
+ for (const id of logIds) {
872
+ await this.storage.delete(COLLECTIONS.LOGS, id);
873
+ }
874
+ }
875
+ async getAllWorlds() {
876
+ return this.storage.getAll(COLLECTIONS.WORLDS);
877
+ }
878
+ async getWorldsByIds(worldIds) {
879
+ const worlds = [];
880
+ for (const id of worldIds) {
881
+ const w = await this.storage.get(COLLECTIONS.WORLDS, id);
882
+ if (w)
883
+ worlds.push(w);
884
+ }
885
+ return worlds;
886
+ }
887
+ async createWorlds(worlds) {
888
+ const ids = [];
889
+ for (const world of worlds) {
890
+ const id = world.id;
891
+ await this.storage.set(COLLECTIONS.WORLDS, id, { ...world, id });
892
+ ids.push(id);
893
+ }
894
+ return ids;
895
+ }
896
+ async deleteWorlds(worldIds) {
897
+ for (const id of worldIds) {
898
+ await this.storage.delete(COLLECTIONS.WORLDS, id);
899
+ }
900
+ }
901
+ async updateWorlds(worlds) {
902
+ for (const world of worlds) {
903
+ if (!world.id)
904
+ continue;
905
+ const existing = await this.storage.get(COLLECTIONS.WORLDS, world.id);
906
+ if (!existing)
907
+ continue;
908
+ await this.storage.set(COLLECTIONS.WORLDS, world.id, {
909
+ ...existing,
910
+ ...world
911
+ });
912
+ }
913
+ }
914
+ async upsertWorlds(worlds) {
915
+ for (const world of worlds) {
916
+ const id = world.id;
917
+ const existing = await this.storage.get(COLLECTIONS.WORLDS, id);
918
+ await this.storage.set(COLLECTIONS.WORLDS, id, {
919
+ ...existing ?? {},
920
+ ...world,
921
+ id
922
+ });
923
+ }
924
+ }
925
+ async getRoomsByIds(roomIds) {
926
+ const rooms = [];
927
+ for (const id of roomIds) {
928
+ const room = await this.storage.get(COLLECTIONS.ROOMS, id);
929
+ if (room)
930
+ rooms.push(room);
931
+ }
932
+ return rooms;
933
+ }
934
+ async deleteRoomsByWorldIds(worldIds) {
935
+ if (worldIds.length === 0)
936
+ return;
937
+ const worldSet = new Set(worldIds);
938
+ const rooms = await this.storage.getWhere(COLLECTIONS.ROOMS, (r) => r.worldId ? worldSet.has(r.worldId) : false);
939
+ const roomIds = rooms.map((r) => r.id).filter((id) => id !== undefined);
940
+ await this.deleteRooms(roomIds);
941
+ }
942
+ async getRoomsForParticipants(entityIds) {
943
+ if (entityIds.length === 0)
944
+ return [];
945
+ const entitySet = new Set(entityIds);
946
+ const participants = await this.storage.getWhere(COLLECTIONS.PARTICIPANTS, (p) => entitySet.has(p.entityId));
947
+ return [...new Set(participants.map((p) => p.roomId))];
948
+ }
949
+ async getRoomsByWorlds(worldIds, limit, offset) {
950
+ if (worldIds.length === 0)
951
+ return [];
952
+ const worldSet = new Set(worldIds);
953
+ let rooms = await this.storage.getWhere(COLLECTIONS.ROOMS, (r) => r.worldId ? worldSet.has(r.worldId) : false);
954
+ const off = offset ?? 0;
955
+ if (off > 0)
956
+ rooms = rooms.slice(off);
957
+ if (limit !== undefined)
958
+ rooms = rooms.slice(0, limit);
959
+ return rooms;
960
+ }
961
+ async createRooms(rooms) {
962
+ const ids = [];
963
+ for (const room of rooms) {
964
+ const id = room.id;
965
+ await this.storage.set(COLLECTIONS.ROOMS, id, { ...room, id });
966
+ ids.push(id);
967
+ }
968
+ return ids;
969
+ }
970
+ async upsertRooms(rooms) {
971
+ for (const room of rooms) {
972
+ const id = room.id;
973
+ const existing = await this.storage.get(COLLECTIONS.ROOMS, id);
974
+ await this.storage.set(COLLECTIONS.ROOMS, id, {
975
+ ...existing ?? {},
976
+ ...room,
977
+ id
978
+ });
979
+ }
980
+ }
981
+ async updateRooms(rooms) {
982
+ for (const room of rooms) {
983
+ if (!room.id)
984
+ continue;
985
+ const existing = await this.storage.get(COLLECTIONS.ROOMS, room.id);
986
+ if (!existing)
987
+ continue;
988
+ await this.storage.set(COLLECTIONS.ROOMS, room.id, {
989
+ ...existing,
990
+ ...room
991
+ });
992
+ }
993
+ }
994
+ async deleteRooms(roomIds) {
995
+ if (roomIds.length === 0)
996
+ return;
997
+ const set = new Set(roomIds);
998
+ for (const id of roomIds) {
999
+ await this.storage.delete(COLLECTIONS.ROOMS, id);
1000
+ }
1001
+ await this.storage.deleteWhere(COLLECTIONS.PARTICIPANTS, (p) => set.has(p.roomId));
1002
+ await this.storage.deleteWhere(COLLECTIONS.MEMORIES, (m) => set.has(m.roomId));
1003
+ }
1004
+ async createRoomParticipants(entityIds, roomId) {
1005
+ const ids = [];
1006
+ for (const entityId of entityIds) {
1007
+ const existing = await this.storage.getWhere(COLLECTIONS.PARTICIPANTS, (p) => p.entityId === entityId && p.roomId === roomId);
1008
+ const existingParticipant = existing[0];
1009
+ if (existingParticipant) {
1010
+ ids.push(existingParticipant.id);
1011
+ continue;
1012
+ }
1013
+ const id = randomUUID();
1014
+ const participant = { id, entityId, roomId };
1015
+ await this.storage.set(COLLECTIONS.PARTICIPANTS, id, participant);
1016
+ ids.push(id);
1017
+ }
1018
+ return ids;
1019
+ }
1020
+ async deleteParticipants(participants) {
1021
+ let removed = false;
1022
+ for (const { entityId, roomId } of participants) {
1023
+ const matches = await this.storage.getWhere(COLLECTIONS.PARTICIPANTS, (p) => p.entityId === entityId && p.roomId === roomId);
1024
+ for (const p of matches) {
1025
+ if (p.id) {
1026
+ await this.storage.delete(COLLECTIONS.PARTICIPANTS, p.id);
1027
+ removed = true;
1028
+ }
1029
+ }
1030
+ }
1031
+ return removed;
1032
+ }
1033
+ async updateParticipants(participants) {
1034
+ for (const { entityId, roomId, updates } of participants) {
1035
+ const matches = await this.storage.getWhere(COLLECTIONS.PARTICIPANTS, (p) => p.entityId === entityId && p.roomId === roomId);
1036
+ for (const p of matches) {
1037
+ if (!p.id)
1038
+ continue;
1039
+ const next = {
1040
+ ...p,
1041
+ userState: updates.roomState ?? p.userState,
1042
+ metadata: { ...p.metadata ?? {}, ...updates.metadata ?? {} }
1043
+ };
1044
+ await this.storage.set(COLLECTIONS.PARTICIPANTS, p.id, next);
1045
+ }
1046
+ }
1047
+ }
1048
+ async getParticipantsForEntities(entityIds) {
1049
+ if (entityIds.length === 0)
1050
+ return [];
1051
+ const set = new Set(entityIds);
1052
+ const stored = await this.storage.getWhere(COLLECTIONS.PARTICIPANTS, (p) => set.has(p.entityId));
1053
+ const participants = [];
1054
+ for (const p of stored) {
1055
+ const entity = await this.storage.get(COLLECTIONS.ENTITIES, p.entityId);
1056
+ if (entity)
1057
+ participants.push({ id: p.id, entity });
1058
+ }
1059
+ return participants;
1060
+ }
1061
+ async getParticipantsForRooms(roomIds) {
1062
+ const result = [];
1063
+ for (const roomId of roomIds) {
1064
+ const stored = await this.storage.getWhere(COLLECTIONS.PARTICIPANTS, (p) => p.roomId === roomId);
1065
+ result.push({
1066
+ roomId,
1067
+ entityIds: [...new Set(stored.map((p) => p.entityId))]
1068
+ });
1069
+ }
1070
+ return result;
1071
+ }
1072
+ async areRoomParticipants(pairs) {
1073
+ const result = [];
1074
+ for (const { roomId, entityId } of pairs) {
1075
+ const matches = await this.storage.getWhere(COLLECTIONS.PARTICIPANTS, (p) => p.roomId === roomId && p.entityId === entityId);
1076
+ result.push(matches.length > 0);
1077
+ }
1078
+ return result;
1079
+ }
1080
+ async getParticipantUserStates(pairs) {
1081
+ const result = [];
1082
+ for (const { roomId, entityId } of pairs) {
1083
+ const matches = await this.storage.getWhere(COLLECTIONS.PARTICIPANTS, (p) => p.roomId === roomId && p.entityId === entityId);
1084
+ const state = matches[0]?.userState ?? null;
1085
+ result.push(state);
1086
+ }
1087
+ return result;
1088
+ }
1089
+ async updateParticipantUserStates(updates) {
1090
+ for (const { roomId, entityId, state } of updates) {
1091
+ const matches = await this.storage.getWhere(COLLECTIONS.PARTICIPANTS, (p) => p.roomId === roomId && p.entityId === entityId);
1092
+ for (const p of matches) {
1093
+ if (!p.id)
1094
+ continue;
1095
+ await this.storage.set(COLLECTIONS.PARTICIPANTS, p.id, {
1096
+ ...p,
1097
+ userState: state
1098
+ });
1099
+ }
1100
+ }
1101
+ }
1102
+ async getRelationshipsByPairs(pairs) {
1103
+ const result = [];
1104
+ for (const pair of pairs) {
1105
+ const matches = await this.storage.getWhere(COLLECTIONS.RELATIONSHIPS, (r) => r.sourceEntityId === pair.sourceEntityId && r.targetEntityId === pair.targetEntityId);
1106
+ const first = matches[0];
1107
+ result.push(first ? relationshipFromStored(first, this.agentId) : null);
1108
+ }
1109
+ return result;
1110
+ }
1111
+ async getRelationships(params) {
1112
+ const entitySet = params.entityIds ? new Set(params.entityIds) : null;
1113
+ let stored = await this.storage.getWhere(COLLECTIONS.RELATIONSHIPS, (r) => {
1114
+ if (entitySet) {
1115
+ if (!entitySet.has(r.sourceEntityId) && !entitySet.has(r.targetEntityId)) {
1116
+ return false;
1117
+ }
1118
+ }
1119
+ if (params.tags && params.tags.length > 0) {
1120
+ const tags = r.tags ?? [];
1121
+ if (!params.tags.some((t) => tags.includes(t)))
1122
+ return false;
1123
+ }
1124
+ return true;
1125
+ });
1126
+ const offset = params.offset ?? 0;
1127
+ if (offset > 0)
1128
+ stored = stored.slice(offset);
1129
+ if (params.limit !== undefined)
1130
+ stored = stored.slice(0, params.limit);
1131
+ return stored.map((r) => relationshipFromStored(r, this.agentId));
1132
+ }
1133
+ async createRelationships(relationships) {
1134
+ const ids = [];
1135
+ for (const rel of relationships) {
1136
+ const id = randomUUID();
1137
+ const stored = {
1138
+ id,
1139
+ sourceEntityId: rel.sourceEntityId,
1140
+ targetEntityId: rel.targetEntityId,
1141
+ agentId: this.agentId,
1142
+ tags: rel.tags ?? [],
1143
+ metadata: rel.metadata ?? {},
1144
+ createdAt: new Date().toISOString()
1145
+ };
1146
+ await this.storage.set(COLLECTIONS.RELATIONSHIPS, id, stored);
1147
+ ids.push(id);
1148
+ }
1149
+ return ids;
1150
+ }
1151
+ async getRelationshipsByIds(relationshipIds) {
1152
+ const relationships = [];
1153
+ for (const id of relationshipIds) {
1154
+ const r = await this.storage.get(COLLECTIONS.RELATIONSHIPS, id);
1155
+ if (r)
1156
+ relationships.push(relationshipFromStored(r, this.agentId));
1157
+ }
1158
+ return relationships;
1159
+ }
1160
+ async updateRelationships(relationships) {
1161
+ for (const rel of relationships) {
1162
+ if (!rel.id)
1163
+ continue;
1164
+ const existing = await this.storage.get(COLLECTIONS.RELATIONSHIPS, rel.id);
1165
+ if (!existing)
1166
+ continue;
1167
+ const next = {
1168
+ ...existing,
1169
+ sourceEntityId: rel.sourceEntityId,
1170
+ targetEntityId: rel.targetEntityId,
1171
+ agentId: rel.agentId,
1172
+ tags: rel.tags,
1173
+ metadata: { ...existing.metadata ?? {}, ...rel.metadata ?? {} }
1174
+ };
1175
+ await this.storage.set(COLLECTIONS.RELATIONSHIPS, rel.id, next);
1176
+ }
1177
+ }
1178
+ async deleteRelationships(relationshipIds) {
1179
+ for (const id of relationshipIds) {
1180
+ await this.storage.delete(COLLECTIONS.RELATIONSHIPS, id);
1181
+ }
1182
+ }
1183
+ async getAgents() {
1184
+ return this.storage.getAll(COLLECTIONS.AGENTS);
1185
+ }
1186
+ async getAgentsByIds(agentIds) {
1187
+ const agents = [];
1188
+ for (const id of agentIds) {
1189
+ const agent = await this.storage.get(COLLECTIONS.AGENTS, id);
1190
+ if (agent)
1191
+ agents.push(agent);
1192
+ }
1193
+ return agents;
1194
+ }
1195
+ async createAgents(agents) {
1196
+ const ids = [];
1197
+ for (const agent of agents) {
1198
+ const id = agent.id ?? randomUUID();
1199
+ await this.storage.set(COLLECTIONS.AGENTS, id, { ...agent, id });
1200
+ ids.push(id);
1201
+ }
1202
+ return ids;
1203
+ }
1204
+ async updateAgents(updates) {
1205
+ let updated = false;
1206
+ for (const { agentId, agent } of updates) {
1207
+ const existing = await this.storage.get(COLLECTIONS.AGENTS, agentId);
1208
+ if (!existing)
1209
+ continue;
1210
+ await this.storage.set(COLLECTIONS.AGENTS, agentId, {
1211
+ ...existing,
1212
+ ...agent
1213
+ });
1214
+ updated = true;
1215
+ }
1216
+ return updated;
1217
+ }
1218
+ async upsertAgents(agents) {
1219
+ for (const agent of agents) {
1220
+ const id = agent.id ?? randomUUID();
1221
+ const existing = await this.storage.get(COLLECTIONS.AGENTS, id);
1222
+ await this.storage.set(COLLECTIONS.AGENTS, id, {
1223
+ ...existing ?? {},
1224
+ ...agent,
1225
+ id
1226
+ });
1227
+ }
1228
+ }
1229
+ async deleteAgents(agentIds) {
1230
+ let removed = false;
1231
+ for (const id of agentIds) {
1232
+ const ok = await this.storage.delete(COLLECTIONS.AGENTS, id);
1233
+ if (ok)
1234
+ removed = true;
1235
+ }
1236
+ return removed;
1237
+ }
1238
+ async countAgents() {
1239
+ return this.storage.count(COLLECTIONS.AGENTS);
1240
+ }
1241
+ async cleanupAgents() {}
1242
+ async getCaches(keys) {
1243
+ const out = new Map;
1244
+ for (const key of keys) {
1245
+ const entry = await this.storage.get(COLLECTIONS.CACHE, key);
1246
+ if (!entry)
1247
+ continue;
1248
+ if (entry.expiresAt && Date.now() > entry.expiresAt) {
1249
+ await this.storage.delete(COLLECTIONS.CACHE, key);
1250
+ continue;
1251
+ }
1252
+ out.set(key, entry.value);
1253
+ }
1254
+ return out;
1255
+ }
1256
+ async setCaches(entries) {
1257
+ for (const { key, value } of entries) {
1258
+ await this.storage.set(COLLECTIONS.CACHE, key, { value });
1259
+ }
1260
+ return true;
1261
+ }
1262
+ async deleteCaches(keys) {
1263
+ let removed = false;
1264
+ for (const key of keys) {
1265
+ const ok = await this.storage.delete(COLLECTIONS.CACHE, key);
1266
+ if (ok)
1267
+ removed = true;
1268
+ }
1269
+ return removed;
1270
+ }
1271
+ async getTasks(params) {
1272
+ const agentSet = new Set(params.agentIds);
1273
+ let tasks = await this.storage.getWhere(COLLECTIONS.TASKS, (t) => {
1274
+ const taskAgentId = t.agentId;
1275
+ if (agentSet.size > 0 && taskAgentId !== undefined && !agentSet.has(taskAgentId)) {
1276
+ return false;
1277
+ }
1278
+ if (params.roomId && t.roomId !== params.roomId)
1279
+ return false;
1280
+ if (params.entityId && t.entityId !== params.entityId)
1281
+ return false;
1282
+ if (params.tags && params.tags.length > 0) {
1283
+ const tags = t.tags ?? [];
1284
+ if (!params.tags.some((tag) => tags.includes(tag)))
1285
+ return false;
1286
+ }
1287
+ return true;
1288
+ });
1289
+ const offset = params.offset ?? 0;
1290
+ if (offset > 0)
1291
+ tasks = tasks.slice(offset);
1292
+ if (params.limit !== undefined)
1293
+ tasks = tasks.slice(0, params.limit);
1294
+ return tasks;
1295
+ }
1296
+ async getTasksByName(name) {
1297
+ return this.storage.getWhere(COLLECTIONS.TASKS, (t) => t.name === name);
1298
+ }
1299
+ async createTasks(tasks) {
1300
+ const ids = [];
1301
+ for (const task of tasks) {
1302
+ const id = task.id ?? randomUUID();
1303
+ await this.storage.set(COLLECTIONS.TASKS, id, { ...task, id });
1304
+ ids.push(id);
1305
+ }
1306
+ return ids;
1307
+ }
1308
+ async getTasksByIds(taskIds) {
1309
+ const tasks = [];
1310
+ for (const id of taskIds) {
1311
+ const task = await this.storage.get(COLLECTIONS.TASKS, id);
1312
+ if (task)
1313
+ tasks.push(task);
1314
+ }
1315
+ return tasks;
1316
+ }
1317
+ async updateTasks(updates) {
1318
+ for (const { id, task } of updates) {
1319
+ const existing = await this.storage.get(COLLECTIONS.TASKS, id);
1320
+ if (!existing)
1321
+ continue;
1322
+ await this.storage.set(COLLECTIONS.TASKS, id, { ...existing, ...task });
1323
+ }
1324
+ }
1325
+ async deleteTasks(taskIds) {
1326
+ for (const id of taskIds) {
1327
+ await this.storage.delete(COLLECTIONS.TASKS, id);
1328
+ }
1329
+ }
1330
+ async getPairingRequests(queries) {
1331
+ const result = [];
1332
+ for (const { channel, agentId } of queries) {
1333
+ const requests = await this.storage.getWhere(COLLECTIONS.PAIRING_REQUESTS, (r) => r.channel === channel && r.agentId === agentId);
1334
+ result.push({ channel, agentId, requests });
1335
+ }
1336
+ return result;
1337
+ }
1338
+ async getPairingAllowlists(queries) {
1339
+ const result = [];
1340
+ for (const { channel, agentId } of queries) {
1341
+ const entries = await this.storage.getWhere(COLLECTIONS.PAIRING_ALLOWLIST, (e) => e.channel === channel && e.agentId === agentId);
1342
+ result.push({ channel, agentId, entries });
1343
+ }
1344
+ return result;
1345
+ }
1346
+ async createPairingRequests(requests) {
1347
+ const ids = [];
1348
+ for (const request of requests) {
1349
+ const id = request.id;
1350
+ await this.storage.set(COLLECTIONS.PAIRING_REQUESTS, id, {
1351
+ ...request,
1352
+ id
1353
+ });
1354
+ ids.push(id);
1355
+ }
1356
+ return ids;
1357
+ }
1358
+ async updatePairingRequests(requests) {
1359
+ for (const request of requests) {
1360
+ if (!request.id)
1361
+ continue;
1362
+ const existing = await this.storage.get(COLLECTIONS.PAIRING_REQUESTS, request.id);
1363
+ if (!existing)
1364
+ continue;
1365
+ await this.storage.set(COLLECTIONS.PAIRING_REQUESTS, request.id, {
1366
+ ...existing,
1367
+ ...request
1368
+ });
1369
+ }
1370
+ }
1371
+ async deletePairingRequests(ids) {
1372
+ for (const id of ids) {
1373
+ await this.storage.delete(COLLECTIONS.PAIRING_REQUESTS, id);
1374
+ }
1375
+ }
1376
+ async createPairingAllowlistEntries(entries) {
1377
+ const ids = [];
1378
+ for (const entry of entries) {
1379
+ const id = entry.id;
1380
+ await this.storage.set(COLLECTIONS.PAIRING_ALLOWLIST, id, {
1381
+ ...entry,
1382
+ id
1383
+ });
1384
+ ids.push(id);
1385
+ }
1386
+ return ids;
1387
+ }
1388
+ async updatePairingAllowlistEntries(entries) {
1389
+ for (const entry of entries) {
1390
+ if (!entry.id)
1391
+ continue;
1392
+ const existing = await this.storage.get(COLLECTIONS.PAIRING_ALLOWLIST, entry.id);
1393
+ if (!existing)
1394
+ continue;
1395
+ await this.storage.set(COLLECTIONS.PAIRING_ALLOWLIST, entry.id, {
1396
+ ...existing,
1397
+ ...entry
1398
+ });
1399
+ }
1400
+ }
1401
+ async deletePairingAllowlistEntries(ids) {
1402
+ for (const id of ids) {
1403
+ await this.storage.delete(COLLECTIONS.PAIRING_ALLOWLIST, id);
1404
+ }
1405
+ }
1406
+ }
1407
+
1408
+ // storage-memory.ts
1409
+ class MemoryStorage {
1410
+ collections = new Map;
1411
+ ready = false;
1412
+ async init() {
1413
+ this.ready = true;
1414
+ }
1415
+ async close() {
1416
+ this.collections.clear();
1417
+ this.ready = false;
1418
+ }
1419
+ async isReady() {
1420
+ return this.ready;
1421
+ }
1422
+ getCollection(collection) {
1423
+ this.assertReady();
1424
+ let col = this.collections.get(collection);
1425
+ if (!col) {
1426
+ col = new Map;
1427
+ this.collections.set(collection, col);
1428
+ }
1429
+ return col;
1430
+ }
1431
+ assertReady() {
1432
+ if (!this.ready) {
1433
+ throw new Error("MemoryStorage is not initialized");
1434
+ }
1435
+ }
1436
+ async get(collection, id) {
1437
+ const col = this.getCollection(collection);
1438
+ const item = col.get(id);
1439
+ return item !== undefined ? item : null;
1440
+ }
1441
+ async getAll(collection) {
1442
+ const col = this.getCollection(collection);
1443
+ return Array.from(col.values());
1444
+ }
1445
+ async getWhere(collection, predicate) {
1446
+ const all = await this.getAll(collection);
1447
+ return all.filter(predicate);
1448
+ }
1449
+ async set(collection, id, data) {
1450
+ const col = this.getCollection(collection);
1451
+ col.set(id, data);
1452
+ }
1453
+ async delete(collection, id) {
1454
+ const col = this.getCollection(collection);
1455
+ return col.delete(id);
1456
+ }
1457
+ async deleteMany(collection, ids) {
1458
+ const col = this.getCollection(collection);
1459
+ for (const id of ids) {
1460
+ col.delete(id);
1461
+ }
1462
+ }
1463
+ async deleteWhere(collection, predicate) {
1464
+ const col = this.getCollection(collection);
1465
+ const toDelete = [];
1466
+ for (const [id, item] of col) {
1467
+ if (predicate(item)) {
1468
+ toDelete.push(id);
1469
+ }
1470
+ }
1471
+ for (const id of toDelete) {
1472
+ col.delete(id);
1473
+ }
1474
+ }
1475
+ async count(collection, predicate) {
1476
+ const col = this.getCollection(collection);
1477
+ if (!predicate) {
1478
+ return col.size;
1479
+ }
1480
+ let count = 0;
1481
+ for (const item of col.values()) {
1482
+ if (predicate(item)) {
1483
+ count++;
1484
+ }
1485
+ }
1486
+ return count;
1487
+ }
1488
+ async clear() {
1489
+ this.assertReady();
1490
+ this.collections.clear();
1491
+ }
1492
+ }
1493
+
1494
+ // index.ts
1495
+ var GLOBAL_SINGLETONS = Symbol.for("elizaos.plugin-inmemorydb.global-singletons");
1496
+ var globalSymbols = globalThis;
1497
+ if (!globalSymbols[GLOBAL_SINGLETONS]) {
1498
+ globalSymbols[GLOBAL_SINGLETONS] = {};
1499
+ }
1500
+ var globalSingletons = globalSymbols[GLOBAL_SINGLETONS];
1501
+ function createDatabaseAdapter(agentId) {
1502
+ if (!globalSingletons.storageManager) {
1503
+ globalSingletons.storageManager = new MemoryStorage;
1504
+ }
1505
+ return new InMemoryDatabaseAdapter(globalSingletons.storageManager, agentId);
1506
+ }
1507
+ var plugin = {
1508
+ name: "@elizaos/plugin-inmemorydb",
1509
+ description: "Pure in-memory, ephemeral database storage for elizaOS - no persistence",
1510
+ async init(_config, runtime) {
1511
+ logger2.info({ src: "plugin:inmemorydb" }, "Initializing in-memory database plugin");
1512
+ const r = runtime;
1513
+ const hasAdapter = r.adapter !== undefined || r.databaseAdapter !== undefined || (r.hasDatabaseAdapter?.() ?? false);
1514
+ if (hasAdapter) {
1515
+ logger2.debug({ src: "plugin:inmemorydb" }, "Database adapter already exists; keeping current adapter");
1516
+ return;
1517
+ }
1518
+ const adapter = createDatabaseAdapter(runtime.agentId);
1519
+ await adapter.initialize();
1520
+ r.registerDatabaseAdapter?.(adapter);
1521
+ logger2.success({ src: "plugin:inmemorydb" }, "In-memory database adapter registered successfully");
1522
+ }
1523
+ };
1524
+ var plugin_inmemorydb_default = plugin;
1525
+ export {
1526
+ plugin,
1527
+ plugin_inmemorydb_default as default,
1528
+ createDatabaseAdapter,
1529
+ MemoryStorage,
1530
+ InMemoryDatabaseAdapter,
1531
+ EphemeralHNSW,
1532
+ COLLECTIONS
1533
+ };
1534
+
1535
+ //# debugId=5D21BF0F093E14FA64756E2164756E21
1536
+ //# sourceMappingURL=index.js.map