@mastra/cloudflare-d1 0.0.0-toolOptionTypes-20250917085558 → 0.0.0-top-level-fix-20251211103030

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
@@ -3,8 +3,9 @@
3
3
  var error = require('@mastra/core/error');
4
4
  var storage = require('@mastra/core/storage');
5
5
  var Cloudflare = require('cloudflare');
6
- var utils = require('@mastra/core/utils');
7
6
  var agent = require('@mastra/core/agent');
7
+ var utils = require('@mastra/core/utils');
8
+ var evals = require('@mastra/core/evals');
8
9
 
9
10
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
10
11
 
@@ -247,16 +248,6 @@ function isArrayOfRecords(value) {
247
248
  }
248
249
  function deserializeValue(value, type) {
249
250
  if (value === null || value === void 0) return null;
250
- if (type === "date" && typeof value === "string") {
251
- return new Date(value);
252
- }
253
- if (type === "jsonb" && typeof value === "string") {
254
- try {
255
- return JSON.parse(value);
256
- } catch {
257
- return value;
258
- }
259
- }
260
251
  if (typeof value === "string" && (value.startsWith("{") || value.startsWith("["))) {
261
252
  try {
262
253
  return JSON.parse(value);
@@ -267,155 +258,7 @@ function deserializeValue(value, type) {
267
258
  return value;
268
259
  }
269
260
 
270
- // src/storage/domains/legacy-evals/index.ts
271
- var LegacyEvalsStorageD1 = class extends storage.LegacyEvalsStorage {
272
- operations;
273
- constructor({ operations }) {
274
- super();
275
- this.operations = operations;
276
- }
277
- async getEvals(options) {
278
- const { agentName, type, page = 0, perPage = 40, dateRange } = options || {};
279
- const fullTableName = this.operations.getTableName(storage.TABLE_EVALS);
280
- const conditions = [];
281
- const queryParams = [];
282
- if (agentName) {
283
- conditions.push(`agent_name = ?`);
284
- queryParams.push(agentName);
285
- }
286
- if (type === "test") {
287
- conditions.push(`(test_info IS NOT NULL AND json_extract(test_info, '$.testPath') IS NOT NULL)`);
288
- } else if (type === "live") {
289
- conditions.push(`(test_info IS NULL OR json_extract(test_info, '$.testPath') IS NULL)`);
290
- }
291
- if (dateRange?.start) {
292
- conditions.push(`created_at >= ?`);
293
- queryParams.push(storage.serializeDate(dateRange.start));
294
- }
295
- if (dateRange?.end) {
296
- conditions.push(`created_at <= ?`);
297
- queryParams.push(storage.serializeDate(dateRange.end));
298
- }
299
- const countQueryBuilder = createSqlBuilder().count().from(fullTableName);
300
- if (conditions.length > 0) {
301
- countQueryBuilder.where(conditions.join(" AND "), ...queryParams);
302
- }
303
- const { sql: countSql, params: countParams } = countQueryBuilder.build();
304
- try {
305
- const countResult = await this.operations.executeQuery({
306
- sql: countSql,
307
- params: countParams,
308
- first: true
309
- });
310
- const total = Number(countResult?.count || 0);
311
- const currentOffset = page * perPage;
312
- if (total === 0) {
313
- return {
314
- evals: [],
315
- total: 0,
316
- page,
317
- perPage,
318
- hasMore: false
319
- };
320
- }
321
- const dataQueryBuilder = createSqlBuilder().select("*").from(fullTableName);
322
- if (conditions.length > 0) {
323
- dataQueryBuilder.where(conditions.join(" AND "), ...queryParams);
324
- }
325
- dataQueryBuilder.orderBy("created_at", "DESC").limit(perPage).offset(currentOffset);
326
- const { sql: dataSql, params: dataParams } = dataQueryBuilder.build();
327
- const rows = await this.operations.executeQuery({
328
- sql: dataSql,
329
- params: dataParams
330
- });
331
- const evals = (isArrayOfRecords(rows) ? rows : []).map((row) => {
332
- const result = deserializeValue(row.result);
333
- const testInfo = row.test_info ? deserializeValue(row.test_info) : void 0;
334
- if (!result || typeof result !== "object" || !("score" in result)) {
335
- throw new Error(`Invalid MetricResult format: ${JSON.stringify(result)}`);
336
- }
337
- return {
338
- input: row.input,
339
- output: row.output,
340
- result,
341
- agentName: row.agent_name,
342
- metricName: row.metric_name,
343
- instructions: row.instructions,
344
- testInfo,
345
- globalRunId: row.global_run_id,
346
- runId: row.run_id,
347
- createdAt: row.created_at
348
- };
349
- });
350
- const hasMore = currentOffset + evals.length < total;
351
- return {
352
- evals,
353
- total,
354
- page,
355
- perPage,
356
- hasMore
357
- };
358
- } catch (error$1) {
359
- throw new error.MastraError(
360
- {
361
- id: "CLOUDFLARE_D1_STORAGE_GET_EVALS_ERROR",
362
- domain: error.ErrorDomain.STORAGE,
363
- category: error.ErrorCategory.THIRD_PARTY,
364
- text: `Failed to retrieve evals for agent ${agentName}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
365
- details: { agentName: agentName ?? "", type: type ?? "" }
366
- },
367
- error$1
368
- );
369
- }
370
- }
371
- /**
372
- * @deprecated use getEvals instead
373
- */
374
- async getEvalsByAgentName(agentName, type) {
375
- const fullTableName = this.operations.getTableName(storage.TABLE_EVALS);
376
- try {
377
- let query = createSqlBuilder().select("*").from(fullTableName).where("agent_name = ?", agentName);
378
- if (type === "test") {
379
- query = query.andWhere("test_info IS NOT NULL AND json_extract(test_info, '$.testPath') IS NOT NULL");
380
- } else if (type === "live") {
381
- query = query.andWhere("(test_info IS NULL OR json_extract(test_info, '$.testPath') IS NULL)");
382
- }
383
- query.orderBy("created_at", "DESC");
384
- const { sql, params } = query.build();
385
- const results = await this.operations.executeQuery({ sql, params });
386
- return isArrayOfRecords(results) ? results.map((row) => {
387
- const result = deserializeValue(row.result);
388
- const testInfo = row.test_info ? deserializeValue(row.test_info) : void 0;
389
- return {
390
- input: row.input || "",
391
- output: row.output || "",
392
- result,
393
- agentName: row.agent_name || "",
394
- metricName: row.metric_name || "",
395
- instructions: row.instructions || "",
396
- runId: row.run_id || "",
397
- globalRunId: row.global_run_id || "",
398
- createdAt: row.created_at || "",
399
- testInfo
400
- };
401
- }) : [];
402
- } catch (error$1) {
403
- const mastraError = new error.MastraError(
404
- {
405
- id: "CLOUDFLARE_D1_STORAGE_GET_EVALS_ERROR",
406
- domain: error.ErrorDomain.STORAGE,
407
- category: error.ErrorCategory.THIRD_PARTY,
408
- text: `Failed to retrieve evals for agent ${agentName}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
409
- details: { agentName }
410
- },
411
- error$1
412
- );
413
- this.logger?.error(mastraError.toString());
414
- this.logger?.trackException(mastraError);
415
- return [];
416
- }
417
- }
418
- };
261
+ // src/storage/domains/memory/index.ts
419
262
  var MemoryStorageD1 = class extends storage.MemoryStorage {
420
263
  operations;
421
264
  constructor({ operations }) {
@@ -438,7 +281,7 @@ var MemoryStorageD1 = class extends storage.MemoryStorage {
438
281
  } catch (error$1) {
439
282
  const mastraError = new error.MastraError(
440
283
  {
441
- id: "CLOUDFLARE_D1_STORAGE_GET_RESOURCE_BY_ID_ERROR",
284
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "GET_RESOURCE_BY_ID", "FAILED"),
442
285
  domain: error.ErrorDomain.STORAGE,
443
286
  category: error.ErrorCategory.THIRD_PARTY,
444
287
  text: `Error processing resource ${resourceId}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
@@ -477,7 +320,7 @@ var MemoryStorageD1 = class extends storage.MemoryStorage {
477
320
  } catch (error$1) {
478
321
  throw new error.MastraError(
479
322
  {
480
- id: "CLOUDFLARE_D1_STORAGE_SAVE_RESOURCE_ERROR",
323
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "SAVE_RESOURCE", "FAILED"),
481
324
  domain: error.ErrorDomain.STORAGE,
482
325
  category: error.ErrorCategory.THIRD_PARTY,
483
326
  text: `Failed to save resource to ${fullTableName}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
@@ -524,7 +367,7 @@ var MemoryStorageD1 = class extends storage.MemoryStorage {
524
367
  } catch (error$1) {
525
368
  throw new error.MastraError(
526
369
  {
527
- id: "CLOUDFLARE_D1_STORAGE_UPDATE_RESOURCE_ERROR",
370
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "UPDATE_RESOURCE", "FAILED"),
528
371
  domain: error.ErrorDomain.STORAGE,
529
372
  category: error.ErrorCategory.THIRD_PARTY,
530
373
  text: `Failed to update resource ${resourceId}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
@@ -550,7 +393,7 @@ var MemoryStorageD1 = class extends storage.MemoryStorage {
550
393
  } catch (error$1) {
551
394
  const mastraError = new error.MastraError(
552
395
  {
553
- id: "CLOUDFLARE_D1_STORAGE_GET_THREAD_BY_ID_ERROR",
396
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "GET_THREAD_BY_ID", "FAILED"),
554
397
  domain: error.ErrorDomain.STORAGE,
555
398
  category: error.ErrorCategory.THIRD_PARTY,
556
399
  text: `Error processing thread ${threadId}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
@@ -563,39 +406,22 @@ var MemoryStorageD1 = class extends storage.MemoryStorage {
563
406
  return null;
564
407
  }
565
408
  }
566
- /**
567
- * @deprecated use getThreadsByResourceIdPaginated instead
568
- */
569
- async getThreadsByResourceId({ resourceId }) {
570
- const fullTableName = this.operations.getTableName(storage.TABLE_THREADS);
571
- try {
572
- const query = createSqlBuilder().select("*").from(fullTableName).where("resourceId = ?", resourceId);
573
- const { sql, params } = query.build();
574
- const results = await this.operations.executeQuery({ sql, params });
575
- return (isArrayOfRecords(results) ? results : []).map((thread) => ({
576
- ...thread,
577
- createdAt: storage.ensureDate(thread.createdAt),
578
- updatedAt: storage.ensureDate(thread.updatedAt),
579
- metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata || "{}") : thread.metadata || {}
580
- }));
581
- } catch (error$1) {
582
- const mastraError = new error.MastraError(
409
+ async listThreadsByResourceId(args) {
410
+ const { resourceId, page = 0, perPage: perPageInput, orderBy } = args;
411
+ const perPage = storage.normalizePerPage(perPageInput, 100);
412
+ if (page < 0) {
413
+ throw new error.MastraError(
583
414
  {
584
- id: "CLOUDFLARE_D1_STORAGE_GET_THREADS_BY_RESOURCE_ID_ERROR",
415
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "LIST_THREADS_BY_RESOURCE_ID", "INVALID_PAGE"),
585
416
  domain: error.ErrorDomain.STORAGE,
586
- category: error.ErrorCategory.THIRD_PARTY,
587
- text: `Error getting threads by resourceId ${resourceId}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
588
- details: { resourceId }
417
+ category: error.ErrorCategory.USER,
418
+ details: { page }
589
419
  },
590
- error$1
420
+ new Error("page must be >= 0")
591
421
  );
592
- this.logger?.error(mastraError.toString());
593
- this.logger?.trackException(mastraError);
594
- return [];
595
422
  }
596
- }
597
- async getThreadsByResourceIdPaginated(args) {
598
- const { resourceId, page, perPage } = args;
423
+ const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
424
+ const { field, direction } = this.parseOrderBy(orderBy);
599
425
  const fullTableName = this.operations.getTableName(storage.TABLE_THREADS);
600
426
  const mapRowToStorageThreadType = (row) => ({
601
427
  ...row,
@@ -607,20 +433,21 @@ var MemoryStorageD1 = class extends storage.MemoryStorage {
607
433
  const countQuery = createSqlBuilder().count().from(fullTableName).where("resourceId = ?", resourceId);
608
434
  const countResult = await this.operations.executeQuery(countQuery.build());
609
435
  const total = Number(countResult?.[0]?.count ?? 0);
610
- const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("resourceId = ?", resourceId).orderBy("createdAt", "DESC").limit(perPage).offset(page * perPage);
436
+ const limitValue = perPageInput === false ? total : perPage;
437
+ const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("resourceId = ?", resourceId).orderBy(field, direction).limit(limitValue).offset(offset);
611
438
  const results = await this.operations.executeQuery(selectQuery.build());
612
439
  const threads = results.map(mapRowToStorageThreadType);
613
440
  return {
614
441
  threads,
615
442
  total,
616
443
  page,
617
- perPage,
618
- hasMore: page * perPage + threads.length < total
444
+ perPage: perPageForResponse,
445
+ hasMore: perPageInput === false ? false : offset + perPage < total
619
446
  };
620
447
  } catch (error$1) {
621
448
  const mastraError = new error.MastraError(
622
449
  {
623
- id: "CLOUDFLARE_D1_STORAGE_GET_THREADS_BY_RESOURCE_ID_PAGINATED_ERROR",
450
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "LIST_THREADS_BY_RESOURCE_ID", "FAILED"),
624
451
  domain: error.ErrorDomain.STORAGE,
625
452
  category: error.ErrorCategory.THIRD_PARTY,
626
453
  text: `Error getting threads by resourceId ${resourceId}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
@@ -634,7 +461,7 @@ var MemoryStorageD1 = class extends storage.MemoryStorage {
634
461
  threads: [],
635
462
  total: 0,
636
463
  page,
637
- perPage,
464
+ perPage: perPageForResponse,
638
465
  hasMore: false
639
466
  };
640
467
  }
@@ -667,7 +494,7 @@ var MemoryStorageD1 = class extends storage.MemoryStorage {
667
494
  } catch (error$1) {
668
495
  throw new error.MastraError(
669
496
  {
670
- id: "CLOUDFLARE_D1_STORAGE_SAVE_THREAD_ERROR",
497
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "SAVE_THREAD", "FAILED"),
671
498
  domain: error.ErrorDomain.STORAGE,
672
499
  category: error.ErrorCategory.THIRD_PARTY,
673
500
  text: `Failed to save thread to ${fullTableName}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
@@ -710,7 +537,7 @@ var MemoryStorageD1 = class extends storage.MemoryStorage {
710
537
  } catch (error$1) {
711
538
  throw new error.MastraError(
712
539
  {
713
- id: "CLOUDFLARE_D1_STORAGE_UPDATE_THREAD_ERROR",
540
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "UPDATE_THREAD", "FAILED"),
714
541
  domain: error.ErrorDomain.STORAGE,
715
542
  category: error.ErrorCategory.THIRD_PARTY,
716
543
  text: `Failed to update thread ${id}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
@@ -733,7 +560,7 @@ var MemoryStorageD1 = class extends storage.MemoryStorage {
733
560
  } catch (error$1) {
734
561
  throw new error.MastraError(
735
562
  {
736
- id: "CLOUDFLARE_D1_STORAGE_DELETE_THREAD_ERROR",
563
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "DELETE_THREAD", "FAILED"),
737
564
  domain: error.ErrorDomain.STORAGE,
738
565
  category: error.ErrorCategory.THIRD_PARTY,
739
566
  text: `Failed to delete thread ${threadId}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
@@ -744,8 +571,8 @@ var MemoryStorageD1 = class extends storage.MemoryStorage {
744
571
  }
745
572
  }
746
573
  async saveMessages(args) {
747
- const { messages, format = "v1" } = args;
748
- if (messages.length === 0) return [];
574
+ const { messages } = args;
575
+ if (messages.length === 0) return { messages: [] };
749
576
  try {
750
577
  const now = /* @__PURE__ */ new Date();
751
578
  const threadId = messages[0]?.threadId;
@@ -793,12 +620,11 @@ var MemoryStorageD1 = class extends storage.MemoryStorage {
793
620
  ]);
794
621
  this.logger.debug(`Saved ${messages.length} messages`);
795
622
  const list = new agent.MessageList().add(messages, "memory");
796
- if (format === `v2`) return list.get.all.v2();
797
- return list.get.all.v1();
623
+ return { messages: list.get.all.db() };
798
624
  } catch (error$1) {
799
625
  throw new error.MastraError(
800
626
  {
801
- id: "CLOUDFLARE_D1_STORAGE_SAVE_MESSAGES_ERROR",
627
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "SAVE_MESSAGES", "FAILED"),
802
628
  domain: error.ErrorDomain.STORAGE,
803
629
  category: error.ErrorCategory.THIRD_PARTY,
804
630
  text: `Failed to save messages: ${error$1 instanceof Error ? error$1.message : String(error$1)}`
@@ -807,24 +633,25 @@ var MemoryStorageD1 = class extends storage.MemoryStorage {
807
633
  );
808
634
  }
809
635
  }
810
- async _getIncludedMessages(threadId, selectBy) {
811
- if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
812
- const include = selectBy?.include;
813
- if (!include) return null;
636
+ async _getIncludedMessages(include) {
637
+ if (!include || include.length === 0) return null;
814
638
  const unionQueries = [];
815
639
  const params = [];
816
640
  let paramIdx = 1;
641
+ const tableName = this.operations.getTableName(storage.TABLE_MESSAGES);
817
642
  for (const inc of include) {
818
643
  const { id, withPreviousMessages = 0, withNextMessages = 0 } = inc;
819
- const searchId = inc.threadId || threadId;
820
644
  unionQueries.push(`
821
645
  SELECT * FROM (
822
- WITH ordered_messages AS (
646
+ WITH target_thread AS (
647
+ SELECT thread_id FROM ${tableName} WHERE id = ?
648
+ ),
649
+ ordered_messages AS (
823
650
  SELECT
824
651
  *,
825
652
  ROW_NUMBER() OVER (ORDER BY createdAt ASC) AS row_num
826
- FROM ${this.operations.getTableName(storage.TABLE_MESSAGES)}
827
- WHERE thread_id = ?
653
+ FROM ${tableName}
654
+ WHERE thread_id = (SELECT thread_id FROM target_thread)
828
655
  )
829
656
  SELECT
830
657
  m.id,
@@ -847,7 +674,7 @@ var MemoryStorageD1 = class extends storage.MemoryStorage {
847
674
  )
848
675
  ) AS query_${paramIdx}
849
676
  `);
850
- params.push(searchId, id, id, withNextMessages, withPreviousMessages);
677
+ params.push(id, id, id, withNextMessages, withPreviousMessages);
851
678
  paramIdx++;
852
679
  }
853
680
  const finalQuery = unionQueries.join(" UNION ALL ") + " ORDER BY createdAt ASC";
@@ -865,74 +692,8 @@ var MemoryStorageD1 = class extends storage.MemoryStorage {
865
692
  });
866
693
  return processedMessages;
867
694
  }
868
- async getMessages({
869
- threadId,
870
- resourceId,
871
- selectBy,
872
- format
873
- }) {
874
- try {
875
- if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
876
- const fullTableName = this.operations.getTableName(storage.TABLE_MESSAGES);
877
- const limit = storage.resolveMessageLimit({
878
- last: selectBy?.last,
879
- defaultLimit: 40
880
- });
881
- const include = selectBy?.include || [];
882
- const messages = [];
883
- if (include.length) {
884
- const includeResult = await this._getIncludedMessages(threadId, selectBy);
885
- if (Array.isArray(includeResult)) messages.push(...includeResult);
886
- }
887
- const excludeIds = messages.map((m) => m.id);
888
- const query = createSqlBuilder().select(["id", "content", "role", "type", "createdAt", "thread_id AS threadId"]).from(fullTableName).where("thread_id = ?", threadId);
889
- if (excludeIds.length > 0) {
890
- query.andWhere(`id NOT IN (${excludeIds.map(() => "?").join(",")})`, ...excludeIds);
891
- }
892
- query.orderBy("createdAt", "DESC").limit(limit);
893
- const { sql, params } = query.build();
894
- const result = await this.operations.executeQuery({ sql, params });
895
- if (Array.isArray(result)) messages.push(...result);
896
- messages.sort((a, b) => {
897
- const aRecord = a;
898
- const bRecord = b;
899
- const timeA = new Date(aRecord.createdAt).getTime();
900
- const timeB = new Date(bRecord.createdAt).getTime();
901
- return timeA - timeB;
902
- });
903
- const processedMessages = messages.map((message) => {
904
- const processedMsg = {};
905
- for (const [key, value] of Object.entries(message)) {
906
- if (key === `type` && value === `v2`) continue;
907
- processedMsg[key] = deserializeValue(value);
908
- }
909
- return processedMsg;
910
- });
911
- this.logger.debug(`Retrieved ${messages.length} messages for thread ${threadId}`);
912
- const list = new agent.MessageList().add(processedMessages, "memory");
913
- if (format === `v2`) return list.get.all.v2();
914
- return list.get.all.v1();
915
- } catch (error$1) {
916
- const mastraError = new error.MastraError(
917
- {
918
- id: "CLOUDFLARE_D1_STORAGE_GET_MESSAGES_ERROR",
919
- domain: error.ErrorDomain.STORAGE,
920
- category: error.ErrorCategory.THIRD_PARTY,
921
- text: `Failed to retrieve messages for thread ${threadId}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
922
- details: { threadId, resourceId: resourceId ?? "" }
923
- },
924
- error$1
925
- );
926
- this.logger?.error(mastraError.toString());
927
- this.logger?.trackException(mastraError);
928
- throw mastraError;
929
- }
930
- }
931
- async getMessagesById({
932
- messageIds,
933
- format
934
- }) {
935
- if (messageIds.length === 0) return [];
695
+ async listMessagesById({ messageIds }) {
696
+ if (messageIds.length === 0) return { messages: [] };
936
697
  const fullTableName = this.operations.getTableName(storage.TABLE_MESSAGES);
937
698
  const messages = [];
938
699
  try {
@@ -951,12 +712,11 @@ var MemoryStorageD1 = class extends storage.MemoryStorage {
951
712
  });
952
713
  this.logger.debug(`Retrieved ${messages.length} messages`);
953
714
  const list = new agent.MessageList().add(processedMessages, "memory");
954
- if (format === `v1`) return list.get.all.v1();
955
- return list.get.all.v2();
715
+ return { messages: list.get.all.db() };
956
716
  } catch (error$1) {
957
717
  const mastraError = new error.MastraError(
958
718
  {
959
- id: "CLOUDFLARE_D1_STORAGE_GET_MESSAGES_BY_ID_ERROR",
719
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "LIST_MESSAGES_BY_ID", "FAILED"),
960
720
  domain: error.ErrorDomain.STORAGE,
961
721
  category: error.ErrorCategory.THIRD_PARTY,
962
722
  text: `Failed to retrieve messages by ID: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
@@ -969,118 +729,158 @@ var MemoryStorageD1 = class extends storage.MemoryStorage {
969
729
  throw mastraError;
970
730
  }
971
731
  }
972
- async getMessagesPaginated({
973
- threadId,
974
- resourceId,
975
- selectBy,
976
- format
977
- }) {
978
- const { dateRange, page = 0, perPage: perPageInput } = selectBy?.pagination || {};
979
- const { start: fromDate, end: toDate } = dateRange || {};
980
- const perPage = perPageInput !== void 0 ? perPageInput : storage.resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
981
- const fullTableName = this.operations.getTableName(storage.TABLE_MESSAGES);
982
- const messages = [];
732
+ async listMessages(args) {
733
+ const { threadId, resourceId, include, filter, perPage: perPageInput, page = 0, orderBy } = args;
734
+ const threadIds = Array.isArray(threadId) ? threadId : [threadId];
735
+ if (threadIds.length === 0 || threadIds.some((id) => !id.trim())) {
736
+ throw new error.MastraError(
737
+ {
738
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "LIST_MESSAGES", "INVALID_THREAD_ID"),
739
+ domain: error.ErrorDomain.STORAGE,
740
+ category: error.ErrorCategory.THIRD_PARTY,
741
+ details: { threadId: Array.isArray(threadId) ? threadId.join(",") : threadId }
742
+ },
743
+ new Error("threadId must be a non-empty string or array of non-empty strings")
744
+ );
745
+ }
746
+ if (page < 0) {
747
+ throw new error.MastraError(
748
+ {
749
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "LIST_MESSAGES", "INVALID_PAGE"),
750
+ domain: error.ErrorDomain.STORAGE,
751
+ category: error.ErrorCategory.USER,
752
+ details: { page }
753
+ },
754
+ new Error("page must be >= 0")
755
+ );
756
+ }
757
+ const perPage = storage.normalizePerPage(perPageInput, 40);
758
+ const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
983
759
  try {
984
- if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
985
- if (selectBy?.include?.length) {
986
- const includeResult = await this._getIncludedMessages(threadId, selectBy);
987
- if (Array.isArray(includeResult)) messages.push(...includeResult);
760
+ const fullTableName = this.operations.getTableName(storage.TABLE_MESSAGES);
761
+ let query = `
762
+ SELECT id, content, role, type, createdAt, thread_id AS threadId, resourceId
763
+ FROM ${fullTableName}
764
+ WHERE thread_id = ?
765
+ `;
766
+ const queryParams = [threadId];
767
+ if (resourceId) {
768
+ query += ` AND resourceId = ?`;
769
+ queryParams.push(resourceId);
988
770
  }
989
- const countQuery = createSqlBuilder().count().from(fullTableName).where("thread_id = ?", threadId);
990
- if (fromDate) {
991
- countQuery.andWhere("createdAt >= ?", storage.serializeDate(fromDate));
771
+ const dateRange = filter?.dateRange;
772
+ if (dateRange?.start) {
773
+ const startDate = dateRange.start instanceof Date ? storage.serializeDate(dateRange.start) : storage.serializeDate(new Date(dateRange.start));
774
+ query += ` AND createdAt >= ?`;
775
+ queryParams.push(startDate);
992
776
  }
993
- if (toDate) {
994
- countQuery.andWhere("createdAt <= ?", storage.serializeDate(toDate));
777
+ if (dateRange?.end) {
778
+ const endDate = dateRange.end instanceof Date ? storage.serializeDate(dateRange.end) : storage.serializeDate(new Date(dateRange.end));
779
+ query += ` AND createdAt <= ?`;
780
+ queryParams.push(endDate);
995
781
  }
996
- const countResult = await this.operations.executeQuery(countQuery.build());
782
+ const { field, direction } = this.parseOrderBy(orderBy, "ASC");
783
+ query += ` ORDER BY "${field}" ${direction}`;
784
+ if (perPage !== Number.MAX_SAFE_INTEGER) {
785
+ query += ` LIMIT ? OFFSET ?`;
786
+ queryParams.push(perPage, offset);
787
+ }
788
+ const results = await this.operations.executeQuery({ sql: query, params: queryParams });
789
+ const paginatedMessages = (isArrayOfRecords(results) ? results : []).map((message) => {
790
+ const processedMsg = {};
791
+ for (const [key, value] of Object.entries(message)) {
792
+ if (key === `type` && value === `v2`) continue;
793
+ processedMsg[key] = deserializeValue(value);
794
+ }
795
+ return processedMsg;
796
+ });
797
+ const paginatedCount = paginatedMessages.length;
798
+ let countQuery = `SELECT count() as count FROM ${fullTableName} WHERE thread_id = ?`;
799
+ const countParams = [threadId];
800
+ if (resourceId) {
801
+ countQuery += ` AND resourceId = ?`;
802
+ countParams.push(resourceId);
803
+ }
804
+ if (dateRange?.start) {
805
+ const startDate = dateRange.start instanceof Date ? storage.serializeDate(dateRange.start) : storage.serializeDate(new Date(dateRange.start));
806
+ countQuery += ` AND createdAt >= ?`;
807
+ countParams.push(startDate);
808
+ }
809
+ if (dateRange?.end) {
810
+ const endDate = dateRange.end instanceof Date ? storage.serializeDate(dateRange.end) : storage.serializeDate(new Date(dateRange.end));
811
+ countQuery += ` AND createdAt <= ?`;
812
+ countParams.push(endDate);
813
+ }
814
+ const countResult = await this.operations.executeQuery({ sql: countQuery, params: countParams });
997
815
  const total = Number(countResult[0]?.count ?? 0);
998
- if (total === 0 && messages.length === 0) {
816
+ if (total === 0 && paginatedCount === 0 && (!include || include.length === 0)) {
999
817
  return {
1000
818
  messages: [],
1001
819
  total: 0,
1002
820
  page,
1003
- perPage,
821
+ perPage: perPageForResponse,
1004
822
  hasMore: false
1005
823
  };
1006
824
  }
1007
- const excludeIds = messages.map((m) => m.id);
1008
- const excludeCondition = excludeIds.length > 0 ? `AND id NOT IN (${excludeIds.map(() => "?").join(",")})` : "";
1009
- let query;
1010
- let queryParams = [threadId];
1011
- if (fromDate) {
1012
- queryParams.push(storage.serializeDate(fromDate));
1013
- }
1014
- if (toDate) {
1015
- queryParams.push(storage.serializeDate(toDate));
1016
- }
1017
- if (excludeIds.length > 0) {
1018
- queryParams.push(...excludeIds);
1019
- }
1020
- if (selectBy?.last && selectBy.last > 0) {
1021
- query = `
1022
- SELECT id, content, role, type, createdAt, thread_id AS threadId, resourceId
1023
- FROM ${fullTableName}
1024
- WHERE thread_id = ?
1025
- ${fromDate ? "AND createdAt >= ?" : ""}
1026
- ${toDate ? "AND createdAt <= ?" : ""}
1027
- ${excludeCondition}
1028
- ORDER BY createdAt DESC
1029
- LIMIT ?
1030
- `;
1031
- queryParams.push(selectBy.last);
1032
- } else {
1033
- query = `
1034
- SELECT id, content, role, type, createdAt, thread_id AS threadId, resourceId
1035
- FROM ${fullTableName}
1036
- WHERE thread_id = ?
1037
- ${fromDate ? "AND createdAt >= ?" : ""}
1038
- ${toDate ? "AND createdAt <= ?" : ""}
1039
- ${excludeCondition}
1040
- ORDER BY createdAt DESC
1041
- LIMIT ? OFFSET ?
1042
- `;
1043
- queryParams.push(perPage, page * perPage);
825
+ const messageIds = new Set(paginatedMessages.map((m) => m.id));
826
+ let includeMessages = [];
827
+ if (include && include.length > 0) {
828
+ const includeResult = await this._getIncludedMessages(include);
829
+ if (Array.isArray(includeResult)) {
830
+ includeMessages = includeResult;
831
+ for (const includeMsg of includeMessages) {
832
+ if (!messageIds.has(includeMsg.id)) {
833
+ paginatedMessages.push(includeMsg);
834
+ messageIds.add(includeMsg.id);
835
+ }
836
+ }
837
+ }
1044
838
  }
1045
- const results = await this.operations.executeQuery({ sql: query, params: queryParams });
1046
- const processedMessages = results.map((message) => {
1047
- const processedMsg = {};
1048
- for (const [key, value] of Object.entries(message)) {
1049
- if (key === `type` && value === `v2`) continue;
1050
- processedMsg[key] = deserializeValue(value);
839
+ const list = new agent.MessageList().add(paginatedMessages, "memory");
840
+ let finalMessages = list.get.all.db();
841
+ finalMessages = finalMessages.sort((a, b) => {
842
+ const isDateField = field === "createdAt" || field === "updatedAt";
843
+ const aValue = isDateField ? new Date(a[field]).getTime() : a[field];
844
+ const bValue = isDateField ? new Date(b[field]).getTime() : b[field];
845
+ if (aValue === bValue) {
846
+ return a.id.localeCompare(b.id);
1051
847
  }
1052
- return processedMsg;
848
+ if (typeof aValue === "number" && typeof bValue === "number") {
849
+ return direction === "ASC" ? aValue - bValue : bValue - aValue;
850
+ }
851
+ return direction === "ASC" ? String(aValue).localeCompare(String(bValue)) : String(bValue).localeCompare(String(aValue));
1053
852
  });
1054
- if (selectBy?.last) {
1055
- processedMessages.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
1056
- }
1057
- const list = new agent.MessageList().add(processedMessages, "memory");
1058
- messages.push(...format === `v2` ? list.get.all.v2() : list.get.all.v1());
853
+ const returnedThreadMessageIds = new Set(finalMessages.filter((m) => m.threadId === threadId).map((m) => m.id));
854
+ const allThreadMessagesReturned = returnedThreadMessageIds.size >= total;
855
+ const hasMore = perPageInput === false ? false : allThreadMessagesReturned ? false : offset + paginatedCount < total;
1059
856
  return {
1060
- messages,
857
+ messages: finalMessages,
1061
858
  total,
1062
859
  page,
1063
- perPage,
1064
- hasMore: selectBy?.last ? false : page * perPage + messages.length < total
860
+ perPage: perPageForResponse,
861
+ hasMore
1065
862
  };
1066
863
  } catch (error$1) {
1067
864
  const mastraError = new error.MastraError(
1068
865
  {
1069
- id: "CLOUDFLARE_D1_STORAGE_GET_MESSAGES_PAGINATED_ERROR",
866
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "LIST_MESSAGES", "FAILED"),
1070
867
  domain: error.ErrorDomain.STORAGE,
1071
868
  category: error.ErrorCategory.THIRD_PARTY,
1072
- text: `Failed to retrieve messages for thread ${threadId}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
1073
- details: { threadId, resourceId: resourceId ?? "" }
869
+ text: `Failed to list messages for thread ${Array.isArray(threadId) ? threadId.join(",") : threadId}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
870
+ details: {
871
+ threadId: Array.isArray(threadId) ? threadId.join(",") : threadId,
872
+ resourceId: resourceId ?? ""
873
+ }
1074
874
  },
1075
875
  error$1
1076
876
  );
1077
- this.logger?.error(mastraError.toString());
1078
- this.logger?.trackException(mastraError);
877
+ this.logger?.error?.(mastraError.toString());
878
+ this.logger?.trackException?.(mastraError);
1079
879
  return {
1080
880
  messages: [],
1081
881
  total: 0,
1082
882
  page,
1083
- perPage,
883
+ perPage: perPageForResponse,
1084
884
  hasMore: false
1085
885
  };
1086
886
  }
@@ -1176,7 +976,7 @@ var MemoryStorageD1 = class extends storage.MemoryStorage {
1176
976
  } catch (error$1) {
1177
977
  throw new error.MastraError(
1178
978
  {
1179
- id: "CLOUDFLARE_D1_STORAGE_UPDATE_MESSAGES_FAILED",
979
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "UPDATE_MESSAGES", "FAILED"),
1180
980
  domain: error.ErrorDomain.STORAGE,
1181
981
  category: error.ErrorCategory.THIRD_PARTY,
1182
982
  details: { count: messages.length }
@@ -1245,7 +1045,7 @@ var StoreOperationsD1 = class extends storage.StoreOperations {
1245
1045
  } catch (error$1) {
1246
1046
  throw new error.MastraError(
1247
1047
  {
1248
- id: "CLOUDFLARE_D1_STORE_OPERATIONS_WORKERS_BINDING_QUERY_FAILED",
1048
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "WORKERS_BINDING_QUERY", "FAILED"),
1249
1049
  domain: error.ErrorDomain.STORAGE,
1250
1050
  category: error.ErrorCategory.THIRD_PARTY,
1251
1051
  details: { sql }
@@ -1277,7 +1077,7 @@ var StoreOperationsD1 = class extends storage.StoreOperations {
1277
1077
  } catch (error$1) {
1278
1078
  throw new error.MastraError(
1279
1079
  {
1280
- id: "CLOUDFLARE_D1_STORE_OPERATIONS_REST_QUERY_FAILED",
1080
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "REST_QUERY", "FAILED"),
1281
1081
  domain: error.ErrorDomain.STORAGE,
1282
1082
  category: error.ErrorCategory.THIRD_PARTY,
1283
1083
  details: { sql }
@@ -1358,7 +1158,7 @@ var StoreOperationsD1 = class extends storage.StoreOperations {
1358
1158
  } catch (error$1) {
1359
1159
  throw new error.MastraError(
1360
1160
  {
1361
- id: "CLOUDFLARE_D1_STORE_OPERATIONS_CREATE_TABLE_FAILED",
1161
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "CREATE_TABLE", "FAILED"),
1362
1162
  domain: error.ErrorDomain.STORAGE,
1363
1163
  category: error.ErrorCategory.THIRD_PARTY,
1364
1164
  details: { tableName }
@@ -1377,7 +1177,7 @@ var StoreOperationsD1 = class extends storage.StoreOperations {
1377
1177
  } catch (error$1) {
1378
1178
  throw new error.MastraError(
1379
1179
  {
1380
- id: "CLOUDFLARE_D1_STORE_OPERATIONS_CLEAR_TABLE_FAILED",
1180
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "CLEAR_TABLE", "FAILED"),
1381
1181
  domain: error.ErrorDomain.STORAGE,
1382
1182
  category: error.ErrorCategory.THIRD_PARTY,
1383
1183
  details: { tableName }
@@ -1395,7 +1195,7 @@ var StoreOperationsD1 = class extends storage.StoreOperations {
1395
1195
  } catch (error$1) {
1396
1196
  throw new error.MastraError(
1397
1197
  {
1398
- id: "CLOUDFLARE_D1_STORE_OPERATIONS_DROP_TABLE_FAILED",
1198
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "DROP_TABLE", "FAILED"),
1399
1199
  domain: error.ErrorDomain.STORAGE,
1400
1200
  category: error.ErrorCategory.THIRD_PARTY,
1401
1201
  details: { tableName }
@@ -1421,7 +1221,7 @@ var StoreOperationsD1 = class extends storage.StoreOperations {
1421
1221
  } catch (error$1) {
1422
1222
  throw new error.MastraError(
1423
1223
  {
1424
- id: "CLOUDFLARE_D1_STORE_OPERATIONS_ALTER_TABLE_FAILED",
1224
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "ALTER_TABLE", "FAILED"),
1425
1225
  domain: error.ErrorDomain.STORAGE,
1426
1226
  category: error.ErrorCategory.THIRD_PARTY,
1427
1227
  details: { tableName: args.tableName }
@@ -1442,7 +1242,7 @@ var StoreOperationsD1 = class extends storage.StoreOperations {
1442
1242
  } catch (error$1) {
1443
1243
  throw new error.MastraError(
1444
1244
  {
1445
- id: "CLOUDFLARE_D1_STORE_OPERATIONS_INSERT_FAILED",
1245
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "INSERT", "FAILED"),
1446
1246
  domain: error.ErrorDomain.STORAGE,
1447
1247
  category: error.ErrorCategory.THIRD_PARTY,
1448
1248
  details: { tableName }
@@ -1466,7 +1266,7 @@ var StoreOperationsD1 = class extends storage.StoreOperations {
1466
1266
  } catch (error$1) {
1467
1267
  throw new error.MastraError(
1468
1268
  {
1469
- id: "CLOUDFLARE_D1_STORE_OPERATIONS_BATCH_INSERT_FAILED",
1269
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "BATCH_INSERT", "FAILED"),
1470
1270
  domain: error.ErrorDomain.STORAGE,
1471
1271
  category: error.ErrorCategory.THIRD_PARTY,
1472
1272
  details: { tableName }
@@ -1503,7 +1303,7 @@ var StoreOperationsD1 = class extends storage.StoreOperations {
1503
1303
  } catch (error$1) {
1504
1304
  throw new error.MastraError(
1505
1305
  {
1506
- id: "CLOUDFLARE_D1_STORE_OPERATIONS_LOAD_FAILED",
1306
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "LOAD", "FAILED"),
1507
1307
  domain: error.ErrorDomain.STORAGE,
1508
1308
  category: error.ErrorCategory.THIRD_PARTY,
1509
1309
  details: { tableName }
@@ -1561,7 +1361,7 @@ var StoreOperationsD1 = class extends storage.StoreOperations {
1561
1361
  } catch (error$1) {
1562
1362
  throw new error.MastraError(
1563
1363
  {
1564
- id: "CLOUDFLARE_D1_STORAGE_BATCH_UPSERT_ERROR",
1364
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "BATCH_UPSERT", "FAILED"),
1565
1365
  domain: error.ErrorDomain.STORAGE,
1566
1366
  category: error.ErrorCategory.THIRD_PARTY,
1567
1367
  text: `Failed to batch upsert into ${tableName}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
@@ -1573,19 +1373,12 @@ var StoreOperationsD1 = class extends storage.StoreOperations {
1573
1373
  }
1574
1374
  };
1575
1375
  function transformScoreRow(row) {
1576
- const deserialized = { ...row };
1577
- deserialized.input = storage.safelyParseJSON(row.input);
1578
- deserialized.output = storage.safelyParseJSON(row.output);
1579
- deserialized.scorer = storage.safelyParseJSON(row.scorer);
1580
- deserialized.preprocessStepResult = storage.safelyParseJSON(row.preprocessStepResult);
1581
- deserialized.analyzeStepResult = storage.safelyParseJSON(row.analyzeStepResult);
1582
- deserialized.metadata = storage.safelyParseJSON(row.metadata);
1583
- deserialized.additionalContext = storage.safelyParseJSON(row.additionalContext);
1584
- deserialized.runtimeContext = storage.safelyParseJSON(row.runtimeContext);
1585
- deserialized.entity = storage.safelyParseJSON(row.entity);
1586
- deserialized.createdAt = row.createdAtZ || row.createdAt;
1587
- deserialized.updatedAt = row.updatedAtZ || row.updatedAt;
1588
- return deserialized;
1376
+ return storage.transformScoreRow(row, {
1377
+ preferredTimestampFields: {
1378
+ createdAt: "createdAtZ",
1379
+ updatedAt: "updatedAtZ"
1380
+ }
1381
+ });
1589
1382
  }
1590
1383
  var ScoresStorageD1 = class extends storage.ScoresStorage {
1591
1384
  operations;
@@ -1606,7 +1399,7 @@ var ScoresStorageD1 = class extends storage.ScoresStorage {
1606
1399
  } catch (error$1) {
1607
1400
  throw new error.MastraError(
1608
1401
  {
1609
- id: "CLOUDFLARE_D1_STORE_SCORES_GET_SCORE_BY_ID_FAILED",
1402
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "GET_SCORE_BY_ID", "FAILED"),
1610
1403
  domain: error.ErrorDomain.STORAGE,
1611
1404
  category: error.ErrorCategory.THIRD_PARTY
1612
1405
  },
@@ -1615,12 +1408,31 @@ var ScoresStorageD1 = class extends storage.ScoresStorage {
1615
1408
  }
1616
1409
  }
1617
1410
  async saveScore(score) {
1411
+ let parsedScore;
1412
+ try {
1413
+ parsedScore = evals.saveScorePayloadSchema.parse(score);
1414
+ } catch (error$1) {
1415
+ throw new error.MastraError(
1416
+ {
1417
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "SAVE_SCORE", "VALIDATION_FAILED"),
1418
+ domain: error.ErrorDomain.STORAGE,
1419
+ category: error.ErrorCategory.USER,
1420
+ details: {
1421
+ scorer: score.scorer?.id ?? "unknown",
1422
+ entityId: score.entityId ?? "unknown",
1423
+ entityType: score.entityType ?? "unknown",
1424
+ traceId: score.traceId ?? "",
1425
+ spanId: score.spanId ?? ""
1426
+ }
1427
+ },
1428
+ error$1
1429
+ );
1430
+ }
1431
+ const id = crypto.randomUUID();
1618
1432
  try {
1619
- const id = crypto.randomUUID();
1620
1433
  const fullTableName = this.operations.getTableName(storage.TABLE_SCORERS);
1621
- const { input, ...rest } = score;
1622
1434
  const serializedRecord = {};
1623
- for (const [key, value] of Object.entries(rest)) {
1435
+ for (const [key, value] of Object.entries(parsedScore)) {
1624
1436
  if (value !== null && value !== void 0) {
1625
1437
  if (typeof value === "object") {
1626
1438
  serializedRecord[key] = JSON.stringify(value);
@@ -1631,29 +1443,29 @@ var ScoresStorageD1 = class extends storage.ScoresStorage {
1631
1443
  serializedRecord[key] = null;
1632
1444
  }
1633
1445
  }
1446
+ const now = /* @__PURE__ */ new Date();
1634
1447
  serializedRecord.id = id;
1635
- serializedRecord.input = JSON.stringify(input);
1636
- serializedRecord.createdAt = (/* @__PURE__ */ new Date()).toISOString();
1637
- serializedRecord.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1448
+ serializedRecord.createdAt = now.toISOString();
1449
+ serializedRecord.updatedAt = now.toISOString();
1638
1450
  const columns = Object.keys(serializedRecord);
1639
1451
  const values = Object.values(serializedRecord);
1640
1452
  const query = createSqlBuilder().insert(fullTableName, columns, values);
1641
1453
  const { sql, params } = query.build();
1642
1454
  await this.operations.executeQuery({ sql, params });
1643
- const scoreFromDb = await this.getScoreById({ id });
1644
- return { score: scoreFromDb };
1455
+ return { score: { ...parsedScore, id, createdAt: now, updatedAt: now } };
1645
1456
  } catch (error$1) {
1646
1457
  throw new error.MastraError(
1647
1458
  {
1648
- id: "CLOUDFLARE_D1_STORE_SCORES_SAVE_SCORE_FAILED",
1459
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "SAVE_SCORE", "FAILED"),
1649
1460
  domain: error.ErrorDomain.STORAGE,
1650
- category: error.ErrorCategory.THIRD_PARTY
1461
+ category: error.ErrorCategory.THIRD_PARTY,
1462
+ details: { id }
1651
1463
  },
1652
1464
  error$1
1653
1465
  );
1654
1466
  }
1655
1467
  }
1656
- async getScoresByScorerId({
1468
+ async listScoresByScorerId({
1657
1469
  scorerId,
1658
1470
  entityId,
1659
1471
  entityType,
@@ -1661,6 +1473,9 @@ var ScoresStorageD1 = class extends storage.ScoresStorage {
1661
1473
  pagination
1662
1474
  }) {
1663
1475
  try {
1476
+ const { page, perPage: perPageInput } = pagination;
1477
+ const perPage = storage.normalizePerPage(perPageInput, 100);
1478
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
1664
1479
  const fullTableName = this.operations.getTableName(storage.TABLE_SCORERS);
1665
1480
  const countQuery = createSqlBuilder().count().from(fullTableName).where("scorerId = ?", scorerId);
1666
1481
  if (entityId) {
@@ -1678,13 +1493,15 @@ var ScoresStorageD1 = class extends storage.ScoresStorage {
1678
1493
  return {
1679
1494
  pagination: {
1680
1495
  total: 0,
1681
- page: pagination.page,
1682
- perPage: pagination.perPage,
1496
+ page,
1497
+ perPage: perPageForResponse,
1683
1498
  hasMore: false
1684
1499
  },
1685
1500
  scores: []
1686
1501
  };
1687
1502
  }
1503
+ const end = perPageInput === false ? total : start + perPage;
1504
+ const limitValue = perPageInput === false ? total : perPage;
1688
1505
  const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("scorerId = ?", scorerId);
1689
1506
  if (entityId) {
1690
1507
  selectQuery.andWhere("entityId = ?", entityId);
@@ -1695,23 +1512,23 @@ var ScoresStorageD1 = class extends storage.ScoresStorage {
1695
1512
  if (source) {
1696
1513
  selectQuery.andWhere("source = ?", source);
1697
1514
  }
1698
- selectQuery.limit(pagination.perPage).offset(pagination.page * pagination.perPage);
1515
+ selectQuery.limit(limitValue).offset(start);
1699
1516
  const { sql, params } = selectQuery.build();
1700
1517
  const results = await this.operations.executeQuery({ sql, params });
1701
1518
  const scores = Array.isArray(results) ? results.map(transformScoreRow) : [];
1702
1519
  return {
1703
1520
  pagination: {
1704
1521
  total,
1705
- page: pagination.page,
1706
- perPage: pagination.perPage,
1707
- hasMore: total > (pagination.page + 1) * pagination.perPage
1522
+ page,
1523
+ perPage: perPageForResponse,
1524
+ hasMore: end < total
1708
1525
  },
1709
1526
  scores
1710
1527
  };
1711
1528
  } catch (error$1) {
1712
1529
  throw new error.MastraError(
1713
1530
  {
1714
- id: "CLOUDFLARE_D1_STORE_SCORES_GET_SCORES_BY_SCORER_ID_FAILED",
1531
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "GET_SCORES_BY_SCORER_ID", "FAILED"),
1715
1532
  domain: error.ErrorDomain.STORAGE,
1716
1533
  category: error.ErrorCategory.THIRD_PARTY
1717
1534
  },
@@ -1719,11 +1536,14 @@ var ScoresStorageD1 = class extends storage.ScoresStorage {
1719
1536
  );
1720
1537
  }
1721
1538
  }
1722
- async getScoresByRunId({
1539
+ async listScoresByRunId({
1723
1540
  runId,
1724
1541
  pagination
1725
1542
  }) {
1726
1543
  try {
1544
+ const { page, perPage: perPageInput } = pagination;
1545
+ const perPage = storage.normalizePerPage(perPageInput, 100);
1546
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
1727
1547
  const fullTableName = this.operations.getTableName(storage.TABLE_SCORERS);
1728
1548
  const countQuery = createSqlBuilder().count().from(fullTableName).where("runId = ?", runId);
1729
1549
  const countResult = await this.operations.executeQuery(countQuery.build());
@@ -1732,30 +1552,32 @@ var ScoresStorageD1 = class extends storage.ScoresStorage {
1732
1552
  return {
1733
1553
  pagination: {
1734
1554
  total: 0,
1735
- page: pagination.page,
1736
- perPage: pagination.perPage,
1555
+ page,
1556
+ perPage: perPageForResponse,
1737
1557
  hasMore: false
1738
1558
  },
1739
1559
  scores: []
1740
1560
  };
1741
1561
  }
1742
- const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("runId = ?", runId).limit(pagination.perPage).offset(pagination.page * pagination.perPage);
1562
+ const end = perPageInput === false ? total : start + perPage;
1563
+ const limitValue = perPageInput === false ? total : perPage;
1564
+ const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("runId = ?", runId).limit(limitValue).offset(start);
1743
1565
  const { sql, params } = selectQuery.build();
1744
1566
  const results = await this.operations.executeQuery({ sql, params });
1745
1567
  const scores = Array.isArray(results) ? results.map(transformScoreRow) : [];
1746
1568
  return {
1747
1569
  pagination: {
1748
1570
  total,
1749
- page: pagination.page,
1750
- perPage: pagination.perPage,
1751
- hasMore: total > (pagination.page + 1) * pagination.perPage
1571
+ page,
1572
+ perPage: perPageForResponse,
1573
+ hasMore: end < total
1752
1574
  },
1753
1575
  scores
1754
1576
  };
1755
1577
  } catch (error$1) {
1756
1578
  throw new error.MastraError(
1757
1579
  {
1758
- id: "CLOUDFLARE_D1_STORE_SCORES_GET_SCORES_BY_RUN_ID_FAILED",
1580
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "GET_SCORES_BY_RUN_ID", "FAILED"),
1759
1581
  domain: error.ErrorDomain.STORAGE,
1760
1582
  category: error.ErrorCategory.THIRD_PARTY
1761
1583
  },
@@ -1763,12 +1585,15 @@ var ScoresStorageD1 = class extends storage.ScoresStorage {
1763
1585
  );
1764
1586
  }
1765
1587
  }
1766
- async getScoresByEntityId({
1588
+ async listScoresByEntityId({
1767
1589
  entityId,
1768
1590
  entityType,
1769
1591
  pagination
1770
1592
  }) {
1771
1593
  try {
1594
+ const { page, perPage: perPageInput } = pagination;
1595
+ const perPage = storage.normalizePerPage(perPageInput, 100);
1596
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
1772
1597
  const fullTableName = this.operations.getTableName(storage.TABLE_SCORERS);
1773
1598
  const countQuery = createSqlBuilder().count().from(fullTableName).where("entityId = ?", entityId).andWhere("entityType = ?", entityType);
1774
1599
  const countResult = await this.operations.executeQuery(countQuery.build());
@@ -1777,30 +1602,32 @@ var ScoresStorageD1 = class extends storage.ScoresStorage {
1777
1602
  return {
1778
1603
  pagination: {
1779
1604
  total: 0,
1780
- page: pagination.page,
1781
- perPage: pagination.perPage,
1605
+ page,
1606
+ perPage: perPageForResponse,
1782
1607
  hasMore: false
1783
1608
  },
1784
1609
  scores: []
1785
1610
  };
1786
1611
  }
1787
- const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("entityId = ?", entityId).andWhere("entityType = ?", entityType).limit(pagination.perPage).offset(pagination.page * pagination.perPage);
1612
+ const end = perPageInput === false ? total : start + perPage;
1613
+ const limitValue = perPageInput === false ? total : perPage;
1614
+ const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("entityId = ?", entityId).andWhere("entityType = ?", entityType).limit(limitValue).offset(start);
1788
1615
  const { sql, params } = selectQuery.build();
1789
1616
  const results = await this.operations.executeQuery({ sql, params });
1790
1617
  const scores = Array.isArray(results) ? results.map(transformScoreRow) : [];
1791
1618
  return {
1792
1619
  pagination: {
1793
1620
  total,
1794
- page: pagination.page,
1795
- perPage: pagination.perPage,
1796
- hasMore: total > (pagination.page + 1) * pagination.perPage
1621
+ page,
1622
+ perPage: perPageForResponse,
1623
+ hasMore: end < total
1797
1624
  },
1798
1625
  scores
1799
1626
  };
1800
1627
  } catch (error$1) {
1801
1628
  throw new error.MastraError(
1802
1629
  {
1803
- id: "CLOUDFLARE_D1_STORE_SCORES_GET_SCORES_BY_ENTITY_ID_FAILED",
1630
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "GET_SCORES_BY_ENTITY_ID", "FAILED"),
1804
1631
  domain: error.ErrorDomain.STORAGE,
1805
1632
  category: error.ErrorCategory.THIRD_PARTY
1806
1633
  },
@@ -1808,128 +1635,56 @@ var ScoresStorageD1 = class extends storage.ScoresStorage {
1808
1635
  );
1809
1636
  }
1810
1637
  }
1811
- };
1812
- function isArrayOfRecords2(value) {
1813
- return value && Array.isArray(value) && value.length > 0;
1814
- }
1815
- var TracesStorageD1 = class extends storage.TracesStorage {
1816
- operations;
1817
- constructor({ operations }) {
1818
- super();
1819
- this.operations = operations;
1820
- }
1821
- async getTraces(args) {
1822
- const paginatedArgs = {
1823
- name: args.name,
1824
- scope: args.scope,
1825
- page: args.page,
1826
- perPage: args.perPage,
1827
- attributes: args.attributes,
1828
- filters: args.filters,
1829
- dateRange: args.fromDate || args.toDate ? {
1830
- start: args.fromDate,
1831
- end: args.toDate
1832
- } : void 0
1833
- };
1834
- try {
1835
- const result = await this.getTracesPaginated(paginatedArgs);
1836
- return result.traces;
1837
- } catch (error$1) {
1838
- throw new error.MastraError(
1839
- {
1840
- id: "CLOUDFLARE_D1_STORAGE_GET_TRACES_ERROR",
1841
- domain: error.ErrorDomain.STORAGE,
1842
- category: error.ErrorCategory.THIRD_PARTY,
1843
- text: `Failed to retrieve traces: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
1844
- details: {
1845
- name: args.name ?? "",
1846
- scope: args.scope ?? ""
1847
- }
1848
- },
1849
- error$1
1850
- );
1851
- }
1852
- }
1853
- async getTracesPaginated(args) {
1854
- const { name, scope, page = 0, perPage = 100, attributes, dateRange } = args;
1855
- const fromDate = dateRange?.start;
1856
- const toDate = dateRange?.end;
1857
- const fullTableName = this.operations.getTableName(storage.TABLE_TRACES);
1638
+ async listScoresBySpan({
1639
+ traceId,
1640
+ spanId,
1641
+ pagination
1642
+ }) {
1858
1643
  try {
1859
- const dataQuery = createSqlBuilder().select("*").from(fullTableName).where("1=1");
1860
- const countQuery = createSqlBuilder().count().from(fullTableName).where("1=1");
1861
- if (name) {
1862
- dataQuery.andWhere("name LIKE ?", `%${name}%`);
1863
- countQuery.andWhere("name LIKE ?", `%${name}%`);
1864
- }
1865
- if (scope) {
1866
- dataQuery.andWhere("scope = ?", scope);
1867
- countQuery.andWhere("scope = ?", scope);
1868
- }
1869
- if (attributes && Object.keys(attributes).length > 0) {
1870
- for (const [key, value] of Object.entries(attributes)) {
1871
- dataQuery.jsonLike("attributes", key, value);
1872
- countQuery.jsonLike("attributes", key, value);
1873
- }
1874
- }
1875
- if (fromDate) {
1876
- const fromDateStr = fromDate instanceof Date ? fromDate.toISOString() : fromDate;
1877
- dataQuery.andWhere("createdAt >= ?", fromDateStr);
1878
- countQuery.andWhere("createdAt >= ?", fromDateStr);
1879
- }
1880
- if (toDate) {
1881
- const toDateStr = toDate instanceof Date ? toDate.toISOString() : toDate;
1882
- dataQuery.andWhere("createdAt <= ?", toDateStr);
1883
- countQuery.andWhere("createdAt <= ?", toDateStr);
1884
- }
1885
- const allDataResult = await this.operations.executeQuery(
1886
- createSqlBuilder().select("*").from(fullTableName).where("1=1").build()
1887
- );
1888
- console.log("allDataResult", allDataResult);
1644
+ const { page, perPage: perPageInput } = pagination;
1645
+ const perPage = storage.normalizePerPage(perPageInput, 100);
1646
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
1647
+ const fullTableName = this.operations.getTableName(storage.TABLE_SCORERS);
1648
+ const countQuery = createSqlBuilder().count().from(fullTableName).where("traceId = ?", traceId).andWhere("spanId = ?", spanId);
1889
1649
  const countResult = await this.operations.executeQuery(countQuery.build());
1890
- const total = Number(countResult?.[0]?.count ?? 0);
1891
- dataQuery.orderBy("startTime", "DESC").limit(perPage).offset(page * perPage);
1892
- const results = await this.operations.executeQuery(dataQuery.build());
1893
- const traces = isArrayOfRecords2(results) ? results.map(
1894
- (trace) => ({
1895
- ...trace,
1896
- attributes: deserializeValue(trace.attributes, "jsonb"),
1897
- status: deserializeValue(trace.status, "jsonb"),
1898
- events: deserializeValue(trace.events, "jsonb"),
1899
- links: deserializeValue(trace.links, "jsonb"),
1900
- other: deserializeValue(trace.other, "jsonb")
1901
- })
1902
- ) : [];
1650
+ const total = Array.isArray(countResult) ? Number(countResult?.[0]?.count ?? 0) : Number(countResult?.count ?? 0);
1651
+ if (total === 0) {
1652
+ return {
1653
+ pagination: {
1654
+ total: 0,
1655
+ page,
1656
+ perPage: perPageForResponse,
1657
+ hasMore: false
1658
+ },
1659
+ scores: []
1660
+ };
1661
+ }
1662
+ const end = perPageInput === false ? total : start + perPage;
1663
+ const limitValue = perPageInput === false ? total : perPage;
1664
+ const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("traceId = ?", traceId).andWhere("spanId = ?", spanId).orderBy("createdAt", "DESC").limit(limitValue).offset(start);
1665
+ const { sql, params } = selectQuery.build();
1666
+ const results = await this.operations.executeQuery({ sql, params });
1667
+ const scores = Array.isArray(results) ? results.map(transformScoreRow) : [];
1903
1668
  return {
1904
- traces,
1905
- total,
1906
- page,
1907
- perPage,
1908
- hasMore: page * perPage + traces.length < total
1669
+ pagination: {
1670
+ total,
1671
+ page,
1672
+ perPage: perPageForResponse,
1673
+ hasMore: end < total
1674
+ },
1675
+ scores
1909
1676
  };
1910
1677
  } catch (error$1) {
1911
- const mastraError = new error.MastraError(
1678
+ throw new error.MastraError(
1912
1679
  {
1913
- id: "CLOUDFLARE_D1_STORAGE_GET_TRACES_PAGINATED_ERROR",
1680
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "GET_SCORES_BY_SPAN", "FAILED"),
1914
1681
  domain: error.ErrorDomain.STORAGE,
1915
- category: error.ErrorCategory.THIRD_PARTY,
1916
- text: `Failed to retrieve traces: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
1917
- details: { name: name ?? "", scope: scope ?? "" }
1682
+ category: error.ErrorCategory.THIRD_PARTY
1918
1683
  },
1919
1684
  error$1
1920
1685
  );
1921
- this.logger?.error(mastraError.toString());
1922
- this.logger?.trackException(mastraError);
1923
- return { traces: [], total: 0, page, perPage, hasMore: false };
1924
1686
  }
1925
1687
  }
1926
- async batchTraceInsert({ records }) {
1927
- this.logger.debug("Batch inserting traces", { count: records.length });
1928
- await this.operations.batchInsert({
1929
- tableName: storage.TABLE_TRACES,
1930
- records
1931
- });
1932
- }
1933
1688
  };
1934
1689
  var WorkflowsStorageD1 = class extends storage.WorkflowsStorage {
1935
1690
  operations;
@@ -1942,7 +1697,7 @@ var WorkflowsStorageD1 = class extends storage.WorkflowsStorage {
1942
1697
  // runId,
1943
1698
  // stepId,
1944
1699
  // result,
1945
- // runtimeContext,
1700
+ // requestContext,
1946
1701
  }) {
1947
1702
  throw new Error("Method not implemented.");
1948
1703
  }
@@ -1993,7 +1748,7 @@ var WorkflowsStorageD1 = class extends storage.WorkflowsStorage {
1993
1748
  } catch (error$1) {
1994
1749
  throw new error.MastraError(
1995
1750
  {
1996
- id: "CLOUDFLARE_D1_STORAGE_PERSIST_WORKFLOW_SNAPSHOT_ERROR",
1751
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "PERSIST_WORKFLOW_SNAPSHOT", "FAILED"),
1997
1752
  domain: error.ErrorDomain.STORAGE,
1998
1753
  category: error.ErrorCategory.THIRD_PARTY,
1999
1754
  text: `Failed to persist workflow snapshot: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
@@ -2018,7 +1773,7 @@ var WorkflowsStorageD1 = class extends storage.WorkflowsStorage {
2018
1773
  } catch (error$1) {
2019
1774
  throw new error.MastraError(
2020
1775
  {
2021
- id: "CLOUDFLARE_D1_STORAGE_LOAD_WORKFLOW_SNAPSHOT_ERROR",
1776
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "LOAD_WORKFLOW_SNAPSHOT", "FAILED"),
2022
1777
  domain: error.ErrorDomain.STORAGE,
2023
1778
  category: error.ErrorCategory.THIRD_PARTY,
2024
1779
  text: `Failed to load workflow snapshot: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
@@ -2046,19 +1801,24 @@ var WorkflowsStorageD1 = class extends storage.WorkflowsStorage {
2046
1801
  resourceId: row.resourceId
2047
1802
  };
2048
1803
  }
2049
- async getWorkflowRuns({
1804
+ async listWorkflowRuns({
2050
1805
  workflowName,
2051
1806
  fromDate,
2052
1807
  toDate,
2053
- limit,
2054
- offset,
2055
- resourceId
1808
+ page,
1809
+ perPage,
1810
+ resourceId,
1811
+ status
2056
1812
  } = {}) {
2057
1813
  const fullTableName = this.operations.getTableName(storage.TABLE_WORKFLOW_SNAPSHOT);
2058
1814
  try {
2059
1815
  const builder = createSqlBuilder().select().from(fullTableName);
2060
1816
  const countBuilder = createSqlBuilder().count().from(fullTableName);
2061
1817
  if (workflowName) builder.whereAnd("workflow_name = ?", workflowName);
1818
+ if (status) {
1819
+ builder.whereAnd("json_extract(snapshot, '$.status') = ?", status);
1820
+ countBuilder.whereAnd("json_extract(snapshot, '$.status') = ?", status);
1821
+ }
2062
1822
  if (resourceId) {
2063
1823
  const hasResourceId = await this.operations.hasColumn(fullTableName, "resourceId");
2064
1824
  if (hasResourceId) {
@@ -2077,11 +1837,14 @@ var WorkflowsStorageD1 = class extends storage.WorkflowsStorage {
2077
1837
  countBuilder.whereAnd("createdAt <= ?", toDate instanceof Date ? toDate.toISOString() : toDate);
2078
1838
  }
2079
1839
  builder.orderBy("createdAt", "DESC");
2080
- if (typeof limit === "number") builder.limit(limit);
2081
- if (typeof offset === "number") builder.offset(offset);
1840
+ if (typeof perPage === "number" && typeof page === "number") {
1841
+ const offset = page * perPage;
1842
+ builder.limit(perPage);
1843
+ builder.offset(offset);
1844
+ }
2082
1845
  const { sql, params } = builder.build();
2083
1846
  let total = 0;
2084
- if (limit !== void 0 && offset !== void 0) {
1847
+ if (perPage !== void 0 && page !== void 0) {
2085
1848
  const { sql: countSql, params: countParams } = countBuilder.build();
2086
1849
  const countResult = await this.operations.executeQuery({
2087
1850
  sql: countSql,
@@ -2096,7 +1859,7 @@ var WorkflowsStorageD1 = class extends storage.WorkflowsStorage {
2096
1859
  } catch (error$1) {
2097
1860
  throw new error.MastraError(
2098
1861
  {
2099
- id: "CLOUDFLARE_D1_STORAGE_GET_WORKFLOW_RUNS_ERROR",
1862
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "LIST_WORKFLOW_RUNS", "FAILED"),
2100
1863
  domain: error.ErrorDomain.STORAGE,
2101
1864
  category: error.ErrorCategory.THIRD_PARTY,
2102
1865
  text: `Failed to retrieve workflow runs: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
@@ -2133,7 +1896,7 @@ var WorkflowsStorageD1 = class extends storage.WorkflowsStorage {
2133
1896
  } catch (error$1) {
2134
1897
  throw new error.MastraError(
2135
1898
  {
2136
- id: "CLOUDFLARE_D1_STORAGE_GET_WORKFLOW_RUN_BY_ID_ERROR",
1899
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "GET_WORKFLOW_RUN_BY_ID", "FAILED"),
2137
1900
  domain: error.ErrorDomain.STORAGE,
2138
1901
  category: error.ErrorCategory.THIRD_PARTY,
2139
1902
  text: `Failed to retrieve workflow run by ID: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
@@ -2143,6 +1906,25 @@ var WorkflowsStorageD1 = class extends storage.WorkflowsStorage {
2143
1906
  );
2144
1907
  }
2145
1908
  }
1909
+ async deleteWorkflowRunById({ runId, workflowName }) {
1910
+ const fullTableName = this.operations.getTableName(storage.TABLE_WORKFLOW_SNAPSHOT);
1911
+ try {
1912
+ const sql = `DELETE FROM ${fullTableName} WHERE workflow_name = ? AND run_id = ?`;
1913
+ const params = [workflowName, runId];
1914
+ await this.operations.executeQuery({ sql, params });
1915
+ } catch (error$1) {
1916
+ throw new error.MastraError(
1917
+ {
1918
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "DELETE_WORKFLOW_RUN_BY_ID", "FAILED"),
1919
+ domain: error.ErrorDomain.STORAGE,
1920
+ category: error.ErrorCategory.THIRD_PARTY,
1921
+ text: `Failed to delete workflow run by ID: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
1922
+ details: { runId, workflowName }
1923
+ },
1924
+ error$1
1925
+ );
1926
+ }
1927
+ }
2146
1928
  };
2147
1929
 
2148
1930
  // src/storage/index.ts
@@ -2158,7 +1940,7 @@ var D1Store = class extends storage.MastraStorage {
2158
1940
  */
2159
1941
  constructor(config) {
2160
1942
  try {
2161
- super({ name: "D1" });
1943
+ super({ id: config.id, name: "D1", disableInit: config.disableInit });
2162
1944
  if (config.tablePrefix && !/^[a-zA-Z0-9_]*$/.test(config.tablePrefix)) {
2163
1945
  throw new Error("Invalid tablePrefix: only letters, numbers, and underscores are allowed.");
2164
1946
  }
@@ -2196,7 +1978,7 @@ var D1Store = class extends storage.MastraStorage {
2196
1978
  } catch (error$1) {
2197
1979
  throw new error.MastraError(
2198
1980
  {
2199
- id: "CLOUDFLARE_D1_STORAGE_INITIALIZATION_ERROR",
1981
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "INITIALIZATION", "FAILED"),
2200
1982
  domain: error.ErrorDomain.STORAGE,
2201
1983
  category: error.ErrorCategory.SYSTEM,
2202
1984
  text: "Error initializing D1Store"
@@ -2212,12 +1994,6 @@ var D1Store = class extends storage.MastraStorage {
2212
1994
  const scores = new ScoresStorageD1({
2213
1995
  operations
2214
1996
  });
2215
- const legacyEvals = new LegacyEvalsStorageD1({
2216
- operations
2217
- });
2218
- const traces = new TracesStorageD1({
2219
- operations
2220
- });
2221
1997
  const workflows = new WorkflowsStorageD1({
2222
1998
  operations
2223
1999
  });
@@ -2227,8 +2003,6 @@ var D1Store = class extends storage.MastraStorage {
2227
2003
  this.stores = {
2228
2004
  operations,
2229
2005
  scores,
2230
- legacyEvals,
2231
- traces,
2232
2006
  workflows,
2233
2007
  memory
2234
2008
  };
@@ -2239,7 +2013,8 @@ var D1Store = class extends storage.MastraStorage {
2239
2013
  resourceWorkingMemory: true,
2240
2014
  hasColumn: true,
2241
2015
  createTable: true,
2242
- deleteMessages: false
2016
+ deleteMessages: false,
2017
+ listScoresBySpan: true
2243
2018
  };
2244
2019
  }
2245
2020
  async createTable({
@@ -2279,15 +2054,6 @@ var D1Store = class extends storage.MastraStorage {
2279
2054
  async getThreadById({ threadId }) {
2280
2055
  return this.stores.memory.getThreadById({ threadId });
2281
2056
  }
2282
- /**
2283
- * @deprecated use getThreadsByResourceIdPaginated instead
2284
- */
2285
- async getThreadsByResourceId({ resourceId }) {
2286
- return this.stores.memory.getThreadsByResourceId({ resourceId });
2287
- }
2288
- async getThreadsByResourceIdPaginated(args) {
2289
- return this.stores.memory.getThreadsByResourceIdPaginated(args);
2290
- }
2291
2057
  async saveThread({ thread }) {
2292
2058
  return this.stores.memory.saveThread({ thread });
2293
2059
  }
@@ -2304,34 +2070,14 @@ var D1Store = class extends storage.MastraStorage {
2304
2070
  async saveMessages(args) {
2305
2071
  return this.stores.memory.saveMessages(args);
2306
2072
  }
2307
- async getMessages({
2308
- threadId,
2309
- selectBy,
2310
- format
2311
- }) {
2312
- return this.stores.memory.getMessages({ threadId, selectBy, format });
2313
- }
2314
- async getMessagesById({
2315
- messageIds,
2316
- format
2317
- }) {
2318
- return this.stores.memory.getMessagesById({ messageIds, format });
2319
- }
2320
- async getMessagesPaginated({
2321
- threadId,
2322
- selectBy,
2323
- format
2324
- }) {
2325
- return this.stores.memory.getMessagesPaginated({ threadId, selectBy, format });
2326
- }
2327
2073
  async updateWorkflowResults({
2328
2074
  workflowName,
2329
2075
  runId,
2330
2076
  stepId,
2331
2077
  result,
2332
- runtimeContext
2078
+ requestContext
2333
2079
  }) {
2334
- return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, runtimeContext });
2080
+ return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, requestContext });
2335
2081
  }
2336
2082
  async updateWorkflowState({
2337
2083
  workflowName,
@@ -2351,15 +2097,8 @@ var D1Store = class extends storage.MastraStorage {
2351
2097
  async loadWorkflowSnapshot(params) {
2352
2098
  return this.stores.workflows.loadWorkflowSnapshot(params);
2353
2099
  }
2354
- async getWorkflowRuns({
2355
- workflowName,
2356
- fromDate,
2357
- toDate,
2358
- limit,
2359
- offset,
2360
- resourceId
2361
- } = {}) {
2362
- return this.stores.workflows.getWorkflowRuns({ workflowName, fromDate, toDate, limit, offset, resourceId });
2100
+ async listWorkflowRuns(args = {}) {
2101
+ return this.stores.workflows.listWorkflowRuns(args);
2363
2102
  }
2364
2103
  async getWorkflowRunById({
2365
2104
  runId,
@@ -2367,6 +2106,9 @@ var D1Store = class extends storage.MastraStorage {
2367
2106
  }) {
2368
2107
  return this.stores.workflows.getWorkflowRunById({ runId, workflowName });
2369
2108
  }
2109
+ async deleteWorkflowRunById({ runId, workflowName }) {
2110
+ return this.stores.workflows.deleteWorkflowRunById({ runId, workflowName });
2111
+ }
2370
2112
  /**
2371
2113
  * Insert multiple records in a batch operation
2372
2114
  * @param tableName The table to insert into
@@ -2375,24 +2117,6 @@ var D1Store = class extends storage.MastraStorage {
2375
2117
  async batchInsert({ tableName, records }) {
2376
2118
  return this.stores.operations.batchInsert({ tableName, records });
2377
2119
  }
2378
- /**
2379
- * @deprecated use getTracesPaginated instead
2380
- */
2381
- async getTraces(args) {
2382
- return this.stores.traces.getTraces(args);
2383
- }
2384
- async getTracesPaginated(args) {
2385
- return this.stores.traces.getTracesPaginated(args);
2386
- }
2387
- /**
2388
- * @deprecated use getEvals instead
2389
- */
2390
- async getEvalsByAgentName(agentName, type) {
2391
- return this.stores.legacyEvals.getEvalsByAgentName(agentName, type);
2392
- }
2393
- async getEvals(options) {
2394
- return this.stores.legacyEvals.getEvals(options);
2395
- }
2396
2120
  async updateMessages(_args) {
2397
2121
  return this.stores.memory.updateMessages(_args);
2398
2122
  }
@@ -2412,34 +2136,41 @@ var D1Store = class extends storage.MastraStorage {
2412
2136
  async getScoreById({ id: _id }) {
2413
2137
  return this.stores.scores.getScoreById({ id: _id });
2414
2138
  }
2415
- async saveScore(_score) {
2416
- return this.stores.scores.saveScore(_score);
2139
+ async saveScore(score) {
2140
+ return this.stores.scores.saveScore(score);
2417
2141
  }
2418
- async getScoresByRunId({
2142
+ async listScoresByRunId({
2419
2143
  runId: _runId,
2420
2144
  pagination: _pagination
2421
2145
  }) {
2422
- return this.stores.scores.getScoresByRunId({ runId: _runId, pagination: _pagination });
2146
+ return this.stores.scores.listScoresByRunId({ runId: _runId, pagination: _pagination });
2423
2147
  }
2424
- async getScoresByEntityId({
2148
+ async listScoresByEntityId({
2425
2149
  entityId: _entityId,
2426
2150
  entityType: _entityType,
2427
2151
  pagination: _pagination
2428
2152
  }) {
2429
- return this.stores.scores.getScoresByEntityId({
2153
+ return this.stores.scores.listScoresByEntityId({
2430
2154
  entityId: _entityId,
2431
2155
  entityType: _entityType,
2432
2156
  pagination: _pagination
2433
2157
  });
2434
2158
  }
2435
- async getScoresByScorerId({
2159
+ async listScoresByScorerId({
2436
2160
  scorerId,
2437
2161
  pagination,
2438
2162
  entityId,
2439
2163
  entityType,
2440
2164
  source
2441
2165
  }) {
2442
- return this.stores.scores.getScoresByScorerId({ scorerId, pagination, entityId, entityType, source });
2166
+ return this.stores.scores.listScoresByScorerId({ scorerId, pagination, entityId, entityType, source });
2167
+ }
2168
+ async listScoresBySpan({
2169
+ traceId,
2170
+ spanId,
2171
+ pagination
2172
+ }) {
2173
+ return this.stores.scores.listScoresBySpan({ traceId, spanId, pagination });
2443
2174
  }
2444
2175
  /**
2445
2176
  * Close the database connection