@ainetwork/adk-provider-memory-mongodb 0.4.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/dist/{chunk-EPJZT2YE.js → chunk-2XJ6S2W5.js} +6 -1
  2. package/dist/chunk-2XJ6S2W5.js.map +1 -0
  3. package/dist/{chunk-T5WRFXBY.js → chunk-QULDFKGZ.js} +2 -1
  4. package/dist/chunk-QULDFKGZ.js.map +1 -0
  5. package/dist/chunk-RC275GLE.js +70 -0
  6. package/dist/chunk-RC275GLE.js.map +1 -0
  7. package/dist/{chunk-ENGJ6NTO.js → chunk-SJ2FHHN6.js} +10 -10
  8. package/dist/chunk-SJ2FHHN6.js.map +1 -0
  9. package/dist/index.cjs +235 -67
  10. package/dist/index.cjs.map +1 -1
  11. package/dist/index.d.cts +5 -3
  12. package/dist/index.d.ts +5 -3
  13. package/dist/index.js +155 -55
  14. package/dist/index.js.map +1 -1
  15. package/dist/models/messages.model.cjs +1 -0
  16. package/dist/models/messages.model.cjs.map +1 -1
  17. package/dist/models/messages.model.js +1 -1
  18. package/dist/models/threads.model.cjs +5 -0
  19. package/dist/models/threads.model.cjs.map +1 -1
  20. package/dist/models/threads.model.d.cts +4 -0
  21. package/dist/models/threads.model.d.ts +4 -0
  22. package/dist/models/threads.model.js +1 -1
  23. package/dist/models/user-workflow.model.cjs +105 -0
  24. package/dist/models/user-workflow.model.cjs.map +1 -0
  25. package/dist/models/user-workflow.model.d.cts +92 -0
  26. package/dist/models/user-workflow.model.d.ts +92 -0
  27. package/dist/models/user-workflow.model.js +9 -0
  28. package/dist/models/{workflow.model.cjs → workflow-template.model.cjs} +15 -15
  29. package/dist/models/workflow-template.model.cjs.map +1 -0
  30. package/dist/models/{workflow.model.d.ts → workflow-template.model.d.cts} +10 -13
  31. package/dist/models/{workflow.model.d.cts → workflow-template.model.d.ts} +10 -13
  32. package/dist/models/workflow-template.model.js +9 -0
  33. package/dist/models/workflow-template.model.js.map +1 -0
  34. package/implements/base.memory.ts +49 -12
  35. package/implements/thread.memory.ts +31 -16
  36. package/implements/user-workflow.memory.ts +87 -0
  37. package/implements/workflow-template.memory.ts +69 -0
  38. package/models/messages.model.ts +2 -0
  39. package/models/threads.model.ts +6 -0
  40. package/models/user-workflow.model.ts +91 -0
  41. package/models/{workflow.model.ts → workflow-template.model.ts} +10 -10
  42. package/package.json +3 -3
  43. package/dist/chunk-ENGJ6NTO.js.map +0 -1
  44. package/dist/chunk-EPJZT2YE.js.map +0 -1
  45. package/dist/chunk-T5WRFXBY.js.map +0 -1
  46. package/dist/models/workflow.model.cjs.map +0 -1
  47. package/dist/models/workflow.model.js +0 -9
  48. package/implements/workflow.memory.ts +0 -78
  49. /package/dist/models/{workflow.model.js.map → user-workflow.model.js.map} +0 -0
package/dist/index.cjs CHANGED
@@ -35,7 +35,7 @@ __export(index_exports, {
35
35
  module.exports = __toCommonJS(index_exports);
36
36
 
37
37
  // implements/base.memory.ts
38
- var import_mongoose10 = __toESM(require("mongoose"), 1);
38
+ var import_mongoose12 = __toESM(require("mongoose"), 1);
39
39
  var import_logger2 = require("@ainetwork/adk/utils/logger");
40
40
 
41
41
  // models/agent.model.ts
@@ -263,6 +263,11 @@ var ThreadObjectSchema = new import_mongoose4.Schema(
263
263
  type: Boolean,
264
264
  required: false,
265
265
  default: false
266
+ },
267
+ workflowId: {
268
+ type: String,
269
+ required: false,
270
+ index: true
266
271
  }
267
272
  },
268
273
  {
@@ -321,6 +326,7 @@ var MessageObjectSchema = new import_mongoose6.Schema(
321
326
  timestamps: true
322
327
  }
323
328
  );
329
+ MessageObjectSchema.index({ threadId: 1, messageId: 1 }, { unique: true });
324
330
  var MessageModel = import_mongoose7.default.model("Message", MessageObjectSchema);
325
331
 
326
332
  // implements/thread.memory.ts
@@ -345,6 +351,7 @@ var MongoDBThread = class {
345
351
  type: thread.type,
346
352
  title: thread.title || "New thread",
347
353
  isPinned: thread.isPinned ?? false,
354
+ workflowId: thread.workflowId,
348
355
  messages: []
349
356
  };
350
357
  messages.forEach((message) => {
@@ -359,31 +366,39 @@ var MongoDBThread = class {
359
366
  return threadObject;
360
367
  }, `getThread(${userId}, ${threadId})`);
361
368
  }
362
- async createThread(type, userId, threadId, title) {
369
+ async createThread(type, userId, threadId, title, workflowId) {
363
370
  return this.executeWithRetry(async () => {
364
371
  await ThreadModel.create({
365
372
  type,
366
373
  userId,
367
374
  threadId,
368
- title
375
+ title,
376
+ workflowId
369
377
  });
370
- return { type, userId, threadId, title, messages: [] };
378
+ return { type, userId, threadId, title, workflowId, messages: [] };
371
379
  }, `createThread(${userId}, ${threadId})`);
372
380
  }
373
381
  async addMessagesToThread(userId, threadId, messages) {
374
382
  return this.executeWithRetry(async () => {
375
- await ThreadModel.updateOne({ threadId, userId }, { $set: {} });
376
- for (const message of messages) {
377
- await MessageModel.create({
378
- threadId,
379
- messageId: message.messageId,
380
- userId,
381
- role: message.role,
382
- content: message.content,
383
- timestamp: message.timestamp,
384
- metadata: message.metadata
385
- });
383
+ if (messages.length > 0) {
384
+ const messageIds = messages.map((m) => m.messageId);
385
+ await MessageModel.deleteMany({ threadId, userId, messageId: { $in: messageIds } });
386
+ await MessageModel.insertMany(
387
+ messages.map((message) => ({
388
+ threadId,
389
+ messageId: message.messageId,
390
+ userId,
391
+ role: message.role,
392
+ content: message.content,
393
+ timestamp: message.timestamp,
394
+ metadata: message.metadata
395
+ }))
396
+ );
386
397
  }
398
+ await ThreadModel.updateOne(
399
+ { threadId, userId },
400
+ { $set: { updatedAt: /* @__PURE__ */ new Date() } }
401
+ );
387
402
  }, `addMessagesToThread(${userId}, ${threadId})`);
388
403
  }
389
404
  async deleteThread(userId, threadId) {
@@ -393,10 +408,13 @@ var MongoDBThread = class {
393
408
  await ThreadModel.deleteOne({ userId, threadId }).maxTimeMS(timeout);
394
409
  }, `deleteThread(${userId}, ${threadId})`);
395
410
  }
396
- async listThreads(userId) {
411
+ async listThreads(userId, filter) {
397
412
  return this.executeWithRetry(async () => {
398
413
  const timeout = this.getOperationTimeout();
399
- const threads = await ThreadModel.find({ userId }).sort({ updatedAt: -1 }).maxTimeMS(timeout);
414
+ const query = { userId };
415
+ if (filter?.workflowId) query.workflowId = filter.workflowId;
416
+ if (filter?.type) query.type = filter.type;
417
+ const threads = await ThreadModel.find(query).sort({ updatedAt: -1 }).maxTimeMS(timeout);
400
418
  const data = threads.map((thread) => {
401
419
  return {
402
420
  type: thread.type,
@@ -404,7 +422,9 @@ var MongoDBThread = class {
404
422
  threadId: thread.threadId,
405
423
  title: thread.title,
406
424
  isPinned: thread.isPinned ?? false,
407
- updatedAt: thread.updatedAt
425
+ workflowId: thread.workflowId,
426
+ createdAt: thread.createdAt?.toISOString(),
427
+ updatedAt: thread.updatedAt?.toISOString()
408
428
  };
409
429
  });
410
430
  return data;
@@ -421,10 +441,10 @@ var MongoDBThread = class {
421
441
  }
422
442
  };
423
443
 
424
- // models/workflow.model.ts
444
+ // models/user-workflow.model.ts
425
445
  var import_mongoose8 = require("mongoose");
426
446
  var import_mongoose9 = __toESM(require("mongoose"), 1);
427
- var WorkflowObjectSchema = new import_mongoose8.Schema(
447
+ var UserWorkflowObjectSchema = new import_mongoose8.Schema(
428
448
  {
429
449
  workflowId: {
430
450
  type: String,
@@ -432,84 +452,203 @@ var WorkflowObjectSchema = new import_mongoose8.Schema(
432
452
  unique: true
433
453
  },
434
454
  userId: {
435
- type: String
455
+ type: String,
456
+ required: true,
457
+ index: true
436
458
  },
437
459
  title: {
438
460
  type: String,
439
461
  required: true
440
462
  },
441
463
  description: {
442
- type: String,
443
- required: true
464
+ type: String
444
465
  },
445
466
  active: {
446
467
  type: Boolean,
447
468
  required: true,
448
469
  default: false
449
470
  },
471
+ templateId: {
472
+ type: String
473
+ },
450
474
  content: {
451
475
  type: String,
452
476
  required: true
453
477
  },
454
478
  variables: {
455
479
  type: import_mongoose8.Schema.Types.Mixed
480
+ },
481
+ variableValues: {
482
+ type: import_mongoose8.Schema.Types.Mixed
483
+ },
484
+ schedule: {
485
+ type: String
486
+ },
487
+ timezone: {
488
+ type: String
489
+ },
490
+ lastRunAt: {
491
+ type: Number
492
+ },
493
+ nextRunAt: {
494
+ type: Number
495
+ },
496
+ lastThreadId: {
497
+ type: String
456
498
  }
457
499
  },
458
500
  {
459
501
  timestamps: true
460
502
  }
461
503
  );
462
- var WorkflowModel = import_mongoose9.default.model("Workflow", WorkflowObjectSchema);
504
+ var UserWorkflowModel = import_mongoose9.default.model(
505
+ "UserWorkflow",
506
+ UserWorkflowObjectSchema
507
+ );
463
508
 
464
- // implements/workflow.memory.ts
465
- var MongoDBWorkflow = class {
509
+ // implements/user-workflow.memory.ts
510
+ var MongoDBUserWorkflow = class {
466
511
  executeWithRetry;
467
512
  getOperationTimeout;
468
513
  constructor(executeWithRetry, getOperationTimeout) {
469
514
  this.executeWithRetry = executeWithRetry;
470
515
  this.getOperationTimeout = getOperationTimeout;
471
516
  }
472
- async createWorkflow(workflow) {
517
+ async createUserWorkflow(workflow) {
473
518
  return this.executeWithRetry(async () => {
474
- const timeout = this.getOperationTimeout();
475
- const created = await WorkflowModel.create(workflow);
519
+ const created = await UserWorkflowModel.create(workflow);
476
520
  return created.toObject();
477
- }, "createWorkflow()");
521
+ }, "createUserWorkflow()");
478
522
  }
479
- async getWorkflow(workflowId) {
523
+ async getUserWorkflow(workflowId) {
480
524
  return this.executeWithRetry(async () => {
481
525
  const timeout = this.getOperationTimeout();
482
- const workflow = await WorkflowModel.findOne({
483
- workflowId
484
- }).maxTimeMS(timeout).lean();
526
+ const workflow = await UserWorkflowModel.findOne({ workflowId }).maxTimeMS(timeout).lean();
485
527
  return workflow || void 0;
486
- }, "getWorkflow()");
528
+ }, "getUserWorkflow()");
487
529
  }
488
- async updateWorkflow(workflowId, updates) {
530
+ async updateUserWorkflow(workflowId, updates) {
489
531
  if (!updates.userId) {
490
- throw new Error("userId is required for updateWorkflow");
532
+ throw new Error("userId is required for updateUserWorkflow");
491
533
  }
534
+ const { userId, workflowId: _workflowId, ...mutableUpdates } = updates;
492
535
  return this.executeWithRetry(async () => {
493
536
  const timeout = this.getOperationTimeout();
494
- await WorkflowModel.updateOne(
495
- { workflowId, userId: updates.userId },
496
- { $set: updates }
537
+ await UserWorkflowModel.updateOne(
538
+ { workflowId, userId },
539
+ { $set: mutableUpdates }
497
540
  ).maxTimeMS(timeout);
498
- }, "updateWorkflow()");
541
+ }, "updateUserWorkflow()");
499
542
  }
500
- async deleteWorkflow(workflowId, userId) {
543
+ async deleteUserWorkflow(workflowId, userId) {
501
544
  return this.executeWithRetry(async () => {
502
545
  const timeout = this.getOperationTimeout();
503
- await WorkflowModel.deleteOne({ workflowId, userId }).maxTimeMS(timeout);
504
- }, "deleteWorkflow()");
546
+ await UserWorkflowModel.deleteOne({ workflowId, userId }).maxTimeMS(timeout);
547
+ }, "deleteUserWorkflow()");
505
548
  }
506
- async listWorkflows(userId) {
549
+ async listUserWorkflows(userId) {
507
550
  return this.executeWithRetry(async () => {
508
551
  const timeout = this.getOperationTimeout();
509
- const query = userId ? { $or: [{ userId }, { userId: { $exists: false } }, { userId: null }] } : { $or: [{ userId: { $exists: false } }, { userId: null }] };
510
- const workflows = await WorkflowModel.find(query).maxTimeMS(timeout).lean();
552
+ const query = userId ? { userId } : {};
553
+ const workflows = await UserWorkflowModel.find(query).maxTimeMS(timeout).lean();
511
554
  return workflows;
512
- }, "listWorkflows()");
555
+ }, "listUserWorkflows()");
556
+ }
557
+ async listActiveScheduledWorkflows() {
558
+ return this.executeWithRetry(async () => {
559
+ const timeout = this.getOperationTimeout();
560
+ const workflows = await UserWorkflowModel.find({
561
+ active: true,
562
+ schedule: { $exists: true, $ne: null }
563
+ }).maxTimeMS(timeout).lean();
564
+ return workflows;
565
+ }, "listActiveScheduledWorkflows()");
566
+ }
567
+ };
568
+
569
+ // models/workflow-template.model.ts
570
+ var import_mongoose10 = require("mongoose");
571
+ var import_mongoose11 = __toESM(require("mongoose"), 1);
572
+ var WorkflowTemplateObjectSchema = new import_mongoose10.Schema(
573
+ {
574
+ templateId: {
575
+ type: String,
576
+ required: true,
577
+ unique: true
578
+ },
579
+ title: {
580
+ type: String,
581
+ required: true
582
+ },
583
+ description: {
584
+ type: String,
585
+ required: true
586
+ },
587
+ active: {
588
+ type: Boolean,
589
+ required: true,
590
+ default: false
591
+ },
592
+ content: {
593
+ type: String,
594
+ required: true
595
+ },
596
+ variables: {
597
+ type: import_mongoose10.Schema.Types.Mixed
598
+ }
599
+ },
600
+ {
601
+ timestamps: true
602
+ }
603
+ );
604
+ var WorkflowTemplateModel = import_mongoose11.default.model(
605
+ "WorkflowTemplate",
606
+ WorkflowTemplateObjectSchema
607
+ );
608
+
609
+ // implements/workflow-template.memory.ts
610
+ var MongoDBWorkflowTemplate = class {
611
+ executeWithRetry;
612
+ getOperationTimeout;
613
+ constructor(executeWithRetry, getOperationTimeout) {
614
+ this.executeWithRetry = executeWithRetry;
615
+ this.getOperationTimeout = getOperationTimeout;
616
+ }
617
+ async createTemplate(template) {
618
+ return this.executeWithRetry(async () => {
619
+ const created = await WorkflowTemplateModel.create(template);
620
+ return created.toObject();
621
+ }, "createTemplate()");
622
+ }
623
+ async getTemplate(templateId) {
624
+ return this.executeWithRetry(async () => {
625
+ const timeout = this.getOperationTimeout();
626
+ const template = await WorkflowTemplateModel.findOne({ templateId }).maxTimeMS(timeout).lean();
627
+ return template || void 0;
628
+ }, "getTemplate()");
629
+ }
630
+ async updateTemplate(templateId, updates) {
631
+ const { templateId: _templateId, ...mutableUpdates } = updates;
632
+ return this.executeWithRetry(async () => {
633
+ const timeout = this.getOperationTimeout();
634
+ await WorkflowTemplateModel.updateOne(
635
+ { templateId },
636
+ { $set: mutableUpdates }
637
+ ).maxTimeMS(timeout);
638
+ }, "updateTemplate()");
639
+ }
640
+ async deleteTemplate(templateId) {
641
+ return this.executeWithRetry(async () => {
642
+ const timeout = this.getOperationTimeout();
643
+ await WorkflowTemplateModel.deleteOne({ templateId }).maxTimeMS(timeout);
644
+ }, "deleteTemplate()");
645
+ }
646
+ async listTemplates() {
647
+ return this.executeWithRetry(async () => {
648
+ const timeout = this.getOperationTimeout();
649
+ const templates = await WorkflowTemplateModel.find().maxTimeMS(timeout).lean();
650
+ return templates;
651
+ }, "listTemplates()");
513
652
  }
514
653
  };
515
654
 
@@ -530,7 +669,8 @@ var MongoDBMemory = class _MongoDBMemory {
530
669
  agentMemory;
531
670
  intentMemory;
532
671
  threadMemory;
533
- workflowMemory;
672
+ workflowTemplateMemory;
673
+ userWorkflowMemory;
534
674
  constructor(config) {
535
675
  const cfg = typeof config === "string" ? { uri: config } : config;
536
676
  this.uri = cfg.uri;
@@ -541,7 +681,9 @@ var MongoDBMemory = class _MongoDBMemory {
541
681
  this.threadTTLSeconds = cfg.threadTTLSeconds;
542
682
  }
543
683
  this.connectionConfig = {
544
- maxPoolSize: cfg.maxPoolSize ?? 1,
684
+ maxPoolSize: cfg.maxPoolSize ?? 10,
685
+ minPoolSize: 0,
686
+ maxIdleTimeMS: 3e4,
545
687
  serverSelectionTimeoutMS: cfg.serverSelectionTimeoutMS ?? 3e4,
546
688
  socketTimeoutMS: cfg.socketTimeoutMS ?? 45e3,
547
689
  connectTimeoutMS: cfg.connectTimeoutMS ?? 3e4,
@@ -566,7 +708,11 @@ var MongoDBMemory = class _MongoDBMemory {
566
708
  this.executeWithRetry.bind(this),
567
709
  this.getOperationTimeout.bind(this)
568
710
  );
569
- this.workflowMemory = new MongoDBWorkflow(
711
+ this.workflowTemplateMemory = new MongoDBWorkflowTemplate(
712
+ this.executeWithRetry.bind(this),
713
+ this.getOperationTimeout.bind(this)
714
+ );
715
+ this.userWorkflowMemory = new MongoDBUserWorkflow(
570
716
  this.executeWithRetry.bind(this),
571
717
  this.getOperationTimeout.bind(this)
572
718
  );
@@ -580,29 +726,32 @@ var MongoDBMemory = class _MongoDBMemory {
580
726
  getIntentMemory() {
581
727
  return this.intentMemory;
582
728
  }
583
- getWorkflowMemory() {
584
- return this.workflowMemory;
729
+ getWorkflowTemplateMemory() {
730
+ return this.workflowTemplateMemory;
731
+ }
732
+ getUserWorkflowMemory() {
733
+ return this.userWorkflowMemory;
585
734
  }
586
735
  setupMongooseEventListeners() {
587
736
  if (this.eventListenersSetup) return;
588
737
  this.eventListenersSetup = true;
589
- import_mongoose10.default.connection.on("connected", () => {
738
+ import_mongoose12.default.connection.on("connected", () => {
590
739
  this.connected = true;
591
740
  this.reconnectAttempts = 0;
592
741
  this.reconnecting = false;
593
742
  import_logger2.loggers.agent.info("MongoDB connected successfully");
594
743
  });
595
- import_mongoose10.default.connection.on("disconnected", () => {
744
+ import_mongoose12.default.connection.on("disconnected", () => {
596
745
  this.connected = false;
597
746
  import_logger2.loggers.agent.warn("MongoDB disconnected");
598
747
  this.handleDisconnection();
599
748
  });
600
- import_mongoose10.default.connection.on("error", (error) => {
749
+ import_mongoose12.default.connection.on("error", (error) => {
601
750
  this.connected = false;
602
751
  import_logger2.loggers.agent.error("MongoDB connection error:", error);
603
752
  this.handleDisconnection();
604
753
  });
605
- import_mongoose10.default.connection.on("reconnected", () => {
754
+ import_mongoose12.default.connection.on("reconnected", () => {
606
755
  this.connected = true;
607
756
  this.reconnectAttempts = 0;
608
757
  this.reconnecting = false;
@@ -614,13 +763,13 @@ var MongoDBMemory = class _MongoDBMemory {
614
763
  return;
615
764
  }
616
765
  this.reconnecting = true;
617
- while (this.reconnectAttempts < this.maxReconnectAttempts && !this.isConnected) {
766
+ while (this.reconnectAttempts < this.maxReconnectAttempts && !this.connected) {
618
767
  this.reconnectAttempts++;
619
768
  import_logger2.loggers.agent.info(
620
769
  `Attempting to reconnect to MongoDB (${this.reconnectAttempts}/${this.maxReconnectAttempts})...`
621
770
  );
622
771
  try {
623
- await import_mongoose10.default.connect(this.uri, this.connectionConfig);
772
+ await import_mongoose12.default.connect(this.uri, this.connectionConfig);
624
773
  this.connected = true;
625
774
  this.reconnectAttempts = 0;
626
775
  this.reconnecting = false;
@@ -639,7 +788,7 @@ var MongoDBMemory = class _MongoDBMemory {
639
788
  }
640
789
  }
641
790
  this.reconnecting = false;
642
- if (!this.isConnected) {
791
+ if (!this.connected) {
643
792
  import_logger2.loggers.agent.error(
644
793
  `Failed to reconnect to MongoDB after ${this.maxReconnectAttempts} attempts`
645
794
  );
@@ -650,7 +799,7 @@ var MongoDBMemory = class _MongoDBMemory {
650
799
  return;
651
800
  }
652
801
  try {
653
- await import_mongoose10.default.connect(this.uri, this.connectionConfig);
802
+ await import_mongoose12.default.connect(this.uri, this.connectionConfig);
654
803
  this.connected = true;
655
804
  this.reconnectAttempts = 0;
656
805
  await this.setupTTLIndex();
@@ -661,7 +810,7 @@ var MongoDBMemory = class _MongoDBMemory {
661
810
  }
662
811
  }
663
812
  async disconnect() {
664
- if (!this.isConnected) {
813
+ if (!this.connected) {
665
814
  return;
666
815
  }
667
816
  try {
@@ -669,7 +818,7 @@ var MongoDBMemory = class _MongoDBMemory {
669
818
  clearInterval(this.orphanCleanupTimer);
670
819
  this.orphanCleanupTimer = void 0;
671
820
  }
672
- await import_mongoose10.default.disconnect();
821
+ await import_mongoose12.default.disconnect();
673
822
  this.connected = false;
674
823
  } catch (error) {
675
824
  import_logger2.loggers.agent.error("Failed to disconnect from MongoDB:", error);
@@ -680,7 +829,7 @@ var MongoDBMemory = class _MongoDBMemory {
680
829
  return this.connected;
681
830
  }
682
831
  async ensureConnection() {
683
- if (!this.isConnected && !this.reconnecting) {
832
+ if (!this.connected && !this.reconnecting) {
684
833
  await this.connect();
685
834
  }
686
835
  const maxWaitTime = 3e4;
@@ -688,14 +837,14 @@ var MongoDBMemory = class _MongoDBMemory {
688
837
  while (this.reconnecting && Date.now() - startTime < maxWaitTime) {
689
838
  await new Promise((resolve) => setTimeout(resolve, 100));
690
839
  }
691
- if (!this.isConnected) {
840
+ if (!this.connected) {
692
841
  throw new Error("MongoDB is not connected and reconnection failed");
693
842
  }
694
843
  }
695
844
  async setupTTLIndex() {
696
845
  if (this.threadTTLSeconds === void 0) return;
697
846
  try {
698
- const db = import_mongoose10.default.connection.db;
847
+ const db = import_mongoose12.default.connection.db;
699
848
  if (!db) return;
700
849
  const collection = db.collection("threads");
701
850
  const indexes = await collection.indexes();
@@ -735,7 +884,7 @@ var MongoDBMemory = class _MongoDBMemory {
735
884
  async cleanupOrphanedMessages() {
736
885
  if (!this.connected) return;
737
886
  try {
738
- const db = import_mongoose10.default.connection.db;
887
+ const db = import_mongoose12.default.connection.db;
739
888
  if (!db) return;
740
889
  const existingThreadIds = await db.collection("threads").distinct("threadId");
741
890
  const result = await MessageModel.deleteMany({
@@ -767,6 +916,25 @@ var MongoDBMemory = class _MongoDBMemory {
767
916
  import_logger2.loggers.agent.error(`${operationName} exceeded time limit`);
768
917
  throw error;
769
918
  }
919
+ if (error.code === 261 || error.codeName === "TooManyLogicalSessions") {
920
+ import_logger2.loggers.agent.warn(
921
+ `${operationName} failed due to too many sessions, disconnecting to release sessions...`
922
+ );
923
+ try {
924
+ await import_mongoose12.default.disconnect();
925
+ this.connected = false;
926
+ } catch (disconnectError) {
927
+ import_logger2.loggers.agent.error("Failed to disconnect during session cleanup:", disconnectError);
928
+ }
929
+ await new Promise((resolve) => setTimeout(resolve, 5e3));
930
+ await this.ensureConnection();
931
+ try {
932
+ return await operation();
933
+ } catch (retryError) {
934
+ import_logger2.loggers.agent.error(`${operationName} failed after session cleanup retry:`, retryError);
935
+ throw retryError;
936
+ }
937
+ }
770
938
  if (error.name === "MongoNetworkError" || error.name === "MongoServerError" || error.message?.includes("connection") || error.message?.includes("disconnect")) {
771
939
  import_logger2.loggers.agent.warn(
772
940
  `${operationName} failed due to connection issue, attempting reconnection...`