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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,10 +3,8 @@
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
- var redis = require('@upstash/redis');
9
- var redis$1 = require('redis');
10
8
 
11
9
  function _arrayLikeToArray(r, a) {
12
10
  (null == a || a > r.length) && (a = r.length);
@@ -381,1989 +379,726 @@ function _unsupportedIterableToArray(r, a) {
381
379
  }
382
380
  }
383
381
 
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) {
658
- var _this;
659
- _this = _MastraMemory.call(this) || this;
660
- _this.kv = void 0;
661
- _this.threadPrefix = 'thread:';
662
- _this.messagePrefix = 'messages:';
663
- _this.kv = new CloudflareKVProvider(namespace);
664
- return _this;
665
- }
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;
671
- return _regeneratorRuntime().wrap(function _callee$(_context) {
672
- while (1) switch (_context.prev = _context.next) {
673
- 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
- })));
836
- 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
- _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
- 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
382
+ var Pool = pg.Pool;
383
+ var PgMemory = /*#__PURE__*/function (_MastraMemory) {
384
+ function PgMemory(config) {
385
+ var _this;
386
+ _this = _MastraMemory.call(this) || this;
387
+ _this.pool = void 0;
388
+ _this.MAX_CONTEXT_TOKENS = void 0;
389
+ _this.pool = new Pool({
390
+ connectionString: config.connectionString
1537
391
  });
392
+ _this.MAX_CONTEXT_TOKENS = config.maxTokens;
393
+ return _this;
1538
394
  }
1539
- var _proto = UpstashProvider.prototype;
1540
- _proto.get = /*#__PURE__*/function () {
1541
- var _get = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(key) {
1542
- var data;
395
+ _inheritsLoose(PgMemory, _MastraMemory);
396
+ var _proto = PgMemory.prototype;
397
+ _proto.drop = /*#__PURE__*/function () {
398
+ var _drop = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
399
+ var client;
1543
400
  return _regeneratorRuntime().wrap(function _callee$(_context) {
1544
401
  while (1) switch (_context.prev = _context.next) {
1545
402
  case 0:
1546
403
  _context.next = 2;
1547
- return this.client.get(key);
404
+ return this.pool.connect();
1548
405
  case 2:
1549
- data = _context.sent;
1550
- return _context.abrupt("return", deserializeData(data));
1551
- case 4:
406
+ client = _context.sent;
407
+ _context.next = 5;
408
+ return client.query('DELETE FROM mastra_messages');
409
+ case 5:
410
+ _context.next = 7;
411
+ return client.query('DELETE FROM mastra_threads');
412
+ case 7:
413
+ client.release();
414
+ _context.next = 10;
415
+ return this.pool.end();
416
+ case 10:
1552
417
  case "end":
1553
418
  return _context.stop();
1554
419
  }
1555
420
  }, _callee, this);
1556
421
  }));
1557
- function get(_x) {
1558
- return _get.apply(this, arguments);
422
+ function drop() {
423
+ return _drop.apply(this, arguments);
1559
424
  }
1560
- return get;
1561
- }();
1562
- _proto.set = /*#__PURE__*/function () {
1563
- var _set = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(key, value) {
425
+ return drop;
426
+ }() // Simplified token estimation
427
+ ;
428
+ _proto.estimateTokens = function estimateTokens(text) {
429
+ return Math.ceil(text.split(' ').length * 1.3);
430
+ };
431
+ _proto.processMessages = function processMessages(messages) {
432
+ return messages.map(function (mssg) {
433
+ return _extends({}, mssg, {
434
+ content: typeof mssg.content === 'string' ? JSON.parse(mssg.content) : mssg.content
435
+ });
436
+ });
437
+ };
438
+ _proto.convertToUIMessages = function convertToUIMessages(messages) {
439
+ function addToolMessageToChat(_ref) {
440
+ var toolMessage = _ref.toolMessage,
441
+ messages = _ref.messages,
442
+ toolResultContents = _ref.toolResultContents;
443
+ var chatMessages = messages.map(function (message) {
444
+ if (message.toolInvocations) {
445
+ return _extends({}, message, {
446
+ toolInvocations: message.toolInvocations.map(function (toolInvocation) {
447
+ var toolResult = toolMessage.content.find(function (tool) {
448
+ return tool.toolCallId === toolInvocation.toolCallId;
449
+ });
450
+ if (toolResult) {
451
+ return _extends({}, toolInvocation, {
452
+ state: 'result',
453
+ result: toolResult.result
454
+ });
455
+ }
456
+ return toolInvocation;
457
+ })
458
+ });
459
+ }
460
+ return message;
461
+ });
462
+ var resultContents = [].concat(toolResultContents, toolMessage.content);
463
+ return {
464
+ chatMessages: chatMessages,
465
+ toolResultContents: resultContents
466
+ };
467
+ }
468
+ var _messages$reduce = messages.reduce(function (obj, message) {
469
+ if (message.role === 'tool') {
470
+ return addToolMessageToChat({
471
+ toolMessage: message,
472
+ messages: obj.chatMessages,
473
+ toolResultContents: obj.toolResultContents
474
+ });
475
+ }
476
+ var textContent = '';
477
+ var toolInvocations = [];
478
+ if (typeof message.content === 'string') {
479
+ textContent = message.content;
480
+ } else if (Array.isArray(message.content)) {
481
+ var _loop = function _loop() {
482
+ var content = _step.value;
483
+ if (content.type === 'text') {
484
+ textContent += content.text;
485
+ } else if (content.type === 'tool-call') {
486
+ var toolResult = obj.toolResultContents.find(function (tool) {
487
+ return tool.toolCallId === content.toolCallId;
488
+ });
489
+ toolInvocations.push({
490
+ state: toolResult ? 'result' : 'call',
491
+ toolCallId: content.toolCallId,
492
+ toolName: content.toolName,
493
+ args: content.args,
494
+ result: toolResult == null ? void 0 : toolResult.result
495
+ });
496
+ }
497
+ };
498
+ for (var _iterator = _createForOfIteratorHelperLoose(message.content), _step; !(_step = _iterator()).done;) {
499
+ _loop();
500
+ }
501
+ }
502
+ obj.chatMessages.push({
503
+ id: message.id,
504
+ role: message.role,
505
+ content: textContent,
506
+ toolInvocations: toolInvocations
507
+ });
508
+ return obj;
509
+ }, {
510
+ chatMessages: [],
511
+ toolResultContents: []
512
+ }),
513
+ chatMessages = _messages$reduce.chatMessages;
514
+ return chatMessages;
515
+ };
516
+ _proto.ensureTablesExist = /*#__PURE__*/function () {
517
+ var _ensureTablesExist = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
518
+ var client, _threadsResult$rows, _messagesResult$rows, threadsResult, messagesResult;
1564
519
  return _regeneratorRuntime().wrap(function _callee2$(_context2) {
1565
520
  while (1) switch (_context2.prev = _context2.next) {
1566
521
  case 0:
1567
- return _context2.abrupt("return", this.client.set(key, serializeData(value)));
1568
- case 1:
522
+ _context2.next = 2;
523
+ return this.pool.connect();
524
+ case 2:
525
+ client = _context2.sent;
526
+ _context2.prev = 3;
527
+ _context2.next = 6;
528
+ return client.query("\n SELECT EXISTS (\n SELECT 1\n FROM information_schema.tables\n WHERE table_name = 'mastra_threads'\n );\n ");
529
+ case 6:
530
+ threadsResult = _context2.sent;
531
+ if (threadsResult != null && (_threadsResult$rows = threadsResult.rows) != null && (_threadsResult$rows = _threadsResult$rows[0]) != null && _threadsResult$rows.exists) {
532
+ _context2.next = 10;
533
+ break;
534
+ }
535
+ _context2.next = 10;
536
+ 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 ");
537
+ case 10:
538
+ _context2.next = 12;
539
+ return client.query("\n SELECT EXISTS (\n SELECT 1\n FROM information_schema.tables\n WHERE table_name = 'mastra_messages'\n );\n ");
540
+ case 12:
541
+ messagesResult = _context2.sent;
542
+ if (messagesResult != null && (_messagesResult$rows = messagesResult.rows) != null && (_messagesResult$rows = _messagesResult$rows[0]) != null && _messagesResult$rows.exists) {
543
+ _context2.next = 16;
544
+ break;
545
+ }
546
+ _context2.next = 16;
547
+ 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 ");
548
+ case 16:
549
+ _context2.prev = 16;
550
+ client.release();
551
+ return _context2.finish(16);
552
+ case 19:
1569
553
  case "end":
1570
554
  return _context2.stop();
1571
555
  }
1572
- }, _callee2, this);
556
+ }, _callee2, this, [[3,, 16, 19]]);
1573
557
  }));
1574
- function set(_x2, _x3) {
1575
- return _set.apply(this, arguments);
558
+ function ensureTablesExist() {
559
+ return _ensureTablesExist.apply(this, arguments);
1576
560
  }
1577
- return set;
561
+ return ensureTablesExist;
1578
562
  }();
1579
- _proto.del = /*#__PURE__*/function () {
1580
- var _del = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3(key) {
563
+ _proto.updateThread = /*#__PURE__*/function () {
564
+ var _updateThread = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3(id, title, metadata) {
565
+ var client, _result$rows, result;
1581
566
  return _regeneratorRuntime().wrap(function _callee3$(_context3) {
1582
567
  while (1) switch (_context3.prev = _context3.next) {
1583
568
  case 0:
1584
- return _context3.abrupt("return", this.client.del(key));
1585
- case 1:
569
+ _context3.next = 2;
570
+ return this.pool.connect();
571
+ case 2:
572
+ client = _context3.sent;
573
+ _context3.prev = 3;
574
+ _context3.next = 6;
575
+ 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]);
576
+ case 6:
577
+ result = _context3.sent;
578
+ return _context3.abrupt("return", result == null || (_result$rows = result.rows) == null ? void 0 : _result$rows[0]);
579
+ case 8:
580
+ _context3.prev = 8;
581
+ client.release();
582
+ return _context3.finish(8);
583
+ case 11:
1586
584
  case "end":
1587
585
  return _context3.stop();
1588
586
  }
1589
- }, _callee3, this);
587
+ }, _callee3, this, [[3,, 8, 11]]);
1590
588
  }));
1591
- function del(_x4) {
1592
- return _del.apply(this, arguments);
589
+ function updateThread(_x, _x2, _x3) {
590
+ return _updateThread.apply(this, arguments);
1593
591
  }
1594
- return del;
592
+ return updateThread;
1595
593
  }();
1596
- _proto.sadd = /*#__PURE__*/function () {
1597
- var _sadd = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee4(key, value) {
594
+ _proto.deleteThread = /*#__PURE__*/function () {
595
+ var _deleteThread = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee4(id) {
596
+ var client;
1598
597
  return _regeneratorRuntime().wrap(function _callee4$(_context4) {
1599
598
  while (1) switch (_context4.prev = _context4.next) {
1600
599
  case 0:
1601
- return _context4.abrupt("return", this.client.sadd(key, value));
1602
- case 1:
600
+ _context4.next = 2;
601
+ return this.pool.connect();
602
+ case 2:
603
+ client = _context4.sent;
604
+ _context4.prev = 3;
605
+ _context4.next = 6;
606
+ return client.query("\n DELETE FROM mastra_messages\n WHERE thread_id = $1\n ", [id]);
607
+ case 6:
608
+ _context4.next = 8;
609
+ return client.query("\n DELETE FROM mastra_threads\n WHERE id = $1\n ", [id]);
610
+ case 8:
611
+ _context4.prev = 8;
612
+ client.release();
613
+ return _context4.finish(8);
614
+ case 11:
1603
615
  case "end":
1604
616
  return _context4.stop();
1605
617
  }
1606
- }, _callee4, this);
618
+ }, _callee4, this, [[3,, 8, 11]]);
1607
619
  }));
1608
- function sadd(_x5, _x6) {
1609
- return _sadd.apply(this, arguments);
620
+ function deleteThread(_x4) {
621
+ return _deleteThread.apply(this, arguments);
1610
622
  }
1611
- return sadd;
623
+ return deleteThread;
1612
624
  }();
1613
- _proto.srem = /*#__PURE__*/function () {
1614
- var _srem = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee5(key, value) {
625
+ _proto.deleteMessage = /*#__PURE__*/function () {
626
+ var _deleteMessage = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee5(id) {
627
+ var client;
1615
628
  return _regeneratorRuntime().wrap(function _callee5$(_context5) {
1616
629
  while (1) switch (_context5.prev = _context5.next) {
1617
630
  case 0:
1618
- return _context5.abrupt("return", this.client.srem(key, value));
1619
- case 1:
1620
- case "end":
1621
- return _context5.stop();
1622
- }
1623
- }, _callee5, this);
1624
- }));
1625
- function srem(_x7, _x8) {
1626
- return _srem.apply(this, arguments);
1627
- }
1628
- return srem;
1629
- }();
1630
- _proto.smembers = /*#__PURE__*/function () {
1631
- var _smembers = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee6(key) {
1632
- return _regeneratorRuntime().wrap(function _callee6$(_context6) {
1633
- while (1) switch (_context6.prev = _context6.next) {
1634
- case 0:
1635
- return _context6.abrupt("return", this.client.smembers(key));
1636
- case 1:
1637
- case "end":
1638
- return _context6.stop();
1639
- }
1640
- }, _callee6, this);
1641
- }));
1642
- function smembers(_x9) {
1643
- return _smembers.apply(this, arguments);
1644
- }
1645
- return smembers;
1646
- }();
1647
- _proto.flushall = /*#__PURE__*/function () {
1648
- var _flushall = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee7() {
1649
- return _regeneratorRuntime().wrap(function _callee7$(_context7) {
1650
- while (1) switch (_context7.prev = _context7.next) {
1651
- case 0:
1652
- return _context7.abrupt("return", this.client.flushall());
1653
- case 1:
1654
- case "end":
1655
- return _context7.stop();
1656
- }
1657
- }, _callee7, this);
1658
- }));
1659
- function flushall() {
1660
- return _flushall.apply(this, arguments);
1661
- }
1662
- return flushall;
1663
- }();
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) {
1744
- case 0:
1745
- _context9.next = 2;
1746
- return this.client.get(key);
631
+ _context5.next = 2;
632
+ return this.pool.connect();
1747
633
  case 2:
1748
- data = _context9.sent;
1749
- return _context9.abrupt("return", data ? deserializeData(JSON.parse(data)) : null);
1750
- case 4:
1751
- case "end":
1752
- return _context9.stop();
1753
- }
1754
- }, _callee9, this);
1755
- }));
1756
- function get(_x10) {
1757
- return _get2.apply(this, arguments);
1758
- }
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) {
1765
- case 0:
1766
- return _context10.abrupt("return", this.client.set(key, JSON.stringify(serializeData(value))));
1767
- case 1:
1768
- case "end":
1769
- return _context10.stop();
1770
- }
1771
- }, _callee10, this);
1772
- }));
1773
- function set(_x11, _x12) {
1774
- return _set2.apply(this, arguments);
1775
- }
1776
- return set;
1777
- }();
1778
- _proto2.del = /*#__PURE__*/function () {
1779
- var _del2 = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee11(key) {
1780
- return _regeneratorRuntime().wrap(function _callee11$(_context11) {
1781
- while (1) switch (_context11.prev = _context11.next) {
1782
- case 0:
1783
- return _context11.abrupt("return", this.client.del(key));
1784
- case 1:
1785
- case "end":
1786
- return _context11.stop();
1787
- }
1788
- }, _callee11, this);
1789
- }));
1790
- function del(_x13) {
1791
- return _del2.apply(this, arguments);
1792
- }
1793
- return del;
1794
- }();
1795
- _proto2.sadd = /*#__PURE__*/function () {
1796
- var _sadd2 = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee12(key, value) {
1797
- return _regeneratorRuntime().wrap(function _callee12$(_context12) {
1798
- while (1) switch (_context12.prev = _context12.next) {
1799
- case 0:
1800
- return _context12.abrupt("return", this.client.sAdd(key, value));
1801
- case 1:
1802
- case "end":
1803
- return _context12.stop();
1804
- }
1805
- }, _callee12, this);
1806
- }));
1807
- function sadd(_x14, _x15) {
1808
- return _sadd2.apply(this, arguments);
1809
- }
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) {
1815
- while (1) switch (_context13.prev = _context13.next) {
1816
- case 0:
1817
- return _context13.abrupt("return", this.client.sRem(key, value));
1818
- case 1:
1819
- case "end":
1820
- return _context13.stop();
1821
- }
1822
- }, _callee13, this);
1823
- }));
1824
- function srem(_x16, _x17) {
1825
- return _srem2.apply(this, arguments);
1826
- }
1827
- return srem;
1828
- }();
1829
- _proto2.smembers = /*#__PURE__*/function () {
1830
- var _smembers2 = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee14(key) {
1831
- return _regeneratorRuntime().wrap(function _callee14$(_context14) {
1832
- while (1) switch (_context14.prev = _context14.next) {
1833
- case 0:
1834
- return _context14.abrupt("return", this.client.sMembers(key));
1835
- case 1:
634
+ client = _context5.sent;
635
+ _context5.prev = 3;
636
+ _context5.next = 6;
637
+ return client.query("\n DELETE FROM mastra_messages\n WHERE id = $1\n ", [id]);
638
+ case 6:
639
+ _context5.prev = 6;
640
+ client.release();
641
+ return _context5.finish(6);
642
+ case 9:
1836
643
  case "end":
1837
- return _context14.stop();
644
+ return _context5.stop();
1838
645
  }
1839
- }, _callee14, this);
646
+ }, _callee5, this, [[3,, 6, 9]]);
1840
647
  }));
1841
- function smembers(_x18) {
1842
- return _smembers2.apply(this, arguments);
648
+ function deleteMessage(_x5) {
649
+ return _deleteMessage.apply(this, arguments);
1843
650
  }
1844
- return smembers;
651
+ return deleteMessage;
1845
652
  }();
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) {
653
+ _proto.getThreadById = /*#__PURE__*/function () {
654
+ var _getThreadById = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee6(_ref2) {
655
+ var threadId, client, result;
656
+ return _regeneratorRuntime().wrap(function _callee6$(_context6) {
657
+ while (1) switch (_context6.prev = _context6.next) {
1850
658
  case 0:
1851
- return _context15.abrupt("return", this.client.flushAll());
1852
- case 1:
659
+ threadId = _ref2.threadId;
660
+ console.log('getThreadById', threadId);
661
+ _context6.next = 4;
662
+ return this.ensureTablesExist();
663
+ case 4:
664
+ _context6.next = 6;
665
+ return this.pool.connect();
666
+ case 6:
667
+ client = _context6.sent;
668
+ _context6.prev = 7;
669
+ _context6.next = 10;
670
+ 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]);
671
+ case 10:
672
+ result = _context6.sent;
673
+ return _context6.abrupt("return", result.rows[0] || null);
674
+ case 12:
675
+ _context6.prev = 12;
676
+ client.release();
677
+ return _context6.finish(12);
678
+ case 15:
1853
679
  case "end":
1854
- return _context15.stop();
680
+ return _context6.stop();
1855
681
  }
1856
- }, _callee15, this);
682
+ }, _callee6, this, [[7,, 12, 15]]);
1857
683
  }));
1858
- function flushall() {
1859
- return _flushall2.apply(this, arguments);
684
+ function getThreadById(_x6) {
685
+ return _getThreadById.apply(this, arguments);
1860
686
  }
1861
- return flushall;
687
+ return getThreadById;
1862
688
  }();
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();
1891
- }
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) {
689
+ _proto.getThreadsByResourceId = /*#__PURE__*/function () {
690
+ var _getThreadsByResourceId = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee7(_ref3) {
691
+ var resourceid, client, result;
692
+ return _regeneratorRuntime().wrap(function _callee7$(_context7) {
693
+ while (1) switch (_context7.prev = _context7.next) {
1906
694
  case 0:
1907
- _context17.next = 2;
1908
- return this.client.quit();
1909
- case 2:
695
+ resourceid = _ref3.resourceid;
696
+ _context7.next = 3;
697
+ return this.ensureTablesExist();
698
+ case 3:
699
+ _context7.next = 5;
700
+ return this.pool.connect();
701
+ case 5:
702
+ client = _context7.sent;
703
+ _context7.prev = 6;
704
+ _context7.next = 9;
705
+ 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]);
706
+ case 9:
707
+ result = _context7.sent;
708
+ return _context7.abrupt("return", result.rows);
709
+ case 11:
710
+ _context7.prev = 11;
711
+ client.release();
712
+ return _context7.finish(11);
713
+ case 14:
1910
714
  case "end":
1911
- return _context17.stop();
715
+ return _context7.stop();
1912
716
  }
1913
- }, _callee17, this);
717
+ }, _callee7, this, [[6,, 11, 14]]);
1914
718
  }));
1915
- function quit() {
1916
- return _quit.apply(this, arguments);
719
+ function getThreadsByResourceId(_x7) {
720
+ return _getThreadsByResourceId.apply(this, arguments);
1917
721
  }
1918
- return quit;
722
+ return getThreadsByResourceId;
1919
723
  }();
1920
- return LocalRedisProvider;
1921
- }();
1922
-
1923
- var RedisMemory = /*#__PURE__*/function (_MastraMemory) {
1924
- function RedisMemory(redis) {
1925
- var _this;
1926
- _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;
1932
- return _this;
1933
- }
1934
- _inheritsLoose(RedisMemory, _MastraMemory);
1935
- var _proto = RedisMemory.prototype;
1936
- _proto.getThreadById = /*#__PURE__*/function () {
1937
- var _getThreadById = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(threadId) {
1938
- var thread;
1939
- return _regeneratorRuntime().wrap(function _callee$(_context) {
1940
- while (1) switch (_context.prev = _context.next) {
724
+ _proto.saveThread = /*#__PURE__*/function () {
725
+ var _saveThread = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee8(_ref4) {
726
+ var thread, client, _result$rows2, id, title, createdAt, updatedAt, resourceid, metadata, result;
727
+ return _regeneratorRuntime().wrap(function _callee8$(_context8) {
728
+ while (1) switch (_context8.prev = _context8.next) {
1941
729
  case 0:
1942
- _context.next = 2;
1943
- return this.redis.get("" + this.threadPrefix + threadId);
1944
- case 2:
1945
- 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);
730
+ thread = _ref4.thread;
731
+ _context8.next = 3;
732
+ return this.ensureTablesExist();
733
+ case 3:
734
+ _context8.next = 5;
735
+ return this.pool.connect();
1951
736
  case 5:
737
+ client = _context8.sent;
738
+ _context8.prev = 6;
739
+ id = thread.id, title = thread.title, createdAt = thread.createdAt, updatedAt = thread.updatedAt, resourceid = thread.resourceid, metadata = thread.metadata;
740
+ _context8.next = 10;
741
+ 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)]);
742
+ case 10:
743
+ result = _context8.sent;
744
+ return _context8.abrupt("return", result == null || (_result$rows2 = result.rows) == null ? void 0 : _result$rows2[0]);
745
+ case 12:
746
+ _context8.prev = 12;
747
+ client.release();
748
+ return _context8.finish(12);
749
+ case 15:
1952
750
  case "end":
1953
- return _context.stop();
751
+ return _context8.stop();
1954
752
  }
1955
- }, _callee, this);
753
+ }, _callee8, this, [[6,, 12, 15]]);
1956
754
  }));
1957
- function getThreadById(_x) {
1958
- return _getThreadById.apply(this, arguments);
755
+ function saveThread(_x8) {
756
+ return _saveThread.apply(this, arguments);
1959
757
  }
1960
- return getThreadById;
758
+ return saveThread;
1961
759
  }();
1962
- _proto.saveThread = /*#__PURE__*/function () {
1963
- var _saveThread = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(thread) {
1964
- return _regeneratorRuntime().wrap(function _callee2$(_context2) {
1965
- while (1) switch (_context2.prev = _context2.next) {
760
+ _proto.checkIfValidArgExists = /*#__PURE__*/function () {
761
+ var _checkIfValidArgExists = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee9(_ref5) {
762
+ var hashedToolCallArgs, client, toolArgsResult;
763
+ return _regeneratorRuntime().wrap(function _callee9$(_context9) {
764
+ while (1) switch (_context9.prev = _context9.next) {
1966
765
  case 0:
1967
- thread.updatedAt = new Date();
1968
- _context2.next = 3;
1969
- return this.redis.set("" + this.threadPrefix + thread.id, thread);
766
+ hashedToolCallArgs = _ref5.hashedToolCallArgs;
767
+ _context9.next = 3;
768
+ return this.ensureTablesExist();
1970
769
  case 3:
1971
- _context2.next = 5;
1972
- return this.redis.sadd('threads', thread.id);
770
+ _context9.next = 5;
771
+ return this.pool.connect();
1973
772
  case 5:
1974
- return _context2.abrupt("return", thread);
1975
- case 6:
773
+ client = _context9.sent;
774
+ _context9.prev = 6;
775
+ _context9.next = 9;
776
+ 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([hashedToolCallArgs]), new Date().toISOString()]);
777
+ case 9:
778
+ toolArgsResult = _context9.sent;
779
+ return _context9.abrupt("return", toolArgsResult.rows.length > 0);
780
+ case 13:
781
+ _context9.prev = 13;
782
+ _context9.t0 = _context9["catch"](6);
783
+ console.log('error checking if valid arg exists====', _context9.t0);
784
+ return _context9.abrupt("return", false);
785
+ case 17:
786
+ _context9.prev = 17;
787
+ client.release();
788
+ return _context9.finish(17);
789
+ case 20:
1976
790
  case "end":
1977
- return _context2.stop();
791
+ return _context9.stop();
1978
792
  }
1979
- }, _callee2, this);
793
+ }, _callee9, this, [[6, 13, 17, 20]]);
1980
794
  }));
1981
- function saveThread(_x2) {
1982
- return _saveThread.apply(this, arguments);
795
+ function checkIfValidArgExists(_x9) {
796
+ return _checkIfValidArgExists.apply(this, arguments);
1983
797
  }
1984
- return saveThread;
798
+ return checkIfValidArgExists;
1985
799
  }();
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;
1990
- return _regeneratorRuntime().wrap(function _callee4$(_context4) {
1991
- while (1) switch (_context4.prev = _context4.next) {
800
+ _proto.getCachedToolResult = /*#__PURE__*/function () {
801
+ var _getCachedToolResult = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee10(_ref6) {
802
+ 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;
803
+ return _regeneratorRuntime().wrap(function _callee10$(_context10) {
804
+ while (1) switch (_context10.prev = _context10.next) {
1992
805
  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;
806
+ threadId = _ref6.threadId, toolArgs = _ref6.toolArgs, toolName = _ref6.toolName;
807
+ _context10.next = 3;
808
+ return this.ensureTablesExist();
809
+ case 3:
810
+ console.log('checking for cached tool result====', JSON.stringify(toolArgs, null, 2));
811
+ _context10.next = 6;
812
+ return this.pool.connect();
813
+ case 6:
814
+ client = _context10.sent;
815
+ _context10.prev = 7;
816
+ hashedToolArgs = crypto.createHash('sha256').update(JSON.stringify({
817
+ args: toolArgs,
818
+ threadId: threadId,
819
+ toolName: toolName
820
+ })).digest('hex');
821
+ console.log('hashedToolArgs====', hashedToolArgs);
822
+ _context10.next = 12;
823
+ 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()]);
824
+ case 12:
825
+ toolArgsResult = _context10.sent;
826
+ if (!(toolArgsResult.rows.length > 0)) {
827
+ _context10.next = 36;
2009
828
  break;
2010
829
  }
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);
830
+ console.log('toolArgsResult====', JSON.stringify(toolArgsResult.rows[0], null, 2));
831
+ toolCallArgs = JSON.parse((_toolArgsResult$rows$ = toolArgsResult.rows[0]) == null ? void 0 : _toolArgsResult$rows$.tool_call_args);
832
+ toolCallIds = JSON.parse((_toolArgsResult$rows$2 = toolArgsResult.rows[0]) == null ? void 0 : _toolArgsResult$rows$2.tool_call_ids);
833
+ createdAt = (_toolArgsResult$rows$3 = toolArgsResult.rows[0]) == null ? void 0 : _toolArgsResult$rows$3.created_at;
834
+ console.log('toolCallArgs====', JSON.stringify(toolCallArgs, null, 2));
835
+ console.log('toolCallIds====', JSON.stringify(toolCallIds, null, 2));
836
+ console.log('createdAt====', createdAt);
837
+ toolCallArgsIndex = toolCallArgs.findIndex(function (arg) {
838
+ return arg === hashedToolArgs;
2016
839
  });
2017
- case 13:
2018
- i++;
2019
- _context4.next = 5;
2020
- break;
2021
- case 16:
2022
- if (locked) {
2023
- _context4.next = 18;
840
+ correspondingToolCallId = toolCallIds[toolCallArgsIndex];
841
+ console.log('correspondingToolCallId====', {
842
+ correspondingToolCallId: correspondingToolCallId,
843
+ toolCallArgsIndex: toolCallArgsIndex
844
+ });
845
+ _context10.next = 26;
846
+ 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()]);
847
+ case 26:
848
+ toolResult = _context10.sent;
849
+ console.log('called toolResult');
850
+ if (!(toolResult.rows.length === 0)) {
851
+ _context10.next = 31;
2024
852
  break;
2025
853
  }
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;
854
+ console.log('no tool result found');
855
+ return _context10.abrupt("return", null);
856
+ case 31:
857
+ toolResultContent = JSON.parse((_toolResult$rows$ = toolResult.rows[0]) == null ? void 0 : _toolResult$rows$.content);
858
+ requiredToolResult = toolResultContent.find(function (part) {
859
+ return part.toolCallId === correspondingToolCallId;
860
+ });
861
+ console.log('requiredToolResult====', JSON.stringify(requiredToolResult, null, 2));
862
+ if (!requiredToolResult) {
863
+ _context10.next = 36;
2064
864
  break;
2065
865
  }
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:
866
+ return _context10.abrupt("return", requiredToolResult.result);
867
+ case 36:
868
+ return _context10.abrupt("return", null);
869
+ case 39:
870
+ _context10.prev = 39;
871
+ _context10.t0 = _context10["catch"](7);
872
+ console.log('error getting cached tool result====', _context10.t0);
873
+ return _context10.abrupt("return", null);
874
+ case 43:
875
+ _context10.prev = 43;
876
+ client.release();
877
+ return _context10.finish(43);
878
+ case 46:
2078
879
  case "end":
2079
- return _context4.stop();
880
+ return _context10.stop();
2080
881
  }
2081
- }, _callee4, this, [[3,, 23, 34], [26, 31]]);
882
+ }, _callee10, this, [[7, 39, 43, 46]]);
2082
883
  }));
2083
- function withLock(_x3, _x4) {
2084
- return _withLock.apply(this, arguments);
884
+ function getCachedToolResult(_x10) {
885
+ return _getCachedToolResult.apply(this, arguments);
2085
886
  }
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;
2094
- return _regeneratorRuntime().wrap(function _callee5$(_context5) {
2095
- while (1) switch (_context5.prev = _context5.next) {
887
+ return getCachedToolResult;
888
+ }();
889
+ _proto.getContextWindow = /*#__PURE__*/function () {
890
+ var _getContextWindow = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee11(_ref7) {
891
+ var threadId, startDate, endDate, client, _result, result;
892
+ return _regeneratorRuntime().wrap(function _callee11$(_context11) {
893
+ while (1) switch (_context11.prev = _context11.next) {
2096
894
  case 0:
2097
- // Clear all timeouts
2098
- for (_iterator = _createForOfIteratorHelperLoose(this.lockTimeouts.values()); !(_step = _iterator()).done;) {
2099
- timeout = _step.value;
2100
- clearTimeout(timeout);
895
+ threadId = _ref7.threadId, startDate = _ref7.startDate, endDate = _ref7.endDate;
896
+ _context11.next = 3;
897
+ return this.ensureTablesExist();
898
+ case 3:
899
+ console.log('table exists');
900
+ _context11.next = 6;
901
+ return this.pool.connect();
902
+ case 6:
903
+ client = _context11.sent;
904
+ _context11.prev = 7;
905
+ if (!this.MAX_CONTEXT_TOKENS) {
906
+ _context11.next = 14;
907
+ break;
2101
908
  }
2102
- this.lockTimeouts.clear();
2103
- case 2:
909
+ _context11.next = 11;
910
+ 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]);
911
+ case 11:
912
+ _result = _context11.sent;
913
+ console.log('result===', JSON.stringify(_result.rows, null, 2));
914
+ return _context11.abrupt("return", this.processMessages(_result.rows));
915
+ case 14:
916
+ _context11.next = 16;
917
+ 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]);
918
+ case 16:
919
+ result = _context11.sent;
920
+ console.log('result===', JSON.stringify(result.rows, null, 2));
921
+ return _context11.abrupt("return", this.processMessages(result.rows));
922
+ case 21:
923
+ _context11.prev = 21;
924
+ _context11.t0 = _context11["catch"](7);
925
+ console.log('error getting context window====', _context11.t0);
926
+ return _context11.abrupt("return", []);
927
+ case 25:
928
+ _context11.prev = 25;
929
+ client.release();
930
+ return _context11.finish(25);
931
+ case 28:
2104
932
  case "end":
2105
- return _context5.stop();
933
+ return _context11.stop();
2106
934
  }
2107
- }, _callee5, this);
935
+ }, _callee11, this, [[7, 21, 25, 28]]);
2108
936
  }));
2109
- function cleanup() {
2110
- return _cleanup.apply(this, arguments);
937
+ function getContextWindow(_x11) {
938
+ return _getContextWindow.apply(this, arguments);
2111
939
  }
2112
- return cleanup;
940
+ return getContextWindow;
2113
941
  }();
2114
942
  _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) {
943
+ var _saveMessages = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee12(_ref8) {
944
+ var _this2 = this;
945
+ var messages, client, _loop2, _iterator2, _step2;
946
+ return _regeneratorRuntime().wrap(function _callee12$(_context13) {
947
+ while (1) switch (_context13.prev = _context13.next) {
2120
948
  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) {
949
+ messages = _ref8.messages;
950
+ _context13.next = 3;
951
+ return this.ensureTablesExist();
952
+ case 3:
953
+ _context13.next = 5;
954
+ return this.pool.connect();
955
+ case 5:
956
+ client = _context13.sent;
957
+ _context13.prev = 6;
958
+ _context13.next = 9;
959
+ return client.query('BEGIN');
960
+ case 9:
961
+ _loop2 = /*#__PURE__*/_regeneratorRuntime().mark(function _loop2() {
962
+ var message, id, content, role, createdAt, threadId, toolCallIds, toolCallArgs, type, toolNames, tokens, _content$, contentMssg, hashedToolCallArgs, validArgExists, i, isValid, toolCallArgsExpireAt;
963
+ return _regeneratorRuntime().wrap(function _loop2$(_context12) {
964
+ while (1) switch (_context12.prev = _context12.next) {
2141
965
  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:
966
+ message = _step2.value;
967
+ console.log('saving message====', JSON.stringify(message, null, 2));
968
+ 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;
969
+ tokens = null;
970
+ if (type === 'text') {
971
+ contentMssg = role === 'assistant' ? ((_content$ = content[0]) == null ? void 0 : _content$.text) || '' : content;
972
+ tokens = _this2.estimateTokens(contentMssg);
973
+ }
974
+ // Hash the toolCallArgs if they exist
975
+ hashedToolCallArgs = toolCallArgs ? toolCallArgs.map(function (args, index) {
976
+ return crypto.createHash('sha256').update(JSON.stringify({
977
+ args: args,
978
+ threadId: threadId,
979
+ toolName: toolNames == null ? void 0 : toolNames[index]
980
+ })).digest('hex');
981
+ }) : null;
982
+ validArgExists = false;
983
+ if (!(hashedToolCallArgs != null && hashedToolCallArgs.length)) {
984
+ _context12.next = 20;
985
+ break;
986
+ }
987
+ // Check all args sequentially
988
+ validArgExists = true; // Start true and set to false if any check fails
989
+ i = 0;
990
+ case 10:
991
+ if (!(i < hashedToolCallArgs.length)) {
992
+ _context12.next = 20;
993
+ break;
994
+ }
995
+ _context12.next = 13;
996
+ return _this2.checkIfValidArgExists({
997
+ hashedToolCallArgs: hashedToolCallArgs[i]
998
+ });
999
+ case 13:
1000
+ isValid = _context12.sent;
1001
+ if (isValid) {
1002
+ _context12.next = 17;
1003
+ break;
1004
+ }
1005
+ validArgExists = false;
1006
+ return _context12.abrupt("break", 20);
1007
+ case 17:
1008
+ i++;
1009
+ _context12.next = 10;
1010
+ break;
1011
+ case 20:
1012
+ toolCallArgsExpireAt = !toolCallArgs ? null : validArgExists ? createdAt : new Date(createdAt.getTime() + 5 * 60 * 1000); // 5 minutes
1013
+ console.log('just before query');
1014
+ _context12.next = 24;
1015
+ 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()]);
1016
+ case 24:
2201
1017
  case "end":
2202
- return _context7.stop();
1018
+ return _context12.stop();
2203
1019
  }
2204
- }, _loop);
1020
+ }, _loop2);
2205
1021
  });
2206
- _i = 0, _Object$entries = Object.entries(messagesByThread);
2207
- case 5:
2208
- if (!(_i < _Object$entries.length)) {
2209
- _context8.next = 10;
1022
+ _iterator2 = _createForOfIteratorHelperLoose(messages);
1023
+ case 11:
1024
+ if ((_step2 = _iterator2()).done) {
1025
+ _context13.next = 15;
2210
1026
  break;
2211
1027
  }
2212
- return _context8.delegateYield(_loop(), "t0", 7);
2213
- case 7:
2214
- _i++;
2215
- _context8.next = 5;
1028
+ return _context13.delegateYield(_loop2(), "t0", 13);
1029
+ case 13:
1030
+ _context13.next = 11;
2216
1031
  break;
2217
- case 10:
2218
- return _context8.abrupt("return", messages);
2219
- case 11:
1032
+ case 15:
1033
+ console.log('just after query');
1034
+ _context13.next = 18;
1035
+ return client.query('COMMIT');
1036
+ case 18:
1037
+ return _context13.abrupt("return", messages);
1038
+ case 21:
1039
+ _context13.prev = 21;
1040
+ _context13.t1 = _context13["catch"](6);
1041
+ _context13.next = 25;
1042
+ return client.query('ROLLBACK');
1043
+ case 25:
1044
+ throw _context13.t1;
1045
+ case 26:
1046
+ _context13.prev = 26;
1047
+ client.release();
1048
+ return _context13.finish(26);
1049
+ case 29:
2220
1050
  case "end":
2221
- return _context8.stop();
1051
+ return _context13.stop();
2222
1052
  }
2223
- }, _callee7);
1053
+ }, _callee12, this, [[6, 21, 26, 29]]);
2224
1054
  }));
2225
- function saveMessages(_x5) {
1055
+ function saveMessages(_x12) {
2226
1056
  return _saveMessages.apply(this, arguments);
2227
1057
  }
2228
1058
  return saveMessages;
2229
1059
  }();
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) {
2235
- 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);
2247
- case 4:
2248
- case "end":
2249
- return _context9.stop();
2250
- }
2251
- }, _callee8, this);
2252
- }));
2253
- function addMessage(_x6, _x7, _x8) {
2254
- return _addMessage.apply(this, arguments);
2255
- }
2256
- return addMessage;
2257
- }();
2258
1060
  _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) {
1061
+ var _getMessages = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee13(_ref9) {
1062
+ var threadId, client, result, messages, uiMessages;
1063
+ return _regeneratorRuntime().wrap(function _callee13$(_context14) {
1064
+ while (1) switch (_context14.prev = _context14.next) {
2263
1065
  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 = [];
1066
+ threadId = _ref9.threadId;
1067
+ _context14.next = 3;
1068
+ return this.ensureTablesExist();
1069
+ case 3:
1070
+ _context14.next = 5;
1071
+ return this.pool.connect();
2273
1072
  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:
1073
+ client = _context14.sent;
1074
+ _context14.prev = 6;
1075
+ _context14.next = 9;
1076
+ 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]);
1077
+ case 9:
1078
+ result = _context14.sent;
1079
+ messages = this.processMessages(result.rows);
1080
+ uiMessages = this.convertToUIMessages(messages);
1081
+ return _context14.abrupt("return", {
1082
+ messages: messages,
1083
+ uiMessages: uiMessages
1084
+ });
1085
+ case 13:
1086
+ _context14.prev = 13;
1087
+ client.release();
1088
+ return _context14.finish(13);
1089
+ case 16:
2281
1090
  case "end":
2282
- return _context10.stop();
1091
+ return _context14.stop();
2283
1092
  }
2284
- }, _callee9, this);
1093
+ }, _callee13, this, [[6,, 13, 16]]);
2285
1094
  }));
2286
- function getMessages(_x9) {
1095
+ function getMessages(_x13) {
2287
1096
  return _getMessages.apply(this, arguments);
2288
1097
  }
2289
1098
  return getMessages;
2290
1099
  }();
2291
- _proto.getAllThreadIds = /*#__PURE__*/function () {
2292
- var _getAllThreadIds = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee10() {
2293
- return _regeneratorRuntime().wrap(function _callee10$(_context11) {
2294
- while (1) switch (_context11.prev = _context11.next) {
2295
- case 0:
2296
- return _context11.abrupt("return", this.redis.smembers('threads'));
2297
- case 1:
2298
- case "end":
2299
- return _context11.stop();
2300
- }
2301
- }, _callee10, this);
2302
- }));
2303
- function getAllThreadIds() {
2304
- return _getAllThreadIds.apply(this, arguments);
2305
- }
2306
- return getAllThreadIds;
2307
- }();
2308
- _proto.deleteThread = /*#__PURE__*/function () {
2309
- var _deleteThread = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee11(threadId) {
2310
- var pipeline;
2311
- return _regeneratorRuntime().wrap(function _callee11$(_context12) {
2312
- while (1) switch (_context12.prev = _context12.next) {
2313
- 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:
2321
- case "end":
2322
- return _context12.stop();
2323
- }
2324
- }, _callee11, this);
2325
- }));
2326
- function deleteThread(_x10) {
2327
- return _deleteThread.apply(this, arguments);
2328
- }
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;
2335
- return _regeneratorRuntime().wrap(function _callee12$(_context13) {
2336
- while (1) switch (_context13.prev = _context13.next) {
2337
- 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:
2348
- case "end":
2349
- return _context13.stop();
2350
- }
2351
- }, _callee12);
2352
- }));
2353
- function getThreads(_x11) {
2354
- return _getThreads.apply(this, arguments);
2355
- }
2356
- return getThreads;
2357
- }();
2358
- _proto.generateId = function generateId() {
2359
- return crypto.randomUUID();
2360
- };
2361
- return RedisMemory;
1100
+ return PgMemory;
2362
1101
  }(core.MastraMemory);
2363
1102
 
2364
- exports.CloudflareKVMemory = CloudflareKVMemory;
2365
- exports.LocalRedisProvider = LocalRedisProvider;
2366
1103
  exports.PgMemory = PgMemory;
2367
- exports.RedisMemory = RedisMemory;
2368
- exports.UpstashProvider = UpstashProvider;
2369
1104
  //# sourceMappingURL=memory.cjs.development.js.map