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