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