@mastra/cloudflare-d1 0.0.0-scorers-api-v2-20250801171841 → 0.0.0-scorers-logs-20251208093427

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.js CHANGED
@@ -1,8 +1,9 @@
1
1
  import { MastraError, ErrorCategory, ErrorDomain } from '@mastra/core/error';
2
- import { MastraStorage, StoreOperations, ScoresStorage, TABLE_SCORERS, LegacyEvalsStorage, TABLE_EVALS, serializeDate, TracesStorage, TABLE_TRACES, WorkflowsStorage, TABLE_WORKFLOW_SNAPSHOT, ensureDate, MemoryStorage, TABLE_RESOURCES, TABLE_THREADS, TABLE_MESSAGES, resolveMessageLimit } from '@mastra/core/storage';
2
+ import { MastraStorage, createStorageErrorId, StoreOperations, ScoresStorage, TABLE_SCORERS, normalizePerPage, calculatePagination, WorkflowsStorage, TABLE_WORKFLOW_SNAPSHOT, ensureDate, MemoryStorage, TABLE_RESOURCES, TABLE_THREADS, TABLE_MESSAGES, serializeDate, transformScoreRow as transformScoreRow$1 } from '@mastra/core/storage';
3
3
  import Cloudflare from 'cloudflare';
4
- import { parseSqlIdentifier } from '@mastra/core/utils';
5
4
  import { MessageList } from '@mastra/core/agent';
5
+ import { parseSqlIdentifier } from '@mastra/core/utils';
6
+ import { saveScorePayloadSchema } from '@mastra/core/evals';
6
7
 
7
8
  // src/storage/index.ts
8
9
  var SqlBuilder = class {
@@ -241,16 +242,6 @@ function isArrayOfRecords(value) {
241
242
  }
242
243
  function deserializeValue(value, type) {
243
244
  if (value === null || value === void 0) return null;
244
- if (type === "date" && typeof value === "string") {
245
- return new Date(value);
246
- }
247
- if (type === "jsonb" && typeof value === "string") {
248
- try {
249
- return JSON.parse(value);
250
- } catch {
251
- return value;
252
- }
253
- }
254
245
  if (typeof value === "string" && (value.startsWith("{") || value.startsWith("["))) {
255
246
  try {
256
247
  return JSON.parse(value);
@@ -261,155 +252,7 @@ function deserializeValue(value, type) {
261
252
  return value;
262
253
  }
263
254
 
264
- // src/storage/domains/legacy-evals/index.ts
265
- var LegacyEvalsStorageD1 = class extends LegacyEvalsStorage {
266
- operations;
267
- constructor({ operations }) {
268
- super();
269
- this.operations = operations;
270
- }
271
- async getEvals(options) {
272
- const { agentName, type, page = 0, perPage = 40, dateRange } = options || {};
273
- const fullTableName = this.operations.getTableName(TABLE_EVALS);
274
- const conditions = [];
275
- const queryParams = [];
276
- if (agentName) {
277
- conditions.push(`agent_name = ?`);
278
- queryParams.push(agentName);
279
- }
280
- if (type === "test") {
281
- conditions.push(`(test_info IS NOT NULL AND json_extract(test_info, '$.testPath') IS NOT NULL)`);
282
- } else if (type === "live") {
283
- conditions.push(`(test_info IS NULL OR json_extract(test_info, '$.testPath') IS NULL)`);
284
- }
285
- if (dateRange?.start) {
286
- conditions.push(`created_at >= ?`);
287
- queryParams.push(serializeDate(dateRange.start));
288
- }
289
- if (dateRange?.end) {
290
- conditions.push(`created_at <= ?`);
291
- queryParams.push(serializeDate(dateRange.end));
292
- }
293
- const countQueryBuilder = createSqlBuilder().count().from(fullTableName);
294
- if (conditions.length > 0) {
295
- countQueryBuilder.where(conditions.join(" AND "), ...queryParams);
296
- }
297
- const { sql: countSql, params: countParams } = countQueryBuilder.build();
298
- try {
299
- const countResult = await this.operations.executeQuery({
300
- sql: countSql,
301
- params: countParams,
302
- first: true
303
- });
304
- const total = Number(countResult?.count || 0);
305
- const currentOffset = page * perPage;
306
- if (total === 0) {
307
- return {
308
- evals: [],
309
- total: 0,
310
- page,
311
- perPage,
312
- hasMore: false
313
- };
314
- }
315
- const dataQueryBuilder = createSqlBuilder().select("*").from(fullTableName);
316
- if (conditions.length > 0) {
317
- dataQueryBuilder.where(conditions.join(" AND "), ...queryParams);
318
- }
319
- dataQueryBuilder.orderBy("created_at", "DESC").limit(perPage).offset(currentOffset);
320
- const { sql: dataSql, params: dataParams } = dataQueryBuilder.build();
321
- const rows = await this.operations.executeQuery({
322
- sql: dataSql,
323
- params: dataParams
324
- });
325
- const evals = (isArrayOfRecords(rows) ? rows : []).map((row) => {
326
- const result = deserializeValue(row.result);
327
- const testInfo = row.test_info ? deserializeValue(row.test_info) : void 0;
328
- if (!result || typeof result !== "object" || !("score" in result)) {
329
- throw new Error(`Invalid MetricResult format: ${JSON.stringify(result)}`);
330
- }
331
- return {
332
- input: row.input,
333
- output: row.output,
334
- result,
335
- agentName: row.agent_name,
336
- metricName: row.metric_name,
337
- instructions: row.instructions,
338
- testInfo,
339
- globalRunId: row.global_run_id,
340
- runId: row.run_id,
341
- createdAt: row.created_at
342
- };
343
- });
344
- const hasMore = currentOffset + evals.length < total;
345
- return {
346
- evals,
347
- total,
348
- page,
349
- perPage,
350
- hasMore
351
- };
352
- } catch (error) {
353
- throw new MastraError(
354
- {
355
- id: "CLOUDFLARE_D1_STORAGE_GET_EVALS_ERROR",
356
- domain: ErrorDomain.STORAGE,
357
- category: ErrorCategory.THIRD_PARTY,
358
- text: `Failed to retrieve evals for agent ${agentName}: ${error instanceof Error ? error.message : String(error)}`,
359
- details: { agentName: agentName ?? "", type: type ?? "" }
360
- },
361
- error
362
- );
363
- }
364
- }
365
- /**
366
- * @deprecated use getEvals instead
367
- */
368
- async getEvalsByAgentName(agentName, type) {
369
- const fullTableName = this.operations.getTableName(TABLE_EVALS);
370
- try {
371
- let query = createSqlBuilder().select("*").from(fullTableName).where("agent_name = ?", agentName);
372
- if (type === "test") {
373
- query = query.andWhere("test_info IS NOT NULL AND json_extract(test_info, '$.testPath') IS NOT NULL");
374
- } else if (type === "live") {
375
- query = query.andWhere("(test_info IS NULL OR json_extract(test_info, '$.testPath') IS NULL)");
376
- }
377
- query.orderBy("created_at", "DESC");
378
- const { sql, params } = query.build();
379
- const results = await this.operations.executeQuery({ sql, params });
380
- return isArrayOfRecords(results) ? results.map((row) => {
381
- const result = deserializeValue(row.result);
382
- const testInfo = row.test_info ? deserializeValue(row.test_info) : void 0;
383
- return {
384
- input: row.input || "",
385
- output: row.output || "",
386
- result,
387
- agentName: row.agent_name || "",
388
- metricName: row.metric_name || "",
389
- instructions: row.instructions || "",
390
- runId: row.run_id || "",
391
- globalRunId: row.global_run_id || "",
392
- createdAt: row.created_at || "",
393
- testInfo
394
- };
395
- }) : [];
396
- } catch (error) {
397
- const mastraError = new MastraError(
398
- {
399
- id: "CLOUDFLARE_D1_STORAGE_GET_EVALS_ERROR",
400
- domain: ErrorDomain.STORAGE,
401
- category: ErrorCategory.THIRD_PARTY,
402
- text: `Failed to retrieve evals for agent ${agentName}: ${error instanceof Error ? error.message : String(error)}`,
403
- details: { agentName }
404
- },
405
- error
406
- );
407
- this.logger?.error(mastraError.toString());
408
- this.logger?.trackException(mastraError);
409
- return [];
410
- }
411
- }
412
- };
255
+ // src/storage/domains/memory/index.ts
413
256
  var MemoryStorageD1 = class extends MemoryStorage {
414
257
  operations;
415
258
  constructor({ operations }) {
@@ -432,7 +275,7 @@ var MemoryStorageD1 = class extends MemoryStorage {
432
275
  } catch (error) {
433
276
  const mastraError = new MastraError(
434
277
  {
435
- id: "CLOUDFLARE_D1_STORAGE_GET_RESOURCE_BY_ID_ERROR",
278
+ id: createStorageErrorId("CLOUDFLARE_D1", "GET_RESOURCE_BY_ID", "FAILED"),
436
279
  domain: ErrorDomain.STORAGE,
437
280
  category: ErrorCategory.THIRD_PARTY,
438
281
  text: `Error processing resource ${resourceId}: ${error instanceof Error ? error.message : String(error)}`,
@@ -471,7 +314,7 @@ var MemoryStorageD1 = class extends MemoryStorage {
471
314
  } catch (error) {
472
315
  throw new MastraError(
473
316
  {
474
- id: "CLOUDFLARE_D1_STORAGE_SAVE_RESOURCE_ERROR",
317
+ id: createStorageErrorId("CLOUDFLARE_D1", "SAVE_RESOURCE", "FAILED"),
475
318
  domain: ErrorDomain.STORAGE,
476
319
  category: ErrorCategory.THIRD_PARTY,
477
320
  text: `Failed to save resource to ${fullTableName}: ${error instanceof Error ? error.message : String(error)}`,
@@ -518,7 +361,7 @@ var MemoryStorageD1 = class extends MemoryStorage {
518
361
  } catch (error) {
519
362
  throw new MastraError(
520
363
  {
521
- id: "CLOUDFLARE_D1_STORAGE_UPDATE_RESOURCE_ERROR",
364
+ id: createStorageErrorId("CLOUDFLARE_D1", "UPDATE_RESOURCE", "FAILED"),
522
365
  domain: ErrorDomain.STORAGE,
523
366
  category: ErrorCategory.THIRD_PARTY,
524
367
  text: `Failed to update resource ${resourceId}: ${error instanceof Error ? error.message : String(error)}`,
@@ -534,7 +377,6 @@ var MemoryStorageD1 = class extends MemoryStorage {
534
377
  keys: { id: threadId }
535
378
  });
536
379
  if (!thread) return null;
537
- console.log("thread", thread);
538
380
  try {
539
381
  return {
540
382
  ...thread,
@@ -545,7 +387,7 @@ var MemoryStorageD1 = class extends MemoryStorage {
545
387
  } catch (error) {
546
388
  const mastraError = new MastraError(
547
389
  {
548
- id: "CLOUDFLARE_D1_STORAGE_GET_THREAD_BY_ID_ERROR",
390
+ id: createStorageErrorId("CLOUDFLARE_D1", "GET_THREAD_BY_ID", "FAILED"),
549
391
  domain: ErrorDomain.STORAGE,
550
392
  category: ErrorCategory.THIRD_PARTY,
551
393
  text: `Error processing thread ${threadId}: ${error instanceof Error ? error.message : String(error)}`,
@@ -558,39 +400,22 @@ var MemoryStorageD1 = class extends MemoryStorage {
558
400
  return null;
559
401
  }
560
402
  }
561
- /**
562
- * @deprecated use getThreadsByResourceIdPaginated instead
563
- */
564
- async getThreadsByResourceId({ resourceId }) {
565
- const fullTableName = this.operations.getTableName(TABLE_THREADS);
566
- try {
567
- const query = createSqlBuilder().select("*").from(fullTableName).where("resourceId = ?", resourceId);
568
- const { sql, params } = query.build();
569
- const results = await this.operations.executeQuery({ sql, params });
570
- return (isArrayOfRecords(results) ? results : []).map((thread) => ({
571
- ...thread,
572
- createdAt: ensureDate(thread.createdAt),
573
- updatedAt: ensureDate(thread.updatedAt),
574
- metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata || "{}") : thread.metadata || {}
575
- }));
576
- } catch (error) {
577
- const mastraError = new MastraError(
403
+ async listThreadsByResourceId(args) {
404
+ const { resourceId, page = 0, perPage: perPageInput, orderBy } = args;
405
+ const perPage = normalizePerPage(perPageInput, 100);
406
+ if (page < 0) {
407
+ throw new MastraError(
578
408
  {
579
- id: "CLOUDFLARE_D1_STORAGE_GET_THREADS_BY_RESOURCE_ID_ERROR",
409
+ id: createStorageErrorId("CLOUDFLARE_D1", "LIST_THREADS_BY_RESOURCE_ID", "INVALID_PAGE"),
580
410
  domain: ErrorDomain.STORAGE,
581
- category: ErrorCategory.THIRD_PARTY,
582
- text: `Error getting threads by resourceId ${resourceId}: ${error instanceof Error ? error.message : String(error)}`,
583
- details: { resourceId }
411
+ category: ErrorCategory.USER,
412
+ details: { page }
584
413
  },
585
- error
414
+ new Error("page must be >= 0")
586
415
  );
587
- this.logger?.error(mastraError.toString());
588
- this.logger?.trackException(mastraError);
589
- return [];
590
416
  }
591
- }
592
- async getThreadsByResourceIdPaginated(args) {
593
- const { resourceId, page, perPage } = args;
417
+ const { offset, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
418
+ const { field, direction } = this.parseOrderBy(orderBy);
594
419
  const fullTableName = this.operations.getTableName(TABLE_THREADS);
595
420
  const mapRowToStorageThreadType = (row) => ({
596
421
  ...row,
@@ -602,20 +427,21 @@ var MemoryStorageD1 = class extends MemoryStorage {
602
427
  const countQuery = createSqlBuilder().count().from(fullTableName).where("resourceId = ?", resourceId);
603
428
  const countResult = await this.operations.executeQuery(countQuery.build());
604
429
  const total = Number(countResult?.[0]?.count ?? 0);
605
- const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("resourceId = ?", resourceId).orderBy("createdAt", "DESC").limit(perPage).offset(page * perPage);
430
+ const limitValue = perPageInput === false ? total : perPage;
431
+ const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("resourceId = ?", resourceId).orderBy(field, direction).limit(limitValue).offset(offset);
606
432
  const results = await this.operations.executeQuery(selectQuery.build());
607
433
  const threads = results.map(mapRowToStorageThreadType);
608
434
  return {
609
435
  threads,
610
436
  total,
611
437
  page,
612
- perPage,
613
- hasMore: page * perPage + threads.length < total
438
+ perPage: perPageForResponse,
439
+ hasMore: perPageInput === false ? false : offset + perPage < total
614
440
  };
615
441
  } catch (error) {
616
442
  const mastraError = new MastraError(
617
443
  {
618
- id: "CLOUDFLARE_D1_STORAGE_GET_THREADS_BY_RESOURCE_ID_PAGINATED_ERROR",
444
+ id: createStorageErrorId("CLOUDFLARE_D1", "LIST_THREADS_BY_RESOURCE_ID", "FAILED"),
619
445
  domain: ErrorDomain.STORAGE,
620
446
  category: ErrorCategory.THIRD_PARTY,
621
447
  text: `Error getting threads by resourceId ${resourceId}: ${error instanceof Error ? error.message : String(error)}`,
@@ -629,7 +455,7 @@ var MemoryStorageD1 = class extends MemoryStorage {
629
455
  threads: [],
630
456
  total: 0,
631
457
  page,
632
- perPage,
458
+ perPage: perPageForResponse,
633
459
  hasMore: false
634
460
  };
635
461
  }
@@ -662,7 +488,7 @@ var MemoryStorageD1 = class extends MemoryStorage {
662
488
  } catch (error) {
663
489
  throw new MastraError(
664
490
  {
665
- id: "CLOUDFLARE_D1_STORAGE_SAVE_THREAD_ERROR",
491
+ id: createStorageErrorId("CLOUDFLARE_D1", "SAVE_THREAD", "FAILED"),
666
492
  domain: ErrorDomain.STORAGE,
667
493
  category: ErrorCategory.THIRD_PARTY,
668
494
  text: `Failed to save thread to ${fullTableName}: ${error instanceof Error ? error.message : String(error)}`,
@@ -705,7 +531,7 @@ var MemoryStorageD1 = class extends MemoryStorage {
705
531
  } catch (error) {
706
532
  throw new MastraError(
707
533
  {
708
- id: "CLOUDFLARE_D1_STORAGE_UPDATE_THREAD_ERROR",
534
+ id: createStorageErrorId("CLOUDFLARE_D1", "UPDATE_THREAD", "FAILED"),
709
535
  domain: ErrorDomain.STORAGE,
710
536
  category: ErrorCategory.THIRD_PARTY,
711
537
  text: `Failed to update thread ${id}: ${error instanceof Error ? error.message : String(error)}`,
@@ -728,7 +554,7 @@ var MemoryStorageD1 = class extends MemoryStorage {
728
554
  } catch (error) {
729
555
  throw new MastraError(
730
556
  {
731
- id: "CLOUDFLARE_D1_STORAGE_DELETE_THREAD_ERROR",
557
+ id: createStorageErrorId("CLOUDFLARE_D1", "DELETE_THREAD", "FAILED"),
732
558
  domain: ErrorDomain.STORAGE,
733
559
  category: ErrorCategory.THIRD_PARTY,
734
560
  text: `Failed to delete thread ${threadId}: ${error instanceof Error ? error.message : String(error)}`,
@@ -739,8 +565,8 @@ var MemoryStorageD1 = class extends MemoryStorage {
739
565
  }
740
566
  }
741
567
  async saveMessages(args) {
742
- const { messages, format = "v1" } = args;
743
- if (messages.length === 0) return [];
568
+ const { messages } = args;
569
+ if (messages.length === 0) return { messages: [] };
744
570
  try {
745
571
  const now = /* @__PURE__ */ new Date();
746
572
  const threadId = messages[0]?.threadId;
@@ -788,12 +614,11 @@ var MemoryStorageD1 = class extends MemoryStorage {
788
614
  ]);
789
615
  this.logger.debug(`Saved ${messages.length} messages`);
790
616
  const list = new MessageList().add(messages, "memory");
791
- if (format === `v2`) return list.get.all.v2();
792
- return list.get.all.v1();
617
+ return { messages: list.get.all.db() };
793
618
  } catch (error) {
794
619
  throw new MastraError(
795
620
  {
796
- id: "CLOUDFLARE_D1_STORAGE_SAVE_MESSAGES_ERROR",
621
+ id: createStorageErrorId("CLOUDFLARE_D1", "SAVE_MESSAGES", "FAILED"),
797
622
  domain: ErrorDomain.STORAGE,
798
623
  category: ErrorCategory.THIRD_PARTY,
799
624
  text: `Failed to save messages: ${error instanceof Error ? error.message : String(error)}`
@@ -802,23 +627,25 @@ var MemoryStorageD1 = class extends MemoryStorage {
802
627
  );
803
628
  }
804
629
  }
805
- async _getIncludedMessages(threadId, selectBy) {
806
- const include = selectBy?.include;
807
- if (!include) return null;
630
+ async _getIncludedMessages(include) {
631
+ if (!include || include.length === 0) return null;
808
632
  const unionQueries = [];
809
633
  const params = [];
810
634
  let paramIdx = 1;
635
+ const tableName = this.operations.getTableName(TABLE_MESSAGES);
811
636
  for (const inc of include) {
812
637
  const { id, withPreviousMessages = 0, withNextMessages = 0 } = inc;
813
- const searchId = inc.threadId || threadId;
814
638
  unionQueries.push(`
815
639
  SELECT * FROM (
816
- WITH ordered_messages AS (
640
+ WITH target_thread AS (
641
+ SELECT thread_id FROM ${tableName} WHERE id = ?
642
+ ),
643
+ ordered_messages AS (
817
644
  SELECT
818
645
  *,
819
646
  ROW_NUMBER() OVER (ORDER BY createdAt ASC) AS row_num
820
- FROM ${this.operations.getTableName(TABLE_MESSAGES)}
821
- WHERE thread_id = ?
647
+ FROM ${tableName}
648
+ WHERE thread_id = (SELECT thread_id FROM target_thread)
822
649
  )
823
650
  SELECT
824
651
  m.id,
@@ -841,7 +668,7 @@ var MemoryStorageD1 = class extends MemoryStorage {
841
668
  )
842
669
  ) AS query_${paramIdx}
843
670
  `);
844
- params.push(searchId, id, id, withNextMessages, withPreviousMessages);
671
+ params.push(id, id, id, withNextMessages, withPreviousMessages);
845
672
  paramIdx++;
846
673
  }
847
674
  const finalQuery = unionQueries.join(" UNION ALL ") + " ORDER BY createdAt ASC";
@@ -859,39 +686,16 @@ var MemoryStorageD1 = class extends MemoryStorage {
859
686
  });
860
687
  return processedMessages;
861
688
  }
862
- async getMessages({
863
- threadId,
864
- selectBy,
865
- format
866
- }) {
689
+ async listMessagesById({ messageIds }) {
690
+ if (messageIds.length === 0) return { messages: [] };
867
691
  const fullTableName = this.operations.getTableName(TABLE_MESSAGES);
868
- const limit = resolveMessageLimit({
869
- last: selectBy?.last,
870
- defaultLimit: 40
871
- });
872
- const include = selectBy?.include || [];
873
692
  const messages = [];
874
693
  try {
875
- if (include.length) {
876
- const includeResult = await this._getIncludedMessages(threadId, selectBy);
877
- if (Array.isArray(includeResult)) messages.push(...includeResult);
878
- }
879
- const excludeIds = messages.map((m) => m.id);
880
- const query = createSqlBuilder().select(["id", "content", "role", "type", "createdAt", "thread_id AS threadId"]).from(fullTableName).where("thread_id = ?", threadId);
881
- if (excludeIds.length > 0) {
882
- query.andWhere(`id NOT IN (${excludeIds.map(() => "?").join(",")})`, ...excludeIds);
883
- }
884
- query.orderBy("createdAt", "DESC").limit(limit);
694
+ const query = createSqlBuilder().select(["id", "content", "role", "type", "createdAt", "thread_id AS threadId", "resourceId"]).from(fullTableName).where(`id in (${messageIds.map(() => "?").join(",")})`, ...messageIds);
695
+ query.orderBy("createdAt", "DESC");
885
696
  const { sql, params } = query.build();
886
697
  const result = await this.operations.executeQuery({ sql, params });
887
698
  if (Array.isArray(result)) messages.push(...result);
888
- messages.sort((a, b) => {
889
- const aRecord = a;
890
- const bRecord = b;
891
- const timeA = new Date(aRecord.createdAt).getTime();
892
- const timeB = new Date(bRecord.createdAt).getTime();
893
- return timeA - timeB;
894
- });
895
699
  const processedMessages = messages.map((message) => {
896
700
  const processedMsg = {};
897
701
  for (const [key, value] of Object.entries(message)) {
@@ -900,18 +704,17 @@ var MemoryStorageD1 = class extends MemoryStorage {
900
704
  }
901
705
  return processedMsg;
902
706
  });
903
- this.logger.debug(`Retrieved ${messages.length} messages for thread ${threadId}`);
707
+ this.logger.debug(`Retrieved ${messages.length} messages`);
904
708
  const list = new MessageList().add(processedMessages, "memory");
905
- if (format === `v2`) return list.get.all.v2();
906
- return list.get.all.v1();
709
+ return { messages: list.get.all.db() };
907
710
  } catch (error) {
908
711
  const mastraError = new MastraError(
909
712
  {
910
- id: "CLOUDFLARE_D1_STORAGE_GET_MESSAGES_ERROR",
713
+ id: createStorageErrorId("CLOUDFLARE_D1", "LIST_MESSAGES_BY_ID", "FAILED"),
911
714
  domain: ErrorDomain.STORAGE,
912
715
  category: ErrorCategory.THIRD_PARTY,
913
- text: `Failed to retrieve messages for thread ${threadId}: ${error instanceof Error ? error.message : String(error)}`,
914
- details: { threadId }
716
+ text: `Failed to retrieve messages by ID: ${error instanceof Error ? error.message : String(error)}`,
717
+ details: { messageIds: JSON.stringify(messageIds) }
915
718
  },
916
719
  error
917
720
  );
@@ -920,116 +723,158 @@ var MemoryStorageD1 = class extends MemoryStorage {
920
723
  throw mastraError;
921
724
  }
922
725
  }
923
- async getMessagesPaginated({
924
- threadId,
925
- selectBy,
926
- format
927
- }) {
928
- const { dateRange, page = 0, perPage: perPageInput } = selectBy?.pagination || {};
929
- const { start: fromDate, end: toDate } = dateRange || {};
930
- const perPage = perPageInput !== void 0 ? perPageInput : resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
931
- const fullTableName = this.operations.getTableName(TABLE_MESSAGES);
932
- const messages = [];
726
+ async listMessages(args) {
727
+ const { threadId, resourceId, include, filter, perPage: perPageInput, page = 0, orderBy } = args;
728
+ const threadIds = Array.isArray(threadId) ? threadId : [threadId];
729
+ if (threadIds.length === 0 || threadIds.some((id) => !id.trim())) {
730
+ throw new MastraError(
731
+ {
732
+ id: createStorageErrorId("CLOUDFLARE_D1", "LIST_MESSAGES", "INVALID_THREAD_ID"),
733
+ domain: ErrorDomain.STORAGE,
734
+ category: ErrorCategory.THIRD_PARTY,
735
+ details: { threadId: Array.isArray(threadId) ? threadId.join(",") : threadId }
736
+ },
737
+ new Error("threadId must be a non-empty string or array of non-empty strings")
738
+ );
739
+ }
740
+ if (page < 0) {
741
+ throw new MastraError(
742
+ {
743
+ id: createStorageErrorId("CLOUDFLARE_D1", "LIST_MESSAGES", "INVALID_PAGE"),
744
+ domain: ErrorDomain.STORAGE,
745
+ category: ErrorCategory.USER,
746
+ details: { page }
747
+ },
748
+ new Error("page must be >= 0")
749
+ );
750
+ }
751
+ const perPage = normalizePerPage(perPageInput, 40);
752
+ const { offset, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
933
753
  try {
934
- if (selectBy?.include?.length) {
935
- const includeResult = await this._getIncludedMessages(threadId, selectBy);
936
- if (Array.isArray(includeResult)) messages.push(...includeResult);
754
+ const fullTableName = this.operations.getTableName(TABLE_MESSAGES);
755
+ let query = `
756
+ SELECT id, content, role, type, createdAt, thread_id AS threadId, resourceId
757
+ FROM ${fullTableName}
758
+ WHERE thread_id = ?
759
+ `;
760
+ const queryParams = [threadId];
761
+ if (resourceId) {
762
+ query += ` AND resourceId = ?`;
763
+ queryParams.push(resourceId);
937
764
  }
938
- const countQuery = createSqlBuilder().count().from(fullTableName).where("thread_id = ?", threadId);
939
- if (fromDate) {
940
- countQuery.andWhere("createdAt >= ?", serializeDate(fromDate));
765
+ const dateRange = filter?.dateRange;
766
+ if (dateRange?.start) {
767
+ const startDate = dateRange.start instanceof Date ? serializeDate(dateRange.start) : serializeDate(new Date(dateRange.start));
768
+ query += ` AND createdAt >= ?`;
769
+ queryParams.push(startDate);
941
770
  }
942
- if (toDate) {
943
- countQuery.andWhere("createdAt <= ?", serializeDate(toDate));
771
+ if (dateRange?.end) {
772
+ const endDate = dateRange.end instanceof Date ? serializeDate(dateRange.end) : serializeDate(new Date(dateRange.end));
773
+ query += ` AND createdAt <= ?`;
774
+ queryParams.push(endDate);
944
775
  }
945
- const countResult = await this.operations.executeQuery(countQuery.build());
776
+ const { field, direction } = this.parseOrderBy(orderBy, "ASC");
777
+ query += ` ORDER BY "${field}" ${direction}`;
778
+ if (perPage !== Number.MAX_SAFE_INTEGER) {
779
+ query += ` LIMIT ? OFFSET ?`;
780
+ queryParams.push(perPage, offset);
781
+ }
782
+ const results = await this.operations.executeQuery({ sql: query, params: queryParams });
783
+ const paginatedMessages = (isArrayOfRecords(results) ? results : []).map((message) => {
784
+ const processedMsg = {};
785
+ for (const [key, value] of Object.entries(message)) {
786
+ if (key === `type` && value === `v2`) continue;
787
+ processedMsg[key] = deserializeValue(value);
788
+ }
789
+ return processedMsg;
790
+ });
791
+ const paginatedCount = paginatedMessages.length;
792
+ let countQuery = `SELECT count() as count FROM ${fullTableName} WHERE thread_id = ?`;
793
+ const countParams = [threadId];
794
+ if (resourceId) {
795
+ countQuery += ` AND resourceId = ?`;
796
+ countParams.push(resourceId);
797
+ }
798
+ if (dateRange?.start) {
799
+ const startDate = dateRange.start instanceof Date ? serializeDate(dateRange.start) : serializeDate(new Date(dateRange.start));
800
+ countQuery += ` AND createdAt >= ?`;
801
+ countParams.push(startDate);
802
+ }
803
+ if (dateRange?.end) {
804
+ const endDate = dateRange.end instanceof Date ? serializeDate(dateRange.end) : serializeDate(new Date(dateRange.end));
805
+ countQuery += ` AND createdAt <= ?`;
806
+ countParams.push(endDate);
807
+ }
808
+ const countResult = await this.operations.executeQuery({ sql: countQuery, params: countParams });
946
809
  const total = Number(countResult[0]?.count ?? 0);
947
- if (total === 0 && messages.length === 0) {
810
+ if (total === 0 && paginatedCount === 0 && (!include || include.length === 0)) {
948
811
  return {
949
812
  messages: [],
950
813
  total: 0,
951
814
  page,
952
- perPage,
815
+ perPage: perPageForResponse,
953
816
  hasMore: false
954
817
  };
955
818
  }
956
- const excludeIds = messages.map((m) => m.id);
957
- const excludeCondition = excludeIds.length > 0 ? `AND id NOT IN (${excludeIds.map(() => "?").join(",")})` : "";
958
- let query;
959
- let queryParams = [threadId];
960
- if (fromDate) {
961
- queryParams.push(serializeDate(fromDate));
962
- }
963
- if (toDate) {
964
- queryParams.push(serializeDate(toDate));
965
- }
966
- if (excludeIds.length > 0) {
967
- queryParams.push(...excludeIds);
968
- }
969
- if (selectBy?.last && selectBy.last > 0) {
970
- query = `
971
- SELECT id, content, role, type, createdAt, thread_id AS threadId, resourceId
972
- FROM ${fullTableName}
973
- WHERE thread_id = ?
974
- ${fromDate ? "AND createdAt >= ?" : ""}
975
- ${toDate ? "AND createdAt <= ?" : ""}
976
- ${excludeCondition}
977
- ORDER BY createdAt DESC
978
- LIMIT ?
979
- `;
980
- queryParams.push(selectBy.last);
981
- } else {
982
- query = `
983
- SELECT id, content, role, type, createdAt, thread_id AS threadId, resourceId
984
- FROM ${fullTableName}
985
- WHERE thread_id = ?
986
- ${fromDate ? "AND createdAt >= ?" : ""}
987
- ${toDate ? "AND createdAt <= ?" : ""}
988
- ${excludeCondition}
989
- ORDER BY createdAt DESC
990
- LIMIT ? OFFSET ?
991
- `;
992
- queryParams.push(perPage, page * perPage);
819
+ const messageIds = new Set(paginatedMessages.map((m) => m.id));
820
+ let includeMessages = [];
821
+ if (include && include.length > 0) {
822
+ const includeResult = await this._getIncludedMessages(include);
823
+ if (Array.isArray(includeResult)) {
824
+ includeMessages = includeResult;
825
+ for (const includeMsg of includeMessages) {
826
+ if (!messageIds.has(includeMsg.id)) {
827
+ paginatedMessages.push(includeMsg);
828
+ messageIds.add(includeMsg.id);
829
+ }
830
+ }
831
+ }
993
832
  }
994
- const results = await this.operations.executeQuery({ sql: query, params: queryParams });
995
- const processedMessages = results.map((message) => {
996
- const processedMsg = {};
997
- for (const [key, value] of Object.entries(message)) {
998
- if (key === `type` && value === `v2`) continue;
999
- processedMsg[key] = deserializeValue(value);
833
+ const list = new MessageList().add(paginatedMessages, "memory");
834
+ let finalMessages = list.get.all.db();
835
+ finalMessages = finalMessages.sort((a, b) => {
836
+ const isDateField = field === "createdAt" || field === "updatedAt";
837
+ const aValue = isDateField ? new Date(a[field]).getTime() : a[field];
838
+ const bValue = isDateField ? new Date(b[field]).getTime() : b[field];
839
+ if (aValue === bValue) {
840
+ return a.id.localeCompare(b.id);
1000
841
  }
1001
- return processedMsg;
842
+ if (typeof aValue === "number" && typeof bValue === "number") {
843
+ return direction === "ASC" ? aValue - bValue : bValue - aValue;
844
+ }
845
+ return direction === "ASC" ? String(aValue).localeCompare(String(bValue)) : String(bValue).localeCompare(String(aValue));
1002
846
  });
1003
- if (selectBy?.last) {
1004
- processedMessages.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
1005
- }
1006
- const list = new MessageList().add(processedMessages, "memory");
1007
- messages.push(...format === `v2` ? list.get.all.v2() : list.get.all.v1());
847
+ const returnedThreadMessageIds = new Set(finalMessages.filter((m) => m.threadId === threadId).map((m) => m.id));
848
+ const allThreadMessagesReturned = returnedThreadMessageIds.size >= total;
849
+ const hasMore = perPageInput === false ? false : allThreadMessagesReturned ? false : offset + paginatedCount < total;
1008
850
  return {
1009
- messages,
851
+ messages: finalMessages,
1010
852
  total,
1011
853
  page,
1012
- perPage,
1013
- hasMore: selectBy?.last ? false : page * perPage + messages.length < total
854
+ perPage: perPageForResponse,
855
+ hasMore
1014
856
  };
1015
857
  } catch (error) {
1016
858
  const mastraError = new MastraError(
1017
859
  {
1018
- id: "CLOUDFLARE_D1_STORAGE_GET_MESSAGES_PAGINATED_ERROR",
860
+ id: createStorageErrorId("CLOUDFLARE_D1", "LIST_MESSAGES", "FAILED"),
1019
861
  domain: ErrorDomain.STORAGE,
1020
862
  category: ErrorCategory.THIRD_PARTY,
1021
- text: `Failed to retrieve messages for thread ${threadId}: ${error instanceof Error ? error.message : String(error)}`,
1022
- details: { threadId }
863
+ text: `Failed to list messages for thread ${Array.isArray(threadId) ? threadId.join(",") : threadId}: ${error instanceof Error ? error.message : String(error)}`,
864
+ details: {
865
+ threadId: Array.isArray(threadId) ? threadId.join(",") : threadId,
866
+ resourceId: resourceId ?? ""
867
+ }
1023
868
  },
1024
869
  error
1025
870
  );
1026
- this.logger?.error(mastraError.toString());
1027
- this.logger?.trackException(mastraError);
871
+ this.logger?.error?.(mastraError.toString());
872
+ this.logger?.trackException?.(mastraError);
1028
873
  return {
1029
874
  messages: [],
1030
875
  total: 0,
1031
876
  page,
1032
- perPage,
877
+ perPage: perPageForResponse,
1033
878
  hasMore: false
1034
879
  };
1035
880
  }
@@ -1125,7 +970,7 @@ var MemoryStorageD1 = class extends MemoryStorage {
1125
970
  } catch (error) {
1126
971
  throw new MastraError(
1127
972
  {
1128
- id: "CLOUDFLARE_D1_STORAGE_UPDATE_MESSAGES_FAILED",
973
+ id: createStorageErrorId("CLOUDFLARE_D1", "UPDATE_MESSAGES", "FAILED"),
1129
974
  domain: ErrorDomain.STORAGE,
1130
975
  category: ErrorCategory.THIRD_PARTY,
1131
976
  details: { count: messages.length }
@@ -1194,7 +1039,7 @@ var StoreOperationsD1 = class extends StoreOperations {
1194
1039
  } catch (error) {
1195
1040
  throw new MastraError(
1196
1041
  {
1197
- id: "CLOUDFLARE_D1_STORE_OPERATIONS_WORKERS_BINDING_QUERY_FAILED",
1042
+ id: createStorageErrorId("CLOUDFLARE_D1", "WORKERS_BINDING_QUERY", "FAILED"),
1198
1043
  domain: ErrorDomain.STORAGE,
1199
1044
  category: ErrorCategory.THIRD_PARTY,
1200
1045
  details: { sql }
@@ -1226,7 +1071,7 @@ var StoreOperationsD1 = class extends StoreOperations {
1226
1071
  } catch (error) {
1227
1072
  throw new MastraError(
1228
1073
  {
1229
- id: "CLOUDFLARE_D1_STORE_OPERATIONS_REST_QUERY_FAILED",
1074
+ id: createStorageErrorId("CLOUDFLARE_D1", "REST_QUERY", "FAILED"),
1230
1075
  domain: ErrorDomain.STORAGE,
1231
1076
  category: ErrorCategory.THIRD_PARTY,
1232
1077
  details: { sql }
@@ -1307,7 +1152,7 @@ var StoreOperationsD1 = class extends StoreOperations {
1307
1152
  } catch (error) {
1308
1153
  throw new MastraError(
1309
1154
  {
1310
- id: "CLOUDFLARE_D1_STORE_OPERATIONS_CREATE_TABLE_FAILED",
1155
+ id: createStorageErrorId("CLOUDFLARE_D1", "CREATE_TABLE", "FAILED"),
1311
1156
  domain: ErrorDomain.STORAGE,
1312
1157
  category: ErrorCategory.THIRD_PARTY,
1313
1158
  details: { tableName }
@@ -1326,7 +1171,7 @@ var StoreOperationsD1 = class extends StoreOperations {
1326
1171
  } catch (error) {
1327
1172
  throw new MastraError(
1328
1173
  {
1329
- id: "CLOUDFLARE_D1_STORE_OPERATIONS_CLEAR_TABLE_FAILED",
1174
+ id: createStorageErrorId("CLOUDFLARE_D1", "CLEAR_TABLE", "FAILED"),
1330
1175
  domain: ErrorDomain.STORAGE,
1331
1176
  category: ErrorCategory.THIRD_PARTY,
1332
1177
  details: { tableName }
@@ -1344,7 +1189,7 @@ var StoreOperationsD1 = class extends StoreOperations {
1344
1189
  } catch (error) {
1345
1190
  throw new MastraError(
1346
1191
  {
1347
- id: "CLOUDFLARE_D1_STORE_OPERATIONS_DROP_TABLE_FAILED",
1192
+ id: createStorageErrorId("CLOUDFLARE_D1", "DROP_TABLE", "FAILED"),
1348
1193
  domain: ErrorDomain.STORAGE,
1349
1194
  category: ErrorCategory.THIRD_PARTY,
1350
1195
  details: { tableName }
@@ -1370,7 +1215,7 @@ var StoreOperationsD1 = class extends StoreOperations {
1370
1215
  } catch (error) {
1371
1216
  throw new MastraError(
1372
1217
  {
1373
- id: "CLOUDFLARE_D1_STORE_OPERATIONS_ALTER_TABLE_FAILED",
1218
+ id: createStorageErrorId("CLOUDFLARE_D1", "ALTER_TABLE", "FAILED"),
1374
1219
  domain: ErrorDomain.STORAGE,
1375
1220
  category: ErrorCategory.THIRD_PARTY,
1376
1221
  details: { tableName: args.tableName }
@@ -1391,7 +1236,7 @@ var StoreOperationsD1 = class extends StoreOperations {
1391
1236
  } catch (error) {
1392
1237
  throw new MastraError(
1393
1238
  {
1394
- id: "CLOUDFLARE_D1_STORE_OPERATIONS_INSERT_FAILED",
1239
+ id: createStorageErrorId("CLOUDFLARE_D1", "INSERT", "FAILED"),
1395
1240
  domain: ErrorDomain.STORAGE,
1396
1241
  category: ErrorCategory.THIRD_PARTY,
1397
1242
  details: { tableName }
@@ -1415,7 +1260,7 @@ var StoreOperationsD1 = class extends StoreOperations {
1415
1260
  } catch (error) {
1416
1261
  throw new MastraError(
1417
1262
  {
1418
- id: "CLOUDFLARE_D1_STORE_OPERATIONS_BATCH_INSERT_FAILED",
1263
+ id: createStorageErrorId("CLOUDFLARE_D1", "BATCH_INSERT", "FAILED"),
1419
1264
  domain: ErrorDomain.STORAGE,
1420
1265
  category: ErrorCategory.THIRD_PARTY,
1421
1266
  details: { tableName }
@@ -1437,6 +1282,7 @@ var StoreOperationsD1 = class extends StoreOperations {
1437
1282
  query.andWhere(`${key} = ?`, value);
1438
1283
  }
1439
1284
  }
1285
+ query.orderBy("createdAt", "DESC");
1440
1286
  query.limit(1);
1441
1287
  const { sql, params } = query.build();
1442
1288
  const result = await this.executeQuery({ sql, params, first: true });
@@ -1451,7 +1297,7 @@ var StoreOperationsD1 = class extends StoreOperations {
1451
1297
  } catch (error) {
1452
1298
  throw new MastraError(
1453
1299
  {
1454
- id: "CLOUDFLARE_D1_STORE_OPERATIONS_LOAD_FAILED",
1300
+ id: createStorageErrorId("CLOUDFLARE_D1", "LOAD", "FAILED"),
1455
1301
  domain: ErrorDomain.STORAGE,
1456
1302
  category: ErrorCategory.THIRD_PARTY,
1457
1303
  details: { tableName }
@@ -1509,7 +1355,7 @@ var StoreOperationsD1 = class extends StoreOperations {
1509
1355
  } catch (error) {
1510
1356
  throw new MastraError(
1511
1357
  {
1512
- id: "CLOUDFLARE_D1_STORAGE_BATCH_UPSERT_ERROR",
1358
+ id: createStorageErrorId("CLOUDFLARE_D1", "BATCH_UPSERT", "FAILED"),
1513
1359
  domain: ErrorDomain.STORAGE,
1514
1360
  category: ErrorCategory.THIRD_PARTY,
1515
1361
  text: `Failed to batch upsert into ${tableName}: ${error instanceof Error ? error.message : String(error)}`,
@@ -1521,20 +1367,12 @@ var StoreOperationsD1 = class extends StoreOperations {
1521
1367
  }
1522
1368
  };
1523
1369
  function transformScoreRow(row) {
1524
- let input = void 0;
1525
- if (row.input) {
1526
- try {
1527
- input = JSON.parse(row.input);
1528
- } catch {
1529
- input = row.input;
1370
+ return transformScoreRow$1(row, {
1371
+ preferredTimestampFields: {
1372
+ createdAt: "createdAtZ",
1373
+ updatedAt: "updatedAtZ"
1530
1374
  }
1531
- }
1532
- return {
1533
- ...row,
1534
- input,
1535
- createdAt: row.createdAtZ || row.createdAt,
1536
- updatedAt: row.updatedAtZ || row.updatedAt
1537
- };
1375
+ });
1538
1376
  }
1539
1377
  var ScoresStorageD1 = class extends ScoresStorage {
1540
1378
  operations;
@@ -1555,7 +1393,7 @@ var ScoresStorageD1 = class extends ScoresStorage {
1555
1393
  } catch (error) {
1556
1394
  throw new MastraError(
1557
1395
  {
1558
- id: "CLOUDFLARE_D1_STORE_SCORES_GET_SCORE_BY_ID_FAILED",
1396
+ id: createStorageErrorId("CLOUDFLARE_D1", "GET_SCORE_BY_ID", "FAILED"),
1559
1397
  domain: ErrorDomain.STORAGE,
1560
1398
  category: ErrorCategory.THIRD_PARTY
1561
1399
  },
@@ -1564,11 +1402,31 @@ var ScoresStorageD1 = class extends ScoresStorage {
1564
1402
  }
1565
1403
  }
1566
1404
  async saveScore(score) {
1405
+ let parsedScore;
1406
+ try {
1407
+ parsedScore = saveScorePayloadSchema.parse(score);
1408
+ } catch (error) {
1409
+ throw new MastraError(
1410
+ {
1411
+ id: createStorageErrorId("CLOUDFLARE_D1", "SAVE_SCORE", "VALIDATION_FAILED"),
1412
+ domain: ErrorDomain.STORAGE,
1413
+ category: ErrorCategory.USER,
1414
+ details: {
1415
+ scorer: score.scorer?.id ?? "unknown",
1416
+ entityId: score.entityId ?? "unknown",
1417
+ entityType: score.entityType ?? "unknown",
1418
+ traceId: score.traceId ?? "",
1419
+ spanId: score.spanId ?? ""
1420
+ }
1421
+ },
1422
+ error
1423
+ );
1424
+ }
1425
+ const id = crypto.randomUUID();
1567
1426
  try {
1568
1427
  const fullTableName = this.operations.getTableName(TABLE_SCORERS);
1569
- const { input, ...rest } = score;
1570
1428
  const serializedRecord = {};
1571
- for (const [key, value] of Object.entries(rest)) {
1429
+ for (const [key, value] of Object.entries(parsedScore)) {
1572
1430
  if (value !== null && value !== void 0) {
1573
1431
  if (typeof value === "object") {
1574
1432
  serializedRecord[key] = JSON.stringify(value);
@@ -1579,64 +1437,92 @@ var ScoresStorageD1 = class extends ScoresStorage {
1579
1437
  serializedRecord[key] = null;
1580
1438
  }
1581
1439
  }
1582
- serializedRecord.input = JSON.stringify(input);
1583
- serializedRecord.createdAt = (/* @__PURE__ */ new Date()).toISOString();
1584
- serializedRecord.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1440
+ const now = /* @__PURE__ */ new Date();
1441
+ serializedRecord.id = id;
1442
+ serializedRecord.createdAt = now.toISOString();
1443
+ serializedRecord.updatedAt = now.toISOString();
1585
1444
  const columns = Object.keys(serializedRecord);
1586
1445
  const values = Object.values(serializedRecord);
1587
1446
  const query = createSqlBuilder().insert(fullTableName, columns, values);
1588
1447
  const { sql, params } = query.build();
1589
1448
  await this.operations.executeQuery({ sql, params });
1590
- const scoreFromDb = await this.getScoreById({ id: score.id });
1591
- return { score: scoreFromDb };
1449
+ return { score: { ...parsedScore, id, createdAt: now, updatedAt: now } };
1592
1450
  } catch (error) {
1593
1451
  throw new MastraError(
1594
1452
  {
1595
- id: "CLOUDFLARE_D1_STORE_SCORES_SAVE_SCORE_FAILED",
1453
+ id: createStorageErrorId("CLOUDFLARE_D1", "SAVE_SCORE", "FAILED"),
1596
1454
  domain: ErrorDomain.STORAGE,
1597
- category: ErrorCategory.THIRD_PARTY
1455
+ category: ErrorCategory.THIRD_PARTY,
1456
+ details: { id }
1598
1457
  },
1599
1458
  error
1600
1459
  );
1601
1460
  }
1602
1461
  }
1603
- async getScoresByScorerId({
1462
+ async listScoresByScorerId({
1604
1463
  scorerId,
1464
+ entityId,
1465
+ entityType,
1466
+ source,
1605
1467
  pagination
1606
1468
  }) {
1607
1469
  try {
1470
+ const { page, perPage: perPageInput } = pagination;
1471
+ const perPage = normalizePerPage(perPageInput, 100);
1472
+ const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
1608
1473
  const fullTableName = this.operations.getTableName(TABLE_SCORERS);
1609
1474
  const countQuery = createSqlBuilder().count().from(fullTableName).where("scorerId = ?", scorerId);
1475
+ if (entityId) {
1476
+ countQuery.andWhere("entityId = ?", entityId);
1477
+ }
1478
+ if (entityType) {
1479
+ countQuery.andWhere("entityType = ?", entityType);
1480
+ }
1481
+ if (source) {
1482
+ countQuery.andWhere("source = ?", source);
1483
+ }
1610
1484
  const countResult = await this.operations.executeQuery(countQuery.build());
1611
1485
  const total = Array.isArray(countResult) ? Number(countResult?.[0]?.count ?? 0) : Number(countResult?.count ?? 0);
1612
1486
  if (total === 0) {
1613
1487
  return {
1614
1488
  pagination: {
1615
1489
  total: 0,
1616
- page: pagination.page,
1617
- perPage: pagination.perPage,
1490
+ page,
1491
+ perPage: perPageForResponse,
1618
1492
  hasMore: false
1619
1493
  },
1620
1494
  scores: []
1621
1495
  };
1622
1496
  }
1623
- const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("scorerId = ?", scorerId).limit(pagination.perPage).offset(pagination.page * pagination.perPage);
1497
+ const end = perPageInput === false ? total : start + perPage;
1498
+ const limitValue = perPageInput === false ? total : perPage;
1499
+ const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("scorerId = ?", scorerId);
1500
+ if (entityId) {
1501
+ selectQuery.andWhere("entityId = ?", entityId);
1502
+ }
1503
+ if (entityType) {
1504
+ selectQuery.andWhere("entityType = ?", entityType);
1505
+ }
1506
+ if (source) {
1507
+ selectQuery.andWhere("source = ?", source);
1508
+ }
1509
+ selectQuery.limit(limitValue).offset(start);
1624
1510
  const { sql, params } = selectQuery.build();
1625
1511
  const results = await this.operations.executeQuery({ sql, params });
1626
1512
  const scores = Array.isArray(results) ? results.map(transformScoreRow) : [];
1627
1513
  return {
1628
1514
  pagination: {
1629
1515
  total,
1630
- page: pagination.page,
1631
- perPage: pagination.perPage,
1632
- hasMore: total > (pagination.page + 1) * pagination.perPage
1516
+ page,
1517
+ perPage: perPageForResponse,
1518
+ hasMore: end < total
1633
1519
  },
1634
1520
  scores
1635
1521
  };
1636
1522
  } catch (error) {
1637
1523
  throw new MastraError(
1638
1524
  {
1639
- id: "CLOUDFLARE_D1_STORE_SCORES_GET_SCORES_BY_SCORER_ID_FAILED",
1525
+ id: createStorageErrorId("CLOUDFLARE_D1", "GET_SCORES_BY_SCORER_ID", "FAILED"),
1640
1526
  domain: ErrorDomain.STORAGE,
1641
1527
  category: ErrorCategory.THIRD_PARTY
1642
1528
  },
@@ -1644,11 +1530,14 @@ var ScoresStorageD1 = class extends ScoresStorage {
1644
1530
  );
1645
1531
  }
1646
1532
  }
1647
- async getScoresByRunId({
1533
+ async listScoresByRunId({
1648
1534
  runId,
1649
1535
  pagination
1650
1536
  }) {
1651
1537
  try {
1538
+ const { page, perPage: perPageInput } = pagination;
1539
+ const perPage = normalizePerPage(perPageInput, 100);
1540
+ const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
1652
1541
  const fullTableName = this.operations.getTableName(TABLE_SCORERS);
1653
1542
  const countQuery = createSqlBuilder().count().from(fullTableName).where("runId = ?", runId);
1654
1543
  const countResult = await this.operations.executeQuery(countQuery.build());
@@ -1657,30 +1546,32 @@ var ScoresStorageD1 = class extends ScoresStorage {
1657
1546
  return {
1658
1547
  pagination: {
1659
1548
  total: 0,
1660
- page: pagination.page,
1661
- perPage: pagination.perPage,
1549
+ page,
1550
+ perPage: perPageForResponse,
1662
1551
  hasMore: false
1663
1552
  },
1664
1553
  scores: []
1665
1554
  };
1666
1555
  }
1667
- const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("runId = ?", runId).limit(pagination.perPage).offset(pagination.page * pagination.perPage);
1556
+ const end = perPageInput === false ? total : start + perPage;
1557
+ const limitValue = perPageInput === false ? total : perPage;
1558
+ const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("runId = ?", runId).limit(limitValue).offset(start);
1668
1559
  const { sql, params } = selectQuery.build();
1669
1560
  const results = await this.operations.executeQuery({ sql, params });
1670
1561
  const scores = Array.isArray(results) ? results.map(transformScoreRow) : [];
1671
1562
  return {
1672
1563
  pagination: {
1673
1564
  total,
1674
- page: pagination.page,
1675
- perPage: pagination.perPage,
1676
- hasMore: total > (pagination.page + 1) * pagination.perPage
1565
+ page,
1566
+ perPage: perPageForResponse,
1567
+ hasMore: end < total
1677
1568
  },
1678
1569
  scores
1679
1570
  };
1680
1571
  } catch (error) {
1681
1572
  throw new MastraError(
1682
1573
  {
1683
- id: "CLOUDFLARE_D1_STORE_SCORES_GET_SCORES_BY_RUN_ID_FAILED",
1574
+ id: createStorageErrorId("CLOUDFLARE_D1", "GET_SCORES_BY_RUN_ID", "FAILED"),
1684
1575
  domain: ErrorDomain.STORAGE,
1685
1576
  category: ErrorCategory.THIRD_PARTY
1686
1577
  },
@@ -1688,12 +1579,15 @@ var ScoresStorageD1 = class extends ScoresStorage {
1688
1579
  );
1689
1580
  }
1690
1581
  }
1691
- async getScoresByEntityId({
1582
+ async listScoresByEntityId({
1692
1583
  entityId,
1693
1584
  entityType,
1694
1585
  pagination
1695
1586
  }) {
1696
1587
  try {
1588
+ const { page, perPage: perPageInput } = pagination;
1589
+ const perPage = normalizePerPage(perPageInput, 100);
1590
+ const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
1697
1591
  const fullTableName = this.operations.getTableName(TABLE_SCORERS);
1698
1592
  const countQuery = createSqlBuilder().count().from(fullTableName).where("entityId = ?", entityId).andWhere("entityType = ?", entityType);
1699
1593
  const countResult = await this.operations.executeQuery(countQuery.build());
@@ -1702,30 +1596,32 @@ var ScoresStorageD1 = class extends ScoresStorage {
1702
1596
  return {
1703
1597
  pagination: {
1704
1598
  total: 0,
1705
- page: pagination.page,
1706
- perPage: pagination.perPage,
1599
+ page,
1600
+ perPage: perPageForResponse,
1707
1601
  hasMore: false
1708
1602
  },
1709
1603
  scores: []
1710
1604
  };
1711
1605
  }
1712
- const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("entityId = ?", entityId).andWhere("entityType = ?", entityType).limit(pagination.perPage).offset(pagination.page * pagination.perPage);
1606
+ const end = perPageInput === false ? total : start + perPage;
1607
+ const limitValue = perPageInput === false ? total : perPage;
1608
+ const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("entityId = ?", entityId).andWhere("entityType = ?", entityType).limit(limitValue).offset(start);
1713
1609
  const { sql, params } = selectQuery.build();
1714
1610
  const results = await this.operations.executeQuery({ sql, params });
1715
1611
  const scores = Array.isArray(results) ? results.map(transformScoreRow) : [];
1716
1612
  return {
1717
1613
  pagination: {
1718
1614
  total,
1719
- page: pagination.page,
1720
- perPage: pagination.perPage,
1721
- hasMore: total > (pagination.page + 1) * pagination.perPage
1615
+ page,
1616
+ perPage: perPageForResponse,
1617
+ hasMore: end < total
1722
1618
  },
1723
1619
  scores
1724
1620
  };
1725
1621
  } catch (error) {
1726
1622
  throw new MastraError(
1727
1623
  {
1728
- id: "CLOUDFLARE_D1_STORE_SCORES_GET_SCORES_BY_ENTITY_ID_FAILED",
1624
+ id: createStorageErrorId("CLOUDFLARE_D1", "GET_SCORES_BY_ENTITY_ID", "FAILED"),
1729
1625
  domain: ErrorDomain.STORAGE,
1730
1626
  category: ErrorCategory.THIRD_PARTY
1731
1627
  },
@@ -1733,128 +1629,56 @@ var ScoresStorageD1 = class extends ScoresStorage {
1733
1629
  );
1734
1630
  }
1735
1631
  }
1736
- };
1737
- function isArrayOfRecords2(value) {
1738
- return value && Array.isArray(value) && value.length > 0;
1739
- }
1740
- var TracesStorageD1 = class extends TracesStorage {
1741
- operations;
1742
- constructor({ operations }) {
1743
- super();
1744
- this.operations = operations;
1745
- }
1746
- async getTraces(args) {
1747
- const paginatedArgs = {
1748
- name: args.name,
1749
- scope: args.scope,
1750
- page: args.page,
1751
- perPage: args.perPage,
1752
- attributes: args.attributes,
1753
- filters: args.filters,
1754
- dateRange: args.fromDate || args.toDate ? {
1755
- start: args.fromDate,
1756
- end: args.toDate
1757
- } : void 0
1758
- };
1759
- try {
1760
- const result = await this.getTracesPaginated(paginatedArgs);
1761
- return result.traces;
1762
- } catch (error) {
1763
- throw new MastraError(
1764
- {
1765
- id: "CLOUDFLARE_D1_STORAGE_GET_TRACES_ERROR",
1766
- domain: ErrorDomain.STORAGE,
1767
- category: ErrorCategory.THIRD_PARTY,
1768
- text: `Failed to retrieve traces: ${error instanceof Error ? error.message : String(error)}`,
1769
- details: {
1770
- name: args.name ?? "",
1771
- scope: args.scope ?? ""
1772
- }
1773
- },
1774
- error
1775
- );
1776
- }
1777
- }
1778
- async getTracesPaginated(args) {
1779
- const { name, scope, page = 0, perPage = 100, attributes, dateRange } = args;
1780
- const fromDate = dateRange?.start;
1781
- const toDate = dateRange?.end;
1782
- const fullTableName = this.operations.getTableName(TABLE_TRACES);
1632
+ async listScoresBySpan({
1633
+ traceId,
1634
+ spanId,
1635
+ pagination
1636
+ }) {
1783
1637
  try {
1784
- const dataQuery = createSqlBuilder().select("*").from(fullTableName).where("1=1");
1785
- const countQuery = createSqlBuilder().count().from(fullTableName).where("1=1");
1786
- if (name) {
1787
- dataQuery.andWhere("name LIKE ?", `%${name}%`);
1788
- countQuery.andWhere("name LIKE ?", `%${name}%`);
1789
- }
1790
- if (scope) {
1791
- dataQuery.andWhere("scope = ?", scope);
1792
- countQuery.andWhere("scope = ?", scope);
1793
- }
1794
- if (attributes && Object.keys(attributes).length > 0) {
1795
- for (const [key, value] of Object.entries(attributes)) {
1796
- dataQuery.jsonLike("attributes", key, value);
1797
- countQuery.jsonLike("attributes", key, value);
1798
- }
1799
- }
1800
- if (fromDate) {
1801
- const fromDateStr = fromDate instanceof Date ? fromDate.toISOString() : fromDate;
1802
- dataQuery.andWhere("createdAt >= ?", fromDateStr);
1803
- countQuery.andWhere("createdAt >= ?", fromDateStr);
1804
- }
1805
- if (toDate) {
1806
- const toDateStr = toDate instanceof Date ? toDate.toISOString() : toDate;
1807
- dataQuery.andWhere("createdAt <= ?", toDateStr);
1808
- countQuery.andWhere("createdAt <= ?", toDateStr);
1809
- }
1810
- const allDataResult = await this.operations.executeQuery(
1811
- createSqlBuilder().select("*").from(fullTableName).where("1=1").build()
1812
- );
1813
- console.log("allDataResult", allDataResult);
1638
+ const { page, perPage: perPageInput } = pagination;
1639
+ const perPage = normalizePerPage(perPageInput, 100);
1640
+ const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
1641
+ const fullTableName = this.operations.getTableName(TABLE_SCORERS);
1642
+ const countQuery = createSqlBuilder().count().from(fullTableName).where("traceId = ?", traceId).andWhere("spanId = ?", spanId);
1814
1643
  const countResult = await this.operations.executeQuery(countQuery.build());
1815
- const total = Number(countResult?.[0]?.count ?? 0);
1816
- dataQuery.orderBy("startTime", "DESC").limit(perPage).offset(page * perPage);
1817
- const results = await this.operations.executeQuery(dataQuery.build());
1818
- const traces = isArrayOfRecords2(results) ? results.map(
1819
- (trace) => ({
1820
- ...trace,
1821
- attributes: deserializeValue(trace.attributes, "jsonb"),
1822
- status: deserializeValue(trace.status, "jsonb"),
1823
- events: deserializeValue(trace.events, "jsonb"),
1824
- links: deserializeValue(trace.links, "jsonb"),
1825
- other: deserializeValue(trace.other, "jsonb")
1826
- })
1827
- ) : [];
1644
+ const total = Array.isArray(countResult) ? Number(countResult?.[0]?.count ?? 0) : Number(countResult?.count ?? 0);
1645
+ if (total === 0) {
1646
+ return {
1647
+ pagination: {
1648
+ total: 0,
1649
+ page,
1650
+ perPage: perPageForResponse,
1651
+ hasMore: false
1652
+ },
1653
+ scores: []
1654
+ };
1655
+ }
1656
+ const end = perPageInput === false ? total : start + perPage;
1657
+ const limitValue = perPageInput === false ? total : perPage;
1658
+ const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("traceId = ?", traceId).andWhere("spanId = ?", spanId).orderBy("createdAt", "DESC").limit(limitValue).offset(start);
1659
+ const { sql, params } = selectQuery.build();
1660
+ const results = await this.operations.executeQuery({ sql, params });
1661
+ const scores = Array.isArray(results) ? results.map(transformScoreRow) : [];
1828
1662
  return {
1829
- traces,
1830
- total,
1831
- page,
1832
- perPage,
1833
- hasMore: page * perPage + traces.length < total
1663
+ pagination: {
1664
+ total,
1665
+ page,
1666
+ perPage: perPageForResponse,
1667
+ hasMore: end < total
1668
+ },
1669
+ scores
1834
1670
  };
1835
1671
  } catch (error) {
1836
- const mastraError = new MastraError(
1672
+ throw new MastraError(
1837
1673
  {
1838
- id: "CLOUDFLARE_D1_STORAGE_GET_TRACES_PAGINATED_ERROR",
1674
+ id: createStorageErrorId("CLOUDFLARE_D1", "GET_SCORES_BY_SPAN", "FAILED"),
1839
1675
  domain: ErrorDomain.STORAGE,
1840
- category: ErrorCategory.THIRD_PARTY,
1841
- text: `Failed to retrieve traces: ${error instanceof Error ? error.message : String(error)}`,
1842
- details: { name: name ?? "", scope: scope ?? "" }
1676
+ category: ErrorCategory.THIRD_PARTY
1843
1677
  },
1844
1678
  error
1845
1679
  );
1846
- this.logger?.error(mastraError.toString());
1847
- this.logger?.trackException(mastraError);
1848
- return { traces: [], total: 0, page, perPage, hasMore: false };
1849
1680
  }
1850
1681
  }
1851
- async batchTraceInsert({ records }) {
1852
- this.logger.debug("Batch inserting traces", { count: records.length });
1853
- await this.operations.batchInsert({
1854
- tableName: TABLE_TRACES,
1855
- records
1856
- });
1857
- }
1858
1682
  };
1859
1683
  var WorkflowsStorageD1 = class extends WorkflowsStorage {
1860
1684
  operations;
@@ -1862,9 +1686,26 @@ var WorkflowsStorageD1 = class extends WorkflowsStorage {
1862
1686
  super();
1863
1687
  this.operations = operations;
1864
1688
  }
1689
+ updateWorkflowResults({
1690
+ // workflowName,
1691
+ // runId,
1692
+ // stepId,
1693
+ // result,
1694
+ // requestContext,
1695
+ }) {
1696
+ throw new Error("Method not implemented.");
1697
+ }
1698
+ updateWorkflowState({
1699
+ // workflowName,
1700
+ // runId,
1701
+ // opts,
1702
+ }) {
1703
+ throw new Error("Method not implemented.");
1704
+ }
1865
1705
  async persistWorkflowSnapshot({
1866
1706
  workflowName,
1867
1707
  runId,
1708
+ resourceId,
1868
1709
  snapshot
1869
1710
  }) {
1870
1711
  const fullTableName = this.operations.getTableName(TABLE_WORKFLOW_SNAPSHOT);
@@ -1875,11 +1716,13 @@ var WorkflowsStorageD1 = class extends WorkflowsStorage {
1875
1716
  });
1876
1717
  const persisting = currentSnapshot ? {
1877
1718
  ...currentSnapshot,
1719
+ resourceId,
1878
1720
  snapshot: JSON.stringify(snapshot),
1879
1721
  updatedAt: now
1880
1722
  } : {
1881
1723
  workflow_name: workflowName,
1882
1724
  run_id: runId,
1725
+ resourceId,
1883
1726
  snapshot,
1884
1727
  createdAt: now,
1885
1728
  updatedAt: now
@@ -1899,7 +1742,7 @@ var WorkflowsStorageD1 = class extends WorkflowsStorage {
1899
1742
  } catch (error) {
1900
1743
  throw new MastraError(
1901
1744
  {
1902
- id: "CLOUDFLARE_D1_STORAGE_PERSIST_WORKFLOW_SNAPSHOT_ERROR",
1745
+ id: createStorageErrorId("CLOUDFLARE_D1", "PERSIST_WORKFLOW_SNAPSHOT", "FAILED"),
1903
1746
  domain: ErrorDomain.STORAGE,
1904
1747
  category: ErrorCategory.THIRD_PARTY,
1905
1748
  text: `Failed to persist workflow snapshot: ${error instanceof Error ? error.message : String(error)}`,
@@ -1924,7 +1767,7 @@ var WorkflowsStorageD1 = class extends WorkflowsStorage {
1924
1767
  } catch (error) {
1925
1768
  throw new MastraError(
1926
1769
  {
1927
- id: "CLOUDFLARE_D1_STORAGE_LOAD_WORKFLOW_SNAPSHOT_ERROR",
1770
+ id: createStorageErrorId("CLOUDFLARE_D1", "LOAD_WORKFLOW_SNAPSHOT", "FAILED"),
1928
1771
  domain: ErrorDomain.STORAGE,
1929
1772
  category: ErrorCategory.THIRD_PARTY,
1930
1773
  text: `Failed to load workflow snapshot: ${error instanceof Error ? error.message : String(error)}`,
@@ -1952,19 +1795,24 @@ var WorkflowsStorageD1 = class extends WorkflowsStorage {
1952
1795
  resourceId: row.resourceId
1953
1796
  };
1954
1797
  }
1955
- async getWorkflowRuns({
1798
+ async listWorkflowRuns({
1956
1799
  workflowName,
1957
1800
  fromDate,
1958
1801
  toDate,
1959
- limit,
1960
- offset,
1961
- resourceId
1802
+ page,
1803
+ perPage,
1804
+ resourceId,
1805
+ status
1962
1806
  } = {}) {
1963
1807
  const fullTableName = this.operations.getTableName(TABLE_WORKFLOW_SNAPSHOT);
1964
1808
  try {
1965
1809
  const builder = createSqlBuilder().select().from(fullTableName);
1966
1810
  const countBuilder = createSqlBuilder().count().from(fullTableName);
1967
1811
  if (workflowName) builder.whereAnd("workflow_name = ?", workflowName);
1812
+ if (status) {
1813
+ builder.whereAnd("json_extract(snapshot, '$.status') = ?", status);
1814
+ countBuilder.whereAnd("json_extract(snapshot, '$.status') = ?", status);
1815
+ }
1968
1816
  if (resourceId) {
1969
1817
  const hasResourceId = await this.operations.hasColumn(fullTableName, "resourceId");
1970
1818
  if (hasResourceId) {
@@ -1983,11 +1831,14 @@ var WorkflowsStorageD1 = class extends WorkflowsStorage {
1983
1831
  countBuilder.whereAnd("createdAt <= ?", toDate instanceof Date ? toDate.toISOString() : toDate);
1984
1832
  }
1985
1833
  builder.orderBy("createdAt", "DESC");
1986
- if (typeof limit === "number") builder.limit(limit);
1987
- if (typeof offset === "number") builder.offset(offset);
1834
+ if (typeof perPage === "number" && typeof page === "number") {
1835
+ const offset = page * perPage;
1836
+ builder.limit(perPage);
1837
+ builder.offset(offset);
1838
+ }
1988
1839
  const { sql, params } = builder.build();
1989
1840
  let total = 0;
1990
- if (limit !== void 0 && offset !== void 0) {
1841
+ if (perPage !== void 0 && page !== void 0) {
1991
1842
  const { sql: countSql, params: countParams } = countBuilder.build();
1992
1843
  const countResult = await this.operations.executeQuery({
1993
1844
  sql: countSql,
@@ -2002,7 +1853,7 @@ var WorkflowsStorageD1 = class extends WorkflowsStorage {
2002
1853
  } catch (error) {
2003
1854
  throw new MastraError(
2004
1855
  {
2005
- id: "CLOUDFLARE_D1_STORAGE_GET_WORKFLOW_RUNS_ERROR",
1856
+ id: createStorageErrorId("CLOUDFLARE_D1", "LIST_WORKFLOW_RUNS", "FAILED"),
2006
1857
  domain: ErrorDomain.STORAGE,
2007
1858
  category: ErrorCategory.THIRD_PARTY,
2008
1859
  text: `Failed to retrieve workflow runs: ${error instanceof Error ? error.message : String(error)}`,
@@ -2039,7 +1890,7 @@ var WorkflowsStorageD1 = class extends WorkflowsStorage {
2039
1890
  } catch (error) {
2040
1891
  throw new MastraError(
2041
1892
  {
2042
- id: "CLOUDFLARE_D1_STORAGE_GET_WORKFLOW_RUN_BY_ID_ERROR",
1893
+ id: createStorageErrorId("CLOUDFLARE_D1", "GET_WORKFLOW_RUN_BY_ID", "FAILED"),
2043
1894
  domain: ErrorDomain.STORAGE,
2044
1895
  category: ErrorCategory.THIRD_PARTY,
2045
1896
  text: `Failed to retrieve workflow run by ID: ${error instanceof Error ? error.message : String(error)}`,
@@ -2064,7 +1915,7 @@ var D1Store = class extends MastraStorage {
2064
1915
  */
2065
1916
  constructor(config) {
2066
1917
  try {
2067
- super({ name: "D1" });
1918
+ super({ id: config.id, name: "D1", disableInit: config.disableInit });
2068
1919
  if (config.tablePrefix && !/^[a-zA-Z0-9_]*$/.test(config.tablePrefix)) {
2069
1920
  throw new Error("Invalid tablePrefix: only letters, numbers, and underscores are allowed.");
2070
1921
  }
@@ -2102,7 +1953,7 @@ var D1Store = class extends MastraStorage {
2102
1953
  } catch (error) {
2103
1954
  throw new MastraError(
2104
1955
  {
2105
- id: "CLOUDFLARE_D1_STORAGE_INITIALIZATION_ERROR",
1956
+ id: createStorageErrorId("CLOUDFLARE_D1", "INITIALIZATION", "FAILED"),
2106
1957
  domain: ErrorDomain.STORAGE,
2107
1958
  category: ErrorCategory.SYSTEM,
2108
1959
  text: "Error initializing D1Store"
@@ -2118,12 +1969,6 @@ var D1Store = class extends MastraStorage {
2118
1969
  const scores = new ScoresStorageD1({
2119
1970
  operations
2120
1971
  });
2121
- const legacyEvals = new LegacyEvalsStorageD1({
2122
- operations
2123
- });
2124
- const traces = new TracesStorageD1({
2125
- operations
2126
- });
2127
1972
  const workflows = new WorkflowsStorageD1({
2128
1973
  operations
2129
1974
  });
@@ -2133,8 +1978,6 @@ var D1Store = class extends MastraStorage {
2133
1978
  this.stores = {
2134
1979
  operations,
2135
1980
  scores,
2136
- legacyEvals,
2137
- traces,
2138
1981
  workflows,
2139
1982
  memory
2140
1983
  };
@@ -2145,7 +1988,8 @@ var D1Store = class extends MastraStorage {
2145
1988
  resourceWorkingMemory: true,
2146
1989
  hasColumn: true,
2147
1990
  createTable: true,
2148
- deleteMessages: false
1991
+ deleteMessages: false,
1992
+ listScoresBySpan: true
2149
1993
  };
2150
1994
  }
2151
1995
  async createTable({
@@ -2185,15 +2029,6 @@ var D1Store = class extends MastraStorage {
2185
2029
  async getThreadById({ threadId }) {
2186
2030
  return this.stores.memory.getThreadById({ threadId });
2187
2031
  }
2188
- /**
2189
- * @deprecated use getThreadsByResourceIdPaginated instead
2190
- */
2191
- async getThreadsByResourceId({ resourceId }) {
2192
- return this.stores.memory.getThreadsByResourceId({ resourceId });
2193
- }
2194
- async getThreadsByResourceIdPaginated(args) {
2195
- return this.stores.memory.getThreadsByResourceIdPaginated(args);
2196
- }
2197
2032
  async saveThread({ thread }) {
2198
2033
  return this.stores.memory.saveThread({ thread });
2199
2034
  }
@@ -2210,39 +2045,35 @@ var D1Store = class extends MastraStorage {
2210
2045
  async saveMessages(args) {
2211
2046
  return this.stores.memory.saveMessages(args);
2212
2047
  }
2213
- async getMessages({
2214
- threadId,
2215
- selectBy,
2216
- format
2048
+ async updateWorkflowResults({
2049
+ workflowName,
2050
+ runId,
2051
+ stepId,
2052
+ result,
2053
+ requestContext
2217
2054
  }) {
2218
- return this.stores.memory.getMessages({ threadId, selectBy, format });
2055
+ return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, requestContext });
2219
2056
  }
2220
- async getMessagesPaginated({
2221
- threadId,
2222
- selectBy,
2223
- format
2057
+ async updateWorkflowState({
2058
+ workflowName,
2059
+ runId,
2060
+ opts
2224
2061
  }) {
2225
- return this.stores.memory.getMessagesPaginated({ threadId, selectBy, format });
2062
+ return this.stores.workflows.updateWorkflowState({ workflowName, runId, opts });
2226
2063
  }
2227
2064
  async persistWorkflowSnapshot({
2228
2065
  workflowName,
2229
2066
  runId,
2067
+ resourceId,
2230
2068
  snapshot
2231
2069
  }) {
2232
- return this.stores.workflows.persistWorkflowSnapshot({ workflowName, runId, snapshot });
2070
+ return this.stores.workflows.persistWorkflowSnapshot({ workflowName, runId, resourceId, snapshot });
2233
2071
  }
2234
2072
  async loadWorkflowSnapshot(params) {
2235
2073
  return this.stores.workflows.loadWorkflowSnapshot(params);
2236
2074
  }
2237
- async getWorkflowRuns({
2238
- workflowName,
2239
- fromDate,
2240
- toDate,
2241
- limit,
2242
- offset,
2243
- resourceId
2244
- } = {}) {
2245
- return this.stores.workflows.getWorkflowRuns({ workflowName, fromDate, toDate, limit, offset, resourceId });
2075
+ async listWorkflowRuns(args = {}) {
2076
+ return this.stores.workflows.listWorkflowRuns(args);
2246
2077
  }
2247
2078
  async getWorkflowRunById({
2248
2079
  runId,
@@ -2258,24 +2089,6 @@ var D1Store = class extends MastraStorage {
2258
2089
  async batchInsert({ tableName, records }) {
2259
2090
  return this.stores.operations.batchInsert({ tableName, records });
2260
2091
  }
2261
- /**
2262
- * @deprecated use getTracesPaginated instead
2263
- */
2264
- async getTraces(args) {
2265
- return this.stores.traces.getTraces(args);
2266
- }
2267
- async getTracesPaginated(args) {
2268
- return this.stores.traces.getTracesPaginated(args);
2269
- }
2270
- /**
2271
- * @deprecated use getEvals instead
2272
- */
2273
- async getEvalsByAgentName(agentName, type) {
2274
- return this.stores.legacyEvals.getEvalsByAgentName(agentName, type);
2275
- }
2276
- async getEvals(options) {
2277
- return this.stores.legacyEvals.getEvals(options);
2278
- }
2279
2092
  async updateMessages(_args) {
2280
2093
  return this.stores.memory.updateMessages(_args);
2281
2094
  }
@@ -2295,31 +2108,41 @@ var D1Store = class extends MastraStorage {
2295
2108
  async getScoreById({ id: _id }) {
2296
2109
  return this.stores.scores.getScoreById({ id: _id });
2297
2110
  }
2298
- async saveScore(_score) {
2299
- return this.stores.scores.saveScore(_score);
2111
+ async saveScore(score) {
2112
+ return this.stores.scores.saveScore(score);
2300
2113
  }
2301
- async getScoresByRunId({
2114
+ async listScoresByRunId({
2302
2115
  runId: _runId,
2303
2116
  pagination: _pagination
2304
2117
  }) {
2305
- return this.stores.scores.getScoresByRunId({ runId: _runId, pagination: _pagination });
2118
+ return this.stores.scores.listScoresByRunId({ runId: _runId, pagination: _pagination });
2306
2119
  }
2307
- async getScoresByEntityId({
2120
+ async listScoresByEntityId({
2308
2121
  entityId: _entityId,
2309
2122
  entityType: _entityType,
2310
2123
  pagination: _pagination
2311
2124
  }) {
2312
- return this.stores.scores.getScoresByEntityId({
2125
+ return this.stores.scores.listScoresByEntityId({
2313
2126
  entityId: _entityId,
2314
2127
  entityType: _entityType,
2315
2128
  pagination: _pagination
2316
2129
  });
2317
2130
  }
2318
- async getScoresByScorerId({
2319
- scorerId: _scorerId,
2320
- pagination: _pagination
2131
+ async listScoresByScorerId({
2132
+ scorerId,
2133
+ pagination,
2134
+ entityId,
2135
+ entityType,
2136
+ source
2137
+ }) {
2138
+ return this.stores.scores.listScoresByScorerId({ scorerId, pagination, entityId, entityType, source });
2139
+ }
2140
+ async listScoresBySpan({
2141
+ traceId,
2142
+ spanId,
2143
+ pagination
2321
2144
  }) {
2322
- return this.stores.scores.getScoresByScorerId({ scorerId: _scorerId, pagination: _pagination });
2145
+ return this.stores.scores.listScoresBySpan({ traceId, spanId, pagination });
2323
2146
  }
2324
2147
  /**
2325
2148
  * Close the database connection