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

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