@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.cjs CHANGED
@@ -4,113 +4,13 @@ var error = require('@mastra/core/error');
4
4
  var storage = require('@mastra/core/storage');
5
5
  var Cloudflare = require('cloudflare');
6
6
  var agent = require('@mastra/core/agent');
7
- var scores = require('@mastra/core/scores');
7
+ var evals = require('@mastra/core/evals');
8
8
 
9
9
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
10
10
 
11
11
  var Cloudflare__default = /*#__PURE__*/_interopDefault(Cloudflare);
12
12
 
13
13
  // src/storage/index.ts
14
- var LegacyEvalsStorageCloudflare = class extends storage.LegacyEvalsStorage {
15
- operations;
16
- constructor({ operations }) {
17
- super();
18
- this.operations = operations;
19
- }
20
- async getEvalsByAgentName(agentName, type) {
21
- try {
22
- const prefix = this.operations.namespacePrefix ? `${this.operations.namespacePrefix}:` : "";
23
- const keyObjs = await this.operations.listKV(storage.TABLE_EVALS, { prefix: `${prefix}${storage.TABLE_EVALS}` });
24
- const evals = [];
25
- for (const { name: key } of keyObjs) {
26
- const data = await this.operations.getKV(storage.TABLE_EVALS, key);
27
- if (!data) continue;
28
- if (data.agent_name !== agentName) continue;
29
- if (type) {
30
- const isTest = data.test_info !== null && data.test_info !== void 0;
31
- const evalType = isTest ? "test" : "live";
32
- if (evalType !== type) continue;
33
- }
34
- const mappedData = {
35
- ...data,
36
- runId: data.run_id,
37
- testInfo: data.test_info
38
- };
39
- evals.push(mappedData);
40
- }
41
- evals.sort((a, b) => {
42
- const aTime = new Date(a.createdAt || 0).getTime();
43
- const bTime = new Date(b.createdAt || 0).getTime();
44
- return bTime - aTime;
45
- });
46
- return evals;
47
- } catch (error$1) {
48
- throw new error.MastraError(
49
- {
50
- id: "CLOUDFLARE_STORAGE_GET_EVALS_BY_AGENT_NAME_FAILED",
51
- domain: error.ErrorDomain.STORAGE,
52
- category: error.ErrorCategory.THIRD_PARTY,
53
- text: "Failed to get evals by agent name"
54
- },
55
- error$1
56
- );
57
- }
58
- }
59
- async getEvals(options) {
60
- try {
61
- const { agentName, type, page = 0, perPage = 100, dateRange } = options;
62
- const prefix = this.operations.namespacePrefix ? `${this.operations.namespacePrefix}:` : "";
63
- const keyObjs = await this.operations.listKV(storage.TABLE_EVALS, { prefix: `${prefix}${storage.TABLE_EVALS}` });
64
- const evals = [];
65
- for (const { name: key } of keyObjs) {
66
- const data = await this.operations.getKV(storage.TABLE_EVALS, key);
67
- if (!data) continue;
68
- if (agentName && data.agent_name !== agentName) continue;
69
- if (type) {
70
- const isTest = data.test_info !== null && data.test_info !== void 0;
71
- const evalType = isTest ? "test" : "live";
72
- if (evalType !== type) continue;
73
- }
74
- if (dateRange?.start || dateRange?.end) {
75
- const evalDate = new Date(data.createdAt || data.created_at || 0);
76
- if (dateRange.start && evalDate < dateRange.start) continue;
77
- if (dateRange.end && evalDate > dateRange.end) continue;
78
- }
79
- const mappedData = {
80
- ...data,
81
- runId: data.run_id,
82
- testInfo: data.test_info
83
- };
84
- evals.push(mappedData);
85
- }
86
- evals.sort((a, b) => {
87
- const aTime = new Date(a.createdAt || 0).getTime();
88
- const bTime = new Date(b.createdAt || 0).getTime();
89
- return bTime - aTime;
90
- });
91
- const start = page * perPage;
92
- const end = start + perPage;
93
- const paginatedEvals = evals.slice(start, end);
94
- return {
95
- page,
96
- perPage,
97
- total: evals.length,
98
- hasMore: start + perPage < evals.length,
99
- evals: paginatedEvals
100
- };
101
- } catch (error$1) {
102
- throw new error.MastraError(
103
- {
104
- id: "CLOUDFLARE_STORAGE_GET_EVALS_FAILED",
105
- domain: error.ErrorDomain.STORAGE,
106
- category: error.ErrorCategory.THIRD_PARTY,
107
- text: "Failed to get evals"
108
- },
109
- error$1
110
- );
111
- }
112
- }
113
- };
114
14
  var MemoryStorageCloudflare = class extends storage.MemoryStorage {
115
15
  operations;
116
16
  constructor({ operations }) {
@@ -121,6 +21,17 @@ var MemoryStorageCloudflare = class extends storage.MemoryStorage {
121
21
  if (!metadata) return void 0;
122
22
  return typeof metadata === "string" ? JSON.parse(metadata) : metadata;
123
23
  }
24
+ /**
25
+ * Summarizes message content without exposing raw data (for logging).
26
+ * Returns type, length, and keys only to prevent PII leakage.
27
+ */
28
+ summarizeMessageContent(content) {
29
+ if (!content) return { type: "undefined" };
30
+ if (typeof content === "string") return { type: "string", length: content.length };
31
+ if (Array.isArray(content)) return { type: "array", length: content.length };
32
+ if (typeof content === "object") return { type: "object", keys: Object.keys(content) };
33
+ return { type: typeof content };
34
+ }
124
35
  async getThreadById({ threadId }) {
125
36
  const thread = await this.operations.load({ tableName: storage.TABLE_THREADS, keys: { id: threadId } });
126
37
  if (!thread) return null;
@@ -148,61 +59,23 @@ var MemoryStorageCloudflare = class extends storage.MemoryStorage {
148
59
  return null;
149
60
  }
150
61
  }
151
- async getThreadsByResourceId({ resourceId }) {
62
+ async listThreadsByResourceId(args) {
152
63
  try {
153
- const keyList = await this.operations.listKV(storage.TABLE_THREADS);
154
- const threads = await Promise.all(
155
- keyList.map(async (keyObj) => {
156
- try {
157
- const data = await this.operations.getKV(storage.TABLE_THREADS, keyObj.name);
158
- if (!data) return null;
159
- const thread = typeof data === "string" ? JSON.parse(data) : data;
160
- if (!thread || !thread.resourceId || thread.resourceId !== resourceId) return null;
161
- return {
162
- ...thread,
163
- createdAt: storage.ensureDate(thread.createdAt),
164
- updatedAt: storage.ensureDate(thread.updatedAt),
165
- metadata: this.ensureMetadata(thread.metadata)
166
- };
167
- } catch (error$1) {
168
- const mastraError = new error.MastraError(
169
- {
170
- id: "CLOUDFLARE_STORAGE_GET_THREADS_BY_RESOURCE_ID_FAILED",
171
- domain: error.ErrorDomain.STORAGE,
172
- category: error.ErrorCategory.THIRD_PARTY,
173
- details: {
174
- resourceId
175
- }
176
- },
177
- error$1
178
- );
179
- this.logger?.trackException(mastraError);
180
- this.logger?.error(mastraError.toString());
181
- return null;
182
- }
183
- })
184
- );
185
- return threads.filter((thread) => thread !== null);
186
- } catch (error$1) {
187
- const mastraError = new error.MastraError(
188
- {
189
- id: "CLOUDFLARE_STORAGE_GET_THREADS_BY_RESOURCE_ID_FAILED",
190
- domain: error.ErrorDomain.STORAGE,
191
- category: error.ErrorCategory.THIRD_PARTY,
192
- details: {
193
- resourceId
194
- }
195
- },
196
- error$1
197
- );
198
- this.logger?.trackException(mastraError);
199
- this.logger?.error(mastraError.toString());
200
- return [];
201
- }
202
- }
203
- async getThreadsByResourceIdPaginated(args) {
204
- try {
205
- const { resourceId, page = 0, perPage = 100 } = args;
64
+ const { resourceId, page = 0, perPage: perPageInput, orderBy } = args;
65
+ const perPage = storage.normalizePerPage(perPageInput, 100);
66
+ if (page < 0) {
67
+ throw new error.MastraError(
68
+ {
69
+ id: "STORAGE_CLOUDFLARE_LIST_THREADS_BY_RESOURCE_ID_INVALID_PAGE",
70
+ domain: error.ErrorDomain.STORAGE,
71
+ category: error.ErrorCategory.USER,
72
+ details: { page }
73
+ },
74
+ new Error("page must be >= 0")
75
+ );
76
+ }
77
+ const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
78
+ const { field, direction } = this.parseOrderBy(orderBy);
206
79
  const prefix = this.operations.namespacePrefix ? `${this.operations.namespacePrefix}:` : "";
207
80
  const keyObjs = await this.operations.listKV(storage.TABLE_THREADS, { prefix: `${prefix}${storage.TABLE_THREADS}` });
208
81
  const threads = [];
@@ -213,24 +86,23 @@ var MemoryStorageCloudflare = class extends storage.MemoryStorage {
213
86
  threads.push(data);
214
87
  }
215
88
  threads.sort((a, b) => {
216
- const aTime = new Date(a.createdAt || 0).getTime();
217
- const bTime = new Date(b.createdAt || 0).getTime();
218
- return bTime - aTime;
89
+ const aTime = new Date(a[field] || 0).getTime();
90
+ const bTime = new Date(b[field] || 0).getTime();
91
+ return direction === "ASC" ? aTime - bTime : bTime - aTime;
219
92
  });
220
- const start = page * perPage;
221
- const end = start + perPage;
222
- const paginatedThreads = threads.slice(start, end);
93
+ const end = perPageInput === false ? threads.length : offset + perPage;
94
+ const paginatedThreads = threads.slice(offset, end);
223
95
  return {
224
96
  page,
225
- perPage,
97
+ perPage: perPageForResponse,
226
98
  total: threads.length,
227
- hasMore: start + perPage < threads.length,
99
+ hasMore: perPageInput === false ? false : offset + perPage < threads.length,
228
100
  threads: paginatedThreads
229
101
  };
230
102
  } catch (error$1) {
231
103
  throw new error.MastraError(
232
104
  {
233
- id: "CLOUDFLARE_STORAGE_GET_THREADS_BY_RESOURCE_ID_PAGINATED_FAILED",
105
+ id: "CLOUDFLARE_STORAGE_LIST_THREADS_BY_RESOURCE_ID_FAILED",
234
106
  domain: error.ErrorDomain.STORAGE,
235
107
  category: error.ErrorCategory.THIRD_PARTY,
236
108
  text: "Failed to get threads by resource ID with pagination"
@@ -298,7 +170,7 @@ var MemoryStorageCloudflare = class extends storage.MemoryStorage {
298
170
  return this.operations.getKey(storage.TABLE_MESSAGES, { threadId, id: messageId });
299
171
  } catch (error) {
300
172
  const message = error instanceof Error ? error.message : String(error);
301
- this.logger.error(`Error getting message key for thread ${threadId} and message ${messageId}:`, { message });
173
+ this.logger?.error(`Error getting message key for thread ${threadId} and message ${messageId}:`, { message });
302
174
  throw error;
303
175
  }
304
176
  }
@@ -307,7 +179,7 @@ var MemoryStorageCloudflare = class extends storage.MemoryStorage {
307
179
  return this.operations.getKey(storage.TABLE_MESSAGES, { threadId, id: "messages" });
308
180
  } catch (error) {
309
181
  const message = error instanceof Error ? error.message : String(error);
310
- this.logger.error(`Error getting thread messages key for thread ${threadId}:`, { message });
182
+ this.logger?.error(`Error getting thread messages key for thread ${threadId}:`, { message });
311
183
  throw error;
312
184
  }
313
185
  }
@@ -397,7 +269,7 @@ var MemoryStorageCloudflare = class extends storage.MemoryStorage {
397
269
  });
398
270
  } catch (error) {
399
271
  const message = error instanceof Error ? error.message : String(error);
400
- this.logger.error(`Error updating sorted order for key ${orderKey}:`, { message });
272
+ this.logger?.error(`Error updating sorted order for key ${orderKey}:`, { message });
401
273
  throw error;
402
274
  } finally {
403
275
  if (this.updateQueue.get(orderKey) === nextPromise) {
@@ -415,7 +287,7 @@ var MemoryStorageCloudflare = class extends storage.MemoryStorage {
415
287
  const arr = JSON.parse(typeof raw === "string" ? raw : JSON.stringify(raw));
416
288
  return Array.isArray(arr) ? arr : [];
417
289
  } catch (e) {
418
- this.logger.error(`Error parsing order data for key ${orderKey}:`, { e });
290
+ this.logger?.error(`Error parsing order data for key ${orderKey}:`, { e });
419
291
  return [];
420
292
  }
421
293
  }
@@ -446,8 +318,8 @@ var MemoryStorageCloudflare = class extends storage.MemoryStorage {
446
318
  }
447
319
  }
448
320
  async saveMessages(args) {
449
- const { messages, format = "v1" } = args;
450
- if (!Array.isArray(messages) || messages.length === 0) return [];
321
+ const { messages } = args;
322
+ if (!Array.isArray(messages) || messages.length === 0) return { messages: [] };
451
323
  try {
452
324
  const validatedMessages = messages.map((message, index) => {
453
325
  const errors = [];
@@ -470,9 +342,11 @@ var MemoryStorageCloudflare = class extends storage.MemoryStorage {
470
342
  const messageMigrationTasks = [];
471
343
  for (const message of validatedMessages) {
472
344
  const existingMessage = await this.findMessageInAnyThread(message.id);
473
- console.info(`Checking message ${message.id}: existing=${existingMessage?.threadId}, new=${message.threadId}`);
345
+ this.logger?.debug(
346
+ `Checking message ${message.id}: existing=${existingMessage?.threadId}, new=${message.threadId}`
347
+ );
474
348
  if (existingMessage && existingMessage.threadId && existingMessage.threadId !== message.threadId) {
475
- console.info(`Migrating message ${message.id} from ${existingMessage.threadId} to ${message.threadId}`);
349
+ this.logger?.debug(`Migrating message ${message.id} from ${existingMessage.threadId} to ${message.threadId}`);
476
350
  messageMigrationTasks.push(this.migrateMessage(message.id, existingMessage.threadId, message.threadId));
477
351
  }
478
352
  }
@@ -501,10 +375,8 @@ var MemoryStorageCloudflare = class extends storage.MemoryStorage {
501
375
  ...cleanMessage,
502
376
  createdAt: storage.serializeDate(cleanMessage.createdAt)
503
377
  };
504
- console.info(`Saving message ${message.id} with content:`, {
505
- content: serializedMessage.content,
506
- contentType: typeof serializedMessage.content,
507
- isArray: Array.isArray(serializedMessage.content)
378
+ this.logger?.debug(`Saving message ${message.id}`, {
379
+ contentSummary: this.summarizeMessageContent(serializedMessage.content)
508
380
  });
509
381
  await this.operations.putKV({ tableName: storage.TABLE_MESSAGES, key, value: serializedMessage });
510
382
  })
@@ -540,8 +412,7 @@ var MemoryStorageCloudflare = class extends storage.MemoryStorage {
540
412
  ({ _index, ...message }) => ({ ...message, type: message.type !== "v2" ? message.type : void 0 })
541
413
  );
542
414
  const list = new agent.MessageList().add(prepared, "memory");
543
- if (format === `v2`) return list.get.all.v2();
544
- return list.get.all.v1();
415
+ return { messages: list.get.all.db() };
545
416
  } catch (error$1) {
546
417
  throw new error.MastraError(
547
418
  {
@@ -604,7 +475,7 @@ var MemoryStorageCloudflare = class extends storage.MemoryStorage {
604
475
  const latestIds = await this.getLastN(threadMessagesKey, limit);
605
476
  latestIds.forEach((id) => messageIds.add(id));
606
477
  } catch {
607
- console.info(`No message order found for thread ${threadId}, skipping latest messages`);
478
+ this.logger?.debug(`No message order found for thread ${threadId}, skipping latest messages`);
608
479
  }
609
480
  }
610
481
  async fetchAndParseMessagesFromMultipleThreads(messageIds, include, targetThreadId) {
@@ -635,111 +506,21 @@ var MemoryStorageCloudflare = class extends storage.MemoryStorage {
635
506
  const data = await this.operations.getKV(storage.TABLE_MESSAGES, key);
636
507
  if (!data) return null;
637
508
  const parsed = typeof data === "string" ? JSON.parse(data) : data;
638
- console.info(`Retrieved message ${id} from thread ${threadId} with content:`, {
639
- content: parsed.content,
640
- contentType: typeof parsed.content,
641
- isArray: Array.isArray(parsed.content)
509
+ this.logger?.debug(`Retrieved message ${id} from thread ${threadId}`, {
510
+ contentSummary: this.summarizeMessageContent(parsed.content)
642
511
  });
643
512
  return parsed;
644
513
  } catch (error) {
645
514
  const message = error instanceof Error ? error.message : String(error);
646
- this.logger.error(`Error retrieving message ${id}:`, { message });
515
+ this.logger?.error(`Error retrieving message ${id}:`, { message });
647
516
  return null;
648
517
  }
649
518
  })
650
519
  );
651
520
  return messages.filter((msg) => msg !== null);
652
521
  }
653
- async getMessages({
654
- threadId,
655
- resourceId,
656
- selectBy,
657
- format
658
- }) {
659
- console.info(`getMessages called with format: ${format}, threadId: ${threadId}`);
660
- const actualFormat = format || "v1";
661
- console.info(`Using format: ${actualFormat}`);
662
- const limit = storage.resolveMessageLimit({ last: selectBy?.last, defaultLimit: 40 });
663
- const messageIds = /* @__PURE__ */ new Set();
664
- if (limit === 0 && !selectBy?.include?.length) return [];
665
- try {
666
- if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
667
- await Promise.all([
668
- selectBy?.include?.length ? this.getIncludedMessagesWithContext(threadId, selectBy.include, messageIds) : Promise.resolve(),
669
- limit > 0 ? this.getRecentMessages(threadId, limit, messageIds) : Promise.resolve()
670
- ]);
671
- const targetThreadId = selectBy?.include?.length ? void 0 : threadId;
672
- const messages = await this.fetchAndParseMessagesFromMultipleThreads(
673
- Array.from(messageIds),
674
- selectBy?.include,
675
- targetThreadId
676
- );
677
- if (!messages.length) return [];
678
- try {
679
- const threadMessagesKey = this.getThreadMessagesKey(threadId);
680
- const messageOrder = await this.getFullOrder(threadMessagesKey);
681
- const orderMap = new Map(messageOrder.map((id, index) => [id, index]));
682
- messages.sort((a, b) => {
683
- const indexA = orderMap.get(a.id);
684
- const indexB = orderMap.get(b.id);
685
- if (indexA !== void 0 && indexB !== void 0) return orderMap.get(a.id) - orderMap.get(b.id);
686
- return new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime();
687
- });
688
- } catch (error$1) {
689
- const mastraError = new error.MastraError(
690
- {
691
- id: "CLOUDFLARE_STORAGE_SORT_MESSAGES_FAILED",
692
- domain: error.ErrorDomain.STORAGE,
693
- category: error.ErrorCategory.THIRD_PARTY,
694
- text: `Error sorting messages for thread ${threadId} falling back to creation time`,
695
- details: {
696
- threadId
697
- }
698
- },
699
- error$1
700
- );
701
- this.logger?.trackException(mastraError);
702
- this.logger?.error(mastraError.toString());
703
- messages.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
704
- }
705
- const prepared = messages.map(({ _index, ...message }) => ({
706
- ...message,
707
- type: message.type === `v2` ? void 0 : message.type,
708
- createdAt: storage.ensureDate(message.createdAt)
709
- }));
710
- if (actualFormat === `v1`) {
711
- console.info(`Processing ${prepared.length} messages for v1 format - returning directly without MessageList`);
712
- return prepared.map((msg) => ({
713
- ...msg,
714
- createdAt: new Date(msg.createdAt)
715
- }));
716
- }
717
- const list = new agent.MessageList({ threadId, resourceId }).add(prepared, "memory");
718
- return list.get.all.v2();
719
- } catch (error$1) {
720
- const mastraError = new error.MastraError(
721
- {
722
- id: "CLOUDFLARE_STORAGE_GET_MESSAGES_FAILED",
723
- domain: error.ErrorDomain.STORAGE,
724
- category: error.ErrorCategory.THIRD_PARTY,
725
- text: `Error retrieving messages for thread ${threadId}`,
726
- details: {
727
- threadId,
728
- resourceId: resourceId ?? ""
729
- }
730
- },
731
- error$1
732
- );
733
- this.logger?.trackException(mastraError);
734
- this.logger?.error(mastraError.toString());
735
- return [];
736
- }
737
- }
738
- async getMessagesById({
739
- messageIds,
740
- format
741
- }) {
742
- if (messageIds.length === 0) return [];
522
+ async listMessagesById({ messageIds }) {
523
+ if (messageIds.length === 0) return { messages: [] };
743
524
  try {
744
525
  const messages = (await Promise.all(messageIds.map((id) => this.findMessageInAnyThread(id)))).filter(
745
526
  (result) => !!result
@@ -750,12 +531,11 @@ var MemoryStorageCloudflare = class extends storage.MemoryStorage {
750
531
  createdAt: storage.ensureDate(message.createdAt)
751
532
  }));
752
533
  const list = new agent.MessageList().add(prepared, "memory");
753
- if (format === `v1`) return list.get.all.v1();
754
- return list.get.all.v2();
534
+ return { messages: list.get.all.db() };
755
535
  } catch (error$1) {
756
536
  const mastraError = new error.MastraError(
757
537
  {
758
- id: "CLOUDFLARE_STORAGE_GET_MESSAGES_BY_ID_FAILED",
538
+ id: "CLOUDFLARE_STORAGE_LIST_MESSAGES_BY_ID_FAILED",
759
539
  domain: error.ErrorDomain.STORAGE,
760
540
  category: error.ErrorCategory.THIRD_PARTY,
761
541
  text: `Error retrieving messages by ID`,
@@ -767,42 +547,202 @@ var MemoryStorageCloudflare = class extends storage.MemoryStorage {
767
547
  );
768
548
  this.logger?.trackException(mastraError);
769
549
  this.logger?.error(mastraError.toString());
770
- return [];
550
+ return { messages: [] };
771
551
  }
772
552
  }
773
- async getMessagesPaginated(args) {
774
- const { threadId, resourceId, selectBy, format = "v1" } = args;
775
- const { page = 0, perPage = 100 } = selectBy?.pagination || {};
553
+ async listMessages(args) {
554
+ const { threadId, resourceId, include, filter, perPage: perPageInput, page = 0, orderBy } = args;
555
+ if (!threadId.trim()) {
556
+ throw new error.MastraError(
557
+ {
558
+ id: "STORAGE_CLOUDFLARE_LIST_MESSAGES_INVALID_THREAD_ID",
559
+ domain: error.ErrorDomain.STORAGE,
560
+ category: error.ErrorCategory.THIRD_PARTY,
561
+ details: { threadId }
562
+ },
563
+ new Error("threadId must be a non-empty string")
564
+ );
565
+ }
566
+ const perPage = storage.normalizePerPage(perPageInput, 40);
567
+ const { offset, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
776
568
  try {
777
- if (!threadId.trim()) throw new Error("threadId must be a non-empty string");
778
- const messages = format === "v2" ? await this.getMessages({ threadId, selectBy, format: "v2" }) : await this.getMessages({ threadId, selectBy, format: "v1" });
569
+ if (page < 0) {
570
+ throw new error.MastraError(
571
+ {
572
+ id: "STORAGE_CLOUDFLARE_LIST_MESSAGES_INVALID_PAGE",
573
+ domain: error.ErrorDomain.STORAGE,
574
+ category: error.ErrorCategory.USER,
575
+ details: { page }
576
+ },
577
+ new Error("page must be >= 0")
578
+ );
579
+ }
580
+ const { field, direction } = this.parseOrderBy(orderBy, "ASC");
581
+ const messageIds = /* @__PURE__ */ new Set();
582
+ const hasFilters = !!resourceId || !!filter?.dateRange;
583
+ if (hasFilters || perPage === Number.MAX_SAFE_INTEGER) {
584
+ try {
585
+ const threadMessagesKey = this.getThreadMessagesKey(threadId);
586
+ const allIds = await this.getFullOrder(threadMessagesKey);
587
+ allIds.forEach((id) => messageIds.add(id));
588
+ } catch {
589
+ }
590
+ } else {
591
+ if (perPage > 0) {
592
+ try {
593
+ const threadMessagesKey = this.getThreadMessagesKey(threadId);
594
+ const fullOrder = await this.getFullOrder(threadMessagesKey);
595
+ const totalMessages = fullOrder.length;
596
+ let start;
597
+ let end;
598
+ if (direction === "ASC") {
599
+ start = offset;
600
+ end = Math.min(offset + perPage - 1, totalMessages - 1);
601
+ } else {
602
+ start = Math.max(totalMessages - offset - perPage, 0);
603
+ end = totalMessages - offset - 1;
604
+ }
605
+ const paginatedIds = await this.getRange(threadMessagesKey, start, end);
606
+ paginatedIds.forEach((id) => messageIds.add(id));
607
+ } catch {
608
+ }
609
+ }
610
+ }
611
+ if (include && include.length > 0) {
612
+ await this.getIncludedMessagesWithContext(threadId, include, messageIds);
613
+ }
614
+ const messages = await this.fetchAndParseMessagesFromMultipleThreads(
615
+ Array.from(messageIds),
616
+ include,
617
+ include && include.length > 0 ? void 0 : threadId
618
+ );
779
619
  let filteredMessages = messages;
780
- if (selectBy?.pagination?.dateRange) {
781
- const { start: dateStart, end: dateEnd } = selectBy.pagination.dateRange;
782
- filteredMessages = messages.filter((message) => {
783
- const messageDate = new Date(message.createdAt);
784
- if (dateStart && messageDate < dateStart) return false;
785
- if (dateEnd && messageDate > dateEnd) return false;
620
+ if (resourceId) {
621
+ filteredMessages = filteredMessages.filter((msg) => msg.resourceId === resourceId);
622
+ }
623
+ const dateRange = filter?.dateRange;
624
+ if (dateRange) {
625
+ filteredMessages = filteredMessages.filter((msg) => {
626
+ const messageDate = new Date(msg.createdAt);
627
+ if (dateRange.start && messageDate < new Date(dateRange.start)) return false;
628
+ if (dateRange.end && messageDate > new Date(dateRange.end)) return false;
786
629
  return true;
787
630
  });
788
631
  }
789
- const start = page * perPage;
790
- const end = start + perPage;
791
- const paginatedMessages = filteredMessages.slice(start, end);
632
+ let total;
633
+ if (hasFilters) {
634
+ total = filteredMessages.length;
635
+ } else {
636
+ try {
637
+ const threadMessagesKey = this.getThreadMessagesKey(threadId);
638
+ const fullOrder = await this.getFullOrder(threadMessagesKey);
639
+ total = fullOrder.length;
640
+ } catch {
641
+ total = filteredMessages.length;
642
+ }
643
+ }
644
+ if (perPage === 0 && (!include || include.length === 0)) {
645
+ return {
646
+ messages: [],
647
+ total,
648
+ page,
649
+ perPage: perPageForResponse,
650
+ hasMore: offset < total
651
+ };
652
+ }
653
+ if (hasFilters && perPage !== Number.MAX_SAFE_INTEGER && perPage > 0) {
654
+ if (direction === "ASC") {
655
+ filteredMessages = filteredMessages.slice(offset, offset + perPage);
656
+ } else {
657
+ const start = Math.max(filteredMessages.length - offset - perPage, 0);
658
+ const end = filteredMessages.length - offset;
659
+ filteredMessages = filteredMessages.slice(start, end);
660
+ }
661
+ }
662
+ const paginatedCount = hasFilters && perPage !== Number.MAX_SAFE_INTEGER && perPage > 0 ? filteredMessages.length : filteredMessages.length;
663
+ try {
664
+ const threadMessagesKey = this.getThreadMessagesKey(threadId);
665
+ const messageOrder = await this.getFullOrder(threadMessagesKey);
666
+ const orderMap = new Map(messageOrder.map((id, index) => [id, index]));
667
+ filteredMessages.sort((a, b) => {
668
+ const indexA = orderMap.get(a.id);
669
+ const indexB = orderMap.get(b.id);
670
+ if (indexA !== void 0 && indexB !== void 0) {
671
+ return direction === "ASC" ? indexA - indexB : indexB - indexA;
672
+ }
673
+ const timeA = new Date(a.createdAt).getTime();
674
+ const timeB = new Date(b.createdAt).getTime();
675
+ const timeDiff = direction === "ASC" ? timeA - timeB : timeB - timeA;
676
+ if (timeDiff === 0) {
677
+ return a.id.localeCompare(b.id);
678
+ }
679
+ return timeDiff;
680
+ });
681
+ } catch {
682
+ filteredMessages.sort((a, b) => {
683
+ const timeA = new Date(a.createdAt).getTime();
684
+ const timeB = new Date(b.createdAt).getTime();
685
+ const timeDiff = direction === "ASC" ? timeA - timeB : timeB - timeA;
686
+ if (timeDiff === 0) {
687
+ return a.id.localeCompare(b.id);
688
+ }
689
+ return timeDiff;
690
+ });
691
+ }
692
+ if (total === 0 && filteredMessages.length === 0 && (!include || include.length === 0)) {
693
+ return {
694
+ messages: [],
695
+ total: 0,
696
+ page,
697
+ perPage: perPageForResponse,
698
+ hasMore: false
699
+ };
700
+ }
701
+ const prepared = filteredMessages.map(({ _index, ...message }) => ({
702
+ ...message,
703
+ type: message.type !== "v2" ? message.type : void 0,
704
+ createdAt: storage.ensureDate(message.createdAt)
705
+ }));
706
+ const list = new agent.MessageList({ threadId, resourceId }).add(prepared, "memory");
707
+ let finalMessages = list.get.all.db();
708
+ finalMessages = finalMessages.sort((a, b) => {
709
+ const isDateField = field === "createdAt" || field === "updatedAt";
710
+ const aVal = isDateField ? new Date(a[field]).getTime() : a[field];
711
+ const bVal = isDateField ? new Date(b[field]).getTime() : b[field];
712
+ if (aVal == null && bVal == null) return a.id.localeCompare(b.id);
713
+ if (aVal == null) return 1;
714
+ if (bVal == null) return -1;
715
+ if (typeof aVal === "number" && typeof bVal === "number") {
716
+ const cmp2 = direction === "ASC" ? aVal - bVal : bVal - aVal;
717
+ return cmp2 !== 0 ? cmp2 : a.id.localeCompare(b.id);
718
+ }
719
+ const cmp = direction === "ASC" ? String(aVal).localeCompare(String(bVal)) : String(bVal).localeCompare(String(aVal));
720
+ return cmp !== 0 ? cmp : a.id.localeCompare(b.id);
721
+ });
722
+ const returnedThreadMessageIds = new Set(finalMessages.filter((m) => m.threadId === threadId).map((m) => m.id));
723
+ const allThreadMessagesReturned = returnedThreadMessageIds.size >= total;
724
+ let hasMore;
725
+ if (perPageInput === false || allThreadMessagesReturned) {
726
+ hasMore = false;
727
+ } else if (direction === "ASC") {
728
+ hasMore = offset + paginatedCount < total;
729
+ } else {
730
+ hasMore = total - offset - perPage > 0;
731
+ }
792
732
  return {
733
+ messages: finalMessages,
734
+ total,
793
735
  page,
794
- perPage,
795
- total: filteredMessages.length,
796
- hasMore: start + perPage < filteredMessages.length,
797
- messages: paginatedMessages
736
+ perPage: perPageForResponse,
737
+ hasMore
798
738
  };
799
739
  } catch (error$1) {
800
740
  const mastraError = new error.MastraError(
801
741
  {
802
- id: "CLOUDFLARE_STORAGE_GET_MESSAGES_PAGINATED_FAILED",
742
+ id: "CLOUDFLARE_STORAGE_LIST_MESSAGES_FAILED",
803
743
  domain: error.ErrorDomain.STORAGE,
804
744
  category: error.ErrorCategory.THIRD_PARTY,
805
- text: "Failed to get messages with pagination",
745
+ text: `Failed to list messages for thread ${threadId}: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
806
746
  details: {
807
747
  threadId,
808
748
  resourceId: resourceId ?? ""
@@ -810,9 +750,15 @@ var MemoryStorageCloudflare = class extends storage.MemoryStorage {
810
750
  },
811
751
  error$1
812
752
  );
813
- this.logger?.trackException?.(mastraError);
814
753
  this.logger?.error?.(mastraError.toString());
815
- return { messages: [], total: 0, page, perPage: perPage || 40, hasMore: false };
754
+ this.logger?.trackException?.(mastraError);
755
+ return {
756
+ messages: [],
757
+ total: 0,
758
+ page,
759
+ perPage: perPageForResponse,
760
+ hasMore: false
761
+ };
816
762
  }
817
763
  }
818
764
  async updateMessages(args) {
@@ -1098,10 +1044,6 @@ var StoreOperationsCloudflare = class extends storage.StoreOperations {
1098
1044
  case storage.TABLE_TRACES:
1099
1045
  if (!record.id) throw new Error("Trace ID is required");
1100
1046
  return `${prefix}${tableName}:${record.id}`;
1101
- case storage.TABLE_EVALS:
1102
- const evalId = record.id || record.run_id;
1103
- if (!evalId) throw new Error("Eval ID or run_id is required");
1104
- return `${prefix}${tableName}:${evalId}`;
1105
1047
  case storage.TABLE_SCORERS:
1106
1048
  if (!record.id) throw new Error("Score ID is required");
1107
1049
  return `${prefix}${tableName}:${record.id}`;
@@ -1341,11 +1283,6 @@ var StoreOperationsCloudflare = class extends storage.StoreOperations {
1341
1283
  throw new Error("Trace record missing required fields");
1342
1284
  }
1343
1285
  break;
1344
- case storage.TABLE_EVALS:
1345
- if (!("agent_name" in recordTyped) || !("run_id" in recordTyped)) {
1346
- throw new Error("Eval record missing required fields");
1347
- }
1348
- break;
1349
1286
  case storage.TABLE_SCORERS:
1350
1287
  if (!("id" in recordTyped) || !("scorerId" in recordTyped)) {
1351
1288
  throw new Error("Score record missing required fields");
@@ -1363,12 +1300,7 @@ var StoreOperationsCloudflare = class extends storage.StoreOperations {
1363
1300
  async insert({ tableName, record }) {
1364
1301
  try {
1365
1302
  const key = this.getKey(tableName, record);
1366
- const processedRecord = {
1367
- ...record,
1368
- createdAt: record.createdAt ? storage.serializeDate(record.createdAt) : void 0,
1369
- updatedAt: record.updatedAt ? storage.serializeDate(record.updatedAt) : void 0,
1370
- metadata: record.metadata ? JSON.stringify(record.metadata) : ""
1371
- };
1303
+ const processedRecord = { ...record };
1372
1304
  await this.validateRecord(processedRecord, tableName);
1373
1305
  await this.putKV({ tableName, key, value: processedRecord });
1374
1306
  } catch (error$1) {
@@ -1385,22 +1317,12 @@ var StoreOperationsCloudflare = class extends storage.StoreOperations {
1385
1317
  );
1386
1318
  }
1387
1319
  }
1388
- ensureMetadata(metadata) {
1389
- if (!metadata) return {};
1390
- return typeof metadata === "string" ? JSON.parse(metadata) : metadata;
1391
- }
1392
1320
  async load({ tableName, keys }) {
1393
1321
  try {
1394
1322
  const key = this.getKey(tableName, keys);
1395
1323
  const data = await this.getKV(tableName, key);
1396
1324
  if (!data) return null;
1397
- const processed = {
1398
- ...data,
1399
- createdAt: storage.ensureDate(data.createdAt),
1400
- updatedAt: storage.ensureDate(data.updatedAt),
1401
- metadata: this.ensureMetadata(data.metadata)
1402
- };
1403
- return processed;
1325
+ return data;
1404
1326
  } catch (error$1) {
1405
1327
  const mastraError = new error.MastraError(
1406
1328
  {
@@ -1424,13 +1346,7 @@ var StoreOperationsCloudflare = class extends storage.StoreOperations {
1424
1346
  await Promise.all(
1425
1347
  input.records.map(async (record) => {
1426
1348
  const key = this.getKey(input.tableName, record);
1427
- const processedRecord = {
1428
- ...record,
1429
- createdAt: record.createdAt ? storage.serializeDate(record.createdAt) : void 0,
1430
- updatedAt: record.updatedAt ? storage.serializeDate(record.updatedAt) : void 0,
1431
- metadata: record.metadata ? JSON.stringify(record.metadata) : void 0
1432
- };
1433
- await this.putKV({ tableName: input.tableName, key, value: processedRecord });
1349
+ await this.putKV({ tableName: input.tableName, key, value: record });
1434
1350
  })
1435
1351
  );
1436
1352
  } catch (error$1) {
@@ -1588,7 +1504,7 @@ function transformScoreRow(row) {
1588
1504
  deserialized.analyzeStepResult = storage.safelyParseJSON(row.analyzeStepResult);
1589
1505
  deserialized.metadata = storage.safelyParseJSON(row.metadata);
1590
1506
  deserialized.additionalContext = storage.safelyParseJSON(row.additionalContext);
1591
- deserialized.runtimeContext = storage.safelyParseJSON(row.runtimeContext);
1507
+ deserialized.requestContext = storage.safelyParseJSON(row.requestContext);
1592
1508
  deserialized.entity = storage.safelyParseJSON(row.entity);
1593
1509
  return deserialized;
1594
1510
  }
@@ -1623,7 +1539,7 @@ var ScoresStorageCloudflare = class extends storage.ScoresStorage {
1623
1539
  async saveScore(score) {
1624
1540
  let parsedScore;
1625
1541
  try {
1626
- parsedScore = scores.saveScorePayloadSchema.parse(score);
1542
+ parsedScore = evals.saveScorePayloadSchema.parse(score);
1627
1543
  } catch (error$1) {
1628
1544
  throw new error.MastraError(
1629
1545
  {
@@ -1674,7 +1590,7 @@ var ScoresStorageCloudflare = class extends storage.ScoresStorage {
1674
1590
  throw mastraError;
1675
1591
  }
1676
1592
  }
1677
- async getScoresByScorerId({
1593
+ async listScoresByScorerId({
1678
1594
  scorerId,
1679
1595
  entityId,
1680
1596
  entityType,
@@ -1704,15 +1620,17 @@ var ScoresStorageCloudflare = class extends storage.ScoresStorage {
1704
1620
  const dateB = new Date(b.createdAt || 0).getTime();
1705
1621
  return dateB - dateA;
1706
1622
  });
1623
+ const { page, perPage: perPageInput } = pagination;
1624
+ const perPage = storage.normalizePerPage(perPageInput, 100);
1625
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
1707
1626
  const total = scores.length;
1708
- const start = pagination.page * pagination.perPage;
1709
- const end = start + pagination.perPage;
1627
+ const end = perPageInput === false ? scores.length : start + perPage;
1710
1628
  const pagedScores = scores.slice(start, end);
1711
1629
  return {
1712
1630
  pagination: {
1713
1631
  total,
1714
- page: pagination.page,
1715
- perPage: pagination.perPage,
1632
+ page,
1633
+ perPage: perPageForResponse,
1716
1634
  hasMore: end < total
1717
1635
  },
1718
1636
  scores: pagedScores
@@ -1732,7 +1650,7 @@ var ScoresStorageCloudflare = class extends storage.ScoresStorage {
1732
1650
  return { pagination: { total: 0, page: 0, perPage: 100, hasMore: false }, scores: [] };
1733
1651
  }
1734
1652
  }
1735
- async getScoresByRunId({
1653
+ async listScoresByRunId({
1736
1654
  runId,
1737
1655
  pagination
1738
1656
  }) {
@@ -1750,15 +1668,17 @@ var ScoresStorageCloudflare = class extends storage.ScoresStorage {
1750
1668
  const dateB = new Date(b.createdAt || 0).getTime();
1751
1669
  return dateB - dateA;
1752
1670
  });
1671
+ const { page, perPage: perPageInput } = pagination;
1672
+ const perPage = storage.normalizePerPage(perPageInput, 100);
1673
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
1753
1674
  const total = scores.length;
1754
- const start = pagination.page * pagination.perPage;
1755
- const end = start + pagination.perPage;
1675
+ const end = perPageInput === false ? scores.length : start + perPage;
1756
1676
  const pagedScores = scores.slice(start, end);
1757
1677
  return {
1758
1678
  pagination: {
1759
1679
  total,
1760
- page: pagination.page,
1761
- perPage: pagination.perPage,
1680
+ page,
1681
+ perPage: perPageForResponse,
1762
1682
  hasMore: end < total
1763
1683
  },
1764
1684
  scores: pagedScores
@@ -1778,7 +1698,7 @@ var ScoresStorageCloudflare = class extends storage.ScoresStorage {
1778
1698
  return { pagination: { total: 0, page: 0, perPage: 100, hasMore: false }, scores: [] };
1779
1699
  }
1780
1700
  }
1781
- async getScoresByEntityId({
1701
+ async listScoresByEntityId({
1782
1702
  entityId,
1783
1703
  entityType,
1784
1704
  pagination
@@ -1797,15 +1717,17 @@ var ScoresStorageCloudflare = class extends storage.ScoresStorage {
1797
1717
  const dateB = new Date(b.createdAt || 0).getTime();
1798
1718
  return dateB - dateA;
1799
1719
  });
1720
+ const { page, perPage: perPageInput } = pagination;
1721
+ const perPage = storage.normalizePerPage(perPageInput, 100);
1722
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
1800
1723
  const total = scores.length;
1801
- const start = pagination.page * pagination.perPage;
1802
- const end = start + pagination.perPage;
1724
+ const end = perPageInput === false ? scores.length : start + perPage;
1803
1725
  const pagedScores = scores.slice(start, end);
1804
1726
  return {
1805
1727
  pagination: {
1806
1728
  total,
1807
- page: pagination.page,
1808
- perPage: pagination.perPage,
1729
+ page,
1730
+ perPage: perPageForResponse,
1809
1731
  hasMore: end < total
1810
1732
  },
1811
1733
  scores: pagedScores
@@ -1825,7 +1747,7 @@ var ScoresStorageCloudflare = class extends storage.ScoresStorage {
1825
1747
  return { pagination: { total: 0, page: 0, perPage: 100, hasMore: false }, scores: [] };
1826
1748
  }
1827
1749
  }
1828
- async getScoresBySpan({
1750
+ async listScoresBySpan({
1829
1751
  traceId,
1830
1752
  spanId,
1831
1753
  pagination
@@ -1844,21 +1766,23 @@ var ScoresStorageCloudflare = class extends storage.ScoresStorage {
1844
1766
  const dateB = new Date(b.createdAt || 0).getTime();
1845
1767
  return dateB - dateA;
1846
1768
  });
1769
+ const { page, perPage: perPageInput } = pagination;
1770
+ const perPage = storage.normalizePerPage(perPageInput, 100);
1771
+ const { offset: start, perPage: perPageForResponse } = storage.calculatePagination(page, perPageInput, perPage);
1847
1772
  const total = scores.length;
1848
- const start = pagination.page * pagination.perPage;
1849
- const end = start + pagination.perPage;
1773
+ const end = perPageInput === false ? scores.length : start + perPage;
1850
1774
  const pagedScores = scores.slice(start, end);
1851
1775
  return {
1852
1776
  pagination: {
1853
1777
  total,
1854
- page: pagination.page,
1855
- perPage: pagination.perPage,
1778
+ page,
1779
+ perPage: perPageForResponse,
1856
1780
  hasMore: end < total
1857
1781
  },
1858
1782
  scores: pagedScores
1859
1783
  };
1860
1784
  } catch (error$1) {
1861
- throw new error.MastraError(
1785
+ const mastraError = new error.MastraError(
1862
1786
  {
1863
1787
  id: "CLOUDFLARE_STORAGE_SCORES_GET_SCORES_BY_SPAN_FAILED",
1864
1788
  domain: error.ErrorDomain.STORAGE,
@@ -1867,129 +1791,12 @@ var ScoresStorageCloudflare = class extends storage.ScoresStorage {
1867
1791
  },
1868
1792
  error$1
1869
1793
  );
1794
+ this.logger?.trackException(mastraError);
1795
+ this.logger?.error(mastraError.toString());
1796
+ return { pagination: { total: 0, page: 0, perPage: 100, hasMore: false }, scores: [] };
1870
1797
  }
1871
1798
  }
1872
1799
  };
1873
- var TracesStorageCloudflare = class extends storage.TracesStorage {
1874
- operations;
1875
- constructor({ operations }) {
1876
- super();
1877
- this.operations = operations;
1878
- }
1879
- async getTraces(args) {
1880
- const paginatedArgs = {
1881
- name: args.name,
1882
- scope: args.scope,
1883
- page: args.page,
1884
- perPage: args.perPage,
1885
- attributes: args.attributes,
1886
- filters: args.filters,
1887
- dateRange: args.fromDate || args.toDate ? {
1888
- start: args.fromDate,
1889
- end: args.toDate
1890
- } : void 0
1891
- };
1892
- try {
1893
- const result = await this.getTracesPaginated(paginatedArgs);
1894
- return result.traces;
1895
- } catch (error$1) {
1896
- throw new error.MastraError(
1897
- {
1898
- id: "CLOUDFLARE_STORAGE_GET_TRACES_ERROR",
1899
- domain: error.ErrorDomain.STORAGE,
1900
- category: error.ErrorCategory.THIRD_PARTY,
1901
- text: `Failed to retrieve traces: ${error$1 instanceof Error ? error$1.message : String(error$1)}`,
1902
- details: {
1903
- name: args.name ?? "",
1904
- scope: args.scope ?? ""
1905
- }
1906
- },
1907
- error$1
1908
- );
1909
- }
1910
- }
1911
- async getTracesPaginated(args) {
1912
- try {
1913
- const { name, scope, attributes, filters, page = 0, perPage = 100, dateRange } = args;
1914
- const prefix = this.operations.namespacePrefix ? `${this.operations.namespacePrefix}:` : "";
1915
- const keyObjs = await this.operations.listKV(storage.TABLE_TRACES, { prefix: `${prefix}${storage.TABLE_TRACES}` });
1916
- const traces = [];
1917
- for (const { name: key } of keyObjs) {
1918
- try {
1919
- const data = await this.operations.getKV(storage.TABLE_TRACES, key);
1920
- if (!data) continue;
1921
- if (name && data.name !== name) continue;
1922
- if (scope && data.scope !== scope) continue;
1923
- if (attributes) {
1924
- const dataAttributes = data.attributes || {};
1925
- let shouldSkip = false;
1926
- for (const [key2, value] of Object.entries(attributes)) {
1927
- if (dataAttributes[key2] !== value) {
1928
- shouldSkip = true;
1929
- break;
1930
- }
1931
- }
1932
- if (shouldSkip) continue;
1933
- }
1934
- if (dateRange?.start || dateRange?.end) {
1935
- const traceDate = new Date(data.createdAt || 0);
1936
- if (dateRange.start && traceDate < dateRange.start) continue;
1937
- if (dateRange.end && traceDate > dateRange.end) continue;
1938
- }
1939
- if (filters) {
1940
- let shouldSkip = false;
1941
- for (const [key2, value] of Object.entries(filters)) {
1942
- if (data[key2] !== value) {
1943
- shouldSkip = true;
1944
- break;
1945
- }
1946
- }
1947
- if (shouldSkip) continue;
1948
- }
1949
- traces.push(data);
1950
- } catch (err) {
1951
- this.logger.error("Failed to parse trace:", { key, error: err });
1952
- }
1953
- }
1954
- traces.sort((a, b) => {
1955
- const aTime = new Date(a.createdAt || 0).getTime();
1956
- const bTime = new Date(b.createdAt || 0).getTime();
1957
- return bTime - aTime;
1958
- });
1959
- const total = traces.length;
1960
- const start = page * perPage;
1961
- const end = start + perPage;
1962
- const pagedTraces = traces.slice(start, end);
1963
- return {
1964
- traces: pagedTraces,
1965
- total,
1966
- page,
1967
- perPage,
1968
- hasMore: end < total
1969
- };
1970
- } catch (error$1) {
1971
- const mastraError = new error.MastraError(
1972
- {
1973
- id: "CLOUDFLARE_STORAGE_GET_TRACES_PAGINATED_FAILED",
1974
- domain: error.ErrorDomain.STORAGE,
1975
- category: error.ErrorCategory.THIRD_PARTY,
1976
- text: "Error getting traces with pagination"
1977
- },
1978
- error$1
1979
- );
1980
- this.logger.trackException?.(mastraError);
1981
- this.logger.error(mastraError.toString());
1982
- return { traces: [], total: 0, page: 0, perPage: 100, hasMore: false };
1983
- }
1984
- }
1985
- async batchTraceInsert({ records }) {
1986
- this.logger.debug("Batch inserting traces", { count: records.length });
1987
- await this.operations.batchInsert({
1988
- tableName: storage.TABLE_TRACES,
1989
- records
1990
- });
1991
- }
1992
- };
1993
1800
  var WorkflowsStorageCloudflare = class extends storage.WorkflowsStorage {
1994
1801
  operations;
1995
1802
  constructor({ operations }) {
@@ -2007,7 +1814,7 @@ var WorkflowsStorageCloudflare = class extends storage.WorkflowsStorage {
2007
1814
  // runId,
2008
1815
  // stepId,
2009
1816
  // result,
2010
- // runtimeContext,
1817
+ // requestContext,
2011
1818
  }) {
2012
1819
  throw new Error("Method not implemented.");
2013
1820
  }
@@ -2028,7 +1835,7 @@ var WorkflowsStorageCloudflare = class extends storage.WorkflowsStorage {
2028
1835
  workflow_name: workflowName,
2029
1836
  run_id: runId,
2030
1837
  resourceId,
2031
- snapshot: typeof snapshot === "string" ? snapshot : JSON.stringify(snapshot),
1838
+ snapshot: JSON.stringify(snapshot),
2032
1839
  createdAt: /* @__PURE__ */ new Date(),
2033
1840
  updatedAt: /* @__PURE__ */ new Date()
2034
1841
  }
@@ -2107,15 +1914,29 @@ var WorkflowsStorageCloudflare = class extends storage.WorkflowsStorage {
2107
1914
  if (resourceId) key += `:${resourceId}`;
2108
1915
  return key;
2109
1916
  }
2110
- async getWorkflowRuns({
1917
+ async listWorkflowRuns({
2111
1918
  workflowName,
2112
- limit = 20,
2113
- offset = 0,
1919
+ page = 0,
1920
+ perPage = 20,
2114
1921
  resourceId,
2115
1922
  fromDate,
2116
- toDate
1923
+ toDate,
1924
+ status
2117
1925
  } = {}) {
2118
1926
  try {
1927
+ if (page < 0 || !Number.isInteger(page)) {
1928
+ throw new error.MastraError(
1929
+ {
1930
+ id: "CLOUDFLARE_STORE_INVALID_PAGE",
1931
+ domain: error.ErrorDomain.STORAGE,
1932
+ category: error.ErrorCategory.USER,
1933
+ details: { page }
1934
+ },
1935
+ new Error("page must be a non-negative integer")
1936
+ );
1937
+ }
1938
+ const normalizedPerPage = storage.normalizePerPage(perPage, 20);
1939
+ const offset = page * normalizedPerPage;
2119
1940
  const prefix = this.buildWorkflowSnapshotPrefix({ workflowName });
2120
1941
  const keyObjs = await this.operations.listKV(storage.TABLE_WORKFLOW_SNAPSHOT, { prefix });
2121
1942
  const runs = [];
@@ -2131,10 +1952,11 @@ var WorkflowsStorageCloudflare = class extends storage.WorkflowsStorage {
2131
1952
  if (!data) continue;
2132
1953
  try {
2133
1954
  if (resourceId && !keyResourceId) continue;
1955
+ const snapshotData = typeof data.snapshot === "string" ? JSON.parse(data.snapshot) : data.snapshot;
1956
+ if (status && snapshotData.status !== status) continue;
2134
1957
  const createdAt = storage.ensureDate(data.createdAt);
2135
1958
  if (fromDate && createdAt && createdAt < fromDate) continue;
2136
1959
  if (toDate && createdAt && createdAt > toDate) continue;
2137
- const snapshotData = typeof data.snapshot === "string" ? JSON.parse(data.snapshot) : data.snapshot;
2138
1960
  const resourceIdToUse = keyResourceId || data.resourceId;
2139
1961
  const run = this.parseWorkflowRun({
2140
1962
  ...data,
@@ -2152,7 +1974,7 @@ var WorkflowsStorageCloudflare = class extends storage.WorkflowsStorage {
2152
1974
  const bDate = b.createdAt ? new Date(b.createdAt).getTime() : 0;
2153
1975
  return bDate - aDate;
2154
1976
  });
2155
- const pagedRuns = runs.slice(offset, offset + limit);
1977
+ const pagedRuns = runs.slice(offset, offset + normalizedPerPage);
2156
1978
  return {
2157
1979
  runs: pagedRuns,
2158
1980
  total: runs.length
@@ -2160,7 +1982,7 @@ var WorkflowsStorageCloudflare = class extends storage.WorkflowsStorage {
2160
1982
  } catch (error$1) {
2161
1983
  const mastraError = new error.MastraError(
2162
1984
  {
2163
- id: "CLOUDFLARE_STORAGE_GET_WORKFLOW_RUNS_FAILED",
1985
+ id: "CLOUDFLARE_STORAGE_LIST_WORKFLOW_RUNS_FAILED",
2164
1986
  domain: error.ErrorDomain.STORAGE,
2165
1987
  category: error.ErrorCategory.THIRD_PARTY
2166
1988
  },
@@ -2234,14 +2056,7 @@ var CloudflareStore = class extends storage.MastraStorage {
2234
2056
  if (!config.bindings) {
2235
2057
  throw new Error("KV bindings are required when using Workers Binding API");
2236
2058
  }
2237
- const requiredTables = [
2238
- storage.TABLE_THREADS,
2239
- storage.TABLE_MESSAGES,
2240
- storage.TABLE_WORKFLOW_SNAPSHOT,
2241
- storage.TABLE_EVALS,
2242
- storage.TABLE_SCORERS,
2243
- storage.TABLE_TRACES
2244
- ];
2059
+ const requiredTables = [storage.TABLE_THREADS, storage.TABLE_MESSAGES, storage.TABLE_WORKFLOW_SNAPSHOT, storage.TABLE_SCORERS];
2245
2060
  for (const table of requiredTables) {
2246
2061
  if (!(table in config.bindings)) {
2247
2062
  throw new Error(`Missing KV binding for table: ${table}`);
@@ -2261,11 +2076,13 @@ var CloudflareStore = class extends storage.MastraStorage {
2261
2076
  }
2262
2077
  get supports() {
2263
2078
  const supports = super.supports;
2264
- supports.getScoresBySpan = true;
2079
+ supports.listScoresBySpan = true;
2080
+ supports.resourceWorkingMemory = true;
2081
+ supports.selectByIncludeResourceScope = true;
2265
2082
  return supports;
2266
2083
  }
2267
2084
  constructor(config) {
2268
- super({ name: "Cloudflare" });
2085
+ super({ id: config.id, name: "Cloudflare" });
2269
2086
  try {
2270
2087
  if (isWorkersConfig(config)) {
2271
2088
  this.validateWorkersConfig(config);
@@ -2287,15 +2104,9 @@ var CloudflareStore = class extends storage.MastraStorage {
2287
2104
  namespacePrefix: this.namespacePrefix,
2288
2105
  bindings: this.bindings
2289
2106
  });
2290
- const legacyEvals = new LegacyEvalsStorageCloudflare({
2291
- operations
2292
- });
2293
2107
  const workflows = new WorkflowsStorageCloudflare({
2294
2108
  operations
2295
2109
  });
2296
- const traces = new TracesStorageCloudflare({
2297
- operations
2298
- });
2299
2110
  const memory = new MemoryStorageCloudflare({
2300
2111
  operations
2301
2112
  });
@@ -2304,9 +2115,7 @@ var CloudflareStore = class extends storage.MastraStorage {
2304
2115
  });
2305
2116
  this.stores = {
2306
2117
  operations,
2307
- legacyEvals,
2308
2118
  workflows,
2309
- traces,
2310
2119
  memory,
2311
2120
  scores
2312
2121
  };
@@ -2348,9 +2157,6 @@ var CloudflareStore = class extends storage.MastraStorage {
2348
2157
  async getThreadById({ threadId }) {
2349
2158
  return this.stores.memory.getThreadById({ threadId });
2350
2159
  }
2351
- async getThreadsByResourceId({ resourceId }) {
2352
- return this.stores.memory.getThreadsByResourceId({ resourceId });
2353
- }
2354
2160
  async saveThread({ thread }) {
2355
2161
  return this.stores.memory.saveThread({ thread });
2356
2162
  }
@@ -2367,22 +2173,14 @@ var CloudflareStore = class extends storage.MastraStorage {
2367
2173
  async saveMessages(args) {
2368
2174
  return this.stores.memory.saveMessages(args);
2369
2175
  }
2370
- async getMessages({
2371
- threadId,
2372
- resourceId,
2373
- selectBy,
2374
- format
2375
- }) {
2376
- return this.stores.memory.getMessages({ threadId, resourceId, selectBy, format });
2377
- }
2378
2176
  async updateWorkflowResults({
2379
2177
  workflowName,
2380
2178
  runId,
2381
2179
  stepId,
2382
2180
  result,
2383
- runtimeContext
2181
+ requestContext
2384
2182
  }) {
2385
- return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, runtimeContext });
2183
+ return this.stores.workflows.updateWorkflowResults({ workflowName, runId, stepId, result, requestContext });
2386
2184
  }
2387
2185
  async updateWorkflowState({
2388
2186
  workflowName,
@@ -2391,11 +2189,8 @@ var CloudflareStore = class extends storage.MastraStorage {
2391
2189
  }) {
2392
2190
  return this.stores.workflows.updateWorkflowState({ workflowName, runId, opts });
2393
2191
  }
2394
- async getMessagesById({
2395
- messageIds,
2396
- format
2397
- }) {
2398
- return this.stores.memory.getMessagesById({ messageIds, format });
2192
+ async listMessagesById({ messageIds }) {
2193
+ return this.stores.memory.listMessagesById({ messageIds });
2399
2194
  }
2400
2195
  async persistWorkflowSnapshot(params) {
2401
2196
  return this.stores.workflows.persistWorkflowSnapshot(params);
@@ -2406,46 +2201,23 @@ var CloudflareStore = class extends storage.MastraStorage {
2406
2201
  async batchInsert(input) {
2407
2202
  return this.stores.operations.batchInsert(input);
2408
2203
  }
2409
- async getTraces({
2410
- name,
2411
- scope,
2412
- page = 0,
2413
- perPage = 100,
2414
- attributes,
2415
- fromDate,
2416
- toDate
2417
- }) {
2418
- return this.stores.traces.getTraces({
2419
- name,
2420
- scope,
2421
- page,
2422
- perPage,
2423
- attributes,
2424
- fromDate,
2425
- toDate
2426
- });
2427
- }
2428
- async getEvalsByAgentName(agentName, type) {
2429
- return this.stores.legacyEvals.getEvalsByAgentName(agentName, type);
2430
- }
2431
- async getEvals(options) {
2432
- return this.stores.legacyEvals.getEvals(options);
2433
- }
2434
- async getWorkflowRuns({
2204
+ async listWorkflowRuns({
2435
2205
  workflowName,
2436
- limit = 20,
2437
- offset = 0,
2206
+ perPage = 20,
2207
+ page = 0,
2438
2208
  resourceId,
2439
2209
  fromDate,
2440
- toDate
2210
+ toDate,
2211
+ status
2441
2212
  } = {}) {
2442
- return this.stores.workflows.getWorkflowRuns({
2213
+ return this.stores.workflows.listWorkflowRuns({
2443
2214
  workflowName,
2444
- limit,
2445
- offset,
2215
+ perPage,
2216
+ page,
2446
2217
  resourceId,
2447
2218
  fromDate,
2448
- toDate
2219
+ toDate,
2220
+ status
2449
2221
  });
2450
2222
  }
2451
2223
  async getWorkflowRunById({
@@ -2454,15 +2226,6 @@ var CloudflareStore = class extends storage.MastraStorage {
2454
2226
  }) {
2455
2227
  return this.stores.workflows.getWorkflowRunById({ runId, workflowName });
2456
2228
  }
2457
- async getTracesPaginated(args) {
2458
- return this.stores.traces.getTracesPaginated(args);
2459
- }
2460
- async getThreadsByResourceIdPaginated(args) {
2461
- return this.stores.memory.getThreadsByResourceIdPaginated(args);
2462
- }
2463
- async getMessagesPaginated(args) {
2464
- return this.stores.memory.getMessagesPaginated(args);
2465
- }
2466
2229
  async updateMessages(args) {
2467
2230
  return this.stores.memory.updateMessages(args);
2468
2231
  }
@@ -2472,34 +2235,34 @@ var CloudflareStore = class extends storage.MastraStorage {
2472
2235
  async saveScore(score) {
2473
2236
  return this.stores.scores.saveScore(score);
2474
2237
  }
2475
- async getScoresByRunId({
2238
+ async listScoresByRunId({
2476
2239
  runId,
2477
2240
  pagination
2478
2241
  }) {
2479
- return this.stores.scores.getScoresByRunId({ runId, pagination });
2242
+ return this.stores.scores.listScoresByRunId({ runId, pagination });
2480
2243
  }
2481
- async getScoresByEntityId({
2244
+ async listScoresByEntityId({
2482
2245
  entityId,
2483
2246
  entityType,
2484
2247
  pagination
2485
2248
  }) {
2486
- return this.stores.scores.getScoresByEntityId({ entityId, entityType, pagination });
2249
+ return this.stores.scores.listScoresByEntityId({ entityId, entityType, pagination });
2487
2250
  }
2488
- async getScoresByScorerId({
2251
+ async listScoresByScorerId({
2489
2252
  scorerId,
2490
2253
  entityId,
2491
2254
  entityType,
2492
2255
  source,
2493
2256
  pagination
2494
2257
  }) {
2495
- return this.stores.scores.getScoresByScorerId({ scorerId, entityId, entityType, source, pagination });
2258
+ return this.stores.scores.listScoresByScorerId({ scorerId, entityId, entityType, source, pagination });
2496
2259
  }
2497
- async getScoresBySpan({
2260
+ async listScoresBySpan({
2498
2261
  traceId,
2499
2262
  spanId,
2500
2263
  pagination
2501
2264
  }) {
2502
- return this.stores.scores.getScoresBySpan({ traceId, spanId, pagination });
2265
+ return this.stores.scores.listScoresBySpan({ traceId, spanId, pagination });
2503
2266
  }
2504
2267
  async getResourceById({ resourceId }) {
2505
2268
  return this.stores.memory.getResourceById({ resourceId });