@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.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)}`,
@@ -540,7 +383,6 @@ var MemoryStorageD1 = class extends storage.MemoryStorage {
540
383
  keys: { id: threadId }
541
384
  });
542
385
  if (!thread) return null;
543
- console.log("thread", thread);
544
386
  try {
545
387
  return {
546
388
  ...thread,
@@ -551,7 +393,7 @@ var MemoryStorageD1 = class extends storage.MemoryStorage {
551
393
  } catch (error$1) {
552
394
  const mastraError = new error.MastraError(
553
395
  {
554
- id: "CLOUDFLARE_D1_STORAGE_GET_THREAD_BY_ID_ERROR",
396
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "GET_THREAD_BY_ID", "FAILED"),
555
397
  domain: error.ErrorDomain.STORAGE,
556
398
  category: error.ErrorCategory.THIRD_PARTY,
557
399
  text: `Error processing thread ${threadId}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
@@ -564,39 +406,22 @@ var MemoryStorageD1 = class extends storage.MemoryStorage {
564
406
  return null;
565
407
  }
566
408
  }
567
- /**
568
- * @deprecated use getThreadsByResourceIdPaginated instead
569
- */
570
- async getThreadsByResourceId({ resourceId }) {
571
- const fullTableName = this.operations.getTableName(storage.TABLE_THREADS);
572
- try {
573
- const query = createSqlBuilder().select("*").from(fullTableName).where("resourceId = ?", resourceId);
574
- const { sql, params } = query.build();
575
- const results = await this.operations.executeQuery({ sql, params });
576
- return (isArrayOfRecords(results) ? results : []).map((thread) => ({
577
- ...thread,
578
- createdAt: storage.ensureDate(thread.createdAt),
579
- updatedAt: storage.ensureDate(thread.updatedAt),
580
- metadata: typeof thread.metadata === "string" ? JSON.parse(thread.metadata || "{}") : thread.metadata || {}
581
- }));
582
- } catch (error$1) {
583
- 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(
584
414
  {
585
- id: "CLOUDFLARE_D1_STORAGE_GET_THREADS_BY_RESOURCE_ID_ERROR",
415
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "LIST_THREADS_BY_RESOURCE_ID", "INVALID_PAGE"),
586
416
  domain: error.ErrorDomain.STORAGE,
587
- category: error.ErrorCategory.THIRD_PARTY,
588
- text: `Error getting threads by resourceId ${resourceId}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
589
- details: { resourceId }
417
+ category: error.ErrorCategory.USER,
418
+ details: { page }
590
419
  },
591
- error$1
420
+ new Error("page must be >= 0")
592
421
  );
593
- this.logger?.error(mastraError.toString());
594
- this.logger?.trackException(mastraError);
595
- return [];
596
422
  }
597
- }
598
- async getThreadsByResourceIdPaginated(args) {
599
- const { resourceId, page, perPage } = args;
423
+ const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
424
+ const { field, direction } = this.parseOrderBy(orderBy);
600
425
  const fullTableName = this.operations.getTableName(storage.TABLE_THREADS);
601
426
  const mapRowToStorageThreadType = (row) => ({
602
427
  ...row,
@@ -608,20 +433,21 @@ var MemoryStorageD1 = class extends storage.MemoryStorage {
608
433
  const countQuery = createSqlBuilder().count().from(fullTableName).where("resourceId = ?", resourceId);
609
434
  const countResult = await this.operations.executeQuery(countQuery.build());
610
435
  const total = Number(countResult?.[0]?.count ?? 0);
611
- 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);
612
438
  const results = await this.operations.executeQuery(selectQuery.build());
613
439
  const threads = results.map(mapRowToStorageThreadType);
614
440
  return {
615
441
  threads,
616
442
  total,
617
443
  page,
618
- perPage,
619
- hasMore: page * perPage + threads.length < total
444
+ perPage: perPageForResponse,
445
+ hasMore: perPageInput === false ? false : offset + perPage < total
620
446
  };
621
447
  } catch (error$1) {
622
448
  const mastraError = new error.MastraError(
623
449
  {
624
- id: "CLOUDFLARE_D1_STORAGE_GET_THREADS_BY_RESOURCE_ID_PAGINATED_ERROR",
450
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "LIST_THREADS_BY_RESOURCE_ID", "FAILED"),
625
451
  domain: error.ErrorDomain.STORAGE,
626
452
  category: error.ErrorCategory.THIRD_PARTY,
627
453
  text: `Error getting threads by resourceId ${resourceId}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
@@ -635,7 +461,7 @@ var MemoryStorageD1 = class extends storage.MemoryStorage {
635
461
  threads: [],
636
462
  total: 0,
637
463
  page,
638
- perPage,
464
+ perPage: perPageForResponse,
639
465
  hasMore: false
640
466
  };
641
467
  }
@@ -668,7 +494,7 @@ var MemoryStorageD1 = class extends storage.MemoryStorage {
668
494
  } catch (error$1) {
669
495
  throw new error.MastraError(
670
496
  {
671
- id: "CLOUDFLARE_D1_STORAGE_SAVE_THREAD_ERROR",
497
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "SAVE_THREAD", "FAILED"),
672
498
  domain: error.ErrorDomain.STORAGE,
673
499
  category: error.ErrorCategory.THIRD_PARTY,
674
500
  text: `Failed to save thread to ${fullTableName}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
@@ -711,7 +537,7 @@ var MemoryStorageD1 = class extends storage.MemoryStorage {
711
537
  } catch (error$1) {
712
538
  throw new error.MastraError(
713
539
  {
714
- id: "CLOUDFLARE_D1_STORAGE_UPDATE_THREAD_ERROR",
540
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "UPDATE_THREAD", "FAILED"),
715
541
  domain: error.ErrorDomain.STORAGE,
716
542
  category: error.ErrorCategory.THIRD_PARTY,
717
543
  text: `Failed to update thread ${id}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
@@ -734,7 +560,7 @@ var MemoryStorageD1 = class extends storage.MemoryStorage {
734
560
  } catch (error$1) {
735
561
  throw new error.MastraError(
736
562
  {
737
- id: "CLOUDFLARE_D1_STORAGE_DELETE_THREAD_ERROR",
563
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "DELETE_THREAD", "FAILED"),
738
564
  domain: error.ErrorDomain.STORAGE,
739
565
  category: error.ErrorCategory.THIRD_PARTY,
740
566
  text: `Failed to delete thread ${threadId}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
@@ -745,8 +571,8 @@ var MemoryStorageD1 = class extends storage.MemoryStorage {
745
571
  }
746
572
  }
747
573
  async saveMessages(args) {
748
- const { messages, format = "v1" } = args;
749
- if (messages.length === 0) return [];
574
+ const { messages } = args;
575
+ if (messages.length === 0) return { messages: [] };
750
576
  try {
751
577
  const now = /* @__PURE__ */ new Date();
752
578
  const threadId = messages[0]?.threadId;
@@ -794,12 +620,11 @@ var MemoryStorageD1 = class extends storage.MemoryStorage {
794
620
  ]);
795
621
  this.logger.debug(`Saved ${messages.length} messages`);
796
622
  const list = new agent.MessageList().add(messages, "memory");
797
- if (format === `v2`) return list.get.all.v2();
798
- return list.get.all.v1();
623
+ return { messages: list.get.all.db() };
799
624
  } catch (error$1) {
800
625
  throw new error.MastraError(
801
626
  {
802
- id: "CLOUDFLARE_D1_STORAGE_SAVE_MESSAGES_ERROR",
627
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "SAVE_MESSAGES", "FAILED"),
803
628
  domain: error.ErrorDomain.STORAGE,
804
629
  category: error.ErrorCategory.THIRD_PARTY,
805
630
  text: `Failed to save messages: ${error$1 instanceof Error ? error$1.message : String(error$1)}`
@@ -808,23 +633,25 @@ var MemoryStorageD1 = class extends storage.MemoryStorage {
808
633
  );
809
634
  }
810
635
  }
811
- async _getIncludedMessages(threadId, selectBy) {
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,39 +692,16 @@ var MemoryStorageD1 = class extends storage.MemoryStorage {
865
692
  });
866
693
  return processedMessages;
867
694
  }
868
- async getMessages({
869
- threadId,
870
- selectBy,
871
- format
872
- }) {
695
+ async listMessagesById({ messageIds }) {
696
+ if (messageIds.length === 0) return { messages: [] };
873
697
  const fullTableName = this.operations.getTableName(storage.TABLE_MESSAGES);
874
- const limit = storage.resolveMessageLimit({
875
- last: selectBy?.last,
876
- defaultLimit: 40
877
- });
878
- const include = selectBy?.include || [];
879
698
  const messages = [];
880
699
  try {
881
- if (include.length) {
882
- const includeResult = await this._getIncludedMessages(threadId, selectBy);
883
- if (Array.isArray(includeResult)) messages.push(...includeResult);
884
- }
885
- const excludeIds = messages.map((m) => m.id);
886
- const query = createSqlBuilder().select(["id", "content", "role", "type", "createdAt", "thread_id AS threadId"]).from(fullTableName).where("thread_id = ?", threadId);
887
- if (excludeIds.length > 0) {
888
- query.andWhere(`id NOT IN (${excludeIds.map(() => "?").join(",")})`, ...excludeIds);
889
- }
890
- query.orderBy("createdAt", "DESC").limit(limit);
700
+ const query = createSqlBuilder().select(["id", "content", "role", "type", "createdAt", "thread_id AS threadId", "resourceId"]).from(fullTableName).where(`id in (${messageIds.map(() => "?").join(",")})`, ...messageIds);
701
+ query.orderBy("createdAt", "DESC");
891
702
  const { sql, params } = query.build();
892
703
  const result = await this.operations.executeQuery({ sql, params });
893
704
  if (Array.isArray(result)) messages.push(...result);
894
- messages.sort((a, b) => {
895
- const aRecord = a;
896
- const bRecord = b;
897
- const timeA = new Date(aRecord.createdAt).getTime();
898
- const timeB = new Date(bRecord.createdAt).getTime();
899
- return timeA - timeB;
900
- });
901
705
  const processedMessages = messages.map((message) => {
902
706
  const processedMsg = {};
903
707
  for (const [key, value] of Object.entries(message)) {
@@ -906,18 +710,17 @@ var MemoryStorageD1 = class extends storage.MemoryStorage {
906
710
  }
907
711
  return processedMsg;
908
712
  });
909
- this.logger.debug(`Retrieved ${messages.length} messages for thread ${threadId}`);
713
+ this.logger.debug(`Retrieved ${messages.length} messages`);
910
714
  const list = new agent.MessageList().add(processedMessages, "memory");
911
- if (format === `v2`) return list.get.all.v2();
912
- return list.get.all.v1();
715
+ return { messages: list.get.all.db() };
913
716
  } catch (error$1) {
914
717
  const mastraError = new error.MastraError(
915
718
  {
916
- id: "CLOUDFLARE_D1_STORAGE_GET_MESSAGES_ERROR",
719
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "LIST_MESSAGES_BY_ID", "FAILED"),
917
720
  domain: error.ErrorDomain.STORAGE,
918
721
  category: error.ErrorCategory.THIRD_PARTY,
919
- text: `Failed to retrieve messages for thread ${threadId}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
920
- details: { threadId }
722
+ text: `Failed to retrieve messages by ID: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
723
+ details: { messageIds: JSON.stringify(messageIds) }
921
724
  },
922
725
  error$1
923
726
  );
@@ -926,116 +729,158 @@ var MemoryStorageD1 = class extends storage.MemoryStorage {
926
729
  throw mastraError;
927
730
  }
928
731
  }
929
- async getMessagesPaginated({
930
- threadId,
931
- selectBy,
932
- format
933
- }) {
934
- const { dateRange, page = 0, perPage: perPageInput } = selectBy?.pagination || {};
935
- const { start: fromDate, end: toDate } = dateRange || {};
936
- const perPage = perPageInput !== void 0 ? perPageInput : storage.resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
937
- const fullTableName = this.operations.getTableName(storage.TABLE_MESSAGES);
938
- 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);
939
759
  try {
940
- if (selectBy?.include?.length) {
941
- const includeResult = await this._getIncludedMessages(threadId, selectBy);
942
- 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);
943
770
  }
944
- const countQuery = createSqlBuilder().count().from(fullTableName).where("thread_id = ?", threadId);
945
- if (fromDate) {
946
- 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);
947
776
  }
948
- if (toDate) {
949
- 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);
950
781
  }
951
- 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 });
952
815
  const total = Number(countResult[0]?.count ?? 0);
953
- if (total === 0 && messages.length === 0) {
816
+ if (total === 0 && paginatedCount === 0 && (!include || include.length === 0)) {
954
817
  return {
955
818
  messages: [],
956
819
  total: 0,
957
820
  page,
958
- perPage,
821
+ perPage: perPageForResponse,
959
822
  hasMore: false
960
823
  };
961
824
  }
962
- const excludeIds = messages.map((m) => m.id);
963
- const excludeCondition = excludeIds.length > 0 ? `AND id NOT IN (${excludeIds.map(() => "?").join(",")})` : "";
964
- let query;
965
- let queryParams = [threadId];
966
- if (fromDate) {
967
- queryParams.push(storage.serializeDate(fromDate));
968
- }
969
- if (toDate) {
970
- queryParams.push(storage.serializeDate(toDate));
971
- }
972
- if (excludeIds.length > 0) {
973
- queryParams.push(...excludeIds);
974
- }
975
- if (selectBy?.last && selectBy.last > 0) {
976
- query = `
977
- SELECT id, content, role, type, createdAt, thread_id AS threadId, resourceId
978
- FROM ${fullTableName}
979
- WHERE thread_id = ?
980
- ${fromDate ? "AND createdAt >= ?" : ""}
981
- ${toDate ? "AND createdAt <= ?" : ""}
982
- ${excludeCondition}
983
- ORDER BY createdAt DESC
984
- LIMIT ?
985
- `;
986
- queryParams.push(selectBy.last);
987
- } else {
988
- query = `
989
- SELECT id, content, role, type, createdAt, thread_id AS threadId, resourceId
990
- FROM ${fullTableName}
991
- WHERE thread_id = ?
992
- ${fromDate ? "AND createdAt >= ?" : ""}
993
- ${toDate ? "AND createdAt <= ?" : ""}
994
- ${excludeCondition}
995
- ORDER BY createdAt DESC
996
- LIMIT ? OFFSET ?
997
- `;
998
- 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
+ }
999
838
  }
1000
- const results = await this.operations.executeQuery({ sql: query, params: queryParams });
1001
- const processedMessages = results.map((message) => {
1002
- const processedMsg = {};
1003
- for (const [key, value] of Object.entries(message)) {
1004
- if (key === `type` && value === `v2`) continue;
1005
- 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);
1006
847
  }
1007
- 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));
1008
852
  });
1009
- if (selectBy?.last) {
1010
- processedMessages.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
1011
- }
1012
- const list = new agent.MessageList().add(processedMessages, "memory");
1013
- 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;
1014
856
  return {
1015
- messages,
857
+ messages: finalMessages,
1016
858
  total,
1017
859
  page,
1018
- perPage,
1019
- hasMore: selectBy?.last ? false : page * perPage + messages.length < total
860
+ perPage: perPageForResponse,
861
+ hasMore
1020
862
  };
1021
863
  } catch (error$1) {
1022
864
  const mastraError = new error.MastraError(
1023
865
  {
1024
- id: "CLOUDFLARE_D1_STORAGE_GET_MESSAGES_PAGINATED_ERROR",
866
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "LIST_MESSAGES", "FAILED"),
1025
867
  domain: error.ErrorDomain.STORAGE,
1026
868
  category: error.ErrorCategory.THIRD_PARTY,
1027
- text: `Failed to retrieve messages for thread ${threadId}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
1028
- details: { threadId }
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
+ }
1029
874
  },
1030
875
  error$1
1031
876
  );
1032
- this.logger?.error(mastraError.toString());
1033
- this.logger?.trackException(mastraError);
877
+ this.logger?.error?.(mastraError.toString());
878
+ this.logger?.trackException?.(mastraError);
1034
879
  return {
1035
880
  messages: [],
1036
881
  total: 0,
1037
882
  page,
1038
- perPage,
883
+ perPage: perPageForResponse,
1039
884
  hasMore: false
1040
885
  };
1041
886
  }
@@ -1131,7 +976,7 @@ var MemoryStorageD1 = class extends storage.MemoryStorage {
1131
976
  } catch (error$1) {
1132
977
  throw new error.MastraError(
1133
978
  {
1134
- id: "CLOUDFLARE_D1_STORAGE_UPDATE_MESSAGES_FAILED",
979
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "UPDATE_MESSAGES", "FAILED"),
1135
980
  domain: error.ErrorDomain.STORAGE,
1136
981
  category: error.ErrorCategory.THIRD_PARTY,
1137
982
  details: { count: messages.length }
@@ -1200,7 +1045,7 @@ var StoreOperationsD1 = class extends storage.StoreOperations {
1200
1045
  } catch (error$1) {
1201
1046
  throw new error.MastraError(
1202
1047
  {
1203
- id: "CLOUDFLARE_D1_STORE_OPERATIONS_WORKERS_BINDING_QUERY_FAILED",
1048
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "WORKERS_BINDING_QUERY", "FAILED"),
1204
1049
  domain: error.ErrorDomain.STORAGE,
1205
1050
  category: error.ErrorCategory.THIRD_PARTY,
1206
1051
  details: { sql }
@@ -1232,7 +1077,7 @@ var StoreOperationsD1 = class extends storage.StoreOperations {
1232
1077
  } catch (error$1) {
1233
1078
  throw new error.MastraError(
1234
1079
  {
1235
- id: "CLOUDFLARE_D1_STORE_OPERATIONS_REST_QUERY_FAILED",
1080
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "REST_QUERY", "FAILED"),
1236
1081
  domain: error.ErrorDomain.STORAGE,
1237
1082
  category: error.ErrorCategory.THIRD_PARTY,
1238
1083
  details: { sql }
@@ -1313,7 +1158,7 @@ var StoreOperationsD1 = class extends storage.StoreOperations {
1313
1158
  } catch (error$1) {
1314
1159
  throw new error.MastraError(
1315
1160
  {
1316
- id: "CLOUDFLARE_D1_STORE_OPERATIONS_CREATE_TABLE_FAILED",
1161
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "CREATE_TABLE", "FAILED"),
1317
1162
  domain: error.ErrorDomain.STORAGE,
1318
1163
  category: error.ErrorCategory.THIRD_PARTY,
1319
1164
  details: { tableName }
@@ -1332,7 +1177,7 @@ var StoreOperationsD1 = class extends storage.StoreOperations {
1332
1177
  } catch (error$1) {
1333
1178
  throw new error.MastraError(
1334
1179
  {
1335
- id: "CLOUDFLARE_D1_STORE_OPERATIONS_CLEAR_TABLE_FAILED",
1180
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "CLEAR_TABLE", "FAILED"),
1336
1181
  domain: error.ErrorDomain.STORAGE,
1337
1182
  category: error.ErrorCategory.THIRD_PARTY,
1338
1183
  details: { tableName }
@@ -1350,7 +1195,7 @@ var StoreOperationsD1 = class extends storage.StoreOperations {
1350
1195
  } catch (error$1) {
1351
1196
  throw new error.MastraError(
1352
1197
  {
1353
- id: "CLOUDFLARE_D1_STORE_OPERATIONS_DROP_TABLE_FAILED",
1198
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "DROP_TABLE", "FAILED"),
1354
1199
  domain: error.ErrorDomain.STORAGE,
1355
1200
  category: error.ErrorCategory.THIRD_PARTY,
1356
1201
  details: { tableName }
@@ -1376,7 +1221,7 @@ var StoreOperationsD1 = class extends storage.StoreOperations {
1376
1221
  } catch (error$1) {
1377
1222
  throw new error.MastraError(
1378
1223
  {
1379
- id: "CLOUDFLARE_D1_STORE_OPERATIONS_ALTER_TABLE_FAILED",
1224
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "ALTER_TABLE", "FAILED"),
1380
1225
  domain: error.ErrorDomain.STORAGE,
1381
1226
  category: error.ErrorCategory.THIRD_PARTY,
1382
1227
  details: { tableName: args.tableName }
@@ -1397,7 +1242,7 @@ var StoreOperationsD1 = class extends storage.StoreOperations {
1397
1242
  } catch (error$1) {
1398
1243
  throw new error.MastraError(
1399
1244
  {
1400
- id: "CLOUDFLARE_D1_STORE_OPERATIONS_INSERT_FAILED",
1245
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "INSERT", "FAILED"),
1401
1246
  domain: error.ErrorDomain.STORAGE,
1402
1247
  category: error.ErrorCategory.THIRD_PARTY,
1403
1248
  details: { tableName }
@@ -1421,7 +1266,7 @@ var StoreOperationsD1 = class extends storage.StoreOperations {
1421
1266
  } catch (error$1) {
1422
1267
  throw new error.MastraError(
1423
1268
  {
1424
- id: "CLOUDFLARE_D1_STORE_OPERATIONS_BATCH_INSERT_FAILED",
1269
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "BATCH_INSERT", "FAILED"),
1425
1270
  domain: error.ErrorDomain.STORAGE,
1426
1271
  category: error.ErrorCategory.THIRD_PARTY,
1427
1272
  details: { tableName }
@@ -1443,6 +1288,7 @@ var StoreOperationsD1 = class extends storage.StoreOperations {
1443
1288
  query.andWhere(`${key} = ?`, value);
1444
1289
  }
1445
1290
  }
1291
+ query.orderBy("createdAt", "DESC");
1446
1292
  query.limit(1);
1447
1293
  const { sql, params } = query.build();
1448
1294
  const result = await this.executeQuery({ sql, params, first: true });
@@ -1457,7 +1303,7 @@ var StoreOperationsD1 = class extends storage.StoreOperations {
1457
1303
  } catch (error$1) {
1458
1304
  throw new error.MastraError(
1459
1305
  {
1460
- id: "CLOUDFLARE_D1_STORE_OPERATIONS_LOAD_FAILED",
1306
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "LOAD", "FAILED"),
1461
1307
  domain: error.ErrorDomain.STORAGE,
1462
1308
  category: error.ErrorCategory.THIRD_PARTY,
1463
1309
  details: { tableName }
@@ -1515,7 +1361,7 @@ var StoreOperationsD1 = class extends storage.StoreOperations {
1515
1361
  } catch (error$1) {
1516
1362
  throw new error.MastraError(
1517
1363
  {
1518
- id: "CLOUDFLARE_D1_STORAGE_BATCH_UPSERT_ERROR",
1364
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "BATCH_UPSERT", "FAILED"),
1519
1365
  domain: error.ErrorDomain.STORAGE,
1520
1366
  category: error.ErrorCategory.THIRD_PARTY,
1521
1367
  text: `Failed to batch upsert into ${tableName}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
@@ -1527,20 +1373,12 @@ var StoreOperationsD1 = class extends storage.StoreOperations {
1527
1373
  }
1528
1374
  };
1529
1375
  function transformScoreRow(row) {
1530
- let input = void 0;
1531
- if (row.input) {
1532
- try {
1533
- input = JSON.parse(row.input);
1534
- } catch {
1535
- input = row.input;
1376
+ return storage.transformScoreRow(row, {
1377
+ preferredTimestampFields: {
1378
+ createdAt: "createdAtZ",
1379
+ updatedAt: "updatedAtZ"
1536
1380
  }
1537
- }
1538
- return {
1539
- ...row,
1540
- input,
1541
- createdAt: row.createdAtZ || row.createdAt,
1542
- updatedAt: row.updatedAtZ || row.updatedAt
1543
- };
1381
+ });
1544
1382
  }
1545
1383
  var ScoresStorageD1 = class extends storage.ScoresStorage {
1546
1384
  operations;
@@ -1561,7 +1399,7 @@ var ScoresStorageD1 = class extends storage.ScoresStorage {
1561
1399
  } catch (error$1) {
1562
1400
  throw new error.MastraError(
1563
1401
  {
1564
- id: "CLOUDFLARE_D1_STORE_SCORES_GET_SCORE_BY_ID_FAILED",
1402
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "GET_SCORE_BY_ID", "FAILED"),
1565
1403
  domain: error.ErrorDomain.STORAGE,
1566
1404
  category: error.ErrorCategory.THIRD_PARTY
1567
1405
  },
@@ -1570,11 +1408,31 @@ var ScoresStorageD1 = class extends storage.ScoresStorage {
1570
1408
  }
1571
1409
  }
1572
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();
1573
1432
  try {
1574
1433
  const fullTableName = this.operations.getTableName(storage.TABLE_SCORERS);
1575
- const { input, ...rest } = score;
1576
1434
  const serializedRecord = {};
1577
- for (const [key, value] of Object.entries(rest)) {
1435
+ for (const [key, value] of Object.entries(parsedScore)) {
1578
1436
  if (value !== null && value !== void 0) {
1579
1437
  if (typeof value === "object") {
1580
1438
  serializedRecord[key] = JSON.stringify(value);
@@ -1585,64 +1443,92 @@ var ScoresStorageD1 = class extends storage.ScoresStorage {
1585
1443
  serializedRecord[key] = null;
1586
1444
  }
1587
1445
  }
1588
- serializedRecord.input = JSON.stringify(input);
1589
- serializedRecord.createdAt = (/* @__PURE__ */ new Date()).toISOString();
1590
- serializedRecord.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1446
+ const now = /* @__PURE__ */ new Date();
1447
+ serializedRecord.id = id;
1448
+ serializedRecord.createdAt = now.toISOString();
1449
+ serializedRecord.updatedAt = now.toISOString();
1591
1450
  const columns = Object.keys(serializedRecord);
1592
1451
  const values = Object.values(serializedRecord);
1593
1452
  const query = createSqlBuilder().insert(fullTableName, columns, values);
1594
1453
  const { sql, params } = query.build();
1595
1454
  await this.operations.executeQuery({ sql, params });
1596
- const scoreFromDb = await this.getScoreById({ id: score.id });
1597
- return { score: scoreFromDb };
1455
+ return { score: { ...parsedScore, id, createdAt: now, updatedAt: now } };
1598
1456
  } catch (error$1) {
1599
1457
  throw new error.MastraError(
1600
1458
  {
1601
- id: "CLOUDFLARE_D1_STORE_SCORES_SAVE_SCORE_FAILED",
1459
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "SAVE_SCORE", "FAILED"),
1602
1460
  domain: error.ErrorDomain.STORAGE,
1603
- category: error.ErrorCategory.THIRD_PARTY
1461
+ category: error.ErrorCategory.THIRD_PARTY,
1462
+ details: { id }
1604
1463
  },
1605
1464
  error$1
1606
1465
  );
1607
1466
  }
1608
1467
  }
1609
- async getScoresByScorerId({
1468
+ async listScoresByScorerId({
1610
1469
  scorerId,
1470
+ entityId,
1471
+ entityType,
1472
+ source,
1611
1473
  pagination
1612
1474
  }) {
1613
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);
1614
1479
  const fullTableName = this.operations.getTableName(storage.TABLE_SCORERS);
1615
1480
  const countQuery = createSqlBuilder().count().from(fullTableName).where("scorerId = ?", scorerId);
1481
+ if (entityId) {
1482
+ countQuery.andWhere("entityId = ?", entityId);
1483
+ }
1484
+ if (entityType) {
1485
+ countQuery.andWhere("entityType = ?", entityType);
1486
+ }
1487
+ if (source) {
1488
+ countQuery.andWhere("source = ?", source);
1489
+ }
1616
1490
  const countResult = await this.operations.executeQuery(countQuery.build());
1617
1491
  const total = Array.isArray(countResult) ? Number(countResult?.[0]?.count ?? 0) : Number(countResult?.count ?? 0);
1618
1492
  if (total === 0) {
1619
1493
  return {
1620
1494
  pagination: {
1621
1495
  total: 0,
1622
- page: pagination.page,
1623
- perPage: pagination.perPage,
1496
+ page,
1497
+ perPage: perPageForResponse,
1624
1498
  hasMore: false
1625
1499
  },
1626
1500
  scores: []
1627
1501
  };
1628
1502
  }
1629
- const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("scorerId = ?", scorerId).limit(pagination.perPage).offset(pagination.page * pagination.perPage);
1503
+ const end = perPageInput === false ? total : start + perPage;
1504
+ const limitValue = perPageInput === false ? total : perPage;
1505
+ const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("scorerId = ?", scorerId);
1506
+ if (entityId) {
1507
+ selectQuery.andWhere("entityId = ?", entityId);
1508
+ }
1509
+ if (entityType) {
1510
+ selectQuery.andWhere("entityType = ?", entityType);
1511
+ }
1512
+ if (source) {
1513
+ selectQuery.andWhere("source = ?", source);
1514
+ }
1515
+ selectQuery.limit(limitValue).offset(start);
1630
1516
  const { sql, params } = selectQuery.build();
1631
1517
  const results = await this.operations.executeQuery({ sql, params });
1632
1518
  const scores = Array.isArray(results) ? results.map(transformScoreRow) : [];
1633
1519
  return {
1634
1520
  pagination: {
1635
1521
  total,
1636
- page: pagination.page,
1637
- perPage: pagination.perPage,
1638
- hasMore: total > (pagination.page + 1) * pagination.perPage
1522
+ page,
1523
+ perPage: perPageForResponse,
1524
+ hasMore: end < total
1639
1525
  },
1640
1526
  scores
1641
1527
  };
1642
1528
  } catch (error$1) {
1643
1529
  throw new error.MastraError(
1644
1530
  {
1645
- id: "CLOUDFLARE_D1_STORE_SCORES_GET_SCORES_BY_SCORER_ID_FAILED",
1531
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "GET_SCORES_BY_SCORER_ID", "FAILED"),
1646
1532
  domain: error.ErrorDomain.STORAGE,
1647
1533
  category: error.ErrorCategory.THIRD_PARTY
1648
1534
  },
@@ -1650,11 +1536,14 @@ var ScoresStorageD1 = class extends storage.ScoresStorage {
1650
1536
  );
1651
1537
  }
1652
1538
  }
1653
- async getScoresByRunId({
1539
+ async listScoresByRunId({
1654
1540
  runId,
1655
1541
  pagination
1656
1542
  }) {
1657
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);
1658
1547
  const fullTableName = this.operations.getTableName(storage.TABLE_SCORERS);
1659
1548
  const countQuery = createSqlBuilder().count().from(fullTableName).where("runId = ?", runId);
1660
1549
  const countResult = await this.operations.executeQuery(countQuery.build());
@@ -1663,30 +1552,32 @@ var ScoresStorageD1 = class extends storage.ScoresStorage {
1663
1552
  return {
1664
1553
  pagination: {
1665
1554
  total: 0,
1666
- page: pagination.page,
1667
- perPage: pagination.perPage,
1555
+ page,
1556
+ perPage: perPageForResponse,
1668
1557
  hasMore: false
1669
1558
  },
1670
1559
  scores: []
1671
1560
  };
1672
1561
  }
1673
- 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);
1674
1565
  const { sql, params } = selectQuery.build();
1675
1566
  const results = await this.operations.executeQuery({ sql, params });
1676
1567
  const scores = Array.isArray(results) ? results.map(transformScoreRow) : [];
1677
1568
  return {
1678
1569
  pagination: {
1679
1570
  total,
1680
- page: pagination.page,
1681
- perPage: pagination.perPage,
1682
- hasMore: total > (pagination.page + 1) * pagination.perPage
1571
+ page,
1572
+ perPage: perPageForResponse,
1573
+ hasMore: end < total
1683
1574
  },
1684
1575
  scores
1685
1576
  };
1686
1577
  } catch (error$1) {
1687
1578
  throw new error.MastraError(
1688
1579
  {
1689
- id: "CLOUDFLARE_D1_STORE_SCORES_GET_SCORES_BY_RUN_ID_FAILED",
1580
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "GET_SCORES_BY_RUN_ID", "FAILED"),
1690
1581
  domain: error.ErrorDomain.STORAGE,
1691
1582
  category: error.ErrorCategory.THIRD_PARTY
1692
1583
  },
@@ -1694,12 +1585,15 @@ var ScoresStorageD1 = class extends storage.ScoresStorage {
1694
1585
  );
1695
1586
  }
1696
1587
  }
1697
- async getScoresByEntityId({
1588
+ async listScoresByEntityId({
1698
1589
  entityId,
1699
1590
  entityType,
1700
1591
  pagination
1701
1592
  }) {
1702
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);
1703
1597
  const fullTableName = this.operations.getTableName(storage.TABLE_SCORERS);
1704
1598
  const countQuery = createSqlBuilder().count().from(fullTableName).where("entityId = ?", entityId).andWhere("entityType = ?", entityType);
1705
1599
  const countResult = await this.operations.executeQuery(countQuery.build());
@@ -1708,30 +1602,32 @@ var ScoresStorageD1 = class extends storage.ScoresStorage {
1708
1602
  return {
1709
1603
  pagination: {
1710
1604
  total: 0,
1711
- page: pagination.page,
1712
- perPage: pagination.perPage,
1605
+ page,
1606
+ perPage: perPageForResponse,
1713
1607
  hasMore: false
1714
1608
  },
1715
1609
  scores: []
1716
1610
  };
1717
1611
  }
1718
- 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);
1719
1615
  const { sql, params } = selectQuery.build();
1720
1616
  const results = await this.operations.executeQuery({ sql, params });
1721
1617
  const scores = Array.isArray(results) ? results.map(transformScoreRow) : [];
1722
1618
  return {
1723
1619
  pagination: {
1724
1620
  total,
1725
- page: pagination.page,
1726
- perPage: pagination.perPage,
1727
- hasMore: total > (pagination.page + 1) * pagination.perPage
1621
+ page,
1622
+ perPage: perPageForResponse,
1623
+ hasMore: end < total
1728
1624
  },
1729
1625
  scores
1730
1626
  };
1731
1627
  } catch (error$1) {
1732
1628
  throw new error.MastraError(
1733
1629
  {
1734
- id: "CLOUDFLARE_D1_STORE_SCORES_GET_SCORES_BY_ENTITY_ID_FAILED",
1630
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "GET_SCORES_BY_ENTITY_ID", "FAILED"),
1735
1631
  domain: error.ErrorDomain.STORAGE,
1736
1632
  category: error.ErrorCategory.THIRD_PARTY
1737
1633
  },
@@ -1739,128 +1635,56 @@ var ScoresStorageD1 = class extends storage.ScoresStorage {
1739
1635
  );
1740
1636
  }
1741
1637
  }
1742
- };
1743
- function isArrayOfRecords2(value) {
1744
- return value && Array.isArray(value) && value.length > 0;
1745
- }
1746
- var TracesStorageD1 = class extends storage.TracesStorage {
1747
- operations;
1748
- constructor({ operations }) {
1749
- super();
1750
- this.operations = operations;
1751
- }
1752
- async getTraces(args) {
1753
- const paginatedArgs = {
1754
- name: args.name,
1755
- scope: args.scope,
1756
- page: args.page,
1757
- perPage: args.perPage,
1758
- attributes: args.attributes,
1759
- filters: args.filters,
1760
- dateRange: args.fromDate || args.toDate ? {
1761
- start: args.fromDate,
1762
- end: args.toDate
1763
- } : void 0
1764
- };
1765
- try {
1766
- const result = await this.getTracesPaginated(paginatedArgs);
1767
- return result.traces;
1768
- } catch (error$1) {
1769
- throw new error.MastraError(
1770
- {
1771
- id: "CLOUDFLARE_D1_STORAGE_GET_TRACES_ERROR",
1772
- domain: error.ErrorDomain.STORAGE,
1773
- category: error.ErrorCategory.THIRD_PARTY,
1774
- text: `Failed to retrieve traces: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
1775
- details: {
1776
- name: args.name ?? "",
1777
- scope: args.scope ?? ""
1778
- }
1779
- },
1780
- error$1
1781
- );
1782
- }
1783
- }
1784
- async getTracesPaginated(args) {
1785
- const { name, scope, page = 0, perPage = 100, attributes, dateRange } = args;
1786
- const fromDate = dateRange?.start;
1787
- const toDate = dateRange?.end;
1788
- const fullTableName = this.operations.getTableName(storage.TABLE_TRACES);
1638
+ async listScoresBySpan({
1639
+ traceId,
1640
+ spanId,
1641
+ pagination
1642
+ }) {
1789
1643
  try {
1790
- const dataQuery = createSqlBuilder().select("*").from(fullTableName).where("1=1");
1791
- const countQuery = createSqlBuilder().count().from(fullTableName).where("1=1");
1792
- if (name) {
1793
- dataQuery.andWhere("name LIKE ?", `%${name}%`);
1794
- countQuery.andWhere("name LIKE ?", `%${name}%`);
1795
- }
1796
- if (scope) {
1797
- dataQuery.andWhere("scope = ?", scope);
1798
- countQuery.andWhere("scope = ?", scope);
1799
- }
1800
- if (attributes && Object.keys(attributes).length > 0) {
1801
- for (const [key, value] of Object.entries(attributes)) {
1802
- dataQuery.jsonLike("attributes", key, value);
1803
- countQuery.jsonLike("attributes", key, value);
1804
- }
1805
- }
1806
- if (fromDate) {
1807
- const fromDateStr = fromDate instanceof Date ? fromDate.toISOString() : fromDate;
1808
- dataQuery.andWhere("createdAt >= ?", fromDateStr);
1809
- countQuery.andWhere("createdAt >= ?", fromDateStr);
1810
- }
1811
- if (toDate) {
1812
- const toDateStr = toDate instanceof Date ? toDate.toISOString() : toDate;
1813
- dataQuery.andWhere("createdAt <= ?", toDateStr);
1814
- countQuery.andWhere("createdAt <= ?", toDateStr);
1815
- }
1816
- const allDataResult = await this.operations.executeQuery(
1817
- createSqlBuilder().select("*").from(fullTableName).where("1=1").build()
1818
- );
1819
- 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);
1820
1649
  const countResult = await this.operations.executeQuery(countQuery.build());
1821
- const total = Number(countResult?.[0]?.count ?? 0);
1822
- dataQuery.orderBy("startTime", "DESC").limit(perPage).offset(page * perPage);
1823
- const results = await this.operations.executeQuery(dataQuery.build());
1824
- const traces = isArrayOfRecords2(results) ? results.map(
1825
- (trace) => ({
1826
- ...trace,
1827
- attributes: deserializeValue(trace.attributes, "jsonb"),
1828
- status: deserializeValue(trace.status, "jsonb"),
1829
- events: deserializeValue(trace.events, "jsonb"),
1830
- links: deserializeValue(trace.links, "jsonb"),
1831
- other: deserializeValue(trace.other, "jsonb")
1832
- })
1833
- ) : [];
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) : [];
1834
1668
  return {
1835
- traces,
1836
- total,
1837
- page,
1838
- perPage,
1839
- hasMore: page * perPage + traces.length < total
1669
+ pagination: {
1670
+ total,
1671
+ page,
1672
+ perPage: perPageForResponse,
1673
+ hasMore: end < total
1674
+ },
1675
+ scores
1840
1676
  };
1841
1677
  } catch (error$1) {
1842
- const mastraError = new error.MastraError(
1678
+ throw new error.MastraError(
1843
1679
  {
1844
- id: "CLOUDFLARE_D1_STORAGE_GET_TRACES_PAGINATED_ERROR",
1680
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "GET_SCORES_BY_SPAN", "FAILED"),
1845
1681
  domain: error.ErrorDomain.STORAGE,
1846
- category: error.ErrorCategory.THIRD_PARTY,
1847
- text: `Failed to retrieve traces: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
1848
- details: { name: name ?? "", scope: scope ?? "" }
1682
+ category: error.ErrorCategory.THIRD_PARTY
1849
1683
  },
1850
1684
  error$1
1851
1685
  );
1852
- this.logger?.error(mastraError.toString());
1853
- this.logger?.trackException(mastraError);
1854
- return { traces: [], total: 0, page, perPage, hasMore: false };
1855
1686
  }
1856
1687
  }
1857
- async batchTraceInsert({ records }) {
1858
- this.logger.debug("Batch inserting traces", { count: records.length });
1859
- await this.operations.batchInsert({
1860
- tableName: storage.TABLE_TRACES,
1861
- records
1862
- });
1863
- }
1864
1688
  };
1865
1689
  var WorkflowsStorageD1 = class extends storage.WorkflowsStorage {
1866
1690
  operations;
@@ -1868,9 +1692,26 @@ var WorkflowsStorageD1 = class extends storage.WorkflowsStorage {
1868
1692
  super();
1869
1693
  this.operations = operations;
1870
1694
  }
1695
+ updateWorkflowResults({
1696
+ // workflowName,
1697
+ // runId,
1698
+ // stepId,
1699
+ // result,
1700
+ // requestContext,
1701
+ }) {
1702
+ throw new Error("Method not implemented.");
1703
+ }
1704
+ updateWorkflowState({
1705
+ // workflowName,
1706
+ // runId,
1707
+ // opts,
1708
+ }) {
1709
+ throw new Error("Method not implemented.");
1710
+ }
1871
1711
  async persistWorkflowSnapshot({
1872
1712
  workflowName,
1873
1713
  runId,
1714
+ resourceId,
1874
1715
  snapshot
1875
1716
  }) {
1876
1717
  const fullTableName = this.operations.getTableName(storage.TABLE_WORKFLOW_SNAPSHOT);
@@ -1881,11 +1722,13 @@ var WorkflowsStorageD1 = class extends storage.WorkflowsStorage {
1881
1722
  });
1882
1723
  const persisting = currentSnapshot ? {
1883
1724
  ...currentSnapshot,
1725
+ resourceId,
1884
1726
  snapshot: JSON.stringify(snapshot),
1885
1727
  updatedAt: now
1886
1728
  } : {
1887
1729
  workflow_name: workflowName,
1888
1730
  run_id: runId,
1731
+ resourceId,
1889
1732
  snapshot,
1890
1733
  createdAt: now,
1891
1734
  updatedAt: now
@@ -1905,7 +1748,7 @@ var WorkflowsStorageD1 = class extends storage.WorkflowsStorage {
1905
1748
  } catch (error$1) {
1906
1749
  throw new error.MastraError(
1907
1750
  {
1908
- id: "CLOUDFLARE_D1_STORAGE_PERSIST_WORKFLOW_SNAPSHOT_ERROR",
1751
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "PERSIST_WORKFLOW_SNAPSHOT", "FAILED"),
1909
1752
  domain: error.ErrorDomain.STORAGE,
1910
1753
  category: error.ErrorCategory.THIRD_PARTY,
1911
1754
  text: `Failed to persist workflow snapshot: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
@@ -1930,7 +1773,7 @@ var WorkflowsStorageD1 = class extends storage.WorkflowsStorage {
1930
1773
  } catch (error$1) {
1931
1774
  throw new error.MastraError(
1932
1775
  {
1933
- id: "CLOUDFLARE_D1_STORAGE_LOAD_WORKFLOW_SNAPSHOT_ERROR",
1776
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "LOAD_WORKFLOW_SNAPSHOT", "FAILED"),
1934
1777
  domain: error.ErrorDomain.STORAGE,
1935
1778
  category: error.ErrorCategory.THIRD_PARTY,
1936
1779
  text: `Failed to load workflow snapshot: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
@@ -1958,19 +1801,24 @@ var WorkflowsStorageD1 = class extends storage.WorkflowsStorage {
1958
1801
  resourceId: row.resourceId
1959
1802
  };
1960
1803
  }
1961
- async getWorkflowRuns({
1804
+ async listWorkflowRuns({
1962
1805
  workflowName,
1963
1806
  fromDate,
1964
1807
  toDate,
1965
- limit,
1966
- offset,
1967
- resourceId
1808
+ page,
1809
+ perPage,
1810
+ resourceId,
1811
+ status
1968
1812
  } = {}) {
1969
1813
  const fullTableName = this.operations.getTableName(storage.TABLE_WORKFLOW_SNAPSHOT);
1970
1814
  try {
1971
1815
  const builder = createSqlBuilder().select().from(fullTableName);
1972
1816
  const countBuilder = createSqlBuilder().count().from(fullTableName);
1973
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
+ }
1974
1822
  if (resourceId) {
1975
1823
  const hasResourceId = await this.operations.hasColumn(fullTableName, "resourceId");
1976
1824
  if (hasResourceId) {
@@ -1989,11 +1837,14 @@ var WorkflowsStorageD1 = class extends storage.WorkflowsStorage {
1989
1837
  countBuilder.whereAnd("createdAt <= ?", toDate instanceof Date ? toDate.toISOString() : toDate);
1990
1838
  }
1991
1839
  builder.orderBy("createdAt", "DESC");
1992
- if (typeof limit === "number") builder.limit(limit);
1993
- 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
+ }
1994
1845
  const { sql, params } = builder.build();
1995
1846
  let total = 0;
1996
- if (limit !== void 0 && offset !== void 0) {
1847
+ if (perPage !== void 0 && page !== void 0) {
1997
1848
  const { sql: countSql, params: countParams } = countBuilder.build();
1998
1849
  const countResult = await this.operations.executeQuery({
1999
1850
  sql: countSql,
@@ -2008,7 +1859,7 @@ var WorkflowsStorageD1 = class extends storage.WorkflowsStorage {
2008
1859
  } catch (error$1) {
2009
1860
  throw new error.MastraError(
2010
1861
  {
2011
- id: "CLOUDFLARE_D1_STORAGE_GET_WORKFLOW_RUNS_ERROR",
1862
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "LIST_WORKFLOW_RUNS", "FAILED"),
2012
1863
  domain: error.ErrorDomain.STORAGE,
2013
1864
  category: error.ErrorCategory.THIRD_PARTY,
2014
1865
  text: `Failed to retrieve workflow runs: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
@@ -2045,7 +1896,7 @@ var WorkflowsStorageD1 = class extends storage.WorkflowsStorage {
2045
1896
  } catch (error$1) {
2046
1897
  throw new error.MastraError(
2047
1898
  {
2048
- id: "CLOUDFLARE_D1_STORAGE_GET_WORKFLOW_RUN_BY_ID_ERROR",
1899
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "GET_WORKFLOW_RUN_BY_ID", "FAILED"),
2049
1900
  domain: error.ErrorDomain.STORAGE,
2050
1901
  category: error.ErrorCategory.THIRD_PARTY,
2051
1902
  text: `Failed to retrieve workflow run by ID: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
@@ -2070,7 +1921,7 @@ var D1Store = class extends storage.MastraStorage {
2070
1921
  */
2071
1922
  constructor(config) {
2072
1923
  try {
2073
- super({ name: "D1" });
1924
+ super({ id: config.id, name: "D1", disableInit: config.disableInit });
2074
1925
  if (config.tablePrefix && !/^[a-zA-Z0-9_]*$/.test(config.tablePrefix)) {
2075
1926
  throw new Error("Invalid tablePrefix: only letters, numbers, and underscores are allowed.");
2076
1927
  }
@@ -2108,7 +1959,7 @@ var D1Store = class extends storage.MastraStorage {
2108
1959
  } catch (error$1) {
2109
1960
  throw new error.MastraError(
2110
1961
  {
2111
- id: "CLOUDFLARE_D1_STORAGE_INITIALIZATION_ERROR",
1962
+ id: storage.createStorageErrorId("CLOUDFLARE_D1", "INITIALIZATION", "FAILED"),
2112
1963
  domain: error.ErrorDomain.STORAGE,
2113
1964
  category: error.ErrorCategory.SYSTEM,
2114
1965
  text: "Error initializing D1Store"
@@ -2124,12 +1975,6 @@ var D1Store = class extends storage.MastraStorage {
2124
1975
  const scores = new ScoresStorageD1({
2125
1976
  operations
2126
1977
  });
2127
- const legacyEvals = new LegacyEvalsStorageD1({
2128
- operations
2129
- });
2130
- const traces = new TracesStorageD1({
2131
- operations
2132
- });
2133
1978
  const workflows = new WorkflowsStorageD1({
2134
1979
  operations
2135
1980
  });
@@ -2139,8 +1984,6 @@ var D1Store = class extends storage.MastraStorage {
2139
1984
  this.stores = {
2140
1985
  operations,
2141
1986
  scores,
2142
- legacyEvals,
2143
- traces,
2144
1987
  workflows,
2145
1988
  memory
2146
1989
  };
@@ -2151,7 +1994,8 @@ var D1Store = class extends storage.MastraStorage {
2151
1994
  resourceWorkingMemory: true,
2152
1995
  hasColumn: true,
2153
1996
  createTable: true,
2154
- deleteMessages: false
1997
+ deleteMessages: false,
1998
+ listScoresBySpan: true
2155
1999
  };
2156
2000
  }
2157
2001
  async createTable({
@@ -2191,15 +2035,6 @@ var D1Store = class extends storage.MastraStorage {
2191
2035
  async getThreadById({ threadId }) {
2192
2036
  return this.stores.memory.getThreadById({ threadId });
2193
2037
  }
2194
- /**
2195
- * @deprecated use getThreadsByResourceIdPaginated instead
2196
- */
2197
- async getThreadsByResourceId({ resourceId }) {
2198
- return this.stores.memory.getThreadsByResourceId({ resourceId });
2199
- }
2200
- async getThreadsByResourceIdPaginated(args) {
2201
- return this.stores.memory.getThreadsByResourceIdPaginated(args);
2202
- }
2203
2038
  async saveThread({ thread }) {
2204
2039
  return this.stores.memory.saveThread({ thread });
2205
2040
  }
@@ -2216,39 +2051,35 @@ var D1Store = class extends storage.MastraStorage {
2216
2051
  async saveMessages(args) {
2217
2052
  return this.stores.memory.saveMessages(args);
2218
2053
  }
2219
- async getMessages({
2220
- threadId,
2221
- selectBy,
2222
- format
2054
+ async updateWorkflowResults({
2055
+ workflowName,
2056
+ runId,
2057
+ stepId,
2058
+ result,
2059
+ requestContext
2223
2060
  }) {
2224
- return this.stores.memory.getMessages({ threadId, selectBy, format });
2061
+ return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, requestContext });
2225
2062
  }
2226
- async getMessagesPaginated({
2227
- threadId,
2228
- selectBy,
2229
- format
2063
+ async updateWorkflowState({
2064
+ workflowName,
2065
+ runId,
2066
+ opts
2230
2067
  }) {
2231
- return this.stores.memory.getMessagesPaginated({ threadId, selectBy, format });
2068
+ return this.stores.workflows.updateWorkflowState({ workflowName, runId, opts });
2232
2069
  }
2233
2070
  async persistWorkflowSnapshot({
2234
2071
  workflowName,
2235
2072
  runId,
2073
+ resourceId,
2236
2074
  snapshot
2237
2075
  }) {
2238
- return this.stores.workflows.persistWorkflowSnapshot({ workflowName, runId, snapshot });
2076
+ return this.stores.workflows.persistWorkflowSnapshot({ workflowName, runId, resourceId, snapshot });
2239
2077
  }
2240
2078
  async loadWorkflowSnapshot(params) {
2241
2079
  return this.stores.workflows.loadWorkflowSnapshot(params);
2242
2080
  }
2243
- async getWorkflowRuns({
2244
- workflowName,
2245
- fromDate,
2246
- toDate,
2247
- limit,
2248
- offset,
2249
- resourceId
2250
- } = {}) {
2251
- return this.stores.workflows.getWorkflowRuns({ workflowName, fromDate, toDate, limit, offset, resourceId });
2081
+ async listWorkflowRuns(args = {}) {
2082
+ return this.stores.workflows.listWorkflowRuns(args);
2252
2083
  }
2253
2084
  async getWorkflowRunById({
2254
2085
  runId,
@@ -2264,24 +2095,6 @@ var D1Store = class extends storage.MastraStorage {
2264
2095
  async batchInsert({ tableName, records }) {
2265
2096
  return this.stores.operations.batchInsert({ tableName, records });
2266
2097
  }
2267
- /**
2268
- * @deprecated use getTracesPaginated instead
2269
- */
2270
- async getTraces(args) {
2271
- return this.stores.traces.getTraces(args);
2272
- }
2273
- async getTracesPaginated(args) {
2274
- return this.stores.traces.getTracesPaginated(args);
2275
- }
2276
- /**
2277
- * @deprecated use getEvals instead
2278
- */
2279
- async getEvalsByAgentName(agentName, type) {
2280
- return this.stores.legacyEvals.getEvalsByAgentName(agentName, type);
2281
- }
2282
- async getEvals(options) {
2283
- return this.stores.legacyEvals.getEvals(options);
2284
- }
2285
2098
  async updateMessages(_args) {
2286
2099
  return this.stores.memory.updateMessages(_args);
2287
2100
  }
@@ -2301,31 +2114,41 @@ var D1Store = class extends storage.MastraStorage {
2301
2114
  async getScoreById({ id: _id }) {
2302
2115
  return this.stores.scores.getScoreById({ id: _id });
2303
2116
  }
2304
- async saveScore(_score) {
2305
- return this.stores.scores.saveScore(_score);
2117
+ async saveScore(score) {
2118
+ return this.stores.scores.saveScore(score);
2306
2119
  }
2307
- async getScoresByRunId({
2120
+ async listScoresByRunId({
2308
2121
  runId: _runId,
2309
2122
  pagination: _pagination
2310
2123
  }) {
2311
- return this.stores.scores.getScoresByRunId({ runId: _runId, pagination: _pagination });
2124
+ return this.stores.scores.listScoresByRunId({ runId: _runId, pagination: _pagination });
2312
2125
  }
2313
- async getScoresByEntityId({
2126
+ async listScoresByEntityId({
2314
2127
  entityId: _entityId,
2315
2128
  entityType: _entityType,
2316
2129
  pagination: _pagination
2317
2130
  }) {
2318
- return this.stores.scores.getScoresByEntityId({
2131
+ return this.stores.scores.listScoresByEntityId({
2319
2132
  entityId: _entityId,
2320
2133
  entityType: _entityType,
2321
2134
  pagination: _pagination
2322
2135
  });
2323
2136
  }
2324
- async getScoresByScorerId({
2325
- scorerId: _scorerId,
2326
- pagination: _pagination
2137
+ async listScoresByScorerId({
2138
+ scorerId,
2139
+ pagination,
2140
+ entityId,
2141
+ entityType,
2142
+ source
2143
+ }) {
2144
+ return this.stores.scores.listScoresByScorerId({ scorerId, pagination, entityId, entityType, source });
2145
+ }
2146
+ async listScoresBySpan({
2147
+ traceId,
2148
+ spanId,
2149
+ pagination
2327
2150
  }) {
2328
- return this.stores.scores.getScoresByScorerId({ scorerId: _scorerId, pagination: _pagination });
2151
+ return this.stores.scores.listScoresBySpan({ traceId, spanId, pagination });
2329
2152
  }
2330
2153
  /**
2331
2154
  * Close the database connection