@mastra/dynamodb 0.0.0-share-agent-metadata-with-cloud-20250718123411 → 0.0.0-taofeeq-fix-tool-call-showing-after-message-20250806162745

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.
Files changed (53) hide show
  1. package/dist/entities/eval.d.ts +102 -0
  2. package/dist/entities/eval.d.ts.map +1 -0
  3. package/dist/entities/index.d.ts +746 -0
  4. package/dist/entities/index.d.ts.map +1 -0
  5. package/dist/entities/message.d.ts +100 -0
  6. package/dist/entities/message.d.ts.map +1 -0
  7. package/dist/entities/resource.d.ts +54 -0
  8. package/dist/entities/resource.d.ts.map +1 -0
  9. package/dist/entities/score.d.ts +229 -0
  10. package/dist/entities/score.d.ts.map +1 -0
  11. package/dist/entities/thread.d.ts +69 -0
  12. package/dist/entities/thread.d.ts.map +1 -0
  13. package/dist/entities/trace.d.ts +127 -0
  14. package/dist/entities/trace.d.ts.map +1 -0
  15. package/dist/entities/utils.d.ts +21 -0
  16. package/dist/entities/utils.d.ts.map +1 -0
  17. package/dist/entities/workflow-snapshot.d.ts +74 -0
  18. package/dist/entities/workflow-snapshot.d.ts.map +1 -0
  19. package/dist/index.cjs +2031 -538
  20. package/dist/index.cjs.map +1 -0
  21. package/dist/index.d.ts +2 -2
  22. package/dist/index.d.ts.map +1 -0
  23. package/dist/index.js +2032 -539
  24. package/dist/index.js.map +1 -0
  25. package/dist/storage/domains/legacy-evals/index.d.ts +19 -0
  26. package/dist/storage/domains/legacy-evals/index.d.ts.map +1 -0
  27. package/dist/storage/domains/memory/index.d.ts +81 -0
  28. package/dist/storage/domains/memory/index.d.ts.map +1 -0
  29. package/dist/storage/domains/operations/index.d.ts +69 -0
  30. package/dist/storage/domains/operations/index.d.ts.map +1 -0
  31. package/dist/storage/domains/score/index.d.ts +42 -0
  32. package/dist/storage/domains/score/index.d.ts.map +1 -0
  33. package/dist/storage/domains/traces/index.d.ts +28 -0
  34. package/dist/storage/domains/traces/index.d.ts.map +1 -0
  35. package/dist/storage/domains/workflows/index.d.ts +32 -0
  36. package/dist/storage/domains/workflows/index.d.ts.map +1 -0
  37. package/dist/storage/index.d.ts +220 -0
  38. package/dist/storage/index.d.ts.map +1 -0
  39. package/package.json +12 -11
  40. package/src/entities/index.ts +5 -1
  41. package/src/entities/resource.ts +57 -0
  42. package/src/entities/score.ts +317 -0
  43. package/src/storage/domains/legacy-evals/index.ts +243 -0
  44. package/src/storage/domains/memory/index.ts +931 -0
  45. package/src/storage/domains/operations/index.ts +433 -0
  46. package/src/storage/domains/score/index.ts +288 -0
  47. package/src/storage/domains/traces/index.ts +286 -0
  48. package/src/storage/domains/workflows/index.ts +297 -0
  49. package/src/storage/index.test.ts +1346 -1409
  50. package/src/storage/index.ts +166 -1063
  51. package/dist/_tsup-dts-rollup.d.cts +0 -1160
  52. package/dist/_tsup-dts-rollup.d.ts +0 -1160
  53. package/dist/index.d.cts +0 -2
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
1
  import { DynamoDBClient, DescribeTableCommand } from '@aws-sdk/client-dynamodb';
2
2
  import { DynamoDBDocumentClient } from '@aws-sdk/lib-dynamodb';
3
- import { MessageList } from '@mastra/core/agent';
4
3
  import { MastraError, ErrorCategory, ErrorDomain } from '@mastra/core/error';
5
- import { MastraStorage, TABLE_TRACES, TABLE_EVALS, TABLE_WORKFLOW_SNAPSHOT, TABLE_MESSAGES, TABLE_THREADS } from '@mastra/core/storage';
4
+ import { MastraStorage, StoreOperations, TracesStorage, TABLE_TRACES, WorkflowsStorage, MemoryStorage, resolveMessageLimit, ScoresStorage, LegacyEvalsStorage, TABLE_RESOURCES, TABLE_SCORERS, TABLE_EVALS, TABLE_WORKFLOW_SNAPSHOT, TABLE_MESSAGES, TABLE_THREADS } from '@mastra/core/storage';
6
5
  import { Entity, Service } from 'electrodb';
6
+ import { MessageList } from '@mastra/core/agent';
7
7
 
8
8
  // src/storage/index.ts
9
9
 
@@ -294,9 +294,9 @@ var messageEntity = new Entity({
294
294
  }
295
295
  }
296
296
  });
297
- var threadEntity = new Entity({
297
+ var resourceEntity = new Entity({
298
298
  model: {
299
- entity: "thread",
299
+ entity: "resource",
300
300
  version: "1",
301
301
  service: "mastra"
302
302
  },
@@ -310,25 +310,21 @@ var threadEntity = new Entity({
310
310
  type: "string",
311
311
  required: true
312
312
  },
313
- resourceId: {
314
- type: "string",
315
- required: true
316
- },
317
- title: {
313
+ workingMemory: {
318
314
  type: "string",
319
- required: true
315
+ required: false
320
316
  },
321
317
  metadata: {
322
318
  type: "string",
323
319
  required: false,
324
- // Stringify metadata object on set if it's not already a string
320
+ // Stringify content object on set if it's not already a string
325
321
  set: (value) => {
326
322
  if (value && typeof value !== "string") {
327
323
  return JSON.stringify(value);
328
324
  }
329
325
  return value;
330
326
  },
331
- // Parse JSON string to object on get
327
+ // Parse JSON string to object on get ONLY if it looks like JSON
332
328
  get: (value) => {
333
329
  if (value && typeof value === "string") {
334
330
  try {
@@ -346,18 +342,13 @@ var threadEntity = new Entity({
346
342
  indexes: {
347
343
  primary: {
348
344
  pk: { field: "pk", composite: ["entity", "id"] },
349
- sk: { field: "sk", composite: ["id"] }
350
- },
351
- byResource: {
352
- index: "gsi1",
353
- pk: { field: "gsi1pk", composite: ["entity", "resourceId"] },
354
- sk: { field: "gsi1sk", composite: ["createdAt"] }
345
+ sk: { field: "sk", composite: ["entity"] }
355
346
  }
356
347
  }
357
348
  });
358
- var traceEntity = new Entity({
349
+ var scoreEntity = new Entity({
359
350
  model: {
360
- entity: "trace",
351
+ entity: "score",
361
352
  version: "1",
362
353
  service: "mastra"
363
354
  },
@@ -371,123 +362,306 @@ var traceEntity = new Entity({
371
362
  type: "string",
372
363
  required: true
373
364
  },
374
- parentSpanId: {
365
+ scorerId: {
366
+ type: "string",
367
+ required: true
368
+ },
369
+ traceId: {
375
370
  type: "string",
376
371
  required: false
377
372
  },
378
- name: {
373
+ runId: {
379
374
  type: "string",
380
375
  required: true
381
376
  },
382
- traceId: {
377
+ scorer: {
383
378
  type: "string",
384
- required: true
379
+ required: true,
380
+ set: (value) => {
381
+ if (value && typeof value !== "string") {
382
+ return JSON.stringify(value);
383
+ }
384
+ return value;
385
+ },
386
+ get: (value) => {
387
+ if (value && typeof value === "string") {
388
+ try {
389
+ if (value.startsWith("{") || value.startsWith("[")) {
390
+ return JSON.parse(value);
391
+ }
392
+ } catch {
393
+ return value;
394
+ }
395
+ }
396
+ return value;
397
+ }
385
398
  },
386
- scope: {
399
+ extractStepResult: {
387
400
  type: "string",
388
- required: true
401
+ required: false,
402
+ set: (value) => {
403
+ if (value && typeof value !== "string") {
404
+ return JSON.stringify(value);
405
+ }
406
+ return value;
407
+ },
408
+ get: (value) => {
409
+ if (value && typeof value === "string") {
410
+ try {
411
+ if (value.startsWith("{") || value.startsWith("[")) {
412
+ return JSON.parse(value);
413
+ }
414
+ } catch {
415
+ return value;
416
+ }
417
+ }
418
+ return value;
419
+ }
389
420
  },
390
- kind: {
421
+ preprocessStepResult: {
422
+ type: "string",
423
+ required: false,
424
+ set: (value) => {
425
+ if (value && typeof value !== "string") {
426
+ return JSON.stringify(value);
427
+ }
428
+ return value;
429
+ },
430
+ get: (value) => {
431
+ if (value && typeof value === "string") {
432
+ try {
433
+ if (value.startsWith("{") || value.startsWith("[")) {
434
+ return JSON.parse(value);
435
+ }
436
+ } catch {
437
+ return value;
438
+ }
439
+ }
440
+ return value;
441
+ }
442
+ },
443
+ analyzeStepResult: {
444
+ type: "string",
445
+ required: false,
446
+ set: (value) => {
447
+ if (value && typeof value !== "string") {
448
+ return JSON.stringify(value);
449
+ }
450
+ return value;
451
+ },
452
+ get: (value) => {
453
+ if (value && typeof value === "string") {
454
+ try {
455
+ if (value.startsWith("{") || value.startsWith("[")) {
456
+ return JSON.parse(value);
457
+ }
458
+ } catch {
459
+ return value;
460
+ }
461
+ }
462
+ return value;
463
+ }
464
+ },
465
+ score: {
391
466
  type: "number",
392
467
  required: true
393
468
  },
394
- attributes: {
469
+ reason: {
395
470
  type: "string",
396
- // JSON stringified
397
- required: false,
398
- // Stringify object on set
471
+ required: false
472
+ },
473
+ extractPrompt: {
474
+ type: "string",
475
+ required: false
476
+ },
477
+ analyzePrompt: {
478
+ type: "string",
479
+ required: false
480
+ },
481
+ // Deprecated in favor of generateReasonPrompt
482
+ reasonPrompt: {
483
+ type: "string",
484
+ required: false
485
+ },
486
+ generateScorePrompt: {
487
+ type: "string",
488
+ required: false
489
+ },
490
+ generateReasonPrompt: {
491
+ type: "string",
492
+ required: false
493
+ },
494
+ input: {
495
+ type: "string",
496
+ required: true,
399
497
  set: (value) => {
400
498
  if (value && typeof value !== "string") {
401
499
  return JSON.stringify(value);
402
500
  }
403
501
  return value;
404
502
  },
405
- // Parse JSON string to object on get
406
503
  get: (value) => {
407
- return value ? JSON.parse(value) : value;
504
+ if (value && typeof value === "string") {
505
+ try {
506
+ if (value.startsWith("{") || value.startsWith("[")) {
507
+ return JSON.parse(value);
508
+ }
509
+ } catch {
510
+ return value;
511
+ }
512
+ }
513
+ return value;
408
514
  }
409
515
  },
410
- status: {
516
+ output: {
517
+ type: "string",
518
+ required: true,
519
+ set: (value) => {
520
+ if (value && typeof value !== "string") {
521
+ return JSON.stringify(value);
522
+ }
523
+ return value;
524
+ },
525
+ get: (value) => {
526
+ if (value && typeof value === "string") {
527
+ try {
528
+ if (value.startsWith("{") || value.startsWith("[")) {
529
+ return JSON.parse(value);
530
+ }
531
+ } catch {
532
+ return value;
533
+ }
534
+ }
535
+ return value;
536
+ }
537
+ },
538
+ additionalContext: {
411
539
  type: "string",
412
- // JSON stringified
413
540
  required: false,
414
- // Stringify object on set
415
541
  set: (value) => {
416
542
  if (value && typeof value !== "string") {
417
543
  return JSON.stringify(value);
418
544
  }
419
545
  return value;
420
546
  },
421
- // Parse JSON string to object on get
422
547
  get: (value) => {
548
+ if (value && typeof value === "string") {
549
+ try {
550
+ if (value.startsWith("{") || value.startsWith("[")) {
551
+ return JSON.parse(value);
552
+ }
553
+ } catch {
554
+ return value;
555
+ }
556
+ }
423
557
  return value;
424
558
  }
425
559
  },
426
- events: {
560
+ runtimeContext: {
427
561
  type: "string",
428
- // JSON stringified
429
562
  required: false,
430
- // Stringify object on set
431
563
  set: (value) => {
432
564
  if (value && typeof value !== "string") {
433
565
  return JSON.stringify(value);
434
566
  }
435
567
  return value;
436
568
  },
437
- // Parse JSON string to object on get
438
569
  get: (value) => {
570
+ if (value && typeof value === "string") {
571
+ try {
572
+ if (value.startsWith("{") || value.startsWith("[")) {
573
+ return JSON.parse(value);
574
+ }
575
+ } catch {
576
+ return value;
577
+ }
578
+ }
439
579
  return value;
440
580
  }
441
581
  },
442
- links: {
582
+ entityType: {
583
+ type: "string",
584
+ required: false
585
+ },
586
+ entityData: {
443
587
  type: "string",
444
- // JSON stringified
445
588
  required: false,
446
- // Stringify object on set
447
589
  set: (value) => {
448
590
  if (value && typeof value !== "string") {
449
591
  return JSON.stringify(value);
450
592
  }
451
593
  return value;
452
594
  },
453
- // Parse JSON string to object on get
454
595
  get: (value) => {
596
+ if (value && typeof value === "string") {
597
+ try {
598
+ if (value.startsWith("{") || value.startsWith("[")) {
599
+ return JSON.parse(value);
600
+ }
601
+ } catch {
602
+ return value;
603
+ }
604
+ }
455
605
  return value;
456
606
  }
457
607
  },
458
- other: {
608
+ entityId: {
459
609
  type: "string",
460
610
  required: false
461
611
  },
462
- startTime: {
463
- type: "number",
612
+ source: {
613
+ type: "string",
464
614
  required: true
465
615
  },
466
- endTime: {
467
- type: "number",
468
- required: true
616
+ resourceId: {
617
+ type: "string",
618
+ required: false
619
+ },
620
+ threadId: {
621
+ type: "string",
622
+ required: false
469
623
  }
470
624
  },
471
625
  indexes: {
472
626
  primary: {
473
627
  pk: { field: "pk", composite: ["entity", "id"] },
474
- sk: { field: "sk", composite: [] }
628
+ sk: { field: "sk", composite: ["entity"] }
475
629
  },
476
- byName: {
630
+ byScorer: {
477
631
  index: "gsi1",
478
- pk: { field: "gsi1pk", composite: ["entity", "name"] },
479
- sk: { field: "gsi1sk", composite: ["startTime"] }
632
+ pk: { field: "gsi1pk", composite: ["entity", "scorerId"] },
633
+ sk: { field: "gsi1sk", composite: ["createdAt"] }
480
634
  },
481
- byScope: {
635
+ byRun: {
482
636
  index: "gsi2",
483
- pk: { field: "gsi2pk", composite: ["entity", "scope"] },
484
- sk: { field: "gsi2sk", composite: ["startTime"] }
637
+ pk: { field: "gsi2pk", composite: ["entity", "runId"] },
638
+ sk: { field: "gsi2sk", composite: ["createdAt"] }
639
+ },
640
+ byTrace: {
641
+ index: "gsi3",
642
+ pk: { field: "gsi3pk", composite: ["entity", "traceId"] },
643
+ sk: { field: "gsi3sk", composite: ["createdAt"] }
644
+ },
645
+ byEntityData: {
646
+ index: "gsi4",
647
+ pk: { field: "gsi4pk", composite: ["entity", "entityId"] },
648
+ sk: { field: "gsi4sk", composite: ["createdAt"] }
649
+ },
650
+ byResource: {
651
+ index: "gsi5",
652
+ pk: { field: "gsi5pk", composite: ["entity", "resourceId"] },
653
+ sk: { field: "gsi5sk", composite: ["createdAt"] }
654
+ },
655
+ byThread: {
656
+ index: "gsi6",
657
+ pk: { field: "gsi6pk", composite: ["entity", "threadId"] },
658
+ sk: { field: "gsi6sk", composite: ["createdAt"] }
485
659
  }
486
660
  }
487
661
  });
488
- var workflowSnapshotEntity = new Entity({
662
+ var threadEntity = new Entity({
489
663
  model: {
490
- entity: "workflow_snapshot",
664
+ entity: "thread",
491
665
  version: "1",
492
666
  service: "mastra"
493
667
  },
@@ -497,18 +671,209 @@ var workflowSnapshotEntity = new Entity({
497
671
  required: true
498
672
  },
499
673
  ...baseAttributes,
500
- workflow_name: {
674
+ id: {
501
675
  type: "string",
502
676
  required: true
503
677
  },
504
- run_id: {
678
+ resourceId: {
505
679
  type: "string",
506
680
  required: true
507
681
  },
508
- snapshot: {
682
+ title: {
509
683
  type: "string",
510
- // JSON stringified
511
- required: true,
684
+ required: true
685
+ },
686
+ metadata: {
687
+ type: "string",
688
+ required: false,
689
+ // Stringify metadata object on set if it's not already a string
690
+ set: (value) => {
691
+ if (value && typeof value !== "string") {
692
+ return JSON.stringify(value);
693
+ }
694
+ return value;
695
+ },
696
+ // Parse JSON string to object on get
697
+ get: (value) => {
698
+ if (value && typeof value === "string") {
699
+ try {
700
+ if (value.startsWith("{") || value.startsWith("[")) {
701
+ return JSON.parse(value);
702
+ }
703
+ } catch {
704
+ return value;
705
+ }
706
+ }
707
+ return value;
708
+ }
709
+ }
710
+ },
711
+ indexes: {
712
+ primary: {
713
+ pk: { field: "pk", composite: ["entity", "id"] },
714
+ sk: { field: "sk", composite: ["id"] }
715
+ },
716
+ byResource: {
717
+ index: "gsi1",
718
+ pk: { field: "gsi1pk", composite: ["entity", "resourceId"] },
719
+ sk: { field: "gsi1sk", composite: ["createdAt"] }
720
+ }
721
+ }
722
+ });
723
+ var traceEntity = new Entity({
724
+ model: {
725
+ entity: "trace",
726
+ version: "1",
727
+ service: "mastra"
728
+ },
729
+ attributes: {
730
+ entity: {
731
+ type: "string",
732
+ required: true
733
+ },
734
+ ...baseAttributes,
735
+ id: {
736
+ type: "string",
737
+ required: true
738
+ },
739
+ parentSpanId: {
740
+ type: "string",
741
+ required: false
742
+ },
743
+ name: {
744
+ type: "string",
745
+ required: true
746
+ },
747
+ traceId: {
748
+ type: "string",
749
+ required: true
750
+ },
751
+ scope: {
752
+ type: "string",
753
+ required: true
754
+ },
755
+ kind: {
756
+ type: "number",
757
+ required: true
758
+ },
759
+ attributes: {
760
+ type: "string",
761
+ // JSON stringified
762
+ required: false,
763
+ // Stringify object on set
764
+ set: (value) => {
765
+ if (value && typeof value !== "string") {
766
+ return JSON.stringify(value);
767
+ }
768
+ return value;
769
+ },
770
+ // Parse JSON string to object on get
771
+ get: (value) => {
772
+ return value ? JSON.parse(value) : value;
773
+ }
774
+ },
775
+ status: {
776
+ type: "string",
777
+ // JSON stringified
778
+ required: false,
779
+ // Stringify object on set
780
+ set: (value) => {
781
+ if (value && typeof value !== "string") {
782
+ return JSON.stringify(value);
783
+ }
784
+ return value;
785
+ },
786
+ // Parse JSON string to object on get
787
+ get: (value) => {
788
+ return value;
789
+ }
790
+ },
791
+ events: {
792
+ type: "string",
793
+ // JSON stringified
794
+ required: false,
795
+ // Stringify object on set
796
+ set: (value) => {
797
+ if (value && typeof value !== "string") {
798
+ return JSON.stringify(value);
799
+ }
800
+ return value;
801
+ },
802
+ // Parse JSON string to object on get
803
+ get: (value) => {
804
+ return value;
805
+ }
806
+ },
807
+ links: {
808
+ type: "string",
809
+ // JSON stringified
810
+ required: false,
811
+ // Stringify object on set
812
+ set: (value) => {
813
+ if (value && typeof value !== "string") {
814
+ return JSON.stringify(value);
815
+ }
816
+ return value;
817
+ },
818
+ // Parse JSON string to object on get
819
+ get: (value) => {
820
+ return value;
821
+ }
822
+ },
823
+ other: {
824
+ type: "string",
825
+ required: false
826
+ },
827
+ startTime: {
828
+ type: "number",
829
+ required: true
830
+ },
831
+ endTime: {
832
+ type: "number",
833
+ required: true
834
+ }
835
+ },
836
+ indexes: {
837
+ primary: {
838
+ pk: { field: "pk", composite: ["entity", "id"] },
839
+ sk: { field: "sk", composite: [] }
840
+ },
841
+ byName: {
842
+ index: "gsi1",
843
+ pk: { field: "gsi1pk", composite: ["entity", "name"] },
844
+ sk: { field: "gsi1sk", composite: ["startTime"] }
845
+ },
846
+ byScope: {
847
+ index: "gsi2",
848
+ pk: { field: "gsi2pk", composite: ["entity", "scope"] },
849
+ sk: { field: "gsi2sk", composite: ["startTime"] }
850
+ }
851
+ }
852
+ });
853
+ var workflowSnapshotEntity = new Entity({
854
+ model: {
855
+ entity: "workflow_snapshot",
856
+ version: "1",
857
+ service: "mastra"
858
+ },
859
+ attributes: {
860
+ entity: {
861
+ type: "string",
862
+ required: true
863
+ },
864
+ ...baseAttributes,
865
+ workflow_name: {
866
+ type: "string",
867
+ required: true
868
+ },
869
+ run_id: {
870
+ type: "string",
871
+ required: true
872
+ },
873
+ snapshot: {
874
+ type: "string",
875
+ // JSON stringified
876
+ required: true,
512
877
  // Stringify snapshot object on set
513
878
  set: (value) => {
514
879
  if (value && typeof value !== "string") {
@@ -538,94 +903,959 @@ var workflowSnapshotEntity = new Entity({
538
903
  sk: { field: "gsi2sk", composite: ["workflow_name"] }
539
904
  }
540
905
  }
541
- });
542
-
543
- // src/entities/index.ts
544
- function getElectroDbService(client, tableName) {
545
- return new Service(
546
- {
547
- thread: threadEntity,
548
- message: messageEntity,
549
- eval: evalEntity,
550
- trace: traceEntity,
551
- workflowSnapshot: workflowSnapshotEntity
552
- },
553
- {
554
- client,
555
- table: tableName
556
- }
557
- );
558
- }
559
-
560
- // src/storage/index.ts
561
- var DynamoDBStore = class extends MastraStorage {
562
- tableName;
563
- client;
564
- service;
565
- hasInitialized = null;
566
- constructor({ name, config }) {
567
- super({ name });
906
+ });
907
+
908
+ // src/entities/index.ts
909
+ function getElectroDbService(client, tableName) {
910
+ return new Service(
911
+ {
912
+ thread: threadEntity,
913
+ message: messageEntity,
914
+ eval: evalEntity,
915
+ trace: traceEntity,
916
+ workflow_snapshot: workflowSnapshotEntity,
917
+ resource: resourceEntity,
918
+ score: scoreEntity
919
+ },
920
+ {
921
+ client,
922
+ table: tableName
923
+ }
924
+ );
925
+ }
926
+ var LegacyEvalsDynamoDB = class extends LegacyEvalsStorage {
927
+ service;
928
+ tableName;
929
+ constructor({ service, tableName }) {
930
+ super();
931
+ this.service = service;
932
+ this.tableName = tableName;
933
+ }
934
+ // Eval operations
935
+ async getEvalsByAgentName(agentName, type) {
936
+ this.logger.debug("Getting evals for agent", { agentName, type });
937
+ try {
938
+ const query = this.service.entities.eval.query.byAgent({ entity: "eval", agent_name: agentName });
939
+ const results = await query.go({ order: "desc", limit: 100 });
940
+ if (!results.data.length) {
941
+ return [];
942
+ }
943
+ let filteredData = results.data;
944
+ if (type) {
945
+ filteredData = filteredData.filter((evalRecord) => {
946
+ try {
947
+ const testInfo = evalRecord.test_info && typeof evalRecord.test_info === "string" ? JSON.parse(evalRecord.test_info) : void 0;
948
+ if (type === "test" && !testInfo) {
949
+ return false;
950
+ }
951
+ if (type === "live" && testInfo) {
952
+ return false;
953
+ }
954
+ } catch (e) {
955
+ this.logger.warn("Failed to parse test_info during filtering", { record: evalRecord, error: e });
956
+ }
957
+ return true;
958
+ });
959
+ }
960
+ return filteredData.map((evalRecord) => {
961
+ try {
962
+ return {
963
+ input: evalRecord.input,
964
+ output: evalRecord.output,
965
+ // Safely parse result and test_info
966
+ result: evalRecord.result && typeof evalRecord.result === "string" ? JSON.parse(evalRecord.result) : void 0,
967
+ agentName: evalRecord.agent_name,
968
+ createdAt: evalRecord.created_at,
969
+ // Keep as string from DDB?
970
+ metricName: evalRecord.metric_name,
971
+ instructions: evalRecord.instructions,
972
+ runId: evalRecord.run_id,
973
+ globalRunId: evalRecord.global_run_id,
974
+ testInfo: evalRecord.test_info && typeof evalRecord.test_info === "string" ? JSON.parse(evalRecord.test_info) : void 0
975
+ };
976
+ } catch (parseError) {
977
+ this.logger.error("Failed to parse eval record", { record: evalRecord, error: parseError });
978
+ return {
979
+ agentName: evalRecord.agent_name,
980
+ createdAt: evalRecord.created_at,
981
+ runId: evalRecord.run_id,
982
+ globalRunId: evalRecord.global_run_id
983
+ };
984
+ }
985
+ });
986
+ } catch (error) {
987
+ throw new MastraError(
988
+ {
989
+ id: "STORAGE_DYNAMODB_STORE_GET_EVALS_BY_AGENT_NAME_FAILED",
990
+ domain: ErrorDomain.STORAGE,
991
+ category: ErrorCategory.THIRD_PARTY,
992
+ details: { agentName }
993
+ },
994
+ error
995
+ );
996
+ }
997
+ }
998
+ async getEvals(options = {}) {
999
+ const { agentName, type, page = 0, perPage = 100, dateRange } = options;
1000
+ this.logger.debug("Getting evals with pagination", { agentName, type, page, perPage, dateRange });
1001
+ try {
1002
+ let query;
1003
+ if (agentName) {
1004
+ query = this.service.entities.eval.query.byAgent({ entity: "eval", agent_name: agentName });
1005
+ } else {
1006
+ query = this.service.entities.eval.query.byEntity({ entity: "eval" });
1007
+ }
1008
+ const results = await query.go({
1009
+ order: "desc",
1010
+ pages: "all"
1011
+ // Get all pages to apply filtering and pagination
1012
+ });
1013
+ if (!results.data.length) {
1014
+ return {
1015
+ evals: [],
1016
+ total: 0,
1017
+ page,
1018
+ perPage,
1019
+ hasMore: false
1020
+ };
1021
+ }
1022
+ let filteredData = results.data;
1023
+ if (type) {
1024
+ filteredData = filteredData.filter((evalRecord) => {
1025
+ try {
1026
+ const testInfo = evalRecord.test_info && typeof evalRecord.test_info === "string" ? JSON.parse(evalRecord.test_info) : void 0;
1027
+ if (type === "test" && !testInfo) {
1028
+ return false;
1029
+ }
1030
+ if (type === "live" && testInfo) {
1031
+ return false;
1032
+ }
1033
+ } catch (e) {
1034
+ this.logger.warn("Failed to parse test_info during filtering", { record: evalRecord, error: e });
1035
+ }
1036
+ return true;
1037
+ });
1038
+ }
1039
+ if (dateRange) {
1040
+ const fromDate = dateRange.start;
1041
+ const toDate = dateRange.end;
1042
+ filteredData = filteredData.filter((evalRecord) => {
1043
+ const recordDate = new Date(evalRecord.created_at);
1044
+ if (fromDate && recordDate < fromDate) {
1045
+ return false;
1046
+ }
1047
+ if (toDate && recordDate > toDate) {
1048
+ return false;
1049
+ }
1050
+ return true;
1051
+ });
1052
+ }
1053
+ const total = filteredData.length;
1054
+ const start = page * perPage;
1055
+ const end = start + perPage;
1056
+ const paginatedData = filteredData.slice(start, end);
1057
+ const evals = paginatedData.map((evalRecord) => {
1058
+ try {
1059
+ return {
1060
+ input: evalRecord.input,
1061
+ output: evalRecord.output,
1062
+ result: evalRecord.result && typeof evalRecord.result === "string" ? JSON.parse(evalRecord.result) : void 0,
1063
+ agentName: evalRecord.agent_name,
1064
+ createdAt: evalRecord.created_at,
1065
+ metricName: evalRecord.metric_name,
1066
+ instructions: evalRecord.instructions,
1067
+ runId: evalRecord.run_id,
1068
+ globalRunId: evalRecord.global_run_id,
1069
+ testInfo: evalRecord.test_info && typeof evalRecord.test_info === "string" ? JSON.parse(evalRecord.test_info) : void 0
1070
+ };
1071
+ } catch (parseError) {
1072
+ this.logger.error("Failed to parse eval record", { record: evalRecord, error: parseError });
1073
+ return {
1074
+ agentName: evalRecord.agent_name,
1075
+ createdAt: evalRecord.created_at,
1076
+ runId: evalRecord.run_id,
1077
+ globalRunId: evalRecord.global_run_id
1078
+ };
1079
+ }
1080
+ });
1081
+ const hasMore = end < total;
1082
+ return {
1083
+ evals,
1084
+ total,
1085
+ page,
1086
+ perPage,
1087
+ hasMore
1088
+ };
1089
+ } catch (error) {
1090
+ throw new MastraError(
1091
+ {
1092
+ id: "STORAGE_DYNAMODB_STORE_GET_EVALS_FAILED",
1093
+ domain: ErrorDomain.STORAGE,
1094
+ category: ErrorCategory.THIRD_PARTY,
1095
+ details: {
1096
+ agentName: agentName || "all",
1097
+ type: type || "all",
1098
+ page,
1099
+ perPage
1100
+ }
1101
+ },
1102
+ error
1103
+ );
1104
+ }
1105
+ }
1106
+ };
1107
+ var MemoryStorageDynamoDB = class extends MemoryStorage {
1108
+ service;
1109
+ constructor({ service }) {
1110
+ super();
1111
+ this.service = service;
1112
+ }
1113
+ // Helper function to parse message data (handle JSON fields)
1114
+ parseMessageData(data) {
1115
+ return {
1116
+ ...data,
1117
+ // Ensure dates are Date objects if needed (ElectroDB might return strings)
1118
+ createdAt: data.createdAt ? new Date(data.createdAt) : void 0,
1119
+ updatedAt: data.updatedAt ? new Date(data.updatedAt) : void 0
1120
+ // Other fields like content, toolCallArgs etc. are assumed to be correctly
1121
+ // transformed by the ElectroDB entity getters.
1122
+ };
1123
+ }
1124
+ // Helper function to transform and sort threads
1125
+ transformAndSortThreads(rawThreads, orderBy, sortDirection) {
1126
+ return rawThreads.map((data) => ({
1127
+ ...data,
1128
+ // Convert date strings back to Date objects for consistency
1129
+ createdAt: typeof data.createdAt === "string" ? new Date(data.createdAt) : data.createdAt,
1130
+ updatedAt: typeof data.updatedAt === "string" ? new Date(data.updatedAt) : data.updatedAt
1131
+ })).sort((a, b) => {
1132
+ const fieldA = orderBy === "createdAt" ? a.createdAt : a.updatedAt;
1133
+ const fieldB = orderBy === "createdAt" ? b.createdAt : b.updatedAt;
1134
+ const comparison = fieldA.getTime() - fieldB.getTime();
1135
+ return sortDirection === "DESC" ? -comparison : comparison;
1136
+ });
1137
+ }
1138
+ async getThreadById({ threadId }) {
1139
+ this.logger.debug("Getting thread by ID", { threadId });
1140
+ try {
1141
+ const result = await this.service.entities.thread.get({ entity: "thread", id: threadId }).go();
1142
+ if (!result.data) {
1143
+ return null;
1144
+ }
1145
+ const data = result.data;
1146
+ return {
1147
+ ...data,
1148
+ // Convert date strings back to Date objects for consistency
1149
+ createdAt: typeof data.createdAt === "string" ? new Date(data.createdAt) : data.createdAt,
1150
+ updatedAt: typeof data.updatedAt === "string" ? new Date(data.updatedAt) : data.updatedAt
1151
+ // metadata: data.metadata ? JSON.parse(data.metadata) : undefined, // REMOVED by AI
1152
+ // metadata is already transformed by the entity's getter
1153
+ };
1154
+ } catch (error) {
1155
+ throw new MastraError(
1156
+ {
1157
+ id: "STORAGE_DYNAMODB_STORE_GET_THREAD_BY_ID_FAILED",
1158
+ domain: ErrorDomain.STORAGE,
1159
+ category: ErrorCategory.THIRD_PARTY,
1160
+ details: { threadId }
1161
+ },
1162
+ error
1163
+ );
1164
+ }
1165
+ }
1166
+ /**
1167
+ * @deprecated use getThreadsByResourceIdPaginated instead for paginated results.
1168
+ */
1169
+ async getThreadsByResourceId(args) {
1170
+ const resourceId = args.resourceId;
1171
+ const orderBy = this.castThreadOrderBy(args.orderBy);
1172
+ const sortDirection = this.castThreadSortDirection(args.sortDirection);
1173
+ this.logger.debug("Getting threads by resource ID", { resourceId, orderBy, sortDirection });
1174
+ try {
1175
+ const result = await this.service.entities.thread.query.byResource({ entity: "thread", resourceId }).go();
1176
+ if (!result.data.length) {
1177
+ return [];
1178
+ }
1179
+ return this.transformAndSortThreads(result.data, orderBy, sortDirection);
1180
+ } catch (error) {
1181
+ throw new MastraError(
1182
+ {
1183
+ id: "STORAGE_DYNAMODB_STORE_GET_THREADS_BY_RESOURCE_ID_FAILED",
1184
+ domain: ErrorDomain.STORAGE,
1185
+ category: ErrorCategory.THIRD_PARTY,
1186
+ details: { resourceId }
1187
+ },
1188
+ error
1189
+ );
1190
+ }
1191
+ }
1192
+ async saveThread({ thread }) {
1193
+ this.logger.debug("Saving thread", { threadId: thread.id });
1194
+ const now = /* @__PURE__ */ new Date();
1195
+ const threadData = {
1196
+ entity: "thread",
1197
+ id: thread.id,
1198
+ resourceId: thread.resourceId,
1199
+ title: thread.title || `Thread ${thread.id}`,
1200
+ createdAt: thread.createdAt?.toISOString() || now.toISOString(),
1201
+ updatedAt: now.toISOString(),
1202
+ metadata: thread.metadata ? JSON.stringify(thread.metadata) : void 0
1203
+ };
1204
+ try {
1205
+ await this.service.entities.thread.upsert(threadData).go();
1206
+ return {
1207
+ id: thread.id,
1208
+ resourceId: thread.resourceId,
1209
+ title: threadData.title,
1210
+ createdAt: thread.createdAt || now,
1211
+ updatedAt: now,
1212
+ metadata: thread.metadata
1213
+ };
1214
+ } catch (error) {
1215
+ throw new MastraError(
1216
+ {
1217
+ id: "STORAGE_DYNAMODB_STORE_SAVE_THREAD_FAILED",
1218
+ domain: ErrorDomain.STORAGE,
1219
+ category: ErrorCategory.THIRD_PARTY,
1220
+ details: { threadId: thread.id }
1221
+ },
1222
+ error
1223
+ );
1224
+ }
1225
+ }
1226
+ async updateThread({
1227
+ id,
1228
+ title,
1229
+ metadata
1230
+ }) {
1231
+ this.logger.debug("Updating thread", { threadId: id });
1232
+ try {
1233
+ const existingThread = await this.getThreadById({ threadId: id });
1234
+ if (!existingThread) {
1235
+ throw new Error(`Thread not found: ${id}`);
1236
+ }
1237
+ const now = /* @__PURE__ */ new Date();
1238
+ const updateData = {
1239
+ updatedAt: now.toISOString()
1240
+ };
1241
+ if (title) {
1242
+ updateData.title = title;
1243
+ }
1244
+ if (metadata) {
1245
+ const existingMetadata = existingThread.metadata ? typeof existingThread.metadata === "string" ? JSON.parse(existingThread.metadata) : existingThread.metadata : {};
1246
+ const mergedMetadata = { ...existingMetadata, ...metadata };
1247
+ updateData.metadata = JSON.stringify(mergedMetadata);
1248
+ }
1249
+ await this.service.entities.thread.update({ entity: "thread", id }).set(updateData).go();
1250
+ return {
1251
+ ...existingThread,
1252
+ title: title || existingThread.title,
1253
+ metadata: metadata ? { ...existingThread.metadata, ...metadata } : existingThread.metadata,
1254
+ updatedAt: now
1255
+ };
1256
+ } catch (error) {
1257
+ throw new MastraError(
1258
+ {
1259
+ id: "STORAGE_DYNAMODB_STORE_UPDATE_THREAD_FAILED",
1260
+ domain: ErrorDomain.STORAGE,
1261
+ category: ErrorCategory.THIRD_PARTY,
1262
+ details: { threadId: id }
1263
+ },
1264
+ error
1265
+ );
1266
+ }
1267
+ }
1268
+ async deleteThread({ threadId }) {
1269
+ this.logger.debug("Deleting thread", { threadId });
1270
+ try {
1271
+ const messages = await this.getMessages({ threadId });
1272
+ if (messages.length > 0) {
1273
+ const batchSize = 25;
1274
+ for (let i = 0; i < messages.length; i += batchSize) {
1275
+ const batch = messages.slice(i, i + batchSize);
1276
+ await Promise.all(
1277
+ batch.map(
1278
+ (message) => this.service.entities.message.delete({
1279
+ entity: "message",
1280
+ id: message.id,
1281
+ threadId: message.threadId
1282
+ }).go()
1283
+ )
1284
+ );
1285
+ }
1286
+ }
1287
+ await this.service.entities.thread.delete({ entity: "thread", id: threadId }).go();
1288
+ } catch (error) {
1289
+ throw new MastraError(
1290
+ {
1291
+ id: "STORAGE_DYNAMODB_STORE_DELETE_THREAD_FAILED",
1292
+ domain: ErrorDomain.STORAGE,
1293
+ category: ErrorCategory.THIRD_PARTY,
1294
+ details: { threadId }
1295
+ },
1296
+ error
1297
+ );
1298
+ }
1299
+ }
1300
+ async getMessages({
1301
+ threadId,
1302
+ resourceId,
1303
+ selectBy,
1304
+ format
1305
+ }) {
1306
+ this.logger.debug("Getting messages", { threadId, selectBy });
1307
+ try {
1308
+ const messages = [];
1309
+ const limit = resolveMessageLimit({ last: selectBy?.last, defaultLimit: Number.MAX_SAFE_INTEGER });
1310
+ if (selectBy?.include?.length) {
1311
+ const includeMessages = await this._getIncludedMessages(threadId, selectBy);
1312
+ if (includeMessages) {
1313
+ messages.push(...includeMessages);
1314
+ }
1315
+ }
1316
+ if (limit !== 0) {
1317
+ const query = this.service.entities.message.query.byThread({ entity: "message", threadId });
1318
+ let results;
1319
+ if (limit !== Number.MAX_SAFE_INTEGER && limit > 0) {
1320
+ results = await query.go({ limit, order: "desc" });
1321
+ results.data = results.data.reverse();
1322
+ } else {
1323
+ results = await query.go();
1324
+ }
1325
+ let allThreadMessages = results.data.map((data) => this.parseMessageData(data)).filter((msg) => "content" in msg);
1326
+ allThreadMessages.sort((a, b) => {
1327
+ const timeA = a.createdAt.getTime();
1328
+ const timeB = b.createdAt.getTime();
1329
+ if (timeA === timeB) {
1330
+ return a.id.localeCompare(b.id);
1331
+ }
1332
+ return timeA - timeB;
1333
+ });
1334
+ messages.push(...allThreadMessages);
1335
+ }
1336
+ messages.sort((a, b) => {
1337
+ const timeA = a.createdAt.getTime();
1338
+ const timeB = b.createdAt.getTime();
1339
+ if (timeA === timeB) {
1340
+ return a.id.localeCompare(b.id);
1341
+ }
1342
+ return timeA - timeB;
1343
+ });
1344
+ const uniqueMessages = messages.filter(
1345
+ (message, index, self) => index === self.findIndex((m) => m.id === message.id)
1346
+ );
1347
+ const list = new MessageList({ threadId, resourceId }).add(uniqueMessages, "memory");
1348
+ if (format === `v2`) return list.get.all.v2();
1349
+ return list.get.all.v1();
1350
+ } catch (error) {
1351
+ throw new MastraError(
1352
+ {
1353
+ id: "STORAGE_DYNAMODB_STORE_GET_MESSAGES_FAILED",
1354
+ domain: ErrorDomain.STORAGE,
1355
+ category: ErrorCategory.THIRD_PARTY,
1356
+ details: { threadId }
1357
+ },
1358
+ error
1359
+ );
1360
+ }
1361
+ }
1362
+ async saveMessages(args) {
1363
+ const { messages, format = "v1" } = args;
1364
+ this.logger.debug("Saving messages", { count: messages.length });
1365
+ if (!messages.length) {
1366
+ return [];
1367
+ }
1368
+ const threadId = messages[0]?.threadId;
1369
+ if (!threadId) {
1370
+ throw new Error("Thread ID is required");
1371
+ }
1372
+ const messagesToSave = messages.map((msg) => {
1373
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1374
+ return {
1375
+ entity: "message",
1376
+ // Add entity type
1377
+ id: msg.id,
1378
+ threadId: msg.threadId,
1379
+ role: msg.role,
1380
+ type: msg.type,
1381
+ resourceId: msg.resourceId,
1382
+ // Ensure complex fields are stringified if not handled by attribute setters
1383
+ content: typeof msg.content === "string" ? msg.content : JSON.stringify(msg.content),
1384
+ toolCallArgs: `toolCallArgs` in msg && msg.toolCallArgs ? JSON.stringify(msg.toolCallArgs) : void 0,
1385
+ toolCallIds: `toolCallIds` in msg && msg.toolCallIds ? JSON.stringify(msg.toolCallIds) : void 0,
1386
+ toolNames: `toolNames` in msg && msg.toolNames ? JSON.stringify(msg.toolNames) : void 0,
1387
+ createdAt: msg.createdAt instanceof Date ? msg.createdAt.toISOString() : msg.createdAt || now,
1388
+ updatedAt: now
1389
+ // Add updatedAt
1390
+ };
1391
+ });
1392
+ try {
1393
+ const savedMessageIds = [];
1394
+ for (const messageData of messagesToSave) {
1395
+ if (!messageData.entity) {
1396
+ this.logger.error("Missing entity property in message data for create", { messageData });
1397
+ throw new Error("Internal error: Missing entity property during saveMessages");
1398
+ }
1399
+ try {
1400
+ await this.service.entities.message.put(messageData).go();
1401
+ savedMessageIds.push(messageData.id);
1402
+ } catch (error) {
1403
+ for (const savedId of savedMessageIds) {
1404
+ try {
1405
+ await this.service.entities.message.delete({ entity: "message", id: savedId }).go();
1406
+ } catch (rollbackError) {
1407
+ this.logger.error("Failed to rollback message during save error", {
1408
+ messageId: savedId,
1409
+ error: rollbackError
1410
+ });
1411
+ }
1412
+ }
1413
+ throw error;
1414
+ }
1415
+ }
1416
+ await this.service.entities.thread.update({ entity: "thread", id: threadId }).set({
1417
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
1418
+ }).go();
1419
+ const list = new MessageList().add(messages, "memory");
1420
+ if (format === `v1`) return list.get.all.v1();
1421
+ return list.get.all.v2();
1422
+ } catch (error) {
1423
+ throw new MastraError(
1424
+ {
1425
+ id: "STORAGE_DYNAMODB_STORE_SAVE_MESSAGES_FAILED",
1426
+ domain: ErrorDomain.STORAGE,
1427
+ category: ErrorCategory.THIRD_PARTY,
1428
+ details: { count: messages.length }
1429
+ },
1430
+ error
1431
+ );
1432
+ }
1433
+ }
1434
+ async getThreadsByResourceIdPaginated(args) {
1435
+ const { resourceId, page = 0, perPage = 100 } = args;
1436
+ const orderBy = this.castThreadOrderBy(args.orderBy);
1437
+ const sortDirection = this.castThreadSortDirection(args.sortDirection);
1438
+ this.logger.debug("Getting threads by resource ID with pagination", {
1439
+ resourceId,
1440
+ page,
1441
+ perPage,
1442
+ orderBy,
1443
+ sortDirection
1444
+ });
1445
+ try {
1446
+ const query = this.service.entities.thread.query.byResource({ entity: "thread", resourceId });
1447
+ const results = await query.go();
1448
+ const allThreads = this.transformAndSortThreads(results.data, orderBy, sortDirection);
1449
+ const startIndex = page * perPage;
1450
+ const endIndex = startIndex + perPage;
1451
+ const paginatedThreads = allThreads.slice(startIndex, endIndex);
1452
+ const total = allThreads.length;
1453
+ const hasMore = endIndex < total;
1454
+ return {
1455
+ threads: paginatedThreads,
1456
+ total,
1457
+ page,
1458
+ perPage,
1459
+ hasMore
1460
+ };
1461
+ } catch (error) {
1462
+ throw new MastraError(
1463
+ {
1464
+ id: "STORAGE_DYNAMODB_STORE_GET_THREADS_BY_RESOURCE_ID_PAGINATED_FAILED",
1465
+ domain: ErrorDomain.STORAGE,
1466
+ category: ErrorCategory.THIRD_PARTY,
1467
+ details: { resourceId, page, perPage }
1468
+ },
1469
+ error
1470
+ );
1471
+ }
1472
+ }
1473
+ async getMessagesPaginated(args) {
1474
+ const { threadId, resourceId, selectBy, format = "v1" } = args;
1475
+ const { page = 0, perPage = 40, dateRange } = selectBy?.pagination || {};
1476
+ const fromDate = dateRange?.start;
1477
+ const toDate = dateRange?.end;
1478
+ const limit = resolveMessageLimit({ last: selectBy?.last, defaultLimit: Number.MAX_SAFE_INTEGER });
1479
+ this.logger.debug("Getting messages with pagination", { threadId, page, perPage, fromDate, toDate, limit });
1480
+ try {
1481
+ let messages = [];
1482
+ if (selectBy?.include?.length) {
1483
+ const includeMessages = await this._getIncludedMessages(threadId, selectBy);
1484
+ if (includeMessages) {
1485
+ messages.push(...includeMessages);
1486
+ }
1487
+ }
1488
+ if (limit !== 0) {
1489
+ const query = this.service.entities.message.query.byThread({ entity: "message", threadId });
1490
+ let results;
1491
+ if (limit !== Number.MAX_SAFE_INTEGER && limit > 0) {
1492
+ results = await query.go({ limit, order: "desc" });
1493
+ results.data = results.data.reverse();
1494
+ } else {
1495
+ results = await query.go();
1496
+ }
1497
+ let allThreadMessages = results.data.map((data) => this.parseMessageData(data)).filter((msg) => "content" in msg);
1498
+ allThreadMessages.sort((a, b) => {
1499
+ const timeA = a.createdAt.getTime();
1500
+ const timeB = b.createdAt.getTime();
1501
+ if (timeA === timeB) {
1502
+ return a.id.localeCompare(b.id);
1503
+ }
1504
+ return timeA - timeB;
1505
+ });
1506
+ const excludeIds = messages.map((m) => m.id);
1507
+ if (excludeIds.length > 0) {
1508
+ allThreadMessages = allThreadMessages.filter((msg) => !excludeIds.includes(msg.id));
1509
+ }
1510
+ messages.push(...allThreadMessages);
1511
+ }
1512
+ messages.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
1513
+ if (fromDate || toDate) {
1514
+ messages = messages.filter((msg) => {
1515
+ const createdAt = new Date(msg.createdAt).getTime();
1516
+ if (fromDate && createdAt < new Date(fromDate).getTime()) return false;
1517
+ if (toDate && createdAt > new Date(toDate).getTime()) return false;
1518
+ return true;
1519
+ });
1520
+ }
1521
+ const total = messages.length;
1522
+ const start = page * perPage;
1523
+ const end = start + perPage;
1524
+ const paginatedMessages = messages.slice(start, end);
1525
+ const hasMore = end < total;
1526
+ const list = new MessageList({ threadId, resourceId }).add(paginatedMessages, "memory");
1527
+ const finalMessages = format === "v2" ? list.get.all.v2() : list.get.all.v1();
1528
+ return {
1529
+ messages: finalMessages,
1530
+ total,
1531
+ page,
1532
+ perPage,
1533
+ hasMore
1534
+ };
1535
+ } catch (error) {
1536
+ throw new MastraError(
1537
+ {
1538
+ id: "STORAGE_DYNAMODB_STORE_GET_MESSAGES_PAGINATED_FAILED",
1539
+ domain: ErrorDomain.STORAGE,
1540
+ category: ErrorCategory.THIRD_PARTY,
1541
+ details: { threadId }
1542
+ },
1543
+ error
1544
+ );
1545
+ }
1546
+ }
1547
+ // Helper method to get included messages with context
1548
+ async _getIncludedMessages(threadId, selectBy) {
1549
+ if (!selectBy?.include?.length) {
1550
+ return [];
1551
+ }
1552
+ const includeMessages = [];
1553
+ for (const includeItem of selectBy.include) {
1554
+ try {
1555
+ const { id, threadId: targetThreadId, withPreviousMessages = 0, withNextMessages = 0 } = includeItem;
1556
+ const searchThreadId = targetThreadId || threadId;
1557
+ this.logger.debug("Getting included messages for", {
1558
+ id,
1559
+ targetThreadId,
1560
+ searchThreadId,
1561
+ withPreviousMessages,
1562
+ withNextMessages
1563
+ });
1564
+ const query = this.service.entities.message.query.byThread({ entity: "message", threadId: searchThreadId });
1565
+ const results = await query.go();
1566
+ const allMessages = results.data.map((data) => this.parseMessageData(data)).filter((msg) => "content" in msg && typeof msg.content === "object");
1567
+ this.logger.debug("Found messages in thread", {
1568
+ threadId: searchThreadId,
1569
+ messageCount: allMessages.length,
1570
+ messageIds: allMessages.map((m) => m.id)
1571
+ });
1572
+ allMessages.sort((a, b) => {
1573
+ const timeA = a.createdAt.getTime();
1574
+ const timeB = b.createdAt.getTime();
1575
+ if (timeA === timeB) {
1576
+ return a.id.localeCompare(b.id);
1577
+ }
1578
+ return timeA - timeB;
1579
+ });
1580
+ const targetIndex = allMessages.findIndex((msg) => msg.id === id);
1581
+ if (targetIndex === -1) {
1582
+ this.logger.warn("Target message not found", { id, threadId: searchThreadId });
1583
+ continue;
1584
+ }
1585
+ this.logger.debug("Found target message at index", { id, targetIndex, totalMessages: allMessages.length });
1586
+ const startIndex = Math.max(0, targetIndex - withPreviousMessages);
1587
+ const endIndex = Math.min(allMessages.length, targetIndex + withNextMessages + 1);
1588
+ const contextMessages = allMessages.slice(startIndex, endIndex);
1589
+ this.logger.debug("Context messages", {
1590
+ startIndex,
1591
+ endIndex,
1592
+ contextCount: contextMessages.length,
1593
+ contextIds: contextMessages.map((m) => m.id)
1594
+ });
1595
+ includeMessages.push(...contextMessages);
1596
+ } catch (error) {
1597
+ this.logger.warn("Failed to get included message", { messageId: includeItem.id, error });
1598
+ }
1599
+ }
1600
+ this.logger.debug("Total included messages", {
1601
+ count: includeMessages.length,
1602
+ ids: includeMessages.map((m) => m.id)
1603
+ });
1604
+ return includeMessages;
1605
+ }
1606
+ async updateMessages(args) {
1607
+ const { messages } = args;
1608
+ this.logger.debug("Updating messages", { count: messages.length });
1609
+ if (!messages.length) {
1610
+ return [];
1611
+ }
1612
+ const updatedMessages = [];
1613
+ const affectedThreadIds = /* @__PURE__ */ new Set();
1614
+ try {
1615
+ for (const updateData of messages) {
1616
+ const { id, ...updates } = updateData;
1617
+ const existingMessage = await this.service.entities.message.get({ entity: "message", id }).go();
1618
+ if (!existingMessage.data) {
1619
+ this.logger.warn("Message not found for update", { id });
1620
+ continue;
1621
+ }
1622
+ const existingMsg = this.parseMessageData(existingMessage.data);
1623
+ const originalThreadId = existingMsg.threadId;
1624
+ affectedThreadIds.add(originalThreadId);
1625
+ const updatePayload = {
1626
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
1627
+ };
1628
+ if ("role" in updates && updates.role !== void 0) updatePayload.role = updates.role;
1629
+ if ("type" in updates && updates.type !== void 0) updatePayload.type = updates.type;
1630
+ if ("resourceId" in updates && updates.resourceId !== void 0) updatePayload.resourceId = updates.resourceId;
1631
+ if ("threadId" in updates && updates.threadId !== void 0 && updates.threadId !== null) {
1632
+ updatePayload.threadId = updates.threadId;
1633
+ affectedThreadIds.add(updates.threadId);
1634
+ }
1635
+ if (updates.content) {
1636
+ const existingContent = existingMsg.content;
1637
+ let newContent = { ...existingContent };
1638
+ if (updates.content.metadata !== void 0) {
1639
+ newContent.metadata = {
1640
+ ...existingContent.metadata || {},
1641
+ ...updates.content.metadata || {}
1642
+ };
1643
+ }
1644
+ if (updates.content.content !== void 0) {
1645
+ newContent.content = updates.content.content;
1646
+ }
1647
+ if ("parts" in updates.content && updates.content.parts !== void 0) {
1648
+ newContent.parts = updates.content.parts;
1649
+ }
1650
+ updatePayload.content = JSON.stringify(newContent);
1651
+ }
1652
+ await this.service.entities.message.update({ entity: "message", id }).set(updatePayload).go();
1653
+ const updatedMessage = await this.service.entities.message.get({ entity: "message", id }).go();
1654
+ if (updatedMessage.data) {
1655
+ updatedMessages.push(this.parseMessageData(updatedMessage.data));
1656
+ }
1657
+ }
1658
+ for (const threadId of affectedThreadIds) {
1659
+ await this.service.entities.thread.update({ entity: "thread", id: threadId }).set({
1660
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
1661
+ }).go();
1662
+ }
1663
+ return updatedMessages;
1664
+ } catch (error) {
1665
+ throw new MastraError(
1666
+ {
1667
+ id: "STORAGE_DYNAMODB_STORE_UPDATE_MESSAGES_FAILED",
1668
+ domain: ErrorDomain.STORAGE,
1669
+ category: ErrorCategory.THIRD_PARTY,
1670
+ details: { count: messages.length }
1671
+ },
1672
+ error
1673
+ );
1674
+ }
1675
+ }
1676
+ async getResourceById({ resourceId }) {
1677
+ this.logger.debug("Getting resource by ID", { resourceId });
1678
+ try {
1679
+ const result = await this.service.entities.resource.get({ entity: "resource", id: resourceId }).go();
1680
+ if (!result.data) {
1681
+ return null;
1682
+ }
1683
+ const data = result.data;
1684
+ return {
1685
+ ...data,
1686
+ // Convert date strings back to Date objects for consistency
1687
+ createdAt: typeof data.createdAt === "string" ? new Date(data.createdAt) : data.createdAt,
1688
+ updatedAt: typeof data.updatedAt === "string" ? new Date(data.updatedAt) : data.updatedAt,
1689
+ // Ensure workingMemory is always returned as a string, regardless of automatic parsing
1690
+ workingMemory: typeof data.workingMemory === "object" ? JSON.stringify(data.workingMemory) : data.workingMemory
1691
+ // metadata is already transformed by the entity's getter
1692
+ };
1693
+ } catch (error) {
1694
+ throw new MastraError(
1695
+ {
1696
+ id: "STORAGE_DYNAMODB_STORE_GET_RESOURCE_BY_ID_FAILED",
1697
+ domain: ErrorDomain.STORAGE,
1698
+ category: ErrorCategory.THIRD_PARTY,
1699
+ details: { resourceId }
1700
+ },
1701
+ error
1702
+ );
1703
+ }
1704
+ }
1705
+ async saveResource({ resource }) {
1706
+ this.logger.debug("Saving resource", { resourceId: resource.id });
1707
+ const now = /* @__PURE__ */ new Date();
1708
+ const resourceData = {
1709
+ entity: "resource",
1710
+ id: resource.id,
1711
+ workingMemory: resource.workingMemory,
1712
+ metadata: resource.metadata ? JSON.stringify(resource.metadata) : void 0,
1713
+ createdAt: resource.createdAt?.toISOString() || now.toISOString(),
1714
+ updatedAt: now.toISOString()
1715
+ };
568
1716
  try {
569
- if (!config.tableName || typeof config.tableName !== "string" || config.tableName.trim() === "") {
570
- throw new Error("DynamoDBStore: config.tableName must be provided and cannot be empty.");
571
- }
572
- if (!/^[a-zA-Z0-9_.-]{3,255}$/.test(config.tableName)) {
573
- throw new Error(
574
- `DynamoDBStore: config.tableName "${config.tableName}" contains invalid characters or is not between 3 and 255 characters long.`
575
- );
576
- }
577
- const dynamoClient = new DynamoDBClient({
578
- region: config.region || "us-east-1",
579
- endpoint: config.endpoint,
580
- credentials: config.credentials
581
- });
582
- this.tableName = config.tableName;
583
- this.client = DynamoDBDocumentClient.from(dynamoClient);
584
- this.service = getElectroDbService(this.client, this.tableName);
1717
+ await this.service.entities.resource.upsert(resourceData).go();
1718
+ return {
1719
+ id: resource.id,
1720
+ workingMemory: resource.workingMemory,
1721
+ metadata: resource.metadata,
1722
+ createdAt: resource.createdAt || now,
1723
+ updatedAt: now
1724
+ };
585
1725
  } catch (error) {
586
1726
  throw new MastraError(
587
1727
  {
588
- id: "STORAGE_DYNAMODB_STORE_CONSTRUCTOR_FAILED",
1728
+ id: "STORAGE_DYNAMODB_STORE_SAVE_RESOURCE_FAILED",
589
1729
  domain: ErrorDomain.STORAGE,
590
- category: ErrorCategory.USER
1730
+ category: ErrorCategory.THIRD_PARTY,
1731
+ details: { resourceId: resource.id }
591
1732
  },
592
1733
  error
593
1734
  );
594
1735
  }
595
1736
  }
596
- /**
597
- * This method is modified for DynamoDB with ElectroDB single-table design.
598
- * It assumes the table is created and managed externally via CDK/CloudFormation.
599
- *
600
- * This implementation only validates that the required table exists and is accessible.
601
- * No table creation is attempted - we simply check if we can access the table.
602
- */
603
- async createTable({ tableName }) {
604
- this.logger.debug("Validating access to externally managed table", { tableName, physicalTable: this.tableName });
1737
+ async updateResource({
1738
+ resourceId,
1739
+ workingMemory,
1740
+ metadata
1741
+ }) {
1742
+ this.logger.debug("Updating resource", { resourceId });
605
1743
  try {
606
- const tableExists = await this.validateTableExists();
607
- if (!tableExists) {
608
- this.logger.error(
609
- `Table ${this.tableName} does not exist or is not accessible. It should be created via CDK/CloudFormation.`
610
- );
611
- throw new Error(
612
- `Table ${this.tableName} does not exist or is not accessible. Ensure it's created via CDK/CloudFormation before using this store.`
613
- );
1744
+ const existingResource = await this.getResourceById({ resourceId });
1745
+ if (!existingResource) {
1746
+ const newResource = {
1747
+ id: resourceId,
1748
+ workingMemory,
1749
+ metadata: metadata || {},
1750
+ createdAt: /* @__PURE__ */ new Date(),
1751
+ updatedAt: /* @__PURE__ */ new Date()
1752
+ };
1753
+ return this.saveResource({ resource: newResource });
614
1754
  }
615
- this.logger.debug(`Table ${this.tableName} exists and is accessible`);
1755
+ const now = /* @__PURE__ */ new Date();
1756
+ const updateData = {
1757
+ updatedAt: now.toISOString()
1758
+ };
1759
+ if (workingMemory !== void 0) {
1760
+ updateData.workingMemory = workingMemory;
1761
+ }
1762
+ if (metadata) {
1763
+ const existingMetadata = existingResource.metadata || {};
1764
+ const mergedMetadata = { ...existingMetadata, ...metadata };
1765
+ updateData.metadata = JSON.stringify(mergedMetadata);
1766
+ }
1767
+ await this.service.entities.resource.update({ entity: "resource", id: resourceId }).set(updateData).go();
1768
+ return {
1769
+ ...existingResource,
1770
+ workingMemory: workingMemory !== void 0 ? workingMemory : existingResource.workingMemory,
1771
+ metadata: metadata ? { ...existingResource.metadata, ...metadata } : existingResource.metadata,
1772
+ updatedAt: now
1773
+ };
616
1774
  } catch (error) {
617
- this.logger.error("Error validating table access", { tableName: this.tableName, error });
618
1775
  throw new MastraError(
619
1776
  {
620
- id: "STORAGE_DYNAMODB_STORE_VALIDATE_TABLE_ACCESS_FAILED",
1777
+ id: "STORAGE_DYNAMODB_STORE_UPDATE_RESOURCE_FAILED",
621
1778
  domain: ErrorDomain.STORAGE,
622
1779
  category: ErrorCategory.THIRD_PARTY,
623
- details: { tableName: this.tableName }
1780
+ details: { resourceId }
624
1781
  },
625
1782
  error
626
1783
  );
627
1784
  }
628
1785
  }
1786
+ };
1787
+ var StoreOperationsDynamoDB = class extends StoreOperations {
1788
+ client;
1789
+ tableName;
1790
+ service;
1791
+ constructor({
1792
+ service,
1793
+ tableName,
1794
+ client
1795
+ }) {
1796
+ super();
1797
+ this.service = service;
1798
+ this.client = client;
1799
+ this.tableName = tableName;
1800
+ }
1801
+ async hasColumn() {
1802
+ return true;
1803
+ }
1804
+ async dropTable() {
1805
+ }
1806
+ // Helper methods for entity/table mapping
1807
+ getEntityNameForTable(tableName) {
1808
+ const mapping = {
1809
+ [TABLE_THREADS]: "thread",
1810
+ [TABLE_MESSAGES]: "message",
1811
+ [TABLE_WORKFLOW_SNAPSHOT]: "workflow_snapshot",
1812
+ [TABLE_EVALS]: "eval",
1813
+ [TABLE_SCORERS]: "score",
1814
+ [TABLE_TRACES]: "trace",
1815
+ [TABLE_RESOURCES]: "resource"
1816
+ };
1817
+ return mapping[tableName] || null;
1818
+ }
1819
+ /**
1820
+ * Pre-processes a record to ensure Date objects are converted to ISO strings
1821
+ * This is necessary because ElectroDB validation happens before setters are applied
1822
+ */
1823
+ preprocessRecord(record) {
1824
+ const processed = { ...record };
1825
+ if (processed.createdAt instanceof Date) {
1826
+ processed.createdAt = processed.createdAt.toISOString();
1827
+ }
1828
+ if (processed.updatedAt instanceof Date) {
1829
+ processed.updatedAt = processed.updatedAt.toISOString();
1830
+ }
1831
+ if (processed.created_at instanceof Date) {
1832
+ processed.created_at = processed.created_at.toISOString();
1833
+ }
1834
+ if (processed.result && typeof processed.result === "object") {
1835
+ processed.result = JSON.stringify(processed.result);
1836
+ }
1837
+ if (processed.test_info && typeof processed.test_info === "object") {
1838
+ processed.test_info = JSON.stringify(processed.test_info);
1839
+ } else if (processed.test_info === void 0 || processed.test_info === null) {
1840
+ delete processed.test_info;
1841
+ }
1842
+ if (processed.snapshot && typeof processed.snapshot === "object") {
1843
+ processed.snapshot = JSON.stringify(processed.snapshot);
1844
+ }
1845
+ if (processed.attributes && typeof processed.attributes === "object") {
1846
+ processed.attributes = JSON.stringify(processed.attributes);
1847
+ }
1848
+ if (processed.status && typeof processed.status === "object") {
1849
+ processed.status = JSON.stringify(processed.status);
1850
+ }
1851
+ if (processed.events && typeof processed.events === "object") {
1852
+ processed.events = JSON.stringify(processed.events);
1853
+ }
1854
+ if (processed.links && typeof processed.links === "object") {
1855
+ processed.links = JSON.stringify(processed.links);
1856
+ }
1857
+ return processed;
1858
+ }
629
1859
  /**
630
1860
  * Validates that the required DynamoDB table exists and is accessible.
631
1861
  * This does not check the table structure - it assumes the table
@@ -654,20 +1884,30 @@ var DynamoDBStore = class extends MastraStorage {
654
1884
  }
655
1885
  }
656
1886
  /**
657
- * Initialize storage, validating the externally managed table is accessible.
658
- * For the single-table design, we only validate once that we can access
659
- * the table that was created via CDK/CloudFormation.
1887
+ * This method is modified for DynamoDB with ElectroDB single-table design.
1888
+ * It assumes the table is created and managed externally via CDK/CloudFormation.
1889
+ *
1890
+ * This implementation only validates that the required table exists and is accessible.
1891
+ * No table creation is attempted - we simply check if we can access the table.
660
1892
  */
661
- async init() {
662
- if (this.hasInitialized === null) {
663
- this.hasInitialized = this._performInitializationAndStore();
664
- }
1893
+ async createTable({ tableName }) {
1894
+ this.logger.debug("Validating access to externally managed table", { tableName, physicalTable: this.tableName });
665
1895
  try {
666
- await this.hasInitialized;
1896
+ const tableExists = await this.validateTableExists();
1897
+ if (!tableExists) {
1898
+ this.logger.error(
1899
+ `Table ${this.tableName} does not exist or is not accessible. It should be created via CDK/CloudFormation.`
1900
+ );
1901
+ throw new Error(
1902
+ `Table ${this.tableName} does not exist or is not accessible. Ensure it's created via CDK/CloudFormation before using this store.`
1903
+ );
1904
+ }
1905
+ this.logger.debug(`Table ${this.tableName} exists and is accessible`);
667
1906
  } catch (error) {
1907
+ this.logger.error("Error validating table access", { tableName: this.tableName, error });
668
1908
  throw new MastraError(
669
1909
  {
670
- id: "STORAGE_DYNAMODB_STORE_INIT_FAILED",
1910
+ id: "STORAGE_DYNAMODB_STORE_VALIDATE_TABLE_ACCESS_FAILED",
671
1911
  domain: ErrorDomain.STORAGE,
672
1912
  category: ErrorCategory.THIRD_PARTY,
673
1913
  details: { tableName: this.tableName }
@@ -676,39 +1916,32 @@ var DynamoDBStore = class extends MastraStorage {
676
1916
  );
677
1917
  }
678
1918
  }
679
- /**
680
- * Performs the actual table validation and stores the promise.
681
- * Handles resetting the stored promise on failure to allow retries.
682
- */
683
- _performInitializationAndStore() {
684
- return this.validateTableExists().then((exists) => {
685
- if (!exists) {
686
- throw new Error(
687
- `Table ${this.tableName} does not exist or is not accessible. Ensure it's created via CDK/CloudFormation before using this store.`
688
- );
689
- }
690
- return true;
691
- }).catch((err) => {
692
- this.hasInitialized = null;
693
- throw err;
694
- });
695
- }
696
- /**
697
- * Pre-processes a record to ensure Date objects are converted to ISO strings
698
- * This is necessary because ElectroDB validation happens before setters are applied
699
- */
700
- preprocessRecord(record) {
701
- const processed = { ...record };
702
- if (processed.createdAt instanceof Date) {
703
- processed.createdAt = processed.createdAt.toISOString();
704
- }
705
- if (processed.updatedAt instanceof Date) {
706
- processed.updatedAt = processed.updatedAt.toISOString();
1919
+ async insert({ tableName, record }) {
1920
+ this.logger.debug("DynamoDB insert called", { tableName });
1921
+ const entityName = this.getEntityNameForTable(tableName);
1922
+ if (!entityName || !this.service.entities[entityName]) {
1923
+ throw new MastraError({
1924
+ id: "STORAGE_DYNAMODB_STORE_INSERT_INVALID_ARGS",
1925
+ domain: ErrorDomain.STORAGE,
1926
+ category: ErrorCategory.USER,
1927
+ text: "No entity defined for tableName",
1928
+ details: { tableName }
1929
+ });
707
1930
  }
708
- if (processed.created_at instanceof Date) {
709
- processed.created_at = processed.created_at.toISOString();
1931
+ try {
1932
+ const dataToSave = { entity: entityName, ...this.preprocessRecord(record) };
1933
+ await this.service.entities[entityName].create(dataToSave).go();
1934
+ } catch (error) {
1935
+ throw new MastraError(
1936
+ {
1937
+ id: "STORAGE_DYNAMODB_STORE_INSERT_FAILED",
1938
+ domain: ErrorDomain.STORAGE,
1939
+ category: ErrorCategory.THIRD_PARTY,
1940
+ details: { tableName }
1941
+ },
1942
+ error
1943
+ );
710
1944
  }
711
- return processed;
712
1945
  }
713
1946
  async alterTable(_args) {
714
1947
  }
@@ -745,70 +1978,41 @@ var DynamoDBStore = class extends MastraStorage {
745
1978
  if (!item.id) throw new Error(`Missing required key 'id' for entity 'message'`);
746
1979
  key.id = item.id;
747
1980
  break;
748
- case "workflowSnapshot":
1981
+ case "workflow_snapshot":
749
1982
  if (!item.workflow_name)
750
- throw new Error(`Missing required key 'workflow_name' for entity 'workflowSnapshot'`);
751
- if (!item.run_id) throw new Error(`Missing required key 'run_id' for entity 'workflowSnapshot'`);
1983
+ throw new Error(`Missing required key 'workflow_name' for entity 'workflow_snapshot'`);
1984
+ if (!item.run_id) throw new Error(`Missing required key 'run_id' for entity 'workflow_snapshot'`);
752
1985
  key.workflow_name = item.workflow_name;
753
1986
  key.run_id = item.run_id;
754
- break;
755
- case "eval":
756
- if (!item.run_id) throw new Error(`Missing required key 'run_id' for entity 'eval'`);
757
- key.run_id = item.run_id;
758
- break;
759
- case "trace":
760
- if (!item.id) throw new Error(`Missing required key 'id' for entity 'trace'`);
761
- key.id = item.id;
762
- break;
763
- default:
764
- this.logger.warn(`Unknown entity type encountered during clearTable: ${entityName}`);
765
- throw new Error(`Cannot construct delete key for unknown entity type: ${entityName}`);
766
- }
767
- return key;
768
- });
769
- const batchSize = 25;
770
- for (let i = 0; i < keysToDelete.length; i += batchSize) {
771
- const batchKeys = keysToDelete.slice(i, i + batchSize);
772
- await this.service.entities[entityName].delete(batchKeys).go();
773
- }
774
- this.logger.debug(`Successfully cleared all records for ${tableName}`);
775
- } catch (error) {
776
- throw new MastraError(
777
- {
778
- id: "STORAGE_DYNAMODB_STORE_CLEAR_TABLE_FAILED",
779
- domain: ErrorDomain.STORAGE,
780
- category: ErrorCategory.THIRD_PARTY,
781
- details: { tableName }
782
- },
783
- error
784
- );
785
- }
786
- }
787
- /**
788
- * Insert a record into the specified "table" (entity)
789
- */
790
- async insert({
791
- tableName,
792
- record
793
- }) {
794
- this.logger.debug("DynamoDB insert called", { tableName });
795
- const entityName = this.getEntityNameForTable(tableName);
796
- if (!entityName || !this.service.entities[entityName]) {
797
- throw new MastraError({
798
- id: "STORAGE_DYNAMODB_STORE_INSERT_INVALID_ARGS",
799
- domain: ErrorDomain.STORAGE,
800
- category: ErrorCategory.USER,
801
- text: "No entity defined for tableName",
802
- details: { tableName }
1987
+ break;
1988
+ case "eval":
1989
+ if (!item.run_id) throw new Error(`Missing required key 'run_id' for entity 'eval'`);
1990
+ key.run_id = item.run_id;
1991
+ break;
1992
+ case "trace":
1993
+ if (!item.id) throw new Error(`Missing required key 'id' for entity 'trace'`);
1994
+ key.id = item.id;
1995
+ break;
1996
+ case "score":
1997
+ if (!item.id) throw new Error(`Missing required key 'id' for entity 'score'`);
1998
+ key.id = item.id;
1999
+ break;
2000
+ default:
2001
+ this.logger.warn(`Unknown entity type encountered during clearTable: ${entityName}`);
2002
+ throw new Error(`Cannot construct delete key for unknown entity type: ${entityName}`);
2003
+ }
2004
+ return key;
803
2005
  });
804
- }
805
- try {
806
- const dataToSave = { entity: entityName, ...this.preprocessRecord(record) };
807
- await this.service.entities[entityName].create(dataToSave).go();
2006
+ const batchSize = 25;
2007
+ for (let i = 0; i < keysToDelete.length; i += batchSize) {
2008
+ const batchKeys = keysToDelete.slice(i, i + batchSize);
2009
+ await this.service.entities[entityName].delete(batchKeys).go();
2010
+ }
2011
+ this.logger.debug(`Successfully cleared all records for ${tableName}`);
808
2012
  } catch (error) {
809
2013
  throw new MastraError(
810
2014
  {
811
- id: "STORAGE_DYNAMODB_STORE_INSERT_FAILED",
2015
+ id: "STORAGE_DYNAMODB_STORE_CLEAR_TABLE_FAILED",
812
2016
  domain: ErrorDomain.STORAGE,
813
2017
  category: ErrorCategory.THIRD_PARTY,
814
2018
  details: { tableName }
@@ -820,10 +2024,7 @@ var DynamoDBStore = class extends MastraStorage {
820
2024
  /**
821
2025
  * Insert multiple records as a batch
822
2026
  */
823
- async batchInsert({
824
- tableName,
825
- records
826
- }) {
2027
+ async batchInsert({ tableName, records }) {
827
2028
  this.logger.debug("DynamoDB batchInsert called", { tableName, count: records.length });
828
2029
  const entityName = this.getEntityNameForTable(tableName);
829
2030
  if (!entityName || !this.service.entities[entityName]) {
@@ -868,10 +2069,7 @@ var DynamoDBStore = class extends MastraStorage {
868
2069
  /**
869
2070
  * Load a record by its keys
870
2071
  */
871
- async load({
872
- tableName,
873
- keys
874
- }) {
2072
+ async load({ tableName, keys }) {
875
2073
  this.logger.debug("DynamoDB load called", { tableName, keys });
876
2074
  const entityName = this.getEntityNameForTable(tableName);
877
2075
  if (!entityName || !this.service.entities[entityName]) {
@@ -903,268 +2101,228 @@ var DynamoDBStore = class extends MastraStorage {
903
2101
  );
904
2102
  }
905
2103
  }
906
- // Thread operations
907
- async getThreadById({ threadId }) {
908
- this.logger.debug("Getting thread by ID", { threadId });
2104
+ };
2105
+ var ScoresStorageDynamoDB = class extends ScoresStorage {
2106
+ service;
2107
+ constructor({ service }) {
2108
+ super();
2109
+ this.service = service;
2110
+ }
2111
+ // Helper function to parse score data (handle JSON fields)
2112
+ parseScoreData(data) {
2113
+ return {
2114
+ ...data,
2115
+ // Convert date strings back to Date objects for consistency
2116
+ createdAt: data.createdAt ? new Date(data.createdAt) : /* @__PURE__ */ new Date(),
2117
+ updatedAt: data.updatedAt ? new Date(data.updatedAt) : /* @__PURE__ */ new Date()
2118
+ // JSON fields are already transformed by the entity's getters
2119
+ };
2120
+ }
2121
+ async getScoreById({ id }) {
2122
+ this.logger.debug("Getting score by ID", { id });
909
2123
  try {
910
- const result = await this.service.entities.thread.get({ entity: "thread", id: threadId }).go();
2124
+ const result = await this.service.entities.score.get({ entity: "score", id }).go();
911
2125
  if (!result.data) {
912
2126
  return null;
913
2127
  }
914
- const data = result.data;
915
- return {
916
- ...data,
917
- // Convert date strings back to Date objects for consistency
918
- createdAt: typeof data.createdAt === "string" ? new Date(data.createdAt) : data.createdAt,
919
- updatedAt: typeof data.updatedAt === "string" ? new Date(data.updatedAt) : data.updatedAt
920
- // metadata: data.metadata ? JSON.parse(data.metadata) : undefined, // REMOVED by AI
921
- // metadata is already transformed by the entity's getter
922
- };
923
- } catch (error) {
924
- throw new MastraError(
925
- {
926
- id: "STORAGE_DYNAMODB_STORE_GET_THREAD_BY_ID_FAILED",
927
- domain: ErrorDomain.STORAGE,
928
- category: ErrorCategory.THIRD_PARTY,
929
- details: { threadId }
930
- },
931
- error
932
- );
933
- }
934
- }
935
- async getThreadsByResourceId({ resourceId }) {
936
- this.logger.debug("Getting threads by resource ID", { resourceId });
937
- try {
938
- const result = await this.service.entities.thread.query.byResource({ entity: "thread", resourceId }).go();
939
- if (!result.data.length) {
940
- return [];
941
- }
942
- return result.data.map((data) => ({
943
- ...data,
944
- // Convert date strings back to Date objects for consistency
945
- createdAt: typeof data.createdAt === "string" ? new Date(data.createdAt) : data.createdAt,
946
- updatedAt: typeof data.updatedAt === "string" ? new Date(data.updatedAt) : data.updatedAt
947
- // metadata: data.metadata ? JSON.parse(data.metadata) : undefined, // REMOVED by AI
948
- // metadata is already transformed by the entity's getter
949
- }));
2128
+ return this.parseScoreData(result.data);
950
2129
  } catch (error) {
951
2130
  throw new MastraError(
952
2131
  {
953
- id: "STORAGE_DYNAMODB_STORE_GET_THREADS_BY_RESOURCE_ID_FAILED",
2132
+ id: "STORAGE_DYNAMODB_STORE_GET_SCORE_BY_ID_FAILED",
954
2133
  domain: ErrorDomain.STORAGE,
955
2134
  category: ErrorCategory.THIRD_PARTY,
956
- details: { resourceId }
2135
+ details: { id }
957
2136
  },
958
2137
  error
959
2138
  );
960
2139
  }
961
2140
  }
962
- async saveThread({ thread }) {
963
- this.logger.debug("Saving thread", { threadId: thread.id });
2141
+ async saveScore(score) {
2142
+ this.logger.debug("Saving score", { scorerId: score.scorerId, runId: score.runId });
964
2143
  const now = /* @__PURE__ */ new Date();
965
- const threadData = {
966
- entity: "thread",
967
- id: thread.id,
968
- resourceId: thread.resourceId,
969
- title: thread.title || `Thread ${thread.id}`,
970
- createdAt: thread.createdAt?.toISOString() || now.toISOString(),
971
- updatedAt: now.toISOString(),
972
- metadata: thread.metadata ? JSON.stringify(thread.metadata) : void 0
2144
+ const scoreId = `score-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
2145
+ const scoreData = {
2146
+ entity: "score",
2147
+ id: scoreId,
2148
+ scorerId: score.scorerId,
2149
+ traceId: score.traceId || "",
2150
+ runId: score.runId,
2151
+ scorer: typeof score.scorer === "string" ? score.scorer : JSON.stringify(score.scorer),
2152
+ preprocessStepResult: typeof score.preprocessStepResult === "string" ? score.preprocessStepResult : JSON.stringify(score.preprocessStepResult),
2153
+ analyzeStepResult: typeof score.analyzeStepResult === "string" ? score.analyzeStepResult : JSON.stringify(score.analyzeStepResult),
2154
+ score: score.score,
2155
+ reason: score.reason,
2156
+ preprocessPrompt: score.preprocessPrompt,
2157
+ generateScorePrompt: score.generateScorePrompt,
2158
+ analyzePrompt: score.analyzePrompt,
2159
+ reasonPrompt: score.reasonPrompt,
2160
+ input: typeof score.input === "string" ? score.input : JSON.stringify(score.input),
2161
+ output: typeof score.output === "string" ? score.output : JSON.stringify(score.output),
2162
+ additionalContext: typeof score.additionalContext === "string" ? score.additionalContext : JSON.stringify(score.additionalContext),
2163
+ runtimeContext: typeof score.runtimeContext === "string" ? score.runtimeContext : JSON.stringify(score.runtimeContext),
2164
+ entityType: score.entityType,
2165
+ entityData: typeof score.entity === "string" ? score.entity : JSON.stringify(score.entity),
2166
+ entityId: score.entityId,
2167
+ source: score.source,
2168
+ resourceId: score.resourceId || "",
2169
+ threadId: score.threadId || "",
2170
+ createdAt: now.toISOString(),
2171
+ updatedAt: now.toISOString()
973
2172
  };
974
2173
  try {
975
- await this.service.entities.thread.upsert(threadData).go();
976
- return {
977
- id: thread.id,
978
- resourceId: thread.resourceId,
979
- title: threadData.title,
980
- createdAt: thread.createdAt || now,
981
- updatedAt: now,
982
- metadata: thread.metadata
2174
+ await this.service.entities.score.upsert(scoreData).go();
2175
+ const savedScore = {
2176
+ ...score,
2177
+ id: scoreId,
2178
+ createdAt: now,
2179
+ updatedAt: now
983
2180
  };
2181
+ return { score: savedScore };
984
2182
  } catch (error) {
985
2183
  throw new MastraError(
986
2184
  {
987
- id: "STORAGE_DYNAMODB_STORE_SAVE_THREAD_FAILED",
2185
+ id: "STORAGE_DYNAMODB_STORE_SAVE_SCORE_FAILED",
988
2186
  domain: ErrorDomain.STORAGE,
989
2187
  category: ErrorCategory.THIRD_PARTY,
990
- details: { threadId: thread.id }
2188
+ details: { scorerId: score.scorerId, runId: score.runId }
991
2189
  },
992
2190
  error
993
2191
  );
994
2192
  }
995
2193
  }
996
- async updateThread({
997
- id,
998
- title,
999
- metadata
2194
+ async getScoresByScorerId({
2195
+ scorerId,
2196
+ pagination,
2197
+ entityId,
2198
+ entityType
1000
2199
  }) {
1001
- this.logger.debug("Updating thread", { threadId: id });
2200
+ this.logger.debug("Getting scores by scorer ID", { scorerId, pagination, entityId, entityType });
1002
2201
  try {
1003
- const existingThread = await this.getThreadById({ threadId: id });
1004
- if (!existingThread) {
1005
- throw new Error(`Thread not found: ${id}`);
1006
- }
1007
- const now = /* @__PURE__ */ new Date();
1008
- const updateData = {
1009
- updatedAt: now.toISOString()
1010
- };
1011
- if (title) {
1012
- updateData.title = title;
2202
+ const query = this.service.entities.score.query.byScorer({ entity: "score", scorerId });
2203
+ const results = await query.go();
2204
+ let allScores = results.data.map((data) => this.parseScoreData(data));
2205
+ if (entityId) {
2206
+ allScores = allScores.filter((score) => score.entityId === entityId);
1013
2207
  }
1014
- if (metadata) {
1015
- updateData.metadata = JSON.stringify(metadata);
2208
+ if (entityType) {
2209
+ allScores = allScores.filter((score) => score.entityType === entityType);
1016
2210
  }
1017
- await this.service.entities.thread.update({ entity: "thread", id }).set(updateData).go();
2211
+ allScores.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
2212
+ const startIndex = pagination.page * pagination.perPage;
2213
+ const endIndex = startIndex + pagination.perPage;
2214
+ const paginatedScores = allScores.slice(startIndex, endIndex);
2215
+ const total = allScores.length;
2216
+ const hasMore = endIndex < total;
1018
2217
  return {
1019
- ...existingThread,
1020
- title: title || existingThread.title,
1021
- metadata: metadata || existingThread.metadata,
1022
- updatedAt: now
2218
+ scores: paginatedScores,
2219
+ pagination: {
2220
+ total,
2221
+ page: pagination.page,
2222
+ perPage: pagination.perPage,
2223
+ hasMore
2224
+ }
1023
2225
  };
1024
2226
  } catch (error) {
1025
2227
  throw new MastraError(
1026
2228
  {
1027
- id: "STORAGE_DYNAMODB_STORE_UPDATE_THREAD_FAILED",
2229
+ id: "STORAGE_DYNAMODB_STORE_GET_SCORES_BY_SCORER_ID_FAILED",
1028
2230
  domain: ErrorDomain.STORAGE,
1029
2231
  category: ErrorCategory.THIRD_PARTY,
1030
- details: { threadId: id }
2232
+ details: {
2233
+ scorerId: scorerId || "",
2234
+ entityId: entityId || "",
2235
+ entityType: entityType || "",
2236
+ page: pagination.page,
2237
+ perPage: pagination.perPage
2238
+ }
1031
2239
  },
1032
2240
  error
1033
2241
  );
1034
2242
  }
1035
2243
  }
1036
- async deleteThread({ threadId }) {
1037
- this.logger.debug("Deleting thread", { threadId });
2244
+ async getScoresByRunId({
2245
+ runId,
2246
+ pagination
2247
+ }) {
2248
+ this.logger.debug("Getting scores by run ID", { runId, pagination });
1038
2249
  try {
1039
- await this.service.entities.thread.delete({ entity: "thread", id: threadId }).go();
2250
+ const query = this.service.entities.score.query.byRun({ entity: "score", runId });
2251
+ const results = await query.go();
2252
+ const allScores = results.data.map((data) => this.parseScoreData(data));
2253
+ allScores.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
2254
+ const startIndex = pagination.page * pagination.perPage;
2255
+ const endIndex = startIndex + pagination.perPage;
2256
+ const paginatedScores = allScores.slice(startIndex, endIndex);
2257
+ const total = allScores.length;
2258
+ const hasMore = endIndex < total;
2259
+ return {
2260
+ scores: paginatedScores,
2261
+ pagination: {
2262
+ total,
2263
+ page: pagination.page,
2264
+ perPage: pagination.perPage,
2265
+ hasMore
2266
+ }
2267
+ };
1040
2268
  } catch (error) {
1041
2269
  throw new MastraError(
1042
2270
  {
1043
- id: "STORAGE_DYNAMODB_STORE_DELETE_THREAD_FAILED",
2271
+ id: "STORAGE_DYNAMODB_STORE_GET_SCORES_BY_RUN_ID_FAILED",
1044
2272
  domain: ErrorDomain.STORAGE,
1045
2273
  category: ErrorCategory.THIRD_PARTY,
1046
- details: { threadId }
2274
+ details: { runId, page: pagination.page, perPage: pagination.perPage }
1047
2275
  },
1048
2276
  error
1049
2277
  );
1050
2278
  }
1051
2279
  }
1052
- async getMessages({
1053
- threadId,
1054
- resourceId,
1055
- selectBy,
1056
- format
2280
+ async getScoresByEntityId({
2281
+ entityId,
2282
+ entityType,
2283
+ pagination
1057
2284
  }) {
1058
- this.logger.debug("Getting messages", { threadId, selectBy });
2285
+ this.logger.debug("Getting scores by entity ID", { entityId, entityType, pagination });
1059
2286
  try {
1060
- const query = this.service.entities.message.query.byThread({ entity: "message", threadId });
1061
- const limit = this.resolveMessageLimit({ last: selectBy?.last, defaultLimit: Number.MAX_SAFE_INTEGER });
1062
- if (limit !== Number.MAX_SAFE_INTEGER) {
1063
- const results2 = await query.go({ limit, order: "desc" });
1064
- const list2 = new MessageList({ threadId, resourceId }).add(
1065
- results2.data.map((data) => this.parseMessageData(data)),
1066
- "memory"
1067
- );
1068
- if (format === `v2`) return list2.get.all.v2();
1069
- return list2.get.all.v1();
1070
- }
2287
+ const query = this.service.entities.score.query.byEntityData({ entity: "score", entityId });
1071
2288
  const results = await query.go();
1072
- const list = new MessageList({ threadId, resourceId }).add(
1073
- results.data.map((data) => this.parseMessageData(data)),
1074
- "memory"
1075
- );
1076
- if (format === `v2`) return list.get.all.v2();
1077
- return list.get.all.v1();
1078
- } catch (error) {
1079
- throw new MastraError(
1080
- {
1081
- id: "STORAGE_DYNAMODB_STORE_GET_MESSAGES_FAILED",
1082
- domain: ErrorDomain.STORAGE,
1083
- category: ErrorCategory.THIRD_PARTY,
1084
- details: { threadId }
1085
- },
1086
- error
1087
- );
1088
- }
1089
- }
1090
- async saveMessages(args) {
1091
- const { messages, format = "v1" } = args;
1092
- this.logger.debug("Saving messages", { count: messages.length });
1093
- if (!messages.length) {
1094
- return [];
1095
- }
1096
- const threadId = messages[0]?.threadId;
1097
- if (!threadId) {
1098
- throw new Error("Thread ID is required");
1099
- }
1100
- const messagesToSave = messages.map((msg) => {
1101
- const now = (/* @__PURE__ */ new Date()).toISOString();
2289
+ let allScores = results.data.map((data) => this.parseScoreData(data));
2290
+ allScores = allScores.filter((score) => score.entityType === entityType);
2291
+ allScores.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
2292
+ const startIndex = pagination.page * pagination.perPage;
2293
+ const endIndex = startIndex + pagination.perPage;
2294
+ const paginatedScores = allScores.slice(startIndex, endIndex);
2295
+ const total = allScores.length;
2296
+ const hasMore = endIndex < total;
1102
2297
  return {
1103
- entity: "message",
1104
- // Add entity type
1105
- id: msg.id,
1106
- threadId: msg.threadId,
1107
- role: msg.role,
1108
- type: msg.type,
1109
- resourceId: msg.resourceId,
1110
- // Ensure complex fields are stringified if not handled by attribute setters
1111
- content: typeof msg.content === "string" ? msg.content : JSON.stringify(msg.content),
1112
- toolCallArgs: `toolCallArgs` in msg && msg.toolCallArgs ? JSON.stringify(msg.toolCallArgs) : void 0,
1113
- toolCallIds: `toolCallIds` in msg && msg.toolCallIds ? JSON.stringify(msg.toolCallIds) : void 0,
1114
- toolNames: `toolNames` in msg && msg.toolNames ? JSON.stringify(msg.toolNames) : void 0,
1115
- createdAt: msg.createdAt instanceof Date ? msg.createdAt.toISOString() : msg.createdAt || now,
1116
- updatedAt: now
1117
- // Add updatedAt
2298
+ scores: paginatedScores,
2299
+ pagination: {
2300
+ total,
2301
+ page: pagination.page,
2302
+ perPage: pagination.perPage,
2303
+ hasMore
2304
+ }
1118
2305
  };
1119
- });
1120
- try {
1121
- const batchSize = 25;
1122
- const batches = [];
1123
- for (let i = 0; i < messagesToSave.length; i += batchSize) {
1124
- const batch = messagesToSave.slice(i, i + batchSize);
1125
- batches.push(batch);
1126
- }
1127
- await Promise.all([
1128
- // Process message batches
1129
- ...batches.map(async (batch) => {
1130
- for (const messageData of batch) {
1131
- if (!messageData.entity) {
1132
- this.logger.error("Missing entity property in message data for create", { messageData });
1133
- throw new Error("Internal error: Missing entity property during saveMessages");
1134
- }
1135
- await this.service.entities.message.put(messageData).go();
1136
- }
1137
- }),
1138
- // Update thread's updatedAt timestamp
1139
- this.service.entities.thread.update({ entity: "thread", id: threadId }).set({
1140
- updatedAt: (/* @__PURE__ */ new Date()).toISOString()
1141
- }).go()
1142
- ]);
1143
- const list = new MessageList().add(messages, "memory");
1144
- if (format === `v1`) return list.get.all.v1();
1145
- return list.get.all.v2();
1146
2306
  } catch (error) {
1147
2307
  throw new MastraError(
1148
2308
  {
1149
- id: "STORAGE_DYNAMODB_STORE_SAVE_MESSAGES_FAILED",
2309
+ id: "STORAGE_DYNAMODB_STORE_GET_SCORES_BY_ENTITY_ID_FAILED",
1150
2310
  domain: ErrorDomain.STORAGE,
1151
2311
  category: ErrorCategory.THIRD_PARTY,
1152
- details: { count: messages.length }
2312
+ details: { entityId, entityType, page: pagination.page, perPage: pagination.perPage }
1153
2313
  },
1154
2314
  error
1155
2315
  );
1156
2316
  }
1157
2317
  }
1158
- // Helper function to parse message data (handle JSON fields)
1159
- parseMessageData(data) {
1160
- return {
1161
- ...data,
1162
- // Ensure dates are Date objects if needed (ElectroDB might return strings)
1163
- createdAt: data.createdAt ? new Date(data.createdAt) : void 0,
1164
- updatedAt: data.updatedAt ? new Date(data.updatedAt) : void 0
1165
- // Other fields like content, toolCallArgs etc. are assumed to be correctly
1166
- // transformed by the ElectroDB entity getters.
1167
- };
2318
+ };
2319
+ var TracesStorageDynamoDB = class extends TracesStorage {
2320
+ service;
2321
+ operations;
2322
+ constructor({ service, operations }) {
2323
+ super();
2324
+ this.service = service;
2325
+ this.operations = operations;
1168
2326
  }
1169
2327
  // Trace operations
1170
2328
  async getTraces(args) {
@@ -1215,7 +2373,7 @@ var DynamoDBStore = class extends MastraStorage {
1215
2373
  }
1216
2374
  try {
1217
2375
  const recordsToSave = records.map((rec) => ({ entity: "trace", ...rec }));
1218
- await this.batchInsert({
2376
+ await this.operations.batchInsert({
1219
2377
  tableName: TABLE_TRACES,
1220
2378
  records: recordsToSave
1221
2379
  // Pass records with 'entity' included
@@ -1223,15 +2381,190 @@ var DynamoDBStore = class extends MastraStorage {
1223
2381
  } catch (error) {
1224
2382
  throw new MastraError(
1225
2383
  {
1226
- id: "STORAGE_DYNAMODB_STORE_BATCH_TRACE_INSERT_FAILED",
2384
+ id: "STORAGE_DYNAMODB_STORE_BATCH_TRACE_INSERT_FAILED",
2385
+ domain: ErrorDomain.STORAGE,
2386
+ category: ErrorCategory.THIRD_PARTY,
2387
+ details: { count: records.length }
2388
+ },
2389
+ error
2390
+ );
2391
+ }
2392
+ }
2393
+ async getTracesPaginated(args) {
2394
+ const { name, scope, page = 0, perPage = 100, attributes, filters, dateRange } = args;
2395
+ this.logger.debug("Getting traces with pagination", { name, scope, page, perPage, attributes, filters, dateRange });
2396
+ try {
2397
+ let query;
2398
+ if (name) {
2399
+ query = this.service.entities.trace.query.byName({ entity: "trace", name });
2400
+ } else if (scope) {
2401
+ query = this.service.entities.trace.query.byScope({ entity: "trace", scope });
2402
+ } else {
2403
+ this.logger.warn("Performing a scan operation on traces - consider using a more specific query");
2404
+ query = this.service.entities.trace.scan;
2405
+ }
2406
+ const results = await query.go({
2407
+ order: "desc",
2408
+ pages: "all"
2409
+ // Get all pages to apply filtering and pagination
2410
+ });
2411
+ if (!results.data.length) {
2412
+ return {
2413
+ traces: [],
2414
+ total: 0,
2415
+ page,
2416
+ perPage,
2417
+ hasMore: false
2418
+ };
2419
+ }
2420
+ let filteredData = results.data;
2421
+ if (attributes) {
2422
+ filteredData = filteredData.filter((item) => {
2423
+ try {
2424
+ let itemAttributes = {};
2425
+ if (item.attributes) {
2426
+ if (typeof item.attributes === "string") {
2427
+ if (item.attributes === "[object Object]") {
2428
+ itemAttributes = {};
2429
+ } else {
2430
+ try {
2431
+ itemAttributes = JSON.parse(item.attributes);
2432
+ } catch {
2433
+ itemAttributes = {};
2434
+ }
2435
+ }
2436
+ } else if (typeof item.attributes === "object") {
2437
+ itemAttributes = item.attributes;
2438
+ }
2439
+ }
2440
+ return Object.entries(attributes).every(([key, value]) => itemAttributes[key] === value);
2441
+ } catch (e) {
2442
+ this.logger.warn("Failed to parse attributes during filtering", { item, error: e });
2443
+ return false;
2444
+ }
2445
+ });
2446
+ }
2447
+ if (dateRange?.start) {
2448
+ filteredData = filteredData.filter((item) => {
2449
+ const itemDate = new Date(item.createdAt);
2450
+ return itemDate >= dateRange.start;
2451
+ });
2452
+ }
2453
+ if (dateRange?.end) {
2454
+ filteredData = filteredData.filter((item) => {
2455
+ const itemDate = new Date(item.createdAt);
2456
+ return itemDate <= dateRange.end;
2457
+ });
2458
+ }
2459
+ const total = filteredData.length;
2460
+ const start = page * perPage;
2461
+ const end = start + perPage;
2462
+ const paginatedData = filteredData.slice(start, end);
2463
+ const traces = paginatedData.map((item) => {
2464
+ let attributes2;
2465
+ if (item.attributes) {
2466
+ if (typeof item.attributes === "string") {
2467
+ if (item.attributes === "[object Object]") {
2468
+ attributes2 = void 0;
2469
+ } else {
2470
+ try {
2471
+ attributes2 = JSON.parse(item.attributes);
2472
+ } catch {
2473
+ attributes2 = void 0;
2474
+ }
2475
+ }
2476
+ } else if (typeof item.attributes === "object") {
2477
+ attributes2 = item.attributes;
2478
+ }
2479
+ }
2480
+ let status;
2481
+ if (item.status) {
2482
+ if (typeof item.status === "string") {
2483
+ try {
2484
+ status = JSON.parse(item.status);
2485
+ } catch {
2486
+ status = void 0;
2487
+ }
2488
+ } else if (typeof item.status === "object") {
2489
+ status = item.status;
2490
+ }
2491
+ }
2492
+ let events;
2493
+ if (item.events) {
2494
+ if (typeof item.events === "string") {
2495
+ try {
2496
+ events = JSON.parse(item.events);
2497
+ } catch {
2498
+ events = void 0;
2499
+ }
2500
+ } else if (Array.isArray(item.events)) {
2501
+ events = item.events;
2502
+ }
2503
+ }
2504
+ let links;
2505
+ if (item.links) {
2506
+ if (typeof item.links === "string") {
2507
+ try {
2508
+ links = JSON.parse(item.links);
2509
+ } catch {
2510
+ links = void 0;
2511
+ }
2512
+ } else if (Array.isArray(item.links)) {
2513
+ links = item.links;
2514
+ }
2515
+ }
2516
+ return {
2517
+ id: item.id,
2518
+ parentSpanId: item.parentSpanId,
2519
+ name: item.name,
2520
+ traceId: item.traceId,
2521
+ scope: item.scope,
2522
+ kind: item.kind,
2523
+ attributes: attributes2,
2524
+ status,
2525
+ events,
2526
+ links,
2527
+ other: item.other,
2528
+ startTime: item.startTime,
2529
+ endTime: item.endTime,
2530
+ createdAt: item.createdAt
2531
+ };
2532
+ });
2533
+ return {
2534
+ traces,
2535
+ total,
2536
+ page,
2537
+ perPage,
2538
+ hasMore: end < total
2539
+ };
2540
+ } catch (error) {
2541
+ throw new MastraError(
2542
+ {
2543
+ id: "STORAGE_DYNAMODB_STORE_GET_TRACES_PAGINATED_FAILED",
1227
2544
  domain: ErrorDomain.STORAGE,
1228
- category: ErrorCategory.THIRD_PARTY,
1229
- details: { count: records.length }
2545
+ category: ErrorCategory.THIRD_PARTY
1230
2546
  },
1231
2547
  error
1232
2548
  );
1233
2549
  }
1234
2550
  }
2551
+ };
2552
+ function formatWorkflowRun(snapshotData) {
2553
+ return {
2554
+ workflowName: snapshotData.workflow_name,
2555
+ runId: snapshotData.run_id,
2556
+ snapshot: snapshotData.snapshot,
2557
+ createdAt: new Date(snapshotData.createdAt),
2558
+ updatedAt: new Date(snapshotData.updatedAt),
2559
+ resourceId: snapshotData.resourceId
2560
+ };
2561
+ }
2562
+ var WorkflowStorageDynamoDB = class extends WorkflowsStorage {
2563
+ service;
2564
+ constructor({ service }) {
2565
+ super();
2566
+ this.service = service;
2567
+ }
1235
2568
  // Workflow operations
1236
2569
  async persistWorkflowSnapshot({
1237
2570
  workflowName,
@@ -1253,7 +2586,7 @@ var DynamoDBStore = class extends MastraStorage {
1253
2586
  updatedAt: now,
1254
2587
  resourceId
1255
2588
  };
1256
- await this.service.entities.workflowSnapshot.upsert(data).go();
2589
+ await this.service.entities.workflow_snapshot.upsert(data).go();
1257
2590
  } catch (error) {
1258
2591
  throw new MastraError(
1259
2592
  {
@@ -1272,7 +2605,7 @@ var DynamoDBStore = class extends MastraStorage {
1272
2605
  }) {
1273
2606
  this.logger.debug("Loading workflow snapshot", { workflowName, runId });
1274
2607
  try {
1275
- const result = await this.service.entities.workflowSnapshot.get({
2608
+ const result = await this.service.entities.workflow_snapshot.get({
1276
2609
  entity: "workflow_snapshot",
1277
2610
  // Add entity type
1278
2611
  workflow_name: workflowName,
@@ -1301,14 +2634,14 @@ var DynamoDBStore = class extends MastraStorage {
1301
2634
  const offset = args?.offset || 0;
1302
2635
  let query;
1303
2636
  if (args?.workflowName) {
1304
- query = this.service.entities.workflowSnapshot.query.primary({
2637
+ query = this.service.entities.workflow_snapshot.query.primary({
1305
2638
  entity: "workflow_snapshot",
1306
2639
  // Add entity type
1307
2640
  workflow_name: args.workflowName
1308
2641
  });
1309
2642
  } else {
1310
2643
  this.logger.warn("Performing a scan operation on workflow snapshots - consider using a more specific query");
1311
- query = this.service.entities.workflowSnapshot.scan;
2644
+ query = this.service.entities.workflow_snapshot.scan;
1312
2645
  }
1313
2646
  const allMatchingSnapshots = [];
1314
2647
  let cursor = null;
@@ -1346,7 +2679,7 @@ var DynamoDBStore = class extends MastraStorage {
1346
2679
  }
1347
2680
  const total = allMatchingSnapshots.length;
1348
2681
  const paginatedData = allMatchingSnapshots.slice(offset, offset + limit);
1349
- const runs = paginatedData.map((snapshot) => this.formatWorkflowRun(snapshot));
2682
+ const runs = paginatedData.map((snapshot) => formatWorkflowRun(snapshot));
1350
2683
  return {
1351
2684
  runs,
1352
2685
  total
@@ -1366,15 +2699,18 @@ var DynamoDBStore = class extends MastraStorage {
1366
2699
  async getWorkflowRunById(args) {
1367
2700
  const { runId, workflowName } = args;
1368
2701
  this.logger.debug("Getting workflow run by ID", { runId, workflowName });
2702
+ console.log("workflowName", workflowName);
2703
+ console.log("runId", runId);
1369
2704
  try {
1370
2705
  if (workflowName) {
1371
2706
  this.logger.debug("WorkflowName provided, using direct GET operation.");
1372
- const result2 = await this.service.entities.workflowSnapshot.get({
2707
+ const result2 = await this.service.entities.workflow_snapshot.get({
1373
2708
  entity: "workflow_snapshot",
1374
2709
  // Entity type for PK
1375
2710
  workflow_name: workflowName,
1376
2711
  run_id: runId
1377
2712
  }).go();
2713
+ console.log("result", result2);
1378
2714
  if (!result2.data) {
1379
2715
  return null;
1380
2716
  }
@@ -1391,7 +2727,7 @@ var DynamoDBStore = class extends MastraStorage {
1391
2727
  this.logger.debug(
1392
2728
  'WorkflowName not provided. Attempting to find workflow run by runId using GSI. Ensure GSI (e.g., "byRunId") is defined on the workflowSnapshot entity with run_id as its key and provisioned in DynamoDB.'
1393
2729
  );
1394
- const result = await this.service.entities.workflowSnapshot.query.gsi2({ entity: "workflow_snapshot", run_id: runId }).go();
2730
+ const result = await this.service.entities.workflow_snapshot.query.gsi2({ entity: "workflow_snapshot", run_id: runId }).go();
1395
2731
  const matchingRunDbItem = result.data && result.data.length > 0 ? result.data[0] : null;
1396
2732
  if (!matchingRunDbItem) {
1397
2733
  return null;
@@ -1417,121 +2753,248 @@ var DynamoDBStore = class extends MastraStorage {
1417
2753
  );
1418
2754
  }
1419
2755
  }
1420
- // Helper function to format workflow run
1421
- formatWorkflowRun(snapshotData) {
1422
- return {
1423
- workflowName: snapshotData.workflow_name,
1424
- runId: snapshotData.run_id,
1425
- snapshot: snapshotData.snapshot,
1426
- createdAt: new Date(snapshotData.createdAt),
1427
- updatedAt: new Date(snapshotData.updatedAt),
1428
- resourceId: snapshotData.resourceId
1429
- };
2756
+ };
2757
+
2758
+ // src/storage/index.ts
2759
+ var DynamoDBStore = class extends MastraStorage {
2760
+ tableName;
2761
+ client;
2762
+ service;
2763
+ hasInitialized = null;
2764
+ stores;
2765
+ constructor({ name, config }) {
2766
+ super({ name });
2767
+ try {
2768
+ if (!config.tableName || typeof config.tableName !== "string" || config.tableName.trim() === "") {
2769
+ throw new Error("DynamoDBStore: config.tableName must be provided and cannot be empty.");
2770
+ }
2771
+ if (!/^[a-zA-Z0-9_.-]{3,255}$/.test(config.tableName)) {
2772
+ throw new Error(
2773
+ `DynamoDBStore: config.tableName "${config.tableName}" contains invalid characters or is not between 3 and 255 characters long.`
2774
+ );
2775
+ }
2776
+ const dynamoClient = new DynamoDBClient({
2777
+ region: config.region || "us-east-1",
2778
+ endpoint: config.endpoint,
2779
+ credentials: config.credentials
2780
+ });
2781
+ this.tableName = config.tableName;
2782
+ this.client = DynamoDBDocumentClient.from(dynamoClient);
2783
+ this.service = getElectroDbService(this.client, this.tableName);
2784
+ const operations = new StoreOperationsDynamoDB({
2785
+ service: this.service,
2786
+ tableName: this.tableName,
2787
+ client: this.client
2788
+ });
2789
+ const traces = new TracesStorageDynamoDB({ service: this.service, operations });
2790
+ const workflows = new WorkflowStorageDynamoDB({ service: this.service });
2791
+ const memory = new MemoryStorageDynamoDB({ service: this.service });
2792
+ const scores = new ScoresStorageDynamoDB({ service: this.service });
2793
+ this.stores = {
2794
+ operations,
2795
+ legacyEvals: new LegacyEvalsDynamoDB({ service: this.service, tableName: this.tableName }),
2796
+ traces,
2797
+ workflows,
2798
+ memory,
2799
+ scores
2800
+ };
2801
+ } catch (error) {
2802
+ throw new MastraError(
2803
+ {
2804
+ id: "STORAGE_DYNAMODB_STORE_CONSTRUCTOR_FAILED",
2805
+ domain: ErrorDomain.STORAGE,
2806
+ category: ErrorCategory.USER
2807
+ },
2808
+ error
2809
+ );
2810
+ }
1430
2811
  }
1431
- // Helper methods for entity/table mapping
1432
- getEntityNameForTable(tableName) {
1433
- const mapping = {
1434
- [TABLE_THREADS]: "thread",
1435
- [TABLE_MESSAGES]: "message",
1436
- [TABLE_WORKFLOW_SNAPSHOT]: "workflowSnapshot",
1437
- [TABLE_EVALS]: "eval",
1438
- [TABLE_TRACES]: "trace"
2812
+ get supports() {
2813
+ return {
2814
+ selectByIncludeResourceScope: true,
2815
+ resourceWorkingMemory: true,
2816
+ hasColumn: false,
2817
+ createTable: false,
2818
+ deleteMessages: false
1439
2819
  };
1440
- return mapping[tableName] || null;
1441
2820
  }
1442
- // Eval operations
1443
- async getEvalsByAgentName(agentName, type) {
1444
- this.logger.debug("Getting evals for agent", { agentName, type });
2821
+ /**
2822
+ * Validates that the required DynamoDB table exists and is accessible.
2823
+ * This does not check the table structure - it assumes the table
2824
+ * was created with the correct structure via CDK/CloudFormation.
2825
+ */
2826
+ async validateTableExists() {
1445
2827
  try {
1446
- const query = this.service.entities.eval.query.byAgent({ entity: "eval", agent_name: agentName });
1447
- const results = await query.go({ order: "desc", limit: 100 });
1448
- if (!results.data.length) {
1449
- return [];
1450
- }
1451
- let filteredData = results.data;
1452
- if (type) {
1453
- filteredData = filteredData.filter((evalRecord) => {
1454
- try {
1455
- const testInfo = evalRecord.test_info && typeof evalRecord.test_info === "string" ? JSON.parse(evalRecord.test_info) : void 0;
1456
- if (type === "test" && !testInfo) {
1457
- return false;
1458
- }
1459
- if (type === "live" && testInfo) {
1460
- return false;
1461
- }
1462
- } catch (e) {
1463
- this.logger.warn("Failed to parse test_info during filtering", { record: evalRecord, error: e });
1464
- }
1465
- return true;
1466
- });
1467
- }
1468
- return filteredData.map((evalRecord) => {
1469
- try {
1470
- return {
1471
- input: evalRecord.input,
1472
- output: evalRecord.output,
1473
- // Safely parse result and test_info
1474
- result: evalRecord.result && typeof evalRecord.result === "string" ? JSON.parse(evalRecord.result) : void 0,
1475
- agentName: evalRecord.agent_name,
1476
- createdAt: evalRecord.created_at,
1477
- // Keep as string from DDB?
1478
- metricName: evalRecord.metric_name,
1479
- instructions: evalRecord.instructions,
1480
- runId: evalRecord.run_id,
1481
- globalRunId: evalRecord.global_run_id,
1482
- testInfo: evalRecord.test_info && typeof evalRecord.test_info === "string" ? JSON.parse(evalRecord.test_info) : void 0
1483
- };
1484
- } catch (parseError) {
1485
- this.logger.error("Failed to parse eval record", { record: evalRecord, error: parseError });
1486
- return {
1487
- agentName: evalRecord.agent_name,
1488
- createdAt: evalRecord.created_at,
1489
- runId: evalRecord.run_id,
1490
- globalRunId: evalRecord.global_run_id
1491
- };
1492
- }
2828
+ const command = new DescribeTableCommand({
2829
+ TableName: this.tableName
1493
2830
  });
2831
+ await this.client.send(command);
2832
+ return true;
2833
+ } catch (error) {
2834
+ if (error.name === "ResourceNotFoundException") {
2835
+ return false;
2836
+ }
2837
+ throw new MastraError(
2838
+ {
2839
+ id: "STORAGE_DYNAMODB_STORE_VALIDATE_TABLE_EXISTS_FAILED",
2840
+ domain: ErrorDomain.STORAGE,
2841
+ category: ErrorCategory.THIRD_PARTY,
2842
+ details: { tableName: this.tableName }
2843
+ },
2844
+ error
2845
+ );
2846
+ }
2847
+ }
2848
+ /**
2849
+ * Initialize storage, validating the externally managed table is accessible.
2850
+ * For the single-table design, we only validate once that we can access
2851
+ * the table that was created via CDK/CloudFormation.
2852
+ */
2853
+ async init() {
2854
+ if (this.hasInitialized === null) {
2855
+ this.hasInitialized = this._performInitializationAndStore();
2856
+ }
2857
+ try {
2858
+ await this.hasInitialized;
1494
2859
  } catch (error) {
1495
2860
  throw new MastraError(
1496
2861
  {
1497
- id: "STORAGE_DYNAMODB_STORE_GET_EVALS_BY_AGENT_NAME_FAILED",
2862
+ id: "STORAGE_DYNAMODB_STORE_INIT_FAILED",
1498
2863
  domain: ErrorDomain.STORAGE,
1499
2864
  category: ErrorCategory.THIRD_PARTY,
1500
- details: { agentName }
2865
+ details: { tableName: this.tableName }
1501
2866
  },
1502
2867
  error
1503
2868
  );
1504
2869
  }
1505
2870
  }
2871
+ /**
2872
+ * Performs the actual table validation and stores the promise.
2873
+ * Handles resetting the stored promise on failure to allow retries.
2874
+ */
2875
+ _performInitializationAndStore() {
2876
+ return this.validateTableExists().then((exists) => {
2877
+ if (!exists) {
2878
+ throw new Error(
2879
+ `Table ${this.tableName} does not exist or is not accessible. Ensure it's created via CDK/CloudFormation before using this store.`
2880
+ );
2881
+ }
2882
+ return true;
2883
+ }).catch((err) => {
2884
+ this.hasInitialized = null;
2885
+ throw err;
2886
+ });
2887
+ }
2888
+ async createTable({ tableName, schema }) {
2889
+ return this.stores.operations.createTable({ tableName, schema });
2890
+ }
2891
+ async alterTable(_args) {
2892
+ return this.stores.operations.alterTable(_args);
2893
+ }
2894
+ async clearTable({ tableName }) {
2895
+ return this.stores.operations.clearTable({ tableName });
2896
+ }
2897
+ async dropTable({ tableName }) {
2898
+ return this.stores.operations.dropTable({ tableName });
2899
+ }
2900
+ async insert({ tableName, record }) {
2901
+ return this.stores.operations.insert({ tableName, record });
2902
+ }
2903
+ async batchInsert({ tableName, records }) {
2904
+ return this.stores.operations.batchInsert({ tableName, records });
2905
+ }
2906
+ async load({ tableName, keys }) {
2907
+ return this.stores.operations.load({ tableName, keys });
2908
+ }
2909
+ // Thread operations
2910
+ async getThreadById({ threadId }) {
2911
+ return this.stores.memory.getThreadById({ threadId });
2912
+ }
2913
+ async getThreadsByResourceId(args) {
2914
+ return this.stores.memory.getThreadsByResourceId(args);
2915
+ }
2916
+ async saveThread({ thread }) {
2917
+ return this.stores.memory.saveThread({ thread });
2918
+ }
2919
+ async updateThread({
2920
+ id,
2921
+ title,
2922
+ metadata
2923
+ }) {
2924
+ return this.stores.memory.updateThread({ id, title, metadata });
2925
+ }
2926
+ async deleteThread({ threadId }) {
2927
+ return this.stores.memory.deleteThread({ threadId });
2928
+ }
2929
+ async getMessages({
2930
+ threadId,
2931
+ resourceId,
2932
+ selectBy,
2933
+ format
2934
+ }) {
2935
+ return this.stores.memory.getMessages({ threadId, resourceId, selectBy, format });
2936
+ }
2937
+ async saveMessages(args) {
2938
+ return this.stores.memory.saveMessages(args);
2939
+ }
2940
+ async getThreadsByResourceIdPaginated(args) {
2941
+ return this.stores.memory.getThreadsByResourceIdPaginated(args);
2942
+ }
2943
+ async getMessagesPaginated(args) {
2944
+ return this.stores.memory.getMessagesPaginated(args);
2945
+ }
2946
+ async updateMessages(_args) {
2947
+ return this.stores.memory.updateMessages(_args);
2948
+ }
2949
+ // Trace operations
2950
+ async getTraces(args) {
2951
+ return this.stores.traces.getTraces(args);
2952
+ }
2953
+ async batchTraceInsert({ records }) {
2954
+ return this.stores.traces.batchTraceInsert({ records });
2955
+ }
1506
2956
  async getTracesPaginated(_args) {
1507
- throw new MastraError(
1508
- {
1509
- id: "STORAGE_DYNAMODB_STORE_GET_TRACES_PAGINATED_FAILED",
1510
- domain: ErrorDomain.STORAGE,
1511
- category: ErrorCategory.THIRD_PARTY
1512
- },
1513
- new Error("Method not implemented.")
1514
- );
2957
+ return this.stores.traces.getTracesPaginated(_args);
1515
2958
  }
1516
- async getThreadsByResourceIdPaginated(_args) {
1517
- throw new MastraError(
1518
- {
1519
- id: "STORAGE_DYNAMODB_STORE_GET_THREADS_BY_RESOURCE_ID_PAGINATED_FAILED",
1520
- domain: ErrorDomain.STORAGE,
1521
- category: ErrorCategory.THIRD_PARTY
1522
- },
1523
- new Error("Method not implemented.")
1524
- );
2959
+ // Workflow operations
2960
+ async persistWorkflowSnapshot({
2961
+ workflowName,
2962
+ runId,
2963
+ snapshot
2964
+ }) {
2965
+ return this.stores.workflows.persistWorkflowSnapshot({ workflowName, runId, snapshot });
1525
2966
  }
1526
- async getMessagesPaginated(_args) {
1527
- throw new MastraError(
1528
- {
1529
- id: "STORAGE_DYNAMODB_STORE_GET_MESSAGES_PAGINATED_FAILED",
1530
- domain: ErrorDomain.STORAGE,
1531
- category: ErrorCategory.THIRD_PARTY
1532
- },
1533
- new Error("Method not implemented.")
1534
- );
2967
+ async loadWorkflowSnapshot({
2968
+ workflowName,
2969
+ runId
2970
+ }) {
2971
+ return this.stores.workflows.loadWorkflowSnapshot({ workflowName, runId });
2972
+ }
2973
+ async getWorkflowRuns(args) {
2974
+ return this.stores.workflows.getWorkflowRuns(args);
2975
+ }
2976
+ async getWorkflowRunById(args) {
2977
+ return this.stores.workflows.getWorkflowRunById(args);
2978
+ }
2979
+ async getResourceById({ resourceId }) {
2980
+ return this.stores.memory.getResourceById({ resourceId });
2981
+ }
2982
+ async saveResource({ resource }) {
2983
+ return this.stores.memory.saveResource({ resource });
2984
+ }
2985
+ async updateResource({
2986
+ resourceId,
2987
+ workingMemory,
2988
+ metadata
2989
+ }) {
2990
+ return this.stores.memory.updateResource({ resourceId, workingMemory, metadata });
2991
+ }
2992
+ // Eval operations
2993
+ async getEvalsByAgentName(agentName, type) {
2994
+ return this.stores.legacyEvals.getEvalsByAgentName(agentName, type);
2995
+ }
2996
+ async getEvals(options) {
2997
+ return this.stores.legacyEvals.getEvals(options);
1535
2998
  }
1536
2999
  /**
1537
3000
  * Closes the DynamoDB client connection and cleans up resources.
@@ -1553,10 +3016,40 @@ var DynamoDBStore = class extends MastraStorage {
1553
3016
  );
1554
3017
  }
1555
3018
  }
1556
- async updateMessages(_args) {
1557
- this.logger.error("updateMessages is not yet implemented in DynamoDBStore");
1558
- throw new Error("Method not implemented");
3019
+ /**
3020
+ * SCORERS - Not implemented
3021
+ */
3022
+ async getScoreById({ id: _id }) {
3023
+ return this.stores.scores.getScoreById({ id: _id });
3024
+ }
3025
+ async saveScore(_score) {
3026
+ return this.stores.scores.saveScore(_score);
3027
+ }
3028
+ async getScoresByRunId({
3029
+ runId: _runId,
3030
+ pagination: _pagination
3031
+ }) {
3032
+ return this.stores.scores.getScoresByRunId({ runId: _runId, pagination: _pagination });
3033
+ }
3034
+ async getScoresByEntityId({
3035
+ entityId: _entityId,
3036
+ entityType: _entityType,
3037
+ pagination: _pagination
3038
+ }) {
3039
+ return this.stores.scores.getScoresByEntityId({
3040
+ entityId: _entityId,
3041
+ entityType: _entityType,
3042
+ pagination: _pagination
3043
+ });
3044
+ }
3045
+ async getScoresByScorerId({
3046
+ scorerId: _scorerId,
3047
+ pagination: _pagination
3048
+ }) {
3049
+ return this.stores.scores.getScoresByScorerId({ scorerId: _scorerId, pagination: _pagination });
1559
3050
  }
1560
3051
  };
1561
3052
 
1562
3053
  export { DynamoDBStore };
3054
+ //# sourceMappingURL=index.js.map
3055
+ //# sourceMappingURL=index.js.map