@elizaos/plugin-inmemorydb 2.0.0-alpha.6 → 2.0.0-beta.1

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.
@@ -1,15 +1,16 @@
1
- // typescript/index.ts
1
+ // index.ts
2
2
  import {
3
3
  logger as logger2
4
4
  } from "@elizaos/core";
5
5
 
6
- // typescript/adapter.ts
6
+ // adapter.ts
7
+ import { randomUUID } from "node:crypto";
7
8
  import {
8
9
  DatabaseAdapter,
9
10
  logger
10
11
  } from "@elizaos/core";
11
12
 
12
- // typescript/hnsw.ts
13
+ // hnsw.ts
13
14
  function cosineDistance(a, b) {
14
15
  if (a.length !== b.length) {
15
16
  throw new Error(`Vector dimension mismatch: ${a.length} vs ${b.length}`);
@@ -18,9 +19,11 @@ function cosineDistance(a, b) {
18
19
  let normA = 0;
19
20
  let normB = 0;
20
21
  for (let i = 0;i < a.length; i++) {
21
- dotProduct += a[i] * b[i];
22
- normA += a[i] * a[i];
23
- normB += b[i] * b[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;
24
27
  }
25
28
  const magnitude = Math.sqrt(normA) * Math.sqrt(normB);
26
29
  if (magnitude === 0)
@@ -105,7 +108,10 @@ class EphemeralHNSW {
105
108
  }
106
109
  }
107
110
  if (neighbors.length > 0) {
108
- currentNode = neighbors[0].id;
111
+ const closestNeighbor = neighbors[0];
112
+ if (closestNeighbor) {
113
+ currentNode = closestNeighbor.id;
114
+ }
109
115
  }
110
116
  }
111
117
  this.nodes.set(id, newNode);
@@ -131,6 +137,8 @@ class EphemeralHNSW {
131
137
  break;
132
138
  results.sort((a, b) => b.distance - a.distance);
133
139
  const furthestResult = results[0];
140
+ if (!furthestResult)
141
+ break;
134
142
  if (current.distance > furthestResult.distance) {
135
143
  break;
136
144
  }
@@ -216,8 +224,9 @@ class EphemeralHNSW {
216
224
  let currentNode = this.entryPoint;
217
225
  for (let l = this.maxLevel;l > 0; l--) {
218
226
  const closest = this.searchLayer(query, currentNode, 1, l);
219
- if (closest.length > 0) {
220
- currentNode = closest[0].id;
227
+ const closestNode = closest[0];
228
+ if (closestNode) {
229
+ currentNode = closestNode.id;
221
230
  }
222
231
  }
223
232
  const results = this.searchLayer(query, currentNode, Math.max(k, this.config.efSearch), 0);
@@ -237,7 +246,7 @@ class EphemeralHNSW {
237
246
  }
238
247
  }
239
248
 
240
- // typescript/types.ts
249
+ // types.ts
241
250
  var COLLECTIONS = {
242
251
  AGENTS: "agents",
243
252
  ENTITIES: "entities",
@@ -255,7 +264,7 @@ var COLLECTIONS = {
255
264
  PAIRING_ALLOWLIST: "pairing_allowlist"
256
265
  };
257
266
 
258
- // typescript/adapter.ts
267
+ // adapter.ts
259
268
  function toMemory(stored) {
260
269
  return {
261
270
  id: stored.id,
@@ -271,8 +280,80 @@ function toMemory(stored) {
271
280
  metadata: stored.metadata
272
281
  };
273
282
  }
274
- function toMemories(stored) {
275
- return stored.map(toMemory);
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];
276
357
  }
277
358
 
278
359
  class InMemoryDatabaseAdapter extends DatabaseAdapter {
@@ -288,15 +369,15 @@ class InMemoryDatabaseAdapter extends DatabaseAdapter {
288
369
  this.db = storage;
289
370
  this.vectorIndex = new EphemeralHNSW;
290
371
  }
291
- async initialize() {
292
- await this.init();
293
- }
294
- async init() {
372
+ async initialize(_config) {
295
373
  await this.storage.init();
296
374
  await this.vectorIndex.init(this.embeddingDimension);
297
375
  this.ready = true;
298
376
  logger.info({ src: "plugin:inmemorydb" }, "In-memory database initialized");
299
377
  }
378
+ async init() {
379
+ await this.initialize();
380
+ }
300
381
  async runPluginMigrations(_plugins, _options) {
301
382
  logger.debug({ src: "plugin:inmemorydb" }, "Plugin migrations not needed for in-memory storage");
302
383
  }
@@ -312,30 +393,8 @@ class InMemoryDatabaseAdapter extends DatabaseAdapter {
312
393
  async getConnection() {
313
394
  return this.storage;
314
395
  }
315
- async getAgent(agentId) {
316
- return this.storage.get(COLLECTIONS.AGENTS, agentId);
317
- }
318
- async getAgents() {
319
- return this.storage.getAll(COLLECTIONS.AGENTS);
320
- }
321
- async createAgent(agent) {
322
- if (!agent.id)
323
- return false;
324
- await this.storage.set(COLLECTIONS.AGENTS, agent.id, agent);
325
- return true;
326
- }
327
- async updateAgent(agentId, agent) {
328
- const existing = await this.getAgent(agentId);
329
- if (!existing)
330
- return false;
331
- await this.storage.set(COLLECTIONS.AGENTS, agentId, {
332
- ...existing,
333
- ...agent
334
- });
335
- return true;
336
- }
337
- async deleteAgent(agentId) {
338
- return this.storage.delete(COLLECTIONS.AGENTS, agentId);
396
+ async transaction(callback, _options) {
397
+ return callback(this);
339
398
  }
340
399
  async ensureEmbeddingDimension(dimension) {
341
400
  if (this.embeddingDimension !== dimension) {
@@ -343,6 +402,26 @@ class InMemoryDatabaseAdapter extends DatabaseAdapter {
343
402
  await this.vectorIndex.init(dimension);
344
403
  }
345
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
+ }
346
425
  async getEntitiesByIds(entityIds) {
347
426
  const entities = [];
348
427
  for (const id of entityIds) {
@@ -350,57 +429,187 @@ class InMemoryDatabaseAdapter extends DatabaseAdapter {
350
429
  if (entity)
351
430
  entities.push(entity);
352
431
  }
353
- return entities.length > 0 ? entities : null;
432
+ return entities;
354
433
  }
355
- async getEntitiesForRoom(roomId, includeComponents = false) {
356
- const participants = await this.storage.getWhere(COLLECTIONS.PARTICIPANTS, (p) => p.roomId === roomId);
357
- const entityIds = participants.map((p) => p.entityId);
358
- const entities = [];
359
- for (const entityId of entityIds) {
360
- const entity = await this.storage.get(COLLECTIONS.ENTITIES, entityId);
361
- if (entity) {
362
- if (includeComponents) {
363
- const components = await this.getComponents(entityId);
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]);
364
463
  entity.components = components;
365
464
  }
366
- entities.push(entity);
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;
367
520
  }
368
521
  }
369
522
  return entities;
370
523
  }
371
- async createEntities(entities) {
372
- for (const entity of entities) {
373
- if (!entity.id)
374
- continue;
375
- await this.storage.set(COLLECTIONS.ENTITIES, entity.id, entity);
524
+ async createComponents(components) {
525
+ const ids = [];
526
+ for (const component of components) {
527
+ const id = component.id ?? randomUUID();
528
+ await this.storage.set(COLLECTIONS.COMPONENTS, id, { ...component, id });
529
+ ids.push(id);
376
530
  }
377
- return true;
531
+ return ids;
378
532
  }
379
- async updateEntity(entity) {
380
- if (!entity.id)
381
- return;
382
- await this.storage.set(COLLECTIONS.ENTITIES, entity.id, entity);
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;
383
541
  }
384
- async getComponent(entityId, type, worldId, sourceEntityId) {
385
- const components = await this.storage.getWhere(COLLECTIONS.COMPONENTS, (c) => c.entityId === entityId && c.type === type && (worldId === undefined || c.worldId === worldId) && (sourceEntityId === undefined || c.sourceEntityId === sourceEntityId));
386
- return components[0] ?? null;
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
+ }
387
554
  }
388
- async getComponents(entityId, worldId, sourceEntityId) {
389
- return this.storage.getWhere(COLLECTIONS.COMPONENTS, (c) => c.entityId === entityId && (worldId === undefined || c.worldId === worldId) && (sourceEntityId === undefined || c.sourceEntityId === sourceEntityId));
555
+ async deleteComponents(componentIds) {
556
+ for (const id of componentIds) {
557
+ await this.storage.delete(COLLECTIONS.COMPONENTS, id);
558
+ }
390
559
  }
391
- async createComponent(component) {
392
- if (!component.id)
393
- return false;
394
- await this.storage.set(COLLECTIONS.COMPONENTS, component.id, component);
395
- return true;
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 ?? null) === (component.worldId ?? null) && (c.sourceEntityId ?? null) === (component.sourceEntityId ?? null));
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 ?? randomUUID();
572
+ await this.storage.set(COLLECTIONS.COMPONENTS, id, {
573
+ ...component,
574
+ id
575
+ });
576
+ }
577
+ }
396
578
  }
397
- async updateComponent(component) {
398
- if (!component.id)
399
- return;
400
- await this.storage.set(COLLECTIONS.COMPONENTS, component.id, component);
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 ?? null) === (key.worldId ?? null) && (c.sourceEntityId ?? null) === (key.sourceEntityId ?? null));
596
+ result.push(matches[0] ?? null);
597
+ }
598
+ return result;
401
599
  }
402
- async deleteComponent(componentId) {
403
- await this.storage.delete(COLLECTIONS.COMPONENTS, componentId);
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
+ });
404
613
  }
405
614
  async getMemories(params) {
406
615
  let memories = await this.storage.getWhere(COLLECTIONS.MEMORIES, (m) => {
@@ -420,108 +629,66 @@ class InMemoryDatabaseAdapter extends DatabaseAdapter {
420
629
  return false;
421
630
  if (params.unique && !m.unique)
422
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
+ }
423
639
  return true;
424
640
  });
425
641
  memories.sort((a, b) => (b.createdAt ?? 0) - (a.createdAt ?? 0));
426
- if (params.offset) {
427
- memories = memories.slice(params.offset);
428
- }
429
- if (params.count) {
430
- memories = memories.slice(0, params.count);
431
- }
432
- return toMemories(memories);
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);
433
649
  }
434
650
  async getMemoriesByRoomIds(params) {
435
- const memories = await this.storage.getWhere(COLLECTIONS.MEMORIES, (m) => params.roomIds.includes(m.roomId) && (params.tableName ? m.metadata?.type === params.tableName : true));
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));
436
655
  memories.sort((a, b) => (b.createdAt ?? 0) - (a.createdAt ?? 0));
437
- if (params.limit) {
438
- return toMemories(memories.slice(0, params.limit));
439
- }
440
- return toMemories(memories);
441
- }
442
- async getMemoryById(id) {
443
- return this.storage.get(COLLECTIONS.MEMORIES, id);
656
+ const sliced = params.limit ? memories.slice(0, params.limit) : memories;
657
+ return sliced.map(toMemory);
444
658
  }
445
659
  async getMemoriesByIds(memoryIds, tableName) {
446
660
  const memories = [];
447
661
  for (const id of memoryIds) {
448
- const memory = await this.storage.get(COLLECTIONS.MEMORIES, id);
449
- if (memory) {
450
- if (tableName && memory.metadata?.type !== tableName)
451
- continue;
452
- memories.push(toMemory(memory));
453
- }
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));
454
668
  }
455
669
  return memories;
456
670
  }
457
671
  async getCachedEmbeddings(params) {
458
- const memories = await this.storage.getWhere(COLLECTIONS.MEMORIES, (m) => m.metadata?.type === params.query_table_name);
672
+ const memories = await this.storage.getWhere(COLLECTIONS.MEMORIES, (m) => m.metadata?.type === params.query_table_name && !!m.embedding);
459
673
  const results = [];
460
674
  for (const memory of memories) {
461
675
  if (!memory.embedding)
462
676
  continue;
463
- const memoryRecord = memory;
464
- const fieldValue = memoryRecord[params.query_field_name];
465
- const content = String(fieldValue ?? "");
466
- const score = this.simpleStringScore(params.query_input, content);
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);
467
681
  if (score <= params.query_threshold) {
468
- results.push({
469
- embedding: memory.embedding,
470
- levenshtein_score: score
471
- });
682
+ results.push({ embedding: memory.embedding, levenshtein_score: score });
472
683
  }
473
684
  }
685
+ results.sort((a, b) => a.levenshtein_score - b.levenshtein_score);
474
686
  return results.slice(0, params.query_match_count);
475
687
  }
476
- simpleStringScore(a, b) {
477
- if (a === b)
478
- return 0;
479
- const aLower = a.toLowerCase();
480
- const bLower = b.toLowerCase();
481
- if (aLower === bLower)
482
- return 0.1;
483
- if (aLower.includes(bLower) || bLower.includes(aLower))
484
- return 0.3;
485
- return 1;
486
- }
487
- async log(params) {
488
- const id = crypto.randomUUID();
489
- const log = {
490
- id,
491
- entityId: params.entityId,
492
- roomId: params.roomId,
493
- body: params.body,
494
- type: params.type,
495
- createdAt: new Date
496
- };
497
- await this.storage.set(COLLECTIONS.LOGS, id, log);
498
- }
499
- async getLogs(params) {
500
- let logs = await this.storage.getWhere(COLLECTIONS.LOGS, (l) => {
501
- if (params.entityId && l.entityId !== params.entityId)
502
- return false;
503
- if (params.roomId && l.roomId !== params.roomId)
504
- return false;
505
- if (params.type && l.type !== params.type)
506
- return false;
507
- return true;
508
- });
509
- logs.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
510
- if (params.offset) {
511
- logs = logs.slice(params.offset);
512
- }
513
- if (params.count) {
514
- logs = logs.slice(0, params.count);
515
- }
516
- return logs;
517
- }
518
- async deleteLog(logId) {
519
- await this.storage.delete(COLLECTIONS.LOGS, logId);
520
- }
521
688
  async searchMemories(params) {
522
689
  const threshold = params.match_threshold ?? 0.5;
523
- const count = params.count ?? 10;
524
- const results = await this.vectorIndex.search(params.embedding, count * 2, threshold);
690
+ const limit = params.limit ?? 10;
691
+ const results = await this.vectorIndex.search(params.embedding, limit * 2, threshold);
525
692
  const memories = [];
526
693
  for (const result of results) {
527
694
  const memory = await this.storage.get(COLLECTIONS.MEMORIES, result.id);
@@ -537,101 +704,223 @@ class InMemoryDatabaseAdapter extends DatabaseAdapter {
537
704
  continue;
538
705
  if (params.unique && !memory.unique)
539
706
  continue;
540
- memories.push({
541
- ...toMemory(memory),
542
- similarity: result.similarity
543
- });
707
+ memories.push({ ...toMemory(memory), similarity: result.similarity });
544
708
  }
545
- return memories.slice(0, count);
709
+ return memories.slice(0, limit);
546
710
  }
547
- async createMemory(memory, tableName, unique = false) {
548
- const id = memory.id ?? crypto.randomUUID();
549
- const now = Date.now();
550
- const storedMemory = {
551
- ...memory,
552
- id,
553
- agentId: memory.agentId ?? this.agentId,
554
- unique: unique || memory.unique,
555
- createdAt: memory.createdAt ?? now,
556
- metadata: {
557
- ...memory.metadata ?? {},
558
- type: tableName
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);
559
729
  }
560
- };
561
- await this.storage.set(COLLECTIONS.MEMORIES, id, storedMemory);
562
- if (memory.embedding && memory.embedding.length > 0) {
563
- await this.vectorIndex.add(id, memory.embedding);
564
- }
565
- return id;
566
- }
567
- async updateMemory(memory) {
568
- const existing = await this.getMemoryById(memory.id);
569
- if (!existing)
570
- return false;
571
- const updated = {
572
- ...existing,
573
- ...memory,
574
- metadata: {
575
- ...existing.metadata ?? {},
576
- ...memory.metadata ?? {}
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);
577
750
  }
578
- };
579
- await this.storage.set(COLLECTIONS.MEMORIES, memory.id, updated);
580
- if (memory.embedding && memory.embedding.length > 0) {
581
- await this.vectorIndex.add(memory.id, memory.embedding);
582
751
  }
583
- return true;
584
752
  }
585
- async deleteMemory(memoryId) {
586
- await this.storage.delete(COLLECTIONS.MEMORIES, memoryId);
587
- await this.vectorIndex.remove(memoryId);
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
+ }
588
776
  }
589
- async deleteManyMemories(memoryIds) {
777
+ async deleteMemories(memoryIds) {
590
778
  for (const id of memoryIds) {
591
- await this.deleteMemory(id);
779
+ await this.storage.delete(COLLECTIONS.MEMORIES, id);
780
+ await this.vectorIndex.remove(id);
592
781
  }
593
782
  }
594
- async deleteAllMemories(roomId, tableName) {
595
- const memories = await this.getMemories({ roomId, tableName });
596
- await this.deleteManyMemories(memories.map((m) => m.id).filter((id) => id !== undefined));
597
- }
598
- async countMemories(roomId, unique = false, tableName) {
599
- return this.storage.count(COLLECTIONS.MEMORIES, (memory) => {
600
- if (memory.roomId !== roomId)
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))
601
795
  return false;
602
- if (unique && !memory.unique)
796
+ if (params.unique && !m.unique)
603
797
  return false;
604
- if (tableName && memory.metadata?.type !== tableName)
798
+ if (params.tableName && m.metadata?.type !== params.tableName)
605
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
+ }
606
811
  return true;
607
812
  });
608
813
  }
609
814
  async getMemoriesByWorldId(params) {
610
- const memories = await this.storage.getWhere(COLLECTIONS.MEMORIES, (m) => m.worldId === params.worldId && (params.tableName ? m.metadata?.type === params.tableName : true));
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));
611
817
  memories.sort((a, b) => (b.createdAt ?? 0) - (a.createdAt ?? 0));
612
- if (params.count) {
613
- return toMemories(memories.slice(0, params.count));
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);
614
851
  }
615
- return toMemories(memories);
616
852
  }
617
- async createWorld(world) {
618
- const id = world.id ?? crypto.randomUUID();
619
- await this.storage.set(COLLECTIONS.WORLDS, id, { ...world, id });
620
- return id;
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;
621
861
  }
622
- async getWorld(id) {
623
- return this.storage.get(COLLECTIONS.WORLDS, id);
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
+ }
624
869
  }
625
- async removeWorld(id) {
626
- await this.storage.delete(COLLECTIONS.WORLDS, id);
870
+ async deleteLogs(logIds) {
871
+ for (const id of logIds) {
872
+ await this.storage.delete(COLLECTIONS.LOGS, id);
873
+ }
627
874
  }
628
875
  async getAllWorlds() {
629
876
  return this.storage.getAll(COLLECTIONS.WORLDS);
630
877
  }
631
- async updateWorld(world) {
632
- if (!world.id)
633
- return;
634
- await this.storage.set(COLLECTIONS.WORLDS, world.id, world);
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 ?? randomUUID();
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 ?? randomUUID();
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
+ }
635
924
  }
636
925
  async getRoomsByIds(roomIds) {
637
926
  const rooms = [];
@@ -640,107 +929,169 @@ class InMemoryDatabaseAdapter extends DatabaseAdapter {
640
929
  if (room)
641
930
  rooms.push(room);
642
931
  }
643
- return rooms.length > 0 ? rooms : null;
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;
644
960
  }
645
961
  async createRooms(rooms) {
646
962
  const ids = [];
647
963
  for (const room of rooms) {
648
- const id = room.id ?? crypto.randomUUID();
964
+ const id = room.id ?? randomUUID();
649
965
  await this.storage.set(COLLECTIONS.ROOMS, id, { ...room, id });
650
966
  ids.push(id);
651
967
  }
652
968
  return ids;
653
969
  }
654
- async deleteRoom(roomId) {
655
- await this.storage.delete(COLLECTIONS.ROOMS, roomId);
656
- await this.storage.deleteWhere(COLLECTIONS.PARTICIPANTS, (p) => p.roomId === roomId);
657
- await this.storage.deleteWhere(COLLECTIONS.MEMORIES, (m) => m.roomId === roomId);
970
+ async upsertRooms(rooms) {
971
+ for (const room of rooms) {
972
+ const id = room.id ?? randomUUID();
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
+ }
658
980
  }
659
- async deleteRoomsByWorldId(worldId) {
660
- const rooms = await this.getRoomsByWorld(worldId);
981
+ async updateRooms(rooms) {
661
982
  for (const room of rooms) {
662
- if (room.id) {
663
- await this.deleteRoom(room.id);
664
- }
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
+ });
665
992
  }
666
993
  }
667
- async updateRoom(room) {
668
- if (!room.id)
994
+ async deleteRooms(roomIds) {
995
+ if (roomIds.length === 0)
669
996
  return;
670
- await this.storage.set(COLLECTIONS.ROOMS, room.id, room);
671
- }
672
- async getRoomsForParticipant(entityId) {
673
- const participants = await this.storage.getWhere(COLLECTIONS.PARTICIPANTS, (p) => p.entityId === entityId);
674
- return participants.map((p) => p.roomId);
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));
675
1003
  }
676
- async getRoomsForParticipants(userIds) {
677
- const participants = await this.storage.getWhere(COLLECTIONS.PARTICIPANTS, (p) => userIds.includes(p.entityId));
678
- return [...new Set(participants.map((p) => p.roomId))];
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;
679
1019
  }
680
- async getRoomsByWorld(worldId) {
681
- return this.storage.getWhere(COLLECTIONS.ROOMS, (r) => r.worldId === worldId);
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;
682
1032
  }
683
- async removeParticipant(entityId, roomId) {
684
- const participants = await this.storage.getWhere(COLLECTIONS.PARTICIPANTS, (p) => p.entityId === entityId && p.roomId === roomId);
685
- if (participants.length === 0)
686
- return false;
687
- for (const p of participants) {
688
- if (p.id) {
689
- await this.storage.delete(COLLECTIONS.PARTICIPANTS, p.id);
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);
690
1045
  }
691
1046
  }
692
- return true;
693
1047
  }
694
- async getParticipantsForEntity(entityId) {
695
- const stored = await this.storage.getWhere(COLLECTIONS.PARTICIPANTS, (p) => p.entityId === entityId);
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));
696
1053
  const participants = [];
697
1054
  for (const p of stored) {
698
1055
  const entity = await this.storage.get(COLLECTIONS.ENTITIES, p.entityId);
699
- if (entity) {
700
- participants.push({
701
- id: p.id,
702
- entity
703
- });
704
- }
1056
+ if (entity)
1057
+ participants.push({ id: p.id, entity });
705
1058
  }
706
1059
  return participants;
707
1060
  }
708
- async getParticipantsForRoom(roomId) {
709
- const participants = await this.storage.getWhere(COLLECTIONS.PARTICIPANTS, (p) => p.roomId === roomId);
710
- return participants.map((p) => p.entityId);
711
- }
712
- async isRoomParticipant(roomId, entityId) {
713
- const participants = await this.storage.getWhere(COLLECTIONS.PARTICIPANTS, (p) => p.roomId === roomId && p.entityId === entityId);
714
- return participants.length > 0;
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;
715
1071
  }
716
- async addParticipantsRoom(entityIds, roomId) {
717
- for (const entityId of entityIds) {
718
- const exists = await this.isRoomParticipant(roomId, entityId);
719
- if (!exists) {
720
- const id = crypto.randomUUID();
721
- const participant = {
722
- id,
723
- entityId,
724
- roomId
725
- };
726
- await this.storage.set(COLLECTIONS.PARTICIPANTS, id, participant);
727
- }
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);
728
1077
  }
729
- return true;
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;
730
1088
  }
731
- async getParticipantUserState(roomId, entityId) {
732
- const participants = await this.storage.getWhere(COLLECTIONS.PARTICIPANTS, (p) => p.roomId === roomId && p.entityId === entityId);
733
- if (participants.length === 0)
734
- return null;
735
- const state = participants[0].userState;
736
- if (state === "FOLLOWED" || state === "MUTED")
737
- return state;
738
- return null;
739
- }
740
- async setParticipantUserState(roomId, entityId, state) {
741
- const participants = await this.storage.getWhere(COLLECTIONS.PARTICIPANTS, (p) => p.roomId === roomId && p.entityId === entityId);
742
- for (const p of participants) {
743
- if (p.id) {
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;
744
1095
  await this.storage.set(COLLECTIONS.PARTICIPANTS, p.id, {
745
1096
  ...p,
746
1097
  userState: state
@@ -748,157 +1099,313 @@ class InMemoryDatabaseAdapter extends DatabaseAdapter {
748
1099
  }
749
1100
  }
750
1101
  }
751
- async createRelationship(params) {
752
- const id = crypto.randomUUID();
753
- const relationship = {
754
- id,
755
- sourceEntityId: params.sourceEntityId,
756
- targetEntityId: params.targetEntityId,
757
- agentId: this.agentId,
758
- tags: params.tags ?? [],
759
- metadata: params.metadata ?? {},
760
- createdAt: new Date().toISOString()
761
- };
762
- await this.storage.set(COLLECTIONS.RELATIONSHIPS, id, relationship);
763
- return true;
764
- }
765
- async getRelationship(params) {
766
- const relationships = await this.storage.getWhere(COLLECTIONS.RELATIONSHIPS, (r2) => r2.sourceEntityId === params.sourceEntityId && r2.targetEntityId === params.targetEntityId);
767
- if (relationships.length === 0)
768
- return null;
769
- const r = relationships[0];
770
- return {
771
- id: r.id,
772
- sourceEntityId: r.sourceEntityId,
773
- targetEntityId: r.targetEntityId,
774
- agentId: r.agentId ?? this.agentId,
775
- tags: r.tags ?? [],
776
- metadata: r.metadata ?? {},
777
- createdAt: r.createdAt
778
- };
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;
779
1110
  }
780
1111
  async getRelationships(params) {
781
- const stored = await this.storage.getWhere(COLLECTIONS.RELATIONSHIPS, (r) => {
782
- const isInvolved = r.sourceEntityId === params.entityId || r.targetEntityId === params.entityId;
783
- if (!isInvolved)
784
- return false;
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
+ }
785
1119
  if (params.tags && params.tags.length > 0) {
786
- return params.tags.some((tag) => r.tags?.includes(tag));
1120
+ const tags = r.tags ?? [];
1121
+ if (!params.tags.some((t) => tags.includes(t)))
1122
+ return false;
787
1123
  }
788
1124
  return true;
789
1125
  });
790
- return stored.map((r) => ({
791
- id: r.id,
792
- sourceEntityId: r.sourceEntityId,
793
- targetEntityId: r.targetEntityId,
794
- agentId: r.agentId ?? this.agentId,
795
- tags: r.tags ?? [],
796
- metadata: r.metadata ?? {},
797
- createdAt: r.createdAt
798
- }));
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;
799
1150
  }
800
- async updateRelationship(relationship) {
801
- const existing = await this.getRelationship({
802
- sourceEntityId: relationship.sourceEntityId,
803
- targetEntityId: relationship.targetEntityId
804
- });
805
- if (!existing || !existing.id)
806
- return;
807
- const stored = {
808
- id: existing.id,
809
- sourceEntityId: relationship.sourceEntityId,
810
- targetEntityId: relationship.targetEntityId,
811
- agentId: relationship.agentId,
812
- tags: relationship.tags ?? existing.tags ?? [],
813
- metadata: { ...existing.metadata ?? {}, ...relationship.metadata ?? {} },
814
- createdAt: existing.createdAt ?? new Date().toISOString()
815
- };
816
- await this.storage.set(COLLECTIONS.RELATIONSHIPS, existing.id, stored);
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;
817
1159
  }
818
- async getCache(key) {
819
- const cached = await this.storage.get(COLLECTIONS.CACHE, key);
820
- if (!cached)
821
- return;
822
- if (cached.expiresAt && Date.now() > cached.expiresAt) {
823
- await this.deleteCache(key);
824
- return;
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 ?? existing.sourceEntityId,
1170
+ targetEntityId: rel.targetEntityId ?? existing.targetEntityId,
1171
+ agentId: rel.agentId ?? existing.agentId,
1172
+ tags: rel.tags ?? existing.tags,
1173
+ metadata: { ...existing.metadata ?? {}, ...rel.metadata ?? {} }
1174
+ };
1175
+ await this.storage.set(COLLECTIONS.RELATIONSHIPS, rel.id, next);
825
1176
  }
826
- return cached.value;
827
1177
  }
828
- async setCache(key, value) {
829
- await this.storage.set(COLLECTIONS.CACHE, key, { value });
830
- return true;
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;
831
1255
  }
832
- async deleteCache(key) {
833
- return this.storage.delete(COLLECTIONS.CACHE, key);
1256
+ async setCaches(entries) {
1257
+ for (const { key, value } of entries) {
1258
+ await this.storage.set(COLLECTIONS.CACHE, key, { value });
1259
+ }
1260
+ return true;
834
1261
  }
835
- async createTask(task) {
836
- const id = task.id ?? crypto.randomUUID();
837
- await this.storage.set(COLLECTIONS.TASKS, id, { ...task, id });
838
- return id;
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;
839
1270
  }
840
1271
  async getTasks(params) {
841
- return this.storage.getWhere(COLLECTIONS.TASKS, (t) => {
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
+ }
842
1278
  if (params.roomId && t.roomId !== params.roomId)
843
1279
  return false;
844
1280
  if (params.entityId && t.entityId !== params.entityId)
845
1281
  return false;
846
1282
  if (params.tags && params.tags.length > 0) {
847
- if (!t.tags?.some((tag) => params.tags?.includes(tag)))
1283
+ const tags = t.tags ?? [];
1284
+ if (!params.tags.some((tag) => tags.includes(tag)))
848
1285
  return false;
849
1286
  }
850
1287
  return true;
851
1288
  });
852
- }
853
- async getTask(id) {
854
- return this.storage.get(COLLECTIONS.TASKS, id);
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;
855
1295
  }
856
1296
  async getTasksByName(name) {
857
1297
  return this.storage.getWhere(COLLECTIONS.TASKS, (t) => t.name === name);
858
1298
  }
859
- async updateTask(id, task) {
860
- const existing = await this.getTask(id);
861
- if (!existing)
862
- return;
863
- await this.storage.set(COLLECTIONS.TASKS, id, { ...existing, ...task });
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;
864
1307
  }
865
- async deleteTask(id) {
866
- await this.storage.delete(COLLECTIONS.TASKS, id);
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;
867
1316
  }
868
- async getPairingRequests(channel, agentId) {
869
- return this.storage.getWhere(COLLECTIONS.PAIRING_REQUESTS, (r) => r.channel === channel && r.agentId === agentId);
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
+ }
870
1324
  }
871
- async createPairingRequest(request) {
872
- const id = request.id ?? crypto.randomUUID();
873
- await this.storage.set(COLLECTIONS.PAIRING_REQUESTS, id, { ...request, id });
874
- return id;
1325
+ async deleteTasks(taskIds) {
1326
+ for (const id of taskIds) {
1327
+ await this.storage.delete(COLLECTIONS.TASKS, id);
1328
+ }
875
1329
  }
876
- async updatePairingRequest(request) {
877
- const existing = await this.storage.get(COLLECTIONS.PAIRING_REQUESTS, request.id);
878
- if (existing) {
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 ?? randomUUID();
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;
879
1365
  await this.storage.set(COLLECTIONS.PAIRING_REQUESTS, request.id, {
880
1366
  ...existing,
881
1367
  ...request
882
1368
  });
883
1369
  }
884
1370
  }
885
- async deletePairingRequest(id) {
886
- await this.storage.delete(COLLECTIONS.PAIRING_REQUESTS, id);
1371
+ async deletePairingRequests(ids) {
1372
+ for (const id of ids) {
1373
+ await this.storage.delete(COLLECTIONS.PAIRING_REQUESTS, id);
1374
+ }
887
1375
  }
888
- async getPairingAllowlist(channel, agentId) {
889
- return this.storage.getWhere(COLLECTIONS.PAIRING_ALLOWLIST, (e) => e.channel === channel && e.agentId === agentId);
1376
+ async createPairingAllowlistEntries(entries) {
1377
+ const ids = [];
1378
+ for (const entry of entries) {
1379
+ const id = entry.id ?? randomUUID();
1380
+ await this.storage.set(COLLECTIONS.PAIRING_ALLOWLIST, id, {
1381
+ ...entry,
1382
+ id
1383
+ });
1384
+ ids.push(id);
1385
+ }
1386
+ return ids;
890
1387
  }
891
- async createPairingAllowlistEntry(entry) {
892
- const id = entry.id ?? crypto.randomUUID();
893
- await this.storage.set(COLLECTIONS.PAIRING_ALLOWLIST, id, { ...entry, id });
894
- return id;
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
+ }
895
1400
  }
896
- async deletePairingAllowlistEntry(id) {
897
- await this.storage.delete(COLLECTIONS.PAIRING_ALLOWLIST, id);
1401
+ async deletePairingAllowlistEntries(ids) {
1402
+ for (const id of ids) {
1403
+ await this.storage.delete(COLLECTIONS.PAIRING_ALLOWLIST, id);
1404
+ }
898
1405
  }
899
1406
  }
900
1407
 
901
- // typescript/storage-memory.ts
1408
+ // storage-memory.ts
902
1409
  class MemoryStorage {
903
1410
  collections = new Map;
904
1411
  ready = false;
@@ -977,8 +1484,8 @@ class MemoryStorage {
977
1484
  }
978
1485
  }
979
1486
 
980
- // typescript/index.ts
981
- var GLOBAL_SINGLETONS = Symbol.for("@elizaos/plugin-inmemorydb/global-singletons");
1487
+ // index.ts
1488
+ var GLOBAL_SINGLETONS = Symbol.for("elizaos.plugin-inmemorydb.global-singletons");
982
1489
  var globalSymbols = globalThis;
983
1490
  if (!globalSymbols[GLOBAL_SINGLETONS]) {
984
1491
  globalSymbols[GLOBAL_SINGLETONS] = {};
@@ -995,22 +1502,22 @@ var plugin = {
995
1502
  description: "Pure in-memory, ephemeral database storage for elizaOS - no persistence",
996
1503
  async init(_config, runtime) {
997
1504
  logger2.info({ src: "plugin:inmemorydb" }, "Initializing in-memory database plugin");
998
- const runtimeWithAdapter = runtime;
999
- const hasAdapter = runtimeWithAdapter.adapter !== undefined || runtimeWithAdapter.databaseAdapter !== undefined || (runtimeWithAdapter.hasDatabaseAdapter?.() ?? false);
1505
+ const r = runtime;
1506
+ const hasAdapter = r.adapter !== undefined || r.databaseAdapter !== undefined || (r.hasDatabaseAdapter?.() ?? false);
1000
1507
  if (hasAdapter) {
1001
1508
  logger2.debug({ src: "plugin:inmemorydb" }, "Database adapter already exists, skipping initialization");
1002
1509
  return;
1003
1510
  }
1004
1511
  const adapter = createDatabaseAdapter(runtime.agentId);
1005
- await adapter.init();
1006
- runtime.registerDatabaseAdapter(adapter);
1512
+ await adapter.initialize();
1513
+ r.registerDatabaseAdapter?.(adapter);
1007
1514
  logger2.success({ src: "plugin:inmemorydb" }, "In-memory database adapter registered successfully");
1008
1515
  }
1009
1516
  };
1010
- var typescript_default = plugin;
1517
+ var plugin_inmemorydb_default = plugin;
1011
1518
  export {
1012
1519
  plugin,
1013
- typescript_default as default,
1520
+ plugin_inmemorydb_default as default,
1014
1521
  createDatabaseAdapter,
1015
1522
  MemoryStorage,
1016
1523
  InMemoryDatabaseAdapter,
@@ -1018,5 +1525,5 @@ export {
1018
1525
  COLLECTIONS
1019
1526
  };
1020
1527
 
1021
- //# debugId=A96220E613784BE464756E2164756E21
1528
+ //# debugId=417ABAD5882812F964756E2164756E21
1022
1529
  //# sourceMappingURL=index.js.map