@mastra/memory 0.0.2-alpha.0 → 0.0.2-alpha.10

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.
@@ -3,10 +3,9 @@
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  var core = require('@mastra/core');
6
- var crypto$1 = require('crypto');
6
+ var crypto = require('crypto');
7
7
  var pg = require('pg');
8
8
  var redis = require('@upstash/redis');
9
- var redis$1 = require('redis');
10
9
 
11
10
  function _arrayLikeToArray(r, a) {
12
11
  (null == a || a > r.length) && (a = r.length);
@@ -381,1573 +380,689 @@ function _unsupportedIterableToArray(r, a) {
381
380
  }
382
381
  }
383
382
 
384
- var CloudflareKVProvider = /*#__PURE__*/function () {
385
- function CloudflareKVProvider(namespace) {
386
- this.namespace = void 0;
387
- this.namespace = namespace;
388
- }
389
- var _proto2 = CloudflareKVProvider.prototype;
390
- _proto2.get = /*#__PURE__*/function () {
391
- var _get2 = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee5(key) {
392
- return _regeneratorRuntime().wrap(function _callee5$(_context5) {
393
- while (1) switch (_context5.prev = _context5.next) {
394
- case 0:
395
- return _context5.abrupt("return", this.namespace.get(key, 'json'));
396
- case 1:
397
- case "end":
398
- return _context5.stop();
399
- }
400
- }, _callee5, this);
401
- }));
402
- function get(_x7) {
403
- return _get2.apply(this, arguments);
404
- }
405
- return get;
406
- }();
407
- _proto2.set = /*#__PURE__*/function () {
408
- var _set = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee6(key, value) {
409
- return _regeneratorRuntime().wrap(function _callee6$(_context6) {
410
- while (1) switch (_context6.prev = _context6.next) {
411
- case 0:
412
- _context6.next = 2;
413
- return this.namespace.put(key, JSON.stringify(value));
414
- case 2:
415
- case "end":
416
- return _context6.stop();
417
- }
418
- }, _callee6, this);
419
- }));
420
- function set(_x8, _x9) {
421
- return _set.apply(this, arguments);
422
- }
423
- return set;
424
- }();
425
- _proto2.del = /*#__PURE__*/function () {
426
- var _del = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee7(key) {
427
- return _regeneratorRuntime().wrap(function _callee7$(_context7) {
428
- while (1) switch (_context7.prev = _context7.next) {
429
- case 0:
430
- _context7.next = 2;
431
- return this.namespace["delete"](key);
432
- case 2:
433
- case "end":
434
- return _context7.stop();
435
- }
436
- }, _callee7, this);
437
- }));
438
- function del(_x10) {
439
- return _del.apply(this, arguments);
440
- }
441
- return del;
442
- }();
443
- _proto2.sadd = /*#__PURE__*/function () {
444
- var _sadd = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee8(key, value) {
445
- var set;
446
- return _regeneratorRuntime().wrap(function _callee8$(_context8) {
447
- while (1) switch (_context8.prev = _context8.next) {
448
- case 0:
449
- _context8.next = 2;
450
- return this.get(key);
451
- case 2:
452
- _context8.t0 = _context8.sent;
453
- if (_context8.t0) {
454
- _context8.next = 5;
455
- break;
456
- }
457
- _context8.t0 = [];
458
- case 5:
459
- set = _context8.t0;
460
- if (set.includes(value)) {
461
- _context8.next = 11;
462
- break;
463
- }
464
- set.push(value);
465
- _context8.next = 10;
466
- return this.set(key, set);
467
- case 10:
468
- return _context8.abrupt("return", 1);
469
- case 11:
470
- return _context8.abrupt("return", 0);
471
- case 12:
472
- case "end":
473
- return _context8.stop();
474
- }
475
- }, _callee8, this);
476
- }));
477
- function sadd(_x11, _x12) {
478
- return _sadd.apply(this, arguments);
479
- }
480
- return sadd;
481
- }();
482
- _proto2.srem = /*#__PURE__*/function () {
483
- var _srem = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee9(key, value) {
484
- var set, index;
485
- return _regeneratorRuntime().wrap(function _callee9$(_context9) {
486
- while (1) switch (_context9.prev = _context9.next) {
487
- case 0:
488
- _context9.next = 2;
489
- return this.get(key);
490
- case 2:
491
- _context9.t0 = _context9.sent;
492
- if (_context9.t0) {
493
- _context9.next = 5;
494
- break;
495
- }
496
- _context9.t0 = [];
497
- case 5:
498
- set = _context9.t0;
499
- index = set.indexOf(value);
500
- if (!(index !== -1)) {
501
- _context9.next = 12;
502
- break;
503
- }
504
- set.splice(index, 1);
505
- _context9.next = 11;
506
- return this.set(key, set);
507
- case 11:
508
- return _context9.abrupt("return", 1);
509
- case 12:
510
- return _context9.abrupt("return", 0);
511
- case 13:
512
- case "end":
513
- return _context9.stop();
514
- }
515
- }, _callee9, this);
516
- }));
517
- function srem(_x13, _x14) {
518
- return _srem.apply(this, arguments);
519
- }
520
- return srem;
521
- }();
522
- _proto2.smembers = /*#__PURE__*/function () {
523
- var _smembers = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee10(key) {
524
- return _regeneratorRuntime().wrap(function _callee10$(_context10) {
525
- while (1) switch (_context10.prev = _context10.next) {
526
- case 0:
527
- _context10.next = 2;
528
- return this.get(key);
529
- case 2:
530
- _context10.t0 = _context10.sent;
531
- if (_context10.t0) {
532
- _context10.next = 5;
533
- break;
534
- }
535
- _context10.t0 = [];
536
- case 5:
537
- return _context10.abrupt("return", _context10.t0);
538
- case 6:
539
- case "end":
540
- return _context10.stop();
541
- }
542
- }, _callee10, this);
543
- }));
544
- function smembers(_x15) {
545
- return _smembers.apply(this, arguments);
546
- }
547
- return smembers;
548
- }();
549
- _proto2.flushall = /*#__PURE__*/function () {
550
- var _flushall = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee11() {
551
- var _this = this;
552
- var cursor, result;
553
- return _regeneratorRuntime().wrap(function _callee11$(_context11) {
554
- while (1) switch (_context11.prev = _context11.next) {
555
- case 0:
556
- _context11.next = 2;
557
- return this.namespace.list({
558
- cursor: cursor
559
- });
560
- case 2:
561
- result = _context11.sent;
562
- _context11.next = 5;
563
- return Promise.all(result.keys.map(function (key) {
564
- return _this.namespace["delete"](key.name);
565
- }));
566
- case 5:
567
- cursor = result.cursor;
568
- case 6:
569
- if (cursor) {
570
- _context11.next = 0;
571
- break;
572
- }
573
- case 7:
574
- case "end":
575
- return _context11.stop();
576
- }
577
- }, _callee11, this);
578
- }));
579
- function flushall() {
580
- return _flushall.apply(this, arguments);
581
- }
582
- return flushall;
583
- }();
584
- _proto2.getWithVersion = /*#__PURE__*/function () {
585
- var _getWithVersion = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee12(key) {
586
- var versionKey, _yield$Promise$all, data, version;
587
- return _regeneratorRuntime().wrap(function _callee12$(_context12) {
588
- while (1) switch (_context12.prev = _context12.next) {
589
- case 0:
590
- versionKey = key + ":version";
591
- _context12.next = 3;
592
- return Promise.all([this.get(key), this.get(versionKey).then(function (v) {
593
- return v || 0;
594
- })]);
595
- case 3:
596
- _yield$Promise$all = _context12.sent;
597
- data = _yield$Promise$all[0];
598
- version = _yield$Promise$all[1];
599
- return _context12.abrupt("return", {
600
- data: data,
601
- version: version
602
- });
603
- case 7:
604
- case "end":
605
- return _context12.stop();
606
- }
607
- }, _callee12, this);
608
- }));
609
- function getWithVersion(_x16) {
610
- return _getWithVersion.apply(this, arguments);
611
- }
612
- return getWithVersion;
613
- }();
614
- _proto2.setWithVersion = /*#__PURE__*/function () {
615
- var _setWithVersion = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee13(key, value, expectedVersion) {
616
- var versionKey, currentVersion;
617
- return _regeneratorRuntime().wrap(function _callee13$(_context13) {
618
- while (1) switch (_context13.prev = _context13.next) {
619
- case 0:
620
- versionKey = key + ":version";
621
- _context13.next = 3;
622
- return this.get(versionKey);
623
- case 3:
624
- _context13.t0 = _context13.sent;
625
- if (_context13.t0) {
626
- _context13.next = 6;
627
- break;
628
- }
629
- _context13.t0 = 0;
630
- case 6:
631
- currentVersion = _context13.t0;
632
- if (!(currentVersion !== expectedVersion)) {
633
- _context13.next = 9;
634
- break;
635
- }
636
- return _context13.abrupt("return", false);
637
- case 9:
638
- _context13.next = 11;
639
- return Promise.all([this.set(key, value), this.set(versionKey, expectedVersion + 1)]);
640
- case 11:
641
- return _context13.abrupt("return", true);
642
- case 12:
643
- case "end":
644
- return _context13.stop();
645
- }
646
- }, _callee13, this);
647
- }));
648
- function setWithVersion(_x17, _x18, _x19) {
649
- return _setWithVersion.apply(this, arguments);
650
- }
651
- return setWithVersion;
652
- }();
653
- return CloudflareKVProvider;
654
- }();
655
-
656
- var CloudflareKVMemory = /*#__PURE__*/function (_MastraMemory) {
657
- function CloudflareKVMemory(namespace) {
383
+ var Pool = pg.Pool;
384
+ var PgMemory = /*#__PURE__*/function (_MastraMemory) {
385
+ function PgMemory(config) {
658
386
  var _this;
659
387
  _this = _MastraMemory.call(this) || this;
660
- _this.kv = void 0;
661
- _this.threadPrefix = 'thread:';
662
- _this.messagePrefix = 'messages:';
663
- _this.kv = new CloudflareKVProvider(namespace);
388
+ _this.pool = void 0;
389
+ _this.hasTables = false;
390
+ _this.pool = new Pool({
391
+ connectionString: config.connectionString
392
+ });
393
+ _this.MAX_CONTEXT_TOKENS = config.maxTokens;
664
394
  return _this;
665
395
  }
666
- _inheritsLoose(CloudflareKVMemory, _MastraMemory);
667
- var _proto = CloudflareKVMemory.prototype;
668
- _proto.getThreadById = /*#__PURE__*/function () {
669
- var _getThreadById = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(threadId) {
670
- var thread;
396
+ /**
397
+ * Threads
398
+ */
399
+ _inheritsLoose(PgMemory, _MastraMemory);
400
+ var _proto = PgMemory.prototype;
401
+ _proto.getThreadById =
402
+ /*#__PURE__*/
403
+ function () {
404
+ var _getThreadById = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(_ref) {
405
+ var threadId, client, result;
671
406
  return _regeneratorRuntime().wrap(function _callee$(_context) {
672
407
  while (1) switch (_context.prev = _context.next) {
673
408
  case 0:
674
- _context.next = 2;
675
- return this.kv.get("" + this.threadPrefix + threadId);
676
- case 2:
677
- thread = _context.sent;
678
- if (thread && typeof thread.createdAt === 'string') {
679
- thread.createdAt = new Date(thread.createdAt);
680
- thread.updatedAt = new Date(thread.updatedAt);
681
- }
682
- return _context.abrupt("return", thread);
683
- case 5:
684
- case "end":
685
- return _context.stop();
686
- }
687
- }, _callee, this);
688
- }));
689
- function getThreadById(_x) {
690
- return _getThreadById.apply(this, arguments);
691
- }
692
- return getThreadById;
693
- }();
694
- _proto.saveThread = /*#__PURE__*/function () {
695
- var _saveThread = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(thread) {
696
- return _regeneratorRuntime().wrap(function _callee2$(_context2) {
697
- while (1) switch (_context2.prev = _context2.next) {
698
- case 0:
699
- thread.updatedAt = new Date();
700
- _context2.next = 3;
701
- return this.kv.set("" + this.threadPrefix + thread.id, thread);
702
- case 3:
703
- _context2.next = 5;
704
- return this.kv.sadd('threads', thread.id);
705
- case 5:
706
- return _context2.abrupt("return", thread);
707
- case 6:
708
- case "end":
709
- return _context2.stop();
710
- }
711
- }, _callee2, this);
712
- }));
713
- function saveThread(_x2) {
714
- return _saveThread.apply(this, arguments);
715
- }
716
- return saveThread;
717
- }();
718
- _proto.retryOperation = /*#__PURE__*/function () {
719
- var _retryOperation = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3(operation, maxRetries) {
720
- var lastError, _loop, _ret, attempt;
721
- return _regeneratorRuntime().wrap(function _callee3$(_context4) {
722
- while (1) switch (_context4.prev = _context4.next) {
723
- case 0:
724
- if (maxRetries === void 0) {
725
- maxRetries = 5;
726
- }
727
- _loop = /*#__PURE__*/_regeneratorRuntime().mark(function _loop(attempt) {
728
- return _regeneratorRuntime().wrap(function _loop$(_context3) {
729
- while (1) switch (_context3.prev = _context3.next) {
730
- case 0:
731
- _context3.prev = 0;
732
- _context3.next = 3;
733
- return operation();
734
- case 3:
735
- _context3.t0 = _context3.sent;
736
- return _context3.abrupt("return", {
737
- v: _context3.t0
738
- });
739
- case 7:
740
- _context3.prev = 7;
741
- _context3.t1 = _context3["catch"](0);
742
- lastError = _context3.t1;
743
- _context3.next = 12;
744
- return new Promise(function (resolve) {
745
- return setTimeout(resolve, Math.random() * 100 * Math.pow(2, attempt));
746
- });
747
- case 12:
748
- case "end":
749
- return _context3.stop();
750
- }
751
- }, _loop, null, [[0, 7]]);
752
- });
753
- attempt = 0;
754
- case 3:
755
- if (!(attempt < maxRetries)) {
756
- _context4.next = 11;
757
- break;
758
- }
759
- return _context4.delegateYield(_loop(attempt), "t0", 5);
760
- case 5:
761
- _ret = _context4.t0;
762
- if (!_ret) {
763
- _context4.next = 8;
764
- break;
765
- }
766
- return _context4.abrupt("return", _ret.v);
767
- case 8:
768
- attempt++;
769
- _context4.next = 3;
770
- break;
771
- case 11:
772
- throw lastError || new Error("Operation failed after " + maxRetries + " attempts");
773
- case 12:
774
- case "end":
775
- return _context4.stop();
776
- }
777
- }, _callee3);
778
- }));
779
- function retryOperation(_x3, _x4) {
780
- return _retryOperation.apply(this, arguments);
781
- }
782
- return retryOperation;
783
- }();
784
- _proto.addMessage = /*#__PURE__*/function () {
785
- var _addMessage = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee5(threadId, content, role) {
786
- var _this2 = this;
787
- var message;
788
- return _regeneratorRuntime().wrap(function _callee5$(_context6) {
789
- while (1) switch (_context6.prev = _context6.next) {
790
- case 0:
791
- message = {
792
- id: this.generateId(),
793
- content: content,
794
- role: role,
795
- createdAt: new Date(),
796
- threadId: threadId
797
- };
798
- _context6.next = 3;
799
- return this.retryOperation(/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee4() {
800
- var key, existingMessages, messageMap, updatedMessages;
801
- return _regeneratorRuntime().wrap(function _callee4$(_context5) {
802
- while (1) switch (_context5.prev = _context5.next) {
803
- case 0:
804
- key = "" + _this2.messagePrefix + threadId;
805
- _context5.next = 3;
806
- return _this2.kv.get(key);
807
- case 3:
808
- _context5.t0 = _context5.sent;
809
- if (_context5.t0) {
810
- _context5.next = 6;
811
- break;
812
- }
813
- _context5.t0 = [];
814
- case 6:
815
- existingMessages = _context5.t0;
816
- messageMap = new Map();
817
- existingMessages.forEach(function (msg) {
818
- messageMap.set(msg.id, _extends({}, msg, {
819
- createdAt: new Date(msg.createdAt)
820
- }));
821
- });
822
- messageMap.set(message.id, message);
823
- updatedMessages = Array.from(messageMap.values());
824
- updatedMessages.sort(function (a, b) {
825
- var timeCompare = a.createdAt.getTime() - b.createdAt.getTime();
826
- return timeCompare === 0 ? a.id.localeCompare(b.id) : timeCompare;
827
- });
828
- _context5.next = 14;
829
- return _this2.kv.set(key, updatedMessages);
830
- case 14:
831
- case "end":
832
- return _context5.stop();
833
- }
834
- }, _callee4);
835
- })));
409
+ threadId = _ref.threadId;
410
+ _context.next = 3;
411
+ return this.ensureTablesExist();
836
412
  case 3:
837
- return _context6.abrupt("return", message);
838
- case 4:
839
- case "end":
840
- return _context6.stop();
841
- }
842
- }, _callee5, this);
843
- }));
844
- function addMessage(_x5, _x6, _x7) {
845
- return _addMessage.apply(this, arguments);
846
- }
847
- return addMessage;
848
- }();
849
- _proto.saveMessages = /*#__PURE__*/function () {
850
- var _saveMessages = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee7(messages) {
851
- var _this3 = this;
852
- var messagesByThread, _iterator, _step, message, key;
853
- return _regeneratorRuntime().wrap(function _callee7$(_context9) {
854
- while (1) switch (_context9.prev = _context9.next) {
855
- case 0:
856
- if (messages.length) {
857
- _context9.next = 2;
858
- break;
859
- }
860
- return _context9.abrupt("return", []);
861
- case 2:
862
- messagesByThread = new Map();
863
- for (_iterator = _createForOfIteratorHelperLoose(messages); !(_step = _iterator()).done;) {
864
- message = _step.value;
865
- key = "" + this.messagePrefix + message.threadId;
866
- if (!messagesByThread.has(key)) {
867
- messagesByThread.set(key, []);
868
- }
869
- messagesByThread.get(key).push(_extends({}, message, {
870
- createdAt: new Date(message.createdAt)
871
- }));
872
- }
873
- _context9.next = 6;
874
- return Promise.all(Array.from(messagesByThread.entries()).map(function (_ref2) {
875
- var key = _ref2[0],
876
- threadMessages = _ref2[1];
877
- return _this3.retryOperation(/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee6() {
878
- var saved, _loop2;
879
- return _regeneratorRuntime().wrap(function _callee6$(_context8) {
880
- while (1) switch (_context8.prev = _context8.next) {
881
- case 0:
882
- saved = false;
883
- _loop2 = /*#__PURE__*/_regeneratorRuntime().mark(function _loop2() {
884
- var _yield$_this3$kv$getW, existingMessages, version, messageMap, updatedMessages;
885
- return _regeneratorRuntime().wrap(function _loop2$(_context7) {
886
- while (1) switch (_context7.prev = _context7.next) {
887
- case 0:
888
- _context7.next = 2;
889
- return _this3.kv.getWithVersion(key);
890
- case 2:
891
- _yield$_this3$kv$getW = _context7.sent;
892
- existingMessages = _yield$_this3$kv$getW.data;
893
- version = _yield$_this3$kv$getW.version;
894
- console.log('Read version:', version, 'Messages:', (existingMessages == null ? void 0 : existingMessages.length) || 0);
895
- messageMap = new Map();
896
- (existingMessages || []).forEach(function (msg) {
897
- messageMap.set(msg.id, _extends({}, msg, {
898
- createdAt: new Date(msg.createdAt)
899
- }));
900
- });
901
- threadMessages.forEach(function (msg) {
902
- messageMap.set(msg.id, msg);
903
- });
904
- updatedMessages = Array.from(messageMap.values());
905
- updatedMessages.sort(function (a, b) {
906
- var timeCompare = a.createdAt.getTime() - b.createdAt.getTime();
907
- return timeCompare === 0 ? a.id.localeCompare(b.id) : timeCompare;
908
- });
909
- _context7.next = 13;
910
- return _this3.kv.setWithVersion(key, updatedMessages, version);
911
- case 13:
912
- saved = _context7.sent;
913
- console.log('Save attempt with version:', version, 'Success:', saved);
914
- if (saved) {
915
- _context7.next = 18;
916
- break;
917
- }
918
- _context7.next = 18;
919
- return new Promise(function (resolve) {
920
- return setTimeout(resolve, Math.random() * 50);
921
- });
922
- case 18:
923
- case "end":
924
- return _context7.stop();
925
- }
926
- }, _loop2);
927
- });
928
- case 2:
929
- if (saved) {
930
- _context8.next = 6;
931
- break;
932
- }
933
- return _context8.delegateYield(_loop2(), "t0", 4);
934
- case 4:
935
- _context8.next = 2;
936
- break;
937
- case 6:
938
- case "end":
939
- return _context8.stop();
940
- }
941
- }, _callee6);
942
- })));
943
- }));
944
- case 6:
945
- return _context9.abrupt("return", messages);
946
- case 7:
947
- case "end":
948
- return _context9.stop();
949
- }
950
- }, _callee7, this);
951
- }));
952
- function saveMessages(_x8) {
953
- return _saveMessages.apply(this, arguments);
954
- }
955
- return saveMessages;
956
- }();
957
- _proto.getMessages = /*#__PURE__*/function () {
958
- var _getMessages = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee8(threadId) {
959
- var messages;
960
- return _regeneratorRuntime().wrap(function _callee8$(_context10) {
961
- while (1) switch (_context10.prev = _context10.next) {
962
- case 0:
963
- _context10.next = 2;
964
- return this.kv.get("" + this.messagePrefix + threadId);
965
- case 2:
966
- _context10.t0 = _context10.sent;
967
- if (_context10.t0) {
968
- _context10.next = 5;
969
- break;
970
- }
971
- _context10.t0 = [];
972
- case 5:
973
- messages = _context10.t0;
974
- return _context10.abrupt("return", messages.map(function (msg) {
975
- return _extends({}, msg, {
976
- createdAt: new Date(msg.createdAt)
977
- });
978
- }));
979
- case 7:
980
- case "end":
981
- return _context10.stop();
982
- }
983
- }, _callee8, this);
984
- }));
985
- function getMessages(_x9) {
986
- return _getMessages.apply(this, arguments);
987
- }
988
- return getMessages;
989
- }();
990
- _proto.getAllThreadIds = /*#__PURE__*/function () {
991
- var _getAllThreadIds = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee9() {
992
- return _regeneratorRuntime().wrap(function _callee9$(_context11) {
993
- while (1) switch (_context11.prev = _context11.next) {
994
- case 0:
995
- return _context11.abrupt("return", this.kv.smembers('threads'));
996
- case 1:
997
- case "end":
998
- return _context11.stop();
999
- }
1000
- }, _callee9, this);
1001
- }));
1002
- function getAllThreadIds() {
1003
- return _getAllThreadIds.apply(this, arguments);
1004
- }
1005
- return getAllThreadIds;
1006
- }();
1007
- _proto.deleteThread = /*#__PURE__*/function () {
1008
- var _deleteThread = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee10(threadId) {
1009
- return _regeneratorRuntime().wrap(function _callee10$(_context12) {
1010
- while (1) switch (_context12.prev = _context12.next) {
1011
- case 0:
1012
- _context12.next = 2;
1013
- return Promise.all([this.kv.del("" + this.threadPrefix + threadId), this.kv.del("" + this.messagePrefix + threadId), this.kv.srem('threads', threadId)]);
1014
- case 2:
1015
- case "end":
1016
- return _context12.stop();
1017
- }
1018
- }, _callee10, this);
1019
- }));
1020
- function deleteThread(_x10) {
1021
- return _deleteThread.apply(this, arguments);
1022
- }
1023
- return deleteThread;
1024
- }();
1025
- _proto.getThreads = /*#__PURE__*/function () {
1026
- var _getThreads = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee11(threadIds) {
1027
- var _this4 = this;
1028
- var threads;
1029
- return _regeneratorRuntime().wrap(function _callee11$(_context13) {
1030
- while (1) switch (_context13.prev = _context13.next) {
1031
- case 0:
1032
- _context13.next = 2;
1033
- return Promise.all(threadIds.map(function (id) {
1034
- return _this4.getThreadById(id);
1035
- }));
1036
- case 2:
1037
- threads = _context13.sent;
1038
- return _context13.abrupt("return", threads.filter(function (t) {
1039
- return t !== null;
1040
- }));
1041
- case 4:
1042
- case "end":
1043
- return _context13.stop();
1044
- }
1045
- }, _callee11);
1046
- }));
1047
- function getThreads(_x11) {
1048
- return _getThreads.apply(this, arguments);
1049
- }
1050
- return getThreads;
1051
- }();
1052
- _proto.cleanup = /*#__PURE__*/function () {
1053
- var _cleanup = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee12() {
1054
- return _regeneratorRuntime().wrap(function _callee12$(_context14) {
1055
- while (1) switch (_context14.prev = _context14.next) {
1056
- case 0:
1057
- _context14.next = 2;
1058
- return this.kv.flushall();
1059
- case 2:
1060
- case "end":
1061
- return _context14.stop();
1062
- }
1063
- }, _callee12, this);
1064
- }));
1065
- function cleanup() {
1066
- return _cleanup.apply(this, arguments);
1067
- }
1068
- return cleanup;
1069
- }();
1070
- return CloudflareKVMemory;
1071
- }(core.MastraMemory);
1072
-
1073
- var Pool = pg.Pool;
1074
- var PgMemory = /*#__PURE__*/function (_MastraMemory) {
1075
- function PgMemory(connectionString) {
1076
- var _this;
1077
- _this = _MastraMemory.call(this) || this;
1078
- _this.pool = void 0;
1079
- _this.pool = new Pool({
1080
- connectionString: connectionString
1081
- });
1082
- return _this;
1083
- }
1084
- _inheritsLoose(PgMemory, _MastraMemory);
1085
- var _proto = PgMemory.prototype;
1086
- _proto.drop = /*#__PURE__*/function () {
1087
- var _drop = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
1088
- var client;
1089
- return _regeneratorRuntime().wrap(function _callee$(_context) {
1090
- while (1) switch (_context.prev = _context.next) {
1091
- case 0:
1092
- _context.next = 2;
1093
- return this.pool.connect();
1094
- case 2:
1095
- client = _context.sent;
1096
413
  _context.next = 5;
1097
- return client.query('DELETE FROM mastra_messages');
1098
- case 5:
1099
- _context.next = 7;
1100
- return client.query('DELETE FROM mastra_threads');
1101
- case 7:
1102
- client.release();
1103
- _context.next = 10;
1104
- return this.pool.end();
1105
- case 10:
1106
- case "end":
1107
- return _context.stop();
1108
- }
1109
- }, _callee, this);
1110
- }));
1111
- function drop() {
1112
- return _drop.apply(this, arguments);
1113
- }
1114
- return drop;
1115
- }();
1116
- _proto.ensureTablesExist = /*#__PURE__*/function () {
1117
- var _ensureTablesExist = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
1118
- var client, _threadsResult$rows, _messagesResult$rows, threadsResult, messagesResult;
1119
- return _regeneratorRuntime().wrap(function _callee2$(_context2) {
1120
- while (1) switch (_context2.prev = _context2.next) {
1121
- case 0:
1122
- _context2.next = 2;
1123
- return this.pool.connect();
1124
- case 2:
1125
- client = _context2.sent;
1126
- _context2.prev = 3;
1127
- _context2.next = 6;
1128
- return client.query("\n SELECT EXISTS (\n SELECT 1\n FROM information_schema.tables\n WHERE table_name = 'mastra_threads'\n );\n ");
1129
- case 6:
1130
- threadsResult = _context2.sent;
1131
- if (threadsResult != null && (_threadsResult$rows = threadsResult.rows) != null && (_threadsResult$rows = _threadsResult$rows[0]) != null && _threadsResult$rows.exists) {
1132
- _context2.next = 10;
1133
- break;
1134
- }
1135
- _context2.next = 10;
1136
- return client.query("\n CREATE TABLE IF NOT EXISTS mastra_threads (\n id UUID PRIMARY KEY,\n title TEXT,\n created_at TIMESTAMP WITH TIME ZONE NOT NULL,\n updated_at TIMESTAMP WITH TIME ZONE NOT NULL,\n metadata JSONB\n );\n ");
1137
- case 10:
1138
- _context2.next = 12;
1139
- return client.query("\n SELECT EXISTS (\n SELECT 1\n FROM information_schema.tables\n WHERE table_name = 'mastra_messages'\n );\n ");
1140
- case 12:
1141
- messagesResult = _context2.sent;
1142
- if (messagesResult != null && (_messagesResult$rows = messagesResult.rows) != null && (_messagesResult$rows = _messagesResult$rows[0]) != null && _messagesResult$rows.exists) {
1143
- _context2.next = 16;
1144
- break;
1145
- }
1146
- _context2.next = 16;
1147
- return client.query("\n CREATE TABLE IF NOT EXISTS mastra_messages (\n id UUID PRIMARY KEY,\n content TEXT NOT NULL,\n role VARCHAR(20) NOT NULL,\n created_at TIMESTAMP WITH TIME ZONE NOT NULL,\n thread_id UUID NOT NULL,\n FOREIGN KEY (thread_id) REFERENCES mastra_threads(id)\n );\n ");
1148
- case 16:
1149
- _context2.prev = 16;
1150
- client.release();
1151
- return _context2.finish(16);
1152
- case 19:
1153
- case "end":
1154
- return _context2.stop();
1155
- }
1156
- }, _callee2, this, [[3,, 16, 19]]);
1157
- }));
1158
- function ensureTablesExist() {
1159
- return _ensureTablesExist.apply(this, arguments);
1160
- }
1161
- return ensureTablesExist;
1162
- }();
1163
- _proto.updateThread = /*#__PURE__*/function () {
1164
- var _updateThread = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3(id, title, metadata) {
1165
- var client, _result$rows, result;
1166
- return _regeneratorRuntime().wrap(function _callee3$(_context3) {
1167
- while (1) switch (_context3.prev = _context3.next) {
1168
- case 0:
1169
- _context3.next = 2;
1170
- return this.pool.connect();
1171
- case 2:
1172
- client = _context3.sent;
1173
- _context3.prev = 3;
1174
- _context3.next = 6;
1175
- return client.query("\n UPDATE mastra_threads\n SET title = $1, metadata = $2, updated_at = NOW()\n WHERE id = $3\n RETURNING *\n ", [title, JSON.stringify(metadata), id]);
1176
- case 6:
1177
- result = _context3.sent;
1178
- return _context3.abrupt("return", result == null || (_result$rows = result.rows) == null ? void 0 : _result$rows[0]);
1179
- case 8:
1180
- _context3.prev = 8;
1181
- client.release();
1182
- return _context3.finish(8);
1183
- case 11:
1184
- case "end":
1185
- return _context3.stop();
1186
- }
1187
- }, _callee3, this, [[3,, 8, 11]]);
1188
- }));
1189
- function updateThread(_x, _x2, _x3) {
1190
- return _updateThread.apply(this, arguments);
1191
- }
1192
- return updateThread;
1193
- }();
1194
- _proto.deleteThread = /*#__PURE__*/function () {
1195
- var _deleteThread = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee4(id) {
1196
- var client;
1197
- return _regeneratorRuntime().wrap(function _callee4$(_context4) {
1198
- while (1) switch (_context4.prev = _context4.next) {
1199
- case 0:
1200
- _context4.next = 2;
1201
- return this.pool.connect();
1202
- case 2:
1203
- client = _context4.sent;
1204
- _context4.prev = 3;
1205
- _context4.next = 6;
1206
- return client.query("\n DELETE FROM mastra_messages\n WHERE thread_id = $1\n ", [id]);
1207
- case 6:
1208
- _context4.next = 8;
1209
- return client.query("\n DELETE FROM mastra_threads\n WHERE id = $1\n ", [id]);
1210
- case 8:
1211
- _context4.prev = 8;
1212
- client.release();
1213
- return _context4.finish(8);
1214
- case 11:
1215
- case "end":
1216
- return _context4.stop();
1217
- }
1218
- }, _callee4, this, [[3,, 8, 11]]);
1219
- }));
1220
- function deleteThread(_x4) {
1221
- return _deleteThread.apply(this, arguments);
1222
- }
1223
- return deleteThread;
1224
- }();
1225
- _proto.deleteMessage = /*#__PURE__*/function () {
1226
- var _deleteMessage = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee5(id) {
1227
- var client;
1228
- return _regeneratorRuntime().wrap(function _callee5$(_context5) {
1229
- while (1) switch (_context5.prev = _context5.next) {
1230
- case 0:
1231
- _context5.next = 2;
1232
- return this.pool.connect();
1233
- case 2:
1234
- client = _context5.sent;
1235
- _context5.prev = 3;
1236
- _context5.next = 6;
1237
- return client.query("\n DELETE FROM mastra_messages\n WHERE id = $1\n ", [id]);
1238
- case 6:
1239
- _context5.prev = 6;
1240
- client.release();
1241
- return _context5.finish(6);
1242
- case 9:
1243
- case "end":
1244
- return _context5.stop();
1245
- }
1246
- }, _callee5, this, [[3,, 6, 9]]);
1247
- }));
1248
- function deleteMessage(_x5) {
1249
- return _deleteMessage.apply(this, arguments);
1250
- }
1251
- return deleteMessage;
1252
- }();
1253
- _proto.getThreadById = /*#__PURE__*/function () {
1254
- var _getThreadById = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee6(threadId) {
1255
- var client, result;
1256
- return _regeneratorRuntime().wrap(function _callee6$(_context6) {
1257
- while (1) switch (_context6.prev = _context6.next) {
1258
- case 0:
1259
- _context6.next = 2;
1260
- return this.ensureTablesExist();
1261
- case 2:
1262
- _context6.next = 4;
1263
- return this.pool.connect();
1264
- case 4:
1265
- client = _context6.sent;
1266
- _context6.prev = 5;
1267
- _context6.next = 8;
1268
- return client.query("\n SELECT id, title, created_at AS createdAt, updated_at AS updatedAt, metadata\n FROM mastra_threads\n WHERE id = $1\n ", [threadId]);
1269
- case 8:
1270
- result = _context6.sent;
1271
- return _context6.abrupt("return", result.rows[0] || null);
1272
- case 10:
1273
- _context6.prev = 10;
1274
- client.release();
1275
- return _context6.finish(10);
1276
- case 13:
1277
- case "end":
1278
- return _context6.stop();
1279
- }
1280
- }, _callee6, this, [[5,, 10, 13]]);
1281
- }));
1282
- function getThreadById(_x6) {
1283
- return _getThreadById.apply(this, arguments);
1284
- }
1285
- return getThreadById;
1286
- }();
1287
- _proto.saveThread = /*#__PURE__*/function () {
1288
- var _saveThread = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee7(thread) {
1289
- var client, _result$rows2, id, title, createdAt, updatedAt, metadata, result;
1290
- return _regeneratorRuntime().wrap(function _callee7$(_context7) {
1291
- while (1) switch (_context7.prev = _context7.next) {
1292
- case 0:
1293
- _context7.next = 2;
1294
- return this.ensureTablesExist();
1295
- case 2:
1296
- _context7.next = 4;
1297
- return this.pool.connect();
1298
- case 4:
1299
- client = _context7.sent;
1300
- _context7.prev = 5;
1301
- id = thread.id, title = thread.title, createdAt = thread.createdAt, updatedAt = thread.updatedAt, metadata = thread.metadata;
1302
- _context7.next = 9;
1303
- return client.query("\n INSERT INTO mastra_threads (id, title, created_at, updated_at, metadata)\n VALUES ($1, $2, $3, $4, $5)\n ON CONFLICT (id) DO UPDATE SET title = $2, updated_at = $4, metadata = $5\n RETURNING id, title, created_at AS createdAt, updated_at AS updatedAt, metadata\n ", [id, title, createdAt, updatedAt, JSON.stringify(metadata)]);
1304
- case 9:
1305
- result = _context7.sent;
1306
- return _context7.abrupt("return", result == null || (_result$rows2 = result.rows) == null ? void 0 : _result$rows2[0]);
1307
- case 11:
1308
- _context7.prev = 11;
1309
- client.release();
1310
- return _context7.finish(11);
1311
- case 14:
1312
- case "end":
1313
- return _context7.stop();
1314
- }
1315
- }, _callee7, this, [[5,, 11, 14]]);
1316
- }));
1317
- function saveThread(_x7) {
1318
- return _saveThread.apply(this, arguments);
1319
- }
1320
- return saveThread;
1321
- }();
1322
- _proto.saveMessages = /*#__PURE__*/function () {
1323
- var _saveMessages = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee8(messages) {
1324
- var client, _iterator, _step, message, id, content, role, createdAt, threadId;
1325
- return _regeneratorRuntime().wrap(function _callee8$(_context8) {
1326
- while (1) switch (_context8.prev = _context8.next) {
1327
- case 0:
1328
- _context8.next = 2;
1329
- return this.ensureTablesExist();
1330
- case 2:
1331
- _context8.next = 4;
1332
- return this.pool.connect();
1333
- case 4:
1334
- client = _context8.sent;
1335
- _context8.prev = 5;
1336
- _context8.next = 8;
1337
- return client.query('BEGIN');
1338
- case 8:
1339
- _iterator = _createForOfIteratorHelperLoose(messages);
1340
- case 9:
1341
- if ((_step = _iterator()).done) {
1342
- _context8.next = 16;
1343
- break;
1344
- }
1345
- message = _step.value;
1346
- id = message.id, content = message.content, role = message.role, createdAt = message.createdAt, threadId = message.threadId;
1347
- _context8.next = 14;
1348
- return client.query("\n INSERT INTO mastra_messages (id, content, role, created_at, thread_id)\n VALUES ($1, $2, $3, $4, $5)\n ", [id, content, role, createdAt.toISOString(), threadId]);
1349
- case 14:
1350
- _context8.next = 9;
1351
- break;
1352
- case 16:
1353
- _context8.next = 18;
1354
- return client.query('COMMIT');
1355
- case 18:
1356
- return _context8.abrupt("return", messages);
1357
- case 21:
1358
- _context8.prev = 21;
1359
- _context8.t0 = _context8["catch"](5);
1360
- _context8.next = 25;
1361
- return client.query('ROLLBACK');
1362
- case 25:
1363
- throw _context8.t0;
1364
- case 26:
1365
- _context8.prev = 26;
1366
- client.release();
1367
- return _context8.finish(26);
1368
- case 29:
1369
- case "end":
1370
- return _context8.stop();
1371
- }
1372
- }, _callee8, this, [[5, 21, 26, 29]]);
1373
- }));
1374
- function saveMessages(_x8) {
1375
- return _saveMessages.apply(this, arguments);
1376
- }
1377
- return saveMessages;
1378
- }();
1379
- _proto.getMessages = /*#__PURE__*/function () {
1380
- var _getMessages = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee9(threadId) {
1381
- var client, result;
1382
- return _regeneratorRuntime().wrap(function _callee9$(_context9) {
1383
- while (1) switch (_context9.prev = _context9.next) {
1384
- case 0:
1385
- _context9.next = 2;
1386
- return this.ensureTablesExist();
1387
- case 2:
1388
- _context9.next = 4;
1389
414
  return this.pool.connect();
1390
- case 4:
1391
- client = _context9.sent;
1392
- _context9.prev = 5;
1393
- _context9.next = 8;
1394
- return client.query("\n SELECT \n id, \n content, \n role, \n created_at AS createdAt, \n thread_id AS threadId\n FROM mastra_messages\n WHERE thread_id = $1\n ORDER BY created_at ASC\n ", [threadId]);
1395
- case 8:
1396
- result = _context9.sent;
1397
- return _context9.abrupt("return", result.rows);
1398
- case 10:
1399
- _context9.prev = 10;
1400
- client.release();
1401
- return _context9.finish(10);
1402
- case 13:
1403
- case "end":
1404
- return _context9.stop();
1405
- }
1406
- }, _callee9, this, [[5,, 10, 13]]);
1407
- }));
1408
- function getMessages(_x9) {
1409
- return _getMessages.apply(this, arguments);
1410
- }
1411
- return getMessages;
1412
- }();
1413
- _proto.createThread = /*#__PURE__*/function () {
1414
- var _createThread = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee10(title, metadata) {
1415
- var id, now, thread;
1416
- return _regeneratorRuntime().wrap(function _callee10$(_context10) {
1417
- while (1) switch (_context10.prev = _context10.next) {
1418
- case 0:
1419
- _context10.next = 2;
1420
- return this.ensureTablesExist();
1421
- case 2:
1422
- id = crypto$1.randomUUID();
1423
- now = new Date();
1424
- thread = {
1425
- id: id,
1426
- title: title,
1427
- createdAt: now,
1428
- updatedAt: now,
1429
- metadata: metadata
1430
- };
1431
- return _context10.abrupt("return", this.saveThread(thread));
1432
- case 6:
1433
- case "end":
1434
- return _context10.stop();
1435
- }
1436
- }, _callee10, this);
1437
- }));
1438
- function createThread(_x10, _x11) {
1439
- return _createThread.apply(this, arguments);
1440
- }
1441
- return createThread;
1442
- }();
1443
- _proto.addMessage = /*#__PURE__*/function () {
1444
- var _addMessage = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee11(threadId, content, role) {
1445
- var thread, id, message, _yield$this$saveMessa, savedMessage;
1446
- return _regeneratorRuntime().wrap(function _callee11$(_context11) {
1447
- while (1) switch (_context11.prev = _context11.next) {
1448
- case 0:
1449
- _context11.next = 2;
1450
- return this.ensureTablesExist();
1451
- case 2:
1452
- _context11.next = 4;
1453
- return this.getThreadById(threadId);
1454
- case 4:
1455
- thread = _context11.sent;
1456
- if (thread) {
1457
- _context11.next = 7;
1458
- break;
1459
- }
1460
- throw new Error("Thread with ID " + threadId + " does not exist.");
1461
- case 7:
1462
- id = crypto$1.randomUUID();
1463
- message = {
1464
- id: id,
1465
- content: content,
1466
- role: role,
1467
- createdAt: new Date(),
1468
- threadId: threadId
1469
- };
1470
- _context11.next = 11;
1471
- return this.saveMessages([message]);
1472
- case 11:
1473
- _yield$this$saveMessa = _context11.sent;
1474
- savedMessage = _yield$this$saveMessa[0];
1475
- return _context11.abrupt("return", savedMessage);
1476
- case 14:
1477
- case "end":
1478
- return _context11.stop();
1479
- }
1480
- }, _callee11, this);
1481
- }));
1482
- function addMessage(_x12, _x13, _x14) {
1483
- return _addMessage.apply(this, arguments);
1484
- }
1485
- return addMessage;
1486
- }();
1487
- return PgMemory;
1488
- }(core.MastraMemory);
1489
-
1490
- // Helper functions for date handling
1491
- function serializeData(data) {
1492
- if (data === null || data === undefined) return data;
1493
- if (data instanceof Date) {
1494
- return {
1495
- __type: 'Date',
1496
- value: data.toISOString()
1497
- };
1498
- }
1499
- if (Array.isArray(data)) {
1500
- return data.map(function (item) {
1501
- return serializeData(item);
1502
- });
1503
- }
1504
- if (typeof data === 'object') {
1505
- return Object.keys(data).reduce(function (acc, key) {
1506
- acc[key] = serializeData(data[key]);
1507
- return acc;
1508
- }, {});
1509
- }
1510
- return data;
1511
- }
1512
- function deserializeData(data) {
1513
- if (data === null || data === undefined) return data;
1514
- if (typeof data === 'object' && data.__type === 'Date') {
1515
- return new Date(data.value);
1516
- }
1517
- if (Array.isArray(data)) {
1518
- return data.map(function (item) {
1519
- return deserializeData(item);
1520
- });
1521
- }
1522
- if (typeof data === 'object') {
1523
- return Object.keys(data).reduce(function (acc, key) {
1524
- acc[key] = deserializeData(data[key]);
1525
- return acc;
1526
- }, {});
1527
- }
1528
- return data;
1529
- }
1530
- // Provider for Upstash/Vercel KV
1531
- var UpstashProvider = /*#__PURE__*/function () {
1532
- function UpstashProvider(url, token) {
1533
- this.client = void 0;
1534
- this.client = new redis.Redis({
1535
- url: url,
1536
- token: token
1537
- });
1538
- }
1539
- var _proto = UpstashProvider.prototype;
1540
- _proto.get = /*#__PURE__*/function () {
1541
- var _get = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(key) {
1542
- var data;
1543
- return _regeneratorRuntime().wrap(function _callee$(_context) {
1544
- while (1) switch (_context.prev = _context.next) {
1545
- case 0:
1546
- _context.next = 2;
1547
- return this.client.get(key);
1548
- case 2:
1549
- data = _context.sent;
1550
- return _context.abrupt("return", deserializeData(data));
1551
- case 4:
415
+ case 5:
416
+ client = _context.sent;
417
+ _context.prev = 6;
418
+ _context.next = 9;
419
+ return client.query("\n SELECT id, title, created_at AS createdAt, updated_at AS updatedAt, resourceid, metadata\n FROM mastra_threads\n WHERE id = $1\n ", [threadId]);
420
+ case 9:
421
+ result = _context.sent;
422
+ return _context.abrupt("return", result.rows[0] || null);
423
+ case 11:
424
+ _context.prev = 11;
425
+ client.release();
426
+ return _context.finish(11);
427
+ case 14:
1552
428
  case "end":
1553
429
  return _context.stop();
1554
430
  }
1555
- }, _callee, this);
431
+ }, _callee, this, [[6,, 11, 14]]);
1556
432
  }));
1557
- function get(_x) {
1558
- return _get.apply(this, arguments);
433
+ function getThreadById(_x) {
434
+ return _getThreadById.apply(this, arguments);
1559
435
  }
1560
- return get;
436
+ return getThreadById;
1561
437
  }();
1562
- _proto.set = /*#__PURE__*/function () {
1563
- var _set = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(key, value) {
438
+ _proto.getThreadsByResourceId = /*#__PURE__*/function () {
439
+ var _getThreadsByResourceId = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(_ref2) {
440
+ var resourceid, client, result;
1564
441
  return _regeneratorRuntime().wrap(function _callee2$(_context2) {
1565
442
  while (1) switch (_context2.prev = _context2.next) {
1566
443
  case 0:
1567
- return _context2.abrupt("return", this.client.set(key, serializeData(value)));
1568
- case 1:
444
+ resourceid = _ref2.resourceid;
445
+ _context2.next = 3;
446
+ return this.ensureTablesExist();
447
+ case 3:
448
+ _context2.next = 5;
449
+ return this.pool.connect();
450
+ case 5:
451
+ client = _context2.sent;
452
+ _context2.prev = 6;
453
+ _context2.next = 9;
454
+ return client.query("\n SELECT id, title, resourceid, created_at AS createdAt, updated_at AS updatedAt, metadata\n FROM mastra_threads\n WHERE resourceid = $1\n ", [resourceid]);
455
+ case 9:
456
+ result = _context2.sent;
457
+ return _context2.abrupt("return", result.rows);
458
+ case 11:
459
+ _context2.prev = 11;
460
+ client.release();
461
+ return _context2.finish(11);
462
+ case 14:
1569
463
  case "end":
1570
464
  return _context2.stop();
1571
465
  }
1572
- }, _callee2, this);
466
+ }, _callee2, this, [[6,, 11, 14]]);
1573
467
  }));
1574
- function set(_x2, _x3) {
1575
- return _set.apply(this, arguments);
468
+ function getThreadsByResourceId(_x2) {
469
+ return _getThreadsByResourceId.apply(this, arguments);
1576
470
  }
1577
- return set;
471
+ return getThreadsByResourceId;
1578
472
  }();
1579
- _proto.del = /*#__PURE__*/function () {
1580
- var _del = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3(key) {
473
+ _proto.saveThread = /*#__PURE__*/function () {
474
+ var _saveThread = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3(_ref3) {
475
+ var thread, client, _result$rows, id, title, createdAt, updatedAt, resourceid, metadata, result;
1581
476
  return _regeneratorRuntime().wrap(function _callee3$(_context3) {
1582
477
  while (1) switch (_context3.prev = _context3.next) {
1583
478
  case 0:
1584
- return _context3.abrupt("return", this.client.del(key));
1585
- case 1:
479
+ thread = _ref3.thread;
480
+ _context3.next = 3;
481
+ return this.ensureTablesExist();
482
+ case 3:
483
+ _context3.next = 5;
484
+ return this.pool.connect();
485
+ case 5:
486
+ client = _context3.sent;
487
+ _context3.prev = 6;
488
+ id = thread.id, title = thread.title, createdAt = thread.createdAt, updatedAt = thread.updatedAt, resourceid = thread.resourceid, metadata = thread.metadata;
489
+ _context3.next = 10;
490
+ return client.query("\n INSERT INTO mastra_threads (id, title, created_at, updated_at, resourceid, metadata)\n VALUES ($1, $2, $3, $4, $5, $6)\n ON CONFLICT (id) DO UPDATE SET title = $2, updated_at = $4, resourceid = $5, metadata = $6\n RETURNING id, title, created_at AS createdAt, updated_at AS updatedAt, resourceid, metadata\n ", [id, title, createdAt, updatedAt, resourceid, JSON.stringify(metadata)]);
491
+ case 10:
492
+ result = _context3.sent;
493
+ return _context3.abrupt("return", result == null || (_result$rows = result.rows) == null ? void 0 : _result$rows[0]);
494
+ case 12:
495
+ _context3.prev = 12;
496
+ client.release();
497
+ return _context3.finish(12);
498
+ case 15:
1586
499
  case "end":
1587
500
  return _context3.stop();
1588
501
  }
1589
- }, _callee3, this);
502
+ }, _callee3, this, [[6,, 12, 15]]);
1590
503
  }));
1591
- function del(_x4) {
1592
- return _del.apply(this, arguments);
504
+ function saveThread(_x3) {
505
+ return _saveThread.apply(this, arguments);
1593
506
  }
1594
- return del;
507
+ return saveThread;
1595
508
  }();
1596
- _proto.sadd = /*#__PURE__*/function () {
1597
- var _sadd = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee4(key, value) {
509
+ _proto.updateThread = /*#__PURE__*/function () {
510
+ var _updateThread = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee4(id, title, metadata) {
511
+ var client, _result$rows2, result;
1598
512
  return _regeneratorRuntime().wrap(function _callee4$(_context4) {
1599
513
  while (1) switch (_context4.prev = _context4.next) {
1600
514
  case 0:
1601
- return _context4.abrupt("return", this.client.sadd(key, value));
1602
- case 1:
515
+ _context4.next = 2;
516
+ return this.pool.connect();
517
+ case 2:
518
+ client = _context4.sent;
519
+ _context4.prev = 3;
520
+ _context4.next = 6;
521
+ return client.query("\n UPDATE mastra_threads\n SET title = $1, metadata = $2, updated_at = NOW()\n WHERE id = $3\n RETURNING *\n ", [title, JSON.stringify(metadata), id]);
522
+ case 6:
523
+ result = _context4.sent;
524
+ return _context4.abrupt("return", result == null || (_result$rows2 = result.rows) == null ? void 0 : _result$rows2[0]);
525
+ case 8:
526
+ _context4.prev = 8;
527
+ client.release();
528
+ return _context4.finish(8);
529
+ case 11:
1603
530
  case "end":
1604
531
  return _context4.stop();
1605
532
  }
1606
- }, _callee4, this);
533
+ }, _callee4, this, [[3,, 8, 11]]);
1607
534
  }));
1608
- function sadd(_x5, _x6) {
1609
- return _sadd.apply(this, arguments);
535
+ function updateThread(_x4, _x5, _x6) {
536
+ return _updateThread.apply(this, arguments);
1610
537
  }
1611
- return sadd;
538
+ return updateThread;
1612
539
  }();
1613
- _proto.srem = /*#__PURE__*/function () {
1614
- var _srem = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee5(key, value) {
540
+ _proto.deleteThread = /*#__PURE__*/function () {
541
+ var _deleteThread = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee5(id) {
542
+ var client;
1615
543
  return _regeneratorRuntime().wrap(function _callee5$(_context5) {
1616
544
  while (1) switch (_context5.prev = _context5.next) {
1617
545
  case 0:
1618
- return _context5.abrupt("return", this.client.srem(key, value));
1619
- case 1:
546
+ _context5.next = 2;
547
+ return this.pool.connect();
548
+ case 2:
549
+ client = _context5.sent;
550
+ _context5.prev = 3;
551
+ _context5.next = 6;
552
+ return client.query("\n DELETE FROM mastra_messages\n WHERE thread_id = $1\n ", [id]);
553
+ case 6:
554
+ _context5.next = 8;
555
+ return client.query("\n DELETE FROM mastra_threads\n WHERE id = $1\n ", [id]);
556
+ case 8:
557
+ _context5.prev = 8;
558
+ client.release();
559
+ return _context5.finish(8);
560
+ case 11:
1620
561
  case "end":
1621
562
  return _context5.stop();
1622
563
  }
1623
- }, _callee5, this);
564
+ }, _callee5, this, [[3,, 8, 11]]);
1624
565
  }));
1625
- function srem(_x7, _x8) {
1626
- return _srem.apply(this, arguments);
566
+ function deleteThread(_x7) {
567
+ return _deleteThread.apply(this, arguments);
1627
568
  }
1628
- return srem;
1629
- }();
1630
- _proto.smembers = /*#__PURE__*/function () {
1631
- var _smembers = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee6(key) {
569
+ return deleteThread;
570
+ }()
571
+ /**
572
+ * Tool Cache
573
+ */
574
+ ;
575
+ _proto.validateToolCallArgs =
576
+ /*#__PURE__*/
577
+ function () {
578
+ var _validateToolCallArgs = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee6(_ref4) {
579
+ var hashedArgs, client, toolArgsResult;
1632
580
  return _regeneratorRuntime().wrap(function _callee6$(_context6) {
1633
581
  while (1) switch (_context6.prev = _context6.next) {
1634
582
  case 0:
1635
- return _context6.abrupt("return", this.client.smembers(key));
1636
- case 1:
583
+ hashedArgs = _ref4.hashedArgs;
584
+ _context6.next = 3;
585
+ return this.ensureTablesExist();
586
+ case 3:
587
+ _context6.next = 5;
588
+ return this.pool.connect();
589
+ case 5:
590
+ client = _context6.sent;
591
+ _context6.prev = 6;
592
+ _context6.next = 9;
593
+ return client.query(" SELECT tool_call_ids as toolCallIds, \n tool_call_args as toolCallArgs,\n created_at AS createdAt\n FROM mastra_messages\n WHERE tool_call_args::jsonb @> $1\n AND tool_call_args_expire_at > $2\n ORDER BY created_at ASC\n LIMIT 1", [JSON.stringify([hashedArgs]), new Date().toISOString()]);
594
+ case 9:
595
+ toolArgsResult = _context6.sent;
596
+ return _context6.abrupt("return", toolArgsResult.rows.length > 0);
597
+ case 13:
598
+ _context6.prev = 13;
599
+ _context6.t0 = _context6["catch"](6);
600
+ console.log('error checking if valid arg exists====', _context6.t0);
601
+ return _context6.abrupt("return", false);
602
+ case 17:
603
+ _context6.prev = 17;
604
+ client.release();
605
+ return _context6.finish(17);
606
+ case 20:
1637
607
  case "end":
1638
608
  return _context6.stop();
1639
609
  }
1640
- }, _callee6, this);
610
+ }, _callee6, this, [[6, 13, 17, 20]]);
1641
611
  }));
1642
- function smembers(_x9) {
1643
- return _smembers.apply(this, arguments);
612
+ function validateToolCallArgs(_x8) {
613
+ return _validateToolCallArgs.apply(this, arguments);
1644
614
  }
1645
- return smembers;
615
+ return validateToolCallArgs;
1646
616
  }();
1647
- _proto.flushall = /*#__PURE__*/function () {
1648
- var _flushall = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee7() {
617
+ _proto.getToolResult = /*#__PURE__*/function () {
618
+ var _getToolResult = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee7(_ref5) {
619
+ var threadId, toolArgs, toolName, client, hashedToolArgs, toolArgsResult, _toolArgsResult$rows$, _toolArgsResult$rows$2, _toolArgsResult$rows$3, _toolResult$rows$, toolCallArgs, toolCallIds, createdAt, toolCallArgsIndex, correspondingToolCallId, toolResult, toolResultContent, requiredToolResult;
1649
620
  return _regeneratorRuntime().wrap(function _callee7$(_context7) {
1650
621
  while (1) switch (_context7.prev = _context7.next) {
1651
622
  case 0:
1652
- return _context7.abrupt("return", this.client.flushall());
1653
- case 1:
623
+ threadId = _ref5.threadId, toolArgs = _ref5.toolArgs, toolName = _ref5.toolName;
624
+ _context7.next = 3;
625
+ return this.ensureTablesExist();
626
+ case 3:
627
+ console.log('checking for cached tool result====', JSON.stringify(toolArgs, null, 2));
628
+ _context7.next = 6;
629
+ return this.pool.connect();
630
+ case 6:
631
+ client = _context7.sent;
632
+ _context7.prev = 7;
633
+ hashedToolArgs = crypto.createHash('sha256').update(JSON.stringify({
634
+ args: toolArgs,
635
+ threadId: threadId,
636
+ toolName: toolName
637
+ })).digest('hex');
638
+ _context7.next = 11;
639
+ return client.query("SELECT tool_call_ids, \n tool_call_args,\n created_at\n FROM mastra_messages\n WHERE tool_call_args::jsonb @> $1\n AND tool_call_args_expire_at > $2\n ORDER BY created_at ASC\n LIMIT 1", [JSON.stringify([hashedToolArgs]), new Date().toISOString()]);
640
+ case 11:
641
+ toolArgsResult = _context7.sent;
642
+ if (!(toolArgsResult.rows.length > 0)) {
643
+ _context7.next = 28;
644
+ break;
645
+ }
646
+ toolCallArgs = JSON.parse((_toolArgsResult$rows$ = toolArgsResult.rows[0]) == null ? void 0 : _toolArgsResult$rows$.tool_call_args);
647
+ toolCallIds = JSON.parse((_toolArgsResult$rows$2 = toolArgsResult.rows[0]) == null ? void 0 : _toolArgsResult$rows$2.tool_call_ids);
648
+ createdAt = (_toolArgsResult$rows$3 = toolArgsResult.rows[0]) == null ? void 0 : _toolArgsResult$rows$3.created_at;
649
+ toolCallArgsIndex = toolCallArgs.findIndex(function (arg) {
650
+ return arg === hashedToolArgs;
651
+ });
652
+ correspondingToolCallId = toolCallIds[toolCallArgsIndex];
653
+ _context7.next = 20;
654
+ return client.query("SELECT content \n FROM mastra_messages \n WHERE thread_id = $1\n AND tool_call_ids ILIKE $2\n AND type = 'tool-result'\n AND created_at = $3\n LIMIT 1", [threadId, "%" + correspondingToolCallId + "%", new Date(createdAt).toISOString()]);
655
+ case 20:
656
+ toolResult = _context7.sent;
657
+ if (!(toolResult.rows.length === 0)) {
658
+ _context7.next = 24;
659
+ break;
660
+ }
661
+ console.log('no tool result found');
662
+ return _context7.abrupt("return", null);
663
+ case 24:
664
+ toolResultContent = JSON.parse((_toolResult$rows$ = toolResult.rows[0]) == null ? void 0 : _toolResult$rows$.content);
665
+ requiredToolResult = toolResultContent.find(function (part) {
666
+ return part.toolCallId === correspondingToolCallId;
667
+ });
668
+ if (!requiredToolResult) {
669
+ _context7.next = 28;
670
+ break;
671
+ }
672
+ return _context7.abrupt("return", requiredToolResult.result);
673
+ case 28:
674
+ return _context7.abrupt("return", null);
675
+ case 31:
676
+ _context7.prev = 31;
677
+ _context7.t0 = _context7["catch"](7);
678
+ console.log('error getting cached tool result====', _context7.t0);
679
+ return _context7.abrupt("return", null);
680
+ case 35:
681
+ _context7.prev = 35;
682
+ client.release();
683
+ return _context7.finish(35);
684
+ case 38:
1654
685
  case "end":
1655
686
  return _context7.stop();
1656
687
  }
1657
- }, _callee7, this);
688
+ }, _callee7, this, [[7, 31, 35, 38]]);
1658
689
  }));
1659
- function flushall() {
1660
- return _flushall.apply(this, arguments);
690
+ function getToolResult(_x9) {
691
+ return _getToolResult.apply(this, arguments);
1661
692
  }
1662
- return flushall;
693
+ return getToolResult;
1663
694
  }();
1664
- _proto.pipeline = function pipeline() {
1665
- var multi = this.client.multi();
1666
- var pipeline = {
1667
- get: function get(key) {
1668
- multi.get(key);
1669
- return pipeline;
1670
- },
1671
- set: function set(key, value) {
1672
- multi.set(key, JSON.stringify(serializeData(value)));
1673
- return pipeline;
1674
- },
1675
- del: function del(key) {
1676
- multi.del(key);
1677
- return pipeline;
1678
- },
1679
- srem: function srem(key, value) {
1680
- multi.srem(key, value);
1681
- return pipeline;
1682
- },
1683
- exec: function () {
1684
- var _exec = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee8() {
1685
- var results;
1686
- return _regeneratorRuntime().wrap(function _callee8$(_context8) {
1687
- while (1) switch (_context8.prev = _context8.next) {
1688
- case 0:
1689
- _context8.next = 2;
1690
- return multi.exec();
1691
- case 2:
1692
- results = _context8.sent;
1693
- return _context8.abrupt("return", results.map(function (result) {
1694
- try {
1695
- // For get operations that return string data
1696
- if (typeof result === 'string') {
1697
- return deserializeData(JSON.parse(result));
1698
- }
1699
- // For array results (like from lists/sets)
1700
- if (Array.isArray(result)) {
1701
- return result.map(function (item) {
1702
- try {
1703
- return typeof item === 'string' ? deserializeData(JSON.parse(item)) : item;
1704
- } catch (_unused) {
1705
- return item;
1706
- }
1707
- });
1708
- }
1709
- return result;
1710
- } catch (_unused2) {
1711
- return result;
1712
- }
1713
- }));
1714
- case 4:
1715
- case "end":
1716
- return _context8.stop();
1717
- }
1718
- }, _callee8);
1719
- }));
1720
- function exec() {
1721
- return _exec.apply(this, arguments);
1722
- }
1723
- return exec;
1724
- }()
1725
- };
1726
- return pipeline;
1727
- };
1728
- return UpstashProvider;
1729
- }();
1730
- var LocalRedisProvider = /*#__PURE__*/function () {
1731
- function LocalRedisProvider() {
1732
- this.client = void 0;
1733
- this.client = redis$1.createClient({
1734
- url: 'redis://localhost:6379'
1735
- });
1736
- this.client.connect();
1737
- }
1738
- var _proto2 = LocalRedisProvider.prototype;
1739
- _proto2.get = /*#__PURE__*/function () {
1740
- var _get2 = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee9(key) {
1741
- var data;
1742
- return _regeneratorRuntime().wrap(function _callee9$(_context9) {
1743
- while (1) switch (_context9.prev = _context9.next) {
695
+ _proto.getContextWindow = /*#__PURE__*/function () {
696
+ var _getContextWindow = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee8(_ref6) {
697
+ var threadId, startDate, endDate, _ref6$format, format, client, _result, result;
698
+ return _regeneratorRuntime().wrap(function _callee8$(_context8) {
699
+ while (1) switch (_context8.prev = _context8.next) {
1744
700
  case 0:
1745
- _context9.next = 2;
1746
- return this.client.get(key);
1747
- case 2:
1748
- data = _context9.sent;
1749
- return _context9.abrupt("return", data ? deserializeData(JSON.parse(data)) : null);
1750
- case 4:
701
+ threadId = _ref6.threadId, startDate = _ref6.startDate, endDate = _ref6.endDate, _ref6$format = _ref6.format, format = _ref6$format === void 0 ? 'raw' : _ref6$format;
702
+ _context8.next = 3;
703
+ return this.ensureTablesExist();
704
+ case 3:
705
+ _context8.next = 5;
706
+ return this.pool.connect();
707
+ case 5:
708
+ client = _context8.sent;
709
+ _context8.prev = 6;
710
+ if (!this.MAX_CONTEXT_TOKENS) {
711
+ _context8.next = 13;
712
+ break;
713
+ }
714
+ _context8.next = 10;
715
+ return client.query("WITH RankedMessages AS (\n SELECT *,\n SUM(tokens) OVER (ORDER BY created_at DESC) as running_total\n FROM mastra_messages\n WHERE thread_id = $1\n AND type = 'text'\n " + (startDate ? "AND created_at >= '" + startDate.toISOString() + "'" : '') + "\n " + (endDate ? "AND created_at <= '" + endDate.toISOString() + "'" : '') + "\n ORDER BY created_at DESC\n )\n SELECT id, \n content, \n role, \n type,\n created_at AS createdAt, \n thread_id AS threadId\n FROM RankedMessages\n WHERE running_total <= $2\n ORDER BY created_at ASC", [threadId, this.MAX_CONTEXT_TOKENS]);
716
+ case 10:
717
+ _result = _context8.sent;
718
+ console.log('Format', format);
719
+ return _context8.abrupt("return", this.parseMessages(_result.rows));
720
+ case 13:
721
+ _context8.next = 15;
722
+ return client.query("SELECT id, \n content, \n role, \n type,\n created_at AS createdAt, \n thread_id AS threadId\n FROM mastra_messages\n WHERE thread_id = $1\n AND type = 'text'\n " + (startDate ? "AND created_at >= '" + startDate.toISOString() + "'" : '') + "\n " + (endDate ? "AND created_at <= '" + endDate.toISOString() + "'" : '') + "\n ORDER BY created_at ASC", [threadId]);
723
+ case 15:
724
+ result = _context8.sent;
725
+ console.log('Format', format);
726
+ return _context8.abrupt("return", this.parseMessages(result.rows));
727
+ case 20:
728
+ _context8.prev = 20;
729
+ _context8.t0 = _context8["catch"](6);
730
+ console.log('error getting context window====', _context8.t0);
731
+ return _context8.abrupt("return", []);
732
+ case 24:
733
+ _context8.prev = 24;
734
+ client.release();
735
+ return _context8.finish(24);
736
+ case 27:
1751
737
  case "end":
1752
- return _context9.stop();
738
+ return _context8.stop();
1753
739
  }
1754
- }, _callee9, this);
740
+ }, _callee8, this, [[6, 20, 24, 27]]);
1755
741
  }));
1756
- function get(_x10) {
1757
- return _get2.apply(this, arguments);
742
+ function getContextWindow(_x10) {
743
+ return _getContextWindow.apply(this, arguments);
1758
744
  }
1759
- return get;
1760
- }();
1761
- _proto2.set = /*#__PURE__*/function () {
1762
- var _set2 = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee10(key, value) {
1763
- return _regeneratorRuntime().wrap(function _callee10$(_context10) {
1764
- while (1) switch (_context10.prev = _context10.next) {
745
+ return getContextWindow;
746
+ }()
747
+ /**
748
+ * Messages
749
+ */
750
+ ;
751
+ _proto.getMessages =
752
+ /*#__PURE__*/
753
+ function () {
754
+ var _getMessages = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee9(_ref7) {
755
+ var threadId, client, result, messages, uiMessages;
756
+ return _regeneratorRuntime().wrap(function _callee9$(_context9) {
757
+ while (1) switch (_context9.prev = _context9.next) {
1765
758
  case 0:
1766
- return _context10.abrupt("return", this.client.set(key, JSON.stringify(serializeData(value))));
1767
- case 1:
759
+ threadId = _ref7.threadId;
760
+ _context9.next = 3;
761
+ return this.ensureTablesExist();
762
+ case 3:
763
+ _context9.next = 5;
764
+ return this.pool.connect();
765
+ case 5:
766
+ client = _context9.sent;
767
+ _context9.prev = 6;
768
+ _context9.next = 9;
769
+ return client.query("\n SELECT \n id, \n content, \n role, \n type,\n created_at AS createdAt, \n thread_id AS threadId\n FROM mastra_messages\n WHERE thread_id = $1\n ORDER BY created_at ASC\n ", [threadId]);
770
+ case 9:
771
+ result = _context9.sent;
772
+ messages = this.parseMessages(result.rows);
773
+ uiMessages = this.convertToUIMessages(messages);
774
+ return _context9.abrupt("return", {
775
+ messages: messages,
776
+ uiMessages: uiMessages
777
+ });
778
+ case 13:
779
+ _context9.prev = 13;
780
+ client.release();
781
+ return _context9.finish(13);
782
+ case 16:
1768
783
  case "end":
1769
- return _context10.stop();
784
+ return _context9.stop();
1770
785
  }
1771
- }, _callee10, this);
786
+ }, _callee9, this, [[6,, 13, 16]]);
1772
787
  }));
1773
- function set(_x11, _x12) {
1774
- return _set2.apply(this, arguments);
788
+ function getMessages(_x11) {
789
+ return _getMessages.apply(this, arguments);
1775
790
  }
1776
- return set;
791
+ return getMessages;
1777
792
  }();
1778
- _proto2.del = /*#__PURE__*/function () {
1779
- var _del2 = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee11(key) {
1780
- return _regeneratorRuntime().wrap(function _callee11$(_context11) {
793
+ _proto.saveMessages = /*#__PURE__*/function () {
794
+ var _saveMessages = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee10(_ref8) {
795
+ var _this2 = this;
796
+ var messages, client, _loop, _iterator, _step;
797
+ return _regeneratorRuntime().wrap(function _callee10$(_context11) {
1781
798
  while (1) switch (_context11.prev = _context11.next) {
1782
799
  case 0:
1783
- return _context11.abrupt("return", this.client.del(key));
1784
- case 1:
800
+ messages = _ref8.messages;
801
+ _context11.next = 3;
802
+ return this.ensureTablesExist();
803
+ case 3:
804
+ _context11.next = 5;
805
+ return this.pool.connect();
806
+ case 5:
807
+ client = _context11.sent;
808
+ _context11.prev = 6;
809
+ _context11.next = 9;
810
+ return client.query('BEGIN');
811
+ case 9:
812
+ _loop = /*#__PURE__*/_regeneratorRuntime().mark(function _loop() {
813
+ var message, id, content, role, createdAt, threadId, toolCallIds, toolCallArgs, type, toolNames, tokens, _content$, contentMssg, hashedToolCallArgs, validArgExists, i, isValid, toolCallArgsExpireAt;
814
+ return _regeneratorRuntime().wrap(function _loop$(_context10) {
815
+ while (1) switch (_context10.prev = _context10.next) {
816
+ case 0:
817
+ message = _step.value;
818
+ id = message.id, content = message.content, role = message.role, createdAt = message.createdAt, threadId = message.threadId, toolCallIds = message.toolCallIds, toolCallArgs = message.toolCallArgs, type = message.type, toolNames = message.toolNames;
819
+ tokens = null;
820
+ if (type === 'text') {
821
+ contentMssg = role === 'assistant' ? ((_content$ = content[0]) == null ? void 0 : _content$.text) || '' : content;
822
+ tokens = _this2.estimateTokens(contentMssg);
823
+ }
824
+ // Hash the toolCallArgs if they exist
825
+ hashedToolCallArgs = toolCallArgs ? toolCallArgs.map(function (args, index) {
826
+ return crypto.createHash('sha256').update(JSON.stringify({
827
+ args: args,
828
+ threadId: threadId,
829
+ toolName: toolNames == null ? void 0 : toolNames[index]
830
+ })).digest('hex');
831
+ }) : null;
832
+ validArgExists = false;
833
+ if (!(hashedToolCallArgs != null && hashedToolCallArgs.length)) {
834
+ _context10.next = 19;
835
+ break;
836
+ }
837
+ // Check all args sequentially
838
+ validArgExists = true; // Start true and set to false if any check fails
839
+ i = 0;
840
+ case 9:
841
+ if (!(i < hashedToolCallArgs.length)) {
842
+ _context10.next = 19;
843
+ break;
844
+ }
845
+ _context10.next = 12;
846
+ return _this2.validateToolCallArgs({
847
+ hashedArgs: hashedToolCallArgs[i]
848
+ });
849
+ case 12:
850
+ isValid = _context10.sent;
851
+ if (isValid) {
852
+ _context10.next = 16;
853
+ break;
854
+ }
855
+ validArgExists = false;
856
+ return _context10.abrupt("break", 19);
857
+ case 16:
858
+ i++;
859
+ _context10.next = 9;
860
+ break;
861
+ case 19:
862
+ toolCallArgsExpireAt = !toolCallArgs ? null : validArgExists ? createdAt : new Date(createdAt.getTime() + 5 * 60 * 1000); // 5 minutes
863
+ _context10.next = 22;
864
+ return client.query("\n INSERT INTO mastra_messages (id, content, role, created_at, thread_id, tool_call_ids, tool_call_args, type, tokens, tool_call_args_expire_at)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)\n ", [id, JSON.stringify(content), role, createdAt.toISOString(), threadId, JSON.stringify(toolCallIds), JSON.stringify(hashedToolCallArgs), type, tokens, toolCallArgsExpireAt == null ? void 0 : toolCallArgsExpireAt.toISOString()]);
865
+ case 22:
866
+ case "end":
867
+ return _context10.stop();
868
+ }
869
+ }, _loop);
870
+ });
871
+ _iterator = _createForOfIteratorHelperLoose(messages);
872
+ case 11:
873
+ if ((_step = _iterator()).done) {
874
+ _context11.next = 15;
875
+ break;
876
+ }
877
+ return _context11.delegateYield(_loop(), "t0", 13);
878
+ case 13:
879
+ _context11.next = 11;
880
+ break;
881
+ case 15:
882
+ _context11.next = 17;
883
+ return client.query('COMMIT');
884
+ case 17:
885
+ return _context11.abrupt("return", messages);
886
+ case 20:
887
+ _context11.prev = 20;
888
+ _context11.t1 = _context11["catch"](6);
889
+ _context11.next = 24;
890
+ return client.query('ROLLBACK');
891
+ case 24:
892
+ throw _context11.t1;
893
+ case 25:
894
+ _context11.prev = 25;
895
+ client.release();
896
+ return _context11.finish(25);
897
+ case 28:
1785
898
  case "end":
1786
899
  return _context11.stop();
1787
900
  }
1788
- }, _callee11, this);
901
+ }, _callee10, this, [[6, 20, 25, 28]]);
1789
902
  }));
1790
- function del(_x13) {
1791
- return _del2.apply(this, arguments);
903
+ function saveMessages(_x12) {
904
+ return _saveMessages.apply(this, arguments);
1792
905
  }
1793
- return del;
906
+ return saveMessages;
1794
907
  }();
1795
- _proto2.sadd = /*#__PURE__*/function () {
1796
- var _sadd2 = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee12(key, value) {
1797
- return _regeneratorRuntime().wrap(function _callee12$(_context12) {
908
+ _proto.deleteMessage = /*#__PURE__*/function () {
909
+ var _deleteMessage = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee11(id) {
910
+ var client;
911
+ return _regeneratorRuntime().wrap(function _callee11$(_context12) {
1798
912
  while (1) switch (_context12.prev = _context12.next) {
1799
913
  case 0:
1800
- return _context12.abrupt("return", this.client.sAdd(key, value));
1801
- case 1:
914
+ _context12.next = 2;
915
+ return this.pool.connect();
916
+ case 2:
917
+ client = _context12.sent;
918
+ _context12.prev = 3;
919
+ _context12.next = 6;
920
+ return client.query("\n DELETE FROM mastra_messages\n WHERE id = $1\n ", [id]);
921
+ case 6:
922
+ _context12.prev = 6;
923
+ client.release();
924
+ return _context12.finish(6);
925
+ case 9:
1802
926
  case "end":
1803
927
  return _context12.stop();
1804
928
  }
1805
- }, _callee12, this);
929
+ }, _callee11, this, [[3,, 6, 9]]);
1806
930
  }));
1807
- function sadd(_x14, _x15) {
1808
- return _sadd2.apply(this, arguments);
931
+ function deleteMessage(_x13) {
932
+ return _deleteMessage.apply(this, arguments);
1809
933
  }
1810
- return sadd;
1811
- }();
1812
- _proto2.srem = /*#__PURE__*/function () {
1813
- var _srem2 = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee13(key, value) {
1814
- return _regeneratorRuntime().wrap(function _callee13$(_context13) {
934
+ return deleteMessage;
935
+ }()
936
+ /**
937
+ * Table Management
938
+ */
939
+ ;
940
+ _proto.drop =
941
+ /*#__PURE__*/
942
+ function () {
943
+ var _drop = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee12() {
944
+ var client;
945
+ return _regeneratorRuntime().wrap(function _callee12$(_context13) {
1815
946
  while (1) switch (_context13.prev = _context13.next) {
1816
947
  case 0:
1817
- return _context13.abrupt("return", this.client.sRem(key, value));
1818
- case 1:
948
+ _context13.next = 2;
949
+ return this.pool.connect();
950
+ case 2:
951
+ client = _context13.sent;
952
+ _context13.next = 5;
953
+ return client.query('DELETE FROM mastra_messages');
954
+ case 5:
955
+ _context13.next = 7;
956
+ return client.query('DELETE FROM mastra_threads');
957
+ case 7:
958
+ client.release();
959
+ _context13.next = 10;
960
+ return this.pool.end();
961
+ case 10:
1819
962
  case "end":
1820
963
  return _context13.stop();
1821
964
  }
1822
- }, _callee13, this);
965
+ }, _callee12, this);
1823
966
  }));
1824
- function srem(_x16, _x17) {
1825
- return _srem2.apply(this, arguments);
967
+ function drop() {
968
+ return _drop.apply(this, arguments);
1826
969
  }
1827
- return srem;
970
+ return drop;
1828
971
  }();
1829
- _proto2.smembers = /*#__PURE__*/function () {
1830
- var _smembers2 = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee14(key) {
1831
- return _regeneratorRuntime().wrap(function _callee14$(_context14) {
972
+ _proto.ensureTablesExist = /*#__PURE__*/function () {
973
+ var _ensureTablesExist = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee13() {
974
+ var client, _threadsResult$rows, _messagesResult$rows, threadsResult, messagesResult;
975
+ return _regeneratorRuntime().wrap(function _callee13$(_context14) {
1832
976
  while (1) switch (_context14.prev = _context14.next) {
1833
977
  case 0:
1834
- return _context14.abrupt("return", this.client.sMembers(key));
1835
- case 1:
1836
- case "end":
1837
- return _context14.stop();
1838
- }
1839
- }, _callee14, this);
1840
- }));
1841
- function smembers(_x18) {
1842
- return _smembers2.apply(this, arguments);
1843
- }
1844
- return smembers;
1845
- }();
1846
- _proto2.flushall = /*#__PURE__*/function () {
1847
- var _flushall2 = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee15() {
1848
- return _regeneratorRuntime().wrap(function _callee15$(_context15) {
1849
- while (1) switch (_context15.prev = _context15.next) {
1850
- case 0:
1851
- return _context15.abrupt("return", this.client.flushAll());
1852
- case 1:
1853
- case "end":
1854
- return _context15.stop();
1855
- }
1856
- }, _callee15, this);
1857
- }));
1858
- function flushall() {
1859
- return _flushall2.apply(this, arguments);
1860
- }
1861
- return flushall;
1862
- }();
1863
- _proto2.pipeline = function pipeline() {
1864
- var multi = this.client.multi();
1865
- var pipeline = {
1866
- get: function get(key) {
1867
- multi.get(key);
1868
- return pipeline;
1869
- },
1870
- set: function set(key, value) {
1871
- multi.set(key, JSON.stringify(value));
1872
- return pipeline;
1873
- },
1874
- del: function del(key) {
1875
- multi.del(key);
1876
- return pipeline;
1877
- },
1878
- srem: function srem(key, value) {
1879
- multi.sRem(key, value);
1880
- return pipeline;
1881
- },
1882
- exec: function () {
1883
- var _exec2 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee16() {
1884
- return _regeneratorRuntime().wrap(function _callee16$(_context16) {
1885
- while (1) switch (_context16.prev = _context16.next) {
1886
- case 0:
1887
- return _context16.abrupt("return", multi.exec());
1888
- case 1:
1889
- case "end":
1890
- return _context16.stop();
978
+ if (!this.hasTables) {
979
+ _context14.next = 2;
980
+ break;
981
+ }
982
+ return _context14.abrupt("return");
983
+ case 2:
984
+ _context14.next = 4;
985
+ return this.pool.connect();
986
+ case 4:
987
+ client = _context14.sent;
988
+ _context14.prev = 5;
989
+ _context14.next = 8;
990
+ return client.query("\n SELECT EXISTS (\n SELECT 1\n FROM information_schema.tables\n WHERE table_name = 'mastra_threads'\n );\n ");
991
+ case 8:
992
+ threadsResult = _context14.sent;
993
+ if (threadsResult != null && (_threadsResult$rows = threadsResult.rows) != null && (_threadsResult$rows = _threadsResult$rows[0]) != null && _threadsResult$rows.exists) {
994
+ _context14.next = 12;
995
+ break;
996
+ }
997
+ _context14.next = 12;
998
+ return client.query("\n CREATE TABLE IF NOT EXISTS mastra_threads (\n id UUID PRIMARY KEY,\n resourceid TEXT,\n title TEXT,\n created_at TIMESTAMP WITH TIME ZONE NOT NULL,\n updated_at TIMESTAMP WITH TIME ZONE NOT NULL,\n metadata JSONB\n );\n ");
999
+ case 12:
1000
+ _context14.next = 14;
1001
+ return client.query("\n SELECT EXISTS (\n SELECT 1\n FROM information_schema.tables\n WHERE table_name = 'mastra_messages'\n );\n ");
1002
+ case 14:
1003
+ messagesResult = _context14.sent;
1004
+ if (messagesResult != null && (_messagesResult$rows = messagesResult.rows) != null && (_messagesResult$rows = _messagesResult$rows[0]) != null && _messagesResult$rows.exists) {
1005
+ _context14.next = 18;
1006
+ break;
1891
1007
  }
1892
- }, _callee16);
1893
- }));
1894
- function exec() {
1895
- return _exec2.apply(this, arguments);
1896
- }
1897
- return exec;
1898
- }()
1899
- };
1900
- return pipeline;
1901
- };
1902
- _proto2.quit = /*#__PURE__*/function () {
1903
- var _quit = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee17() {
1904
- return _regeneratorRuntime().wrap(function _callee17$(_context17) {
1905
- while (1) switch (_context17.prev = _context17.next) {
1906
- case 0:
1907
- _context17.next = 2;
1908
- return this.client.quit();
1909
- case 2:
1008
+ _context14.next = 18;
1009
+ return client.query("\n CREATE TABLE IF NOT EXISTS mastra_messages (\n id UUID PRIMARY KEY,\n content TEXT NOT NULL,\n role VARCHAR(20) NOT NULL,\n created_at TIMESTAMP WITH TIME ZONE NOT NULL,\n tool_call_ids TEXT DEFAULT NULL,\n tool_call_args TEXT DEFAULT NULL,\n tool_call_args_expire_at TIMESTAMP WITH TIME ZONE DEFAULT NULL,\n type VARCHAR(20) NOT NULL,\n tokens INTEGER DEFAULT NULL,\n thread_id UUID NOT NULL,\n FOREIGN KEY (thread_id) REFERENCES mastra_threads(id)\n );\n ");
1010
+ case 18:
1011
+ _context14.prev = 18;
1012
+ client.release();
1013
+ this.hasTables = true;
1014
+ return _context14.finish(18);
1015
+ case 22:
1910
1016
  case "end":
1911
- return _context17.stop();
1017
+ return _context14.stop();
1912
1018
  }
1913
- }, _callee17, this);
1019
+ }, _callee13, this, [[5,, 18, 22]]);
1914
1020
  }));
1915
- function quit() {
1916
- return _quit.apply(this, arguments);
1021
+ function ensureTablesExist() {
1022
+ return _ensureTablesExist.apply(this, arguments);
1917
1023
  }
1918
- return quit;
1024
+ return ensureTablesExist;
1919
1025
  }();
1920
- return LocalRedisProvider;
1921
- }();
1026
+ return PgMemory;
1027
+ }(core.MastraMemory);
1922
1028
 
1923
- var RedisMemory = /*#__PURE__*/function (_MastraMemory) {
1924
- function RedisMemory(redis) {
1029
+ var UpstashKVMemory = /*#__PURE__*/function (_MastraMemory) {
1030
+ function UpstashKVMemory(config) {
1925
1031
  var _this;
1926
1032
  _this = _MastraMemory.call(this) || this;
1927
- _this.redis = void 0;
1928
- _this.threadPrefix = 'thread:';
1929
- _this.messagePrefix = 'messages:';
1930
- _this.lockTimeouts = new Map();
1931
- _this.redis = redis;
1033
+ _this.prefix = void 0;
1034
+ _this.kv = void 0;
1035
+ _this.prefix = config.prefix || 'mastra';
1036
+ _this.MAX_CONTEXT_TOKENS = config.maxTokens;
1037
+ _this.kv = new redis.Redis({
1038
+ url: config.url,
1039
+ token: config.token
1040
+ });
1932
1041
  return _this;
1933
1042
  }
1934
- _inheritsLoose(RedisMemory, _MastraMemory);
1935
- var _proto = RedisMemory.prototype;
1043
+ _inheritsLoose(UpstashKVMemory, _MastraMemory);
1044
+ var _proto = UpstashKVMemory.prototype;
1045
+ _proto.getThreadKey = function getThreadKey(threadId) {
1046
+ return this.prefix + ":thread:" + threadId;
1047
+ };
1048
+ _proto.getMessagesKey = function getMessagesKey(threadId) {
1049
+ return this.prefix + ":messages:" + threadId;
1050
+ };
1051
+ _proto.getToolCacheKey = function getToolCacheKey(hashedArgs) {
1052
+ return this.prefix + ":tool:" + hashedArgs;
1053
+ };
1936
1054
  _proto.getThreadById = /*#__PURE__*/function () {
1937
- var _getThreadById = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(threadId) {
1938
- var thread;
1055
+ var _getThreadById = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(_ref) {
1056
+ var threadId, thread;
1939
1057
  return _regeneratorRuntime().wrap(function _callee$(_context) {
1940
1058
  while (1) switch (_context.prev = _context.next) {
1941
1059
  case 0:
1942
- _context.next = 2;
1943
- return this.redis.get("" + this.threadPrefix + threadId);
1944
- case 2:
1060
+ threadId = _ref.threadId;
1061
+ _context.next = 3;
1062
+ return this.kv.get(this.getThreadKey(threadId));
1063
+ case 3:
1945
1064
  thread = _context.sent;
1946
- if (thread && typeof thread.createdAt === 'string') {
1947
- thread.createdAt = new Date(thread.createdAt);
1948
- thread.updatedAt = new Date(thread.updatedAt);
1949
- }
1950
- return _context.abrupt("return", thread);
1065
+ return _context.abrupt("return", thread ? this.parseThread(thread) : null);
1951
1066
  case 5:
1952
1067
  case "end":
1953
1068
  return _context.stop();
@@ -1959,411 +1074,506 @@ var RedisMemory = /*#__PURE__*/function (_MastraMemory) {
1959
1074
  }
1960
1075
  return getThreadById;
1961
1076
  }();
1962
- _proto.saveThread = /*#__PURE__*/function () {
1963
- var _saveThread = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(thread) {
1077
+ _proto.getThreadsByResourceId = /*#__PURE__*/function () {
1078
+ var _getThreadsByResourceId = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(_ref2) {
1079
+ var _this2 = this;
1080
+ var resourceid, pattern, keys, threads;
1964
1081
  return _regeneratorRuntime().wrap(function _callee2$(_context2) {
1965
1082
  while (1) switch (_context2.prev = _context2.next) {
1966
1083
  case 0:
1967
- thread.updatedAt = new Date();
1968
- _context2.next = 3;
1969
- return this.redis.set("" + this.threadPrefix + thread.id, thread);
1970
- case 3:
1971
- _context2.next = 5;
1972
- return this.redis.sadd('threads', thread.id);
1973
- case 5:
1974
- return _context2.abrupt("return", thread);
1975
- case 6:
1084
+ resourceid = _ref2.resourceid;
1085
+ pattern = this.prefix + ":thread:*";
1086
+ _context2.next = 4;
1087
+ return this.kv.keys(pattern);
1088
+ case 4:
1089
+ keys = _context2.sent;
1090
+ _context2.next = 7;
1091
+ return Promise.all(keys.map(function (key) {
1092
+ return _this2.kv.get(key);
1093
+ }));
1094
+ case 7:
1095
+ threads = _context2.sent;
1096
+ return _context2.abrupt("return", threads.filter(function (thread) {
1097
+ return (thread == null ? void 0 : thread.resourceid) === resourceid;
1098
+ }).map(function (thread) {
1099
+ return _this2.parseThread(thread);
1100
+ }));
1101
+ case 9:
1976
1102
  case "end":
1977
1103
  return _context2.stop();
1978
1104
  }
1979
1105
  }, _callee2, this);
1980
1106
  }));
1981
- function saveThread(_x2) {
1107
+ function getThreadsByResourceId(_x2) {
1108
+ return _getThreadsByResourceId.apply(this, arguments);
1109
+ }
1110
+ return getThreadsByResourceId;
1111
+ }();
1112
+ _proto.saveThread = /*#__PURE__*/function () {
1113
+ var _saveThread = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3(_ref3) {
1114
+ var thread, key, serializedThread;
1115
+ return _regeneratorRuntime().wrap(function _callee3$(_context3) {
1116
+ while (1) switch (_context3.prev = _context3.next) {
1117
+ case 0:
1118
+ thread = _ref3.thread;
1119
+ key = this.getThreadKey(thread.id);
1120
+ serializedThread = _extends({}, thread, {
1121
+ createdAt: thread.createdAt.toISOString(),
1122
+ updatedAt: thread.updatedAt.toISOString()
1123
+ });
1124
+ _context3.next = 5;
1125
+ return this.kv.set(key, serializedThread);
1126
+ case 5:
1127
+ return _context3.abrupt("return", thread);
1128
+ case 6:
1129
+ case "end":
1130
+ return _context3.stop();
1131
+ }
1132
+ }, _callee3, this);
1133
+ }));
1134
+ function saveThread(_x3) {
1982
1135
  return _saveThread.apply(this, arguments);
1983
1136
  }
1984
1137
  return saveThread;
1985
1138
  }();
1986
- _proto.withLock = /*#__PURE__*/function () {
1987
- var _withLock = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee4(key, operation) {
1988
- var _this2 = this;
1989
- var lockKey, lockTimeout, locked, timeoutId, i;
1139
+ _proto.updateThread = /*#__PURE__*/function () {
1140
+ var _updateThread = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee4(id, title, metadata) {
1141
+ var key, thread, updatedThread;
1990
1142
  return _regeneratorRuntime().wrap(function _callee4$(_context4) {
1991
1143
  while (1) switch (_context4.prev = _context4.next) {
1992
1144
  case 0:
1993
- lockKey = "lock:" + key;
1994
- lockTimeout = 5000;
1995
- locked = false;
1996
- _context4.prev = 3;
1997
- i = 0;
1998
- case 5:
1999
- if (!(i < 3)) {
2000
- _context4.next = 16;
2001
- break;
2002
- }
2003
- _context4.next = 8;
2004
- return this.redis.sadd(lockKey, '1');
2005
- case 8:
2006
- locked = _context4.sent;
2007
- if (!locked) {
2008
- _context4.next = 11;
1145
+ key = this.getThreadKey(id);
1146
+ _context4.next = 3;
1147
+ return this.kv.get(key);
1148
+ case 3:
1149
+ thread = _context4.sent;
1150
+ if (thread) {
1151
+ _context4.next = 6;
2009
1152
  break;
2010
1153
  }
2011
- return _context4.abrupt("break", 16);
2012
- case 11:
2013
- _context4.next = 13;
2014
- return new Promise(function (resolve) {
2015
- return setTimeout(resolve, Math.random() * 100);
1154
+ throw new Error("Thread " + id + " not found");
1155
+ case 6:
1156
+ updatedThread = _extends({}, thread, {
1157
+ title: title,
1158
+ metadata: metadata,
1159
+ updatedAt: new Date().toISOString()
2016
1160
  });
2017
- case 13:
2018
- i++;
2019
- _context4.next = 5;
2020
- break;
2021
- case 16:
2022
- if (locked) {
2023
- _context4.next = 18;
2024
- break;
2025
- }
2026
- throw new Error('Could not acquire lock');
2027
- case 18:
2028
- // Set lock timeout
2029
- timeoutId = setTimeout(/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
2030
- return _regeneratorRuntime().wrap(function _callee3$(_context3) {
2031
- while (1) switch (_context3.prev = _context3.next) {
2032
- case 0:
2033
- _context3.prev = 0;
2034
- _context3.next = 3;
2035
- return _this2.redis.del(lockKey);
2036
- case 3:
2037
- _context3.next = 7;
2038
- break;
2039
- case 5:
2040
- _context3.prev = 5;
2041
- _context3.t0 = _context3["catch"](0);
2042
- case 7:
2043
- _this2.lockTimeouts["delete"](lockKey);
2044
- case 8:
2045
- case "end":
2046
- return _context3.stop();
2047
- }
2048
- }, _callee3, null, [[0, 5]]);
2049
- })), lockTimeout);
2050
- this.lockTimeouts.set(lockKey, timeoutId);
2051
- // Execute operation
2052
- _context4.next = 22;
2053
- return operation();
2054
- case 22:
2055
- return _context4.abrupt("return", _context4.sent);
2056
- case 23:
2057
- _context4.prev = 23;
2058
- if (timeoutId !== undefined) {
2059
- clearTimeout(timeoutId);
2060
- this.lockTimeouts["delete"](lockKey);
2061
- }
2062
- if (!locked) {
2063
- _context4.next = 33;
2064
- break;
2065
- }
2066
- _context4.prev = 26;
2067
- _context4.next = 29;
2068
- return this.redis.del(lockKey);
2069
- case 29:
2070
- _context4.next = 33;
2071
- break;
2072
- case 31:
2073
- _context4.prev = 31;
2074
- _context4.t0 = _context4["catch"](26);
2075
- case 33:
2076
- return _context4.finish(23);
2077
- case 34:
1161
+ _context4.next = 9;
1162
+ return this.kv.set(key, updatedThread);
1163
+ case 9:
1164
+ return _context4.abrupt("return", this.parseThread(updatedThread));
1165
+ case 10:
2078
1166
  case "end":
2079
1167
  return _context4.stop();
2080
1168
  }
2081
- }, _callee4, this, [[3,, 23, 34], [26, 31]]);
1169
+ }, _callee4, this);
2082
1170
  }));
2083
- function withLock(_x3, _x4) {
2084
- return _withLock.apply(this, arguments);
1171
+ function updateThread(_x4, _x5, _x6) {
1172
+ return _updateThread.apply(this, arguments);
2085
1173
  }
2086
- return withLock;
2087
- }() // Add cleanup method
2088
- ;
2089
- _proto.cleanup =
2090
- /*#__PURE__*/
2091
- function () {
2092
- var _cleanup = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee5() {
2093
- var _iterator, _step, timeout;
1174
+ return updateThread;
1175
+ }();
1176
+ _proto.deleteThread = /*#__PURE__*/function () {
1177
+ var _deleteThread = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee5(id) {
2094
1178
  return _regeneratorRuntime().wrap(function _callee5$(_context5) {
2095
1179
  while (1) switch (_context5.prev = _context5.next) {
2096
1180
  case 0:
2097
- // Clear all timeouts
2098
- for (_iterator = _createForOfIteratorHelperLoose(this.lockTimeouts.values()); !(_step = _iterator()).done;) {
2099
- timeout = _step.value;
2100
- clearTimeout(timeout);
2101
- }
2102
- this.lockTimeouts.clear();
1181
+ _context5.next = 2;
1182
+ return this.kv.del(this.getThreadKey(id));
2103
1183
  case 2:
1184
+ _context5.next = 4;
1185
+ return this.kv.del(this.getMessagesKey(id));
1186
+ case 4:
2104
1187
  case "end":
2105
1188
  return _context5.stop();
2106
1189
  }
2107
1190
  }, _callee5, this);
2108
1191
  }));
2109
- function cleanup() {
2110
- return _cleanup.apply(this, arguments);
1192
+ function deleteThread(_x7) {
1193
+ return _deleteThread.apply(this, arguments);
1194
+ }
1195
+ return deleteThread;
1196
+ }()
1197
+ /**
1198
+ * Tool Cache
1199
+ */
1200
+ ;
1201
+ _proto.validateToolCallArgs =
1202
+ /*#__PURE__*/
1203
+ function () {
1204
+ var _validateToolCallArgs = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee6(_ref4) {
1205
+ var hashedArgs, cacheKey, cached;
1206
+ return _regeneratorRuntime().wrap(function _callee6$(_context6) {
1207
+ while (1) switch (_context6.prev = _context6.next) {
1208
+ case 0:
1209
+ hashedArgs = _ref4.hashedArgs;
1210
+ cacheKey = this.getToolCacheKey(hashedArgs);
1211
+ _context6.next = 4;
1212
+ return this.kv.get(cacheKey);
1213
+ case 4:
1214
+ cached = _context6.sent;
1215
+ return _context6.abrupt("return", !!cached && new Date(cached.expireAt) > new Date());
1216
+ case 6:
1217
+ case "end":
1218
+ return _context6.stop();
1219
+ }
1220
+ }, _callee6, this);
1221
+ }));
1222
+ function validateToolCallArgs(_x8) {
1223
+ return _validateToolCallArgs.apply(this, arguments);
2111
1224
  }
2112
- return cleanup;
1225
+ return validateToolCallArgs;
2113
1226
  }();
2114
- _proto.saveMessages = /*#__PURE__*/function () {
2115
- var _saveMessages = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee7(messages) {
2116
- var _this3 = this;
2117
- var messagesByThread, _loop, _i, _Object$entries;
2118
- return _regeneratorRuntime().wrap(function _callee7$(_context8) {
2119
- while (1) switch (_context8.prev = _context8.next) {
1227
+ _proto.getToolResult = /*#__PURE__*/function () {
1228
+ var _getToolResult = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee7(_ref5) {
1229
+ var threadId, toolArgs, toolName, hashedToolArgs, cacheKey, cached;
1230
+ return _regeneratorRuntime().wrap(function _callee7$(_context7) {
1231
+ while (1) switch (_context7.prev = _context7.next) {
2120
1232
  case 0:
2121
- if (messages.length) {
2122
- _context8.next = 2;
2123
- break;
2124
- }
2125
- return _context8.abrupt("return", []);
2126
- case 2:
2127
- messagesByThread = messages.reduce(function (acc, message) {
2128
- var key = "" + _this3.messagePrefix + message.threadId;
2129
- if (!acc[key]) {
2130
- acc[key] = [];
2131
- }
2132
- acc[key].push(_extends({}, message, {
2133
- createdAt: new Date(message.createdAt)
2134
- }));
2135
- return acc;
2136
- }, {});
2137
- _loop = /*#__PURE__*/_regeneratorRuntime().mark(function _loop() {
2138
- var _Object$entries$_i, key, threadMessages;
2139
- return _regeneratorRuntime().wrap(function _loop$(_context7) {
2140
- while (1) switch (_context7.prev = _context7.next) {
2141
- case 0:
2142
- _Object$entries$_i = _Object$entries[_i], key = _Object$entries$_i[0], threadMessages = _Object$entries$_i[1];
2143
- _context7.next = 3;
2144
- return _this3.withLock(key, /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee6() {
2145
- var _threadMessages$;
2146
- var existingMessages, messageMap, updatedMessages, _threadMessages$2, thread;
2147
- return _regeneratorRuntime().wrap(function _callee6$(_context6) {
2148
- while (1) switch (_context6.prev = _context6.next) {
2149
- case 0:
2150
- _context6.next = 2;
2151
- return _this3.redis.get(key);
2152
- case 2:
2153
- _context6.t0 = _context6.sent;
2154
- if (_context6.t0) {
2155
- _context6.next = 5;
2156
- break;
2157
- }
2158
- _context6.t0 = [];
2159
- case 5:
2160
- existingMessages = _context6.t0;
2161
- messageMap = new Map(); // Process existing messages
2162
- existingMessages.forEach(function (msg) {
2163
- messageMap.set(msg.id, _extends({}, msg, {
2164
- createdAt: new Date(msg.createdAt)
2165
- }));
2166
- });
2167
- // Add new messages
2168
- threadMessages.forEach(function (msg) {
2169
- messageMap.set(msg.id, msg);
2170
- });
2171
- updatedMessages = Array.from(messageMap.values());
2172
- updatedMessages.sort(function (a, b) {
2173
- var timeCompare = a.createdAt.getTime() - b.createdAt.getTime();
2174
- return timeCompare === 0 ? a.id.localeCompare(b.id) : timeCompare;
2175
- });
2176
- _context6.next = 13;
2177
- return _this3.redis.set(key, updatedMessages);
2178
- case 13:
2179
- if (!(threadMessages != null && (_threadMessages$ = threadMessages[0]) != null && _threadMessages$.threadId)) {
2180
- _context6.next = 21;
2181
- break;
2182
- }
2183
- _context6.next = 16;
2184
- return _this3.getThreadById(threadMessages == null || (_threadMessages$2 = threadMessages[0]) == null ? void 0 : _threadMessages$2.threadId);
2185
- case 16:
2186
- thread = _context6.sent;
2187
- if (!thread) {
2188
- _context6.next = 21;
2189
- break;
2190
- }
2191
- thread.updatedAt = new Date();
2192
- _context6.next = 21;
2193
- return _this3.redis.set("" + _this3.threadPrefix + thread.id, thread);
2194
- case 21:
2195
- case "end":
2196
- return _context6.stop();
2197
- }
2198
- }, _callee6);
2199
- })));
2200
- case 3:
2201
- case "end":
2202
- return _context7.stop();
2203
- }
2204
- }, _loop);
2205
- });
2206
- _i = 0, _Object$entries = Object.entries(messagesByThread);
1233
+ threadId = _ref5.threadId, toolArgs = _ref5.toolArgs, toolName = _ref5.toolName;
1234
+ hashedToolArgs = crypto.createHash('sha256').update(JSON.stringify({
1235
+ args: toolArgs,
1236
+ threadId: threadId,
1237
+ toolName: toolName
1238
+ })).digest('hex');
1239
+ cacheKey = this.getToolCacheKey(hashedToolArgs);
1240
+ _context7.next = 5;
1241
+ return this.kv.get(cacheKey);
2207
1242
  case 5:
2208
- if (!(_i < _Object$entries.length)) {
2209
- _context8.next = 10;
1243
+ cached = _context7.sent;
1244
+ if (!(cached && new Date(cached.expireAt) > new Date())) {
1245
+ _context7.next = 8;
2210
1246
  break;
2211
1247
  }
2212
- return _context8.delegateYield(_loop(), "t0", 7);
2213
- case 7:
2214
- _i++;
2215
- _context8.next = 5;
2216
- break;
2217
- case 10:
2218
- return _context8.abrupt("return", messages);
2219
- case 11:
1248
+ return _context7.abrupt("return", cached.result || null);
1249
+ case 8:
1250
+ return _context7.abrupt("return", null);
1251
+ case 9:
2220
1252
  case "end":
2221
- return _context8.stop();
1253
+ return _context7.stop();
2222
1254
  }
2223
- }, _callee7);
1255
+ }, _callee7, this);
2224
1256
  }));
2225
- function saveMessages(_x5) {
2226
- return _saveMessages.apply(this, arguments);
1257
+ function getToolResult(_x9) {
1258
+ return _getToolResult.apply(this, arguments);
2227
1259
  }
2228
- return saveMessages;
1260
+ return getToolResult;
2229
1261
  }();
2230
- _proto.addMessage = /*#__PURE__*/function () {
2231
- var _addMessage = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee8(threadId, content, role) {
2232
- var message;
2233
- return _regeneratorRuntime().wrap(function _callee8$(_context9) {
2234
- while (1) switch (_context9.prev = _context9.next) {
1262
+ _proto.getContextWindow = /*#__PURE__*/function () {
1263
+ var _getContextWindow = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee8(_ref6) {
1264
+ var threadId, startDate, endDate, _ref6$format, format, messagesKey, messages, filteredMessages, totalTokens, messagesWithinTokenLimit, _iterator, _step, _message$content$, message, content, tokens;
1265
+ return _regeneratorRuntime().wrap(function _callee8$(_context8) {
1266
+ while (1) switch (_context8.prev = _context8.next) {
2235
1267
  case 0:
2236
- message = {
2237
- id: this.generateId(),
2238
- content: content,
2239
- role: role,
2240
- createdAt: new Date(),
2241
- threadId: threadId
2242
- };
2243
- _context9.next = 3;
2244
- return this.saveMessages([message]);
2245
- case 3:
2246
- return _context9.abrupt("return", message);
1268
+ threadId = _ref6.threadId, startDate = _ref6.startDate, endDate = _ref6.endDate, _ref6$format = _ref6.format, format = _ref6$format === void 0 ? 'raw' : _ref6$format;
1269
+ messagesKey = this.getMessagesKey(threadId);
1270
+ _context8.next = 4;
1271
+ return this.kv.lrange(messagesKey, 0, -1);
2247
1272
  case 4:
1273
+ messages = _context8.sent;
1274
+ filteredMessages = messages.filter(function (msg) {
1275
+ return msg.type === 'text';
1276
+ });
1277
+ if (startDate) {
1278
+ filteredMessages = filteredMessages.filter(function (msg) {
1279
+ return new Date(msg.createdAt) >= startDate;
1280
+ });
1281
+ }
1282
+ if (endDate) {
1283
+ filteredMessages = filteredMessages.filter(function (msg) {
1284
+ return new Date(msg.createdAt) <= endDate;
1285
+ });
1286
+ }
1287
+ if (!this.MAX_CONTEXT_TOKENS) {
1288
+ _context8.next = 24;
1289
+ break;
1290
+ }
1291
+ totalTokens = 0;
1292
+ messagesWithinTokenLimit = []; // Process messages from newest to oldest
1293
+ _iterator = _createForOfIteratorHelperLoose(filteredMessages.reverse());
1294
+ case 12:
1295
+ if ((_step = _iterator()).done) {
1296
+ _context8.next = 22;
1297
+ break;
1298
+ }
1299
+ message = _step.value;
1300
+ content = message.role === 'assistant' ? ((_message$content$ = message.content[0]) == null ? void 0 : _message$content$.text) || '' : message.content; // Use a more aggressive token estimation
1301
+ // Roughly estimate 1 token per 4 characters
1302
+ tokens = Math.ceil(content.length / 4); // Check if adding this message would exceed the token limit
1303
+ if (!(totalTokens + tokens > this.MAX_CONTEXT_TOKENS)) {
1304
+ _context8.next = 18;
1305
+ break;
1306
+ }
1307
+ return _context8.abrupt("break", 22);
1308
+ case 18:
1309
+ totalTokens += tokens;
1310
+ messagesWithinTokenLimit.unshift(_extends({}, message, {
1311
+ tokens: tokens
1312
+ }));
1313
+ case 20:
1314
+ _context8.next = 12;
1315
+ break;
1316
+ case 22:
1317
+ console.log('Format:', format);
1318
+ // Return messages in chronological order
1319
+ return _context8.abrupt("return", this.parseMessages(messagesWithinTokenLimit));
1320
+ case 24:
1321
+ return _context8.abrupt("return", this.parseMessages(filteredMessages));
1322
+ case 25:
2248
1323
  case "end":
2249
- return _context9.stop();
1324
+ return _context8.stop();
2250
1325
  }
2251
1326
  }, _callee8, this);
2252
1327
  }));
2253
- function addMessage(_x6, _x7, _x8) {
2254
- return _addMessage.apply(this, arguments);
1328
+ function getContextWindow(_x10) {
1329
+ return _getContextWindow.apply(this, arguments);
2255
1330
  }
2256
- return addMessage;
2257
- }();
2258
- _proto.getMessages = /*#__PURE__*/function () {
2259
- var _getMessages = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee9(threadId) {
2260
- var messages;
2261
- return _regeneratorRuntime().wrap(function _callee9$(_context10) {
2262
- while (1) switch (_context10.prev = _context10.next) {
1331
+ return getContextWindow;
1332
+ }()
1333
+ /**
1334
+ * Messages
1335
+ */
1336
+ ;
1337
+ _proto.getMessages =
1338
+ /*#__PURE__*/
1339
+ function () {
1340
+ var _getMessages = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee9(_ref7) {
1341
+ var threadId, messagesKey, messages, parsedMessages, uiMessages;
1342
+ return _regeneratorRuntime().wrap(function _callee9$(_context9) {
1343
+ while (1) switch (_context9.prev = _context9.next) {
2263
1344
  case 0:
2264
- _context10.next = 2;
2265
- return this.redis.get("" + this.messagePrefix + threadId);
2266
- case 2:
2267
- _context10.t0 = _context10.sent;
2268
- if (_context10.t0) {
2269
- _context10.next = 5;
2270
- break;
2271
- }
2272
- _context10.t0 = [];
2273
- case 5:
2274
- messages = _context10.t0;
2275
- return _context10.abrupt("return", messages.map(function (msg) {
2276
- return _extends({}, msg, {
2277
- createdAt: new Date(msg.createdAt)
2278
- });
2279
- }));
2280
- case 7:
1345
+ threadId = _ref7.threadId;
1346
+ messagesKey = this.getMessagesKey(threadId);
1347
+ _context9.next = 4;
1348
+ return this.kv.lrange(messagesKey, 0, -1);
1349
+ case 4:
1350
+ messages = _context9.sent;
1351
+ parsedMessages = this.parseMessages(messages);
1352
+ uiMessages = this.convertToUIMessages(parsedMessages);
1353
+ return _context9.abrupt("return", {
1354
+ messages: parsedMessages,
1355
+ uiMessages: uiMessages
1356
+ });
1357
+ case 8:
2281
1358
  case "end":
2282
- return _context10.stop();
1359
+ return _context9.stop();
2283
1360
  }
2284
1361
  }, _callee9, this);
2285
1362
  }));
2286
- function getMessages(_x9) {
1363
+ function getMessages(_x11) {
2287
1364
  return _getMessages.apply(this, arguments);
2288
1365
  }
2289
1366
  return getMessages;
2290
1367
  }();
2291
- _proto.getAllThreadIds = /*#__PURE__*/function () {
2292
- var _getAllThreadIds = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee10() {
1368
+ _proto.saveMessages = /*#__PURE__*/function () {
1369
+ var _saveMessages = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee10(_ref8) {
1370
+ var _this3 = this;
1371
+ var messages, processedMessages, _loop, _iterator2, _step2;
2293
1372
  return _regeneratorRuntime().wrap(function _callee10$(_context11) {
2294
1373
  while (1) switch (_context11.prev = _context11.next) {
2295
1374
  case 0:
2296
- return _context11.abrupt("return", this.redis.smembers('threads'));
2297
- case 1:
1375
+ messages = _ref8.messages;
1376
+ processedMessages = [];
1377
+ _loop = /*#__PURE__*/_regeneratorRuntime().mark(function _loop() {
1378
+ var message, threadId, toolCallArgs, toolNames, createdAt, messagesKey, processedMessage, _message$content$2, content, hashedToolCallArgs, validArgExists, _iterator3, _step3, hashedArg, isValid, expireAt, _iterator4, _step4, _hashedArg, cacheKey;
1379
+ return _regeneratorRuntime().wrap(function _loop$(_context10) {
1380
+ while (1) switch (_context10.prev = _context10.next) {
1381
+ case 0:
1382
+ message = _step2.value;
1383
+ threadId = message.threadId, toolCallArgs = message.toolCallArgs, toolNames = message.toolNames, createdAt = message.createdAt;
1384
+ messagesKey = _this3.getMessagesKey(threadId);
1385
+ processedMessage = _extends({}, message);
1386
+ if (message.type === 'text') {
1387
+ content = message.role === 'assistant' ? ((_message$content$2 = message.content[0]) == null ? void 0 : _message$content$2.text) || '' : message.content;
1388
+ processedMessage.tokens = _this3.estimateTokens(content);
1389
+ }
1390
+ if (!(toolCallArgs != null && toolCallArgs.length)) {
1391
+ _context10.next = 28;
1392
+ break;
1393
+ }
1394
+ hashedToolCallArgs = toolCallArgs.map(function (args, index) {
1395
+ return crypto.createHash('sha256').update(JSON.stringify({
1396
+ args: args,
1397
+ threadId: threadId,
1398
+ toolName: toolNames == null ? void 0 : toolNames[index]
1399
+ })).digest('hex');
1400
+ });
1401
+ validArgExists = true;
1402
+ _iterator3 = _createForOfIteratorHelperLoose(hashedToolCallArgs);
1403
+ case 9:
1404
+ if ((_step3 = _iterator3()).done) {
1405
+ _context10.next = 19;
1406
+ break;
1407
+ }
1408
+ hashedArg = _step3.value;
1409
+ _context10.next = 13;
1410
+ return _this3.validateToolCallArgs({
1411
+ hashedArgs: hashedArg
1412
+ });
1413
+ case 13:
1414
+ isValid = _context10.sent;
1415
+ if (isValid) {
1416
+ _context10.next = 17;
1417
+ break;
1418
+ }
1419
+ validArgExists = false;
1420
+ return _context10.abrupt("break", 19);
1421
+ case 17:
1422
+ _context10.next = 9;
1423
+ break;
1424
+ case 19:
1425
+ expireAt = validArgExists ? createdAt : new Date(createdAt.getTime() + 5 * 60 * 1000); // 5 minutes
1426
+ _iterator4 = _createForOfIteratorHelperLoose(hashedToolCallArgs);
1427
+ case 21:
1428
+ if ((_step4 = _iterator4()).done) {
1429
+ _context10.next = 28;
1430
+ break;
1431
+ }
1432
+ _hashedArg = _step4.value;
1433
+ cacheKey = _this3.getToolCacheKey(_hashedArg);
1434
+ _context10.next = 26;
1435
+ return _this3.kv.set(cacheKey, {
1436
+ expireAt: expireAt.toISOString()
1437
+ });
1438
+ case 26:
1439
+ _context10.next = 21;
1440
+ break;
1441
+ case 28:
1442
+ _context10.next = 30;
1443
+ return _this3.kv.rpush(messagesKey, processedMessage);
1444
+ case 30:
1445
+ processedMessages.push(processedMessage);
1446
+ case 31:
1447
+ case "end":
1448
+ return _context10.stop();
1449
+ }
1450
+ }, _loop);
1451
+ });
1452
+ _iterator2 = _createForOfIteratorHelperLoose(messages);
1453
+ case 4:
1454
+ if ((_step2 = _iterator2()).done) {
1455
+ _context11.next = 8;
1456
+ break;
1457
+ }
1458
+ return _context11.delegateYield(_loop(), "t0", 6);
1459
+ case 6:
1460
+ _context11.next = 4;
1461
+ break;
1462
+ case 8:
1463
+ return _context11.abrupt("return", processedMessages);
1464
+ case 9:
2298
1465
  case "end":
2299
1466
  return _context11.stop();
2300
1467
  }
2301
- }, _callee10, this);
1468
+ }, _callee10);
2302
1469
  }));
2303
- function getAllThreadIds() {
2304
- return _getAllThreadIds.apply(this, arguments);
1470
+ function saveMessages(_x12) {
1471
+ return _saveMessages.apply(this, arguments);
2305
1472
  }
2306
- return getAllThreadIds;
1473
+ return saveMessages;
2307
1474
  }();
2308
- _proto.deleteThread = /*#__PURE__*/function () {
2309
- var _deleteThread = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee11(threadId) {
2310
- var pipeline;
1475
+ _proto.deleteMessage = /*#__PURE__*/function () {
1476
+ var _deleteMessage = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee11(id) {
1477
+ var pattern, keys, _iterator5, _step5, key, messages, filteredMessages, _this$kv;
2311
1478
  return _regeneratorRuntime().wrap(function _callee11$(_context12) {
2312
1479
  while (1) switch (_context12.prev = _context12.next) {
2313
1480
  case 0:
2314
- pipeline = this.redis.pipeline();
2315
- pipeline.del("" + this.threadPrefix + threadId);
2316
- pipeline.del("" + this.messagePrefix + threadId);
2317
- pipeline.srem('threads', threadId);
2318
- _context12.next = 6;
2319
- return pipeline.exec();
2320
- case 6:
1481
+ pattern = this.prefix + ":messages:*";
1482
+ _context12.next = 3;
1483
+ return this.kv.keys(pattern);
1484
+ case 3:
1485
+ keys = _context12.sent;
1486
+ _iterator5 = _createForOfIteratorHelperLoose(keys);
1487
+ case 5:
1488
+ if ((_step5 = _iterator5()).done) {
1489
+ _context12.next = 19;
1490
+ break;
1491
+ }
1492
+ key = _step5.value;
1493
+ _context12.next = 9;
1494
+ return this.kv.lrange(key, 0, -1);
1495
+ case 9:
1496
+ messages = _context12.sent;
1497
+ filteredMessages = messages.filter(function (msg) {
1498
+ return msg.id !== id;
1499
+ });
1500
+ if (!(messages.length !== filteredMessages.length)) {
1501
+ _context12.next = 17;
1502
+ break;
1503
+ }
1504
+ _context12.next = 14;
1505
+ return this.kv.del(key);
1506
+ case 14:
1507
+ if (!(filteredMessages.length > 0)) {
1508
+ _context12.next = 17;
1509
+ break;
1510
+ }
1511
+ _context12.next = 17;
1512
+ return (_this$kv = this.kv).rpush.apply(_this$kv, [key].concat(filteredMessages));
1513
+ case 17:
1514
+ _context12.next = 5;
1515
+ break;
1516
+ case 19:
2321
1517
  case "end":
2322
1518
  return _context12.stop();
2323
1519
  }
2324
1520
  }, _callee11, this);
2325
1521
  }));
2326
- function deleteThread(_x10) {
2327
- return _deleteThread.apply(this, arguments);
1522
+ function deleteMessage(_x13) {
1523
+ return _deleteMessage.apply(this, arguments);
2328
1524
  }
2329
- return deleteThread;
2330
- }();
2331
- _proto.getThreads = /*#__PURE__*/function () {
2332
- var _getThreads = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee12(threadIds) {
2333
- var _this4 = this;
2334
- var threads;
1525
+ return deleteMessage;
1526
+ }()
1527
+ /**
1528
+ * Cleanup
1529
+ */
1530
+ ;
1531
+ _proto.drop =
1532
+ /*#__PURE__*/
1533
+ function () {
1534
+ var _drop = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee12() {
1535
+ var pattern, keys, _this$kv2;
2335
1536
  return _regeneratorRuntime().wrap(function _callee12$(_context13) {
2336
1537
  while (1) switch (_context13.prev = _context13.next) {
2337
1538
  case 0:
2338
- _context13.next = 2;
2339
- return Promise.all(threadIds.map(function (id) {
2340
- return _this4.getThreadById(id);
2341
- }));
2342
- case 2:
2343
- threads = _context13.sent;
2344
- return _context13.abrupt("return", threads.filter(function (t) {
2345
- return t !== null;
2346
- }));
2347
- case 4:
1539
+ pattern = this.prefix + ":*";
1540
+ _context13.next = 3;
1541
+ return this.kv.keys(pattern);
1542
+ case 3:
1543
+ keys = _context13.sent;
1544
+ if (!(keys.length > 0)) {
1545
+ _context13.next = 7;
1546
+ break;
1547
+ }
1548
+ _context13.next = 7;
1549
+ return (_this$kv2 = this.kv).del.apply(_this$kv2, keys);
1550
+ case 7:
2348
1551
  case "end":
2349
1552
  return _context13.stop();
2350
1553
  }
2351
- }, _callee12);
1554
+ }, _callee12, this);
2352
1555
  }));
2353
- function getThreads(_x11) {
2354
- return _getThreads.apply(this, arguments);
1556
+ function drop() {
1557
+ return _drop.apply(this, arguments);
2355
1558
  }
2356
- return getThreads;
1559
+ return drop;
2357
1560
  }();
2358
- _proto.generateId = function generateId() {
2359
- return crypto.randomUUID();
1561
+ _proto.parseThread = function parseThread(thread) {
1562
+ return _extends({}, thread, {
1563
+ createdAt: new Date(thread.createdAt),
1564
+ updatedAt: new Date(thread.updatedAt)
1565
+ });
1566
+ };
1567
+ _proto.parseMessages = function parseMessages(messages) {
1568
+ return messages.map(function (message) {
1569
+ return _extends({}, message, {
1570
+ createdAt: new Date(message.createdAt)
1571
+ });
1572
+ });
2360
1573
  };
2361
- return RedisMemory;
1574
+ return UpstashKVMemory;
2362
1575
  }(core.MastraMemory);
2363
1576
 
2364
- exports.CloudflareKVMemory = CloudflareKVMemory;
2365
- exports.LocalRedisProvider = LocalRedisProvider;
2366
1577
  exports.PgMemory = PgMemory;
2367
- exports.RedisMemory = RedisMemory;
2368
- exports.UpstashProvider = UpstashProvider;
1578
+ exports.UpstashKVMemory = UpstashKVMemory;
2369
1579
  //# sourceMappingURL=memory.cjs.development.js.map