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

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