@mastra/cloudflare 0.0.0-toolOptionTypes-20250917085558 → 0.0.0-trace-timeline-update-20251121114225

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,109 +1,10 @@
1
1
  import { MastraError, ErrorCategory, ErrorDomain } from '@mastra/core/error';
2
- import { MastraStorage, TABLE_THREADS, TABLE_MESSAGES, TABLE_WORKFLOW_SNAPSHOT, TABLE_EVALS, TABLE_SCORERS, TABLE_TRACES, StoreOperations, serializeDate, ensureDate, LegacyEvalsStorage, WorkflowsStorage, TracesStorage, MemoryStorage, resolveMessageLimit, TABLE_RESOURCES, ScoresStorage, safelyParseJSON } from '@mastra/core/storage';
2
+ import { MastraStorage, TABLE_THREADS, TABLE_MESSAGES, TABLE_WORKFLOW_SNAPSHOT, TABLE_SCORERS, StoreOperations, TABLE_TRACES, WorkflowsStorage, ensureDate, normalizePerPage, MemoryStorage, calculatePagination, serializeDate, TABLE_RESOURCES, ScoresStorage, safelyParseJSON } from '@mastra/core/storage';
3
3
  import Cloudflare from 'cloudflare';
4
4
  import { MessageList } from '@mastra/core/agent';
5
+ import { saveScorePayloadSchema } from '@mastra/core/evals';
5
6
 
6
7
  // src/storage/index.ts
7
- var LegacyEvalsStorageCloudflare = class extends LegacyEvalsStorage {
8
- operations;
9
- constructor({ operations }) {
10
- super();
11
- this.operations = operations;
12
- }
13
- async getEvalsByAgentName(agentName, type) {
14
- try {
15
- const prefix = this.operations.namespacePrefix ? `${this.operations.namespacePrefix}:` : "";
16
- const keyObjs = await this.operations.listKV(TABLE_EVALS, { prefix: `${prefix}${TABLE_EVALS}` });
17
- const evals = [];
18
- for (const { name: key } of keyObjs) {
19
- const data = await this.operations.getKV(TABLE_EVALS, key);
20
- if (!data) continue;
21
- if (data.agent_name !== agentName) continue;
22
- if (type) {
23
- const isTest = data.test_info !== null && data.test_info !== void 0;
24
- const evalType = isTest ? "test" : "live";
25
- if (evalType !== type) continue;
26
- }
27
- const mappedData = {
28
- ...data,
29
- runId: data.run_id,
30
- testInfo: data.test_info
31
- };
32
- evals.push(mappedData);
33
- }
34
- evals.sort((a, b) => {
35
- const aTime = new Date(a.createdAt || 0).getTime();
36
- const bTime = new Date(b.createdAt || 0).getTime();
37
- return bTime - aTime;
38
- });
39
- return evals;
40
- } catch (error) {
41
- throw new MastraError(
42
- {
43
- id: "CLOUDFLARE_STORAGE_GET_EVALS_BY_AGENT_NAME_FAILED",
44
- domain: ErrorDomain.STORAGE,
45
- category: ErrorCategory.THIRD_PARTY,
46
- text: "Failed to get evals by agent name"
47
- },
48
- error
49
- );
50
- }
51
- }
52
- async getEvals(options) {
53
- try {
54
- const { agentName, type, page = 0, perPage = 100, dateRange } = options;
55
- const prefix = this.operations.namespacePrefix ? `${this.operations.namespacePrefix}:` : "";
56
- const keyObjs = await this.operations.listKV(TABLE_EVALS, { prefix: `${prefix}${TABLE_EVALS}` });
57
- const evals = [];
58
- for (const { name: key } of keyObjs) {
59
- const data = await this.operations.getKV(TABLE_EVALS, key);
60
- if (!data) continue;
61
- if (agentName && data.agent_name !== agentName) continue;
62
- if (type) {
63
- const isTest = data.test_info !== null && data.test_info !== void 0;
64
- const evalType = isTest ? "test" : "live";
65
- if (evalType !== type) continue;
66
- }
67
- if (dateRange?.start || dateRange?.end) {
68
- const evalDate = new Date(data.createdAt || data.created_at || 0);
69
- if (dateRange.start && evalDate < dateRange.start) continue;
70
- if (dateRange.end && evalDate > dateRange.end) continue;
71
- }
72
- const mappedData = {
73
- ...data,
74
- runId: data.run_id,
75
- testInfo: data.test_info
76
- };
77
- evals.push(mappedData);
78
- }
79
- evals.sort((a, b) => {
80
- const aTime = new Date(a.createdAt || 0).getTime();
81
- const bTime = new Date(b.createdAt || 0).getTime();
82
- return bTime - aTime;
83
- });
84
- const start = page * perPage;
85
- const end = start + perPage;
86
- const paginatedEvals = evals.slice(start, end);
87
- return {
88
- page,
89
- perPage,
90
- total: evals.length,
91
- hasMore: start + perPage < evals.length,
92
- evals: paginatedEvals
93
- };
94
- } catch (error) {
95
- throw new MastraError(
96
- {
97
- id: "CLOUDFLARE_STORAGE_GET_EVALS_FAILED",
98
- domain: ErrorDomain.STORAGE,
99
- category: ErrorCategory.THIRD_PARTY,
100
- text: "Failed to get evals"
101
- },
102
- error
103
- );
104
- }
105
- }
106
- };
107
8
  var MemoryStorageCloudflare = class extends MemoryStorage {
108
9
  operations;
109
10
  constructor({ operations }) {
@@ -114,6 +15,17 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
114
15
  if (!metadata) return void 0;
115
16
  return typeof metadata === "string" ? JSON.parse(metadata) : metadata;
116
17
  }
18
+ /**
19
+ * Summarizes message content without exposing raw data (for logging).
20
+ * Returns type, length, and keys only to prevent PII leakage.
21
+ */
22
+ summarizeMessageContent(content) {
23
+ if (!content) return { type: "undefined" };
24
+ if (typeof content === "string") return { type: "string", length: content.length };
25
+ if (Array.isArray(content)) return { type: "array", length: content.length };
26
+ if (typeof content === "object") return { type: "object", keys: Object.keys(content) };
27
+ return { type: typeof content };
28
+ }
117
29
  async getThreadById({ threadId }) {
118
30
  const thread = await this.operations.load({ tableName: TABLE_THREADS, keys: { id: threadId } });
119
31
  if (!thread) return null;
@@ -141,61 +53,23 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
141
53
  return null;
142
54
  }
143
55
  }
144
- async getThreadsByResourceId({ resourceId }) {
145
- try {
146
- const keyList = await this.operations.listKV(TABLE_THREADS);
147
- const threads = await Promise.all(
148
- keyList.map(async (keyObj) => {
149
- try {
150
- const data = await this.operations.getKV(TABLE_THREADS, keyObj.name);
151
- if (!data) return null;
152
- const thread = typeof data === "string" ? JSON.parse(data) : data;
153
- if (!thread || !thread.resourceId || thread.resourceId !== resourceId) return null;
154
- return {
155
- ...thread,
156
- createdAt: ensureDate(thread.createdAt),
157
- updatedAt: ensureDate(thread.updatedAt),
158
- metadata: this.ensureMetadata(thread.metadata)
159
- };
160
- } catch (error) {
161
- const mastraError = new MastraError(
162
- {
163
- id: "CLOUDFLARE_STORAGE_GET_THREADS_BY_RESOURCE_ID_FAILED",
164
- domain: ErrorDomain.STORAGE,
165
- category: ErrorCategory.THIRD_PARTY,
166
- details: {
167
- resourceId
168
- }
169
- },
170
- error
171
- );
172
- this.logger?.trackException(mastraError);
173
- this.logger?.error(mastraError.toString());
174
- return null;
175
- }
176
- })
177
- );
178
- return threads.filter((thread) => thread !== null);
179
- } catch (error) {
180
- const mastraError = new MastraError(
181
- {
182
- id: "CLOUDFLARE_STORAGE_GET_THREADS_BY_RESOURCE_ID_FAILED",
183
- domain: ErrorDomain.STORAGE,
184
- category: ErrorCategory.THIRD_PARTY,
185
- details: {
186
- resourceId
187
- }
188
- },
189
- error
190
- );
191
- this.logger?.trackException(mastraError);
192
- this.logger?.error(mastraError.toString());
193
- return [];
194
- }
195
- }
196
- async getThreadsByResourceIdPaginated(args) {
56
+ async listThreadsByResourceId(args) {
197
57
  try {
198
- const { resourceId, page = 0, perPage = 100 } = args;
58
+ const { resourceId, page = 0, perPage: perPageInput, orderBy } = args;
59
+ const perPage = normalizePerPage(perPageInput, 100);
60
+ if (page < 0) {
61
+ throw new MastraError(
62
+ {
63
+ id: "STORAGE_CLOUDFLARE_LIST_THREADS_BY_RESOURCE_ID_INVALID_PAGE",
64
+ domain: ErrorDomain.STORAGE,
65
+ category: ErrorCategory.USER,
66
+ details: { page }
67
+ },
68
+ new Error("page must be >= 0")
69
+ );
70
+ }
71
+ const { offset, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
72
+ const { field, direction } = this.parseOrderBy(orderBy);
199
73
  const prefix = this.operations.namespacePrefix ? `${this.operations.namespacePrefix}:` : "";
200
74
  const keyObjs = await this.operations.listKV(TABLE_THREADS, { prefix: `${prefix}${TABLE_THREADS}` });
201
75
  const threads = [];
@@ -206,24 +80,23 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
206
80
  threads.push(data);
207
81
  }
208
82
  threads.sort((a, b) => {
209
- const aTime = new Date(a.createdAt || 0).getTime();
210
- const bTime = new Date(b.createdAt || 0).getTime();
211
- return bTime - aTime;
83
+ const aTime = new Date(a[field] || 0).getTime();
84
+ const bTime = new Date(b[field] || 0).getTime();
85
+ return direction === "ASC" ? aTime - bTime : bTime - aTime;
212
86
  });
213
- const start = page * perPage;
214
- const end = start + perPage;
215
- const paginatedThreads = threads.slice(start, end);
87
+ const end = perPageInput === false ? threads.length : offset + perPage;
88
+ const paginatedThreads = threads.slice(offset, end);
216
89
  return {
217
90
  page,
218
- perPage,
91
+ perPage: perPageForResponse,
219
92
  total: threads.length,
220
- hasMore: start + perPage < threads.length,
93
+ hasMore: perPageInput === false ? false : offset + perPage < threads.length,
221
94
  threads: paginatedThreads
222
95
  };
223
96
  } catch (error) {
224
97
  throw new MastraError(
225
98
  {
226
- id: "CLOUDFLARE_STORAGE_GET_THREADS_BY_RESOURCE_ID_PAGINATED_FAILED",
99
+ id: "CLOUDFLARE_STORAGE_LIST_THREADS_BY_RESOURCE_ID_FAILED",
227
100
  domain: ErrorDomain.STORAGE,
228
101
  category: ErrorCategory.THIRD_PARTY,
229
102
  text: "Failed to get threads by resource ID with pagination"
@@ -291,7 +164,7 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
291
164
  return this.operations.getKey(TABLE_MESSAGES, { threadId, id: messageId });
292
165
  } catch (error) {
293
166
  const message = error instanceof Error ? error.message : String(error);
294
- this.logger.error(`Error getting message key for thread ${threadId} and message ${messageId}:`, { message });
167
+ this.logger?.error(`Error getting message key for thread ${threadId} and message ${messageId}:`, { message });
295
168
  throw error;
296
169
  }
297
170
  }
@@ -300,7 +173,7 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
300
173
  return this.operations.getKey(TABLE_MESSAGES, { threadId, id: "messages" });
301
174
  } catch (error) {
302
175
  const message = error instanceof Error ? error.message : String(error);
303
- this.logger.error(`Error getting thread messages key for thread ${threadId}:`, { message });
176
+ this.logger?.error(`Error getting thread messages key for thread ${threadId}:`, { message });
304
177
  throw error;
305
178
  }
306
179
  }
@@ -390,7 +263,7 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
390
263
  });
391
264
  } catch (error) {
392
265
  const message = error instanceof Error ? error.message : String(error);
393
- this.logger.error(`Error updating sorted order for key ${orderKey}:`, { message });
266
+ this.logger?.error(`Error updating sorted order for key ${orderKey}:`, { message });
394
267
  throw error;
395
268
  } finally {
396
269
  if (this.updateQueue.get(orderKey) === nextPromise) {
@@ -408,7 +281,7 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
408
281
  const arr = JSON.parse(typeof raw === "string" ? raw : JSON.stringify(raw));
409
282
  return Array.isArray(arr) ? arr : [];
410
283
  } catch (e) {
411
- this.logger.error(`Error parsing order data for key ${orderKey}:`, { e });
284
+ this.logger?.error(`Error parsing order data for key ${orderKey}:`, { e });
412
285
  return [];
413
286
  }
414
287
  }
@@ -439,8 +312,8 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
439
312
  }
440
313
  }
441
314
  async saveMessages(args) {
442
- const { messages, format = "v1" } = args;
443
- if (!Array.isArray(messages) || messages.length === 0) return [];
315
+ const { messages } = args;
316
+ if (!Array.isArray(messages) || messages.length === 0) return { messages: [] };
444
317
  try {
445
318
  const validatedMessages = messages.map((message, index) => {
446
319
  const errors = [];
@@ -463,9 +336,11 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
463
336
  const messageMigrationTasks = [];
464
337
  for (const message of validatedMessages) {
465
338
  const existingMessage = await this.findMessageInAnyThread(message.id);
466
- console.log(`Checking message ${message.id}: existing=${existingMessage?.threadId}, new=${message.threadId}`);
339
+ this.logger?.debug(
340
+ `Checking message ${message.id}: existing=${existingMessage?.threadId}, new=${message.threadId}`
341
+ );
467
342
  if (existingMessage && existingMessage.threadId && existingMessage.threadId !== message.threadId) {
468
- console.log(`Migrating message ${message.id} from ${existingMessage.threadId} to ${message.threadId}`);
343
+ this.logger?.debug(`Migrating message ${message.id} from ${existingMessage.threadId} to ${message.threadId}`);
469
344
  messageMigrationTasks.push(this.migrateMessage(message.id, existingMessage.threadId, message.threadId));
470
345
  }
471
346
  }
@@ -494,10 +369,8 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
494
369
  ...cleanMessage,
495
370
  createdAt: serializeDate(cleanMessage.createdAt)
496
371
  };
497
- console.log(`Saving message ${message.id} with content:`, {
498
- content: serializedMessage.content,
499
- contentType: typeof serializedMessage.content,
500
- isArray: Array.isArray(serializedMessage.content)
372
+ this.logger?.debug(`Saving message ${message.id}`, {
373
+ contentSummary: this.summarizeMessageContent(serializedMessage.content)
501
374
  });
502
375
  await this.operations.putKV({ tableName: TABLE_MESSAGES, key, value: serializedMessage });
503
376
  })
@@ -533,8 +406,7 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
533
406
  ({ _index, ...message }) => ({ ...message, type: message.type !== "v2" ? message.type : void 0 })
534
407
  );
535
408
  const list = new MessageList().add(prepared, "memory");
536
- if (format === `v2`) return list.get.all.v2();
537
- return list.get.all.v1();
409
+ return { messages: list.get.all.db() };
538
410
  } catch (error) {
539
411
  throw new MastraError(
540
412
  {
@@ -597,7 +469,7 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
597
469
  const latestIds = await this.getLastN(threadMessagesKey, limit);
598
470
  latestIds.forEach((id) => messageIds.add(id));
599
471
  } catch {
600
- console.log(`No message order found for thread ${threadId}, skipping latest messages`);
472
+ this.logger?.debug(`No message order found for thread ${threadId}, skipping latest messages`);
601
473
  }
602
474
  }
603
475
  async fetchAndParseMessagesFromMultipleThreads(messageIds, include, targetThreadId) {
@@ -628,111 +500,21 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
628
500
  const data = await this.operations.getKV(TABLE_MESSAGES, key);
629
501
  if (!data) return null;
630
502
  const parsed = typeof data === "string" ? JSON.parse(data) : data;
631
- console.log(`Retrieved message ${id} from thread ${threadId} with content:`, {
632
- content: parsed.content,
633
- contentType: typeof parsed.content,
634
- isArray: Array.isArray(parsed.content)
503
+ this.logger?.debug(`Retrieved message ${id} from thread ${threadId}`, {
504
+ contentSummary: this.summarizeMessageContent(parsed.content)
635
505
  });
636
506
  return parsed;
637
507
  } catch (error) {
638
508
  const message = error instanceof Error ? error.message : String(error);
639
- this.logger.error(`Error retrieving message ${id}:`, { message });
509
+ this.logger?.error(`Error retrieving message ${id}:`, { message });
640
510
  return null;
641
511
  }
642
512
  })
643
513
  );
644
514
  return messages.filter((msg) => msg !== null);
645
515
  }
646
- async getMessages({
647
- threadId,
648
- resourceId,
649
- selectBy,
650
- format
651
- }) {
652
- console.log(`getMessages called with format: ${format}, threadId: ${threadId}`);
653
- const actualFormat = format || "v1";
654
- console.log(`Using format: ${actualFormat}`);
655
- const limit = resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
656
- const messageIds = /* @__PURE__ */ new Set();
657
- if (limit === 0 && !selectBy?.include?.length) return [];
658
- try {
659
- if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
660
- await Promise.all([
661
- selectBy?.include?.length ? this.getIncludedMessagesWithContext(threadId, selectBy.include, messageIds) : Promise.resolve(),
662
- limit > 0 ? this.getRecentMessages(threadId, limit, messageIds) : Promise.resolve()
663
- ]);
664
- const targetThreadId = selectBy?.include?.length ? void 0 : threadId;
665
- const messages = await this.fetchAndParseMessagesFromMultipleThreads(
666
- Array.from(messageIds),
667
- selectBy?.include,
668
- targetThreadId
669
- );
670
- if (!messages.length) return [];
671
- try {
672
- const threadMessagesKey = this.getThreadMessagesKey(threadId);
673
- const messageOrder = await this.getFullOrder(threadMessagesKey);
674
- const orderMap = new Map(messageOrder.map((id, index) => [id, index]));
675
- messages.sort((a, b) => {
676
- const indexA = orderMap.get(a.id);
677
- const indexB = orderMap.get(b.id);
678
- if (indexA !== void 0 && indexB !== void 0) return orderMap.get(a.id) - orderMap.get(b.id);
679
- return new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime();
680
- });
681
- } catch (error) {
682
- const mastraError = new MastraError(
683
- {
684
- id: "CLOUDFLARE_STORAGE_SORT_MESSAGES_FAILED",
685
- domain: ErrorDomain.STORAGE,
686
- category: ErrorCategory.THIRD_PARTY,
687
- text: `Error sorting messages for thread ${threadId} falling back to creation time`,
688
- details: {
689
- threadId
690
- }
691
- },
692
- error
693
- );
694
- this.logger?.trackException(mastraError);
695
- this.logger?.error(mastraError.toString());
696
- messages.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
697
- }
698
- const prepared = messages.map(({ _index, ...message }) => ({
699
- ...message,
700
- type: message.type === `v2` ? void 0 : message.type,
701
- createdAt: ensureDate(message.createdAt)
702
- }));
703
- if (actualFormat === `v1`) {
704
- console.log(`Processing ${prepared.length} messages for v1 format - returning directly without MessageList`);
705
- return prepared.map((msg) => ({
706
- ...msg,
707
- createdAt: new Date(msg.createdAt)
708
- }));
709
- }
710
- const list = new MessageList({ threadId, resourceId }).add(prepared, "memory");
711
- return list.get.all.v2();
712
- } catch (error) {
713
- const mastraError = new MastraError(
714
- {
715
- id: "CLOUDFLARE_STORAGE_GET_MESSAGES_FAILED",
716
- domain: ErrorDomain.STORAGE,
717
- category: ErrorCategory.THIRD_PARTY,
718
- text: `Error retrieving messages for thread ${threadId}`,
719
- details: {
720
- threadId,
721
- resourceId: resourceId ?? ""
722
- }
723
- },
724
- error
725
- );
726
- this.logger?.trackException(mastraError);
727
- this.logger?.error(mastraError.toString());
728
- return [];
729
- }
730
- }
731
- async getMessagesById({
732
- messageIds,
733
- format
734
- }) {
735
- if (messageIds.length === 0) return [];
516
+ async listMessagesById({ messageIds }) {
517
+ if (messageIds.length === 0) return { messages: [] };
736
518
  try {
737
519
  const messages = (await Promise.all(messageIds.map((id) => this.findMessageInAnyThread(id)))).filter(
738
520
  (result) => !!result
@@ -743,12 +525,11 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
743
525
  createdAt: ensureDate(message.createdAt)
744
526
  }));
745
527
  const list = new MessageList().add(prepared, "memory");
746
- if (format === `v1`) return list.get.all.v1();
747
- return list.get.all.v2();
528
+ return { messages: list.get.all.db() };
748
529
  } catch (error) {
749
530
  const mastraError = new MastraError(
750
531
  {
751
- id: "CLOUDFLARE_STORAGE_GET_MESSAGES_BY_ID_FAILED",
532
+ id: "CLOUDFLARE_STORAGE_LIST_MESSAGES_BY_ID_FAILED",
752
533
  domain: ErrorDomain.STORAGE,
753
534
  category: ErrorCategory.THIRD_PARTY,
754
535
  text: `Error retrieving messages by ID`,
@@ -760,42 +541,202 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
760
541
  );
761
542
  this.logger?.trackException(mastraError);
762
543
  this.logger?.error(mastraError.toString());
763
- return [];
544
+ return { messages: [] };
764
545
  }
765
546
  }
766
- async getMessagesPaginated(args) {
767
- const { threadId, resourceId, selectBy, format = "v1" } = args;
768
- const { page = 0, perPage = 100 } = selectBy?.pagination || {};
547
+ async listMessages(args) {
548
+ const { threadId, resourceId, include, filter, perPage: perPageInput, page = 0, orderBy } = args;
549
+ if (!threadId.trim()) {
550
+ throw new MastraError(
551
+ {
552
+ id: "STORAGE_CLOUDFLARE_LIST_MESSAGES_INVALID_THREAD_ID",
553
+ domain: ErrorDomain.STORAGE,
554
+ category: ErrorCategory.THIRD_PARTY,
555
+ details: { threadId }
556
+ },
557
+ new Error("threadId must be a non-empty string")
558
+ );
559
+ }
560
+ const perPage = normalizePerPage(perPageInput, 40);
561
+ const { offset, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
769
562
  try {
770
- if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
771
- const messages = format === "v2" ? await this.getMessages({ threadId, selectBy, format: "v2" }) : await this.getMessages({ threadId, selectBy, format: "v1" });
563
+ if (page < 0) {
564
+ throw new MastraError(
565
+ {
566
+ id: "STORAGE_CLOUDFLARE_LIST_MESSAGES_INVALID_PAGE",
567
+ domain: ErrorDomain.STORAGE,
568
+ category: ErrorCategory.USER,
569
+ details: { page }
570
+ },
571
+ new Error("page must be >= 0")
572
+ );
573
+ }
574
+ const { field, direction } = this.parseOrderBy(orderBy, "ASC");
575
+ const messageIds = /* @__PURE__ */ new Set();
576
+ const hasFilters = !!resourceId || !!filter?.dateRange;
577
+ if (hasFilters || perPage === Number.MAX_SAFE_INTEGER) {
578
+ try {
579
+ const threadMessagesKey = this.getThreadMessagesKey(threadId);
580
+ const allIds = await this.getFullOrder(threadMessagesKey);
581
+ allIds.forEach((id) => messageIds.add(id));
582
+ } catch {
583
+ }
584
+ } else {
585
+ if (perPage > 0) {
586
+ try {
587
+ const threadMessagesKey = this.getThreadMessagesKey(threadId);
588
+ const fullOrder = await this.getFullOrder(threadMessagesKey);
589
+ const totalMessages = fullOrder.length;
590
+ let start;
591
+ let end;
592
+ if (direction === "ASC") {
593
+ start = offset;
594
+ end = Math.min(offset + perPage - 1, totalMessages - 1);
595
+ } else {
596
+ start = Math.max(totalMessages - offset - perPage, 0);
597
+ end = totalMessages - offset - 1;
598
+ }
599
+ const paginatedIds = await this.getRange(threadMessagesKey, start, end);
600
+ paginatedIds.forEach((id) => messageIds.add(id));
601
+ } catch {
602
+ }
603
+ }
604
+ }
605
+ if (include && include.length > 0) {
606
+ await this.getIncludedMessagesWithContext(threadId, include, messageIds);
607
+ }
608
+ const messages = await this.fetchAndParseMessagesFromMultipleThreads(
609
+ Array.from(messageIds),
610
+ include,
611
+ include && include.length > 0 ? void 0 : threadId
612
+ );
772
613
  let filteredMessages = messages;
773
- if (selectBy?.pagination?.dateRange) {
774
- const { start: dateStart, end: dateEnd } = selectBy.pagination.dateRange;
775
- filteredMessages = messages.filter((message) => {
776
- const messageDate = new Date(message.createdAt);
777
- if (dateStart && messageDate < dateStart) return false;
778
- if (dateEnd && messageDate > dateEnd) return false;
614
+ if (resourceId) {
615
+ filteredMessages = filteredMessages.filter((msg) => msg.resourceId === resourceId);
616
+ }
617
+ const dateRange = filter?.dateRange;
618
+ if (dateRange) {
619
+ filteredMessages = filteredMessages.filter((msg) => {
620
+ const messageDate = new Date(msg.createdAt);
621
+ if (dateRange.start && messageDate < new Date(dateRange.start)) return false;
622
+ if (dateRange.end && messageDate > new Date(dateRange.end)) return false;
779
623
  return true;
780
624
  });
781
625
  }
782
- const start = page * perPage;
783
- const end = start + perPage;
784
- const paginatedMessages = filteredMessages.slice(start, end);
626
+ let total;
627
+ if (hasFilters) {
628
+ total = filteredMessages.length;
629
+ } else {
630
+ try {
631
+ const threadMessagesKey = this.getThreadMessagesKey(threadId);
632
+ const fullOrder = await this.getFullOrder(threadMessagesKey);
633
+ total = fullOrder.length;
634
+ } catch {
635
+ total = filteredMessages.length;
636
+ }
637
+ }
638
+ if (perPage === 0 && (!include || include.length === 0)) {
639
+ return {
640
+ messages: [],
641
+ total,
642
+ page,
643
+ perPage: perPageForResponse,
644
+ hasMore: offset < total
645
+ };
646
+ }
647
+ if (hasFilters && perPage !== Number.MAX_SAFE_INTEGER && perPage > 0) {
648
+ if (direction === "ASC") {
649
+ filteredMessages = filteredMessages.slice(offset, offset + perPage);
650
+ } else {
651
+ const start = Math.max(filteredMessages.length - offset - perPage, 0);
652
+ const end = filteredMessages.length - offset;
653
+ filteredMessages = filteredMessages.slice(start, end);
654
+ }
655
+ }
656
+ const paginatedCount = hasFilters && perPage !== Number.MAX_SAFE_INTEGER && perPage > 0 ? filteredMessages.length : filteredMessages.length;
657
+ try {
658
+ const threadMessagesKey = this.getThreadMessagesKey(threadId);
659
+ const messageOrder = await this.getFullOrder(threadMessagesKey);
660
+ const orderMap = new Map(messageOrder.map((id, index) => [id, index]));
661
+ filteredMessages.sort((a, b) => {
662
+ const indexA = orderMap.get(a.id);
663
+ const indexB = orderMap.get(b.id);
664
+ if (indexA !== void 0 && indexB !== void 0) {
665
+ return direction === "ASC" ? indexA - indexB : indexB - indexA;
666
+ }
667
+ const timeA = new Date(a.createdAt).getTime();
668
+ const timeB = new Date(b.createdAt).getTime();
669
+ const timeDiff = direction === "ASC" ? timeA - timeB : timeB - timeA;
670
+ if (timeDiff === 0) {
671
+ return a.id.localeCompare(b.id);
672
+ }
673
+ return timeDiff;
674
+ });
675
+ } catch {
676
+ filteredMessages.sort((a, b) => {
677
+ const timeA = new Date(a.createdAt).getTime();
678
+ const timeB = new Date(b.createdAt).getTime();
679
+ const timeDiff = direction === "ASC" ? timeA - timeB : timeB - timeA;
680
+ if (timeDiff === 0) {
681
+ return a.id.localeCompare(b.id);
682
+ }
683
+ return timeDiff;
684
+ });
685
+ }
686
+ if (total === 0 && filteredMessages.length === 0 && (!include || include.length === 0)) {
687
+ return {
688
+ messages: [],
689
+ total: 0,
690
+ page,
691
+ perPage: perPageForResponse,
692
+ hasMore: false
693
+ };
694
+ }
695
+ const prepared = filteredMessages.map(({ _index, ...message }) => ({
696
+ ...message,
697
+ type: message.type !== "v2" ? message.type : void 0,
698
+ createdAt: ensureDate(message.createdAt)
699
+ }));
700
+ const list = new MessageList({ threadId, resourceId }).add(prepared, "memory");
701
+ let finalMessages = list.get.all.db();
702
+ finalMessages = finalMessages.sort((a, b) => {
703
+ const isDateField = field === "createdAt" || field === "updatedAt";
704
+ const aVal = isDateField ? new Date(a[field]).getTime() : a[field];
705
+ const bVal = isDateField ? new Date(b[field]).getTime() : b[field];
706
+ if (aVal == null && bVal == null) return a.id.localeCompare(b.id);
707
+ if (aVal == null) return 1;
708
+ if (bVal == null) return -1;
709
+ if (typeof aVal === "number" && typeof bVal === "number") {
710
+ const cmp2 = direction === "ASC" ? aVal - bVal : bVal - aVal;
711
+ return cmp2 !== 0 ? cmp2 : a.id.localeCompare(b.id);
712
+ }
713
+ const cmp = direction === "ASC" ? String(aVal).localeCompare(String(bVal)) : String(bVal).localeCompare(String(aVal));
714
+ return cmp !== 0 ? cmp : a.id.localeCompare(b.id);
715
+ });
716
+ const returnedThreadMessageIds = new Set(finalMessages.filter((m) => m.threadId === threadId).map((m) => m.id));
717
+ const allThreadMessagesReturned = returnedThreadMessageIds.size >= total;
718
+ let hasMore;
719
+ if (perPageInput === false || allThreadMessagesReturned) {
720
+ hasMore = false;
721
+ } else if (direction === "ASC") {
722
+ hasMore = offset + paginatedCount < total;
723
+ } else {
724
+ hasMore = total - offset - perPage > 0;
725
+ }
785
726
  return {
727
+ messages: finalMessages,
728
+ total,
786
729
  page,
787
- perPage,
788
- total: filteredMessages.length,
789
- hasMore: start + perPage < filteredMessages.length,
790
- messages: paginatedMessages
730
+ perPage: perPageForResponse,
731
+ hasMore
791
732
  };
792
733
  } catch (error) {
793
734
  const mastraError = new MastraError(
794
735
  {
795
- id: "CLOUDFLARE_STORAGE_GET_MESSAGES_PAGINATED_FAILED",
736
+ id: "CLOUDFLARE_STORAGE_LIST_MESSAGES_FAILED",
796
737
  domain: ErrorDomain.STORAGE,
797
738
  category: ErrorCategory.THIRD_PARTY,
798
- text: "Failed to get messages with pagination",
739
+ text: `Failed to list messages for thread ${threadId}: ${error instanceof Error ? error.message : String(error)}`,
799
740
  details: {
800
741
  threadId,
801
742
  resourceId: resourceId ?? ""
@@ -803,9 +744,15 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
803
744
  },
804
745
  error
805
746
  );
806
- this.logger?.trackException?.(mastraError);
807
747
  this.logger?.error?.(mastraError.toString());
808
- return { messages: [], total: 0, page, perPage: perPage || 40, hasMore: false };
748
+ this.logger?.trackException?.(mastraError);
749
+ return {
750
+ messages: [],
751
+ total: 0,
752
+ page,
753
+ perPage: perPageForResponse,
754
+ hasMore: false
755
+ };
809
756
  }
810
757
  }
811
758
  async updateMessages(args) {
@@ -1091,10 +1038,6 @@ var StoreOperationsCloudflare = class extends StoreOperations {
1091
1038
  case TABLE_TRACES:
1092
1039
  if (!record.id) throw new Error("Trace ID is required");
1093
1040
  return `${prefix}${tableName}:${record.id}`;
1094
- case TABLE_EVALS:
1095
- const evalId = record.id || record.run_id;
1096
- if (!evalId) throw new Error("Eval ID or run_id is required");
1097
- return `${prefix}${tableName}:${evalId}`;
1098
1041
  case TABLE_SCORERS:
1099
1042
  if (!record.id) throw new Error("Score ID is required");
1100
1043
  return `${prefix}${tableName}:${record.id}`;
@@ -1334,11 +1277,6 @@ var StoreOperationsCloudflare = class extends StoreOperations {
1334
1277
  throw new Error("Trace record missing required fields");
1335
1278
  }
1336
1279
  break;
1337
- case TABLE_EVALS:
1338
- if (!("agent_name" in recordTyped) || !("run_id" in recordTyped)) {
1339
- throw new Error("Eval record missing required fields");
1340
- }
1341
- break;
1342
1280
  case TABLE_SCORERS:
1343
1281
  if (!("id" in recordTyped) || !("scorerId" in recordTyped)) {
1344
1282
  throw new Error("Score record missing required fields");
@@ -1356,12 +1294,7 @@ var StoreOperationsCloudflare = class extends StoreOperations {
1356
1294
  async insert({ tableName, record }) {
1357
1295
  try {
1358
1296
  const key = this.getKey(tableName, record);
1359
- const processedRecord = {
1360
- ...record,
1361
- createdAt: record.createdAt ? serializeDate(record.createdAt) : void 0,
1362
- updatedAt: record.updatedAt ? serializeDate(record.updatedAt) : void 0,
1363
- metadata: record.metadata ? JSON.stringify(record.metadata) : ""
1364
- };
1297
+ const processedRecord = { ...record };
1365
1298
  await this.validateRecord(processedRecord, tableName);
1366
1299
  await this.putKV({ tableName, key, value: processedRecord });
1367
1300
  } catch (error) {
@@ -1378,22 +1311,12 @@ var StoreOperationsCloudflare = class extends StoreOperations {
1378
1311
  );
1379
1312
  }
1380
1313
  }
1381
- ensureMetadata(metadata) {
1382
- if (!metadata) return {};
1383
- return typeof metadata === "string" ? JSON.parse(metadata) : metadata;
1384
- }
1385
1314
  async load({ tableName, keys }) {
1386
1315
  try {
1387
1316
  const key = this.getKey(tableName, keys);
1388
1317
  const data = await this.getKV(tableName, key);
1389
1318
  if (!data) return null;
1390
- const processed = {
1391
- ...data,
1392
- createdAt: ensureDate(data.createdAt),
1393
- updatedAt: ensureDate(data.updatedAt),
1394
- metadata: this.ensureMetadata(data.metadata)
1395
- };
1396
- return processed;
1319
+ return data;
1397
1320
  } catch (error) {
1398
1321
  const mastraError = new MastraError(
1399
1322
  {
@@ -1417,13 +1340,7 @@ var StoreOperationsCloudflare = class extends StoreOperations {
1417
1340
  await Promise.all(
1418
1341
  input.records.map(async (record) => {
1419
1342
  const key = this.getKey(input.tableName, record);
1420
- const processedRecord = {
1421
- ...record,
1422
- createdAt: record.createdAt ? serializeDate(record.createdAt) : void 0,
1423
- updatedAt: record.updatedAt ? serializeDate(record.updatedAt) : void 0,
1424
- metadata: record.metadata ? JSON.stringify(record.metadata) : void 0
1425
- };
1426
- await this.putKV({ tableName: input.tableName, key, value: processedRecord });
1343
+ await this.putKV({ tableName: input.tableName, key, value: record });
1427
1344
  })
1428
1345
  );
1429
1346
  } catch (error) {
@@ -1581,7 +1498,7 @@ function transformScoreRow(row) {
1581
1498
  deserialized.analyzeStepResult = safelyParseJSON(row.analyzeStepResult);
1582
1499
  deserialized.metadata = safelyParseJSON(row.metadata);
1583
1500
  deserialized.additionalContext = safelyParseJSON(row.additionalContext);
1584
- deserialized.runtimeContext = safelyParseJSON(row.runtimeContext);
1501
+ deserialized.requestContext = safelyParseJSON(row.requestContext);
1585
1502
  deserialized.entity = safelyParseJSON(row.entity);
1586
1503
  return deserialized;
1587
1504
  }
@@ -1614,11 +1531,24 @@ var ScoresStorageCloudflare = class extends ScoresStorage {
1614
1531
  }
1615
1532
  }
1616
1533
  async saveScore(score) {
1534
+ let parsedScore;
1535
+ try {
1536
+ parsedScore = saveScorePayloadSchema.parse(score);
1537
+ } catch (error) {
1538
+ throw new MastraError(
1539
+ {
1540
+ id: "CLOUDFLARE_STORAGE_SAVE_SCORE_FAILED_INVALID_SCORE_PAYLOAD",
1541
+ domain: ErrorDomain.STORAGE,
1542
+ category: ErrorCategory.USER,
1543
+ details: { scoreId: score.id }
1544
+ },
1545
+ error
1546
+ );
1547
+ }
1617
1548
  try {
1618
1549
  const id = crypto.randomUUID();
1619
- const { input, ...rest } = score;
1620
1550
  const serializedRecord = {};
1621
- for (const [key, value] of Object.entries(rest)) {
1551
+ for (const [key, value] of Object.entries(parsedScore)) {
1622
1552
  if (value !== null && value !== void 0) {
1623
1553
  if (typeof value === "object") {
1624
1554
  serializedRecord[key] = JSON.stringify(value);
@@ -1654,7 +1584,7 @@ var ScoresStorageCloudflare = class extends ScoresStorage {
1654
1584
  throw mastraError;
1655
1585
  }
1656
1586
  }
1657
- async getScoresByScorerId({
1587
+ async listScoresByScorerId({
1658
1588
  scorerId,
1659
1589
  entityId,
1660
1590
  entityType,
@@ -1684,15 +1614,17 @@ var ScoresStorageCloudflare = class extends ScoresStorage {
1684
1614
  const dateB = new Date(b.createdAt || 0).getTime();
1685
1615
  return dateB - dateA;
1686
1616
  });
1617
+ const { page, perPage: perPageInput } = pagination;
1618
+ const perPage = normalizePerPage(perPageInput, 100);
1619
+ const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
1687
1620
  const total = scores.length;
1688
- const start = pagination.page * pagination.perPage;
1689
- const end = start + pagination.perPage;
1621
+ const end = perPageInput === false ? scores.length : start + perPage;
1690
1622
  const pagedScores = scores.slice(start, end);
1691
1623
  return {
1692
1624
  pagination: {
1693
1625
  total,
1694
- page: pagination.page,
1695
- perPage: pagination.perPage,
1626
+ page,
1627
+ perPage: perPageForResponse,
1696
1628
  hasMore: end < total
1697
1629
  },
1698
1630
  scores: pagedScores
@@ -1712,7 +1644,7 @@ var ScoresStorageCloudflare = class extends ScoresStorage {
1712
1644
  return { pagination: { total: 0, page: 0, perPage: 100, hasMore: false }, scores: [] };
1713
1645
  }
1714
1646
  }
1715
- async getScoresByRunId({
1647
+ async listScoresByRunId({
1716
1648
  runId,
1717
1649
  pagination
1718
1650
  }) {
@@ -1730,15 +1662,17 @@ var ScoresStorageCloudflare = class extends ScoresStorage {
1730
1662
  const dateB = new Date(b.createdAt || 0).getTime();
1731
1663
  return dateB - dateA;
1732
1664
  });
1665
+ const { page, perPage: perPageInput } = pagination;
1666
+ const perPage = normalizePerPage(perPageInput, 100);
1667
+ const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
1733
1668
  const total = scores.length;
1734
- const start = pagination.page * pagination.perPage;
1735
- const end = start + pagination.perPage;
1669
+ const end = perPageInput === false ? scores.length : start + perPage;
1736
1670
  const pagedScores = scores.slice(start, end);
1737
1671
  return {
1738
1672
  pagination: {
1739
1673
  total,
1740
- page: pagination.page,
1741
- perPage: pagination.perPage,
1674
+ page,
1675
+ perPage: perPageForResponse,
1742
1676
  hasMore: end < total
1743
1677
  },
1744
1678
  scores: pagedScores
@@ -1758,7 +1692,7 @@ var ScoresStorageCloudflare = class extends ScoresStorage {
1758
1692
  return { pagination: { total: 0, page: 0, perPage: 100, hasMore: false }, scores: [] };
1759
1693
  }
1760
1694
  }
1761
- async getScoresByEntityId({
1695
+ async listScoresByEntityId({
1762
1696
  entityId,
1763
1697
  entityType,
1764
1698
  pagination
@@ -1777,15 +1711,17 @@ var ScoresStorageCloudflare = class extends ScoresStorage {
1777
1711
  const dateB = new Date(b.createdAt || 0).getTime();
1778
1712
  return dateB - dateA;
1779
1713
  });
1714
+ const { page, perPage: perPageInput } = pagination;
1715
+ const perPage = normalizePerPage(perPageInput, 100);
1716
+ const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
1780
1717
  const total = scores.length;
1781
- const start = pagination.page * pagination.perPage;
1782
- const end = start + pagination.perPage;
1718
+ const end = perPageInput === false ? scores.length : start + perPage;
1783
1719
  const pagedScores = scores.slice(start, end);
1784
1720
  return {
1785
1721
  pagination: {
1786
1722
  total,
1787
- page: pagination.page,
1788
- perPage: pagination.perPage,
1723
+ page,
1724
+ perPage: perPageForResponse,
1789
1725
  hasMore: end < total
1790
1726
  },
1791
1727
  scores: pagedScores
@@ -1805,126 +1741,55 @@ var ScoresStorageCloudflare = class extends ScoresStorage {
1805
1741
  return { pagination: { total: 0, page: 0, perPage: 100, hasMore: false }, scores: [] };
1806
1742
  }
1807
1743
  }
1808
- };
1809
- var TracesStorageCloudflare = class extends TracesStorage {
1810
- operations;
1811
- constructor({ operations }) {
1812
- super();
1813
- this.operations = operations;
1814
- }
1815
- async getTraces(args) {
1816
- const paginatedArgs = {
1817
- name: args.name,
1818
- scope: args.scope,
1819
- page: args.page,
1820
- perPage: args.perPage,
1821
- attributes: args.attributes,
1822
- filters: args.filters,
1823
- dateRange: args.fromDate || args.toDate ? {
1824
- start: args.fromDate,
1825
- end: args.toDate
1826
- } : void 0
1827
- };
1828
- try {
1829
- const result = await this.getTracesPaginated(paginatedArgs);
1830
- return result.traces;
1831
- } catch (error) {
1832
- throw new MastraError(
1833
- {
1834
- id: "CLOUDFLARE_STORAGE_GET_TRACES_ERROR",
1835
- domain: ErrorDomain.STORAGE,
1836
- category: ErrorCategory.THIRD_PARTY,
1837
- text: `Failed to retrieve traces: ${error instanceof Error ? error.message : String(error)}`,
1838
- details: {
1839
- name: args.name ?? "",
1840
- scope: args.scope ?? ""
1841
- }
1842
- },
1843
- error
1844
- );
1845
- }
1846
- }
1847
- async getTracesPaginated(args) {
1744
+ async listScoresBySpan({
1745
+ traceId,
1746
+ spanId,
1747
+ pagination
1748
+ }) {
1848
1749
  try {
1849
- const { name, scope, attributes, filters, page = 0, perPage = 100, dateRange } = args;
1850
- const prefix = this.operations.namespacePrefix ? `${this.operations.namespacePrefix}:` : "";
1851
- const keyObjs = await this.operations.listKV(TABLE_TRACES, { prefix: `${prefix}${TABLE_TRACES}` });
1852
- const traces = [];
1853
- for (const { name: key } of keyObjs) {
1854
- try {
1855
- const data = await this.operations.getKV(TABLE_TRACES, key);
1856
- if (!data) continue;
1857
- if (name && data.name !== name) continue;
1858
- if (scope && data.scope !== scope) continue;
1859
- if (attributes) {
1860
- const dataAttributes = data.attributes || {};
1861
- let shouldSkip = false;
1862
- for (const [key2, value] of Object.entries(attributes)) {
1863
- if (dataAttributes[key2] !== value) {
1864
- shouldSkip = true;
1865
- break;
1866
- }
1867
- }
1868
- if (shouldSkip) continue;
1869
- }
1870
- if (dateRange?.start || dateRange?.end) {
1871
- const traceDate = new Date(data.createdAt || 0);
1872
- if (dateRange.start && traceDate < dateRange.start) continue;
1873
- if (dateRange.end && traceDate > dateRange.end) continue;
1874
- }
1875
- if (filters) {
1876
- let shouldSkip = false;
1877
- for (const [key2, value] of Object.entries(filters)) {
1878
- if (data[key2] !== value) {
1879
- shouldSkip = true;
1880
- break;
1881
- }
1882
- }
1883
- if (shouldSkip) continue;
1884
- }
1885
- traces.push(data);
1886
- } catch (err) {
1887
- this.logger.error("Failed to parse trace:", { key, error: err });
1750
+ const keys = await this.operations.listKV(TABLE_SCORERS);
1751
+ const scores = [];
1752
+ for (const { name: key } of keys) {
1753
+ const score = await this.operations.getKV(TABLE_SCORERS, key);
1754
+ if (score && score.traceId === traceId && score.spanId === spanId) {
1755
+ scores.push(transformScoreRow(score));
1888
1756
  }
1889
1757
  }
1890
- traces.sort((a, b) => {
1891
- const aTime = new Date(a.createdAt || 0).getTime();
1892
- const bTime = new Date(b.createdAt || 0).getTime();
1893
- return bTime - aTime;
1758
+ scores.sort((a, b) => {
1759
+ const dateA = new Date(a.createdAt || 0).getTime();
1760
+ const dateB = new Date(b.createdAt || 0).getTime();
1761
+ return dateB - dateA;
1894
1762
  });
1895
- const total = traces.length;
1896
- const start = page * perPage;
1897
- const end = start + perPage;
1898
- const pagedTraces = traces.slice(start, end);
1763
+ const { page, perPage: perPageInput } = pagination;
1764
+ const perPage = normalizePerPage(perPageInput, 100);
1765
+ const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
1766
+ const total = scores.length;
1767
+ const end = perPageInput === false ? scores.length : start + perPage;
1768
+ const pagedScores = scores.slice(start, end);
1899
1769
  return {
1900
- traces: pagedTraces,
1901
- total,
1902
- page,
1903
- perPage,
1904
- hasMore: end < total
1770
+ pagination: {
1771
+ total,
1772
+ page,
1773
+ perPage: perPageForResponse,
1774
+ hasMore: end < total
1775
+ },
1776
+ scores: pagedScores
1905
1777
  };
1906
1778
  } catch (error) {
1907
1779
  const mastraError = new MastraError(
1908
1780
  {
1909
- id: "CLOUDFLARE_STORAGE_GET_TRACES_PAGINATED_FAILED",
1781
+ id: "CLOUDFLARE_STORAGE_SCORES_GET_SCORES_BY_SPAN_FAILED",
1910
1782
  domain: ErrorDomain.STORAGE,
1911
1783
  category: ErrorCategory.THIRD_PARTY,
1912
- text: "Error getting traces with pagination"
1784
+ text: `Failed to get scores by span: traceId=${traceId}, spanId=${spanId}`
1913
1785
  },
1914
1786
  error
1915
1787
  );
1916
- this.logger.trackException?.(mastraError);
1917
- this.logger.error(mastraError.toString());
1918
- return { traces: [], total: 0, page: 0, perPage: 100, hasMore: false };
1788
+ this.logger?.trackException(mastraError);
1789
+ this.logger?.error(mastraError.toString());
1790
+ return { pagination: { total: 0, page: 0, perPage: 100, hasMore: false }, scores: [] };
1919
1791
  }
1920
1792
  }
1921
- async batchTraceInsert({ records }) {
1922
- this.logger.debug("Batch inserting traces", { count: records.length });
1923
- await this.operations.batchInsert({
1924
- tableName: TABLE_TRACES,
1925
- records
1926
- });
1927
- }
1928
1793
  };
1929
1794
  var WorkflowsStorageCloudflare = class extends WorkflowsStorage {
1930
1795
  operations;
@@ -1943,7 +1808,7 @@ var WorkflowsStorageCloudflare = class extends WorkflowsStorage {
1943
1808
  // runId,
1944
1809
  // stepId,
1945
1810
  // result,
1946
- // runtimeContext,
1811
+ // requestContext,
1947
1812
  }) {
1948
1813
  throw new Error("Method not implemented.");
1949
1814
  }
@@ -1964,7 +1829,7 @@ var WorkflowsStorageCloudflare = class extends WorkflowsStorage {
1964
1829
  workflow_name: workflowName,
1965
1830
  run_id: runId,
1966
1831
  resourceId,
1967
- snapshot: typeof snapshot === "string" ? snapshot : JSON.stringify(snapshot),
1832
+ snapshot: JSON.stringify(snapshot),
1968
1833
  createdAt: /* @__PURE__ */ new Date(),
1969
1834
  updatedAt: /* @__PURE__ */ new Date()
1970
1835
  }
@@ -2043,15 +1908,29 @@ var WorkflowsStorageCloudflare = class extends WorkflowsStorage {
2043
1908
  if (resourceId) key += `:${resourceId}`;
2044
1909
  return key;
2045
1910
  }
2046
- async getWorkflowRuns({
1911
+ async listWorkflowRuns({
2047
1912
  workflowName,
2048
- limit = 20,
2049
- offset = 0,
1913
+ page = 0,
1914
+ perPage = 20,
2050
1915
  resourceId,
2051
1916
  fromDate,
2052
- toDate
1917
+ toDate,
1918
+ status
2053
1919
  } = {}) {
2054
1920
  try {
1921
+ if (page < 0 || !Number.isInteger(page)) {
1922
+ throw new MastraError(
1923
+ {
1924
+ id: "CLOUDFLARE_STORE_INVALID_PAGE",
1925
+ domain: ErrorDomain.STORAGE,
1926
+ category: ErrorCategory.USER,
1927
+ details: { page }
1928
+ },
1929
+ new Error("page must be a non-negative integer")
1930
+ );
1931
+ }
1932
+ const normalizedPerPage = normalizePerPage(perPage, 20);
1933
+ const offset = page * normalizedPerPage;
2055
1934
  const prefix = this.buildWorkflowSnapshotPrefix({ workflowName });
2056
1935
  const keyObjs = await this.operations.listKV(TABLE_WORKFLOW_SNAPSHOT, { prefix });
2057
1936
  const runs = [];
@@ -2067,10 +1946,11 @@ var WorkflowsStorageCloudflare = class extends WorkflowsStorage {
2067
1946
  if (!data) continue;
2068
1947
  try {
2069
1948
  if (resourceId && !keyResourceId) continue;
1949
+ const snapshotData = typeof data.snapshot === "string" ? JSON.parse(data.snapshot) : data.snapshot;
1950
+ if (status && snapshotData.status !== status) continue;
2070
1951
  const createdAt = ensureDate(data.createdAt);
2071
1952
  if (fromDate && createdAt && createdAt < fromDate) continue;
2072
1953
  if (toDate && createdAt && createdAt > toDate) continue;
2073
- const snapshotData = typeof data.snapshot === "string" ? JSON.parse(data.snapshot) : data.snapshot;
2074
1954
  const resourceIdToUse = keyResourceId || data.resourceId;
2075
1955
  const run = this.parseWorkflowRun({
2076
1956
  ...data,
@@ -2088,7 +1968,7 @@ var WorkflowsStorageCloudflare = class extends WorkflowsStorage {
2088
1968
  const bDate = b.createdAt ? new Date(b.createdAt).getTime() : 0;
2089
1969
  return bDate - aDate;
2090
1970
  });
2091
- const pagedRuns = runs.slice(offset, offset + limit);
1971
+ const pagedRuns = runs.slice(offset, offset + normalizedPerPage);
2092
1972
  return {
2093
1973
  runs: pagedRuns,
2094
1974
  total: runs.length
@@ -2096,7 +1976,7 @@ var WorkflowsStorageCloudflare = class extends WorkflowsStorage {
2096
1976
  } catch (error) {
2097
1977
  const mastraError = new MastraError(
2098
1978
  {
2099
- id: "CLOUDFLARE_STORAGE_GET_WORKFLOW_RUNS_FAILED",
1979
+ id: "CLOUDFLARE_STORAGE_LIST_WORKFLOW_RUNS_FAILED",
2100
1980
  domain: ErrorDomain.STORAGE,
2101
1981
  category: ErrorCategory.THIRD_PARTY
2102
1982
  },
@@ -2170,14 +2050,7 @@ var CloudflareStore = class extends MastraStorage {
2170
2050
  if (!config.bindings) {
2171
2051
  throw new Error("KV bindings are required when using Workers Binding API");
2172
2052
  }
2173
- const requiredTables = [
2174
- TABLE_THREADS,
2175
- TABLE_MESSAGES,
2176
- TABLE_WORKFLOW_SNAPSHOT,
2177
- TABLE_EVALS,
2178
- TABLE_SCORERS,
2179
- TABLE_TRACES
2180
- ];
2053
+ const requiredTables = [TABLE_THREADS, TABLE_MESSAGES, TABLE_WORKFLOW_SNAPSHOT, TABLE_SCORERS];
2181
2054
  for (const table of requiredTables) {
2182
2055
  if (!(table in config.bindings)) {
2183
2056
  throw new Error(`Missing KV binding for table: ${table}`);
@@ -2195,8 +2068,15 @@ var CloudflareStore = class extends MastraStorage {
2195
2068
  throw new Error("apiToken is required for REST API");
2196
2069
  }
2197
2070
  }
2071
+ get supports() {
2072
+ const supports = super.supports;
2073
+ supports.listScoresBySpan = true;
2074
+ supports.resourceWorkingMemory = true;
2075
+ supports.selectByIncludeResourceScope = true;
2076
+ return supports;
2077
+ }
2198
2078
  constructor(config) {
2199
- super({ name: "Cloudflare" });
2079
+ super({ id: config.id, name: "Cloudflare" });
2200
2080
  try {
2201
2081
  if (isWorkersConfig(config)) {
2202
2082
  this.validateWorkersConfig(config);
@@ -2218,15 +2098,9 @@ var CloudflareStore = class extends MastraStorage {
2218
2098
  namespacePrefix: this.namespacePrefix,
2219
2099
  bindings: this.bindings
2220
2100
  });
2221
- const legacyEvals = new LegacyEvalsStorageCloudflare({
2222
- operations
2223
- });
2224
2101
  const workflows = new WorkflowsStorageCloudflare({
2225
2102
  operations
2226
2103
  });
2227
- const traces = new TracesStorageCloudflare({
2228
- operations
2229
- });
2230
2104
  const memory = new MemoryStorageCloudflare({
2231
2105
  operations
2232
2106
  });
@@ -2235,9 +2109,7 @@ var CloudflareStore = class extends MastraStorage {
2235
2109
  });
2236
2110
  this.stores = {
2237
2111
  operations,
2238
- legacyEvals,
2239
2112
  workflows,
2240
- traces,
2241
2113
  memory,
2242
2114
  scores
2243
2115
  };
@@ -2279,9 +2151,6 @@ var CloudflareStore = class extends MastraStorage {
2279
2151
  async getThreadById({ threadId }) {
2280
2152
  return this.stores.memory.getThreadById({ threadId });
2281
2153
  }
2282
- async getThreadsByResourceId({ resourceId }) {
2283
- return this.stores.memory.getThreadsByResourceId({ resourceId });
2284
- }
2285
2154
  async saveThread({ thread }) {
2286
2155
  return this.stores.memory.saveThread({ thread });
2287
2156
  }
@@ -2298,22 +2167,14 @@ var CloudflareStore = class extends MastraStorage {
2298
2167
  async saveMessages(args) {
2299
2168
  return this.stores.memory.saveMessages(args);
2300
2169
  }
2301
- async getMessages({
2302
- threadId,
2303
- resourceId,
2304
- selectBy,
2305
- format
2306
- }) {
2307
- return this.stores.memory.getMessages({ threadId, resourceId, selectBy, format });
2308
- }
2309
2170
  async updateWorkflowResults({
2310
2171
  workflowName,
2311
2172
  runId,
2312
2173
  stepId,
2313
2174
  result,
2314
- runtimeContext
2175
+ requestContext
2315
2176
  }) {
2316
- return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, runtimeContext });
2177
+ return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, requestContext });
2317
2178
  }
2318
2179
  async updateWorkflowState({
2319
2180
  workflowName,
@@ -2322,11 +2183,8 @@ var CloudflareStore = class extends MastraStorage {
2322
2183
  }) {
2323
2184
  return this.stores.workflows.updateWorkflowState({ workflowName, runId, opts });
2324
2185
  }
2325
- async getMessagesById({
2326
- messageIds,
2327
- format
2328
- }) {
2329
- return this.stores.memory.getMessagesById({ messageIds, format });
2186
+ async listMessagesById({ messageIds }) {
2187
+ return this.stores.memory.listMessagesById({ messageIds });
2330
2188
  }
2331
2189
  async persistWorkflowSnapshot(params) {
2332
2190
  return this.stores.workflows.persistWorkflowSnapshot(params);
@@ -2337,46 +2195,23 @@ var CloudflareStore = class extends MastraStorage {
2337
2195
  async batchInsert(input) {
2338
2196
  return this.stores.operations.batchInsert(input);
2339
2197
  }
2340
- async getTraces({
2341
- name,
2342
- scope,
2343
- page = 0,
2344
- perPage = 100,
2345
- attributes,
2346
- fromDate,
2347
- toDate
2348
- }) {
2349
- return this.stores.traces.getTraces({
2350
- name,
2351
- scope,
2352
- page,
2353
- perPage,
2354
- attributes,
2355
- fromDate,
2356
- toDate
2357
- });
2358
- }
2359
- async getEvalsByAgentName(agentName, type) {
2360
- return this.stores.legacyEvals.getEvalsByAgentName(agentName, type);
2361
- }
2362
- async getEvals(options) {
2363
- return this.stores.legacyEvals.getEvals(options);
2364
- }
2365
- async getWorkflowRuns({
2198
+ async listWorkflowRuns({
2366
2199
  workflowName,
2367
- limit = 20,
2368
- offset = 0,
2200
+ perPage = 20,
2201
+ page = 0,
2369
2202
  resourceId,
2370
2203
  fromDate,
2371
- toDate
2204
+ toDate,
2205
+ status
2372
2206
  } = {}) {
2373
- return this.stores.workflows.getWorkflowRuns({
2207
+ return this.stores.workflows.listWorkflowRuns({
2374
2208
  workflowName,
2375
- limit,
2376
- offset,
2209
+ perPage,
2210
+ page,
2377
2211
  resourceId,
2378
2212
  fromDate,
2379
- toDate
2213
+ toDate,
2214
+ status
2380
2215
  });
2381
2216
  }
2382
2217
  async getWorkflowRunById({
@@ -2385,15 +2220,6 @@ var CloudflareStore = class extends MastraStorage {
2385
2220
  }) {
2386
2221
  return this.stores.workflows.getWorkflowRunById({ runId, workflowName });
2387
2222
  }
2388
- async getTracesPaginated(args) {
2389
- return this.stores.traces.getTracesPaginated(args);
2390
- }
2391
- async getThreadsByResourceIdPaginated(args) {
2392
- return this.stores.memory.getThreadsByResourceIdPaginated(args);
2393
- }
2394
- async getMessagesPaginated(args) {
2395
- return this.stores.memory.getMessagesPaginated(args);
2396
- }
2397
2223
  async updateMessages(args) {
2398
2224
  return this.stores.memory.updateMessages(args);
2399
2225
  }
@@ -2403,27 +2229,34 @@ var CloudflareStore = class extends MastraStorage {
2403
2229
  async saveScore(score) {
2404
2230
  return this.stores.scores.saveScore(score);
2405
2231
  }
2406
- async getScoresByRunId({
2232
+ async listScoresByRunId({
2407
2233
  runId,
2408
2234
  pagination
2409
2235
  }) {
2410
- return this.stores.scores.getScoresByRunId({ runId, pagination });
2236
+ return this.stores.scores.listScoresByRunId({ runId, pagination });
2411
2237
  }
2412
- async getScoresByEntityId({
2238
+ async listScoresByEntityId({
2413
2239
  entityId,
2414
2240
  entityType,
2415
2241
  pagination
2416
2242
  }) {
2417
- return this.stores.scores.getScoresByEntityId({ entityId, entityType, pagination });
2243
+ return this.stores.scores.listScoresByEntityId({ entityId, entityType, pagination });
2418
2244
  }
2419
- async getScoresByScorerId({
2245
+ async listScoresByScorerId({
2420
2246
  scorerId,
2421
2247
  entityId,
2422
2248
  entityType,
2423
2249
  source,
2424
2250
  pagination
2425
2251
  }) {
2426
- return this.stores.scores.getScoresByScorerId({ scorerId, entityId, entityType, source, pagination });
2252
+ return this.stores.scores.listScoresByScorerId({ scorerId, entityId, entityType, source, pagination });
2253
+ }
2254
+ async listScoresBySpan({
2255
+ traceId,
2256
+ spanId,
2257
+ pagination
2258
+ }) {
2259
+ return this.stores.scores.listScoresBySpan({ traceId, spanId, pagination });
2427
2260
  }
2428
2261
  async getResourceById({ resourceId }) {
2429
2262
  return this.stores.memory.getResourceById({ resourceId });