@mastra/memory 0.0.2-alpha.2 → 0.0.2-alpha.3

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.
@@ -5,6 +5,7 @@ Object.defineProperty(exports, '__esModule', { value: true });
5
5
  var core = require('@mastra/core');
6
6
  var crypto = require('crypto');
7
7
  var pg = require('pg');
8
+ var redis = require('@upstash/redis');
8
9
 
9
10
  function _arrayLikeToArray(r, a) {
10
11
  (null == a || a > r.length) && (a = r.length);
@@ -385,215 +386,129 @@ var PgMemory = /*#__PURE__*/function (_MastraMemory) {
385
386
  var _this;
386
387
  _this = _MastraMemory.call(this) || this;
387
388
  _this.pool = void 0;
388
- _this.MAX_CONTEXT_TOKENS = void 0;
389
+ _this.hasTables = false;
389
390
  _this.pool = new Pool({
390
391
  connectionString: config.connectionString
391
392
  });
392
393
  _this.MAX_CONTEXT_TOKENS = config.maxTokens;
393
394
  return _this;
394
395
  }
396
+ /**
397
+ * Threads
398
+ */
395
399
  _inheritsLoose(PgMemory, _MastraMemory);
396
400
  var _proto = PgMemory.prototype;
397
- _proto.drop = /*#__PURE__*/function () {
398
- var _drop = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
399
- var client;
401
+ _proto.getThreadById =
402
+ /*#__PURE__*/
403
+ function () {
404
+ var _getThreadById = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(_ref) {
405
+ var threadId, client, result;
400
406
  return _regeneratorRuntime().wrap(function _callee$(_context) {
401
407
  while (1) switch (_context.prev = _context.next) {
402
408
  case 0:
403
- _context.next = 2;
404
- return this.pool.connect();
405
- case 2:
406
- client = _context.sent;
409
+ threadId = _ref.threadId;
410
+ _context.next = 3;
411
+ return this.ensureTablesExist();
412
+ case 3:
407
413
  _context.next = 5;
408
- return client.query('DELETE FROM mastra_messages');
414
+ return this.pool.connect();
409
415
  case 5:
410
- _context.next = 7;
411
- return client.query('DELETE FROM mastra_threads');
412
- case 7:
416
+ client = _context.sent;
417
+ _context.prev = 6;
418
+ _context.next = 9;
419
+ return client.query("\n SELECT id, title, created_at AS createdAt, updated_at AS updatedAt, resourceid, metadata\n FROM mastra_threads\n WHERE id = $1\n ", [threadId]);
420
+ case 9:
421
+ result = _context.sent;
422
+ return _context.abrupt("return", result.rows[0] || null);
423
+ case 11:
424
+ _context.prev = 11;
413
425
  client.release();
414
- _context.next = 10;
415
- return this.pool.end();
416
- case 10:
426
+ return _context.finish(11);
427
+ case 14:
417
428
  case "end":
418
429
  return _context.stop();
419
430
  }
420
- }, _callee, this);
431
+ }, _callee, this, [[6,, 11, 14]]);
421
432
  }));
422
- function drop() {
423
- return _drop.apply(this, arguments);
424
- }
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
- };
433
+ function getThreadById(_x) {
434
+ return _getThreadById.apply(this, arguments);
467
435
  }
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;
436
+ return getThreadById;
437
+ }();
438
+ _proto.getThreadsByResourceId = /*#__PURE__*/function () {
439
+ var _getThreadsByResourceId = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(_ref2) {
440
+ var resourceid, client, result;
519
441
  return _regeneratorRuntime().wrap(function _callee2$(_context2) {
520
442
  while (1) switch (_context2.prev = _context2.next) {
521
443
  case 0:
522
- _context2.next = 2;
444
+ resourceid = _ref2.resourceid;
445
+ _context2.next = 3;
446
+ return this.ensureTablesExist();
447
+ case 3:
448
+ _context2.next = 5;
523
449
  return this.pool.connect();
524
- case 2:
450
+ case 5:
525
451
  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;
452
+ _context2.prev = 6;
453
+ _context2.next = 9;
454
+ return client.query("\n SELECT id, title, resourceid, created_at AS createdAt, updated_at AS updatedAt, metadata\n FROM mastra_threads\n WHERE resourceid = $1\n ", [resourceid]);
455
+ case 9:
456
+ result = _context2.sent;
457
+ return _context2.abrupt("return", result.rows);
458
+ case 11:
459
+ _context2.prev = 11;
550
460
  client.release();
551
- return _context2.finish(16);
552
- case 19:
461
+ return _context2.finish(11);
462
+ case 14:
553
463
  case "end":
554
464
  return _context2.stop();
555
465
  }
556
- }, _callee2, this, [[3,, 16, 19]]);
466
+ }, _callee2, this, [[6,, 11, 14]]);
557
467
  }));
558
- function ensureTablesExist() {
559
- return _ensureTablesExist.apply(this, arguments);
468
+ function getThreadsByResourceId(_x2) {
469
+ return _getThreadsByResourceId.apply(this, arguments);
560
470
  }
561
- return ensureTablesExist;
471
+ return getThreadsByResourceId;
562
472
  }();
563
- _proto.updateThread = /*#__PURE__*/function () {
564
- var _updateThread = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3(id, title, metadata) {
565
- var client, _result$rows, result;
473
+ _proto.saveThread = /*#__PURE__*/function () {
474
+ var _saveThread = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3(_ref3) {
475
+ var thread, client, _result$rows, id, title, createdAt, updatedAt, resourceid, metadata, result;
566
476
  return _regeneratorRuntime().wrap(function _callee3$(_context3) {
567
477
  while (1) switch (_context3.prev = _context3.next) {
568
478
  case 0:
569
- _context3.next = 2;
479
+ thread = _ref3.thread;
480
+ _context3.next = 3;
481
+ return this.ensureTablesExist();
482
+ case 3:
483
+ _context3.next = 5;
570
484
  return this.pool.connect();
571
- case 2:
485
+ case 5:
572
486
  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:
487
+ _context3.prev = 6;
488
+ id = thread.id, title = thread.title, createdAt = thread.createdAt, updatedAt = thread.updatedAt, resourceid = thread.resourceid, metadata = thread.metadata;
489
+ _context3.next = 10;
490
+ return client.query("\n INSERT INTO mastra_threads (id, title, created_at, updated_at, resourceid, metadata)\n VALUES ($1, $2, $3, $4, $5, $6)\n ON CONFLICT (id) DO UPDATE SET title = $2, updated_at = $4, resourceid = $5, metadata = $6\n RETURNING id, title, created_at AS createdAt, updated_at AS updatedAt, resourceid, metadata\n ", [id, title, createdAt, updatedAt, resourceid, JSON.stringify(metadata)]);
491
+ case 10:
577
492
  result = _context3.sent;
578
493
  return _context3.abrupt("return", result == null || (_result$rows = result.rows) == null ? void 0 : _result$rows[0]);
579
- case 8:
580
- _context3.prev = 8;
494
+ case 12:
495
+ _context3.prev = 12;
581
496
  client.release();
582
- return _context3.finish(8);
583
- case 11:
497
+ return _context3.finish(12);
498
+ case 15:
584
499
  case "end":
585
500
  return _context3.stop();
586
501
  }
587
- }, _callee3, this, [[3,, 8, 11]]);
502
+ }, _callee3, this, [[6,, 12, 15]]);
588
503
  }));
589
- function updateThread(_x, _x2, _x3) {
590
- return _updateThread.apply(this, arguments);
504
+ function saveThread(_x3) {
505
+ return _saveThread.apply(this, arguments);
591
506
  }
592
- return updateThread;
507
+ return saveThread;
593
508
  }();
594
- _proto.deleteThread = /*#__PURE__*/function () {
595
- var _deleteThread = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee4(id) {
596
- var client;
509
+ _proto.updateThread = /*#__PURE__*/function () {
510
+ var _updateThread = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee4(id, title, metadata) {
511
+ var client, _result$rows2, result;
597
512
  return _regeneratorRuntime().wrap(function _callee4$(_context4) {
598
513
  while (1) switch (_context4.prev = _context4.next) {
599
514
  case 0:
@@ -603,10 +518,10 @@ var PgMemory = /*#__PURE__*/function (_MastraMemory) {
603
518
  client = _context4.sent;
604
519
  _context4.prev = 3;
605
520
  _context4.next = 6;
606
- return client.query("\n DELETE FROM mastra_messages\n WHERE thread_id = $1\n ", [id]);
521
+ return client.query("\n UPDATE mastra_threads\n SET title = $1, metadata = $2, updated_at = NOW()\n WHERE id = $3\n RETURNING *\n ", [title, JSON.stringify(metadata), id]);
607
522
  case 6:
608
- _context4.next = 8;
609
- return client.query("\n DELETE FROM mastra_threads\n WHERE id = $1\n ", [id]);
523
+ result = _context4.sent;
524
+ return _context4.abrupt("return", result == null || (_result$rows2 = result.rows) == null ? void 0 : _result$rows2[0]);
610
525
  case 8:
611
526
  _context4.prev = 8;
612
527
  client.release();
@@ -617,13 +532,13 @@ var PgMemory = /*#__PURE__*/function (_MastraMemory) {
617
532
  }
618
533
  }, _callee4, this, [[3,, 8, 11]]);
619
534
  }));
620
- function deleteThread(_x4) {
621
- return _deleteThread.apply(this, arguments);
535
+ function updateThread(_x4, _x5, _x6) {
536
+ return _updateThread.apply(this, arguments);
622
537
  }
623
- return deleteThread;
538
+ return updateThread;
624
539
  }();
625
- _proto.deleteMessage = /*#__PURE__*/function () {
626
- var _deleteMessage = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee5(id) {
540
+ _proto.deleteThread = /*#__PURE__*/function () {
541
+ var _deleteThread = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee5(id) {
627
542
  var client;
628
543
  return _regeneratorRuntime().wrap(function _callee5$(_context5) {
629
544
  while (1) switch (_context5.prev = _context5.next) {
@@ -634,197 +549,99 @@ var PgMemory = /*#__PURE__*/function (_MastraMemory) {
634
549
  client = _context5.sent;
635
550
  _context5.prev = 3;
636
551
  _context5.next = 6;
637
- return client.query("\n DELETE FROM mastra_messages\n WHERE id = $1\n ", [id]);
552
+ return client.query("\n DELETE FROM mastra_messages\n WHERE thread_id = $1\n ", [id]);
638
553
  case 6:
639
- _context5.prev = 6;
554
+ _context5.next = 8;
555
+ return client.query("\n DELETE FROM mastra_threads\n WHERE id = $1\n ", [id]);
556
+ case 8:
557
+ _context5.prev = 8;
640
558
  client.release();
641
- return _context5.finish(6);
642
- case 9:
559
+ return _context5.finish(8);
560
+ case 11:
643
561
  case "end":
644
562
  return _context5.stop();
645
563
  }
646
- }, _callee5, this, [[3,, 6, 9]]);
564
+ }, _callee5, this, [[3,, 8, 11]]);
647
565
  }));
648
- function deleteMessage(_x5) {
649
- return _deleteMessage.apply(this, arguments);
566
+ function deleteThread(_x7) {
567
+ return _deleteThread.apply(this, arguments);
650
568
  }
651
- return deleteMessage;
652
- }();
653
- _proto.getThreadById = /*#__PURE__*/function () {
654
- var _getThreadById = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee6(_ref2) {
655
- var threadId, client, result;
569
+ return deleteThread;
570
+ }()
571
+ /**
572
+ * Tool Cache
573
+ */
574
+ ;
575
+ _proto.validateToolCallArgs =
576
+ /*#__PURE__*/
577
+ function () {
578
+ var _validateToolCallArgs = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee6(_ref4) {
579
+ var hashedArgs, client, toolArgsResult;
656
580
  return _regeneratorRuntime().wrap(function _callee6$(_context6) {
657
581
  while (1) switch (_context6.prev = _context6.next) {
658
582
  case 0:
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:
679
- case "end":
680
- return _context6.stop();
681
- }
682
- }, _callee6, this, [[7,, 12, 15]]);
683
- }));
684
- function getThreadById(_x6) {
685
- return _getThreadById.apply(this, arguments);
686
- }
687
- return getThreadById;
688
- }();
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) {
694
- case 0:
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:
714
- case "end":
715
- return _context7.stop();
716
- }
717
- }, _callee7, this, [[6,, 11, 14]]);
718
- }));
719
- function getThreadsByResourceId(_x7) {
720
- return _getThreadsByResourceId.apply(this, arguments);
721
- }
722
- return getThreadsByResourceId;
723
- }();
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) {
729
- case 0:
730
- thread = _ref4.thread;
731
- _context8.next = 3;
732
- return this.ensureTablesExist();
733
- case 3:
734
- _context8.next = 5;
735
- return this.pool.connect();
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:
750
- case "end":
751
- return _context8.stop();
752
- }
753
- }, _callee8, this, [[6,, 12, 15]]);
754
- }));
755
- function saveThread(_x8) {
756
- return _saveThread.apply(this, arguments);
757
- }
758
- return saveThread;
759
- }();
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) {
765
- case 0:
766
- hashedToolCallArgs = _ref5.hashedToolCallArgs;
767
- _context9.next = 3;
583
+ hashedArgs = _ref4.hashedArgs;
584
+ _context6.next = 3;
768
585
  return this.ensureTablesExist();
769
586
  case 3:
770
- _context9.next = 5;
587
+ _context6.next = 5;
771
588
  return this.pool.connect();
772
589
  case 5:
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()]);
590
+ client = _context6.sent;
591
+ _context6.prev = 6;
592
+ _context6.next = 9;
593
+ return client.query(" SELECT tool_call_ids as toolCallIds, \n tool_call_args as toolCallArgs,\n created_at AS createdAt\n FROM mastra_messages\n WHERE tool_call_args::jsonb @> $1\n AND tool_call_args_expire_at > $2\n ORDER BY created_at ASC\n LIMIT 1", [JSON.stringify([hashedArgs]), new Date().toISOString()]);
777
594
  case 9:
778
- toolArgsResult = _context9.sent;
779
- return _context9.abrupt("return", toolArgsResult.rows.length > 0);
595
+ toolArgsResult = _context6.sent;
596
+ return _context6.abrupt("return", toolArgsResult.rows.length > 0);
780
597
  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);
598
+ _context6.prev = 13;
599
+ _context6.t0 = _context6["catch"](6);
600
+ console.log('error checking if valid arg exists====', _context6.t0);
601
+ return _context6.abrupt("return", false);
785
602
  case 17:
786
- _context9.prev = 17;
603
+ _context6.prev = 17;
787
604
  client.release();
788
- return _context9.finish(17);
605
+ return _context6.finish(17);
789
606
  case 20:
790
607
  case "end":
791
- return _context9.stop();
608
+ return _context6.stop();
792
609
  }
793
- }, _callee9, this, [[6, 13, 17, 20]]);
610
+ }, _callee6, this, [[6, 13, 17, 20]]);
794
611
  }));
795
- function checkIfValidArgExists(_x9) {
796
- return _checkIfValidArgExists.apply(this, arguments);
612
+ function validateToolCallArgs(_x8) {
613
+ return _validateToolCallArgs.apply(this, arguments);
797
614
  }
798
- return checkIfValidArgExists;
615
+ return validateToolCallArgs;
799
616
  }();
800
- _proto.getCachedToolResult = /*#__PURE__*/function () {
801
- var _getCachedToolResult = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee10(_ref6) {
617
+ _proto.getToolResult = /*#__PURE__*/function () {
618
+ var _getToolResult = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee7(_ref5) {
802
619
  var threadId, toolArgs, toolName, client, hashedToolArgs, toolArgsResult, _toolArgsResult$rows$, _toolArgsResult$rows$2, _toolArgsResult$rows$3, _toolResult$rows$, toolCallArgs, toolCallIds, createdAt, toolCallArgsIndex, correspondingToolCallId, toolResult, toolResultContent, requiredToolResult;
803
- return _regeneratorRuntime().wrap(function _callee10$(_context10) {
804
- while (1) switch (_context10.prev = _context10.next) {
620
+ return _regeneratorRuntime().wrap(function _callee7$(_context7) {
621
+ while (1) switch (_context7.prev = _context7.next) {
805
622
  case 0:
806
- threadId = _ref6.threadId, toolArgs = _ref6.toolArgs, toolName = _ref6.toolName;
807
- _context10.next = 3;
623
+ threadId = _ref5.threadId, toolArgs = _ref5.toolArgs, toolName = _ref5.toolName;
624
+ _context7.next = 3;
808
625
  return this.ensureTablesExist();
809
626
  case 3:
810
627
  console.log('checking for cached tool result====', JSON.stringify(toolArgs, null, 2));
811
- _context10.next = 6;
628
+ _context7.next = 6;
812
629
  return this.pool.connect();
813
630
  case 6:
814
- client = _context10.sent;
815
- _context10.prev = 7;
631
+ client = _context7.sent;
632
+ _context7.prev = 7;
816
633
  hashedToolArgs = crypto.createHash('sha256').update(JSON.stringify({
817
634
  args: toolArgs,
818
635
  threadId: threadId,
819
636
  toolName: toolName
820
637
  })).digest('hex');
821
638
  console.log('hashedToolArgs====', hashedToolArgs);
822
- _context10.next = 12;
639
+ _context7.next = 12;
823
640
  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
641
  case 12:
825
- toolArgsResult = _context10.sent;
642
+ toolArgsResult = _context7.sent;
826
643
  if (!(toolArgsResult.rows.length > 0)) {
827
- _context10.next = 36;
644
+ _context7.next = 36;
828
645
  break;
829
646
  }
830
647
  console.log('toolArgsResult====', JSON.stringify(toolArgsResult.rows[0], null, 2));
@@ -842,17 +659,17 @@ var PgMemory = /*#__PURE__*/function (_MastraMemory) {
842
659
  correspondingToolCallId: correspondingToolCallId,
843
660
  toolCallArgsIndex: toolCallArgsIndex
844
661
  });
845
- _context10.next = 26;
662
+ _context7.next = 26;
846
663
  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
664
  case 26:
848
- toolResult = _context10.sent;
665
+ toolResult = _context7.sent;
849
666
  console.log('called toolResult');
850
667
  if (!(toolResult.rows.length === 0)) {
851
- _context10.next = 31;
668
+ _context7.next = 31;
852
669
  break;
853
670
  }
854
671
  console.log('no tool result found');
855
- return _context10.abrupt("return", null);
672
+ return _context7.abrupt("return", null);
856
673
  case 31:
857
674
  toolResultContent = JSON.parse((_toolResult$rows$ = toolResult.rows[0]) == null ? void 0 : _toolResult$rows$.content);
858
675
  requiredToolResult = toolResultContent.find(function (part) {
@@ -860,110 +677,155 @@ var PgMemory = /*#__PURE__*/function (_MastraMemory) {
860
677
  });
861
678
  console.log('requiredToolResult====', JSON.stringify(requiredToolResult, null, 2));
862
679
  if (!requiredToolResult) {
863
- _context10.next = 36;
680
+ _context7.next = 36;
864
681
  break;
865
682
  }
866
- return _context10.abrupt("return", requiredToolResult.result);
683
+ return _context7.abrupt("return", requiredToolResult.result);
867
684
  case 36:
868
- return _context10.abrupt("return", null);
685
+ return _context7.abrupt("return", null);
869
686
  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);
687
+ _context7.prev = 39;
688
+ _context7.t0 = _context7["catch"](7);
689
+ console.log('error getting cached tool result====', _context7.t0);
690
+ return _context7.abrupt("return", null);
874
691
  case 43:
875
- _context10.prev = 43;
692
+ _context7.prev = 43;
876
693
  client.release();
877
- return _context10.finish(43);
694
+ return _context7.finish(43);
878
695
  case 46:
879
696
  case "end":
880
- return _context10.stop();
697
+ return _context7.stop();
881
698
  }
882
- }, _callee10, this, [[7, 39, 43, 46]]);
699
+ }, _callee7, this, [[7, 39, 43, 46]]);
883
700
  }));
884
- function getCachedToolResult(_x10) {
885
- return _getCachedToolResult.apply(this, arguments);
701
+ function getToolResult(_x9) {
702
+ return _getToolResult.apply(this, arguments);
886
703
  }
887
- return getCachedToolResult;
704
+ return getToolResult;
888
705
  }();
889
706
  _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) {
707
+ var _getContextWindow = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee8(_ref6) {
708
+ var threadId, startDate, endDate, _ref6$format, format, client, _result, result;
709
+ return _regeneratorRuntime().wrap(function _callee8$(_context8) {
710
+ while (1) switch (_context8.prev = _context8.next) {
894
711
  case 0:
895
- threadId = _ref7.threadId, startDate = _ref7.startDate, endDate = _ref7.endDate;
896
- _context11.next = 3;
712
+ threadId = _ref6.threadId, startDate = _ref6.startDate, endDate = _ref6.endDate, _ref6$format = _ref6.format, format = _ref6$format === void 0 ? 'raw' : _ref6$format;
713
+ _context8.next = 3;
897
714
  return this.ensureTablesExist();
898
715
  case 3:
899
- console.log('table exists');
900
- _context11.next = 6;
716
+ _context8.next = 5;
901
717
  return this.pool.connect();
902
- case 6:
903
- client = _context11.sent;
904
- _context11.prev = 7;
718
+ case 5:
719
+ client = _context8.sent;
720
+ _context8.prev = 6;
905
721
  if (!this.MAX_CONTEXT_TOKENS) {
906
- _context11.next = 14;
722
+ _context8.next = 13;
907
723
  break;
908
724
  }
909
- _context11.next = 11;
725
+ _context8.next = 10;
910
726
  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;
727
+ case 10:
728
+ _result = _context8.sent;
729
+ console.log('Format', format);
730
+ return _context8.abrupt("return", this.parseMessages(_result.rows));
731
+ case 13:
732
+ _context8.next = 15;
917
733
  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;
734
+ case 15:
735
+ result = _context8.sent;
736
+ console.log('Format', format);
737
+ return _context8.abrupt("return", this.parseMessages(result.rows));
738
+ case 20:
739
+ _context8.prev = 20;
740
+ _context8.t0 = _context8["catch"](6);
741
+ console.log('error getting context window====', _context8.t0);
742
+ return _context8.abrupt("return", []);
743
+ case 24:
744
+ _context8.prev = 24;
929
745
  client.release();
930
- return _context11.finish(25);
931
- case 28:
746
+ return _context8.finish(24);
747
+ case 27:
932
748
  case "end":
933
- return _context11.stop();
749
+ return _context8.stop();
934
750
  }
935
- }, _callee11, this, [[7, 21, 25, 28]]);
751
+ }, _callee8, this, [[6, 20, 24, 27]]);
936
752
  }));
937
- function getContextWindow(_x11) {
753
+ function getContextWindow(_x10) {
938
754
  return _getContextWindow.apply(this, arguments);
939
755
  }
940
756
  return getContextWindow;
941
- }();
942
- _proto.saveMessages = /*#__PURE__*/function () {
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) {
757
+ }()
758
+ /**
759
+ * Messages
760
+ */
761
+ ;
762
+ _proto.getMessages =
763
+ /*#__PURE__*/
764
+ function () {
765
+ var _getMessages = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee9(_ref7) {
766
+ var threadId, client, result, messages, uiMessages;
767
+ return _regeneratorRuntime().wrap(function _callee9$(_context9) {
768
+ while (1) switch (_context9.prev = _context9.next) {
948
769
  case 0:
949
- messages = _ref8.messages;
950
- _context13.next = 3;
770
+ threadId = _ref7.threadId;
771
+ _context9.next = 3;
951
772
  return this.ensureTablesExist();
952
773
  case 3:
953
- _context13.next = 5;
774
+ _context9.next = 5;
954
775
  return this.pool.connect();
955
776
  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() {
777
+ client = _context9.sent;
778
+ _context9.prev = 6;
779
+ _context9.next = 9;
780
+ 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]);
781
+ case 9:
782
+ result = _context9.sent;
783
+ messages = this.parseMessages(result.rows);
784
+ uiMessages = this.convertToUIMessages(messages);
785
+ return _context9.abrupt("return", {
786
+ messages: messages,
787
+ uiMessages: uiMessages
788
+ });
789
+ case 13:
790
+ _context9.prev = 13;
791
+ client.release();
792
+ return _context9.finish(13);
793
+ case 16:
794
+ case "end":
795
+ return _context9.stop();
796
+ }
797
+ }, _callee9, this, [[6,, 13, 16]]);
798
+ }));
799
+ function getMessages(_x11) {
800
+ return _getMessages.apply(this, arguments);
801
+ }
802
+ return getMessages;
803
+ }();
804
+ _proto.saveMessages = /*#__PURE__*/function () {
805
+ var _saveMessages = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee10(_ref8) {
806
+ var _this2 = this;
807
+ var messages, client, _loop, _iterator, _step;
808
+ return _regeneratorRuntime().wrap(function _callee10$(_context11) {
809
+ while (1) switch (_context11.prev = _context11.next) {
810
+ case 0:
811
+ messages = _ref8.messages;
812
+ _context11.next = 3;
813
+ return this.ensureTablesExist();
814
+ case 3:
815
+ _context11.next = 5;
816
+ return this.pool.connect();
817
+ case 5:
818
+ client = _context11.sent;
819
+ _context11.prev = 6;
820
+ _context11.next = 9;
821
+ return client.query('BEGIN');
822
+ case 9:
823
+ _loop = /*#__PURE__*/_regeneratorRuntime().mark(function _loop() {
962
824
  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) {
825
+ return _regeneratorRuntime().wrap(function _loop$(_context10) {
826
+ while (1) switch (_context10.prev = _context10.next) {
965
827
  case 0:
966
- message = _step2.value;
828
+ message = _step.value;
967
829
  console.log('saving message====', JSON.stringify(message, null, 2));
968
830
  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
831
  tokens = null;
@@ -981,7 +843,7 @@ var PgMemory = /*#__PURE__*/function (_MastraMemory) {
981
843
  }) : null;
982
844
  validArgExists = false;
983
845
  if (!(hashedToolCallArgs != null && hashedToolCallArgs.length)) {
984
- _context12.next = 20;
846
+ _context10.next = 20;
985
847
  break;
986
848
  }
987
849
  // Check all args sequentially
@@ -989,116 +851,743 @@ var PgMemory = /*#__PURE__*/function (_MastraMemory) {
989
851
  i = 0;
990
852
  case 10:
991
853
  if (!(i < hashedToolCallArgs.length)) {
992
- _context12.next = 20;
854
+ _context10.next = 20;
993
855
  break;
994
856
  }
995
- _context12.next = 13;
996
- return _this2.checkIfValidArgExists({
997
- hashedToolCallArgs: hashedToolCallArgs[i]
857
+ _context10.next = 13;
858
+ return _this2.validateToolCallArgs({
859
+ hashedArgs: hashedToolCallArgs[i]
998
860
  });
999
861
  case 13:
1000
- isValid = _context12.sent;
862
+ isValid = _context10.sent;
1001
863
  if (isValid) {
1002
- _context12.next = 17;
864
+ _context10.next = 17;
1003
865
  break;
1004
866
  }
1005
867
  validArgExists = false;
1006
- return _context12.abrupt("break", 20);
868
+ return _context10.abrupt("break", 20);
1007
869
  case 17:
1008
870
  i++;
1009
- _context12.next = 10;
871
+ _context10.next = 10;
1010
872
  break;
1011
873
  case 20:
1012
874
  toolCallArgsExpireAt = !toolCallArgs ? null : validArgExists ? createdAt : new Date(createdAt.getTime() + 5 * 60 * 1000); // 5 minutes
1013
875
  console.log('just before query');
1014
- _context12.next = 24;
876
+ _context10.next = 24;
1015
877
  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
878
  case 24:
1017
879
  case "end":
1018
- return _context12.stop();
880
+ return _context10.stop();
1019
881
  }
1020
- }, _loop2);
882
+ }, _loop);
1021
883
  });
1022
- _iterator2 = _createForOfIteratorHelperLoose(messages);
884
+ _iterator = _createForOfIteratorHelperLoose(messages);
1023
885
  case 11:
1024
- if ((_step2 = _iterator2()).done) {
1025
- _context13.next = 15;
886
+ if ((_step = _iterator()).done) {
887
+ _context11.next = 15;
1026
888
  break;
1027
889
  }
1028
- return _context13.delegateYield(_loop2(), "t0", 13);
890
+ return _context11.delegateYield(_loop(), "t0", 13);
1029
891
  case 13:
1030
- _context13.next = 11;
892
+ _context11.next = 11;
1031
893
  break;
1032
894
  case 15:
1033
895
  console.log('just after query');
1034
- _context13.next = 18;
896
+ _context11.next = 18;
1035
897
  return client.query('COMMIT');
1036
898
  case 18:
1037
- return _context13.abrupt("return", messages);
899
+ return _context11.abrupt("return", messages);
1038
900
  case 21:
1039
- _context13.prev = 21;
1040
- _context13.t1 = _context13["catch"](6);
1041
- _context13.next = 25;
901
+ _context11.prev = 21;
902
+ _context11.t1 = _context11["catch"](6);
903
+ _context11.next = 25;
1042
904
  return client.query('ROLLBACK');
1043
905
  case 25:
1044
- throw _context13.t1;
906
+ throw _context11.t1;
1045
907
  case 26:
1046
- _context13.prev = 26;
908
+ _context11.prev = 26;
1047
909
  client.release();
1048
- return _context13.finish(26);
910
+ return _context11.finish(26);
1049
911
  case 29:
1050
912
  case "end":
1051
- return _context13.stop();
913
+ return _context11.stop();
1052
914
  }
1053
- }, _callee12, this, [[6, 21, 26, 29]]);
915
+ }, _callee10, this, [[6, 21, 26, 29]]);
1054
916
  }));
1055
917
  function saveMessages(_x12) {
1056
918
  return _saveMessages.apply(this, arguments);
1057
919
  }
1058
920
  return saveMessages;
1059
921
  }();
1060
- _proto.getMessages = /*#__PURE__*/function () {
1061
- var _getMessages = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee13(_ref9) {
1062
- var threadId, client, result, messages, uiMessages;
922
+ _proto.deleteMessage = /*#__PURE__*/function () {
923
+ var _deleteMessage = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee11(id) {
924
+ var client;
925
+ return _regeneratorRuntime().wrap(function _callee11$(_context12) {
926
+ while (1) switch (_context12.prev = _context12.next) {
927
+ case 0:
928
+ _context12.next = 2;
929
+ return this.pool.connect();
930
+ case 2:
931
+ client = _context12.sent;
932
+ _context12.prev = 3;
933
+ _context12.next = 6;
934
+ return client.query("\n DELETE FROM mastra_messages\n WHERE id = $1\n ", [id]);
935
+ case 6:
936
+ _context12.prev = 6;
937
+ client.release();
938
+ return _context12.finish(6);
939
+ case 9:
940
+ case "end":
941
+ return _context12.stop();
942
+ }
943
+ }, _callee11, this, [[3,, 6, 9]]);
944
+ }));
945
+ function deleteMessage(_x13) {
946
+ return _deleteMessage.apply(this, arguments);
947
+ }
948
+ return deleteMessage;
949
+ }()
950
+ /**
951
+ * Table Management
952
+ */
953
+ ;
954
+ _proto.drop =
955
+ /*#__PURE__*/
956
+ function () {
957
+ var _drop = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee12() {
958
+ var client;
959
+ return _regeneratorRuntime().wrap(function _callee12$(_context13) {
960
+ while (1) switch (_context13.prev = _context13.next) {
961
+ case 0:
962
+ _context13.next = 2;
963
+ return this.pool.connect();
964
+ case 2:
965
+ client = _context13.sent;
966
+ _context13.next = 5;
967
+ return client.query('DELETE FROM mastra_messages');
968
+ case 5:
969
+ _context13.next = 7;
970
+ return client.query('DELETE FROM mastra_threads');
971
+ case 7:
972
+ client.release();
973
+ _context13.next = 10;
974
+ return this.pool.end();
975
+ case 10:
976
+ case "end":
977
+ return _context13.stop();
978
+ }
979
+ }, _callee12, this);
980
+ }));
981
+ function drop() {
982
+ return _drop.apply(this, arguments);
983
+ }
984
+ return drop;
985
+ }();
986
+ _proto.ensureTablesExist = /*#__PURE__*/function () {
987
+ var _ensureTablesExist = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee13() {
988
+ var client, _threadsResult$rows, _messagesResult$rows, threadsResult, messagesResult;
1063
989
  return _regeneratorRuntime().wrap(function _callee13$(_context14) {
1064
990
  while (1) switch (_context14.prev = _context14.next) {
1065
991
  case 0:
1066
- threadId = _ref9.threadId;
1067
- _context14.next = 3;
1068
- return this.ensureTablesExist();
1069
- case 3:
1070
- _context14.next = 5;
992
+ if (!this.hasTables) {
993
+ _context14.next = 2;
994
+ break;
995
+ }
996
+ return _context14.abrupt("return");
997
+ case 2:
998
+ _context14.next = 4;
1071
999
  return this.pool.connect();
1072
- case 5:
1000
+ case 4:
1073
1001
  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]);
1002
+ _context14.prev = 5;
1003
+ _context14.next = 8;
1004
+ return client.query("\n SELECT EXISTS (\n SELECT 1\n FROM information_schema.tables\n WHERE table_name = 'mastra_threads'\n );\n ");
1005
+ case 8:
1006
+ threadsResult = _context14.sent;
1007
+ if (threadsResult != null && (_threadsResult$rows = threadsResult.rows) != null && (_threadsResult$rows = _threadsResult$rows[0]) != null && _threadsResult$rows.exists) {
1008
+ _context14.next = 12;
1009
+ break;
1010
+ }
1011
+ _context14.next = 12;
1012
+ 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 ");
1013
+ case 12:
1014
+ _context14.next = 14;
1015
+ return client.query("\n SELECT EXISTS (\n SELECT 1\n FROM information_schema.tables\n WHERE table_name = 'mastra_messages'\n );\n ");
1016
+ case 14:
1017
+ messagesResult = _context14.sent;
1018
+ if (messagesResult != null && (_messagesResult$rows = messagesResult.rows) != null && (_messagesResult$rows = _messagesResult$rows[0]) != null && _messagesResult$rows.exists) {
1019
+ _context14.next = 18;
1020
+ break;
1021
+ }
1022
+ _context14.next = 18;
1023
+ 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 ");
1024
+ case 18:
1025
+ _context14.prev = 18;
1026
+ client.release();
1027
+ this.hasTables = true;
1028
+ return _context14.finish(18);
1029
+ case 22:
1030
+ case "end":
1031
+ return _context14.stop();
1032
+ }
1033
+ }, _callee13, this, [[5,, 18, 22]]);
1034
+ }));
1035
+ function ensureTablesExist() {
1036
+ return _ensureTablesExist.apply(this, arguments);
1037
+ }
1038
+ return ensureTablesExist;
1039
+ }();
1040
+ return PgMemory;
1041
+ }(core.MastraMemory);
1042
+
1043
+ var UpstashKVMemory = /*#__PURE__*/function (_MastraMemory) {
1044
+ function UpstashKVMemory(config) {
1045
+ var _this;
1046
+ _this = _MastraMemory.call(this) || this;
1047
+ _this.prefix = void 0;
1048
+ _this.kv = void 0;
1049
+ _this.prefix = config.prefix || 'mastra';
1050
+ _this.MAX_CONTEXT_TOKENS = config.maxTokens;
1051
+ _this.kv = new redis.Redis({
1052
+ url: config.url,
1053
+ token: config.token
1054
+ });
1055
+ return _this;
1056
+ }
1057
+ _inheritsLoose(UpstashKVMemory, _MastraMemory);
1058
+ var _proto = UpstashKVMemory.prototype;
1059
+ _proto.getThreadKey = function getThreadKey(threadId) {
1060
+ return this.prefix + ":thread:" + threadId;
1061
+ };
1062
+ _proto.getMessagesKey = function getMessagesKey(threadId) {
1063
+ return this.prefix + ":messages:" + threadId;
1064
+ };
1065
+ _proto.getToolCacheKey = function getToolCacheKey(hashedArgs) {
1066
+ return this.prefix + ":tool:" + hashedArgs;
1067
+ };
1068
+ _proto.getThreadById = /*#__PURE__*/function () {
1069
+ var _getThreadById = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(_ref) {
1070
+ var threadId, thread;
1071
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
1072
+ while (1) switch (_context.prev = _context.next) {
1073
+ case 0:
1074
+ threadId = _ref.threadId;
1075
+ _context.next = 3;
1076
+ return this.kv.get(this.getThreadKey(threadId));
1077
+ case 3:
1078
+ thread = _context.sent;
1079
+ return _context.abrupt("return", thread ? this.parseThread(thread) : null);
1080
+ case 5:
1081
+ case "end":
1082
+ return _context.stop();
1083
+ }
1084
+ }, _callee, this);
1085
+ }));
1086
+ function getThreadById(_x) {
1087
+ return _getThreadById.apply(this, arguments);
1088
+ }
1089
+ return getThreadById;
1090
+ }();
1091
+ _proto.getThreadsByResourceId = /*#__PURE__*/function () {
1092
+ var _getThreadsByResourceId = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(_ref2) {
1093
+ var _this2 = this;
1094
+ var resourceid, pattern, keys, threads;
1095
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
1096
+ while (1) switch (_context2.prev = _context2.next) {
1097
+ case 0:
1098
+ resourceid = _ref2.resourceid;
1099
+ pattern = this.prefix + ":thread:*";
1100
+ _context2.next = 4;
1101
+ return this.kv.keys(pattern);
1102
+ case 4:
1103
+ keys = _context2.sent;
1104
+ _context2.next = 7;
1105
+ return Promise.all(keys.map(function (key) {
1106
+ return _this2.kv.get(key);
1107
+ }));
1108
+ case 7:
1109
+ threads = _context2.sent;
1110
+ return _context2.abrupt("return", threads.filter(function (thread) {
1111
+ return (thread == null ? void 0 : thread.resourceid) === resourceid;
1112
+ }).map(function (thread) {
1113
+ return _this2.parseThread(thread);
1114
+ }));
1077
1115
  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,
1116
+ case "end":
1117
+ return _context2.stop();
1118
+ }
1119
+ }, _callee2, this);
1120
+ }));
1121
+ function getThreadsByResourceId(_x2) {
1122
+ return _getThreadsByResourceId.apply(this, arguments);
1123
+ }
1124
+ return getThreadsByResourceId;
1125
+ }();
1126
+ _proto.saveThread = /*#__PURE__*/function () {
1127
+ var _saveThread = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3(_ref3) {
1128
+ var thread, key, serializedThread;
1129
+ return _regeneratorRuntime().wrap(function _callee3$(_context3) {
1130
+ while (1) switch (_context3.prev = _context3.next) {
1131
+ case 0:
1132
+ thread = _ref3.thread;
1133
+ key = this.getThreadKey(thread.id);
1134
+ serializedThread = _extends({}, thread, {
1135
+ createdAt: thread.createdAt.toISOString(),
1136
+ updatedAt: thread.updatedAt.toISOString()
1137
+ });
1138
+ _context3.next = 5;
1139
+ return this.kv.set(key, serializedThread);
1140
+ case 5:
1141
+ return _context3.abrupt("return", thread);
1142
+ case 6:
1143
+ case "end":
1144
+ return _context3.stop();
1145
+ }
1146
+ }, _callee3, this);
1147
+ }));
1148
+ function saveThread(_x3) {
1149
+ return _saveThread.apply(this, arguments);
1150
+ }
1151
+ return saveThread;
1152
+ }();
1153
+ _proto.updateThread = /*#__PURE__*/function () {
1154
+ var _updateThread = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee4(id, title, metadata) {
1155
+ var key, thread, updatedThread;
1156
+ return _regeneratorRuntime().wrap(function _callee4$(_context4) {
1157
+ while (1) switch (_context4.prev = _context4.next) {
1158
+ case 0:
1159
+ key = this.getThreadKey(id);
1160
+ _context4.next = 3;
1161
+ return this.kv.get(key);
1162
+ case 3:
1163
+ thread = _context4.sent;
1164
+ if (thread) {
1165
+ _context4.next = 6;
1166
+ break;
1167
+ }
1168
+ throw new Error("Thread " + id + " not found");
1169
+ case 6:
1170
+ updatedThread = _extends({}, thread, {
1171
+ title: title,
1172
+ metadata: metadata,
1173
+ updatedAt: new Date().toISOString()
1174
+ });
1175
+ _context4.next = 9;
1176
+ return this.kv.set(key, updatedThread);
1177
+ case 9:
1178
+ return _context4.abrupt("return", this.parseThread(updatedThread));
1179
+ case 10:
1180
+ case "end":
1181
+ return _context4.stop();
1182
+ }
1183
+ }, _callee4, this);
1184
+ }));
1185
+ function updateThread(_x4, _x5, _x6) {
1186
+ return _updateThread.apply(this, arguments);
1187
+ }
1188
+ return updateThread;
1189
+ }();
1190
+ _proto.deleteThread = /*#__PURE__*/function () {
1191
+ var _deleteThread = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee5(id) {
1192
+ return _regeneratorRuntime().wrap(function _callee5$(_context5) {
1193
+ while (1) switch (_context5.prev = _context5.next) {
1194
+ case 0:
1195
+ _context5.next = 2;
1196
+ return this.kv.del(this.getThreadKey(id));
1197
+ case 2:
1198
+ _context5.next = 4;
1199
+ return this.kv.del(this.getMessagesKey(id));
1200
+ case 4:
1201
+ case "end":
1202
+ return _context5.stop();
1203
+ }
1204
+ }, _callee5, this);
1205
+ }));
1206
+ function deleteThread(_x7) {
1207
+ return _deleteThread.apply(this, arguments);
1208
+ }
1209
+ return deleteThread;
1210
+ }()
1211
+ /**
1212
+ * Tool Cache
1213
+ */
1214
+ ;
1215
+ _proto.validateToolCallArgs =
1216
+ /*#__PURE__*/
1217
+ function () {
1218
+ var _validateToolCallArgs = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee6(_ref4) {
1219
+ var hashedArgs, cacheKey, cached;
1220
+ return _regeneratorRuntime().wrap(function _callee6$(_context6) {
1221
+ while (1) switch (_context6.prev = _context6.next) {
1222
+ case 0:
1223
+ hashedArgs = _ref4.hashedArgs;
1224
+ cacheKey = this.getToolCacheKey(hashedArgs);
1225
+ _context6.next = 4;
1226
+ return this.kv.get(cacheKey);
1227
+ case 4:
1228
+ cached = _context6.sent;
1229
+ return _context6.abrupt("return", !!cached && new Date(cached.expireAt) > new Date());
1230
+ case 6:
1231
+ case "end":
1232
+ return _context6.stop();
1233
+ }
1234
+ }, _callee6, this);
1235
+ }));
1236
+ function validateToolCallArgs(_x8) {
1237
+ return _validateToolCallArgs.apply(this, arguments);
1238
+ }
1239
+ return validateToolCallArgs;
1240
+ }();
1241
+ _proto.getToolResult = /*#__PURE__*/function () {
1242
+ var _getToolResult = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee7(_ref5) {
1243
+ var threadId, toolArgs, toolName, hashedToolArgs, cacheKey, cached;
1244
+ return _regeneratorRuntime().wrap(function _callee7$(_context7) {
1245
+ while (1) switch (_context7.prev = _context7.next) {
1246
+ case 0:
1247
+ threadId = _ref5.threadId, toolArgs = _ref5.toolArgs, toolName = _ref5.toolName;
1248
+ hashedToolArgs = crypto.createHash('sha256').update(JSON.stringify({
1249
+ args: toolArgs,
1250
+ threadId: threadId,
1251
+ toolName: toolName
1252
+ })).digest('hex');
1253
+ cacheKey = this.getToolCacheKey(hashedToolArgs);
1254
+ _context7.next = 5;
1255
+ return this.kv.get(cacheKey);
1256
+ case 5:
1257
+ cached = _context7.sent;
1258
+ if (!(cached && new Date(cached.expireAt) > new Date())) {
1259
+ _context7.next = 8;
1260
+ break;
1261
+ }
1262
+ return _context7.abrupt("return", cached.result || null);
1263
+ case 8:
1264
+ return _context7.abrupt("return", null);
1265
+ case 9:
1266
+ case "end":
1267
+ return _context7.stop();
1268
+ }
1269
+ }, _callee7, this);
1270
+ }));
1271
+ function getToolResult(_x9) {
1272
+ return _getToolResult.apply(this, arguments);
1273
+ }
1274
+ return getToolResult;
1275
+ }();
1276
+ _proto.getContextWindow = /*#__PURE__*/function () {
1277
+ var _getContextWindow = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee8(_ref6) {
1278
+ var threadId, startDate, endDate, _ref6$format, format, messagesKey, messages, filteredMessages, totalTokens, messagesWithinTokenLimit, _iterator, _step, _message$content$, message, content, tokens;
1279
+ return _regeneratorRuntime().wrap(function _callee8$(_context8) {
1280
+ while (1) switch (_context8.prev = _context8.next) {
1281
+ case 0:
1282
+ threadId = _ref6.threadId, startDate = _ref6.startDate, endDate = _ref6.endDate, _ref6$format = _ref6.format, format = _ref6$format === void 0 ? 'raw' : _ref6$format;
1283
+ messagesKey = this.getMessagesKey(threadId);
1284
+ _context8.next = 4;
1285
+ return this.kv.lrange(messagesKey, 0, -1);
1286
+ case 4:
1287
+ messages = _context8.sent;
1288
+ filteredMessages = messages.filter(function (msg) {
1289
+ return msg.type === 'text';
1290
+ });
1291
+ if (startDate) {
1292
+ filteredMessages = filteredMessages.filter(function (msg) {
1293
+ return new Date(msg.createdAt) >= startDate;
1294
+ });
1295
+ }
1296
+ if (endDate) {
1297
+ filteredMessages = filteredMessages.filter(function (msg) {
1298
+ return new Date(msg.createdAt) <= endDate;
1299
+ });
1300
+ }
1301
+ if (!this.MAX_CONTEXT_TOKENS) {
1302
+ _context8.next = 24;
1303
+ break;
1304
+ }
1305
+ totalTokens = 0;
1306
+ messagesWithinTokenLimit = []; // Process messages from newest to oldest
1307
+ _iterator = _createForOfIteratorHelperLoose(filteredMessages.reverse());
1308
+ case 12:
1309
+ if ((_step = _iterator()).done) {
1310
+ _context8.next = 22;
1311
+ break;
1312
+ }
1313
+ message = _step.value;
1314
+ content = message.role === 'assistant' ? ((_message$content$ = message.content[0]) == null ? void 0 : _message$content$.text) || '' : message.content; // Use a more aggressive token estimation
1315
+ // Roughly estimate 1 token per 4 characters
1316
+ tokens = Math.ceil(content.length / 4); // Check if adding this message would exceed the token limit
1317
+ if (!(totalTokens + tokens > this.MAX_CONTEXT_TOKENS)) {
1318
+ _context8.next = 18;
1319
+ break;
1320
+ }
1321
+ return _context8.abrupt("break", 22);
1322
+ case 18:
1323
+ totalTokens += tokens;
1324
+ messagesWithinTokenLimit.unshift(_extends({}, message, {
1325
+ tokens: tokens
1326
+ }));
1327
+ case 20:
1328
+ _context8.next = 12;
1329
+ break;
1330
+ case 22:
1331
+ console.log('Format:', format);
1332
+ // Return messages in chronological order
1333
+ return _context8.abrupt("return", this.parseMessages(messagesWithinTokenLimit));
1334
+ case 24:
1335
+ return _context8.abrupt("return", this.parseMessages(filteredMessages));
1336
+ case 25:
1337
+ case "end":
1338
+ return _context8.stop();
1339
+ }
1340
+ }, _callee8, this);
1341
+ }));
1342
+ function getContextWindow(_x10) {
1343
+ return _getContextWindow.apply(this, arguments);
1344
+ }
1345
+ return getContextWindow;
1346
+ }()
1347
+ /**
1348
+ * Messages
1349
+ */
1350
+ ;
1351
+ _proto.getMessages =
1352
+ /*#__PURE__*/
1353
+ function () {
1354
+ var _getMessages = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee9(_ref7) {
1355
+ var threadId, messagesKey, messages, parsedMessages, uiMessages;
1356
+ return _regeneratorRuntime().wrap(function _callee9$(_context9) {
1357
+ while (1) switch (_context9.prev = _context9.next) {
1358
+ case 0:
1359
+ threadId = _ref7.threadId;
1360
+ messagesKey = this.getMessagesKey(threadId);
1361
+ _context9.next = 4;
1362
+ return this.kv.lrange(messagesKey, 0, -1);
1363
+ case 4:
1364
+ messages = _context9.sent;
1365
+ parsedMessages = this.parseMessages(messages);
1366
+ uiMessages = this.convertToUIMessages(parsedMessages);
1367
+ return _context9.abrupt("return", {
1368
+ messages: parsedMessages,
1083
1369
  uiMessages: uiMessages
1084
1370
  });
1085
- case 13:
1086
- _context14.prev = 13;
1087
- client.release();
1088
- return _context14.finish(13);
1089
- case 16:
1371
+ case 8:
1090
1372
  case "end":
1091
- return _context14.stop();
1373
+ return _context9.stop();
1092
1374
  }
1093
- }, _callee13, this, [[6,, 13, 16]]);
1375
+ }, _callee9, this);
1094
1376
  }));
1095
- function getMessages(_x13) {
1377
+ function getMessages(_x11) {
1096
1378
  return _getMessages.apply(this, arguments);
1097
1379
  }
1098
1380
  return getMessages;
1099
1381
  }();
1100
- return PgMemory;
1382
+ _proto.saveMessages = /*#__PURE__*/function () {
1383
+ var _saveMessages = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee10(_ref8) {
1384
+ var _this3 = this;
1385
+ var messages, processedMessages, _loop, _iterator2, _step2;
1386
+ return _regeneratorRuntime().wrap(function _callee10$(_context11) {
1387
+ while (1) switch (_context11.prev = _context11.next) {
1388
+ case 0:
1389
+ messages = _ref8.messages;
1390
+ processedMessages = [];
1391
+ _loop = /*#__PURE__*/_regeneratorRuntime().mark(function _loop() {
1392
+ var message, threadId, toolCallArgs, toolNames, createdAt, messagesKey, processedMessage, _message$content$2, content, hashedToolCallArgs, validArgExists, _iterator3, _step3, hashedArg, isValid, expireAt, _iterator4, _step4, _hashedArg, cacheKey;
1393
+ return _regeneratorRuntime().wrap(function _loop$(_context10) {
1394
+ while (1) switch (_context10.prev = _context10.next) {
1395
+ case 0:
1396
+ message = _step2.value;
1397
+ threadId = message.threadId, toolCallArgs = message.toolCallArgs, toolNames = message.toolNames, createdAt = message.createdAt;
1398
+ messagesKey = _this3.getMessagesKey(threadId);
1399
+ processedMessage = _extends({}, message);
1400
+ if (message.type === 'text') {
1401
+ content = message.role === 'assistant' ? ((_message$content$2 = message.content[0]) == null ? void 0 : _message$content$2.text) || '' : message.content;
1402
+ processedMessage.tokens = _this3.estimateTokens(content);
1403
+ }
1404
+ if (!(toolCallArgs != null && toolCallArgs.length)) {
1405
+ _context10.next = 28;
1406
+ break;
1407
+ }
1408
+ hashedToolCallArgs = toolCallArgs.map(function (args, index) {
1409
+ return crypto.createHash('sha256').update(JSON.stringify({
1410
+ args: args,
1411
+ threadId: threadId,
1412
+ toolName: toolNames == null ? void 0 : toolNames[index]
1413
+ })).digest('hex');
1414
+ });
1415
+ validArgExists = true;
1416
+ _iterator3 = _createForOfIteratorHelperLoose(hashedToolCallArgs);
1417
+ case 9:
1418
+ if ((_step3 = _iterator3()).done) {
1419
+ _context10.next = 19;
1420
+ break;
1421
+ }
1422
+ hashedArg = _step3.value;
1423
+ _context10.next = 13;
1424
+ return _this3.validateToolCallArgs({
1425
+ hashedArgs: hashedArg
1426
+ });
1427
+ case 13:
1428
+ isValid = _context10.sent;
1429
+ if (isValid) {
1430
+ _context10.next = 17;
1431
+ break;
1432
+ }
1433
+ validArgExists = false;
1434
+ return _context10.abrupt("break", 19);
1435
+ case 17:
1436
+ _context10.next = 9;
1437
+ break;
1438
+ case 19:
1439
+ expireAt = validArgExists ? createdAt : new Date(createdAt.getTime() + 5 * 60 * 1000); // 5 minutes
1440
+ _iterator4 = _createForOfIteratorHelperLoose(hashedToolCallArgs);
1441
+ case 21:
1442
+ if ((_step4 = _iterator4()).done) {
1443
+ _context10.next = 28;
1444
+ break;
1445
+ }
1446
+ _hashedArg = _step4.value;
1447
+ cacheKey = _this3.getToolCacheKey(_hashedArg);
1448
+ _context10.next = 26;
1449
+ return _this3.kv.set(cacheKey, {
1450
+ expireAt: expireAt.toISOString()
1451
+ });
1452
+ case 26:
1453
+ _context10.next = 21;
1454
+ break;
1455
+ case 28:
1456
+ _context10.next = 30;
1457
+ return _this3.kv.rpush(messagesKey, processedMessage);
1458
+ case 30:
1459
+ processedMessages.push(processedMessage);
1460
+ case 31:
1461
+ case "end":
1462
+ return _context10.stop();
1463
+ }
1464
+ }, _loop);
1465
+ });
1466
+ _iterator2 = _createForOfIteratorHelperLoose(messages);
1467
+ case 4:
1468
+ if ((_step2 = _iterator2()).done) {
1469
+ _context11.next = 8;
1470
+ break;
1471
+ }
1472
+ return _context11.delegateYield(_loop(), "t0", 6);
1473
+ case 6:
1474
+ _context11.next = 4;
1475
+ break;
1476
+ case 8:
1477
+ return _context11.abrupt("return", processedMessages);
1478
+ case 9:
1479
+ case "end":
1480
+ return _context11.stop();
1481
+ }
1482
+ }, _callee10);
1483
+ }));
1484
+ function saveMessages(_x12) {
1485
+ return _saveMessages.apply(this, arguments);
1486
+ }
1487
+ return saveMessages;
1488
+ }();
1489
+ _proto.deleteMessage = /*#__PURE__*/function () {
1490
+ var _deleteMessage = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee11(id) {
1491
+ var pattern, keys, _iterator5, _step5, key, messages, filteredMessages, _this$kv;
1492
+ return _regeneratorRuntime().wrap(function _callee11$(_context12) {
1493
+ while (1) switch (_context12.prev = _context12.next) {
1494
+ case 0:
1495
+ pattern = this.prefix + ":messages:*";
1496
+ _context12.next = 3;
1497
+ return this.kv.keys(pattern);
1498
+ case 3:
1499
+ keys = _context12.sent;
1500
+ _iterator5 = _createForOfIteratorHelperLoose(keys);
1501
+ case 5:
1502
+ if ((_step5 = _iterator5()).done) {
1503
+ _context12.next = 19;
1504
+ break;
1505
+ }
1506
+ key = _step5.value;
1507
+ _context12.next = 9;
1508
+ return this.kv.lrange(key, 0, -1);
1509
+ case 9:
1510
+ messages = _context12.sent;
1511
+ filteredMessages = messages.filter(function (msg) {
1512
+ return msg.id !== id;
1513
+ });
1514
+ if (!(messages.length !== filteredMessages.length)) {
1515
+ _context12.next = 17;
1516
+ break;
1517
+ }
1518
+ _context12.next = 14;
1519
+ return this.kv.del(key);
1520
+ case 14:
1521
+ if (!(filteredMessages.length > 0)) {
1522
+ _context12.next = 17;
1523
+ break;
1524
+ }
1525
+ _context12.next = 17;
1526
+ return (_this$kv = this.kv).rpush.apply(_this$kv, [key].concat(filteredMessages));
1527
+ case 17:
1528
+ _context12.next = 5;
1529
+ break;
1530
+ case 19:
1531
+ case "end":
1532
+ return _context12.stop();
1533
+ }
1534
+ }, _callee11, this);
1535
+ }));
1536
+ function deleteMessage(_x13) {
1537
+ return _deleteMessage.apply(this, arguments);
1538
+ }
1539
+ return deleteMessage;
1540
+ }()
1541
+ /**
1542
+ * Cleanup
1543
+ */
1544
+ ;
1545
+ _proto.drop =
1546
+ /*#__PURE__*/
1547
+ function () {
1548
+ var _drop = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee12() {
1549
+ var pattern, keys, _this$kv2;
1550
+ return _regeneratorRuntime().wrap(function _callee12$(_context13) {
1551
+ while (1) switch (_context13.prev = _context13.next) {
1552
+ case 0:
1553
+ pattern = this.prefix + ":*";
1554
+ _context13.next = 3;
1555
+ return this.kv.keys(pattern);
1556
+ case 3:
1557
+ keys = _context13.sent;
1558
+ if (!(keys.length > 0)) {
1559
+ _context13.next = 7;
1560
+ break;
1561
+ }
1562
+ _context13.next = 7;
1563
+ return (_this$kv2 = this.kv).del.apply(_this$kv2, keys);
1564
+ case 7:
1565
+ case "end":
1566
+ return _context13.stop();
1567
+ }
1568
+ }, _callee12, this);
1569
+ }));
1570
+ function drop() {
1571
+ return _drop.apply(this, arguments);
1572
+ }
1573
+ return drop;
1574
+ }();
1575
+ _proto.parseThread = function parseThread(thread) {
1576
+ return _extends({}, thread, {
1577
+ createdAt: new Date(thread.createdAt),
1578
+ updatedAt: new Date(thread.updatedAt)
1579
+ });
1580
+ };
1581
+ _proto.parseMessages = function parseMessages(messages) {
1582
+ return messages.map(function (message) {
1583
+ return _extends({}, message, {
1584
+ createdAt: new Date(message.createdAt)
1585
+ });
1586
+ });
1587
+ };
1588
+ return UpstashKVMemory;
1101
1589
  }(core.MastraMemory);
1102
1590
 
1103
1591
  exports.PgMemory = PgMemory;
1592
+ exports.UpstashKVMemory = UpstashKVMemory;
1104
1593
  //# sourceMappingURL=memory.cjs.development.js.map