@mastra/cloudflare-d1 0.0.0-pgvector-index-fix-20250905222058 → 0.0.0-playground-studio-again-20251114100107

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 }) {
@@ -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_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: "CLOUDFLARE_D1_STORAGE_LIST_THREADS_BY_RESOURCE_ID_ERROR",
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
  }
@@ -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,8 +620,7 @@ 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
  {
@@ -807,9 +633,8 @@ var MemoryStorageD1 = class extends storage.MemoryStorage {
807
633
  );
808
634
  }
809
635
  }
810
- async _getIncludedMessages(threadId, selectBy) {
636
+ async _getIncludedMessages(threadId, include) {
811
637
  if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
812
- const include = selectBy?.include;
813
638
  if (!include) return null;
814
639
  const unionQueries = [];
815
640
  const params = [];
@@ -865,74 +690,8 @@ var MemoryStorageD1 = class extends storage.MemoryStorage {
865
690
  });
866
691
  return processedMessages;
867
692
  }
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 [];
693
+ async listMessagesById({ messageIds }) {
694
+ if (messageIds.length === 0) return { messages: [] };
936
695
  const fullTableName = this.operations.getTableName(storage.TABLE_MESSAGES);
937
696
  const messages = [];
938
697
  try {
@@ -951,12 +710,11 @@ var MemoryStorageD1 = class extends storage.MemoryStorage {
951
710
  });
952
711
  this.logger.debug(`Retrieved ${messages.length} messages`);
953
712
  const list = new agent.MessageList().add(processedMessages, "memory");
954
- if (format === `v1`) return list.get.all.v1();
955
- return list.get.all.v2();
713
+ return { messages: list.get.all.db() };
956
714
  } catch (error$1) {
957
715
  const mastraError = new error.MastraError(
958
716
  {
959
- id: "CLOUDFLARE_D1_STORAGE_GET_MESSAGES_BY_ID_ERROR",
717
+ id: "CLOUDFLARE_D1_STORAGE_LIST_MESSAGES_BY_ID_ERROR",
960
718
  domain: error.ErrorDomain.STORAGE,
961
719
  category: error.ErrorCategory.THIRD_PARTY,
962
720
  text: `Failed to retrieve messages by ID: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
@@ -969,118 +727,157 @@ var MemoryStorageD1 = class extends storage.MemoryStorage {
969
727
  throw mastraError;
970
728
  }
971
729
  }
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 = [];
730
+ async listMessages(args) {
731
+ const { threadId, resourceId, include, filter, perPage: perPageInput, page = 0, orderBy } = args;
732
+ if (!threadId.trim()) {
733
+ throw new error.MastraError(
734
+ {
735
+ id: "STORAGE_CLOUDFLARE_D1_LIST_MESSAGES_INVALID_THREAD_ID",
736
+ domain: error.ErrorDomain.STORAGE,
737
+ category: error.ErrorCategory.THIRD_PARTY,
738
+ details: { threadId }
739
+ },
740
+ new Error("threadId must be a non-empty string")
741
+ );
742
+ }
743
+ if (page < 0) {
744
+ throw new error.MastraError(
745
+ {
746
+ id: "STORAGE_CLOUDFLARE_D1_LIST_MESSAGES_INVALID_PAGE",
747
+ domain: error.ErrorDomain.STORAGE,
748
+ category: error.ErrorCategory.USER,
749
+ details: { page }
750
+ },
751
+ new Error("page must be >= 0")
752
+ );
753
+ }
754
+ const perPage = storage.normalizePerPage(perPageInput, 40);
755
+ const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
983
756
  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);
757
+ const fullTableName = this.operations.getTableName(storage.TABLE_MESSAGES);
758
+ let query = `
759
+ SELECT id, content, role, type, createdAt, thread_id AS threadId, resourceId
760
+ FROM ${fullTableName}
761
+ WHERE thread_id = ?
762
+ `;
763
+ const queryParams = [threadId];
764
+ if (resourceId) {
765
+ query += ` AND resourceId = ?`;
766
+ queryParams.push(resourceId);
988
767
  }
989
- const countQuery = createSqlBuilder().count().from(fullTableName).where("thread_id = ?", threadId);
990
- if (fromDate) {
991
- countQuery.andWhere("createdAt >= ?", storage.serializeDate(fromDate));
768
+ const dateRange = filter?.dateRange;
769
+ if (dateRange?.start) {
770
+ const startDate = dateRange.start instanceof Date ? storage.serializeDate(dateRange.start) : storage.serializeDate(new Date(dateRange.start));
771
+ query += ` AND createdAt >= ?`;
772
+ queryParams.push(startDate);
992
773
  }
993
- if (toDate) {
994
- countQuery.andWhere("createdAt <= ?", storage.serializeDate(toDate));
774
+ if (dateRange?.end) {
775
+ const endDate = dateRange.end instanceof Date ? storage.serializeDate(dateRange.end) : storage.serializeDate(new Date(dateRange.end));
776
+ query += ` AND createdAt <= ?`;
777
+ queryParams.push(endDate);
995
778
  }
996
- const countResult = await this.operations.executeQuery(countQuery.build());
779
+ const { field, direction } = this.parseOrderBy(orderBy, "ASC");
780
+ query += ` ORDER BY "${field}" ${direction}`;
781
+ if (perPage !== Number.MAX_SAFE_INTEGER) {
782
+ query += ` LIMIT ? OFFSET ?`;
783
+ queryParams.push(perPage, offset);
784
+ }
785
+ const results = await this.operations.executeQuery({ sql: query, params: queryParams });
786
+ const paginatedMessages = (isArrayOfRecords(results) ? results : []).map((message) => {
787
+ const processedMsg = {};
788
+ for (const [key, value] of Object.entries(message)) {
789
+ if (key === `type` && value === `v2`) continue;
790
+ processedMsg[key] = deserializeValue(value);
791
+ }
792
+ return processedMsg;
793
+ });
794
+ const paginatedCount = paginatedMessages.length;
795
+ let countQuery = `SELECT count() as count FROM ${fullTableName} WHERE thread_id = ?`;
796
+ const countParams = [threadId];
797
+ if (resourceId) {
798
+ countQuery += ` AND resourceId = ?`;
799
+ countParams.push(resourceId);
800
+ }
801
+ if (dateRange?.start) {
802
+ const startDate = dateRange.start instanceof Date ? storage.serializeDate(dateRange.start) : storage.serializeDate(new Date(dateRange.start));
803
+ countQuery += ` AND createdAt >= ?`;
804
+ countParams.push(startDate);
805
+ }
806
+ if (dateRange?.end) {
807
+ const endDate = dateRange.end instanceof Date ? storage.serializeDate(dateRange.end) : storage.serializeDate(new Date(dateRange.end));
808
+ countQuery += ` AND createdAt <= ?`;
809
+ countParams.push(endDate);
810
+ }
811
+ const countResult = await this.operations.executeQuery({ sql: countQuery, params: countParams });
997
812
  const total = Number(countResult[0]?.count ?? 0);
998
- if (total === 0 && messages.length === 0) {
813
+ if (total === 0 && paginatedCount === 0 && (!include || include.length === 0)) {
999
814
  return {
1000
815
  messages: [],
1001
816
  total: 0,
1002
817
  page,
1003
- perPage,
818
+ perPage: perPageForResponse,
1004
819
  hasMore: false
1005
820
  };
1006
821
  }
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);
822
+ const messageIds = new Set(paginatedMessages.map((m) => m.id));
823
+ let includeMessages = [];
824
+ if (include && include.length > 0) {
825
+ const includeResult = await this._getIncludedMessages(threadId, include);
826
+ if (Array.isArray(includeResult)) {
827
+ includeMessages = includeResult;
828
+ for (const includeMsg of includeMessages) {
829
+ if (!messageIds.has(includeMsg.id)) {
830
+ paginatedMessages.push(includeMsg);
831
+ messageIds.add(includeMsg.id);
832
+ }
833
+ }
834
+ }
1044
835
  }
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);
836
+ const list = new agent.MessageList().add(paginatedMessages, "memory");
837
+ let finalMessages = list.get.all.db();
838
+ finalMessages = finalMessages.sort((a, b) => {
839
+ const isDateField = field === "createdAt" || field === "updatedAt";
840
+ const aValue = isDateField ? new Date(a[field]).getTime() : a[field];
841
+ const bValue = isDateField ? new Date(b[field]).getTime() : b[field];
842
+ if (aValue === bValue) {
843
+ return a.id.localeCompare(b.id);
1051
844
  }
1052
- return processedMsg;
845
+ if (typeof aValue === "number" && typeof bValue === "number") {
846
+ return direction === "ASC" ? aValue - bValue : bValue - aValue;
847
+ }
848
+ return direction === "ASC" ? String(aValue).localeCompare(String(bValue)) : String(bValue).localeCompare(String(aValue));
1053
849
  });
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());
850
+ const returnedThreadMessageIds = new Set(finalMessages.filter((m) => m.threadId === threadId).map((m) => m.id));
851
+ const allThreadMessagesReturned = returnedThreadMessageIds.size >= total;
852
+ const hasMore = perPageInput === false ? false : allThreadMessagesReturned ? false : offset + paginatedCount < total;
1059
853
  return {
1060
- messages,
854
+ messages: finalMessages,
1061
855
  total,
1062
856
  page,
1063
- perPage,
1064
- hasMore: selectBy?.last ? false : page * perPage + messages.length < total
857
+ perPage: perPageForResponse,
858
+ hasMore
1065
859
  };
1066
860
  } catch (error$1) {
1067
861
  const mastraError = new error.MastraError(
1068
862
  {
1069
- id: "CLOUDFLARE_D1_STORAGE_GET_MESSAGES_PAGINATED_ERROR",
863
+ id: "CLOUDFLARE_D1_STORAGE_LIST_MESSAGES_ERROR",
1070
864
  domain: error.ErrorDomain.STORAGE,
1071
865
  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 ?? "" }
866
+ text: `Failed to list messages for thread ${threadId}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
867
+ details: {
868
+ threadId,
869
+ resourceId: resourceId ?? ""
870
+ }
1074
871
  },
1075
872
  error$1
1076
873
  );
1077
- this.logger?.error(mastraError.toString());
1078
- this.logger?.trackException(mastraError);
874
+ this.logger?.error?.(mastraError.toString());
875
+ this.logger?.trackException?.(mastraError);
1079
876
  return {
1080
877
  messages: [],
1081
878
  total: 0,
1082
879
  page,
1083
- perPage,
880
+ perPage: perPageForResponse,
1084
881
  hasMore: false
1085
882
  };
1086
883
  }
@@ -1581,7 +1378,7 @@ function transformScoreRow(row) {
1581
1378
  deserialized.analyzeStepResult = storage.safelyParseJSON(row.analyzeStepResult);
1582
1379
  deserialized.metadata = storage.safelyParseJSON(row.metadata);
1583
1380
  deserialized.additionalContext = storage.safelyParseJSON(row.additionalContext);
1584
- deserialized.runtimeContext = storage.safelyParseJSON(row.runtimeContext);
1381
+ deserialized.requestContext = storage.safelyParseJSON(row.requestContext);
1585
1382
  deserialized.entity = storage.safelyParseJSON(row.entity);
1586
1383
  deserialized.createdAt = row.createdAtZ || row.createdAt;
1587
1384
  deserialized.updatedAt = row.updatedAtZ || row.updatedAt;
@@ -1615,12 +1412,25 @@ var ScoresStorageD1 = class extends storage.ScoresStorage {
1615
1412
  }
1616
1413
  }
1617
1414
  async saveScore(score) {
1415
+ let parsedScore;
1416
+ try {
1417
+ parsedScore = evals.saveScorePayloadSchema.parse(score);
1418
+ } catch (error$1) {
1419
+ throw new error.MastraError(
1420
+ {
1421
+ id: "CLOUDFLARE_D1_STORE_SCORES_SAVE_SCORE_FAILED_INVALID_SCORE_PAYLOAD",
1422
+ domain: error.ErrorDomain.STORAGE,
1423
+ category: error.ErrorCategory.USER,
1424
+ details: { scoreId: score.id }
1425
+ },
1426
+ error$1
1427
+ );
1428
+ }
1618
1429
  try {
1619
1430
  const id = crypto.randomUUID();
1620
1431
  const fullTableName = this.operations.getTableName(storage.TABLE_SCORERS);
1621
- const { input, ...rest } = score;
1622
1432
  const serializedRecord = {};
1623
- for (const [key, value] of Object.entries(rest)) {
1433
+ for (const [key, value] of Object.entries(parsedScore)) {
1624
1434
  if (value !== null && value !== void 0) {
1625
1435
  if (typeof value === "object") {
1626
1436
  serializedRecord[key] = JSON.stringify(value);
@@ -1632,7 +1442,6 @@ var ScoresStorageD1 = class extends storage.ScoresStorage {
1632
1442
  }
1633
1443
  }
1634
1444
  serializedRecord.id = id;
1635
- serializedRecord.input = JSON.stringify(input);
1636
1445
  serializedRecord.createdAt = (/* @__PURE__ */ new Date()).toISOString();
1637
1446
  serializedRecord.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1638
1447
  const columns = Object.keys(serializedRecord);
@@ -1653,7 +1462,7 @@ var ScoresStorageD1 = class extends storage.ScoresStorage {
1653
1462
  );
1654
1463
  }
1655
1464
  }
1656
- async getScoresByScorerId({
1465
+ async listScoresByScorerId({
1657
1466
  scorerId,
1658
1467
  entityId,
1659
1468
  entityType,
@@ -1661,6 +1470,9 @@ var ScoresStorageD1 = class extends storage.ScoresStorage {
1661
1470
  pagination
1662
1471
  }) {
1663
1472
  try {
1473
+ const { page, perPage: perPageInput } = pagination;
1474
+ const perPage = storage.normalizePerPage(perPageInput, 100);
1475
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
1664
1476
  const fullTableName = this.operations.getTableName(storage.TABLE_SCORERS);
1665
1477
  const countQuery = createSqlBuilder().count().from(fullTableName).where("scorerId = ?", scorerId);
1666
1478
  if (entityId) {
@@ -1678,13 +1490,15 @@ var ScoresStorageD1 = class extends storage.ScoresStorage {
1678
1490
  return {
1679
1491
  pagination: {
1680
1492
  total: 0,
1681
- page: pagination.page,
1682
- perPage: pagination.perPage,
1493
+ page,
1494
+ perPage: perPageForResponse,
1683
1495
  hasMore: false
1684
1496
  },
1685
1497
  scores: []
1686
1498
  };
1687
1499
  }
1500
+ const end = perPageInput === false ? total : start + perPage;
1501
+ const limitValue = perPageInput === false ? total : perPage;
1688
1502
  const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("scorerId = ?", scorerId);
1689
1503
  if (entityId) {
1690
1504
  selectQuery.andWhere("entityId = ?", entityId);
@@ -1695,16 +1509,16 @@ var ScoresStorageD1 = class extends storage.ScoresStorage {
1695
1509
  if (source) {
1696
1510
  selectQuery.andWhere("source = ?", source);
1697
1511
  }
1698
- selectQuery.limit(pagination.perPage).offset(pagination.page * pagination.perPage);
1512
+ selectQuery.limit(limitValue).offset(start);
1699
1513
  const { sql, params } = selectQuery.build();
1700
1514
  const results = await this.operations.executeQuery({ sql, params });
1701
1515
  const scores = Array.isArray(results) ? results.map(transformScoreRow) : [];
1702
1516
  return {
1703
1517
  pagination: {
1704
1518
  total,
1705
- page: pagination.page,
1706
- perPage: pagination.perPage,
1707
- hasMore: total > (pagination.page + 1) * pagination.perPage
1519
+ page,
1520
+ perPage: perPageForResponse,
1521
+ hasMore: end < total
1708
1522
  },
1709
1523
  scores
1710
1524
  };
@@ -1719,11 +1533,14 @@ var ScoresStorageD1 = class extends storage.ScoresStorage {
1719
1533
  );
1720
1534
  }
1721
1535
  }
1722
- async getScoresByRunId({
1536
+ async listScoresByRunId({
1723
1537
  runId,
1724
1538
  pagination
1725
1539
  }) {
1726
1540
  try {
1541
+ const { page, perPage: perPageInput } = pagination;
1542
+ const perPage = storage.normalizePerPage(perPageInput, 100);
1543
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
1727
1544
  const fullTableName = this.operations.getTableName(storage.TABLE_SCORERS);
1728
1545
  const countQuery = createSqlBuilder().count().from(fullTableName).where("runId = ?", runId);
1729
1546
  const countResult = await this.operations.executeQuery(countQuery.build());
@@ -1732,23 +1549,25 @@ var ScoresStorageD1 = class extends storage.ScoresStorage {
1732
1549
  return {
1733
1550
  pagination: {
1734
1551
  total: 0,
1735
- page: pagination.page,
1736
- perPage: pagination.perPage,
1552
+ page,
1553
+ perPage: perPageForResponse,
1737
1554
  hasMore: false
1738
1555
  },
1739
1556
  scores: []
1740
1557
  };
1741
1558
  }
1742
- const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("runId = ?", runId).limit(pagination.perPage).offset(pagination.page * pagination.perPage);
1559
+ const end = perPageInput === false ? total : start + perPage;
1560
+ const limitValue = perPageInput === false ? total : perPage;
1561
+ const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("runId = ?", runId).limit(limitValue).offset(start);
1743
1562
  const { sql, params } = selectQuery.build();
1744
1563
  const results = await this.operations.executeQuery({ sql, params });
1745
1564
  const scores = Array.isArray(results) ? results.map(transformScoreRow) : [];
1746
1565
  return {
1747
1566
  pagination: {
1748
1567
  total,
1749
- page: pagination.page,
1750
- perPage: pagination.perPage,
1751
- hasMore: total > (pagination.page + 1) * pagination.perPage
1568
+ page,
1569
+ perPage: perPageForResponse,
1570
+ hasMore: end < total
1752
1571
  },
1753
1572
  scores
1754
1573
  };
@@ -1763,12 +1582,15 @@ var ScoresStorageD1 = class extends storage.ScoresStorage {
1763
1582
  );
1764
1583
  }
1765
1584
  }
1766
- async getScoresByEntityId({
1585
+ async listScoresByEntityId({
1767
1586
  entityId,
1768
1587
  entityType,
1769
1588
  pagination
1770
1589
  }) {
1771
1590
  try {
1591
+ const { page, perPage: perPageInput } = pagination;
1592
+ const perPage = storage.normalizePerPage(perPageInput, 100);
1593
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
1772
1594
  const fullTableName = this.operations.getTableName(storage.TABLE_SCORERS);
1773
1595
  const countQuery = createSqlBuilder().count().from(fullTableName).where("entityId = ?", entityId).andWhere("entityType = ?", entityType);
1774
1596
  const countResult = await this.operations.executeQuery(countQuery.build());
@@ -1777,23 +1599,25 @@ var ScoresStorageD1 = class extends storage.ScoresStorage {
1777
1599
  return {
1778
1600
  pagination: {
1779
1601
  total: 0,
1780
- page: pagination.page,
1781
- perPage: pagination.perPage,
1602
+ page,
1603
+ perPage: perPageForResponse,
1782
1604
  hasMore: false
1783
1605
  },
1784
1606
  scores: []
1785
1607
  };
1786
1608
  }
1787
- const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("entityId = ?", entityId).andWhere("entityType = ?", entityType).limit(pagination.perPage).offset(pagination.page * pagination.perPage);
1609
+ const end = perPageInput === false ? total : start + perPage;
1610
+ const limitValue = perPageInput === false ? total : perPage;
1611
+ const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("entityId = ?", entityId).andWhere("entityType = ?", entityType).limit(limitValue).offset(start);
1788
1612
  const { sql, params } = selectQuery.build();
1789
1613
  const results = await this.operations.executeQuery({ sql, params });
1790
1614
  const scores = Array.isArray(results) ? results.map(transformScoreRow) : [];
1791
1615
  return {
1792
1616
  pagination: {
1793
1617
  total,
1794
- page: pagination.page,
1795
- perPage: pagination.perPage,
1796
- hasMore: total > (pagination.page + 1) * pagination.perPage
1618
+ page,
1619
+ perPage: perPageForResponse,
1620
+ hasMore: end < total
1797
1621
  },
1798
1622
  scores
1799
1623
  };
@@ -1808,128 +1632,56 @@ var ScoresStorageD1 = class extends storage.ScoresStorage {
1808
1632
  );
1809
1633
  }
1810
1634
  }
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);
1635
+ async listScoresBySpan({
1636
+ traceId,
1637
+ spanId,
1638
+ pagination
1639
+ }) {
1858
1640
  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);
1641
+ const { page, perPage: perPageInput } = pagination;
1642
+ const perPage = storage.normalizePerPage(perPageInput, 100);
1643
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
1644
+ const fullTableName = this.operations.getTableName(storage.TABLE_SCORERS);
1645
+ const countQuery = createSqlBuilder().count().from(fullTableName).where("traceId = ?", traceId).andWhere("spanId = ?", spanId);
1889
1646
  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
- ) : [];
1647
+ const total = Array.isArray(countResult) ? Number(countResult?.[0]?.count ?? 0) : Number(countResult?.count ?? 0);
1648
+ if (total === 0) {
1649
+ return {
1650
+ pagination: {
1651
+ total: 0,
1652
+ page,
1653
+ perPage: perPageForResponse,
1654
+ hasMore: false
1655
+ },
1656
+ scores: []
1657
+ };
1658
+ }
1659
+ const end = perPageInput === false ? total : start + perPage;
1660
+ const limitValue = perPageInput === false ? total : perPage;
1661
+ const selectQuery = createSqlBuilder().select("*").from(fullTableName).where("traceId = ?", traceId).andWhere("spanId = ?", spanId).orderBy("createdAt", "DESC").limit(limitValue).offset(start);
1662
+ const { sql, params } = selectQuery.build();
1663
+ const results = await this.operations.executeQuery({ sql, params });
1664
+ const scores = Array.isArray(results) ? results.map(transformScoreRow) : [];
1903
1665
  return {
1904
- traces,
1905
- total,
1906
- page,
1907
- perPage,
1908
- hasMore: page * perPage + traces.length < total
1666
+ pagination: {
1667
+ total,
1668
+ page,
1669
+ perPage: perPageForResponse,
1670
+ hasMore: end < total
1671
+ },
1672
+ scores
1909
1673
  };
1910
1674
  } catch (error$1) {
1911
- const mastraError = new error.MastraError(
1675
+ throw new error.MastraError(
1912
1676
  {
1913
- id: "CLOUDFLARE_D1_STORAGE_GET_TRACES_PAGINATED_ERROR",
1677
+ id: "CLOUDFLARE_D1_STORE_SCORES_GET_SCORES_BY_SPAN_FAILED",
1914
1678
  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 ?? "" }
1679
+ category: error.ErrorCategory.THIRD_PARTY
1918
1680
  },
1919
1681
  error$1
1920
1682
  );
1921
- this.logger?.error(mastraError.toString());
1922
- this.logger?.trackException(mastraError);
1923
- return { traces: [], total: 0, page, perPage, hasMore: false };
1924
1683
  }
1925
1684
  }
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
1685
  };
1934
1686
  var WorkflowsStorageD1 = class extends storage.WorkflowsStorage {
1935
1687
  operations;
@@ -1942,7 +1694,7 @@ var WorkflowsStorageD1 = class extends storage.WorkflowsStorage {
1942
1694
  // runId,
1943
1695
  // stepId,
1944
1696
  // result,
1945
- // runtimeContext,
1697
+ // requestContext,
1946
1698
  }) {
1947
1699
  throw new Error("Method not implemented.");
1948
1700
  }
@@ -1956,6 +1708,7 @@ var WorkflowsStorageD1 = class extends storage.WorkflowsStorage {
1956
1708
  async persistWorkflowSnapshot({
1957
1709
  workflowName,
1958
1710
  runId,
1711
+ resourceId,
1959
1712
  snapshot
1960
1713
  }) {
1961
1714
  const fullTableName = this.operations.getTableName(storage.TABLE_WORKFLOW_SNAPSHOT);
@@ -1966,11 +1719,13 @@ var WorkflowsStorageD1 = class extends storage.WorkflowsStorage {
1966
1719
  });
1967
1720
  const persisting = currentSnapshot ? {
1968
1721
  ...currentSnapshot,
1722
+ resourceId,
1969
1723
  snapshot: JSON.stringify(snapshot),
1970
1724
  updatedAt: now
1971
1725
  } : {
1972
1726
  workflow_name: workflowName,
1973
1727
  run_id: runId,
1728
+ resourceId,
1974
1729
  snapshot,
1975
1730
  createdAt: now,
1976
1731
  updatedAt: now
@@ -2043,19 +1798,24 @@ var WorkflowsStorageD1 = class extends storage.WorkflowsStorage {
2043
1798
  resourceId: row.resourceId
2044
1799
  };
2045
1800
  }
2046
- async getWorkflowRuns({
1801
+ async listWorkflowRuns({
2047
1802
  workflowName,
2048
1803
  fromDate,
2049
1804
  toDate,
2050
- limit,
2051
- offset,
2052
- resourceId
1805
+ page,
1806
+ perPage,
1807
+ resourceId,
1808
+ status
2053
1809
  } = {}) {
2054
1810
  const fullTableName = this.operations.getTableName(storage.TABLE_WORKFLOW_SNAPSHOT);
2055
1811
  try {
2056
1812
  const builder = createSqlBuilder().select().from(fullTableName);
2057
1813
  const countBuilder = createSqlBuilder().count().from(fullTableName);
2058
1814
  if (workflowName) builder.whereAnd("workflow_name = ?", workflowName);
1815
+ if (status) {
1816
+ builder.whereAnd("json_extract(snapshot, '$.status') = ?", status);
1817
+ countBuilder.whereAnd("json_extract(snapshot, '$.status') = ?", status);
1818
+ }
2059
1819
  if (resourceId) {
2060
1820
  const hasResourceId = await this.operations.hasColumn(fullTableName, "resourceId");
2061
1821
  if (hasResourceId) {
@@ -2074,11 +1834,14 @@ var WorkflowsStorageD1 = class extends storage.WorkflowsStorage {
2074
1834
  countBuilder.whereAnd("createdAt <= ?", toDate instanceof Date ? toDate.toISOString() : toDate);
2075
1835
  }
2076
1836
  builder.orderBy("createdAt", "DESC");
2077
- if (typeof limit === "number") builder.limit(limit);
2078
- if (typeof offset === "number") builder.offset(offset);
1837
+ if (typeof perPage === "number" && typeof page === "number") {
1838
+ const offset = page * perPage;
1839
+ builder.limit(perPage);
1840
+ builder.offset(offset);
1841
+ }
2079
1842
  const { sql, params } = builder.build();
2080
1843
  let total = 0;
2081
- if (limit !== void 0 && offset !== void 0) {
1844
+ if (perPage !== void 0 && page !== void 0) {
2082
1845
  const { sql: countSql, params: countParams } = countBuilder.build();
2083
1846
  const countResult = await this.operations.executeQuery({
2084
1847
  sql: countSql,
@@ -2093,7 +1856,7 @@ var WorkflowsStorageD1 = class extends storage.WorkflowsStorage {
2093
1856
  } catch (error$1) {
2094
1857
  throw new error.MastraError(
2095
1858
  {
2096
- id: "CLOUDFLARE_D1_STORAGE_GET_WORKFLOW_RUNS_ERROR",
1859
+ id: "CLOUDFLARE_D1_STORAGE_LIST_WORKFLOW_RUNS_ERROR",
2097
1860
  domain: error.ErrorDomain.STORAGE,
2098
1861
  category: error.ErrorCategory.THIRD_PARTY,
2099
1862
  text: `Failed to retrieve workflow runs: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
@@ -2155,7 +1918,7 @@ var D1Store = class extends storage.MastraStorage {
2155
1918
  */
2156
1919
  constructor(config) {
2157
1920
  try {
2158
- super({ name: "D1" });
1921
+ super({ id: config.id, name: "D1" });
2159
1922
  if (config.tablePrefix && !/^[a-zA-Z0-9_]*$/.test(config.tablePrefix)) {
2160
1923
  throw new Error("Invalid tablePrefix: only letters, numbers, and underscores are allowed.");
2161
1924
  }
@@ -2209,12 +1972,6 @@ var D1Store = class extends storage.MastraStorage {
2209
1972
  const scores = new ScoresStorageD1({
2210
1973
  operations
2211
1974
  });
2212
- const legacyEvals = new LegacyEvalsStorageD1({
2213
- operations
2214
- });
2215
- const traces = new TracesStorageD1({
2216
- operations
2217
- });
2218
1975
  const workflows = new WorkflowsStorageD1({
2219
1976
  operations
2220
1977
  });
@@ -2224,8 +1981,6 @@ var D1Store = class extends storage.MastraStorage {
2224
1981
  this.stores = {
2225
1982
  operations,
2226
1983
  scores,
2227
- legacyEvals,
2228
- traces,
2229
1984
  workflows,
2230
1985
  memory
2231
1986
  };
@@ -2236,7 +1991,8 @@ var D1Store = class extends storage.MastraStorage {
2236
1991
  resourceWorkingMemory: true,
2237
1992
  hasColumn: true,
2238
1993
  createTable: true,
2239
- deleteMessages: false
1994
+ deleteMessages: false,
1995
+ listScoresBySpan: true
2240
1996
  };
2241
1997
  }
2242
1998
  async createTable({
@@ -2276,15 +2032,6 @@ var D1Store = class extends storage.MastraStorage {
2276
2032
  async getThreadById({ threadId }) {
2277
2033
  return this.stores.memory.getThreadById({ threadId });
2278
2034
  }
2279
- /**
2280
- * @deprecated use getThreadsByResourceIdPaginated instead
2281
- */
2282
- async getThreadsByResourceId({ resourceId }) {
2283
- return this.stores.memory.getThreadsByResourceId({ resourceId });
2284
- }
2285
- async getThreadsByResourceIdPaginated(args) {
2286
- return this.stores.memory.getThreadsByResourceIdPaginated(args);
2287
- }
2288
2035
  async saveThread({ thread }) {
2289
2036
  return this.stores.memory.saveThread({ thread });
2290
2037
  }
@@ -2301,34 +2048,14 @@ var D1Store = class extends storage.MastraStorage {
2301
2048
  async saveMessages(args) {
2302
2049
  return this.stores.memory.saveMessages(args);
2303
2050
  }
2304
- async getMessages({
2305
- threadId,
2306
- selectBy,
2307
- format
2308
- }) {
2309
- return this.stores.memory.getMessages({ threadId, selectBy, format });
2310
- }
2311
- async getMessagesById({
2312
- messageIds,
2313
- format
2314
- }) {
2315
- return this.stores.memory.getMessagesById({ messageIds, format });
2316
- }
2317
- async getMessagesPaginated({
2318
- threadId,
2319
- selectBy,
2320
- format
2321
- }) {
2322
- return this.stores.memory.getMessagesPaginated({ threadId, selectBy, format });
2323
- }
2324
2051
  async updateWorkflowResults({
2325
2052
  workflowName,
2326
2053
  runId,
2327
2054
  stepId,
2328
2055
  result,
2329
- runtimeContext
2056
+ requestContext
2330
2057
  }) {
2331
- return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, runtimeContext });
2058
+ return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, requestContext });
2332
2059
  }
2333
2060
  async updateWorkflowState({
2334
2061
  workflowName,
@@ -2340,22 +2067,16 @@ var D1Store = class extends storage.MastraStorage {
2340
2067
  async persistWorkflowSnapshot({
2341
2068
  workflowName,
2342
2069
  runId,
2070
+ resourceId,
2343
2071
  snapshot
2344
2072
  }) {
2345
- return this.stores.workflows.persistWorkflowSnapshot({ workflowName, runId, snapshot });
2073
+ return this.stores.workflows.persistWorkflowSnapshot({ workflowName, runId, resourceId, snapshot });
2346
2074
  }
2347
2075
  async loadWorkflowSnapshot(params) {
2348
2076
  return this.stores.workflows.loadWorkflowSnapshot(params);
2349
2077
  }
2350
- async getWorkflowRuns({
2351
- workflowName,
2352
- fromDate,
2353
- toDate,
2354
- limit,
2355
- offset,
2356
- resourceId
2357
- } = {}) {
2358
- return this.stores.workflows.getWorkflowRuns({ workflowName, fromDate, toDate, limit, offset, resourceId });
2078
+ async listWorkflowRuns(args = {}) {
2079
+ return this.stores.workflows.listWorkflowRuns(args);
2359
2080
  }
2360
2081
  async getWorkflowRunById({
2361
2082
  runId,
@@ -2371,24 +2092,6 @@ var D1Store = class extends storage.MastraStorage {
2371
2092
  async batchInsert({ tableName, records }) {
2372
2093
  return this.stores.operations.batchInsert({ tableName, records });
2373
2094
  }
2374
- /**
2375
- * @deprecated use getTracesPaginated instead
2376
- */
2377
- async getTraces(args) {
2378
- return this.stores.traces.getTraces(args);
2379
- }
2380
- async getTracesPaginated(args) {
2381
- return this.stores.traces.getTracesPaginated(args);
2382
- }
2383
- /**
2384
- * @deprecated use getEvals instead
2385
- */
2386
- async getEvalsByAgentName(agentName, type) {
2387
- return this.stores.legacyEvals.getEvalsByAgentName(agentName, type);
2388
- }
2389
- async getEvals(options) {
2390
- return this.stores.legacyEvals.getEvals(options);
2391
- }
2392
2095
  async updateMessages(_args) {
2393
2096
  return this.stores.memory.updateMessages(_args);
2394
2097
  }
@@ -2411,31 +2114,38 @@ var D1Store = class extends storage.MastraStorage {
2411
2114
  async saveScore(_score) {
2412
2115
  return this.stores.scores.saveScore(_score);
2413
2116
  }
2414
- async getScoresByRunId({
2117
+ async listScoresByRunId({
2415
2118
  runId: _runId,
2416
2119
  pagination: _pagination
2417
2120
  }) {
2418
- return this.stores.scores.getScoresByRunId({ runId: _runId, pagination: _pagination });
2121
+ return this.stores.scores.listScoresByRunId({ runId: _runId, pagination: _pagination });
2419
2122
  }
2420
- async getScoresByEntityId({
2123
+ async listScoresByEntityId({
2421
2124
  entityId: _entityId,
2422
2125
  entityType: _entityType,
2423
2126
  pagination: _pagination
2424
2127
  }) {
2425
- return this.stores.scores.getScoresByEntityId({
2128
+ return this.stores.scores.listScoresByEntityId({
2426
2129
  entityId: _entityId,
2427
2130
  entityType: _entityType,
2428
2131
  pagination: _pagination
2429
2132
  });
2430
2133
  }
2431
- async getScoresByScorerId({
2134
+ async listScoresByScorerId({
2432
2135
  scorerId,
2433
2136
  pagination,
2434
2137
  entityId,
2435
2138
  entityType,
2436
2139
  source
2437
2140
  }) {
2438
- return this.stores.scores.getScoresByScorerId({ scorerId, pagination, entityId, entityType, source });
2141
+ return this.stores.scores.listScoresByScorerId({ scorerId, pagination, entityId, entityType, source });
2142
+ }
2143
+ async listScoresBySpan({
2144
+ traceId,
2145
+ spanId,
2146
+ pagination
2147
+ }) {
2148
+ return this.stores.scores.listScoresBySpan({ traceId, spanId, pagination });
2439
2149
  }
2440
2150
  /**
2441
2151
  * Close the database connection