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

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,100 +549,156 @@ 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;
583
+ hashedArgs = _ref4.hashedArgs;
584
+ _context6.next = 3;
662
585
  return this.ensureTablesExist();
663
- case 4:
664
- _context6.next = 6;
586
+ case 3:
587
+ _context6.next = 5;
665
588
  return this.pool.connect();
666
- case 6:
589
+ case 5:
667
590
  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;
591
+ _context6.prev = 6;
592
+ _context6.next = 9;
593
+ return client.query(" SELECT tool_call_ids as toolCallIds, \n tool_call_args as toolCallArgs,\n created_at AS createdAt\n FROM mastra_messages\n WHERE tool_call_args::jsonb @> $1\n AND tool_call_args_expire_at > $2\n ORDER BY created_at ASC\n LIMIT 1", [JSON.stringify([hashedArgs]), new Date().toISOString()]);
594
+ case 9:
595
+ toolArgsResult = _context6.sent;
596
+ return _context6.abrupt("return", toolArgsResult.rows.length > 0);
597
+ case 13:
598
+ _context6.prev = 13;
599
+ _context6.t0 = _context6["catch"](6);
600
+ console.log('error checking if valid arg exists====', _context6.t0);
601
+ return _context6.abrupt("return", false);
602
+ case 17:
603
+ _context6.prev = 17;
676
604
  client.release();
677
- return _context6.finish(12);
678
- case 15:
605
+ return _context6.finish(17);
606
+ case 20:
679
607
  case "end":
680
608
  return _context6.stop();
681
609
  }
682
- }, _callee6, this, [[7,, 12, 15]]);
610
+ }, _callee6, this, [[6, 13, 17, 20]]);
683
611
  }));
684
- function getThreadById(_x6) {
685
- return _getThreadById.apply(this, arguments);
612
+ function validateToolCallArgs(_x8) {
613
+ return _validateToolCallArgs.apply(this, arguments);
686
614
  }
687
- return getThreadById;
615
+ return validateToolCallArgs;
688
616
  }();
689
- _proto.getThreadsByResourceId = /*#__PURE__*/function () {
690
- var _getThreadsByResourceId = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee7(_ref3) {
691
- var resourceid, client, result;
617
+ _proto.getToolResult = /*#__PURE__*/function () {
618
+ var _getToolResult = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee7(_ref5) {
619
+ var threadId, toolArgs, toolName, client, hashedToolArgs, toolArgsResult, _toolArgsResult$rows$, _toolArgsResult$rows$2, _toolArgsResult$rows$3, _toolResult$rows$, toolCallArgs, toolCallIds, createdAt, toolCallArgsIndex, correspondingToolCallId, toolResult, toolResultContent, requiredToolResult;
692
620
  return _regeneratorRuntime().wrap(function _callee7$(_context7) {
693
621
  while (1) switch (_context7.prev = _context7.next) {
694
622
  case 0:
695
- resourceid = _ref3.resourceid;
623
+ threadId = _ref5.threadId, toolArgs = _ref5.toolArgs, toolName = _ref5.toolName;
696
624
  _context7.next = 3;
697
625
  return this.ensureTablesExist();
698
626
  case 3:
699
- _context7.next = 5;
627
+ console.log('checking for cached tool result====', JSON.stringify(toolArgs, null, 2));
628
+ _context7.next = 6;
700
629
  return this.pool.connect();
701
- case 5:
630
+ case 6:
702
631
  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);
632
+ _context7.prev = 7;
633
+ hashedToolArgs = crypto.createHash('sha256').update(JSON.stringify({
634
+ args: toolArgs,
635
+ threadId: threadId,
636
+ toolName: toolName
637
+ })).digest('hex');
638
+ _context7.next = 11;
639
+ return client.query("SELECT tool_call_ids, \n tool_call_args,\n created_at\n FROM mastra_messages\n WHERE tool_call_args::jsonb @> $1\n AND tool_call_args_expire_at > $2\n ORDER BY created_at ASC\n LIMIT 1", [JSON.stringify([hashedToolArgs]), new Date().toISOString()]);
709
640
  case 11:
710
- _context7.prev = 11;
641
+ toolArgsResult = _context7.sent;
642
+ if (!(toolArgsResult.rows.length > 0)) {
643
+ _context7.next = 28;
644
+ break;
645
+ }
646
+ toolCallArgs = JSON.parse((_toolArgsResult$rows$ = toolArgsResult.rows[0]) == null ? void 0 : _toolArgsResult$rows$.tool_call_args);
647
+ toolCallIds = JSON.parse((_toolArgsResult$rows$2 = toolArgsResult.rows[0]) == null ? void 0 : _toolArgsResult$rows$2.tool_call_ids);
648
+ createdAt = (_toolArgsResult$rows$3 = toolArgsResult.rows[0]) == null ? void 0 : _toolArgsResult$rows$3.created_at;
649
+ toolCallArgsIndex = toolCallArgs.findIndex(function (arg) {
650
+ return arg === hashedToolArgs;
651
+ });
652
+ correspondingToolCallId = toolCallIds[toolCallArgsIndex];
653
+ _context7.next = 20;
654
+ return client.query("SELECT content \n FROM mastra_messages \n WHERE thread_id = $1\n AND tool_call_ids ILIKE $2\n AND type = 'tool-result'\n AND created_at = $3\n LIMIT 1", [threadId, "%" + correspondingToolCallId + "%", new Date(createdAt).toISOString()]);
655
+ case 20:
656
+ toolResult = _context7.sent;
657
+ if (!(toolResult.rows.length === 0)) {
658
+ _context7.next = 24;
659
+ break;
660
+ }
661
+ console.log('no tool result found');
662
+ return _context7.abrupt("return", null);
663
+ case 24:
664
+ toolResultContent = JSON.parse((_toolResult$rows$ = toolResult.rows[0]) == null ? void 0 : _toolResult$rows$.content);
665
+ requiredToolResult = toolResultContent.find(function (part) {
666
+ return part.toolCallId === correspondingToolCallId;
667
+ });
668
+ if (!requiredToolResult) {
669
+ _context7.next = 28;
670
+ break;
671
+ }
672
+ return _context7.abrupt("return", requiredToolResult.result);
673
+ case 28:
674
+ return _context7.abrupt("return", null);
675
+ case 31:
676
+ _context7.prev = 31;
677
+ _context7.t0 = _context7["catch"](7);
678
+ console.log('error getting cached tool result====', _context7.t0);
679
+ return _context7.abrupt("return", null);
680
+ case 35:
681
+ _context7.prev = 35;
711
682
  client.release();
712
- return _context7.finish(11);
713
- case 14:
683
+ return _context7.finish(35);
684
+ case 38:
714
685
  case "end":
715
686
  return _context7.stop();
716
687
  }
717
- }, _callee7, this, [[6,, 11, 14]]);
688
+ }, _callee7, this, [[7, 31, 35, 38]]);
718
689
  }));
719
- function getThreadsByResourceId(_x7) {
720
- return _getThreadsByResourceId.apply(this, arguments);
690
+ function getToolResult(_x9) {
691
+ return _getToolResult.apply(this, arguments);
721
692
  }
722
- return getThreadsByResourceId;
693
+ return getToolResult;
723
694
  }();
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;
695
+ _proto.getContextWindow = /*#__PURE__*/function () {
696
+ var _getContextWindow = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee8(_ref6) {
697
+ var threadId, startDate, endDate, _ref6$format, format, client, _result, result;
727
698
  return _regeneratorRuntime().wrap(function _callee8$(_context8) {
728
699
  while (1) switch (_context8.prev = _context8.next) {
729
700
  case 0:
730
- thread = _ref4.thread;
701
+ threadId = _ref6.threadId, startDate = _ref6.startDate, endDate = _ref6.endDate, _ref6$format = _ref6.format, format = _ref6$format === void 0 ? 'raw' : _ref6$format;
731
702
  _context8.next = 3;
732
703
  return this.ensureTablesExist();
733
704
  case 3:
@@ -736,34 +707,56 @@ var PgMemory = /*#__PURE__*/function (_MastraMemory) {
736
707
  case 5:
737
708
  client = _context8.sent;
738
709
  _context8.prev = 6;
739
- id = thread.id, title = thread.title, createdAt = thread.createdAt, updatedAt = thread.updatedAt, resourceid = thread.resourceid, metadata = thread.metadata;
710
+ if (!this.MAX_CONTEXT_TOKENS) {
711
+ _context8.next = 13;
712
+ break;
713
+ }
740
714
  _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)]);
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 IN ('text', 'tool-result')\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]);
742
716
  case 10:
717
+ _result = _context8.sent;
718
+ console.log('Format', format);
719
+ return _context8.abrupt("return", this.parseMessages(_result.rows));
720
+ case 13:
721
+ _context8.next = 15;
722
+ return client.query("SELECT id, \n content, \n role, \n type,\n created_at AS createdAt, \n thread_id AS threadId\n FROM mastra_messages\n WHERE thread_id = $1\n AND type IN ('text', 'tool-result')\n " + (startDate ? "AND created_at >= '" + startDate.toISOString() + "'" : '') + "\n " + (endDate ? "AND created_at <= '" + endDate.toISOString() + "'" : '') + "\n ORDER BY created_at ASC", [threadId]);
723
+ case 15:
743
724
  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;
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;
747
734
  client.release();
748
- return _context8.finish(12);
749
- case 15:
735
+ return _context8.finish(24);
736
+ case 27:
750
737
  case "end":
751
738
  return _context8.stop();
752
739
  }
753
- }, _callee8, this, [[6,, 12, 15]]);
740
+ }, _callee8, this, [[6, 20, 24, 27]]);
754
741
  }));
755
- function saveThread(_x8) {
756
- return _saveThread.apply(this, arguments);
742
+ function getContextWindow(_x10) {
743
+ return _getContextWindow.apply(this, arguments);
757
744
  }
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;
745
+ return getContextWindow;
746
+ }()
747
+ /**
748
+ * Messages
749
+ */
750
+ ;
751
+ _proto.getMessages =
752
+ /*#__PURE__*/
753
+ function () {
754
+ var _getMessages = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee9(_ref7) {
755
+ var threadId, client, result, messages, uiMessages;
763
756
  return _regeneratorRuntime().wrap(function _callee9$(_context9) {
764
757
  while (1) switch (_context9.prev = _context9.next) {
765
758
  case 0:
766
- hashedToolCallArgs = _ref5.hashedToolCallArgs;
759
+ threadId = _ref7.threadId;
767
760
  _context9.next = 3;
768
761
  return this.ensureTablesExist();
769
762
  case 3:
@@ -773,198 +766,55 @@ var PgMemory = /*#__PURE__*/function (_MastraMemory) {
773
766
  client = _context9.sent;
774
767
  _context9.prev = 6;
775
768
  _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()]);
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]);
777
770
  case 9:
778
- toolArgsResult = _context9.sent;
779
- return _context9.abrupt("return", toolArgsResult.rows.length > 0);
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
+ });
780
778
  case 13:
781
779
  _context9.prev = 13;
782
- _context9.t0 = _context9["catch"](6);
783
- console.log('error checking if valid arg exists====', _context9.t0);
784
- return _context9.abrupt("return", false);
785
- case 17:
786
- _context9.prev = 17;
787
780
  client.release();
788
- return _context9.finish(17);
789
- case 20:
781
+ return _context9.finish(13);
782
+ case 16:
790
783
  case "end":
791
784
  return _context9.stop();
792
785
  }
793
- }, _callee9, this, [[6, 13, 17, 20]]);
786
+ }, _callee9, this, [[6,, 13, 16]]);
794
787
  }));
795
- function checkIfValidArgExists(_x9) {
796
- return _checkIfValidArgExists.apply(this, arguments);
788
+ function getMessages(_x11) {
789
+ return _getMessages.apply(this, arguments);
797
790
  }
798
- return checkIfValidArgExists;
791
+ return getMessages;
799
792
  }();
800
- _proto.getCachedToolResult = /*#__PURE__*/function () {
801
- var _getCachedToolResult = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee10(_ref6) {
802
- var threadId, toolArgs, toolName, client, hashedToolArgs, toolArgsResult, _toolArgsResult$rows$, _toolArgsResult$rows$2, _toolArgsResult$rows$3, _toolResult$rows$, toolCallArgs, toolCallIds, createdAt, toolCallArgsIndex, correspondingToolCallId, toolResult, toolResultContent, requiredToolResult;
803
- return _regeneratorRuntime().wrap(function _callee10$(_context10) {
804
- while (1) switch (_context10.prev = _context10.next) {
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) {
805
799
  case 0:
806
- threadId = _ref6.threadId, toolArgs = _ref6.toolArgs, toolName = _ref6.toolName;
807
- _context10.next = 3;
800
+ messages = _ref8.messages;
801
+ _context11.next = 3;
808
802
  return this.ensureTablesExist();
809
803
  case 3:
810
- console.log('checking for cached tool result====', JSON.stringify(toolArgs, null, 2));
811
- _context10.next = 6;
812
- return this.pool.connect();
813
- case 6:
814
- client = _context10.sent;
815
- _context10.prev = 7;
816
- hashedToolArgs = crypto.createHash('sha256').update(JSON.stringify({
817
- args: toolArgs,
818
- threadId: threadId,
819
- toolName: toolName
820
- })).digest('hex');
821
- console.log('hashedToolArgs====', hashedToolArgs);
822
- _context10.next = 12;
823
- return client.query("SELECT tool_call_ids, \n tool_call_args,\n created_at\n FROM mastra_messages\n WHERE tool_call_args::jsonb @> $1\n AND tool_call_args_expire_at > $2\n ORDER BY created_at ASC\n LIMIT 1", [JSON.stringify([hashedToolArgs]), new Date().toISOString()]);
824
- case 12:
825
- toolArgsResult = _context10.sent;
826
- if (!(toolArgsResult.rows.length > 0)) {
827
- _context10.next = 36;
828
- break;
829
- }
830
- console.log('toolArgsResult====', JSON.stringify(toolArgsResult.rows[0], null, 2));
831
- toolCallArgs = JSON.parse((_toolArgsResult$rows$ = toolArgsResult.rows[0]) == null ? void 0 : _toolArgsResult$rows$.tool_call_args);
832
- toolCallIds = JSON.parse((_toolArgsResult$rows$2 = toolArgsResult.rows[0]) == null ? void 0 : _toolArgsResult$rows$2.tool_call_ids);
833
- createdAt = (_toolArgsResult$rows$3 = toolArgsResult.rows[0]) == null ? void 0 : _toolArgsResult$rows$3.created_at;
834
- console.log('toolCallArgs====', JSON.stringify(toolCallArgs, null, 2));
835
- console.log('toolCallIds====', JSON.stringify(toolCallIds, null, 2));
836
- console.log('createdAt====', createdAt);
837
- toolCallArgsIndex = toolCallArgs.findIndex(function (arg) {
838
- return arg === hashedToolArgs;
839
- });
840
- correspondingToolCallId = toolCallIds[toolCallArgsIndex];
841
- console.log('correspondingToolCallId====', {
842
- correspondingToolCallId: correspondingToolCallId,
843
- toolCallArgsIndex: toolCallArgsIndex
844
- });
845
- _context10.next = 26;
846
- return client.query("SELECT content \n FROM mastra_messages \n WHERE thread_id = $1\n AND tool_call_ids ILIKE $2\n AND type = 'tool-result'\n AND created_at = $3\n LIMIT 1", [threadId, "%" + correspondingToolCallId + "%", new Date(createdAt).toISOString()]);
847
- case 26:
848
- toolResult = _context10.sent;
849
- console.log('called toolResult');
850
- if (!(toolResult.rows.length === 0)) {
851
- _context10.next = 31;
852
- break;
853
- }
854
- console.log('no tool result found');
855
- return _context10.abrupt("return", null);
856
- case 31:
857
- toolResultContent = JSON.parse((_toolResult$rows$ = toolResult.rows[0]) == null ? void 0 : _toolResult$rows$.content);
858
- requiredToolResult = toolResultContent.find(function (part) {
859
- return part.toolCallId === correspondingToolCallId;
860
- });
861
- console.log('requiredToolResult====', JSON.stringify(requiredToolResult, null, 2));
862
- if (!requiredToolResult) {
863
- _context10.next = 36;
864
- break;
865
- }
866
- return _context10.abrupt("return", requiredToolResult.result);
867
- case 36:
868
- return _context10.abrupt("return", null);
869
- case 39:
870
- _context10.prev = 39;
871
- _context10.t0 = _context10["catch"](7);
872
- console.log('error getting cached tool result====', _context10.t0);
873
- return _context10.abrupt("return", null);
874
- case 43:
875
- _context10.prev = 43;
876
- client.release();
877
- return _context10.finish(43);
878
- case 46:
879
- case "end":
880
- return _context10.stop();
881
- }
882
- }, _callee10, this, [[7, 39, 43, 46]]);
883
- }));
884
- function getCachedToolResult(_x10) {
885
- return _getCachedToolResult.apply(this, arguments);
886
- }
887
- return getCachedToolResult;
888
- }();
889
- _proto.getContextWindow = /*#__PURE__*/function () {
890
- var _getContextWindow = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee11(_ref7) {
891
- var threadId, startDate, endDate, client, _result, result;
892
- return _regeneratorRuntime().wrap(function _callee11$(_context11) {
893
- while (1) switch (_context11.prev = _context11.next) {
894
- case 0:
895
- threadId = _ref7.threadId, startDate = _ref7.startDate, endDate = _ref7.endDate;
896
- _context11.next = 3;
897
- return this.ensureTablesExist();
898
- case 3:
899
- console.log('table exists');
900
- _context11.next = 6;
901
- return this.pool.connect();
902
- case 6:
903
- client = _context11.sent;
904
- _context11.prev = 7;
905
- if (!this.MAX_CONTEXT_TOKENS) {
906
- _context11.next = 14;
907
- break;
908
- }
909
- _context11.next = 11;
910
- return client.query("WITH RankedMessages AS (\n SELECT *,\n SUM(tokens) OVER (ORDER BY created_at DESC) as running_total\n FROM mastra_messages\n WHERE thread_id = $1\n AND type = 'text'\n " + (startDate ? "AND created_at >= '" + startDate.toISOString() + "'" : '') + "\n " + (endDate ? "AND created_at <= '" + endDate.toISOString() + "'" : '') + "\n ORDER BY created_at DESC\n )\n SELECT id, \n content, \n role, \n type,\n created_at AS createdAt, \n thread_id AS threadId\n FROM RankedMessages\n WHERE running_total <= $2\n ORDER BY created_at ASC", [threadId, this.MAX_CONTEXT_TOKENS]);
911
- case 11:
912
- _result = _context11.sent;
913
- console.log('result===', JSON.stringify(_result.rows, null, 2));
914
- return _context11.abrupt("return", this.processMessages(_result.rows));
915
- case 14:
916
- _context11.next = 16;
917
- return client.query("SELECT id, \n content, \n role, \n type,\n created_at AS createdAt, \n thread_id AS threadId\n FROM mastra_messages\n WHERE thread_id = $1\n AND type = 'text'\n " + (startDate ? "AND created_at >= '" + startDate.toISOString() + "'" : '') + "\n " + (endDate ? "AND created_at <= '" + endDate.toISOString() + "'" : '') + "\n ORDER BY created_at ASC", [threadId]);
918
- case 16:
919
- result = _context11.sent;
920
- console.log('result===', JSON.stringify(result.rows, null, 2));
921
- return _context11.abrupt("return", this.processMessages(result.rows));
922
- case 21:
923
- _context11.prev = 21;
924
- _context11.t0 = _context11["catch"](7);
925
- console.log('error getting context window====', _context11.t0);
926
- return _context11.abrupt("return", []);
927
- case 25:
928
- _context11.prev = 25;
929
- client.release();
930
- return _context11.finish(25);
931
- case 28:
932
- case "end":
933
- return _context11.stop();
934
- }
935
- }, _callee11, this, [[7, 21, 25, 28]]);
936
- }));
937
- function getContextWindow(_x11) {
938
- return _getContextWindow.apply(this, arguments);
939
- }
940
- 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) {
948
- case 0:
949
- messages = _ref8.messages;
950
- _context13.next = 3;
951
- return this.ensureTablesExist();
952
- 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,747 @@ 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, 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;
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' || msg.type === 'tool-result';
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 = 23;
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
+ return _context8.abrupt("return", this.parseMessages(messagesWithinTokenLimit));
1318
+ case 23:
1319
+ return _context8.abrupt("return", this.parseMessages(filteredMessages));
1320
+ case 24:
1321
+ case "end":
1322
+ return _context8.stop();
1323
+ }
1324
+ }, _callee8, this);
1325
+ }));
1326
+ function getContextWindow(_x10) {
1327
+ return _getContextWindow.apply(this, arguments);
1328
+ }
1329
+ return getContextWindow;
1330
+ }()
1331
+ /**
1332
+ * Messages
1333
+ */
1334
+ ;
1335
+ _proto.getMessages =
1336
+ /*#__PURE__*/
1337
+ function () {
1338
+ var _getMessages = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee9(_ref7) {
1339
+ var threadId, messagesKey, messages, parsedMessages, uiMessages;
1340
+ return _regeneratorRuntime().wrap(function _callee9$(_context9) {
1341
+ while (1) switch (_context9.prev = _context9.next) {
1342
+ case 0:
1343
+ threadId = _ref7.threadId;
1344
+ messagesKey = this.getMessagesKey(threadId);
1345
+ _context9.next = 4;
1346
+ return this.kv.lrange(messagesKey, 0, -1);
1347
+ case 4:
1348
+ messages = _context9.sent;
1349
+ parsedMessages = this.parseMessages(messages);
1350
+ uiMessages = this.convertToUIMessages(parsedMessages);
1351
+ return _context9.abrupt("return", {
1352
+ messages: parsedMessages,
1083
1353
  uiMessages: uiMessages
1084
1354
  });
1085
- case 13:
1086
- _context14.prev = 13;
1087
- client.release();
1088
- return _context14.finish(13);
1089
- case 16:
1355
+ case 8:
1090
1356
  case "end":
1091
- return _context14.stop();
1357
+ return _context9.stop();
1092
1358
  }
1093
- }, _callee13, this, [[6,, 13, 16]]);
1359
+ }, _callee9, this);
1094
1360
  }));
1095
- function getMessages(_x13) {
1361
+ function getMessages(_x11) {
1096
1362
  return _getMessages.apply(this, arguments);
1097
1363
  }
1098
1364
  return getMessages;
1099
1365
  }();
1100
- return PgMemory;
1366
+ _proto.saveMessages = /*#__PURE__*/function () {
1367
+ var _saveMessages = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee10(_ref8) {
1368
+ var _this3 = this;
1369
+ var messages, processedMessages, _loop, _iterator2, _step2;
1370
+ return _regeneratorRuntime().wrap(function _callee10$(_context11) {
1371
+ while (1) switch (_context11.prev = _context11.next) {
1372
+ case 0:
1373
+ messages = _ref8.messages;
1374
+ processedMessages = [];
1375
+ _loop = /*#__PURE__*/_regeneratorRuntime().mark(function _loop() {
1376
+ var message, threadId, toolCallArgs, toolNames, createdAt, messagesKey, processedMessage, _message$content$2, content, hashedToolCallArgs, validArgExists, _iterator3, _step3, hashedArg, isValid, expireAt, _iterator4, _step4, _hashedArg, cacheKey;
1377
+ return _regeneratorRuntime().wrap(function _loop$(_context10) {
1378
+ while (1) switch (_context10.prev = _context10.next) {
1379
+ case 0:
1380
+ message = _step2.value;
1381
+ threadId = message.threadId, toolCallArgs = message.toolCallArgs, toolNames = message.toolNames, createdAt = message.createdAt;
1382
+ messagesKey = _this3.getMessagesKey(threadId);
1383
+ processedMessage = _extends({}, message);
1384
+ if (message.type === 'text') {
1385
+ content = message.role === 'assistant' ? ((_message$content$2 = message.content[0]) == null ? void 0 : _message$content$2.text) || '' : message.content;
1386
+ processedMessage.tokens = _this3.estimateTokens(content);
1387
+ }
1388
+ if (!(toolCallArgs != null && toolCallArgs.length)) {
1389
+ _context10.next = 28;
1390
+ break;
1391
+ }
1392
+ hashedToolCallArgs = toolCallArgs.map(function (args, index) {
1393
+ return crypto.createHash('sha256').update(JSON.stringify({
1394
+ args: args,
1395
+ threadId: threadId,
1396
+ toolName: toolNames == null ? void 0 : toolNames[index]
1397
+ })).digest('hex');
1398
+ });
1399
+ validArgExists = true;
1400
+ _iterator3 = _createForOfIteratorHelperLoose(hashedToolCallArgs);
1401
+ case 9:
1402
+ if ((_step3 = _iterator3()).done) {
1403
+ _context10.next = 19;
1404
+ break;
1405
+ }
1406
+ hashedArg = _step3.value;
1407
+ _context10.next = 13;
1408
+ return _this3.validateToolCallArgs({
1409
+ hashedArgs: hashedArg
1410
+ });
1411
+ case 13:
1412
+ isValid = _context10.sent;
1413
+ if (isValid) {
1414
+ _context10.next = 17;
1415
+ break;
1416
+ }
1417
+ validArgExists = false;
1418
+ return _context10.abrupt("break", 19);
1419
+ case 17:
1420
+ _context10.next = 9;
1421
+ break;
1422
+ case 19:
1423
+ expireAt = validArgExists ? createdAt : new Date(createdAt.getTime() + 5 * 60 * 1000); // 5 minutes
1424
+ _iterator4 = _createForOfIteratorHelperLoose(hashedToolCallArgs);
1425
+ case 21:
1426
+ if ((_step4 = _iterator4()).done) {
1427
+ _context10.next = 28;
1428
+ break;
1429
+ }
1430
+ _hashedArg = _step4.value;
1431
+ cacheKey = _this3.getToolCacheKey(_hashedArg);
1432
+ _context10.next = 26;
1433
+ return _this3.kv.set(cacheKey, {
1434
+ expireAt: expireAt.toISOString()
1435
+ });
1436
+ case 26:
1437
+ _context10.next = 21;
1438
+ break;
1439
+ case 28:
1440
+ _context10.next = 30;
1441
+ return _this3.kv.rpush(messagesKey, processedMessage);
1442
+ case 30:
1443
+ processedMessages.push(processedMessage);
1444
+ case 31:
1445
+ case "end":
1446
+ return _context10.stop();
1447
+ }
1448
+ }, _loop);
1449
+ });
1450
+ _iterator2 = _createForOfIteratorHelperLoose(messages);
1451
+ case 4:
1452
+ if ((_step2 = _iterator2()).done) {
1453
+ _context11.next = 8;
1454
+ break;
1455
+ }
1456
+ return _context11.delegateYield(_loop(), "t0", 6);
1457
+ case 6:
1458
+ _context11.next = 4;
1459
+ break;
1460
+ case 8:
1461
+ return _context11.abrupt("return", processedMessages);
1462
+ case 9:
1463
+ case "end":
1464
+ return _context11.stop();
1465
+ }
1466
+ }, _callee10);
1467
+ }));
1468
+ function saveMessages(_x12) {
1469
+ return _saveMessages.apply(this, arguments);
1470
+ }
1471
+ return saveMessages;
1472
+ }();
1473
+ _proto.deleteMessage = /*#__PURE__*/function () {
1474
+ var _deleteMessage = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee11(id) {
1475
+ var pattern, keys, _iterator5, _step5, key, messages, filteredMessages, _this$kv;
1476
+ return _regeneratorRuntime().wrap(function _callee11$(_context12) {
1477
+ while (1) switch (_context12.prev = _context12.next) {
1478
+ case 0:
1479
+ pattern = this.prefix + ":messages:*";
1480
+ _context12.next = 3;
1481
+ return this.kv.keys(pattern);
1482
+ case 3:
1483
+ keys = _context12.sent;
1484
+ _iterator5 = _createForOfIteratorHelperLoose(keys);
1485
+ case 5:
1486
+ if ((_step5 = _iterator5()).done) {
1487
+ _context12.next = 19;
1488
+ break;
1489
+ }
1490
+ key = _step5.value;
1491
+ _context12.next = 9;
1492
+ return this.kv.lrange(key, 0, -1);
1493
+ case 9:
1494
+ messages = _context12.sent;
1495
+ filteredMessages = messages.filter(function (msg) {
1496
+ return msg.id !== id;
1497
+ });
1498
+ if (!(messages.length !== filteredMessages.length)) {
1499
+ _context12.next = 17;
1500
+ break;
1501
+ }
1502
+ _context12.next = 14;
1503
+ return this.kv.del(key);
1504
+ case 14:
1505
+ if (!(filteredMessages.length > 0)) {
1506
+ _context12.next = 17;
1507
+ break;
1508
+ }
1509
+ _context12.next = 17;
1510
+ return (_this$kv = this.kv).rpush.apply(_this$kv, [key].concat(filteredMessages));
1511
+ case 17:
1512
+ _context12.next = 5;
1513
+ break;
1514
+ case 19:
1515
+ case "end":
1516
+ return _context12.stop();
1517
+ }
1518
+ }, _callee11, this);
1519
+ }));
1520
+ function deleteMessage(_x13) {
1521
+ return _deleteMessage.apply(this, arguments);
1522
+ }
1523
+ return deleteMessage;
1524
+ }()
1525
+ /**
1526
+ * Cleanup
1527
+ */
1528
+ ;
1529
+ _proto.drop =
1530
+ /*#__PURE__*/
1531
+ function () {
1532
+ var _drop = /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee12() {
1533
+ var pattern, keys, _this$kv2;
1534
+ return _regeneratorRuntime().wrap(function _callee12$(_context13) {
1535
+ while (1) switch (_context13.prev = _context13.next) {
1536
+ case 0:
1537
+ pattern = this.prefix + ":*";
1538
+ _context13.next = 3;
1539
+ return this.kv.keys(pattern);
1540
+ case 3:
1541
+ keys = _context13.sent;
1542
+ if (!(keys.length > 0)) {
1543
+ _context13.next = 7;
1544
+ break;
1545
+ }
1546
+ _context13.next = 7;
1547
+ return (_this$kv2 = this.kv).del.apply(_this$kv2, keys);
1548
+ case 7:
1549
+ case "end":
1550
+ return _context13.stop();
1551
+ }
1552
+ }, _callee12, this);
1553
+ }));
1554
+ function drop() {
1555
+ return _drop.apply(this, arguments);
1556
+ }
1557
+ return drop;
1558
+ }();
1559
+ _proto.parseThread = function parseThread(thread) {
1560
+ return _extends({}, thread, {
1561
+ createdAt: new Date(thread.createdAt),
1562
+ updatedAt: new Date(thread.updatedAt)
1563
+ });
1564
+ };
1565
+ _proto.parseMessages = function parseMessages(messages) {
1566
+ return messages.map(function (message) {
1567
+ return _extends({}, message, {
1568
+ createdAt: new Date(message.createdAt)
1569
+ });
1570
+ });
1571
+ };
1572
+ return UpstashKVMemory;
1101
1573
  }(core.MastraMemory);
1102
1574
 
1103
1575
  exports.PgMemory = PgMemory;
1576
+ exports.UpstashKVMemory = UpstashKVMemory;
1104
1577
  //# sourceMappingURL=memory.cjs.development.js.map