@mastra/dynamodb 0.0.0-pgvector-index-fix-20250905222058 → 0.0.0-playground-studio-cloud-20251031080052

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.
package/dist/index.cjs CHANGED
@@ -6,6 +6,7 @@ var error = require('@mastra/core/error');
6
6
  var storage = require('@mastra/core/storage');
7
7
  var electrodb = require('electrodb');
8
8
  var agent = require('@mastra/core/agent');
9
+ var scores = require('@mastra/core/scores');
9
10
 
10
11
  // src/storage/index.ts
11
12
 
@@ -372,6 +373,10 @@ var scoreEntity = new electrodb.Entity({
372
373
  type: "string",
373
374
  required: false
374
375
  },
376
+ spanId: {
377
+ type: "string",
378
+ required: false
379
+ },
375
380
  runId: {
376
381
  type: "string",
377
382
  required: true
@@ -658,6 +663,11 @@ var scoreEntity = new electrodb.Entity({
658
663
  index: "gsi6",
659
664
  pk: { field: "gsi6pk", composite: ["entity", "threadId"] },
660
665
  sk: { field: "gsi6sk", composite: ["createdAt"] }
666
+ },
667
+ bySpan: {
668
+ index: "gsi7",
669
+ pk: { field: "gsi7pk", composite: ["entity", "traceId", "spanId"] },
670
+ sk: { field: "gsi7sk", composite: ["createdAt"] }
661
671
  }
662
672
  }
663
673
  });
@@ -2036,6 +2046,10 @@ var StoreOperationsDynamoDB = class extends storage.StoreOperations {
2036
2046
  if (!item.id) throw new Error(`Missing required key 'id' for entity 'score'`);
2037
2047
  key.id = item.id;
2038
2048
  break;
2049
+ case "resource":
2050
+ if (!item.id) throw new Error(`Missing required key 'id' for entity 'resource'`);
2051
+ key.id = item.id;
2052
+ break;
2039
2053
  default:
2040
2054
  this.logger.warn(`Unknown entity type encountered during clearTable: ${entityName}`);
2041
2055
  throw new Error(`Cannot construct delete key for unknown entity type: ${entityName}`);
@@ -2178,34 +2192,47 @@ var ScoresStorageDynamoDB = class extends storage.ScoresStorage {
2178
2192
  }
2179
2193
  }
2180
2194
  async saveScore(score) {
2181
- this.logger.debug("Saving score", { scorerId: score.scorerId, runId: score.runId });
2195
+ let validatedScore;
2196
+ try {
2197
+ validatedScore = scores.saveScorePayloadSchema.parse(score);
2198
+ } catch (error$1) {
2199
+ throw new error.MastraError(
2200
+ {
2201
+ id: "STORAGE_DYNAMODB_STORE_SAVE_SCORE_FAILED",
2202
+ domain: error.ErrorDomain.STORAGE,
2203
+ category: error.ErrorCategory.THIRD_PARTY
2204
+ },
2205
+ error$1
2206
+ );
2207
+ }
2182
2208
  const now = /* @__PURE__ */ new Date();
2183
2209
  const scoreId = `score-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
2184
2210
  const scoreData = {
2185
2211
  entity: "score",
2186
2212
  id: scoreId,
2187
- scorerId: score.scorerId,
2188
- traceId: score.traceId || "",
2189
- runId: score.runId,
2190
- scorer: typeof score.scorer === "string" ? score.scorer : JSON.stringify(score.scorer),
2191
- preprocessStepResult: typeof score.preprocessStepResult === "string" ? score.preprocessStepResult : JSON.stringify(score.preprocessStepResult),
2192
- analyzeStepResult: typeof score.analyzeStepResult === "string" ? score.analyzeStepResult : JSON.stringify(score.analyzeStepResult),
2193
- score: score.score,
2194
- reason: score.reason,
2195
- preprocessPrompt: score.preprocessPrompt,
2196
- generateScorePrompt: score.generateScorePrompt,
2197
- analyzePrompt: score.analyzePrompt,
2198
- reasonPrompt: score.reasonPrompt,
2199
- input: typeof score.input === "string" ? score.input : JSON.stringify(score.input),
2200
- output: typeof score.output === "string" ? score.output : JSON.stringify(score.output),
2201
- additionalContext: typeof score.additionalContext === "string" ? score.additionalContext : JSON.stringify(score.additionalContext),
2202
- runtimeContext: typeof score.runtimeContext === "string" ? score.runtimeContext : JSON.stringify(score.runtimeContext),
2203
- entityType: score.entityType,
2204
- entityData: typeof score.entity === "string" ? score.entity : JSON.stringify(score.entity),
2205
- entityId: score.entityId,
2206
- source: score.source,
2207
- resourceId: score.resourceId || "",
2208
- threadId: score.threadId || "",
2213
+ scorerId: validatedScore.scorerId,
2214
+ traceId: validatedScore.traceId || "",
2215
+ spanId: validatedScore.spanId || "",
2216
+ runId: validatedScore.runId,
2217
+ scorer: typeof validatedScore.scorer === "string" ? validatedScore.scorer : JSON.stringify(validatedScore.scorer),
2218
+ preprocessStepResult: typeof validatedScore.preprocessStepResult === "string" ? validatedScore.preprocessStepResult : JSON.stringify(validatedScore.preprocessStepResult),
2219
+ analyzeStepResult: typeof validatedScore.analyzeStepResult === "string" ? validatedScore.analyzeStepResult : JSON.stringify(validatedScore.analyzeStepResult),
2220
+ score: validatedScore.score,
2221
+ reason: validatedScore.reason,
2222
+ preprocessPrompt: validatedScore.preprocessPrompt,
2223
+ generateScorePrompt: validatedScore.generateScorePrompt,
2224
+ generateReasonPrompt: validatedScore.generateReasonPrompt,
2225
+ analyzePrompt: validatedScore.analyzePrompt,
2226
+ input: typeof validatedScore.input === "string" ? validatedScore.input : JSON.stringify(validatedScore.input),
2227
+ output: typeof validatedScore.output === "string" ? validatedScore.output : JSON.stringify(validatedScore.output),
2228
+ additionalContext: typeof validatedScore.additionalContext === "string" ? validatedScore.additionalContext : JSON.stringify(validatedScore.additionalContext),
2229
+ runtimeContext: typeof validatedScore.runtimeContext === "string" ? validatedScore.runtimeContext : JSON.stringify(validatedScore.runtimeContext),
2230
+ entityType: validatedScore.entityType,
2231
+ entityData: typeof validatedScore.entity === "string" ? validatedScore.entity : JSON.stringify(validatedScore.entity),
2232
+ entityId: validatedScore.entityId,
2233
+ source: validatedScore.source,
2234
+ resourceId: validatedScore.resourceId || "",
2235
+ threadId: validatedScore.threadId || "",
2209
2236
  createdAt: now.toISOString(),
2210
2237
  updatedAt: now.toISOString()
2211
2238
  };
@@ -2358,234 +2385,38 @@ var ScoresStorageDynamoDB = class extends storage.ScoresStorage {
2358
2385
  );
2359
2386
  }
2360
2387
  }
2361
- };
2362
- var TracesStorageDynamoDB = class extends storage.TracesStorage {
2363
- service;
2364
- operations;
2365
- constructor({ service, operations }) {
2366
- super();
2367
- this.service = service;
2368
- this.operations = operations;
2369
- }
2370
- // Trace operations
2371
- async getTraces(args) {
2372
- const { name, scope, page, perPage } = args;
2373
- this.logger.debug("Getting traces", { name, scope, page, perPage });
2374
- try {
2375
- let query;
2376
- if (name) {
2377
- query = this.service.entities.trace.query.byName({ entity: "trace", name });
2378
- } else if (scope) {
2379
- query = this.service.entities.trace.query.byScope({ entity: "trace", scope });
2380
- } else {
2381
- this.logger.warn("Performing a scan operation on traces - consider using a more specific query");
2382
- query = this.service.entities.trace.scan;
2383
- }
2384
- let items = [];
2385
- let cursor = null;
2386
- let pagesFetched = 0;
2387
- const startPage = page > 0 ? page : 1;
2388
- do {
2389
- const results = await query.go({ cursor, limit: perPage });
2390
- pagesFetched++;
2391
- if (pagesFetched === startPage) {
2392
- items = results.data;
2393
- break;
2394
- }
2395
- cursor = results.cursor;
2396
- if (!cursor && results.data.length > 0 && pagesFetched < startPage) {
2397
- break;
2398
- }
2399
- } while (cursor && pagesFetched < startPage);
2400
- return items;
2401
- } catch (error$1) {
2402
- throw new error.MastraError(
2403
- {
2404
- id: "STORAGE_DYNAMODB_STORE_GET_TRACES_FAILED",
2405
- domain: error.ErrorDomain.STORAGE,
2406
- category: error.ErrorCategory.THIRD_PARTY
2407
- },
2408
- error$1
2409
- );
2410
- }
2411
- }
2412
- async batchTraceInsert({ records }) {
2413
- this.logger.debug("Batch inserting traces", { count: records.length });
2414
- if (!records.length) {
2415
- return;
2416
- }
2417
- try {
2418
- const recordsToSave = records.map((rec) => ({ entity: "trace", ...rec }));
2419
- await this.operations.batchInsert({
2420
- tableName: storage.TABLE_TRACES,
2421
- records: recordsToSave
2422
- // Pass records with 'entity' included
2423
- });
2424
- } catch (error$1) {
2425
- throw new error.MastraError(
2426
- {
2427
- id: "STORAGE_DYNAMODB_STORE_BATCH_TRACE_INSERT_FAILED",
2428
- domain: error.ErrorDomain.STORAGE,
2429
- category: error.ErrorCategory.THIRD_PARTY,
2430
- details: { count: records.length }
2431
- },
2432
- error$1
2433
- );
2434
- }
2435
- }
2436
- async getTracesPaginated(args) {
2437
- const { name, scope, page = 0, perPage = 100, attributes, filters, dateRange } = args;
2438
- this.logger.debug("Getting traces with pagination", { name, scope, page, perPage, attributes, filters, dateRange });
2388
+ async getScoresBySpan({
2389
+ traceId,
2390
+ spanId,
2391
+ pagination
2392
+ }) {
2393
+ this.logger.debug("Getting scores by span", { traceId, spanId, pagination });
2439
2394
  try {
2440
- let query;
2441
- if (name) {
2442
- query = this.service.entities.trace.query.byName({ entity: "trace", name });
2443
- } else if (scope) {
2444
- query = this.service.entities.trace.query.byScope({ entity: "trace", scope });
2445
- } else {
2446
- this.logger.warn("Performing a scan operation on traces - consider using a more specific query");
2447
- query = this.service.entities.trace.scan;
2448
- }
2449
- const results = await query.go({
2450
- order: "desc",
2451
- pages: "all"
2452
- // Get all pages to apply filtering and pagination
2453
- });
2454
- if (!results.data.length) {
2455
- return {
2456
- traces: [],
2457
- total: 0,
2458
- page,
2459
- perPage,
2460
- hasMore: false
2461
- };
2462
- }
2463
- let filteredData = results.data;
2464
- if (attributes) {
2465
- filteredData = filteredData.filter((item) => {
2466
- try {
2467
- let itemAttributes = {};
2468
- if (item.attributes) {
2469
- if (typeof item.attributes === "string") {
2470
- if (item.attributes === "[object Object]") {
2471
- itemAttributes = {};
2472
- } else {
2473
- try {
2474
- itemAttributes = JSON.parse(item.attributes);
2475
- } catch {
2476
- itemAttributes = {};
2477
- }
2478
- }
2479
- } else if (typeof item.attributes === "object") {
2480
- itemAttributes = item.attributes;
2481
- }
2482
- }
2483
- return Object.entries(attributes).every(([key, value]) => itemAttributes[key] === value);
2484
- } catch (e) {
2485
- this.logger.warn("Failed to parse attributes during filtering", { item, error: e });
2486
- return false;
2487
- }
2488
- });
2489
- }
2490
- if (dateRange?.start) {
2491
- filteredData = filteredData.filter((item) => {
2492
- const itemDate = new Date(item.createdAt);
2493
- return itemDate >= dateRange.start;
2494
- });
2495
- }
2496
- if (dateRange?.end) {
2497
- filteredData = filteredData.filter((item) => {
2498
- const itemDate = new Date(item.createdAt);
2499
- return itemDate <= dateRange.end;
2500
- });
2501
- }
2502
- const total = filteredData.length;
2503
- const start = page * perPage;
2504
- const end = start + perPage;
2505
- const paginatedData = filteredData.slice(start, end);
2506
- const traces = paginatedData.map((item) => {
2507
- let attributes2;
2508
- if (item.attributes) {
2509
- if (typeof item.attributes === "string") {
2510
- if (item.attributes === "[object Object]") {
2511
- attributes2 = void 0;
2512
- } else {
2513
- try {
2514
- attributes2 = JSON.parse(item.attributes);
2515
- } catch {
2516
- attributes2 = void 0;
2517
- }
2518
- }
2519
- } else if (typeof item.attributes === "object") {
2520
- attributes2 = item.attributes;
2521
- }
2522
- }
2523
- let status;
2524
- if (item.status) {
2525
- if (typeof item.status === "string") {
2526
- try {
2527
- status = JSON.parse(item.status);
2528
- } catch {
2529
- status = void 0;
2530
- }
2531
- } else if (typeof item.status === "object") {
2532
- status = item.status;
2533
- }
2534
- }
2535
- let events;
2536
- if (item.events) {
2537
- if (typeof item.events === "string") {
2538
- try {
2539
- events = JSON.parse(item.events);
2540
- } catch {
2541
- events = void 0;
2542
- }
2543
- } else if (Array.isArray(item.events)) {
2544
- events = item.events;
2545
- }
2546
- }
2547
- let links;
2548
- if (item.links) {
2549
- if (typeof item.links === "string") {
2550
- try {
2551
- links = JSON.parse(item.links);
2552
- } catch {
2553
- links = void 0;
2554
- }
2555
- } else if (Array.isArray(item.links)) {
2556
- links = item.links;
2557
- }
2558
- }
2559
- return {
2560
- id: item.id,
2561
- parentSpanId: item.parentSpanId,
2562
- name: item.name,
2563
- traceId: item.traceId,
2564
- scope: item.scope,
2565
- kind: item.kind,
2566
- attributes: attributes2,
2567
- status,
2568
- events,
2569
- links,
2570
- other: item.other,
2571
- startTime: item.startTime,
2572
- endTime: item.endTime,
2573
- createdAt: item.createdAt
2574
- };
2575
- });
2395
+ const query = this.service.entities.score.query.bySpan({ entity: "score", traceId, spanId });
2396
+ const results = await query.go();
2397
+ const allScores = results.data.map((data) => this.parseScoreData(data));
2398
+ allScores.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
2399
+ const startIndex = pagination.page * pagination.perPage;
2400
+ const endIndex = startIndex + pagination.perPage;
2401
+ const paginatedScores = allScores.slice(startIndex, endIndex);
2402
+ const total = allScores.length;
2403
+ const hasMore = endIndex < total;
2576
2404
  return {
2577
- traces,
2578
- total,
2579
- page,
2580
- perPage,
2581
- hasMore: end < total
2405
+ scores: paginatedScores,
2406
+ pagination: {
2407
+ total,
2408
+ page: pagination.page,
2409
+ perPage: pagination.perPage,
2410
+ hasMore
2411
+ }
2582
2412
  };
2583
2413
  } catch (error$1) {
2584
2414
  throw new error.MastraError(
2585
2415
  {
2586
- id: "STORAGE_DYNAMODB_STORE_GET_TRACES_PAGINATED_FAILED",
2416
+ id: "STORAGE_DYNAMODB_STORE_GET_SCORES_BY_SPAN_FAILED",
2587
2417
  domain: error.ErrorDomain.STORAGE,
2588
- category: error.ErrorCategory.THIRD_PARTY
2418
+ category: error.ErrorCategory.THIRD_PARTY,
2419
+ details: { traceId, spanId, page: pagination.page, perPage: pagination.perPage }
2589
2420
  },
2590
2421
  error$1
2591
2422
  );
@@ -2628,11 +2459,11 @@ var WorkflowStorageDynamoDB = class extends storage.WorkflowsStorage {
2628
2459
  async persistWorkflowSnapshot({
2629
2460
  workflowName,
2630
2461
  runId,
2462
+ resourceId,
2631
2463
  snapshot
2632
2464
  }) {
2633
2465
  this.logger.debug("Persisting workflow snapshot", { workflowName, runId });
2634
2466
  try {
2635
- const resourceId = "resourceId" in snapshot ? snapshot.resourceId : void 0;
2636
2467
  const now = (/* @__PURE__ */ new Date()).toISOString();
2637
2468
  const data = {
2638
2469
  entity: "workflow_snapshot",
@@ -2758,8 +2589,6 @@ var WorkflowStorageDynamoDB = class extends storage.WorkflowsStorage {
2758
2589
  async getWorkflowRunById(args) {
2759
2590
  const { runId, workflowName } = args;
2760
2591
  this.logger.debug("Getting workflow run by ID", { runId, workflowName });
2761
- console.log("workflowName", workflowName);
2762
- console.log("runId", runId);
2763
2592
  try {
2764
2593
  if (workflowName) {
2765
2594
  this.logger.debug("WorkflowName provided, using direct GET operation.");
@@ -2769,7 +2598,6 @@ var WorkflowStorageDynamoDB = class extends storage.WorkflowsStorage {
2769
2598
  workflow_name: workflowName,
2770
2599
  run_id: runId
2771
2600
  }).go();
2772
- console.log("result", result2);
2773
2601
  if (!result2.data) {
2774
2602
  return null;
2775
2603
  }
@@ -2845,14 +2673,12 @@ var DynamoDBStore = class extends storage.MastraStorage {
2845
2673
  tableName: this.tableName,
2846
2674
  client: this.client
2847
2675
  });
2848
- const traces = new TracesStorageDynamoDB({ service: this.service, operations });
2849
2676
  const workflows = new WorkflowStorageDynamoDB({ service: this.service });
2850
2677
  const memory = new MemoryStorageDynamoDB({ service: this.service });
2851
2678
  const scores = new ScoresStorageDynamoDB({ service: this.service });
2852
2679
  this.stores = {
2853
2680
  operations,
2854
2681
  legacyEvals: new LegacyEvalsDynamoDB({ service: this.service, tableName: this.tableName }),
2855
- traces,
2856
2682
  workflows,
2857
2683
  memory,
2858
2684
  scores
@@ -2874,7 +2700,8 @@ var DynamoDBStore = class extends storage.MastraStorage {
2874
2700
  resourceWorkingMemory: true,
2875
2701
  hasColumn: false,
2876
2702
  createTable: false,
2877
- deleteMessages: false
2703
+ deleteMessages: false,
2704
+ getScoresBySpan: true
2878
2705
  };
2879
2706
  }
2880
2707
  /**
@@ -3011,16 +2838,6 @@ var DynamoDBStore = class extends storage.MastraStorage {
3011
2838
  async updateMessages(_args) {
3012
2839
  return this.stores.memory.updateMessages(_args);
3013
2840
  }
3014
- // Trace operations
3015
- async getTraces(args) {
3016
- return this.stores.traces.getTraces(args);
3017
- }
3018
- async batchTraceInsert({ records }) {
3019
- return this.stores.traces.batchTraceInsert({ records });
3020
- }
3021
- async getTracesPaginated(_args) {
3022
- return this.stores.traces.getTracesPaginated(_args);
3023
- }
3024
2841
  // Workflow operations
3025
2842
  async updateWorkflowResults({
3026
2843
  workflowName,
@@ -3041,9 +2858,10 @@ var DynamoDBStore = class extends storage.MastraStorage {
3041
2858
  async persistWorkflowSnapshot({
3042
2859
  workflowName,
3043
2860
  runId,
2861
+ resourceId,
3044
2862
  snapshot
3045
2863
  }) {
3046
- return this.stores.workflows.persistWorkflowSnapshot({ workflowName, runId, snapshot });
2864
+ return this.stores.workflows.persistWorkflowSnapshot({ workflowName, runId, resourceId, snapshot });
3047
2865
  }
3048
2866
  async loadWorkflowSnapshot({
3049
2867
  workflowName,
@@ -3132,6 +2950,13 @@ var DynamoDBStore = class extends storage.MastraStorage {
3132
2950
  }) {
3133
2951
  return this.stores.scores.getScoresByScorerId({ scorerId, source, entityId, entityType, pagination });
3134
2952
  }
2953
+ async getScoresBySpan({
2954
+ traceId,
2955
+ spanId,
2956
+ pagination
2957
+ }) {
2958
+ return this.stores.scores.getScoresBySpan({ traceId, spanId, pagination });
2959
+ }
3135
2960
  };
3136
2961
 
3137
2962
  exports.DynamoDBStore = DynamoDBStore;