@mastra/cloudflare 0.13.2 → 1.0.0-beta.1

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,110 +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/scores';
5
+ import { saveScorePayloadSchema } from '@mastra/core/evals';
6
6
 
7
7
  // src/storage/index.ts
8
- var LegacyEvalsStorageCloudflare = class extends LegacyEvalsStorage {
9
- operations;
10
- constructor({ operations }) {
11
- super();
12
- this.operations = operations;
13
- }
14
- async getEvalsByAgentName(agentName, type) {
15
- try {
16
- const prefix = this.operations.namespacePrefix ? `${this.operations.namespacePrefix}:` : "";
17
- const keyObjs = await this.operations.listKV(TABLE_EVALS, { prefix: `${prefix}${TABLE_EVALS}` });
18
- const evals = [];
19
- for (const { name: key } of keyObjs) {
20
- const data = await this.operations.getKV(TABLE_EVALS, key);
21
- if (!data) continue;
22
- if (data.agent_name !== agentName) continue;
23
- if (type) {
24
- const isTest = data.test_info !== null && data.test_info !== void 0;
25
- const evalType = isTest ? "test" : "live";
26
- if (evalType !== type) continue;
27
- }
28
- const mappedData = {
29
- ...data,
30
- runId: data.run_id,
31
- testInfo: data.test_info
32
- };
33
- evals.push(mappedData);
34
- }
35
- evals.sort((a, b) => {
36
- const aTime = new Date(a.createdAt || 0).getTime();
37
- const bTime = new Date(b.createdAt || 0).getTime();
38
- return bTime - aTime;
39
- });
40
- return evals;
41
- } catch (error) {
42
- throw new MastraError(
43
- {
44
- id: "CLOUDFLARE_STORAGE_GET_EVALS_BY_AGENT_NAME_FAILED",
45
- domain: ErrorDomain.STORAGE,
46
- category: ErrorCategory.THIRD_PARTY,
47
- text: "Failed to get evals by agent name"
48
- },
49
- error
50
- );
51
- }
52
- }
53
- async getEvals(options) {
54
- try {
55
- const { agentName, type, page = 0, perPage = 100, dateRange } = options;
56
- const prefix = this.operations.namespacePrefix ? `${this.operations.namespacePrefix}:` : "";
57
- const keyObjs = await this.operations.listKV(TABLE_EVALS, { prefix: `${prefix}${TABLE_EVALS}` });
58
- const evals = [];
59
- for (const { name: key } of keyObjs) {
60
- const data = await this.operations.getKV(TABLE_EVALS, key);
61
- if (!data) continue;
62
- if (agentName && data.agent_name !== agentName) continue;
63
- if (type) {
64
- const isTest = data.test_info !== null && data.test_info !== void 0;
65
- const evalType = isTest ? "test" : "live";
66
- if (evalType !== type) continue;
67
- }
68
- if (dateRange?.start || dateRange?.end) {
69
- const evalDate = new Date(data.createdAt || data.created_at || 0);
70
- if (dateRange.start && evalDate < dateRange.start) continue;
71
- if (dateRange.end && evalDate > dateRange.end) continue;
72
- }
73
- const mappedData = {
74
- ...data,
75
- runId: data.run_id,
76
- testInfo: data.test_info
77
- };
78
- evals.push(mappedData);
79
- }
80
- evals.sort((a, b) => {
81
- const aTime = new Date(a.createdAt || 0).getTime();
82
- const bTime = new Date(b.createdAt || 0).getTime();
83
- return bTime - aTime;
84
- });
85
- const start = page * perPage;
86
- const end = start + perPage;
87
- const paginatedEvals = evals.slice(start, end);
88
- return {
89
- page,
90
- perPage,
91
- total: evals.length,
92
- hasMore: start + perPage < evals.length,
93
- evals: paginatedEvals
94
- };
95
- } catch (error) {
96
- throw new MastraError(
97
- {
98
- id: "CLOUDFLARE_STORAGE_GET_EVALS_FAILED",
99
- domain: ErrorDomain.STORAGE,
100
- category: ErrorCategory.THIRD_PARTY,
101
- text: "Failed to get evals"
102
- },
103
- error
104
- );
105
- }
106
- }
107
- };
108
8
  var MemoryStorageCloudflare = class extends MemoryStorage {
109
9
  operations;
110
10
  constructor({ operations }) {
@@ -115,6 +15,17 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
115
15
  if (!metadata) return void 0;
116
16
  return typeof metadata === "string" ? JSON.parse(metadata) : metadata;
117
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
+ }
118
29
  async getThreadById({ threadId }) {
119
30
  const thread = await this.operations.load({ tableName: TABLE_THREADS, keys: { id: threadId } });
120
31
  if (!thread) return null;
@@ -142,61 +53,23 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
142
53
  return null;
143
54
  }
144
55
  }
145
- async getThreadsByResourceId({ resourceId }) {
56
+ async listThreadsByResourceId(args) {
146
57
  try {
147
- const keyList = await this.operations.listKV(TABLE_THREADS);
148
- const threads = await Promise.all(
149
- keyList.map(async (keyObj) => {
150
- try {
151
- const data = await this.operations.getKV(TABLE_THREADS, keyObj.name);
152
- if (!data) return null;
153
- const thread = typeof data === "string" ? JSON.parse(data) : data;
154
- if (!thread || !thread.resourceId || thread.resourceId !== resourceId) return null;
155
- return {
156
- ...thread,
157
- createdAt: ensureDate(thread.createdAt),
158
- updatedAt: ensureDate(thread.updatedAt),
159
- metadata: this.ensureMetadata(thread.metadata)
160
- };
161
- } catch (error) {
162
- const mastraError = new MastraError(
163
- {
164
- id: "CLOUDFLARE_STORAGE_GET_THREADS_BY_RESOURCE_ID_FAILED",
165
- domain: ErrorDomain.STORAGE,
166
- category: ErrorCategory.THIRD_PARTY,
167
- details: {
168
- resourceId
169
- }
170
- },
171
- error
172
- );
173
- this.logger?.trackException(mastraError);
174
- this.logger?.error(mastraError.toString());
175
- return null;
176
- }
177
- })
178
- );
179
- return threads.filter((thread) => thread !== null);
180
- } catch (error) {
181
- const mastraError = new MastraError(
182
- {
183
- id: "CLOUDFLARE_STORAGE_GET_THREADS_BY_RESOURCE_ID_FAILED",
184
- domain: ErrorDomain.STORAGE,
185
- category: ErrorCategory.THIRD_PARTY,
186
- details: {
187
- resourceId
188
- }
189
- },
190
- error
191
- );
192
- this.logger?.trackException(mastraError);
193
- this.logger?.error(mastraError.toString());
194
- return [];
195
- }
196
- }
197
- async getThreadsByResourceIdPaginated(args) {
198
- try {
199
- 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);
200
73
  const prefix = this.operations.namespacePrefix ? `${this.operations.namespacePrefix}:` : "";
201
74
  const keyObjs = await this.operations.listKV(TABLE_THREADS, { prefix: `${prefix}${TABLE_THREADS}` });
202
75
  const threads = [];
@@ -207,24 +80,23 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
207
80
  threads.push(data);
208
81
  }
209
82
  threads.sort((a, b) => {
210
- const aTime = new Date(a.createdAt || 0).getTime();
211
- const bTime = new Date(b.createdAt || 0).getTime();
212
- 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;
213
86
  });
214
- const start = page * perPage;
215
- const end = start + perPage;
216
- const paginatedThreads = threads.slice(start, end);
87
+ const end = perPageInput === false ? threads.length : offset + perPage;
88
+ const paginatedThreads = threads.slice(offset, end);
217
89
  return {
218
90
  page,
219
- perPage,
91
+ perPage: perPageForResponse,
220
92
  total: threads.length,
221
- hasMore: start + perPage < threads.length,
93
+ hasMore: perPageInput === false ? false : offset + perPage < threads.length,
222
94
  threads: paginatedThreads
223
95
  };
224
96
  } catch (error) {
225
97
  throw new MastraError(
226
98
  {
227
- id: "CLOUDFLARE_STORAGE_GET_THREADS_BY_RESOURCE_ID_PAGINATED_FAILED",
99
+ id: "CLOUDFLARE_STORAGE_LIST_THREADS_BY_RESOURCE_ID_FAILED",
228
100
  domain: ErrorDomain.STORAGE,
229
101
  category: ErrorCategory.THIRD_PARTY,
230
102
  text: "Failed to get threads by resource ID with pagination"
@@ -292,7 +164,7 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
292
164
  return this.operations.getKey(TABLE_MESSAGES, { threadId, id: messageId });
293
165
  } catch (error) {
294
166
  const message = error instanceof Error ? error.message : String(error);
295
- 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 });
296
168
  throw error;
297
169
  }
298
170
  }
@@ -301,7 +173,7 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
301
173
  return this.operations.getKey(TABLE_MESSAGES, { threadId, id: "messages" });
302
174
  } catch (error) {
303
175
  const message = error instanceof Error ? error.message : String(error);
304
- 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 });
305
177
  throw error;
306
178
  }
307
179
  }
@@ -391,7 +263,7 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
391
263
  });
392
264
  } catch (error) {
393
265
  const message = error instanceof Error ? error.message : String(error);
394
- this.logger.error(`Error updating sorted order for key ${orderKey}:`, { message });
266
+ this.logger?.error(`Error updating sorted order for key ${orderKey}:`, { message });
395
267
  throw error;
396
268
  } finally {
397
269
  if (this.updateQueue.get(orderKey) === nextPromise) {
@@ -409,7 +281,7 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
409
281
  const arr = JSON.parse(typeof raw === "string" ? raw : JSON.stringify(raw));
410
282
  return Array.isArray(arr) ? arr : [];
411
283
  } catch (e) {
412
- this.logger.error(`Error parsing order data for key ${orderKey}:`, { e });
284
+ this.logger?.error(`Error parsing order data for key ${orderKey}:`, { e });
413
285
  return [];
414
286
  }
415
287
  }
@@ -440,8 +312,8 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
440
312
  }
441
313
  }
442
314
  async saveMessages(args) {
443
- const { messages, format = "v1" } = args;
444
- if (!Array.isArray(messages) || messages.length === 0) return [];
315
+ const { messages } = args;
316
+ if (!Array.isArray(messages) || messages.length === 0) return { messages: [] };
445
317
  try {
446
318
  const validatedMessages = messages.map((message, index) => {
447
319
  const errors = [];
@@ -464,9 +336,11 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
464
336
  const messageMigrationTasks = [];
465
337
  for (const message of validatedMessages) {
466
338
  const existingMessage = await this.findMessageInAnyThread(message.id);
467
- console.info(`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
+ );
468
342
  if (existingMessage && existingMessage.threadId && existingMessage.threadId !== message.threadId) {
469
- console.info(`Migrating message ${message.id} from ${existingMessage.threadId} to ${message.threadId}`);
343
+ this.logger?.debug(`Migrating message ${message.id} from ${existingMessage.threadId} to ${message.threadId}`);
470
344
  messageMigrationTasks.push(this.migrateMessage(message.id, existingMessage.threadId, message.threadId));
471
345
  }
472
346
  }
@@ -495,10 +369,8 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
495
369
  ...cleanMessage,
496
370
  createdAt: serializeDate(cleanMessage.createdAt)
497
371
  };
498
- console.info(`Saving message ${message.id} with content:`, {
499
- content: serializedMessage.content,
500
- contentType: typeof serializedMessage.content,
501
- isArray: Array.isArray(serializedMessage.content)
372
+ this.logger?.debug(`Saving message ${message.id}`, {
373
+ contentSummary: this.summarizeMessageContent(serializedMessage.content)
502
374
  });
503
375
  await this.operations.putKV({ tableName: TABLE_MESSAGES, key, value: serializedMessage });
504
376
  })
@@ -534,8 +406,7 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
534
406
  ({ _index, ...message }) => ({ ...message, type: message.type !== "v2" ? message.type : void 0 })
535
407
  );
536
408
  const list = new MessageList().add(prepared, "memory");
537
- if (format === `v2`) return list.get.all.v2();
538
- return list.get.all.v1();
409
+ return { messages: list.get.all.db() };
539
410
  } catch (error) {
540
411
  throw new MastraError(
541
412
  {
@@ -598,7 +469,7 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
598
469
  const latestIds = await this.getLastN(threadMessagesKey, limit);
599
470
  latestIds.forEach((id) => messageIds.add(id));
600
471
  } catch {
601
- console.info(`No message order found for thread ${threadId}, skipping latest messages`);
472
+ this.logger?.debug(`No message order found for thread ${threadId}, skipping latest messages`);
602
473
  }
603
474
  }
604
475
  async fetchAndParseMessagesFromMultipleThreads(messageIds, include, targetThreadId) {
@@ -629,111 +500,21 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
629
500
  const data = await this.operations.getKV(TABLE_MESSAGES, key);
630
501
  if (!data) return null;
631
502
  const parsed = typeof data === "string" ? JSON.parse(data) : data;
632
- console.info(`Retrieved message ${id} from thread ${threadId} with content:`, {
633
- content: parsed.content,
634
- contentType: typeof parsed.content,
635
- isArray: Array.isArray(parsed.content)
503
+ this.logger?.debug(`Retrieved message ${id} from thread ${threadId}`, {
504
+ contentSummary: this.summarizeMessageContent(parsed.content)
636
505
  });
637
506
  return parsed;
638
507
  } catch (error) {
639
508
  const message = error instanceof Error ? error.message : String(error);
640
- this.logger.error(`Error retrieving message ${id}:`, { message });
509
+ this.logger?.error(`Error retrieving message ${id}:`, { message });
641
510
  return null;
642
511
  }
643
512
  })
644
513
  );
645
514
  return messages.filter((msg) => msg !== null);
646
515
  }
647
- async getMessages({
648
- threadId,
649
- resourceId,
650
- selectBy,
651
- format
652
- }) {
653
- console.info(`getMessages called with format: ${format}, threadId: ${threadId}`);
654
- const actualFormat = format || "v1";
655
- console.info(`Using format: ${actualFormat}`);
656
- const limit = resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
657
- const messageIds = /* @__PURE__ */ new Set();
658
- if (limit === 0 && !selectBy?.include?.length) return [];
659
- try {
660
- if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
661
- await Promise.all([
662
- selectBy?.include?.length ? this.getIncludedMessagesWithContext(threadId, selectBy.include, messageIds) : Promise.resolve(),
663
- limit > 0 ? this.getRecentMessages(threadId, limit, messageIds) : Promise.resolve()
664
- ]);
665
- const targetThreadId = selectBy?.include?.length ? void 0 : threadId;
666
- const messages = await this.fetchAndParseMessagesFromMultipleThreads(
667
- Array.from(messageIds),
668
- selectBy?.include,
669
- targetThreadId
670
- );
671
- if (!messages.length) return [];
672
- try {
673
- const threadMessagesKey = this.getThreadMessagesKey(threadId);
674
- const messageOrder = await this.getFullOrder(threadMessagesKey);
675
- const orderMap = new Map(messageOrder.map((id, index) => [id, index]));
676
- messages.sort((a, b) => {
677
- const indexA = orderMap.get(a.id);
678
- const indexB = orderMap.get(b.id);
679
- if (indexA !== void 0 && indexB !== void 0) return orderMap.get(a.id) - orderMap.get(b.id);
680
- return new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime();
681
- });
682
- } catch (error) {
683
- const mastraError = new MastraError(
684
- {
685
- id: "CLOUDFLARE_STORAGE_SORT_MESSAGES_FAILED",
686
- domain: ErrorDomain.STORAGE,
687
- category: ErrorCategory.THIRD_PARTY,
688
- text: `Error sorting messages for thread ${threadId} falling back to creation time`,
689
- details: {
690
- threadId
691
- }
692
- },
693
- error
694
- );
695
- this.logger?.trackException(mastraError);
696
- this.logger?.error(mastraError.toString());
697
- messages.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
698
- }
699
- const prepared = messages.map(({ _index, ...message }) => ({
700
- ...message,
701
- type: message.type === `v2` ? void 0 : message.type,
702
- createdAt: ensureDate(message.createdAt)
703
- }));
704
- if (actualFormat === `v1`) {
705
- console.info(`Processing ${prepared.length} messages for v1 format - returning directly without MessageList`);
706
- return prepared.map((msg) => ({
707
- ...msg,
708
- createdAt: new Date(msg.createdAt)
709
- }));
710
- }
711
- const list = new MessageList({ threadId, resourceId }).add(prepared, "memory");
712
- return list.get.all.v2();
713
- } catch (error) {
714
- const mastraError = new MastraError(
715
- {
716
- id: "CLOUDFLARE_STORAGE_GET_MESSAGES_FAILED",
717
- domain: ErrorDomain.STORAGE,
718
- category: ErrorCategory.THIRD_PARTY,
719
- text: `Error retrieving messages for thread ${threadId}`,
720
- details: {
721
- threadId,
722
- resourceId: resourceId ?? ""
723
- }
724
- },
725
- error
726
- );
727
- this.logger?.trackException(mastraError);
728
- this.logger?.error(mastraError.toString());
729
- return [];
730
- }
731
- }
732
- async getMessagesById({
733
- messageIds,
734
- format
735
- }) {
736
- if (messageIds.length === 0) return [];
516
+ async listMessagesById({ messageIds }) {
517
+ if (messageIds.length === 0) return { messages: [] };
737
518
  try {
738
519
  const messages = (await Promise.all(messageIds.map((id) => this.findMessageInAnyThread(id)))).filter(
739
520
  (result) => !!result
@@ -744,12 +525,11 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
744
525
  createdAt: ensureDate(message.createdAt)
745
526
  }));
746
527
  const list = new MessageList().add(prepared, "memory");
747
- if (format === `v1`) return list.get.all.v1();
748
- return list.get.all.v2();
528
+ return { messages: list.get.all.db() };
749
529
  } catch (error) {
750
530
  const mastraError = new MastraError(
751
531
  {
752
- id: "CLOUDFLARE_STORAGE_GET_MESSAGES_BY_ID_FAILED",
532
+ id: "CLOUDFLARE_STORAGE_LIST_MESSAGES_BY_ID_FAILED",
753
533
  domain: ErrorDomain.STORAGE,
754
534
  category: ErrorCategory.THIRD_PARTY,
755
535
  text: `Error retrieving messages by ID`,
@@ -761,42 +541,202 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
761
541
  );
762
542
  this.logger?.trackException(mastraError);
763
543
  this.logger?.error(mastraError.toString());
764
- return [];
544
+ return { messages: [] };
765
545
  }
766
546
  }
767
- async getMessagesPaginated(args) {
768
- const { threadId, resourceId, selectBy, format = "v1" } = args;
769
- 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);
770
562
  try {
771
- if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
772
- 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
+ );
773
613
  let filteredMessages = messages;
774
- if (selectBy?.pagination?.dateRange) {
775
- const { start: dateStart, end: dateEnd } = selectBy.pagination.dateRange;
776
- filteredMessages = messages.filter((message) => {
777
- const messageDate = new Date(message.createdAt);
778
- if (dateStart && messageDate < dateStart) return false;
779
- 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;
780
623
  return true;
781
624
  });
782
625
  }
783
- const start = page * perPage;
784
- const end = start + perPage;
785
- 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
+ }
786
726
  return {
727
+ messages: finalMessages,
728
+ total,
787
729
  page,
788
- perPage,
789
- total: filteredMessages.length,
790
- hasMore: start + perPage < filteredMessages.length,
791
- messages: paginatedMessages
730
+ perPage: perPageForResponse,
731
+ hasMore
792
732
  };
793
733
  } catch (error) {
794
734
  const mastraError = new MastraError(
795
735
  {
796
- id: "CLOUDFLARE_STORAGE_GET_MESSAGES_PAGINATED_FAILED",
736
+ id: "CLOUDFLARE_STORAGE_LIST_MESSAGES_FAILED",
797
737
  domain: ErrorDomain.STORAGE,
798
738
  category: ErrorCategory.THIRD_PARTY,
799
- text: "Failed to get messages with pagination",
739
+ text: `Failed to list messages for thread ${threadId}: ${error instanceof Error ? error.message : String(error)}`,
800
740
  details: {
801
741
  threadId,
802
742
  resourceId: resourceId ?? ""
@@ -804,9 +744,15 @@ var MemoryStorageCloudflare = class extends MemoryStorage {
804
744
  },
805
745
  error
806
746
  );
807
- this.logger?.trackException?.(mastraError);
808
747
  this.logger?.error?.(mastraError.toString());
809
- 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
+ };
810
756
  }
811
757
  }
812
758
  async updateMessages(args) {
@@ -1092,10 +1038,6 @@ var StoreOperationsCloudflare = class extends StoreOperations {
1092
1038
  case TABLE_TRACES:
1093
1039
  if (!record.id) throw new Error("Trace ID is required");
1094
1040
  return `${prefix}${tableName}:${record.id}`;
1095
- case TABLE_EVALS:
1096
- const evalId = record.id || record.run_id;
1097
- if (!evalId) throw new Error("Eval ID or run_id is required");
1098
- return `${prefix}${tableName}:${evalId}`;
1099
1041
  case TABLE_SCORERS:
1100
1042
  if (!record.id) throw new Error("Score ID is required");
1101
1043
  return `${prefix}${tableName}:${record.id}`;
@@ -1335,11 +1277,6 @@ var StoreOperationsCloudflare = class extends StoreOperations {
1335
1277
  throw new Error("Trace record missing required fields");
1336
1278
  }
1337
1279
  break;
1338
- case TABLE_EVALS:
1339
- if (!("agent_name" in recordTyped) || !("run_id" in recordTyped)) {
1340
- throw new Error("Eval record missing required fields");
1341
- }
1342
- break;
1343
1280
  case TABLE_SCORERS:
1344
1281
  if (!("id" in recordTyped) || !("scorerId" in recordTyped)) {
1345
1282
  throw new Error("Score record missing required fields");
@@ -1357,12 +1294,7 @@ var StoreOperationsCloudflare = class extends StoreOperations {
1357
1294
  async insert({ tableName, record }) {
1358
1295
  try {
1359
1296
  const key = this.getKey(tableName, record);
1360
- const processedRecord = {
1361
- ...record,
1362
- createdAt: record.createdAt ? serializeDate(record.createdAt) : void 0,
1363
- updatedAt: record.updatedAt ? serializeDate(record.updatedAt) : void 0,
1364
- metadata: record.metadata ? JSON.stringify(record.metadata) : ""
1365
- };
1297
+ const processedRecord = { ...record };
1366
1298
  await this.validateRecord(processedRecord, tableName);
1367
1299
  await this.putKV({ tableName, key, value: processedRecord });
1368
1300
  } catch (error) {
@@ -1379,22 +1311,12 @@ var StoreOperationsCloudflare = class extends StoreOperations {
1379
1311
  );
1380
1312
  }
1381
1313
  }
1382
- ensureMetadata(metadata) {
1383
- if (!metadata) return {};
1384
- return typeof metadata === "string" ? JSON.parse(metadata) : metadata;
1385
- }
1386
1314
  async load({ tableName, keys }) {
1387
1315
  try {
1388
1316
  const key = this.getKey(tableName, keys);
1389
1317
  const data = await this.getKV(tableName, key);
1390
1318
  if (!data) return null;
1391
- const processed = {
1392
- ...data,
1393
- createdAt: ensureDate(data.createdAt),
1394
- updatedAt: ensureDate(data.updatedAt),
1395
- metadata: this.ensureMetadata(data.metadata)
1396
- };
1397
- return processed;
1319
+ return data;
1398
1320
  } catch (error) {
1399
1321
  const mastraError = new MastraError(
1400
1322
  {
@@ -1418,13 +1340,7 @@ var StoreOperationsCloudflare = class extends StoreOperations {
1418
1340
  await Promise.all(
1419
1341
  input.records.map(async (record) => {
1420
1342
  const key = this.getKey(input.tableName, record);
1421
- const processedRecord = {
1422
- ...record,
1423
- createdAt: record.createdAt ? serializeDate(record.createdAt) : void 0,
1424
- updatedAt: record.updatedAt ? serializeDate(record.updatedAt) : void 0,
1425
- metadata: record.metadata ? JSON.stringify(record.metadata) : void 0
1426
- };
1427
- await this.putKV({ tableName: input.tableName, key, value: processedRecord });
1343
+ await this.putKV({ tableName: input.tableName, key, value: record });
1428
1344
  })
1429
1345
  );
1430
1346
  } catch (error) {
@@ -1582,7 +1498,7 @@ function transformScoreRow(row) {
1582
1498
  deserialized.analyzeStepResult = safelyParseJSON(row.analyzeStepResult);
1583
1499
  deserialized.metadata = safelyParseJSON(row.metadata);
1584
1500
  deserialized.additionalContext = safelyParseJSON(row.additionalContext);
1585
- deserialized.runtimeContext = safelyParseJSON(row.runtimeContext);
1501
+ deserialized.requestContext = safelyParseJSON(row.requestContext);
1586
1502
  deserialized.entity = safelyParseJSON(row.entity);
1587
1503
  return deserialized;
1588
1504
  }
@@ -1668,7 +1584,7 @@ var ScoresStorageCloudflare = class extends ScoresStorage {
1668
1584
  throw mastraError;
1669
1585
  }
1670
1586
  }
1671
- async getScoresByScorerId({
1587
+ async listScoresByScorerId({
1672
1588
  scorerId,
1673
1589
  entityId,
1674
1590
  entityType,
@@ -1698,15 +1614,17 @@ var ScoresStorageCloudflare = class extends ScoresStorage {
1698
1614
  const dateB = new Date(b.createdAt || 0).getTime();
1699
1615
  return dateB - dateA;
1700
1616
  });
1617
+ const { page, perPage: perPageInput } = pagination;
1618
+ const perPage = normalizePerPage(perPageInput, 100);
1619
+ const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
1701
1620
  const total = scores.length;
1702
- const start = pagination.page * pagination.perPage;
1703
- const end = start + pagination.perPage;
1621
+ const end = perPageInput === false ? scores.length : start + perPage;
1704
1622
  const pagedScores = scores.slice(start, end);
1705
1623
  return {
1706
1624
  pagination: {
1707
1625
  total,
1708
- page: pagination.page,
1709
- perPage: pagination.perPage,
1626
+ page,
1627
+ perPage: perPageForResponse,
1710
1628
  hasMore: end < total
1711
1629
  },
1712
1630
  scores: pagedScores
@@ -1726,7 +1644,7 @@ var ScoresStorageCloudflare = class extends ScoresStorage {
1726
1644
  return { pagination: { total: 0, page: 0, perPage: 100, hasMore: false }, scores: [] };
1727
1645
  }
1728
1646
  }
1729
- async getScoresByRunId({
1647
+ async listScoresByRunId({
1730
1648
  runId,
1731
1649
  pagination
1732
1650
  }) {
@@ -1744,15 +1662,17 @@ var ScoresStorageCloudflare = class extends ScoresStorage {
1744
1662
  const dateB = new Date(b.createdAt || 0).getTime();
1745
1663
  return dateB - dateA;
1746
1664
  });
1665
+ const { page, perPage: perPageInput } = pagination;
1666
+ const perPage = normalizePerPage(perPageInput, 100);
1667
+ const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
1747
1668
  const total = scores.length;
1748
- const start = pagination.page * pagination.perPage;
1749
- const end = start + pagination.perPage;
1669
+ const end = perPageInput === false ? scores.length : start + perPage;
1750
1670
  const pagedScores = scores.slice(start, end);
1751
1671
  return {
1752
1672
  pagination: {
1753
1673
  total,
1754
- page: pagination.page,
1755
- perPage: pagination.perPage,
1674
+ page,
1675
+ perPage: perPageForResponse,
1756
1676
  hasMore: end < total
1757
1677
  },
1758
1678
  scores: pagedScores
@@ -1772,7 +1692,7 @@ var ScoresStorageCloudflare = class extends ScoresStorage {
1772
1692
  return { pagination: { total: 0, page: 0, perPage: 100, hasMore: false }, scores: [] };
1773
1693
  }
1774
1694
  }
1775
- async getScoresByEntityId({
1695
+ async listScoresByEntityId({
1776
1696
  entityId,
1777
1697
  entityType,
1778
1698
  pagination
@@ -1791,15 +1711,17 @@ var ScoresStorageCloudflare = class extends ScoresStorage {
1791
1711
  const dateB = new Date(b.createdAt || 0).getTime();
1792
1712
  return dateB - dateA;
1793
1713
  });
1714
+ const { page, perPage: perPageInput } = pagination;
1715
+ const perPage = normalizePerPage(perPageInput, 100);
1716
+ const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
1794
1717
  const total = scores.length;
1795
- const start = pagination.page * pagination.perPage;
1796
- const end = start + pagination.perPage;
1718
+ const end = perPageInput === false ? scores.length : start + perPage;
1797
1719
  const pagedScores = scores.slice(start, end);
1798
1720
  return {
1799
1721
  pagination: {
1800
1722
  total,
1801
- page: pagination.page,
1802
- perPage: pagination.perPage,
1723
+ page,
1724
+ perPage: perPageForResponse,
1803
1725
  hasMore: end < total
1804
1726
  },
1805
1727
  scores: pagedScores
@@ -1819,7 +1741,7 @@ var ScoresStorageCloudflare = class extends ScoresStorage {
1819
1741
  return { pagination: { total: 0, page: 0, perPage: 100, hasMore: false }, scores: [] };
1820
1742
  }
1821
1743
  }
1822
- async getScoresBySpan({
1744
+ async listScoresBySpan({
1823
1745
  traceId,
1824
1746
  spanId,
1825
1747
  pagination
@@ -1838,21 +1760,23 @@ var ScoresStorageCloudflare = class extends ScoresStorage {
1838
1760
  const dateB = new Date(b.createdAt || 0).getTime();
1839
1761
  return dateB - dateA;
1840
1762
  });
1763
+ const { page, perPage: perPageInput } = pagination;
1764
+ const perPage = normalizePerPage(perPageInput, 100);
1765
+ const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);
1841
1766
  const total = scores.length;
1842
- const start = pagination.page * pagination.perPage;
1843
- const end = start + pagination.perPage;
1767
+ const end = perPageInput === false ? scores.length : start + perPage;
1844
1768
  const pagedScores = scores.slice(start, end);
1845
1769
  return {
1846
1770
  pagination: {
1847
1771
  total,
1848
- page: pagination.page,
1849
- perPage: pagination.perPage,
1772
+ page,
1773
+ perPage: perPageForResponse,
1850
1774
  hasMore: end < total
1851
1775
  },
1852
1776
  scores: pagedScores
1853
1777
  };
1854
1778
  } catch (error) {
1855
- throw new MastraError(
1779
+ const mastraError = new MastraError(
1856
1780
  {
1857
1781
  id: "CLOUDFLARE_STORAGE_SCORES_GET_SCORES_BY_SPAN_FAILED",
1858
1782
  domain: ErrorDomain.STORAGE,
@@ -1861,129 +1785,12 @@ var ScoresStorageCloudflare = class extends ScoresStorage {
1861
1785
  },
1862
1786
  error
1863
1787
  );
1788
+ this.logger?.trackException(mastraError);
1789
+ this.logger?.error(mastraError.toString());
1790
+ return { pagination: { total: 0, page: 0, perPage: 100, hasMore: false }, scores: [] };
1864
1791
  }
1865
1792
  }
1866
1793
  };
1867
- var TracesStorageCloudflare = class extends TracesStorage {
1868
- operations;
1869
- constructor({ operations }) {
1870
- super();
1871
- this.operations = operations;
1872
- }
1873
- async getTraces(args) {
1874
- const paginatedArgs = {
1875
- name: args.name,
1876
- scope: args.scope,
1877
- page: args.page,
1878
- perPage: args.perPage,
1879
- attributes: args.attributes,
1880
- filters: args.filters,
1881
- dateRange: args.fromDate || args.toDate ? {
1882
- start: args.fromDate,
1883
- end: args.toDate
1884
- } : void 0
1885
- };
1886
- try {
1887
- const result = await this.getTracesPaginated(paginatedArgs);
1888
- return result.traces;
1889
- } catch (error) {
1890
- throw new MastraError(
1891
- {
1892
- id: "CLOUDFLARE_STORAGE_GET_TRACES_ERROR",
1893
- domain: ErrorDomain.STORAGE,
1894
- category: ErrorCategory.THIRD_PARTY,
1895
- text: `Failed to retrieve traces: ${error instanceof Error ? error.message : String(error)}`,
1896
- details: {
1897
- name: args.name ?? "",
1898
- scope: args.scope ?? ""
1899
- }
1900
- },
1901
- error
1902
- );
1903
- }
1904
- }
1905
- async getTracesPaginated(args) {
1906
- try {
1907
- const { name, scope, attributes, filters, page = 0, perPage = 100, dateRange } = args;
1908
- const prefix = this.operations.namespacePrefix ? `${this.operations.namespacePrefix}:` : "";
1909
- const keyObjs = await this.operations.listKV(TABLE_TRACES, { prefix: `${prefix}${TABLE_TRACES}` });
1910
- const traces = [];
1911
- for (const { name: key } of keyObjs) {
1912
- try {
1913
- const data = await this.operations.getKV(TABLE_TRACES, key);
1914
- if (!data) continue;
1915
- if (name && data.name !== name) continue;
1916
- if (scope && data.scope !== scope) continue;
1917
- if (attributes) {
1918
- const dataAttributes = data.attributes || {};
1919
- let shouldSkip = false;
1920
- for (const [key2, value] of Object.entries(attributes)) {
1921
- if (dataAttributes[key2] !== value) {
1922
- shouldSkip = true;
1923
- break;
1924
- }
1925
- }
1926
- if (shouldSkip) continue;
1927
- }
1928
- if (dateRange?.start || dateRange?.end) {
1929
- const traceDate = new Date(data.createdAt || 0);
1930
- if (dateRange.start && traceDate < dateRange.start) continue;
1931
- if (dateRange.end && traceDate > dateRange.end) continue;
1932
- }
1933
- if (filters) {
1934
- let shouldSkip = false;
1935
- for (const [key2, value] of Object.entries(filters)) {
1936
- if (data[key2] !== value) {
1937
- shouldSkip = true;
1938
- break;
1939
- }
1940
- }
1941
- if (shouldSkip) continue;
1942
- }
1943
- traces.push(data);
1944
- } catch (err) {
1945
- this.logger.error("Failed to parse trace:", { key, error: err });
1946
- }
1947
- }
1948
- traces.sort((a, b) => {
1949
- const aTime = new Date(a.createdAt || 0).getTime();
1950
- const bTime = new Date(b.createdAt || 0).getTime();
1951
- return bTime - aTime;
1952
- });
1953
- const total = traces.length;
1954
- const start = page * perPage;
1955
- const end = start + perPage;
1956
- const pagedTraces = traces.slice(start, end);
1957
- return {
1958
- traces: pagedTraces,
1959
- total,
1960
- page,
1961
- perPage,
1962
- hasMore: end < total
1963
- };
1964
- } catch (error) {
1965
- const mastraError = new MastraError(
1966
- {
1967
- id: "CLOUDFLARE_STORAGE_GET_TRACES_PAGINATED_FAILED",
1968
- domain: ErrorDomain.STORAGE,
1969
- category: ErrorCategory.THIRD_PARTY,
1970
- text: "Error getting traces with pagination"
1971
- },
1972
- error
1973
- );
1974
- this.logger.trackException?.(mastraError);
1975
- this.logger.error(mastraError.toString());
1976
- return { traces: [], total: 0, page: 0, perPage: 100, hasMore: false };
1977
- }
1978
- }
1979
- async batchTraceInsert({ records }) {
1980
- this.logger.debug("Batch inserting traces", { count: records.length });
1981
- await this.operations.batchInsert({
1982
- tableName: TABLE_TRACES,
1983
- records
1984
- });
1985
- }
1986
- };
1987
1794
  var WorkflowsStorageCloudflare = class extends WorkflowsStorage {
1988
1795
  operations;
1989
1796
  constructor({ operations }) {
@@ -2001,7 +1808,7 @@ var WorkflowsStorageCloudflare = class extends WorkflowsStorage {
2001
1808
  // runId,
2002
1809
  // stepId,
2003
1810
  // result,
2004
- // runtimeContext,
1811
+ // requestContext,
2005
1812
  }) {
2006
1813
  throw new Error("Method not implemented.");
2007
1814
  }
@@ -2022,7 +1829,7 @@ var WorkflowsStorageCloudflare = class extends WorkflowsStorage {
2022
1829
  workflow_name: workflowName,
2023
1830
  run_id: runId,
2024
1831
  resourceId,
2025
- snapshot: typeof snapshot === "string" ? snapshot : JSON.stringify(snapshot),
1832
+ snapshot: JSON.stringify(snapshot),
2026
1833
  createdAt: /* @__PURE__ */ new Date(),
2027
1834
  updatedAt: /* @__PURE__ */ new Date()
2028
1835
  }
@@ -2101,15 +1908,29 @@ var WorkflowsStorageCloudflare = class extends WorkflowsStorage {
2101
1908
  if (resourceId) key += `:${resourceId}`;
2102
1909
  return key;
2103
1910
  }
2104
- async getWorkflowRuns({
1911
+ async listWorkflowRuns({
2105
1912
  workflowName,
2106
- limit = 20,
2107
- offset = 0,
1913
+ page = 0,
1914
+ perPage = 20,
2108
1915
  resourceId,
2109
1916
  fromDate,
2110
- toDate
1917
+ toDate,
1918
+ status
2111
1919
  } = {}) {
2112
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;
2113
1934
  const prefix = this.buildWorkflowSnapshotPrefix({ workflowName });
2114
1935
  const keyObjs = await this.operations.listKV(TABLE_WORKFLOW_SNAPSHOT, { prefix });
2115
1936
  const runs = [];
@@ -2125,10 +1946,11 @@ var WorkflowsStorageCloudflare = class extends WorkflowsStorage {
2125
1946
  if (!data) continue;
2126
1947
  try {
2127
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;
2128
1951
  const createdAt = ensureDate(data.createdAt);
2129
1952
  if (fromDate && createdAt && createdAt < fromDate) continue;
2130
1953
  if (toDate && createdAt && createdAt > toDate) continue;
2131
- const snapshotData = typeof data.snapshot === "string" ? JSON.parse(data.snapshot) : data.snapshot;
2132
1954
  const resourceIdToUse = keyResourceId || data.resourceId;
2133
1955
  const run = this.parseWorkflowRun({
2134
1956
  ...data,
@@ -2146,7 +1968,7 @@ var WorkflowsStorageCloudflare = class extends WorkflowsStorage {
2146
1968
  const bDate = b.createdAt ? new Date(b.createdAt).getTime() : 0;
2147
1969
  return bDate - aDate;
2148
1970
  });
2149
- const pagedRuns = runs.slice(offset, offset + limit);
1971
+ const pagedRuns = runs.slice(offset, offset + normalizedPerPage);
2150
1972
  return {
2151
1973
  runs: pagedRuns,
2152
1974
  total: runs.length
@@ -2154,7 +1976,7 @@ var WorkflowsStorageCloudflare = class extends WorkflowsStorage {
2154
1976
  } catch (error) {
2155
1977
  const mastraError = new MastraError(
2156
1978
  {
2157
- id: "CLOUDFLARE_STORAGE_GET_WORKFLOW_RUNS_FAILED",
1979
+ id: "CLOUDFLARE_STORAGE_LIST_WORKFLOW_RUNS_FAILED",
2158
1980
  domain: ErrorDomain.STORAGE,
2159
1981
  category: ErrorCategory.THIRD_PARTY
2160
1982
  },
@@ -2228,14 +2050,7 @@ var CloudflareStore = class extends MastraStorage {
2228
2050
  if (!config.bindings) {
2229
2051
  throw new Error("KV bindings are required when using Workers Binding API");
2230
2052
  }
2231
- const requiredTables = [
2232
- TABLE_THREADS,
2233
- TABLE_MESSAGES,
2234
- TABLE_WORKFLOW_SNAPSHOT,
2235
- TABLE_EVALS,
2236
- TABLE_SCORERS,
2237
- TABLE_TRACES
2238
- ];
2053
+ const requiredTables = [TABLE_THREADS, TABLE_MESSAGES, TABLE_WORKFLOW_SNAPSHOT, TABLE_SCORERS];
2239
2054
  for (const table of requiredTables) {
2240
2055
  if (!(table in config.bindings)) {
2241
2056
  throw new Error(`Missing KV binding for table: ${table}`);
@@ -2255,11 +2070,13 @@ var CloudflareStore = class extends MastraStorage {
2255
2070
  }
2256
2071
  get supports() {
2257
2072
  const supports = super.supports;
2258
- supports.getScoresBySpan = true;
2073
+ supports.listScoresBySpan = true;
2074
+ supports.resourceWorkingMemory = true;
2075
+ supports.selectByIncludeResourceScope = true;
2259
2076
  return supports;
2260
2077
  }
2261
2078
  constructor(config) {
2262
- super({ name: "Cloudflare" });
2079
+ super({ id: config.id, name: "Cloudflare" });
2263
2080
  try {
2264
2081
  if (isWorkersConfig(config)) {
2265
2082
  this.validateWorkersConfig(config);
@@ -2281,15 +2098,9 @@ var CloudflareStore = class extends MastraStorage {
2281
2098
  namespacePrefix: this.namespacePrefix,
2282
2099
  bindings: this.bindings
2283
2100
  });
2284
- const legacyEvals = new LegacyEvalsStorageCloudflare({
2285
- operations
2286
- });
2287
2101
  const workflows = new WorkflowsStorageCloudflare({
2288
2102
  operations
2289
2103
  });
2290
- const traces = new TracesStorageCloudflare({
2291
- operations
2292
- });
2293
2104
  const memory = new MemoryStorageCloudflare({
2294
2105
  operations
2295
2106
  });
@@ -2298,9 +2109,7 @@ var CloudflareStore = class extends MastraStorage {
2298
2109
  });
2299
2110
  this.stores = {
2300
2111
  operations,
2301
- legacyEvals,
2302
2112
  workflows,
2303
- traces,
2304
2113
  memory,
2305
2114
  scores
2306
2115
  };
@@ -2342,9 +2151,6 @@ var CloudflareStore = class extends MastraStorage {
2342
2151
  async getThreadById({ threadId }) {
2343
2152
  return this.stores.memory.getThreadById({ threadId });
2344
2153
  }
2345
- async getThreadsByResourceId({ resourceId }) {
2346
- return this.stores.memory.getThreadsByResourceId({ resourceId });
2347
- }
2348
2154
  async saveThread({ thread }) {
2349
2155
  return this.stores.memory.saveThread({ thread });
2350
2156
  }
@@ -2361,22 +2167,14 @@ var CloudflareStore = class extends MastraStorage {
2361
2167
  async saveMessages(args) {
2362
2168
  return this.stores.memory.saveMessages(args);
2363
2169
  }
2364
- async getMessages({
2365
- threadId,
2366
- resourceId,
2367
- selectBy,
2368
- format
2369
- }) {
2370
- return this.stores.memory.getMessages({ threadId, resourceId, selectBy, format });
2371
- }
2372
2170
  async updateWorkflowResults({
2373
2171
  workflowName,
2374
2172
  runId,
2375
2173
  stepId,
2376
2174
  result,
2377
- runtimeContext
2175
+ requestContext
2378
2176
  }) {
2379
- return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, runtimeContext });
2177
+ return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, requestContext });
2380
2178
  }
2381
2179
  async updateWorkflowState({
2382
2180
  workflowName,
@@ -2385,11 +2183,8 @@ var CloudflareStore = class extends MastraStorage {
2385
2183
  }) {
2386
2184
  return this.stores.workflows.updateWorkflowState({ workflowName, runId, opts });
2387
2185
  }
2388
- async getMessagesById({
2389
- messageIds,
2390
- format
2391
- }) {
2392
- return this.stores.memory.getMessagesById({ messageIds, format });
2186
+ async listMessagesById({ messageIds }) {
2187
+ return this.stores.memory.listMessagesById({ messageIds });
2393
2188
  }
2394
2189
  async persistWorkflowSnapshot(params) {
2395
2190
  return this.stores.workflows.persistWorkflowSnapshot(params);
@@ -2400,46 +2195,23 @@ var CloudflareStore = class extends MastraStorage {
2400
2195
  async batchInsert(input) {
2401
2196
  return this.stores.operations.batchInsert(input);
2402
2197
  }
2403
- async getTraces({
2404
- name,
2405
- scope,
2406
- page = 0,
2407
- perPage = 100,
2408
- attributes,
2409
- fromDate,
2410
- toDate
2411
- }) {
2412
- return this.stores.traces.getTraces({
2413
- name,
2414
- scope,
2415
- page,
2416
- perPage,
2417
- attributes,
2418
- fromDate,
2419
- toDate
2420
- });
2421
- }
2422
- async getEvalsByAgentName(agentName, type) {
2423
- return this.stores.legacyEvals.getEvalsByAgentName(agentName, type);
2424
- }
2425
- async getEvals(options) {
2426
- return this.stores.legacyEvals.getEvals(options);
2427
- }
2428
- async getWorkflowRuns({
2198
+ async listWorkflowRuns({
2429
2199
  workflowName,
2430
- limit = 20,
2431
- offset = 0,
2200
+ perPage = 20,
2201
+ page = 0,
2432
2202
  resourceId,
2433
2203
  fromDate,
2434
- toDate
2204
+ toDate,
2205
+ status
2435
2206
  } = {}) {
2436
- return this.stores.workflows.getWorkflowRuns({
2207
+ return this.stores.workflows.listWorkflowRuns({
2437
2208
  workflowName,
2438
- limit,
2439
- offset,
2209
+ perPage,
2210
+ page,
2440
2211
  resourceId,
2441
2212
  fromDate,
2442
- toDate
2213
+ toDate,
2214
+ status
2443
2215
  });
2444
2216
  }
2445
2217
  async getWorkflowRunById({
@@ -2448,15 +2220,6 @@ var CloudflareStore = class extends MastraStorage {
2448
2220
  }) {
2449
2221
  return this.stores.workflows.getWorkflowRunById({ runId, workflowName });
2450
2222
  }
2451
- async getTracesPaginated(args) {
2452
- return this.stores.traces.getTracesPaginated(args);
2453
- }
2454
- async getThreadsByResourceIdPaginated(args) {
2455
- return this.stores.memory.getThreadsByResourceIdPaginated(args);
2456
- }
2457
- async getMessagesPaginated(args) {
2458
- return this.stores.memory.getMessagesPaginated(args);
2459
- }
2460
2223
  async updateMessages(args) {
2461
2224
  return this.stores.memory.updateMessages(args);
2462
2225
  }
@@ -2466,34 +2229,34 @@ var CloudflareStore = class extends MastraStorage {
2466
2229
  async saveScore(score) {
2467
2230
  return this.stores.scores.saveScore(score);
2468
2231
  }
2469
- async getScoresByRunId({
2232
+ async listScoresByRunId({
2470
2233
  runId,
2471
2234
  pagination
2472
2235
  }) {
2473
- return this.stores.scores.getScoresByRunId({ runId, pagination });
2236
+ return this.stores.scores.listScoresByRunId({ runId, pagination });
2474
2237
  }
2475
- async getScoresByEntityId({
2238
+ async listScoresByEntityId({
2476
2239
  entityId,
2477
2240
  entityType,
2478
2241
  pagination
2479
2242
  }) {
2480
- return this.stores.scores.getScoresByEntityId({ entityId, entityType, pagination });
2243
+ return this.stores.scores.listScoresByEntityId({ entityId, entityType, pagination });
2481
2244
  }
2482
- async getScoresByScorerId({
2245
+ async listScoresByScorerId({
2483
2246
  scorerId,
2484
2247
  entityId,
2485
2248
  entityType,
2486
2249
  source,
2487
2250
  pagination
2488
2251
  }) {
2489
- return this.stores.scores.getScoresByScorerId({ scorerId, entityId, entityType, source, pagination });
2252
+ return this.stores.scores.listScoresByScorerId({ scorerId, entityId, entityType, source, pagination });
2490
2253
  }
2491
- async getScoresBySpan({
2254
+ async listScoresBySpan({
2492
2255
  traceId,
2493
2256
  spanId,
2494
2257
  pagination
2495
2258
  }) {
2496
- return this.stores.scores.getScoresBySpan({ traceId, spanId, pagination });
2259
+ return this.stores.scores.listScoresBySpan({ traceId, spanId, pagination });
2497
2260
  }
2498
2261
  async getResourceById({ resourceId }) {
2499
2262
  return this.stores.memory.getResourceById({ resourceId });